agentix-cli 0.193.0 → 0.195.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 (161) hide show
  1. package/README.md +1 -1
  2. package/apps/mac-helper/Sources/AgentXHelper/Presence.swift +70 -6
  3. package/apps/mac-helper/Sources/AgentXHelper/PresenceTag.swift +42 -5
  4. package/apps/mac-helper/Sources/AgentXHelper/main.swift +2 -1
  5. package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +107 -4
  6. package/apps/mac-voice/Sources/AgentXVoice/Config.swift +0 -9
  7. package/apps/mac-voice/Sources/AgentXVoice/HistoryWindow.swift +3 -2
  8. package/apps/mac-voice/Sources/AgentXVoice/OpenRequests.swift +276 -8
  9. package/apps/mac-voice/Sources/AgentXVoice/RequestsWindow.swift +357 -26
  10. package/apps/mac-voice/Sources/AgentXVoice/SettingsWindow.swift +27 -0
  11. package/apps/mac-voice/Sources/AgentXVoice/StatusMenu.swift +17 -2
  12. package/apps/mac-voice/Sources/AgentXVoice/VoiceSettings.swift +23 -1
  13. package/apps/mac-voice/Sources/AgentXVoice/main.swift +335 -30
  14. package/dist/{App-6TNGC3UR.js → App-HBM52GXI.js} +2 -2
  15. package/dist/{ChatApp-FUDLZ6HZ.js → ChatApp-N4P7M2TD.js} +2 -2
  16. package/dist/{absorb-eval-YSWPPGQF.js → absorb-eval-HRWWPKT3.js} +2 -2
  17. package/dist/{adapter-EEBNOFDS.js → adapter-X6T3YBUB.js} +2 -2
  18. package/dist/{agent-QX2POUEM.js → agent-3B4RMEDI.js} +2 -2
  19. package/dist/{board-dashboard-VVFHNABJ.js → board-dashboard-ZIDDOCOO.js} +1866 -6115
  20. package/dist/board-dashboard-ZIDDOCOO.js.map +1 -0
  21. package/dist/{chunk-2O72AHK5.js → chunk-2GCPSAXQ.js} +2 -2
  22. package/dist/{chunk-KHKG7H6Q.js → chunk-2KYGPVTX.js} +2 -2
  23. package/dist/chunk-3FZ6WHKX.js +2 -0
  24. package/dist/{chunk-MQRAQJSS.js.map → chunk-3FZ6WHKX.js.map} +1 -1
  25. package/dist/{chunk-HNA4BW47.js → chunk-6NQ7KYJH.js} +2 -2
  26. package/dist/{chunk-Z2NYUCTE.js → chunk-7L54Z4EH.js} +2 -2
  27. package/dist/{chunk-EH7Y2W77.js → chunk-BOCLWYWL.js} +2 -2
  28. package/dist/chunk-F2FJXKDG.js +7 -0
  29. package/dist/{chunk-DS2ZIVIH.js.map → chunk-F2FJXKDG.js.map} +1 -1
  30. package/dist/{chunk-OYXB6KZX.js → chunk-F3CMNSON.js} +2 -2
  31. package/dist/{chunk-52NME3AU.js → chunk-FO762MEC.js} +2 -2
  32. package/dist/{chunk-AAL5WIXB.js → chunk-HNZEXUNM.js} +2 -2
  33. package/dist/{chunk-H5XBQWAI.js → chunk-HOZZUN47.js} +2 -2
  34. package/dist/chunk-I45E5TLK.js +934 -0
  35. package/dist/chunk-I45E5TLK.js.map +1 -0
  36. package/dist/{chunk-Q7ZPW55P.js → chunk-K2BEV3BD.js} +2 -2
  37. package/dist/{chunk-QTBFMRJ2.js → chunk-KE6BF4ZJ.js} +2 -2
  38. package/dist/{chunk-DACZSUCN.js → chunk-KXJRXRSD.js} +2 -2
  39. package/dist/{chunk-TDZDIDFG.js → chunk-LQIF2OHS.js} +2 -2
  40. package/dist/chunk-M2E3CNFS.js +38 -0
  41. package/dist/chunk-M2E3CNFS.js.map +1 -0
  42. package/dist/{chunk-22WO5X4L.js → chunk-MB5CBY2C.js} +106 -106
  43. package/dist/chunk-MB5CBY2C.js.map +1 -0
  44. package/dist/{chunk-JGZ6CA5L.js → chunk-MC3ZZA5G.js} +2 -2
  45. package/dist/{chunk-PSP3NAFU.js → chunk-OEG476JY.js} +79 -76
  46. package/dist/chunk-OEG476JY.js.map +1 -0
  47. package/dist/{chunk-6ZAQ3IT5.js → chunk-P6WSD2UR.js} +23 -23
  48. package/dist/chunk-P6WSD2UR.js.map +1 -0
  49. package/dist/{chunk-GLYBXXO7.js → chunk-PMSL4A5Y.js} +3 -3
  50. package/dist/{chunk-VK2TW3RL.js → chunk-PO2SORKY.js} +2 -2
  51. package/dist/{chunk-N56EHPTR.js → chunk-PX7PWXBI.js} +2 -2
  52. package/dist/{chunk-EI3TZ52P.js → chunk-RW5FKJRE.js} +2 -2
  53. package/dist/{chunk-6FUWODBV.js → chunk-UOIWIVU3.js} +2 -2
  54. package/dist/{chunk-2VQ3VKBR.js → chunk-VX4PSOKU.js} +2 -2
  55. package/dist/{chunk-FEXG2PKQ.js → chunk-XH36J3Z2.js} +2 -2
  56. package/dist/{chunk-462FRP7L.js → chunk-XQF7UUZK.js} +332 -319
  57. package/dist/chunk-XQF7UUZK.js.map +1 -0
  58. package/dist/{chunk-MQV3IU6F.js → chunk-ZALVAXQ4.js} +2 -2
  59. package/dist/cli.js +1 -1
  60. package/dist/{client-5USANRIL.js → client-YN3T56NM.js} +2 -2
  61. package/dist/{config-N7DHUZMH.js → config-G7T3TMWE.js} +2 -2
  62. package/dist/{config-mutate-OVUXNS5X.js → config-mutate-6CRKZQVQ.js} +2 -2
  63. package/dist/config-mutator-7VS3J5BY.js +2 -0
  64. package/dist/{contributions-LTDE6UOQ.js → contributions-6VZ4OXJ5.js} +2 -2
  65. package/dist/{doctor-C3DTKR7C.js → doctor-GFZZTK7C.js} +2 -2
  66. package/dist/{follow-up-tool-NCFOTJ5Y.js → follow-up-tool-NVP56W7E.js} +2 -2
  67. package/dist/{hub-F3X7NL4B.js → hub-B434CABZ.js} +2 -2
  68. package/dist/index.d.ts +38 -6
  69. package/dist/index.js +1 -1
  70. package/dist/{program-6HWZZ2D3.js → program-DW6VZ6LN.js} +238 -238
  71. package/dist/program-DW6VZ6LN.js.map +1 -0
  72. package/dist/{promote-FSOPSHJ4.js → promote-3P6PGJOW.js} +2 -2
  73. package/dist/{query-UDRKDTSB.js → query-E4V7TS5S.js} +2 -2
  74. package/dist/{query-settings-DJGEGG62.js → query-settings-C5UBKJMN.js} +2 -2
  75. package/dist/{registry-AVGT5KPR.js → registry-IG324PR3.js} +2 -2
  76. package/dist/{request-planner-SAQX26AR.js → request-planner-G6IAUMSE.js} +2 -2
  77. package/dist/{review-candidates-67MPNU42.js → review-candidates-ZL2SJXWC.js} +2 -2
  78. package/dist/{routing-7DUO5PI7.js → routing-2IBIZYQU.js} +2 -2
  79. package/dist/schedule-tool-QCTT2R3B.js +2 -0
  80. package/dist/{scheduler-3IADVHIN.js → scheduler-ZGB7IKZQ.js} +2 -2
  81. package/dist/{seat-YWSYQBCW.js → seat-CFY7LMPS.js} +2 -2
  82. package/dist/{select-PA7AHZ3W.js → select-MU52ACKG.js} +2 -2
  83. package/dist/self-ELWZIMVY.js +2 -0
  84. package/dist/{set-enabled-DD6L2ZQ6.js → set-enabled-XRNSYEI3.js} +2 -2
  85. package/dist/{sprint-tool-PKJA6LYF.js → sprint-tool-E4MABD2N.js} +2 -2
  86. package/dist/{tool-WJ72TBMV.js → tool-V5Z4KWK7.js} +2 -2
  87. package/dist/{tool-PJSLWK45.js → tool-W6M7GYRZ.js} +2 -2
  88. package/dist/{tool-KOGZBOCR.js → tool-ZYVT4VUU.js} +2 -2
  89. package/dist/{wiki-HQBMWH23.js → wiki-VP6XRWIS.js} +2 -2
  90. package/dist/wiki-enrich-LUFXPUYY.js +2 -0
  91. package/package.json +1 -1
  92. package/dist/board-dashboard-VVFHNABJ.js.map +0 -1
  93. package/dist/chunk-22WO5X4L.js.map +0 -1
  94. package/dist/chunk-462FRP7L.js.map +0 -1
  95. package/dist/chunk-6ZAQ3IT5.js.map +0 -1
  96. package/dist/chunk-BKTKJNCR.js +0 -36
  97. package/dist/chunk-BKTKJNCR.js.map +0 -1
  98. package/dist/chunk-DS2ZIVIH.js +0 -7
  99. package/dist/chunk-MQRAQJSS.js +0 -2
  100. package/dist/chunk-PSP3NAFU.js.map +0 -1
  101. package/dist/chunk-RDENYWNG.js +0 -898
  102. package/dist/chunk-RDENYWNG.js.map +0 -1
  103. package/dist/config-mutator-OK7CDCHW.js +0 -2
  104. package/dist/program-6HWZZ2D3.js.map +0 -1
  105. package/dist/schedule-tool-LZOW5SVQ.js +0 -2
  106. package/dist/self-KACQLLDA.js +0 -2
  107. package/dist/wiki-enrich-7RPM5DQF.js +0 -2
  108. /package/dist/{App-6TNGC3UR.js.map → App-HBM52GXI.js.map} +0 -0
  109. /package/dist/{ChatApp-FUDLZ6HZ.js.map → ChatApp-N4P7M2TD.js.map} +0 -0
  110. /package/dist/{absorb-eval-YSWPPGQF.js.map → absorb-eval-HRWWPKT3.js.map} +0 -0
  111. /package/dist/{adapter-EEBNOFDS.js.map → adapter-X6T3YBUB.js.map} +0 -0
  112. /package/dist/{agent-QX2POUEM.js.map → agent-3B4RMEDI.js.map} +0 -0
  113. /package/dist/{chunk-2O72AHK5.js.map → chunk-2GCPSAXQ.js.map} +0 -0
  114. /package/dist/{chunk-KHKG7H6Q.js.map → chunk-2KYGPVTX.js.map} +0 -0
  115. /package/dist/{chunk-HNA4BW47.js.map → chunk-6NQ7KYJH.js.map} +0 -0
  116. /package/dist/{chunk-Z2NYUCTE.js.map → chunk-7L54Z4EH.js.map} +0 -0
  117. /package/dist/{chunk-EH7Y2W77.js.map → chunk-BOCLWYWL.js.map} +0 -0
  118. /package/dist/{chunk-OYXB6KZX.js.map → chunk-F3CMNSON.js.map} +0 -0
  119. /package/dist/{chunk-52NME3AU.js.map → chunk-FO762MEC.js.map} +0 -0
  120. /package/dist/{chunk-AAL5WIXB.js.map → chunk-HNZEXUNM.js.map} +0 -0
  121. /package/dist/{chunk-H5XBQWAI.js.map → chunk-HOZZUN47.js.map} +0 -0
  122. /package/dist/{chunk-Q7ZPW55P.js.map → chunk-K2BEV3BD.js.map} +0 -0
  123. /package/dist/{chunk-QTBFMRJ2.js.map → chunk-KE6BF4ZJ.js.map} +0 -0
  124. /package/dist/{chunk-DACZSUCN.js.map → chunk-KXJRXRSD.js.map} +0 -0
  125. /package/dist/{chunk-TDZDIDFG.js.map → chunk-LQIF2OHS.js.map} +0 -0
  126. /package/dist/{chunk-JGZ6CA5L.js.map → chunk-MC3ZZA5G.js.map} +0 -0
  127. /package/dist/{chunk-GLYBXXO7.js.map → chunk-PMSL4A5Y.js.map} +0 -0
  128. /package/dist/{chunk-VK2TW3RL.js.map → chunk-PO2SORKY.js.map} +0 -0
  129. /package/dist/{chunk-N56EHPTR.js.map → chunk-PX7PWXBI.js.map} +0 -0
  130. /package/dist/{chunk-EI3TZ52P.js.map → chunk-RW5FKJRE.js.map} +0 -0
  131. /package/dist/{chunk-6FUWODBV.js.map → chunk-UOIWIVU3.js.map} +0 -0
  132. /package/dist/{chunk-2VQ3VKBR.js.map → chunk-VX4PSOKU.js.map} +0 -0
  133. /package/dist/{chunk-FEXG2PKQ.js.map → chunk-XH36J3Z2.js.map} +0 -0
  134. /package/dist/{chunk-MQV3IU6F.js.map → chunk-ZALVAXQ4.js.map} +0 -0
  135. /package/dist/{client-5USANRIL.js.map → client-YN3T56NM.js.map} +0 -0
  136. /package/dist/{config-N7DHUZMH.js.map → config-G7T3TMWE.js.map} +0 -0
  137. /package/dist/{config-mutate-OVUXNS5X.js.map → config-mutate-6CRKZQVQ.js.map} +0 -0
  138. /package/dist/{config-mutator-OK7CDCHW.js.map → config-mutator-7VS3J5BY.js.map} +0 -0
  139. /package/dist/{contributions-LTDE6UOQ.js.map → contributions-6VZ4OXJ5.js.map} +0 -0
  140. /package/dist/{doctor-C3DTKR7C.js.map → doctor-GFZZTK7C.js.map} +0 -0
  141. /package/dist/{follow-up-tool-NCFOTJ5Y.js.map → follow-up-tool-NVP56W7E.js.map} +0 -0
  142. /package/dist/{hub-F3X7NL4B.js.map → hub-B434CABZ.js.map} +0 -0
  143. /package/dist/{promote-FSOPSHJ4.js.map → promote-3P6PGJOW.js.map} +0 -0
  144. /package/dist/{query-UDRKDTSB.js.map → query-E4V7TS5S.js.map} +0 -0
  145. /package/dist/{query-settings-DJGEGG62.js.map → query-settings-C5UBKJMN.js.map} +0 -0
  146. /package/dist/{registry-AVGT5KPR.js.map → registry-IG324PR3.js.map} +0 -0
  147. /package/dist/{request-planner-SAQX26AR.js.map → request-planner-G6IAUMSE.js.map} +0 -0
  148. /package/dist/{review-candidates-67MPNU42.js.map → review-candidates-ZL2SJXWC.js.map} +0 -0
  149. /package/dist/{routing-7DUO5PI7.js.map → routing-2IBIZYQU.js.map} +0 -0
  150. /package/dist/{schedule-tool-LZOW5SVQ.js.map → schedule-tool-QCTT2R3B.js.map} +0 -0
  151. /package/dist/{scheduler-3IADVHIN.js.map → scheduler-ZGB7IKZQ.js.map} +0 -0
  152. /package/dist/{seat-YWSYQBCW.js.map → seat-CFY7LMPS.js.map} +0 -0
  153. /package/dist/{select-PA7AHZ3W.js.map → select-MU52ACKG.js.map} +0 -0
  154. /package/dist/{self-KACQLLDA.js.map → self-ELWZIMVY.js.map} +0 -0
  155. /package/dist/{set-enabled-DD6L2ZQ6.js.map → set-enabled-XRNSYEI3.js.map} +0 -0
  156. /package/dist/{sprint-tool-PKJA6LYF.js.map → sprint-tool-E4MABD2N.js.map} +0 -0
  157. /package/dist/{tool-WJ72TBMV.js.map → tool-V5Z4KWK7.js.map} +0 -0
  158. /package/dist/{tool-PJSLWK45.js.map → tool-W6M7GYRZ.js.map} +0 -0
  159. /package/dist/{tool-KOGZBOCR.js.map → tool-ZYVT4VUU.js.map} +0 -0
  160. /package/dist/{wiki-HQBMWH23.js.map → wiki-VP6XRWIS.js.map} +0 -0
  161. /package/dist/{wiki-enrich-7RPM5DQF.js.map → wiki-enrich-LUFXPUYY.js.map} +0 -0
@@ -1,8 +1,8 @@
1
- import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-H5XBQWAI.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-DACZSUCN.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function j(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
1
+ import{a as _,b as q}from"./chunk-RKPAVWXF.js";import{a as R,b as O,c as B,d as b,f as k,g as z,h as v,i as w,j as S,k as m}from"./chunk-HOZZUN47.js";import{a as x,b as C,c as E,d as P,e as D}from"./chunk-KXJRXRSD.js";import{existsSync as J,readFileSync as M}from"fs";var V=new Set(["cron","heartbeat","api","a2a","mesh"]),W=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=W){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Y(n){let e=x(n);if(!J(e))throw new Error(`config not found at ${e}`);return JSON.parse(M(e,"utf-8"))}function Z(n,e){return n?.agents?.[e]?.admin===!0}function K(n,e,t){return Z(n,t.agentId)||e?.createdBy===t.agentId}function Q(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function j(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!V.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function ee(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!m(e)?S(w(e.schedule,r,t),r):"\u2014",p=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",h=[`- ${n} [${p}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&h.push(` notify: ${e.notify.channel} ${e.notify.chatId} ${z(e)}`),e.command?h.push(` command: ${A(String(e.command))}`):e.prompt&&h.push(` prompt: ${A(String(e.prompt))}`),h.join(`
2
2
  `)}async function L(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function ae(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,p;try{p=Y(t.configPath)}catch(a){return`Error: ${a.message}`}let h=p.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(h).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>ee(i,f,d)).join(`
3
3
  `):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!p.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),I=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=_(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!p.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||R;if(!b(g))return`Error: unknown timezone "${g}".`;let u=o||q(i.matched,f);if(!B(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(h[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=j(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let y=s(n.report);if(y&&y!=="always"&&y!=="exceptions")return'Error: `report` must be "always" or "exceptions".';let G={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},H=k({parsed:i,agent:f,prompt:l,timezone:g,notify:$,report:y,enabled:!1,createdBy:e.agentId,approval:G}),N=await I(F=>E(F,`crons.${u}`,H));if(!N.success)return`Error: ${N.error}`;let T=S(w(i.cron,g,d),g),U=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${T}`,`Agent: ${f}`,$?`${y==="exceptions"?"Exceptions":"Results"} and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
4
4
  `),X=await L(p,t,U);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${T}.`,"It is saved DISABLED and will not run until the operator approves it.",X].join(`
5
5
  `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=h[o];if(!c)return`Error: schedule "${o}" not found.`;if(!K(p,c,e))return Q(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&m(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await I(i=>E(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(m(c)&&c.approval.requestedBy===e.agentId){let u=await I($=>D($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(m(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await I(u=>{if(!P(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);E(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",f=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?S(w(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
6
  `),g=await L(p,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
7
  `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function ie(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),p=s(r?e.AGENTX_CHAT_ID:n.chatId),h=s(n.accountId);return{agentId:t,channel:d,chatId:p,...h?{accountId:h}:{}}}export{ae as a,ie as b};
8
- //# sourceMappingURL=chunk-Q7ZPW55P.js.map
8
+ //# sourceMappingURL=chunk-K2BEV3BD.js.map
@@ -1,2 +1,2 @@
1
- import{b as m,d as g,f as i,g as h}from"./chunk-5ELIX7BQ.js";import{b as l}from"./chunk-AJ5HMDRW.js";import{a as f}from"./chunk-MQRAQJSS.js";import{readFileSync as p,statSync as T}from"fs";import{resolve as y}from"path";function A(a,o=process.cwd()){let e=y(o,a),n;try{n=T(e).size}catch{throw new i(`No file at ${e}.`)}if(n>m)throw new i(`The picture is ${(n/(1024*1024)).toFixed(1)} MB; the limit is 1 MB. Make it smaller and try again.`,413);let r=p(e);return h(r),r}async function N(a,o,e){let n=e.env??process.env,r=e.agentId??n.AGENTX_AGENT_ID?.trim();if(!r)return{ok:!1,message:"This is not an agent's run (AGENTX_AGENT_ID is not set)."};if(o&&o!==r)return{ok:!1,message:`An agent can only change its own picture: you are "${r}", not "${o}". Ask the owner to change it in Settings.`};let c=l(n);if(!Object.keys(c).length)return{ok:!1,message:"This run carries no proof of who you are (AGENTX_TASK_ID, or AGENTX_CHANNEL and AGENTX_CHAT_ID). Ask the owner to set the picture in Settings."};let s;if(a!==null)try{s=A(a,e.cwd)}catch(t){return{ok:!1,message:t.message}}let d=`${e.daemonUrl.replace(/\/+$/,"")}${g}?agent=${encodeURIComponent(r)}`;try{let t=await(e.fetch??fetch)(d,{method:s?"PUT":"DELETE",headers:{...c,...s?{"Content-Type":"application/octet-stream"}:{}},body:s,signal:AbortSignal.timeout(3e4)}),u=await t.json().catch(()=>({}));return t.ok?s?{ok:!0,message:`Your picture is set. It shows on the ${f}, the Org page and Settings on their next load.`}:{ok:!0,message:u.removed?"Your picture is removed; your initials show again.":"You had no picture; nothing changed."}:{ok:!1,message:u?.error||`HTTP ${t.status}`}}catch(t){return{ok:!1,message:`Couldn't reach the daemon at ${e.daemonUrl} (${t?.message??t}).`}}}export{A as a,N as b};
2
- //# sourceMappingURL=chunk-QTBFMRJ2.js.map
1
+ import{b as m,d as g,f as i,g as h}from"./chunk-5ELIX7BQ.js";import{b as l}from"./chunk-AJ5HMDRW.js";import{a as f}from"./chunk-3FZ6WHKX.js";import{readFileSync as p,statSync as T}from"fs";import{resolve as y}from"path";function A(a,o=process.cwd()){let e=y(o,a),n;try{n=T(e).size}catch{throw new i(`No file at ${e}.`)}if(n>m)throw new i(`The picture is ${(n/(1024*1024)).toFixed(1)} MB; the limit is 1 MB. Make it smaller and try again.`,413);let r=p(e);return h(r),r}async function N(a,o,e){let n=e.env??process.env,r=e.agentId??n.AGENTX_AGENT_ID?.trim();if(!r)return{ok:!1,message:"This is not an agent's run (AGENTX_AGENT_ID is not set)."};if(o&&o!==r)return{ok:!1,message:`An agent can only change its own picture: you are "${r}", not "${o}". Ask the owner to change it in Settings.`};let c=l(n);if(!Object.keys(c).length)return{ok:!1,message:"This run carries no proof of who you are (AGENTX_TASK_ID, or AGENTX_CHANNEL and AGENTX_CHAT_ID). Ask the owner to set the picture in Settings."};let s;if(a!==null)try{s=A(a,e.cwd)}catch(t){return{ok:!1,message:t.message}}let d=`${e.daemonUrl.replace(/\/+$/,"")}${g}?agent=${encodeURIComponent(r)}`;try{let t=await(e.fetch??fetch)(d,{method:s?"PUT":"DELETE",headers:{...c,...s?{"Content-Type":"application/octet-stream"}:{}},body:s,signal:AbortSignal.timeout(3e4)}),u=await t.json().catch(()=>({}));return t.ok?s?{ok:!0,message:`Your picture is set. It shows on the ${f}, the Org page and Settings on their next load.`}:{ok:!0,message:u.removed?"Your picture is removed; your initials show again.":"You had no picture; nothing changed."}:{ok:!1,message:u?.error||`HTTP ${t.status}`}}catch(t){return{ok:!1,message:`Couldn't reach the daemon at ${e.daemonUrl} (${t?.message??t}).`}}}export{A as a,N as b};
2
+ //# sourceMappingURL=chunk-KE6BF4ZJ.js.map
@@ -1,7 +1,7 @@
1
- import{Hb as S,wb as b,xb as k,zb as x}from"./chunk-6ZAQ3IT5.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
1
+ import{Ab as x,Ib as S,xb as b,yb as k}from"./chunk-P6WSD2UR.js";S();import{readFileSync as w,writeFileSync as v,existsSync as P}from"fs";import{resolve as d}from"path";function O(r){if(r)return d(r);let e=[d(process.cwd(),"agentx.json"),d(process.cwd(),".agentx/config.json")];for(let n of e)if(P(n))return n;return e[0]}function R(r){return JSON.parse(JSON.stringify(r))}async function C(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/reload`,{method:"POST",signal:AbortSignal.timeout(3e3)});return e.ok?{ok:!0}:{ok:!1,reason:`HTTP ${e.status}`}}catch(e){return{ok:!1,reason:e?.cause?.code||e?.message||"unreachable"}}}async function N(r,e={}){let{validate:n=!0,dryRun:t=!1,reload:s=!0,configPath:l,daemonUrl:c}=e,o=O(l);if(!P(o))return{success:!1,path:o,error:`Config not found at ${o}. Run \`agentx init\` first.`};let g;try{g=w(o,"utf-8")}catch(a){return{success:!1,path:o,error:`Cannot read ${o}: ${a.message}`}}let p;try{p=JSON.parse(g)}catch(a){return{success:!1,path:o,error:`Invalid JSON in ${o}: ${a.message}`}}let i=R(p);try{await r(i)}catch(a){return{success:!1,path:o,error:`Mutator threw: ${a.message}`}}if(n){let a=k(i),u=b.safeParse(a);if(!u.success){let f=u.error.issues.map($=>` ${$.path.join(".")||"<root>"}: ${$.message}`).join(`
2
2
  `);return{success:!1,path:o,error:`Validation failed:
3
3
  ${f}`,after:i}}let m=x(u.data);if(m.length)return{success:!1,path:o,error:`Validation failed:
4
4
  ${m.map(f=>` ${f}`).join(`
5
5
  `)}`,after:i}}if(t)return{success:!0,path:o,after:i,dryRun:!0};try{v(o,JSON.stringify(i,null,2)+`
6
6
  `)}catch(a){return{success:!1,path:o,error:`Write failed: ${a.message}`,after:i}}let h=!1,y;if(s){let a=c||M(i),u=await C(a);u.ok?h=!0:y=u.reason}return{success:!0,path:o,after:i,reloaded:h,reloadSkipped:y}}function M(r){let e=r?.node?.bind;if(!e)return"http://127.0.0.1:18800";let[n,t]=e.split(":");return`http://${n==="0.0.0.0"||n==="::"?"127.0.0.1":n}:${t}`}function A(r,e,n){let t=e.split("."),s=r;for(let l=0;l<t.length-1;l++){let c=t[l];(s[c]===void 0||s[c]===null)&&(s[c]={}),s=s[c]}s[t[t.length-1]]=n}function F(r,e){let n=e.split("."),t=r;for(let s of n){if(t==null)return;t=t[s]}return t}function U(r,e){let n=e.split("."),t=r;for(let s=0;s<n.length-1;s++){if(t==null)return;t=t[n[s]]}t!=null&&delete t[n[n.length-1]]}export{O as a,N as b,A as c,F as d,U as e};
7
- //# sourceMappingURL=chunk-DACZSUCN.js.map
7
+ //# sourceMappingURL=chunk-KXJRXRSD.js.map
@@ -1,3 +1,3 @@
1
- import{Hb as $,gb as y}from"./chunk-6ZAQ3IT5.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as S,writeFileSync as C}from"fs";import{resolve as u}from"path";function f(t){return u(t,".agentx","email")}function d(t,e){k(u(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
1
+ import{Ib as $,hb as y}from"./chunk-P6WSD2UR.js";import{randomBytes as x}from"crypto";import{existsSync as b,mkdirSync as k,readdirSync as M,readFileSync as j,renameSync as E,unlinkSync as S,writeFileSync as C}from"fs";import{resolve as u}from"path";function f(t){return u(t,".agentx","email")}function d(t,e){k(u(t,".."),{recursive:!0});let r=`${t}.${process.pid}.tmp`;C(r,JSON.stringify(e,null,2)+`
2
2
  `,{mode:384}),E(r,t)}function g(t){try{return JSON.parse(j(t,"utf-8"))}catch{return null}}var D=t=>u(f(t),"threads.json");function w(t){return g(D(t))??{}}function F(t,e){return w(t)[e.toLowerCase()]}function I(t,e){let r=w(t);r[e.to.toLowerCase()]=e,d(D(t),r)}var h=(t,e)=>u(f(t),"cursors",`${e}.json`);function L(t,e){return g(h(t,e))}function z(t,e,r){d(h(t,e),r)}var T=2e4,_=t=>u(f(t),"drafts"),N=t=>/^[a-z0-9-]{8,64}$/.test(t),c=(t,e)=>u(_(t),`${e}.json`);function B(t,e,r=Date.now()){let n=e.text.trim().slice(0,T);if(!n)throw new Error("empty reply");let s={...e,text:n,id:`${r.toString(36)}-${x(4).toString("hex")}`,status:"pending",created_at:new Date(r).toISOString()};return d(c(t,s.id),s),s}function v(t,e){return N(e)?g(c(t,e)):null}function U(t,e){let r=_(t);return b(r)?M(r).filter(n=>n.endsWith(".json")).map(n=>v(t,n.slice(0,-5))).filter(n=>!!n&&(!e||n.status===e)).sort((n,s)=>n.created_at.localeCompare(s.created_at)):[]}async function V(t,e,r,n){let s=v(t,e);if(!s||s.status!=="pending")return{ok:!1,error:`no email reply "${e}" is waiting`};let i=`${c(t,e)}.${process.pid}.${x(3).toString("hex")}.claim`;try{E(c(t,e),i)}catch{return{ok:!1,error:`email reply "${e}" is already being decided`}}let a=n.text!==void 0&&n.text.trim()!==""&&n.text.trim()!==s.text,o={...s,...a?{text:n.text.trim().slice(0,T),edited:!0}:{},decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString()};if(r==="no")o.status="rejected";else{let m=await n.send(o).catch(p=>({ok:!1,error:String(p?.message??p)}));if(!m.ok){d(c(t,e),{...s,error:m.error});try{S(i)}catch{}return{ok:!1,error:`not sent: ${m.error}`}}o.status="sent",delete o.error}d(c(t,e),o);try{S(i)}catch{}return{ok:!0,draft:o}}$();function l(t,e){return(t??"").replace(/\$\{(\w+)\}/g,(r,n)=>e[n]??"")}function P(t,e=process.env){let r={host:t.imap.host,port:t.imap.port,secure:t.imap.secure,user:l(t.imap.user,e)||t.address,password:l(t.imap.password,e)},n={host:t.smtp.host,port:t.smtp.port,secure:t.smtp.secure,user:l(t.smtp.user,e)||r.user,password:l(t.smtp.password,e)||r.password};return{imap:r,smtp:n}}async function J(t,e,r,n=process.env){let{smtp:s}=P(t,n);if(!s.password)throw new Error(`no SMTP password for ${t.address}: set it in .env`);let{default:i}=await import("nodemailer"),a=i.createTransport({host:s.host,port:s.port,secure:s.secure,auth:{user:s.user,pass:s.password},connectionTimeout:2e4,greetingTimeout:2e4,socketTimeout:6e4});try{return(await a.sendMail({from:{name:e,address:t.address},to:r.toName?{name:r.toName,address:r.to}:r.to,subject:r.subject,text:r.text,...r.inReplyTo?{inReplyTo:r.inReplyTo}:{},...r.references?{references:r.references}:{},headers:{"Auto-Submitted":"auto-replied"}})).messageId}finally{a.close()}}function q(t,e){return async r=>{let n=t?.channels?.email?.accounts?.[r.account];if(!n)return{ok:!1,error:`no email account "${r.account}" in agentx.json`};let s=y.safeParse(n);if(!s.success)return{ok:!1,error:`email account "${r.account}": ${s.error.issues[0]?.message}`};let i=s.data,a=i.name||t?.agents?.[r.agent]?.name||r.agent;return await J(i,a,{to:r.to,toName:r.to_name,subject:r.subject,inReplyTo:r.in_reply_to,references:r.references,text:r.text},e),{ok:!0}}}export{F as a,I as b,L as c,z as d,B as e,v as f,U as g,V as h,P as i,J as j,q as k};
3
- //# sourceMappingURL=chunk-TDZDIDFG.js.map
3
+ //# sourceMappingURL=chunk-LQIF2OHS.js.map
@@ -0,0 +1,38 @@
1
+ import{a as E}from"./chunk-IMLAPB7G.js";import{n as x}from"./chunk-XPZSEDE3.js";import{d as se}from"./chunk-QPABR72X.js";import{b as ae}from"./chunk-KP7KDLZ2.js";import{ca as ne,da as re,ea as oe,fa as ie,la as I,qa as Je}from"./chunk-P6WSD2UR.js";import{accessSync as Qe,closeSync as Ye,constants as Ze,existsSync as pe,openSync as et,readFileSync as tt,readSync as nt,statSync as rt}from"node:fs";import{dirname as T,join as C}from"node:path";import{fileURLToPath as ot}from"node:url";import{homedir as it}from"node:os";import{join as ue,win32 as F}from"path";function $(e){return e==="darwin"?"macos":e==="win32"?"windows":null}var j="agentx-helper.exe";function Ke(e){return F.join(e,"Programs","AgentX",j)}var le="AgentX Helper.app";function B(e){return ue(e,"Applications",le,"Contents/MacOS/agentx-mac-helper")}function ze(e,t){let n=t.AGENTX_DESKTOP_HELPER?.trim();if(n)return n;let r=t.AGENTX_MAC_HELPER?.trim();return r&&$(e)==="macos"?r:void 0}function ce(e){let t=ze(e.platform,e.env);if(t)return t;let n=$(e.platform);if(n==="macos"){let r=B(e.home);return e.exists(r)||!e.root?r:ue(e.root,"apps/mac-helper/build",le,"Contents/MacOS/agentx-mac-helper")}if(n==="windows"){let r=e.env.LOCALAPPDATA||F.join(e.home,"AppData","Local"),o=Ke(r);return e.exists(o)||!e.root?o:F.join(e.root,"apps","win-helper","build",j)}return null}function Ve(e){let t=$(e);return t==="macos"?"Run agentx desktop install (or build it with apps/mac-helper/build.sh).":t==="windows"?`Put ${j} in %LOCALAPPDATA%\\Programs\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`:"AgentX has no desktop helper for this system yet."}function Xt(e){let t=$(e);if(t==="macos")return"helper not built \u2014 run apps/mac-helper/build.sh (or agentx desktop install)";if(t==="windows"){let n=Ve(e);return`Windows helper not found \u2014 ${n[0].toLowerCase()}${n.slice(1,-1)}`}return`computer use (point, teach, act) is not available on ${e} yet \u2014 macOS now, Windows in progress (#1594)`}var X="tn.acme.agentx.voice",Yt="AgentX Desktop.app",Zt="AgentX Helper.app";function en(e,t,n){return e!=="darwin"||t!=="arm64"||Number(n.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function tn(e,t){if(t&&!Object.hasOwn(e,t))throw new Error(`Unknown agent: ${t}. Run agentx agent list.`);let n=t||Object.keys(e)[0];if(!n)throw new Error("No agents configured. Run agentx setup first.");return n}function U(e){return`'${e.replace(/'/g,"'\\''")}'`}var de="/usr/bin:/bin:/usr/sbin:/sbin";function nn(e,t){return t||[...new Set([...e?[T(e)]:[],...de.split(":")])].join(":")}function O(e){let t={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return e.replace(/&(amp|lt|gt|quot|apos);/g,(n,r)=>t[r])}function rn(e){let t=e.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);return t?O(t[1]):de}var on=e=>/agentx\.voice.*\.plist$/.test(e);function sn(e,t){let n=null,r=[];for(let{file:o,plist:i}of[...t].sort((s,l)=>s.file<l.file?-1:1)){let s=i.match(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/)?.[1],l=i.match(/<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/)?.[1];!s||!l||!O(l).endsWith("/Contents/MacOS/AgentXVoice")||(n?r.push({file:o,label:O(s)}):n={file:o,label:O(s)})}return{keep:n??{file:C(e,`${X}.plist`),label:X},remove:r}}function me(e,t,n){for(let r of t.split(":"))if(r&&n(C(r,e)))return C(r,e);return null}function an(e){try{if(Qe(e,Ze.X_OK),!rt(e).isFile())return!1;let t=et(e,"r"),n=Buffer.alloc(2);try{nt(t,n,0,2,0)}finally{Ye(t)}return n.toString("latin1")!=="#!"}catch{return!1}}function un(e){let t=r=>r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),n={PATH:e.path,...e.agent?{AGENTX_VOICE_AGENT:e.agent}:{},AGENTX_DAEMON_URL:e.url,AGENTX_MAC_HELPER:e.helper,AGENTX_PASTE_COMMAND:`cd ${U(e.cwd)} && ${U(e.node)} ${U(e.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>Label</key><string>${t(e.label??X)}</string>
5
+ <key>ProgramArguments</key><array><string>${t(e.executable)}</string></array>
6
+ <key>WorkingDirectory</key><string>${t(e.cwd)}</string>
7
+ <key>EnvironmentVariables</key><dict>${Object.entries(n).map(([r,o])=>`<key>${r}</key><string>${t(o)}</string>`).join("")}</dict>
8
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
9
+ <key>ProcessType</key><string>Interactive</string>
10
+ <key>StandardErrorPath</key><string>${t(e.log)}</string>
11
+ </dict></plist>
12
+ `}function ln(e){return e?["--icon",e]:[]}var cn=B;function st(e=T(ot(import.meta.url))){for(let t=e;;t=T(t)){try{if(JSON.parse(tt(C(t,"package.json"),"utf8")).name==="agentix-cli")return t}catch{}if(T(t)===t)return null}}function k(){let e=ce({platform:process.platform,root:st(),home:it(),env:process.env,exists:pe});return e&&pe(e)?e:null}import{accessSync as dt,constants as mt}from"fs";import{execFile as G}from"child_process";var fe=5e3,y=(e,t)=>new Promise(n=>{try{G(e,t,{timeout:fe},r=>n(!r))}catch{n(!1)}}),m=(e,t)=>new Promise(n=>{try{G(e,t,{timeout:fe},(r,o)=>n(r?null:String(o)))}catch{n(null)}}),L=(e,t)=>new Promise((n,r)=>{G(e,t,{timeout:3e4,maxBuffer:8*1024*1024},(o,i,s)=>{o?r(new Error(`${e} ${t[0]}: ${(s||o.message).trim()}`)):n(i)})});var ge=e=>e.helper===void 0?k():e.helper;async function J(e,t=m){if(!e)return"missing";let n=await t(e,["notify-status"]),r=null;try{r=n?JSON.parse(n):null}catch{r=null}return r?r.authorization==="notDetermined"?"not-asked":r.authorization==="denied"?"not-allowed":r.alertStyle==="none"?"hidden":"ready":"outdated"}function ye(e={}){let t=e.run??y;return{async post({title:n,message:r}){let o=ge(e);return o&&await t(o,["notify","--title",n,"--message",r])||await t("/usr/bin/osascript",["-e","on run argv","-e","display notification (item 2 of argv) with title (item 1 of argv)","-e","end run",n,r])?"posted":"failed"},status:()=>J(ge(e),e.capture)}}function at(e){let t=e.match(/"HIDIdleTime"\s*=\s*(\d+)/);return t?Math.floor(Number(t[1])/1e9):null}function we(e={}){let t=e.capture??m;return{async seconds(){let n=await t("/usr/sbin/ioreg",["-c","IOHIDSystem","-d","4"]);return n?at(n):null}}}var ut=`
13
+ function run(argv) {
14
+ var folderName = argv[0], title = argv[1], body = argv[2]
15
+ var Notes = Application("Notes")
16
+ var esc = function (s) { return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }
17
+ var folder = Notes.folders.whose({ name: folderName })()[0]
18
+ if (!folder) {
19
+ folder = Notes.Folder({ name: folderName })
20
+ Notes.folders.push(folder)
21
+ folder = Notes.folders.whose({ name: folderName })()[0]
22
+ }
23
+ var lines = body.split("\\n").map(function (l) { return "<div>" + (l ? esc(l) : "<br>") + "</div>" })
24
+ // Notes takes the title from the first line: a name as well would show it twice.
25
+ var note = Notes.Note({ body: "<div><h1>" + esc(title) + "</h1></div>" + lines.join("") })
26
+ folder.notes.push(note)
27
+ return note.id()
28
+ }
29
+ `;function he(e=L){return{async add({folder:t,title:n,body:r}){let i=(await e("/usr/bin/osascript",["-l","JavaScript","-e",ut,t,n,r])).trim();if(!i)throw new Error("Notes did not return the new note's id");return{id:i}}}}import{existsSync as lt,readdirSync as ct}from"fs";var xe="/System/Library/Sounds";function Se(e){if(!/^[\w -]+$/.test(e))return null;let t=`${xe}/${e}.aiff`;return lt(t)?t:null}function Ne(e={}){let t=e.run??y;return{async play(n,r){let o=Se(n);o&&await t("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,r))),o])},has:n=>Se(n)!==null,async names(){try{return ct(xe).filter(n=>n.endsWith(".aiff")).map(n=>n.slice(0,-5)).sort()}catch{return[]}}}}var Ae={say:"a spoken line (say)",afplay:"a sound playing (afplay)"};function pt(e,t,n=process.pid){for(let r of e.split(`
30
+ `)){let o=r.trim().match(/^(\d+)\s+(\d+)\s+(\S+)/);if(!o)continue;let[i,s,l]=[Number(o[1]),Number(o[2]),o[3]],a=l.slice(l.lastIndexOf("/")+1);if(!(!(a in Ae)||i===n||t.includes(s)))return Ae[a]}return null}function be(e={}){let t=e.capture??m;return{async othersSpeaking(n={}){let r=await t("/bin/ps",["-axo","pid=,ppid=,comm="]);return r?pt(r,n.exceptParents??[]):null}}}var Re="\u200B";function M(e){return e.startsWith("-")?Re+e:e}var ve=e=>e?.startsWith(Re+"-")?e.slice(1):e;function K(e){if(!e.trim()||e.startsWith("-"))throw new Error(`Reminders list name "${e}" is not usable: it must not be empty or start with "-"`);return e}var ke=e=>new Date(Math.floor(e.getTime()/6e4)*6e4).toISOString().replace(/\.\d{3}Z$/,"Z");function Pe(e="remindctl",t=L){return{async ensureList(n){let r=await t(e,["list","--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} list: expected a JSON array`);o.some(i=>i?.title===n)||await t(e,["list",K(n),"--create","--json","--no-input"])},async listOpen(n){let r=await t(e,["show","all","--list",K(n),"--json","--no-input"]),o=JSON.parse(r.trim()||"[]");if(!Array.isArray(o))throw new Error(`${e} show: expected a JSON array`);return o.filter(i=>i&&typeof i.id=="string"&&!i.isCompleted).map(i=>({...i,title:ve(i.title)??"",...i.notes!==void 0?{notes:ve(i.notes)}:{}}))},async add({list:n,title:r,notes:o,due:i,priority:s}){let l=["add","--title",M(r),"--list",K(n),"--notes",M(o)];i&&l.push("--due",ke(i)),s&&s!=="none"&&l.push("--priority",s);let a=await t(e,[...l,"--json","--no-input"]),c;try{c=JSON.parse(a.trim())?.id}catch{c=void 0}if(typeof c!="string"||!c)throw new Error(`${e} add: no reminder id in its answer`);return{id:c}},async update(n,r){let o=["edit",n];r.title!==void 0&&o.push("--title",M(r.title)),r.notes!==void 0&&o.push("--notes",M(r.notes)),r.due===null?o.push("--clear-due"):r.due&&o.push("--due",ke(r.due)),o.length!==2&&await t(e,[...o,"--json","--no-input"])},async complete(n){await t(e,["complete",n,"--json","--no-input"])},async remove(n){await t(e,["delete",n,"--force","--json","--no-input"])}}}var ft=e=>{try{return dt(e,mt.X_OK),!0}catch{return!1}},gt={async active(){let e=ae();return e.active?!0:e.reason==="no active Focus assertion"?!1:null}};function Ie(e={},t={}){let n=e.reminders?.command||"remindctl";return{os:"macos",tasks:Pe(n,t.output),notes:he(t.output),banner:ye(t),sound:Ne(t),focus:gt,speech:be(t),idle:we(t),async describe(){let r=[],o=t.isExecutable??ft;return(n.includes("/")?o(n):!!me(n,process.env.PATH||"",o))||r.push(`Reminders: ${n} not found (brew install steipete/tap/remindctl, or set reminders.command).`),{os:"macos",tasks:!0,notes:!0,banner:!0,sound:!0,focus:!0,problems:r}}}}function _(e){return{os:"none",async describe(){return{os:"none",tasks:!1,notes:!1,banner:!1,sound:!1,focus:!1,problems:[e]}}}}import{existsSync as Nt,readdirSync as At}from"fs";import{win32 as bt}from"path";var N="powershell.exe";function A(e){return`'${e.replace(/['‘’‚‛]/g,t=>t+t)}'`}function b(e){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var yt="{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";function wt(e,t){return["$ErrorActionPreference = 'Stop'","[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","$t = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)","$x = $t.GetElementsByTagName('text')",`$x.Item(0).AppendChild($t.CreateTextNode(${A(e)})) | Out-Null`,`$x.Item(1).AppendChild($t.CreateTextNode(${A(t)})) | Out-Null`,`[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${A(yt)}).Show([Windows.UI.Notifications.ToastNotification]::new($t))`].join(`
31
+ `)}function Ee(e){let t=e.run??y;return{async post({title:n,message:r}){let o=e.helper();return o&&await t(o,["notify","--title",n,"--message",r])||await t(N,b(wt(n,r)))?"posted":"failed"},status:()=>J(e.helper(),e.capture??m)}}var ht=["Add-Type -TypeDefinition @'","using System; using System.Runtime.InteropServices;","public static class AgentXIdle {"," [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }",' [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);'," public static long Ms() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);"," if (!GetLastInputInfo(ref i)) return -1; return (long)(uint)(Environment.TickCount - (int)i.dwTime); }","}","'@","[AgentXIdle]::Ms()"].join(`
32
+ `);function St(e){let t=Number(e.trim());return Number.isFinite(t)&&t>=0&&e.trim()!==""?Math.floor(t/1e3):null}function $e(e={}){let t=e.capture??m;return{async seconds(){let n=await t(N,b(ht));return n?St(n):null}}}import{win32 as xt}from"path";function Te(e,t){if(!/^[\w -]+$/.test(e))return null;let n=xt.join(t.media,`${e}.wav`);return t.exists(n)?n:null}function Oe(e){let t=e.run??y;return{async play(n,r){let o=Te(n,e);!o||!(r>0)||await t(N,b(`(New-Object Media.SoundPlayer ${A(o)}).PlaySync()`))},has:n=>Te(n,e)!==null,async names(){try{return e.list(e.media).filter(n=>/\.wav$/i.test(n)).map(n=>n.slice(0,-4)).sort()}catch{return[]}}}}function Ce(e={},t={}){let n=()=>t.helper===void 0?k():t.helper,r=t.media??bt.join(process.env.WINDIR||process.env.SystemRoot||"C:\\Windows","Media"),o=t.exists??Nt,i=t.list??(s=>At(s));return{os:"windows",banner:Ee({run:t.run,capture:t.capture,helper:n}),sound:Oe({run:t.run,media:r,exists:o,list:i}),idle:$e({capture:t.capture}),async describe(){let s=["Tasks, notes and Focus: AgentX has no Windows adapter for these yet."];return n()||s.push("Banners come from Windows PowerShell until the AgentX Windows helper is installed."),{os:"windows",tasks:!1,notes:!1,banner:!0,sound:!0,focus:!1,problems:s}}}}var vt={darwin:Ie,win32:Ce};function z(e={},t={}){if(e.native?.adapter==="none")return _('Turned off: native.adapter is "none".');let n=t.platform??process.platform,r=(t.factories??vt)[n];return r?r(e,t.io??{}):_(`AgentX has no native adapter for ${n} yet.`)}import{existsSync as kt}from"fs";import{homedir as Rt}from"os";import{isAbsolute as Pt}from"path";var Le={banner:!0,sound:!0,soundName:"Glass",volume:.4,quietWaitSeconds:15};function fr(e){return{...Le,...e??{}}}function gr(e,t={}){let n=z({native:t.native},{platform:t.platform,io:{run:t.run,capture:t.capture,helper:t.helper}});return async(r,o)=>{let i=[];if(e.banner&&n.banner&&i.push(n.banner.post({title:r,message:o})),e.sound&&n.sound){let s=n.sound;i.push(It(n.speech,(e.quietWaitSeconds??Le.quietWaitSeconds)*1e3,t.pollMs??500).then(l=>l?s.play(e.soundName,e.volume):void 0))}await Promise.all(i)}}async function It(e,t,n){if(!e||t<=0)return!0;let r=Date.now()+t;for(;;){if(!await e.othersSpeaking())return!0;if(Date.now()>=r)return!1;await new Promise(o=>setTimeout(o,n))}}function yr(e,t,n=process.platform){let r={...e??{}},o=z({},{platform:n});if("banner"in t&&(r.banner=!!t.banner),"sound"in t&&(r.sound=!!t.sound),"soundName"in t){let i=String(t.soundName).trim();if(!(o.sound?o.sound.has(i):/^[\w -]+$/.test(i)))throw new Error(`no system sound named "${i}" on this machine`);r.soundName=i}if("icon"in t){let i=String(t.icon??"").trim().replace(/^~(?=\/)/,Rt());if(!i)delete r.icon;else{if(!Pt(i)||!/\.(png|jpe?g|icns)$/i.test(i))throw new Error("icon must be the full path to a .png, .jpg or .icns file");if(o.banner&&!kt(i))throw new Error(`no icon file at ${i}`);r.icon=i}}if("volume"in t){let i=Number(t.volume);if(!Number.isFinite(i)||i<0||i>1)throw new Error("volume must be between 0 and 1");r.volume=i}return r}import{existsSync as Lt,mkdirSync as Mt,readFileSync as _t,renameSync as Dt,writeFileSync as Wt}from"fs";import{dirname as He,resolve as qt}from"path";oe();Je();oe();var Nr=["owner","agent","person"],Et=36e5,$t=e=>ie.includes(e.state);function Me(e){return t=>!e||e.get(t)?.state!=="active"?null:e.steps(t).find(n=>n.state==="active")?.agentId??null}function V(e,t){return e.state==="waiting_owner"?{group:"owner",who:I}:e.promise&&e.owedTo&&e.owedTo!==I&&!t.isAgent(e.owedTo)?{group:"person",who:e.owedTo}:e.state==="needs_attention"?{group:"owner",who:I}:{group:"agent",who:t.activeStepAgent?.(e.id)??e.agentId}}function Q(e,t,n){return $t(e)?e.state==="needs_attention"?e.attentionReason??"needs attention":e.dueAt!==null?n>e.dueAt?`past its due time (${Tt(e.dueAt)})`:null:n-e.updatedAt>t*Et?`no activity for ${t} h or more`:null:null}function Ar(e,t,n,r){let o={owner:[],agent:[],person:[]};for(let i of e){let s=Q(i,t,n);if(!s)continue;let{group:l,who:a}=V(i,r);o[l].push({request:i,group:l,who:a,why:s})}return o}function br(e,t){return e==="owner"?"you":e==="agent"?`agent ${t}`:`${t} (outside person)`}var Tt=e=>new Date(e).toISOString().slice(0,16).replace("T"," ")+" UTC";function vr(e){if(e==null||e==="")return;let t=typeof e=="number"?e:typeof e=="string"?Date.parse(e.trim()):NaN;return!Number.isFinite(t)||t<=0?"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds":t}function kr(e){return t=>ne(t,e())}var Ot=10;async function Rr(e,t,n){let r=e.dueForCheck(n.now-n.everyMinutes*6e4,Ot),o=0;return await Promise.all(r.map(async i=>{e.markChecked(i.id,i.verifyState,i.verifyDetail??"",n.now);let s=await t(i.closeWhen,i).catch(l=>({verdict:"unverifiable",detail:String(l?.message??l)}));if(s.verdict==="met"){e.closeVerified(i.id,s.detail,n.now)&&(o++,n.log(`[requests] ${i.id} closed by its check: ${s.detail}`));return}e.markChecked(i.id,s.verdict==="unverifiable"?"unverified":i.verifyState==="failed"?"failed":null,s.detail,n.now)})),{checked:r.length,closed:o}}var We=200,_e=4e3,De="Nothing, just so you know.";function Y(e,t=We){let n=e.headline?e.headline.length>t?`${e.headline.slice(0,t-1)}\u2026`:e.headline:w(e.text,t),r=e.state==="needs_attention"?`Hand it back to ${e.agentId}, or drop it.`:e.state==="waiting_owner"?e.need??(e.question?`Answer: ${w(e.question,150)}`:"Your answer."):e.state==="candidate"||e.state==="in_progress"||e.state==="waiting_other"?e.need??De:De;return{headline:n,need:r,said:qe(e.text)}}function qe(e){return e.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm,"").replace(/[*_~`]+/g,"").replace(/\s+/g," ").trim()}function w(e,t=We){let n=qe(e);if(n.length<=t)return n;let r=n.slice(0,t),o=Math.max(r.lastIndexOf(". "),r.lastIndexOf("? "),r.lastIndexOf("! "));return o>t/2?r.slice(0,o+1):`${r.slice(0,t-1).trimEnd()}\u2026`}function Ct(e){return e.promise||e.dueAt!==null||e.closeWhen?{owedTo:e.owedTo,promise:e.promise,dueAt:e.dueAt,check:e.closeWhen?re(e.closeWhen):null,verifyState:e.verifyState,verifyDetail:e.verifyDetail}:null}function Or(e,t,n,r){let o=n?.get(e.id),i=r?Q(e,r.staleAfterHours,r.now):null,s=t.lastAnswer(e.id),l=s&&s.text.length>_e?`${s.text.slice(0,_e)}
33
+
34
+ \u2026`:s?.text,a=Y(e);return{...e,summary:a.headline,needed:a.need,textHtml:E(e.text),why:e.state==="waiting_owner"?e.question:e.state==="needs_attention"?e.attentionReason:null,ownerNoteHtml:e.ownerNote?E(e.ownerNote):null,lastAnswer:s?{agentId:s.agentId,at:s.at,html:E(l)}:null,loop:Ct(e),awaitingQa:se(e),stall:r&&i?{...V(e,{isAgent:r.isAgent,activeStepAgent:Me(n)}),why:i}:null,plan:o?{state:o.state,steps:n.steps(e.id).map(c=>({idx:c.idx,name:c.name,kind:c.kind,agentId:c.agentId,state:c.state,approval:c.needsApproval?c.approval:null,evidence:c.evidence,note:c.note,nudges:c.nudges}))}:null}}var Z=3,Ht=30*24*36e5;function Be(e){return qt(e,".agentx","native-mirror.json")}function ee(e){try{let t=JSON.parse(_t(Be(e),"utf-8"));return{...t,items:t?.items&&typeof t.items=="object"?t.items:{}}}catch{return{items:{}}}}function Fe(e,t){let n=Be(e);Lt(He(n))||Mt(He(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Wt(r,JSON.stringify(t,null,2)+`
35
+ `),Dt(r,n)}var Ft=5*6e4;function Wr(e,t,n=Date.now()){let r=ee(e),o=r.checkedAt?Date.parse(r.checkedAt):NaN;return!r.cards||!(n-o<=Ft)?!1:r.items[`card:${t}`]?.state!=="failed"}var te=24*36e5;function Ue(e,t,n){let r=e+t.dueAfterMinutes*6e4;return new Date(n!==void 0&&Number.isFinite(n)?Math.max(e,Math.min(r,n)):r)}function jt(e,t,n,r){let o=Date.parse(e.expires),i=[w(e.ask,x.ask)];return e.choices?.length&&i.push(...e.choices.map((s,l)=>`${l+1}. ${s}`)),e.recommend&&i.push(`Recommended: ${w(e.recommend,x.recommend)}`),i.push(`Answer: ${n}`,`agentx: card=${e.id}`),{key:`card:${e.id}`,title:w(e.title,x.title),notes:i.join(`
36
+ `),due:Ue(r,t,o),priority:Number.isFinite(o)&&o-r<=te?"high":"none"}}function Bt(e,t,n,r){let o=[w(e.question||e.text,x.ask),`Asked of ${e.agentId}.`,`Answer: ${n}`,`agentx: request=${e.id}`],i=e.dueAt??void 0;return{key:`request:${e.id}`,title:Y(e,x.title).headline,notes:o.join(`
37
+ `),due:Ue(r,t,i),priority:i!==void 0&&i-r<=te?"high":"none"}}async function qr(e){let{root:t,settings:n,tasks:r,log:o}=e,i=e.now??Date.now(),s=new Date(i).toISOString(),l={created:0,completed:0,dismissed:0,failed:0},a=ee(t);delete a.lastError;let c=u=>{a.lastError={at:s,message:u}},g=new Map;try{if(n.include.includes("card"))for(let u of e.cards())u.status==="pending"&&Date.parse(u.expires)>i&&g.set(`card:${u.id}`,jt(u,n,e.answerUrl,i));if(n.include.includes("request"))for(let u of e.requests())u.state==="waiting_owner"&&g.set(`request:${u.id}`,Bt(u,n,e.answerUrl,i))}catch(u){return o(`[mirror] could not read what is waiting: ${u?.message??u}`),c(String(u?.message??u)),Fe(t,a),l}let D=!0,h=new Map,Xe=async u=>{if(!h.has(u))try{h.set(u,new Set((await r.listOpen(u)).map(p=>p.id)))}catch(p){o(`[mirror] could not read list "${u}": ${p?.message??p}`),c(String(p?.message??p)),h.set(u,null),D=!1}return h.get(u)};for(let[u,p]of Object.entries(a.items)){if(p.state!=="open"||!p.id)continue;let d=await Xe(p.list);if(d)if(g.has(u))d.has(p.id)||(a.items[u]={...p,state:"dismissed",at:s},l.dismissed++,o(`[mirror] ${u}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`));else{if(d.has(p.id))try{await r.complete(p.id)}catch(S){o(`[mirror] ${u}: could not complete its task: ${S?.message??S}`),c(String(S?.message??S));continue}a.items[u]={...p,state:"completed",at:s},l.completed++}}let R=null,W="",q=0,v=[];for(let[u,p]of g){let d=a.items[u];if(d&&(d.state==="open"||d.state==="dismissed")||d?.state==="failed"&&d.failures>=Z)continue;if(R===null)try{await r.ensureList(n.list),R=!0}catch(f){o(`[mirror] could not make list "${n.list}": ${f?.message??f}`),W=String(f?.message??f),c(W),R=!1}let S=d?.state==="failed"?d.failures:0;try{if(R===!1)throw new Error(W);let{id:f}=await r.add({list:n.list,title:p.title,notes:p.notes,due:p.due,priority:p.priority});a.items[u]={id:f,list:n.list,state:"open",at:s,createdAt:s,failures:0},l.created++}catch(f){let P=String(f?.message??f);u.startsWith("card:")&&q++;let H=S+1;a.items[u]={list:n.list,state:"failed",at:s,failures:H,lastError:P},c(P),l.failed++,o(`[mirror] ${u}: could not add to Reminders (${H}/${Z}): ${P}`),H===Z&&v.push({title:p.title,message:P})}}q&&o(`[mirror] ${q} card(s) could not be added to Reminders; the Mac popup shows them instead`);let Ge=a.failureToldAt?Date.parse(a.failureToldAt):NaN;if(v.length&&!(i-Ge<te)){let u=v[0],p=v.length>1?` (and ${v.length-1} more)`:"";try{await e.notify("Could not add to Reminders",`${u.title}${p}: ${w(u.message,200)}. Still on the Desk.`),a.failureToldAt=s}catch(d){o(`[mirror] could not tell the owner: ${d?.message??d}`)}}D&&(a.checkedAt=s,a.cards=n.include.includes("card"));for(let[u,p]of Object.entries(a.items))p.state!=="open"&&!g.has(u)&&i-Date.parse(p.at)>Ht&&delete a.items[u];return Fe(t,a),l}var je=5*6e4;function Hr(e,t,n,r,o=Date.now()){let i=ee(e),s=a=>{let c=a?Date.parse(a):NaN;return c>=n&&c<r},l={from:new Date(n).toISOString(),to:new Date(r).toISOString(),raised:0,created:{cards:0,requests:0},missed:[],closedFast:0,tooNew:0};for(let[a,c]of Object.entries(i.items))!c.id||!s(c.createdAt)||(a.startsWith("card:")?l.created.cards++:l.created.requests++);for(let a of t){if(!s(a.created_at))continue;l.raised++;let c=i.items[`card:${a.id}`];if(c?.id)continue;let g=Date.parse(a.created_at);if((a.status==="pending"?NaN:Date.parse(a.decided_at??""))-g<=je){l.closedFast++;continue}if(a.status==="pending"&&o-g<=je){l.tooNew++;continue}let h=c?.state==="failed"?`could not be added (${c.failures}x): ${c.lastError??"unknown error"}`:"no pass reached it";l.missed.push({id:a.id,title:a.title,reason:h})}return l}function Fr(e){let t=[e.closedFast?`closed within 5 min: ${e.closedFast}`:"",e.tooNew?`raised in the last 5 min: ${e.tooNew}`:""].filter(Boolean);return`cards raised ${e.raised} / Reminders created ${e.created.cards+e.created.requests} (${e.created.cards} cards, ${e.created.requests} requests) / missed ${e.missed.length}${t.length?` \xB7 ${t.join(" \xB7 ")}`:""}`}export{Nr as a,Me as b,V as c,Q as d,Ar as e,br as f,Tt as g,vr as h,kr as i,Rr as j,Y as k,w as l,Ct as m,Or as n,$ as o,ce as p,Ve as q,Xt as r,Yt as s,Zt as t,en as u,tn as v,nn as w,rn as x,on as y,sn as z,me as A,an as B,un as C,ln as D,cn as E,st as F,k as G,Se as H,z as I,Le as J,fr as K,gr as L,yr as M,ee as N,Wr as O,qr as P,Hr as Q,Fr as R};
38
+ //# sourceMappingURL=chunk-M2E3CNFS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/desktop/install.ts","../src/computer-use/helper.ts","../src/native/macos/index.ts","../src/native/macos/run.ts","../src/native/macos/banner.ts","../src/native/macos/idle.ts","../src/native/macos/notes.ts","../src/native/macos/sound.ts","../src/native/macos/speech.ts","../src/native/macos/tasks.ts","../src/native/none.ts","../src/native/windows/index.ts","../src/native/windows/powershell.ts","../src/native/windows/banner.ts","../src/native/windows/idle.ts","../src/native/windows/sound.ts","../src/native/index.ts","../src/notify/local.ts","../src/approvals/mirror.ts","../src/requests/card-view.ts","../src/requests/loops.ts"],"sourcesContent":["import { accessSync, closeSync, constants, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { homedir } from 'node:os'\nimport { installedMacHelper, resolveDesktopHelper } from '@/computer-use/helper'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\nfunction unxml(s: string): string {\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return s.replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n return m ? unxml(m[1]) : LAUNCHD_PATH\n}\n/** Login item files the voice app may have been installed under. */\nexport const isVoiceLoginItemFile = (name: string) => /agentx\\.voice.*\\.plist$/.test(name)\nexport type LoginItem = { file: string; label: string }\n/** One login item per Mac. The label was renamed once and\n * apps/mac-voice/install.sh writes its own, so adopt the first existing\n * `*agentx.voice*` item that runs the voice app (any bundle name) and\n * retire the others; with none, use DESKTOP_LABEL. Plists are XML text. */\nexport function adoptLoginItem(dir: string, items: { file: string; plist: string }[]): { keep: LoginItem; remove: LoginItem[] } {\n let keep: LoginItem | null = null\n const remove: LoginItem[] = []\n for (const { file, plist } of [...items].sort((a, b) => (a.file < b.file ? -1 : 1))) {\n const label = plist.match(/<key>Label<\\/key>\\s*<string>([^<]*)<\\/string>/)?.[1]\n const program = plist.match(/<key>ProgramArguments<\\/key>\\s*<array>\\s*<string>([^<]*)<\\/string>/)?.[1]\n if (!label || !program || !unxml(program).endsWith('/Contents/MacOS/AgentXVoice')) continue\n if (keep) remove.push({ file, label: unxml(label) })\n else keep = { file, label: unxml(label) }\n }\n return { keep: keep ?? { file: join(dir, `${DESKTOP_LABEL}.plist`), label: DESKTOP_LABEL }, remove }\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\n/** True for an executable file that is not a `#!` script. A wrapper script\n * named ffmpeg can sit ahead of the real one on a shell's PATH; its folder\n * would then shadow every other tool for the login item. */\nexport function isNativeExecutable(file: string): boolean {\n try {\n accessSync(file, constants.X_OK)\n if (!statSync(file).isFile()) return false\n const fd = openSync(file, 'r')\n const head = Buffer.alloc(2)\n try { readSync(fd, head, 0, 2, 0) } finally { closeSync(fd) }\n return head.toString('latin1') !== '#!'\n } catch { return false }\n}\n/** Without `agent` the app talks to the agent picked in its menu-bar\n * icon; with it, that agent is pinned and the menu cannot switch. */\nexport function desktopPlist(opts: { label?: string; executable: string; cwd: string; agent?: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;')\n const env = {\n PATH: opts.path,\n ...(opts.agent ? { AGENTX_VOICE_AGENT: opts.agent } : {}),\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${xml(opts.label ?? DESKTOP_LABEL)}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport const installedHelper = installedMacHelper\n/** The AgentX package folder, found by walking up from this file (dist/\n * when installed, src/ in a checkout) — never from the caller's cwd, so\n * `agentx notify` finds a repo-built helper from any folder. */\nexport function packageRoot(from = dirname(fileURLToPath(import.meta.url))): string | null {\n for (let dir = from; ; dir = dirname(dir)) {\n try {\n if (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name === 'agentix-cli') return dir\n } catch { /* no package.json here — keep walking up */ }\n if (dirname(dir) === dir) return null\n }\n}\n/** The helper to run: an explicit path, else the one `agentx desktop\n * install` put in ~/Applications, else one built in the package. */\nexport function resolveHelper(root: string | null, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n if (existsSync(installed) || !root) return installed\n return join(root, 'apps/mac-helper/build', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\n/** The desktop helper for this OS when one is built or installed, else\n * null. AGENTX_DESKTOP_HELPER (or, on a Mac, AGENTX_MAC_HELPER) points at\n * a helper somewhere else. */\nexport function findHelper(): string | null {\n const path = resolveDesktopHelper({ platform: process.platform, root: packageRoot(), home: homedir(), env: process.env, exists: existsSync })\n return path && existsSync(path) ? path : null\n}\n","import { join, win32 } from \"path\"\n\n// --- Which desktop helper this machine runs (#1594) ---\n//\n// Computer use talks to one native CLI by subcommand, JSON on stdout (the\n// verbs are listed in ./contract.ts). macOS has the Swift helper in\n// apps/mac-helper. Windows gets its own binary that answers the same verbs,\n// so point, teach and act stay the same code on both. This file only picks\n// the binary; it never runs it.\n\nexport type HelperOs = \"macos\" | \"windows\"\n\n/** The helper family for this platform, or null where AgentX has none yet. */\nexport function helperOs(platform: NodeJS.Platform): HelperOs | null {\n if (platform === \"darwin\") return \"macos\"\n if (platform === \"win32\") return \"windows\"\n return null\n}\n\n/** Where the Windows helper is installed for one user. */\nexport const WINDOWS_HELPER_EXE = \"agentx-helper.exe\"\nexport function installedWindowsHelper(localAppData: string): string {\n return win32.join(localAppData, \"Programs\", \"AgentX\", WINDOWS_HELPER_EXE)\n}\n\nexport const MAC_HELPER_APP = \"AgentX Helper.app\"\nexport function installedMacHelper(home: string): string {\n return join(home, \"Applications\", MAC_HELPER_APP, \"Contents/MacOS/agentx-mac-helper\")\n}\n\n/** An explicit helper path from the environment. AGENTX_DESKTOP_HELPER\n * works on every OS; AGENTX_MAC_HELPER is the older name, still read on\n * a Mac so existing login items keep working. */\nexport function helperOverride(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string | undefined {\n const any = env.AGENTX_DESKTOP_HELPER?.trim()\n if (any) return any\n const mac = env.AGENTX_MAC_HELPER?.trim()\n return mac && helperOs(platform) === \"macos\" ? mac : undefined\n}\n\nexport interface HelperLookup {\n platform: NodeJS.Platform\n /** The AgentX package folder, or null when it can't be found. */\n root: string | null\n home: string\n env: NodeJS.ProcessEnv\n exists: (path: string) => boolean\n}\n\n/** The helper to run: an explicit path, else the installed one, else one\n * built inside the package. On a platform without a helper the answer is\n * null, and callers say so with helperMissingMessage. */\nexport function resolveDesktopHelper(l: HelperLookup): string | null {\n const override = helperOverride(l.platform, l.env)\n if (override) return override\n const os = helperOs(l.platform)\n if (os === \"macos\") {\n const installed = installedMacHelper(l.home)\n if (l.exists(installed) || !l.root) return installed\n return join(l.root, \"apps/mac-helper/build\", MAC_HELPER_APP, \"Contents/MacOS/agentx-mac-helper\")\n }\n if (os === \"windows\") {\n const localAppData = l.env.LOCALAPPDATA || win32.join(l.home, \"AppData\", \"Local\")\n const installed = installedWindowsHelper(localAppData)\n if (l.exists(installed) || !l.root) return installed\n return win32.join(l.root, \"apps\", \"win-helper\", \"build\", WINDOWS_HELPER_EXE)\n }\n return null\n}\n\n/** How to put the helper in place, as one instruction. */\nexport function helperInstallHint(platform: NodeJS.Platform): string {\n const os = helperOs(platform)\n if (os === \"macos\") return \"Run agentx desktop install (or build it with apps/mac-helper/build.sh).\"\n if (os === \"windows\") return `Put ${WINDOWS_HELPER_EXE} in %LOCALAPPDATA%\\\\Programs\\\\AgentX, or set AGENTX_DESKTOP_HELPER to its path.`\n return \"AgentX has no desktop helper for this system yet.\"\n}\n\n/** What to tell someone whose helper is not there, in plain words. */\nexport function helperMissingMessage(platform: NodeJS.Platform): string {\n const os = helperOs(platform)\n if (os === \"macos\") return \"helper not built — run apps/mac-helper/build.sh (or agentx desktop install)\"\n if (os === \"windows\") {\n const hint = helperInstallHint(platform)\n return `Windows helper not found — ${hint[0].toLowerCase()}${hint.slice(1, -1)}`\n }\n return `computer use (point, teach, act) is not available on ${platform} yet — macOS now, Windows in progress (#1594)`\n}\n","import { accessSync, constants } from \"fs\"\nimport { findOnPath } from \"@/desktop/install\"\nimport { readSystemFocus } from \"@/notify/focus\"\nimport type { NativeAdapter, NativeFocus } from \"../types\"\nimport { macosBanner } from \"./banner\"\nimport { macosIdle } from \"./idle\"\nimport { macosNotes } from \"./notes\"\nimport type { Capture, Output, Run } from \"./run\"\nimport { macosSound } from \"./sound\"\nimport { macosSpeech } from \"./speech\"\nimport { macosTasks } from \"./tasks\"\n\n/** Programs the adapter runs, so tests can stand in for them. */\nexport interface MacosIo {\n run?: Run\n capture?: Capture\n output?: Output\n /** The AgentX Helper binary; null means none. Unset: looked up on use. */\n helper?: string | null\n /** Is this file an executable? Used to find remindctl. */\n isExecutable?: (file: string) => boolean\n}\n\nconst executable = (file: string): boolean => {\n try { accessSync(file, constants.X_OK); return true } catch { return false }\n}\n\n/** System Focus from the private Focus database (notify/focus.ts). That\n * reader answers \"not in Focus\" when it can't read the file, so here\n * anything but a clean answer is null: the OS could not tell. */\nconst focus: NativeFocus = {\n async active() {\n const s = readSystemFocus()\n if (s.active) return true\n return s.reason === \"no active Focus assertion\" ? false : null\n },\n}\n\nexport function macosAdapter(cfg: { reminders?: { command?: string } } = {}, io: MacosIo = {}): NativeAdapter {\n const command = cfg.reminders?.command || \"remindctl\"\n return {\n os: \"macos\",\n tasks: macosTasks(command, io.output),\n notes: macosNotes(io.output),\n banner: macosBanner(io),\n sound: macosSound(io),\n focus,\n speech: macosSpeech(io),\n idle: macosIdle(io),\n async describe() {\n const problems: string[] = []\n const isExec = io.isExecutable ?? executable\n const found = command.includes(\"/\") ? isExec(command) : !!findOnPath(command, process.env.PATH || \"\", isExec)\n if (!found) problems.push(`Reminders: ${command} not found (brew install steipete/tap/remindctl, or set reminders.command).`)\n return { os: \"macos\", tasks: true, notes: true, banner: true, sound: true, focus: true, problems }\n },\n }\n}\n","import { execFile } from \"child_process\"\n\n/** Runs a program; resolves true when it exited 0. Never rejects. */\nexport type Run = (file: string, args: string[]) => Promise<boolean>\n\n/** Runs a program; resolves its stdout, or rejects with its stderr. */\nexport type Output = (file: string, args: string[]) => Promise<string>\n\n/** Runs a program; resolves its stdout, or null when it failed. */\nexport type Capture = (file: string, args: string[]) => Promise<string | null>\n\n/** A banner or a sound may not hold a caller hostage: afplay on a long\n * custom sound, or osascript stuck on a permission prompt, is cut off. */\nconst STEP_TIMEOUT_MS = 5_000\n\nexport const run: Run = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err) => done(!err))\n } catch {\n done(false) // the program is not on this machine: not worth reporting\n }\n })\n\nexport const capture: Capture = (file, args) =>\n new Promise((done) => {\n try {\n execFile(file, args, { timeout: STEP_TIMEOUT_MS }, (err, stdout) => done(err ? null : String(stdout)))\n } catch {\n done(null)\n }\n })\n\nexport const output: Output = (file, args) =>\n new Promise((resolve, reject) => {\n execFile(file, args, { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {\n if (err) reject(new Error(`${file} ${args[0]}: ${(stderr || err.message).trim()}`))\n else resolve(stdout)\n })\n })\n","import { findHelper } from \"@/desktop/install\"\nimport type { BannerStatus, NativeBanner } from \"../types\"\nimport { capture as defaultCapture, run as defaultRun, type Capture, type Run } from \"./run\"\n\n// The banner is posted by the AgentX Helper app when it is installed, so it\n// carries the helper's icon (the AgentX logo by default). Without the\n// helper, or before macOS has allowed it to notify, osascript posts it, and\n// macOS shows it as coming from Script Editor.\n\nexport interface BannerIo {\n run?: Run\n capture?: Capture\n /** The helper binary; null means none. Unset: looked up on each use. */\n helper?: string | null\n}\n\nconst helperOf = (io: BannerIo): string | null => (io.helper === undefined ? findHelper() : io.helper)\n\n/** What the helper reports about its notification permission. Never shows\n * the macOS \"allow notifications\" prompt and never posts a banner. */\nexport async function helperBannerStatus(path: string | null, capture: Capture = defaultCapture): Promise<BannerStatus> {\n if (!path) return \"missing\"\n const out = await capture(path, [\"notify-status\"])\n let status: { authorization?: string; alertStyle?: string } | null = null\n try { status = out ? JSON.parse(out) : null } catch { status = null }\n if (!status) return \"outdated\"\n if (status.authorization === \"notDetermined\") return \"not-asked\"\n if (status.authorization === \"denied\") return \"not-allowed\"\n if (status.alertStyle === \"none\") return \"hidden\"\n return \"ready\"\n}\n\nexport function macosBanner(io: BannerIo = {}): NativeBanner {\n const exec = io.run ?? defaultRun\n return {\n async post({ title, message }) {\n const helper = helperOf(io)\n // A non-zero exit is usually \"not allowed to notify yet\" (the first\n // banner asks), so this one goes through osascript instead.\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return \"posted\"\n // Title and message travel as argv, never spliced into the script,\n // so a quote in either cannot turn into AppleScript.\n const ok = await exec(\"/usr/bin/osascript\", [\n \"-e\", \"on run argv\",\n \"-e\", \"display notification (item 2 of argv) with title (item 1 of argv)\",\n \"-e\", \"end run\",\n title, message,\n ])\n return ok ? \"posted\" : \"failed\"\n },\n status: () => helperBannerStatus(helperOf(io), io.capture),\n }\n}\n","import type { NativeIdle } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"./run\"\n\n// --- How long since the person touched this Mac (#1138 step B) ---\n//\n// The HID system keeps the time since the last keyboard, mouse or trackpad\n// input, in nanoseconds. ioreg prints it without any permission prompt.\n\n/** Seconds idle from `ioreg -c IOHIDSystem -d 4` output, or null. */\nexport function idleSecondsIn(ioreg: string): number | null {\n const m = ioreg.match(/\"HIDIdleTime\"\\s*=\\s*(\\d+)/)\n return m ? Math.floor(Number(m[1]) / 1e9) : null\n}\n\nexport function macosIdle(io: { capture?: Capture } = {}): NativeIdle {\n const capture = io.capture ?? defaultCapture\n return {\n async seconds() {\n const out = await capture(\"/usr/sbin/ioreg\", [\"-c\", \"IOHIDSystem\", \"-d\", \"4\"])\n return out ? idleSecondsIn(out) : null\n },\n }\n}\n","import type { NativeNotes } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Notes through JXA (osascript -l JavaScript). The folder, title\n// and body travel as argv and are read by the script, never spliced into\n// it, so nothing in them can run as code. Notes stores a body as HTML:\n// the script escapes the text and keeps its line breaks. The first call\n// from the daemon's process asks for the macOS Automation permission\n// (System Settings › Privacy & Security › Automation › Notes).\n\nexport const NOTES_SCRIPT = `\nfunction run(argv) {\n var folderName = argv[0], title = argv[1], body = argv[2]\n var Notes = Application(\"Notes\")\n var esc = function (s) { return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\") }\n var folder = Notes.folders.whose({ name: folderName })()[0]\n if (!folder) {\n folder = Notes.Folder({ name: folderName })\n Notes.folders.push(folder)\n folder = Notes.folders.whose({ name: folderName })()[0]\n }\n var lines = body.split(\"\\\\n\").map(function (l) { return \"<div>\" + (l ? esc(l) : \"<br>\") + \"</div>\" })\n // Notes takes the title from the first line: a name as well would show it twice.\n var note = Notes.Note({ body: \"<div><h1>\" + esc(title) + \"</h1></div>\" + lines.join(\"\") })\n folder.notes.push(note)\n return note.id()\n}\n`\n\nexport function macosNotes(exec: Output = defaultOutput): NativeNotes {\n return {\n async add({ folder, title, body }) {\n const raw = await exec(\"/usr/bin/osascript\", [\"-l\", \"JavaScript\", \"-e\", NOTES_SCRIPT, folder, title, body])\n const id = raw.trim()\n if (!id) throw new Error(\"Notes did not return the new note's id\")\n return { id }\n },\n }\n}\n","import { existsSync, readdirSync } from \"fs\"\nimport type { NativeSound } from \"../types\"\nimport { run as defaultRun, type Run } from \"./run\"\n\nconst SOUNDS = \"/System/Library/Sounds\"\n\n/** The system sound file for a name, or null when there is none. Names\n * only: a path in the config must not reach afplay. */\nexport function soundPath(name: string): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = `${SOUNDS}/${name}.aiff`\n return existsSync(path) ? path : null\n}\n\nexport function macosSound(io: { run?: Run } = {}): NativeSound {\n const exec = io.run ?? defaultRun\n return {\n async play(name, volume) {\n const path = soundPath(name)\n if (!path) return\n await exec(\"/usr/bin/afplay\", [\"-v\", String(Math.min(1, Math.max(0, volume))), path])\n },\n has: (name) => soundPath(name) !== null,\n async names() {\n try {\n return readdirSync(SOUNDS).filter((f) => f.endsWith(\".aiff\")).map((f) => f.slice(0, -5)).sort()\n } catch {\n return []\n }\n },\n }\n}\n","import type { NativeSpeech } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"./run\"\n\n// --- Is something else speaking on this Mac? (#1126) ---\n//\n// A script that narrates with `say`, or plays a recording with `afplay`,\n// talks to the person at this Mac without going through AgentX's speaking\n// queue. Before AgentX speaks or chimes, it looks at the process list:\n// one such program running, not started by AgentX itself, means wait.\n\n/** Programs that speak or play sound, and how the owner would say it. */\nconst SPEAKERS: Record<string, string> = { say: \"a spoken line (say)\", afplay: \"a sound playing (afplay)\" }\n\n/** \"pid ppid command\" lines from ps, the speakers among them. */\nexport function speakersIn(ps: string, exceptParents: number[], self = process.pid): string | null {\n for (const line of ps.split(\"\\n\")) {\n const m = line.trim().match(/^(\\d+)\\s+(\\d+)\\s+(\\S+)/)\n if (!m) continue\n const [pid, ppid, comm] = [Number(m[1]), Number(m[2]), m[3]]\n const name = comm.slice(comm.lastIndexOf(\"/\") + 1)\n if (!(name in SPEAKERS) || pid === self || exceptParents.includes(ppid)) continue\n return SPEAKERS[name]\n }\n return null\n}\n\nexport function macosSpeech(io: { capture?: Capture } = {}): NativeSpeech {\n const capture = io.capture ?? defaultCapture\n return {\n async othersSpeaking(opts = {}) {\n const ps = await capture(\"/bin/ps\", [\"-axo\", \"pid=,ppid=,comm=\"])\n return ps ? speakersIn(ps, opts.exceptParents ?? []) : null\n },\n }\n}\n","import type { NativeTask, NativeTasks } from \"../types\"\nimport { output as defaultOutput, type Output } from \"./run\"\n\n// Apple Reminders through remindctl (Homebrew). It is the same tool the\n// mac-pim skill uses, so the daemon and the skill see the same lists. The\n// first call from the daemon's process triggers the macOS Reminders\n// permission prompt.\n//\n// Every value travels as its own argv entry, never through a shell, so\n// quotes and newlines arrive as typed. remindctl 0.1.1 reads any value\n// that starts with \"-\" as an option (and a value equal to --help or\n// --version runs that), and has no \"--opt=value\" form, so such a value\n// gets an invisible zero-width space in front. Reminders keeps that\n// character; listOpen takes it off again. A list name is a lookup key and\n// cannot carry it, so a list name that starts with \"-\" is refused.\n//\n// Reminders keeps a due time to the minute, in this Mac's time zone:\n// seconds are dropped.\n\nconst ZWSP = \"\\u200b\"\n\n/** A value remindctl takes literally. */\nexport function argValue(v: string): string {\n return v.startsWith(\"-\") ? ZWSP + v : v\n}\n\nconst unArg = (v: string | undefined): string | undefined => (v?.startsWith(ZWSP + \"-\") ? v.slice(1) : v)\n\nfunction listName(list: string): string {\n if (!list.trim() || list.startsWith(\"-\")) throw new Error(`Reminders list name \"${list}\" is not usable: it must not be empty or start with \"-\"`)\n return list\n}\n\n/** ISO to the minute, which is all Reminders keeps. */\nconst isoDue = (d: Date): string => new Date(Math.floor(d.getTime() / 60_000) * 60_000).toISOString().replace(/\\.\\d{3}Z$/, \"Z\")\n\nexport function macosTasks(command = \"remindctl\", exec: Output = defaultOutput): NativeTasks {\n return {\n async ensureList(list) {\n const raw = await exec(command, [\"list\", \"--json\", \"--no-input\"])\n const lists = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(lists)) throw new Error(`${command} list: expected a JSON array`)\n if (lists.some((l: { title?: string }) => l?.title === list)) return\n await exec(command, [\"list\", listName(list), \"--create\", \"--json\", \"--no-input\"])\n },\n async listOpen(list) {\n const raw = await exec(command, [\"show\", \"all\", \"--list\", listName(list), \"--json\", \"--no-input\"])\n const items = JSON.parse(raw.trim() || \"[]\")\n if (!Array.isArray(items)) throw new Error(`${command} show: expected a JSON array`)\n return items\n .filter((r: NativeTask) => r && typeof r.id === \"string\" && !r.isCompleted)\n .map((r: NativeTask) => ({ ...r, title: unArg(r.title) ?? \"\", ...(r.notes !== undefined ? { notes: unArg(r.notes) } : {}) }))\n },\n async add({ list, title, notes, due, priority }) {\n const args = [\"add\", \"--title\", argValue(title), \"--list\", listName(list), \"--notes\", argValue(notes)]\n if (due) args.push(\"--due\", isoDue(due))\n if (priority && priority !== \"none\") args.push(\"--priority\", priority)\n const raw = await exec(command, [...args, \"--json\", \"--no-input\"])\n let id: unknown\n try { id = JSON.parse(raw.trim())?.id } catch { id = undefined }\n if (typeof id !== \"string\" || !id) throw new Error(`${command} add: no reminder id in its answer`)\n return { id }\n },\n async update(id, patch) {\n const args = [\"edit\", id]\n if (patch.title !== undefined) args.push(\"--title\", argValue(patch.title))\n if (patch.notes !== undefined) args.push(\"--notes\", argValue(patch.notes))\n if (patch.due === null) args.push(\"--clear-due\")\n else if (patch.due) args.push(\"--due\", isoDue(patch.due))\n // remindctl refuses an edit that changes nothing; so does this.\n if (args.length === 2) return\n await exec(command, [...args, \"--json\", \"--no-input\"])\n },\n async complete(id) {\n await exec(command, [\"complete\", id, \"--json\", \"--no-input\"])\n },\n async remove(id) {\n await exec(command, [\"delete\", id, \"--force\", \"--json\", \"--no-input\"])\n },\n }\n}\n","import type { NativeAdapter } from \"./types\"\n\n/** The adapter for a machine AgentX has no OS layer for, or where the owner\n * turned it off. Every capability is absent; describe() says why. */\nexport function noneAdapter(reason: string): NativeAdapter {\n return {\n os: \"none\",\n async describe() {\n return { os: \"none\", tasks: false, notes: false, banner: false, sound: false, focus: false, problems: [reason] }\n },\n }\n}\n","import { existsSync, readdirSync } from \"fs\"\nimport { win32 } from \"path\"\nimport { findHelper } from \"@/desktop/install\"\nimport type { NativeAdapter } from \"../types\"\nimport type { Capture, Run } from \"../macos/run\"\nimport { windowsBanner } from \"./banner\"\nimport { windowsIdle } from \"./idle\"\nimport { windowsSound } from \"./sound\"\n\n// --- Windows (#1594) ---\n//\n// Only what Windows does with nothing installed: toasts, system sounds and\n// idle time. Tasks, notes and Focus have no adapter here yet, so callers see\n// them as absent and keep their own fallbacks; describe() says so.\n\n/** Programs and files the adapter touches, so tests can stand in for them. */\nexport interface WindowsIo {\n run?: Run\n capture?: Capture\n /** The desktop helper binary; null means none. Unset: looked up on use. */\n helper?: string | null\n /** %WINDIR%\\Media; defaults from WINDIR. */\n media?: string\n exists?: (path: string) => boolean\n list?: (dir: string) => string[]\n}\n\nexport function windowsAdapter(_cfg: unknown = {}, io: WindowsIo = {}): NativeAdapter {\n const helper = () => (io.helper === undefined ? findHelper() : io.helper)\n const media = io.media ?? win32.join(process.env.WINDIR || process.env.SystemRoot || \"C:\\\\Windows\", \"Media\")\n const exists = io.exists ?? existsSync\n const list = io.list ?? ((dir: string) => readdirSync(dir))\n return {\n os: \"windows\",\n banner: windowsBanner({ run: io.run, capture: io.capture, helper }),\n sound: windowsSound({ run: io.run, media, exists, list }),\n idle: windowsIdle({ capture: io.capture }),\n async describe() {\n const problems = [\"Tasks, notes and Focus: AgentX has no Windows adapter for these yet.\"]\n if (!helper()) problems.push(\"Banners come from Windows PowerShell until the AgentX Windows helper is installed.\")\n return { os: \"windows\", tasks: false, notes: false, banner: true, sound: true, focus: false, problems }\n },\n }\n}\n","// --- Running a short PowerShell script safely (#1594) ---\n//\n// Windows PowerShell 5.1 ships with every Windows 10 and 11, so the adapter\n// needs nothing installed. Values never travel on a command line that cmd\n// or PowerShell would parse: the script goes as -EncodedCommand (base64\n// UTF-16LE), and every value inside it is a single-quoted literal.\n\nexport const POWERSHELL = \"powershell.exe\"\n\n/** A PowerShell single-quoted string literal. Inside one only a quote is\n * special, and PowerShell treats the curly quotes as quotes too, so each\n * is doubled. Nothing in it is expanded. */\nexport function psString(value: string): string {\n return `'${value.replace(/['‘’‚‛]/g, (q) => q + q)}'`\n}\n\n/** Arguments that run `script` with no profile and no prompt. */\nexport function psArgs(script: string): string[] {\n return [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", Buffer.from(script, \"utf16le\").toString(\"base64\")]\n}\n","import type { NativeBanner } from \"../types\"\nimport { helperBannerStatus } from \"../macos/banner\"\nimport { capture as defaultCapture, run as defaultRun, type Capture, type Run } from \"../macos/run\"\nimport { POWERSHELL, psArgs, psString } from \"./powershell\"\n\n// A Windows toast. The AgentX Windows helper posts it when installed, so it\n// carries the helper's name; without it, PowerShell posts it and Windows\n// shows it as coming from Windows PowerShell. The helper answers the same\n// `notify` / `notify-status` verbs as the macOS one (computer-use/contract.ts).\n\n/** Windows PowerShell's own app id, which may post toasts with no setup. */\nexport const POWERSHELL_APP_ID = \"{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\"\n\n/** The PowerShell that shows one toast with a title line and a message line. */\nexport function toastScript(title: string, message: string): string {\n return [\n \"$ErrorActionPreference = 'Stop'\",\n \"[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null\",\n \"$t = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)\",\n \"$x = $t.GetElementsByTagName('text')\",\n `$x.Item(0).AppendChild($t.CreateTextNode(${psString(title)})) | Out-Null`,\n `$x.Item(1).AppendChild($t.CreateTextNode(${psString(message)})) | Out-Null`,\n `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(${psString(POWERSHELL_APP_ID)}).Show([Windows.UI.Notifications.ToastNotification]::new($t))`,\n ].join(\"\\n\")\n}\n\nexport interface WindowsBannerIo {\n run?: Run\n capture?: Capture\n /** The helper binary; null means none. */\n helper: () => string | null\n}\n\nexport function windowsBanner(io: WindowsBannerIo): NativeBanner {\n const exec = io.run ?? defaultRun\n return {\n async post({ title, message }) {\n const helper = io.helper()\n if (helper && await exec(helper, [\"notify\", \"--title\", title, \"--message\", message])) return \"posted\"\n return (await exec(POWERSHELL, psArgs(toastScript(title, message)))) ? \"posted\" : \"failed\"\n },\n status: () => helperBannerStatus(io.helper(), io.capture ?? defaultCapture),\n }\n}\n","import type { NativeIdle } from \"../types\"\nimport { capture as defaultCapture, type Capture } from \"../macos/run\"\nimport { POWERSHELL, psArgs } from \"./powershell\"\n\n// --- How long since the person touched this PC ---\n//\n// GetLastInputInfo gives the tick of the last keyboard or mouse input for\n// this session, with no permission needed. PowerShell reaches it through a\n// small inline type; the script prints milliseconds idle.\n\nexport const IDLE_SCRIPT = [\n \"Add-Type -TypeDefinition @'\",\n \"using System; using System.Runtime.InteropServices;\",\n \"public static class AgentXIdle {\",\n \" [StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }\",\n \" [DllImport(\\\"user32.dll\\\")] static extern bool GetLastInputInfo(ref LASTINPUTINFO p);\",\n \" public static long Ms() { var i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);\",\n \" if (!GetLastInputInfo(ref i)) return -1; return (long)(uint)(Environment.TickCount - (int)i.dwTime); }\",\n \"}\",\n \"'@\",\n \"[AgentXIdle]::Ms()\",\n].join(\"\\n\")\n\n/** Seconds idle from the script's output, or null. */\nexport function idleSecondsFromMs(out: string): number | null {\n const ms = Number(out.trim())\n return Number.isFinite(ms) && ms >= 0 && out.trim() !== \"\" ? Math.floor(ms / 1000) : null\n}\n\nexport function windowsIdle(io: { capture?: Capture } = {}): NativeIdle {\n const capture = io.capture ?? defaultCapture\n return {\n async seconds() {\n const out = await capture(POWERSHELL, psArgs(IDLE_SCRIPT))\n return out ? idleSecondsFromMs(out) : null\n },\n }\n}\n","import { win32 } from \"path\"\nimport type { NativeSound } from \"../types\"\nimport { run as defaultRun, type Run } from \"../macos/run\"\nimport { POWERSHELL, psArgs, psString } from \"./powershell\"\n\n// Windows keeps its system sounds as .wav files in %WINDIR%\\Media\n// (\"Windows Notify System Generic\", \"chimes\", \"tada\" and so on). PowerShell's\n// SoundPlayer plays one with nothing installed. It has no volume control,\n// so the volume only decides whether the sound plays at all.\n\nexport interface WindowsSoundIo {\n run?: Run\n /** The Media folder; defaults to %WINDIR%\\Media. */\n media: string\n exists: (path: string) => boolean\n list: (dir: string) => string[]\n}\n\n/** The .wav for a sound name, or null. Names only: a path in the config\n * must not reach the player. */\nexport function windowsSoundPath(name: string, io: Pick<WindowsSoundIo, \"media\" | \"exists\">): string | null {\n if (!/^[\\w -]+$/.test(name)) return null\n const path = win32.join(io.media, `${name}.wav`)\n return io.exists(path) ? path : null\n}\n\nexport function windowsSound(io: WindowsSoundIo): NativeSound {\n const exec = io.run ?? defaultRun\n return {\n async play(name, volume) {\n const path = windowsSoundPath(name, io)\n if (!path || !(volume > 0)) return\n await exec(POWERSHELL, psArgs(`(New-Object Media.SoundPlayer ${psString(path)}).PlaySync()`))\n },\n has: (name) => windowsSoundPath(name, io) !== null,\n async names() {\n try {\n return io.list(io.media).filter((f) => /\\.wav$/i.test(f)).map((f) => f.slice(0, -4)).sort()\n } catch {\n return []\n }\n },\n }\n}\n","import { macosAdapter, type MacosIo } from \"./macos\"\nimport { noneAdapter } from \"./none\"\nimport { windowsAdapter, type WindowsIo } from \"./windows\"\nimport type { NativeAdapter } from \"./types\"\n\nexport * from \"./types\"\nexport { noneAdapter } from \"./none\"\n\nexport type NativeAdapterChoice = \"auto\" | \"none\"\n\nexport type NativeConfig = { native?: { adapter?: NativeAdapterChoice }; reminders?: { command?: string } }\n\n/** Programs an adapter runs, so tests can stand in for them. */\nexport type NativeIo = MacosIo & WindowsIo\n\n/** Builds the adapter for one OS. Each OS adapter registers here. */\nexport type NativeAdapterFactory = (cfg: NativeConfig, io: NativeIo) => NativeAdapter\n\nconst FACTORIES: Partial<Record<NodeJS.Platform, NativeAdapterFactory>> = {\n darwin: macosAdapter,\n win32: windowsAdapter,\n}\n\n/** The adapter for this machine. `native.adapter: \"none\"` forces none on\n * any OS; \"auto\" (the default) picks by platform. */\nexport function loadNativeAdapter(\n cfg: NativeConfig = {},\n opts: { platform?: NodeJS.Platform; factories?: Partial<Record<NodeJS.Platform, NativeAdapterFactory>>; io?: NativeIo } = {},\n): NativeAdapter {\n if (cfg.native?.adapter === \"none\") return noneAdapter(\"Turned off: native.adapter is \\\"none\\\".\")\n const platform = opts.platform ?? process.platform\n const make = (opts.factories ?? FACTORIES)[platform]\n return make ? make(cfg, opts.io ?? {}) : noneAdapter(`AgentX has no native adapter for ${platform} yet.`)\n}\n","import { existsSync } from \"fs\"\nimport { homedir } from \"os\"\nimport { isAbsolute } from \"path\"\nimport { loadNativeAdapter, type NativeConfig, type NativeIo, type NativeSpeech } from \"@/native\"\n\nexport { findHelper } from \"@/desktop/install\"\n\n// What happens on THIS machine when a notification is delivered: a banner\n// on screen and a short sound. The push goes to the phone; these are for\n// the person sitting at the computer that raised the event. Both go\n// through the native adapter (src/native); a machine without one skips\n// them.\n//\n// Both are awaited rather than fired and forgotten. A caller that exits\n// straight after notifying — a `launchctl submit` job that removes itself,\n// a cron one-liner — used to take the sound down with it before it\n// played. Waiting costs about a second and makes the step reliable.\n//\n// Never fatal: a notification whose banner failed still arrived, and no\n// caller should have to handle an audio error to say a build finished.\n\nexport interface LocalSettings {\n /** Show a desktop banner (macOS only; other platforms skip it). */\n banner: boolean\n /** Play a sound (macOS only). */\n sound: boolean\n /** A system sound, by name (on a Mac, one of the sounds in System Settings › Sound). */\n soundName: string\n /** 0 (silent) … 1 (full). */\n volume: number\n /** Seconds the sound waits while something else speaks on this machine\n * (#1126). Still speaking after that: no sound, the banner is enough.\n * 0: never wait. */\n quietWaitSeconds?: number\n /** Image for the helper's app icon, which macOS puts on its banners.\n * Unset: the AgentX logo. Applied when `agentx desktop install` builds\n * the helper, since macOS reads the icon from the app, not the banner. */\n icon?: string\n}\n\n/** Glass is the gentlest system sound that is still audible over a\n * keyboard — Basso and Sosumi are alerts, Funk and Frog are jokes, and\n * Ping is the one every other app already uses. */\nexport const DEFAULT_LOCAL: LocalSettings = { banner: true, sound: true, soundName: \"Glass\", volume: 0.4, quietWaitSeconds: 15 }\n\n/** Shows the banner and plays the sound for one delivered notification. */\nexport type LocalAlert = (title: string, message: string) => Promise<void>\n\n/** Fill gaps in a partial `notifications.local` block with the defaults. */\nexport function localSettings(cfg: Partial<LocalSettings> | undefined): LocalSettings {\n return { ...DEFAULT_LOCAL, ...(cfg ?? {}) }\n}\n\nexport function localAlert(\n settings: LocalSettings,\n deps: {\n run?: NativeIo[\"run\"]; capture?: NativeIo[\"capture\"]; platform?: NodeJS.Platform; helper?: string | null; native?: NativeConfig[\"native\"]\n /** For tests: the poll between two looks at who is speaking. */\n pollMs?: number\n } = {},\n): LocalAlert {\n const native = loadNativeAdapter({ native: deps.native }, { platform: deps.platform, io: { run: deps.run, capture: deps.capture, helper: deps.helper } })\n return async (title, message) => {\n const steps: Promise<unknown>[] = []\n if (settings.banner && native.banner) steps.push(native.banner.post({ title, message }))\n if (settings.sound && native.sound) {\n const sound = native.sound\n // A chime over someone speaking is the collision #1126 is about:\n // the banner goes up at once, the sound waits for quiet.\n steps.push(quiet(native.speech, (settings.quietWaitSeconds ?? DEFAULT_LOCAL.quietWaitSeconds!) * 1000, deps.pollMs ?? 500)\n .then((ok) => (ok ? sound.play(settings.soundName, settings.volume) : undefined)))\n }\n await Promise.all(steps)\n }\n}\n\n/** True once nothing else speaks on this machine, false when something\n * still does after `waitMs`. Without a way to tell, true at once. The\n * daemon's own speech counts too (no `exceptParents` here, unlike the\n * speaking queue): a chime over a spoken reply is the same interruption,\n * so it waits, and past the wait the banner shows without the sound. */\nasync function quiet(speech: NativeSpeech | undefined, waitMs: number, pollMs: number): Promise<boolean> {\n if (!speech || waitMs <= 0) return true\n const until = Date.now() + waitMs\n for (;;) {\n if (!(await speech.othersSpeaking())) return true\n if (Date.now() >= until) return false\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Apply a change to a stored `notifications.local` block, the one rule\n * both the CLI and the dashboard write through. Returns the new block;\n * throws on a value that would not load. Only a machine with a native\n * adapter has sounds to check a name against; elsewhere the setting is\n * inert, so it need only be well-formed.\n */\nexport function patchLocal(\n current: Partial<LocalSettings> | undefined,\n patch: Record<string, unknown>,\n platform: NodeJS.Platform = process.platform,\n): Partial<LocalSettings> {\n const next = { ...(current ?? {}) }\n const native = loadNativeAdapter({}, { platform })\n if (\"banner\" in patch) next.banner = Boolean(patch.banner)\n if (\"sound\" in patch) next.sound = Boolean(patch.sound)\n if (\"soundName\" in patch) {\n const name = String(patch.soundName).trim()\n const ok = native.sound ? native.sound.has(name) : /^[\\w -]+$/.test(name)\n if (!ok) throw new Error(`no system sound named \"${name}\" on this machine`)\n next.soundName = name\n }\n if (\"icon\" in patch) {\n const icon = String(patch.icon ?? \"\").trim().replace(/^~(?=\\/)/, homedir())\n if (!icon) delete next.icon\n else {\n if (!isAbsolute(icon) || !/\\.(png|jpe?g|icns)$/i.test(icon)) throw new Error(\"icon must be the full path to a .png, .jpg or .icns file\")\n if (native.banner && !existsSync(icon)) throw new Error(`no icon file at ${icon}`)\n next.icon = icon\n }\n }\n if (\"volume\" in patch) {\n const v = Number(patch.volume)\n if (!Number.isFinite(v) || v < 0 || v > 1) throw new Error(\"volume must be between 0 and 1\")\n next.volume = v\n }\n return next\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { NativePriority, NativeTasks } from \"@/native\"\nimport { cardWords, summarize } from \"@/requests/card-view\"\nimport type { RequestRecord } from \"@/requests/store\"\nimport { CARD_LIMITS, type DecisionCard } from \"./cards\"\n\n// --- The Reminders mirror (#1062 step 5) ---\n//\n// Each pending decision card, and each request waiting on the owner,\n// becomes one task in the OS task app (Apple Reminders on a Mac) with a due\n// time. Calendar shows it, and the system alert comes back when it falls\n// due. Answering stays on the Desk, the Approvals page or the CLI: a task\n// cannot carry choices or a draft.\n//\n// Runs once a minute beside the approvals sweep, on the node that holds the\n// cards (forwarded cards live on the owner's node, so that is where they\n// are mirrored). Off by default.\n//\n// Rules:\n// - one task per card or request, created once;\n// - the card is answered, expires or is closed, or the request stops\n// waiting on the owner: the task is completed;\n// - the owner ticks the task off or deletes it while the item still\n// waits: the item stays on the Desk and is never mirrored again.\n// Ticking a task is not an answer;\n// - three failed adds for one item: the owner is told once and that\n// item is not tried again;\n// - every task ends with `agentx: card=<id>` or `agentx: request=<id>`,\n// which check-ins and the reminders hand-back skip, so a mirrored\n// task never turns back into a card or an agent's job.\n//\n// State lives in its own file, written only by the daemon, not in the card\n// files that the CLI and the dashboard also write.\n\nexport interface MirrorSettings {\n enabled: boolean\n list: string\n dueAfterMinutes: number\n include: (\"card\" | \"request\")[]\n /** Where the owner answers. Unset: the local dashboard's Approvals page. */\n answerUrl?: string\n}\n\nexport type MirrorState = \"open\" | \"completed\" | \"dismissed\" | \"failed\"\n\nexport interface MirrorEntry {\n /** The task's id in the OS task app, once added. */\n id?: string\n list: string\n state: MirrorState\n /** ISO time of the last change. */\n at: string\n /** ISO time its task was added. Unset on entries from before #1062's\n * trial, and on items whose task was never added. */\n createdAt?: string\n failures: number\n lastError?: string\n}\n\nexport interface MirrorFile {\n /** Keyed `card:<id>` or `request:<id>`, the inbox's keys. */\n items: Record<string, MirrorEntry>\n /** ISO time of the last pass that read every list it needed. Stale\n * (the mirror was turned off, or the list can't be read) means the\n * mirror no longer covers anything, and the Mac popup is back. */\n checkedAt?: string\n /** That pass mirrored cards (include has \"card\"). */\n cards?: boolean\n /** ISO time the owner was last told adds are failing: once a day. */\n failureToldAt?: string\n /** The latest pass's last error, for doctor. */\n lastError?: { at: string; message: string }\n}\n\nexport const MAX_ADD_FAILURES = 3\n/** Closed entries are kept this long, then forgotten. */\nconst KEEP_CLOSED_MS = 30 * 24 * 3_600_000\n\nexport function mirrorPath(root: string): string {\n return resolve(root, \".agentx\", \"native-mirror.json\")\n}\n\nexport function readMirror(root: string): MirrorFile {\n try {\n const parsed = JSON.parse(readFileSync(mirrorPath(root), \"utf-8\"))\n return { ...parsed, items: parsed?.items && typeof parsed.items === \"object\" ? parsed.items : {} }\n } catch {\n return { items: {} }\n }\n}\n\nfunction writeMirror(root: string, file: MirrorFile): void {\n const path = mirrorPath(root)\n if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true })\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(file, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\n/** A pass older than this means the mirror is not running. */\nexport const MIRROR_FRESH_MS = 5 * 60_000\n\n/** True when the mirror is running and covers this card: it has a task,\n * or gets one on the next pass, or the owner ticked its task off. The Mac\n * popup then leaves it alone, so the owner is not alerted twice. A card\n * whose task could not be added is not covered. */\nexport function mirrorCovers(root: string, cardId: string, now = Date.now()): boolean {\n const file = readMirror(root)\n const checked = file.checkedAt ? Date.parse(file.checkedAt) : NaN\n if (!file.cards || !(now - checked <= MIRROR_FRESH_MS)) return false\n return file.items[`card:${cardId}`]?.state !== \"failed\"\n}\n\n/** What one task says. */\nexport interface MirrorItem {\n key: string\n title: string\n notes: string\n due: Date\n priority: NativePriority\n}\n\nconst DAY_MS = 24 * 3_600_000\n\nfunction dueFor(now: number, settings: MirrorSettings, limit?: number): Date {\n const due = now + settings.dueAfterMinutes * 60_000\n return new Date(limit !== undefined && Number.isFinite(limit) ? Math.max(now, Math.min(due, limit)) : due)\n}\n\nexport function cardItem(card: DecisionCard, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const expires = Date.parse(card.expires)\n const lines = [summarize(card.ask, CARD_LIMITS.ask)]\n if (card.choices?.length) lines.push(...card.choices.map((c, i) => `${i + 1}. ${c}`))\n if (card.recommend) lines.push(`Recommended: ${summarize(card.recommend, CARD_LIMITS.recommend)}`)\n lines.push(`Answer: ${answerUrl}`, `agentx: card=${card.id}`)\n return {\n key: `card:${card.id}`,\n title: summarize(card.title, CARD_LIMITS.title),\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, expires),\n priority: Number.isFinite(expires) && expires - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport function requestItem(r: RequestRecord, settings: MirrorSettings, answerUrl: string, now: number): MirrorItem {\n const lines = [summarize(r.question || r.text, CARD_LIMITS.ask), `Asked of ${r.agentId}.`, `Answer: ${answerUrl}`, `agentx: request=${r.id}`]\n const dueAt = r.dueAt ?? undefined\n return {\n key: `request:${r.id}`,\n title: cardWords(r, CARD_LIMITS.title).headline,\n notes: lines.join(\"\\n\"),\n due: dueFor(now, settings, dueAt),\n priority: dueAt !== undefined && dueAt - now <= DAY_MS ? \"high\" : \"none\",\n }\n}\n\nexport interface MirrorDeps {\n root: string\n settings: MirrorSettings\n tasks: NativeTasks\n /** Pending cards on this node. */\n cards: () => DecisionCard[]\n /** Requests in waiting_owner. */\n requests: () => RequestRecord[]\n answerUrl: string\n /** Tell the owner, through the usual notification. */\n notify: (title: string, message: string) => Promise<void>\n log: (msg: string) => void\n now?: number\n}\n\nexport interface MirrorResult {\n created: number\n completed: number\n dismissed: number\n failed: number\n}\n\n/** One pass of the mirror. Never throws. */\nexport async function runMirror(deps: MirrorDeps): Promise<MirrorResult> {\n const { root, settings, tasks, log } = deps\n const now = deps.now ?? Date.now()\n const at = new Date(now).toISOString()\n const result: MirrorResult = { created: 0, completed: 0, dismissed: 0, failed: 0 }\n const file = readMirror(root)\n // lastError says how the latest pass went: a clean pass clears it.\n delete file.lastError\n const fail = (message: string) => { file.lastError = { at, message } }\n\n const waiting = new Map<string, MirrorItem>()\n try {\n if (settings.include.includes(\"card\")) {\n for (const c of deps.cards()) if (c.status === \"pending\" && Date.parse(c.expires) > now) waiting.set(`card:${c.id}`, cardItem(c, settings, deps.answerUrl, now))\n }\n if (settings.include.includes(\"request\")) {\n for (const r of deps.requests()) if (r.state === \"waiting_owner\") waiting.set(`request:${r.id}`, requestItem(r, settings, deps.answerUrl, now))\n }\n } catch (e: any) {\n log(`[mirror] could not read what is waiting: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n writeMirror(root, file)\n return result\n }\n\n // Close or notice dismissal for what is already mirrored. The open list\n // is read once per list; when it can't be read, nothing is closed or\n // dismissed this pass, so a hiccup never loses a task.\n let allRead = true\n const openIds = new Map<string, Set<string> | null>()\n const openIn = async (list: string): Promise<Set<string> | null> => {\n if (!openIds.has(list)) {\n try {\n openIds.set(list, new Set((await tasks.listOpen(list)).map((t) => t.id)))\n } catch (e: any) {\n log(`[mirror] could not read list \"${list}\": ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n openIds.set(list, null)\n allRead = false\n }\n }\n return openIds.get(list)!\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" || !entry.id) continue\n const open = await openIn(entry.list)\n if (!open) continue\n if (!waiting.has(key)) {\n if (open.has(entry.id)) {\n try {\n await tasks.complete(entry.id)\n } catch (e: any) {\n log(`[mirror] ${key}: could not complete its task: ${e?.message ?? e}`)\n fail(String(e?.message ?? e))\n continue\n }\n }\n file.items[key] = { ...entry, state: \"completed\", at }\n result.completed++\n } else if (!open.has(entry.id)) {\n file.items[key] = { ...entry, state: \"dismissed\", at }\n result.dismissed++\n log(`[mirror] ${key}: its task was ticked off or deleted; it stays on the Desk and is not mirrored again`)\n }\n }\n\n let listReady: boolean | null = null\n let listError = \"\"\n let cardsMissed = 0\n const gaveUp: { title: string; message: string }[] = []\n for (const [key, item] of waiting) {\n const entry = file.items[key]\n if (entry && (entry.state === \"open\" || entry.state === \"dismissed\")) continue\n if (entry?.state === \"failed\" && entry.failures >= MAX_ADD_FAILURES) continue\n // The list is made on the first add of a pass, when it is missing.\n if (listReady === null) {\n try {\n await tasks.ensureList(settings.list)\n listReady = true\n } catch (e: any) {\n log(`[mirror] could not make list \"${settings.list}\": ${e?.message ?? e}`)\n listError = String(e?.message ?? e)\n fail(listError)\n listReady = false\n }\n }\n const failures = entry?.state === \"failed\" ? entry.failures : 0\n try {\n // No list (access denied, or a permission prompt nobody answers under\n // launchd, which runs into the timeout): every add would fail the\n // same way, one timeout each. Count it as this item's failed add\n // without trying.\n if (listReady === false) throw new Error(listError)\n const { id } = await tasks.add({ list: settings.list, title: item.title, notes: item.notes, due: item.due, priority: item.priority })\n file.items[key] = { id, list: settings.list, state: \"open\", at, createdAt: at, failures: 0 }\n result.created++\n } catch (e: any) {\n const message = String(e?.message ?? e)\n if (key.startsWith(\"card:\")) cardsMissed++\n const n = failures + 1\n file.items[key] = { list: settings.list, state: \"failed\", at, failures: n, lastError: message }\n fail(message)\n result.failed++\n log(`[mirror] ${key}: could not add to Reminders (${n}/${MAX_ADD_FAILURES}): ${message}`)\n if (n === MAX_ADD_FAILURES) gaveUp.push({ title: item.title, message })\n }\n }\n\n // A card without a task is not covered (mirrorCovers): the Mac popup\n // shows it. Said once a pass, so the fallback is in the log.\n if (cardsMissed) log(`[mirror] ${cardsMissed} card(s) could not be added to Reminders; the Mac popup shows them instead`)\n\n // One notification a day at most, however many items gave up: a missing\n // permission fails every card the same way.\n const told = file.failureToldAt ? Date.parse(file.failureToldAt) : NaN\n if (gaveUp.length && !(now - told < DAY_MS)) {\n const first = gaveUp[0]\n const more = gaveUp.length > 1 ? ` (and ${gaveUp.length - 1} more)` : \"\"\n try {\n await deps.notify(\"Could not add to Reminders\", `${first.title}${more}: ${summarize(first.message, 200)}. Still on the Desk.`)\n file.failureToldAt = at\n } catch (err: any) {\n log(`[mirror] could not tell the owner: ${err?.message ?? err}`)\n }\n }\n\n if (allRead) {\n file.checkedAt = at\n file.cards = settings.include.includes(\"card\")\n }\n\n for (const [key, entry] of Object.entries(file.items)) {\n if (entry.state !== \"open\" && !waiting.has(key) && now - Date.parse(entry.at) > KEEP_CLOSED_MS) delete file.items[key]\n }\n writeMirror(root, file)\n return result\n}\n\n// --- The trial count (#1062 step 5) ---\n//\n// One line a day while the mirror is on trial: cards raised, Reminders\n// created, cards missed. A card closed before a pass could reach it (within\n// the grace below of being raised) is counted apart, not as a miss; so is\n// one still that new. Read from the card files and the mirror file, both\n// on this node.\n\n/** A card closed or still pending this soon after it was raised may never\n * have met a pass: it is not a miss. */\nexport const MIRROR_GRACE_MS = 5 * 60_000\n\nexport interface MirrorTally {\n from: string\n to: string\n /** Cards raised in [from, to). */\n raised: number\n /** Tasks added in [from, to), by kind. */\n created: { cards: number; requests: number }\n /** Cards raised in the window that never got a task, with why. */\n missed: { id: string; title: string; reason: string }[]\n /** Raised in the window and closed within the grace, with no task. */\n closedFast: number\n /** Raised within the grace of now, with no task yet. */\n tooNew: number\n}\n\nexport function mirrorTally(root: string, cards: DecisionCard[], from: number, to: number, now = Date.now()): MirrorTally {\n const file = readMirror(root)\n const inWindow = (iso?: string) => {\n const t = iso ? Date.parse(iso) : NaN\n return t >= from && t < to\n }\n const tally: MirrorTally = {\n from: new Date(from).toISOString(), to: new Date(to).toISOString(),\n raised: 0, created: { cards: 0, requests: 0 }, missed: [], closedFast: 0, tooNew: 0,\n }\n for (const [key, entry] of Object.entries(file.items)) {\n if (!entry.id || !inWindow(entry.createdAt)) continue\n if (key.startsWith(\"card:\")) tally.created.cards++\n else tally.created.requests++\n }\n for (const card of cards) {\n if (!inWindow(card.created_at)) continue\n tally.raised++\n const entry = file.items[`card:${card.id}`]\n if (entry?.id) continue\n const raisedAt = Date.parse(card.created_at)\n const closedAt = card.status === \"pending\" ? NaN : Date.parse(card.decided_at ?? \"\")\n if (closedAt - raisedAt <= MIRROR_GRACE_MS) { tally.closedFast++; continue }\n if (card.status === \"pending\" && now - raisedAt <= MIRROR_GRACE_MS) { tally.tooNew++; continue }\n const reason = entry?.state === \"failed\" ? `could not be added (${entry.failures}x): ${entry.lastError ?? \"unknown error\"}` : \"no pass reached it\"\n tally.missed.push({ id: card.id, title: card.title, reason })\n }\n return tally\n}\n\n/** The day's line for the trial issue. */\nexport function tallyLine(t: MirrorTally): string {\n const extra = [t.closedFast ? `closed within 5 min: ${t.closedFast}` : \"\", t.tooNew ? `raised in the last 5 min: ${t.tooNew}` : \"\"].filter(Boolean)\n return `cards raised ${t.raised} / Reminders created ${t.created.cards + t.created.requests} (${t.created.cards} cards, ${t.created.requests} requests) / missed ${t.missed.length}${extra.length ? ` · ${extra.join(\" · \")}` : \"\"}`\n}\n","import { markdownToHtml } from \"@/utils/markdown-html\"\nimport type { RequestRecord, RequestStore } from \"./store\"\nimport type { PlanState, PlanStore, StepState } from \"./plan-store\"\nimport { describeCloseWhen } from \"./checkers\"\nimport { activeStepAgentOf, stalledWhy, waitsOn, type StallGroup } from \"./loops\"\nimport { awaitingQa } from \"./qa\"\n\n// --- One open request as a card the owner can read in seconds (#459) ---\n//\n// The Approvals page shows each open request as a card: a short plain\n// summary, where it stands and why it is not finished, then the words the\n// owner used and the agent's last answer, both rendered. markdownToHtml\n// escapes before it marks up, so nothing an agent or a channel wrote\n// reaches the page as HTML. The summary is the request's headline (#1126);\n// a request without one yet falls back to the start of its own words,\n// without the markdown marks.\n\nexport const SUMMARY_MAX = 200\n/** An answer of pages is cut: the card is for reading quickly. */\nexport const ANSWER_MAX = 4000\n\n/** What a request needs from the owner when nothing does. */\nexport const NOTHING_NEEDED = \"Nothing, just so you know.\"\n\n/** A request as every surface titles it (#1126): what it is, the one\n * thing needed from the owner, and the owner's own words. The need\n * follows where it stands: a request that needs attention or waits on\n * the owner's answer says so, whatever the agent wrote earlier. */\nexport function cardWords(\n r: Pick<RequestRecord, \"text\" | \"headline\" | \"need\" | \"state\" | \"question\" | \"agentId\">,\n max = SUMMARY_MAX,\n): { headline: string; need: string; said: string } {\n const headline = r.headline ? (r.headline.length > max ? `${r.headline.slice(0, max - 1)}…` : r.headline) : summarize(r.text, max)\n const need = r.state === \"needs_attention\" ? `Hand it back to ${r.agentId}, or drop it.`\n : r.state === \"waiting_owner\" ? (r.need ?? (r.question ? `Answer: ${summarize(r.question, 150)}` : \"Your answer.\"))\n : r.state === \"candidate\" || r.state === \"in_progress\" || r.state === \"waiting_other\" ? (r.need ?? NOTHING_NEEDED)\n : NOTHING_NEEDED\n return { headline, need, said: plain(r.text) }\n}\n\nexport interface RequestCard extends RequestRecord {\n summary: string\n /** The one thing needed from the owner, in words: the agent's `need`\n * or what follows from where the request stands (cardWords). */\n needed: string\n /** The request in the owner's words (the transcript, when spoken). */\n textHtml: string\n /** Why it is not finished, or what is being asked. Null: work is under way. */\n why: string | null\n ownerNoteHtml: string | null\n lastAnswer: { agentId: string; at: number; html: string } | null\n /** The open loop (#1039): who it is owed to, when it is due, what\n * closes it. Null on a request with none of it. */\n loop: {\n owedTo: string | null\n promise: boolean\n dueAt: number | null\n /** What its check waits for, in words. */\n check: string | null\n verifyState: string | null\n verifyDetail: string | null\n } | null\n /** Marked as needing QA, with no verdict since (#1188). The verdict\n * itself is `qa`, from the record. */\n awaitingQa: boolean\n /** Stalled, and what it waits on. Null: not stalled, or not asked. */\n stall: { group: StallGroup; who: string; why: string } | null\n /** Its tracked plan (#788), step by step. Null: no plan. */\n plan: {\n state: PlanState\n steps: Array<{ idx: number; name: string; kind: string; agentId: string; state: StepState; approval: string | null; evidence: string | null; note: string | null; nudges: number }>\n } | null\n}\n\n/** Markdown to the words alone, on one line. */\nexport function plain(md: string): string {\n return md\n .replace(/```[\\s\\S]*?```/g, \" \")\n .replace(/!?\\[([^\\]]*)\\]\\([^)]*\\)/g, \"$1\")\n .replace(/^\\s{0,3}(#{1,6}|>|[-*+]|\\d+[.)])\\s+/gm, \"\")\n .replace(/[*_~`]+/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n}\n\n/** The start of the request, cut at a sentence when one ends in reach. */\nexport function summarize(md: string, max = SUMMARY_MAX): string {\n const text = plain(md)\n if (text.length <= max) return text\n const cut = text.slice(0, max)\n const end = Math.max(cut.lastIndexOf(\". \"), cut.lastIndexOf(\"? \"), cut.lastIndexOf(\"! \"))\n return end > max / 2 ? cut.slice(0, end + 1) : `${cut.slice(0, max - 1).trimEnd()}…`\n}\n\n/** What the stall view needs: the quiet time, the clock, and which ids are agents. */\nexport interface StallLookup { staleAfterHours: number; now: number; isAgent: (id: string) => boolean }\n\n/** A request's open loop (#1039): who it is owed to, when it is due, what\n * check closes it and what that check last said. Null: none of it. The\n * card and the Hub's post (#1440) both show it. */\nexport function loopOf(r: RequestRecord): RequestCard[\"loop\"] {\n return r.promise || r.dueAt !== null || r.closeWhen ? {\n owedTo: r.owedTo, promise: r.promise, dueAt: r.dueAt, check: r.closeWhen ? describeCloseWhen(r.closeWhen) : null,\n verifyState: r.verifyState, verifyDetail: r.verifyDetail,\n } : null\n}\n\nexport function requestCard(\n r: RequestRecord,\n store: Pick<RequestStore, \"lastAnswer\">,\n plans?: Pick<PlanStore, \"get\" | \"steps\"> | null,\n stall?: StallLookup,\n): RequestCard {\n const plan = plans?.get(r.id)\n const why = stall ? stalledWhy(r, stall.staleAfterHours, stall.now) : null\n const answer = store.lastAnswer(r.id)\n const cutAnswer = answer && answer.text.length > ANSWER_MAX ? `${answer.text.slice(0, ANSWER_MAX)}\\n\\n…` : answer?.text\n const words = cardWords(r)\n return {\n ...r,\n summary: words.headline,\n needed: words.need,\n textHtml: markdownToHtml(r.text),\n why: r.state === \"waiting_owner\" ? r.question : r.state === \"needs_attention\" ? r.attentionReason : null,\n ownerNoteHtml: r.ownerNote ? markdownToHtml(r.ownerNote) : null,\n lastAnswer: answer ? { agentId: answer.agentId, at: answer.at, html: markdownToHtml(cutAnswer!) } : null,\n loop: loopOf(r),\n awaitingQa: awaitingQa(r),\n stall: stall && why ? { ...waitsOn(r, { isAgent: stall.isAgent, activeStepAgent: activeStepAgentOf(plans) }), why } : null,\n plan: plan ? {\n state: plan.state,\n steps: plans!.steps(r.id).map((s) => ({\n idx: s.idx, name: s.name, kind: s.kind, agentId: s.agentId, state: s.state,\n approval: s.needsApproval ? s.approval : null, evidence: s.evidence, note: s.note, nudges: s.nudges,\n })),\n } : null,\n }\n}\n","import { OPEN_STATES, OWED_TO_OWNER, type RequestRecord, type RequestStore } from \"./store\"\nimport { runCheck, type CheckContext, type CheckResult, type CloseWhen } from \"./checkers\"\n\n// --- Open loops: who each one waits on, and when it is stalled (#1039) ---\n//\n// A loop is an open request: one the owner asked for, or one an agent\n// promised (action promise). It is stalled when it is past its due time,\n// or, without one, when nothing has happened for staleAfterHours. A loop\n// that needs attention is stalled too: nothing is retrying it.\n//\n// Stalled loops are grouped by what they wait on:\n// owner the owner's answer (waiting_owner), or the owner's decision\n// on one that needs attention\n// agent an agent: the one that has it, a plan step's agent, or the\n// agent it is owed to\n// person an outside person: a promise owed to a known person\n// The requests panel, `agentx requests --stalled` and the sweep's notice\n// all use this one grouping.\n\nexport const STALL_GROUPS = [\"owner\", \"agent\", \"person\"] as const\nexport type StallGroup = (typeof STALL_GROUPS)[number]\n\nexport interface StalledLoop {\n request: RequestRecord\n group: StallGroup\n /** Who it waits on: \"owner\", an agent id or a person id. */\n who: string\n /** Why it counts as stalled, in words. */\n why: string\n}\n\nexport interface LoopLookups {\n isAgent: (id: string) => boolean\n /** The agent of the active step of the request's plan, if it has one. */\n activeStepAgent?: (requestId: string) => string | null\n}\n\nconst HOUR = 3_600_000\nconst isOpen = (r: RequestRecord) => (OPEN_STATES as readonly string[]).includes(r.state)\n\n/** The agent of each request's active plan step, from the plan store. */\nexport function activeStepAgentOf(plans: { get(id: string): { state: string } | null; steps(id: string): Array<{ state: string; agentId: string }> } | null | undefined) {\n return (requestId: string): string | null => {\n if (!plans || plans.get(requestId)?.state !== \"active\") return null\n return plans.steps(requestId).find((s) => s.state === \"active\")?.agentId ?? null\n }\n}\n\n/** What an open loop waits on. */\nexport function waitsOn(r: RequestRecord, look: LoopLookups): { group: StallGroup; who: string } {\n if (r.state === \"waiting_owner\") return { group: \"owner\", who: OWED_TO_OWNER }\n if (r.promise && r.owedTo && r.owedTo !== OWED_TO_OWNER && !look.isAgent(r.owedTo)) return { group: \"person\", who: r.owedTo }\n if (r.state === \"needs_attention\") return { group: \"owner\", who: OWED_TO_OWNER }\n const step = look.activeStepAgent?.(r.id)\n return { group: \"agent\", who: step ?? r.agentId }\n}\n\n/** Why an open loop is stalled, or null when it is not. */\nexport function stalledWhy(r: RequestRecord, staleAfterHours: number, now: number): string | null {\n if (!isOpen(r)) return null\n if (r.state === \"needs_attention\") return r.attentionReason ?? \"needs attention\"\n if (r.dueAt !== null) return now > r.dueAt ? `past its due time (${when(r.dueAt)})` : null\n return now - r.updatedAt > staleAfterHours * HOUR ? `no activity for ${staleAfterHours} h or more` : null\n}\n\n/** Stalled loops among `items`, oldest first, grouped. */\nexport function stalledLoops(items: RequestRecord[], staleAfterHours: number, now: number, look: LoopLookups): Record<StallGroup, StalledLoop[]> {\n const out: Record<StallGroup, StalledLoop[]> = { owner: [], agent: [], person: [] }\n for (const r of items) {\n const why = stalledWhy(r, staleAfterHours, now)\n if (!why) continue\n const { group, who } = waitsOn(r, look)\n out[group].push({ request: r, group, who, why })\n }\n return out\n}\n\n/** The group, in words, for people. */\nexport function waitsOnWords(group: StallGroup, who: string): string {\n return group === \"owner\" ? \"you\" : group === \"agent\" ? `agent ${who}` : `${who} (outside person)`\n}\n\nexport const when = (ms: number) => new Date(ms).toISOString().slice(0, 16).replace(\"T\", \" \") + \" UTC\"\n\n/** A due time an agent or the owner gave: epoch ms, or an ISO date.\n * Undefined when absent, a string when it is not a time. */\nexport function parseDue(v: unknown): number | undefined | string {\n if (v === undefined || v === null || v === \"\") return undefined\n const at = typeof v === \"number\" ? v : typeof v === \"string\" ? Date.parse(v.trim()) : NaN\n if (!Number.isFinite(at) || at <= 0) return \"due must be an ISO date (2030-01-31T17:00:00Z) or epoch milliseconds\"\n return at\n}\n\n// ── Running the checkers from the requests check ─────────────────────────\n\n/** Runs a loop's checker. The daemon's own; tests give their own. */\nexport type LoopChecker = (spec: CloseWhen, request: RequestRecord) => Promise<CheckResult>\n\nexport function loopChecker(ctx: () => CheckContext): LoopChecker {\n return (spec) => runCheck(spec, ctx())\n}\n\n/** How many checkers run at once, and how many loops one check takes on. */\nconst CHECK_BATCH = 10\n\n/** Run the checker of every open loop whose last check is older than\n * `everyMinutes`. Met closes it as done with the checker's evidence;\n * unverifiable marks it unverified; not met leaves it as it is. */\nexport async function checkLoops(\n store: RequestStore,\n check: LoopChecker,\n opts: { everyMinutes: number; now: number; log: (msg: string) => void },\n): Promise<{ checked: number; closed: number }> {\n const due = store.dueForCheck(opts.now - opts.everyMinutes * 60_000, CHECK_BATCH)\n let closed = 0\n await Promise.all(due.map(async (r) => {\n // Marked before the call: a check that hangs is not started again\n // at the next minute.\n store.markChecked(r.id, r.verifyState, r.verifyDetail ?? \"\", opts.now)\n const res = await check(r.closeWhen!, r).catch((e: any): CheckResult => ({ verdict: \"unverifiable\", detail: String(e?.message ?? e) }))\n if (res.verdict === \"met\") {\n if (store.closeVerified(r.id, res.detail, opts.now)) {\n closed++\n opts.log(`[requests] ${r.id} closed by its check: ${res.detail}`)\n }\n return\n }\n // A refused done stays \"failed\" until the check says otherwise.\n store.markChecked(r.id, res.verdict === \"unverifiable\" ? \"unverified\" : r.verifyState === \"failed\" ? \"failed\" : null, res.detail, opts.now)\n }))\n return { checked: due.length, closed }\n}\n"],"mappings":"wPAAA,OAAS,cAAAA,GAAY,aAAAC,GAAW,aAAAC,GAAW,cAAAC,GAAY,YAAAC,GAAU,gBAAAC,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OAAAmD,CAAO,CAAC,EAE9D,OAAOF,CACT,CAGO,SAASG,GAAU1B,EAAwB,CAChD,IAAM2B,EAAQ,CAAC3B,EAAE,WAAa,wBAAwBA,EAAE,aAAe,GAAIA,EAAE,OAAS,6BAA6BA,EAAE,SAAW,EAAE,EAAE,OAAO,OAAO,EAClJ,MAAO,gBAAgBA,EAAE,8BAA8BA,EAAE,QAAQ,MAAQA,EAAE,QAAQ,aAAaA,EAAE,QAAQ,gBAAgBA,EAAE,QAAQ,+BAA+BA,EAAE,OAAO,SAAS2B,EAAM,OAAS,SAAMA,EAAM,KAAK,QAAK,IAAM,IAClO","names":["accessSync","closeSync","constants","existsSync","openSync","readFileSync","readSync","statSync","dirname","join","fileURLToPath","homedir","join","win32","helperOs","platform","WINDOWS_HELPER_EXE","installedWindowsHelper","localAppData","MAC_HELPER_APP","installedMacHelper","home","helperOverride","env","any","mac","resolveDesktopHelper","l","override","os","installed","helperInstallHint","helperMissingMessage","hint","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","dirname","unxml","s","ents","_","e","plistPathEnv","plist","m","isVoiceLoginItemFile","name","adoptLoginItem","dir","items","keep","remove","file","a","b","label","program","join","findOnPath","bin","path","isExecutable","isNativeExecutable","accessSync","constants","statSync","fd","openSync","head","readSync","closeSync","desktopPlist","opts","xml","env","k","v","helperBuildArgs","icon","installedHelper","installedMacHelper","packageRoot","from","fileURLToPath","readFileSync","findHelper","path","resolveDesktopHelper","packageRoot","homedir","existsSync","accessSync","constants","execFile","STEP_TIMEOUT_MS","run","file","args","done","err","capture","stdout","output","resolve","reject","stderr","helperOf","io","findHelper","helperBannerStatus","path","capture","out","status","macosBanner","exec","run","title","message","helper","idleSecondsIn","ioreg","m","macosIdle","io","capture","out","NOTES_SCRIPT","macosNotes","exec","output","folder","title","body","id","existsSync","readdirSync","SOUNDS","soundPath","name","path","existsSync","macosSound","io","exec","run","volume","readdirSync","f","SPEAKERS","speakersIn","ps","exceptParents","self","line","m","pid","ppid","comm","name","macosSpeech","io","capture","opts","ZWSP","argValue","v","unArg","listName","list","isoDue","d","macosTasks","command","exec","output","raw","lists","l","items","r","title","notes","due","priority","args","id","patch","executable","file","accessSync","constants","focus","s","readSystemFocus","macosAdapter","cfg","io","command","macosTasks","macosNotes","macosBanner","macosSound","macosSpeech","macosIdle","problems","isExec","findOnPath","noneAdapter","reason","existsSync","readdirSync","win32","POWERSHELL","psString","value","q","psArgs","script","POWERSHELL_APP_ID","toastScript","title","message","psString","windowsBanner","io","exec","run","helper","POWERSHELL","psArgs","helperBannerStatus","capture","IDLE_SCRIPT","idleSecondsFromMs","out","ms","windowsIdle","io","capture","POWERSHELL","psArgs","win32","windowsSoundPath","name","io","path","win32","windowsSound","exec","run","volume","POWERSHELL","psArgs","psString","f","windowsAdapter","_cfg","io","helper","findHelper","media","win32","exists","existsSync","list","dir","readdirSync","windowsBanner","windowsSound","windowsIdle","problems","FACTORIES","macosAdapter","windowsAdapter","loadNativeAdapter","cfg","opts","noneAdapter","platform","make","existsSync","homedir","isAbsolute","DEFAULT_LOCAL","localSettings","cfg","localAlert","settings","deps","native","loadNativeAdapter","title","message","steps","sound","quiet","ok","speech","waitMs","pollMs","until","r","patchLocal","current","patch","platform","next","name","icon","homedir","isAbsolute","existsSync","v","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","init_checkers","init_store","init_checkers","STALL_GROUPS","HOUR","isOpen","r","OPEN_STATES","activeStepAgentOf","plans","requestId","s","waitsOn","look","OWED_TO_OWNER","stalledWhy","staleAfterHours","now","when","stalledLoops","items","out","why","group","who","waitsOnWords","ms","parseDue","v","at","loopChecker","ctx","spec","runCheck","CHECK_BATCH","checkLoops","store","check","opts","due","closed","res","e","SUMMARY_MAX","ANSWER_MAX","NOTHING_NEEDED","cardWords","r","max","headline","summarize","need","plain","md","text","cut","end","loopOf","describeCloseWhen","requestCard","store","plans","stall","plan","why","stalledWhy","answer","cutAnswer","words","markdownToHtml","awaitingQa","waitsOn","activeStepAgentOf","s","MAX_ADD_FAILURES","KEEP_CLOSED_MS","mirrorPath","root","resolve","readMirror","parsed","readFileSync","writeMirror","file","path","existsSync","dirname","mkdirSync","tmp","writeFileSync","renameSync","MIRROR_FRESH_MS","mirrorCovers","cardId","now","checked","DAY_MS","dueFor","settings","limit","due","cardItem","card","answerUrl","expires","lines","summarize","CARD_LIMITS","c","i","requestItem","r","dueAt","cardWords","runMirror","deps","tasks","log","at","result","fail","message","waiting","e","allRead","openIds","openIn","list","t","key","entry","open","listReady","listError","cardsMissed","gaveUp","item","failures","id","n","told","first","more","err","MIRROR_GRACE_MS","mirrorTally","cards","from","to","inWindow","iso","tally","raisedAt","reason","tallyLine","extra"]}