agentix-cli 0.111.0 → 0.111.1

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.
@@ -0,0 +1,4 @@
1
+ import{c as C,e as w,f as _}from"./chunk-Y4CYQV7G.js";import{existsSync as O,mkdirSync as v,readdirSync as E,readFileSync as A,renameSync as R,writeFileSync as L}from"fs";import{resolve as b}from"path";function S(e,r){let t=e.list?` in the "${e.list}" list`:"",n=[`This card came from the operator's reminder "${e.title}"${t} (id ${e.id}).`];return n.push(r?`Do what the operator chose, then tick the reminder off: remindctl complete ${e.id}`:"Leave the reminder open; it will come back at a later check-in."),n}var D=["discard","keep","pause","approve"],d={title:120,ask:300,recommend:300,source:500,note:500,pendingPerAgent:25},N={defaultExpiryDays:3,maxExpiryDays:30};function m(e){return b(e,".agentx","approvals")}var T=/^[a-z0-9][a-z0-9-]{0,80}$/;function $(e){return T.test(e)}function I(e,r){if(!$(r))throw new Error(`invalid card id: ${r}`);return b(m(e),`${r}.json`)}function q(e,r){let t=new Date(e).toISOString().slice(0,10),n=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return`${t}-${n||"card"}-${Math.random().toString(36).slice(2,6)}`}function f(e,r){v(m(e),{recursive:!0});let t=I(e,r.id),n=`${t}.${process.pid}.tmp`;L(n,JSON.stringify(r,null,2)+`
2
+ `),R(n,t)}function y(e,r){if(!$(r))return null;try{return JSON.parse(A(I(e,r),"utf-8"))}catch{return null}}function k(e,r){let t=m(e);if(!O(t))return[];let n=[];for(let i of E(t).filter(s=>s.endsWith(".json")&&!s.startsWith("_")).sort()){let s=y(e,i.slice(0,-5));s&&(!r||s.status===r)&&n.push(s)}return n}function o(e){return typeof e=="string"?e.replace(/\s+/g," ").trim():""}function j(e,r,t){let n=r+t.maxExpiryDays*864e5,i,s=o(e);if(!s)i=r+t.defaultExpiryDays*864e5;else{let a=/^(\d+)\s*([hd])$/i.exec(s);if(a)i=r+Number(a[1])*(a[2].toLowerCase()==="d"?864e5:36e5);else if(i=Date.parse(s),Number.isNaN(i))return{ok:!1,error:`expires must be an ISO date or time, or like "12h" / "3d" (got "${s}")`}}return i<=r?{ok:!1,error:"expires must be in the future"}:{ok:!0,at:new Date(Math.min(i,n)).toISOString()}}function z(e,r={}){let t=r.now??Date.now(),n=r.settings??N,i=o(e.title),s=o(e.ask),a=o(e.recommend),l=o(e.raised_by);if(!i)return{ok:!1,error:"title is required"};if(!s)return{ok:!1,error:"ask is required: the yes/no question"};if(!a)return{ok:!1,error:"recommend is required: your advice and why, in one line"};if(!l)return{ok:!1,error:"raised_by is required: the agent id"};if(i.length>d.title)return{ok:!1,error:`title is longer than ${d.title} characters`};if(s.length>d.ask)return{ok:!1,error:`ask is longer than ${d.ask} characters`};if(a.length>d.recommend)return{ok:!1,error:`recommend is longer than ${d.recommend} characters`};let x=o(e.if_silent).toLowerCase();if(!D.includes(x))return{ok:!1,error:`if_silent must be one of ${D.join(", ")}`};let g=j(e.expires,t,n);if(!g.ok)return g;let u=o(e.source);if(u.length>d.source)return{ok:!1,error:`source is longer than ${d.source} characters`};if(u&&/^[a-z][a-z0-9+.-]*:/i.test(u)&&!/^https?:\/\//i.test(u))return{ok:!1,error:"source must be an http(s) link or a plain reference"};let p=C(e);if(!p.ok)return p;let h,c=e.reply;return c&&typeof c=="object"&&o(c.channel)&&o(c.chatId)&&(h={channel:o(c.channel),chatId:o(c.chatId),...o(c.accountId)?{accountId:o(c.accountId)}:{}}),{ok:!0,card:{id:q(t,i),title:i,ask:s,recommend:a,if_silent:x,expires:g.at,...u?{source:u}:{},raised_by:l,...r.node?{node:r.node}:{},created_at:new Date(t).toISOString(),...h?{reply:h}:{},...p.value,...r.origin?{origin:r.origin}:{},status:"pending"}}}function J(e,r,t={}){let n=z(r,t);if(!n.ok)return n;let i=k(e,"pending").filter(s=>s.raised_by===n.card.raised_by).length;return i>=d.pendingPerAgent?{ok:!1,error:`${n.card.raised_by} already has ${i} cards waiting; wait for decisions before raising more`}:(f(e,n.card),n)}function P(e,r,t,n={}){let i=y(e,r);if(!i)return{ok:!1,error:`no card "${r}"`};if(i.status!=="pending")return{ok:!1,error:`card "${r}" is already ${i.status}`};let s=w(i,t,n);if(!s.ok)return s;let a=o(n.note).slice(0,d.note),l={...i,status:"decided",verdict:t,decided_by:n.by??"operator",decided_at:new Date(n.now??Date.now()).toISOString(),...a?{note:a}:{},...s.choice?{choice:s.choice}:{},...s.text?{text:s.text}:{}};return f(e,l),{ok:!0,card:l}}function U(e,r=Date.now()){let t=[];for(let n of k(e,"pending")){if(Date.parse(n.expires)>r)continue;let i={...n,status:"expired",outcome:n.if_silent,decided_by:"expiry",decided_at:new Date(r).toISOString()};f(e,i),t.push(i)}return t}function W(e){return k(e).filter(r=>r.status!=="pending"&&!r.agent_notified_at)}function G(e,r,t=Date.now()){let n=y(e,r);!n||n.agent_notified_at||f(e,{...n,agent_notified_at:new Date(t).toISOString()})}function Q(e){let r=e.status==="decided"?e.verdict==="yes"?"The operator said YES.":"The operator said NO.":`Nobody answered before it expired, so the default applied: ${e.outcome??e.if_silent}.`,t=[`[Approval result] Your decision card "${e.title}" (${e.id}) is closed.`,`Question: ${e.ask}`,r];return e.status==="decided"&&e.verdict==="yes"&&t.push(..._(e)),e.note&&t.push(`Operator note: ${e.note}`),e.source&&t.push(`Source: ${e.source}`),e.origin?.kind==="reminder"&&t.push(...S(e.origin,e.status==="decided"&&e.verdict==="yes")),e.reply&&t.push(`You raised it from ${e.reply.channel} chat ${e.reply.chatId}; reply there if the requester should know.`),e.node&&t.push(`The operator answered it on another machine; the card was forwarded from ${e.node}.`),t.push("Act on this result now. Do not raise the same card again."),t.join(`
3
+ `)}export{D as a,d as b,m as c,$ as d,y as e,k as f,J as g,P as h,U as i,W as j,G as k,Q as l};
4
+ //# sourceMappingURL=chunk-JIT5GPTX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/approvals/cards.ts","../src/approvals/origin.ts"],"sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { answerLines, buildChoices, resolveAnswer, type CardChoices } from \"./choices\"\nimport { originLines, type CardOrigin } from \"./origin\"\n\n// --- Decision cards: what an agent asks the operator ---\n//\n// An agent that needs a yes/no from the operator writes a card instead of\n// asking in chat. A card says what it is, the question, what the agent\n// recommends, and what happens if nobody answers by `expires`. Nothing\n// waits forever: past `expires` the daemon applies `if_silent` (sweep.ts).\n//\n// Storage: one JSON file per card under `.agentx/approvals/`, written\n// atomically, like wiki proposals. The CLI, the dashboard and the daemon\n// are separate processes and all read the same files.\n//\n// Field names match the API (`if_silent`, `raised_by`), so a stored card is\n// exactly what `POST /approvals` accepted.\n\nexport type IfSilent = \"discard\" | \"keep\" | \"pause\" | \"approve\"\nexport const IF_SILENT_VALUES: readonly IfSilent[] = [\"discard\", \"keep\", \"pause\", \"approve\"]\n\nexport type CardStatus = \"pending\" | \"decided\" | \"expired\"\nexport type Verdict = \"yes\" | \"no\"\n\n/** Where the agent was asked, so the verdict can be taken back there. */\nexport interface ReplyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface DecisionCard extends CardChoices {\n id: string\n title: string\n ask: string\n recommend: string\n if_silent: IfSilent\n /** ISO time the default applies. Always set. */\n expires: string\n /** Link to the draft, PR or issue. */\n source?: string\n raised_by: string\n /** The mesh node the raising agent is on, when the card was forwarded\n * here from there (forward.ts, #668). Unset: this node. */\n node?: string\n created_at: string\n reply?: ReplyTarget\n status: CardStatus\n /** The operator's answer (status \"decided\"). */\n verdict?: Verdict\n /** What applied on expiry (status \"expired\"). */\n outcome?: IfSilent\n decided_by?: string\n decided_at?: string\n note?: string\n /** The option the operator picked, when the card offered choices. */\n choice?: string\n /** The message the operator approved, after any edit. */\n text?: string\n /** Set once the raising agent has been told the result. */\n agent_notified_at?: string\n /** What the card is about, when the daemon raised it (origin.ts). */\n origin?: CardOrigin\n}\n\nexport const CARD_LIMITS = {\n title: 120,\n ask: 300,\n recommend: 300,\n source: 500,\n note: 500,\n /** Pending cards one agent may have open at a time. */\n pendingPerAgent: 25,\n} as const\n\nexport interface CardSettings {\n defaultExpiryDays: number\n maxExpiryDays: number\n}\n\nexport const DEFAULT_CARD_SETTINGS: CardSettings = { defaultExpiryDays: 3, maxExpiryDays: 30 }\n\nexport function approvalsDir(root: string): string {\n return resolve(root, \".agentx\", \"approvals\")\n}\n\nconst CARD_ID_RE = /^[a-z0-9][a-z0-9-]{0,80}$/\n\nexport function isValidCardId(id: string): boolean {\n return CARD_ID_RE.test(id)\n}\n\nfunction fileFor(root: string, id: string): string {\n if (!isValidCardId(id)) throw new Error(`invalid card id: ${id}`)\n return resolve(approvalsDir(root), `${id}.json`)\n}\n\nexport function newCardId(now: number, title: string): string {\n const day = new Date(now).toISOString().slice(0, 10)\n const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 40)\n return `${day}-${slug || \"card\"}-${Math.random().toString(36).slice(2, 6)}`\n}\n\nexport function saveCard(root: string, card: DecisionCard): void {\n mkdirSync(approvalsDir(root), { recursive: true })\n const path = fileFor(root, card.id)\n const tmp = `${path}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(card, null, 2) + \"\\n\")\n renameSync(tmp, path)\n}\n\nexport function readCard(root: string, id: string): DecisionCard | null {\n if (!isValidCardId(id)) return null\n try {\n return JSON.parse(readFileSync(fileFor(root, id), \"utf-8\")) as DecisionCard\n } catch {\n return null\n }\n}\n\n/** Cards, oldest first; only `status` ones when given. */\nexport function listCards(root: string, status?: CardStatus): DecisionCard[] {\n const dir = approvalsDir(root)\n if (!existsSync(dir)) return []\n const out: DecisionCard[] = []\n for (const f of readdirSync(dir).filter((f) => f.endsWith(\".json\") && !f.startsWith(\"_\")).sort()) {\n const c = readCard(root, f.slice(0, -5))\n if (c && (!status || c.status === status)) out.push(c)\n }\n return out\n}\n\nfunction oneLine(v: unknown): string {\n return typeof v === \"string\" ? v.replace(/\\s+/g, \" \").trim() : \"\"\n}\n\n/**\n * `expires` as given by an agent: an ISO date or time, or a relative\n * \"12h\" / \"3d\". Unset: the default. Always capped at maxExpiryDays, so a\n * card can't be parked for a year.\n */\nexport function resolveExpiry(input: unknown, now: number, settings: CardSettings): { ok: true; at: string } | { ok: false; error: string } {\n const max = now + settings.maxExpiryDays * 86_400_000\n let at: number\n const raw = oneLine(input)\n if (!raw) {\n at = now + settings.defaultExpiryDays * 86_400_000\n } else {\n const rel = /^(\\d+)\\s*([hd])$/i.exec(raw)\n if (rel) {\n at = now + Number(rel[1]) * (rel[2].toLowerCase() === \"d\" ? 86_400_000 : 3_600_000)\n } else {\n at = Date.parse(raw)\n if (Number.isNaN(at)) return { ok: false, error: `expires must be an ISO date or time, or like \"12h\" / \"3d\" (got \"${raw}\")` }\n }\n }\n if (at <= now) return { ok: false, error: \"expires must be in the future\" }\n return { ok: true, at: new Date(Math.min(at, max)).toISOString() }\n}\n\nexport interface CardInput {\n title?: unknown\n ask?: unknown\n recommend?: unknown\n if_silent?: unknown\n expires?: unknown\n source?: unknown\n raised_by?: unknown\n reply?: unknown\n choices?: unknown\n draft?: unknown\n say?: unknown\n context?: unknown\n}\n\n/** Validate what an agent sent and build a pending card. Never saves. */\nexport interface BuildCardOptions {\n now?: number\n settings?: CardSettings\n origin?: CardOrigin\n /** The peer the card was forwarded from. The daemon sets it after\n * checking the name against its mesh peers; never taken as sent. */\n node?: string\n}\n\nexport function buildCard(\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const now = opts.now ?? Date.now()\n const settings = opts.settings ?? DEFAULT_CARD_SETTINGS\n const title = oneLine(input.title)\n const ask = oneLine(input.ask)\n const recommend = oneLine(input.recommend)\n const raisedBy = oneLine(input.raised_by)\n if (!title) return { ok: false, error: \"title is required\" }\n if (!ask) return { ok: false, error: \"ask is required: the yes/no question\" }\n if (!recommend) return { ok: false, error: \"recommend is required: your advice and why, in one line\" }\n if (!raisedBy) return { ok: false, error: \"raised_by is required: the agent id\" }\n if (title.length > CARD_LIMITS.title) return { ok: false, error: `title is longer than ${CARD_LIMITS.title} characters` }\n if (ask.length > CARD_LIMITS.ask) return { ok: false, error: `ask is longer than ${CARD_LIMITS.ask} characters` }\n if (recommend.length > CARD_LIMITS.recommend) return { ok: false, error: `recommend is longer than ${CARD_LIMITS.recommend} characters` }\n const ifSilent = oneLine(input.if_silent).toLowerCase()\n if (!IF_SILENT_VALUES.includes(ifSilent as IfSilent)) {\n return { ok: false, error: `if_silent must be one of ${IF_SILENT_VALUES.join(\", \")}` }\n }\n const expiry = resolveExpiry(input.expires, now, settings)\n if (!expiry.ok) return expiry\n const source = oneLine(input.source)\n if (source.length > CARD_LIMITS.source) return { ok: false, error: `source is longer than ${CARD_LIMITS.source} characters` }\n if (source && /^[a-z][a-z0-9+.-]*:/i.test(source) && !/^https?:\\/\\//i.test(source)) {\n return { ok: false, error: \"source must be an http(s) link or a plain reference\" }\n }\n const extras = buildChoices(input)\n if (!extras.ok) return extras\n let reply: ReplyTarget | undefined\n const r = input.reply as Record<string, unknown> | undefined\n if (r && typeof r === \"object\" && oneLine(r.channel) && oneLine(r.chatId)) {\n reply = { channel: oneLine(r.channel), chatId: oneLine(r.chatId), ...(oneLine(r.accountId) ? { accountId: oneLine(r.accountId) } : {}) }\n }\n return {\n ok: true,\n card: {\n id: newCardId(now, title),\n title,\n ask,\n recommend,\n if_silent: ifSilent as IfSilent,\n expires: expiry.at,\n ...(source ? { source } : {}),\n raised_by: raisedBy,\n ...(opts.node ? { node: opts.node } : {}),\n created_at: new Date(now).toISOString(),\n ...(reply ? { reply } : {}),\n ...extras.value,\n // Set by the daemon only (check-ins), never from what an agent sent.\n ...(opts.origin ? { origin: opts.origin } : {}),\n status: \"pending\",\n },\n }\n}\n\n/** Validate, enforce the per-agent cap, and save. */\nexport function createCard(\n root: string,\n input: CardInput,\n opts: BuildCardOptions = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const built = buildCard(input, opts)\n if (!built.ok) return built\n const open = listCards(root, \"pending\").filter((c) => c.raised_by === built.card.raised_by).length\n if (open >= CARD_LIMITS.pendingPerAgent) {\n return { ok: false, error: `${built.card.raised_by} already has ${open} cards waiting; wait for decisions before raising more` }\n }\n saveCard(root, built.card)\n return built\n}\n\n/** Record the operator's answer. Refuses anything no longer pending. */\nexport function decideCard(\n root: string,\n id: string,\n verdict: Verdict,\n opts: { by?: string; note?: string; now?: number; choice?: string | number; text?: string } = {},\n): { ok: true; card: DecisionCard } | { ok: false; error: string } {\n const card = readCard(root, id)\n if (!card) return { ok: false, error: `no card \"${id}\"` }\n if (card.status !== \"pending\") return { ok: false, error: `card \"${id}\" is already ${card.status}` }\n const answer = resolveAnswer(card, verdict, opts)\n if (!answer.ok) return answer\n const note = oneLine(opts.note).slice(0, CARD_LIMITS.note)\n const decided: DecisionCard = {\n ...card,\n status: \"decided\",\n verdict,\n decided_by: opts.by ?? \"operator\",\n decided_at: new Date(opts.now ?? Date.now()).toISOString(),\n ...(note ? { note } : {}),\n ...(answer.choice ? { choice: answer.choice } : {}),\n ...(answer.text ? { text: answer.text } : {}),\n }\n saveCard(root, decided)\n return { ok: true, card: decided }\n}\n\n/** Apply `if_silent` to every pending card past its expiry. */\nexport function expireCards(root: string, now: number = Date.now()): DecisionCard[] {\n const out: DecisionCard[] = []\n for (const card of listCards(root, \"pending\")) {\n if (Date.parse(card.expires) > now) continue\n const expired: DecisionCard = {\n ...card,\n status: \"expired\",\n outcome: card.if_silent,\n decided_by: \"expiry\",\n decided_at: new Date(now).toISOString(),\n }\n saveCard(root, expired)\n out.push(expired)\n }\n return out\n}\n\n/** Decided or expired cards whose agent hasn't been told yet. */\nexport function cardsAwaitingAgentNotice(root: string): DecisionCard[] {\n return listCards(root).filter((c) => c.status !== \"pending\" && !c.agent_notified_at)\n}\n\nexport function markAgentNotified(root: string, id: string, now: number = Date.now()): void {\n const card = readCard(root, id)\n if (!card || card.agent_notified_at) return\n saveCard(root, { ...card, agent_notified_at: new Date(now).toISOString() })\n}\n\n/** What the raising agent is told. Plain text, one short message. */\nexport function verdictMessage(card: DecisionCard): string {\n const result = card.status === \"decided\"\n ? (card.verdict === \"yes\" ? \"The operator said YES.\" : \"The operator said NO.\")\n : `Nobody answered before it expired, so the default applied: ${card.outcome ?? card.if_silent}.`\n const lines = [\n `[Approval result] Your decision card \"${card.title}\" (${card.id}) is closed.`,\n `Question: ${card.ask}`,\n result,\n ]\n if (card.status === \"decided\" && card.verdict === \"yes\") lines.push(...answerLines(card))\n if (card.note) lines.push(`Operator note: ${card.note}`)\n if (card.source) lines.push(`Source: ${card.source}`)\n if (card.origin?.kind === \"reminder\") lines.push(...originLines(card.origin, card.status === \"decided\" && card.verdict === \"yes\"))\n if (card.reply) lines.push(`You raised it from ${card.reply.channel} chat ${card.reply.chatId}; reply there if the requester should know.`)\n if (card.node) lines.push(`The operator answered it on another machine; the card was forwarded from ${card.node}.`)\n lines.push(\"Act on this result now. Do not raise the same card again.\")\n return lines.join(\"\\n\")\n}\n","// --- Where a card came from, when the daemon raised it ---\n//\n// Agents raise most cards themselves. A check-in (checkin.ts) raises one on\n// an agent's behalf for an open Apple Reminder, and records the reminder\n// here so the agent that gets the answer knows what to act on and what to\n// tick off. Only the daemon sets it: POST /approvals and the agent tool\n// never pass it through.\n\nexport interface ReminderOrigin {\n kind: \"reminder\"\n /** The reminder's full id, as remindctl prints it. */\n id: string\n title: string\n list?: string\n}\n\n/** An open request that needs attention, shown as a card on the Mac\n * (popup-runner.ts). Never stored: the request is the record. */\nexport interface RequestOrigin {\n kind: \"request\"\n id: string\n}\n\nexport type CardOrigin = ReminderOrigin | RequestOrigin\n\n/** Lines for the owning agent's result message. */\nexport function originLines(origin: ReminderOrigin, approved: boolean): string[] {\n const where = origin.list ? ` in the \"${origin.list}\" list` : \"\"\n const lines = [`This card came from the operator's reminder \"${origin.title}\"${where} (id ${origin.id}).`]\n lines.push(approved\n ? `Do what the operator chose, then tick the reminder off: remindctl complete ${origin.id}`\n : \"Leave the reminder open; it will come back at a later check-in.\")\n return lines\n}\n"],"mappings":"sDAAA,OAAS,cAAAA,EAAY,aAAAC,EAAW,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KAC5F,OAAS,WAAAC,MAAe,OCyBjB,SAASC,EAAYC,EAAwBC,EAA6B,CAC/E,IAAMC,EAAQF,EAAO,KAAO,YAAYA,EAAO,aAAe,GACxDG,EAAQ,CAAC,gDAAgDH,EAAO,SAASE,SAAaF,EAAO,MAAM,EACzG,OAAAG,EAAM,KAAKF,EACP,8EAA8ED,EAAO,KACrF,iEAAiE,EAC9DG,CACT,CDbO,IAAMC,EAAwC,CAAC,UAAW,OAAQ,QAAS,SAAS,EA8C9EC,EAAc,CACzB,MAAO,IACP,IAAK,IACL,UAAW,IACX,OAAQ,IACR,KAAM,IAEN,gBAAiB,EACnB,EAOaC,EAAsC,CAAE,kBAAmB,EAAG,cAAe,EAAG,EAEtF,SAASC,EAAaC,EAAsB,CACjD,OAAOC,EAAQD,EAAM,UAAW,WAAW,CAC7C,CAEA,IAAME,EAAa,4BAEZ,SAASC,EAAcC,EAAqB,CACjD,OAAOF,EAAW,KAAKE,CAAE,CAC3B,CAEA,SAASC,EAAQL,EAAcI,EAAoB,CACjD,GAAI,CAACD,EAAcC,CAAE,EAAG,MAAM,IAAI,MAAM,oBAAoBA,GAAI,EAChE,OAAOH,EAAQF,EAAaC,CAAI,EAAG,GAAGI,QAAS,CACjD,CAEO,SAASE,EAAUC,EAAaC,EAAuB,CAC5D,IAAMC,EAAM,IAAI,KAAKF,CAAG,EAAE,YAAY,EAAE,MAAM,EAAG,EAAE,EAC7CG,EAAOF,EAAM,YAAY,EAAE,QAAQ,cAAe,GAAG,EAAE,QAAQ,WAAY,EAAE,EAAE,MAAM,EAAG,EAAE,EAChG,MAAO,GAAGC,KAAOC,GAAQ,UAAU,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,EAAG,CAAC,GAC1E,CAEO,SAASC,EAASX,EAAcY,EAA0B,CAC/DC,EAAUd,EAAaC,CAAI,EAAG,CAAE,UAAW,EAAK,CAAC,EACjD,IAAMc,EAAOT,EAAQL,EAAMY,EAAK,EAAE,EAC5BG,EAAM,GAAGD,KAAQ,QAAQ,UAC/BE,EAAcD,EAAK,KAAK,UAAUH,EAAM,KAAM,CAAC,EAAI;AAAA,CAAI,EACvDK,EAAWF,EAAKD,CAAI,CACtB,CAEO,SAASI,EAASlB,EAAcI,EAAiC,CACtE,GAAI,CAACD,EAAcC,CAAE,EAAG,OAAO,KAC/B,GAAI,CACF,OAAO,KAAK,MAAMe,EAAad,EAAQL,EAAMI,CAAE,EAAG,OAAO,CAAC,CAC5D,MAAE,CACA,OAAO,IACT,CACF,CAGO,SAASgB,EAAUpB,EAAcqB,EAAqC,CAC3E,IAAMC,EAAMvB,EAAaC,CAAI,EAC7B,GAAI,CAACuB,EAAWD,CAAG,EAAG,MAAO,CAAC,EAC9B,IAAME,EAAsB,CAAC,EAC7B,QAAWC,KAAKC,EAAYJ,CAAG,EAAE,OAAQG,GAAMA,EAAE,SAAS,OAAO,GAAK,CAACA,EAAE,WAAW,GAAG,CAAC,EAAE,KAAK,EAAG,CAChG,IAAME,EAAIT,EAASlB,EAAMyB,EAAE,MAAM,EAAG,EAAE,CAAC,EACnCE,IAAM,CAACN,GAAUM,EAAE,SAAWN,IAASG,EAAI,KAAKG,CAAC,EAEvD,OAAOH,CACT,CAEA,SAASI,EAAQC,EAAoB,CACnC,OAAO,OAAOA,GAAM,SAAWA,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAI,EACjE,CAOO,SAASC,EAAcC,EAAgBxB,EAAayB,EAAiF,CAC1I,IAAMC,EAAM1B,EAAMyB,EAAS,cAAgB,MACvCE,EACEC,EAAMP,EAAQG,CAAK,EACzB,GAAI,CAACI,EACHD,EAAK3B,EAAMyB,EAAS,kBAAoB,UACnC,CACL,IAAMI,EAAM,oBAAoB,KAAKD,CAAG,EACxC,GAAIC,EACFF,EAAK3B,EAAM,OAAO6B,EAAI,CAAC,CAAC,GAAKA,EAAI,CAAC,EAAE,YAAY,IAAM,IAAM,MAAa,cAEzEF,EAAK,KAAK,MAAMC,CAAG,EACf,OAAO,MAAMD,CAAE,EAAG,MAAO,CAAE,GAAI,GAAO,MAAO,mEAAmEC,KAAQ,EAGhI,OAAID,GAAM3B,EAAY,CAAE,GAAI,GAAO,MAAO,+BAAgC,EACnE,CAAE,GAAI,GAAM,GAAI,IAAI,KAAK,KAAK,IAAI2B,EAAID,CAAG,CAAC,EAAE,YAAY,CAAE,CACnE,CA2BO,SAASI,EACdN,EACAO,EAAyB,CAAC,EACuC,CACjE,IAAM/B,EAAM+B,EAAK,KAAO,KAAK,IAAI,EAC3BN,EAAWM,EAAK,UAAYxC,EAC5BU,EAAQoB,EAAQG,EAAM,KAAK,EAC3BQ,EAAMX,EAAQG,EAAM,GAAG,EACvBS,EAAYZ,EAAQG,EAAM,SAAS,EACnCU,EAAWb,EAAQG,EAAM,SAAS,EACxC,GAAI,CAACvB,EAAO,MAAO,CAAE,GAAI,GAAO,MAAO,mBAAoB,EAC3D,GAAI,CAAC+B,EAAK,MAAO,CAAE,GAAI,GAAO,MAAO,sCAAuC,EAC5E,GAAI,CAACC,EAAW,MAAO,CAAE,GAAI,GAAO,MAAO,yDAA0D,EACrG,GAAI,CAACC,EAAU,MAAO,CAAE,GAAI,GAAO,MAAO,qCAAsC,EAChF,GAAIjC,EAAM,OAASX,EAAY,MAAO,MAAO,CAAE,GAAI,GAAO,MAAO,wBAAwBA,EAAY,kBAAmB,EACxH,GAAI0C,EAAI,OAAS1C,EAAY,IAAK,MAAO,CAAE,GAAI,GAAO,MAAO,sBAAsBA,EAAY,gBAAiB,EAChH,GAAI2C,EAAU,OAAS3C,EAAY,UAAW,MAAO,CAAE,GAAI,GAAO,MAAO,4BAA4BA,EAAY,sBAAuB,EACxI,IAAM6C,EAAWd,EAAQG,EAAM,SAAS,EAAE,YAAY,EACtD,GAAI,CAACnC,EAAiB,SAAS8C,CAAoB,EACjD,MAAO,CAAE,GAAI,GAAO,MAAO,4BAA4B9C,EAAiB,KAAK,IAAI,GAAI,EAEvF,IAAM+C,EAASb,EAAcC,EAAM,QAASxB,EAAKyB,CAAQ,EACzD,GAAI,CAACW,EAAO,GAAI,OAAOA,EACvB,IAAMC,EAAShB,EAAQG,EAAM,MAAM,EACnC,GAAIa,EAAO,OAAS/C,EAAY,OAAQ,MAAO,CAAE,GAAI,GAAO,MAAO,yBAAyBA,EAAY,mBAAoB,EAC5H,GAAI+C,GAAU,uBAAuB,KAAKA,CAAM,GAAK,CAAC,gBAAgB,KAAKA,CAAM,EAC/E,MAAO,CAAE,GAAI,GAAO,MAAO,qDAAsD,EAEnF,IAAMC,EAASC,EAAaf,CAAK,EACjC,GAAI,CAACc,EAAO,GAAI,OAAOA,EACvB,IAAIE,EACEC,EAAIjB,EAAM,MAChB,OAAIiB,GAAK,OAAOA,GAAM,UAAYpB,EAAQoB,EAAE,OAAO,GAAKpB,EAAQoB,EAAE,MAAM,IACtED,EAAQ,CAAE,QAASnB,EAAQoB,EAAE,OAAO,EAAG,OAAQpB,EAAQoB,EAAE,MAAM,EAAG,GAAIpB,EAAQoB,EAAE,SAAS,EAAI,CAAE,UAAWpB,EAAQoB,EAAE,SAAS,CAAE,EAAI,CAAC,CAAG,GAElI,CACL,GAAI,GACJ,KAAM,CACJ,GAAI1C,EAAUC,EAAKC,CAAK,EACxB,MAAAA,EACA,IAAA+B,EACA,UAAAC,EACA,UAAWE,EACX,QAASC,EAAO,GAChB,GAAIC,EAAS,CAAE,OAAAA,CAAO,EAAI,CAAC,EAC3B,UAAWH,EACX,GAAIH,EAAK,KAAO,CAAE,KAAMA,EAAK,IAAK,EAAI,CAAC,EACvC,WAAY,IAAI,KAAK/B,CAAG,EAAE,YAAY,EACtC,GAAIwC,EAAQ,CAAE,MAAAA,CAAM,EAAI,CAAC,EACzB,GAAGF,EAAO,MAEV,GAAIP,EAAK,OAAS,CAAE,OAAQA,EAAK,MAAO,EAAI,CAAC,EAC7C,OAAQ,SACV,CACF,CACF,CAGO,SAASW,EACdjD,EACA+B,EACAO,EAAyB,CAAC,EACuC,CACjE,IAAMY,EAAQb,EAAUN,EAAOO,CAAI,EACnC,GAAI,CAACY,EAAM,GAAI,OAAOA,EACtB,IAAMC,EAAO/B,EAAUpB,EAAM,SAAS,EAAE,OAAQ2B,GAAMA,EAAE,YAAcuB,EAAM,KAAK,SAAS,EAAE,OAC5F,OAAIC,GAAQtD,EAAY,gBACf,CAAE,GAAI,GAAO,MAAO,GAAGqD,EAAM,KAAK,yBAAyBC,yDAA6D,GAEjIxC,EAASX,EAAMkD,EAAM,IAAI,EAClBA,EACT,CAGO,SAASE,EACdpD,EACAI,EACAiD,EACAf,EAA8F,CAAC,EAC9B,CACjE,IAAM1B,EAAOM,EAASlB,EAAMI,CAAE,EAC9B,GAAI,CAACQ,EAAM,MAAO,CAAE,GAAI,GAAO,MAAO,YAAYR,IAAM,EACxD,GAAIQ,EAAK,SAAW,UAAW,MAAO,CAAE,GAAI,GAAO,MAAO,SAASR,iBAAkBQ,EAAK,QAAS,EACnG,IAAM0C,EAASC,EAAc3C,EAAMyC,EAASf,CAAI,EAChD,GAAI,CAACgB,EAAO,GAAI,OAAOA,EACvB,IAAME,EAAO5B,EAAQU,EAAK,IAAI,EAAE,MAAM,EAAGzC,EAAY,IAAI,EACnD4D,EAAwB,CAC5B,GAAG7C,EACH,OAAQ,UACR,QAAAyC,EACA,WAAYf,EAAK,IAAM,WACvB,WAAY,IAAI,KAAKA,EAAK,KAAO,KAAK,IAAI,CAAC,EAAE,YAAY,EACzD,GAAIkB,EAAO,CAAE,KAAAA,CAAK,EAAI,CAAC,EACvB,GAAIF,EAAO,OAAS,CAAE,OAAQA,EAAO,MAAO,EAAI,CAAC,EACjD,GAAIA,EAAO,KAAO,CAAE,KAAMA,EAAO,IAAK,EAAI,CAAC,CAC7C,EACA,OAAA3C,EAASX,EAAMyD,CAAO,EACf,CAAE,GAAI,GAAM,KAAMA,CAAQ,CACnC,CAGO,SAASC,EAAY1D,EAAcO,EAAc,KAAK,IAAI,EAAmB,CAClF,IAAMiB,EAAsB,CAAC,EAC7B,QAAWZ,KAAQQ,EAAUpB,EAAM,SAAS,EAAG,CAC7C,GAAI,KAAK,MAAMY,EAAK,OAAO,EAAIL,EAAK,SACpC,IAAMoD,EAAwB,CAC5B,GAAG/C,EACH,OAAQ,UACR,QAASA,EAAK,UACd,WAAY,SACZ,WAAY,IAAI,KAAKL,CAAG,EAAE,YAAY,CACxC,EACAI,EAASX,EAAM2D,CAAO,EACtBnC,EAAI,KAAKmC,CAAO,EAElB,OAAOnC,CACT,CAGO,SAASoC,EAAyB5D,EAA8B,CACrE,OAAOoB,EAAUpB,CAAI,EAAE,OAAQ2B,GAAMA,EAAE,SAAW,WAAa,CAACA,EAAE,iBAAiB,CACrF,CAEO,SAASkC,EAAkB7D,EAAcI,EAAYG,EAAc,KAAK,IAAI,EAAS,CAC1F,IAAMK,EAAOM,EAASlB,EAAMI,CAAE,EAC1B,CAACQ,GAAQA,EAAK,mBAClBD,EAASX,EAAM,CAAE,GAAGY,EAAM,kBAAmB,IAAI,KAAKL,CAAG,EAAE,YAAY,CAAE,CAAC,CAC5E,CAGO,SAASuD,EAAelD,EAA4B,CACzD,IAAMmD,EAASnD,EAAK,SAAW,UAC1BA,EAAK,UAAY,MAAQ,yBAA2B,wBACrD,8DAA8DA,EAAK,SAAWA,EAAK,aACjFoD,EAAQ,CACZ,yCAAyCpD,EAAK,WAAWA,EAAK,iBAC9D,aAAaA,EAAK,MAClBmD,CACF,EACA,OAAInD,EAAK,SAAW,WAAaA,EAAK,UAAY,OAAOoD,EAAM,KAAK,GAAGC,EAAYrD,CAAI,CAAC,EACpFA,EAAK,MAAMoD,EAAM,KAAK,kBAAkBpD,EAAK,MAAM,EACnDA,EAAK,QAAQoD,EAAM,KAAK,WAAWpD,EAAK,QAAQ,EAChDA,EAAK,QAAQ,OAAS,YAAYoD,EAAM,KAAK,GAAGE,EAAYtD,EAAK,OAAQA,EAAK,SAAW,WAAaA,EAAK,UAAY,KAAK,CAAC,EAC7HA,EAAK,OAAOoD,EAAM,KAAK,sBAAsBpD,EAAK,MAAM,gBAAgBA,EAAK,MAAM,mDAAmD,EACtIA,EAAK,MAAMoD,EAAM,KAAK,4EAA4EpD,EAAK,OAAO,EAClHoD,EAAM,KAAK,2DAA2D,EAC/DA,EAAM,KAAK;AAAA,CAAI,CACxB","names":["existsSync","mkdirSync","readdirSync","readFileSync","renameSync","writeFileSync","resolve","originLines","origin","approved","where","lines","IF_SILENT_VALUES","CARD_LIMITS","DEFAULT_CARD_SETTINGS","approvalsDir","root","resolve","CARD_ID_RE","isValidCardId","id","fileFor","newCardId","now","title","day","slug","saveCard","card","mkdirSync","path","tmp","writeFileSync","renameSync","readCard","readFileSync","listCards","status","dir","existsSync","out","f","readdirSync","c","oneLine","v","resolveExpiry","input","settings","max","at","raw","rel","buildCard","opts","ask","recommend","raisedBy","ifSilent","expiry","source","extras","buildChoices","reply","r","createCard","built","open","decideCard","verdict","answer","resolveAnswer","note","decided","expireCards","expired","cardsAwaitingAgentNotice","markAgentNotified","verdictMessage","result","lines","answerLines","originLines"]}
@@ -1,4 +1,4 @@
1
- import{$ as al,Aa as qr,Ba as wl,Ca as bl,D as Gd,Da as kl,Ea as vl,F as Hd,Ga as Sl,H as Bd,I as Ur,J as Wd,K as Pe,L as qd,M as An,Na as Il,O as Gr,Oa as $l,P as Vd,Q as Br,R as Ge,S as tl,T as nl,W as He,X as sl,Xa as Vr,Y as rl,Ya as Jr,Z as il,_ as ol,_a as Tl,a as id,aa as cl,b as Mr,ca as le,da as Rn,ea as Wr,f as _r,fa as dl,g as od,ga as Et,h as ad,ha as ll,i as Ee,ia as ke,j as cd,ja as ul,k as dd,ka as hl,la as gl,m as ld,ma as En,na as Cn,o as ud,oa as pl,p as Sd,pa as ml,q as Id,r as $d,s as Td,t as xd,u as Ad,ua as fl,v as Rd,ya as yl,z as xn,za as Pn}from"./chunk-WYSNRZV4.js";import{c as nd,f as sd,g as rd}from"./chunk-U52IS3AF.js";import{m as gd,n as pd,o as Dr,p as Ce,r as md,s as pe}from"./chunk-S2GAEH2F.js";import{c as el}from"./chunk-DG5I6PPM.js";import{a as hd}from"./chunk-ZVP6GB4G.js";import{a as Ld}from"./chunk-PPUN7YHA.js";import{a as Fd,b as Ud}from"./chunk-VZLIBDLH.js";import{b as Jd,c as Xd,d as Hr,e as Kd,f as zd,g as Yd,h as Qd,i as Zd}from"./chunk-EKJG63EJ.js";import{o as Or}from"./chunk-LWYKS5JU.js";import{b as Nr}from"./chunk-ACFQBLPX.js";import{g as fd}from"./chunk-LQE73AZR.js";import{b as yd,c as wd}from"./chunk-2D3RYIDU.js";import{i as Cd,m as Fr,n as Pd,p as Md,q as _d,r as Od,s as Dd,t as Nd,u as jd}from"./chunk-XF26QNAW.js";import{b as jr,c as bd,d as Sn,e as In,g as $n,i as kd,j as vd,k as Lr,l as Tn,o as Ed}from"./chunk-RXLU6HJ6.js";import{A as dc,B as lc,C as uc,D as se,E as gc,F as pc,G as mc,H as fc,I as yc,J as wc,K as bc,L as Gc,M as Hc,N as Bc,O as Wc,P as qc,Q as Vc,U as Kc,a as Da,b as Ir,c as ja,ca as zc,d as qa,e as Va,f as Tt,h as Tr,i as xr,j as Ar,k as Ja,l as Xa,s as Ka,t as Qa,u as xt,v as Za,w as nc,x as B,z as cc}from"./chunk-DTQQ4DAY.js";import{B as Xc,a as za,c as ec,d as tc,e as Ue,f as et,l as kc,m as vc,o as _c,p as Oc,q as Lc,r as Fc,t as Uc,v as Jc}from"./chunk-53OS4TDU.js";import{b as Rc,c as Ec,d as Cr,f as wn,g as Cc,h as Pc,i as Mc,j as At,k as bn}from"./chunk-GLQLCBJS.js";import{a as Rr,b as Ya}from"./chunk-6W74CHNW.js";import{A as Yc,B as kn,C as Qc,h as ra,n as ia,o as hr}from"./chunk-HCTWKWS3.js";import{b as ta}from"./chunk-SFQUP3BP.js";import{a as Zc,b as vn,c as ed,d as td}from"./chunk-LLNPKE7H.js";import{a as nt,b as st}from"./chunk-SHEUCITK.js";import{a as Rt}from"./chunk-Y4CYQV7G.js";import{a as Sc,b as Er,c as Ic,d as $c,e as Tc,i as xc}from"./chunk-76Z4VHDX.js";import{b as hc}from"./chunk-W4YR2RO2.js";import{b as ne,d as tt,f as mn,g as fn,i as ie,j as Ac,k as Ae,l as Re,m as jc,s as Pr}from"./chunk-M2L6S3Z5.js";import{a as Dc,b as Nc}from"./chunk-QJP37VVA.js";import{d as sc,e as rc,f as ic,g as oc,h as ac,j as yn}from"./chunk-X5C5W3E4.js";import{c as Oa}from"./chunk-MYVHVJWZ.js";import{d as La,e as Fa,f as $r,g as pn,h as Ua,i as Ga,j as Ha,k as Ba,q as Wa}from"./chunk-AV7T3SYT.js";import{b as Na}from"./chunk-2GIDVZ4H.js";import{d as oa,e as Gf,m as Pa,n as Yf,q as Ma,v as _a,y as Ze,z as gn}from"./chunk-GQMUFSKB.js";import{a as Fe,b as $t,f as Sr}from"./chunk-72SZI2UW.js";import{a as gr,b as Uf}from"./chunk-FCPTN6NF.js";import{a as an,b as Ff}from"./chunk-7I7IEX4S.js";import{b as na,e as sa}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as Jf,B as ka,D as kr,F as va,G as Sa,H as hn,I as Ia,J as $a,K as Ta,L as xa,M as Xf,P as Aa,S as Ra,T as Ea,X as Kf,d as Qe,e as aa,f as pr,g as Bf,h as cn,i as mr,ia as vr,j as dn,ja as Ca,l as je,la as zf,m as fr,p as ln,q as Wf,r as un,s as ca,t as qf,z as ba}from"./chunk-SIOWVLZG.js";import{a as ua,b as ha,c as ga,e as pa,f as wr,g as ma,h as fa,i as br,j as ya,k as wa,n as Vf}from"./chunk-UIBUZ2N3.js";import{e as Le,f as da,g as la,h as yr}from"./chunk-BRK6M6LA.js";import{e as Hf}from"./chunk-2QNT5JDS.js";import{d as Ye}from"./chunk-QIJLFPWE.js";import{existsSync as Qf,readFileSync as Zf}from"fs";var xl=["answer","narration","line"];function Al(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Rl(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),l=String(s.kind??"line");if(!c||!d||!xl.includes(l))return{status:400,body:{error:`Required: text and agentId; kind is ${xl.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(d);if(!u)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:m,done:f}=r.enqueue({voice:u,text:c,agentId:d,kind:l});return s.wait!==!0?{status:202,body:{item:m}}:{status:200,body:{item:m,played:await f}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Xr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Xr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Xr(i)}default:return{status:404,body:{error:"Not found"}}}}function El(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
1
+ import{$ as sl,$a as Vr,Ca as yl,D as Ud,Da as Pn,Ea as qr,Fa as wl,Ga as bl,H as Gd,Ha as kl,Ia as vl,J as Hd,Ka as Sl,L as Bd,M as Ur,N as Wd,O as Pe,P as qd,Q as An,Ra as Il,S as Gr,Sa as $l,T as Vd,U as Br,V as Ge,W as tl,X as nl,_ as He,a as id,aa as rl,ab as Jr,b as Mr,ba as il,ca as ol,cb as Tl,da as al,ea as cl,f as _r,g as od,ga as le,h as ad,ha as Rn,i as Ee,ia as Wr,j as cd,ja as dl,k as dd,ka as Et,la as ll,m as ld,ma as ke,na as ul,o as ud,oa as hl,p as Sd,pa as gl,q as Id,qa as En,r as $d,ra as Cn,s as Td,sa as pl,t as xd,ta as ml,u as Ad,v as Rd,ya as fl,z as xn}from"./chunk-3RTOS727.js";import{c as nd,f as sd,g as rd}from"./chunk-U52IS3AF.js";import{m as gd,n as pd,o as Dr,p as Ce,r as md,s as pe}from"./chunk-S2GAEH2F.js";import{c as el}from"./chunk-DG5I6PPM.js";import{a as hd}from"./chunk-ZVP6GB4G.js";import{a as jd}from"./chunk-PPUN7YHA.js";import{a as Ld,b as Fd}from"./chunk-VZLIBDLH.js";import{b as Jd,c as Xd,d as Hr,e as Kd,f as zd,g as Yd,h as Qd,i as Zd}from"./chunk-EKJG63EJ.js";import{o as Or}from"./chunk-LWYKS5JU.js";import{b as Nr}from"./chunk-ACFQBLPX.js";import{g as fd}from"./chunk-LQE73AZR.js";import{b as yd,c as wd}from"./chunk-2D3RYIDU.js";import{i as Ed,m as Fr,n as Cd,p as Pd,q as Md,r as _d,s as Od,t as Dd,u as Nd}from"./chunk-QLWGLRT5.js";import{b as jr,c as bd,d as Sn,e as In,g as $n,i as kd,j as vd,k as Lr,l as Tn}from"./chunk-JIT5GPTX.js";import{A as dc,B as lc,C as uc,D as se,E as gc,F as pc,G as mc,H as fc,I as yc,J as wc,K as bc,L as Gc,M as Hc,N as Bc,O as Wc,P as qc,Q as Vc,U as Kc,a as Da,b as Ir,c as ja,ca as zc,d as qa,e as Va,f as Tt,h as Tr,i as xr,j as Ar,k as Ja,l as Xa,s as Ka,t as Qa,u as xt,v as Za,w as nc,x as B,z as cc}from"./chunk-DTQQ4DAY.js";import{B as Xc,a as za,c as ec,d as tc,e as Ue,f as et,l as kc,m as vc,o as _c,p as Oc,q as Lc,r as Fc,t as Uc,v as Jc}from"./chunk-53OS4TDU.js";import{b as Rc,c as Ec,d as Cr,f as wn,g as Cc,h as Pc,i as Mc,j as At,k as bn}from"./chunk-GLQLCBJS.js";import{a as Rr,b as Ya}from"./chunk-6W74CHNW.js";import{A as Yc,B as kn,C as Qc,h as ra,n as ia,o as hr}from"./chunk-HCTWKWS3.js";import{b as ta}from"./chunk-SFQUP3BP.js";import{a as Zc,b as vn,c as ed,d as td}from"./chunk-LLNPKE7H.js";import{a as nt,b as st}from"./chunk-SHEUCITK.js";import{a as Rt}from"./chunk-Y4CYQV7G.js";import{a as Sc,b as Er,c as Ic,d as $c,e as Tc,i as xc}from"./chunk-76Z4VHDX.js";import{b as hc}from"./chunk-W4YR2RO2.js";import{b as ne,d as tt,f as mn,g as fn,i as ie,j as Ac,k as Ae,l as Re,m as jc,s as Pr}from"./chunk-M2L6S3Z5.js";import{a as Dc,b as Nc}from"./chunk-QJP37VVA.js";import{d as sc,e as rc,f as ic,g as oc,h as ac,j as yn}from"./chunk-X5C5W3E4.js";import{c as Oa}from"./chunk-MYVHVJWZ.js";import{d as La,e as Fa,f as $r,g as pn,h as Ua,i as Ga,j as Ha,k as Ba,q as Wa}from"./chunk-AV7T3SYT.js";import{b as Na}from"./chunk-2GIDVZ4H.js";import{d as oa,e as Gf,m as Pa,n as Yf,q as Ma,v as _a,y as Ze,z as gn}from"./chunk-GQMUFSKB.js";import{a as Fe,b as $t,f as Sr}from"./chunk-72SZI2UW.js";import{a as gr,b as Uf}from"./chunk-FCPTN6NF.js";import{a as an,b as Ff}from"./chunk-7I7IEX4S.js";import{b as na,e as sa}from"./chunk-JHCI6XCJ.js";import{e as Ne}from"./chunk-DSYKYZMT.js";import{A as Jf,B as ka,D as kr,F as va,G as Sa,H as hn,I as Ia,J as $a,K as Ta,L as xa,M as Xf,P as Aa,S as Ra,T as Ea,X as Kf,d as Qe,e as aa,f as pr,g as Bf,h as cn,i as mr,ia as vr,j as dn,ja as Ca,l as je,la as zf,m as fr,p as ln,q as Wf,r as un,s as ca,t as qf,z as ba}from"./chunk-SIOWVLZG.js";import{a as ua,b as ha,c as ga,e as pa,f as wr,g as ma,h as fa,i as br,j as ya,k as wa,n as Vf}from"./chunk-UIBUZ2N3.js";import{e as Le,f as da,g as la,h as yr}from"./chunk-BRK6M6LA.js";import{e as Hf}from"./chunk-2QNT5JDS.js";import{d as Ye}from"./chunk-QIJLFPWE.js";import{existsSync as Qf,readFileSync as Zf}from"fs";var xl=["answer","narration","line"];function Al(r){return r==="/voice/queue"||r.startsWith("/voice/queue/")}async function Rl(r,e,t,n,s){if(n==="/voice/queue"){if(t==="GET")return{status:200,body:r.view()};if(t!=="POST")return{status:405,body:{error:"GET or POST"}};let c=String(s.text??"").trim(),d=String(s.agentId??s.agent??""),l=String(s.kind??"line");if(!c||!d||!xl.includes(l))return{status:400,body:{error:`Required: text and agentId; kind is ${xl.join(" | ")}`}};if(c.length>5e3)return{status:413,body:{error:"text is over 5000 characters"}};let u=e(d);if(!u)return{status:404,body:{error:`Unknown agent: ${d}`}};let{item:m,done:f}=r.enqueue({voice:u,text:c,agentId:d,kind:l});return s.wait!==!0?{status:202,body:{item:m}}:{status:200,body:{item:m,played:await f}}}if(t==="POST"&&n==="/voice/queue/pause")return r.pause(),{status:200,body:r.view()};if(t==="POST"&&n==="/voice/queue/resume")return r.resume(),{status:200,body:r.view()};let[,,,i,o,a]=n.split("/");if(t!=="POST"||!i||a!==void 0)return{status:404,body:{error:"Not found"}};switch(o){case"skip":return r.skip(i)?{status:200,body:r.view()}:Xr(i);case"front":return r.front(i)?{status:200,body:r.view()}:Xr(i);case"replay":{let c=r.replay(i);return c?{status:202,body:{item:c}}:Xr(i)}default:return{status:404,body:{error:"Not found"}}}}function El(r){let e=n=>`${n.agentId??"someone"} (${n.kind}): "${n.text.length>80?`${n.text.slice(0,79)}\u2026`:n.text}" [${n.id}]`;return[r.playing?`Speaking: ${e(r.playing)}`:r.paused?"Paused: the listener is speaking; the queue plays on after.":"Nothing is speaking.",...r.waiting.map((n,s)=>`${s+1}. waiting: ${e(n)}`)].join(`
2
2
  `)}var Xr=r=>({status:404,body:{error:`No such line in the queue: ${r}`}});import{resolve as ey}from"path";var ty={name:"agentx",version:"0.1.0"},ny="2024-11-05",sy={tools:{},elicitation:{form:{}}},ry=0;async function Cl(r,e){let t=++ry;return Be({jsonrpc:"2.0",id:`elicit-${t}`,method:"elicitation/create",params:{mode:"form",message:r,requestedSchema:e}}),new Promise(n=>{Ct.set(`elicit-${t}`,s=>{s?.action==="accept"&&s.content?n(s.content):n(null)}),setTimeout(()=>{Ct.has(`elicit-${t}`)&&(Ct.delete(`elicit-${t}`),n(null))},6e4)})}var Ct=new Map,iy="http://localhost:19900",Kr;function oy(){if(process.env.AGENTX_DAEMON_URL)return process.env.AGENTX_DAEMON_URL;for(let r of["agentx.json",".agentx/config.json"])try{let e=ey(process.cwd(),r);if(!Qf(e))continue;let t=JSON.parse(Zf(e,"utf-8"))?.node?.bind;if(typeof t!="string"||!t.includes(":"))continue;{let n=t.lastIndexOf(":"),s=t.slice(0,n),i=t.slice(n+1),o=!s||s==="0.0.0.0"||s==="::"||s==="*"?"127.0.0.1":s;if(i)return`http://${o}:${i}`}}catch{}return iy}function V(){return Kr===void 0&&(Kr=oy()),Kr}function zr(r=process.env){let e={};return r.AGENTX_TASK_ID&&(e.callerTaskId=r.AGENTX_TASK_ID),r.AGENTX_CHANNEL&&(e.callerChannel=r.AGENTX_CHANNEL),r.AGENTX_CHAT_ID&&(e.callerChatId=r.AGENTX_CHAT_ID),e}async function ay(){let r=process.env.AGENTX_AGENT_ID,e=zr();if(!(!r||!e.callerChannel||!e.callerChatId))try{let t=new URLSearchParams({channel:e.callerChannel,chatId:e.callerChatId}),n=await fetch(`${V()}/agents/${encodeURIComponent(r)}/intent-path?${t}`,{signal:AbortSignal.timeout(2e3)});if(!n.ok)return;let s=await n.json();return{...Array.isArray(s.path)&&s.path.length?{path:s.path}:{},...typeof s.graphWeight=="number"?{graphWeight:s.graphWeight}:{}}}catch{return}}var cy=/\x1B\[[0-9;]*[A-Za-z]/g;function rt(r){return r.replace(cy,"")}async function dy(r,e,t){let n=await fetch(`${V()}/recall`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:r,channel:e,limit:Math.min(Math.max(t??30,1),100)})}),s=await n.json().catch(()=>({}));if(!n.ok)return{content:[{type:"text",text:`Error: ${s.error||n.statusText}`}]};let i=s.turns||[],o=e?`on ${e}`:"on any channel";return i.length===0?{content:[{type:"text",text:`No other messages ${o} today for ${r}.`}]}:{content:[{type:"text",text:ly(i,!!s.hasMore)}]}}function ly(r,e){let t=new Map;for(let s of r){let i=`${s.channel}/${s.chatId}`;t.has(i)||t.set(i,[]),t.get(i).push(s)}let n=[];for(let[s,i]of t){let o=[...i].sort((a,c)=>a.ts.localeCompare(c.ts)).map(a=>{let c=a.role==="agent"?"you":a.senderName||"user";return` [${a.ts.slice(11,16)}] ${c}: ${a.content.slice(0,300)}`});n.push(`From ${s}:
3
3
  ${o.join(`
4
4
  `)}`)}return e&&n.push("[older turns exist \u2014 pass a chatId, or call /recall with before=<ts>]"),n.join(`
@@ -520,7 +520,7 @@ ${d}`)}let S={agentId:o,message:k,context:{channel:y,sender:p?"opencode":"openai
520
520
 
521
521
  `)}}function Vu(r){r.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"})}function Ju(r,e,t,n,s,i){r.write(`data: ${JSON.stringify({id:e,object:"chat.completion.chunk",created:t,model:n,choices:[{index:0,delta:s,finish_reason:i}]})}
522
522
 
523
- `)}function Xu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);vi(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function vi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Ft=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Ft(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Ft.levelOrder[e]<Ft.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Lt=Ft;Ye(Lt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as hb,statSync as gb}from"fs";var ut={version:"0.111.0",commit:"57e0b02",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function pb(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function zu(){let r=null;try{r=gb(hb(process.argv[1])).mtimeMs}catch{}let e=fu().version;return pb(ut,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as mb}from"crypto";var ss=class{constructor(e=new nc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!fb.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};wb(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:mb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=yb(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},fb=["run","task","signal","mesh","channel","status"];function yb(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function wb(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Yu(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as rs,timingSafeEqual as Qu}from"crypto";var is=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(b[k]=S);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let m=this.extractEventType(d,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===d),p=m&&f?.triggers?.[m]||f?.defaultWorkflow||null;if(await this.fireHookSafe(d,m,i,c),p&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:p,entityRef:{kind:"webhook",id:`${d}:${i}:${m??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:m,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${m??"\u2014"}] -> workflow=${p} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:m,workflow:p,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${d}/${m}/${p}]: ${b.message}`)}let y=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===d);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(b=>this.log(`Mesh-forwarded webhook [${d}] -> ${y.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${d}] -> ${y.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:d,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
523
+ `)}function Xu(r,e,t,n,s,i){let o=i?.usage?.inputTokens??0,a=i?.usage?.outputTokens??Math.ceil(s.length/4);vi(r,200,{id:e,object:"chat.completion",created:t,model:n,choices:[{index:0,message:{role:"assistant",content:s},finish_reason:"stop"}],usage:{prompt_tokens:o,completion_tokens:a,total_tokens:o+a}})}function vi(r,e,t){r.writeHead(e,{"Content-Type":"application/json"}),r.end(JSON.stringify(t))}var Ft=class{module;minLevel;constructor(e,t="info"){this.module=e,this.minLevel=t}child(e){return new Ft(`${this.module}:${e}`,this.minLevel)}debug(e,t){this.emit("debug",e,t)}info(e,t){this.emit("info",e,t)}warn(e,t){this.emit("warn",e,t)}error(e,t){this.emit("error",e,t)}asConsoleLog(){return(...e)=>{let n=e.map(s=>typeof s=="string"?s:JSON.stringify(s)).join(" ").replace(/^\[agentx\]\s*/,"");n&&this.info(n)}}emit(e,t,n){if(Ft.levelOrder[e]<Ft.levelOrder[this.minLevel])return;let s={time:new Date().toISOString(),level:e,module:this.module,msg:t,...n},i=e==="error"?"ERROR":e==="warn"?"WARN":"",o=`[${this.module}]`,a=i?`${o} ${i}: ${t}`:`${o} ${t}`;console.error(a)}},Lt=Ft;Ye(Lt,"levelOrder",{debug:0,info:1,warn:2,error:3});import{realpathSync as hb,statSync as gb}from"fs";var ut={version:"0.111.1",commit:"f48477b",startedAt:new Date(Date.now()-process.uptime()*1e3).toISOString()};function pb(r,e){let t=e.mtimeMs!==null&&e.mtimeMs>Date.parse(r.startedAt),n=!!e.version&&!!r.version&&e.version!==r.version;return{newer:t||n,changedAt:e.mtimeMs===null?null:new Date(e.mtimeMs).toISOString(),version:e.version}}function zu(){let r=null;try{r=gb(hb(process.argv[1])).mtimeMs}catch{}let e=fu().version;return pb(ut,{mtimeMs:r,version:e&&e!=="0.0.0"?e:null})}import{randomUUID as mb}from"crypto";var ss=class{constructor(e=new nc){this.core=e}count=0;subscribe(e,t){this.count++;let n=this.core.subscribe((i,o)=>{if(!o||!fb.includes(o.kind))return;let a={...o,rootId:i.rootId,node:i.node};wb(e,a)&&t(a)}),s=!0;return()=>{s&&(s=!1,this.count--,n())}}publish(e){let t={id:typeof e.id=="string"?e.id:mb(),at:typeof e.at=="string"?e.at:new Date().toISOString(),...e},{type:n,summary:s,ref:i,agentId:o}=yb(t);this.core.publish({id:t.id,at:t.at,kind:t.kind,type:n,summary:s,ref:i,agentId:o,rootId:typeof e.rootId=="string"?e.rootId:void 0,data:t})}get size(){return this.count}},fb=["run","task","signal","mesh","channel","status"];function yb(r){switch(r.kind){case"run":return{type:r.phase,ref:r.runId,summary:[r.workflowId,r.nodeId,r.phase,r.note].filter(Boolean).join(" ")};case"task":return{type:r.phase,ref:r.taskId,summary:`${r.title??r.taskId} ${r.phase}`};case"signal":return{type:"emitted",summary:`signal ${r.name} (${r.scope})`};case"mesh":return{type:r.delta,summary:`peer ${r.peer} ${r.delta}`};case"channel":return{type:r.direction,ref:r.messageId,agentId:r.agentId,summary:`${r.channel} ${r.direction==="in"?"inbound":"outbound"}`};case"status":return{type:"status",summary:r.message}}}function wb(r,e){return!(r.kinds&&r.kinds.length>0&&!r.kinds.includes(e.kind)||r.workflowId&&(e.kind==="run"&&e.workflowId!==r.workflowId||e.kind==="task"&&e.workflowId!==r.workflowId||e.kind==="signal"&&e.workflowId&&e.workflowId!==r.workflowId)||r.runId&&(e.kind==="run"&&e.runId!==r.runId||e.kind==="task"&&e.runId!==r.runId)||r.actor&&(e.kind!=="task"||!(e.assignedTo?.includes(r.actor)||e.submittedBy===r.actor))||r.channel&&(e.kind!=="channel"||e.channel!==r.channel))}function Yu(r){if(!r)return;let e=["run","task","signal","mesh","channel","status"],n=r.split(",").map(s=>s.trim()).filter(Boolean).filter(s=>e.includes(s));return n.length?n:void 0}import{createHmac as rs,timingSafeEqual as Qu}from"crypto";var is=class{registry;config;mesh;webhookEntries;log;workflowDispatcher;hooks;constructor(e,t={},n=console.error.bind(console,"[webhook]"),s,i=[],o){this.registry=e,this.config=t,this.log=n,this.mesh=s,this.webhookEntries=i,this.hooks=o}hookEventFor(e,t){if(e==="stripe")return"on:stripe-event";if(e==="sentry")return"on:sentry-issue";if(e==="vercel")return"on:vercel-deployment";if(e==="hubspot")return"on:hubspot-event";if(e==="odoo")return"on:odoo-event";if(e==="github"){let n=(t??"").split(".")[0];return n==="issues"||n==="issue_comment"?"on:github-issue":n==="pull_request"||n==="pull_request_review"?"on:github-pr":n==="push"?"on:github-push":null}return null}async fireHookSafe(e,t,n,s){let i=this.hookEventFor(e,t);if(!i||!this.hooks||!this.hooks.has(i))return;let o={};if(e==="github"){let a=s;typeof a.sender?.login=="string"&&(o.author=a.sender.login),typeof a.repository?.full_name=="string"&&(o.repo=a.repository.full_name);let c=a.issue?.number??a.pull_request?.number;typeof c=="number"&&(o.number=c)}try{await this.hooks.execute(i,{event:i,source:e,eventType:t,agentId:n,payload:s,...o})}catch(a){this.log(`${i} hook error (non-fatal): ${a?.message??a}`)}}setWorkflowDispatcher(e){this.workflowDispatcher=e}setWebhookEntries(e){this.webhookEntries=e}async handle(e,t,n){let s=n.replace(/^\/webhook\/?/,"").split("/").filter(Boolean),i=s[0],o=s[1];if(!i){this.sendJson(t,400,{error:"Missing agent ID. Use /webhook/:agentId"});return}let{raw:a,parsed:c}=await this.readBody(e),d=o||this.detectSource(e.headers);if(process.env.AGENTX_WEBHOOK_DEBUG_HEADERS==="1"){let b={};for(let[k,S]of Object.entries(e.headers))(k.startsWith("x-hubspot")||k.startsWith("x-hub")||k.startsWith("x-github")||k.startsWith("x-gitlab")||k.startsWith("stripe")||k.startsWith("sentry")||k.startsWith("x-vercel")||k.startsWith("x-odoo")||k.startsWith("x-webhook")||k==="user-agent"||k==="content-type"||k==="host"||k==="x-forwarded-host"||k==="x-forwarded-proto"||k==="x-forwarded-for")&&(b[k]=S);this.log(`Webhook [${d}] reqUrl=${e.url} headers: ${JSON.stringify(b)}`)}let l=this.validateSignature(e.headers,a,d,i,e.url);if(l){this.log(`Webhook [${d}] -> ${i}: REJECTED (${l})`),this.sendJson(t,401,{error:l});return}let u=this.buildSummary(d,c,e.headers);this.log(`Webhook [${d}] -> ${i}: ${u.slice(0,100)}`);let m=this.extractEventType(d,c,e.headers),f=this.webhookEntries.find(b=>b.enabled&&b.agentId===i&&b.source===d),p=m&&f?.triggers?.[m]||f?.defaultWorkflow||null;if(await this.fireHookSafe(d,m,i,c),p&&this.workflowDispatcher)try{let b=await this.workflowDispatcher.dispatchWorkflow({workflowId:p,entityRef:{kind:"webhook",id:`${d}:${i}:${m??"\u2014"}:${Date.now()}`},event:{kind:"webhook",source:d,eventType:m,payload:c},trigger:{source:d}});this.log(`Webhook [${d}/${m??"\u2014"}] -> workflow=${p} (claimed=${b.claimed})`),this.sendJson(t,202,{ok:!0,agent:i,source:d,eventType:m,workflow:p,claimed:b.claimed});return}catch(b){this.log(`Workflow dispatch failed [${d}/${m}/${p}]: ${b.message}`)}let y=this.webhookEntries.find(b=>b.enabled&&b.node&&b.agentId===i&&b.source===d);if(y?.node&&this.mesh){this.sendJson(t,202,{ok:!0,agent:i,source:d,node:y.node,status:"accepted"}),this.mesh.sendTask(y.node,u,i,{context:{channel:`webhook:${d}`,sender:`webhook:${d}`}}).then(b=>this.log(`Mesh-forwarded webhook [${d}] -> ${y.node}/${i}: ${b?.slice(0,100)||"ok"}`),b=>this.log(`Mesh forward failed [${d}] -> ${y.node}/${i}: ${b.message}`));return}try{let b=await this.registry.execute({message:u,agentId:i,context:{channel:`webhook:${d}`,sender:`webhook:${d}`}});this.sendJson(t,b.error?500:200,{ok:!b.error,agent:i,source:d,response:b.content?.slice(0,500),error:b.error,duration:b.duration})}catch(b){this.sendJson(t,500,{error:b.message})}}extractEventType(e,t,n){let s=i=>{let o=n[i.toLowerCase()];return Array.isArray(o)?o[0]:o};if(e==="github"){let i=s("x-github-event");if(!i)return;let o=typeof t.action=="string"?t.action:void 0;return o?`${i}.${o}`:i}if(e==="gitlab")return s("x-gitlab-event")||(typeof t.object_kind=="string"?t.object_kind:void 0);if(e==="stripe")return typeof t.type=="string"?t.type:void 0;if(e==="sentry")return s("sentry-hook-resource");if(e==="hubspot"){if(Array.isArray(t)&&t.length>0){let i=t[0];if(i&&typeof i.subscriptionType=="string")return i.subscriptionType}return typeof t.subscriptionType=="string"?t.subscriptionType:void 0}if(e==="odoo")return typeof t.event=="string"?t.event:typeof t.subscriptionType=="string"?t.subscriptionType:typeof t.model=="string"?typeof t.action=="string"?`${t.model}.${t.action}`:t.model:void 0}detectSource(e){return e["x-gitlab-event"]||e["x-gitlab-token"]?"gitlab":e["x-github-event"]?"github":e["stripe-signature"]?"stripe":e["sentry-hook-resource"]?"sentry":e["x-vercel-signature"]?"vercel":e["x-hubspot-signature-v3"]||e["x-hubspot-signature-version"]?"hubspot":e["x-odoo-database"]||e["x-odoo-signature"]?"odoo":e["x-hub-signature-256"]?"github":"unknown"}buildSummary(e,t,n){let s=[`[Webhook from ${e}]`];switch(e){case"gitlab":{let o=n["x-gitlab-event"]||t.object_kind||"event",a=t.project?.path_with_namespace||"",c=t.user?.name||t.user_username||"";if(s.push(`Event: ${o}`),a&&s.push(`Project: ${a}`),c&&s.push(`User: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits)){s.push(`Commits: ${t.commits.length}`);for(let l of t.commits.slice(0,3))s.push(` - ${l.message?.split(`
524
524
  `)[0]||"no message"} (${l.author?.name||""})`)}let d=t.object_attributes;if(d?.title&&(s.push(`Title: ${d.title}`),s.push(`State: ${d.state||""}`),s.push(`Action: ${d.action||""}`),d.source_branch&&s.push(`Branch: ${d.source_branch} -> ${d.target_branch}`),d.url&&s.push(`URL: ${d.url}`)),d?.iid&&!d?.source_branch&&(s.push(`Issue #${d.iid}: ${d.title||""}`),d.description&&s.push(`Description: ${d.description.slice(0,200)}`)),t.object_kind==="pipeline"){let l=t.object_attributes;s.push(`Pipeline: ${l?.status||""} (${l?.ref||""})`),s.push(`Duration: ${l?.duration||0}s`)}break}case"github":{let o=n["x-github-event"]||"event",a=t.repository?.full_name||"",c=t.sender?.login||"";if(s.push(`Event: ${o}`),a&&s.push(`Repository: ${a}`),c&&s.push(`Sender: ${c}`),t.ref&&s.push(`Ref: ${t.ref}`),t.commits&&Array.isArray(t.commits))for(let u of t.commits.slice(0,3))s.push(` - ${u.message?.split(`
525
525
  `)[0]||""} (${u.author?.name||""})`);let d=t.pull_request;d&&(s.push(`PR #${d.number}: ${d.title}`),s.push(`Action: ${t.action}`),s.push(`Branch: ${d.head?.ref} -> ${d.base?.ref}`));let l=t.issue;l&&(s.push(`Issue #${l.number}: ${l.title}`),s.push(`Action: ${t.action}`));break}case"stripe":{let o=t.type||"event",a=t.data?.object||{};s.push(`Event: ${o}`),a.amount&&s.push(`Amount: ${(a.amount/100).toFixed(2)} ${a.currency?.toUpperCase()||""}`),a.customer_email&&s.push(`Customer: ${a.customer_email}`),a.description&&s.push(`Description: ${a.description}`),a.status&&s.push(`Status: ${a.status}`);break}case"sentry":{let o=n["sentry-hook-resource"]||"event";s.push(`Resource: ${o}`);let a=t.data||t;a.error?.title&&s.push(`Error: ${a.error.title}`),a.error?.culprit&&s.push(`Culprit: ${a.error.culprit}`),a.error?.metadata?.value&&s.push(`Message: ${a.error.metadata.value}`),t.url&&s.push(`URL: ${t.url}`);break}case"hubspot":{let o=Array.isArray(t)?t:null,a=o||null;if(a&&a.length){s.push(`Events: ${a.length}`);for(let d of a.slice(0,3)){let l=d.subscriptionType??"?",u=d.objectId??"?",m=d.changeFlag??d.changeSource??"";s.push(` - ${l} (object ${u}${m?`, ${m}`:""})`)}}else{let d=t.subscriptionType??"event",l=t.objectId??"?";s.push(`Event: ${d} (object ${l})`)}let c=a?.[0]?.portalId??t.portalId;c!=null&&s.push(`Portal: ${c}`);break}case"odoo":{let o=typeof t.event=="string"&&t.event||typeof t.subscriptionType=="string"&&t.subscriptionType||typeof t.model=="string"&&(typeof t.action=="string"?`${t.model}.${t.action}`:t.model)||"event";s.push(`Event: ${o}`);let a=n["x-odoo-database"]||(typeof t.database=="string"?t.database:"");a&&s.push(`Database: ${a}`);let c=t.record||t;c?.id&&s.push(`Record id: ${c.id}`),c?.name&&s.push(`Name: ${String(c.name).slice(0,200)}`),c?.partner_id?.[1]&&s.push(`Partner: ${c.partner_id[1]}`),c?.email&&s.push(`Email: ${c.email}`),c?.amount_total!=null&&s.push(`Amount: ${c.amount_total}`),c?.state&&s.push(`State: ${c.state}`);break}default:s.push(`Headers: ${JSON.stringify(Object.keys(n).filter(o=>o.startsWith("x-")).slice(0,5))}`),s.push(`Payload keys: ${Object.keys(t).slice(0,10).join(", ")}`);let i=JSON.stringify(t).slice(0,500);s.push(`Body: ${i}`)}return s.join(`
526
526
  `)}async readBody(e){return new Promise(t=>{let n="";e.on("data",s=>n+=s.toString()),e.on("end",()=>{let s;try{s=n?JSON.parse(n):{}}catch{s={raw:n}}t({raw:n,parsed:s})}),e.on("error",()=>t({raw:"",parsed:{}}))})}validateSignature(e,t,n,s,i){let o=this.webhookEntries.find(l=>l.enabled&&l.agentId===s&&l.source===n);if(!o?.secretEnv)return null;let a=process.env[o.secretEnv];if(!a)return`webhook entry "${o.id}" expects env ${o.secretEnv} but it is unset`;let c=l=>{let u=e[l.toLowerCase()];return Array.isArray(u)?u[0]:u};if(n==="github"){let l=c("x-hub-signature-256");if(!l)return"missing X-Hub-Signature-256";let u="sha256="+rs("sha256",a).update(t).digest("hex");return ht(u,l)}if(n==="gitlab"){let l=c("x-gitlab-token");return l?ht(a,l):"missing X-Gitlab-Token"}if(n==="stripe"){let l=c("stripe-signature");if(!l)return"missing Stripe-Signature";let u=Object.fromEntries(l.split(",").map(f=>f.split("=")));if(!u.t||!u.v1)return"malformed Stripe-Signature";let m=rs("sha256",a).update(`${u.t}.${t}`).digest("hex");return ht(m,u.v1)}if(n==="hubspot"){let l=c("x-hubspot-signature-v3"),u=c("x-hubspot-request-timestamp");if(!l)return"missing X-HubSpot-Signature-v3";if(!u)return"missing X-HubSpot-Request-Timestamp";let m=parseInt(u,10);if(!Number.isFinite(m))return"malformed X-HubSpot-Request-Timestamp";let f=Date.now()-m;if(f>5*6e4)return`HubSpot webhook is ${Math.floor(f/1e3)}s old (>5min replay window)`;let p="POST",y=i||e["x-original-uri"]||e["x-forwarded-path"]||"",b=e["x-forwarded-host"],k=e.host,S=e["x-forwarded-proto"]||"https",I=new Set;b&&y&&I.add(`${S}://${b}${y}`),k&&y&&I.add(`https://${k}${y}`),k&&y&&I.add(`http://${k}${y}`),y&&I.add(y),I.add("");for(let R of I){let D=rs("sha256",a).update(`${p}${R}${t}${u}`).digest("base64");if(l.length===D.length&&Qu(Buffer.from(l),Buffer.from(D)))return null}return`signature mismatch (tried ${I.size} URI variants)`}if(n==="odoo"){let l=c("x-odoo-signature");if(l){let m=rs("sha256",a).update(t).digest("hex"),f=l.startsWith("sha256=")?l.slice(7):l;return ht(m,f)}let u=c("x-odoo-webhook-token")??c("x-webhook-secret");return u?ht(a,u):"missing X-Odoo-Signature or X-Odoo-Webhook-Token"}let d=c("x-webhook-secret");return d?ht(a,d):"missing X-Webhook-Secret"}sendJson(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}};function ht(r,e){if(r.length!==e.length)return"signature mismatch";let t=Buffer.from(r),n=Buffer.from(e);return Qu(t,n)?null:"signature mismatch"}Vf();Uf();pa();function bb(r){return{insertTaskHistory:r.prepare(`
@@ -627,7 +627,7 @@ ${o||"(empty)"}`}function Zb(r){return(r??"").toLowerCase().split("@")[0]}functi
627
627
  ${o.originalMessage??""}`,origin:n,attempt:i,resumedFrom:o.taskId}).then(async a=>{if(a.error||!a.content){r.log(`[resume] ${o.taskId} finished without an answer: ${a.error??"empty"}`);return}await r.send(e(n),t(n,a.content))}).catch(a=>r.log(`[resume] ${o.taskId} failed: ${a?.message??a}`))},tell:async(n,s)=>{n.kind==="mesh"&&await r.send(e(n),t(n,s))}}}function Eh(r,e){let t=r.replyVia,n=r.context;if(!t||typeof t!="object"||!n||typeof n.channel!="string"||typeof n.chatId!="string")return;let s=i=>typeof i=="string"&&i?i:void 0;return{kind:"mesh",node:s(t.node),channel:n.channel,chatId:n.chatId,agentId:e,replyTo:s(t.messageId),accountId:s(t.accountId),context:n}}function Ch(r,e){return!e||r.errorKind!=="interrupted"?r:{...r,error:tc("resuming",1)}}var Ph=100,rk="Decisions are made by the operator only: `agentx approvals approve|reject <key>`, or the Approvals page in the dashboard.";function Mh(r,e,t,n,s){let i=r.toUpperCase();if(e==="/approvals"){if(i==="GET"){let a=xn(s.ctx,{includeSnoozed:n.get("all")==="1"});return{status:200,body:{count:a.items.length,snoozed:a.snoozed,items:a.items.slice(0,Ph),truncated:a.items.length>Ph,errors:a.errors}}}if(i==="POST"){let a=t??{},c=typeof a.raised_by=="string"?a.raised_by.trim():"",d=typeof a.node=="string"?a.node.trim():"",l=d&&!s.hasAgent(c)&&s.hasPeer?.(d)?d:void 0;if(c&&!s.hasAgent(c)&&!l)return{status:400,body:{error:d?`unknown node "${d}": node must be one of this node's mesh peers`:`unknown agent "${c}": raised_by must be an agent on this node`}};let u=$n(s.ctx.root,a,{now:s.ctx.now,settings:s.settings,node:l});return u.ok?{status:201,body:{card:u.card}}:{status:400,body:{error:u.error}}}return{status:405,body:{error:"Method not allowed"}}}if(e==="/approvals/checkin"&&i==="POST"){if(!s.runCheckin)return{status:503,body:{error:"check-ins need macOS"}};let a=t?.daily===!0?"daily":"check";return s.runCheckin(a),{status:202,body:{started:a}}}let o=e.match(/^\/approvals\/([^/]+)$/);if(o&&i==="GET"){let a=decodeURIComponent(o[1]),c=Sn(a)?In(s.ctx.root,a):null;return c?{status:200,body:{card:c}}:{status:404,body:{error:`no card "${a}"`}}}return i!=="GET"&&i!=="HEAD"?{status:403,body:{error:rk}}:{status:404,body:{error:"Not found"}}}function mt(r,e){let t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date(r)),n=i=>t.find(o=>o.type===i)?.value??"00",s=Number(n("hour"))%24;return{date:`${n("year")}-${n("month")}-${n("day")}`,minutes:s*60+Number(n("minute"))}}function ik(r,e,t){let{date:n,minutes:s}=mt(t,r.timezone),[i,o]=r.time.split(":").map(Number);return{due:e!==n&&s>=i*60+o,date:n}}function ok(r,e){let t=r[0],n=[`${r.length} decision${r.length===1?"":"s"} waiting for you.`];if(t){let s=t.expires?` Expires ${t.expires.slice(0,16).replace("T"," ")} UTC${t.if_silent?`, then: ${t.if_silent}`:""}.`:"";n.push(`Most urgent: ${t.title}: ${t.ask}${s}`)}return n.push(e?`Open ${e.replace(/\/$/,"")}/approvals, or run: agentx approvals list`:"Open Approvals in the dashboard, or run: agentx approvals list"),n.join(`
628
628
  `)}var ak=24*36e5;async function ck(r,e,t){let{ctx:n,settings:s,log:i}=e,o=()=>{Lr(n.root,r.id,t);try{e.onCardResult?.(r)}catch(a){i(`[approvals] ${r.id}: result listener failed: ${a?.message??a}`)}};if(!s.notifyAgent||!e.tellPeer)return o(),!1;try{return await e.tellPeer(r.node,r),o(),!0}catch(a){let c=Date.parse(r.decided_at??r.created_at),d=Number.isFinite(c)&&t-c>ak;return i(`[approvals] couldn't send ${r.id}'s result to ${r.node} for ${r.raised_by}: ${a?.message??a}${d?"; giving up":"; will retry"}`),d&&o(),!1}}async function _h(r){let{ctx:e,settings:t,log:n}=r,s=e.now??Date.now(),i={expired:0,notified:0,digest:"not-due"};try{for(let o of kd(e.root,s))i.expired++,n(`[approvals] ${o.id} from ${o.raised_by} expired; default applied: ${o.if_silent}`)}catch(o){n(`[approvals] expiry failed: ${o?.message??o}`)}try{for(let o of vd(e.root)){if(o.node){await ck(o,r,s)&&i.notified++;continue}Lr(e.root,o.id,s);try{r.onCardResult?.(o)}catch(a){n(`[approvals] ${o.id}: result listener failed: ${a?.message??a}`)}if(!(!t.notifyAgent||!r.tellAgent)){if(r.hasAgent&&!r.hasAgent(o.raised_by)){n(`[approvals] ${o.id}: agent "${o.raised_by}" isn't on this node; result not delivered`);continue}try{await r.tellAgent(o.raised_by,Tn(o),o),i.notified++}catch(a){n(`[approvals] couldn't tell ${o.raised_by} about ${o.id}: ${a?.message??a}`)}}}}catch(o){n(`[approvals] agent notices failed: ${o?.message??o}`)}try{if(!t.digest.enabled)return i.digest="disabled",i;let{due:o,date:a}=ik(t.digest,xd(e.root).lastDigest,s);if(!o)return i;let c=t.digest.destination??r.fallbackDestination;if(!c||!r.sendDigest)return i.digest="no-destination",i;let{items:d}=xn(e,{includeSnoozed:!0});if(d.length===0)return i.digest="empty",i;Ad(e.root,a);try{await r.sendDigest(c,ok(d,r.dashboardUrl)),i.digest="sent",n(`[approvals] digest sent: ${d.length} waiting`)}catch(l){i.digest="failed",n(`[approvals] digest failed: ${l?.message??l}`)}}catch(o){i.digest="failed",n(`[approvals] digest failed: ${o?.message??o}`)}return i}function dk(r){let e=r.peer.token||(r.env??process.env).MESH_TOKEN;return{"Content-Type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}async function Di(r,e,t,n){let s=r.fetch??fetch,i=`${r.peer.url.replace(/\/+$/,"")}${t}`;try{let o=await s(i,{method:e,headers:dk(r),...n!==void 0?{body:JSON.stringify(n)}:{},signal:AbortSignal.timeout(r.timeoutMs??1e4)}),a=await o.json().catch(()=>({}));return{status:o.status,body:a}}catch(o){return{status:502,body:{error:`couldn't reach ${r.peer.name} (${r.peer.url}): ${o?.message??o}`}}}}function Oh(r,e){return Di(e,"POST","/approvals",{...r,node:e.self})}function Dh(r,e){return Di(e,"GET",`/approvals/${encodeURIComponent(r)}`)}async function Nh(r,e){let t=await Di(e,"POST","/approvals/result",{card:r});if(t.status<200||t.status>=300)throw new Error(t.body?.error||`HTTP ${t.status}`)}function jh(r,e){if(!e.authorized)return{ok:!1,status:401,error:"a card result needs a mesh token (Authorization: Bearer <token>)"};if(!e.forwardTo)return{ok:!1,status:409,error:"this node does not forward cards (approvals.forwardTo is unset)"};let t=r?.card;return!t||typeof t!="object"?{ok:!1,status:400,error:"card is required"}:typeof t.id!="string"||!Sn(t.id)?{ok:!1,status:400,error:"card.id is not a card id"}:t.status!=="decided"&&t.status!=="expired"?{ok:!1,status:400,error:"card.status must be decided or expired"}:typeof t.raised_by!="string"||!e.hasAgent(t.raised_by)?{ok:!1,status:400,error:`unknown agent "${t.raised_by??""}": raised_by must be an agent on this node`}:Ut(t.node)!==Ut(e.self)?{ok:!1,status:400,error:`card.node "${t.node??""}" is not this node ("${e.self}")`}:{ok:!0,card:t}}function Ut(r){return typeof r=="string"?r.toLowerCase().replace(/[^a-z0-9]/g,""):""}function Lh(r,e,t=[]){let n=Ut(r);if(!n)return;let s=e.find(o=>Ut(o.name)===n);if(s)return s;let i=t.find(o=>o.node&&Ut(o.node)===n);return i?e.find(o=>o.name===i.peer):void 0}Jf();Sa();function Fh(r,e,t){let n=new ba(r),s=new va(n,e,t),i=B(),o=s.taskStarted.bind(s),a=s.taskCompleted.bind(s);return i.on("task:started",o),i.on("task:completed",a),{store:n,tracker:s,detach:()=>{i.off("task:started",o),i.off("task:completed",a)}}}function Ni(r,e,t,n){return!t?.error||et(t.error)?!1:(e.ownerNote&&!e.noteSaid&&r.setNoteSaid(e.id,e.ownerNote,!1),r.needsAttention(e.id,`Could not hand it back to ${e.agentId}: ${t.error}`,n))}function lk(r){let e=r.askedAgent&&r.askedAgent!==r.agentId?r.askedAgent:null,t=`on ${r.channel} (chat ${r.chatId}) on ${new Date(r.createdAt).toISOString().slice(0,16).replace("T"," ")} UTC and was not finished.`,n=e?`That chat is ${e}'s: you may have no way to write there, so do not report in it. Give your report as the answer to this turn: the owner reads it on the request's card. If you have a chat of your own with them, you can report there as well.`:"Report to them in that chat.";return[`[agentx:request-pickup id=${r.id}]`,e?`The owner handed this request to you. It was asked of ${e} ${t}`:`The owner asked you to pick this request up again. It was asked ${t}`,"","What they asked:",r.text,"",...r.ownerNote&&!r.noteSaid?["What they say now:",r.ownerNote,""]:[],`Do the work now. ${n} When it is finished, close it with agentx_request: {action:"done", id:"${r.id}", evidence:"<link>"}. If you will not do it, use decline with the reason.`].join(`
629
629
  `)}var Uh=36e5;function uk(r){let e=r.text.replace(/\s+/g," ").trim();return[`A request you gave ${r.agentId} on ${r.channel} is not finished.`,`You asked: ${e.length>240?`${e.slice(0,239)}\u2026`:e}`,`What happened: ${r.attentionReason??"unknown"}`,"Nothing is retrying it. Ask again, or drop it."].join(`
630
- `)}async function Gh(r){let{store:e,settings:t,log:n}=r,s=r.now??Date.now(),i={quiet:0,notified:0,pruned:0,pickedUp:0};if(!t.enabled)return i;try{for(let o of e.takePickups()){if(!r.tellAgent||r.hasAgent&&!r.hasAgent(o.agentId)){e.needsAttention(o.id,`Could not hand it back: agent "${o.agentId}" is not on this node`,s);continue}let a=o.ownerNote&&!o.noteSaid?o.ownerNote:null;a&&e.setNoteSaid(o.id,a,!0);try{await r.tellAgent(o.agentId,lk(o),o),i.pickedUp++}catch(c){a&&e.setNoteSaid(o.id,a,!1),e.needsAttention(o.id,`Could not hand it back to ${o.agentId}: ${c?.message??c}`,s)}}}catch(o){n(`[requests] pick-ups failed: ${o?.message??o}`)}try{let o=t.staleAfterHours;for(let a of e.quietSince(["candidate","in_progress","waiting_other"],s-o*Uh)){let c=a.state==="candidate"?`The turn that received it never reported an end (${o} h ago or more)`:`No activity for ${o} h`;e.needsAttention(a.id,c,s)&&i.quiet++}}catch(o){n(`[requests] quiet check failed: ${o?.message??o}`)}try{for(let o of e.awaitingNotice())if(e.markNotified(o.id,s),!!r.notify)try{await r.notify("Request not finished",uk(o),o),i.notified++}catch(a){e.markNotified(o.id,null),n(`[requests] couldn't tell the owner about ${o.id}, will try again: ${a?.message??a}`)}}catch(o){n(`[requests] notices failed: ${o?.message??o}`)}try{i.pruned=e.pruneClosed(s-t.retentionDays*24*Uh)}catch(o){n(`[requests] retention failed: ${o?.message??o}`)}return i}Sa();Xf();var ji=/^\/mesh\/guest\//,Bh=/^\/mesh\/guests(\/|$)/;async function Wh(r,e,t,n,s){let i=r.toUpperCase(),o=s.log??(c=>console.log(c));if(e==="/mesh/guest/join"&&i==="POST"){let c=await Cd(t??{},n.address,s);return c.status===200?{status:200,body:c.body,token:c.token}:{status:c.status,body:c.body}}if(ji.test(e)){let c=Pd(n.token,s);if(!c.ok)return{status:c.status,body:{error:c.error,..."waiting"in c&&c.waiting?{waiting:!0}:{},..."paused"in c&&c.paused?{paused:!0}:{}}};let{grant:d}=c;if(e==="/mesh/guest/me"&&i==="GET")return{status:200,body:jd(d)};if(e==="/mesh/guest/task"&&i==="POST"){let l=typeof t?.message=="string"?t.message.trim():"";if(!l)return{status:400,body:{error:"message is required"}};if(l.length>2e4)return{status:413,body:{error:"message is longer than 20000 characters"}};s.guests.log({grant:d.id,event:"task",address:n.address,detail:l.slice(0,120)}),o(`[guests] ${d.id}: ${d.guest} asked ${d.agentId} (${d.level}): ${l.slice(0,80).replace(/\s+/g," ")}`);let u=await s.run(Md(d,l));return s.guests.used(d.id,u.tokensUsed??0),u.error?{status:502,body:{error:u.error,grant:d.id}}:{status:200,body:{content:u.content,grant:d.id,agentId:d.agentId}}}return{status:404,body:{error:"Not found"}}}if(e==="/mesh/guests"&&i==="GET")return{status:200,body:{grants:s.guests.grants().map(d=>Fr(s,d)).sort((d,l)=>l.createdAt.localeCompare(d.createdAt)).map(d=>Hh(s.guests,d,5))}};let a=e.match(/^\/mesh\/guests\/([^/]+)(?:\/(pause|resume|end|update))?$/);if(a){let c=decodeURIComponent(a[1]),d=a[2],l=s.guests.get(c);if(!l)return{status:404,body:{error:`no grant "${c}"`}};let u=Fr(s,l);if(!d&&i==="GET")return{status:200,body:{grant:Hh(s.guests,u,50)}};if(!d||i!=="POST")return{status:405,body:{error:"Method not allowed"}};if(d==="pause"){let f=_d(s,c);if(!f)return{status:409,body:{error:`grant "${c}" is ${u.state}, not active`}};let p=s.cancel?.(f)??0;return o(`[guests] ${c}: paused by the operator; ${p} running turn(s) stopped`),{status:200,body:{grant:f,stopped:p}}}if(d==="resume"){let f=Od(s,c);return f?{status:200,body:{grant:f}}:{status:409,body:{error:`grant "${c}" is ${u.state}, not paused`}}}if(d==="end"){let f=Dd(s,c);if(!f)return{status:409,body:{error:`grant "${c}" is already ended`}};let p=s.cancel?.(f)??0;return o(`[guests] ${c}: ended by the operator; ${p} running turn(s) stopped`),{status:200,body:{grant:f,stopped:p}}}let m=Nd(s,c,t??{});return m.ok?{status:200,body:{grant:m.grant}}:{status:400,body:{error:m.error}}}return{status:404,body:{error:"Not found"}}}function Hh(r,e,t){return{...e,trail:r.events(e.id,t)}}var hk="Only the owner drops a request: `agentx requests drop <id>`, or the Approvals page in the dashboard.",ft=r=>typeof r=="string"?r.trim():"";function qh(r,e,t,n,s={}){let i=r.toUpperCase(),{store:o}=n;if(e==="/requests"&&i==="GET"){let c=o.listOpen();return{status:200,body:{enabled:n.enabled,count:c.length,items:c.slice(0,100),truncated:c.length>100}}}let a=e.match(/^\/requests\/([^/]+)$/);if(a&&i==="GET"){let c=o.get(decodeURIComponent(a[1]));return!c||c.state==="candidate"?{status:404,body:{error:`no request "${decodeURIComponent(a[1])}"`}}:{status:200,body:{request:c,links:o.links(c.id)}}}if(e==="/requests"&&i==="POST"){let c=t??{},d=ft(c.action).toLowerCase();if(d==="drop")return{status:403,body:{error:hk}};if(!["accept","wait","done","decline"].includes(d))return{status:400,body:{error:`unknown action "${d}": use accept, wait, done or decline`}};if(!n.enabled)return{status:409,body:{error:"Requests are turned off on this node (requests.enabled)."}};let l=ft(c.agentId);if(!l||!n.hasAgent(l))return{status:400,body:{error:"agentId must be an agent on this node"}};let u=n.runningTurn(l,s);if(!u)return{status:403,body:{error:`no running turn of "${l}" matches this call: use the agentx_request tool from inside your run`}};let m=ft(c.id),f=null;if(m)f=o.get(m);else{let y=n.tracker.liveRequestId(l,u.channel,u.chatId);f=y?o.get(y):null}if(!f)return{status:404,body:{error:m?`no request "${m}"`:"This turn has no recorded request. Pass the id of the request you mean (list shows them); only the owner's own messages are recorded."}};if(f.agentId!==l)return{status:403,body:{error:`request "${f.id}" belongs to another agent`}};if(["done","declined","dropped"].includes(f.state))return{status:409,body:{error:`request "${f.id}" is already closed (${f.state})`}};let p=n.now??Date.now();try{if(d==="accept")o.progress(f.id,p);else if(d==="wait"){let y=ft(c.question);if(!y)return{status:400,body:{error:"wait needs `question`: what you are asking the owner"}};o.waitOnOwner(f.id,y,p)}else d==="done"?o.close(f.id,"done",ft(c.evidence),p):o.close(f.id,"declined",ft(c.reason),p)}catch(y){return{status:400,body:{error:y?.message??String(y)}}}return{status:200,body:{request:o.get(f.id)}}}return i!=="GET"&&i!=="HEAD"?{status:405,body:{error:"Method not allowed"}}:{status:404,body:{error:"Not found"}}}import{randomUUID as gk}from"crypto";var Vh=new Set(["gitlab","github"]),pk=/:(issue|merge_request|pull):\d+$/,Li=5,mk=12e4,Jh=864e5,cs=r=>r.toLowerCase().split("@")[0],Fi=class{constructor(e,t,n){this.store=e;this.settings=t;this.deps=n;this.now=n.now??Date.now,this.bootAt=this.now();for(let s of e.open())s.state!=="queued"&&!s.turnLive||(this.orphans.add(s.id),s.turnLive&&e.set(s.id,{turnLive:!1},this.bootAt))}now;bootAt;orphans=new Set;writes=new Map;on(e,t){return Vh.has(cs(e))&&!pk.test(t)?!1:this.settings().channels.map(cs).includes(cs(e))}guard(e,t){try{t()}catch(n){this.deps.log(`[status] ${e} failed: ${n?.message??n}`)}}change(e,t){this.store.set(e,t,this.now()),this.orphans.delete(e),this.push(e)}queued(e){this.guard("queued",()=>{if(!e.humanRoot||!this.on(e.channel,e.chatId)||this.store.inChat(e.agentId,e.channel,e.chatId,"queued"))return;let t=`req-q-${gk()}`;this.store.add({id:t,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"queued",now:this.now()}),this.push(t)})}taskStarted(e){e.taskId&&this.guard("start",()=>{let t=e.resumedFrom?this.store.byRef("run",e.resumedFrom):null;if(t){this.store.ref(t.id,"run",e.taskId),ct.includes(t.state)||this.change(t.id,{state:t.pending>0?"waiting":"working",turnLive:!0});return}if(!this.on(e.channel,e.chatId))return;let n=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");if(n){this.store.ref(n.id,"run",e.taskId),this.change(n.id,{state:"working",turnLive:!0});return}if(!e.humanRoot)return;let s=`req-${e.taskId}`;this.store.add({id:s,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"working",now:this.now()}),this.store.ref(s,"run",e.taskId),this.push(s)})}queueEnded(e){this.guard("queue end",()=>{let t=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");t&&t.createdAt<=e.flushedAt&&this.change(t.id,{state:"failed"})})}taskCompleted(e){e.taskId&&this.guard("end",()=>{let t=this.store.byRef("run",e.taskId);if(!t||ct.includes(t.state)||e.interrupted)return;let n;e.error?n=e.errorKind==="cancelled"?"stopped":/\btimed? ?out\b|timeout/i.test(e.error)?"timed_out":"failed":n=t.pending>0?"waiting":"done",this.change(t.id,{state:n,turnLive:!1})})}delegationStarted(e){this.guard("delegation start",()=>{let t=this.store.inChat(e.caller,e.origin.channel,e.origin.chatId,"live");t&&(this.store.ref(t.id,"delegation",e.id),this.change(t.id,{state:"waiting",waitingOn:e.callee,pending:t.pending+1}))})}delegationDone(e,t){this.guard("delegation end",()=>this.handedBack(this.store.byRef("delegation",e.id),t))}cardRaised(e,t){t&&this.guard("card",()=>{let n=this.store.inChat(e.raised_by,t.channel,t.chatId,"live");n&&(this.store.ref(n.id,"card",e.id),this.change(n.id,{state:"waiting",waitingOn:"an answer from the owner",pending:n.pending+1}))})}cardResolved(e){this.guard("card result",()=>{let t=e.status==="decided"||(e.outcome??e.if_silent)==="approve";this.handedBack(this.store.byRef("card",e.id),t?"done":"timeout")})}handedBack(e,t){if(!e||ct.includes(e.state))return;let n=e.pending-1;if(n>0){this.change(e.id,{pending:n});return}if(e.turnLive){this.change(e.id,{state:"working",pending:n});return}let s={done:"done",error:"failed",timeout:"timed_out",lost:"restart"}[t];this.change(e.id,{state:s,pending:n})}resumeOutcome(e){this.guard("restart",()=>{if(e.decision!=="reported"&&e.decision!=="resume-failed")return;let t=this.store.byRef("run",e.taskId);t&&!ct.includes(t.state)&&this.change(t.id,{state:"restart",turnLive:!1})})}sweep(){let e=this.now();this.guard("restart check",()=>{if(!(this.orphans.size===0||e-this.bootAt<mk)){for(let t of[...this.orphans]){let n=this.store.get(t);n&&!n.turnLive&&(n.state==="queued"||n.state==="working")&&this.change(t,{state:"restart"})}this.orphans.clear()}}),this.guard("catch up",()=>{for(let t of this.store.changedSince(e-Jh))t.shown!==pi(t)&&t.writeFails<Li&&this.push(t.id)}),this.guard("retention",()=>{this.store.prune(e-this.settings().retentionDays*Jh)})}async idle(){for(;this.writes.size;)await Promise.all(this.writes.values())}push(e){let t=(this.writes.get(e)??Promise.resolve()).then(()=>this.write(e)).catch(n=>this.deps.log(`[status] comment for ${e} failed: ${n?.message??n}`)).finally(()=>{this.writes.get(e)===t&&this.writes.delete(e)});this.writes.set(e,t)}async write(e){let t=this.store.get(e);if(!t||!Vh.has(cs(t.channel)))return;let n=pi(t);if(n===t.shown)return;let s="";try{t.commentRef?await this.deps.edit(t,t.commentRef,n)&&(s=t.commentRef):s=await this.deps.post(t,n)}catch(i){this.deps.log(`[status] comment for ${e} failed: ${i?.message??i}`)}if(s){this.store.posted(e,s,n);return}this.store.writeFailed(e)===Li&&this.deps.log(`[status] comment for ${e} on ${t.channel} ${t.chatId} could not be written ${Li} times; not retried until its state changes`)}};function Xh(r,e,t){let n=new Fi(new qn(r),e,t),s=B(),i=n.queued.bind(n),o=n.taskStarted.bind(n),a=n.taskCompleted.bind(n),c=n.queueEnded.bind(n);return s.on("task:queued",i),s.on("task:queue-ended",c),s.on("task:started",o),s.on("task:completed",a),{board:n,detach:()=>{s.off("task:queued",i),s.off("task:queue-ended",c),s.off("task:started",o),s.off("task:completed",a)}}}import{mkdirSync as fk,readFileSync as yk,renameSync as wk,writeFileSync as bk}from"fs";import{dirname as kk,resolve as vk}from"path";function ds(r){return vk(r,".agentx","reminders","claims.json")}function ls(r){try{let e=JSON.parse(yk(r,"utf-8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Kh(r,e){fk(kk(r),{recursive:!0});let t=`${r}.${process.pid}.tmp`;bk(t,JSON.stringify(e,null,2)+`
630
+ `)}async function Gh(r){let{store:e,settings:t,log:n}=r,s=r.now??Date.now(),i={quiet:0,notified:0,pruned:0,pickedUp:0};if(!t.enabled)return i;try{for(let o of e.takePickups()){if(!r.tellAgent||r.hasAgent&&!r.hasAgent(o.agentId)){e.needsAttention(o.id,`Could not hand it back: agent "${o.agentId}" is not on this node`,s);continue}let a=o.ownerNote&&!o.noteSaid?o.ownerNote:null;a&&e.setNoteSaid(o.id,a,!0);try{await r.tellAgent(o.agentId,lk(o),o),i.pickedUp++}catch(c){a&&e.setNoteSaid(o.id,a,!1),e.needsAttention(o.id,`Could not hand it back to ${o.agentId}: ${c?.message??c}`,s)}}}catch(o){n(`[requests] pick-ups failed: ${o?.message??o}`)}try{let o=t.staleAfterHours;for(let a of e.quietSince(["candidate","in_progress","waiting_other"],s-o*Uh)){let c=a.state==="candidate"?`The turn that received it never reported an end (${o} h ago or more)`:`No activity for ${o} h`;e.needsAttention(a.id,c,s)&&i.quiet++}}catch(o){n(`[requests] quiet check failed: ${o?.message??o}`)}try{for(let o of e.awaitingNotice())if(e.markNotified(o.id,s),!!r.notify)try{await r.notify("Request not finished",uk(o),o),i.notified++}catch(a){e.markNotified(o.id,null),n(`[requests] couldn't tell the owner about ${o.id}, will try again: ${a?.message??a}`)}}catch(o){n(`[requests] notices failed: ${o?.message??o}`)}try{i.pruned=e.pruneClosed(s-t.retentionDays*24*Uh)}catch(o){n(`[requests] retention failed: ${o?.message??o}`)}return i}Sa();Xf();var ji=/^\/mesh\/guest\//,Bh=/^\/mesh\/guests(\/|$)/;async function Wh(r,e,t,n,s){let i=r.toUpperCase(),o=s.log??(c=>console.log(c));if(e==="/mesh/guest/join"&&i==="POST"){let c=await Ed(t??{},n.address,s);return c.status===200?{status:200,body:c.body,token:c.token}:{status:c.status,body:c.body}}if(ji.test(e)){let c=Cd(n.token,s);if(!c.ok)return{status:c.status,body:{error:c.error,..."waiting"in c&&c.waiting?{waiting:!0}:{},..."paused"in c&&c.paused?{paused:!0}:{}}};let{grant:d}=c;if(e==="/mesh/guest/me"&&i==="GET")return{status:200,body:Nd(d)};if(e==="/mesh/guest/task"&&i==="POST"){let l=typeof t?.message=="string"?t.message.trim():"";if(!l)return{status:400,body:{error:"message is required"}};if(l.length>2e4)return{status:413,body:{error:"message is longer than 20000 characters"}};s.guests.log({grant:d.id,event:"task",address:n.address,detail:l.slice(0,120)}),o(`[guests] ${d.id}: ${d.guest} asked ${d.agentId} (${d.level}): ${l.slice(0,80).replace(/\s+/g," ")}`);let u=await s.run(Pd(d,l));return s.guests.used(d.id,u.tokensUsed??0),u.error?{status:502,body:{error:u.error,grant:d.id}}:{status:200,body:{content:u.content,grant:d.id,agentId:d.agentId}}}return{status:404,body:{error:"Not found"}}}if(e==="/mesh/guests"&&i==="GET")return{status:200,body:{grants:s.guests.grants().map(d=>Fr(s,d)).sort((d,l)=>l.createdAt.localeCompare(d.createdAt)).map(d=>Hh(s.guests,d,5))}};let a=e.match(/^\/mesh\/guests\/([^/]+)(?:\/(pause|resume|end|update))?$/);if(a){let c=decodeURIComponent(a[1]),d=a[2],l=s.guests.get(c);if(!l)return{status:404,body:{error:`no grant "${c}"`}};let u=Fr(s,l);if(!d&&i==="GET")return{status:200,body:{grant:Hh(s.guests,u,50)}};if(!d||i!=="POST")return{status:405,body:{error:"Method not allowed"}};if(d==="pause"){let f=Md(s,c);if(!f)return{status:409,body:{error:`grant "${c}" is ${u.state}, not active`}};let p=s.cancel?.(f)??0;return o(`[guests] ${c}: paused by the operator; ${p} running turn(s) stopped`),{status:200,body:{grant:f,stopped:p}}}if(d==="resume"){let f=_d(s,c);return f?{status:200,body:{grant:f}}:{status:409,body:{error:`grant "${c}" is ${u.state}, not paused`}}}if(d==="end"){let f=Od(s,c);if(!f)return{status:409,body:{error:`grant "${c}" is already ended`}};let p=s.cancel?.(f)??0;return o(`[guests] ${c}: ended by the operator; ${p} running turn(s) stopped`),{status:200,body:{grant:f,stopped:p}}}let m=Dd(s,c,t??{});return m.ok?{status:200,body:{grant:m.grant}}:{status:400,body:{error:m.error}}}return{status:404,body:{error:"Not found"}}}function Hh(r,e,t){return{...e,trail:r.events(e.id,t)}}var hk="Only the owner drops a request: `agentx requests drop <id>`, or the Approvals page in the dashboard.",ft=r=>typeof r=="string"?r.trim():"";function qh(r,e,t,n,s={}){let i=r.toUpperCase(),{store:o}=n;if(e==="/requests"&&i==="GET"){let c=o.listOpen();return{status:200,body:{enabled:n.enabled,count:c.length,items:c.slice(0,100),truncated:c.length>100}}}let a=e.match(/^\/requests\/([^/]+)$/);if(a&&i==="GET"){let c=o.get(decodeURIComponent(a[1]));return!c||c.state==="candidate"?{status:404,body:{error:`no request "${decodeURIComponent(a[1])}"`}}:{status:200,body:{request:c,links:o.links(c.id)}}}if(e==="/requests"&&i==="POST"){let c=t??{},d=ft(c.action).toLowerCase();if(d==="drop")return{status:403,body:{error:hk}};if(!["accept","wait","done","decline"].includes(d))return{status:400,body:{error:`unknown action "${d}": use accept, wait, done or decline`}};if(!n.enabled)return{status:409,body:{error:"Requests are turned off on this node (requests.enabled)."}};let l=ft(c.agentId);if(!l||!n.hasAgent(l))return{status:400,body:{error:"agentId must be an agent on this node"}};let u=n.runningTurn(l,s);if(!u)return{status:403,body:{error:`no running turn of "${l}" matches this call: use the agentx_request tool from inside your run`}};let m=ft(c.id),f=null;if(m)f=o.get(m);else{let y=n.tracker.liveRequestId(l,u.channel,u.chatId);f=y?o.get(y):null}if(!f)return{status:404,body:{error:m?`no request "${m}"`:"This turn has no recorded request. Pass the id of the request you mean (list shows them); only the owner's own messages are recorded."}};if(f.agentId!==l)return{status:403,body:{error:`request "${f.id}" belongs to another agent`}};if(["done","declined","dropped"].includes(f.state))return{status:409,body:{error:`request "${f.id}" is already closed (${f.state})`}};let p=n.now??Date.now();try{if(d==="accept")o.progress(f.id,p);else if(d==="wait"){let y=ft(c.question);if(!y)return{status:400,body:{error:"wait needs `question`: what you are asking the owner"}};o.waitOnOwner(f.id,y,p)}else d==="done"?o.close(f.id,"done",ft(c.evidence),p):o.close(f.id,"declined",ft(c.reason),p)}catch(y){return{status:400,body:{error:y?.message??String(y)}}}return{status:200,body:{request:o.get(f.id)}}}return i!=="GET"&&i!=="HEAD"?{status:405,body:{error:"Method not allowed"}}:{status:404,body:{error:"Not found"}}}import{randomUUID as gk}from"crypto";var Vh=new Set(["gitlab","github"]),pk=/:(issue|merge_request|pull):\d+$/,Li=5,mk=12e4,Jh=864e5,cs=r=>r.toLowerCase().split("@")[0],Fi=class{constructor(e,t,n){this.store=e;this.settings=t;this.deps=n;this.now=n.now??Date.now,this.bootAt=this.now();for(let s of e.open())s.state!=="queued"&&!s.turnLive||(this.orphans.add(s.id),s.turnLive&&e.set(s.id,{turnLive:!1},this.bootAt))}now;bootAt;orphans=new Set;writes=new Map;on(e,t){return Vh.has(cs(e))&&!pk.test(t)?!1:this.settings().channels.map(cs).includes(cs(e))}guard(e,t){try{t()}catch(n){this.deps.log(`[status] ${e} failed: ${n?.message??n}`)}}change(e,t){this.store.set(e,t,this.now()),this.orphans.delete(e),this.push(e)}queued(e){this.guard("queued",()=>{if(!e.humanRoot||!this.on(e.channel,e.chatId)||this.store.inChat(e.agentId,e.channel,e.chatId,"queued"))return;let t=`req-q-${gk()}`;this.store.add({id:t,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"queued",now:this.now()}),this.push(t)})}taskStarted(e){e.taskId&&this.guard("start",()=>{let t=e.resumedFrom?this.store.byRef("run",e.resumedFrom):null;if(t){this.store.ref(t.id,"run",e.taskId),ct.includes(t.state)||this.change(t.id,{state:t.pending>0?"waiting":"working",turnLive:!0});return}if(!this.on(e.channel,e.chatId))return;let n=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");if(n){this.store.ref(n.id,"run",e.taskId),this.change(n.id,{state:"working",turnLive:!0});return}if(!e.humanRoot)return;let s=`req-${e.taskId}`;this.store.add({id:s,channel:e.channel,chatId:e.chatId,agentId:e.agentId,senderId:e.sender?.id??e.sender?.username??null,state:"working",now:this.now()}),this.store.ref(s,"run",e.taskId),this.push(s)})}queueEnded(e){this.guard("queue end",()=>{let t=this.store.inChat(e.agentId,e.channel,e.chatId,"queued");t&&t.createdAt<=e.flushedAt&&this.change(t.id,{state:"failed"})})}taskCompleted(e){e.taskId&&this.guard("end",()=>{let t=this.store.byRef("run",e.taskId);if(!t||ct.includes(t.state)||e.interrupted)return;let n;e.error?n=e.errorKind==="cancelled"?"stopped":/\btimed? ?out\b|timeout/i.test(e.error)?"timed_out":"failed":n=t.pending>0?"waiting":"done",this.change(t.id,{state:n,turnLive:!1})})}delegationStarted(e){this.guard("delegation start",()=>{let t=this.store.inChat(e.caller,e.origin.channel,e.origin.chatId,"live");t&&(this.store.ref(t.id,"delegation",e.id),this.change(t.id,{state:"waiting",waitingOn:e.callee,pending:t.pending+1}))})}delegationDone(e,t){this.guard("delegation end",()=>this.handedBack(this.store.byRef("delegation",e.id),t))}cardRaised(e,t){t&&this.guard("card",()=>{let n=this.store.inChat(e.raised_by,t.channel,t.chatId,"live");n&&(this.store.ref(n.id,"card",e.id),this.change(n.id,{state:"waiting",waitingOn:"an answer from the owner",pending:n.pending+1}))})}cardResolved(e){this.guard("card result",()=>{let t=e.status==="decided"||(e.outcome??e.if_silent)==="approve";this.handedBack(this.store.byRef("card",e.id),t?"done":"timeout")})}handedBack(e,t){if(!e||ct.includes(e.state))return;let n=e.pending-1;if(n>0){this.change(e.id,{pending:n});return}if(e.turnLive){this.change(e.id,{state:"working",pending:n});return}let s={done:"done",error:"failed",timeout:"timed_out",lost:"restart"}[t];this.change(e.id,{state:s,pending:n})}resumeOutcome(e){this.guard("restart",()=>{if(e.decision!=="reported"&&e.decision!=="resume-failed")return;let t=this.store.byRef("run",e.taskId);t&&!ct.includes(t.state)&&this.change(t.id,{state:"restart",turnLive:!1})})}sweep(){let e=this.now();this.guard("restart check",()=>{if(!(this.orphans.size===0||e-this.bootAt<mk)){for(let t of[...this.orphans]){let n=this.store.get(t);n&&!n.turnLive&&(n.state==="queued"||n.state==="working")&&this.change(t,{state:"restart"})}this.orphans.clear()}}),this.guard("catch up",()=>{for(let t of this.store.changedSince(e-Jh))t.shown!==pi(t)&&t.writeFails<Li&&this.push(t.id)}),this.guard("retention",()=>{this.store.prune(e-this.settings().retentionDays*Jh)})}async idle(){for(;this.writes.size;)await Promise.all(this.writes.values())}push(e){let t=(this.writes.get(e)??Promise.resolve()).then(()=>this.write(e)).catch(n=>this.deps.log(`[status] comment for ${e} failed: ${n?.message??n}`)).finally(()=>{this.writes.get(e)===t&&this.writes.delete(e)});this.writes.set(e,t)}async write(e){let t=this.store.get(e);if(!t||!Vh.has(cs(t.channel)))return;let n=pi(t);if(n===t.shown)return;let s="";try{t.commentRef?await this.deps.edit(t,t.commentRef,n)&&(s=t.commentRef):s=await this.deps.post(t,n)}catch(i){this.deps.log(`[status] comment for ${e} failed: ${i?.message??i}`)}if(s){this.store.posted(e,s,n);return}this.store.writeFailed(e)===Li&&this.deps.log(`[status] comment for ${e} on ${t.channel} ${t.chatId} could not be written ${Li} times; not retried until its state changes`)}};function Xh(r,e,t){let n=new Fi(new qn(r),e,t),s=B(),i=n.queued.bind(n),o=n.taskStarted.bind(n),a=n.taskCompleted.bind(n),c=n.queueEnded.bind(n);return s.on("task:queued",i),s.on("task:queue-ended",c),s.on("task:started",o),s.on("task:completed",a),{board:n,detach:()=>{s.off("task:queued",i),s.off("task:queue-ended",c),s.off("task:started",o),s.off("task:completed",a)}}}import{mkdirSync as fk,readFileSync as yk,renameSync as wk,writeFileSync as bk}from"fs";import{dirname as kk,resolve as vk}from"path";function ds(r){return vk(r,".agentx","reminders","claims.json")}function ls(r){try{let e=JSON.parse(yk(r,"utf-8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Kh(r,e){fk(kk(r),{recursive:!0});let t=`${r}.${process.pid}.tmp`;bk(t,JSON.stringify(e,null,2)+`
631
631
  `),wk(t,r)}function zh(r,e,t,n=7){let s=t-n*864e5,i={};for(let[o,a]of Object.entries(r))(e.has(o)||Date.parse(a.at)>=s)&&(i[o]=a);return i}var Sk=/^agentx:\s*(.*)$/;function us(r){let e=(r??"").split(/\r?\n/),t=e.length-1;for(;t>=0&&!e[t].trim();)t--;if(t<0)return null;let n=Sk.exec(e[t].trim());if(!n)return null;let s={};for(let i of n[1].split(/\s+/)){let o=i.indexOf("=");o>0&&(s[i.slice(0,o)]=i.slice(o+1))}return s.agent?{agent:s.agent,...s.context?{context:s.context}:{},detail:e.slice(0,t).join(`
632
632
  `).trim()}:null}function Yh(r){if(!r)return null;let e=r.indexOf(":");return e<=0||e===r.length-1?null:{channel:r.slice(0,e),chatId:r.slice(e+1)}}var Qh=4;function Zh(r,e,t){let n=e?e.detail:(r.notes??"").trim();return["[Check-in] The operator has an open reminder. Decide whether it needs them now. If it does, prepare a card they can answer in one click.","",`Reminder: "${r.title}"`,r.listName?`List: ${r.listName}`:"",`Due: ${r.dueDate??"no due date"} (now: ${t})`,n?`Notes: ${n}`:"",e?.context?`It came from: ${e.context}`:"","","Do the homework first: look at their calendar for free slots, read the thread it is about.","Do not message anyone and do not act yet. Nothing goes out until they click.","","Reply with ONLY one JSON object, no other text. When it needs them:",'{"needs_operator": true, "title": "short, under 80 characters", "context": "what they need to know, a few lines",',' "ask": "the question", "recommend": "your advice and why, one line; with choices, start with the exact option you advise",',' "choices": ["2 to 4 short options, e.g. free slots or reply choices"],',' "draft": "the message you would send; {choice} is replaced by their pick", "say": "one short spoken line",',' "if_silent": "keep", "expires": "2d"}',`Limits, in characters: context ${Rt.context}, ask ${jr.ask}, recommend ${jr.recommend}, each choice ${Rt.label}, say ${Rt.say}. A longer field loses the card.`,"choices and draft are optional; leave choices out for a plain yes/no. Write the draft in the language of the person it goes to.",'When it does not need them (already done, not theirs, not time yet): {"needs_operator": false, "why": "one line"}',"","When they answer you get their pick and the exact text. Then you do it, and tick the reminder off."].filter((s,i,o)=>s!==""||o[i-1]!=="").join(`
633
633
  `)}function Ik(r){let e=r.lastIndexOf("}");for(let t=r.lastIndexOf("{",e);t>=0;t=r.lastIndexOf("{",t-1))try{return JSON.parse(r.slice(t,e+1))}catch{}}function $k(r,e=Rt.context){if(typeof r!="string")return r;let t=r.replace(/\r\n?/g,`
@@ -1076,7 +1076,7 @@ ${l.slice(0,300)}`,agentId:d,accountId:f.notify.accountId})}catch(p){this.log(`[
1076
1076
  ${u.message}`}),{alert:(u,m)=>pe(Ce(this.config.notifications.local))(u,m)})},log:c=>this.log(c)});let a=()=>{let c=Ge(Date.now(),this.voiceHealth?.hasMissing()?Br:void 0);this.voiceHealth?.check(this.config,c).catch(d=>this.log(`[voice] voice check failed: ${d?.message??d}`))};nl(a),a(),setInterval(a,Br).unref()}if(await this.cron.start(),this.mesh){await this.mesh.start();let a=this.mesh;this.peerFeed=new zs({bus:B(),peers:()=>a.directory().map(c=>({name:c.peer,url:c.peerUrl,healthy:c.healthy,headers:a.authHeaders(c.peer)})),skipTypes:()=>this.config.mesh.feed.skipTypes,enabled:()=>this.config.mesh.feed.enabled,log:c=>this.log(c)}).start()}let t=this.mesh?.directory().map(a=>({peer:a.peer,healthy:a.healthy,skills:a.skills}))||[];this.landscape.build(t),this.log(` Landscape: built for ${Object.keys(this.config.agents).length} agents`),this.scheduleMidnightHook(),this.startApprovalsSweep(),this.startReminders();let n=this.waTriage?.resume()??0;n&&this.log(` WhatsApp triage: ${n} queued message(s) picked up`);try{let a=new Date(Date.now()-864e5).toISOString().slice(0,10),c=this.registry.getTokenTracker().catchUpTokenCosts(a);c.length>0&&this.log(` Cost tracking: caught up ${c.length} missed day${c.length===1?"":"s"} (${c[0]}${c.length>1?` \u2192 ${c[c.length-1]}`:""})`)}catch(a){this.log(` Cost tracking: catch-up failed (non-fatal): ${a.message}`)}this.business&&(this.business.start(),this.log(` ${this.business.summary()}`)),await this.startHttpApi(),this.log(""),this.log(" Agents:");for(let a of this.registry.list())this.log(` ${a.id} (${a.tier}) \u2192 ${a.workspace}`);this.installAgentMemorySurface(),this.operatorKey=$a(process.cwd(),{create:!0}),this.operatorKey||this.log(" requests: could not create .agentx/operator.key \u2014 phone app turns will not be recorded as yours"),this.installAgentMcpConfig(),Fa(this.config.agents,this.log);let s=this.cron.list();if(s.length){this.log(""),this.log(" Cron Jobs:");for(let a of s){let c=a.enabled?"enabled":"disabled";this.log(` ${a.id} [${c}] \u2192 ${a.agent} (${a.schedule})`)}}if(this.mesh){this.log(""),this.log(" Mesh Peers:");for(let a of this.mesh.directory()){let c=a.healthy?"\u2713":"\u2717";this.log(` ${c} ${a.peer} (${a.peerUrl})`)}}process.env.AGENTX_AUTO_RELOAD!=="false"&&this.startConfigWatcher();try{let a=this.registry.pruneTaskHistory();a>0&&this.log(` Pruned ${a} old task-history folder(s)`)}catch{}for(let[a,c]of Object.entries(this.config.agents))if(c.workspace)try{let d=Xc(c.workspace,{create:!1});d>0&&this.log(` Removed ${d} old outbox file(s) for ${a}`)}catch(d){this.log(` Outbox cleanup for ${a} skipped: ${d?.message??d}`)}try{if(this.db){let a=wa(this.db,90),c=a.taskHistory+a.rotations+a.routeTraces;c>0&&this.log(` Pruned ${c} old SQLite row(s) (task_history=${a.taskHistory}, rotations=${a.rotations}, route_traces=${a.routeTraces})`)}}catch(a){this.log(` SQLite prune skipped: ${a?.message??a}`)}try{let a=this.registry.hydrateLastSummariesFromDisk();a>0&&this.log(` Loaded last-activity summaries for ${a} agent(s)`)}catch{}try{xc();let a=Er().length;this.log(` Built-in actions: ${a} registered`)}catch(a){this.log(` Built-in actions: registration failed (${a.message})`)}this.log(""),this.log(" Ready."),this.bootTimes=$h(Q(process.cwd(),".agentx")),this.bootLog=pg(Q(process.cwd(),".agentx"),Date.parse(ut.startedAt),this.bootTimes.slice(0,-1)),this.interruptedRuns.length>0&&setTimeout(()=>{this.resumeInterruptedRuns()},5e3).unref?.(),this.log("");let i=Q(process.cwd(),".agentx/daemon.pid");jf(DI(i),{recursive:!0}),Yo(i,String(process.pid)),this.log(` PID: ${process.pid} (${i})`),process.on("uncaughtException",a=>{this.log(`UNCAUGHT EXCEPTION: ${a.message}`),this.log(a.stack||"")}),process.on("unhandledRejection",a=>{this.log(`UNHANDLED REJECTION: ${a}`)});let o=async a=>{this.shuttingDown||(this.shuttingDown=!0,this.shutdownRequest=Xd(Q(process.cwd(),".agentx")),gg(Q(process.cwd(),".agentx"),{at:new Date().toISOString(),by:this.shutdownRequest?.by??Hr(),reason:a}),this.log(`
1077
1077
  `+Kd({signal:a,request:this.shutdownRequest,manager:Hr(),inflight:this.registry.getActiveTaskCount()+this.router.getActiveMeshForwardCount(),uptimeSec:process.uptime()})),await this.stop())};this.requestShutdown=o,process.on("SIGINT",()=>o("SIGINT")),process.on("SIGTERM",()=>o("SIGTERM"))}async stop(){let e=Date.now();this.shuttingDown=!0,this.delegations.stop(),this.voiceTalk.close(),this.screenBuffer?.stop();try{this.log(" Stopping channels..."),await Promise.race([this.router.stopAll(),new Promise(t=>setTimeout(t,5e3))])}catch(t){this.log(` Channel stop error: ${t.message}`)}try{this.log(" Stopping crons (saving last run times)..."),await this.cron.stop(),this.workflowPolls?.stop()}catch{}try{this.log(" Stopping heartbeats..."),this.heartbeat.stopAll(),this.stopEventWaker?.()}catch{}try{this.business&&(this.log(" Stopping business layer..."),this.business.stop())}catch{}try{let t=Yd({configSeconds:this.config.shutdown?.drainTimeoutSeconds,env:process.env,agentSeconds:this.registry.runningAgentDrainSeconds()}),n=Date.now(),s=()=>this.registry.getActiveTaskCount()+this.router.getActiveMeshForwardCount(),i=s();if(i>0){for(this.log(` Draining ${i} in-flight task(s) \u2014 local=${this.registry.getActiveTaskCount()}, mesh-forwards=${this.router.getActiveMeshForwardCount()} (max ${Math.round(t/1e3)}s)...`);i>0&&Date.now()-n<t;)await new Promise(a=>setTimeout(a,500)),i=s();let o=Date.now()-n;if(i===0)this.log(` Drain complete (${o}ms)`);else{this.log(` Drain timeout after ${o}ms \u2014 ${i} task(s) still in flight (local=${this.registry.getActiveTaskCount()}, mesh-forwards=${this.router.getActiveMeshForwardCount()}), exiting anyway`);let a=Qd({drainMs:t,request:this.shutdownRequest}),c=this.registry.interruptRunning(a),d=Date.now();for(;this.registry.getActiveTaskCount()>0&&Date.now()-d<zd;)await new Promise(l=>setTimeout(l,200));this.log(` Interrupted ${c} run(s): ${a}`)}}}catch(t){this.log(` Drain error: ${t.message}`)}try{this.router.flushPersistence?.()}catch(t){this.log(` Router flush error: ${t.message}`)}try{Da.stop(),Oa.stop(),this.sessionMonitor?.stop(),this.processRegistry&&(this.log(" Stopping persistent claude processes..."),await this.processRegistry.stop(),Ir(null))}catch(t){this.log(` ProcessRegistry stop error: ${t.message}`)}try{this.projectRules.stop()}catch{}try{this.mesh&&(this.log(" Stopping mesh..."),this.peerFeed?.stop(),await this.mesh.stop())}catch{}try{this.botManager&&this.botManager.shutdown()}catch{}try{this.cameraWatch?.shutdown()}catch{}try{this.webrtc&&this.webrtc.shutdown()}catch{}for(let t of this.loadedPlugins)try{await t.dispose()}catch(n){this.log(` Plugin dispose error (${t.manifest.name}): ${n?.message??n}`)}if(this.midnightTimer&&clearTimeout(this.midnightTimer),this.approvalsTimer&&clearInterval(this.approvalsTimer),this.stopReminders?.(),this.waTriage?.stop(),this.configWatcher)try{this.configWatcher.close()}catch{}this.attachSweep&&clearInterval(this.attachSweep),this.callSweep&&clearInterval(this.callSweep),this.httpServer&&this.httpServer.close();try{let t=Q(process.cwd(),".agentx/daemon.pid");It(t)&&OI(t)}catch{}this.log(` Shutdown complete (${Date.now()-e}ms)`),process.exit(this.exitCode)}ownerSender(){return async({title:e,message:t,priority:n,channel:s,chatId:i})=>{await this.router.sendOutbound({channel:s??pt(this.config),chatId:i??"default",text:t,title:e,priority:n,agentId:this.config.node.defaultAgent})}}runningSummaries(){let e=Date.now(),t=[];for(let n of this.registry.list())for(let s of n.runningTasks)t.push({agentId:n.id,taskId:s.id,channel:s.channel,chatId:s.chatId,step:s.step,ageSeconds:Math.max(0,Math.round((e-s.startedAt.getTime())/1e3))});return t.sort((n,s)=>s.ageSeconds-n.ageSeconds)}inflightCounts(){let e=this.registry.getActiveTaskCount(),t=this.router.getActiveMeshForwardCount();return{local:e,meshForwards:t,total:e+t}}requestShutdown;exitCode=0;selfRestartInfo;idleRestart=new ws({inflight:()=>this.inflightCounts().total,fire:(e,t)=>{let n=this.restartService().plan;if(!n.ok){this.log(` Restart when idle: cancelled \u2014 ${n.reason}`);return}this.exitCode=n.exitCode,this.log(` Restart when idle: ${e==="idle"?"no tasks running":"waited long enough, restarting anyway"}; ${n.how}`);try{Jd(Q(process.cwd(),".agentx"),{by:`restart-when-idle from ${t.requestedBy}`,pid:process.pid,at:new Date().toISOString()})}catch{}this.requestShutdown?this.requestShutdown("restart"):this.stop()}});restartService(){if(!this.selfRestartInfo){let e=Xg(process.pid);this.selfRestartInfo={service:e,plan:qg(e,e.kind==="none"?null:Kg(e))}}return this.selfRestartInfo}midnightTimer;shuttingDown=!1;shutdownRequest=null;interruptedRuns=[];bootTimes=[];bootLog=[];async resumeInterruptedRuns(){let e=this.interruptedRuns;if(this.interruptedRuns=[],!(!this.db||e.length===0))try{let t=new as;t.register("router",this.router.createResumer());let n=(a,c,d)=>this.registry.execute({message:d,agentId:a,context:{channel:"a2a",sender:`agent:${c}`,chatId:c,[Qa]:!0}}).catch(l=>this.log(`[resume] couldn't tell ${a}: ${l?.message??l}`));t.register("direct",{resume:async({origin:a,note:c,attempt:d,run:l})=>{if(a.kind!=="direct")throw new Error("not a direct run");let u=xt(a),m=this.registry.execute({message:`${c}
1078
1078
  ${l.originalMessage??""}`,agentId:l.agentId,context:a.context,model:a.model,autonomy:a.autonomy,origin:a,resumeAttempt:d,resumedFrom:l.taskId});if(!u){m.catch(f=>this.log(`[resume] ${l.taskId} failed: ${f?.message??f}`));return}m.then(f=>n(u,l.agentId,Th(l,f)),f=>this.log(`[resume] ${l.taskId} failed: ${f?.message??f}`))},tell:async(a,c)=>{let d=xt(a);if(!d)throw new Error("no chat to tell");let l=a.kind==="direct"?String(a.context?.chatId??"an agent"):"an agent";await n(d,l,`[AgentX resume] ${c}`)}}),t.register("mesh",Rh({peers:()=>this.mesh?.directory()??[],send:async(a,c)=>{let d=await fetch(`${a.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(a.peer)},body:JSON.stringify(c),signal:AbortSignal.timeout(15e3)});if(!d.ok)throw new Error(`peer ${a.peer} /channel/send -> ${d.status} ${(await d.text().catch(()=>"")).slice(0,200)}`)},execute:({agentId:a,message:c,origin:d,attempt:l,resumedFrom:u})=>this.registry.execute({message:c,agentId:a,context:d.context,origin:d,resumeAttempt:l,resumedFrom:u}),log:this.log}));let s=this.config.notifications?.destination,i=await t.run({db:this.db,runs:e,settings:this.config.resume,now:Date.now(),boots:this.bootTimes,log:this.log,staggerMs:2e3,notifyOperator:s?async a=>{await this.router.sendOutbound({channel:s.channel,chatId:s.chatId,accountId:s.accountId,text:a})}:void 0});for(let a of i)this.requests?.tracker.resumeOutcome(a),this.status?.board.resumeOutcome(a);let o=a=>i.filter(c=>c.decision===a).length;this.log(` Resume: ${o("resumed")} resumed, ${o("reported")} reported, ${o("skipped")} skipped, ${o("resume-failed")} failed`)}catch(t){this.log(`[resume] step failed, nothing more resumed: ${t?.message??t}`)}}initDecisions(){let e=this.config.decisions;if(e?.enabled)try{Pa({provider:e.backends.local.provider,model:e.backends.local.model,structureMode:e.backends.local.structureMode,normalizeProbabilities:e.backends.local.normalizeProbabilities,nRetryMalformedStructure:e.backends.local.nRetryMalformedStructure,maxStateChars:e.backends.local.maxStateChars},{baseUrl:e.backends.simpleJev.baseUrl,model:e.backends.simpleJev.model,apiKeyEnv:e.backends.simpleJev.apiKeyEnv,timeoutMs:e.backends.simpleJev.timeoutMs,maxStateChars:e.backends.simpleJev.maxStateChars,maxChoiceOptions:e.backends.simpleJev.maxChoiceOptions},{baseUrl:e.backends.jev.baseUrl,path:e.backends.jev.path,model:e.backends.jev.model,apiKeyEnv:e.backends.jev.apiKeyEnv,timeoutMs:e.backends.jev.timeoutMs,maxStateChars:e.backends.jev.maxStateChars,maxChoiceOptions:e.backends.jev.maxChoiceOptions},{baseUrl:e.backends.typesafe.baseUrl,path:e.backends.typesafe.path,model:e.backends.typesafe.model,apiKeyEnv:e.backends.typesafe.apiKeyEnv,timeoutMs:e.backends.typesafe.timeoutMs,maxStateChars:e.backends.typesafe.maxStateChars,maxChoiceOptions:e.backends.typesafe.maxChoiceOptions});let t=null;try{t=new oa({path:e.dbPath})}catch(s){this.log(` Decisions: store unavailable (${s.message}) \u2014 seats answer but do not record`)}Ma({enabled:!0,defaultBackend:e.defaultBackend,store:t,seats:Object.fromEntries(Object.entries(e.seats).map(([s,i])=>[s,{...i,redactState:e.redactState,keepStateRows:e.keepStateRows}]))});let n=Object.entries(e.seats).filter(([,s])=>s.mode!=="off");this.log(n.length>0?` Decisions: ${n.map(([s,i])=>`${s}=${i.mode}/${i.backend??e.defaultBackend}`).join(", ")}`:" Decisions: enabled, no seat is on")}catch(t){this.log(` Decisions: init failed (${t.message})`)}}startConfigWatcher(){let e=this.configPath||Q(process.cwd(),"agentx.json");if(It(e))try{this.configWatcher=yu(e,()=>{this.reload().catch(t=>this.log(`[reload] failed: ${t?.message||t}`))}),this.log(` Watching ${e} for config changes`)}catch(t){this.log(` Config watcher failed to start: ${t.message}`)}}async reload(){let e;try{e=vr(this.configPath)}catch(k){return this.log(`[reload] config invalid, keeping previous: ${k.message}`),{applied:[],restartRequired:[],error:k.message}}let t=[],n=[];if(["maxClaudeCodeDispatchesPerHour","maxClaudeCodeDispatchesPer5h"].some(k=>this.config.session[k]!==e.session[k])&&(gc({maxPerHour:e.session.maxClaudeCodeDispatchesPerHour,maxPer5h:e.session.maxClaudeCodeDispatchesPer5h}),t.push("dispatch-budget")),JSON.stringify(this.config.crons)!==JSON.stringify(e.crons))try{await this.cron.stop(),this.cron=new Pr(e,this.registry,this.hooks,this.log),this.cron.setNotifyCallback(async(k,S,I,R)=>{this.log(`[CRON ALERT] Cron "${k}" failed (${R}x) \u2014 ${I.slice(0,200)}`),this.broadcastSSE("cron-failure",JSON.stringify({jobId:k,agent:S,error:I,consecutiveErrors:R}));let D=e.crons[k];if(D?.notify)try{await this.router.sendOutbound({channel:D.notify.channel,chatId:D.notify.chatId,text:`Cron "${k}" failed (${R}x)
1079
- ${I.slice(0,300)}`,agentId:S,accountId:D.notify.accountId})}catch(C){this.log(`[CRON ALERT] notify send failed: ${C.message}`)}}),await this.cron.start(),t.push("crons")}catch(k){this.log(`[reload] cron reload failed: ${k.message}`)}let i=this.config.channels?.telegram,o=e.channels?.telegram,a=JSON.stringify(i)!==JSON.stringify(o),c=!1;if(a&&o?.enabled){let k=this.router.getChannel("telegram");if(k)try{let S=await k.reloadAccounts(o.accounts,o.policy);this.router.updateConfig(e);let I=[];S.added.length&&I.push(`+${S.added.join(",")}`),S.removed.length&&I.push(`-${S.removed.join(",")}`),S.tokenChanged.length&&I.push(`~${S.tokenChanged.join(",")}`),t.push(I.length?`telegram(${I.join(" ")})`:"telegram"),c=!0}catch(S){this.log(`[reload] telegram hot-reload failed: ${S.message}`)}}else a&&!o?.enabled&&i?.enabled||a&&o?.enabled&&!i?.enabled?c=!1:a||(c=!0);if(JSON.stringify(this.config.providers)!==JSON.stringify(e.providers))try{this.registry.setProviders(e.providers),t.push("providers")}catch(k){this.log(`[reload] providers hot-reload failed: ${k.message}`)}let d=this.config.mesh,l=e.mesh,u=JSON.stringify(d)!==JSON.stringify(l),m=!u;if(u&&l.enabled&&d.enabled&&this.mesh&&!(JSON.stringify(d.healthCheck)!==JSON.stringify(l.healthCheck)))try{let S=await this.mesh.reloadPeers(e),I=[];S.added.length&&I.push(`+${S.added.join(",")}`),S.removed.length&&I.push(`-${S.removed.join(",")}`),S.updated.length&&I.push(`~${S.updated.join(",")}`),t.push(I.length?`mesh(${I.join(" ")})`:"mesh"),m=!0}catch(S){this.log(`[reload] mesh hot-reload failed: ${S.message}`)}if(JSON.stringify(this.config.services)!==JSON.stringify(e.services))try{let k=this.router.getServiceMatcher();if(k){let{count:S}=k.reload(e.services);t.push(`services(${S})`)}else if(Object.keys(e.services).length>0){let S=new sn(e.services,this.log);this.router.setServiceMatcher(S),t.push(`services(${Object.keys(e.services).length})`)}}catch(k){this.log(`[reload] services hot-reload failed: ${k.message}`)}try{let k=this.hooks.size?.()??0;this.hooks.clear(),hr(process.cwd(),this.hooks);let S=this.hooks.size?.()??0;k!==S&&t.push(`hooks(${S})`)}catch(k){this.log(`[reload] hooks reload failed: ${k.message}`)}if(JSON.stringify(this.config.business)!==JSON.stringify(e.business)||JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){try{this.landscape=new Bt(e),this.registry.setLandscape(this.landscape),t.push("landscape")}catch(k){this.log(`[reload] landscape rebuild failed: ${k.message}`)}if(this.mesh&&this.mesh.peerCount()>0)try{let k=await this.mesh.refreshAll(),S=k.filter(I=>I.healthy).length;t.push(`mesh.refresh(${S}/${k.length})`)}catch(k){this.log(`[reload] mesh refresh failed: ${k.message}`)}}if(JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){let k=Object.keys(this.config.agents).sort().join(","),S=Object.keys(e.agents).sort().join(",");k===S&&(this.registry.setConfig(e),t.push("agents.meta"));let I=FI(this.config.agents,e.agents);I.length>0&&n.push(`agents(${I.join(",")})`)}JSON.stringify(this.config.people)!==JSON.stringify(e.people)&&(this.registry.setPeople(e.people),t.push(`people(${e.people.length})`)),m||n.push("mesh"),JSON.stringify(this.config.node)!==JSON.stringify(e.node)&&n.push("node");let f={...this.config.channels,telegram:void 0},p={...e.channels,telegram:void 0};JSON.stringify(f)!==JSON.stringify(p)?n.push("channels"):a&&!c&&n.push("channels.telegram");{let k=this.contacts.size(),S=this.contacts.reload();S.error?this.log(`[reload] contacts.json invalid: ${S.error}`):S.count!==k&&t.push(`contacts(${S.count})`)}if(JSON.stringify(this.config.webhooks)!==JSON.stringify(e.webhooks))try{this.webhooks.setWebhookEntries(e.webhooks),t.push(`webhooks(${e.webhooks.length})`)}catch(k){this.log(`[reload] webhooks hot-reload failed: ${k.message}`)}JSON.stringify(this.config.whatsappTriage)!==JSON.stringify(e.whatsappTriage)&&t.push(`whatsappTriage(${e.whatsappTriage.rules.length} rule(s))`);let y=JSON.stringify(this.config.screen)!==JSON.stringify(e.screen),b=JSON.stringify(this.config.reminders)!==JSON.stringify(e.reminders);return this.config=e,B().configure({node:e.node.name||e.node.id,ringSize:e.events.ringSize}),this.router.updateConfig(e),y&&(this.screenBuffer?.configure(Jr(e.screen)),t.push("screen")),b&&(this.stopReminders?.(),this.startReminders(),t.push("reminders")),t.length&&this.log(`[reload] applied: ${t.join(", ")}`),n.length?(this.log(`[reload] restart required to apply changes in: ${n.join(", ")}`),this.broadcastSSE("reload-partial",JSON.stringify({applied:t,restartRequired:n}))):t.length&&this.broadcastSSE("reload-complete",JSON.stringify({applied:t})),this.workflowPolls?.sync(),{applied:t,restartRequired:n}}requests=null;guestStore=new Ld(process.cwd());guestJoinLimiter=new Ed;operatorKey=null;requestsSweeping=!1;status=null;forwardCommentEdit(e){return async(t,n,s,i,o)=>{let a=this.mesh?.directory().find(l=>l.peer===t&&l.healthy);if(!a)return this.log(`[${e}] edit-comment forward: peer "${t}" not found or unhealthy`),!1;let c=await fetch(`${a.peerUrl}/channel/edit-comment`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(a.peer)},body:JSON.stringify({channel:e,chatId:n,commentId:s,agentId:i,text:o})}),d=await c.json().catch(()=>({}));return c.ok&&d.ok===!0}}approvalsTimer;approvalsSweeping=!1;startApprovalsSweep(){let e=async()=>{if(!(this.approvalsSweeping||this.shuttingDown)){this.approvalsSweeping=!0;try{let t=this.config.notifications?.destination;if(await _h({ctx:{root:process.cwd()},settings:this.config.approvals,fallbackDestination:t?{channel:t.channel,chatId:t.chatId,accountId:t.accountId}:void 0,hasAgent:n=>!!this.registry.getAgent(n),onCardResult:n=>{this.requests?.tracker.cardResolved(n),this.status?.board.cardResolved(n)},tellAgent:async(n,s,i)=>this.tellAgentCardResult(i,s),tellPeer:async(n,s)=>{let i=this.approvalsPeer(n);if(!i)throw new Error(`no mesh peer named "${n}"`);await Nh(s,{self:this.config.node.name,peer:i})},sendDigest:async(n,s)=>{await this.router.sendOutbound({channel:n.channel,chatId:n.chatId,accountId:n.accountId,text:s})},log:this.log}),this.requests&&!this.requestsSweeping){this.requestsSweeping=!0;let n=new Promise((s,i)=>{setTimeout(()=>i(new Error("timed out after 5 min")),3e5).unref?.()});Promise.race([this.sweepRequests(this.requests),n]).catch(s=>this.log(`[requests] sweep failed: ${s?.message??s}`)).finally(()=>{this.requestsSweeping=!1})}this.status?.board.sweep(),Gd({ctx:{root:process.cwd()},settings:this.config.approvals.popup,log:this.log,agentName:n=>this.registry.getAgent(n)?.name,speak:n=>this.voiceTalk.speech.say({voice:{provider:"system",elevenlabs:"",system:this.config.approvals.popup.voice??null,fallback:!1},text:n,kind:"line"})}).catch(n=>this.log(`[approvals] popup failed: ${n?.message??n}`)),this.runCheckin().catch(n=>this.log(`[checkin] failed: ${n?.message??n}`))}catch(t){this.log(`[approvals] sweep failed: ${t?.message??t}`)}finally{this.approvalsSweeping=!1}}};this.approvalsTimer=setInterval(()=>{e()},6e4),this.approvalsTimer.unref?.()}tellAgentCardResult(e,t=Tn(e)){this.registry.execute({agentId:e.raised_by,message:t,context:{channel:"approvals",chatId:e.id,sender:"operator"}}).catch(n=>this.log(`[approvals] ${e.id}: turn on ${e.raised_by} failed: ${n?.message??n}`))}approvalsPeer(e){return Lh(e,this.config.mesh.peers,this.mesh?.directory()??[])}forwardToWarned;approvalsForward(){let e=this.config.approvals.forwardTo;if(!e)return;let t=this.approvalsPeer(e);if(!t){this.forwardToWarned!==e&&(this.forwardToWarned=e,this.log(`[approvals] approvals.forwardTo names "${e}", which is not in mesh.peers; cards stay on this node`));return}return{self:this.config.node.name,peer:t}}carriesMeshToken(e){let t=String(e.headers.authorization||""),n=t.startsWith("Bearer ")?t.slice(7).trim():"";return!!n&&An(this.config).has(n)}async sweepRequests(e){await Gh({store:e.store,settings:this.config.requests,notify:async(t,n,s)=>{await gt({title:t,message:n,from:s.agentId,priority:4},async i=>{try{await this.router.sendOutbound({channel:i.channel??pt(this.config),chatId:i.chatId??"default",text:`${i.title}
1079
+ ${I.slice(0,300)}`,agentId:S,accountId:D.notify.accountId})}catch(C){this.log(`[CRON ALERT] notify send failed: ${C.message}`)}}),await this.cron.start(),t.push("crons")}catch(k){this.log(`[reload] cron reload failed: ${k.message}`)}let i=this.config.channels?.telegram,o=e.channels?.telegram,a=JSON.stringify(i)!==JSON.stringify(o),c=!1;if(a&&o?.enabled){let k=this.router.getChannel("telegram");if(k)try{let S=await k.reloadAccounts(o.accounts,o.policy);this.router.updateConfig(e);let I=[];S.added.length&&I.push(`+${S.added.join(",")}`),S.removed.length&&I.push(`-${S.removed.join(",")}`),S.tokenChanged.length&&I.push(`~${S.tokenChanged.join(",")}`),t.push(I.length?`telegram(${I.join(" ")})`:"telegram"),c=!0}catch(S){this.log(`[reload] telegram hot-reload failed: ${S.message}`)}}else a&&!o?.enabled&&i?.enabled||a&&o?.enabled&&!i?.enabled?c=!1:a||(c=!0);if(JSON.stringify(this.config.providers)!==JSON.stringify(e.providers))try{this.registry.setProviders(e.providers),t.push("providers")}catch(k){this.log(`[reload] providers hot-reload failed: ${k.message}`)}let d=this.config.mesh,l=e.mesh,u=JSON.stringify(d)!==JSON.stringify(l),m=!u;if(u&&l.enabled&&d.enabled&&this.mesh&&!(JSON.stringify(d.healthCheck)!==JSON.stringify(l.healthCheck)))try{let S=await this.mesh.reloadPeers(e),I=[];S.added.length&&I.push(`+${S.added.join(",")}`),S.removed.length&&I.push(`-${S.removed.join(",")}`),S.updated.length&&I.push(`~${S.updated.join(",")}`),t.push(I.length?`mesh(${I.join(" ")})`:"mesh"),m=!0}catch(S){this.log(`[reload] mesh hot-reload failed: ${S.message}`)}if(JSON.stringify(this.config.services)!==JSON.stringify(e.services))try{let k=this.router.getServiceMatcher();if(k){let{count:S}=k.reload(e.services);t.push(`services(${S})`)}else if(Object.keys(e.services).length>0){let S=new sn(e.services,this.log);this.router.setServiceMatcher(S),t.push(`services(${Object.keys(e.services).length})`)}}catch(k){this.log(`[reload] services hot-reload failed: ${k.message}`)}try{let k=this.hooks.size?.()??0;this.hooks.clear(),hr(process.cwd(),this.hooks);let S=this.hooks.size?.()??0;k!==S&&t.push(`hooks(${S})`)}catch(k){this.log(`[reload] hooks reload failed: ${k.message}`)}if(JSON.stringify(this.config.business)!==JSON.stringify(e.business)||JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){try{this.landscape=new Bt(e),this.registry.setLandscape(this.landscape),t.push("landscape")}catch(k){this.log(`[reload] landscape rebuild failed: ${k.message}`)}if(this.mesh&&this.mesh.peerCount()>0)try{let k=await this.mesh.refreshAll(),S=k.filter(I=>I.healthy).length;t.push(`mesh.refresh(${S}/${k.length})`)}catch(k){this.log(`[reload] mesh refresh failed: ${k.message}`)}}if(JSON.stringify(this.config.agents)!==JSON.stringify(e.agents)){let k=Object.keys(this.config.agents).sort().join(","),S=Object.keys(e.agents).sort().join(",");k===S&&(this.registry.setConfig(e),t.push("agents.meta"));let I=FI(this.config.agents,e.agents);I.length>0&&n.push(`agents(${I.join(",")})`)}JSON.stringify(this.config.people)!==JSON.stringify(e.people)&&(this.registry.setPeople(e.people),t.push(`people(${e.people.length})`)),m||n.push("mesh"),JSON.stringify(this.config.node)!==JSON.stringify(e.node)&&n.push("node");let f={...this.config.channels,telegram:void 0},p={...e.channels,telegram:void 0};JSON.stringify(f)!==JSON.stringify(p)?n.push("channels"):a&&!c&&n.push("channels.telegram");{let k=this.contacts.size(),S=this.contacts.reload();S.error?this.log(`[reload] contacts.json invalid: ${S.error}`):S.count!==k&&t.push(`contacts(${S.count})`)}if(JSON.stringify(this.config.webhooks)!==JSON.stringify(e.webhooks))try{this.webhooks.setWebhookEntries(e.webhooks),t.push(`webhooks(${e.webhooks.length})`)}catch(k){this.log(`[reload] webhooks hot-reload failed: ${k.message}`)}JSON.stringify(this.config.whatsappTriage)!==JSON.stringify(e.whatsappTriage)&&t.push(`whatsappTriage(${e.whatsappTriage.rules.length} rule(s))`);let y=JSON.stringify(this.config.screen)!==JSON.stringify(e.screen),b=JSON.stringify(this.config.reminders)!==JSON.stringify(e.reminders);return this.config=e,B().configure({node:e.node.name||e.node.id,ringSize:e.events.ringSize}),this.router.updateConfig(e),y&&(this.screenBuffer?.configure(Jr(e.screen)),t.push("screen")),b&&(this.stopReminders?.(),this.startReminders(),t.push("reminders")),t.length&&this.log(`[reload] applied: ${t.join(", ")}`),n.length?(this.log(`[reload] restart required to apply changes in: ${n.join(", ")}`),this.broadcastSSE("reload-partial",JSON.stringify({applied:t,restartRequired:n}))):t.length&&this.broadcastSSE("reload-complete",JSON.stringify({applied:t})),this.workflowPolls?.sync(),{applied:t,restartRequired:n}}requests=null;guestStore=new jd(process.cwd());guestJoinLimiter=new Ud;operatorKey=null;requestsSweeping=!1;status=null;forwardCommentEdit(e){return async(t,n,s,i,o)=>{let a=this.mesh?.directory().find(l=>l.peer===t&&l.healthy);if(!a)return this.log(`[${e}] edit-comment forward: peer "${t}" not found or unhealthy`),!1;let c=await fetch(`${a.peerUrl}/channel/edit-comment`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(a.peer)},body:JSON.stringify({channel:e,chatId:n,commentId:s,agentId:i,text:o})}),d=await c.json().catch(()=>({}));return c.ok&&d.ok===!0}}approvalsTimer;approvalsSweeping=!1;startApprovalsSweep(){let e=async()=>{if(!(this.approvalsSweeping||this.shuttingDown)){this.approvalsSweeping=!0;try{let t=this.config.notifications?.destination;if(await _h({ctx:{root:process.cwd()},settings:this.config.approvals,fallbackDestination:t?{channel:t.channel,chatId:t.chatId,accountId:t.accountId}:void 0,hasAgent:n=>!!this.registry.getAgent(n),onCardResult:n=>{this.requests?.tracker.cardResolved(n),this.status?.board.cardResolved(n)},tellAgent:async(n,s,i)=>this.tellAgentCardResult(i,s),tellPeer:async(n,s)=>{let i=this.approvalsPeer(n);if(!i)throw new Error(`no mesh peer named "${n}"`);await Nh(s,{self:this.config.node.name,peer:i})},sendDigest:async(n,s)=>{await this.router.sendOutbound({channel:n.channel,chatId:n.chatId,accountId:n.accountId,text:s})},log:this.log}),this.requests&&!this.requestsSweeping){this.requestsSweeping=!0;let n=new Promise((s,i)=>{setTimeout(()=>i(new Error("timed out after 5 min")),3e5).unref?.()});Promise.race([this.sweepRequests(this.requests),n]).catch(s=>this.log(`[requests] sweep failed: ${s?.message??s}`)).finally(()=>{this.requestsSweeping=!1})}this.status?.board.sweep(),Gd({ctx:{root:process.cwd()},settings:this.config.approvals.popup,log:this.log,agentName:n=>this.registry.getAgent(n)?.name,speak:n=>this.voiceTalk.speech.say({voice:{provider:"system",elevenlabs:"",system:this.config.approvals.popup.voice??null,fallback:!1},text:n,kind:"line"})}).catch(n=>this.log(`[approvals] popup failed: ${n?.message??n}`)),this.runCheckin().catch(n=>this.log(`[checkin] failed: ${n?.message??n}`))}catch(t){this.log(`[approvals] sweep failed: ${t?.message??t}`)}finally{this.approvalsSweeping=!1}}};this.approvalsTimer=setInterval(()=>{e()},6e4),this.approvalsTimer.unref?.()}tellAgentCardResult(e,t=Tn(e)){this.registry.execute({agentId:e.raised_by,message:t,context:{channel:"approvals",chatId:e.id,sender:"operator"}}).catch(n=>this.log(`[approvals] ${e.id}: turn on ${e.raised_by} failed: ${n?.message??n}`))}approvalsPeer(e){return Lh(e,this.config.mesh.peers,this.mesh?.directory()??[])}forwardToWarned;approvalsForward(){let e=this.config.approvals.forwardTo;if(!e)return;let t=this.approvalsPeer(e);if(!t){this.forwardToWarned!==e&&(this.forwardToWarned=e,this.log(`[approvals] approvals.forwardTo names "${e}", which is not in mesh.peers; cards stay on this node`));return}return{self:this.config.node.name,peer:t}}carriesMeshToken(e){let t=String(e.headers.authorization||""),n=t.startsWith("Bearer ")?t.slice(7).trim():"";return!!n&&An(this.config).has(n)}async sweepRequests(e){await Gh({store:e.store,settings:this.config.requests,notify:async(t,n,s)=>{await gt({title:t,message:n,from:s.agentId,priority:4},async i=>{try{await this.router.sendOutbound({channel:i.channel??pt(this.config),chatId:i.chatId??"default",text:`${i.title}
1080
1080
  ${i.message}`,priority:i.priority,agentId:s.agentId})}catch(o){if(this.log(`[requests] push for ${s.id} failed: ${o?.message??o}`),process.platform!=="darwin")throw o}},{alert:pe(Ce(this.config.notifications.local))})},hasAgent:t=>!!this.registry.getAgent(t),tellAgent:async(t,n,s)=>{this.registry.execute({agentId:t,message:n,context:ka(s.id)}).then(i=>{Ni(e.store,s,i,Date.now())&&this.log(`[requests] ${s.id}: could not hand it back to ${t}: ${i.error}`)}).catch(i=>{Ni(e.store,s,{error:i?.message??String(i)},Date.now()),this.log(`[requests] ${s.id}: turn on ${t} failed: ${i?.message??i}`)})},log:this.log})}runCheckin(e){if(process.platform!=="darwin")return Promise.resolve(null);let t={root:process.cwd(),settings:this.config.approvals.checkin,cardSettings:this.config.approvals,source:ps(this.config.reminders.command),...this.config.reminders.enabled?{claimsPath:ds(process.cwd())}:{},hasAgent:n=>!!this.registry.getAgent(n),ask:async(n,s,i)=>{let o=await this.registry.execute({agentId:n,message:s,timeoutMinutes:this.config.approvals.checkin.composeTimeoutSeconds/60,context:{channel:"reminder",chatId:`checkin:${i.id}`,sender:"approvals"}});if(o.error)throw new Error(o.error);return o.content??""},notify:async(n,s)=>{let i=this.config.approvals.checkin.agent;await gt({title:n,message:s,from:i,priority:4},async o=>{try{await this.router.sendOutbound({channel:o.channel??pt(this.config),chatId:o.chatId??"default",text:`${o.title}
1081
1081
  ${o.message}`,priority:o.priority,agentId:i})}catch(a){this.log(`[checkin] push for "${o.title}" failed: ${a?.message??a}`)}},{alert:pe(Ce(this.config.notifications.local))})},log:this.log};return ig(t,e)}stopReminders;startReminders(){let e=this.config.notifications?.destination;this.stopReminders=cg({settings:this.config.reminders,root:process.cwd(),execute:(t,n,s,i)=>this.registry.execute(t,n,s,i),hasAgent:t=>!!this.registry.getAgent(t),send:t=>this.router.sendOutbound(t),fallbackDestination:e?{channel:e.channel,chatId:e.chatId,accountId:e.accountId}:void 0,isStopping:()=>this.shuttingDown,log:this.log})}scheduleMidnightHook(){let e=()=>{let t=new Date,n=new Date(t);n.setDate(n.getDate()+1),n.setHours(0,0,5,0);let s=n.getTime()-t.getTime();this.log(` Cost tracking: next run in ${Math.round(s/6e4)}min`),this.midnightTimer=setTimeout(async()=>{await this.runDailyCostReport(),e()},Math.max(s,6e4))};e()}async runDailyCostReport(){let e=new Date(Date.now()-864e5).toISOString().slice(0,10),t=this.registry.getTokenTracker();if(t.hasTokenCostsEntry(e)){this.log(` Cost tracking: ${e} already logged, skipping`);return}let n=t.generateDailyReport(e);if(!n||n.totalTasks===0){this.log(` Cost tracking: no usage for ${e}, skipping`);return}t.appendToTokenCosts(n),this.log(` Cost tracking: ${e} \u2014 ${n.totalTasks} tasks, $${n.totalCost.toFixed(4)} (top: ${n.topAgent} $${n.topCost.toFixed(4)})`)}async startChannels(){if(this.config.channels.telegram.enabled){let e=this.config.channels.telegram.accounts;if(Object.keys(e).length>0){let t=this.config.channels.telegram.policy,n=new Xe(e,{policy:{allowFrom:t?.allowFrom}},this.log);this.router.addChannel(n);let s=t?.allowFrom?.length??0,i=Object.entries(e).filter(([,o])=>!o.allowFrom&&s===0).length;i>0?this.log(` Telegram: enabled \u2014 WARNING: ${i} account(s) have no allowFrom (global or per-account). All incoming messages will be DROPPED.`):this.log(` Telegram: enabled \u2014 global allowFrom entries: ${s}`)}}if(this.config.channels.whatsapp.enabled){let{setWhatsAppQR:e,setWhatsAppStatus:t}=await import("./whatsapp-state-LB3R32BK.js"),n=new Gn({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes,throttle:{minMsBetweenCalls:this.config.channels.whatsapp.ingest?.throttle?.minMsBetweenCalls,maxCallsPerMinute:this.config.channels.whatsapp.ingest?.throttle?.maxCallsPerMinute},onQR:e,onStatus:t},this.log);this.router.addChannel(n),this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes)`)}if(this.config.channels.gitlab?.enabled&&this.config.channels.gitlab.token){let e=new Wn({webhookPort:this.config.channels.gitlab.webhookPort,webhookSecret:this.config.channels.gitlab.webhookSecret,host:this.config.channels.gitlab.host,token:this.config.channels.gitlab.token,routes:this.config.channels.gitlab.routes,agentMappings:this.config.channels.gitlab.agentMappings,knownAgentIds:Object.keys(this.config.agents),agentUsernamePrefixes:this.config.channels.gitlab.agentUsernamePrefixes},this.log,this.hooks);e.setStatusComments(()=>this.config.requestStatus.channels.some(t=>t.toLowerCase()==="gitlab")),this.mesh&&(e.setMesh(this.mesh),e.setEditCommentForwarder(this.forwardCommentEdit("gitlab")),e.setReactForwarder(async(t,n,s,i,o,a,c)=>{let d=this.mesh.directory().find(u=>u.peer===t&&u.healthy);if(!d){this.log(`[gitlab] react forward: peer "${t}" not found or unhealthy`);return}let l=`${d.peerUrl}/gitlab/react`;try{let u=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(d.peer)},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,noteId:o,agentId:a,name:c})}),m=await u.text().catch(()=>"");this.log(`[gitlab] react forward -> ${l} : ${u.status} ${m.slice(0,200)}`)}catch(u){this.log(`[gitlab] react forward FAILED -> ${l} : ${u.message}`)}}),e.setSendNoteForwarder(async(t,n,s,i,o,a)=>{let c=this.mesh.directory().find(l=>l.peer===t&&l.healthy);if(!c)return this.log(`[gitlab] send-note forward: peer "${t}" not found or unhealthy`),"";let d=`${c.peerUrl}/gitlab/send-note`;try{let l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(c.peer)},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:o,text:a})}),u=await l.json().catch(()=>({}));return this.log(`[gitlab] send-note forward -> ${d} : ${l.status} noteId=${u.noteId||"?"}`),u.noteId||""}catch(l){return this.log(`[gitlab] send-note forward FAILED -> ${d} : ${l.message}`),""}}),e.setLogTimeForwarder(async(t,n,s,i,o,a)=>{let c=this.mesh.directory().find(l=>l.peer===t&&l.healthy);if(!c){this.log(`[gitlab] log-time forward: peer "${t}" not found or unhealthy`);return}let d=`${c.peerUrl}/gitlab/log-time`;try{let l=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(c.peer)},body:JSON.stringify({project:n,noteableType:s,noteableIid:i,agentId:o,durationMs:a})}),u=await l.text().catch(()=>"");this.log(`[gitlab] log-time forward -> ${d} : ${l.status} ${u.slice(0,160)}`)}catch(l){this.log(`[gitlab] log-time forward FAILED -> ${d} : ${l.message}`)}})),e.setProjectRules(this.projectRules),this.router.addChannel(e),this.log(` GitLab: enabled (${this.config.channels.gitlab.routes.length} project routes, webhook :${this.config.channels.gitlab.webhookPort})`)}if(this.config.channels.github?.enabled){let e=this.config.channels.github;this.github=new Jn({token:e.token,tokenFile:e.tokenFile,appId:e.appId,clientId:e.clientId,privateKeyFile:e.privateKeyFile,webhookSecret:e.webhookSecret,routes:e.routes,agentMappings:e.agentMappings,issueActions:e.issueActions,pullRequestActions:e.pullRequestActions,ignoreOwnChanges:e.ignoreOwnChanges,debounceSeconds:e.debounceSeconds},this.log),this.mesh&&(this.github.setEditCommentForwarder(this.forwardCommentEdit("github")),this.github.setSendCommentForwarder(async(t,n,s,i,o)=>{let a=this.mesh.directory().find(d=>d.peer===t&&d.healthy);if(!a)return this.log(`[github] send-comment forward: peer "${t}" not found or unhealthy`),"";let c=`${a.peerUrl}/github/send-comment`;try{let d=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(a.peer)},body:JSON.stringify({repo:n,issueNumber:s,agentId:i,text:o})}),l=await d.json().catch(()=>({}));return this.log(`[github] send-comment forward -> ${c} : ${d.status} commentId=${l.commentId||"?"}`),l.commentId||""}catch(d){return this.log(`[github] send-comment forward FAILED -> ${c} : ${d.message}`),""}})),this.mesh&&this.github.setPeerPostingLogins(()=>this.mesh.directory().flatMap(t=>t.githubLogins)),this.github.setProjectRules(this.projectRules),this.router.addChannel(this.github),this.log(` GitHub: enabled (${e.routes.length} repo routes)`)}if(this.config.channels.ntfy?.enabled){let e=this.config.channels.ntfy;if(!e.topic)this.log(" ntfy: enabled but channels.ntfy.topic is unset \u2014 skipping");else{let{NtfyAdapter:t}=await import("./ntfy-52EXHVMD.js"),n=new t({server:e.server,topic:e.topic,token:e.token,defaultPriority:e.defaultPriority,defaultTitle:e.defaultTitle},this.log);this.router.addChannel(n),await n.start(),this.log(` ntfy: enabled (${e.server})`)}}if(this.config.channels.push?.enabled){let e=this.config.channels.push;if(e.relayTo){let{PushRelayAdapter:t}=await import("./push-HEDA6P3B.js"),n=new t(e.relayTo,(s,i)=>this.relayPush(s,i),this.log);this.router.addChannel(n),await n.start()}else if(!e.subject)this.log(" push: enabled but channels.push.subject is unset \u2014 skipping");else{let t=wr();if(!t)this.log(" push: enabled but the SQLite database is unavailable \u2014 skipping");else{let{PushAdapter:n}=await import("./push-HEDA6P3B.js"),{PushStore:s}=await import("./push-store-5VJ4FNI4.js"),{pushKeysPath:i,readPushKeys:o}=await import("./push-keys-2DTD7YNQ.js"),{default:a}=await import("web-push"),c=new Nr,d=i(e.keysFile),l=new n({store:new s(t),keys:()=>o(d),subject:e.subject,ttlSeconds:e.ttlSeconds,keepRecent:e.keepRecent,deviceActive:f=>c.isActive(f),sender:(f,p,y)=>a.sendNotification(f,p,y),log:this.log});this.router.addChannel(l),await l.start();let{attachAnnouncePush:u}=await import("./push-announce-PM5FZJRW.js"),{PushPrefs:m}=await import("./push-prefs-YOJNTOJF.js");u({bus:B(),store:new s(t),prefs:new m(t),send:f=>l.send(f),log:this.log})}}}if(this.config.channels.webrtc?.enabled){let e=this.config.channels.webrtc;if(this.webrtc=new ld(this.config.node.name,e.allowedCallers,this.log),this.mesh&&this.webrtc.setForwarder(async(t,n)=>{try{return await this.mesh.sendSignal(t,n)}catch(s){return this.log(`[webrtc] forward to "${t}" failed: ${s.message}`),!1}}),e.ringNotify.length>0){let t=e.callUrlBase||`http://${this.config.node.bind}`;this.webrtc.setRingHandler(async n=>{let s=dd(n,t);for(let i of e.ringNotify)try{await this.router.sendOutbound({channel:i.channel,chatId:i.chatId,text:s,parseMode:"plain",...i.accountId?{accountId:i.accountId}:{}})}catch(o){this.log(`[webrtc] ring notify via ${i.channel}:${i.chatId} failed: ${o.message}`)}})}if(e.bot.enabled){let t=e.bot,n=[...e.stunServers.map(s=>({urls:s})),...e.turnServers];this.botManager=new es({broker:this.webrtc,iceServers:n,whisperBackend:t.whisperBackend,whisperModel:t.whisperModel,whisperLanguage:t.whisperLanguage,mlxBinary:t.mlxBinary,maxCallMinutes:t.maxCallMinutes,log:this.log,onTranscript:async({invite:s,text:i,durationMs:o})=>{let a=t.transcriptChannel;if(!a)return;let c=`[${new Date().toLocaleTimeString()} \u2022 ${(o/1e3).toFixed(1)}s \u2022 ${s.target}]`;try{await this.router.sendOutbound({channel:a.channel,chatId:a.chatId,text:`${c}
1082
1082
  ${i}`,parseMode:"plain",...a.accountId?{accountId:a.accountId}:{}})}catch(d){this.log(`[bot-manager] transcript send via ${a.channel}:${a.chatId} failed: ${d.message}`)}}}),this.log(` WebRTC bot: enabled (whisper=${t.whisperBackend}, default-agent=${t.defaultAgentId||"(none)"}, transcript=${t.transcriptChannel?`${t.transcriptChannel.channel}:${t.transcriptChannel.chatId}`:"(none)"})`)}this.cameraWatch=this.createCameraWatch(),this.log(` WebRTC signaling: enabled (stun=${e.stunServers.length}, turn=${e.turnServers.length}, allowedCallers=${e.allowedCallers.length||"all"}, ringNotify=${e.ringNotify.length}, bot=${e.bot.enabled?"on":"off"}, camera-bot frames=${e.camera.bot.frameIntervalSeconds?`every ${e.camera.bot.frameIntervalSeconds}s`:"on demand"})`)}await this.bootWorkflowEngine(),this.registry.getSessionStore().setAdapterResolver(e=>this.router.getChannel(e)),await this.router.startAll(),this.delegations.recover().then(e=>{e&&this.log(`[delegation] ${e} delegation(s) lost in the restart were reported to their callers`)}).catch(e=>this.log(`[delegation] recovery failed: ${e?.message??e}`))}async bootWorkflowEngine(){let e=this.config.workflows;if(!e?.enabled){this.log(" Workflows: disabled (set workflows.enabled to turn the engine on)");return}let t=new kc({baseDir:Q(process.cwd(),e.dir)}),n=new vc({baseDir:Q(process.cwd(),e.dir),nodeId:this.config.node.id}),s={};for(let y of this.router.getChannelNames()){let b=this.router.getChannel(y);b&&(s[y]=b)}let i={execute:async y=>{let b=Date.now();try{let k=y.workflowRunId?`workflow:${y.workflowRunId}`:"workflow:adhoc",S=await this.registry.execute({agentId:y.agentId,message:y.message,workflowRunId:y.workflowRunId,timeoutMinutes:y.timeoutMinutes,autonomy:y.autonomy,context:{channel:"workflow",chatId:k,sender:"workflow"}});return{content:S.content??"",error:S.error,errorKind:S.errorKind,autonomyBlocks:S.autonomyBlocks,taskId:`wf-${y.workflowRunId??"na"}-${b.toString(36)}`,durationMs:Date.now()-b}}catch(k){return{content:"",error:k.message}}}},o=this.mesh?{forwardTransition:async(y,b)=>{let k=this.mesh.directory().find(I=>I.peer===y&&I.healthy);if(!k){this.log(`[workflows] forward to "${y}" skipped \u2014 peer not found or unhealthy`);return}let S=`${k.peerUrl}/workflow/event`;try{let I=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(k.peer)},body:JSON.stringify({payload:b})});I.ok||this.log(`[workflows] forward ${S} -> ${I.status}`)}catch(I){this.log(`[workflows] forward ${S} failed: ${I.message}`)}},broadcastTrigger:async y=>{let b=this.mesh.directory().filter(S=>S.healthy);if(b.length===0)return;let k=this.config.node.id;this.log(`[workflows/mesh] broadcasting trigger source="${y.trigger.source}" chat="${y.trigger.chat??"*"}" -> ${b.length} peer(s): ${b.map(S=>S.peer).join(", ")}`),await Promise.allSettled(b.map(async S=>{let I=`${S.peerUrl}/workflow/event`;try{let R=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(S.peer)},body:JSON.stringify({kind:"trigger",fromPeer:k,payload:y}),signal:AbortSignal.timeout(5e3)});R.ok||this.log(`[workflows/mesh] broadcastTrigger ${S.peer} -> ${R.status}`)}catch(R){this.log(`[workflows/mesh] broadcastTrigger ${S.peer} failed: ${R.message}`)}}))},forwardChannelSend:async y=>{let b=this.mesh.directory().filter(D=>D.healthy&&D.channels?.includes(y.channel));if(b.length===0)throw new Error(`no healthy mesh peer hosts channel "${y.channel}"`);let k=b[0],S=`${k.peerUrl}/channel/send`,I=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(k.peer)},body:JSON.stringify(y),signal:AbortSignal.timeout(15e3)});if(!I.ok){let D=await I.text().catch(()=>"");throw new Error(`peer ${k.peer} /channel/send -> ${I.status} ${D.slice(0,200)}`)}return{messageId:(await I.json().catch(()=>({}))).messageId??null}}}:void 0,{TimerService:a}=await import("./timers-KK7GF77Y.js"),c=new a({baseDir:e.dir?Q(process.cwd(),e.dir):void 0,log:y=>this.log(y)}),d=new _c({store:t,runs:n,nodeId:this.config.node.id,channels:s,agents:i,forwarder:o,timers:c,events:this.events,log:y=>this.log(y)});c.start();let l=Oc(d);for(let[y,b]of Object.entries(l))b&&this.hooks.registerHandler(y,`workflows:${y}`,b,50);this.workflowDispatcher=d,this.workflowStore=t,this.workflowRuns=n,this.webhooks.setWorkflowDispatcher(d),this.registry.setWorkflowAutoRunner(async({workflowId:y,channel:b,chatId:k,payload:S})=>{let I=t.get(y);if(!I)throw new Error(`auto-run target workflow not found: ${y}`);let R=Uc(I,{chatId:k,channel:b,message:typeof S.message=="string"?S.message:void 0,agentId:typeof S.agentId=="string"?S.agentId:void 0,senderId:typeof S.senderId=="string"?S.senderId:void 0,senderUsername:typeof S.senderUsername=="string"?S.senderUsername:void 0});if(R.missing.length>0)throw new Error(`inputSchema requires ${R.missing.join(", ")} \u2014 chatId+defaults filled [chatId: ${R.filledFrom.chatId.join(",")||"\u2014"} | defaults: ${R.filledFrom.defaults.join(",")||"\u2014"}]; auto-run skipped (operator can fill manually or extend the inputSchema).`);this.log(`[workflows] auto-run input resolution for ${y}: passthrough=[${R.filledFrom.passthrough.join(",")}] chatId=[${R.filledFrom.chatId.join(",")}] defaults=[${R.filledFrom.defaults.join(",")}]`);let D={backend:"manual",id:k||`auto-${Date.now().toString(36)}`},C=`auto:${y}:${k}:${Date.now()}`;return{runId:(await d.dispatchWorkflow({workflowId:y,entityRef:D,event:{id:C,payload:R.inputs},trigger:{source:"manual"}})).run?.id}});let{cronTimers:u,hookSubscribers:m}=Lc({store:t,dispatcher:d,hooks:this.hooks,log:y=>this.log(y),forgeUsernames:y=>[...Ve(this.config.channels.gitlab?.agentMappings,"gitlabUsernames",y),...Ve(this.config.channels.github?.agentMappings,"githubUsernames",y)]});this.workflowPolls=new Fc({store:t,dispatcher:d,log:y=>this.log(y)});let f=this.workflowPolls.start(),p=t.list().length;this.log(` Workflows: enabled (${p} definition${p===1?"":"s"} loaded from ${e.dir}, editor=${e.editor}, cron=${u}, hook=${m}, poll=${f})`);try{let{detectConflicts:y}=await import("./conflict-detector-KS7OSS45.js"),b=y(t.list(),this.config);if(b.length>0){this.log(` Workflows: ${b.length} dispatch conflict(s) detected`);for(let k of b)this.log(` [${k.severity}] ${k.workflowId}: ${k.summary}`),this.log(` \u2192 ${k.suggestion}`)}}catch(y){this.log(` Workflows: conflict-detector failed: ${y.message}`)}}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),n=parseInt(t||"18800",10);this.httpServer=MI(async(s,i)=>{if(Gr(s.headers)==="foreign"&&Vd(s.method)){this.log(`[auth] \u2717 refused ${s.method} ${(s.url||"").split("?")[0]} from a page on another origin (${s.headers.origin||s.headers["sec-fetch-site"]})`),this.json(i,403,{error:"Forbidden: request from a page on another origin"});return}if(this.shuttingDown&&Zd(s.method,(s.url||"/").split("?")[0])){i.setHeader("Retry-After","30"),this.json(i,503,{error:"daemon is restarting; retry shortly"});return}if(s.method==="OPTIONS"){i.writeHead(204),i.end();return}await this.handleHttp(s,i)}),this.httpServer.on("error",s=>{s.code==="EADDRINUSE"?(this.log(` ERROR: Port ${n} is already in use. Retrying in 5s...`),setTimeout(()=>{this.httpServer?.close(),this.httpServer?.listen(n,e||"0.0.0.0")},5e3)):this.log(` HTTP error: ${s.message}`)}),this.httpServer.listen(n,e||"0.0.0.0",()=>{this.log(` HTTP API: http://${e||"0.0.0.0"}:${n}`);let s=kg(this.config,i=>!!this.registry.getAgent(i));for(let i of s)this.log(` [mesh-relay] \u26A0 inbox "${i.name}" names agent "${i.agent}", which is not on this node \u2014 it will refuse messages`)}),this.attachSweep=setInterval(()=>{try{let s=se();s.sweep(),s.prune()}catch{}},1e3),this.attachSweep.unref?.()}delegationGate(e,t,n,s={}){let i=jo(e,t),o=Lo(i,this.registry),a=Uo(n.callee,o,this.registry,this.syncWaits);if(a)return{refused:a};if(!n.peer&&this.registry.getAgent(n.callee)){let l=ff(n.callee,i,o,this.registry,this.syncWaits);if(l)return{refused:l}}let c=s.callback===!1?null:this.startCallback(t,o,n);if(c)return{accepted:c};let d;return{track:{...o?{root:Le(o.context,o.agentId)}:{},onStart:l=>{d=l,o?.taskId&&this.syncWaits.begin(o.taskId,l,Fo(o,this.syncWaits))},end:()=>{d&&this.syncWaits.end(d)}}}}startCallback(e,t,n){let s=e.async===!0?!0:e.async===!1?!1:void 0;if(!t||!this.delegations.shouldCallback(t,s))return null;let i=n.peer;if(!i&&!this.registry.getAgent(n.callee)){let c=this.mesh?.findAgentPeer(n.callee);if(!c?.healthy)return null;i=c.peer}let o={};if(!i){let c=this.recordInboundDispatch(n.callee,{channel:"a2a",sender:`agent:${t.agentId}`,chatId:`a2a:${t.agentId}:${n.callee}`,initiator:Le(t.context,t.agentId)},n.message,t.agentId);c&&(o.intentRef=c)}let{taskId:a}=this.delegations.start({caller:t,callee:n.callee,peer:i,message:n.message,calleeContext:n.calleeContext,extras:o});return wf(a,n.callee,i)}recordInboundDispatch(e,t,n,s,i=Ea(this.config.people,t)?.id??null){if(ie("mesh")!=="off")try{let o=_g(ne(),{agentId:e,senderAgentId:s,context:t},Mg(e,s,t,n,i),{agentId:e,outcome:"dispatched",reason:s?`from ${s}`:null});return o.outcome==="dispatched"?{eventId:o.eventId,decidedBy:o.decidedBy}:void 0}catch(o){this.log(`[ledger] ${t?.channel??"mesh"} agent="${e}" record failed: ${o?.message??o}`);return}}broadcastSSE(e,t){if(this.sseClients.size===0)return;let n=`event: ${e}
@@ -1139,10 +1139,10 @@ data: ${JSON.stringify(be)}
1139
1139
 
1140
1140
  `)}catch{}},15e3);re.unref?.();let $e=!1;t.on("close",()=>{if($e)return;$e=!0,clearInterval(re);let F=h.context??{};F.channel&&F.chatId&&(this.processRegistry?.kill({agentId:g,channel:F.channel,chatId:F.chatId},"client-interrupt").catch(()=>{}),this.registry.cancelChatTasks(g,F.channel,F.chatId,"client-interrupt"))});let Te=F=>{F&&W("text",{text:F})},X=F=>{F&&W("thinking",{text:F})},de=F=>{if(!F||typeof F!="object")return"";let be=F.file_path??F.path??F.notebook_path;if(typeof be=="string")return be.split("/").pop()||be;let ge=F.command??F.pattern??F.query??F.url??F.prompt??F.description;if(typeof ge=="string")return ge.replace(/\s+/g," ").slice(0,48);let ea=Object.values(F).find(Lf=>typeof Lf=="string");return ea?ea.replace(/\s+/g," ").slice(0,48):""},xe=new Set,on=F=>{let be=F?.type;if(be==="tool_call")W("tool",{status:"start",id:F.id,name:F.name,arg:de(F.input)});else if(be==="tool_result")W("tool",{status:"result",id:F.id,name:F.name,error:F.is_error===!0});else if(be==="assistant"&&Array.isArray(F.message?.content))for(let ge of F.message.content)ge?.type==="tool_use"&&ge.id&&!xe.has(ge.id)&&(xe.add(ge.id),W("tool",{status:"start",id:ge.id,name:ge.name,arg:de(ge.input)}))};try{let F=await mn(A,()=>this.registry.execute({agentId:g,message:h.message,context:h.context,contextStrategy:x,intentRef:M,freshSession:L,onStart:T.onStart},Te,X,on)).finally(T.end);$e=!0,clearInterval(re),F.error?W("error",{error:F.error,errorKind:F.errorKind}):W("done",{content:F.content,duration:F.duration,usage:F.usage})}catch(F){$e=!0,clearInterval(re),W("error",{error:F?.message??String(F)})}try{t.end()}catch{}break}let he=Eh(h,g),H=Ch(await mn(A,()=>this.registry.execute({agentId:g,message:h.message,context:h.context,contextStrategy:x,intentRef:M,freshSession:L,systemPromptAppend:ml(h.context),origin:he,onStart:T.onStart},()=>{})).finally(T.end),he);this.json(t,H.error?500:200,H);break}case"POST /voice/phrase":{let h=await G(e),g=String(h.tool??""),w=String(h.detail??""),v=Number(h.elapsedSeconds??0);if(!g&&!w){this.json(t,400,{error:"Required: tool or detail"});return}try{let $=await Ze(Vm,Xm({tool:g,detail:w,elapsedSeconds:v}),Jm,{timeoutMs:4e3,features:{tool:g}});if(!$||$.mode!=="active"){this.json(t,200,{say:null});return}let T=Km($.answers);this.json(t,200,T)}catch{this.json(t,200,{say:null})}break}case"POST /voice/address":{let h=await G(e),g=String(h.target??""),w=Object.entries(this.config.agents).map(([$,T])=>({id:$,name:T.name,mentions:T.mentions})),v=ym(this.mesh?.directory()??[],$=>!!this.config.agents[$]);this.json(t,200,wm({text:String(h.text??""),target:g,local:w,remote:v,localNode:this.config.node.id,localLook:$=>{let T=this.config.agents[$];return T?{color:ce($,T).color,palette:T.presence?.palette,colorSet:!!T.presence?.color}:void 0},defaultPalette:this.config.voice.palette}));break}case"GET /voice/settings":{this.json(t,200,Io(this.config,Ge()));break}case"POST /voice/settings":{let h=await G(e),g=await $m(h,this.config,this.configPath);if(!g.ok){this.json(t,g.status,{error:g.error,errors:g.errors});break}let w=await this.reload();this.json(t,200,{ok:!0,applied:w.applied,restartRequired:w.restartRequired,settings:Io(this.config,Ge())});break}case"POST /voice/preview":{let h=await G(e),g=Tm(h,this.config,Ge());if("error"in g){this.json(t,400,{error:g.error});break}let{item:w}=this.voiceTalk.speech.enqueue({...g,kind:"line"},!0);this.json(t,202,{item:w});break}case"POST /ask":case"GET /ask":{let h=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`),g=h.searchParams.get("q")||h.searchParams.get("message")||"",w=h.searchParams.get("agent")||"",v=h.searchParams.get("session")||"";if(e.method==="POST"){let X=await G(e);g=X.message||X.q||g,w=X.agent||X.agentId||w,v=X.session||v}let $=w.trim()||this.config.node.defaultAgent;if(!$){this.json(t,400,{error:"No agent (pass ?agent=... or set node.defaultAgent)"});return}if(!g){this.json(t,400,{error:"Missing message (pass as ?q=... or {message:...})"});return}let T=/^AgentXVoice\//.test(String(e.headers["user-agent"]||""))?"desktop":"voice",x=v.trim()||T,E=this.voiceMesh.switchTo(x,g,$);if(E){let de=!this.registry.getAgent(E)?this.voiceMesh.voices.voice(E):le(E,this.config.agents,this.config.voice),xe=this.voiceIntros.needsIntro(x,E)?de.intro:"I'm here.";this.voiceIntros.spoke(x,E),this.json(t,200,{agentId:E,voice:Et(de,xe),presence:null,text:xe,full:xe,ui:null,switched:!0});break}let M=this.voiceMesh.target(x,$),A=!this.registry.getAgent(M)&&this.voiceMesh.isRemote(M);if(!A&&!this.registry.getAgent(M)){this.json(t,404,{error:`Unknown agent: "${M}"`,agents:this.voiceMesh.known()});return}let O=A?this.voiceMesh.voices.voice(M):le(M,this.config.agents,this.config.voice),L=this.voiceIntros.needsIntro(x,M),j=this.config.voice.noiseFilter;if(j.enabled&&ca(g,j.markers)){this.log(`[voice] ${M}: noise transcript dropped (${JSON.stringify(g.slice(0,60))})`),this.json(t,200,{agentId:M,voice:Et(O,un),presence:null,text:un,full:un,ui:null,noise:!0});break}let q=A?null:await this.voiceTalk.presence.decide(M,g);if(q?.seat==="active"&&(q.mode==="teach"||q.mode==="watch"||q.mode==="act")&&this.voiceTalk.startLesson(M,g,q.mode,q.app??void 0).status===201){this.voiceIntros.spoke(x,M);let de=q.mode==="watch"?"Go ahead, I'm watching.":"Sure, I'll show you on screen.";this.json(t,200,{agentId:M,voice:O,presence:q,text:de,full:de,ui:null});break}if(A){let X=await this.voiceMesh.ask(M,g,O,L),{cleanText:de,ui:xe}=Ee(X.content);X.error||this.voiceIntros.spoke(x,M);let on=X.error?null:ln(de,this.config.voice.spokenMaxChars);this.json(t,X.error?502:200,{agentId:M,voice:Et(O,on),presence:null,text:on,full:X.error?null:de,ui:xe??null,error:X.error,duration:X.duration,peer:X.peer});break}let he=this.recordInboundDispatch(M,{channel:T,sender:T==="desktop"?"Desktop":"Voice",chatId:`${T}:${M}`},g,void 0,Ra(this.config.people)?.id??null),H=await this.registry.execute({agentId:M,message:g,systemPromptAppend:`${pl}
1141
1141
  ${En(O,L)}`+(this.config.voice.look==="character"&&this.voiceTalk.guide.listening?`
1142
- ${Kp}`:""),context:hn({channel:"voice",sender:"Voice",chatId:`voice:${M}`}),intentRef:he}),W={agentId:M,voice:O},K=Ue(H.error);if(K){let X=K.pending;this.json(t,202,{...W,text:X>1?`I'm still on your last request, and ${X} more are waiting. Give me a moment.`:"I'm still working on your last request. Give me a moment.",full:null,ui:null,queued:!0,pending:X,duration:H.duration});return}let{cleanText:re,ui:$e}=Ee(H.content??""),Te=ln(re,this.config.voice.spokenMaxChars);H.error||this.voiceIntros.spoke(x,M),this.voiceTalk.presence.hide(M),this.json(t,H.error?500:200,{...W,voice:Et(O,Te),presence:q,text:Te,full:re,ui:$e??null,error:H.error,duration:H.duration});break}case"POST /mesh/task":{let h=await G(e);if(!h.peer||!h.message){this.json(t,400,{error:"Missing: peer, message"});return}let g=Uo(String(h.agent||h.peer),Lo(jo(e,h),this.registry),this.registry,this.syncWaits);if(g){this.json(t,409,{error:g});return}let w=new Fd(process.cwd()).get(String(h.peer));if(w){let A=await Ud(w,String(h.message));this.json(t,A.error?502:200,A.error?{error:A.error,host:w.name}:{content:A.content,host:w.name,agentId:w.agentId});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let v=this.operatorVouchFor(h.context,e),$=String(e.headers.accept||"");if(h.stream===!0||$.includes("text/event-stream")){t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-store, must-revalidate",Connection:"keep-alive","X-Accel-Buffering":"no"});let A=(j,q)=>{try{t.write(`event: ${j}
1142
+ ${Kp}`:""),context:hn({channel:"voice",sender:"Voice",chatId:`voice:${M}`}),intentRef:he}),W={agentId:M,voice:O},K=Ue(H.error);if(K){let X=K.pending;this.json(t,202,{...W,text:X>1?`I'm still on your last request, and ${X} more are waiting. Give me a moment.`:"I'm still working on your last request. Give me a moment.",full:null,ui:null,queued:!0,pending:X,duration:H.duration});return}let{cleanText:re,ui:$e}=Ee(H.content??""),Te=ln(re,this.config.voice.spokenMaxChars);H.error||this.voiceIntros.spoke(x,M),this.voiceTalk.presence.hide(M),this.json(t,H.error?500:200,{...W,voice:Et(O,Te),presence:q,text:Te,full:re,ui:$e??null,error:H.error,duration:H.duration});break}case"POST /mesh/task":{let h=await G(e);if(!h.peer||!h.message){this.json(t,400,{error:"Missing: peer, message"});return}let g=Uo(String(h.agent||h.peer),Lo(jo(e,h),this.registry),this.registry,this.syncWaits);if(g){this.json(t,409,{error:g});return}let w=new Ld(process.cwd()).get(String(h.peer));if(w){let A=await Fd(w,String(h.message));this.json(t,A.error?502:200,A.error?{error:A.error,host:w.name}:{content:A.content,host:w.name,agentId:w.agentId});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let v=this.operatorVouchFor(h.context,e),$=String(e.headers.accept||"");if(h.stream===!0||$.includes("text/event-stream")){t.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-store, must-revalidate",Connection:"keep-alive","X-Accel-Buffering":"no"});let A=(j,q)=>{try{t.write(`event: ${j}
1143
1143
  data: ${JSON.stringify(q)}
1144
1144
 
1145
1145
  `)}catch{}},O=setInterval(()=>{try{t.write(`: ping
1146
1146
 
1147
1147
  `)}catch{}},15e3);O.unref?.();let L=new AbortController;t.on("close",()=>{t.writableEnded||L.abort()});try{for await(let j of this.mesh.sendTaskStream(h.peer,h.message,h.agent,{context:h.context,signal:L.signal,vouchOwner:v}))A(j.event,j.data)}catch(j){A("error",{error:j?.message??String(j)})}finally{clearInterval(O);try{t.end()}catch{}}break}let x=h.context,E=typeof h.senderAgentId=="string"?h.senderAgentId:void 0;if(yf(h,!0)==="callback"){let A=this.delegationGate(e,h,{callee:h.agent,peer:h.peer,message:h.message,calleeContext:x});if(!("track"in A)){let O=tr(A);this.json(t,O.status,O.body);break}}if(h.async===!0){let A=x?.channel,O=x?.chatId;if(!A||!O){this.json(t,400,{error:"async requires context.channel and context.chatId \u2014 there is no route back otherwise"});return}let L=`mesh-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`;this.json(t,202,{accepted:!0,taskId:L,deliverTo:`${A}:${O}`,note:"result will be delivered to the originating chat when the peer finishes"});let j=h.peer,q=h.agent,he=this.mesh;(async()=>{let H=Date.now(),W;try{W=await he.sendTask(j,h.message,q,{vouchOwner:v,context:x,senderAgentId:E}),this.log(`[mesh/task async ${L}] ${j}/${q??"default"} finished in ${Date.now()-H}ms`)}catch(K){W=`Delegation to ${j}/${q??"default"} failed: ${K?.message??K}`,this.log(`[mesh/task async ${L}] failed: ${K?.message??K}`)}try{await this.router.sendOutbound({channel:A,chatId:O,text:W,agentId:x?.agentId??E,accountId:x?.accountId})}catch(K){this.log(`[mesh/task async ${L}] delivery failed: ${K?.message??K}`)}})();break}let M=await this.mesh.sendTask(h.peer,h.message,h.agent,{context:x,senderAgentId:E,vouchOwner:v});this.json(t,200,{response:M});break}case"POST /webrtc/signal/out":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let g=await G(e);if(!g.kind||!g.callId||!g.from||!g.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=await this.webrtc.handleOutgoing(g);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/signal":{if(!this.webrtc){this.json(t,404,{error:"WebRTC signaling not enabled"});return}let g=await G(e);if(!g.kind||!g.callId||!g.from||!g.to){this.json(t,400,{error:"Missing: kind, callId, from, to"});return}let w=this.webrtc.handleIncoming(g);this.json(t,w.ok?200:400,w);break}case"POST /webrtc/bot/invite":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled (channels.webrtc.bot.enabled=false)"});return}let h=await G(e),g=h.callId,w=h.target,v=h.agentId||this.config.channels.webrtc?.bot.defaultAgentId;if(!g||!w||!v){this.json(t,400,{error:"Missing: callId, target, agentId (or defaultAgentId in config)"});return}let $=await this.botManager.invite({callId:g,target:w,agentId:v});this.json(t,$.ok?200:500,$);break}case"GET /webrtc/bots":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active()});break}case"GET /webrtc/history":{if(!this.botManager){this.json(t,404,{error:"WebRTC bot not enabled"});return}this.json(t,200,{active:this.botManager.active(),history:this.botManager.history()});break}case"GET /webrtc/config":{let h=this.config.channels.webrtc;if(!h?.enabled){this.json(t,404,{error:"WebRTC signaling not enabled"});return}this.json(t,200,{localName:this.config.node.name,iceServers:[...h.stunServers.map(g=>({urls:g})),...h.turnServers],peers:this.mesh?.directory().map(g=>({name:g.peer,healthy:g.healthy}))||[],camera:h.camera,agents:this.registry.list().map(g=>({id:g.id,name:g.name}))});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(h=>{let g=this.config.agents[h.id]||{},w=typeof g.description=="string"&&g.description.trim()||LI(g.systemPrompt)||`Agent "${h.name}" (${h.tier})`,v=Array.isArray(g.mentions)?g.mentions.slice(0,4):[];return{id:h.id,name:h.name,description:w,tags:[h.tier,...v],color:ce(h.id,g).color}}),channels:this.router.getChannelNames(),githubLogins:this.github?.postingAccounts()??[],defaultInputModes:["text"],defaultOutputModes:["text"]});break;case"GET /wiki/agents":{let h=this.registry.getWikiHub();this.json(t,200,{nodeId:this.config.node.id,agents:h.summary()});break}case"GET /wiki/entries":{let h=this.registry.getWikiHub(),g=n.searchParams.get("agent")||void 0,w=n.searchParams.get("after")||void 0,v=g?h.getAgentEntries(g):h.getSharedStore().listEntries({after:w});this.json(t,200,{nodeId:this.config.node.id,count:v.length,entries:v.map($=>({id:$.id,date:$.date,agentId:$.agentId,source:$.source,sourceContext:$.sourceContext,content:$.content}))});break}case"GET /wiki/articles":{let h=this.registry.getWikiHub(),g=n.searchParams.get("agent");if(!g){this.json(t,400,{error:"?agent= required"});break}let v=h.getAgentWiki(g).rebuildIndex();this.json(t,200,{nodeId:this.config.node.id,agentId:g,articles:v.articles});break}case"GET /wiki/article":{let h=this.registry.getWikiHub(),g=n.searchParams.get("agent"),w=n.searchParams.get("path");if(!g||!w){this.json(t,400,{error:"?agent= and ?path= required"});break}let $=h.getAgentWiki(g).readArticle(w);if(!$){this.json(t,404,{error:"Article not found"});break}this.json(t,200,{nodeId:this.config.node.id,agentId:g,path:$.path,title:$.meta.title,tags:$.meta.tags,owner:$.meta.owner,created:$.meta.created,lastUpdated:$.meta.lastUpdated,sources:$.meta.sources,content:$.content});break}case"GET /graph/schema":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,schema:h.loadSchema()});break}case"GET /graph/nodes":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}this.json(t,200,{nodeId:this.config.node.id,...h.loadNodes()});break}case"GET /graph/classifications":{let h=this.registry.getGraphStore();if(!h){this.json(t,404,{error:"graph disabled on this node"});break}let g=n.searchParams.get("status")||"approved",w=Math.max(1,Math.min(1e3,parseInt(n.searchParams.get("limit")||"200",10)||200)),v=h.listByStatus(g,w);this.json(t,200,{nodeId:this.config.node.id,status:g,count:v.length,classifications:v});break}default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /routines \u2014 schedules + cron/hook workflows with staleness flags","GET /mesh","GET /wiki/agents","GET /wiki/entries[?agent=X&after=YYYY-MM-DD]","GET /wiki/articles?agent=X","GET /graph/schema","GET /graph/nodes","GET /graph/classifications[?status=approved|pending|rejected&limit=N]","POST /task { agent, message, context?, freshSession?: bool }","GET /agents/:id \u2014 resolved agent config (permission, tier, model, persistentProcess, toolUseRequired)","POST /agents/:id/selftest { message? } \u2014 canary probe; runs a fresh-session task and reports {ok, durationMs, tokens, billedModel}","GET /traces[?agentId=&channel=&chatId=&workflowRunId=&status=&since=&until=&limit=]","GET /traces/:taskId \u2014 full per-task execution trace (steps + tokens)","GET /voice/history[?agent=&limit=&before=] \u2014 past voice exchanges, bounded summaries","GET /voice/history/:id \u2014 one voice exchange in full; POST /voice/history/:id/replay","GET /api/processes \u2014 live persistent claude processes (JSON)","POST /api/processes/kill { agentId, channel, chatId, reason? }","GET /api/actions/builtin \u2014 list shipped built-in typed actions","POST /api/actions/builtin/:name \u2014 run a built-in with JSON body input","POST /mesh/task { peer, message }","POST /webhook/:agentId[/:source] \u2014 webhook callback","POST /reload \u2014 re-read agentx.json (hot-swaps crons)","GET /usage/plan \u2014 Claude plan windows, cold-dispatch counters, active holds","POST /usage/plan/lift \u2014 drop the active Claude plan holds","GET /daemon/restart \u2014 in-flight count, service manager, pending restart","POST /daemon/restart \u2014 restart when idle { timeoutMinutes?, onTimeout? }","POST /daemon/restart/cancel","GET /.well-known/agent-card.json","GET /call \u2014 browser UI for P2P A/V calls (requires channels.webrtc.enabled)","GET /webrtc/config \u2014 ICE servers + peer directory for the call page","GET /webrtc/events?callId=&as= \u2014 SSE stream of signaling events","POST /webrtc/signal/out \u2014 browser-originated signal, forwarded to remote peer","POST /webrtc/signal \u2014 remote-peer-originated signal, fanned out to local browser","POST /webrtc/bot/invite { callId, target, agentId } \u2014 spawn a transcribing bot peer for a call","GET /webrtc/bots \u2014 active bot sessions","POST /webrtc/camera/watch { callId, agentId } \u2014 an agent watches the phone camera share","GET /webrtc/camera/watch \u2014 agents watching a camera now","POST /webrtc/camera/watch/:id/look { note? } \u2014 ask the watching agent what it sees","POST /webrtc/camera/look { agentId } \u2014 from an agent's run: the newest frame as a PNG path"]})}}catch(i){this.json(t,500,{error:i.message})}}async handleOpenAICompat(e,t,n){let s=await G(e);await Ku(e,t,n,s,{execute:(i,o,a,c)=>this.registry.execute(i,o,a,c),agentIds:Object.keys(this.config.agents),cancel:(i,o,a,c)=>{let d=this.registry.list().find(l=>l.id===i)?.runningTasks.filter(l=>l.channel===o&&l.chatId===a)||[];for(let l of d)this.registry.cancelRunningTask(l.id,c)},log:i=>this.log(i)})}json(e,t,n){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(n,null,2))}resolveGitlabTokenForAgent(e){if(!e)return{token:this.config.channels.gitlab?.token,source:"global"};let t=(this.config.channels.gitlab?.agentMappings||[]).find(s=>s.agentId===e);if(t?.token)return{token:t.token,source:"agentMappings"};let n=op(this.config,e,"gitlab-user","tokenEnv");return n.status==="ok"&&n.value?{token:n.value,source:`integrations(${n.envVar})`}:this.config.channels.gitlab?.token?{token:this.config.channels.gitlab.token,source:"global"}:{token:void 0,source:n.status}}resolveTodayUsage(){let e=Sh();if(e==="json")return this.registry.getTodayUsage();let t=vh(this.db);return e==="sqlite"||Object.keys(t.agents).length>0?t:this.registry.getTodayUsage()}installAgentMemorySurface(){let e=parseInt(this.config.node.bind.split(":")[1]||"18800",10);for(let t of this.registry.list()){let n=t.workspace;if(!(!n||!It(n)))try{let s=Q(n,".claude","skills");jf(s,{recursive:!0});let i=Q(s,ap);if(!It(i))Yo(i,Qi(e)),this.log(` memory-skill: installed remember.md \u2192 ${t.id}`);else{let o=dp(rn(i,"utf-8"),e);o&&(Yo(i,o),this.log(` memory-skill: updated remember.md \u2192 ${t.id}`))}this.agentMemory.syncToWorkspace(t.id,n,this.config.session.memoryIndexMaxChars)}catch(s){this.log(` memory-skill: ${t.id} install failed \u2014 ${s?.message??s}`)}}}installAgentMcpConfig(){for(let[e,t]of Object.entries(this.config.agents)){let n=t.workspace;if(!n||!It(n))continue;let s=wc(La(t),this.config.requests.enabled?yc():null);try{switch(bc(n,s)){case"installed":this.log(` mcp: installed ${Object.keys(s).length} server(s) \u2192 ${e}`);break;case"updated":this.log(` mcp: updated .mcp.json (${Object.keys(s).length} server(s)) \u2192 ${e}`);break;case"removed":this.log(` mcp: removed managed .mcp.json (config now empty) \u2192 ${e}`);break;case"skipped-operator-owned":Object.keys(s).length>0&&this.log(` mcp: ${e} has operator-owned .mcp.json \u2014 skipping (delete file or marker to let agentx manage)`);break;case"noop":break}}catch(i){this.log(` mcp: ${e} install failed \u2014 ${i?.message??i}`)}}}workspaceFor(e){for(let t of this.registry.list())if(t.id===e)return t.workspace;return null}handleMemoryApi(e,t,n,s){return Fg(e,t,n,s,{mem:this.agentMemory,workspaceFor:i=>this.workspaceFor(i),runningTaskOwner:i=>this.registry.runningTaskOwner(i),indexMaxChars:()=>this.config.session.memoryIndexMaxChars})}async handleWorkflowEvent(e,t){if(!this.workflowDispatcher){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let n;try{n=await te(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=n?.payload??n,i=s?.event,o=s?.entityRef;if(!i?.id||!o?.backend||!o?.id){this.json(t,400,{error:"missing event or entityRef"});return}let a=n?.kind;try{if(a==="trigger"&&s.trigger){let m=typeof n?.fromPeer=="string"?n.fromPeer:"unknown";this.log(`[workflows/mesh] received trigger from "${m}" source="${s.trigger.source}" chat="${s.trigger.chat??"*"}"`);let f=await this.workflowDispatcher.dispatch({trigger:s.trigger,entityRef:o,event:i,fromRemote:{peer:m}});this.log(`[workflows/mesh] dispatched broadcast: matched=${f.claimed.length} ${f.claimed.length?`(${f.claimed.map(p=>p.id).join(", ")})`:"[none \u2014 no workflow with mesh.allowRemote matched]"}`),this.json(t,202,{ok:!0,mode:"trigger-broadcast",matched:f.claimed.map(p=>p.id)});return}let l=(s.workflowId?this.workflowStore?.get(s.workflowId):null)?.nodes.find(m=>m.type.startsWith("trigger."))?.config??{},u={source:String(l.source??"hook"),project:l.filter?.project,repo:l.filter?.repo,chat:l.filter?.chat,labels:l.filter?.labels};await this.workflowDispatcher.dispatch({trigger:u,entityRef:o,event:i}),this.json(t,202,{ok:!0})}catch(c){this.log(`[workflows] /workflow/event failed: ${c.message}`),this.json(t,500,{error:c.message})}}async relayPush(e,t){let n=e.toLowerCase(),s=this.mesh?.directory().find(a=>a.peer.toLowerCase()===n);if(!s)throw new Error(`push: channels.push.relayTo "${e}" is not a mesh peer of this node`);let i=await fetch(`${s.peerUrl}/channel/send`,{method:"POST",headers:{"Content-Type":"application/json",...this.mesh.authHeaders(s.peer)},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!i.ok)throw new Error(`push: ${s.peer} /channel/send -> ${i.status} ${(await i.text().catch(()=>"")).slice(0,200)}`);return(await i.json().catch(()=>({}))).messageId??void 0}async handleChannelSend(e,t){let n;try{n=await te(e)}catch(c){this.json(t,400,{error:"invalid JSON body",message:c.message});return}let s=String(n?.channel??""),i=String(n?.chatId??""),o=String(n?.text??"");if(!s||!i||!o){this.json(t,400,{error:"channel, chatId, and text are required"});return}if(!this.router.getChannel(s)){this.json(t,404,{error:`channel "${s}" not hosted on this node`});return}try{let c=await this.router.sendOutbound({channel:s,chatId:i,text:o,accountId:typeof n.accountId=="string"?n.accountId:void 0,parseMode:typeof n.parseMode=="string"?n.parseMode:void 0,replyTo:typeof n.replyTo=="string"?n.replyTo:void 0,buttons:Array.isArray(n.buttons)?n.buttons:void 0,agentId:typeof n.agentId=="string"?n.agentId:void 0,relayed:n.relayed===!0?!0:void 0},{recordInSession:!1});this.json(t,200,{ok:!0,messageId:c??null})}catch(c){this.log(`[mesh] /channel/send "${s}" failed: ${c.message}`),this.json(t,500,{error:c.message})}}async handleChannelChats(e,t,n={}){let s=new Set,i=[],o=[],a=(d,l)=>{let u=0;for(let m of d)!m.id||s.has(m.id)||(s.add(m.id),i.push({...m,source:l}),u++);u>0&&o.push(`${l}:${u}`)},c=this.router.getChannel(t);if(c?.listKnownChats)try{a(c.listKnownChats(),"local")}catch{}else if(c?.listChats)try{a(c.listChats().map(d=>({id:d.jid,name:d.name,kind:d.isGroup?"group":"dm"})),"local")}catch{}if(!n.localOnly&&this.mesh){let d=this.mesh.directory().filter(l=>l.healthy&&l.channels?.includes(t));await Promise.allSettled(d.map(async l=>{try{let u=await fetch(`${l.peerUrl}/channels/${encodeURIComponent(t)}/chats?local=1`,{headers:this.mesh.authHeaders(l.peer),signal:AbortSignal.timeout(5e3)});if(!u.ok)return;let m=await u.json();Array.isArray(m.chats)&&a(m.chats.map(f=>({id:f.id,name:f.name,kind:f.kind??"dm",accountId:f.accountId})),`mesh:${l.peer}`)}catch{}}))}this.json(e,200,{channel:t,source:o.join(", ")||"none",chats:i})}async handleWorkflowManualRun(e,t,n){if(!this.workflowDispatcher||!this.workflowStore){this.json(t,503,{error:"workflow engine not enabled on this node"});return}let s;try{s=await te(e)}catch{s={}}try{let i=await ip({get:o=>this.workflowStore.get(o),dispatchWorkflow:o=>this.workflowDispatcher.dispatchWorkflow(o)},n,s);this.json(t,i.status,i.body)}catch(i){this.log(`[workflows] manual run "${n}" failed: ${i.message}`),this.json(t,500,{error:i.message})}}},Qo=Zo;Ye(Qo,"MESH_PROTECTED_PATHS",new Set(["/task","/ask","/mesh/task","/mesh/inbox/send","/workflow/event","/workflow/transition","/channel/send","/webrtc/signal","/gitlab/react","/gitlab/send-note","/gitlab/log-time","/channel/edit-comment","/github/send-comment"]));function LI(r){if(typeof r!="string")return"";let e=r.trim();if(!e)return"";let t=e.match(/^[^.!?\n]+[.!?]?/),n=(t?t[0]:e).trim();return n.length>140?n.slice(0,137)+"\u2026":n}function te(r){return new Promise((e,t)=>{let n="";r.setEncoding("utf8"),r.on("data",s=>{n+=s}),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch(s){t(s)}}),r.on("error",t)})}function FI(r,e){let t=["model","workspace","tier","permissionMode","mcpServers"],n=new Set,s=new Set([...Object.keys(r),...Object.keys(e)]);for(let i of s){let o=r[i],a=e[i];if(!o||!a){n.add("add/remove");continue}for(let c of t)JSON.stringify(o[c])!==JSON.stringify(a[c])&&n.add(`${i}.${c}`)}return Array.from(n).slice(0,6)}async function G(r){return new Promise((e,t)=>{let n="";r.on("data",s=>n+=s.toString()),r.on("end",()=>{try{e(n?JSON.parse(n):{})}catch{e({})}}),r.on("error",t)})}Ff();function Dj(r){typeof r=="string"&&(an.error(r),process.exit(1)),r instanceof Error&&(an.error(r.message),process.exit(1)),an.error("Something went wrong. Please try again."),process.exit(1)}export{YI as a,Yr as b,We as c,Pt as d,Ot as e,Xe as f,Gn as g,fu as h,uh as i,Eb as j,Cb as k,fh as l,Me as m,gt as n,bh as o,pt as p,LA as q,FA as r,Vk as s,qi as t,TE as u,xE as v,AE as w,Xg as x,$v as y,ME as z,_E as A,Bt as B,Is as C,Wt as D,$p as E,yS as F,YC as G,As as H,go as I,po as J,Ms as K,ce as L,um as M,Os as N,r0 as O,Im as P,i0 as Q,Am as R,js as S,Qt as T,Gs as U,Bs as V,_m as W,Ro as X,De as Y,we as Z,Gm as _,Hm as $,Bm as aa,Wm as ba,cr as ca,Rf as da,Xo as ea,Cf as fa,xI as ga,gO as ha,Qo as ia,Dj as ja};
1148
- //# sourceMappingURL=chunk-KDD6FPQ6.js.map
1148
+ //# sourceMappingURL=chunk-K24MYJFP.js.map