agentix-cli 0.75.3 → 0.76.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 (111) hide show
  1. package/dist/{App-N2ZWRJKV.js → App-NCTXMA2P.js} +2 -2
  2. package/dist/{ChatApp-PGQKQBHF.js → ChatApp-CQIQEKZ2.js} +2 -2
  3. package/dist/{agent-B46X7Y6V.js → agent-5GQLISLJ.js} +2 -2
  4. package/dist/{board-dashboard-7EZ2VOUK.js → board-dashboard-E4CXJUK5.js} +5 -4
  5. package/dist/board-dashboard-E4CXJUK5.js.map +1 -0
  6. package/dist/{chunk-6CCJMHBA.js → chunk-2KOWJNQJ.js} +2 -2
  7. package/dist/{chunk-TS4JCBSP.js → chunk-676OIOHG.js} +30 -30
  8. package/dist/chunk-676OIOHG.js.map +1 -0
  9. package/dist/{chunk-NWL5KPBJ.js → chunk-72P53PGX.js} +2 -2
  10. package/dist/{chunk-663BLK67.js → chunk-7GC42WAK.js} +32 -32
  11. package/dist/chunk-7GC42WAK.js.map +1 -0
  12. package/dist/{chunk-S5JGQKON.js → chunk-A4ACRRRP.js} +2 -2
  13. package/dist/{chunk-JGEHN4VE.js → chunk-B556VD7A.js} +2 -2
  14. package/dist/{chunk-PUU2ESI2.js → chunk-CW42OBFL.js} +2 -2
  15. package/dist/{chunk-Q2FFZX7Y.js → chunk-EAMSULHF.js} +2 -2
  16. package/dist/{chunk-NZZVUEWI.js → chunk-GT6ZDLXU.js} +197 -189
  17. package/dist/chunk-GT6ZDLXU.js.map +1 -0
  18. package/dist/{chunk-UJ5JLS6Z.js → chunk-IYLQBBON.js} +2 -2
  19. package/dist/{chunk-CUXYJNWT.js → chunk-LQ3PEMBH.js} +2 -2
  20. package/dist/{chunk-55RM7V4N.js → chunk-MODPTVA6.js} +2 -2
  21. package/dist/{chunk-VJ7AFHJ6.js → chunk-N3Y3NORE.js} +2 -2
  22. package/dist/{chunk-PBUJBWOF.js → chunk-P27P7GFY.js} +5 -5
  23. package/dist/{chunk-KHEI4VNM.js → chunk-PDSCFOC4.js} +2 -2
  24. package/dist/{chunk-F2RIMHW5.js → chunk-PK6EBDBU.js} +2 -2
  25. package/dist/{chunk-2HMI5PJG.js → chunk-QGTQ4PIL.js} +2 -2
  26. package/dist/chunk-R5BXA7TL.js +3 -0
  27. package/dist/chunk-R5BXA7TL.js.map +1 -0
  28. package/dist/{chunk-BYJ3A55Y.js → chunk-S2GAEH2F.js} +2 -2
  29. package/dist/{chunk-IR2Q63IV.js → chunk-SC6Q5M4C.js} +2 -2
  30. package/dist/{chunk-RGTHA2EI.js → chunk-SY7ENNNK.js} +2 -2
  31. package/dist/{chunk-CXZ4YDHJ.js → chunk-SZZSUW42.js} +2 -2
  32. package/dist/{chunk-CXZ4YDHJ.js.map → chunk-SZZSUW42.js.map} +1 -1
  33. package/dist/{chunk-QIN6PV4J.js → chunk-URINHGJF.js} +233 -233
  34. package/dist/chunk-URINHGJF.js.map +1 -0
  35. package/dist/{chunk-CAVAMWI5.js → chunk-ZPM7SSJM.js} +2 -2
  36. package/dist/cli.js +1 -1
  37. package/dist/cli.js.map +1 -1
  38. package/dist/client-HLCKITQJ.js +2 -0
  39. package/dist/{config-A23CU2XT.js → config-QLCPWIJN.js} +2 -2
  40. package/dist/config-mutator-BCTMKRPT.js +2 -0
  41. package/dist/{doctor-6RUMFTIH.js → doctor-74P5CWVW.js} +2 -2
  42. package/dist/index.d.ts +60 -0
  43. package/dist/index.js +1 -1
  44. package/dist/index.js.map +1 -1
  45. package/dist/program-ONWCNXKS.js +2 -0
  46. package/dist/{promote-PMMUU4G2.js → promote-VFL66JD2.js} +2 -2
  47. package/dist/{query-CB6FV6JU.js → query-MCCWN6XA.js} +2 -2
  48. package/dist/{registry-A2LPURNS.js → registry-43X3DQTI.js} +2 -2
  49. package/dist/{request-planner-44WOTYCY.js → request-planner-GSGBUGNG.js} +2 -2
  50. package/dist/{review-candidates-BZLS37MN.js → review-candidates-4Z6QTMN2.js} +2 -2
  51. package/dist/{routing-CPLPRA2E.js → routing-T66LO3JY.js} +2 -2
  52. package/dist/schedule-tool-ORNG6HMN.js +2 -0
  53. package/dist/scheduler-VIWJITKR.js +2 -0
  54. package/dist/{seat-CBAZAYGY.js → seat-4H7TTV5X.js} +2 -2
  55. package/dist/{select-4CW3CXBU.js → select-YCVNOR5Q.js} +2 -2
  56. package/dist/{set-enabled-QNSLVBGT.js → set-enabled-6UGUPYW4.js} +2 -2
  57. package/dist/tool-EID3ZKQK.js +4 -0
  58. package/dist/tool-EID3ZKQK.js.map +1 -0
  59. package/dist/wiki-SHHIVZPT.js +2 -0
  60. package/package.json +1 -1
  61. package/dist/board-dashboard-7EZ2VOUK.js.map +0 -1
  62. package/dist/chunk-663BLK67.js.map +0 -1
  63. package/dist/chunk-NZZVUEWI.js.map +0 -1
  64. package/dist/chunk-QIN6PV4J.js.map +0 -1
  65. package/dist/chunk-TS4JCBSP.js.map +0 -1
  66. package/dist/client-5DVNJ4VZ.js +0 -2
  67. package/dist/config-mutator-WDZ6F6Q4.js +0 -2
  68. package/dist/program-MVCIUWJ5.js +0 -2
  69. package/dist/schedule-tool-4I3QUXJK.js +0 -2
  70. package/dist/scheduler-LJ32FB5N.js +0 -2
  71. package/dist/tool-544FGIJK.js +0 -2
  72. package/dist/tool-544FGIJK.js.map +0 -1
  73. package/dist/wiki-4LKOLCP4.js +0 -2
  74. /package/dist/{App-N2ZWRJKV.js.map → App-NCTXMA2P.js.map} +0 -0
  75. /package/dist/{ChatApp-PGQKQBHF.js.map → ChatApp-CQIQEKZ2.js.map} +0 -0
  76. /package/dist/{agent-B46X7Y6V.js.map → agent-5GQLISLJ.js.map} +0 -0
  77. /package/dist/{chunk-6CCJMHBA.js.map → chunk-2KOWJNQJ.js.map} +0 -0
  78. /package/dist/{chunk-NWL5KPBJ.js.map → chunk-72P53PGX.js.map} +0 -0
  79. /package/dist/{chunk-S5JGQKON.js.map → chunk-A4ACRRRP.js.map} +0 -0
  80. /package/dist/{chunk-JGEHN4VE.js.map → chunk-B556VD7A.js.map} +0 -0
  81. /package/dist/{chunk-PUU2ESI2.js.map → chunk-CW42OBFL.js.map} +0 -0
  82. /package/dist/{chunk-Q2FFZX7Y.js.map → chunk-EAMSULHF.js.map} +0 -0
  83. /package/dist/{chunk-UJ5JLS6Z.js.map → chunk-IYLQBBON.js.map} +0 -0
  84. /package/dist/{chunk-CUXYJNWT.js.map → chunk-LQ3PEMBH.js.map} +0 -0
  85. /package/dist/{chunk-55RM7V4N.js.map → chunk-MODPTVA6.js.map} +0 -0
  86. /package/dist/{chunk-VJ7AFHJ6.js.map → chunk-N3Y3NORE.js.map} +0 -0
  87. /package/dist/{chunk-PBUJBWOF.js.map → chunk-P27P7GFY.js.map} +0 -0
  88. /package/dist/{chunk-KHEI4VNM.js.map → chunk-PDSCFOC4.js.map} +0 -0
  89. /package/dist/{chunk-F2RIMHW5.js.map → chunk-PK6EBDBU.js.map} +0 -0
  90. /package/dist/{chunk-2HMI5PJG.js.map → chunk-QGTQ4PIL.js.map} +0 -0
  91. /package/dist/{chunk-BYJ3A55Y.js.map → chunk-S2GAEH2F.js.map} +0 -0
  92. /package/dist/{chunk-IR2Q63IV.js.map → chunk-SC6Q5M4C.js.map} +0 -0
  93. /package/dist/{chunk-RGTHA2EI.js.map → chunk-SY7ENNNK.js.map} +0 -0
  94. /package/dist/{chunk-CAVAMWI5.js.map → chunk-ZPM7SSJM.js.map} +0 -0
  95. /package/dist/{client-5DVNJ4VZ.js.map → client-HLCKITQJ.js.map} +0 -0
  96. /package/dist/{config-A23CU2XT.js.map → config-QLCPWIJN.js.map} +0 -0
  97. /package/dist/{config-mutator-WDZ6F6Q4.js.map → config-mutator-BCTMKRPT.js.map} +0 -0
  98. /package/dist/{doctor-6RUMFTIH.js.map → doctor-74P5CWVW.js.map} +0 -0
  99. /package/dist/{program-MVCIUWJ5.js.map → program-ONWCNXKS.js.map} +0 -0
  100. /package/dist/{promote-PMMUU4G2.js.map → promote-VFL66JD2.js.map} +0 -0
  101. /package/dist/{query-CB6FV6JU.js.map → query-MCCWN6XA.js.map} +0 -0
  102. /package/dist/{registry-A2LPURNS.js.map → registry-43X3DQTI.js.map} +0 -0
  103. /package/dist/{request-planner-44WOTYCY.js.map → request-planner-GSGBUGNG.js.map} +0 -0
  104. /package/dist/{review-candidates-BZLS37MN.js.map → review-candidates-4Z6QTMN2.js.map} +0 -0
  105. /package/dist/{routing-CPLPRA2E.js.map → routing-T66LO3JY.js.map} +0 -0
  106. /package/dist/{schedule-tool-4I3QUXJK.js.map → schedule-tool-ORNG6HMN.js.map} +0 -0
  107. /package/dist/{scheduler-LJ32FB5N.js.map → scheduler-VIWJITKR.js.map} +0 -0
  108. /package/dist/{seat-CBAZAYGY.js.map → seat-4H7TTV5X.js.map} +0 -0
  109. /package/dist/{select-4CW3CXBU.js.map → select-YCVNOR5Q.js.map} +0 -0
  110. /package/dist/{set-enabled-QNSLVBGT.js.map → set-enabled-6UGUPYW4.js.map} +0 -0
  111. /package/dist/{wiki-4LKOLCP4.js.map → wiki-SHHIVZPT.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/business/config.ts","../src/boards/config.ts","../src/guard/autonomy.ts","../src/voice/hotkey.ts","../src/voice/orb-palettes.ts","../src/whatsapp-triage/config.ts","../src/daemon/config.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Business layer configuration schema (EXPERIMENTAL) ---\n// Optional top-level `business` key in agentx.json.\n// When enabled, AgentX simulates a team with roles, schedules, and a work pool.\n// Experimental: off by default, undocumented while the model settles —\n// config shape may change between minor versions without migration.\n\nconst dayEnum = z.enum([\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"])\n\nconst scheduleSchema = z.object({\n days: z.array(dayEnum).default([\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]),\n start: z.string().regex(/^\\d{2}:\\d{2}$/), // \"09:00\"\n end: z.string().regex(/^\\d{2}:\\d{2}$/), // \"17:00\"\n lunch: z.object({\n start: z.string().regex(/^\\d{2}:\\d{2}$/),\n end: z.string().regex(/^\\d{2}:\\d{2}$/),\n }).optional(),\n})\n\nconst roleSchema = z.object({\n title: z.string(),\n responsibilities: z.array(z.string()).default([]),\n sopPath: z.string().optional(),\n kpis: z.array(z.string()).default([]),\n})\n\nconst orgEntrySchema = z.object({\n role: z.string(),\n reportsTo: z.string().optional(),\n schedule: scheduleSchema,\n utilizationTarget: z.number().min(0).max(1).default(0.8),\n})\n\nconst channelRefSchema = z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n})\n\nconst workSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"backlog\"),\n path: z.string().default(\".agentx/backlog.md\"),\n }),\n z.object({\n type: z.literal(\"gitlab\"),\n projects: z.array(z.string()).default([]), // empty = all configured gitlab projects\n }),\n z.object({\n type: z.literal(\"wiki\"),\n path: z.string(),\n glob: z.string().default(\"**/*.md\"),\n }),\n])\n\n/** Per-project metadata. Phase 3 of the architectural rescue —\n * `pm` is the agentId responsible for gating dispatches on this\n * project. Optional; when null, dispatches don't go through a PM\n * gate. The wiring lives in `decideAndCommit` (gated by a flag,\n * separate commit). */\nconst projectSchema = z.object({\n /** Project identifier. For GitLab/GitHub: \"owner/repo\". For\n * acme-internal projects: a stable string. */\n id: z.string(),\n /** AgentId of the PM for this project. Looked up by\n * `Organization.pmFor(project)` at dispatch time. */\n pm: z.string().optional(),\n /** Optional client this project belongs to. Used by the activity\n * graph to attribute non-projected events (Telegram chats, free-\n * text WhatsApp, cron jobs) to the right client. Falls back to\n * the leading segment of `id` (split on \"/\") when unset. */\n client: z.string().optional(),\n})\n\n/** Maps a chat or sender to a client/project so free-text channels\n * (telegram/whatsapp/slack/discord/email) get attributed correctly\n * in the activity graph. Without this, every chat lands in the\n * fallback \"internal\" bucket — the operator can't tell which client\n * the agent was helping.\n *\n * Match priority: chatId > username > channel-default. First match\n * wins. All fields except `client` are optional; `project` falls\n * back to `${client}/_chat` when unset. */\nconst contactMapSchema = z.object({\n /** Channel kind, e.g. \"telegram\", \"whatsapp\", \"slack\", \"discord\". */\n channel: z.string().optional(),\n /** Native chat id (\"-100...\" for tg groups, JID for WhatsApp). */\n chatId: z.string().optional(),\n /** Sender username/handle as exposed by the channel adapter. */\n username: z.string().optional(),\n /** Numeric sender id when username is unstable. */\n senderId: z.string().optional(),\n /** Client this contact belongs to. Required. */\n client: z.string(),\n /** Project this contact's traffic should attribute to. Defaults to\n * `${client}/_chat`. */\n project: z.string().optional(),\n /** Display name override for the initiator pill. */\n displayName: z.string().optional(),\n})\n\n/** Per-client policy. Clients are DERIVED from `projects` and `contactMap`\n * — one exists the moment either mentions it — so nothing needs declaring\n * up front. This record only carries overrides for the two things a\n * heuristic cannot know: how fast a delay costs you, and what an agent may\n * do for this client without asking first. */\nconst clientPolicySchema = z.object({\n /** Display name. Defaults to the client id. */\n name: z.string().optional(),\n /** \"client\" is someone who is waiting on you and can be let down; \"own\"\n * is your own product; \"internal\" is machinery with no external clock. */\n kind: z.enum([\"client\", \"internal\", \"own\"]).optional(),\n /** How long a wait may last before it starts costing: \"4h\", \"90m\", \"2d\".\n * Unset means no external clock, so delay is flat. */\n respondWithin: z.string().optional(),\n /** Capabilities an agent may exercise unattended. \"*\" means all. Ignored\n * for kind \"client\" — see mayProceedUnattended(). */\n standing: z.array(z.string()).default([]),\n})\n\nexport const businessConfigSchema = z.object({\n enabled: z.boolean().default(false),\n timezone: z.string().default(\"UTC\"),\n mainChannel: channelRefSchema,\n workSource: workSourceSchema,\n roles: z.record(z.string(), roleSchema).default({}),\n orgChart: z.record(z.string(), orgEntrySchema).default({}),\n /** Per-project metadata. Phase 3 — defaults to empty array, so\n * existing agentx.json files validate without modification. */\n projects: z.array(projectSchema).default([]),\n /** Maps free-text chat senders to a client/project so the activity\n * graph can attribute Telegram/WhatsApp/etc. to the right client\n * instead of the catch-all \"internal\" bucket. */\n contactMap: z.array(contactMapSchema).default([]),\n /** Overrides for derived clients. Keyed by client id; absent entries get\n * defaults, so this stays empty until you need a clock or an\n * authorization. */\n clients: z.record(z.string(), clientPolicySchema).default({}),\n /** Work-tick cadence in minutes during business hours. Default 15. */\n workTickMinutes: z.number().int().min(1).max(60).default(15),\n /** Max queue depth for an idle agent before skipping the work tick (avoids piling up). */\n idleQueueThreshold: z.number().int().min(0).default(0),\n /** Standup-tick gating + plan-driven priorities. The day-cycle's morning\n * STANDUP used to fire unconditionally per agent — operators reported it\n * as \"mechanical\" because it dispatched a Claude turn even when no human\n * had set a plan for the day. Now: the cycle reads\n * .agentx/plans/<date>.md (day → week → month fallback) and either\n * injects the plan as standup priorities, or posts a \"no plan today\"\n * notification to mainChannel and dispatches no agent. */\n standup: z.object({\n /** Master switch. When false, fireStandup is a no-op (silent). */\n enabled: z.boolean().default(true),\n /** Plans directory, relative to the daemon CWD. */\n plansDir: z.string().default(\".agentx/plans\"),\n /** Hard ceiling on how many agents the standup tick can dispatch in a\n * single morning — guards against an org-chart misconfiguration\n * fanning out to dozens of Claude calls before anyone notices. */\n maxAgentsPerDay: z.number().int().min(1).max(100).default(20),\n /** When true, even with a plan present the cycle won't dispatch — only\n * posts the resolved plan to mainChannel for human review. Useful as\n * a kill-switch while iterating on plan formats. */\n dryRun: z.boolean().default(false),\n }).default({}),\n})\n\nexport type BusinessConfig = z.infer<typeof businessConfigSchema>\nexport type BusinessRole = z.infer<typeof roleSchema>\nexport type BusinessOrgEntry = z.infer<typeof orgEntrySchema>\nexport type BusinessSchedule = z.infer<typeof scheduleSchema>\nexport type BusinessWorkSource = z.infer<typeof workSourceSchema>\nexport type BusinessChannelRef = z.infer<typeof channelRefSchema>\nexport type BusinessProject = z.infer<typeof projectSchema>\n","import { z } from \"zod\"\n\n// --- Kanban board configuration ---\n//\n// Top-level optional keys in agentx.json, independent of the business layer:\n//\n// boards: array of kanban boards, each backed by a WorkSource\n// dashboard: HTTP server controlling whether the board UI serves\n//\n// Both default to empty / disabled so existing installs see no change.\n\nexport const boardLabelSchema = z.object({\n /** Label name — used verbatim as the GitLab label string. */\n name: z.string(),\n color: z.string().regex(/^#[0-9a-f]{6}$/i).default(\"#6366f1\"),\n description: z.string().optional(),\n})\n\n/**\n * A board column. `kind` controls what issues land here and how drag-to-this-column\n * mutates the issue:\n *\n * - \"open-backlog\": opened issues that have NO scoped label matching `scopedPrefix`\n * (default \"Status\"). Dragging INTO this column removes any existing scoped label.\n * - \"scoped-label\": opened issues carrying `scopedLabel` (e.g. \"Status::Doing\").\n * Scoped labels are mutually exclusive by prefix, so adding the new one lets\n * GitLab auto-remove the old one (Premium), but we still explicitly strip the\n * previous column's label for compatibility.\n * - \"closed\": all closed issues. Dragging here closes the issue; dragging away\n * reopens it.\n * - \"label\" (default, legacy): opened issues with `mapsToLabel`; flat add/remove.\n */\nexport const boardColumnSchema = z.object({\n id: z.string().regex(/^[a-z0-9_-]+$/, \"column id must be lowercase slug\"),\n title: z.string(),\n kind: z.enum([\"open-backlog\", \"scoped-label\", \"closed\", \"label\"]).default(\"label\"),\n /** For kind=\"label\": label written on entry, removed on exit. */\n mapsToLabel: z.string().optional(),\n /** For kind=\"scoped-label\": the full scoped label (e.g. \"Status::Doing\"). */\n scopedLabel: z.string().optional(),\n /** For kind=\"open-backlog\": scoped prefix that marks \"claimed\" cards to exclude. */\n scopedPrefix: z.string().default(\"Status\"),\n /** CSS color or hex — shown as the column's top accent bar. */\n accent: z.string().optional(),\n})\nexport type BoardColumnId = string\n\nexport const boardReconcileSchema = z.object({\n enabled: z.boolean().default(true),\n staleDoingMinutes: z.number().int().min(1).default(45),\n respectLunchBreak: z.boolean().default(true),\n respectSchedule: z.boolean().default(true),\n /** Badge only for P1/P3; auto-notify + auto-demote deferred. */\n action: z.enum([\"badge\", \"notify\"]).default(\"badge\"),\n})\n\nexport const boardSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"gitlab\"),\n /** GitLab project paths (e.g. \"globex/globex-system-v2\"). At least one required. */\n projects: z.array(z.string()).min(1),\n }),\n // future: backlog, wiki\n])\n\n/**\n * GitLab-style default board — six columns:\n * Open (backlog) → To Do → Doing → On Hold → Review → Closed\n *\n * Drives the `Status::*` scoped label taxonomy. Moving a card adds/removes the\n * column's scoped label; moving INTO Closed closes the issue; moving OUT of\n * Closed reopens it; moving INTO Open strips any Status::* label.\n */\nexport const DEFAULT_COLUMNS: Array<z.infer<typeof boardColumnSchema>> = [\n { id: \"open\", title: \"Open\", kind: \"open-backlog\", scopedPrefix: \"Status\", accent: \"#6b7280\" },\n { id: \"todo\", title: \"To Do\", kind: \"scoped-label\", scopedLabel: \"Status::To Do\", scopedPrefix: \"Status\", accent: \"#fb7a35\" },\n { id: \"doing\", title: \"Doing\", kind: \"scoped-label\", scopedLabel: \"Status::Doing\", scopedPrefix: \"Status\", accent: \"#22c55e\" },\n { id: \"onhold\", title: \"On Hold\", kind: \"scoped-label\", scopedLabel: \"Status::On Hold\", scopedPrefix: \"Status\", accent: \"#f59e0b\" },\n { id: \"review\", title: \"Review\", kind: \"scoped-label\", scopedLabel: \"Status::Review\", scopedPrefix: \"Status\", accent: \"#3b82f6\" },\n { id: \"closed\", title: \"Closed\", kind: \"closed\", scopedPrefix: \"Status\", accent: \"#6b7280\" },\n]\n\nexport const boardSchema = z.object({\n id: z.string().regex(/^[a-z0-9_-]+$/, \"board id must be lowercase slug\"),\n name: z.string(),\n source: boardSourceSchema,\n /** If set, ANDed into every listAll query and shown as a baseline chip in the UI. */\n primaryToolLabel: z.string().optional(),\n labels: z.array(boardLabelSchema).default([]),\n columns: z.array(boardColumnSchema).min(1).default(DEFAULT_COLUMNS),\n timeRangeDays: z.number().int().min(1).max(365).default(30),\n /** Maximum closed-issue window (days) shown in the Closed column. */\n closedWindowDays: z.number().int().min(1).max(365).default(30),\n reconciliation: boardReconcileSchema.default({}),\n})\n\nexport const boardsConfigSchema = z.array(boardSchema).default([])\n\nexport const dashboardDaemonSchema = z.object({\n name: z.string(),\n /** Daemon HTTP URL (the one serving /agents, /health, /task). */\n url: z.string(),\n /** Optional board-dashboard URL if we want to proxy admin writes to this\n * peer. Defaults to `url` with port :18800/:19900 rewritten to :4202,\n * matching our convention that the dashboard runs alongside the daemon. */\n dashboardUrl: z.string().optional(),\n /** Bearer for the daemon's HTTP API (live snapshot, task stream). */\n token: z.string().optional(),\n /** Bearer for the peer's dashboard when proxying admin calls. Defaults to\n * `token` when unset. */\n dashboardToken: z.string().optional(),\n})\n\nexport const dashboardConfigSchema = z.object({\n enabled: z.boolean().default(false),\n port: z.number().int().default(4202),\n bind: z.string().default(\"127.0.0.1\"),\n /** Opt-in bearer token for writes. If unset, writes are unauthenticated. */\n token: z.string().optional(),\n /** Primary daemon the dashboard talks to for live view + A2A. */\n daemonUrl: z.string().default(\"http://localhost:18800\"),\n /** Additional daemons to poll (beyond peers discovered via primary's /mesh). */\n daemons: z.array(dashboardDaemonSchema).default([]),\n /** Default agent used for AI-assisted drafting in the create-issue flow. */\n draftAgent: z.string().optional(),\n}).default({})\n\nexport type BoardConfig = z.infer<typeof boardSchema>\nexport type BoardLabel = z.infer<typeof boardLabelSchema>\nexport type BoardColumn = z.infer<typeof boardColumnSchema>\nexport type BoardSource = z.infer<typeof boardSourceSchema>\nexport type BoardReconcile = z.infer<typeof boardReconcileSchema>\nexport type DashboardConfig = z.infer<typeof dashboardConfigSchema>\n\n/**\n * Decide which column an item lives in. Walks columns in order; the first\n * matching column wins. Items with `state: \"closed\"` always land in the\n * first `kind: \"closed\"` column; otherwise the first `scoped-label` whose\n * `scopedLabel` is present wins; otherwise the first `label` column whose\n * `mapsToLabel` is present; otherwise the first `open-backlog` column.\n *\n * Returns `null` when the item carries a scoped label matching an\n * `open-backlog` column's `scopedPrefix` but no `scoped-label` column claims\n * it — those are off-board workflow states (e.g. `Status::Done` when no\n * Done column exists) and must not leak into the backlog.\n */\nexport function deriveStage(\n item: { state?: \"opened\" | \"closed\"; labels?: string[] },\n columns: BoardColumn[],\n): BoardColumnId | null {\n const set = new Set(item.labels || [])\n if (item.state === \"closed\") {\n const closed = columns.find((c) => c.kind === \"closed\")\n if (closed) return closed.id\n }\n for (const c of columns) {\n if (c.kind === \"scoped-label\" && c.scopedLabel && set.has(c.scopedLabel)) return c.id\n }\n for (const c of columns) {\n if (c.kind === \"label\" && c.mapsToLabel && set.has(c.mapsToLabel)) return c.id\n }\n const backlog = columns.find((c) => c.kind === \"open-backlog\")\n if (backlog) {\n // If the item has any scoped-prefix label, it's not an open-backlog candidate.\n const prefix = backlog.scopedPrefix + \"::\"\n const hasScoped = [...set].some((l) => l.startsWith(prefix))\n return hasScoped ? null : backlog.id\n }\n return columns[0]?.id ?? null\n}\n\n/**\n * Describes how to mutate an issue to move it between two columns.\n * `closeIssue` / `reopen` take precedence over label mutations on the same action.\n */\nexport interface ColumnTransition {\n addLabels?: string[]\n removeLabels?: string[]\n closeIssue?: boolean\n reopen?: boolean\n}\n\nexport function transitionDiff(\n fromColumn: BoardColumn | undefined,\n toColumn: BoardColumn,\n): ColumnTransition {\n const add: string[] = []\n const remove: string[] = []\n let closeIssue = false\n let reopen = false\n\n // Handle target column.\n if (toColumn.kind === \"scoped-label\" && toColumn.scopedLabel) {\n add.push(toColumn.scopedLabel)\n } else if (toColumn.kind === \"label\" && toColumn.mapsToLabel) {\n add.push(toColumn.mapsToLabel)\n } else if (toColumn.kind === \"closed\") {\n closeIssue = true\n }\n\n // Handle source column — strip its label; if it was \"closed\", reopen.\n if (fromColumn) {\n if (fromColumn.kind === \"scoped-label\" && fromColumn.scopedLabel) {\n remove.push(fromColumn.scopedLabel)\n } else if (fromColumn.kind === \"label\" && fromColumn.mapsToLabel) {\n remove.push(fromColumn.mapsToLabel)\n } else if (fromColumn.kind === \"closed\" && toColumn.kind !== \"closed\") {\n reopen = true\n }\n }\n\n return {\n addLabels: add.length ? add : undefined,\n removeLabels: remove.length ? remove : undefined,\n closeIssue: closeIssue || undefined,\n reopen: reopen || undefined,\n }\n}\n","import { z } from \"zod\"\n\n// --- Routine autonomy levels: the rule sets ---\n//\n// A routine (cron job or workflow agent step) may run below its agent's full\n// power:\n//\n// report — read-only. No file writes, no mutating shell, no outward-posting\n// tools. The only output is the final answer, which the scheduler\n// delivers.\n// propose — may edit files, commit, push a feature branch, open an MR/PR or\n// a draft. Never merge, deploy, delete, force-push, or touch\n// production.\n// act — unchanged: whatever the agent may normally do.\n//\n// This module is PURE: (level, tool call) -> allow | block. It is evaluated\n// by the daemon for every tool call of a restricted task (see\n// autonomy-enforce.ts for the wiring). Deterministic by construction, like\n// the rest of the guard.\n//\n// Shape of the two restricted levels differs on purpose:\n// - report is an ALLOWLIST. A read-only posture cannot be expressed as\n// \"everything except the dangerous things\" — `python -c`, `node x.js`\n// or a `curl -d` are all writes nobody would list. Unknown => blocked.\n// - propose is a DENYLIST over a working agent. Its job is to stop the\n// irreversible, outward steps (merge/deploy/delete/force-push), not to\n// make the agent useless. A determined agent can evade a denylist by\n// indirection (write a script, then run it); propose is a guardrail for\n// honest routines, report is the hard boundary.\n\nexport const autonomyLevelSchema = z.enum([\"report\", \"propose\", \"act\"])\nexport type AutonomyLevel = z.infer<typeof autonomyLevelSchema>\n\n/** True for the levels that need per-task enforcement. */\nexport function isRestricted(level: AutonomyLevel | undefined | null): level is \"report\" | \"propose\" {\n return level === \"report\" || level === \"propose\"\n}\n\nexport interface AutonomyInput {\n tool: string\n command?: string\n filePath?: string\n}\n\nexport interface AutonomyDecision {\n allowed: boolean\n /** Stable id, e.g. \"autonomy.report.write\". Null when allowed. */\n ruleId: string | null\n reason: string | null\n}\n\nconst ALLOW: AutonomyDecision = { allowed: true, ruleId: null, reason: null }\nconst block = (level: string, id: string, reason: string): AutonomyDecision => ({\n allowed: false,\n ruleId: `autonomy.${level}.${id}`,\n reason,\n})\n\n// ---------------------------------------------------------------- tools\n\nconst WRITE_TOOLS = new Set([\"Write\", \"Edit\", \"MultiEdit\", \"NotebookEdit\"])\n\n/** Native tools that never change anything outside the conversation. */\nconst REPORT_SAFE_TOOLS = new Set([\n \"Read\", \"Glob\", \"Grep\", \"LS\", \"NotebookRead\", \"WebFetch\", \"WebSearch\",\n \"TodoWrite\", \"TodoRead\", \"Task\", \"Agent\", \"Skill\", \"ToolSearch\",\n \"BashOutput\", \"KillShell\", \"ExitPlanMode\", \"EnterPlanMode\",\n \"ListMcpResourcesTool\", \"ReadMcpResourceTool\",\n])\n\n/** Split a tool name into lowercase words: `mcp__gitlab__create_merge_request`\n * -> [mcp, gitlab, create, merge, request]; camelCase splits too. */\nexport function toolWords(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((w) => w.toLowerCase())\n}\n\n/** The action words of an MCP tool name (server prefix dropped), with the\n * nouns \"merge request\" / \"pull request\" folded so `create_merge_request`\n * reads as create-an-MR, not as a merge. */\nexport function mcpActionWords(name: string): string[] {\n return toolWords(name)\n .slice(2)\n .join(\" \")\n .replace(/\\b(merge|pull)\\s+requests?\\b/g, \"mergerequest\")\n .split(\" \")\n .filter(Boolean)\n}\n\nconst READ_VERBS = new Set([\n \"get\", \"list\", \"search\", \"read\", \"view\", \"fetch\", \"query\", \"find\", \"show\", \"describe\",\n \"status\", \"diff\", \"inspect\", \"lookup\", \"count\", \"stats\", \"browse\", \"whoami\", \"download\",\n])\n/** Irreversible or outward-facing verbs. Blocked in propose, and in report. */\nconst DESTRUCTIVE_VERBS = new Set([\n \"merge\", \"delete\", \"remove\", \"destroy\", \"drop\", \"deploy\", \"publish\", \"release\", \"approve\",\n \"archive\", \"revoke\", \"purge\", \"close\", \"transfer\", \"force\", \"rollback\", \"restart\", \"erase\",\n \"unprotect\", \"truncate\", \"wipe\", \"kill\", \"terminate\", \"unpublish\", \"promote\",\n])\n/** Any state change at all. Blocked in report. */\nconst MUTATING_VERBS = new Set([\n ...DESTRUCTIVE_VERBS,\n \"create\", \"update\", \"post\", \"send\", \"write\", \"edit\", \"add\", \"set\", \"comment\", \"reply\",\n \"push\", \"run\", \"execute\", \"exec\", \"trigger\", \"upload\", \"move\", \"rename\", \"cancel\", \"retry\",\n \"assign\", \"label\", \"react\", \"invite\", \"notify\", \"schedule\", \"start\", \"stop\", \"submit\", \"save\",\n \"patch\", \"put\", \"insert\", \"upsert\", \"apply\", \"install\", \"import\", \"mark\", \"toggle\", \"enable\",\n \"disable\", \"open\", \"commit\", \"sync\", \"reset\", \"store\", \"remember\", \"forget\", \"broadcast\",\n \"message\", \"call\", \"dispatch\", \"enqueue\", \"resolve\", \"unassign\", \"lock\", \"unlock\", \"pin\",\n])\n\n// ---------------------------------------------------------------- shell view\n\n/**\n * The part of a shell command the shell will actually EXECUTE, flattened so\n * every command position can be inspected:\n * - single-quoted text is blanked (truly literal),\n * - double-quoted text is blanked unless it contains `$(`/backticks, in\n * which case the substitution is executed and must stay visible,\n * - heredoc bodies are blanked unless the delimiter is unquoted and the\n * body substitutes commands.\n * Returns `null` for input too irregular to judge (unbalanced quotes), which\n * callers treat as \"block\" in report mode.\n */\nexport function shellView(command: string): string | null {\n // Heredocs: blank the body unless the delimiter is unquoted AND the body\n // substitutes commands (then the shell executes it — keep it visible).\n const text = command.replace(/<<-?\\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\\1([\\s\\S]*?)^\\s*\\2\\s*$/gm,\n (m, quote: string, _d: string, body: string) =>\n !quote && /\\$\\(|`/.test(body) ? m : m.split(\"\\n\")[0] + \"\\n\")\n let out = \"\"\n let i = 0\n while (i < text.length) {\n const c = text[i]\n if (c === \"\\\\\") { out += text.slice(i, i + 2); i += 2; continue }\n if (c === \"'\") {\n const end = text.indexOf(\"'\", i + 1)\n if (end < 0) return null\n out += \"''\"\n i = end + 1\n continue\n }\n if (c === '\"') {\n let j = i + 1\n while (j < text.length && text[j] !== '\"') j += text[j] === \"\\\\\" ? 2 : 1\n if (j >= text.length) return null\n const inner = text.slice(i + 1, j)\n out += /\\$\\(|`/.test(inner) ? ` ${inner} ` : '\"\"'\n i = j + 1\n continue\n }\n out += c\n i++\n }\n return out\n}\n\n/** Split a shell view into simple-command segments (words arrays). */\nexport function shellSegments(view: string): string[][] {\n return view\n .split(/\\|\\||&&|[;|&\\n`()]|\\$\\(|<\\(|>\\(/)\n .map((s) => s.trim().split(/\\s+/).filter(Boolean))\n .filter((w) => w.length > 0)\n}\n\nconst SHELL_KEYWORDS_STRIP = new Set([\"then\", \"do\", \"else\", \"elif\", \"if\", \"while\", \"until\", \"!\", \"{\", \"}\", \"time\"])\nconst SHELL_KEYWORDS_SKIP = new Set([\"done\", \"fi\", \"esac\", \"for\", \"case\", \"select\", \"in\", \";;\"])\n\n/** Drop leading keywords and `VAR=value` assignments; return the command words. */\nfunction commandWords(words: string[]): string[] {\n let i = 0\n while (i < words.length) {\n const w = words[i]\n if (SHELL_KEYWORDS_SKIP.has(w)) return []\n if (SHELL_KEYWORDS_STRIP.has(w) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) { i++; continue }\n break\n }\n return words.slice(i)\n}\n\n/** `git [-C dir] [--flags] <sub> <rest...>` -> { sub, rest }. */\nfunction gitSubcommand(args: string[]): { sub: string | undefined; rest: string[] } {\n let i = 0\n while (i < args.length && args[i].startsWith(\"-\")) i += /^-(C|c)$|^--(git-dir|work-tree|namespace)$/.test(args[i]) ? 2 : 1\n return { sub: args[i], rest: args.slice(i + 1) }\n}\n\n/** Command name without its path: `/usr/bin/git` -> `git`. */\nconst baseName = (w: string) => w.replace(/^.*\\//, \"\")\n\n// ---------------------------------------------------------------- report\n\nconst REPORT_SHELL_COMMANDS = new Set([\n \"ls\", \"pwd\", \"cd\", \"cat\", \"head\", \"tail\", \"wc\", \"grep\", \"egrep\", \"fgrep\", \"rg\", \"fd\", \"tree\",\n \"stat\", \"file\", \"du\", \"df\", \"date\", \"whoami\", \"id\", \"hostname\", \"uname\", \"which\", \"type\",\n \"sort\", \"uniq\", \"cut\", \"tr\", \"diff\", \"cmp\", \"comm\", \"basename\", \"dirname\", \"realpath\",\n \"readlink\", \"jq\", \"column\", \"nl\", \"seq\", \"true\", \"false\", \"test\", \"[\", \"sleep\", \"ps\",\n \"uptime\", \"echo\", \"printf\", \"base64\", \"md5\", \"md5sum\", \"shasum\", \"sha256sum\", \"less\", \"more\",\n \"printenv\", \"dig\", \"nslookup\", \"host\", \"find\", \"git\", \"gh\", \"glab\", \"curl\",\n])\n\nconst GIT_READ = new Set([\n \"status\", \"log\", \"diff\", \"show\", \"rev-parse\", \"ls-files\", \"ls-tree\", \"blame\", \"shortlog\",\n \"describe\", \"cat-file\", \"grep\", \"branch\", \"tag\", \"remote\", \"config\", \"reflog\", \"rev-list\",\n \"merge-base\", \"name-rev\", \"show-ref\", \"for-each-ref\", \"whatchanged\",\n])\nconst GH_READ_ACTIONS = new Set([\"view\", \"list\", \"diff\", \"status\", \"checks\", \"ls\"])\n\nfunction reportShellWord(words: string[]): string | null {\n const [cmd, ...args] = words\n const base = cmd.replace(/^.*\\//, \"\")\n if (!REPORT_SHELL_COMMANDS.has(base)) return `\\`${base}\\` is not a read-only command`\n const has = (re: RegExp) => args.some((a) => re.test(a))\n switch (base) {\n case \"find\":\n if (has(/^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/)) return \"find with -exec/-delete\"\n return null\n case \"sort\":\n if (has(/^(-o|--output)/)) return \"sort -o writes a file\"\n return null\n case \"git\": {\n if (has(/^(-c|--exec-path|--output)/)) return \"git option that can execute or write\"\n const { sub, rest } = gitSubcommand(args)\n if (!sub || !GIT_READ.has(sub)) return `git ${sub ?? \"\"} is not read-only`.trim()\n if (sub === \"branch\" && rest.some((a) => /^-(d|D|m|M|c|C|f|u)$|^--(delete|move|copy|force|set-upstream|unset-upstream|edit-description)/.test(a) || !a.startsWith(\"-\"))) {\n return \"git branch that changes branches\"\n }\n if (sub === \"tag\" && rest.some((a) => !/^(-l|--list|-n\\d*|--contains|--points-at|--sort=.*|--merged|--no-merged)$/.test(a))) {\n return \"git tag that creates or deletes tags\"\n }\n if (sub === \"remote\" && rest.length > 0 && !/^(-v|--verbose|show|get-url)$/.test(rest[0])) return \"git remote that changes remotes\"\n if (sub === \"config\" && !rest.some((a) => /^(--get|--get-all|--get-regexp|--list|-l)$/.test(a))) return \"git config write\"\n if (sub === \"reflog\" && rest.length > 0 && !/^(show|-)/.test(rest[0])) return \"git reflog that expires or deletes\"\n return null\n }\n case \"gh\":\n case \"glab\": {\n const [group, action] = args.filter((a) => !a.startsWith(\"-\"))\n if (group === \"search\") return null\n if (group === \"api\") {\n const method = args.findIndex((a) => /^(-X|--method)$/.test(a))\n if (method >= 0 && !/^GET$/i.test(args[method + 1] ?? \"\")) return `${base} api with a non-GET method`\n if (has(/^-X(?!GET$)\\w+|^--method=(?!GET$)/i)) return `${base} api with a non-GET method`\n if (has(/^(-f|-F|--field|--raw-field|--input)/)) return `${base} api with a request body`\n return null\n }\n if (!action || !GH_READ_ACTIONS.has(action)) return `${base} ${group ?? \"\"} ${action ?? \"\"} is not read-only`.replace(/\\s+/g, \" \").trim()\n return null\n }\n case \"curl\": {\n const m = args.findIndex((a) => /^(-X|--request)$/.test(a))\n if (m >= 0 && !/^(GET|HEAD|OPTIONS)$/i.test(args[m + 1] ?? \"\")) return \"curl with a non-GET method\"\n if (has(/^-X(?!GET$|HEAD$)\\w+|^--request=(?!GET$|HEAD$)/i)) return \"curl with a non-GET method\"\n if (has(/^(-d|--data|--data-\\w+|--json|-F|--form|-T|--upload-file|-o|--output|-O|--remote-name|-K|--config)/)) {\n return \"curl that sends a body or writes a file\"\n }\n return null\n }\n default:\n return null\n }\n}\n\n/** Redirects that write somewhere other than /dev/null or another fd. */\nfunction hasWritingRedirect(view: string): boolean {\n const cleaned = view\n .replace(/\\d*>>?\\s*\\/dev\\/null/g, \" \")\n .replace(/&>>?\\s*\\/dev\\/null/g, \" \")\n .replace(/\\d*>&\\s*\\d+/g, \" \")\n return /[>]/.test(cleaned)\n}\n\nfunction reportBash(command: string): AutonomyDecision {\n const view = shellView(command)\n if (view === null) return block(\"report\", \"shell\", \"command too irregular to verify as read-only\")\n if (hasWritingRedirect(view)) return block(\"report\", \"shell\", \"output redirection writes a file\")\n for (const seg of shellSegments(view)) {\n const words = commandWords(seg)\n if (words.length === 0) continue\n const why = reportShellWord(words)\n if (why) return block(\"report\", \"shell\", why)\n }\n return ALLOW\n}\n\nfunction reportTool(input: AutonomyInput): AutonomyDecision {\n if (WRITE_TOOLS.has(input.tool)) return block(\"report\", \"write\", `${input.tool} modifies files`)\n if (input.tool === \"Bash\") return reportBash(input.command ?? \"\")\n if (REPORT_SAFE_TOOLS.has(input.tool)) return ALLOW\n if (input.tool.startsWith(\"mcp__\")) {\n const words = mcpActionWords(input.tool)\n const mutating = words.find((w) => MUTATING_VERBS.has(w))\n if (mutating) return block(\"report\", \"outward\", `tool \"${input.tool}\" can change state (${mutating})`)\n if (words.some((w) => READ_VERBS.has(w))) return ALLOW\n return block(\"report\", \"outward\", `tool \"${input.tool}\" is not recognisably read-only`)\n }\n return block(\"report\", \"tool\", `tool \"${input.tool}\" is not on the read-only list`)\n}\n\n// ---------------------------------------------------------------- propose\n\ninterface ShellRule { id: string; re: RegExp; reason: string }\n\n/** Content rules, matched against the RAW command: quoting is how these\n * payloads are delivered (`psql -c 'DROP TABLE x'`), not a disclaimer. */\nconst PROPOSE_RAW_RULES: ShellRule[] = [\n { id: \"merge\", re: /merge_when_pipeline_succeeds|\\bauto[_-]merge\\b/i, reason: \"auto-merging is an act-level action\" },\n { id: \"merge\", re: /\\b(curl|wget|http|gh\\s+api|glab\\s+api)\\b[^\\n]*\\/merges?\\b/i, reason: \"calling a merge endpoint is an act-level action\" },\n { id: \"delete\", re: /(?:^|\\W)(drop|truncate)\\s+(table|database|schema|index|collection)\\b|(?:^|\\W)delete\\s+from\\b|\\bflushall\\b|\\bflushdb\\b/i, reason: \"destroying data is an act-level action\" },\n { id: \"delete\", re: /(-X|--request)[\\s=]*['\"]?DELETE\\b/i, reason: \"HTTP DELETE is an act-level action\" },\n { id: \"delegate\", re: /\\b(curl|wget|http)\\b[^\\n]*(localhost|127\\.0\\.0\\.1|\\[::1\\])[^\\n]*\\/(ask|task|send|chat|mesh|workflows?|crons?|reload|config)\\b/i, reason: \"calling the local daemon to dispatch work escapes this routine's limit\" },\n]\n\n/** Command rules, matched against one simple command (quoted text blanked). */\nconst PROPOSE_COMMAND_RULES: ShellRule[] = [\n { id: \"merge\", re: /^(gh\\s+pr\\s+merge|glab\\s+mr\\s+merge)\\b/i, reason: \"merging is an act-level action\" },\n { id: \"delete\", re: /^rm\\s+(.*\\s)?(-\\w*[rR]\\w*|--recursive)\\b|^(shred|dropdb)\\b|^find\\b.*\\s-delete\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"delete\", re: /^git\\s+(clean\\s+-\\w*f|reset\\s+--hard|branch\\s+(-\\w*[dD]\\w*|--delete)|tag\\s+(-d|--delete)|stash\\s+(drop|clear)|remote\\s+(remove|rm))\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"delete\", re: /^(gh|glab)\\s+\\S+\\s+delete\\b|^docker\\s+(rm|rmi|volume\\s+rm|system\\s+prune)\\b|^(kubectl\\s+delete|aws\\s+s3\\s+(rm|rb)|gsutil\\s+rm)\\b|^doctl\\s+.*\\sdelete\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"deploy\", re: /^(kubectl\\s+(apply|rollout|scale|set|patch|replace|create|edit)|helm\\s+(install|upgrade|rollback|uninstall|delete)|terraform\\s+(apply|destroy|import|taint)|pulumi\\s+(up|destroy)|docker\\s+push|netlify\\s+deploy|fly(ctl)?\\s+deploy|serverless\\s+deploy|vercel\\b.*--prod)\\b/i, reason: \"deploying is an act-level action\" },\n { id: \"deploy\", re: /^((npm|pnpm|yarn|bun)(\\s+run)?|make|just|task|rake)\\s+(\\S+:)?deploy\\b|^((ba|z)?sh|node|python3?)\\s+\\S*deploy[^\\s/]*$|^\\S*\\/deploy(\\.\\w+)?\\b|^deploy(\\.\\w+)?\\b/i, reason: \"deploying is an act-level action\" },\n { id: \"deploy\", re: /^((npm|pnpm|yarn|bun)\\s+publish|cargo\\s+publish|twine\\s+upload|(gh|glab)\\s+release\\s+(create|upload|edit)|(npx\\s+)?prisma\\s+(migrate\\s+(deploy|reset)|db\\s+push))\\b/i, reason: \"publishing or migrating is an act-level action\" },\n { id: \"prod\", re: /^(ssh|scp|sudo|doas|systemctl|launchctl|service|kill|pkill|killall|reboot|shutdown)\\b|^rsync\\b.*\\s\\S+:\\S*/i, reason: \"operating hosts and services is an act-level action\" },\n { id: \"delegate\", re: /^(agentx|agentix)\\s+(ask|send|task|exec|run|chat|mesh|cron|workflow|daemon|config)\\b/i, reason: \"handing work to another agent or reconfiguring the daemon escapes this routine's limit\" },\n]\n\nconst PROTECTED_BRANCH = /^(main|master|trunk|develop|development|prod|production|staging|stable|release([/-].*)?|HEAD|@)$/i\n/** `git push` options that consume the next word. */\nconst PUSH_VALUE_OPTS = /^(-o|--push-option|--repo|--receive-pack|--exec)$/\n\n/** A push may only name feature branches explicitly — no force, no delete,\n * no mirror/tags, no protected destinations, no implicit \"current branch\". */\nfunction proposeGitPush(rest: string[]): AutonomyDecision | null {\n const positional: string[] = []\n for (let i = 0; i < rest.length; i++) {\n const a = rest[i]\n if (PUSH_VALUE_OPTS.test(a)) { i++; continue }\n if (/^(--force.*|-d|--delete|--mirror|--all|--tags|--prune)$/.test(a) || /^-[a-zA-Z]*f/.test(a)) {\n return block(\"propose\", \"push\", \"force, delete, mirror and tag pushes are act-level actions\")\n }\n if (!a.startsWith(\"-\")) positional.push(a)\n }\n const refspecs = positional.slice(1)\n if (refspecs.length === 0) return block(\"propose\", \"push\", \"name the feature branch explicitly: git push <remote> <branch>\")\n for (const ref of refspecs) {\n if (ref.startsWith(\"+\") || ref.startsWith(\":\")) return block(\"propose\", \"push\", `refspec \"${ref}\" force-pushes or deletes`)\n const name = (ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref).replace(/^refs\\/heads\\//, \"\")\n if (PROTECTED_BRANCH.test(name)) return block(\"propose\", \"push\", `pushing to \"${name}\" is an act-level action; push a feature branch and open a merge request`)\n }\n return null\n}\n\nfunction proposeBash(command: string): AutonomyDecision {\n for (const rule of PROPOSE_RAW_RULES) {\n if (rule.re.test(command)) return block(\"propose\", rule.id, rule.reason)\n }\n const view = shellView(command)\n if (view === null) return block(\"propose\", \"shell\", \"command too irregular to verify\")\n for (const seg of shellSegments(view)) {\n const words = commandWords(seg)\n if (words.length === 0) continue\n const line = [baseName(words[0]), ...words.slice(1)].join(\" \")\n for (const rule of PROPOSE_COMMAND_RULES) {\n if (rule.re.test(line)) return block(\"propose\", rule.id, rule.reason)\n }\n if (baseName(words[0]) === \"git\") {\n const { sub, rest } = gitSubcommand(words.slice(1))\n if (sub === \"push\") {\n const hit = proposeGitPush(rest)\n if (hit) return hit\n }\n }\n }\n return ALLOW\n}\n\nfunction proposeTool(input: AutonomyInput): AutonomyDecision {\n if (input.tool === \"Bash\") return proposeBash(input.command ?? \"\")\n if (input.tool.startsWith(\"mcp__\")) {\n const hit = mcpActionWords(input.tool).find((w) => DESTRUCTIVE_VERBS.has(w))\n if (hit) return block(\"propose\", \"outward\", `tool \"${input.tool}\" performs an act-level action (${hit})`)\n if (isDelegation(mcpActionWords(input.tool))) {\n return block(\"propose\", \"delegate\", `tool \"${input.tool}\" hands work to another agent, which would run at its own full autonomy`)\n }\n }\n return ALLOW\n}\n\n/** Handing the task to another agent escapes the limit: that agent's run\n * is not restricted. */\nfunction isDelegation(words: string[]): boolean {\n if (words.includes(\"delegate\") || words.includes(\"handoff\")) return true\n if (words.includes(\"agent\") && words.some((w) => w === \"send\" || w === \"ask\" || w === \"message\" || w === \"task\")) return true\n return words.includes(\"task\") && !words.some((w) => READ_VERBS.has(w))\n}\n\n// ---------------------------------------------------------------- entry\n\n/** Judge one tool call against an autonomy level. `act` allows everything. */\nexport function evaluateAutonomy(level: AutonomyLevel, input: AutonomyInput): AutonomyDecision {\n if (level === \"report\") return reportTool(input)\n if (level === \"propose\") return proposeTool(input)\n return ALLOW\n}\n\n/** One-paragraph brief prepended to a restricted task, so the model knows\n * the boundary up front instead of discovering it by being blocked. The\n * enforcement does not depend on it. */\nexport function autonomyBrief(level: AutonomyLevel): string {\n if (level === \"report\") {\n return \"[Autonomy: report] This routine runs read-only. Investigate and report; do not modify files, run mutating commands, or post anywhere. Your final answer is the deliverable. Blocked actions are enforced and logged; if something needs doing, describe it in the report instead.\"\n }\n if (level === \"propose\") {\n return \"[Autonomy: propose] You may edit files, commit, push a named feature branch, and open a merge request or draft. You may not merge, deploy, delete, force-push, push to protected branches, or operate hosts. These limits are enforced and logged; leave act-level steps as clear recommendations.\"\n }\n return \"\"\n}\n","// --- Keyboard shortcuts for AgentX Voice, as stored in agentx.json ---\n//\n// A shortcut is written as modifiers and one key joined by \"+\", for\n// example \"opt+space\", \"cmd+opt+period\" or \"ctrl+opt+1\". The Mac app\n// (apps/mac-voice Hotkey.swift) reads the same form. Stored in one\n// normal order (ctrl, opt, shift, cmd, then the key) so two ways of\n// writing a shortcut compare equal.\n\nconst MODIFIERS: Record<string, \"ctrl\" | \"opt\" | \"shift\" | \"cmd\"> = {\n ctrl: \"ctrl\", control: \"ctrl\",\n opt: \"opt\", option: \"opt\", alt: \"opt\",\n shift: \"shift\",\n cmd: \"cmd\", command: \"cmd\",\n}\nconst ORDER = [\"ctrl\", \"opt\", \"shift\", \"cmd\"] as const\n\nconst NAMED_KEYS = [\n \"space\", \"period\", \"comma\", \"slash\", \"semicolon\", \"quote\", \"minus\", \"equal\",\n \"leftbracket\", \"rightbracket\", \"backslash\", \"grave\", \"return\", \"tab\",\n]\nconst KEY_ALIASES: Record<string, string> = { \".\": \"period\", \",\": \"comma\", \"/\": \"slash\", \";\": \"semicolon\", \"'\": \"quote\", \"-\": \"minus\", \"=\": \"equal\", \"`\": \"grave\", enter: \"return\" }\n\nconst isFKey = (k: string) => /^f([1-9]|1[0-9]|20)$/.test(k)\nconst isKey = (k: string) => /^[a-z0-9]$/.test(k) || NAMED_KEYS.includes(k) || isFKey(k)\n\nexport type HotkeyParse = { ok: true; value: string } | { ok: false; error: string }\n\n/** A shortcut in its stored form, or why it cannot be one. */\nexport function parseHotkey(input: string): HotkeyParse {\n const raw = String(input ?? \"\").trim().toLowerCase()\n if (!raw) return { ok: false, error: \"is empty\" }\n // \"+\" itself is not a key we accept, so splitting on it is safe.\n const parts = raw.split(\"+\").map((p) => p.trim())\n if (parts.some((p) => !p)) return { ok: false, error: `\"${input}\" has an empty part; write it like opt+space` }\n const key = KEY_ALIASES[parts[parts.length - 1]] ?? parts[parts.length - 1]\n const mods = new Set<string>()\n for (const p of parts.slice(0, -1)) {\n const m = MODIFIERS[p]\n if (!m) return { ok: false, error: `\"${p}\" is not a modifier; use ctrl, opt, shift or cmd` }\n if (mods.has(m)) return { ok: false, error: `\"${input}\" names ${m} twice` }\n mods.add(m)\n }\n if (!isKey(key)) return { ok: false, error: `\"${key}\" is not a key AgentX Voice can use; use a letter, a digit, f1 to f20, or space, period, comma, slash, return, tab` }\n // Without ctrl, opt or cmd the shortcut would swallow ordinary typing.\n if (!isFKey(key) && ![\"ctrl\", \"opt\", \"cmd\"].some((m) => mods.has(m))) {\n return { ok: false, error: `\"${input}\" needs ctrl, opt or cmd, or it would take that key away from your typing` }\n }\n return { ok: true, value: [...ORDER.filter((m) => mods.has(m)), key].join(\"+\") }\n}\n\n/** Zod refinement message helper: undefined when fine. */\nexport function hotkeyError(input: string): string | undefined {\n const r = parseHotkey(input)\n return r.ok ? undefined : r.error\n}\n\n/** \"⌃⌥1\" for \"ctrl+opt+1\", as the Mac shows shortcuts. */\nexport function describeHotkey(value: string): string {\n const sym: Record<string, string> = { ctrl: \"⌃\", opt: \"⌥\", shift: \"⇧\", cmd: \"⌘\" }\n const names: Record<string, string> = { space: \"Space\", period: \".\", comma: \",\", slash: \"/\", semicolon: \";\", quote: \"'\", minus: \"-\", equal: \"=\", leftbracket: \"[\", rightbracket: \"]\", backslash: \"\\\\\", grave: \"`\", return: \"Return\", tab: \"Tab\" }\n const parts = value.split(\"+\")\n const key = parts.pop() ?? \"\"\n return parts.map((m) => sym[m] ?? m).join(\"\") + (names[key] ?? key.toUpperCase())\n}\n\nexport const DEFAULT_HOTKEYS = { talk: \"opt+space\", stop: \"cmd+opt+period\", paste: \"cmd+opt+v\" } as const\n","// --- The voice orb's colour palettes, drawn from nature ---\n//\n// Each agent's orb in AgentX Voice flows through one of these gradients.\n// An agent picks one with presence.palette; without one it gets the\n// palette whose hue is nearest its presence colour, so it stays\n// recognisable as the same agent as its on-screen pointer. The app draws\n// whatever colours the daemon sends, so this file is the only list.\n\nexport interface OrbPalette {\n id: string\n label: string\n /** Five stops, deep to light. The orb's mesh uses all five; the last\n * is its bright core. */\n colors: [string, string, string, string, string]\n /** The hue (0–360) an agent colour is matched against. */\n hue: number\n}\n\nexport const ORB_PALETTES: OrbPalette[] = [\n { id: \"sunrise\", label: \"Sunrise\", hue: 18, colors: [\"#E8505B\", \"#F2726F\", \"#F79A5A\", \"#FBBF4A\", \"#FFE3A3\"] },\n { id: \"desert\", label: \"Desert\", hue: 36, colors: [\"#A4492C\", \"#C8683E\", \"#D9905E\", \"#E7B98A\", \"#F6E3C4\"] },\n { id: \"forest\", label: \"Forest\", hue: 100, colors: [\"#2F5D34\", \"#4C7D3A\", \"#6FA046\", \"#9CC25E\", \"#D5EBA4\"] },\n { id: \"lagoon\", label: \"Lagoon\", hue: 172, colors: [\"#0B6E73\", \"#0E9594\", \"#1FBFB2\", \"#56DCCB\", \"#B8F4EA\"] },\n { id: \"ocean\", label: \"Ocean\", hue: 205, colors: [\"#15457E\", \"#1C6BA8\", \"#2B93CF\", \"#5DBBE8\", \"#BFE6FA\"] },\n { id: \"dusk\", label: \"Dusk\", hue: 268, colors: [\"#2E2A7A\", \"#5B3E9E\", \"#8C4FB0\", \"#C8649E\", \"#F4A7B9\"] },\n { id: \"blossom\", label: \"Blossom\", hue: 330, colors: [\"#A3245B\", \"#CF3F78\", \"#E8699A\", \"#F49BB8\", \"#FFD6E0\"] },\n]\n\nexport const ORB_PALETTE_IDS = ORB_PALETTES.map((p) => p.id) as [string, ...string[]]\n\n/** #RRGGBB to its hue in degrees, or null when it is grey or not a colour. */\nfunction hueOf(hex: string): number | null {\n const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex)\n if (!m) return null\n const [r, g, b] = m.slice(1).map((x) => parseInt(x, 16) / 255)\n const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min\n if (d < 0.04) return null\n const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4\n return (h * 60 + 360) % 360\n}\n\n/** The palette nearest an agent colour by hue. Grey or invalid: lagoon. */\nexport function paletteForColor(hex: string): OrbPalette {\n const hue = hueOf(hex)\n if (hue === null) return ORB_PALETTES.find((p) => p.id === \"lagoon\")!\n let best = ORB_PALETTES[0], bestDistance = 360\n for (const p of ORB_PALETTES) {\n const d = Math.abs(p.hue - hue)\n const distance = Math.min(d, 360 - d)\n if (distance < bestDistance) { best = p; bestDistance = distance }\n }\n return best\n}\n\n/** An agent's palette: the one it chose (presence.palette), else the one\n * nearest its colour (presenceLook's). `set` says which. */\nexport function agentPalette(chosen: string | undefined, color: string): OrbPalette & { set: boolean } {\n const picked = ORB_PALETTES.find((p) => p.id === chosen)\n return picked ? { ...picked, set: true } : { ...paletteForColor(color), set: false }\n}\n","import { z } from \"zod\"\n\n// --- WhatsApp inbound triage settings (agentx.json → whatsappTriage) ---\n//\n// wacli posts each new WhatsApp message to POST /webhook/wacli. A watch\n// rule picks the messages an agent should look at; everything else is\n// dropped without being stored. Nothing is ever sent to the contact\n// unless the owner approves it (see drafts.ts).\n\nconst hhmm = z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/, \"use HH:MM, 24-hour\")\n\nexport const watchRuleSchema = z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, \"lowercase letters, digits, - and _\"),\n enabled: z.boolean().default(true),\n /** Chats to watch: a contact's or a group's JID, or a phone number. */\n chats: z.array(z.string().min(1)).default([]),\n /** Only messages from these people (JID or phone number), in any chat\n * the rule covers. Empty: anyone. */\n senders: z.array(z.string().min(1)).default([]),\n /** The agent that triages the messages. */\n agent: z.string().min(1),\n /** Extra instructions for the agent: who this contact is, where issues\n * go, the tone of a reply. */\n prompt: z.string().max(4000).optional(),\n /** No notifications between these times. Triage and drafts still happen. */\n quietHours: z.object({ start: hhmm, end: hhmm }).optional(),\n /** Send the agent's short acknowledgement without asking. Needs\n * whatsappTriage.allowAutoAck too. */\n autoAck: z.boolean().default(false),\n}).refine((r) => r.chats.length > 0 || r.senders.length > 0, {\n message: \"a rule needs at least one chat or sender\",\n})\n\nexport const whatsappTriageSchema = z.object({\n enabled: z.boolean().default(false),\n /** Environment variable holding the webhook secret given to\n * `wacli sync --webhook-secret`. Unsigned requests are refused. */\n secretEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default(\"WACLI_WEBHOOK_SECRET\"),\n /** Messages from one chat within this many seconds become one task. */\n batchSeconds: z.number().int().min(0).max(600).default(20),\n /** Time zone for quiet hours. Default: this computer's. */\n timezone: z.string().optional(),\n /** Second switch for rules with autoAck. Both must be on. */\n allowAutoAck: z.boolean().default(false),\n /** Download images and voice notes so the agent can read or hear them. */\n describeMedia: z.boolean().default(true),\n wacli: z.object({\n bin: z.string().default(\"wacli\"),\n /** `wacli --account NAME`, when more than one is paired. */\n account: z.string().optional(),\n /** `wacli --store DIR`. */\n store: z.string().optional(),\n }).default({}),\n rules: z.array(watchRuleSchema).default([]),\n}).default({})\n\nexport type WatchRule = z.infer<typeof watchRuleSchema>\nexport type WhatsappTriageConfig = z.infer<typeof whatsappTriageSchema>\nexport type WacliSettings = WhatsappTriageConfig[\"wacli\"]\n","import { z } from \"zod\"\nimport { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { businessConfigSchema } from \"@/business/config\"\nimport { boardsConfigSchema, dashboardConfigSchema } from \"@/boards/config\"\nimport { autonomyLevelSchema } from \"@/guard/autonomy\"\nimport { DEFAULT_HOTKEYS, hotkeyError } from \"@/voice/hotkey\"\nimport { ORB_PALETTE_IDS } from \"@/voice/orb-palettes\"\nimport { whatsappTriageSchema } from \"@/whatsapp-triage/config\"\n\n/**\n * Load .env file into process.env (simple, no dependency).\n */\nfunction loadDotEnv(dir: string): void {\n const envPath = resolve(dir, \".env\")\n if (!existsSync(envPath)) return\n\n const content = readFileSync(envPath, \"utf-8\")\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const eqIdx = trimmed.indexOf(\"=\")\n if (eqIdx === -1) continue\n const key = trimmed.slice(0, eqIdx).trim()\n const value = trimmed.slice(eqIdx + 1).trim()\n if (!process.env[key]) {\n process.env[key] = value\n }\n }\n}\n\n// --- Daemon configuration schema & loader ---\n\nconst providerConfigSchema = z.object({\n apiKey: z.string().optional(),\n defaultModel: z.string().optional(),\n baseUrl: z.string().optional(),\n /** Toggle thinking-mode output on backends that support it (DeepSeek\n * V4 `reasoning_content`). When `true` (the DeepSeek default), the\n * agent streams its reasoning live in the dashboard task modal and\n * the agentic round-trip echoes it back on the next iteration. Set\n * to `false` to disable for cost/latency-sensitive agents. Ignored\n * on backends that don't speak the thinking-mode protocol. */\n thinking: z.boolean().optional(),\n})\n\nconst mcpStdioServerSchema = z.object({\n type: z.literal(\"stdio\").optional(),\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: z.record(z.string(), z.string()).optional(),\n})\n\nconst mcpHttpServerSchema = z.object({\n type: z.literal(\"http\"),\n url: z.string().url(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\n// HTTP variant first so a record with `type: \"http\"` matches the HTTP\n// shape; stdio is the default fallback when `type` is absent (keeps the\n// original `{ command, args, env }` configs valid without a migration).\nconst mcpServerSchema = z.union([mcpHttpServerSchema, mcpStdioServerSchema])\n\n/**\n * Per-agent integration registration. Declares which third-party services\n * an agent has credentials for — e.g. \"@cx-bot has a Telegram bot token,\n * a HubSpot private app token, and a Gmail account\". The actual secret is\n * NEVER stored in agentx.json: only an env-var reference (`tokenEnv`) or a\n * keyring directive. Skills, channel adapters, and the action layer read\n * from this registry to discover what an agent can use.\n *\n * The `kind` field is open-string (well-known values listed below in\n * INTEGRATION_KINDS) so new services can be declared without a schema\n * bump. Doctor warns on unknown kinds.\n */\nconst integrationCredentialsSchema = z.object({\n /** Env var holding the secret. Uppercase identifier; daemon resolves at use-time. */\n tokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n /** Alternate env-var keys for credential schemes that need >1 secret\n * (e.g. HubSpot private app + portal id, OAuth refresh tokens). */\n privateAppTokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n apiKeyEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n refreshTokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n clientIdEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n clientSecretEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n /** OS keyring directive — credential lives in macOS Keychain / Linux\n * Secret Service / Windows Credential Manager. The skill that reads\n * this integration is responsible for resolving the keyring entry\n * (typically keyed by agentId+kind). */\n auth: z.literal(\"keyring\").optional(),\n /** File-based session directory (WhatsApp, Telegram MTProto, etc.). */\n sessionDir: z.string().optional(),\n}).strict()\n\nconst integrationSchema = z.object({\n /** Service identifier — open string, well-known values in INTEGRATION_KINDS. */\n kind: z.string().min(1),\n /** Human-readable label (e.g. \"@cx_bot\", \"Acme CRM\", \"alex@example.com\"). Unique per (agent, kind). */\n label: z.string().min(1),\n credentials: integrationCredentialsSchema.default({}),\n /** Non-secret metadata — username, email, host URL, portal id, JID, etc.\n * Visible in the dashboard and to skills. */\n metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),\n /** Operator-set toggle without removing the entry. */\n enabled: z.boolean().default(true),\n})\n\nexport type Integration = z.infer<typeof integrationSchema>\n\n/**\n * Canonical kind list — for autocomplete + doctor validation. Open string\n * schema so new services drop in without a bump; doctor warns when a kind\n * is outside this list.\n */\nexport const INTEGRATION_KINDS = [\n // Inbound channels\n \"telegram-bot\",\n \"whatsapp\",\n // Code platforms (user-scoped tokens, not channel routing)\n \"gitlab-user\",\n \"github-user\",\n // Email\n \"gmail\",\n \"hotmail\",\n \"smtp\",\n // CRM / ERP\n \"hubspot\",\n \"salesforce\",\n \"pipedrive\",\n \"odoo\",\n // Project management\n \"trello\",\n \"linear\",\n \"asana\",\n \"jira\",\n \"notion\",\n // Payments\n \"stripe\",\n // Observability / hosting\n \"sentry\",\n \"vercel\",\n // Voice / SMS\n \"twilio\",\n // Catch-all\n \"custom\",\n] as const\n\nconst voiceProviderSchema = z.enum([\"system\", \"elevenlabs\"])\n\n/** A macOS voice: a name (\"Daniel\", \"Ava (Premium)\") or identifier;\n * \"system\" for the OS default voice (the only way to get a Siri voice);\n * or one per language, picked by the language of each line:\n * { \"en\": \"Samantha\", \"fr\": \"Thomas\", \"ar\": \"Majed\" }. */\nconst systemVoiceSchema = z.union([z.string(), z.record(z.string(), z.string())])\n\n/** A keyboard shortcut for AgentX Voice, e.g. \"opt+space\" or\n * \"ctrl+opt+1\". See src/voice/hotkey.ts. */\nconst hotkeySchema = z.string().superRefine((s, ctx) => {\n const error = hotkeyError(s)\n if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `shortcut ${error}` })\n})\n\nconst voiceSchema = z.object({\n /** Overrides the global voice.provider for this agent. */\n provider: voiceProviderSchema.optional(),\n /** See systemVoiceSchema. Unset: one is assigned, of the agent's\n * gender when set, different from every other agent's. */\n system: systemVoiceSchema.optional(),\n /** Voices to try, in order, when `system` names one that is not\n * installed (e.g. [\"Ava (Premium)\", \"Allison\"]). Unset, or none\n * installed: the best installed voice of its language and gender. */\n fallbacks: z.array(z.string().min(1)).optional(),\n elevenlabsVoiceId: z.string().optional(),\n gender: z.enum([\"female\", \"male\", \"neutral\"]).optional(),\n /** A few words on manner, e.g. \"warm, upbeat, a little playful\". */\n style: z.string().optional(),\n /** The one-line self-introduction used on first contact. */\n intro: z.string().optional(),\n /** Speak short updates from this agent's real tool steps while it\n * works: \"on\" for everything but cron, \"all\" to include cron. */\n narrate: z.enum([\"off\", \"on\", \"all\"]).optional(),\n /** Speaking speed, 1 = normal. System voices: 175 words a minute times\n * this. ElevenLabs accepts 0.7 to 1.2 and is held to that range. */\n rate: z.number().min(0.75).max(1.5).optional(),\n /** Place in the speaking queue: \"high\" lines go ahead of waiting\n * \"normal\" ones, \"low\" lines after them. Unset: normal. */\n priority: z.enum([\"high\", \"normal\", \"low\"]).optional(),\n /** AgentX Voice: hold this shortcut and speak to ask this agent, without\n * changing the agent picked in the menu. */\n hotkey: hotkeySchema.optional(),\n})\n\n/** One event subscription (src/events/subscriptions.ts). An envelope\n * matches when its kind or type is in `kinds` and every other set filter\n * agrees. Every subscription is readable with `agentx_events`; `digest`\n * also briefs a fresh session and `wake` also starts a turn. */\nexport const eventSubscriptionSchema = z.object({\n /** Envelope `kind` (\"agent\", \"run\") or `type` (\"task:completed\"); \"*\" matches all. */\n kinds: z.array(z.string().min(1)).min(1),\n /** Only events published for these agent ids. */\n agents: z.array(z.string().min(1)).optional(),\n /** Only events published by these nodes (`node.name`). */\n nodes: z.array(z.string().min(1)).optional(),\n /** Only events whose summary contains this text (case-insensitive). */\n match: z.string().min(1).optional(),\n delivery: z.enum([\"pull\", \"digest\", \"wake\"]).default(\"pull\"),\n /** wake only: no wake when the agent was already woken this many times\n * in the past hour. */\n maxPerHour: z.number().int().min(1).max(60).default(4),\n})\n\nconst agentConfigSchema = z.object({\n name: z.string(),\n workspace: z.string(),\n tier: z.enum([\"claude-code\", \"codex-cli\", \"opencode\", \"sdk\", \"orchestrator\"]).default(\"claude-code\"),\n provider: z.string().optional(),\n model: z.string().optional(),\n systemPrompt: z.string().optional(),\n mentions: z.array(z.string()).default([]),\n /** Phase 5 — typed capabilities (drop-condition fallback). Free-form\n * list of intent strings this agent is allowed to handle. When set,\n * the org-chart `canHandle(agentId, project, intent)` check rejects\n * dispatches with intents not in this list. When empty/unset\n * (the default), the agent is permissive — handles any intent.\n * Intent matching is exact-string for now; a glob/prefix layer can\n * come later if it produces real rejections.\n * Example: [\"issue.opened\", \"issue.commented\", \"merge_request.opened\"]\n * Example: [\"cron.fired\", \"message.received\"] */\n intents: z.array(z.string()).default([]),\n /** Phase 8 — capability-bounded security. Max distinct upstream\n * agents in the delegation chain on the same (project, subject)\n * before a dispatch to THIS agent is refused. The ledger itself\n * provides the chain — `decideAndCommit` walks recent decisions on\n * the subject and counts distinct agents. Default 5; set to 0 to\n * disable for an agent that's always called as the bottom of a\n * chain. The check prevents cascade loops where A → B → A → B → ...\n * blows past sane chain depth. */\n maxDelegationDepth: z.number().int().min(0).max(50).default(5),\n /** MCP servers this agent's Claude Code session should load. Synced\n * to <workspace>/.mcp.json at daemon boot via agent-mcp.ts. Operator\n * edits to .mcp.json are respected (see SyncResult.skipped-operator-owned). */\n mcp: z.record(z.string(), mcpServerSchema).optional(),\n /** Enable CodeGraph (https://github.com/colbymchenry/codegraph) for this\n * agent's claude-code or codex-cli workspace. When true, agentx (a) adds\n * a codegraph MCP server to <workspace>/.mcp.json, (b) extends\n * .claude/settings.json permissions.allow with the codegraph_* tools,\n * (c) appends a CodeGraph instruction section to the managed CLAUDE.md,\n * and (d) background-indexes the workspace at daemon boot if .codegraph/\n * is missing. Off by default — flip on for coding agents (globex-v2-coder,\n * initech-v2-coder, umbrella-coding, etc.) where token-volume on exploration\n * loops is the bottleneck. */\n codegraph: z.boolean().default(false),\n /** Per-agent override for the global `session.contextStrategy`. Lets\n * one agent run `planner` (smaller upfront context, more tool-driven\n * exploration) while siblings stay on `layered`. Used for agents that\n * consistently bloat their cache via large workspace reads. */\n contextStrategy: z.enum([\"layered\", \"planner\"]).optional(),\n /** When true, the registry resolves references-recipes for this agent's\n * workspace and renders a deterministic [Verified References] block at\n * priority 4.7. Off by default — flip on per agent (pm-initech, devops-agent,\n * etc.) once a `references/` registry exists in the agent's workspace\n * or repo root. See src/agents/references/. */\n contextReferences: z.boolean().default(false),\n /** Whether this agent may emit in-band `agentx:ui` rich-message directives\n * (buttons/polls/media) on chat channels. Default true — set false to make\n * the render layer strip any directive and send plain text only. */\n richMessages: z.boolean().default(true),\n maxConcurrent: z.number().default(1),\n /** Hard wall-clock cap on a single Claude Code invocation. Exceeding the\n * cap sends SIGTERM (exit 143). Default 20 min — bump for devops/coder\n * agents that do long investigations or multi-file refactors. */\n maxExecutionMinutes: z.number().int().min(1).max(240).default(20),\n /** Time a run may spend between taking a slot and starting its agent\n * process (request gate, classifier, compaction, context planning, model\n * routing, dispatch gates). Past it the run is aborted, its slot freed and\n * its record marked `timeout` with the step it was stuck in. Applies to\n * every run, whatever started it. */\n preSpawnTimeoutSec: z.number().int().min(10).max(3600).default(300),\n /** How long a daemon stop waits for this agent's runs before cutting\n * them off, when that is longer than shutdown.drainTimeoutSeconds. For\n * agents whose runs are long (renders, builds). */\n drainTimeoutSeconds: z.number().int().min(0).max(86_400).optional(),\n permissionMode: z.string().default(\"default\"),\n /** How this agent's `claude` CLI is billed (claude-code tier). Default\n * \"subscription\": the shared OAuth login, ANTHROPIC_API_KEY stripped.\n * \"api\": bill ANTHROPIC_API_KEY instead and drop the OAuth token, so\n * e.g. benchmark agents never draw on the fleet's subscription quota.\n * An \"api\" agent with no key fails its task rather than falling back. */\n billing: z.enum([\"subscription\", \"api\"]).default(\"subscription\"),\n /** Improvement plan #3 — tool-use-required preset. When set,\n * AgentX inspects the stream-json events from each task and\n * fails the response with `tool_required_not_called: <name>`\n * when none of the listed tool names was invoked. Catches the\n * silent-degrade pattern observed when a model below the\n * capability bar (e.g. Haiku on a Write-required prompt)\n * produces a plausible-looking text response without ever\n * calling the required tool. Caller can retry with a stronger\n * model or sharpen the prompt.\n *\n * Tool names match the canonical Claude Code names (\"Write\",\n * \"Edit\", \"Bash\", \"Read\", …). Free-form so future tools work\n * without a schema bump. Empty/unset means no enforcement\n * (default — backward compatible). */\n toolUseRequired: z.array(z.string()).default([]),\n /** Per-agent override for the channel-level `autoReplyLegacy` on\n * gitlab/github. When set, it wins over `channels.<name>.autoReplyLegacy`\n * for this agent's replies: `true` makes the daemon auto-post the agent's\n * final text as a comment (right for coder agents that end their turn with\n * a summary and don't call `agentx_channel_reply`); `false` suppresses it\n * (right for chatty agents whose reasoning shouldn't land as a comment).\n * Unset → fall back to the channel default. */\n gitlabAutoReply: z.boolean().optional(),\n /** Opt into process reuse for claude-code (stream-json) or codex-cli\n * (app-server), or opencode (dedicated v2 server). Conversations have isolated processes. Unsupported Codex\n * versions fall back to exec before submitting any turn. Other tiers\n * ignore this flag. Codex loads the operator's Codex config, unlike exec's\n * --ignore-user-config path: review additional MCP servers before enabling.\n * Codex and OpenCode each use an 8-process cap and 5-minute idle eviction; processPool\n * settings apply to Claude only. Default false for gradual rollout.\n * See docs/architecture/persistent-codex-process.md and\n * docs/architecture/persistent-claude-process.md and\n * docs/architecture/persistent-opencode-process.md for details. */\n persistentProcess: z.boolean().default(false),\n queueMode: z.enum([\"collect\", \"followup\", \"drop\"]).default(\"collect\"),\n heartbeat: z.object({\n enabled: z.boolean().default(false),\n intervalMinutes: z.number().default(30),\n prompt: z.string().default(\"Check inbox, pending tasks, and system health. Report anything that needs attention.\"),\n channel: z.string().default(\"heartbeat\"),\n }).default({}),\n /** Reachability via the external public API.\n * - \"private\" (default): this agent is daemon-internal + channel-bound only.\n * - \"public\": external apps can POST /api/public/agents/<id>/messages\n * with a scoped token (agent:<id> or agent:*). */\n access: z.enum([\"private\", \"public\"]).default(\"private\"),\n /** Governance override for agent-facing management tools. An admin agent\n * may pause, resume and request deletion of schedules created by other\n * agents or by the operator. It never approves anything: approval of a\n * create/delete request stays operator-only (`agentx schedule approve`). */\n admin: z.boolean().optional(),\n /** Events on the bus this agent wants to hear about (issue #165). */\n subscriptions: z.array(eventSubscriptionSchema).default([]),\n /** Per-agent third-party integrations registry. Declares which services\n * this agent has credentials for (telegram-bot, hubspot, gitlab-user,\n * gmail, etc.). Secrets stay in env vars / keyring; this block holds\n * declarations + non-secret metadata only. Skills and channel adapters\n * read from here to know what the agent can use. See INTEGRATION_KINDS. */\n integrations: z.array(integrationSchema).default([]),\n /** How this agent sounds when it speaks (voice widget, `agentx teach`).\n * Every field is optional: no voice id falls back to the global\n * AGENTX_VOICE_ID, no intro is derived from the system prompt. See\n * src/voice/agent-voice.ts. */\n voice: voiceSchema.optional(),\n /** How this agent appears on screen: its own cursor, drawn by the Mac\n * helper and click-through, never the person's real mouse. See\n * src/voice/presence.ts. */\n presence: z.object({\n /** Cursor colour, as #RRGGBB. Default: derived from the agent id. */\n color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),\n /** The voice orb's gradient, one of src/voice/orb-palettes.ts.\n * Default: the palette nearest `color`. */\n palette: z.enum(ORB_PALETTE_IDS).optional(),\n /** One or two letters on the cursor. Default: from the name. */\n initial: z.string().max(2).optional(),\n /** Name shown under the cursor. Default: the agent's name. */\n label: z.string().optional(),\n /** May this agent click and type for the person (presence mode \"act\")?\n * Off by default: without it, \"act\" becomes \"teach\". */\n allowActions: z.boolean().optional(),\n }).optional(),\n})\n\nconst telegramAccountSchema = z.object({\n token: z.string(),\n agentBinding: z.string(),\n /** Per-account sender allowlist. When set, OVERRIDES the global\n * `policy.allowFrom`. Entries accept:\n * - numeric user id (\"1816212449\") — matches sender (from.id)\n * - numeric chat id (\"-1003861455814\") — matches chat (chat.id)\n * - \"@username\" — matches sender username\n * A message is dispatched iff at least one entry matches. */\n allowFrom: z.array(z.string()).optional(),\n /** When false, the daemon keeps the bot token registered so outbound\n * `send()` / ring notifications work, but does NOT long-poll for inbound\n * updates. Use this on nodes where the bound agent lives on a different\n * daemon — otherwise two daemons race on the same `getUpdates` cursor and\n * Telegram responds 409 Conflict on every poll.\n * Defaults to true (poll) so existing single-node setups are unchanged. */\n pollInbound: z.boolean().default(true),\n})\n\n/** An agent watching the phone camera (#325 phase 2, src/camera/watch.ts). */\nexport const cameraBotSchema = z.object({\n /** Seconds between frames the agent gets by itself. 0: only when asked\n * (\"Look now\" on the phone, or the agent's own `agentx camera look`).\n * Each frame handed over by itself is a turn of the agent, so keep\n * this high or off. */\n frameIntervalSeconds: z.number().int().min(0).max(3600).default(0),\n /** The agent's watch ends after this many minutes, whatever the phone does. */\n maxSessionMinutes: z.number().int().min(1).max(240).default(10),\n /** Frames are shrunk so their longer side is at most this many pixels\n * before the agent sees them. */\n maxFrameEdge: z.number().int().min(160).max(3840).default(1024),\n /** Keep the frame files in the agent's workspace after the share ends.\n * Off: every frame is deleted when the share ends. */\n keepFrames: z.boolean().default(false),\n}).default({})\n\nexport type CameraBotConfig = z.infer<typeof cameraBotSchema>\n\nconst channelsConfigSchema = z.object({\n telegram: z.object({\n enabled: z.boolean().default(false),\n accounts: z.record(z.string(), telegramAccountSchema).default({}),\n policy: z.object({\n dm: z.enum([\"pair\", \"block\"]).default(\"pair\"),\n group: z.enum([\"mention-required\", \"all\"]).default(\"mention-required\"),\n /** Global sender allowlist applied to every account that doesn't set\n * its own `allowFrom`. When neither is configured, every incoming\n * message is dropped — closed by default. Same entry forms as the\n * per-account list (user id, chat id, @username). */\n allowFrom: z.array(z.string()).optional(),\n }).default({}),\n }).default({}),\n whatsapp: z.object({\n enabled: z.boolean().default(false),\n sessionDir: z.string().default(\".agentx/whatsapp-sessions\"),\n defaultAgent: z.string().optional(),\n allowFrom: z.array(z.string()).optional(),\n routes: z.array(z.object({\n contact: z.string().optional(),\n group: z.string().optional(),\n agent: z.string(),\n })).default([]),\n /** Data-source ingestion — turns WhatsApp from a messaging-only channel\n * into a source that seeds the wiki with contact/group metadata (and\n * optionally bounded message windows) per an explicit allowlist.\n * Default-deny: `enabled: false` and empty allowlists mean nothing is\n * ingested. See docs/reference/whatsapp-ingest.md for the full story. */\n ingest: z.object({\n enabled: z.boolean().default(false),\n /** `metadata-only` pulls contact/group info; `messages` additionally\n * pulls the last `messageCap` messages per allowlisted chat. */\n mode: z.enum([\"metadata-only\", \"messages\"]).default(\"metadata-only\"),\n /** Phone numbers or JIDs. Substring match, same semantics as allowFrom. */\n allowContacts: z.array(z.string()).default([]),\n allowGroups: z.array(z.string()).default([]),\n denyContacts: z.array(z.string()).default([]),\n denyGroups: z.array(z.string()).default([]),\n /** Per-chat cap when mode = \"messages\". Keeps the raw-entry size bounded. */\n messageCap: z.number().int().min(1).max(500).default(50),\n /** Max age (days) of messages to consider for the bounded window. */\n historyDays: z.number().int().min(1).max(365).default(30),\n /** Skip re-writing a contact entry unless this many days have passed\n * OR the profile hash differs. Prevents churn on unchanged profiles. */\n contactRefreshDays: z.number().int().min(1).max(90).default(7),\n /** Safety rails on live Baileys reads — personal-account accounts\n * can get throttled/banned under burst reads. */\n throttle: z.object({\n minMsBetweenCalls: z.number().int().min(100).default(1500),\n maxCallsPerMinute: z.number().int().min(1).default(20),\n maxChatsPerSweep: z.number().int().min(1).default(25),\n }).default({}),\n /** Purge absorbed raw entries older than this many days. `0` = never. */\n retentionDays: z.number().int().min(0).default(0),\n }).default({}),\n }).default({}),\n gitlab: z.object({\n enabled: z.boolean().default(false),\n webhookPort: z.number().default(18810),\n webhookSecret: z.string().optional(),\n host: z.string().default(\"https://gitlab.com\"),\n token: z.string().optional(),\n /** Legacy auto-reply: when true (default), the router posts the agent's\n * `response.content` as a comment automatically. When false, the agent\n * must call the `channel.reply` action explicitly to reply — agent\n * reasoning text is logged but not posted. Flip to false once the\n * project's agents have migrated their gitlab skill to use channel.reply.\n * Default true preserves today's behaviour for unmigrated projects. */\n autoReplyLegacy: z.boolean().default(true),\n routes: z.array(z.object({\n project: z.string(),\n agent: z.string(),\n })).default([]),\n agentMappings: z.array(z.object({\n agentId: z.string(),\n gitlabUsernames: z.array(z.string()).default([]),\n keywords: z.array(z.string()).default([]),\n token: z.string().optional(),\n /** If set, the agent lives on a remote mesh peer (node id). Forces the\n * username→agent map to resolve to this mapping even when a local\n * agent's token resolves to the same GitLab user — prevents collisions\n * like two agents both claiming @devops-acme. */\n node: z.string().optional(),\n })).default([]),\n /** Extra GitLab usernames each agent answers to, as prefixes. With\n * [\"team-\"], an agent with no agentMappings row answers to @<id> and\n * @team-<id>. Default: only @<id>. */\n agentUsernamePrefixes: z.array(z.string().min(1)).default([]),\n }).default({}),\n github: z.object({\n enabled: z.boolean().default(false),\n /** Legacy auto-reply — same semantics as gitlab.autoReplyLegacy.\n * Defaults true; set false once agent skills use channel.reply. */\n autoReplyLegacy: z.boolean().default(true),\n /** GitHub PAT or env var (${GITHUB_TOKEN}) for posting comments back. */\n token: z.string().optional(),\n /** Path to file containing the token (first line read at startup). */\n tokenFile: z.string().optional(),\n /** GitHub App ID (legacy issuer). */\n appId: z.number().optional(),\n /** GitHub App Client ID (preferred JWT issuer per GitHub's updated docs). */\n clientId: z.string().optional(),\n /** Path to the GitHub App private key PEM file. */\n privateKeyFile: z.string().optional(),\n /** Webhook secret for validating X-Hub-Signature-256. */\n webhookSecret: z.string().optional(),\n /** Repo → agent routing. Use \"owner/repo\" or \"*\" for default. */\n routes: z.array(z.object({\n repo: z.string(),\n agent: z.string(),\n })).default([]),\n /** Per-agent identity mappings (GitHub usernames, tokens, mesh nodes). */\n agentMappings: z.array(z.object({\n agentId: z.string(),\n githubUsernames: z.array(z.string()).default([]),\n token: z.string().optional(),\n tokenFile: z.string().optional(),\n node: z.string().optional(),\n })).default([]),\n }).default({}),\n /** ntfy push notifications — outbound only. The operator-facing tap on\n * the shoulder: cron failures, task errors, and anything an agent decides\n * is worth interrupting a human for. `chatId` on an outgoing message is\n * the topic; empty falls back to `topic` here. */\n ntfy: z.object({\n enabled: z.boolean().default(false),\n /** Self-hosted ntfy base URL. Defaults to the public server. */\n server: z.string().default(\"https://ntfy.sh\"),\n /** Default topic. Treat it as a secret — on ntfy.sh, knowing the topic\n * is the only thing needed to read or publish to it. */\n topic: z.string().optional(),\n /** Access token for protected topics. */\n token: z.string().optional(),\n /** 1 (min) .. 5 (max). ntfy's own default is 3. */\n defaultPriority: z.number().int().min(1).max(5).default(3),\n defaultTitle: z.string().optional(),\n }).default({}),\n /** Web Push to the phone app (/app) — outbound only. The node that hosts\n * the app holds the subscriptions and sends; any other node sets\n * `relayTo` and forwards over the mesh. `chatId` \"default\" means every\n * subscribed phone, or a device id (tok_…) for one. */\n push: z.object({\n enabled: z.boolean().default(false),\n /** VAPID key pair written by `agentx app push-keys`. Relative paths\n * resolve from the folder AgentX runs in (the one holding agentx.json). */\n keysFile: z.string().default(\".agentx/push-keys.json\"),\n /** Contact for the push services: `mailto:you@example.com` or an\n * https:// URL. Required on the hosting node. */\n subject: z.string().regex(/^(mailto:|https:\\/\\/)/, \"must start with mailto: or https://\").optional(),\n /** Mesh peer (id or name) that hosts the phone app. Set it on every\n * other node; leave it unset on the host. */\n relayTo: z.string().optional(),\n /** How long a push service keeps trying an offline phone. */\n ttlSeconds: z.number().int().min(0).max(2419200).default(86400),\n /** Recent pushes kept for the app's Alerts tab. */\n keepRecent: z.number().int().min(0).max(1000).default(50),\n /** Push-service hosts a phone may subscribe with (a host or any\n * subdomain of it). The daemon POSTs to the stored address, so anything\n * else is refused. Defaults cover Chrome/Android, Firefox, Safari/iOS\n * and Edge. */\n allowedHosts: z.array(z.string().min(1)).default([\n \"fcm.googleapis.com\", \"push.services.mozilla.com\", \"push.apple.com\", \"notify.windows.com\",\n ]),\n }).default({}),\n webrtc: z.object({\n enabled: z.boolean().default(false),\n /** ICE STUN servers for NAT discovery. Default is Google's public STUN. */\n stunServers: z.array(z.string()).default([\"stun:stun.l.google.com:19302\"]),\n /** Optional TURN relays (required when both peers are behind symmetric NAT). */\n turnServers: z.array(z.object({\n urls: z.string(),\n username: z.string().optional(),\n credential: z.string().optional(),\n })).default([]),\n /** Peer names permitted to *initiate* a call into this daemon. Empty = allow all mesh peers. */\n allowedCallers: z.array(z.string()).default([]),\n /** Where to send \"someone is calling\" notifications when an inbound ring\n * arrives. Each entry is delivered via the matching channel adapter —\n * same plumbing as any other outbound message. Empty disables notifications. */\n ringNotify: z.array(z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n })).default([]),\n /** Base URL used when building the tap-to-join link in ring notifications.\n * Defaults to `http://<node.bind>` — override when the daemon's public\n * hostname differs (e.g. HTTPS-terminated tunnel, Tailscale MagicDNS). */\n callUrlBase: z.string().optional(),\n /** AI participant (\"bot\") joins calls when a browser opens with `?bot=<id>`.\n * v1 is transcribe-only — bot consumes remote audio, transcribes via\n * Whisper, posts chunks to the configured channel. No TTS-back. */\n bot: z.object({\n enabled: z.boolean().default(false),\n /** Default agent id used to attribute the transcript when the URL\n * doesn't override via `?bot=<other-agent>`. */\n defaultAgentId: z.string().optional(),\n /** \"auto\" tries mlx-whisper, falls back to OpenAI; explicit forces. */\n whisperBackend: z.enum([\"auto\", \"mlx\", \"openai\"]).default(\"auto\"),\n whisperModel: z.string().optional(),\n whisperLanguage: z.string().default(\"auto\"),\n /** Absolute path to mlx_whisper if not on the daemon's PATH (common\n * on macOS launchd, where ~/.pyenv/shims is missing from the env). */\n mlxBinary: z.string().optional(),\n /** Where to send each transcribed chunk. Same shape as ringNotify[]. */\n transcriptChannel: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Hard cap so a forgotten bot doesn't run forever. */\n maxCallMinutes: z.number().int().min(1).max(240).default(30),\n }).default({}),\n /** The phone app's Share camera (#325). The phone asks for this size and\n * rate; the browser picks the nearest the camera supports. The share\n * stops by itself after maxSeconds. */\n camera: z.object({\n width: z.number().int().min(160).max(3840).default(1280),\n height: z.number().int().min(120).max(2160).default(720),\n frameRate: z.number().int().min(1).max(60).default(15),\n maxSeconds: z.number().int().min(10).max(7200).default(600),\n /** An agent watching the phone camera. The bot keeps only the newest\n * frame; the agent gets one when asked, and every\n * frameIntervalSeconds when that is set. */\n bot: cameraBotSchema,\n }).default({}),\n }).default({}),\n})\n\nconst cronJobSchema = z.object({\n enabled: z.boolean().default(true),\n schedule: z.string(),\n timezone: z.string().default(\"UTC\"),\n agent: z.string(),\n prompt: z.string().default(\"\"),\n /**\n * A shell command to run INSTEAD of dispatching the agent.\n *\n * Seven of this fleet's twenty-six crons were a single command wrapped\n * in an agent, and every one of them carried a paragraph like \"Run this\n * EXACT command. Do NOT substitute, rewrite, shorten, or fall back to\n * alternative commands.\" That paragraph is a scar: it exists because\n * models kept substituting, and no amount of prompt severity makes a\n * language model a deterministic executor.\n *\n * Measured before this existed: ~$0.31 and ~24s per run to execute one\n * `node script.js` and repeat ten lines of its output — a 114k-token\n * context for a job with no judgement in it at all.\n *\n * When set, the scheduler runs the command directly. No model, no\n * tokens, no improvisation. `agent` is still required and is who gets\n * told when it fails.\n */\n command: z.string().optional(),\n timeout: z.number().default(600),\n model: z.string().optional(),\n /** Soft cap on output length. Claude Code CLI has no hard flag for this,\n * but appending an instruction to the prompt is reliably honored. Use\n * 1500 for briefs, 500 for status pings, 300 for pure classifiers. */\n maxOutputTokens: z.number().int().min(50).max(8000).optional(),\n /** How much this routine may do: `report` (read-only), `propose` (branch,\n * commit, MR/draft; never merge/deploy/delete) or `act` (the agent's full\n * permissions — the default). Enforced per run by the guard, not by the\n * prompt; only the claude-code tier can enforce it, others refuse. */\n autonomy: autonomyLevelSchema.optional(),\n onError: z.union([\n z.enum([\"log\", \"notify\", \"disable\"]),\n z.array(z.enum([\"log\", \"notify\", \"disable\"])),\n ]).default(\"log\").transform(v => Array.isArray(v) ? v : [v]),\n notify: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Secret that lets an external system fire this job now via\n * `POST /routines/<id>/fire`. Reference an env var (`\"${MY_TOKEN}\"`);\n * a job without one cannot be fired. See src/daemon/routine-fire.ts. */\n fireToken: z.string().optional(),\n /** Agent id that created this job through the agent `schedule` tool.\n * Absent for operator-created jobs. Drives the ownership rule: an agent\n * manages only the routines it created, unless it is `admin`. */\n createdBy: z.string().optional(),\n /** Pending operator approval for an agent-requested change. While a\n * `create` is pending the job never runs, whatever `enabled` says; a\n * pending `delete` leaves the job as it was until approved. Cleared by\n * `agentx schedule approve|reject <id>`. */\n approval: z.object({\n action: z.enum([\"create\", \"delete\"]),\n requestedBy: z.string(),\n requestedAt: z.string(),\n }).optional(),\n}).refine((j) => Boolean(j.command?.trim() || j.prompt?.trim()), {\n message: \"a cron needs either a prompt (dispatch an agent) or a command (run it directly)\",\n}).refine((j) => !(j.command?.trim() && j.autonomy && j.autonomy !== \"act\"), {\n message: \"autonomy applies to agent routines; a command cron runs no agent (remove autonomy or the command)\",\n})\n\nconst serviceSchema = z.object({\n name: z.string(),\n triggers: z.array(z.object({\n pattern: z.string(),\n channel: z.string().optional(),\n })),\n allowedContacts: z.array(z.string()).optional(),\n agent: z.string(),\n prompt: z.string(),\n schedule: z.string().optional(),\n timezone: z.string().default(\"UTC\"),\n notify: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n})\n\nconst meshPeerSchema = z.object({\n url: z.string(),\n name: z.string(),\n token: z.string().optional(),\n})\n\n/** A named, operator-declared destination that remote mesh nodes may send\n * to. Deliberately minimal: the published surface is the name and whether\n * it accepts, so there is nothing here that could leak local state if it\n * were echoed back. Which agent handles it stays private to this node. */\nconst meshInboxSchema = z.object({\n name: z.string(),\n agent: z.string(),\n enabled: z.boolean().default(true),\n})\n\nconst meshConfigSchema = z.object({\n enabled: z.boolean().default(false),\n peers: z.array(meshPeerSchema).default([]),\n /** Empty by default — a node publishes no inboxes until an operator\n * declares one, so this feature is opt-in per node. */\n inboxes: z.array(meshInboxSchema).default([]),\n discovery: z.enum([\"static\", \"mdns\"]).default(\"static\"),\n healthCheck: z.object({\n interval: z.number().default(60),\n timeout: z.number().default(10),\n }).default({}),\n /** Peer event feed (#166): follow each healthy peer's /events and merge\n * its own events into this node's bus. `skipTypes` are left out on the\n * peer's side; per-step agent activity is too chatty to cross the mesh. */\n feed: z.object({\n enabled: z.boolean().default(true),\n skipTypes: z.array(z.string().min(1)).default([\"task:step\"]),\n }).default({}),\n /** Agent-to-agent delegation (#277), local or across peers. When a person\n * started the conversation, a delegation returns at once and the answer\n * comes back to the asking agent as a new turn in the same chat. */\n delegation: z.object({\n /** Off: every delegation waits for its answer, as before. */\n asyncWhenHuman: z.boolean().default(true),\n /** A delegation with no answer after this long is reported as timed out. */\n timeoutMinutes: z.number().int().min(1).max(240).default(30),\n }).default({}),\n})\n\n/** Intent Knowledge Graph — fixed-axis, LLM-proposed taxonomy used by the\n * Intent layer in context.ts and (eventually) wiki retrieval. Off by default\n * so existing installs see no change. */\nconst graphConfigSchema = z.object({\n enabled: z.boolean().default(false),\n /** Where the schema/nodes/classifications live. Relative to cwd. */\n baseDir: z.string().default(\".agentx/graph\"),\n /** Which agent makes LLM classification proposals. Falls back to\n * `dashboard.draftAgent` at call sites if unset. */\n draftAgent: z.string().optional(),\n /** Agent used by `agentx graph review` to triage pending classifications.\n * Should be an agent with the wiki skill so it can call `wiki query` for\n * context before deciding approve/reject. Falls back to draftAgent. */\n reviewAgent: z.string().optional(),\n /** Structural auto-approval policy. Evaluated against each classification\n * independently of `autoApproveConfidence`; either triggers approval.\n * - \"strict\" : never approve via structure — every classification\n * waits for human review\n * - \"extend-leaves\" : auto-approve when the proposed path (a) reuses only\n * existing nodes, or (b) adds exactly one NEW node at\n * the deepest level. Structural changes (new mid-path\n * node, new root) still queue for review. Default.\n * - \"any\" : auto-approve every classification regardless of\n * structural change\n */\n autoApproveStructure: z.enum([\"strict\", \"extend-leaves\", \"any\"]).default(\"extend-leaves\"),\n /** Minimum classifier confidence (0..1) to auto-approve. OR'd with the\n * structural policy — either hitting the threshold lets the classification\n * bypass the pending queue. 1.0 (default) disables this knob, so approval\n * is driven by `autoApproveStructure` alone. Lower it to e.g. 0.7 if you\n * also want high-confidence structural changes auto-approved. */\n autoApproveConfidence: z.number().min(0).max(1).default(1.0),\n /** Anthropic model id used for the direct classifier call (Phase 2 of\n * classifier-retire). Default haiku — classification is metadata, not\n * work, so we use the cheapest fast model. Override only if Haiku is\n * rate-limited or you want to A/B test. */\n classifierModel: z.string().default(\"claude-haiku-4-5-20251001\"),\n /** Weights for the wiki hybrid retrieval score. Path-ancestry match vs\n * BM25 over article text. Sum need not be 1. */\n retrievalWeights: z.object({\n graph: z.number().min(0).default(0.6),\n bm25: z.number().min(0).default(0.4),\n }).default({}),\n}).default({})\n\n// --- Typed-decision seats (src/decisions) ---\n//\n// Everything here defaults off. A seat in \"shadow\" runs alongside the\n// incumbent and only records; \"active\" lets its answer steer behaviour, and\n// no seat should reach it before its calibration report says what threshold\n// to use and what that threshold costs.\nconst decisionSeatSchema = z.object({\n /** off: the seat is unreachable. shadow: runs and records, incumbent stays\n * authoritative. active: the answer is used. */\n mode: z.enum([\"off\", \"shadow\", \"active\"]).default(\"off\"),\n /** Backend name from the decisions registry. Per-seat, so one seat can be\n * graded against a different backend than another at the same time. */\n backend: z.string().optional(),\n model: z.string().optional(),\n timeoutMs: z.number().int().min(100).default(10_000),\n /** Post-hoc temperature fitted on this seat's own labeled rows. 1 means\n * \"not calibrated yet\", which is where every seat starts — see\n * `agentx decisions calibrate`. */\n temperature: z.number().min(0.01).default(1),\n /** Fraction of would-be-skips to run anyway. Not a tuning knob: a skipped\n * decision can never be graded, so without exploration an active seat's\n * metrics are computed on the biased sample it selected for itself.\n * Setting this to 0 in active mode means the calibration report stops\n * being trustworthy the day you promote the seat. */\n explore: z.number().min(0).max(1).default(0.15),\n /** Fraction of turns that bypass the seat as a randomized control group.\n * Unset lets the seat pick its own default; only seats that run an\n * experiment read it (today: request-gate, default 0.1). */\n holdout: z.number().min(0).max(1).optional(),\n}).default({})\n\nconst decisionsConfigSchema = z.object({\n enabled: z.boolean().default(false),\n dbPath: z.string().default(\".agentx/decisions/decisions.sqlite\"),\n /** State can contain message text. With this on, only the hash is kept,\n * which costs the ability to replay a decision offline. */\n redactState: z.boolean().default(false),\n /** Keep the serialized state for this many rows per seat, then prune to\n * hashes. Enough to replay and to grade an alternative backend on\n * identical inputs, without growing without bound. */\n keepStateRows: z.number().int().min(0).default(2000),\n defaultBackend: z.string().default(\"local\"),\n backends: z.object({\n local: z.object({\n provider: z.string().default(\"claude-code\"),\n model: z.string().default(\"claude-haiku-4-5-20251001\"),\n /** auto resolves to a forced tool where the provider guarantees one,\n * and JSON-in-text otherwise (claude-code on OAuth cannot force a\n * tool). Never resolves to logprobs: that costs one call per\n * question, so it has to be asked for. */\n structureMode: z.enum([\"auto\", \"tool\", \"text\"]).default(\"auto\"),\n normalizeProbabilities: z.boolean().default(true),\n nRetryMalformedStructure: z.number().int().min(0).max(3).default(1),\n maxStateChars: z.number().int().min(500).default(24_000),\n }).default({}),\n /** A simple-jev server (featherless-ai/simple-jev). Reads the model's\n * next-token logits rather than asking it to write a probability, so\n * the distribution is the model's posterior instead of a number it\n * chose. Still not calibrated to correctness — that comes from\n * `agentx decisions recalibrate`. */\n simpleJev: z.object({\n baseUrl: z.string().default(\"http://127.0.0.1:8000/v1\"),\n model: z.string().optional(),\n apiKeyEnv: z.string().optional(),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(6_000),\n /** Their Choice takes 2-50 candidates, well under Jev's 255. */\n maxChoiceOptions: z.number().int().min(2).max(255).default(50),\n }).default({}),\n /** TypeSafe Jev through OpenRouter's alpha decisions endpoint.\n * Verified live 2026-09-19 — resolves to typesafe/jev-1.13-20260917,\n * provider \"TypeSafe\", ~0.5s round trip. The id is \"jev-latest\";\n * the namespaced \"typesafe/jev-latest\" 400s, and neither appears in\n * OpenRouter's public model list. Needs OPENROUTER_API_KEY. */\n jev: z.object({\n baseUrl: z.string().default(\"https://openrouter.ai/api/alpha\"),\n path: z.string().default(\"/decisions\"),\n model: z.string().default(\"jev-latest\"),\n apiKeyEnv: z.string().default(\"OPENROUTER_API_KEY\"),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(90_000),\n maxChoiceOptions: z.number().int().min(2).max(255).default(255),\n }).default({}),\n /** Jev direct from TypeSafe rather than through OpenRouter. Same\n * contract, different billing and rate limits. Needs TYPESAFE_API_KEY. */\n typesafe: z.object({\n baseUrl: z.string().default(\"https://api.typesafe.ai/v1\"),\n path: z.string().default(\"/systemone\"),\n model: z.string().default(\"jev-latest\"),\n apiKeyEnv: z.string().default(\"TYPESAFE_API_KEY\"),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(90_000),\n maxChoiceOptions: z.number().int().min(2).max(255).default(255),\n }).default({}),\n }).default({}),\n seats: z.record(z.string(), decisionSeatSchema).default({}),\n /** Model routing driven by the task-tier seat. Models are scoped to their\n * CLI engine; the legacy cheapModel applies only to Claude Code. */\n routing: z.object({\n cheapModel: z.string().optional(),\n cheapModels: z.object({\n \"claude-code\": z.string().optional(),\n \"codex-cli\": z.string().optional(),\n }).optional(),\n }).default({}),\n}).default({})\n\n/** Agents ringing the owner for a live voice call (src/calls). */\nexport const callsSchema = z.object({\n /** Agents allowed to call: ids, or \"*\" for every agent on this node.\n * Empty: nobody can call until the owner allows it. */\n allow: z.array(z.string()).default([]),\n /** Most calls one agent may place in an hour. */\n maxPerHour: z.number().int().min(1).max(60).default(3),\n /** How long a call rings before it counts as missed. */\n ringSeconds: z.number().int().min(10).max(300).default(45),\n /** An answered call nobody hung up (widget quit or crashed, the Mac\n * slept, `agentx call answer` without a conversation) ends after this,\n * so the agent can call again. */\n maxCallMinutes: z.number().int().min(1).max(240).default(30),\n /** Ring sound: a name from /System/Library/Sounds, without the extension. */\n ringSound: z.string().regex(/^[\\w -]+$/).default(\"Submarine\"),\n /** After hang-up, ask the agent for a short summary and file it in the\n * dashboard's conversation history. */\n summary: z.boolean().default(true),\n}).default({})\n\nexport type CallsConfig = z.infer<typeof callsSchema>\n\nconst notificationsSchema = z.object({\n /** Send notification when task takes longer than this (seconds). 0 = disabled. */\n longTaskThreshold: z.number().default(30),\n /** Where to send notifications */\n destination: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Channel `agentx notify` and Focus digests use when none is given.\n * Unset: `push` (the phone app) when channels.push is enabled, else\n * `ntfy`, so upgrading never points notify at a channel that is off. */\n channel: z.string().optional(),\n /** Notify on these events */\n on: z.object({\n taskComplete: z.boolean().default(true),\n taskError: z.boolean().default(true),\n taskQueued: z.boolean().default(false),\n }).default({}),\n /** What `agentx notify` does on this machine when it delivers: a desktop\n * banner and a system sound. macOS only; see src/notify/local.ts. */\n local: z.object({\n banner: z.boolean().default(true),\n sound: z.boolean().default(true),\n /** A name from /System/Library/Sounds, without the extension. */\n soundName: z.string().regex(/^[\\w -]+$/).default(\"Glass\"),\n volume: z.number().min(0).max(1).default(0.4),\n /** Image for the AgentX Helper icon on banners (.png, .jpg, .icns).\n * Unset: the AgentX logo. Applied by `agentx desktop install`. */\n icon: z.string().optional(),\n }).default({}),\n}).default({})\n\nconst screenRectSchema = z.object({\n x: z.number(), y: z.number(), width: z.number().positive(), height: z.number().positive(),\n})\n\n/** Screen capture for agents: how captures are cropped and scaled, how\n * long they wait for the right moment, named regions, and the opt-in\n * in-memory buffer. See src/computer-use/capture.ts. */\nconst screenSchema = z.object({\n /** Pixel budget for a captured frame; larger captures are downscaled. */\n maxPixels: z.number().int().positive().default(1_200_000),\n /** Longest a capture waits for a change or for the screen to settle. */\n timeoutMs: z.number().int().positive().default(5_000),\n /** Time between samples while waiting. */\n intervalMs: z.number().int().positive().default(100),\n /** Mean difference (0–1) above which two samples count as different. */\n changeThreshold: z.number().min(0).max(1).default(0.015),\n /** How long a region must stay unchanged to count as stable. */\n stableMs: z.number().int().nonnegative().default(400),\n /** Named regions in screen points, e.g. { \"chat\": { x, y, width, height } }.\n * A name here overrides the built-in region of the same name. */\n regions: z.record(z.string().regex(/^[a-z][\\w-]*$/), screenRectSchema).default({}),\n /** The last few seconds of a region, kept in memory by the daemon. Off\n * unless enabled; frames are written out only when asked for. */\n buffer: z.object({\n enabled: z.boolean().default(false),\n seconds: z.number().positive().max(120).default(10),\n fps: z.number().positive().max(10).default(2),\n region: z.string().default(\"screen\"),\n maxPixels: z.number().int().positive().default(300_000),\n }).default({}),\n}).default({})\n\n/** The Approvals inbox (src/approvals). Decision cards agents raise, and\n * when the operator hears about what is waiting. */\nexport const approvalsConfigSchema = z.object({\n /** A card without an `expires` gets this many days. */\n defaultExpiryDays: z.number().positive().max(365).default(3),\n /** No card waits longer than this, whatever the agent asked for. */\n maxExpiryDays: z.number().positive().max(365).default(30),\n /** How long \"later\" hides an item. */\n laterHours: z.number().positive().max(24 * 30).default(24),\n /** Tell the agent that raised a card when it is decided or expires. */\n notifyAgent: z.boolean().default(true),\n /** At most one message a day: how many are waiting, and the most urgent. */\n digest: z.object({\n enabled: z.boolean().default(true),\n /** Local time, 24-hour HH:MM. */\n time: z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/, \"use HH:MM, 24-hour\").default(\"09:00\"),\n /** IANA timezone for `time`. Unset: this machine's. */\n timezone: z.string().refine((tz) => {\n try { new Intl.DateTimeFormat(\"en-US\", { timeZone: tz }); return true } catch { return false }\n }, \"unknown timezone\").optional(),\n /** Where it goes. Unset: notifications.destination. */\n destination: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n }).default({}),\n}).default({})\n\nexport const daemonConfigSchema = z.object({\n node: z.object({\n id: z.string(),\n name: z.string(),\n bind: z.string().default(\"127.0.0.1:18800\"),\n /** Default agent for voice/API calls that don't specify one (e.g. Siri) */\n defaultAgent: z.string().optional(),\n }),\n providers: z.record(z.string(), providerConfigSchema).default({}),\n agents: z.record(z.string(), agentConfigSchema).default({}),\n channels: channelsConfigSchema.default({}),\n crons: z.record(z.string(), cronJobSchema).default({}),\n services: z.record(z.string(), serviceSchema).default({}),\n notifications: notificationsSchema,\n calls: callsSchema,\n /** Watched WhatsApp chats triaged by an agent (src/whatsapp-triage). */\n whatsappTriage: whatsappTriageSchema,\n approvals: approvalsConfigSchema,\n /** How a daemon stop treats runs still in flight. */\n shutdown: z.object({\n /** Wait this long for runs to finish before cutting them off (they are\n * then resumed or reported after the restart). Unset: the\n * AGENTX_DRAIN_TIMEOUT_MS env var, else 300 s. Keep the service\n * manager's stop timeout above it, or it kills the daemon mid-wait. */\n drainTimeoutSeconds: z.number().int().min(0).max(86_400).optional(),\n /** Who may ask for \"restart when idle\", and what happens to the others.\n * Unset: any caller may, and onTimeout \"restart\" is honoured. */\n restart: z.object({\n /** Regular expression matched against the request's `by`. Requests\n * from anyone else are held until `window`, or refused when there\n * is no window. */\n allowBy: z.string().optional(),\n /** Local time \"HH:MM\" at which held requests start an idle-only wait. */\n window: z.string().regex(/^\\d{1,2}:\\d{2}$/, \"window must be HH:MM\").optional(),\n /** How long that wait lasts before it gives up. */\n windowWaitMinutes: z.number().int().min(1).max(1440).default(180),\n /** Turn every request into an idle-only one: a wait that runs out\n * gives up instead of restarting over running work. */\n forbidOnTimeoutRestart: z.boolean().default(false),\n }).default({}),\n }).default({}),\n /** What happens to runs a restart cuts off (agents/resume). Chat messages\n * are resumed in their chat; scheduled jobs never are (the next run\n * covers them); everything else is reported unless its channel is in\n * directChannels. */\n resume: z.object({\n enabled: z.boolean().default(true),\n /** Older runs are reported, not resumed. */\n maxAgeMinutes: z.number().int().positive().default(30),\n /** A run cut off while resuming is not retried past this. */\n maxAttempts: z.number().int().min(0).default(1),\n /** Channels whose runs are only reported, even from a chat. */\n reportOnlyChannels: z.array(z.string()).default([]),\n /** Non-chat runs (voice, agent-to-agent, webhooks…) resumed on these\n * channels. Their answer isn't delivered anywhere; opt in only for\n * runs whose work is the point. */\n directChannels: z.array(z.string()).default([]),\n /** This many restarts within the window pauses resuming. */\n crashLoop: z.object({\n restarts: z.number().int().positive().default(3),\n windowMinutes: z.number().positive().default(10),\n }).default({}),\n }).default({}),\n /** Hand due Apple Reminders back to the agent that created them\n * (src/reminders). macOS only; reads reminders whose notes end with the\n * mac-pim skill's `agentx: agent=<id>` trailer. */\n reminders: z.object({\n enabled: z.boolean().default(false),\n /** Reminders lists to watch. */\n lists: z.array(z.string().min(1)).default([\"AgentX\"]),\n pollSeconds: z.number().int().min(15).default(60),\n /** Overdue by more than this (the daemon was down): reported, not run. */\n lookbackHours: z.number().positive().default(24),\n /** The remindctl binary, when it isn't on the daemon's PATH. */\n command: z.string().min(1).default(\"remindctl\"),\n }).default({}),\n /** `agentx demo`, read from the agentx.json in the folder it runs from. */\n demo: z.object({\n /** Seconds each startup step (node /health, dashboard /live, mesh\n * discovery) may take. Unset: AGENTX_DEMO_STARTUP_TIMEOUT, else 60 s\n * scaled up by the load average (src/commands/demo-startup.ts). */\n startupTimeoutSeconds: z.number().int().positive().max(3600).optional(),\n }).default({}),\n /** The in-process event bus (src/events). `ringSize` bounds how many\n * recent events GET /events/recent can return. */\n events: z.object({\n ringSize: z.number().int().min(1).max(100_000).default(1000),\n }).default({}),\n screen: screenSchema,\n mesh: meshConfigSchema.default({}),\n /** Voices for agents on mesh peers, keyed by remote agent id, or by\n * \"<peer>/<id>\" for one peer's agent (it wins over the id). The Mac\n * speaks for them, so their nodes need no ElevenLabs key. Unset fields\n * are derived from the agent card; see src/voice/mesh-voice.ts. */\n meshVoices: z.record(z.string(), voiceSchema.omit({ rate: true, priority: true, hotkey: true }).extend({\n /** What to call the agent aloud, e.g. \"Atlas\" for \"Main Agent\". */\n name: z.string().optional(),\n })).default({}),\n /** How agents speak. The free system voices by default; ElevenLabs is an\n * opt-in upgrade. Each agent's `voice` block can override the provider\n * and pick its voice; see src/voice/agent-voice.ts. */\n voice: z.object({\n provider: voiceProviderSchema.default(\"system\"),\n /** When ElevenLabs cannot speak (no key, an error): the system voice,\n * or silence. */\n fallback: z.enum([\"system\", \"none\"]).default(\"system\"),\n /** The system voice for agents without one of their own (see\n * systemVoiceSchema). Unset: each agent gets its own. */\n system: systemVoiceSchema.optional(),\n /** Language for assigned system voices, e.g. \"en\", \"fr-FR\". */\n locale: z.string().default(\"en\"),\n /** What agents call the person they talk with, e.g. a first name.\n * Unset: \"the user\". */\n listener: z.string().optional(),\n /** AgentX Voice speech to text: \"auto\" uses ElevenLabs when a key is\n * set and the local Whisper otherwise; \"elevenlabs\" or \"local\" pick\n * one (ElevenLabs still falls back to local when it fails). */\n stt: z.enum([\"auto\", \"elevenlabs\", \"local\"]).default(\"auto\"),\n /** Phone voice input where the daemon has no ffmpeg to measure a\n * recording's length: refused by default, since the 2 MB cap alone\n * lets through ~40 minutes of low-bitrate audio. true accepts it. */\n allowUnmeasured: z.boolean().default(false),\n /** The on-device engine behind \"local\" and every fallback:\n * mlx-whisper (Python, all languages) or Parakeet (Core ML, 25\n * European languages, no Arabic; 483 MB downloaded on first use into\n * ~/.agentx/models). mlx-whisper answers until Parakeet is ready. */\n localStt: z.enum([\"mlx-whisper\", \"parakeet\"]).default(\"mlx-whisper\"),\n /** How AgentX Voice hears the end of a hands-free turn: \"vad\" (Silero\n * voice detection, 0.9 MB downloaded on first use; the volume\n * threshold until then) or \"volume\" (the old fixed threshold). */\n endOfTurn: z.enum([\"vad\", \"volume\"]).default(\"vad\"),\n /** AgentX Voice shortcuts: hold `talk` to speak, `stop` silences every\n * voice, `paste` is smart paste. */\n hotkeys: z.object({\n talk: hotkeySchema.default(DEFAULT_HOTKEYS.talk),\n stop: hotkeySchema.default(DEFAULT_HOTKEYS.stop),\n paste: hotkeySchema.default(DEFAULT_HOTKEYS.paste),\n }).default({}),\n /** The answer text AgentX Voice shows inside its pill. */\n card: z.object({\n /** Seconds the answer stays open once it has been spoken; 0 keeps\n * it open until closed. */\n timeout: z.number().min(0).max(600).default(30),\n /** Tallest the answer grows, in points, before it scrolls. */\n maxHeight: z.number().min(120).max(800).default(320),\n }).default({}),\n }).default({}),\n business: businessConfigSchema.optional(),\n boards: boardsConfigSchema,\n dashboard: dashboardConfigSchema,\n graph: graphConfigSchema,\n decisions: decisionsConfigSchema,\n /** Workflow engine — declarative state machines that bind channel events\n * to agents. Off by default; existing installs see no change until\n * flipped. Definitions live under `dir` (default .agentx/workflows/). */\n workflows: z.object({\n enabled: z.boolean().default(false),\n dir: z.string().default(\".agentx/workflows\"),\n /** n8n keeps its several hundred connectors; we keep the agents. Point\n * this at your n8n and the workflow builder lists YOUR n8n workflows as\n * steps, so nobody has to copy a webhook URL by hand. */\n n8n: z.object({\n baseUrl: z.string().default(\"\"),\n apiKey: z.string().default(\"\"),\n }).default({ baseUrl: \"\", apiKey: \"\" }),\n matching: z.object({\n enabled: z.boolean().default(false),\n mode: z.enum([\"suggest\", \"auto\"]).default(\"suggest\"),\n autoRunThreshold: z.number().min(0).max(1).default(0.85),\n suggestThreshold: z.number().min(0).max(1).default(0.65),\n }).default({}),\n /** Controls whether the dashboard exposes the visual editor. \"readonly\"\n * serves the list + run timelines but strips write controls from the\n * page. \"disabled\" hides the tab entirely. */\n editor: z.enum([\"disabled\", \"readonly\", \"edit\"]).default(\"edit\"),\n }).default({}),\n /** Procedures — user-perspective SOPs mined from recurring activity.\n * The extraction cadence itself lives in `crons.procedure-extract`\n * (written by `agentx procedure watch`); this block holds the miner's\n * thresholds and the injection gates the daemon reads. */\n procedures: z.object({\n enabled: z.boolean().default(true),\n dir: z.string().default(\".agentx/procedures\"),\n extraction: z.object({\n enabled: z.boolean().default(false),\n /** Count patterns live after each completed task (no LLM cost). */\n onTaskCompletion: z.boolean().default(false),\n minOccurrences: z.number().int().min(2).default(3),\n sinceDays: z.number().int().min(1).default(7),\n maxClusters: z.number().int().min(1).default(5),\n /** Agent whose session distills drafts (LLM path). */\n via: z.string().optional(),\n }).default({}),\n /** Inject matching procedures into fresh agent sessions as guidance. */\n injection: z.object({\n enabled: z.boolean().default(true),\n maxProcedures: z.number().int().min(1).default(2),\n minScore: z.number().min(0).max(1).default(0.5),\n }).default({}),\n }).default({}),\n /** Registered inbound webhooks — an inventory the dashboard manages. Each\n * entry binds an (agent, source) pair to an optional signing secret. The\n * actual inbound URL is always POST /webhook/<agentId>/<source>. */\n webhooks: z.array(z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, \"webhook id must be lowercase slug\"),\n // Open-string source — runtime + admin-panel + CLI all share a\n // canonical list (kept in sync via WEBHOOK_SOURCES). Loosened from a\n // strict enum so adding a new first-class service (the 5-step recipe)\n // doesn't require a schema bump in three places. Doctor + admin\n // validator still gate writes on the canonical list.\n source: z.string().min(1),\n agentId: z.string(),\n secretEnv: z.string().optional(),\n description: z.string().optional(),\n enabled: z.boolean().default(true),\n /** Route to a mesh peer instead of local execution. */\n node: z.string().optional(),\n /** Per-event-type workflow routing. Keys are platform event-type\n * strings — the format the platform's HTTP header uses, optionally\n * joined with the action. Examples:\n * GitHub: \"issues.opened\", \"pull_request.synchronize\",\n * \"push\" (action-less events use the bare type)\n * GitLab: \"Note Hook\", \"Merge Request Hook\"\n * Values are workflow ids registered via `agentx workflow create`.\n * When the inbound event-type matches a key, the named workflow is\n * dispatched; if no key matches, the webhook falls through to\n * `defaultWorkflow` (or the agent itself). Closes the recurring\n * GitHub problem of multiple event types collapsing to a single\n * workflow. */\n triggers: z.record(z.string(), z.string()).optional(),\n /** Workflow id used when no `triggers` entry matches the event-type.\n * Backward-compatible: pre-existing webhooks without `triggers`\n * always hit this path. */\n defaultWorkflow: z.string().optional(),\n })).default([]),\n /** Session cache-reuse policy. Controls when we drop a Claude `--resume`\n * session and rebuild the prompt from scratch. Every rotation captures a\n * continuity memo that's injected into the chat's next fresh session.\n * - `staleMinutes`: idle timeout before rotation. 12 h default — chat\n * conversations must survive a workday's pauses; overnight silence\n * starts fresh.\n * - `maxTurnsPerSession`: backstop cap on turns per Claude session.\n * Size-based rotation measures real context now, so this rarely fires\n * first.\n * - `tierTwoThresholdTokens`: rotate when the prior turn's END-OF-TURN\n * per-request context (last API call's input + cacheRead + cacheCreate)\n * reaches this. Claude bills the 1.5× long-context rate above 200K\n * per REQUEST — 180K leaves headroom. NOT the cumulative turn total:\n * that sums cache reads across every call and reads 10-20× too high. */\n session: z.object({\n staleMinutes: z.number().int().min(1).max(1440).default(720),\n maxTurnsPerSession: z.number().int().min(2).max(200).default(40),\n tierTwoThresholdTokens: z.number().int().min(50_000).max(200_000).default(180_000),\n /** Context assembly strategy:\n * - \"layered\" (default): the classic stacked layers — session history,\n * memory, cross-chat, wiki hint all appended every turn.\n * - \"planner\": a Haiku pre-call decides what to retrieve before the\n * main agent runs. Always-on core is kept (channel/scope/landscape/\n * identity/intent + last 3 turns verbatim); history blob, wiki hint,\n * and cross-chat are replaced by planner-selected bundles. Per-task\n * overrides via AgentTask.contextStrategy for A/B benchmarking. */\n contextStrategy: z.enum([\"layered\", \"planner\"]).default(\"layered\"),\n /** Soft dispatch budget for claude-code-tier agents (shared OAuth pools\n * one counter across the fleet). Warms at 80% of the cap; short-circuits\n * cold dispatches (no warm Claude session) when exceeded. Warm sessions\n * are always allowed through. Defaults sized for Max 5×:\n * - maxClaudeCodeDispatchesPerHour: 80 (headroom under typical hourly cap)\n * - maxClaudeCodeDispatchesPer5h: 180 (headroom under ~225/5h tier)\n * Raise for Max 20×, lower if your workload stays under the cap naturally. */\n maxClaudeCodeDispatchesPerHour: z.number().int().min(1).max(10_000).default(80),\n maxClaudeCodeDispatchesPer5h: z.number().int().min(1).max(50_000).default(180),\n /** How many requests BEFORE the immediate predecessor to show the\n * session-continuity seat. 0 keeps today's two-message state exactly.\n *\n * Off by default on purpose. A probe over 27 hand-written turns found\n * that at 3, the seat's safety question (`needsHistory`) becomes\n * cleanly separable where two messages leave it straddling zero — but\n * that rests on 7 positive examples from synthetic scenarios, and this\n * seat's failure mode is the agent silently losing conversation\n * context. The promotion gate for that wants labelled production rows,\n * not a good afternoon on a fixture. Raise it to collect them. */\n continuityStateTurns: z.number().int().min(0).max(5).default(0),\n }).default({}),\n /** Move B — JS/TS plugins. Each entry is an installed npm package name\n * (e.g. `agentx-plugin-mattermost` or `@acme/plugin-mattermost`); the\n * loader does a dynamic `import(name)` at boot, validates the manifest,\n * and calls plugin.setup(ctx). Plugins can register channel adapters\n * via ctx.addChannel() and subscribe to bus events via ctx.on(). Empty\n * default — installs that don't list plugins are unaffected. Plugin\n * authoring guide: docs/architecture/plugins.md. */\n plugins: z.array(z.string()).default([]),\n /** Persistent-process pool eviction knobs (handoff #8). The pool keeps\n * one warm Claude subprocess per (agent, channel, chatId) so latency\n * stays low; without bounds, an idle process can serve traffic days\n * later with stale context. These knobs cap that risk. All values are\n * in seconds for operator-friendliness; the registry uses ms internally.\n *\n * - `maxIdleSeconds`: a handle becomes eligible for cap-pressured\n * eviction this many seconds after its last turn. Default 30s\n * (matches the registry's pre-config behavior).\n * - `maxAgeSeconds`: a handle is killed unconditionally on the next\n * sweep once its total wall-clock idleness exceeds this. Default\n * 2700s (45min) — matches the registry's pre-config staleTimeoutMs.\n * - `sweepIntervalSeconds`: how often the sweeper checks. Default 5s.\n *\n * See `agents.<id>.persistentProcess` to opt an agent into the pool. */\n processPool: z.object({\n maxIdleSeconds: z.number().int().min(5).max(86_400).default(30),\n maxAgeSeconds: z.number().int().min(60).max(86_400).default(2700),\n sweepIntervalSeconds: z.number().int().min(1).max(300).default(5),\n }).default({}),\n})\n\nexport type DaemonConfig = z.infer<typeof daemonConfigSchema>\nexport type AgentDef = z.infer<typeof agentConfigSchema>\nexport type EventSubscription = z.infer<typeof eventSubscriptionSchema>\nexport type CronJobDef = z.infer<typeof cronJobSchema>\nexport type MeshPeer = z.infer<typeof meshPeerSchema>\n\n/**\n * Expand environment variables in strings: ${VAR_NAME} -> process.env.VAR_NAME\n */\nexport function expandEnvVars(obj: unknown): unknown {\n if (typeof obj === \"string\") {\n return obj.replace(/\\$\\{(\\w+)\\}/g, (_match, name) => process.env[name] || \"\")\n }\n if (Array.isArray(obj)) {\n return obj.map(expandEnvVars)\n }\n if (obj !== null && typeof obj === \"object\") {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n result[key] = expandEnvVars(value)\n }\n return result\n }\n return obj\n}\n\n/**\n * Translate raw Zod issues into actionable, copy-pasteable fixes for the\n * patterns we see in real first-run failures (missing tokens, missing\n * required env vars, etc.). Falls through silently for unknown patterns —\n * the raw `issues` block is always shown above this hint block.\n */\nfunction friendlyConfigHints(issues: ReadonlyArray<z.ZodIssue>, configPath: string): string[] {\n const hints: string[] = []\n const seen = new Set<string>()\n for (const issue of issues) {\n const path = issue.path.join(\".\")\n // Telegram account block exists but token is empty/missing — by far the\n // most common first-run trip. Tell the operator exactly which two\n // recoveries are valid, with the literal config path to edit.\n const tgTokenMatch = /^channels\\.telegram\\.accounts\\.([^.]+)\\.token$/.exec(path)\n if (tgTokenMatch && issue.message.toLowerCase().includes(\"required\")) {\n const account = tgTokenMatch[1]\n const key = `tg:${account}`\n if (seen.has(key)) continue\n seen.add(key)\n hints.push(\n `Hint: Telegram account \"${account}\" is enabled but has no bot token.\\n` +\n ` Either:\\n` +\n ` A) Open ${configPath} and set channels.telegram.accounts.${account}.token to your bot token (or \"\\${TG_${account.toUpperCase()}_BOT_TOKEN}\" + the matching .env entry).\\n` +\n ` B) If you don't need Telegram on this instance, remove the entire \"telegram\" block under \"channels\" (or set channels.telegram.enabled to false AND drop accounts.${account}).`\n )\n }\n }\n return hints\n}\n\n/**\n * Load daemon config from agentx.json, with env var expansion and validation.\n */\nexport function loadDaemonConfig(configPath?: string): DaemonConfig {\n const paths = configPath\n ? [configPath]\n : [\n resolve(process.cwd(), \"agentx.json\"),\n resolve(process.cwd(), \".agentx/config.json\"),\n ]\n\n // Load .env from same directory as config search\n loadDotEnv(process.cwd())\n\n let raw: string | undefined\n let foundPath: string | undefined\n\n for (const p of paths) {\n if (existsSync(p)) {\n raw = readFileSync(p, \"utf-8\")\n foundPath = p\n break\n }\n }\n\n if (!raw || !foundPath) {\n throw new Error(\n `No config found. Create agentx.json or .agentx/config.json\\n` +\n `Searched: ${paths.join(\", \")}`\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (e: any) {\n throw new Error(`Invalid JSON in ${foundPath}: ${e.message}`)\n }\n\n // Expand environment variables\n const expanded = expandEnvVars(parsed)\n\n // Validate\n const result = daemonConfigSchema.safeParse(expanded)\n if (!result.success) {\n const issues = result.error.issues\n .map((i) => ` ${i.path.join(\".\")}: ${i.message}`)\n .join(\"\\n\")\n const hints = friendlyConfigHints(result.error.issues, foundPath)\n const hintBlock = hints.length ? `\\n\\n${hints.join(\"\\n\\n\")}` : \"\"\n throw new Error(`Config validation failed (${foundPath}):\\n${issues}${hintBlock}`)\n }\n\n return result.data\n}\n\n/**\n * Validate agent workspace directories exist and have .claude/ setup.\n */\nexport function validateWorkspaces(config: DaemonConfig): string[] {\n const warnings: string[] = []\n\n for (const [id, agent] of Object.entries(config.agents)) {\n if (!existsSync(agent.workspace)) {\n warnings.push(`Agent \"${id}\": workspace not found at ${agent.workspace}`)\n continue\n }\n\n if (agent.tier === \"claude-code\") {\n const claudeDir = resolve(agent.workspace, \".claude\")\n if (!existsSync(claudeDir)) {\n warnings.push(\n `Agent \"${id}\": no .claude/ directory in workspace ${agent.workspace}. ` +\n `Claude Code native features (hooks, MCP, skills) won't be available.`\n )\n }\n }\n\n // Check provider availability\n const providerName = agent.provider || \"claude\"\n const providerConfig = config.providers[providerName]\n if (![\"claude-code\", \"codex-cli\", \"opencode\"].includes(agent.tier) && (!providerConfig || !providerConfig.apiKey)) {\n warnings.push(\n `Agent \"${id}\": provider \"${providerName}\" has no API key configured. ` +\n `Set providers.${providerName}.apiKey in config or use a CLI-backed tier (\"claude-code\", \"codex-cli\", or \"opencode\").`\n )\n }\n }\n\n // Validate cron agent bindings\n for (const [id, cron] of Object.entries(config.crons)) {\n if (!config.agents[cron.agent]) {\n warnings.push(`Cron \"${id}\": references unknown agent \"${cron.agent}\"`)\n }\n }\n\n // Validate channel agent bindings\n if (config.channels.telegram.enabled) {\n for (const [name, account] of Object.entries(config.channels.telegram.accounts)) {\n if (!config.agents[account.agentBinding]) {\n warnings.push(\n `Teleg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AAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,EAgBvC,YAAaA,EAAE,OAAO,CACpB,eAAgBA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM,EAAE,QAAQ,EAAE,EAC9D,cAAeA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,IAAI,KAAM,EAAE,QAAQ,IAAI,EAChE,qBAAsBA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,CAAC,CAClE,CAAC,EAAE,QAAQ,CAAC,CAAC,CACf,CAAC","names":["z","dayEnum","scheduleSchema","roleSchema","orgEntrySchema","channelRefSchema","workSourceSchema","projectSchema","contactMapSchema","clientPolicySchema","businessConfigSchema","init_config","__esmMin","z","deriveStage","item","columns","set","closed","c","backlog","prefix","transitionDiff","fromColumn","toColumn","add","remove","closeIssue","reopen","boardLabelSchema","boardColumnSchema","boardReconcileSchema","boardSourceSchema","DEFAULT_COLUMNS","boardSchema","boardsConfigSchema","dashboardDaemonSchema","dashboardConfigSchema","init_config","__esmMin","z","isRestricted","level","toolWords","name","w","mcpActionWords","shellView","command","text","m","quote","_d","body","out","i","c","end","j","inner","shellSegments","view","s","commandWords","words","SHELL_KEYWORDS_SKIP","SHELL_KEYWORDS_STRIP","gitSubcommand","args","reportShellWord","cmd","base","REPORT_SHELL_COMMANDS","has","re","a","sub","rest","GIT_READ","group","action","method","GH_READ_ACTIONS","hasWritingRedirect","cleaned","reportBash","block","seg","why","ALLOW","reportTool","input","WRITE_TOOLS","REPORT_SAFE_TOOLS","mutating","MUTATING_VERBS","READ_VERBS","proposeGitPush","positional","PUSH_VALUE_OPTS","refspecs","ref","PROTECTED_BRANCH","proposeBash","rule","PROPOSE_RAW_RULES","line","baseName","PROPOSE_COMMAND_RULES","hit","proposeTool","DESTRUCTIVE_VERBS","isDelegation","evaluateAutonomy","autonomyBrief","autonomyLevelSchema","init_autonomy","__esmMin","id","reason","parseHotkey","input","raw","parts","p","key","KEY_ALIASES","mods","m","MODIFIERS","isKey","isFKey","ORDER","hotkeyError","r","describeHotkey","value","sym","names","NAMED_KEYS","DEFAULT_HOTKEYS","init_hotkey","__esmMin","k","hueOf","hex","m","r","g","b","x","max","min","paletteForColor","hue","ORB_PALETTES","p","best","bestDistance","d","distance","agentPalette","chosen","color","picked","ORB_PALETTE_IDS","init_orb_palettes","__esmMin","z","hhmm","watchRuleSchema","whatsappTriageSchema","init_config","__esmMin","r","config_exports","__export","INTEGRATION_KINDS","approvalsConfigSchema","callsSchema","cameraBotSchema","daemonConfigSchema","eventSubscriptionSchema","expandEnvVars","loadDaemonConfig","validateWorkspaces","z","readFileSync","existsSync","resolve","loadDotEnv","dir","envPath","content","line","trimmed","eqIdx","key","value","obj","_match","name","result","friendlyConfigHints","issues","configPath","hints","seen","issue","path","tgTokenMatch","account","paths","raw","foundPath","p","parsed","e","expanded","i","hintBlock","config","warnings","id","agent","claudeDir","providerName","providerConfig","cron","providerConfigSchema","mcpStdioServerSchema","mcpHttpServerSchema","mcpServerSchema","integrationCredentialsSchema","integrationSchema","voiceProviderSchema","systemVoiceSchema","hotkeySchema","voiceSchema","agentConfigSchema","telegramAccountSchema","channelsConfigSchema","cronJobSchema","serviceSchema","meshPeerSchema","meshInboxSchema","meshConfigSchema","graphConfigSchema","decisionSeatSchema","decisionsConfigSchema","notificationsSchema","screenRectSchema","screenSchema","init_config","__esmMin","init_autonomy","init_hotkey","init_orb_palettes","s","ctx","error","hotkeyError","ORB_PALETTE_IDS","autonomyLevelSchema","v","j","tz","whatsappTriageSchema","DEFAULT_HOTKEYS","businessConfigSchema","boardsConfigSchema","dashboardConfigSchema"]}
1
+ {"version":3,"sources":["../src/business/config.ts","../src/boards/config.ts","../src/guard/autonomy.ts","../src/voice/hotkey.ts","../src/voice/orb-palettes.ts","../src/whatsapp-triage/config.ts","../src/daemon/config.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Business layer configuration schema (EXPERIMENTAL) ---\n// Optional top-level `business` key in agentx.json.\n// When enabled, AgentX simulates a team with roles, schedules, and a work pool.\n// Experimental: off by default, undocumented while the model settles —\n// config shape may change between minor versions without migration.\n\nconst dayEnum = z.enum([\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"])\n\nconst scheduleSchema = z.object({\n days: z.array(dayEnum).default([\"mon\", \"tue\", \"wed\", \"thu\", \"fri\"]),\n start: z.string().regex(/^\\d{2}:\\d{2}$/), // \"09:00\"\n end: z.string().regex(/^\\d{2}:\\d{2}$/), // \"17:00\"\n lunch: z.object({\n start: z.string().regex(/^\\d{2}:\\d{2}$/),\n end: z.string().regex(/^\\d{2}:\\d{2}$/),\n }).optional(),\n})\n\nconst roleSchema = z.object({\n title: z.string(),\n responsibilities: z.array(z.string()).default([]),\n sopPath: z.string().optional(),\n kpis: z.array(z.string()).default([]),\n})\n\nconst orgEntrySchema = z.object({\n role: z.string(),\n reportsTo: z.string().optional(),\n schedule: scheduleSchema,\n utilizationTarget: z.number().min(0).max(1).default(0.8),\n})\n\nconst channelRefSchema = z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n})\n\nconst workSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"backlog\"),\n path: z.string().default(\".agentx/backlog.md\"),\n }),\n z.object({\n type: z.literal(\"gitlab\"),\n projects: z.array(z.string()).default([]), // empty = all configured gitlab projects\n }),\n z.object({\n type: z.literal(\"wiki\"),\n path: z.string(),\n glob: z.string().default(\"**/*.md\"),\n }),\n])\n\n/** Per-project metadata. Phase 3 of the architectural rescue —\n * `pm` is the agentId responsible for gating dispatches on this\n * project. Optional; when null, dispatches don't go through a PM\n * gate. The wiring lives in `decideAndCommit` (gated by a flag,\n * separate commit). */\nconst projectSchema = z.object({\n /** Project identifier. For GitLab/GitHub: \"owner/repo\". For\n * acme-internal projects: a stable string. */\n id: z.string(),\n /** AgentId of the PM for this project. Looked up by\n * `Organization.pmFor(project)` at dispatch time. */\n pm: z.string().optional(),\n /** Optional client this project belongs to. Used by the activity\n * graph to attribute non-projected events (Telegram chats, free-\n * text WhatsApp, cron jobs) to the right client. Falls back to\n * the leading segment of `id` (split on \"/\") when unset. */\n client: z.string().optional(),\n})\n\n/** Maps a chat or sender to a client/project so free-text channels\n * (telegram/whatsapp/slack/discord/email) get attributed correctly\n * in the activity graph. Without this, every chat lands in the\n * fallback \"internal\" bucket — the operator can't tell which client\n * the agent was helping.\n *\n * Match priority: chatId > username > channel-default. First match\n * wins. All fields except `client` are optional; `project` falls\n * back to `${client}/_chat` when unset. */\nconst contactMapSchema = z.object({\n /** Channel kind, e.g. \"telegram\", \"whatsapp\", \"slack\", \"discord\". */\n channel: z.string().optional(),\n /** Native chat id (\"-100...\" for tg groups, JID for WhatsApp). */\n chatId: z.string().optional(),\n /** Sender username/handle as exposed by the channel adapter. */\n username: z.string().optional(),\n /** Numeric sender id when username is unstable. */\n senderId: z.string().optional(),\n /** Client this contact belongs to. Required. */\n client: z.string(),\n /** Project this contact's traffic should attribute to. Defaults to\n * `${client}/_chat`. */\n project: z.string().optional(),\n /** Display name override for the initiator pill. */\n displayName: z.string().optional(),\n})\n\n/** Per-client policy. Clients are DERIVED from `projects` and `contactMap`\n * — one exists the moment either mentions it — so nothing needs declaring\n * up front. This record only carries overrides for the two things a\n * heuristic cannot know: how fast a delay costs you, and what an agent may\n * do for this client without asking first. */\nconst clientPolicySchema = z.object({\n /** Display name. Defaults to the client id. */\n name: z.string().optional(),\n /** \"client\" is someone who is waiting on you and can be let down; \"own\"\n * is your own product; \"internal\" is machinery with no external clock. */\n kind: z.enum([\"client\", \"internal\", \"own\"]).optional(),\n /** How long a wait may last before it starts costing: \"4h\", \"90m\", \"2d\".\n * Unset means no external clock, so delay is flat. */\n respondWithin: z.string().optional(),\n /** Capabilities an agent may exercise unattended. \"*\" means all. Ignored\n * for kind \"client\" — see mayProceedUnattended(). */\n standing: z.array(z.string()).default([]),\n})\n\nexport const businessConfigSchema = z.object({\n enabled: z.boolean().default(false),\n timezone: z.string().default(\"UTC\"),\n mainChannel: channelRefSchema,\n workSource: workSourceSchema,\n roles: z.record(z.string(), roleSchema).default({}),\n orgChart: z.record(z.string(), orgEntrySchema).default({}),\n /** Per-project metadata. Phase 3 — defaults to empty array, so\n * existing agentx.json files validate without modification. */\n projects: z.array(projectSchema).default([]),\n /** Maps free-text chat senders to a client/project so the activity\n * graph can attribute Telegram/WhatsApp/etc. to the right client\n * instead of the catch-all \"internal\" bucket. */\n contactMap: z.array(contactMapSchema).default([]),\n /** Overrides for derived clients. Keyed by client id; absent entries get\n * defaults, so this stays empty until you need a clock or an\n * authorization. */\n clients: z.record(z.string(), clientPolicySchema).default({}),\n /** Work-tick cadence in minutes during business hours. Default 15. */\n workTickMinutes: z.number().int().min(1).max(60).default(15),\n /** Max queue depth for an idle agent before skipping the work tick (avoids piling up). */\n idleQueueThreshold: z.number().int().min(0).default(0),\n /** Standup-tick gating + plan-driven priorities. The day-cycle's morning\n * STANDUP used to fire unconditionally per agent — operators reported it\n * as \"mechanical\" because it dispatched a Claude turn even when no human\n * had set a plan for the day. Now: the cycle reads\n * .agentx/plans/<date>.md (day → week → month fallback) and either\n * injects the plan as standup priorities, or posts a \"no plan today\"\n * notification to mainChannel and dispatches no agent. */\n standup: z.object({\n /** Master switch. When false, fireStandup is a no-op (silent). */\n enabled: z.boolean().default(true),\n /** Plans directory, relative to the daemon CWD. */\n plansDir: z.string().default(\".agentx/plans\"),\n /** Hard ceiling on how many agents the standup tick can dispatch in a\n * single morning — guards against an org-chart misconfiguration\n * fanning out to dozens of Claude calls before anyone notices. */\n maxAgentsPerDay: z.number().int().min(1).max(100).default(20),\n /** When true, even with a plan present the cycle won't dispatch — only\n * posts the resolved plan to mainChannel for human review. Useful as\n * a kill-switch while iterating on plan formats. */\n dryRun: z.boolean().default(false),\n }).default({}),\n})\n\nexport type BusinessConfig = z.infer<typeof businessConfigSchema>\nexport type BusinessRole = z.infer<typeof roleSchema>\nexport type BusinessOrgEntry = z.infer<typeof orgEntrySchema>\nexport type BusinessSchedule = z.infer<typeof scheduleSchema>\nexport type BusinessWorkSource = z.infer<typeof workSourceSchema>\nexport type BusinessChannelRef = z.infer<typeof channelRefSchema>\nexport type BusinessProject = z.infer<typeof projectSchema>\n","import { z } from \"zod\"\n\n// --- Kanban board configuration ---\n//\n// Top-level optional keys in agentx.json, independent of the business layer:\n//\n// boards: array of kanban boards, each backed by a WorkSource\n// dashboard: HTTP server controlling whether the board UI serves\n//\n// Both default to empty / disabled so existing installs see no change.\n\nexport const boardLabelSchema = z.object({\n /** Label name — used verbatim as the GitLab label string. */\n name: z.string(),\n color: z.string().regex(/^#[0-9a-f]{6}$/i).default(\"#6366f1\"),\n description: z.string().optional(),\n})\n\n/**\n * A board column. `kind` controls what issues land here and how drag-to-this-column\n * mutates the issue:\n *\n * - \"open-backlog\": opened issues that have NO scoped label matching `scopedPrefix`\n * (default \"Status\"). Dragging INTO this column removes any existing scoped label.\n * - \"scoped-label\": opened issues carrying `scopedLabel` (e.g. \"Status::Doing\").\n * Scoped labels are mutually exclusive by prefix, so adding the new one lets\n * GitLab auto-remove the old one (Premium), but we still explicitly strip the\n * previous column's label for compatibility.\n * - \"closed\": all closed issues. Dragging here closes the issue; dragging away\n * reopens it.\n * - \"label\" (default, legacy): opened issues with `mapsToLabel`; flat add/remove.\n */\nexport const boardColumnSchema = z.object({\n id: z.string().regex(/^[a-z0-9_-]+$/, \"column id must be lowercase slug\"),\n title: z.string(),\n kind: z.enum([\"open-backlog\", \"scoped-label\", \"closed\", \"label\"]).default(\"label\"),\n /** For kind=\"label\": label written on entry, removed on exit. */\n mapsToLabel: z.string().optional(),\n /** For kind=\"scoped-label\": the full scoped label (e.g. \"Status::Doing\"). */\n scopedLabel: z.string().optional(),\n /** For kind=\"open-backlog\": scoped prefix that marks \"claimed\" cards to exclude. */\n scopedPrefix: z.string().default(\"Status\"),\n /** CSS color or hex — shown as the column's top accent bar. */\n accent: z.string().optional(),\n})\nexport type BoardColumnId = string\n\nexport const boardReconcileSchema = z.object({\n enabled: z.boolean().default(true),\n staleDoingMinutes: z.number().int().min(1).default(45),\n respectLunchBreak: z.boolean().default(true),\n respectSchedule: z.boolean().default(true),\n /** Badge only for P1/P3; auto-notify + auto-demote deferred. */\n action: z.enum([\"badge\", \"notify\"]).default(\"badge\"),\n})\n\nexport const boardSourceSchema = z.discriminatedUnion(\"type\", [\n z.object({\n type: z.literal(\"gitlab\"),\n /** GitLab project paths (e.g. \"globex/globex-system-v2\"). At least one required. */\n projects: z.array(z.string()).min(1),\n }),\n // future: backlog, wiki\n])\n\n/**\n * GitLab-style default board — six columns:\n * Open (backlog) → To Do → Doing → On Hold → Review → Closed\n *\n * Drives the `Status::*` scoped label taxonomy. Moving a card adds/removes the\n * column's scoped label; moving INTO Closed closes the issue; moving OUT of\n * Closed reopens it; moving INTO Open strips any Status::* label.\n */\nexport const DEFAULT_COLUMNS: Array<z.infer<typeof boardColumnSchema>> = [\n { id: \"open\", title: \"Open\", kind: \"open-backlog\", scopedPrefix: \"Status\", accent: \"#6b7280\" },\n { id: \"todo\", title: \"To Do\", kind: \"scoped-label\", scopedLabel: \"Status::To Do\", scopedPrefix: \"Status\", accent: \"#fb7a35\" },\n { id: \"doing\", title: \"Doing\", kind: \"scoped-label\", scopedLabel: \"Status::Doing\", scopedPrefix: \"Status\", accent: \"#22c55e\" },\n { id: \"onhold\", title: \"On Hold\", kind: \"scoped-label\", scopedLabel: \"Status::On Hold\", scopedPrefix: \"Status\", accent: \"#f59e0b\" },\n { id: \"review\", title: \"Review\", kind: \"scoped-label\", scopedLabel: \"Status::Review\", scopedPrefix: \"Status\", accent: \"#3b82f6\" },\n { id: \"closed\", title: \"Closed\", kind: \"closed\", scopedPrefix: \"Status\", accent: \"#6b7280\" },\n]\n\nexport const boardSchema = z.object({\n id: z.string().regex(/^[a-z0-9_-]+$/, \"board id must be lowercase slug\"),\n name: z.string(),\n source: boardSourceSchema,\n /** If set, ANDed into every listAll query and shown as a baseline chip in the UI. */\n primaryToolLabel: z.string().optional(),\n labels: z.array(boardLabelSchema).default([]),\n columns: z.array(boardColumnSchema).min(1).default(DEFAULT_COLUMNS),\n timeRangeDays: z.number().int().min(1).max(365).default(30),\n /** Maximum closed-issue window (days) shown in the Closed column. */\n closedWindowDays: z.number().int().min(1).max(365).default(30),\n reconciliation: boardReconcileSchema.default({}),\n})\n\nexport const boardsConfigSchema = z.array(boardSchema).default([])\n\nexport const dashboardDaemonSchema = z.object({\n name: z.string(),\n /** Daemon HTTP URL (the one serving /agents, /health, /task). */\n url: z.string(),\n /** Optional board-dashboard URL if we want to proxy admin writes to this\n * peer. Defaults to `url` with port :18800/:19900 rewritten to :4202,\n * matching our convention that the dashboard runs alongside the daemon. */\n dashboardUrl: z.string().optional(),\n /** Bearer for the daemon's HTTP API (live snapshot, task stream). */\n token: z.string().optional(),\n /** Bearer for the peer's dashboard when proxying admin calls. Defaults to\n * `token` when unset. */\n dashboardToken: z.string().optional(),\n})\n\nexport const dashboardConfigSchema = z.object({\n enabled: z.boolean().default(false),\n port: z.number().int().default(4202),\n bind: z.string().default(\"127.0.0.1\"),\n /** Opt-in bearer token for writes. If unset, writes are unauthenticated. */\n token: z.string().optional(),\n /** Primary daemon the dashboard talks to for live view + A2A. */\n daemonUrl: z.string().default(\"http://localhost:18800\"),\n /** Additional daemons to poll (beyond peers discovered via primary's /mesh). */\n daemons: z.array(dashboardDaemonSchema).default([]),\n /** Default agent used for AI-assisted drafting in the create-issue flow. */\n draftAgent: z.string().optional(),\n}).default({})\n\nexport type BoardConfig = z.infer<typeof boardSchema>\nexport type BoardLabel = z.infer<typeof boardLabelSchema>\nexport type BoardColumn = z.infer<typeof boardColumnSchema>\nexport type BoardSource = z.infer<typeof boardSourceSchema>\nexport type BoardReconcile = z.infer<typeof boardReconcileSchema>\nexport type DashboardConfig = z.infer<typeof dashboardConfigSchema>\n\n/**\n * Decide which column an item lives in. Walks columns in order; the first\n * matching column wins. Items with `state: \"closed\"` always land in the\n * first `kind: \"closed\"` column; otherwise the first `scoped-label` whose\n * `scopedLabel` is present wins; otherwise the first `label` column whose\n * `mapsToLabel` is present; otherwise the first `open-backlog` column.\n *\n * Returns `null` when the item carries a scoped label matching an\n * `open-backlog` column's `scopedPrefix` but no `scoped-label` column claims\n * it — those are off-board workflow states (e.g. `Status::Done` when no\n * Done column exists) and must not leak into the backlog.\n */\nexport function deriveStage(\n item: { state?: \"opened\" | \"closed\"; labels?: string[] },\n columns: BoardColumn[],\n): BoardColumnId | null {\n const set = new Set(item.labels || [])\n if (item.state === \"closed\") {\n const closed = columns.find((c) => c.kind === \"closed\")\n if (closed) return closed.id\n }\n for (const c of columns) {\n if (c.kind === \"scoped-label\" && c.scopedLabel && set.has(c.scopedLabel)) return c.id\n }\n for (const c of columns) {\n if (c.kind === \"label\" && c.mapsToLabel && set.has(c.mapsToLabel)) return c.id\n }\n const backlog = columns.find((c) => c.kind === \"open-backlog\")\n if (backlog) {\n // If the item has any scoped-prefix label, it's not an open-backlog candidate.\n const prefix = backlog.scopedPrefix + \"::\"\n const hasScoped = [...set].some((l) => l.startsWith(prefix))\n return hasScoped ? null : backlog.id\n }\n return columns[0]?.id ?? null\n}\n\n/**\n * Describes how to mutate an issue to move it between two columns.\n * `closeIssue` / `reopen` take precedence over label mutations on the same action.\n */\nexport interface ColumnTransition {\n addLabels?: string[]\n removeLabels?: string[]\n closeIssue?: boolean\n reopen?: boolean\n}\n\nexport function transitionDiff(\n fromColumn: BoardColumn | undefined,\n toColumn: BoardColumn,\n): ColumnTransition {\n const add: string[] = []\n const remove: string[] = []\n let closeIssue = false\n let reopen = false\n\n // Handle target column.\n if (toColumn.kind === \"scoped-label\" && toColumn.scopedLabel) {\n add.push(toColumn.scopedLabel)\n } else if (toColumn.kind === \"label\" && toColumn.mapsToLabel) {\n add.push(toColumn.mapsToLabel)\n } else if (toColumn.kind === \"closed\") {\n closeIssue = true\n }\n\n // Handle source column — strip its label; if it was \"closed\", reopen.\n if (fromColumn) {\n if (fromColumn.kind === \"scoped-label\" && fromColumn.scopedLabel) {\n remove.push(fromColumn.scopedLabel)\n } else if (fromColumn.kind === \"label\" && fromColumn.mapsToLabel) {\n remove.push(fromColumn.mapsToLabel)\n } else if (fromColumn.kind === \"closed\" && toColumn.kind !== \"closed\") {\n reopen = true\n }\n }\n\n return {\n addLabels: add.length ? add : undefined,\n removeLabels: remove.length ? remove : undefined,\n closeIssue: closeIssue || undefined,\n reopen: reopen || undefined,\n }\n}\n","import { z } from \"zod\"\n\n// --- Routine autonomy levels: the rule sets ---\n//\n// A routine (cron job or workflow agent step) may run below its agent's full\n// power:\n//\n// report — read-only. No file writes, no mutating shell, no outward-posting\n// tools. The only output is the final answer, which the scheduler\n// delivers.\n// propose — may edit files, commit, push a feature branch, open an MR/PR or\n// a draft. Never merge, deploy, delete, force-push, or touch\n// production.\n// act — unchanged: whatever the agent may normally do.\n//\n// This module is PURE: (level, tool call) -> allow | block. It is evaluated\n// by the daemon for every tool call of a restricted task (see\n// autonomy-enforce.ts for the wiring). Deterministic by construction, like\n// the rest of the guard.\n//\n// Shape of the two restricted levels differs on purpose:\n// - report is an ALLOWLIST. A read-only posture cannot be expressed as\n// \"everything except the dangerous things\" — `python -c`, `node x.js`\n// or a `curl -d` are all writes nobody would list. Unknown => blocked.\n// - propose is a DENYLIST over a working agent. Its job is to stop the\n// irreversible, outward steps (merge/deploy/delete/force-push), not to\n// make the agent useless. A determined agent can evade a denylist by\n// indirection (write a script, then run it); propose is a guardrail for\n// honest routines, report is the hard boundary.\n\nexport const autonomyLevelSchema = z.enum([\"report\", \"propose\", \"act\"])\nexport type AutonomyLevel = z.infer<typeof autonomyLevelSchema>\n\n/** True for the levels that need per-task enforcement. */\nexport function isRestricted(level: AutonomyLevel | undefined | null): level is \"report\" | \"propose\" {\n return level === \"report\" || level === \"propose\"\n}\n\nexport interface AutonomyInput {\n tool: string\n command?: string\n filePath?: string\n}\n\nexport interface AutonomyDecision {\n allowed: boolean\n /** Stable id, e.g. \"autonomy.report.write\". Null when allowed. */\n ruleId: string | null\n reason: string | null\n}\n\nconst ALLOW: AutonomyDecision = { allowed: true, ruleId: null, reason: null }\nconst block = (level: string, id: string, reason: string): AutonomyDecision => ({\n allowed: false,\n ruleId: `autonomy.${level}.${id}`,\n reason,\n})\n\n// ---------------------------------------------------------------- tools\n\nconst WRITE_TOOLS = new Set([\"Write\", \"Edit\", \"MultiEdit\", \"NotebookEdit\"])\n\n/** Native tools that never change anything outside the conversation. */\nconst REPORT_SAFE_TOOLS = new Set([\n \"Read\", \"Glob\", \"Grep\", \"LS\", \"NotebookRead\", \"WebFetch\", \"WebSearch\",\n \"TodoWrite\", \"TodoRead\", \"Task\", \"Agent\", \"Skill\", \"ToolSearch\",\n \"BashOutput\", \"KillShell\", \"ExitPlanMode\", \"EnterPlanMode\",\n \"ListMcpResourcesTool\", \"ReadMcpResourceTool\",\n])\n\n/** Split a tool name into lowercase words: `mcp__gitlab__create_merge_request`\n * -> [mcp, gitlab, create, merge, request]; camelCase splits too. */\nexport function toolWords(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/[^A-Za-z0-9]+/)\n .filter(Boolean)\n .map((w) => w.toLowerCase())\n}\n\n/** The action words of an MCP tool name (server prefix dropped), with the\n * nouns \"merge request\" / \"pull request\" folded so `create_merge_request`\n * reads as create-an-MR, not as a merge. */\nexport function mcpActionWords(name: string): string[] {\n return toolWords(name)\n .slice(2)\n .join(\" \")\n .replace(/\\b(merge|pull)\\s+requests?\\b/g, \"mergerequest\")\n .split(\" \")\n .filter(Boolean)\n}\n\nconst READ_VERBS = new Set([\n \"get\", \"list\", \"search\", \"read\", \"view\", \"fetch\", \"query\", \"find\", \"show\", \"describe\",\n \"status\", \"diff\", \"inspect\", \"lookup\", \"count\", \"stats\", \"browse\", \"whoami\", \"download\",\n])\n/** Irreversible or outward-facing verbs. Blocked in propose, and in report. */\nconst DESTRUCTIVE_VERBS = new Set([\n \"merge\", \"delete\", \"remove\", \"destroy\", \"drop\", \"deploy\", \"publish\", \"release\", \"approve\",\n \"archive\", \"revoke\", \"purge\", \"close\", \"transfer\", \"force\", \"rollback\", \"restart\", \"erase\",\n \"unprotect\", \"truncate\", \"wipe\", \"kill\", \"terminate\", \"unpublish\", \"promote\",\n])\n/** Any state change at all. Blocked in report. */\nconst MUTATING_VERBS = new Set([\n ...DESTRUCTIVE_VERBS,\n \"create\", \"update\", \"post\", \"send\", \"write\", \"edit\", \"add\", \"set\", \"comment\", \"reply\",\n \"push\", \"run\", \"execute\", \"exec\", \"trigger\", \"upload\", \"move\", \"rename\", \"cancel\", \"retry\",\n \"assign\", \"label\", \"react\", \"invite\", \"notify\", \"schedule\", \"start\", \"stop\", \"submit\", \"save\",\n \"patch\", \"put\", \"insert\", \"upsert\", \"apply\", \"install\", \"import\", \"mark\", \"toggle\", \"enable\",\n \"disable\", \"open\", \"commit\", \"sync\", \"reset\", \"store\", \"remember\", \"forget\", \"broadcast\",\n \"message\", \"call\", \"dispatch\", \"enqueue\", \"resolve\", \"unassign\", \"lock\", \"unlock\", \"pin\",\n])\n\n// ---------------------------------------------------------------- shell view\n\n/**\n * The part of a shell command the shell will actually EXECUTE, flattened so\n * every command position can be inspected:\n * - single-quoted text is blanked (truly literal),\n * - double-quoted text is blanked unless it contains `$(`/backticks, in\n * which case the substitution is executed and must stay visible,\n * - heredoc bodies are blanked unless the delimiter is unquoted and the\n * body substitutes commands.\n * Returns `null` for input too irregular to judge (unbalanced quotes), which\n * callers treat as \"block\" in report mode.\n */\nexport function shellView(command: string): string | null {\n // Heredocs: blank the body unless the delimiter is unquoted AND the body\n // substitutes commands (then the shell executes it — keep it visible).\n const text = command.replace(/<<-?\\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\\1([\\s\\S]*?)^\\s*\\2\\s*$/gm,\n (m, quote: string, _d: string, body: string) =>\n !quote && /\\$\\(|`/.test(body) ? m : m.split(\"\\n\")[0] + \"\\n\")\n let out = \"\"\n let i = 0\n while (i < text.length) {\n const c = text[i]\n if (c === \"\\\\\") { out += text.slice(i, i + 2); i += 2; continue }\n if (c === \"'\") {\n const end = text.indexOf(\"'\", i + 1)\n if (end < 0) return null\n out += \"''\"\n i = end + 1\n continue\n }\n if (c === '\"') {\n let j = i + 1\n while (j < text.length && text[j] !== '\"') j += text[j] === \"\\\\\" ? 2 : 1\n if (j >= text.length) return null\n const inner = text.slice(i + 1, j)\n out += /\\$\\(|`/.test(inner) ? ` ${inner} ` : '\"\"'\n i = j + 1\n continue\n }\n out += c\n i++\n }\n return out\n}\n\n/** Split a shell view into simple-command segments (words arrays). */\nexport function shellSegments(view: string): string[][] {\n return view\n .split(/\\|\\||&&|[;|&\\n`()]|\\$\\(|<\\(|>\\(/)\n .map((s) => s.trim().split(/\\s+/).filter(Boolean))\n .filter((w) => w.length > 0)\n}\n\nconst SHELL_KEYWORDS_STRIP = new Set([\"then\", \"do\", \"else\", \"elif\", \"if\", \"while\", \"until\", \"!\", \"{\", \"}\", \"time\"])\nconst SHELL_KEYWORDS_SKIP = new Set([\"done\", \"fi\", \"esac\", \"for\", \"case\", \"select\", \"in\", \";;\"])\n\n/** Drop leading keywords and `VAR=value` assignments; return the command words. */\nfunction commandWords(words: string[]): string[] {\n let i = 0\n while (i < words.length) {\n const w = words[i]\n if (SHELL_KEYWORDS_SKIP.has(w)) return []\n if (SHELL_KEYWORDS_STRIP.has(w) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(w)) { i++; continue }\n break\n }\n return words.slice(i)\n}\n\n/** `git [-C dir] [--flags] <sub> <rest...>` -> { sub, rest }. */\nfunction gitSubcommand(args: string[]): { sub: string | undefined; rest: string[] } {\n let i = 0\n while (i < args.length && args[i].startsWith(\"-\")) i += /^-(C|c)$|^--(git-dir|work-tree|namespace)$/.test(args[i]) ? 2 : 1\n return { sub: args[i], rest: args.slice(i + 1) }\n}\n\n/** Command name without its path: `/usr/bin/git` -> `git`. */\nconst baseName = (w: string) => w.replace(/^.*\\//, \"\")\n\n// ---------------------------------------------------------------- report\n\nconst REPORT_SHELL_COMMANDS = new Set([\n \"ls\", \"pwd\", \"cd\", \"cat\", \"head\", \"tail\", \"wc\", \"grep\", \"egrep\", \"fgrep\", \"rg\", \"fd\", \"tree\",\n \"stat\", \"file\", \"du\", \"df\", \"date\", \"whoami\", \"id\", \"hostname\", \"uname\", \"which\", \"type\",\n \"sort\", \"uniq\", \"cut\", \"tr\", \"diff\", \"cmp\", \"comm\", \"basename\", \"dirname\", \"realpath\",\n \"readlink\", \"jq\", \"column\", \"nl\", \"seq\", \"true\", \"false\", \"test\", \"[\", \"sleep\", \"ps\",\n \"uptime\", \"echo\", \"printf\", \"base64\", \"md5\", \"md5sum\", \"shasum\", \"sha256sum\", \"less\", \"more\",\n \"printenv\", \"dig\", \"nslookup\", \"host\", \"find\", \"git\", \"gh\", \"glab\", \"curl\",\n])\n\nconst GIT_READ = new Set([\n \"status\", \"log\", \"diff\", \"show\", \"rev-parse\", \"ls-files\", \"ls-tree\", \"blame\", \"shortlog\",\n \"describe\", \"cat-file\", \"grep\", \"branch\", \"tag\", \"remote\", \"config\", \"reflog\", \"rev-list\",\n \"merge-base\", \"name-rev\", \"show-ref\", \"for-each-ref\", \"whatchanged\",\n])\nconst GH_READ_ACTIONS = new Set([\"view\", \"list\", \"diff\", \"status\", \"checks\", \"ls\"])\n\nfunction reportShellWord(words: string[]): string | null {\n const [cmd, ...args] = words\n const base = cmd.replace(/^.*\\//, \"\")\n if (!REPORT_SHELL_COMMANDS.has(base)) return `\\`${base}\\` is not a read-only command`\n const has = (re: RegExp) => args.some((a) => re.test(a))\n switch (base) {\n case \"find\":\n if (has(/^-(exec|execdir|ok|okdir|delete|fprint|fprint0|fprintf|fls)$/)) return \"find with -exec/-delete\"\n return null\n case \"sort\":\n if (has(/^(-o|--output)/)) return \"sort -o writes a file\"\n return null\n case \"git\": {\n if (has(/^(-c|--exec-path|--output)/)) return \"git option that can execute or write\"\n const { sub, rest } = gitSubcommand(args)\n if (!sub || !GIT_READ.has(sub)) return `git ${sub ?? \"\"} is not read-only`.trim()\n if (sub === \"branch\" && rest.some((a) => /^-(d|D|m|M|c|C|f|u)$|^--(delete|move|copy|force|set-upstream|unset-upstream|edit-description)/.test(a) || !a.startsWith(\"-\"))) {\n return \"git branch that changes branches\"\n }\n if (sub === \"tag\" && rest.some((a) => !/^(-l|--list|-n\\d*|--contains|--points-at|--sort=.*|--merged|--no-merged)$/.test(a))) {\n return \"git tag that creates or deletes tags\"\n }\n if (sub === \"remote\" && rest.length > 0 && !/^(-v|--verbose|show|get-url)$/.test(rest[0])) return \"git remote that changes remotes\"\n if (sub === \"config\" && !rest.some((a) => /^(--get|--get-all|--get-regexp|--list|-l)$/.test(a))) return \"git config write\"\n if (sub === \"reflog\" && rest.length > 0 && !/^(show|-)/.test(rest[0])) return \"git reflog that expires or deletes\"\n return null\n }\n case \"gh\":\n case \"glab\": {\n const [group, action] = args.filter((a) => !a.startsWith(\"-\"))\n if (group === \"search\") return null\n if (group === \"api\") {\n const method = args.findIndex((a) => /^(-X|--method)$/.test(a))\n if (method >= 0 && !/^GET$/i.test(args[method + 1] ?? \"\")) return `${base} api with a non-GET method`\n if (has(/^-X(?!GET$)\\w+|^--method=(?!GET$)/i)) return `${base} api with a non-GET method`\n if (has(/^(-f|-F|--field|--raw-field|--input)/)) return `${base} api with a request body`\n return null\n }\n if (!action || !GH_READ_ACTIONS.has(action)) return `${base} ${group ?? \"\"} ${action ?? \"\"} is not read-only`.replace(/\\s+/g, \" \").trim()\n return null\n }\n case \"curl\": {\n const m = args.findIndex((a) => /^(-X|--request)$/.test(a))\n if (m >= 0 && !/^(GET|HEAD|OPTIONS)$/i.test(args[m + 1] ?? \"\")) return \"curl with a non-GET method\"\n if (has(/^-X(?!GET$|HEAD$)\\w+|^--request=(?!GET$|HEAD$)/i)) return \"curl with a non-GET method\"\n if (has(/^(-d|--data|--data-\\w+|--json|-F|--form|-T|--upload-file|-o|--output|-O|--remote-name|-K|--config)/)) {\n return \"curl that sends a body or writes a file\"\n }\n return null\n }\n default:\n return null\n }\n}\n\n/** Redirects that write somewhere other than /dev/null or another fd. */\nfunction hasWritingRedirect(view: string): boolean {\n const cleaned = view\n .replace(/\\d*>>?\\s*\\/dev\\/null/g, \" \")\n .replace(/&>>?\\s*\\/dev\\/null/g, \" \")\n .replace(/\\d*>&\\s*\\d+/g, \" \")\n return /[>]/.test(cleaned)\n}\n\nfunction reportBash(command: string): AutonomyDecision {\n const view = shellView(command)\n if (view === null) return block(\"report\", \"shell\", \"command too irregular to verify as read-only\")\n if (hasWritingRedirect(view)) return block(\"report\", \"shell\", \"output redirection writes a file\")\n for (const seg of shellSegments(view)) {\n const words = commandWords(seg)\n if (words.length === 0) continue\n const why = reportShellWord(words)\n if (why) return block(\"report\", \"shell\", why)\n }\n return ALLOW\n}\n\nfunction reportTool(input: AutonomyInput): AutonomyDecision {\n if (WRITE_TOOLS.has(input.tool)) return block(\"report\", \"write\", `${input.tool} modifies files`)\n if (input.tool === \"Bash\") return reportBash(input.command ?? \"\")\n if (REPORT_SAFE_TOOLS.has(input.tool)) return ALLOW\n if (input.tool.startsWith(\"mcp__\")) {\n const words = mcpActionWords(input.tool)\n const mutating = words.find((w) => MUTATING_VERBS.has(w))\n if (mutating) return block(\"report\", \"outward\", `tool \"${input.tool}\" can change state (${mutating})`)\n if (words.some((w) => READ_VERBS.has(w))) return ALLOW\n return block(\"report\", \"outward\", `tool \"${input.tool}\" is not recognisably read-only`)\n }\n return block(\"report\", \"tool\", `tool \"${input.tool}\" is not on the read-only list`)\n}\n\n// ---------------------------------------------------------------- propose\n\ninterface ShellRule { id: string; re: RegExp; reason: string }\n\n/** Content rules, matched against the RAW command: quoting is how these\n * payloads are delivered (`psql -c 'DROP TABLE x'`), not a disclaimer. */\nconst PROPOSE_RAW_RULES: ShellRule[] = [\n { id: \"merge\", re: /merge_when_pipeline_succeeds|\\bauto[_-]merge\\b/i, reason: \"auto-merging is an act-level action\" },\n { id: \"merge\", re: /\\b(curl|wget|http|gh\\s+api|glab\\s+api)\\b[^\\n]*\\/merges?\\b/i, reason: \"calling a merge endpoint is an act-level action\" },\n { id: \"delete\", re: /(?:^|\\W)(drop|truncate)\\s+(table|database|schema|index|collection)\\b|(?:^|\\W)delete\\s+from\\b|\\bflushall\\b|\\bflushdb\\b/i, reason: \"destroying data is an act-level action\" },\n { id: \"delete\", re: /(-X|--request)[\\s=]*['\"]?DELETE\\b/i, reason: \"HTTP DELETE is an act-level action\" },\n { id: \"delegate\", re: /\\b(curl|wget|http)\\b[^\\n]*(localhost|127\\.0\\.0\\.1|\\[::1\\])[^\\n]*\\/(ask|task|send|chat|mesh|workflows?|crons?|reload|config)\\b/i, reason: \"calling the local daemon to dispatch work escapes this routine's limit\" },\n]\n\n/** Command rules, matched against one simple command (quoted text blanked). */\nconst PROPOSE_COMMAND_RULES: ShellRule[] = [\n { id: \"merge\", re: /^(gh\\s+pr\\s+merge|glab\\s+mr\\s+merge)\\b/i, reason: \"merging is an act-level action\" },\n { id: \"delete\", re: /^rm\\s+(.*\\s)?(-\\w*[rR]\\w*|--recursive)\\b|^(shred|dropdb)\\b|^find\\b.*\\s-delete\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"delete\", re: /^git\\s+(clean\\s+-\\w*f|reset\\s+--hard|branch\\s+(-\\w*[dD]\\w*|--delete)|tag\\s+(-d|--delete)|stash\\s+(drop|clear)|remote\\s+(remove|rm))\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"delete\", re: /^(gh|glab)\\s+\\S+\\s+delete\\b|^docker\\s+(rm|rmi|volume\\s+rm|system\\s+prune)\\b|^(kubectl\\s+delete|aws\\s+s3\\s+(rm|rb)|gsutil\\s+rm)\\b|^doctl\\s+.*\\sdelete\\b/i, reason: \"deleting is an act-level action\" },\n { id: \"deploy\", re: /^(kubectl\\s+(apply|rollout|scale|set|patch|replace|create|edit)|helm\\s+(install|upgrade|rollback|uninstall|delete)|terraform\\s+(apply|destroy|import|taint)|pulumi\\s+(up|destroy)|docker\\s+push|netlify\\s+deploy|fly(ctl)?\\s+deploy|serverless\\s+deploy|vercel\\b.*--prod)\\b/i, reason: \"deploying is an act-level action\" },\n { id: \"deploy\", re: /^((npm|pnpm|yarn|bun)(\\s+run)?|make|just|task|rake)\\s+(\\S+:)?deploy\\b|^((ba|z)?sh|node|python3?)\\s+\\S*deploy[^\\s/]*$|^\\S*\\/deploy(\\.\\w+)?\\b|^deploy(\\.\\w+)?\\b/i, reason: \"deploying is an act-level action\" },\n { id: \"deploy\", re: /^((npm|pnpm|yarn|bun)\\s+publish|cargo\\s+publish|twine\\s+upload|(gh|glab)\\s+release\\s+(create|upload|edit)|(npx\\s+)?prisma\\s+(migrate\\s+(deploy|reset)|db\\s+push))\\b/i, reason: \"publishing or migrating is an act-level action\" },\n { id: \"prod\", re: /^(ssh|scp|sudo|doas|systemctl|launchctl|service|kill|pkill|killall|reboot|shutdown)\\b|^rsync\\b.*\\s\\S+:\\S*/i, reason: \"operating hosts and services is an act-level action\" },\n { id: \"delegate\", re: /^(agentx|agentix)\\s+(ask|send|task|exec|run|chat|mesh|cron|workflow|daemon|config)\\b/i, reason: \"handing work to another agent or reconfiguring the daemon escapes this routine's limit\" },\n]\n\nconst PROTECTED_BRANCH = /^(main|master|trunk|develop|development|prod|production|staging|stable|release([/-].*)?|HEAD|@)$/i\n/** `git push` options that consume the next word. */\nconst PUSH_VALUE_OPTS = /^(-o|--push-option|--repo|--receive-pack|--exec)$/\n\n/** A push may only name feature branches explicitly — no force, no delete,\n * no mirror/tags, no protected destinations, no implicit \"current branch\". */\nfunction proposeGitPush(rest: string[]): AutonomyDecision | null {\n const positional: string[] = []\n for (let i = 0; i < rest.length; i++) {\n const a = rest[i]\n if (PUSH_VALUE_OPTS.test(a)) { i++; continue }\n if (/^(--force.*|-d|--delete|--mirror|--all|--tags|--prune)$/.test(a) || /^-[a-zA-Z]*f/.test(a)) {\n return block(\"propose\", \"push\", \"force, delete, mirror and tag pushes are act-level actions\")\n }\n if (!a.startsWith(\"-\")) positional.push(a)\n }\n const refspecs = positional.slice(1)\n if (refspecs.length === 0) return block(\"propose\", \"push\", \"name the feature branch explicitly: git push <remote> <branch>\")\n for (const ref of refspecs) {\n if (ref.startsWith(\"+\") || ref.startsWith(\":\")) return block(\"propose\", \"push\", `refspec \"${ref}\" force-pushes or deletes`)\n const name = (ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref).replace(/^refs\\/heads\\//, \"\")\n if (PROTECTED_BRANCH.test(name)) return block(\"propose\", \"push\", `pushing to \"${name}\" is an act-level action; push a feature branch and open a merge request`)\n }\n return null\n}\n\nfunction proposeBash(command: string): AutonomyDecision {\n for (const rule of PROPOSE_RAW_RULES) {\n if (rule.re.test(command)) return block(\"propose\", rule.id, rule.reason)\n }\n const view = shellView(command)\n if (view === null) return block(\"propose\", \"shell\", \"command too irregular to verify\")\n for (const seg of shellSegments(view)) {\n const words = commandWords(seg)\n if (words.length === 0) continue\n const line = [baseName(words[0]), ...words.slice(1)].join(\" \")\n for (const rule of PROPOSE_COMMAND_RULES) {\n if (rule.re.test(line)) return block(\"propose\", rule.id, rule.reason)\n }\n if (baseName(words[0]) === \"git\") {\n const { sub, rest } = gitSubcommand(words.slice(1))\n if (sub === \"push\") {\n const hit = proposeGitPush(rest)\n if (hit) return hit\n }\n }\n }\n return ALLOW\n}\n\nfunction proposeTool(input: AutonomyInput): AutonomyDecision {\n if (input.tool === \"Bash\") return proposeBash(input.command ?? \"\")\n if (input.tool.startsWith(\"mcp__\")) {\n const hit = mcpActionWords(input.tool).find((w) => DESTRUCTIVE_VERBS.has(w))\n if (hit) return block(\"propose\", \"outward\", `tool \"${input.tool}\" performs an act-level action (${hit})`)\n if (isDelegation(mcpActionWords(input.tool))) {\n return block(\"propose\", \"delegate\", `tool \"${input.tool}\" hands work to another agent, which would run at its own full autonomy`)\n }\n }\n return ALLOW\n}\n\n/** Handing the task to another agent escapes the limit: that agent's run\n * is not restricted. */\nfunction isDelegation(words: string[]): boolean {\n if (words.includes(\"delegate\") || words.includes(\"handoff\")) return true\n if (words.includes(\"agent\") && words.some((w) => w === \"send\" || w === \"ask\" || w === \"message\" || w === \"task\")) return true\n return words.includes(\"task\") && !words.some((w) => READ_VERBS.has(w))\n}\n\n// ---------------------------------------------------------------- entry\n\n/** Judge one tool call against an autonomy level. `act` allows everything. */\nexport function evaluateAutonomy(level: AutonomyLevel, input: AutonomyInput): AutonomyDecision {\n if (level === \"report\") return reportTool(input)\n if (level === \"propose\") return proposeTool(input)\n return ALLOW\n}\n\n/** One-paragraph brief prepended to a restricted task, so the model knows\n * the boundary up front instead of discovering it by being blocked. The\n * enforcement does not depend on it. */\nexport function autonomyBrief(level: AutonomyLevel): string {\n if (level === \"report\") {\n return \"[Autonomy: report] This routine runs read-only. Investigate and report; do not modify files, run mutating commands, or post anywhere. Your final answer is the deliverable. Blocked actions are enforced and logged; if something needs doing, describe it in the report instead.\"\n }\n if (level === \"propose\") {\n return \"[Autonomy: propose] You may edit files, commit, push a named feature branch, and open a merge request or draft. You may not merge, deploy, delete, force-push, push to protected branches, or operate hosts. These limits are enforced and logged; leave act-level steps as clear recommendations.\"\n }\n return \"\"\n}\n","// --- Keyboard shortcuts for AgentX Voice, as stored in agentx.json ---\n//\n// A shortcut is written as modifiers and one key joined by \"+\", for\n// example \"opt+space\", \"cmd+opt+period\" or \"ctrl+opt+1\". The Mac app\n// (apps/mac-voice Hotkey.swift) reads the same form. Stored in one\n// normal order (ctrl, opt, shift, cmd, then the key) so two ways of\n// writing a shortcut compare equal.\n\nconst MODIFIERS: Record<string, \"ctrl\" | \"opt\" | \"shift\" | \"cmd\"> = {\n ctrl: \"ctrl\", control: \"ctrl\",\n opt: \"opt\", option: \"opt\", alt: \"opt\",\n shift: \"shift\",\n cmd: \"cmd\", command: \"cmd\",\n}\nconst ORDER = [\"ctrl\", \"opt\", \"shift\", \"cmd\"] as const\n\nconst NAMED_KEYS = [\n \"space\", \"period\", \"comma\", \"slash\", \"semicolon\", \"quote\", \"minus\", \"equal\",\n \"leftbracket\", \"rightbracket\", \"backslash\", \"grave\", \"return\", \"tab\",\n]\nconst KEY_ALIASES: Record<string, string> = { \".\": \"period\", \",\": \"comma\", \"/\": \"slash\", \";\": \"semicolon\", \"'\": \"quote\", \"-\": \"minus\", \"=\": \"equal\", \"`\": \"grave\", enter: \"return\" }\n\nconst isFKey = (k: string) => /^f([1-9]|1[0-9]|20)$/.test(k)\nconst isKey = (k: string) => /^[a-z0-9]$/.test(k) || NAMED_KEYS.includes(k) || isFKey(k)\n\nexport type HotkeyParse = { ok: true; value: string } | { ok: false; error: string }\n\n/** A shortcut in its stored form, or why it cannot be one. */\nexport function parseHotkey(input: string): HotkeyParse {\n const raw = String(input ?? \"\").trim().toLowerCase()\n if (!raw) return { ok: false, error: \"is empty\" }\n // \"+\" itself is not a key we accept, so splitting on it is safe.\n const parts = raw.split(\"+\").map((p) => p.trim())\n if (parts.some((p) => !p)) return { ok: false, error: `\"${input}\" has an empty part; write it like opt+space` }\n const key = KEY_ALIASES[parts[parts.length - 1]] ?? parts[parts.length - 1]\n const mods = new Set<string>()\n for (const p of parts.slice(0, -1)) {\n const m = MODIFIERS[p]\n if (!m) return { ok: false, error: `\"${p}\" is not a modifier; use ctrl, opt, shift or cmd` }\n if (mods.has(m)) return { ok: false, error: `\"${input}\" names ${m} twice` }\n mods.add(m)\n }\n if (!isKey(key)) return { ok: false, error: `\"${key}\" is not a key AgentX Voice can use; use a letter, a digit, f1 to f20, or space, period, comma, slash, return, tab` }\n // Without ctrl, opt or cmd the shortcut would swallow ordinary typing.\n if (!isFKey(key) && ![\"ctrl\", \"opt\", \"cmd\"].some((m) => mods.has(m))) {\n return { ok: false, error: `\"${input}\" needs ctrl, opt or cmd, or it would take that key away from your typing` }\n }\n return { ok: true, value: [...ORDER.filter((m) => mods.has(m)), key].join(\"+\") }\n}\n\n/** Zod refinement message helper: undefined when fine. */\nexport function hotkeyError(input: string): string | undefined {\n const r = parseHotkey(input)\n return r.ok ? undefined : r.error\n}\n\n/** \"⌃⌥1\" for \"ctrl+opt+1\", as the Mac shows shortcuts. */\nexport function describeHotkey(value: string): string {\n const sym: Record<string, string> = { ctrl: \"⌃\", opt: \"⌥\", shift: \"⇧\", cmd: \"⌘\" }\n const names: Record<string, string> = { space: \"Space\", period: \".\", comma: \",\", slash: \"/\", semicolon: \";\", quote: \"'\", minus: \"-\", equal: \"=\", leftbracket: \"[\", rightbracket: \"]\", backslash: \"\\\\\", grave: \"`\", return: \"Return\", tab: \"Tab\" }\n const parts = value.split(\"+\")\n const key = parts.pop() ?? \"\"\n return parts.map((m) => sym[m] ?? m).join(\"\") + (names[key] ?? key.toUpperCase())\n}\n\nexport const DEFAULT_HOTKEYS = { talk: \"opt+space\", stop: \"cmd+opt+period\", paste: \"cmd+opt+v\" } as const\n","// --- The voice orb's colour palettes, drawn from nature ---\n//\n// Each agent's orb in AgentX Voice flows through one of these gradients.\n// An agent picks one with presence.palette; without one it gets the\n// palette whose hue is nearest its presence colour, so it stays\n// recognisable as the same agent as its on-screen pointer. The app draws\n// whatever colours the daemon sends, so this file is the only list.\n\nexport interface OrbPalette {\n id: string\n label: string\n /** Five stops, deep to light. The orb's mesh uses all five; the last\n * is its bright core. */\n colors: [string, string, string, string, string]\n /** The hue (0–360) an agent colour is matched against. */\n hue: number\n}\n\nexport const ORB_PALETTES: OrbPalette[] = [\n { id: \"sunrise\", label: \"Sunrise\", hue: 18, colors: [\"#E8505B\", \"#F2726F\", \"#F79A5A\", \"#FBBF4A\", \"#FFE3A3\"] },\n { id: \"desert\", label: \"Desert\", hue: 36, colors: [\"#A4492C\", \"#C8683E\", \"#D9905E\", \"#E7B98A\", \"#F6E3C4\"] },\n { id: \"forest\", label: \"Forest\", hue: 100, colors: [\"#2F5D34\", \"#4C7D3A\", \"#6FA046\", \"#9CC25E\", \"#D5EBA4\"] },\n { id: \"lagoon\", label: \"Lagoon\", hue: 172, colors: [\"#0B6E73\", \"#0E9594\", \"#1FBFB2\", \"#56DCCB\", \"#B8F4EA\"] },\n { id: \"ocean\", label: \"Ocean\", hue: 205, colors: [\"#15457E\", \"#1C6BA8\", \"#2B93CF\", \"#5DBBE8\", \"#BFE6FA\"] },\n { id: \"dusk\", label: \"Dusk\", hue: 268, colors: [\"#2E2A7A\", \"#5B3E9E\", \"#8C4FB0\", \"#C8649E\", \"#F4A7B9\"] },\n { id: \"blossom\", label: \"Blossom\", hue: 330, colors: [\"#A3245B\", \"#CF3F78\", \"#E8699A\", \"#F49BB8\", \"#FFD6E0\"] },\n]\n\nexport const ORB_PALETTE_IDS = ORB_PALETTES.map((p) => p.id) as [string, ...string[]]\n\n/** #RRGGBB to its hue in degrees, or null when it is grey or not a colour. */\nfunction hueOf(hex: string): number | null {\n const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex)\n if (!m) return null\n const [r, g, b] = m.slice(1).map((x) => parseInt(x, 16) / 255)\n const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min\n if (d < 0.04) return null\n const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4\n return (h * 60 + 360) % 360\n}\n\n/** The palette nearest an agent colour by hue. Grey or invalid: lagoon. */\nexport function paletteForColor(hex: string): OrbPalette {\n const hue = hueOf(hex)\n if (hue === null) return ORB_PALETTES.find((p) => p.id === \"lagoon\")!\n let best = ORB_PALETTES[0], bestDistance = 360\n for (const p of ORB_PALETTES) {\n const d = Math.abs(p.hue - hue)\n const distance = Math.min(d, 360 - d)\n if (distance < bestDistance) { best = p; bestDistance = distance }\n }\n return best\n}\n\n/** An agent's palette: the one it chose (presence.palette), else the one\n * nearest its colour (presenceLook's). `set` says which. */\nexport function agentPalette(chosen: string | undefined, color: string): OrbPalette & { set: boolean } {\n const picked = ORB_PALETTES.find((p) => p.id === chosen)\n return picked ? { ...picked, set: true } : { ...paletteForColor(color), set: false }\n}\n","import { z } from \"zod\"\n\n// --- WhatsApp inbound triage settings (agentx.json → whatsappTriage) ---\n//\n// wacli posts each new WhatsApp message to POST /webhook/wacli. A watch\n// rule picks the messages an agent should look at; everything else is\n// dropped without being stored. Nothing is ever sent to the contact\n// unless the owner approves it (see drafts.ts).\n\nconst hhmm = z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/, \"use HH:MM, 24-hour\")\n\nexport const watchRuleSchema = z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, \"lowercase letters, digits, - and _\"),\n enabled: z.boolean().default(true),\n /** Chats to watch: a contact's or a group's JID, or a phone number. */\n chats: z.array(z.string().min(1)).default([]),\n /** Only messages from these people (JID or phone number), in any chat\n * the rule covers. Empty: anyone. */\n senders: z.array(z.string().min(1)).default([]),\n /** The agent that triages the messages. */\n agent: z.string().min(1),\n /** Extra instructions for the agent: who this contact is, where issues\n * go, the tone of a reply. */\n prompt: z.string().max(4000).optional(),\n /** No notifications between these times. Triage and drafts still happen. */\n quietHours: z.object({ start: hhmm, end: hhmm }).optional(),\n /** Send the agent's short acknowledgement without asking. Needs\n * whatsappTriage.allowAutoAck too. */\n autoAck: z.boolean().default(false),\n}).refine((r) => r.chats.length > 0 || r.senders.length > 0, {\n message: \"a rule needs at least one chat or sender\",\n})\n\nexport const whatsappTriageSchema = z.object({\n enabled: z.boolean().default(false),\n /** Environment variable holding the webhook secret given to\n * `wacli sync --webhook-secret`. Unsigned requests are refused. */\n secretEnv: z.string().regex(/^[A-Z_][A-Z0-9_]*$/).default(\"WACLI_WEBHOOK_SECRET\"),\n /** Messages from one chat within this many seconds become one task. */\n batchSeconds: z.number().int().min(0).max(600).default(20),\n /** Time zone for quiet hours. Default: this computer's. */\n timezone: z.string().optional(),\n /** Second switch for rules with autoAck. Both must be on. */\n allowAutoAck: z.boolean().default(false),\n /** Download images and voice notes so the agent can read or hear them. */\n describeMedia: z.boolean().default(true),\n wacli: z.object({\n bin: z.string().default(\"wacli\"),\n /** `wacli --account NAME`, when more than one is paired. */\n account: z.string().optional(),\n /** `wacli --store DIR`. */\n store: z.string().optional(),\n }).default({}),\n rules: z.array(watchRuleSchema).default([]),\n}).default({})\n\nexport type WatchRule = z.infer<typeof watchRuleSchema>\nexport type WhatsappTriageConfig = z.infer<typeof whatsappTriageSchema>\nexport type WacliSettings = WhatsappTriageConfig[\"wacli\"]\n","import { z } from \"zod\"\nimport { readFileSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { businessConfigSchema } from \"@/business/config\"\nimport { boardsConfigSchema, dashboardConfigSchema } from \"@/boards/config\"\nimport { autonomyLevelSchema } from \"@/guard/autonomy\"\nimport { DEFAULT_HOTKEYS, hotkeyError } from \"@/voice/hotkey\"\nimport { ORB_PALETTE_IDS } from \"@/voice/orb-palettes\"\nimport { whatsappTriageSchema } from \"@/whatsapp-triage/config\"\n\n/**\n * Load .env file into process.env (simple, no dependency).\n */\nfunction loadDotEnv(dir: string): void {\n const envPath = resolve(dir, \".env\")\n if (!existsSync(envPath)) return\n\n const content = readFileSync(envPath, \"utf-8\")\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith(\"#\")) continue\n const eqIdx = trimmed.indexOf(\"=\")\n if (eqIdx === -1) continue\n const key = trimmed.slice(0, eqIdx).trim()\n const value = trimmed.slice(eqIdx + 1).trim()\n if (!process.env[key]) {\n process.env[key] = value\n }\n }\n}\n\n// --- Daemon configuration schema & loader ---\n\nconst providerConfigSchema = z.object({\n apiKey: z.string().optional(),\n defaultModel: z.string().optional(),\n baseUrl: z.string().optional(),\n /** Toggle thinking-mode output on backends that support it (DeepSeek\n * V4 `reasoning_content`). When `true` (the DeepSeek default), the\n * agent streams its reasoning live in the dashboard task modal and\n * the agentic round-trip echoes it back on the next iteration. Set\n * to `false` to disable for cost/latency-sensitive agents. Ignored\n * on backends that don't speak the thinking-mode protocol. */\n thinking: z.boolean().optional(),\n})\n\nconst mcpStdioServerSchema = z.object({\n type: z.literal(\"stdio\").optional(),\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: z.record(z.string(), z.string()).optional(),\n})\n\nconst mcpHttpServerSchema = z.object({\n type: z.literal(\"http\"),\n url: z.string().url(),\n headers: z.record(z.string(), z.string()).optional(),\n})\n\n// HTTP variant first so a record with `type: \"http\"` matches the HTTP\n// shape; stdio is the default fallback when `type` is absent (keeps the\n// original `{ command, args, env }` configs valid without a migration).\nconst mcpServerSchema = z.union([mcpHttpServerSchema, mcpStdioServerSchema])\n\n/**\n * Per-agent integration registration. Declares which third-party services\n * an agent has credentials for — e.g. \"@cx-bot has a Telegram bot token,\n * a HubSpot private app token, and a Gmail account\". The actual secret is\n * NEVER stored in agentx.json: only an env-var reference (`tokenEnv`) or a\n * keyring directive. Skills, channel adapters, and the action layer read\n * from this registry to discover what an agent can use.\n *\n * The `kind` field is open-string (well-known values listed below in\n * INTEGRATION_KINDS) so new services can be declared without a schema\n * bump. Doctor warns on unknown kinds.\n */\nconst integrationCredentialsSchema = z.object({\n /** Env var holding the secret. Uppercase identifier; daemon resolves at use-time. */\n tokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n /** Alternate env-var keys for credential schemes that need >1 secret\n * (e.g. HubSpot private app + portal id, OAuth refresh tokens). */\n privateAppTokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n apiKeyEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n refreshTokenEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n clientIdEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n clientSecretEnv: z.string().regex(/^[A-Z][A-Z0-9_]*$/).optional(),\n /** OS keyring directive — credential lives in macOS Keychain / Linux\n * Secret Service / Windows Credential Manager. The skill that reads\n * this integration is responsible for resolving the keyring entry\n * (typically keyed by agentId+kind). */\n auth: z.literal(\"keyring\").optional(),\n /** File-based session directory (WhatsApp, Telegram MTProto, etc.). */\n sessionDir: z.string().optional(),\n}).strict()\n\nconst integrationSchema = z.object({\n /** Service identifier — open string, well-known values in INTEGRATION_KINDS. */\n kind: z.string().min(1),\n /** Human-readable label (e.g. \"@cx_bot\", \"Acme CRM\", \"alex@example.com\"). Unique per (agent, kind). */\n label: z.string().min(1),\n credentials: integrationCredentialsSchema.default({}),\n /** Non-secret metadata — username, email, host URL, portal id, JID, etc.\n * Visible in the dashboard and to skills. */\n metadata: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),\n /** Operator-set toggle without removing the entry. */\n enabled: z.boolean().default(true),\n})\n\nexport type Integration = z.infer<typeof integrationSchema>\n\n/**\n * Canonical kind list — for autocomplete + doctor validation. Open string\n * schema so new services drop in without a bump; doctor warns when a kind\n * is outside this list.\n */\nexport const INTEGRATION_KINDS = [\n // Inbound channels\n \"telegram-bot\",\n \"whatsapp\",\n // Code platforms (user-scoped tokens, not channel routing)\n \"gitlab-user\",\n \"github-user\",\n // Email\n \"gmail\",\n \"hotmail\",\n \"smtp\",\n // CRM / ERP\n \"hubspot\",\n \"salesforce\",\n \"pipedrive\",\n \"odoo\",\n // Project management\n \"trello\",\n \"linear\",\n \"asana\",\n \"jira\",\n \"notion\",\n // Payments\n \"stripe\",\n // Observability / hosting\n \"sentry\",\n \"vercel\",\n // Voice / SMS\n \"twilio\",\n // Catch-all\n \"custom\",\n] as const\n\nconst voiceProviderSchema = z.enum([\"system\", \"elevenlabs\"])\n\n/** A macOS voice: a name (\"Daniel\", \"Ava (Premium)\") or identifier;\n * \"system\" for the OS default voice (the only way to get a Siri voice);\n * or one per language, picked by the language of each line:\n * { \"en\": \"Samantha\", \"fr\": \"Thomas\", \"ar\": \"Majed\" }. */\nconst systemVoiceSchema = z.union([z.string(), z.record(z.string(), z.string())])\n\n/** A keyboard shortcut for AgentX Voice, e.g. \"opt+space\" or\n * \"ctrl+opt+1\". See src/voice/hotkey.ts. */\nconst hotkeySchema = z.string().superRefine((s, ctx) => {\n const error = hotkeyError(s)\n if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `shortcut ${error}` })\n})\n\nconst voiceSchema = z.object({\n /** Overrides the global voice.provider for this agent. */\n provider: voiceProviderSchema.optional(),\n /** See systemVoiceSchema. Unset: one is assigned, of the agent's\n * gender when set, different from every other agent's. */\n system: systemVoiceSchema.optional(),\n /** Voices to try, in order, when `system` names one that is not\n * installed (e.g. [\"Ava (Premium)\", \"Allison\"]). Unset, or none\n * installed: the best installed voice of its language and gender. */\n fallbacks: z.array(z.string().min(1)).optional(),\n elevenlabsVoiceId: z.string().optional(),\n gender: z.enum([\"female\", \"male\", \"neutral\"]).optional(),\n /** A few words on manner, e.g. \"warm, upbeat, a little playful\". */\n style: z.string().optional(),\n /** The one-line self-introduction used on first contact. */\n intro: z.string().optional(),\n /** Speak short updates from this agent's real tool steps while it\n * works: \"on\" for everything but cron, \"all\" to include cron. */\n narrate: z.enum([\"off\", \"on\", \"all\"]).optional(),\n /** Speaking speed, 1 = normal. System voices: 175 words a minute times\n * this. ElevenLabs accepts 0.7 to 1.2 and is held to that range. */\n rate: z.number().min(0.75).max(1.5).optional(),\n /** Place in the speaking queue: \"high\" lines go ahead of waiting\n * \"normal\" ones, \"low\" lines after them. Unset: normal. */\n priority: z.enum([\"high\", \"normal\", \"low\"]).optional(),\n /** AgentX Voice: hold this shortcut and speak to ask this agent, without\n * changing the agent picked in the menu. */\n hotkey: hotkeySchema.optional(),\n})\n\n/** One event subscription (src/events/subscriptions.ts). An envelope\n * matches when its kind or type is in `kinds` and every other set filter\n * agrees. Every subscription is readable with `agentx_events`; `digest`\n * also briefs a fresh session and `wake` also starts a turn. */\nexport const eventSubscriptionSchema = z.object({\n /** Envelope `kind` (\"agent\", \"run\") or `type` (\"task:completed\"); \"*\" matches all. */\n kinds: z.array(z.string().min(1)).min(1),\n /** Only events published for these agent ids. */\n agents: z.array(z.string().min(1)).optional(),\n /** Only events published by these nodes (`node.name`). */\n nodes: z.array(z.string().min(1)).optional(),\n /** Only events whose summary contains this text (case-insensitive). */\n match: z.string().min(1).optional(),\n delivery: z.enum([\"pull\", \"digest\", \"wake\"]).default(\"pull\"),\n /** wake only: no wake when the agent was already woken this many times\n * in the past hour. */\n maxPerHour: z.number().int().min(1).max(60).default(4),\n})\n\nconst agentConfigSchema = z.object({\n name: z.string(),\n workspace: z.string(),\n tier: z.enum([\"claude-code\", \"codex-cli\", \"opencode\", \"sdk\", \"orchestrator\"]).default(\"claude-code\"),\n provider: z.string().optional(),\n model: z.string().optional(),\n systemPrompt: z.string().optional(),\n mentions: z.array(z.string()).default([]),\n /** Phase 5 — typed capabilities (drop-condition fallback). Free-form\n * list of intent strings this agent is allowed to handle. When set,\n * the org-chart `canHandle(agentId, project, intent)` check rejects\n * dispatches with intents not in this list. When empty/unset\n * (the default), the agent is permissive — handles any intent.\n * Intent matching is exact-string for now; a glob/prefix layer can\n * come later if it produces real rejections.\n * Example: [\"issue.opened\", \"issue.commented\", \"merge_request.opened\"]\n * Example: [\"cron.fired\", \"message.received\"] */\n intents: z.array(z.string()).default([]),\n /** Phase 8 — capability-bounded security. Max distinct upstream\n * agents in the delegation chain on the same (project, subject)\n * before a dispatch to THIS agent is refused. The ledger itself\n * provides the chain — `decideAndCommit` walks recent decisions on\n * the subject and counts distinct agents. Default 5; set to 0 to\n * disable for an agent that's always called as the bottom of a\n * chain. The check prevents cascade loops where A → B → A → B → ...\n * blows past sane chain depth. */\n maxDelegationDepth: z.number().int().min(0).max(50).default(5),\n /** MCP servers this agent's Claude Code session should load. Synced\n * to <workspace>/.mcp.json at daemon boot via agent-mcp.ts. Operator\n * edits to .mcp.json are respected (see SyncResult.skipped-operator-owned). */\n mcp: z.record(z.string(), mcpServerSchema).optional(),\n /** Enable CodeGraph (https://github.com/colbymchenry/codegraph) for this\n * agent's claude-code or codex-cli workspace. When true, agentx (a) adds\n * a codegraph MCP server to <workspace>/.mcp.json, (b) extends\n * .claude/settings.json permissions.allow with the codegraph_* tools,\n * (c) appends a CodeGraph instruction section to the managed CLAUDE.md,\n * and (d) background-indexes the workspace at daemon boot if .codegraph/\n * is missing. Off by default — flip on for coding agents (globex-v2-coder,\n * initech-v2-coder, umbrella-coding, etc.) where token-volume on exploration\n * loops is the bottleneck. */\n codegraph: z.boolean().default(false),\n /** Per-agent override for the global `session.contextStrategy`. Lets\n * one agent run `planner` (smaller upfront context, more tool-driven\n * exploration) while siblings stay on `layered`. Used for agents that\n * consistently bloat their cache via large workspace reads. */\n contextStrategy: z.enum([\"layered\", \"planner\"]).optional(),\n /** When true, the registry resolves references-recipes for this agent's\n * workspace and renders a deterministic [Verified References] block at\n * priority 4.7. Off by default — flip on per agent (pm-initech, devops-agent,\n * etc.) once a `references/` registry exists in the agent's workspace\n * or repo root. See src/agents/references/. */\n contextReferences: z.boolean().default(false),\n /** Whether this agent may emit in-band `agentx:ui` rich-message directives\n * (buttons/polls/media) on chat channels. Default true — set false to make\n * the render layer strip any directive and send plain text only. */\n richMessages: z.boolean().default(true),\n maxConcurrent: z.number().default(1),\n /** Hard wall-clock cap on a single Claude Code invocation. Exceeding the\n * cap sends SIGTERM (exit 143). Default 20 min — bump for devops/coder\n * agents that do long investigations or multi-file refactors. */\n maxExecutionMinutes: z.number().int().min(1).max(240).default(20),\n /** Time a run may spend between taking a slot and starting its agent\n * process (request gate, classifier, compaction, context planning, model\n * routing, dispatch gates). Past it the run is aborted, its slot freed and\n * its record marked `timeout` with the step it was stuck in. Applies to\n * every run, whatever started it. */\n preSpawnTimeoutSec: z.number().int().min(10).max(3600).default(300),\n /** How long a daemon stop waits for this agent's runs before cutting\n * them off, when that is longer than shutdown.drainTimeoutSeconds. For\n * agents whose runs are long (renders, builds). */\n drainTimeoutSeconds: z.number().int().min(0).max(86_400).optional(),\n permissionMode: z.string().default(\"default\"),\n /** How this agent's `claude` CLI is billed (claude-code tier). Default\n * \"subscription\": the shared OAuth login, ANTHROPIC_API_KEY stripped.\n * \"api\": bill ANTHROPIC_API_KEY instead and drop the OAuth token, so\n * e.g. benchmark agents never draw on the fleet's subscription quota.\n * An \"api\" agent with no key fails its task rather than falling back. */\n billing: z.enum([\"subscription\", \"api\"]).default(\"subscription\"),\n /** Improvement plan #3 — tool-use-required preset. When set,\n * AgentX inspects the stream-json events from each task and\n * fails the response with `tool_required_not_called: <name>`\n * when none of the listed tool names was invoked. Catches the\n * silent-degrade pattern observed when a model below the\n * capability bar (e.g. Haiku on a Write-required prompt)\n * produces a plausible-looking text response without ever\n * calling the required tool. Caller can retry with a stronger\n * model or sharpen the prompt.\n *\n * Tool names match the canonical Claude Code names (\"Write\",\n * \"Edit\", \"Bash\", \"Read\", …). Free-form so future tools work\n * without a schema bump. Empty/unset means no enforcement\n * (default — backward compatible). */\n toolUseRequired: z.array(z.string()).default([]),\n /** Per-agent override for the channel-level `autoReplyLegacy` on\n * gitlab/github. When set, it wins over `channels.<name>.autoReplyLegacy`\n * for this agent's replies: `true` makes the daemon auto-post the agent's\n * final text as a comment (right for coder agents that end their turn with\n * a summary and don't call `agentx_channel_reply`); `false` suppresses it\n * (right for chatty agents whose reasoning shouldn't land as a comment).\n * Unset → fall back to the channel default. */\n gitlabAutoReply: z.boolean().optional(),\n /** Opt into process reuse for claude-code (stream-json) or codex-cli\n * (app-server), or opencode (dedicated v2 server). Conversations have isolated processes. Unsupported Codex\n * versions fall back to exec before submitting any turn. Other tiers\n * ignore this flag. Codex loads the operator's Codex config, unlike exec's\n * --ignore-user-config path: review additional MCP servers before enabling.\n * Codex and OpenCode each use an 8-process cap and 5-minute idle eviction; processPool\n * settings apply to Claude only. Default false for gradual rollout.\n * See docs/architecture/persistent-codex-process.md and\n * docs/architecture/persistent-claude-process.md and\n * docs/architecture/persistent-opencode-process.md for details. */\n persistentProcess: z.boolean().default(false),\n queueMode: z.enum([\"collect\", \"followup\", \"drop\"]).default(\"collect\"),\n heartbeat: z.object({\n enabled: z.boolean().default(false),\n intervalMinutes: z.number().default(30),\n prompt: z.string().default(\"Check inbox, pending tasks, and system health. Report anything that needs attention.\"),\n channel: z.string().default(\"heartbeat\"),\n }).default({}),\n /** Reachability via the external public API.\n * - \"private\" (default): this agent is daemon-internal + channel-bound only.\n * - \"public\": external apps can POST /api/public/agents/<id>/messages\n * with a scoped token (agent:<id> or agent:*). */\n access: z.enum([\"private\", \"public\"]).default(\"private\"),\n /** Governance override for agent-facing management tools. An admin agent\n * may pause, resume and request deletion of schedules created by other\n * agents or by the operator. It never approves anything: approval of a\n * create/delete request stays operator-only (`agentx schedule approve`). */\n admin: z.boolean().optional(),\n /** Events on the bus this agent wants to hear about (issue #165). */\n subscriptions: z.array(eventSubscriptionSchema).default([]),\n /** Per-agent third-party integrations registry. Declares which services\n * this agent has credentials for (telegram-bot, hubspot, gitlab-user,\n * gmail, etc.). Secrets stay in env vars / keyring; this block holds\n * declarations + non-secret metadata only. Skills and channel adapters\n * read from here to know what the agent can use. See INTEGRATION_KINDS. */\n integrations: z.array(integrationSchema).default([]),\n /** How this agent sounds when it speaks (voice widget, `agentx teach`).\n * Every field is optional: no voice id falls back to the global\n * AGENTX_VOICE_ID, no intro is derived from the system prompt. See\n * src/voice/agent-voice.ts. */\n voice: voiceSchema.optional(),\n /** How this agent appears on screen: its own cursor, drawn by the Mac\n * helper and click-through, never the person's real mouse. See\n * src/voice/presence.ts. */\n presence: z.object({\n /** Cursor colour, as #RRGGBB. Default: derived from the agent id. */\n color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),\n /** The voice orb's gradient, one of src/voice/orb-palettes.ts.\n * Default: the palette nearest `color`. */\n palette: z.enum(ORB_PALETTE_IDS).optional(),\n /** One or two letters on the cursor. Default: from the name. */\n initial: z.string().max(2).optional(),\n /** Name shown under the cursor. Default: the agent's name. */\n label: z.string().optional(),\n /** May this agent click and type for the person (presence mode \"act\")?\n * Off by default: without it, \"act\" becomes \"teach\". */\n allowActions: z.boolean().optional(),\n }).optional(),\n})\n\nconst telegramAccountSchema = z.object({\n token: z.string(),\n agentBinding: z.string(),\n /** Per-account sender allowlist. When set, OVERRIDES the global\n * `policy.allowFrom`. Entries accept:\n * - numeric user id (\"1816212449\") — matches sender (from.id)\n * - numeric chat id (\"-1003861455814\") — matches chat (chat.id)\n * - \"@username\" — matches sender username\n * A message is dispatched iff at least one entry matches. */\n allowFrom: z.array(z.string()).optional(),\n /** When false, the daemon keeps the bot token registered so outbound\n * `send()` / ring notifications work, but does NOT long-poll for inbound\n * updates. Use this on nodes where the bound agent lives on a different\n * daemon — otherwise two daemons race on the same `getUpdates` cursor and\n * Telegram responds 409 Conflict on every poll.\n * Defaults to true (poll) so existing single-node setups are unchanged. */\n pollInbound: z.boolean().default(true),\n})\n\n/** An agent watching the phone camera (#325 phase 2, src/camera/watch.ts). */\nexport const cameraBotSchema = z.object({\n /** Seconds between frames the agent gets by itself. 0: only when asked\n * (\"Look now\" on the phone, or the agent's own `agentx camera look`).\n * Each frame handed over by itself is a turn of the agent, so keep\n * this high or off. */\n frameIntervalSeconds: z.number().int().min(0).max(3600).default(0),\n /** The agent's watch ends after this many minutes, whatever the phone does. */\n maxSessionMinutes: z.number().int().min(1).max(240).default(10),\n /** Frames are shrunk so their longer side is at most this many pixels\n * before the agent sees them. */\n maxFrameEdge: z.number().int().min(160).max(3840).default(1024),\n /** Keep the frame files in the agent's workspace after the share ends.\n * Off: every frame is deleted when the share ends. */\n keepFrames: z.boolean().default(false),\n}).default({})\n\nexport type CameraBotConfig = z.infer<typeof cameraBotSchema>\n\nconst channelsConfigSchema = z.object({\n telegram: z.object({\n enabled: z.boolean().default(false),\n accounts: z.record(z.string(), telegramAccountSchema).default({}),\n policy: z.object({\n dm: z.enum([\"pair\", \"block\"]).default(\"pair\"),\n group: z.enum([\"mention-required\", \"all\"]).default(\"mention-required\"),\n /** Global sender allowlist applied to every account that doesn't set\n * its own `allowFrom`. When neither is configured, every incoming\n * message is dropped — closed by default. Same entry forms as the\n * per-account list (user id, chat id, @username). */\n allowFrom: z.array(z.string()).optional(),\n }).default({}),\n }).default({}),\n whatsapp: z.object({\n enabled: z.boolean().default(false),\n sessionDir: z.string().default(\".agentx/whatsapp-sessions\"),\n defaultAgent: z.string().optional(),\n allowFrom: z.array(z.string()).optional(),\n routes: z.array(z.object({\n contact: z.string().optional(),\n group: z.string().optional(),\n agent: z.string(),\n })).default([]),\n /** Data-source ingestion — turns WhatsApp from a messaging-only channel\n * into a source that seeds the wiki with contact/group metadata (and\n * optionally bounded message windows) per an explicit allowlist.\n * Default-deny: `enabled: false` and empty allowlists mean nothing is\n * ingested. See docs/reference/whatsapp-ingest.md for the full story. */\n ingest: z.object({\n enabled: z.boolean().default(false),\n /** `metadata-only` pulls contact/group info; `messages` additionally\n * pulls the last `messageCap` messages per allowlisted chat. */\n mode: z.enum([\"metadata-only\", \"messages\"]).default(\"metadata-only\"),\n /** Phone numbers or JIDs. Substring match, same semantics as allowFrom. */\n allowContacts: z.array(z.string()).default([]),\n allowGroups: z.array(z.string()).default([]),\n denyContacts: z.array(z.string()).default([]),\n denyGroups: z.array(z.string()).default([]),\n /** Per-chat cap when mode = \"messages\". Keeps the raw-entry size bounded. */\n messageCap: z.number().int().min(1).max(500).default(50),\n /** Max age (days) of messages to consider for the bounded window. */\n historyDays: z.number().int().min(1).max(365).default(30),\n /** Skip re-writing a contact entry unless this many days have passed\n * OR the profile hash differs. Prevents churn on unchanged profiles. */\n contactRefreshDays: z.number().int().min(1).max(90).default(7),\n /** Safety rails on live Baileys reads — personal-account accounts\n * can get throttled/banned under burst reads. */\n throttle: z.object({\n minMsBetweenCalls: z.number().int().min(100).default(1500),\n maxCallsPerMinute: z.number().int().min(1).default(20),\n maxChatsPerSweep: z.number().int().min(1).default(25),\n }).default({}),\n /** Purge absorbed raw entries older than this many days. `0` = never. */\n retentionDays: z.number().int().min(0).default(0),\n }).default({}),\n }).default({}),\n gitlab: z.object({\n enabled: z.boolean().default(false),\n webhookPort: z.number().default(18810),\n webhookSecret: z.string().optional(),\n host: z.string().default(\"https://gitlab.com\"),\n token: z.string().optional(),\n /** Legacy auto-reply: when true (default), the router posts the agent's\n * `response.content` as a comment automatically. When false, the agent\n * must call the `channel.reply` action explicitly to reply — agent\n * reasoning text is logged but not posted. Flip to false once the\n * project's agents have migrated their gitlab skill to use channel.reply.\n * Default true preserves today's behaviour for unmigrated projects. */\n autoReplyLegacy: z.boolean().default(true),\n routes: z.array(z.object({\n project: z.string(),\n agent: z.string(),\n })).default([]),\n agentMappings: z.array(z.object({\n agentId: z.string(),\n gitlabUsernames: z.array(z.string()).default([]),\n keywords: z.array(z.string()).default([]),\n token: z.string().optional(),\n /** If set, the agent lives on a remote mesh peer (node id). Forces the\n * username→agent map to resolve to this mapping even when a local\n * agent's token resolves to the same GitLab user — prevents collisions\n * like two agents both claiming @devops-acme. */\n node: z.string().optional(),\n })).default([]),\n /** Extra GitLab usernames each agent answers to, as prefixes. With\n * [\"team-\"], an agent with no agentMappings row answers to @<id> and\n * @team-<id>. Default: only @<id>. */\n agentUsernamePrefixes: z.array(z.string().min(1)).default([]),\n }).default({}),\n github: z.object({\n enabled: z.boolean().default(false),\n /** Legacy auto-reply — same semantics as gitlab.autoReplyLegacy.\n * Defaults true; set false once agent skills use channel.reply. */\n autoReplyLegacy: z.boolean().default(true),\n /** GitHub PAT or env var (${GITHUB_TOKEN}) for posting comments back. */\n token: z.string().optional(),\n /** Path to file containing the token (first line read at startup). */\n tokenFile: z.string().optional(),\n /** GitHub App ID (legacy issuer). */\n appId: z.number().optional(),\n /** GitHub App Client ID (preferred JWT issuer per GitHub's updated docs). */\n clientId: z.string().optional(),\n /** Path to the GitHub App private key PEM file. */\n privateKeyFile: z.string().optional(),\n /** Webhook secret for validating X-Hub-Signature-256. */\n webhookSecret: z.string().optional(),\n /** Repo → agent routing. Use \"owner/repo\" or \"*\" for default. */\n routes: z.array(z.object({\n repo: z.string(),\n agent: z.string(),\n })).default([]),\n /** Per-agent identity mappings (GitHub usernames, tokens, mesh nodes). */\n agentMappings: z.array(z.object({\n agentId: z.string(),\n githubUsernames: z.array(z.string()).default([]),\n token: z.string().optional(),\n tokenFile: z.string().optional(),\n node: z.string().optional(),\n })).default([]),\n }).default({}),\n /** ntfy push notifications — outbound only. The operator-facing tap on\n * the shoulder: cron failures, task errors, and anything an agent decides\n * is worth interrupting a human for. `chatId` on an outgoing message is\n * the topic; empty falls back to `topic` here. */\n ntfy: z.object({\n enabled: z.boolean().default(false),\n /** Self-hosted ntfy base URL. Defaults to the public server. */\n server: z.string().default(\"https://ntfy.sh\"),\n /** Default topic. Treat it as a secret — on ntfy.sh, knowing the topic\n * is the only thing needed to read or publish to it. */\n topic: z.string().optional(),\n /** Access token for protected topics. */\n token: z.string().optional(),\n /** 1 (min) .. 5 (max). ntfy's own default is 3. */\n defaultPriority: z.number().int().min(1).max(5).default(3),\n defaultTitle: z.string().optional(),\n }).default({}),\n /** Web Push to the phone app (/app) — outbound only. The node that hosts\n * the app holds the subscriptions and sends; any other node sets\n * `relayTo` and forwards over the mesh. `chatId` \"default\" means every\n * subscribed phone, or a device id (tok_…) for one. */\n push: z.object({\n enabled: z.boolean().default(false),\n /** VAPID key pair written by `agentx app push-keys`. Relative paths\n * resolve from the folder AgentX runs in (the one holding agentx.json). */\n keysFile: z.string().default(\".agentx/push-keys.json\"),\n /** Contact for the push services: `mailto:you@example.com` or an\n * https:// URL. Required on the hosting node. */\n subject: z.string().regex(/^(mailto:|https:\\/\\/)/, \"must start with mailto: or https://\").optional(),\n /** Mesh peer (id or name) that hosts the phone app. Set it on every\n * other node; leave it unset on the host. */\n relayTo: z.string().optional(),\n /** How long a push service keeps trying an offline phone. */\n ttlSeconds: z.number().int().min(0).max(2419200).default(86400),\n /** Recent pushes kept for the app's Alerts tab. */\n keepRecent: z.number().int().min(0).max(1000).default(50),\n /** Push-service hosts a phone may subscribe with (a host or any\n * subdomain of it). The daemon POSTs to the stored address, so anything\n * else is refused. Defaults cover Chrome/Android, Firefox, Safari/iOS\n * and Edge. */\n allowedHosts: z.array(z.string().min(1)).default([\n \"fcm.googleapis.com\", \"push.services.mozilla.com\", \"push.apple.com\", \"notify.windows.com\",\n ]),\n }).default({}),\n webrtc: z.object({\n enabled: z.boolean().default(false),\n /** ICE STUN servers for NAT discovery. Default is Google's public STUN. */\n stunServers: z.array(z.string()).default([\"stun:stun.l.google.com:19302\"]),\n /** Optional TURN relays (required when both peers are behind symmetric NAT). */\n turnServers: z.array(z.object({\n urls: z.string(),\n username: z.string().optional(),\n credential: z.string().optional(),\n })).default([]),\n /** Peer names permitted to *initiate* a call into this daemon. Empty = allow all mesh peers. */\n allowedCallers: z.array(z.string()).default([]),\n /** Where to send \"someone is calling\" notifications when an inbound ring\n * arrives. Each entry is delivered via the matching channel adapter —\n * same plumbing as any other outbound message. Empty disables notifications. */\n ringNotify: z.array(z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n })).default([]),\n /** Base URL used when building the tap-to-join link in ring notifications.\n * Defaults to `http://<node.bind>` — override when the daemon's public\n * hostname differs (e.g. HTTPS-terminated tunnel, Tailscale MagicDNS). */\n callUrlBase: z.string().optional(),\n /** AI participant (\"bot\") joins calls when a browser opens with `?bot=<id>`.\n * v1 is transcribe-only — bot consumes remote audio, transcribes via\n * Whisper, posts chunks to the configured channel. No TTS-back. */\n bot: z.object({\n enabled: z.boolean().default(false),\n /** Default agent id used to attribute the transcript when the URL\n * doesn't override via `?bot=<other-agent>`. */\n defaultAgentId: z.string().optional(),\n /** \"auto\" tries mlx-whisper, falls back to OpenAI; explicit forces. */\n whisperBackend: z.enum([\"auto\", \"mlx\", \"openai\"]).default(\"auto\"),\n whisperModel: z.string().optional(),\n whisperLanguage: z.string().default(\"auto\"),\n /** Absolute path to mlx_whisper if not on the daemon's PATH (common\n * on macOS launchd, where ~/.pyenv/shims is missing from the env). */\n mlxBinary: z.string().optional(),\n /** Where to send each transcribed chunk. Same shape as ringNotify[]. */\n transcriptChannel: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Hard cap so a forgotten bot doesn't run forever. */\n maxCallMinutes: z.number().int().min(1).max(240).default(30),\n }).default({}),\n /** The phone app's Share camera (#325). The phone asks for this size and\n * rate; the browser picks the nearest the camera supports. The share\n * stops by itself after maxSeconds. */\n camera: z.object({\n width: z.number().int().min(160).max(3840).default(1280),\n height: z.number().int().min(120).max(2160).default(720),\n frameRate: z.number().int().min(1).max(60).default(15),\n maxSeconds: z.number().int().min(10).max(7200).default(600),\n /** An agent watching the phone camera. The bot keeps only the newest\n * frame; the agent gets one when asked, and every\n * frameIntervalSeconds when that is set. */\n bot: cameraBotSchema,\n }).default({}),\n }).default({}),\n})\n\nconst cronJobSchema = z.object({\n enabled: z.boolean().default(true),\n schedule: z.string(),\n timezone: z.string().default(\"UTC\"),\n agent: z.string(),\n prompt: z.string().default(\"\"),\n /**\n * A shell command to run INSTEAD of dispatching the agent.\n *\n * Seven of this fleet's twenty-six crons were a single command wrapped\n * in an agent, and every one of them carried a paragraph like \"Run this\n * EXACT command. Do NOT substitute, rewrite, shorten, or fall back to\n * alternative commands.\" That paragraph is a scar: it exists because\n * models kept substituting, and no amount of prompt severity makes a\n * language model a deterministic executor.\n *\n * Measured before this existed: ~$0.31 and ~24s per run to execute one\n * `node script.js` and repeat ten lines of its output — a 114k-token\n * context for a job with no judgement in it at all.\n *\n * When set, the scheduler runs the command directly. No model, no\n * tokens, no improvisation. `agent` is still required and is who gets\n * told when it fails.\n */\n command: z.string().optional(),\n timeout: z.number().default(600),\n model: z.string().optional(),\n /** Soft cap on output length. Claude Code CLI has no hard flag for this,\n * but appending an instruction to the prompt is reliably honored. Use\n * 1500 for briefs, 500 for status pings, 300 for pure classifiers. */\n maxOutputTokens: z.number().int().min(50).max(8000).optional(),\n /** How much this routine may do: `report` (read-only), `propose` (branch,\n * commit, MR/draft; never merge/deploy/delete) or `act` (the agent's full\n * permissions — the default). Enforced per run by the guard, not by the\n * prompt; only the claude-code tier can enforce it, others refuse. */\n autonomy: autonomyLevelSchema.optional(),\n onError: z.union([\n z.enum([\"log\", \"notify\", \"disable\"]),\n z.array(z.enum([\"log\", \"notify\", \"disable\"])),\n ]).default(\"log\").transform(v => Array.isArray(v) ? v : [v]),\n notify: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Secret that lets an external system fire this job now via\n * `POST /routines/<id>/fire`. Reference an env var (`\"${MY_TOKEN}\"`);\n * a job without one cannot be fired. See src/daemon/routine-fire.ts. */\n fireToken: z.string().optional(),\n /** Agent id that created this job through the agent `schedule` tool.\n * Absent for operator-created jobs. Drives the ownership rule: an agent\n * manages only the routines it created, unless it is `admin`. */\n createdBy: z.string().optional(),\n /** Pending operator approval for an agent-requested change. While a\n * `create` is pending the job never runs, whatever `enabled` says; a\n * pending `delete` leaves the job as it was until approved. Cleared by\n * `agentx schedule approve|reject <id>`. */\n approval: z.object({\n action: z.enum([\"create\", \"delete\"]),\n requestedBy: z.string(),\n requestedAt: z.string(),\n }).optional(),\n}).refine((j) => Boolean(j.command?.trim() || j.prompt?.trim()), {\n message: \"a cron needs either a prompt (dispatch an agent) or a command (run it directly)\",\n}).refine((j) => !(j.command?.trim() && j.autonomy && j.autonomy !== \"act\"), {\n message: \"autonomy applies to agent routines; a command cron runs no agent (remove autonomy or the command)\",\n})\n\nconst serviceSchema = z.object({\n name: z.string(),\n triggers: z.array(z.object({\n pattern: z.string(),\n channel: z.string().optional(),\n })),\n allowedContacts: z.array(z.string()).optional(),\n agent: z.string(),\n prompt: z.string(),\n schedule: z.string().optional(),\n timezone: z.string().default(\"UTC\"),\n notify: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n})\n\nconst meshPeerSchema = z.object({\n url: z.string(),\n name: z.string(),\n token: z.string().optional(),\n})\n\n/** A named, operator-declared destination that remote mesh nodes may send\n * to. Deliberately minimal: the published surface is the name and whether\n * it accepts, so there is nothing here that could leak local state if it\n * were echoed back. Which agent handles it stays private to this node. */\nconst meshInboxSchema = z.object({\n name: z.string(),\n agent: z.string(),\n enabled: z.boolean().default(true),\n})\n\nconst meshConfigSchema = z.object({\n enabled: z.boolean().default(false),\n peers: z.array(meshPeerSchema).default([]),\n /** Empty by default — a node publishes no inboxes until an operator\n * declares one, so this feature is opt-in per node. */\n inboxes: z.array(meshInboxSchema).default([]),\n discovery: z.enum([\"static\", \"mdns\"]).default(\"static\"),\n healthCheck: z.object({\n interval: z.number().default(60),\n timeout: z.number().default(10),\n }).default({}),\n /** Peer event feed (#166): follow each healthy peer's /events and merge\n * its own events into this node's bus. `skipTypes` are left out on the\n * peer's side; per-step agent activity is too chatty to cross the mesh. */\n feed: z.object({\n enabled: z.boolean().default(true),\n skipTypes: z.array(z.string().min(1)).default([\"task:step\"]),\n }).default({}),\n /** Agent-to-agent delegation (#277), local or across peers. When a person\n * started the conversation, a delegation returns at once and the answer\n * comes back to the asking agent as a new turn in the same chat. */\n delegation: z.object({\n /** Off: every delegation waits for its answer, as before. */\n asyncWhenHuman: z.boolean().default(true),\n /** A delegation with no answer after this long is reported as timed out. */\n timeoutMinutes: z.number().int().min(1).max(240).default(30),\n }).default({}),\n})\n\n/** Intent Knowledge Graph — fixed-axis, LLM-proposed taxonomy used by the\n * Intent layer in context.ts and (eventually) wiki retrieval. Off by default\n * so existing installs see no change. */\nconst graphConfigSchema = z.object({\n enabled: z.boolean().default(false),\n /** Where the schema/nodes/classifications live. Relative to cwd. */\n baseDir: z.string().default(\".agentx/graph\"),\n /** Which agent makes LLM classification proposals. Falls back to\n * `dashboard.draftAgent` at call sites if unset. */\n draftAgent: z.string().optional(),\n /** Agent used by `agentx graph review` to triage pending classifications.\n * Should be an agent with the wiki skill so it can call `wiki query` for\n * context before deciding approve/reject. Falls back to draftAgent. */\n reviewAgent: z.string().optional(),\n /** Structural auto-approval policy. Evaluated against each classification\n * independently of `autoApproveConfidence`; either triggers approval.\n * - \"strict\" : never approve via structure — every classification\n * waits for human review\n * - \"extend-leaves\" : auto-approve when the proposed path (a) reuses only\n * existing nodes, or (b) adds exactly one NEW node at\n * the deepest level. Structural changes (new mid-path\n * node, new root) still queue for review. Default.\n * - \"any\" : auto-approve every classification regardless of\n * structural change\n */\n autoApproveStructure: z.enum([\"strict\", \"extend-leaves\", \"any\"]).default(\"extend-leaves\"),\n /** Minimum classifier confidence (0..1) to auto-approve. OR'd with the\n * structural policy — either hitting the threshold lets the classification\n * bypass the pending queue. 1.0 (default) disables this knob, so approval\n * is driven by `autoApproveStructure` alone. Lower it to e.g. 0.7 if you\n * also want high-confidence structural changes auto-approved. */\n autoApproveConfidence: z.number().min(0).max(1).default(1.0),\n /** Anthropic model id used for the direct classifier call (Phase 2 of\n * classifier-retire). Default haiku — classification is metadata, not\n * work, so we use the cheapest fast model. Override only if Haiku is\n * rate-limited or you want to A/B test. */\n classifierModel: z.string().default(\"claude-haiku-4-5-20251001\"),\n /** Weights for the wiki hybrid retrieval score. Path-ancestry match vs\n * BM25 over article text. Sum need not be 1. */\n retrievalWeights: z.object({\n graph: z.number().min(0).default(0.6),\n bm25: z.number().min(0).default(0.4),\n }).default({}),\n}).default({})\n\n// --- Typed-decision seats (src/decisions) ---\n//\n// Everything here defaults off. A seat in \"shadow\" runs alongside the\n// incumbent and only records; \"active\" lets its answer steer behaviour, and\n// no seat should reach it before its calibration report says what threshold\n// to use and what that threshold costs.\nconst decisionSeatSchema = z.object({\n /** off: the seat is unreachable. shadow: runs and records, incumbent stays\n * authoritative. active: the answer is used. */\n mode: z.enum([\"off\", \"shadow\", \"active\"]).default(\"off\"),\n /** Backend name from the decisions registry. Per-seat, so one seat can be\n * graded against a different backend than another at the same time. */\n backend: z.string().optional(),\n model: z.string().optional(),\n timeoutMs: z.number().int().min(100).default(10_000),\n /** Post-hoc temperature fitted on this seat's own labeled rows. 1 means\n * \"not calibrated yet\", which is where every seat starts — see\n * `agentx decisions calibrate`. */\n temperature: z.number().min(0.01).default(1),\n /** Fraction of would-be-skips to run anyway. Not a tuning knob: a skipped\n * decision can never be graded, so without exploration an active seat's\n * metrics are computed on the biased sample it selected for itself.\n * Setting this to 0 in active mode means the calibration report stops\n * being trustworthy the day you promote the seat. */\n explore: z.number().min(0).max(1).default(0.15),\n /** Fraction of turns that bypass the seat as a randomized control group.\n * Unset lets the seat pick its own default; only seats that run an\n * experiment read it (today: request-gate, default 0.1). */\n holdout: z.number().min(0).max(1).optional(),\n}).default({})\n\nconst decisionsConfigSchema = z.object({\n enabled: z.boolean().default(false),\n dbPath: z.string().default(\".agentx/decisions/decisions.sqlite\"),\n /** State can contain message text. With this on, only the hash is kept,\n * which costs the ability to replay a decision offline. */\n redactState: z.boolean().default(false),\n /** Keep the serialized state for this many rows per seat, then prune to\n * hashes. Enough to replay and to grade an alternative backend on\n * identical inputs, without growing without bound. */\n keepStateRows: z.number().int().min(0).default(2000),\n defaultBackend: z.string().default(\"local\"),\n backends: z.object({\n local: z.object({\n provider: z.string().default(\"claude-code\"),\n model: z.string().default(\"claude-haiku-4-5-20251001\"),\n /** auto resolves to a forced tool where the provider guarantees one,\n * and JSON-in-text otherwise (claude-code on OAuth cannot force a\n * tool). Never resolves to logprobs: that costs one call per\n * question, so it has to be asked for. */\n structureMode: z.enum([\"auto\", \"tool\", \"text\"]).default(\"auto\"),\n normalizeProbabilities: z.boolean().default(true),\n nRetryMalformedStructure: z.number().int().min(0).max(3).default(1),\n maxStateChars: z.number().int().min(500).default(24_000),\n }).default({}),\n /** A simple-jev server (featherless-ai/simple-jev). Reads the model's\n * next-token logits rather than asking it to write a probability, so\n * the distribution is the model's posterior instead of a number it\n * chose. Still not calibrated to correctness — that comes from\n * `agentx decisions recalibrate`. */\n simpleJev: z.object({\n baseUrl: z.string().default(\"http://127.0.0.1:8000/v1\"),\n model: z.string().optional(),\n apiKeyEnv: z.string().optional(),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(6_000),\n /** Their Choice takes 2-50 candidates, well under Jev's 255. */\n maxChoiceOptions: z.number().int().min(2).max(255).default(50),\n }).default({}),\n /** TypeSafe Jev through OpenRouter's alpha decisions endpoint.\n * Verified live 2026-09-19 — resolves to typesafe/jev-1.13-20260917,\n * provider \"TypeSafe\", ~0.5s round trip. The id is \"jev-latest\";\n * the namespaced \"typesafe/jev-latest\" 400s, and neither appears in\n * OpenRouter's public model list. Needs OPENROUTER_API_KEY. */\n jev: z.object({\n baseUrl: z.string().default(\"https://openrouter.ai/api/alpha\"),\n path: z.string().default(\"/decisions\"),\n model: z.string().default(\"jev-latest\"),\n apiKeyEnv: z.string().default(\"OPENROUTER_API_KEY\"),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(90_000),\n maxChoiceOptions: z.number().int().min(2).max(255).default(255),\n }).default({}),\n /** Jev direct from TypeSafe rather than through OpenRouter. Same\n * contract, different billing and rate limits. Needs TYPESAFE_API_KEY. */\n typesafe: z.object({\n baseUrl: z.string().default(\"https://api.typesafe.ai/v1\"),\n path: z.string().default(\"/systemone\"),\n model: z.string().default(\"jev-latest\"),\n apiKeyEnv: z.string().default(\"TYPESAFE_API_KEY\"),\n timeoutMs: z.number().int().min(100).default(30_000),\n maxStateChars: z.number().int().min(500).default(90_000),\n maxChoiceOptions: z.number().int().min(2).max(255).default(255),\n }).default({}),\n }).default({}),\n seats: z.record(z.string(), decisionSeatSchema).default({}),\n /** Model routing driven by the task-tier seat. Models are scoped to their\n * CLI engine; the legacy cheapModel applies only to Claude Code. */\n routing: z.object({\n cheapModel: z.string().optional(),\n cheapModels: z.object({\n \"claude-code\": z.string().optional(),\n \"codex-cli\": z.string().optional(),\n }).optional(),\n }).default({}),\n}).default({})\n\n/** Agents ringing the owner for a live voice call (src/calls). */\nexport const callsSchema = z.object({\n /** Agents allowed to call: ids, or \"*\" for every agent on this node.\n * Empty: nobody can call until the owner allows it. */\n allow: z.array(z.string()).default([]),\n /** Most calls one agent may place in an hour. */\n maxPerHour: z.number().int().min(1).max(60).default(3),\n /** How long a call rings before it counts as missed. */\n ringSeconds: z.number().int().min(10).max(300).default(45),\n /** An answered call nobody hung up (widget quit or crashed, the Mac\n * slept, `agentx call answer` without a conversation) ends after this,\n * so the agent can call again. */\n maxCallMinutes: z.number().int().min(1).max(240).default(30),\n /** Ring sound: a name from /System/Library/Sounds, without the extension. */\n ringSound: z.string().regex(/^[\\w -]+$/).default(\"Submarine\"),\n /** After hang-up, ask the agent for a short summary and file it in the\n * dashboard's conversation history. */\n summary: z.boolean().default(true),\n}).default({})\n\nexport type CallsConfig = z.infer<typeof callsSchema>\n\nconst notificationsSchema = z.object({\n /** Send notification when task takes longer than this (seconds). 0 = disabled. */\n longTaskThreshold: z.number().default(30),\n /** Where to send notifications */\n destination: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n /** Channel `agentx notify` and Focus digests use when none is given.\n * Unset: `push` (the phone app) when channels.push is enabled, else\n * `ntfy`, so upgrading never points notify at a channel that is off. */\n channel: z.string().optional(),\n /** Notify on these events */\n on: z.object({\n taskComplete: z.boolean().default(true),\n taskError: z.boolean().default(true),\n taskQueued: z.boolean().default(false),\n }).default({}),\n /** What `agentx notify` does on this machine when it delivers: a desktop\n * banner and a system sound. macOS only; see src/notify/local.ts. */\n local: z.object({\n banner: z.boolean().default(true),\n sound: z.boolean().default(true),\n /** A name from /System/Library/Sounds, without the extension. */\n soundName: z.string().regex(/^[\\w -]+$/).default(\"Glass\"),\n volume: z.number().min(0).max(1).default(0.4),\n /** Image for the AgentX Helper icon on banners (.png, .jpg, .icns).\n * Unset: the AgentX logo. Applied by `agentx desktop install`. */\n icon: z.string().optional(),\n }).default({}),\n}).default({})\n\nconst screenRectSchema = z.object({\n x: z.number(), y: z.number(), width: z.number().positive(), height: z.number().positive(),\n})\n\n/** Screen capture for agents: how captures are cropped and scaled, how\n * long they wait for the right moment, named regions, and the opt-in\n * in-memory buffer. See src/computer-use/capture.ts. */\nconst screenSchema = z.object({\n /** Pixel budget for a captured frame; larger captures are downscaled. */\n maxPixels: z.number().int().positive().default(1_200_000),\n /** Longest a capture waits for a change or for the screen to settle. */\n timeoutMs: z.number().int().positive().default(5_000),\n /** Time between samples while waiting. */\n intervalMs: z.number().int().positive().default(100),\n /** Mean difference (0–1) above which two samples count as different. */\n changeThreshold: z.number().min(0).max(1).default(0.015),\n /** How long a region must stay unchanged to count as stable. */\n stableMs: z.number().int().nonnegative().default(400),\n /** Named regions in screen points, e.g. { \"chat\": { x, y, width, height } }.\n * A name here overrides the built-in region of the same name. */\n regions: z.record(z.string().regex(/^[a-z][\\w-]*$/), screenRectSchema).default({}),\n /** The last few seconds of a region, kept in memory by the daemon. Off\n * unless enabled; frames are written out only when asked for. */\n buffer: z.object({\n enabled: z.boolean().default(false),\n seconds: z.number().positive().max(120).default(10),\n fps: z.number().positive().max(10).default(2),\n region: z.string().default(\"screen\"),\n maxPixels: z.number().int().positive().default(300_000),\n }).default({}),\n}).default({})\n\n/** The Approvals inbox (src/approvals). Decision cards agents raise, and\n * when the operator hears about what is waiting. */\nexport const approvalsConfigSchema = z.object({\n /** A card without an `expires` gets this many days. */\n defaultExpiryDays: z.number().positive().max(365).default(3),\n /** No card waits longer than this, whatever the agent asked for. */\n maxExpiryDays: z.number().positive().max(365).default(30),\n /** How long \"later\" hides an item. */\n laterHours: z.number().positive().max(24 * 30).default(24),\n /** Tell the agent that raised a card when it is decided or expires. */\n notifyAgent: z.boolean().default(true),\n /** At most one message a day: how many are waiting, and the most urgent. */\n digest: z.object({\n enabled: z.boolean().default(true),\n /** Local time, 24-hour HH:MM. */\n time: z.string().regex(/^([01]\\d|2[0-3]):[0-5]\\d$/, \"use HH:MM, 24-hour\").default(\"09:00\"),\n /** IANA timezone for `time`. Unset: this machine's. */\n timezone: z.string().refine((tz) => {\n try { new Intl.DateTimeFormat(\"en-US\", { timeZone: tz }); return true } catch { return false }\n }, \"unknown timezone\").optional(),\n /** Where it goes. Unset: notifications.destination. */\n destination: z.object({\n channel: z.string(),\n chatId: z.string(),\n accountId: z.string().optional(),\n }).optional(),\n }).default({}),\n /** A popup on this Mac for new decision cards: sound, a spoken line,\n * ready-made choices. Held during Focus. macOS only. */\n popup: z.object({\n enabled: z.boolean().default(false),\n /** Speak a short line when it opens. */\n speak: z.boolean().default(true),\n /** A macOS voice name for `say -v`. Unset: the system voice. */\n voice: z.string().regex(/^[\\w .()-]+$/, \"a voice name, as `say -v '?'` lists them\").optional(),\n /** A system sound from /System/Library/Sounds; \"\" for none. */\n sound: z.string().regex(/^[\\w -]*$/, \"a sound name, like Glass\").default(\"Glass\"),\n volume: z.number().min(0).max(1).default(0.4),\n /** Seconds the popup waits for an answer; then the card stays in the inbox. */\n timeoutSeconds: z.number().int().min(10).max(3600).default(600),\n }).default({}),\n}).default({})\n\nexport const daemonConfigSchema = z.object({\n node: z.object({\n id: z.string(),\n name: z.string(),\n bind: z.string().default(\"127.0.0.1:18800\"),\n /** Default agent for voice/API calls that don't specify one (e.g. Siri) */\n defaultAgent: z.string().optional(),\n }),\n providers: z.record(z.string(), providerConfigSchema).default({}),\n agents: z.record(z.string(), agentConfigSchema).default({}),\n channels: channelsConfigSchema.default({}),\n crons: z.record(z.string(), cronJobSchema).default({}),\n services: z.record(z.string(), serviceSchema).default({}),\n notifications: notificationsSchema,\n calls: callsSchema,\n /** Watched WhatsApp chats triaged by an agent (src/whatsapp-triage). */\n whatsappTriage: whatsappTriageSchema,\n approvals: approvalsConfigSchema,\n /** How a daemon stop treats runs still in flight. */\n shutdown: z.object({\n /** Wait this long for runs to finish before cutting them off (they are\n * then resumed or reported after the restart). Unset: the\n * AGENTX_DRAIN_TIMEOUT_MS env var, else 300 s. Keep the service\n * manager's stop timeout above it, or it kills the daemon mid-wait. */\n drainTimeoutSeconds: z.number().int().min(0).max(86_400).optional(),\n /** Who may ask for \"restart when idle\", and what happens to the others.\n * Unset: any caller may, and onTimeout \"restart\" is honoured. */\n restart: z.object({\n /** Regular expression matched against the request's `by`. Requests\n * from anyone else are held until `window`, or refused when there\n * is no window. */\n allowBy: z.string().optional(),\n /** Local time \"HH:MM\" at which held requests start an idle-only wait. */\n window: z.string().regex(/^\\d{1,2}:\\d{2}$/, \"window must be HH:MM\").optional(),\n /** How long that wait lasts before it gives up. */\n windowWaitMinutes: z.number().int().min(1).max(1440).default(180),\n /** Turn every request into an idle-only one: a wait that runs out\n * gives up instead of restarting over running work. */\n forbidOnTimeoutRestart: z.boolean().default(false),\n }).default({}),\n }).default({}),\n /** What happens to runs a restart cuts off (agents/resume). Chat messages\n * are resumed in their chat; scheduled jobs never are (the next run\n * covers them); everything else is reported unless its channel is in\n * directChannels. */\n resume: z.object({\n enabled: z.boolean().default(true),\n /** Older runs are reported, not resumed. */\n maxAgeMinutes: z.number().int().positive().default(30),\n /** A run cut off while resuming is not retried past this. */\n maxAttempts: z.number().int().min(0).default(1),\n /** Channels whose runs are only reported, even from a chat. */\n reportOnlyChannels: z.array(z.string()).default([]),\n /** Non-chat runs (voice, agent-to-agent, webhooks…) resumed on these\n * channels. Their answer isn't delivered anywhere; opt in only for\n * runs whose work is the point. */\n directChannels: z.array(z.string()).default([]),\n /** This many restarts within the window pauses resuming. */\n crashLoop: z.object({\n restarts: z.number().int().positive().default(3),\n windowMinutes: z.number().positive().default(10),\n }).default({}),\n }).default({}),\n /** Hand due Apple Reminders back to the agent that created them\n * (src/reminders). macOS only; reads reminders whose notes end with the\n * mac-pim skill's `agentx: agent=<id>` trailer. */\n reminders: z.object({\n enabled: z.boolean().default(false),\n /** Reminders lists to watch. */\n lists: z.array(z.string().min(1)).default([\"AgentX\"]),\n pollSeconds: z.number().int().min(15).default(60),\n /** Overdue by more than this (the daemon was down): reported, not run. */\n lookbackHours: z.number().positive().default(24),\n /** The remindctl binary, when it isn't on the daemon's PATH. */\n command: z.string().min(1).default(\"remindctl\"),\n }).default({}),\n /** `agentx demo`, read from the agentx.json in the folder it runs from. */\n demo: z.object({\n /** Seconds each startup step (node /health, dashboard /live, mesh\n * discovery) may take. Unset: AGENTX_DEMO_STARTUP_TIMEOUT, else 60 s\n * scaled up by the load average (src/commands/demo-startup.ts). */\n startupTimeoutSeconds: z.number().int().positive().max(3600).optional(),\n }).default({}),\n /** The in-process event bus (src/events). `ringSize` bounds how many\n * recent events GET /events/recent can return. */\n events: z.object({\n ringSize: z.number().int().min(1).max(100_000).default(1000),\n }).default({}),\n screen: screenSchema,\n mesh: meshConfigSchema.default({}),\n /** Voices for agents on mesh peers, keyed by remote agent id, or by\n * \"<peer>/<id>\" for one peer's agent (it wins over the id). The Mac\n * speaks for them, so their nodes need no ElevenLabs key. Unset fields\n * are derived from the agent card; see src/voice/mesh-voice.ts. */\n meshVoices: z.record(z.string(), voiceSchema.omit({ rate: true, priority: true, hotkey: true }).extend({\n /** What to call the agent aloud, e.g. \"Atlas\" for \"Main Agent\". */\n name: z.string().optional(),\n })).default({}),\n /** How agents speak. The free system voices by default; ElevenLabs is an\n * opt-in upgrade. Each agent's `voice` block can override the provider\n * and pick its voice; see src/voice/agent-voice.ts. */\n voice: z.object({\n provider: voiceProviderSchema.default(\"system\"),\n /** When ElevenLabs cannot speak (no key, an error): the system voice,\n * or silence. */\n fallback: z.enum([\"system\", \"none\"]).default(\"system\"),\n /** The system voice for agents without one of their own (see\n * systemVoiceSchema). Unset: each agent gets its own. */\n system: systemVoiceSchema.optional(),\n /** Language for assigned system voices, e.g. \"en\", \"fr-FR\". */\n locale: z.string().default(\"en\"),\n /** What agents call the person they talk with, e.g. a first name.\n * Unset: \"the user\". */\n listener: z.string().optional(),\n /** AgentX Voice speech to text: \"auto\" uses ElevenLabs when a key is\n * set and the local Whisper otherwise; \"elevenlabs\" or \"local\" pick\n * one (ElevenLabs still falls back to local when it fails). */\n stt: z.enum([\"auto\", \"elevenlabs\", \"local\"]).default(\"auto\"),\n /** Phone voice input where the daemon has no ffmpeg to measure a\n * recording's length: refused by default, since the 2 MB cap alone\n * lets through ~40 minutes of low-bitrate audio. true accepts it. */\n allowUnmeasured: z.boolean().default(false),\n /** The on-device engine behind \"local\" and every fallback:\n * mlx-whisper (Python, all languages) or Parakeet (Core ML, 25\n * European languages, no Arabic; 483 MB downloaded on first use into\n * ~/.agentx/models). mlx-whisper answers until Parakeet is ready. */\n localStt: z.enum([\"mlx-whisper\", \"parakeet\"]).default(\"mlx-whisper\"),\n /** How AgentX Voice hears the end of a hands-free turn: \"vad\" (Silero\n * voice detection, 0.9 MB downloaded on first use; the volume\n * threshold until then) or \"volume\" (the old fixed threshold). */\n endOfTurn: z.enum([\"vad\", \"volume\"]).default(\"vad\"),\n /** AgentX Voice shortcuts: hold `talk` to speak, `stop` silences every\n * voice, `paste` is smart paste. */\n hotkeys: z.object({\n talk: hotkeySchema.default(DEFAULT_HOTKEYS.talk),\n stop: hotkeySchema.default(DEFAULT_HOTKEYS.stop),\n paste: hotkeySchema.default(DEFAULT_HOTKEYS.paste),\n }).default({}),\n /** The answer text AgentX Voice shows inside its pill. */\n card: z.object({\n /** Seconds the answer stays open once it has been spoken; 0 keeps\n * it open until closed. */\n timeout: z.number().min(0).max(600).default(30),\n /** Tallest the answer grows, in points, before it scrolls. */\n maxHeight: z.number().min(120).max(800).default(320),\n }).default({}),\n }).default({}),\n business: businessConfigSchema.optional(),\n boards: boardsConfigSchema,\n dashboard: dashboardConfigSchema,\n graph: graphConfigSchema,\n decisions: decisionsConfigSchema,\n /** Workflow engine — declarative state machines that bind channel events\n * to agents. Off by default; existing installs see no change until\n * flipped. Definitions live under `dir` (default .agentx/workflows/). */\n workflows: z.object({\n enabled: z.boolean().default(false),\n dir: z.string().default(\".agentx/workflows\"),\n /** n8n keeps its several hundred connectors; we keep the agents. Point\n * this at your n8n and the workflow builder lists YOUR n8n workflows as\n * steps, so nobody has to copy a webhook URL by hand. */\n n8n: z.object({\n baseUrl: z.string().default(\"\"),\n apiKey: z.string().default(\"\"),\n }).default({ baseUrl: \"\", apiKey: \"\" }),\n matching: z.object({\n enabled: z.boolean().default(false),\n mode: z.enum([\"suggest\", \"auto\"]).default(\"suggest\"),\n autoRunThreshold: z.number().min(0).max(1).default(0.85),\n suggestThreshold: z.number().min(0).max(1).default(0.65),\n }).default({}),\n /** Controls whether the dashboard exposes the visual editor. \"readonly\"\n * serves the list + run timelines but strips write controls from the\n * page. \"disabled\" hides the tab entirely. */\n editor: z.enum([\"disabled\", \"readonly\", \"edit\"]).default(\"edit\"),\n }).default({}),\n /** Procedures — user-perspective SOPs mined from recurring activity.\n * The extraction cadence itself lives in `crons.procedure-extract`\n * (written by `agentx procedure watch`); this block holds the miner's\n * thresholds and the injection gates the daemon reads. */\n procedures: z.object({\n enabled: z.boolean().default(true),\n dir: z.string().default(\".agentx/procedures\"),\n extraction: z.object({\n enabled: z.boolean().default(false),\n /** Count patterns live after each completed task (no LLM cost). */\n onTaskCompletion: z.boolean().default(false),\n minOccurrences: z.number().int().min(2).default(3),\n sinceDays: z.number().int().min(1).default(7),\n maxClusters: z.number().int().min(1).default(5),\n /** Agent whose session distills drafts (LLM path). */\n via: z.string().optional(),\n }).default({}),\n /** Inject matching procedures into fresh agent sessions as guidance. */\n injection: z.object({\n enabled: z.boolean().default(true),\n maxProcedures: z.number().int().min(1).default(2),\n minScore: z.number().min(0).max(1).default(0.5),\n }).default({}),\n }).default({}),\n /** Registered inbound webhooks — an inventory the dashboard manages. Each\n * entry binds an (agent, source) pair to an optional signing secret. The\n * actual inbound URL is always POST /webhook/<agentId>/<source>. */\n webhooks: z.array(z.object({\n id: z.string().regex(/^[a-z0-9][a-z0-9_-]*$/, \"webhook id must be lowercase slug\"),\n // Open-string source — runtime + admin-panel + CLI all share a\n // canonical list (kept in sync via WEBHOOK_SOURCES). Loosened from a\n // strict enum so adding a new first-class service (the 5-step recipe)\n // doesn't require a schema bump in three places. Doctor + admin\n // validator still gate writes on the canonical list.\n source: z.string().min(1),\n agentId: z.string(),\n secretEnv: z.string().optional(),\n description: z.string().optional(),\n enabled: z.boolean().default(true),\n /** Route to a mesh peer instead of local execution. */\n node: z.string().optional(),\n /** Per-event-type workflow routing. Keys are platform event-type\n * strings — the format the platform's HTTP header uses, optionally\n * joined with the action. Examples:\n * GitHub: \"issues.opened\", \"pull_request.synchronize\",\n * \"push\" (action-less events use the bare type)\n * GitLab: \"Note Hook\", \"Merge Request Hook\"\n * Values are workflow ids registered via `agentx workflow create`.\n * When the inbound event-type matches a key, the named workflow is\n * dispatched; if no key matches, the webhook falls through to\n * `defaultWorkflow` (or the agent itself). Closes the recurring\n * GitHub problem of multiple event types collapsing to a single\n * workflow. */\n triggers: z.record(z.string(), z.string()).optional(),\n /** Workflow id used when no `triggers` entry matches the event-type.\n * Backward-compatible: pre-existing webhooks without `triggers`\n * always hit this path. */\n defaultWorkflow: z.string().optional(),\n })).default([]),\n /** Session cache-reuse policy. Controls when we drop a Claude `--resume`\n * session and rebuild the prompt from scratch. Every rotation captures a\n * continuity memo that's injected into the chat's next fresh session.\n * - `staleMinutes`: idle timeout before rotation. 12 h default — chat\n * conversations must survive a workday's pauses; overnight silence\n * starts fresh.\n * - `maxTurnsPerSession`: backstop cap on turns per Claude session.\n * Size-based rotation measures real context now, so this rarely fires\n * first.\n * - `tierTwoThresholdTokens`: rotate when the prior turn's END-OF-TURN\n * per-request context (last API call's input + cacheRead + cacheCreate)\n * reaches this. Claude bills the 1.5× long-context rate above 200K\n * per REQUEST — 180K leaves headroom. NOT the cumulative turn total:\n * that sums cache reads across every call and reads 10-20× too high. */\n session: z.object({\n staleMinutes: z.number().int().min(1).max(1440).default(720),\n maxTurnsPerSession: z.number().int().min(2).max(200).default(40),\n tierTwoThresholdTokens: z.number().int().min(50_000).max(200_000).default(180_000),\n /** Context assembly strategy:\n * - \"layered\" (default): the classic stacked layers — session history,\n * memory, cross-chat, wiki hint all appended every turn.\n * - \"planner\": a Haiku pre-call decides what to retrieve before the\n * main agent runs. Always-on core is kept (channel/scope/landscape/\n * identity/intent + last 3 turns verbatim); history blob, wiki hint,\n * and cross-chat are replaced by planner-selected bundles. Per-task\n * overrides via AgentTask.contextStrategy for A/B benchmarking. */\n contextStrategy: z.enum([\"layered\", \"planner\"]).default(\"layered\"),\n /** Soft dispatch budget for claude-code-tier agents (shared OAuth pools\n * one counter across the fleet). Warms at 80% of the cap; short-circuits\n * cold dispatches (no warm Claude session) when exceeded. Warm sessions\n * are always allowed through. Defaults sized for Max 5×:\n * - maxClaudeCodeDispatchesPerHour: 80 (headroom under typical hourly cap)\n * - maxClaudeCodeDispatchesPer5h: 180 (headroom under ~225/5h tier)\n * Raise for Max 20×, lower if your workload stays under the cap naturally. */\n maxClaudeCodeDispatchesPerHour: z.number().int().min(1).max(10_000).default(80),\n maxClaudeCodeDispatchesPer5h: z.number().int().min(1).max(50_000).default(180),\n /** How many requests BEFORE the immediate predecessor to show the\n * session-continuity seat. 0 keeps today's two-message state exactly.\n *\n * Off by default on purpose. A probe over 27 hand-written turns found\n * that at 3, the seat's safety question (`needsHistory`) becomes\n * cleanly separable where two messages leave it straddling zero — but\n * that rests on 7 positive examples from synthetic scenarios, and this\n * seat's failure mode is the agent silently losing conversation\n * context. The promotion gate for that wants labelled production rows,\n * not a good afternoon on a fixture. Raise it to collect them. */\n continuityStateTurns: z.number().int().min(0).max(5).default(0),\n }).default({}),\n /** Move B — JS/TS plugins. Each entry is an installed npm package name\n * (e.g. `agentx-plugin-mattermost` or `@acme/plugin-mattermost`); the\n * loader does a dynamic `import(name)` at boot, validates the manifest,\n * and calls plugin.setup(ctx). Plugins can register channel adapters\n * via ctx.addChannel() and subscribe to bus events via ctx.on(). Empty\n * default — installs that don't list plugins are unaffected. Plugin\n * authoring guide: docs/architecture/plugins.md. */\n plugins: z.array(z.string()).default([]),\n /** Persistent-process pool eviction knobs (handoff #8). The pool keeps\n * one warm Claude subprocess per (agent, channel, chatId) so latency\n * stays low; without bounds, an idle process can serve traffic days\n * later with stale context. These knobs cap that risk. All values are\n * in seconds for operator-friendliness; the registry uses ms internally.\n *\n * - `maxIdleSeconds`: a handle becomes eligible for cap-pressured\n * eviction this many seconds after its last turn. Default 30s\n * (matches the registry's pre-config behavior).\n * - `maxAgeSeconds`: a handle is killed unconditionally on the next\n * sweep once its total wall-clock idleness exceeds this. Default\n * 2700s (45min) — matches the registry's pre-config staleTimeoutMs.\n * - `sweepIntervalSeconds`: how often the sweeper checks. Default 5s.\n *\n * See `agents.<id>.persistentProcess` to opt an agent into the pool. */\n processPool: z.object({\n maxIdleSeconds: z.number().int().min(5).max(86_400).default(30),\n maxAgeSeconds: z.number().int().min(60).max(86_400).default(2700),\n sweepIntervalSeconds: z.number().int().min(1).max(300).default(5),\n }).default({}),\n})\n\nexport type DaemonConfig = z.infer<typeof daemonConfigSchema>\nexport type AgentDef = z.infer<typeof agentConfigSchema>\nexport type EventSubscription = z.infer<typeof eventSubscriptionSchema>\nexport type CronJobDef = z.infer<typeof cronJobSchema>\nexport type MeshPeer = z.infer<typeof meshPeerSchema>\n\n/**\n * Expand environment variables in strings: ${VAR_NAME} -> process.env.VAR_NAME\n */\nexport function expandEnvVars(obj: unknown): unknown {\n if (typeof obj === \"string\") {\n return obj.replace(/\\$\\{(\\w+)\\}/g, (_match, name) => process.env[name] || \"\")\n }\n if (Array.isArray(obj)) {\n return obj.map(expandEnvVars)\n }\n if (obj !== null && typeof obj === \"object\") {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n result[key] = expandEnvVars(value)\n }\n return result\n }\n return obj\n}\n\n/**\n * Translate raw Zod issues into actionable, copy-pasteable fixes for the\n * patterns we see in real first-run failures (missing tokens, missing\n * required env vars, etc.). Falls through silently for unknown patterns —\n * the raw `issues` block is always shown above this hint block.\n */\nfunction friendlyConfigHints(issues: ReadonlyArray<z.ZodIssue>, configPath: string): string[] {\n const hints: string[] = []\n const seen = new Set<string>()\n for (const issue of issues) {\n const path = issue.path.join(\".\")\n // Telegram account block exists but token is empty/missing — by far the\n // most common first-run trip. Tell the operator exactly which two\n // recoveries are valid, with the literal config path to edit.\n const tgTokenMatch = /^channels\\.telegram\\.accounts\\.([^.]+)\\.token$/.exec(path)\n if (tgTokenMatch && issue.message.toLowerCase().includes(\"required\")) {\n const account = tgTokenMatch[1]\n const key = `tg:${account}`\n if (seen.has(key)) continue\n seen.add(key)\n hints.push(\n `Hint: Telegram account \"${account}\" is enabled but has no bot token.\\n` +\n ` Either:\\n` +\n ` A) Open ${configPath} and set channels.telegram.accounts.${account}.token to your bot token (or \"\\${TG_${account.toUpperCase()}_BOT_TOKEN}\" + the matching .env entry).\\n` +\n ` B) If you don't need Telegram on this instance, remove the entire \"telegram\" block under \"channels\" (or set channels.telegram.enabled to false AND drop accounts.${account}).`\n )\n }\n }\n return hints\n}\n\n/**\n * Load daemon config from agentx.json, with env var expansion and validation.\n */\nexport function loadDaemonConfig(configPath?: string): DaemonConfig {\n const paths = configPath\n ? [configPath]\n : [\n resolve(process.cwd(), \"agentx.json\"),\n resolve(process.cwd(), \".agentx/config.json\"),\n ]\n\n // Load .env from same directory as config search\n loadDotEnv(process.cwd())\n\n let raw: string | undefined\n let foundPath: string | undefined\n\n for (const p of paths) {\n if (existsSync(p)) {\n raw = readFileSync(p, \"utf-8\")\n foundPath = p\n break\n }\n }\n\n if (!raw || !foundPath) {\n throw new Error(\n `No config found. Create agentx.json or .agentx/config.json\\n` +\n `Searched: ${paths.join(\", \")}`\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (e: any) {\n throw new Error(`Invalid JSON in ${foundPath}: ${e.message}`)\n }\n\n // Expand environment variables\n const expanded = expandEnvVars(parsed)\n\n // Validate\n const result = daemonConfigSchema.safeParse(expanded)\n if (!result.success) {\n const issues = result.error.issues\n .map((i) => ` ${i.path.join(\".\")}: ${i.message}`)\n .join(\"\\n\")\n const hints = friendlyConfigHints(result.error.issues, foundPath)\n const hintBlock = hints.length ? `\\n\\n${hints.join(\"\\n\\n\")}` : \"\"\n throw new Error(`Config validation failed (${foundPath}):\\n${issues}${hintBlock}`)\n }\n\n return result.data\n}\n\n/**\n * Validate agent workspace directories exist and have .claude/ setup.\n */\nexport function validateWorkspaces(config: DaemonConfig): string[] {\n const warnings: string[] = []\n\n for (const [id, agent] of Object.entries(config.agents)) {\n if (!existsSync(agent.workspace)) {\n warnings.push(`Agent \"${id}\": workspace not found at ${agent.workspace}`)\n continue\n }\n\n if (agent.tier === \"claude-code\") {\n const claudeDir = resolve(agent.workspace, \".claude\")\n if (!existsSync(claudeDir)) {\n warnings.push(\n `Agent \"${id}\": no .claude/ directory in workspace ${agent.workspace}. ` +\n `Claude Code native features (hooks, MCP, skills) won't be available.`\n )\n }\n }\n\n // Check provider availability\n const providerName = agent.provider || \"claude\"\n const providerConfig = config.providers[providerName]\n if (![\"claude-code\", \"codex-cli\", \"opencode\"].includes(agent.tier) && (!providerConfig || !providerConfig.apiKey)) {\n warnings.push(\n `Agent \"${id}\": provider \"${providerName}\" has no API key configured. ` +\n `Set providers.${providerName}.apiKey in config or use a CLI-backed tier (\"claude-code\", \"codex-cli\", or \"opencode\").`\n )\n }\n }\n\n // Validate cron agent bindings\n for (const [id, cron] of Object.entries(config.crons)) {\n if (!config.agents[cron.agent]) {\n warnings.push(`Cron \"${id}\": references unknown agent \"${cron.agent}\"`)\n }\n }\n\n // Validate channel agent bindings\n if (config.channels.telegram.enabled) {\n for (const [name, account] of Object.entries(config.channels.telegram.accounts)) {\n if (!config.agents[account.agentBinding]) {\n warnings.push(\n `Telegram account \"${name}\": references unknown agent \"${account.agentBinding}\"`\n )\n }\n }\n }\n\n return warnings\n}\n"],"mappings":"gDAAA,OAAS,KAAAA,MAAS,MAAlB,IAQMC,GAEAC,GAUAC,GAOAC,GAOAC,GAMAC,GAqBAC,GAuBAC,GAuBAC,GAcOC,EAzHbC,EAAAC,EAAA,kBAQMX,GAAUD,EAAE,KAAK,CAAC,MAAO,MAAO,MAAO,MAAO,MAAO,MAAO,KAAK,CAAC,EAElEE,GAAiBF,EAAE,OAAO,CAC9B,KAAMA,EAAE,MAAMC,EAAO,EAAE,QAAQ,CAAC,MAAO,MAAO,MAAO,MAAO,KAAK,CAAC,EAClE,MAAOD,EAAE,OA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E,QAAQ,CAAC,CAAC,EAQb,QAASA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,EAgBvC,YAAaA,EAAE,OAAO,CACpB,eAAgBA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM,EAAE,QAAQ,EAAE,EAC9D,cAAeA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,IAAI,KAAM,EAAE,QAAQ,IAAI,EAChE,qBAAsBA,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,CAAC,CAClE,CAAC,EAAE,QAAQ,CAAC,CAAC,CACf,CAAC","names":["z","dayEnum","scheduleSchema","roleSchema","orgEntrySchema","channelRefSchema","workSourceSchema","projectSchema","contactMapSchema","clientPolicySchema","businessConfigSchema","init_config","__esmMin","z","deriveStage","item","columns","set","closed","c","backlog","prefix","transitionDiff","fromColumn","toColumn","add","remove","closeIssue","reopen","boardLabelSchema","boardColumnSchema","boardReconcileSchema","boardSourceSchema","DEFAULT_COLUMNS","boardSchema","boardsConfigSchema","dashboardDaemonSchema","dashboardConfigSchema","init_config","__esmMin","z","isRestricted","level","toolWords","name","w","mcpActionWords","shellView","command","text","m","quote","_d","body","out","i","c","end","j","inner","shellSegments","view","s","commandWords","words","SHELL_KEYWORDS_SKIP","SHELL_KEYWORDS_STRIP","gitSubcommand","args","reportShellWord","cmd","base","REPORT_SHELL_COMMANDS","has","re","a","sub","rest","GIT_READ","group","action","method","GH_READ_ACTIONS","hasWritingRedirect","cleaned","reportBash","block","seg","why","ALLOW","reportTool","input","WRITE_TOOLS","REPORT_SAFE_TOOLS","mutating","MUTATING_VERBS","READ_VERBS","proposeGitPush","positional","PUSH_VALUE_OPTS","refspecs","ref","PROTECTED_BRANCH","proposeBash","rule","PROPOSE_RAW_RULES","line","baseName","PROPOSE_COMMAND_RULES","hit","proposeTool","DESTRUCTIVE_VERBS","isDelegation","evaluateAutonomy","autonomyBrief","autonomyLevelSchema","init_autonomy","__esmMin","id","reason","parseHotkey","input","raw","parts","p","key","KEY_ALIASES","mods","m","MODIFIERS","isKey","isFKey","ORDER","hotkeyError","r","describeHotkey","value","sym","names","NAMED_KEYS","DEFAULT_HOTKEYS","init_hotkey","__esmMin","k","hueOf","hex","m","r","g","b","x","max","min","paletteForColor","hue","ORB_PALETTES","p","best","bestDistance","d","distance","agentPalette","chosen","color","picked","ORB_PALETTE_IDS","init_orb_palettes","__esmMin","z","hhmm","watchRuleSchema","whatsappTriageSchema","init_config","__esmMin","r","config_exports","__export","INTEGRATION_KINDS","approvalsConfigSchema","callsSchema","cameraBotSchema","daemonConfigSchema","eventSubscriptionSchema","expandEnvVars","loadDaemonConfig","validateWorkspaces","z","readFileSync","existsSync","resolve","loadDotEnv","dir","envPath","content","line","trimmed","eqIdx","key","value","obj","_match","name","result","friendlyConfigHints","issues","configPath","hints","seen","issue","path","tgTokenMatch","account","paths","raw","foundPath","p","parsed","e","expanded","i","hintBlock","config","warnings","id","agent","claudeDir","providerName","providerConfig","cron","providerConfigSchema","mcpStdioServerSchema","mcpHttpServerSchema","mcpServerSchema","integrationCredentialsSchema","integrationSchema","voiceProviderSchema","systemVoiceSchema","hotkeySchema","voiceSchema","agentConfigSchema","telegramAccountSchema","channelsConfigSchema","cronJobSchema","serviceSchema","meshPeerSchema","meshInboxSchema","meshConfigSchema","graphConfigSchema","decisionSeatSchema","decisionsConfigSchema","notificationsSchema","screenRectSchema","screenSchema","init_config","__esmMin","init_autonomy","init_hotkey","init_orb_palettes","s","ctx","error","hotkeyError","ORB_PALETTE_IDS","autonomyLevelSchema","v","j","tz","whatsappTriageSchema","DEFAULT_HOTKEYS","businessConfigSchema","boardsConfigSchema","dashboardConfigSchema"]}