agentix-cli 0.116.0 → 0.118.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 (140) hide show
  1. package/README.md +5 -5
  2. package/dist/{App-7Z2PWARZ.js → App-XMSNIAU6.js} +2 -2
  3. package/dist/{ChatApp-GFAIRLGZ.js → ChatApp-BFYTIQF3.js} +2 -2
  4. package/dist/{agent-LXLZGVW3.js → agent-E6W5VBYH.js} +2 -2
  5. package/dist/{board-dashboard-CPCSSVZE.js → board-dashboard-D5FQZKO4.js} +215 -101
  6. package/dist/board-dashboard-D5FQZKO4.js.map +1 -0
  7. package/dist/chunk-23SQSUBI.js +3 -0
  8. package/dist/chunk-23SQSUBI.js.map +1 -0
  9. package/dist/{chunk-UUMNP47Q.js → chunk-2G227TF3.js} +2 -2
  10. package/dist/{chunk-JLCJVPRC.js → chunk-4PQREYBU.js} +2 -2
  11. package/dist/{chunk-4FU4BFCH.js → chunk-5NTWGUSJ.js} +3 -3
  12. package/dist/chunk-5NTWGUSJ.js.map +1 -0
  13. package/dist/{chunk-6LCP6SVR.js → chunk-5PR6DZYW.js} +3 -3
  14. package/dist/chunk-5PR6DZYW.js.map +1 -0
  15. package/dist/{chunk-HOY2GIKV.js → chunk-5UFIHT66.js} +2 -2
  16. package/dist/{chunk-AWQIUI7N.js → chunk-6PC4EZ4P.js} +2 -2
  17. package/dist/chunk-AD4QZZVN.js +8 -0
  18. package/dist/{failure-candidates-PBPF45GN.js.map → chunk-AD4QZZVN.js.map} +1 -1
  19. package/dist/chunk-B6OXEIOF.js +126 -0
  20. package/dist/chunk-B6OXEIOF.js.map +1 -0
  21. package/dist/chunk-BDJWN3PL.js +4 -0
  22. package/dist/chunk-BDJWN3PL.js.map +1 -0
  23. package/dist/{chunk-7IF3LXAU.js → chunk-FSXWNVGL.js} +2 -2
  24. package/dist/{chunk-YMNQYODO.js → chunk-FTZCNID3.js} +2 -2
  25. package/dist/{chunk-S56ZGAFM.js → chunk-GJKYOEDE.js} +2 -2
  26. package/dist/{chunk-KI4CIUVJ.js → chunk-HK7TU5NX.js} +2 -2
  27. package/dist/chunk-IMLLHT7U.js +54 -0
  28. package/dist/chunk-IMLLHT7U.js.map +1 -0
  29. package/dist/chunk-IOYRRGK7.js +2 -0
  30. package/dist/chunk-IOYRRGK7.js.map +1 -0
  31. package/dist/{chunk-R277UDDQ.js → chunk-IVCFXLAR.js} +2 -2
  32. package/dist/{chunk-WRICEAR6.js → chunk-NDPU6AX2.js} +2 -2
  33. package/dist/{chunk-ELWKTURG.js → chunk-NG677JHW.js} +8 -8
  34. package/dist/chunk-NG677JHW.js.map +1 -0
  35. package/dist/{chunk-CCL73Z2P.js → chunk-PVQPXZHE.js} +58 -58
  36. package/dist/{chunk-CCL73Z2P.js.map → chunk-PVQPXZHE.js.map} +1 -1
  37. package/dist/{chunk-B65YTB3T.js → chunk-RJBRYUKU.js} +2 -2
  38. package/dist/{chunk-QLWGLRT5.js → chunk-TJ7IUHC7.js} +2 -2
  39. package/dist/{chunk-HSYNOMM2.js → chunk-U46G24CD.js} +2 -2
  40. package/dist/{chunk-CKYSGX54.js → chunk-V4PVGEWI.js} +196 -197
  41. package/dist/chunk-V4PVGEWI.js.map +1 -0
  42. package/dist/chunk-WCXXXAHV.js +3 -0
  43. package/dist/{chunk-DMHQIACQ.js.map → chunk-WCXXXAHV.js.map} +1 -1
  44. package/dist/chunk-XGOBZCYC.js +2 -0
  45. package/dist/chunk-XGOBZCYC.js.map +1 -0
  46. package/dist/{chunk-IEZ6OYFJ.js → chunk-ZDWE47LM.js} +8 -8
  47. package/dist/chunk-ZDWE47LM.js.map +1 -0
  48. package/dist/cli.js +1 -1
  49. package/dist/{client-CU5GNTKR.js → client-TSYZXEH7.js} +2 -2
  50. package/dist/{config-ITVBNUWW.js → config-QAE3LNFQ.js} +2 -2
  51. package/dist/config-mutator-WRQ7MFQL.js +2 -0
  52. package/dist/{doctor-MLD3XCYE.js → doctor-PVLVKLRA.js} +2 -2
  53. package/dist/failure-candidates-JNGUVBDG.js +2 -0
  54. package/dist/{grants-BRAVOGBP.js → grants-V2ZNLWSJ.js} +2 -2
  55. package/dist/index.d.ts +107 -3
  56. package/dist/index.js +1 -1
  57. package/dist/program-ZYG3YPH2.js +721 -0
  58. package/dist/program-ZYG3YPH2.js.map +1 -0
  59. package/dist/{promote-JMJPWZI7.js → promote-IRBBEXGG.js} +2 -2
  60. package/dist/push-bridge-325SXDGN.js +2 -0
  61. package/dist/{query-QGPVKGYY.js → query-NAU7J34H.js} +2 -2
  62. package/dist/{registry-PZNC5XYT.js → registry-I5PXGCO6.js} +2 -2
  63. package/dist/{request-planner-M4IKDZBU.js → request-planner-CRG3OGGG.js} +2 -2
  64. package/dist/{review-candidates-6DNRBJZ6.js → review-candidates-HAP7P6SH.js} +2 -2
  65. package/dist/{routing-7NSB6O2S.js → routing-G33LLOTF.js} +2 -2
  66. package/dist/schedule-tool-IP7ZCQKI.js +2 -0
  67. package/dist/scheduler-QXLPYSNJ.js +2 -0
  68. package/dist/{seat-ZRCUQCUP.js → seat-IJN7NETF.js} +2 -2
  69. package/dist/{select-OLNLTEBR.js → select-D7AZ2XZF.js} +2 -2
  70. package/dist/{set-enabled-LG3ESZDC.js → set-enabled-5YSDIQXU.js} +2 -2
  71. package/dist/{surface-usage-HCJTUS6Z.js → surface-usage-WSY4SHHL.js} +2 -2
  72. package/dist/{tool-RBXRPIBV.js → tool-GQIQWHWB.js} +2 -2
  73. package/dist/{tool-S6U42ULD.js → tool-XADSW6NL.js} +2 -2
  74. package/dist/wiki-PPX3HYXW.js +2 -0
  75. package/dist/wiki-PPX3HYXW.js.map +1 -0
  76. package/package.json +1 -1
  77. package/dist/board-dashboard-CPCSSVZE.js.map +0 -1
  78. package/dist/chunk-4FU4BFCH.js.map +0 -1
  79. package/dist/chunk-6LCP6SVR.js.map +0 -1
  80. package/dist/chunk-BRL3UPFW.js +0 -2
  81. package/dist/chunk-BRL3UPFW.js.map +0 -1
  82. package/dist/chunk-CKYSGX54.js.map +0 -1
  83. package/dist/chunk-DMHQIACQ.js +0 -3
  84. package/dist/chunk-EKOVLUKH.js +0 -2
  85. package/dist/chunk-EKOVLUKH.js.map +0 -1
  86. package/dist/chunk-ELWKTURG.js.map +0 -1
  87. package/dist/chunk-FBEMUCBO.js +0 -54
  88. package/dist/chunk-FBEMUCBO.js.map +0 -1
  89. package/dist/chunk-IEZ6OYFJ.js.map +0 -1
  90. package/dist/chunk-J3SIOMDL.js +0 -126
  91. package/dist/chunk-J3SIOMDL.js.map +0 -1
  92. package/dist/chunk-JIT5GPTX.js +0 -4
  93. package/dist/chunk-JIT5GPTX.js.map +0 -1
  94. package/dist/chunk-Y3CZE54A.js +0 -2
  95. package/dist/chunk-Y3CZE54A.js.map +0 -1
  96. package/dist/config-mutator-5YRHHA2I.js +0 -2
  97. package/dist/failure-candidates-PBPF45GN.js +0 -8
  98. package/dist/program-IBOVOVZI.js +0 -703
  99. package/dist/program-IBOVOVZI.js.map +0 -1
  100. package/dist/push-bridge-IFUQLIMF.js +0 -2
  101. package/dist/schedule-tool-ZP7H55EL.js +0 -2
  102. package/dist/scheduler-XV5UQQYH.js +0 -2
  103. package/dist/wiki-XKQN5CWR.js +0 -2
  104. /package/dist/{App-7Z2PWARZ.js.map → App-XMSNIAU6.js.map} +0 -0
  105. /package/dist/{ChatApp-GFAIRLGZ.js.map → ChatApp-BFYTIQF3.js.map} +0 -0
  106. /package/dist/{agent-LXLZGVW3.js.map → agent-E6W5VBYH.js.map} +0 -0
  107. /package/dist/{chunk-UUMNP47Q.js.map → chunk-2G227TF3.js.map} +0 -0
  108. /package/dist/{chunk-JLCJVPRC.js.map → chunk-4PQREYBU.js.map} +0 -0
  109. /package/dist/{chunk-HOY2GIKV.js.map → chunk-5UFIHT66.js.map} +0 -0
  110. /package/dist/{chunk-AWQIUI7N.js.map → chunk-6PC4EZ4P.js.map} +0 -0
  111. /package/dist/{chunk-7IF3LXAU.js.map → chunk-FSXWNVGL.js.map} +0 -0
  112. /package/dist/{chunk-YMNQYODO.js.map → chunk-FTZCNID3.js.map} +0 -0
  113. /package/dist/{chunk-S56ZGAFM.js.map → chunk-GJKYOEDE.js.map} +0 -0
  114. /package/dist/{chunk-KI4CIUVJ.js.map → chunk-HK7TU5NX.js.map} +0 -0
  115. /package/dist/{chunk-R277UDDQ.js.map → chunk-IVCFXLAR.js.map} +0 -0
  116. /package/dist/{chunk-WRICEAR6.js.map → chunk-NDPU6AX2.js.map} +0 -0
  117. /package/dist/{chunk-B65YTB3T.js.map → chunk-RJBRYUKU.js.map} +0 -0
  118. /package/dist/{chunk-QLWGLRT5.js.map → chunk-TJ7IUHC7.js.map} +0 -0
  119. /package/dist/{chunk-HSYNOMM2.js.map → chunk-U46G24CD.js.map} +0 -0
  120. /package/dist/{client-CU5GNTKR.js.map → client-TSYZXEH7.js.map} +0 -0
  121. /package/dist/{config-ITVBNUWW.js.map → config-QAE3LNFQ.js.map} +0 -0
  122. /package/dist/{config-mutator-5YRHHA2I.js.map → config-mutator-WRQ7MFQL.js.map} +0 -0
  123. /package/dist/{doctor-MLD3XCYE.js.map → doctor-PVLVKLRA.js.map} +0 -0
  124. /package/dist/{grants-BRAVOGBP.js.map → failure-candidates-JNGUVBDG.js.map} +0 -0
  125. /package/dist/{promote-JMJPWZI7.js.map → grants-V2ZNLWSJ.js.map} +0 -0
  126. /package/dist/{push-bridge-IFUQLIMF.js.map → promote-IRBBEXGG.js.map} +0 -0
  127. /package/dist/{query-QGPVKGYY.js.map → push-bridge-325SXDGN.js.map} +0 -0
  128. /package/dist/{registry-PZNC5XYT.js.map → query-NAU7J34H.js.map} +0 -0
  129. /package/dist/{routing-7NSB6O2S.js.map → registry-I5PXGCO6.js.map} +0 -0
  130. /package/dist/{request-planner-M4IKDZBU.js.map → request-planner-CRG3OGGG.js.map} +0 -0
  131. /package/dist/{review-candidates-6DNRBJZ6.js.map → review-candidates-HAP7P6SH.js.map} +0 -0
  132. /package/dist/{schedule-tool-ZP7H55EL.js.map → routing-G33LLOTF.js.map} +0 -0
  133. /package/dist/{scheduler-XV5UQQYH.js.map → schedule-tool-IP7ZCQKI.js.map} +0 -0
  134. /package/dist/{seat-ZRCUQCUP.js.map → scheduler-QXLPYSNJ.js.map} +0 -0
  135. /package/dist/{surface-usage-HCJTUS6Z.js.map → seat-IJN7NETF.js.map} +0 -0
  136. /package/dist/{select-OLNLTEBR.js.map → select-D7AZ2XZF.js.map} +0 -0
  137. /package/dist/{set-enabled-LG3ESZDC.js.map → set-enabled-5YSDIQXU.js.map} +0 -0
  138. /package/dist/{wiki-XKQN5CWR.js.map → surface-usage-WSY4SHHL.js.map} +0 -0
  139. /package/dist/{tool-RBXRPIBV.js.map → tool-GQIQWHWB.js.map} +0 -0
  140. /package/dist/{tool-S6U42ULD.js.map → tool-XADSW6NL.js.map} +0 -0
@@ -0,0 +1,2 @@
1
+ import{q as d}from"./chunk-B6OXEIOF.js";import{b as i,c as u,d as l,e as c}from"./chunk-4PQREYBU.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
2
+ //# sourceMappingURL=chunk-IOYRRGK7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crons/schedule-ops.ts"],"sourcesContent":["import cronstrue from \"cronstrue\"\nimport { applyConfigMutation, getAtPath, setAtPath, unsetAtPath, type MutationResult } from \"@/daemon/config-mutator\"\nimport type { NlCronResult } from \"@/utils/nl-cron\"\nimport { getNextCronDate } from \"./scheduler\"\n\n// --- Shared schedule operations ---\n//\n// One code path for everything that writes a `crons.<id>` entry from a\n// natural-language schedule: the `agentx schedule` CLI and the agent-facing\n// `agentx_schedule` MCP tool both build jobs here, so the two can never\n// drift into writing different shapes.\n//\n// Also owns the operator side of the approval flow (approve / reject), which\n// only the CLI exposes. Agents can request; they cannot approve.\n\nexport type OnErrorValue = \"log\" | \"notify\" | \"disable\"\n\nexport interface NotifyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface ScheduleApproval {\n action: \"create\" | \"delete\"\n requestedBy: string\n requestedAt: string\n}\n\n/** Default timezone for schedules created without one: this machine's, the\n * same as the CLI's `--timezone` default. */\nexport const DEFAULT_SCHEDULE_TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone\nexport const DEFAULT_SCHEDULE_TIMEOUT = 600\n\nexport const SUPPORTED_PHRASES_HINT =\n 'Try: \"every morning at 9\", \"weekdays at 6pm\", \"every 15 minutes\", \"every monday at 10am\", ' +\n '\"1st of every month at noon\", \"daily at 9:30am\", \"every hour\"'\n\n/** Cron ids become a dot-path segment (`crons.<id>`), so dots and other\n * separators are refused rather than silently nesting the config. */\nconst SCHEDULE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/\n\nexport function isValidScheduleId(id: string): boolean {\n return SCHEDULE_ID_RE.test(id)\n}\n\nexport function isValidTimezone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: tz })\n return true\n } catch {\n return false\n }\n}\n\nexport function parseOnError(flag: string | undefined): OnErrorValue[] {\n if (!flag) return [\"log\"]\n return flag\n .split(\",\")\n .map((s) => s.trim().toLowerCase())\n .filter((s): s is OnErrorValue => s === \"log\" || s === \"notify\" || s === \"disable\")\n}\n\nexport interface ScheduleJobInput {\n parsed: NlCronResult\n agent: string\n prompt: string\n timezone?: string\n timeout?: number\n model?: string\n notify?: NotifyTarget\n /** False keeps `notify` for failure alerts only. Default: each\n * successful run's answer is sent there too. */\n deliverResult?: boolean\n onError?: OnErrorValue[]\n enabled?: boolean\n createdBy?: string\n approval?: ScheduleApproval\n}\n\n/** Build the `crons.<id>` object. A notify target implies the \"notify\"\n * error mode, exactly as the CLI always did. */\nexport function buildScheduleJob(input: ScheduleJobInput): Record<string, unknown> {\n const onError = [...(input.onError ?? [\"log\"])]\n if (input.notify && !onError.includes(\"notify\")) onError.push(\"notify\")\n\n const job: Record<string, unknown> = {\n enabled: input.enabled ?? true,\n schedule: input.parsed.cron,\n timezone: input.timezone || DEFAULT_SCHEDULE_TIMEZONE,\n agent: input.agent,\n prompt: input.prompt,\n timeout: input.timeout ?? DEFAULT_SCHEDULE_TIMEOUT,\n onError,\n }\n if (input.model) job.model = input.model\n if (input.notify) job.notify = input.notify\n if (input.notify && input.deliverResult === false) job.deliverResult = false\n if (input.createdBy) job.createdBy = input.createdBy\n if (input.approval) job.approval = input.approval\n return job\n}\n\nexport function humanizeCron(cron: string): string {\n try {\n return cronstrue.toString(cron, { use24HourTimeFormat: false })\n } catch {\n return cron\n }\n}\n\nexport function nextFireTime(cron: string, timezone: string, now: Date = new Date()): Date | null {\n try {\n return getNextCronDate(cron, now, timezone)\n } catch {\n return null\n }\n}\n\n/** \"Mon, 28 Sep 2026, 10:00 (<tz>)\" — the wall-clock time where the job\n * runs, which is what an operator reading an approval request cares about. */\nexport function formatFireTime(d: Date | null, timezone: string): string {\n if (!d) return \"unknown (no match within a year)\"\n try {\n const local = new Intl.DateTimeFormat(\"en-GB\", {\n timeZone: timezone,\n weekday: \"short\",\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n }).format(d)\n return `${local} (${timezone})`\n } catch {\n return d.toISOString()\n }\n}\n\nexport function isPendingCreate(job: any): boolean {\n return job?.approval?.action === \"create\"\n}\n\n// ── Operator approval ────────────────────────────────────────────────\n\nexport interface ApprovalOutcome {\n success: boolean\n /** What happened, for the CLI to print. */\n message: string\n result?: MutationResult\n}\n\n/**\n * Apply a pending agent request. `create` → enable and clear the marker;\n * `delete` → remove the job. Hot-reloads the daemon through the same\n * mutator the CLI uses.\n */\nexport async function approveSchedule(\n id: string,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<ApprovalOutcome> {\n let message = \"\"\n const result = await applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n const approval = job.approval as ScheduleApproval | undefined\n if (!approval) throw new Error(`cron \"${id}\" has no pending request`)\n if (approval.action === \"create\") {\n delete job.approval\n job.enabled = true\n message = `${id} approved and enabled (requested by ${approval.requestedBy})`\n } else {\n unsetAtPath(cfg, `crons.${id}`)\n message = `${id} deletion approved; job removed (requested by ${approval.requestedBy})`\n }\n }, { configPath: opts.configPath, reload: opts.reload })\n if (!result.success) return { success: false, message: result.error || \"failed\", result }\n return { success: true, message, result }\n}\n\n/** Refuse a pending request. `create` → drop the never-run job; `delete` →\n * keep the job exactly as it was and clear the marker. */\nexport async function rejectSchedule(\n id: string,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<ApprovalOutcome> {\n let message = \"\"\n const result = await applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n const approval = job.approval as ScheduleApproval | undefined\n if (!approval) throw new Error(`cron \"${id}\" has no pending request`)\n if (approval.action === \"create\") {\n unsetAtPath(cfg, `crons.${id}`)\n message = `${id} rejected; pending job removed`\n } else {\n delete job.approval\n message = `${id} deletion rejected; job kept`\n }\n }, { configPath: opts.configPath, reload: opts.reload })\n if (!result.success) return { success: false, message: result.error || \"failed\", result }\n return { success: true, message, result }\n}\n\n/** Enable/disable, refusing to enable a job still awaiting approval. */\nexport async function setScheduleEnabled(\n id: string,\n enabled: boolean,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<MutationResult> {\n return applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n if (enabled && isPendingCreate(job)) {\n throw new Error(`cron \"${id}\" is awaiting approval; run \\`agentx schedule approve ${id}\\``)\n }\n setAtPath(cfg, `crons.${id}.enabled`, enabled)\n }, { configPath: opts.configPath, reload: opts.reload })\n}\n"],"mappings":"qGAAA,OAAOA,MAAe,YA+Bf,IAAMC,EAA4B,KAAK,eAAe,EAAE,gBAAgB,EAAE,SACpEC,EAA2B,IAE3BC,EACX,0JAKIC,EAAiB,mCAEhB,SAASC,EAAkBC,EAAqB,CACrD,OAAOF,EAAe,KAAKE,CAAE,CAC/B,CAEO,SAASC,EAAgBC,EAAqB,CACnD,GAAI,CACF,WAAI,KAAK,eAAe,QAAS,CAAE,SAAUA,CAAG,CAAC,EAC1C,EACT,MAAE,CACA,MAAO,EACT,CACF,CAEO,SAASC,EAAaC,EAA0C,CACrE,OAAKA,EACEA,EACJ,MAAM,GAAG,EACT,IAAKC,GAAMA,EAAE,KAAK,EAAE,YAAY,CAAC,EACjC,OAAQA,GAAyBA,IAAM,OAASA,IAAM,UAAYA,IAAM,SAAS,EAJlE,CAAC,KAAK,CAK1B,CAqBO,SAASC,EAAiBC,EAAkD,CACjF,IAAMC,EAAU,CAAC,GAAID,EAAM,SAAW,CAAC,KAAK,CAAE,EAC1CA,EAAM,QAAU,CAACC,EAAQ,SAAS,QAAQ,GAAGA,EAAQ,KAAK,QAAQ,EAEtE,IAAMC,EAA+B,CACnC,QAASF,EAAM,SAAW,GAC1B,SAAUA,EAAM,OAAO,KACvB,SAAUA,EAAM,UAAYZ,EAC5B,MAAOY,EAAM,MACb,OAAQA,EAAM,OACd,QAASA,EAAM,SAAWX,EAC1B,QAAAY,CACF,EACA,OAAID,EAAM,QAAOE,EAAI,MAAQF,EAAM,OAC/BA,EAAM,SAAQE,EAAI,OAASF,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zD","names":["cronstrue","DEFAULT_SCHEDULE_TIMEZONE","DEFAULT_SCHEDULE_TIMEOUT","SUPPORTED_PHRASES_HINT","SCHEDULE_ID_RE","isValidScheduleId","id","isValidTimezone","tz","parseOnError","flag","s","buildScheduleJob","input","onError","job","humanizeCron","cron","cronstrue","nextFireTime","timezone","now","getNextCronDate","formatFireTime","d","isPendingCreate","approveSchedule","opts","message","result","applyConfigMutation","cfg","getAtPath","approval","unsetAtPath","rejectSchedule","setScheduleEnabled","enabled","setAtPath"]}
@@ -1,4 +1,4 @@
1
- import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-YMNQYODO.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{y as C,z as I}from"./chunk-WRICEAR6.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
1
+ import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-FTZCNID3.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{y as C,z as I}from"./chunk-NDPU6AX2.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
2
2
  ## Intent
3
3
 
4
4
  The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
@@ -46,4 +46,4 @@ ${o}
46
46
  Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
47
47
 
48
48
  Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
49
- //# sourceMappingURL=chunk-R277UDDQ.js.map
49
+ //# sourceMappingURL=chunk-IVCFXLAR.js.map
@@ -1,4 +1,4 @@
1
- import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-FBEMUCBO.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
1
+ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-IMLLHT7U.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
2
2
  ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
3
3
  INSERT INTO schema_version (v) VALUES (3);
4
4
  `)}function Ot(e){e.exec(`
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
111
111
  `)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
112
112
  `),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
113
113
  ${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
114
- //# sourceMappingURL=chunk-WRICEAR6.js.map
114
+ //# sourceMappingURL=chunk-NDPU6AX2.js.map
@@ -1,8 +1,8 @@
1
- import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as q,b as O,c as R,d as B,f as b,g as S,h as E,i as w,j as y}from"./chunk-Y3CZE54A.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-JLCJVPRC.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function A(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(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 K(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&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",u=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",p=[`- ${n} [${h}] ${e.schedule} \u2014 ${S(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${u}`];return e.notify&&p.push(` notify: ${e.notify.channel} ${e.notify.chatId}`),e.command?p.push(` command: ${A(String(e.command))}`):e.prompt&&p.push(` prompt: ${A(String(e.prompt))}`),p.join(`
2
- `)}async function k(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(u){return`Could not notify the operator (${u?.message??u}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),u=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let p=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(p).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,f])=>Q(i,f,u)).join(`
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(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=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=D(a);if(!i)return`Error: couldn't parse "${a}". ${O}.`;let f=s(n.agent)||e.agentId;if(!h.agents?.[f])return`Error: agent "${f}" not found on this node.`;let g=s(n.timezone)||q;if(!B(g))return`Error: unknown timezone "${g}".`;let d=o||_(i.matched,f);if(!R(d))return`Error: invalid id "${d}" (letters, digits, "-" and "_" only).`;if(p[d])return`Error: a schedule "${d}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:u.toISOString()},L=b({parsed:i,agent:f,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),v=await m(U=>I(U,`crons.${d}`,L));if(!v.success)return`Error: ${v.error}`;let N=w(E(i.cron,g,u),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${d}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${f}`,$?`Notify: ${$.channel} ${$.chatId}`:"Notify: none",`Prompt: ${A(l,400)}`,"",`Approve: agentx schedule approve ${d}`,`Reject: agentx schedule reject ${d}`].join(`
4
- `),H=await k(h,t,G);return[`Requested schedule "${d}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
- `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=p[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(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 m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let d=await m($=>P($,`crons.${o}`));return d.success?`Withdrew the pending request "${o}".`:`Error: ${d.error}`}if(y(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:u.toISOString()},l=await m(d=>{if(!x(d,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(d,`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: ${S(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,u),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
- `),g=await k(h,t,f);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
- `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(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)),u=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),p=s(n.accountId);return{agentId:t,channel:u,chatId:h,...p?{accountId:p}:{}}}export{re as a,oe as b};
8
- //# sourceMappingURL=chunk-ELWKTURG.js.map
1
+ import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-IOYRRGK7.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-4PQREYBU.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(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 K(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&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
2
+ `)}async function b(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 re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
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(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=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=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
4
+ `),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
5
+ `)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(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 m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(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 m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
6
+ `),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
7
+ `)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(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),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
8
+ //# sourceMappingURL=chunk-NG677JHW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crons/schedule-tool.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"fs\"\nimport { applyConfigMutation, findConfigPath, getAtPath, setAtPath, unsetAtPath } from \"@/daemon/config-mutator\"\nimport { parseEnglishToCron, slugifyScheduleId } from \"@/utils/nl-cron\"\nimport {\n buildScheduleJob,\n DEFAULT_SCHEDULE_TIMEZONE,\n formatFireTime,\n humanizeCron,\n isPendingCreate,\n isValidScheduleId,\n isValidTimezone,\n nextFireTime,\n SUPPORTED_PHRASES_HINT,\n type NotifyTarget,\n type ScheduleApproval,\n} from \"./schedule-ops\"\n\n// --- Agent-facing `schedule` tool ---\n//\n// Lets an agent list / create / pause / resume / delete routines from any\n// chat. Writes go through the same builder and config mutator as the\n// `agentx schedule` CLI, with two differences that make it safe to hand to\n// a model:\n//\n// 1. create and delete are REQUESTS. Create writes the job disabled with an\n// `approval` marker (the scheduler refuses to run it while that marker\n// says \"create\"); delete only marks the job. The operator is notified\n// with the parsed cron and next fire time, and only\n// `agentx schedule approve|reject <id>` resolves the request. There is\n// no action here that approves anything.\n// 2. Ownership. Jobs record `createdBy`; an agent may touch only its own\n// unless its config says `admin: true`.\n\nexport type ScheduleAction = \"list\" | \"create\" | \"pause\" | \"resume\" | \"delete\"\n\nexport interface ScheduleCaller {\n agentId: string\n /** Chat the request came from — the default notify target. */\n channel?: string\n chatId?: string\n accountId?: string\n}\n\nexport interface ScheduleToolDeps {\n configPath?: string\n /** Hot-reload the daemon after a write. Default true. */\n reload?: boolean\n now?: () => Date\n /** Deliver the approval request to the operator. Throws on failure. */\n notifyOperator?: (dest: NotifyTarget, text: string) => Promise<void>\n}\n\n/** Channels that are not a conversation someone reads, so they never make a\n * sensible default delivery target for a routine's output. */\nconst NON_DELIVERABLE_CHANNELS = new Set([\"cron\", \"heartbeat\", \"api\", \"a2a\", \"mesh\"])\n\nconst PROMPT_PREVIEW = 160\n\nfunction str(v: unknown): string | undefined {\n return typeof v === \"string\" && v.trim() ? v.trim() : undefined\n}\n\nfunction preview(s: string, n = PROMPT_PREVIEW): string {\n const flat = s.replace(/\\s+/g, \" \").trim()\n return flat.length > n ? `${flat.slice(0, n - 1)}…` : flat\n}\n\nfunction readRawConfig(configPath?: string): any {\n const path = findConfigPath(configPath)\n if (!existsSync(path)) throw new Error(`config not found at ${path}`)\n return JSON.parse(readFileSync(path, \"utf-8\"))\n}\n\nfunction isAdmin(cfg: any, agentId: string): boolean {\n return cfg?.agents?.[agentId]?.admin === true\n}\n\nfunction canManage(cfg: any, job: any, caller: ScheduleCaller): boolean {\n return isAdmin(cfg, caller.agentId) || job?.createdBy === caller.agentId\n}\n\nfunction ownershipError(id: string, job: any): string {\n const owner = job?.createdBy ? `agent \"${job.createdBy}\"` : \"the operator\"\n return `Not allowed: \"${id}\" was created by ${owner}. Agents manage only schedules they created (unless configured admin).`\n}\n\nfunction resolveNotify(args: Record<string, unknown>, caller: ScheduleCaller): NotifyTarget | undefined | \"invalid\" {\n const raw = str(args.notify)\n if (raw === \"none\") return undefined\n if (raw && raw !== \"here\") {\n const parts = raw.split(\":\")\n if (parts.length < 2 || !parts[0] || !parts[1]) return \"invalid\"\n // chatIds can contain \":\" (gitlab \"org/repo:issue:1\"), so the channel\n // is the first segment and the rest is the chat id.\n return { channel: parts[0], chatId: parts.slice(1).join(\":\") }\n }\n if (caller.channel && caller.chatId && !NON_DELIVERABLE_CHANNELS.has(caller.channel)) {\n return { channel: caller.channel, chatId: caller.chatId, ...(caller.accountId ? { accountId: caller.accountId } : {}) }\n }\n return undefined\n}\n\nfunction describeJob(id: string, job: any, now: Date): string {\n const tz = job.timezone || \"UTC\"\n const next = job.enabled && !isPendingCreate(job) ? formatFireTime(nextFireTime(job.schedule, tz, now), tz) : \"—\"\n const state = job.approval\n ? `pending ${job.approval.action} approval`\n : job.enabled ? \"active\" : \"paused\"\n const lines = [\n `- ${id} [${state}] ${job.schedule} — ${humanizeCron(job.schedule)} (${tz})`,\n ` agent: ${job.agent}; created by: ${job.createdBy || \"operator\"}; next: ${next}`,\n ]\n if (job.notify) lines.push(` notify: ${job.notify.channel} ${job.notify.chatId}${job.deliverResult === false ? \" (failures only)\" : \" (results and failures)\"}`)\n if (job.command) lines.push(` command: ${preview(String(job.command))}`)\n else if (job.prompt) lines.push(` prompt: ${preview(String(job.prompt))}`)\n return lines.join(\"\\n\")\n}\n\nasync function notifyApproval(\n cfg: any,\n deps: ScheduleToolDeps,\n text: string,\n): Promise<string> {\n const dest = cfg?.notifications?.destination\n if (!dest?.channel || !dest?.chatId) {\n return \"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.\"\n }\n if (!deps.notifyOperator) return \"Operator notification is unavailable in this context.\"\n try {\n await deps.notifyOperator({ channel: dest.channel, chatId: dest.chatId, accountId: dest.accountId }, text)\n return \"The operator has been notified.\"\n } catch (e: any) {\n return `Could not notify the operator (${e?.message ?? e}); the request is still recorded.`\n }\n}\n\n/**\n * Run one tool action. Returns the text the agent sees. Throws only on\n * programming errors — every expected refusal is returned as text so the\n * model can relay it.\n */\nexport async function runScheduleTool(\n args: Record<string, unknown>,\n caller: ScheduleCaller | null,\n deps: ScheduleToolDeps = {},\n): Promise<string> {\n const action = (str(args.action) || \"list\").toLowerCase() as ScheduleAction\n const now = deps.now ? deps.now() : new Date()\n\n let cfg: any\n try {\n cfg = readRawConfig(deps.configPath)\n } catch (e: any) {\n return `Error: ${e.message}`\n }\n const crons: Record<string, any> = cfg.crons || {}\n\n if (action === \"list\") {\n const mineOnly = args.mine === true\n const entries = Object.entries(crons).filter(([, j]) => !mineOnly || (caller && j?.createdBy === caller.agentId))\n if (!entries.length) return mineOnly ? \"You have no schedules.\" : \"No schedules.\"\n return entries.map(([id, j]) => describeJob(id, j, now)).join(\"\\n\")\n }\n\n if (!caller?.agentId) {\n return \"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.\"\n }\n if (!cfg.agents?.[caller.agentId]) {\n return `Error: caller \"${caller.agentId}\" is not an agent on this node.`\n }\n\n const id = str(args.id)\n const mutate = (fn: (c: any) => void) =>\n applyConfigMutation(fn, { configPath: deps.configPath, reload: deps.reload })\n\n if (action === \"create\") {\n const when = str(args.when)\n const prompt = str(args.prompt)\n if (!when || !prompt) return \"Error: create needs `when` (plain English) and `prompt`.\"\n const parsed = parseEnglishToCron(when)\n if (!parsed) return `Error: couldn't parse \"${when}\". ${SUPPORTED_PHRASES_HINT}.`\n\n const agent = str(args.agent) || caller.agentId\n if (!cfg.agents?.[agent]) return `Error: agent \"${agent}\" not found on this node.`\n\n const timezone = str(args.timezone) || DEFAULT_SCHEDULE_TIMEZONE\n if (!isValidTimezone(timezone)) return `Error: unknown timezone \"${timezone}\".`\n\n const jobId = id || slugifyScheduleId(parsed.matched, agent)\n if (!isValidScheduleId(jobId)) return `Error: invalid id \"${jobId}\" (letters, digits, \"-\" and \"_\" only).`\n if (crons[jobId]) return `Error: a schedule \"${jobId}\" already exists. Pick another \\`id\\`.`\n\n const notify = resolveNotify(args, caller)\n if (notify === \"invalid\") return 'Error: `notify` must be \"here\", \"none\", or \"channel:chatId\".'\n\n const approval: ScheduleApproval = {\n action: \"create\",\n requestedBy: caller.agentId,\n requestedAt: now.toISOString(),\n }\n const job = buildScheduleJob({\n parsed,\n agent,\n prompt,\n timezone,\n notify,\n enabled: false,\n createdBy: caller.agentId,\n approval,\n })\n\n const result = await mutate((c) => setAtPath(c, `crons.${jobId}`, job))\n if (!result.success) return `Error: ${result.error}`\n\n const next = formatFireTime(nextFireTime(parsed.cron, timezone, now), timezone)\n const request = [\n `Schedule approval requested by ${caller.agentId}`,\n `Create: ${jobId}`,\n `When: ${parsed.human} — cron \\`${parsed.cron}\\` (${timezone})`,\n `Next fire: ${next}`,\n `Agent: ${agent}`,\n notify ? `Results and failures go to: ${notify.channel} ${notify.chatId}${notify.channel === \"voice\" ? \" (as a push notification)\" : \"\"}` : \"Results go to: run log only (no chat)\",\n `Prompt: ${preview(prompt, 400)}`,\n \"\",\n `Approve: agentx schedule approve ${jobId}`,\n `Reject: agentx schedule reject ${jobId}`,\n ].join(\"\\n\")\n const notified = await notifyApproval(cfg, deps, request)\n\n return [\n `Requested schedule \"${jobId}\": ${parsed.human} (cron ${parsed.cron}, ${timezone}); next fire would be ${next}.`,\n \"It is saved DISABLED and will not run until the operator approves it.\",\n notified,\n ].join(\"\\n\")\n }\n\n if (!id) return `Error: ${action} needs \\`id\\`.`\n const job = crons[id]\n if (!job) return `Error: schedule \"${id}\" not found.`\n if (!canManage(cfg, job, caller)) return ownershipError(id, job)\n\n if (action === \"pause\" || action === \"resume\") {\n const enable = action === \"resume\"\n if (enable && isPendingCreate(job)) {\n return `\"${id}\" is still awaiting operator approval; it can't be resumed until approved.`\n }\n if (job.enabled === enable) return `\"${id}\" is already ${enable ? \"active\" : \"paused\"}.`\n const result = await mutate((c) => setAtPath(c, `crons.${id}.enabled`, enable))\n if (!result.success) return `Error: ${result.error}`\n return `\"${id}\" ${enable ? \"resumed\" : \"paused\"}.`\n }\n\n if (action === \"delete\") {\n // Withdrawing your own never-approved request removes nothing that ever\n // ran, so it needs no approval.\n if (isPendingCreate(job) && job.approval.requestedBy === caller.agentId) {\n const result = await mutate((c) => unsetAtPath(c, `crons.${id}`))\n if (!result.success) return `Error: ${result.error}`\n return `Withdrew the pending request \"${id}\".`\n }\n // Never replace a pending create marker with a delete marker: rejecting\n // that delete would leave a disabled job with no marker, which its owner\n // could then resume without the create ever being approved.\n if (isPendingCreate(job)) {\n return `\"${id}\" is a creation request still awaiting approval; only its requester or the operator (\\`agentx schedule reject ${id}\\`) can drop it.`\n }\n if (job.approval?.action === \"delete\") return `Deletion of \"${id}\" is already awaiting approval.`\n\n const approval: ScheduleApproval = {\n action: \"delete\",\n requestedBy: caller.agentId,\n requestedAt: now.toISOString(),\n }\n const result = await mutate((c) => {\n if (!getAtPath(c, `crons.${id}`)) throw new Error(`schedule \"${id}\" not found`)\n setAtPath(c, `crons.${id}.approval`, approval)\n })\n if (!result.success) return `Error: ${result.error}`\n\n const tz = job.timezone || \"UTC\"\n const request = [\n `Schedule approval requested by ${caller.agentId}`,\n `Delete: ${id}`,\n `When: ${humanizeCron(job.schedule)} — cron \\`${job.schedule}\\` (${tz})`,\n `Next fire: ${job.enabled ? formatFireTime(nextFireTime(job.schedule, tz, now), tz) : \"— (paused)\"}`,\n `Agent: ${job.agent}`,\n \"\",\n `Approve: agentx schedule approve ${id}`,\n `Reject: agentx schedule reject ${id}`,\n ].join(\"\\n\")\n const notified = await notifyApproval(cfg, deps, request)\n return [\n `Deletion of \"${id}\" requested. It keeps its current state until the operator approves.`,\n notified,\n ].join(\"\\n\")\n }\n\n return `Error: unknown action \"${action}\". Use list, create, pause, resume or delete.`\n}\n\n/**\n * Who is calling. The runtime-exported environment wins over model-supplied\n * arguments: an agent launched by AgentX cannot claim another identity by\n * passing `callerAgentId`. The arguments are the fallback for runtimes that\n * don't export the variables (e.g. an operator-configured MCP entry).\n */\nexport function resolveScheduleCaller(\n args: Record<string, unknown>,\n env: NodeJS.ProcessEnv = process.env,\n): ScheduleCaller | null {\n const agentId = str(env.AGENTX_AGENT_ID) || str(args.callerAgentId)\n if (!agentId) return null\n const envChat = Boolean(str(env.AGENTX_CHANNEL) && str(env.AGENTX_CHAT_ID))\n const channel = envChat ? str(env.AGENTX_CHANNEL) : str(args.channel)\n const chatId = envChat ? str(env.AGENTX_CHAT_ID) : str(args.chatId)\n const accountId = str(args.accountId)\n return { agentId, channel, chatId, ...(accountId ? { accountId } : {}) }\n}\n"],"mappings":"mNAAA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,KAsDzC,IAAMC,EAA2B,IAAI,IAAI,CAAC,OAAQ,YAAa,MAAO,MAAO,MAAM,CAAC,EAE9EC,EAAiB,IAEvB,SAASC,EAAIC,EAAgC,CAC3C,OAAO,OAAOA,GAAM,UAAYA,EAAE,KAAK,EAAIA,EAAE,KAAK,EAAI,MACxD,CAEA,SAASC,EAAQC,EAAWC,EAAIL,EAAwB,CACtD,IAAMM,EAAOF,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EACzC,OAAOE,EAAK,OAASD,EAAI,GAAGC,EAAK,MAAM,EAAGD,EAAI,CAAC,UAAOC,CACxD,CAEA,SAASC,EAAcC,EAA0B,CAC/C,IAAMC,EAAOC,EAAeF,CAAU,EACtC,GAAI,CAACG,EAAWF,CAAI,EAAG,MAAM,IAAI,MAAM,uBAAuBA,GAAM,EACpE,OAAO,KAAK,MAAMG,EAAaH,EAAM,OAAO,CAAC,CAC/C,CAEA,SAASI,EAAQC,EAAUC,EAA0B,CACnD,OAAOD,GAAK,SAASC,CAAO,GAAG,QAAU,EAC3C,CAEA,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EAClE,GAAI,CAACR,EAAS,OAAO,KACrB,IAAM4D,EAAU,GAAQ1E,EAAIyE,EAAI,cAAc,GAAKzE,EAAIyE,EAAI,cAAc,GACnEE,EAAoB3E,EAAV0E,EAAcD,EAAI,eAAsBnD,EAAK,OAAb,EAC1CsD,EAAmB5E,EAAV0E,EAAcD,EAAI,eAAsBnD,EAAK,MAAb,EACzCuD,EAAY7E,EAAIsB,EAAK,SAAS,EACpC,MAAO,CAAE,QAAAR,EAAS,QAAA6D,EAAS,OAAAC,EAAQ,GAAIC,EAAY,CAAE,UAAAA,CAAU,EAAI,CAAC,CAAG,CACzE","names":["existsSync","readFileSync","NON_DELIVERABLE_CHANNELS","PROMPT_PREVIEW","str","v","preview","s","n","flat","readRawConfig","configPath","path","findConfigPath","existsSync","readFileSync","isAdmin","cfg","agentId","canManage","job","caller","ownershipError","id","owner","resolveNotify","args","raw","parts","describeJob","now","tz","next","isPendingCreate","formatFireTime","nextFireTime","state","lines","humanizeCron","notifyApproval","deps","text","dest","e","runScheduleTool","action","crons","mineOnly","entries","j","mutate","fn","applyConfigMutation","when","prompt","parsed","parseEnglishToCron","SUPPORTED_PHRASES_HINT","agent","timezone","DEFAULT_SCHEDULE_TIMEZONE","isValidTimezone","jobId","slugifyScheduleId","isValidScheduleId","notify","approval","buildScheduleJob","result","c","setAtPath","request","notified","enable","unsetAtPath","getAtPath","resolveScheduleCaller","env","envChat","channel","chatId","accountId"]}