agentix-cli 0.117.0 → 0.118.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.
- package/README.md +5 -5
- package/dist/{App-UQP7UQYV.js → App-XMSNIAU6.js} +2 -2
- package/dist/{ChatApp-VGSP5O6N.js → ChatApp-BFYTIQF3.js} +2 -2
- package/dist/{agent-MO27U4Y7.js → agent-E6W5VBYH.js} +2 -2
- package/dist/{board-dashboard-CSS7XMIZ.js → board-dashboard-WDO6Z24C.js} +257 -143
- package/dist/board-dashboard-WDO6Z24C.js.map +1 -0
- package/dist/chunk-23SQSUBI.js +3 -0
- package/dist/chunk-23SQSUBI.js.map +1 -0
- package/dist/{chunk-VRXJW6JJ.js → chunk-2G227TF3.js} +2 -2
- package/dist/{chunk-HVZVFCJX.js → chunk-4PQREYBU.js} +2 -2
- package/dist/{chunk-4FU4BFCH.js → chunk-5NTWGUSJ.js} +3 -3
- package/dist/chunk-5NTWGUSJ.js.map +1 -0
- package/dist/{chunk-2WK5A3UV.js → chunk-5PR6DZYW.js} +3 -3
- package/dist/chunk-5PR6DZYW.js.map +1 -0
- package/dist/{chunk-4ELAUGOP.js → chunk-5UFIHT66.js} +2 -2
- package/dist/{chunk-CUZTLQH2.js → chunk-6PC4EZ4P.js} +2 -2
- package/dist/chunk-AD4QZZVN.js +8 -0
- package/dist/{failure-candidates-PBPF45GN.js.map → chunk-AD4QZZVN.js.map} +1 -1
- package/dist/chunk-B6OXEIOF.js +126 -0
- package/dist/chunk-B6OXEIOF.js.map +1 -0
- package/dist/chunk-BDJWN3PL.js +4 -0
- package/dist/chunk-BDJWN3PL.js.map +1 -0
- package/dist/{chunk-OJ7KM2UO.js → chunk-FSXWNVGL.js} +2 -2
- package/dist/{chunk-746KHKT4.js → chunk-FTZCNID3.js} +2 -2
- package/dist/{chunk-PFK3QO6S.js → chunk-GJKYOEDE.js} +2 -2
- package/dist/{chunk-BQ2HJ7TS.js → chunk-HK7TU5NX.js} +2 -2
- package/dist/{chunk-FJI5GRBH.js → chunk-IMLLHT7U.js} +3 -3
- package/dist/chunk-IMLLHT7U.js.map +1 -0
- package/dist/chunk-IOYRRGK7.js +2 -0
- package/dist/chunk-IOYRRGK7.js.map +1 -0
- package/dist/{chunk-T2VDHVYW.js → chunk-IVCFXLAR.js} +2 -2
- package/dist/{chunk-W7WNRPNQ.js → chunk-NDPU6AX2.js} +2 -2
- package/dist/{chunk-45GOH6F7.js → chunk-NG677JHW.js} +8 -8
- package/dist/chunk-NG677JHW.js.map +1 -0
- package/dist/{chunk-MSP25HE5.js → chunk-PVQPXZHE.js} +5 -5
- package/dist/{chunk-5PPMPCHG.js → chunk-RJBRYUKU.js} +2 -2
- package/dist/{chunk-QLWGLRT5.js → chunk-TJ7IUHC7.js} +2 -2
- package/dist/{chunk-J2YLOGNN.js → chunk-U46G24CD.js} +2 -2
- package/dist/{chunk-IZMXAXW3.js → chunk-UQ3MWTGF.js} +196 -197
- package/dist/chunk-UQ3MWTGF.js.map +1 -0
- package/dist/chunk-WCXXXAHV.js +3 -0
- package/dist/{chunk-DMHQIACQ.js.map → chunk-WCXXXAHV.js.map} +1 -1
- package/dist/{chunk-45YETJY4.js → chunk-XGOBZCYC.js} +2 -2
- package/dist/{chunk-CKQ2YDFP.js → chunk-ZDWE47LM.js} +8 -8
- package/dist/chunk-ZDWE47LM.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-5UMNDY7Z.js → client-TSYZXEH7.js} +2 -2
- package/dist/{config-O44DOHFW.js → config-QAE3LNFQ.js} +2 -2
- package/dist/config-mutator-WRQ7MFQL.js +2 -0
- package/dist/{doctor-NKPH74F7.js → doctor-PVLVKLRA.js} +2 -2
- package/dist/failure-candidates-JNGUVBDG.js +2 -0
- package/dist/{grants-BRAVOGBP.js → grants-V2ZNLWSJ.js} +2 -2
- package/dist/index.d.ts +69 -2
- package/dist/index.js +1 -1
- package/dist/program-GHQQAEVB.js +721 -0
- package/dist/program-GHQQAEVB.js.map +1 -0
- package/dist/{promote-ZRNVPWTD.js → promote-IRBBEXGG.js} +2 -2
- package/dist/{push-bridge-VPTQNM43.js → push-bridge-325SXDGN.js} +2 -2
- package/dist/{query-HURONGKA.js → query-NAU7J34H.js} +2 -2
- package/dist/{registry-AYGFAKTC.js → registry-I5PXGCO6.js} +2 -2
- package/dist/{request-planner-ZZRSOBQZ.js → request-planner-CRG3OGGG.js} +2 -2
- package/dist/{review-candidates-KHH47PK7.js → review-candidates-HAP7P6SH.js} +2 -2
- package/dist/{routing-GUBKKWPT.js → routing-G33LLOTF.js} +2 -2
- package/dist/schedule-tool-IP7ZCQKI.js +2 -0
- package/dist/scheduler-QXLPYSNJ.js +2 -0
- package/dist/{seat-CVTTTE5V.js → seat-IJN7NETF.js} +2 -2
- package/dist/{select-OUTM6OBC.js → select-D7AZ2XZF.js} +2 -2
- package/dist/{set-enabled-2QKQRVUN.js → set-enabled-5YSDIQXU.js} +2 -2
- package/dist/{surface-usage-HCJTUS6Z.js → surface-usage-WSY4SHHL.js} +2 -2
- package/dist/{tool-XY7QGHLV.js → tool-GQIQWHWB.js} +2 -2
- package/dist/{tool-OFXHMLE5.js → tool-XADSW6NL.js} +2 -2
- package/dist/wiki-PPX3HYXW.js +2 -0
- package/dist/wiki-PPX3HYXW.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-CSS7XMIZ.js.map +0 -1
- package/dist/chunk-2WK5A3UV.js.map +0 -1
- package/dist/chunk-45GOH6F7.js.map +0 -1
- package/dist/chunk-4FU4BFCH.js.map +0 -1
- package/dist/chunk-CKQ2YDFP.js.map +0 -1
- package/dist/chunk-DMHQIACQ.js +0 -3
- package/dist/chunk-FJI5GRBH.js.map +0 -1
- package/dist/chunk-HYGMWCUU.js +0 -126
- package/dist/chunk-HYGMWCUU.js.map +0 -1
- package/dist/chunk-IZMXAXW3.js.map +0 -1
- package/dist/chunk-JIT5GPTX.js +0 -4
- package/dist/chunk-JIT5GPTX.js.map +0 -1
- package/dist/chunk-PMQ47IPT.js +0 -2
- package/dist/chunk-PMQ47IPT.js.map +0 -1
- package/dist/chunk-VEHTVYP6.js +0 -2
- package/dist/chunk-VEHTVYP6.js.map +0 -1
- package/dist/config-mutator-PRLY2TCE.js +0 -2
- package/dist/failure-candidates-PBPF45GN.js +0 -8
- package/dist/program-RHIJYCEJ.js +0 -703
- package/dist/program-RHIJYCEJ.js.map +0 -1
- package/dist/schedule-tool-VH77T3N3.js +0 -2
- package/dist/scheduler-SZ4YYXJE.js +0 -2
- package/dist/wiki-46GMWX34.js +0 -2
- /package/dist/{App-UQP7UQYV.js.map → App-XMSNIAU6.js.map} +0 -0
- /package/dist/{ChatApp-VGSP5O6N.js.map → ChatApp-BFYTIQF3.js.map} +0 -0
- /package/dist/{agent-MO27U4Y7.js.map → agent-E6W5VBYH.js.map} +0 -0
- /package/dist/{chunk-VRXJW6JJ.js.map → chunk-2G227TF3.js.map} +0 -0
- /package/dist/{chunk-HVZVFCJX.js.map → chunk-4PQREYBU.js.map} +0 -0
- /package/dist/{chunk-4ELAUGOP.js.map → chunk-5UFIHT66.js.map} +0 -0
- /package/dist/{chunk-CUZTLQH2.js.map → chunk-6PC4EZ4P.js.map} +0 -0
- /package/dist/{chunk-OJ7KM2UO.js.map → chunk-FSXWNVGL.js.map} +0 -0
- /package/dist/{chunk-746KHKT4.js.map → chunk-FTZCNID3.js.map} +0 -0
- /package/dist/{chunk-PFK3QO6S.js.map → chunk-GJKYOEDE.js.map} +0 -0
- /package/dist/{chunk-BQ2HJ7TS.js.map → chunk-HK7TU5NX.js.map} +0 -0
- /package/dist/{chunk-T2VDHVYW.js.map → chunk-IVCFXLAR.js.map} +0 -0
- /package/dist/{chunk-W7WNRPNQ.js.map → chunk-NDPU6AX2.js.map} +0 -0
- /package/dist/{chunk-MSP25HE5.js.map → chunk-PVQPXZHE.js.map} +0 -0
- /package/dist/{chunk-5PPMPCHG.js.map → chunk-RJBRYUKU.js.map} +0 -0
- /package/dist/{chunk-QLWGLRT5.js.map → chunk-TJ7IUHC7.js.map} +0 -0
- /package/dist/{chunk-J2YLOGNN.js.map → chunk-U46G24CD.js.map} +0 -0
- /package/dist/{chunk-45YETJY4.js.map → chunk-XGOBZCYC.js.map} +0 -0
- /package/dist/{client-5UMNDY7Z.js.map → client-TSYZXEH7.js.map} +0 -0
- /package/dist/{config-O44DOHFW.js.map → config-QAE3LNFQ.js.map} +0 -0
- /package/dist/{config-mutator-PRLY2TCE.js.map → config-mutator-WRQ7MFQL.js.map} +0 -0
- /package/dist/{doctor-NKPH74F7.js.map → doctor-PVLVKLRA.js.map} +0 -0
- /package/dist/{grants-BRAVOGBP.js.map → failure-candidates-JNGUVBDG.js.map} +0 -0
- /package/dist/{promote-ZRNVPWTD.js.map → grants-V2ZNLWSJ.js.map} +0 -0
- /package/dist/{push-bridge-VPTQNM43.js.map → promote-IRBBEXGG.js.map} +0 -0
- /package/dist/{query-HURONGKA.js.map → push-bridge-325SXDGN.js.map} +0 -0
- /package/dist/{registry-AYGFAKTC.js.map → query-NAU7J34H.js.map} +0 -0
- /package/dist/{routing-GUBKKWPT.js.map → registry-I5PXGCO6.js.map} +0 -0
- /package/dist/{request-planner-ZZRSOBQZ.js.map → request-planner-CRG3OGGG.js.map} +0 -0
- /package/dist/{review-candidates-KHH47PK7.js.map → review-candidates-HAP7P6SH.js.map} +0 -0
- /package/dist/{schedule-tool-VH77T3N3.js.map → routing-G33LLOTF.js.map} +0 -0
- /package/dist/{scheduler-SZ4YYXJE.js.map → schedule-tool-IP7ZCQKI.js.map} +0 -0
- /package/dist/{seat-CVTTTE5V.js.map → scheduler-QXLPYSNJ.js.map} +0 -0
- /package/dist/{surface-usage-HCJTUS6Z.js.map → seat-IJN7NETF.js.map} +0 -0
- /package/dist/{select-OUTM6OBC.js.map → select-D7AZ2XZF.js.map} +0 -0
- /package/dist/{set-enabled-2QKQRVUN.js.map → set-enabled-5YSDIQXU.js.map} +0 -0
- /package/dist/{wiki-46GMWX34.js.map → surface-usage-WSY4SHHL.js.map} +0 -0
- /package/dist/{tool-XY7QGHLV.js.map → tool-GQIQWHWB.js.map} +0 -0
- /package/dist/{tool-OFXHMLE5.js.map → tool-XADSW6NL.js.map} +0 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{q as d}from"./chunk-B6OXEIOF.js";import{b as i,c as u,d as l,e as c}from"./chunk-4PQREYBU.js";import f from"cronstrue";var p=Intl.DateTimeFormat().resolvedOptions().timeZone,m=600,E='Try: "every morning at 9", "weekdays at 6pm", "every 15 minutes", "every monday at 10am", "1st of every month at noon", "daily at 9:30am", "every hour"',g=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function w(e){return g.test(e)}function x(e){try{return new Intl.DateTimeFormat("en-US",{timeZone:e}),!0}catch{return!1}}function $(e){return e?e.split(",").map(r=>r.trim().toLowerCase()).filter(r=>r==="log"||r==="notify"||r==="disable"):["log"]}function S(e){let r=[...e.onError??["log"]];e.notify&&!r.includes("notify")&&r.push("notify");let t={enabled:e.enabled??!0,schedule:e.parsed.cron,timezone:e.timezone||p,agent:e.agent,prompt:e.prompt,timeout:e.timeout??m,onError:r};return e.model&&(t.model=e.model),e.notify&&(t.notify=e.notify),e.notify&&e.deliverResult===!1&&(t.deliverResult=!1),e.createdBy&&(t.createdBy=e.createdBy),e.approval&&(t.approval=e.approval),t}function P(e){try{return f.toString(e,{use24HourTimeFormat:!1})}catch{return e}}function T(e,r,t=new Date){try{return d(e,t,r)}catch{return null}}function A(e,r){if(!e)return"unknown (no match within a year)";try{return`${new Intl.DateTimeFormat("en-GB",{timeZone:r,weekday:"short",day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(e)} (${r})`}catch{return e.toISOString()}}function h(e){return e?.approval?.action==="create"}async function D(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(delete a.approval,a.enabled=!0,t=`${e} approved and enabled (requested by ${s.requestedBy})`):(c(n,`crons.${e}`),t=`${e} deletion approved; job removed (requested by ${s.requestedBy})`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function I(e,r={}){let t="",o=await i(n=>{let a=l(n,`crons.${e}`);if(!a)throw new Error(`cron "${e}" not found`);let s=a.approval;if(!s)throw new Error(`cron "${e}" has no pending request`);s.action==="create"?(c(n,`crons.${e}`),t=`${e} rejected; pending job removed`):(delete a.approval,t=`${e} deletion rejected; job kept`)},{configPath:r.configPath,reload:r.reload});return o.success?{success:!0,message:t,result:o}:{success:!1,message:o.error||"failed",result:o}}async function O(e,r,t={}){return i(o=>{let n=l(o,`crons.${e}`);if(!n)throw new Error(`cron "${e}" not found`);if(r&&h(n))throw new Error(`cron "${e}" is awaiting approval; run \`agentx schedule approve ${e}\``);u(o,`crons.${e}.enabled`,r)},{configPath:t.configPath,reload:t.reload})}export{p as a,E as b,w as c,x as d,$ as e,S as f,P as g,T as h,A as i,h as j,D as k,I as l,O as m};
|
|
2
|
+
//# sourceMappingURL=chunk-IOYRRGK7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crons/schedule-ops.ts"],"sourcesContent":["import cronstrue from \"cronstrue\"\nimport { applyConfigMutation, getAtPath, setAtPath, unsetAtPath, type MutationResult } from \"@/daemon/config-mutator\"\nimport type { NlCronResult } from \"@/utils/nl-cron\"\nimport { getNextCronDate } from \"./scheduler\"\n\n// --- Shared schedule operations ---\n//\n// One code path for everything that writes a `crons.<id>` entry from a\n// natural-language schedule: the `agentx schedule` CLI and the agent-facing\n// `agentx_schedule` MCP tool both build jobs here, so the two can never\n// drift into writing different shapes.\n//\n// Also owns the operator side of the approval flow (approve / reject), which\n// only the CLI exposes. Agents can request; they cannot approve.\n\nexport type OnErrorValue = \"log\" | \"notify\" | \"disable\"\n\nexport interface NotifyTarget {\n channel: string\n chatId: string\n accountId?: string\n}\n\nexport interface ScheduleApproval {\n action: \"create\" | \"delete\"\n requestedBy: string\n requestedAt: string\n}\n\n/** Default timezone for schedules created without one: this machine's, the\n * same as the CLI's `--timezone` default. */\nexport const DEFAULT_SCHEDULE_TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone\nexport const DEFAULT_SCHEDULE_TIMEOUT = 600\n\nexport const SUPPORTED_PHRASES_HINT =\n 'Try: \"every morning at 9\", \"weekdays at 6pm\", \"every 15 minutes\", \"every monday at 10am\", ' +\n '\"1st of every month at noon\", \"daily at 9:30am\", \"every hour\"'\n\n/** Cron ids become a dot-path segment (`crons.<id>`), so dots and other\n * separators are refused rather than silently nesting the config. */\nconst SCHEDULE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/\n\nexport function isValidScheduleId(id: string): boolean {\n return SCHEDULE_ID_RE.test(id)\n}\n\nexport function isValidTimezone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: tz })\n return true\n } catch {\n return false\n }\n}\n\nexport function parseOnError(flag: string | undefined): OnErrorValue[] {\n if (!flag) return [\"log\"]\n return flag\n .split(\",\")\n .map((s) => s.trim().toLowerCase())\n .filter((s): s is OnErrorValue => s === \"log\" || s === \"notify\" || s === \"disable\")\n}\n\nexport interface ScheduleJobInput {\n parsed: NlCronResult\n agent: string\n prompt: string\n timezone?: string\n timeout?: number\n model?: string\n notify?: NotifyTarget\n /** False keeps `notify` for failure alerts only. Default: each\n * successful run's answer is sent there too. */\n deliverResult?: boolean\n onError?: OnErrorValue[]\n enabled?: boolean\n createdBy?: string\n approval?: ScheduleApproval\n}\n\n/** Build the `crons.<id>` object. A notify target implies the \"notify\"\n * error mode, exactly as the CLI always did. */\nexport function buildScheduleJob(input: ScheduleJobInput): Record<string, unknown> {\n const onError = [...(input.onError ?? [\"log\"])]\n if (input.notify && !onError.includes(\"notify\")) onError.push(\"notify\")\n\n const job: Record<string, unknown> = {\n enabled: input.enabled ?? true,\n schedule: input.parsed.cron,\n timezone: input.timezone || DEFAULT_SCHEDULE_TIMEZONE,\n agent: input.agent,\n prompt: input.prompt,\n timeout: input.timeout ?? DEFAULT_SCHEDULE_TIMEOUT,\n onError,\n }\n if (input.model) job.model = input.model\n if (input.notify) job.notify = input.notify\n if (input.notify && input.deliverResult === false) job.deliverResult = false\n if (input.createdBy) job.createdBy = input.createdBy\n if (input.approval) job.approval = input.approval\n return job\n}\n\nexport function humanizeCron(cron: string): string {\n try {\n return cronstrue.toString(cron, { use24HourTimeFormat: false })\n } catch {\n return cron\n }\n}\n\nexport function nextFireTime(cron: string, timezone: string, now: Date = new Date()): Date | null {\n try {\n return getNextCronDate(cron, now, timezone)\n } catch {\n return null\n }\n}\n\n/** \"Mon, 28 Sep 2026, 10:00 (<tz>)\" — the wall-clock time where the job\n * runs, which is what an operator reading an approval request cares about. */\nexport function formatFireTime(d: Date | null, timezone: string): string {\n if (!d) return \"unknown (no match within a year)\"\n try {\n const local = new Intl.DateTimeFormat(\"en-GB\", {\n timeZone: timezone,\n weekday: \"short\",\n day: \"2-digit\",\n month: \"short\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n }).format(d)\n return `${local} (${timezone})`\n } catch {\n return d.toISOString()\n }\n}\n\nexport function isPendingCreate(job: any): boolean {\n return job?.approval?.action === \"create\"\n}\n\n// ── Operator approval ────────────────────────────────────────────────\n\nexport interface ApprovalOutcome {\n success: boolean\n /** What happened, for the CLI to print. */\n message: string\n result?: MutationResult\n}\n\n/**\n * Apply a pending agent request. `create` → enable and clear the marker;\n * `delete` → remove the job. Hot-reloads the daemon through the same\n * mutator the CLI uses.\n */\nexport async function approveSchedule(\n id: string,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<ApprovalOutcome> {\n let message = \"\"\n const result = await applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n const approval = job.approval as ScheduleApproval | undefined\n if (!approval) throw new Error(`cron \"${id}\" has no pending request`)\n if (approval.action === \"create\") {\n delete job.approval\n job.enabled = true\n message = `${id} approved and enabled (requested by ${approval.requestedBy})`\n } else {\n unsetAtPath(cfg, `crons.${id}`)\n message = `${id} deletion approved; job removed (requested by ${approval.requestedBy})`\n }\n }, { configPath: opts.configPath, reload: opts.reload })\n if (!result.success) return { success: false, message: result.error || \"failed\", result }\n return { success: true, message, result }\n}\n\n/** Refuse a pending request. `create` → drop the never-run job; `delete` →\n * keep the job exactly as it was and clear the marker. */\nexport async function rejectSchedule(\n id: string,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<ApprovalOutcome> {\n let message = \"\"\n const result = await applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n const approval = job.approval as ScheduleApproval | undefined\n if (!approval) throw new Error(`cron \"${id}\" has no pending request`)\n if (approval.action === \"create\") {\n unsetAtPath(cfg, `crons.${id}`)\n message = `${id} rejected; pending job removed`\n } else {\n delete job.approval\n message = `${id} deletion rejected; job kept`\n }\n }, { configPath: opts.configPath, reload: opts.reload })\n if (!result.success) return { success: false, message: result.error || \"failed\", result }\n return { success: true, message, result }\n}\n\n/** Enable/disable, refusing to enable a job still awaiting approval. */\nexport async function setScheduleEnabled(\n id: string,\n enabled: boolean,\n opts: { configPath?: string; reload?: boolean } = {},\n): Promise<MutationResult> {\n return applyConfigMutation((cfg) => {\n const job: any = getAtPath(cfg, `crons.${id}`)\n if (!job) throw new Error(`cron \"${id}\" not found`)\n if (enabled && isPendingCreate(job)) {\n throw new Error(`cron \"${id}\" is awaiting approval; run \\`agentx schedule approve ${id}\\``)\n }\n setAtPath(cfg, `crons.${id}.enabled`, enabled)\n }, { configPath: opts.configPath, reload: opts.reload })\n}\n"],"mappings":"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","names":["cronstrue","DEFAULT_SCHEDULE_TIMEZONE","DEFAULT_SCHEDULE_TIMEOUT","SUPPORTED_PHRASES_HINT","SCHEDULE_ID_RE","isValidScheduleId","id","isValidTimezone","tz","parseOnError","flag","s","buildScheduleJob","input","onError","job","humanizeCron","cron","cronstrue","nextFireTime","timezone","now","getNextCronDate","formatFireTime","d","isPendingCreate","approveSchedule","opts","message","result","applyConfigMutation","cfg","getAtPath","approval","unsetAtPath","rejectSchedule","setScheduleEnabled","enabled","setAtPath"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-
|
|
1
|
+
import{a as j,b as O,c as T,d as D,e as _,j as N}from"./chunk-FTZCNID3.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{y as C,z as I}from"./chunk-NDPU6AX2.js";import{b as v,c as W}from"./chunk-QOYAX2FT.js";import{readFileSync as Y,existsSync as B}from"fs";I();import{resolve as x}from"path";import{execSync as L}from"child_process";async function nt(n,a,o,t={}){let u=t.selectorModel??"haiku",g=t.synthModel??"sonnet",l=t.maxCandidates??3,r=t.maxHops??2,s=t.maxArticles??8,h=t.timeoutMs??6e4,p=t.log??console.error.bind(console,"[wiki-query]"),m=t.messagePath?.length?t.messagePath:void 0,w=t.graphWeight??$,i=x(a.baseDir,"_index.md");if(!B(i))return A("no-catalog",n,"No _index.md found \u2014 run `agentx wiki status` to rebuild.");let e=Y(i,"utf-8"),d=Date.now(),f=[],y="";try{let c=await G(n,a,o,l,m,w);c?(f=c,y=`[wiki-rerank seat] ${c.map(k=>k.title).join(" | ")}`):(y=await Q(q(n,e,l,m),u,h),f=K(y))}catch(c){return p("selector failed:",c?.message),{...A("error",n,`Selector: ${c?.message||"unknown"}`),trace:{selectorMs:Date.now()-d,synthesisMs:0,selectorOutput:y}}}let S=Date.now()-d;if(f.length===0)return{...A("no-candidates",n,"Selector returned no candidates."),trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let b=F(f,a,o,r,s);if(b.length===0)return{...A("no-candidates",n,"Candidates did not resolve to readable articles."),candidates:f,trace:{selectorMs:S,synthesisMs:0,selectorOutput:y}};let M=Date.now(),P="";try{P=await Q(J(n,b),g,h*2)}catch(c){return p("synthesis failed:",c?.message),{...A("error",n,`Synthesis: ${c?.message||"unknown"}`),candidates:f,walked:b.map(k=>({title:k.meta.title,path:k.path,type:k.meta.type,hop:k.hop??0})),trace:{selectorMs:S,synthesisMs:Date.now()-M,selectorOutput:y}}}let E=Date.now()-M;return{answer:P.trim(),citations:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type})),candidates:f,walked:b.map(c=>({title:c.meta.title,path:c.path,type:c.meta.type,hop:c.hop??0})),status:"ok",trace:{selectorMs:S,synthesisMs:E,selectorOutput:y}}}function A(n,a,o){return{answer:"",citations:[],candidates:[],walked:[],status:n,error:o}}function F(n,a,o,t,u){let g=new Map;for(let s of a.listArticles(o||""))g.set(s.meta.title.toLowerCase(),s.path);let l=new Map,r=[];for(let s of n)l.has(s.path)||r.push({path:s.path,hop:0});for(;r.length&&l.size<u;){let s=r.shift();if(l.has(s.path)||s.hop>t)continue;let h=o?a.readArticleAs(s.path,o):a.readArticle(s.path);if(h&&(l.set(s.path,{...h,hop:s.hop}),!(s.hop>=t)))for(let p of h.meta.related||[]){let m=g.get(p.toLowerCase());m&&!l.has(m)&&r.push({path:m,hop:s.hop+1})}}return Array.from(l.values())}async function G(n,a,o,t,u,g=$){try{let r=(a.rebuildIndex().articles??[]).filter(i=>i.path&&!i.path.includes("/_versions/"));if(r.length<2)return null;let h=H(n,r,u,g).slice(0,O).map(i=>({id:`k${i}`,title:r[i].title||r[i].path,tags:r[i].tags,excerpt:[r[i].type?`type: ${r[i].type}`:"",(r[i].related??[]).length?`related: ${(r[i].related??[]).join(", ")}`:"",(r[i].graphPath??[]).length?`graph: ${(r[i].graphPath??[]).join(" \u203A ")}`:""].filter(Boolean).join(" \xB7 ")})),p=await C(j,T({query:n,candidates:h,excerptChars:300}),D(h),{features:{agent:o??"unknown",stage:"catalog-selector"}});if(!p||p.mode!=="active")return null;let w=_(p.answers,h).ranked.slice(0,t).map(i=>r[Number(i.slice(1))]).filter(Boolean).map(i=>({title:i.title,path:i.path}));return w.length>0?w:null}catch{return null}}var $=.6;function H(n,a,o,t=$){let u=a.map(e=>[e.title,(e.tags??[]).join(" "),(e.related??[]).join(" ")].join(" ")),g=W(n,v(u)),l=g.reduce((e,d)=>Math.max(e,d.score),0),r=new Map(g.map(e=>[e.docIndex,l>0?e.score/l:0])),s=!!o?.length,h=e=>s&&e.graphPath?.length?N(o,e.graphPath):0,p=(e,d)=>d.score-e.score||e.i-d.i,m=a.map((e,d)=>({i:d,score:(r.get(d)??0)*(1+t*h(e))})).filter(e=>r.has(e.i)).sort(p),w=a.map((e,d)=>({i:d,score:h(e)})).filter(e=>!r.has(e.i)&&e.score>0).sort(p),i=[...m,...w].map(e=>e.i);for(let e=0;e<a.length;e++)i.includes(e)||i.push(e);return i}function q(n,a,o,t){let u=t?.length?`
|
|
2
2
|
## Intent
|
|
3
3
|
|
|
4
4
|
The request was classified under the intent-graph path "${t.join(" \u203A ")}". Prefer articles filed under the same branch when their titles are equally plausible.
|
|
@@ -46,4 +46,4 @@ ${o}
|
|
|
46
46
|
Answer the question in 2\u20136 sentences. Cite articles by their title in square brackets like [Article Title]. If the articles do not answer the question, say so plainly (do not invent). Prefer concrete facts over hedging.
|
|
47
47
|
|
|
48
48
|
Output ONLY the answer \u2014 no preamble, no "here is my answer:", no markdown fencing.`}function K(n){let a=n.match(/\[[\s\S]*?\]/);if(!a)return[];try{let o=JSON.parse(a[0]);return Array.isArray(o)?o.filter(t=>t&&typeof t.title=="string"&&typeof t.path=="string").map(t=>({title:t.title,path:t.path})):[]}catch{return[]}}async function Q(n,a,o){let{writeFileSync:t,mkdirSync:u,rmSync:g}=await import("fs"),{tmpdir:l}=await import("os"),r=x(l(),`agentx-wiki-query-${process.pid}`);u(r,{recursive:!0});let s=x(r,`prompt-${Date.now()}.txt`);t(s,n);try{let h=`cat '${s}' | claude -p - --output-format json --max-turns 1 --model ${a} --disallowedTools "Bash Read Write Edit Glob Grep Agent WebSearch WebFetch NotebookEdit"`,p=L(h,{env:R({...process.env}),encoding:"utf-8",timeout:o,maxBuffer:4*1024*1024});try{let m=JSON.parse(p);return String(m.result||m.content||"")}catch{return p}}finally{try{g(s,{force:!0})}catch{}}}export{nt as a,$ as b,H as c};
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-IVCFXLAR.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-
|
|
1
|
+
import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";import{a as Te,b as ht}from"./chunk-FX3D7YON.js";import{a as ne,b as et}from"./chunk-FCPTN6NF.js";import{o as we,p as Ze}from"./chunk-2PJKGZWP.js";import{la as tt,ma as nt}from"./chunk-IMLLHT7U.js";import{a as it,b as at,c as ct,d as ut,e as lt,f as dt,g as pt,h as mt,i as bt,j as ft,k as gt,l as yt}from"./chunk-RGDKHYY2.js";import{a as E,b as We,c as he}from"./chunk-QIJLFPWE.js";function R(e,t){$.set(e,t),X.delete(e)}function D(e){let t=X.get(e);if(t)return t;let r=$.get(e);if(!r){let o=Ee();throw new Error(`unknown decision backend "${e}"`+(o.length>0?` \u2014 registered: ${o.join(", ")}`:" \u2014 none registered"))}let n=r();return X.set(e,n),n}function Ee(){return[...$.keys()].sort()}function wt(){$.clear(),X.clear()}var $,X,C=E(()=>{"use strict";$=new Map,X=new Map});import Tt from"better-sqlite3";import{createHash as Et}from"crypto";import{mkdirSync as kt}from"fs";import{dirname as St,resolve as xt}from"path";function Q(e){if(e.type==="noul"){let r=e.noul,n={yes:r,no:1-r},o=r>=.5?"yes":"no",s=Math.abs(r-.5)*2;return{predicted:o,confidence:s,probabilities:n,topLabel:o,topProb:Math.max(r,1-r),expectedScore:null,pMax:Math.max(r,1-r),negEntropy:s}}if(e.type==="choice")return{predicted:e.choice,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:e.choice,topProb:e.probabilities[e.choice]??0,expectedScore:null,pMax:e.pMax,negEntropy:e.negEntropy};let t=String(Math.round(e.score));return{predicted:t,confidence:e.confidence,probabilities:{...e.probabilities},topLabel:t,topProb:e.probabilities[t]??0,expectedScore:e.score,pMax:e.pMax,negEntropy:e.negEntropy}}function At(e){if(typeof e!="string"||e.length===0)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Rt(e){e.exec("CREATE TABLE IF NOT EXISTS schema_version (v INTEGER PRIMARY KEY);");let t=e.prepare("SELECT MAX(v) AS v FROM schema_version").get().v??0;t<1&&vt(e),t<2&&Ot(e),t<3&&_t(e)}function _t(e){e.exec(`
|
|
2
2
|
ALTER TABLE decision_calls ADD COLUMN features_json TEXT;
|
|
3
3
|
INSERT INTO schema_version (v) VALUES (3);
|
|
4
4
|
`)}function Ot(e){e.exec(`
|
|
@@ -111,4 +111,4 @@ import{a as rt,b as ot,c as st,d as x,e as A,f as v}from"./chunk-72SZI2UW.js";im
|
|
|
111
111
|
`)}if(!m)throw new Error(`local decision backend could not get a valid answer after ${f+1} attempt(s): ${w}`);let M={},L=!1;for(let[k,q]of Object.entries(s.questions)){let S=_(q,m[k],{normalize:e.normalizeProbabilities??!0});M[k]=S.answer,S.repaired&&(L=!0)}return{model:a,answers:M,usage:h,meta:{backend:"local",structureMode:c,answerMode:"probabilities",repaired:L,retries:f,stateTruncated:l.truncated,latencyMs:Date.now()-i}}}finally{b()}}}}async function Jt(e,t,r,n,o){if(!e.generateRaw)throw new Error(`provider "${e.name}" has no generateRaw(); use structureMode "text"`);let s=[{role:"user",content:r},...n?[{role:"user",content:n}]:[]],i=await e.generateRaw(s,J,[{name:F,description:"Report a probability distribution for every question.",input_schema:se(t)}],{...o,toolChoice:{type:"tool",name:F}}),a=i.content.find(c=>c.type==="tool_use"&&c.name===F),u=a&&a.type==="tool_use"?a.input:null;return{answers:Be(u),usage:{inputTokens:i.usage.input_tokens,outputTokens:i.usage.output_tokens}}}async function Gt(e,t,r,n,o){let s=[r,ae(t)].join(`
|
|
112
112
|
`),i=[{role:"system",content:J},{role:"user",content:s},...n?[{role:"user",content:n}]:[]],a=await e.generate(i,o);return{answers:Be(Te(a.content??"")),usage:{inputTokens:0,outputTokens:a.tokensUsed??0}}}function Be(e){if(e&&typeof e=="object"&&!Array.isArray(e)){let t=e;if(t.answers&&typeof t.answers=="object")return t.answers}return e}function Yt(e,t){return e!=="auto"?e:t.generateRaw&&me[t.name]?.structuredOutput?"tool":"text"}function Kt(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var Xt,$t,Vt,Fe,zt,be=E(()=>{"use strict";Ze();Ue();ht();j();Y();v();z();Xt="claude-code",$t="claude-haiku-4-5-20251001",Vt=24e3,Fe=2e3,zt=3e4});import{readFileSync as Ht}from"fs";import{homedir as Wt}from"os";import{join as Zt}from"path";function N(e={}){let t=(e.baseUrl??en).replace(/\/+$/,""),r=e.path??"/classifier",n=e.name??"simple-jev",o=e.maxStateChars??nn,s=e.maxChoiceOptions??rn,i={probabilitySource:e.probabilitySource??"logits",calibratedProbabilities:!1,maxChoiceOptions:s,maxStateChars:o,parallelQuestions:!0,images:!1};return{name:n,capabilities:i,async decide(a){A(a.questions),cn(a.questions,s);let u=Date.now(),c=a.model??e.model;if(!c)throw new Error("simple-jev backend needs a model id");let l=G(a.state,o),p=e.fetchImpl??fetch,{signal:g,dispose:d}=un(a.abortSignal,a.timeoutMs??e.timeoutMs??tn);try{let b={"Content-Type":"application/json"},h=an(e.apiKeyEnv,e.apiKeyFile);h&&(b.Authorization=`Bearer ${h}`);let T=await qe(p(`${t}${r}`,{method:"POST",headers:b,body:JSON.stringify({model:c,state:l.text,questions:sn(a.questions)}),signal:g}),g);if(!T.ok){let k=await T.text().catch(()=>"");throw new Error(`${n} ${T.status}: ${k.slice(0,300)}`)}let f=await qe(T.json(),g),m=P(a.questions).safeParse(f.answers);if(!m.success)throw new Error(`${n} returned a response that does not match the requested questions (contract drift, not a model slip \u2014 retrying will not help):
|
|
113
113
|
${U(m.error)}`);let w=m.data,M={},L=!1;for(let[k,q]of Object.entries(a.questions)){let S=_(q,w[k]);M[k]=S.answer,S.repaired&&(L=!0)}return{model:f.model??c,answers:M,usage:{inputTokens:f.usage?.input_tokens??0,outputTokens:f.usage?.output_tokens??0},meta:{backend:n,structureMode:i.probabilitySource==="native"?"native":"logprobs",answerMode:"probabilities",repaired:L,retries:0,stateTruncated:l.truncated,latencyMs:Date.now()-u}}}finally{d()}}}}function sn(e){let t={};for(let[r,n]of Object.entries(e))t[r]=n.instructions?n:{...n,instructions:on[n.type]};return t}function an(e,t){let r=e?process.env[e]:void 0;if(r)return r;if(!t)return;let n=t.startsWith("~/")?Zt(Wt(),t.slice(2)):t;if(!Z.has(n))try{let o=Ht(n,"utf-8").trim();Z.set(n,o.length>0?o:null)}catch{Z.set(n,null)}return Z.get(n)??void 0}function cn(e,t){for(let[r,n]of Object.entries(e))if(n.type==="choice"){let o=Object.keys(n.criteria).length;if(o>t)throw new Error(`question "${r}": accepts at most ${t} choice options, got ${o}`)}else if(n.type==="score"&&n.criteria.length>t)throw new Error(`question "${r}": accepts at most ${t} score levels, got ${n.criteria.length}`)}function qe(e,t){return t.aborted?Promise.reject(t.reason??new Error("aborted")):new Promise((r,n)=>{let o=()=>n(t.reason??new Error("aborted"));t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)},s=>{t.removeEventListener("abort",o),n(s)})})}function un(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(new Error(`decision timed out after ${t}ms`)),t),o=()=>r.abort(e?.reason);return e&&(e.aborted?o():e.addEventListener("abort",o,{once:!0})),{signal:r.signal,dispose:()=>{clearTimeout(n),e?.removeEventListener("abort",o)}}}var en,tn,nn,rn,on,Z,fe=E(()=>{"use strict";j();v();z();Y();en="http://127.0.0.1:8000/v1",tn=3e4,nn=6e3,rn=50;on={choice:"Which option best fits?",score:"Which level best fits?",noul:"Is this true of the state?"};Z=new Map});var Xe={};We(Xe,{DEFAULT_SEAT_TIMEOUT_MS:()=>Ve,DecisionStore:()=>I,MAX_CHOICE_OPTIONS:()=>MAX_CHOICE_OPTIONS,SYSTEM_PROMPT:()=>J,TOOL_NAME:()=>F,UNCERTAINTY_HIGH:()=>Ce,UNCERTAINTY_LOW:()=>De,_resetDecisionBackendsForTesting:()=>wt,agreement:()=>it,answerView:()=>Q,applyRecalibrator:()=>ue,applyTemperature:()=>mt,askSeat:()=>yn,band:()=>Ie,bootstrapInterval:()=>ft,brier:()=>lt,buildDesign:()=>ve,calibrationReport:()=>gt,choice:()=>ot,compareCalibrators:()=>It,confidenceFor:()=>re,configureDecisions:()=>pn,configuredSeatTimeout:()=>dn,coverageCurve:()=>pt,createLocalDecisionBackend:()=>W,createMockDecisionBackend:()=>H,createSimpleJevBackend:()=>N,decisionsRuntime:()=>bn,describeIssues:()=>U,ece:()=>ct,expectedScore:()=>Ae,finalizeAnswer:()=>_,fitLogistic:()=>Ne,fitRecalibrator:()=>B,fitTemperature:()=>bt,getDecisionBackend:()=>D,getSeatMode:()=>Je,labelSeatCall:()=>fn,labelsOf:()=>x,listDecisionBackends:()=>Ee,logLoss:()=>dt,logit:()=>le,mce:()=>ut,measureConsistency:()=>Ut,normalizeDistribution:()=>Se,normalizedNegEntropy:()=>oe,noul:()=>rt,pMax:()=>xe,parseSeatMode:()=>ge,rawAnswerSchema:()=>Re,rawAnswersSchema:()=>P,recordSeatOutcome:()=>gn,registerBuiltinDecisionBackends:()=>ln,registerDecisionBackend:()=>R,reliabilityBins:()=>at,renderQuestions:()=>_e,renderShapeInstructions:()=>ae,renderState:()=>G,renderUserPrompt:()=>ie,resetDecisionsRuntime:()=>mn,score:()=>st,seatEnvVar:()=>ze,sigmoid:()=>de,toolInputSchema:()=>se,validateQuestions:()=>A,withUid:()=>Qe});function ln(e={},t={},r={},n={}){R("mock",()=>H()),R("local",()=>W(e)),R("simple-jev",()=>N(t)),R("jev",()=>N({name:"jev",baseUrl:"https://openrouter.ai/api/alpha",path:"/decisions",model:"jev-latest",apiKeyEnv:"OPENROUTER_API_KEY",apiKeyFile:"~/.agentx/openrouter-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...r})),R("typesafe",()=>N({name:"typesafe",baseUrl:"https://api.typesafe.ai/v1",path:"/systemone",model:"jev-latest",apiKeyEnv:"TYPESAFE_API_KEY",apiKeyFile:"~/.agentx/typesafe-key.txt",probabilitySource:"native",maxChoiceOptions:255,maxStateChars:9e4,...n}))}var $e=E(()=>{"use strict";ke();v();j();z();C();Y();V();yt();Me();je();Ge();pe();be();fe();C();pe();be();fe()});function dn(e){return Ke(),y.seats[e]?.timeoutMs}function pn(e){y={...ye,...y,...e},ee=!0}function mn(){y={...ye,seats:{}},ee=!1}function Ke(){if(!ee){ee=!0;try{let{loadDaemonConfig:e}=(nt(),he(tt)),t=e()?.decisions;if(!t?.enabled)return;let{registerBuiltinDecisionBackends:r}=($e(),he(Xe)),n=t.backends??{};r(n.local,n.simpleJev,n.jev,n.typesafe);let o=null;try{o=new I({path:t.dbPath})}catch{}y={enabled:!0,defaultBackend:t.defaultBackend,store:o,seats:Object.fromEntries(Object.entries(t.seats??{}).map(([s,i])=>[s,{...i,redactState:t.redactState,keepStateRows:t.keepStateRows}]))}}catch{}}}function bn(){return y}function ge(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return hn.includes(t)?t:null}function ze(e){return`AGENTX_DECISION_SEAT_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}function Je(e,t=process.env){Ke();let r=ge(t[ze(e)]);return r||(y.enabled?ge(y.seats[e]?.mode)??"off":"off")}function fn(e,t,r,n={}){if(!(!e||!y.store))try{y.store.label(e,t,r,n)}catch{}}function gn(e,t,r=!1){if(!(!e||!y.store))try{y.store.recordOutcome(e,t,r)}catch{}}async function yn(e,t,r,n={}){let o=Je(e);if(o==="off")return null;let s=y.seats[e]??{mode:o},i=n.backend??s.backend??y.defaultBackend,a=Date.now();try{let c=await D(i).decide({state:t,questions:r,model:n.model??s.model,abortSignal:n.signal,timeoutMs:n.timeoutMs??s.timeoutMs??(y.seats[e]?Ve:void 0)}),l=wn(e,o,t,r,c,n,s);return{answers:c.answers,callId:l,mode:o}}catch(u){return Tn(e,o,t,r,i,n,s,a,u),En(e,i,u),null}}function wn(e,t,r,n,o,s,i){if(!y.store)return null;try{return y.store.recordCall({seat:e,mode:t,backend:o.meta.backend,model:o.model,meta:o.meta,state:r,questions:n,answers:o.answers,usage:o.usage,incumbent:He(s.incumbent),links:s.links,features:s.features,keepState:!i.redactState})}catch{return null}}function Tn(e,t,r,n,o,s,i,a,u){if(y.store)try{y.store.recordCall({seat:e,mode:t,backend:o,model:s.model??i.model??"unknown",meta:{structureMode:"text",answerMode:"probabilities",retries:0,stateTruncated:!1,latencyMs:Date.now()-a},state:r,questions:n,answers:{},incumbent:He(s.incumbent),links:s.links,features:s.features,error:String(u?.message??u).slice(0,500),keepState:!i.redactState})}catch{}}function He(e){if(!e)return;let t={};for(let[r,n]of Object.entries(e))n!==void 0&&(t[r]={value:n});return t}function En(e,t,r){let n=Date.now();n-Ye<6e4||(Ye=n,console.warn(`[decisions] seat "${e}" on backend "${t}" failed: ${r?.message??r}`))}var Ve,ye,y,ee,hn,Ye,Ge=E(()=>{C();V();Ve=1e4;ye={enabled:!1,defaultBackend:"local",seats:{},store:null},y={...ye},ee=!1;hn=["off","shadow","active"];Ye=0});export{D as a,Ee as b,C as c,I as d,V as e,It as f,Me as g,Ut as h,je as i,me as j,Xn as k,Ue as l,ln as m,$e as n,Ve as o,dn as p,pn as q,mn as r,bn as s,ge as t,ze as u,Je as v,fn as w,gn as x,yn as y,Ge as z};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-NDPU6AX2.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as
|
|
2
|
-
`)}async function
|
|
3
|
-
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${
|
|
4
|
-
`),H=await
|
|
5
|
-
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=
|
|
6
|
-
`),g=await
|
|
7
|
-
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as D,b as _}from"./chunk-RKPAVWXF.js";import{a as R,b as q,c as O,d as B,f as k,g as v,h as E,i as w,j as y}from"./chunk-IOYRRGK7.js";import{a as T,b as C,c as I,d as x,e as P}from"./chunk-4PQREYBU.js";import{existsSync as X,readFileSync as F}from"fs";var J=new Set(["cron","heartbeat","api","a2a","mesh"]),M=160;function s(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function S(n,e=M){let t=n.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function V(n){let e=T(n);if(!X(e))throw new Error(`config not found at ${e}`);return JSON.parse(F(e,"utf-8"))}function W(n,e){return n?.agents?.[e]?.admin===!0}function Y(n,e,t){return W(n,t.agentId)||e?.createdBy===t.agentId}function Z(n,e){let t=e?.createdBy?`agent "${e.createdBy}"`:"the operator";return`Not allowed: "${n}" was created by ${t}. Agents manage only schedules they created (unless configured admin).`}function K(n,e){let t=s(n.notify);if(t!=="none"){if(t&&t!=="here"){let r=t.split(":");return r.length<2||!r[0]||!r[1]?"invalid":{channel:r[0],chatId:r.slice(1).join(":")}}if(e.channel&&e.chatId&&!J.has(e.channel))return{channel:e.channel,chatId:e.chatId,...e.accountId?{accountId:e.accountId}:{}}}}function Q(n,e,t){let r=e.timezone||"UTC",d=e.enabled&&!y(e)?w(E(e.schedule,r,t),r):"\u2014",h=e.approval?`pending ${e.approval.action} approval`:e.enabled?"active":"paused",f=[`- ${n} [${h}] ${e.schedule} \u2014 ${v(e.schedule)} (${r})`,` agent: ${e.agent}; created by: ${e.createdBy||"operator"}; next: ${d}`];return e.notify&&f.push(` notify: ${e.notify.channel} ${e.notify.chatId}${e.deliverResult===!1?" (failures only)":" (results and failures)"}`),e.command?f.push(` command: ${S(String(e.command))}`):e.prompt&&f.push(` prompt: ${S(String(e.prompt))}`),f.join(`
|
|
2
|
+
`)}async function b(n,e,t){let r=n?.notifications?.destination;if(!r?.channel||!r?.chatId)return"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.";if(!e.notifyOperator)return"Operator notification is unavailable in this context.";try{return await e.notifyOperator({channel:r.channel,chatId:r.chatId,accountId:r.accountId},t),"The operator has been notified."}catch(d){return`Could not notify the operator (${d?.message??d}); the request is still recorded.`}}async function re(n,e,t={}){let r=(s(n.action)||"list").toLowerCase(),d=t.now?t.now():new Date,h;try{h=V(t.configPath)}catch(a){return`Error: ${a.message}`}let f=h.crons||{};if(r==="list"){let a=n.mine===!0,l=Object.entries(f).filter(([,i])=>!a||e&&i?.createdBy===e.agentId);return l.length?l.map(([i,p])=>Q(i,p,d)).join(`
|
|
3
|
+
`):a?"You have no schedules.":"No schedules."}if(!e?.agentId)return"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.";if(!h.agents?.[e.agentId])return`Error: caller "${e.agentId}" is not an agent on this node.`;let o=s(n.id),m=a=>C(a,{configPath:t.configPath,reload:t.reload});if(r==="create"){let a=s(n.when),l=s(n.prompt);if(!a||!l)return"Error: create needs `when` (plain English) and `prompt`.";let i=D(a);if(!i)return`Error: couldn't parse "${a}". ${q}.`;let p=s(n.agent)||e.agentId;if(!h.agents?.[p])return`Error: agent "${p}" not found on this node.`;let g=s(n.timezone)||R;if(!B(g))return`Error: unknown timezone "${g}".`;let u=o||_(i.matched,p);if(!O(u))return`Error: invalid id "${u}" (letters, digits, "-" and "_" only).`;if(f[u])return`Error: a schedule "${u}" already exists. Pick another \`id\`.`;let $=K(n,e);if($==="invalid")return'Error: `notify` must be "here", "none", or "channel:chatId".';let z={action:"create",requestedBy:e.agentId,requestedAt:d.toISOString()},L=k({parsed:i,agent:p,prompt:l,timezone:g,notify:$,enabled:!1,createdBy:e.agentId,approval:z}),A=await m(U=>I(U,`crons.${u}`,L));if(!A.success)return`Error: ${A.error}`;let N=w(E(i.cron,g,d),g),G=[`Schedule approval requested by ${e.agentId}`,`Create: ${u}`,`When: ${i.human} \u2014 cron \`${i.cron}\` (${g})`,`Next fire: ${N}`,`Agent: ${p}`,$?`Results and failures go to: ${$.channel} ${$.chatId}${$.channel==="voice"?" (as a push notification)":""}`:"Results go to: run log only (no chat)",`Prompt: ${S(l,400)}`,"",`Approve: agentx schedule approve ${u}`,`Reject: agentx schedule reject ${u}`].join(`
|
|
4
|
+
`),H=await b(h,t,G);return[`Requested schedule "${u}": ${i.human} (cron ${i.cron}, ${g}); next fire would be ${N}.`,"It is saved DISABLED and will not run until the operator approves it.",H].join(`
|
|
5
|
+
`)}if(!o)return`Error: ${r} needs \`id\`.`;let c=f[o];if(!c)return`Error: schedule "${o}" not found.`;if(!Y(h,c,e))return Z(o,c);if(r==="pause"||r==="resume"){let a=r==="resume";if(a&&y(c))return`"${o}" is still awaiting operator approval; it can't be resumed until approved.`;if(c.enabled===a)return`"${o}" is already ${a?"active":"paused"}.`;let l=await m(i=>I(i,`crons.${o}.enabled`,a));return l.success?`"${o}" ${a?"resumed":"paused"}.`:`Error: ${l.error}`}if(r==="delete"){if(y(c)&&c.approval.requestedBy===e.agentId){let u=await m($=>P($,`crons.${o}`));return u.success?`Withdrew the pending request "${o}".`:`Error: ${u.error}`}if(y(c))return`"${o}" is a creation request still awaiting approval; only its requester or the operator (\`agentx schedule reject ${o}\`) can drop it.`;if(c.approval?.action==="delete")return`Deletion of "${o}" is already awaiting approval.`;let a={action:"delete",requestedBy:e.agentId,requestedAt:d.toISOString()},l=await m(u=>{if(!x(u,`crons.${o}`))throw new Error(`schedule "${o}" not found`);I(u,`crons.${o}.approval`,a)});if(!l.success)return`Error: ${l.error}`;let i=c.timezone||"UTC",p=[`Schedule approval requested by ${e.agentId}`,`Delete: ${o}`,`When: ${v(c.schedule)} \u2014 cron \`${c.schedule}\` (${i})`,`Next fire: ${c.enabled?w(E(c.schedule,i,d),i):"\u2014 (paused)"}`,`Agent: ${c.agent}`,"",`Approve: agentx schedule approve ${o}`,`Reject: agentx schedule reject ${o}`].join(`
|
|
6
|
+
`),g=await b(h,t,p);return[`Deletion of "${o}" requested. It keeps its current state until the operator approves.`,g].join(`
|
|
7
|
+
`)}return`Error: unknown action "${r}". Use list, create, pause, resume or delete.`}function oe(n,e=process.env){let t=s(e.AGENTX_AGENT_ID)||s(n.callerAgentId);if(!t)return null;let r=!!(s(e.AGENTX_CHANNEL)&&s(e.AGENTX_CHAT_ID)),d=s(r?e.AGENTX_CHANNEL:n.channel),h=s(r?e.AGENTX_CHAT_ID:n.chatId),f=s(n.accountId);return{agentId:t,channel:d,chatId:h,...f?{accountId:f}:{}}}export{re as a,oe as b};
|
|
8
|
+
//# sourceMappingURL=chunk-NG677JHW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crons/schedule-tool.ts"],"sourcesContent":["import { existsSync, readFileSync } from \"fs\"\nimport { applyConfigMutation, findConfigPath, getAtPath, setAtPath, unsetAtPath } from \"@/daemon/config-mutator\"\nimport { parseEnglishToCron, slugifyScheduleId } from \"@/utils/nl-cron\"\nimport {\n buildScheduleJob,\n DEFAULT_SCHEDULE_TIMEZONE,\n formatFireTime,\n humanizeCron,\n isPendingCreate,\n isValidScheduleId,\n isValidTimezone,\n nextFireTime,\n SUPPORTED_PHRASES_HINT,\n type NotifyTarget,\n type ScheduleApproval,\n} from \"./schedule-ops\"\n\n// --- Agent-facing `schedule` tool ---\n//\n// Lets an agent list / create / pause / resume / delete routines from any\n// chat. Writes go through the same builder and config mutator as the\n// `agentx schedule` CLI, with two differences that make it safe to hand to\n// a model:\n//\n// 1. create and delete are REQUESTS. Create writes the job disabled with an\n// `approval` marker (the scheduler refuses to run it while that marker\n// says \"create\"); delete only marks the job. The operator is notified\n// with the parsed cron and next fire time, and only\n// `agentx schedule approve|reject <id>` resolves the request. There is\n// no action here that approves anything.\n// 2. Ownership. Jobs record `createdBy`; an agent may touch only its own\n// unless its config says `admin: true`.\n\nexport type ScheduleAction = \"list\" | \"create\" | \"pause\" | \"resume\" | \"delete\"\n\nexport interface ScheduleCaller {\n agentId: string\n /** Chat the request came from — the default notify target. */\n channel?: string\n chatId?: string\n accountId?: string\n}\n\nexport interface ScheduleToolDeps {\n configPath?: string\n /** Hot-reload the daemon after a write. Default true. */\n reload?: boolean\n now?: () => Date\n /** Deliver the approval request to the operator. Throws on failure. */\n notifyOperator?: (dest: NotifyTarget, text: string) => Promise<void>\n}\n\n/** Channels that are not a conversation someone reads, so they never make a\n * sensible default delivery target for a routine's output. */\nconst NON_DELIVERABLE_CHANNELS = new Set([\"cron\", \"heartbeat\", \"api\", \"a2a\", \"mesh\"])\n\nconst PROMPT_PREVIEW = 160\n\nfunction str(v: unknown): string | undefined {\n return typeof v === \"string\" && v.trim() ? v.trim() : undefined\n}\n\nfunction preview(s: string, n = PROMPT_PREVIEW): string {\n const flat = s.replace(/\\s+/g, \" \").trim()\n return flat.length > n ? `${flat.slice(0, n - 1)}…` : flat\n}\n\nfunction readRawConfig(configPath?: string): any {\n const path = findConfigPath(configPath)\n if (!existsSync(path)) throw new Error(`config not found at ${path}`)\n return JSON.parse(readFileSync(path, \"utf-8\"))\n}\n\nfunction isAdmin(cfg: any, agentId: string): boolean {\n return cfg?.agents?.[agentId]?.admin === true\n}\n\nfunction canManage(cfg: any, job: any, caller: ScheduleCaller): boolean {\n return isAdmin(cfg, caller.agentId) || job?.createdBy === caller.agentId\n}\n\nfunction ownershipError(id: string, job: any): string {\n const owner = job?.createdBy ? `agent \"${job.createdBy}\"` : \"the operator\"\n return `Not allowed: \"${id}\" was created by ${owner}. Agents manage only schedules they created (unless configured admin).`\n}\n\nfunction resolveNotify(args: Record<string, unknown>, caller: ScheduleCaller): NotifyTarget | undefined | \"invalid\" {\n const raw = str(args.notify)\n if (raw === \"none\") return undefined\n if (raw && raw !== \"here\") {\n const parts = raw.split(\":\")\n if (parts.length < 2 || !parts[0] || !parts[1]) return \"invalid\"\n // chatIds can contain \":\" (gitlab \"org/repo:issue:1\"), so the channel\n // is the first segment and the rest is the chat id.\n return { channel: parts[0], chatId: parts.slice(1).join(\":\") }\n }\n if (caller.channel && caller.chatId && !NON_DELIVERABLE_CHANNELS.has(caller.channel)) {\n return { channel: caller.channel, chatId: caller.chatId, ...(caller.accountId ? { accountId: caller.accountId } : {}) }\n }\n return undefined\n}\n\nfunction describeJob(id: string, job: any, now: Date): string {\n const tz = job.timezone || \"UTC\"\n const next = job.enabled && !isPendingCreate(job) ? formatFireTime(nextFireTime(job.schedule, tz, now), tz) : \"—\"\n const state = job.approval\n ? `pending ${job.approval.action} approval`\n : job.enabled ? \"active\" : \"paused\"\n const lines = [\n `- ${id} [${state}] ${job.schedule} — ${humanizeCron(job.schedule)} (${tz})`,\n ` agent: ${job.agent}; created by: ${job.createdBy || \"operator\"}; next: ${next}`,\n ]\n if (job.notify) lines.push(` notify: ${job.notify.channel} ${job.notify.chatId}${job.deliverResult === false ? \" (failures only)\" : \" (results and failures)\"}`)\n if (job.command) lines.push(` command: ${preview(String(job.command))}`)\n else if (job.prompt) lines.push(` prompt: ${preview(String(job.prompt))}`)\n return lines.join(\"\\n\")\n}\n\nasync function notifyApproval(\n cfg: any,\n deps: ScheduleToolDeps,\n text: string,\n): Promise<string> {\n const dest = cfg?.notifications?.destination\n if (!dest?.channel || !dest?.chatId) {\n return \"No operator notification destination is configured (notifications.destination); the operator must check `agentx schedule list`.\"\n }\n if (!deps.notifyOperator) return \"Operator notification is unavailable in this context.\"\n try {\n await deps.notifyOperator({ channel: dest.channel, chatId: dest.chatId, accountId: dest.accountId }, text)\n return \"The operator has been notified.\"\n } catch (e: any) {\n return `Could not notify the operator (${e?.message ?? e}); the request is still recorded.`\n }\n}\n\n/**\n * Run one tool action. Returns the text the agent sees. Throws only on\n * programming errors — every expected refusal is returned as text so the\n * model can relay it.\n */\nexport async function runScheduleTool(\n args: Record<string, unknown>,\n caller: ScheduleCaller | null,\n deps: ScheduleToolDeps = {},\n): Promise<string> {\n const action = (str(args.action) || \"list\").toLowerCase() as ScheduleAction\n const now = deps.now ? deps.now() : new Date()\n\n let cfg: any\n try {\n cfg = readRawConfig(deps.configPath)\n } catch (e: any) {\n return `Error: ${e.message}`\n }\n const crons: Record<string, any> = cfg.crons || {}\n\n if (action === \"list\") {\n const mineOnly = args.mine === true\n const entries = Object.entries(crons).filter(([, j]) => !mineOnly || (caller && j?.createdBy === caller.agentId))\n if (!entries.length) return mineOnly ? \"You have no schedules.\" : \"No schedules.\"\n return entries.map(([id, j]) => describeJob(id, j, now)).join(\"\\n\")\n }\n\n if (!caller?.agentId) {\n return \"Error: caller agent is unknown (AGENTX_AGENT_ID not set). Pass callerAgentId.\"\n }\n if (!cfg.agents?.[caller.agentId]) {\n return `Error: caller \"${caller.agentId}\" is not an agent on this node.`\n }\n\n const id = str(args.id)\n const mutate = (fn: (c: any) => void) =>\n applyConfigMutation(fn, { configPath: deps.configPath, reload: deps.reload })\n\n if (action === \"create\") {\n const when = str(args.when)\n const prompt = str(args.prompt)\n if (!when || !prompt) return \"Error: create needs `when` (plain English) and `prompt`.\"\n const parsed = parseEnglishToCron(when)\n if (!parsed) return `Error: couldn't parse \"${when}\". ${SUPPORTED_PHRASES_HINT}.`\n\n const agent = str(args.agent) || caller.agentId\n if (!cfg.agents?.[agent]) return `Error: agent \"${agent}\" not found on this node.`\n\n const timezone = str(args.timezone) || DEFAULT_SCHEDULE_TIMEZONE\n if (!isValidTimezone(timezone)) return `Error: unknown timezone \"${timezone}\".`\n\n const jobId = id || slugifyScheduleId(parsed.matched, agent)\n if (!isValidScheduleId(jobId)) return `Error: invalid id \"${jobId}\" (letters, digits, \"-\" and \"_\" only).`\n if (crons[jobId]) return `Error: a schedule \"${jobId}\" already exists. Pick another \\`id\\`.`\n\n const notify = resolveNotify(args, caller)\n if (notify === \"invalid\") return 'Error: `notify` must be \"here\", \"none\", or \"channel:chatId\".'\n\n const approval: ScheduleApproval = {\n action: \"create\",\n requestedBy: caller.agentId,\n requestedAt: now.toISOString(),\n }\n const job = buildScheduleJob({\n parsed,\n agent,\n prompt,\n timezone,\n notify,\n enabled: false,\n createdBy: caller.agentId,\n approval,\n })\n\n const result = await mutate((c) => setAtPath(c, `crons.${jobId}`, job))\n if (!result.success) return `Error: ${result.error}`\n\n const next = formatFireTime(nextFireTime(parsed.cron, timezone, now), timezone)\n const request = [\n `Schedule approval requested by ${caller.agentId}`,\n `Create: ${jobId}`,\n `When: ${parsed.human} — cron \\`${parsed.cron}\\` (${timezone})`,\n `Next fire: ${next}`,\n `Agent: ${agent}`,\n notify ? `Results and failures go to: ${notify.channel} ${notify.chatId}${notify.channel === \"voice\" ? \" (as a push notification)\" : \"\"}` : \"Results go to: run log only (no chat)\",\n `Prompt: ${preview(prompt, 400)}`,\n \"\",\n `Approve: agentx schedule approve ${jobId}`,\n `Reject: agentx schedule reject ${jobId}`,\n ].join(\"\\n\")\n const notified = await notifyApproval(cfg, deps, request)\n\n return [\n `Requested schedule \"${jobId}\": ${parsed.human} (cron ${parsed.cron}, ${timezone}); next fire would be ${next}.`,\n \"It is saved DISABLED and will not run until the operator approves it.\",\n notified,\n ].join(\"\\n\")\n }\n\n if (!id) return `Error: ${action} needs \\`id\\`.`\n const job = crons[id]\n if (!job) return `Error: schedule \"${id}\" not found.`\n if (!canManage(cfg, job, caller)) return ownershipError(id, job)\n\n if (action === \"pause\" || action === \"resume\") {\n const enable = action === \"resume\"\n if (enable && isPendingCreate(job)) {\n return `\"${id}\" is still awaiting operator approval; it can't be resumed until approved.`\n }\n if (job.enabled === enable) return `\"${id}\" is already ${enable ? \"active\" : \"paused\"}.`\n const result = await mutate((c) => setAtPath(c, `crons.${id}.enabled`, enable))\n if (!result.success) return `Error: ${result.error}`\n return `\"${id}\" ${enable ? \"resumed\" : \"paused\"}.`\n }\n\n if (action === \"delete\") {\n // Withdrawing your own never-approved request removes nothing that ever\n // ran, so it needs no approval.\n if (isPendingCreate(job) && job.approval.requestedBy === caller.agentId) {\n const result = await mutate((c) => unsetAtPath(c, `crons.${id}`))\n if (!result.success) return `Error: ${result.error}`\n return `Withdrew the pending request \"${id}\".`\n }\n // Never replace a pending create marker with a delete marker: rejecting\n // that delete would leave a disabled job with no marker, which its owner\n // could then resume without the create ever being approved.\n if (isPendingCreate(job)) {\n return `\"${id}\" is a creation request still awaiting approval; only its requester or the operator (\\`agentx schedule reject ${id}\\`) can drop it.`\n }\n if (job.approval?.action === \"delete\") return `Deletion of \"${id}\" is already awaiting approval.`\n\n const approval: ScheduleApproval = {\n action: \"delete\",\n requestedBy: caller.agentId,\n requestedAt: now.toISOString(),\n }\n const result = await mutate((c) => {\n if (!getAtPath(c, `crons.${id}`)) throw new Error(`schedule \"${id}\" not found`)\n setAtPath(c, `crons.${id}.approval`, approval)\n })\n if (!result.success) return `Error: ${result.error}`\n\n const tz = job.timezone || \"UTC\"\n const request = [\n `Schedule approval requested by ${caller.agentId}`,\n `Delete: ${id}`,\n `When: ${humanizeCron(job.schedule)} — cron \\`${job.schedule}\\` (${tz})`,\n `Next fire: ${job.enabled ? formatFireTime(nextFireTime(job.schedule, tz, now), tz) : \"— (paused)\"}`,\n `Agent: ${job.agent}`,\n \"\",\n `Approve: agentx schedule approve ${id}`,\n `Reject: agentx schedule reject ${id}`,\n ].join(\"\\n\")\n const notified = await notifyApproval(cfg, deps, request)\n return [\n `Deletion of \"${id}\" requested. It keeps its current state until the operator approves.`,\n notified,\n ].join(\"\\n\")\n }\n\n return `Error: unknown action \"${action}\". Use list, create, pause, resume or delete.`\n}\n\n/**\n * Who is calling. The runtime-exported environment wins over model-supplied\n * arguments: an agent launched by AgentX cannot claim another identity by\n * passing `callerAgentId`. The arguments are the fallback for runtimes that\n * don't export the variables (e.g. an operator-configured MCP entry).\n */\nexport function resolveScheduleCaller(\n args: Record<string, unknown>,\n env: NodeJS.ProcessEnv = process.env,\n): ScheduleCaller | null {\n const agentId = str(env.AGENTX_AGENT_ID) || str(args.callerAgentId)\n if (!agentId) return null\n const envChat = Boolean(str(env.AGENTX_CHANNEL) && str(env.AGENTX_CHAT_ID))\n const channel = envChat ? str(env.AGENTX_CHANNEL) : str(args.channel)\n const chatId = envChat ? str(env.AGENTX_CHAT_ID) : str(args.chatId)\n const accountId = str(args.accountId)\n return { agentId, channel, chatId, ...(accountId ? { accountId } : {}) }\n}\n"],"mappings":"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","names":["existsSync","readFileSync","NON_DELIVERABLE_CHANNELS","PROMPT_PREVIEW","str","v","preview","s","n","flat","readRawConfig","configPath","path","findConfigPath","existsSync","readFileSync","isAdmin","cfg","agentId","canManage","job","caller","ownershipError","id","owner","resolveNotify","args","raw","parts","describeJob","now","tz","next","isPendingCreate","formatFireTime","nextFireTime","state","lines","humanizeCron","notifyApproval","deps","text","dest","e","runScheduleTool","action","crons","mineOnly","entries","j","mutate","fn","applyConfigMutation","when","prompt","parsed","parseEnglishToCron","SUPPORTED_PHRASES_HINT","agent","timezone","DEFAULT_SCHEDULE_TIMEZONE","isValidTimezone","jobId","slugifyScheduleId","isValidScheduleId","notify","approval","buildScheduleJob","result","c","setAtPath","request","notified","enable","unsetAtPath","getAtPath","resolveScheduleCaller","env","envChat","channel","chatId","accountId"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as tr,a as Ns,b as Ls,d as Hs,f as He,l as Ys,s as Vs,u as Zs,z as er}from"./chunk-
|
|
1
|
+
import{B as tr,a as Ns,b as Ls,d as Hs,f as He,l as Ys,s as Vs,u as Zs,z as er}from"./chunk-RJBRYUKU.js";import{a as Os}from"./chunk-GLQLCBJS.js";import{b as Fs}from"./chunk-6W74CHNW.js";import{a as Xs}from"./chunk-W4YR2RO2.js";import{b as js,c as Vt,d as Ws,e as qs,h as Gs}from"./chunk-B6OXEIOF.js";import{a as Rs}from"./chunk-23SQSUBI.js";import{e as Es,f as Ds}from"./chunk-36AXN6ZB.js";import{a as Xt,b as Bs}from"./chunk-J3SOEFRE.js";import{a as Yt,b as Us}from"./chunk-SIU6STB2.js";import{e as Ks,i as Js,j as Qs,k as zs}from"./chunk-X5C5W3E4.js";import{c as bs,f as xs}from"./chunk-2G227TF3.js";import{a as Ss,c as Is}from"./chunk-MYVHVJWZ.js";import{a as Ts,b as vs,c as ks,d as As,l as $s}from"./chunk-AV7T3SYT.js";import{a as Cs,b as Ms}from"./chunk-Y5MFVVTM.js";import{g as Ps,h as _s}from"./chunk-FTZCNID3.js";import{a as ve,c as ye}from"./chunk-2GIDVZ4H.js";import{s as ys,v as lt,w as ws,y as ue,z as zt}from"./chunk-NDPU6AX2.js";import{a as Fe,b as Te,f as ut}from"./chunk-72SZI2UW.js";import{a as Ie,b as Wt}from"./chunk-FCPTN6NF.js";import{c as os,d as is}from"./chunk-QOYAX2FT.js";import{e as he}from"./chunk-DSYKYZMT.js";import{C as us,E as Jt,G as Yi,J as ls,N as Vi,T as gs,U as Qt,V as ps,W as Le,X as fs,Y as ms,_ as hs,ma as Zi}from"./chunk-IMLLHT7U.js";import{g as Gt,h as zi}from"./chunk-BRK6M6LA.js";import{f as Kt,n as Xi}from"./chunk-UIBUZ2N3.js";import{a as as,b as ie,c as ds,d as cs,e as qt}from"./chunk-2QNT5JDS.js";zt();ut();var gt="tool-set",nr=["answer","code","full"],sr={answer:["Read","Grep","Glob"],code:["Read","Grep","Glob","Edit","MultiEdit","Write","Bash"]},ea=.1;function or(n){return{task:rr(n.message,2e3),agent:n.agent,channel:n.channel??null,...n.agentPrompt?{agentInstructions:rr(n.agentPrompt,600)}:{}}}var ir={bundle:Te({answer:"Read-only: the task can be done by reading, searching and listing files and then replying. It changes no file and runs no command (no tests, no git, no scripts).",code:"Change files or run commands in the workspace: edit or write files, run tests, builds, git or shell commands. Still all inside the workspace, with no web access, no sub-agents and no notebooks.",full:"Needs more than that, or it is not clear: fetching or searching the web, starting sub-agents, notebooks, or anything the other two do not clearly cover."},"Which set of built-in tools does an agent need to do this task completely? Pick the smallest set that is clearly enough.")};function ar(n,e=ea){let s=n?.bundle?.probabilities;if(!s)return"full";let r=Zt(s.answer),o=Zt(s.code),i=Zt(s.full);return r===null||o===null||i===null?"full":o+i<e?"answer":i<e?"code":"full"}function dr(n){let e=[...n].filter(t=>!t.startsWith("mcp__"));return e.every(t=>sr.answer.includes(t))?"answer":e.every(t=>sr.code.includes(t))?"code":"full"}function cr(n,e){return nr.indexOf(n)<nr.indexOf(e)}function Zt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function rr(n,e){return n.length>e?`${n.slice(0,e)}\u2026`:n}var ur=!1;function lr(n,e){let t=lt(gt);if(t!=="off")return t==="active"&&!ur&&(ur=!0,e(`[decisions] seat "${gt}" is set to active, but only shadow is built: it records and changes nothing`)),ue(gt,or(n),ir,{incumbent:{bundle:"full"},links:[{kind:"task",id:n.taskId}],features:{agent:n.agent,channel:n.channel??"unknown"}}).then(s=>{if(!s)return null;let r=s.answers,o=ar(r),i=r.bundle?.probabilities??{};return{callId:s.callId,bundle:o,probabilities:i}}).catch(()=>null)}function gr(n,e,t){return n.then(s=>{if(!s||e.error||!e.eventsSeen)return;let r=[...e.toolUses.keys()],o=dr(r);ws(s.callId,"bundle",o,{kind:"outcome",labeledBy:"tool-use"});let i=a=>typeof s.probabilities[a]=="number"?s.probabilities[a].toFixed(2):"-";t(`[${e.agentId}] tool-set shadow: would start with ${s.bundle} (answer ${i("answer")}, code ${i("code")}, full ${i("full")}); run used ${r.filter(a=>!a.startsWith("mcp__")).join(", ")||"no built-in tool"} \u2192 needed ${o}`+(cr(s.bundle,o)?" \u2014 MISS":""))}).catch(()=>{})}zt();ut();var pr="session-continuity",fr={continues:Fe("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Fe("Does the new request refer to something stated earlier in the conversation?")};function mr(n){let e=(n.recentRequests??[]).filter(Boolean);return{newRequest:en(n.message,1200),previousRequest:n.previousMessage?en(n.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>en(t,400))}:{},minutesSinceLastTurn:n.minutesSinceLastTurn,turnsSoFar:n.turnCount,currentContextTokens:n.lastTurnContextTokens,agent:n.agentId,channel:n.channel}}function hr(n,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,s=n.continues.noul,r=n.needsHistory.noul;return s<=t&&r<=t}function en(n,e){let t=String(n??"");return t.length>e?t.slice(0,e):t}import{execa as St}from"execa";import{spawn as ta}from"node:child_process";import{createHash as na}from"node:crypto";import{createInterface as sa}from"node:readline";var le=class extends Error{},ra=n=>ta("codex",["app-server",...n.args],{cwd:n.cwd,env:n.env,stdio:["pipe","pipe","pipe"]}),tn=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),sa({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
|
|
2
2
|
`)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let s=++this.nextId;return new Promise((r,o)=>{this.pending.set(s,{resolve:r,reject:o}),this.write({id:s,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let s of this.pending.values())s.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},nn=class{constructor(e=ra,t=8,s=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=s}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let s=na("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([b],[R])=>b.localeCompare(R))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new le("Conversation already running");r&&(r.fingerprint!==s||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let b=[...this.entries].find(([,R])=>!R.connection.busy);if(!b)throw new le("Codex warm process capacity reached");b[1].connection.close(),this.entries.delete(b[0])}try{r={fingerprint:s,connection:new tn(e,this.launchProcess)}}catch{throw new le("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",d,u,l,f,h=!1,p=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",p,{once:!0});let I=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),k=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let b={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};u=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...b,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=u,clearTimeout(k),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let E=new Promise((O,P)=>{i.failTurn=P,i.notify=(D,N)=>{if(N?.threadId!==u)return;let L=N.item,U={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...N,type:D.replace("/","."),...L?{item:{...L,type:U[L.type]||L.type}}:{}}),D==="item/completed"&&L?.type==="agentMessage"&&L.phase==="final_answer"&&(d=L.text),D==="item/agentMessage/delta"&&(h||(h=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=N.delta,e.onDelta?.(N.delta,c)),D==="thread/tokenUsage/updated"){let H=N.tokenUsage.last;f=H.inputTokens;let q=H.cachedInputTokens||0;l={inputTokens:(l?.inputTokens||0)+Math.max(0,(H.inputTokens||0)-q),outputTokens:(l?.outputTokens||0)+(H.outputTokens||0),cacheReadTokens:(l?.cacheReadTokens||0)+q,cacheCreateTokens:(l?.cacheCreateTokens||0)+(H.cacheWriteInputTokens||0)}}D==="turn/completed"&&(N.turn.status==="completed"?O():P(new Error(N.turn.error?.message||`Codex turn ${N.turn.status}`)))}});return E.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:u,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await E,{content:d??c,codexSessionId:u,billedModel:e.model,usage:l,contextTokens:f,duration:Date.now()-t}}catch(b){if(i.close(),!a&&!e.signal?.aborted)throw new le(b.message);return{content:c,codexSessionId:u,usage:l,contextTokens:f,error:b.message,duration:Date.now()-t}}finally{clearTimeout(k),clearTimeout(I),e.signal?.removeEventListener("abort",p),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},yr=new nn;import{execFile as ka}from"child_process";import{StringDecoder as qe}from"string_decoder";import{mkdtempSync as Or,readFileSync as Nr,rmSync as Lr}from"fs";import{join as bt}from"path";import{tmpdir as Fr}from"os";function pt(n){let e=(n||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let d=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${d?` Resets ${d[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),s;if(t)try{s=JSON.parse(t[0])}catch{}let r=s?.error||s,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ft(n){return n.fix?`${n.message} \u2014 ${n.fix}`:n.message}function mt(n){if(!n||typeof n!="object")return;let e,t=-1,s=-1;for(let[r,o]of Object.entries(n)){let i=o&&typeof o=="object"?o:{},a=typeof i.costUSD=="number"?i.costUSD:0,c=(Number(i.inputTokens)||0)+(Number(i.outputTokens)||0)+(Number(i.cacheReadInputTokens)||0)+(Number(i.cacheCreationInputTokens)||0);(a>t||a===t&&c>s)&&(e=r,t=a,s=c)}return e}var wr=null;function ht(){return wr}function Lu(n){wr=n}function Be(n){return`${n.agentId}:${n.channel}:${n.chatId}`}function oa(n,e){if(n.state()==="busy")return null;let s=n.snapshot(),r=n.opts?.model;return r&&e.model&&r!==e.model?`model changed (${r} -> ${e.model})`:e.resumeSessionId?s.claudeSessionId&&s.claudeSessionId!==e.resumeSessionId?`session changed (${s.claudeSessionId.slice(0,8)} -> ${e.resumeSessionId.slice(0,8)})`:null:s.claudeSessionId?"session rotated":null}var ke=class extends Error{constructor(t,s,r){super(t);this.scope=s;this.cap=r;this.name="RegistryCapExceeded"}},br=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let s=Be(e),r=this.handles.get(s);if(r&&r.state()!=="dead"){let a=oa(r,t);if(!a)return r.claim?.(),r;this.handles.delete(s),this.handleWorkspace.delete(s),this.cfg.log(`[process-registry] respawning ${s}: ${a}`),r.kill(a).catch(()=>{})}if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new ke(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new ke(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(s,i),this.handleWorkspace.set(s,t.workspace),this.cfg.log(`[process-registry] spawned ${s}`),i}release(e,t={}){let s=Be(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=Be(e),s=this.handles.get(t);return s!=null&&s.state()!=="dead"}async kill(e,t="operator"){let s=Be(e),r=this.handles.get(s);r&&(this.handles.delete(s),this.handleWorkspace.delete(s),await r.kill(t))}countForAgent(e){let t=0;for(let s of this.handles.values())s.key.agentId===e&&s.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,s=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<s&&(s=i,t=o)}if(!t)return!1;let r=Be(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,s]of this.handles.entries()){let r=s.snapshot();if(s.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(s.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),s.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(s.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",d=a??"unmarked";s.kill(`claude-md drifted (${c} \u2192 ${d})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${d})`)}}}}}};import{spawn as ia}from"child_process";import{randomUUID as aa}from"crypto";import{existsSync as da,readFileSync as ca}from"fs";import{resolve as ua}from"path";function la(n){let e=ua(n,"CLAUDE.md");if(!da(e))return null;try{let t=ca(e,"utf8");return $s(t)}catch{return null}}var ga=20*60*1e3,pa=5e3,je=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Ue=class extends Error{constructor(t){super(`claude process stopped mid-turn (${t})`);this.reason=t}};function fa(n,e){return n.AGENTX_AGENT_ID=e.agentId,n.AGENTX_CHANNEL=e.channel,n.AGENTX_CHAT_ID=e.chatId,delete n.AGENTX_TASK_ID,n}var xr=class{constructor(e={}){this.opts=e}spawn(e,t){return new sn(e,t,this.opts)}},sn=class{constructor(e,t,s){this.key=e;this.opts=t;this.factoryOpts=s;let r=s.binary??"claude",o=this.buildArgs(t),i=this.log=s.log??(()=>{});this.child=ia(r,o,{cwd:t.workspace,env:ye(fa({...process.env},e),t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:la(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let d of c)d(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;log;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,s=new Promise(h=>{t=h}),r=this.turnQueue;if(this.turnQueue=r.then(()=>s),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=aa(),a=JSON.stringify({type:"user",uuid:i,message:{role:"user",content:e.message}});this.child.stdin.write(a+`
|
|
3
3
|
`);let c=e.deadlineMs??ga,d=o+c,u=()=>(this.kill(`turn deadline (${Math.round(c/6e4)}m)`),new je(c)),l=!1,f=null;try{for(;;){let h=d-Date.now();if(h<=0)throw u();let p=await this.nextEvent(h);if(p===null&&this.killReason)throw new Ue(this.killReason);if(p===null&&!this.exited)throw u();if(p===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(!l){if(p.type==="user"&&p.uuid===i)l=!0,f&&(yield{type:f.type,raw:f});else if(p.type==="system"&&p.subtype==="init")f=p;else if(p.type==="result"){f=null;let I=typeof p.result=="string"?p.result:"";this.log(`[claude pid=${this.snap.pid}] dropped a reply no question asked for (${I.length} chars): ${I.slice(0,120)}`)}continue}if(yield{type:p.type,raw:p},p.type==="result"){this.onResultEvent(p);return}}}finally{let h=this.snap.state==="busy";this.snap={...this.snap,...h?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let s=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},pa);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),e.extraArgs&&t.push(...e.extraArgs),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
|
|
4
4
|
`))!==-1;){let s=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!s.trim())continue;let r;try{r=JSON.parse(s)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let s=!1,r=setTimeout(()=>{if(s)return;s=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{s||(s=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},s=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:s,state:"idle"}}};qt();Xi();Wt();import{resolve as Sr,join as Ir}from"path";var ma=4e3;function yt(n){try{let e=Ir(Sr(n.root),".agentx","db.sqlite"),t=Kt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let s=Ie(),r=n.input.command?n.input.command.slice(0,ma):n.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
|
|
@@ -27,7 +27,7 @@ ${n}`}function $a(n,e,t,s,r){let o=["run","--format","json","--thinking"],i=t||n
|
|
|
27
27
|
`,l)}};O.stdout?.on("data",T=>{L+=H.write(T);let w=L.split(`
|
|
28
28
|
`);L=w.pop()||"";for(let _ of w)G(_)}),O.stderr?.on("data",T=>{U+=q.write(T)});let $=await O;if(i&&i.removeEventListener("abort",N),L+=H.end(),L.trim()&&G(L),U+=q.end(),P)return{content:"",error:D||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if($.exitCode!==0||p){let T=$,w;return T.timedOut?w=`OpenCode timed out after ${Math.round(R/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`:p?w=p:T.code==="ENOENT"||/ENOENT|spawn opencode/i.test((T.shortMessage||"")+" "+U)?w=Rr():w=U.trim()||`OpenCode exited with code ${T.exitCode??"unknown"}`,{content:"",...X(w),duration:Date.now()-c,usage:f,opencodeSessionId:h}}return k=!1,{content:l.trim(),duration:Date.now()-c,usage:f,billedModel:e.model||n.model,opencodeSessionId:h}}catch(R){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let E=/ENOENT|spawn opencode/i.test(R?.message||"")?Rr():R?.message;return{content:l,...X(E||"OpenCode failed"),duration:Date.now()-c,usage:f,opencodeSessionId:h}}finally{b?.(),I?.release(k)}}async function Fa(n,e,t,s){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=pe(n,e,s),c="",d=i({prompt:a,options:{model:e.model||n.model,cwd:n.workspace,permissionMode:"bypassPermissions"}});for await(let u of d)u.type==="result"&&u.subtype==="success"&&(c=u.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...X(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Ha(n,e,t,s,r,o,i,a,c){let d=Date.now(),u=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4),l=new AbortController,f=!1,h=()=>{let k=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{l.abort(new Error(k))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let p=setTimeout(()=>{f=!0;try{l.abort(new Error(`orchestrator timed out after ${Math.round(u/6e4)}m`))}catch{}},u);p.unref?.();let I=()=>({content:"",...X(`Orchestrator timed out after ${Math.round(u/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||"this agent"}" if tasks need longer.`),duration:Date.now()-d});try{let k=n.provider||"claude-code",b=s?`${s}
|
|
29
29
|
|
|
30
|
-
${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=As(n),D=Object.keys(P).length>0,N={task:b,cwd:n.workspace,provider:k,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-
|
|
30
|
+
${e.message}`:e.message,R=e.context?.sender,E=typeof R=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(R),O=e.context?.channel==="web-chat"&&E?{userId:R,agentId:e.agentId||"acme-public"}:void 0,P=As(n),D=Object.keys(P).length>0,N={task:b,cwd:n.workspace,provider:k,model:e.model||n.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:O,providerOpts:o,abortSignal:l.signal,mcpServers:D?P:void 0};if(r){let{generateStream:G}=await import("./agent-E6W5VBYH.js"),$="",T,w,_,x;for await(let v of G(N)){if(c)try{c(v)}catch{}if(v.type==="text_delta")$+=v.text,r(v.text,$);else if(v.type==="thinking_delta")v.text&&i&&i(v.text);else if(v.type==="generate_result"){if(v.result.content&&v.result.content!==$){let K=v.result.content.slice($.length);K?($=v.result.content,r(K,$)):$=v.result.content}T=v.result.tokensUsed,v.result.inputTokens!=null&&(w=v.result.inputTokens),v.result.outputTokens!=null&&(_=v.result.outputTokens)}else if(v.type==="done"){if(v.result.content&&v.result.content!==$){let K=v.result.content.slice($.length);K?($=v.result.content,r(K,$)):$=v.result.content}v.result.tokensUsed!=null&&(T=v.result.tokensUsed)}else v.type==="error"&&(x=v.error)}return x&&!$?f?I():x==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${x}`),duration:Date.now()-d}:((w===void 0||_===void 0)&&T&&(w=Math.round(T*.7),_=T-w),{content:$||"Done.",tokensUsed:T,usage:w!==void 0||_!==void 0?{inputTokens:w||0,outputTokens:_||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d})}let{generate:L}=await import("./agent-E6W5VBYH.js"),U=await L(N),H=U.inputTokens,q=U.outputTokens;if((H===void 0||q===void 0)&&U.tokensUsed){let G=U.tokensUsed;H=Math.round(G*.7),q=G-H}return{content:U.content||"Done.",tokensUsed:U.tokensUsed,usage:H!==void 0||q!==void 0?{inputTokens:H||0,outputTokens:q||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-d}}catch(k){return f?I():k?.message==="cancelled"||a?.aborted||l.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-d}:{content:"",...X(`Orchestrator error: ${k.message}`),duration:Date.now()-d}}finally{clearTimeout(p),a&&a.removeEventListener("abort",h)}}var Ba=1e3;async function ja(n,e){let t=Promise.resolve(n).then(i=>({kind:"exit",r:i})),s,r=e.then(()=>new Promise(i=>{s=setTimeout(()=>i({kind:"grace"}),Ba),s.unref?.()})),o=await Promise.race([t,r]);return s&&clearTimeout(s),o.kind==="exit"?o.r:(t.catch(()=>{}),{exitCode:0,stdout:"",stderr:"",detachedAfterResult:!0})}async function Ua(n,e,t,s,r,o,i){let a=ht();if(!a)return null;let c=Date.now(),{channel:d,chatId:u}=Tt(e.context),l={agentId:e.agentId,channel:d,chatId:u};if(e.freshSession)try{await a.kill(l,"freshSession=true")}catch{}let f,h=!1;try{let $=a.list().length;f=a.acquire(l,{agentId:e.agentId,channel:d,chatId:u,workspace:n.workspace,model:e.model||n.model,permissionMode:n.permissionMode,billing:n.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:s,extraArgs:e.claudeArgs}),h=a.list().length>$}catch($){return $ instanceof ke,null}h&&cn(e.agentId,n,e.model,s,"persistent");let p=pe(n,e,t),I="",k,b,R,E,O,P,D,N="",L="",U=$=>{if(!i||!$)return;let T;if(L&&$.startsWith(L)?T=$.slice(L.length):T=N&&!N.endsWith(`
|
|
31
31
|
`)?`
|
|
32
32
|
|
|
33
33
|
${$}`:$,L=$,!!T){N+=T;try{i(T,N)}catch{}}},H=!1,q=()=>{H=!0,a.kill(l,"operator-cancel").catch(()=>{})};o&&(o.aborted?q():o.addEventListener("abort",q,{once:!0}));let G=!1;try{let $=Math.max(6e4,(n.maxExecutionMinutes??20)*6e4);for await(let T of f.runTurn({message:p,taskId:e.taskId??"unknown",deadlineMs:$})){if(G=!0,r)try{r(T.raw)}catch{}if(T.type==="assistant"){let w=T.raw.message?.content??[];for(let x of w)x.type==="text"&&typeof x.text=="string"?(I=x.text,U(x.text)):x.type==="tool_use"&&(L="");let _=T.raw.message?.usage;if(_){let x=(_.input_tokens||0)+(_.cache_read_input_tokens||0)+(_.cache_creation_input_tokens||0);x>0&&(E=x)}}if(T.type==="result"){let w=T.raw;if(w.is_error){let _=X(typeof w.result=="string"?w.result:"claude error");k=_.error,b=_.errorKind}else typeof w.result=="string"&&w.result.length>0&&(I=w.result,N||U(w.result));typeof w.session_id=="string"&&(D=w.session_id),w.usage&&(R={inputTokens:w.usage.input_tokens||0,outputTokens:w.usage.output_tokens||0,cacheReadTokens:w.usage.cache_read_input_tokens||0,cacheCreateTokens:w.usage.cache_creation_input_tokens||0}),typeof w.num_turns=="number"&&(O=w.num_turns),typeof w.message?.model=="string"?P=w.message.model:typeof w.model=="string"?P=w.model:P=mt(w.modelUsage)||P}}}catch($){if(H)k="task cancelled by operator",b="cancelled";else if(G)if($ instanceof Ue)k=`Claude Code was stopped mid-turn (${$.reason}), before its time limit`,b="interrupted";else if($ instanceof je){let T=X(`Claude Code timed out after ${Math.round($.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${n.name||e.agentId}" if tasks need longer.`);k=T.error,b=T.errorKind}else{let T=X(`persistent claude process error: ${$?.message||String($)}`);k=T.error,b=T.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${$?.message||$}); falling back to spawn-per-task`),a.release(l,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",q),null}finally{o&&o.removeEventListener("abort",q)}return H&&!k&&(k="task cancelled by operator",b="cancelled"),{content:H?"":I,error:k,errorKind:b,duration:Date.now()-c,usage:R,contextTokens:E,numTurns:O,billedModel:P,claudeSessionId:D}}function Jr(n){let e=ie(n.autonomy);if(!e&&!n.personLimits)return{args:[]};if(!n.taskId)return{error:"a guarded task requires a task id to enforce"};let t=e?kr(n.autonomy,n.agentId,n.taskId):{args:[]};return"error"in t||!n.personLimits?t:Pr(t.args,n.taskId,n.agentId)}function Wa(n){return ie(n.autonomy)||!!n.personLimits}async function qa(n,e,t,s,r,o,i){let a=ie(e.autonomy)?e.autonomy:void 0,c=a&&Ar(a,n.tier)||e.personLimits&&_r(n.tier);if(c)return{content:"",error:c,...a?{autonomy:a}:{}};let d=e.taskId||`guarded-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,u={...e,taskId:d,message:a?`${cs(a)}
|
|
@@ -134,7 +134,7 @@ ${lu}`:n==="codex-cli"?yi:""}function wi(n,e){return e!=="claude-code"&&e!=="cod
|
|
|
134
134
|
`)[0]?.slice(0,80)});return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(r=>r.startsWith("@")):s.mentions[0]}cloudSessionStore(){return this.cloudSessions||(this.cloudSessions=new Rt(J(process.cwd(),".agentx/cloud-sessions.json"))),this.cloudSessions}planCloudSession(e,t){let s={...Et,...e.cloudSessions??{}};if(!s.enabled)return{route:"local",reason:"cloud sessions are off for this agent"};let r=t.context?.channel||"api",o=this.config.channels?.[r],i=Cn(t.context?.chatId),a=this.cloudSessionStore();return pi({agent:e,channelEnabled:o?.cloudSessions===!0,context:t.context,openSession:i?a.open(i.repo,i.number,s.openHours):void 0,launchesToday:a.launchesToday(t.agentId)})}async runCloudSession(e,t,s,r){let o={...Et,...e.cloudSessions??{}},i=Date.now(),a=ye(Ge(ve(e.workspace),t),e.billing),c=await hi({route:s,agentId:t.agentId,message:t.message,settings:o,store:this.cloudSessionStore(),traceId:r,launch:d=>mi({...d,env:a,timeoutMs:o.launchTimeoutSeconds*1e3}),log:d=>this.log(d),trace:d=>{try{Y().emit("task:step",{taskId:r,agentId:t.agentId,name:"cloud_session",action:d.action,status:d.status,outputSummary:d.status==="ok"?d.summary:void 0,error:d.status==="error"?d.summary:void 0,ms:Date.now()-i,at:new Date().toISOString()})}catch{}}});return c?{content:c.content,error:c.error,cloudSession:c.cloudSession,duration:Date.now()-i}:null}async execute(e,t,s,r){let o=Date.now(),i;try{i=await this.executeInternal(e,t,s,r)}catch(d){i={content:"",error:d?.message??String(d)}}let a=e.runningTaskId?this.interruptedRuns.get(e.runningTaskId):void 0;a&&(this.interruptedRuns.delete(e.runningTaskId),i={...i,content:"",error:a,errorKind:"interrupted"}),e.runningTaskId&&this.runReleases.get(e.runningTaskId)?.(i);let c=!a&&i.error&&/^timed out before spawn after/.test(i.error);if(c&&!e.preSpawnRetry)return this.log(`[${e.agentId}] ${i.error}; retrying the run once`),this.execute({...e,preSpawnRetry:1,runningTaskId:void 0,onStart:void 0},t,s,r);if(c){let d=i.error.match(/in step "([^"]+)"/)?.[1]??"start";i={...i,error:`I couldn't get started on this: preparing the run stalled twice (step "${d}"). Please send it again.`,errorKind:"interrupted"}}if(e.intentRef)try{let d=i.error?He(i.error)?"queued":/timed out|timeout/i.test(i.error)?"timed-out":"failed":"completed";js().recordResolution({decisionEventId:e.intentRef.eventId,decisionDecidedBy:e.intentRef.decidedBy,resolvedAt:Date.now(),status:d,durationMs:Date.now()-o,resultSummary:i.error?i.error.slice(0,200):i.content?.slice(0,200)??null})}catch(d){this.log(`[ledger] resolution write failed for ${e.intentRef.eventId}/${e.intentRef.decidedBy}: ${d?.message??d}`)}return i}async executeInternal(e,t,s,r){let o=this.refusalFor(e.agentId,e.context);if(o)return{content:o,duration:0};let i=ie(e.autonomy),a=fs(this.config.people,e.context);a?e.personLimits=a:delete e.personLimits;let c=i||a?null:fo().offer({agentId:e.agentId,text:e.message,channel:e.context?.channel||"api",chatId:String(e.context?.chatId||e.context?.group||"default"),sender:String(e.context?.sender||"unknown")});if(c){let g=await c;if(g.kind==="answered")return this.log(`[${e.agentId}] answered by attached session ${g.sessionId}`),{content:g.text,viaAttachedSession:g.sessionId};this.log(`[${e.agentId}] attached session did not take it (${g.reason}) \u2014 spawning`)}let d=this.agents.get(e.agentId);if(!d){if(i)return{content:"",error:`autonomy "${e.autonomy}" cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`,autonomy:e.autonomy};if(a)return{content:"",error:`${a.name}'s tool and skill limits cannot be enforced on a mesh peer \u2014 agent "${e.agentId}" is not local`};if(this.meshFallback){let g=this.meshFallback.directory().find(m=>m.healthy&&m.skills.some(S=>S.id===e.agentId));if(g){this.log(`[${e.agentId}] not local \u2014 routing to mesh peer "${g.peer}"`);try{let m=typeof e.timeoutMinutes=="number"&&e.timeoutMinutes>0?e.timeoutMinutes*60*1e3:void 0;return{content:await this.meshFallback.sendTask(g.peer,e.message,e.agentId,{timeoutMs:m}),viaMesh:g.peer}}catch(m){return this.log(`[${e.agentId}] mesh fallback to "${g.peer}" failed: ${m?.message??m}`),{content:"",error:`mesh fallback failed: ${m?.message??m}`}}}}return{content:"",error:`Unknown agent: ${e.agentId}`}}let{channel:u,chatId:l}=Tt(e.context),f;if(d.activeTasks>=d.def.maxConcurrent)if(u==="api"||u==="app"||u==="a2a"||u==="mcp"||u==="reminder"||u==="events"||u==="guest"||i){let g=Date.now(),m=25*6e4,S=500;for(;d.activeTasks>=d.def.maxConcurrent;){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 slot wait timed out after ${Math.round(m/6e4)}m`};await new Promise(M=>setTimeout(M,S))}}else if(u==="voice"){let g=Date.now(),m=25*6e4,S=`${e.agentId}\0${l}`;for(;this.messageQueue.isBusy(e.agentId,u,l)||this.voiceClaims.has(S);){if(Date.now()-g>m)return{content:"",error:`Agent "${e.agentId}" busy \u2014 voice wait timed out after ${Math.round(m/6e4)}m`};await new Promise(M=>setTimeout(M,500))}f=S,this.voiceClaims.add(S)}else{let g=d.def.queueMode||"collect",m=this.messageQueue.enqueue(e.agentId,u,l,{text:e.message,sender:e.context?.sender||"User",timestamp:Date.now(),channel:u,chatId:l,originalContext:e.context,queuedAt:e.queuedAt});if(m==="drop")return this.log(`[${e.agentId}] busy, message dropped (mode: drop)`),{content:"",error:`Agent "${e.agentId}" is busy \u2014 message dropped`};if(m){let S=this.messageQueue.pendingCount(e.agentId,u,l);return Y().emit("task:queued",{agentId:e.agentId,channel:u,chatId:l,at:new Date().toISOString(),sender:Jt(e.context),humanRoot:Gt(e.context),person:Qt(this.config.people,e.context)?.id??null,messagePreview:e.message.slice(0,200),queuedAt:Date.now()}),this.log(`[${e.agentId}] busy, message queued (mode: ${m}, pending: ${S}) behind=${d.runningTasks.map(M=>M.id).join(",")||"-"} chat=${u}:${l} at=${new Date().toISOString()}`),{content:"",error:Hs(m,S)}}}let h=await this.rateLimiter.acquire(e.agentId,{maxWaitMs:5*6e4,onWait:(g,m)=>{this.log(`[${e.agentId}] ${g} \u2014 queued, resumes in ~${Math.max(1,Math.round(m/1e3))}s`)}});if(f&&this.voiceClaims.delete(f),!h.ok)return this.log(`[${e.agentId}] ${h.reason}`),{content:"",error:h.reason};if(e.queuedAt!==void 0){let g=ro(e.queuedAt);g&&(e.message=`${g}
|
|
135
135
|
${e.message}`),e.queuedAt=void 0}d.activeTasks++,d.totalTasks++,d.lastActive=new Date;let p={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,messagePreview:(e.message||"").slice(0,200),message:e.message||"",channel:e.context?.channel||"api",chatId:e.context?.chatId||e.context?.group,sender:e.context?.sender,startedAt:new Date};d.runningTasks.push(p),e.runningTaskId=p.id;let I=Qt(this.config.people,e.context);if(e.context&&(I?e.context.person=I.id:delete e.context.person),this.runningContexts.set(p.id,e.context??{}),e.onStart)try{e.onStart(p.id)}catch{}let k=new AbortController;this.taskAborts.set(p.id,{agentId:e.agentId,channel:p.channel,chatId:typeof p.chatId=="string"?p.chatId:"",originalMessage:e.message||"",controller:k});let b={agentId:e.agentId,buffer:"",subscribers:new Set,done:!1};this.taskOutputs.set(p.id,b);let R=g=>{if(g){b.buffer+=g,b.buffer.length>bi&&(b.buffer=b.buffer.slice(b.buffer.length-bi));for(let m of b.subscribers)try{m(g)}catch{}}},E=Ie();e.taskId=E;let O=new Map,P=(g,m,S)=>{try{Y().emit("task:step",{taskId:E,agentId:e.agentId,name:"pipeline",action:g,status:S,ms:Date.now()-m,at:new Date().toISOString()})}catch{}},D=0,N=!1,L=()=>{N||(N=!0,D&&P("first-event",D,"ok"))},U;if(t){let g=Iu();U=m=>{L();let S=g(m);if(S&&R(S),Ii(E,e.agentId,m),Si(O,m),wn(m,void 0,e.model||d.def.model),r)try{r(m)}catch{}}}else U=g=>{if(L(),Ii(E,e.agentId,g),Si(O,g),wn(g,void 0,e.model||d.def.model),r)try{r(g)}catch{}};let H=e.timeoutMinutes&&e.timeoutMinutes>0?e.timeoutMinutes*6e4:0,q=H?setTimeout(()=>k.abort(new Error(`timed out after ${Math.round(H/1e3)}s`)),H):void 0;q?.unref?.();let G=(d.def.preSpawnTimeoutSec??mu)*1e3,$=setTimeout(()=>{k.abort(new Error(`timed out before spawn after ${Math.round(G/1e3)}s in step "${p.step??"start"}"`))},G);$.unref?.();let T=()=>{$&&clearTimeout($),$=void 0},w=()=>`task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`,_;k.signal.addEventListener("abort",()=>{let g=Xe(k.signal).message;/^timed out/.test(g)&&(_=p.step??"start"),this.log(`[${e.agentId}] task ${p.id} aborted in step "${p.step??"start"}" \u2014 ${g} ${w()}`)},{once:!0});let x=g=>{p.step=g,this.log(`[${e.agentId}] step ${g} ${w()}`)},v=(g,m,S=0)=>{if(k.signal.aborted)return Promise.reject(Xe(k.signal));x(g),(g==="agent"||g==="workflow-auto-run")&&(T(),D=Date.now());let M=Date.now(),W=gi(m(),uu[g]??0,g);return li(W,k.signal,S).then(j=>(P(g,M,"ok"),j),j=>{throw P(g,M,"error"),j instanceof _e&&this.log(`[${e.agentId}] ${j.message}; continuing without it ${w()}`),j})},K=async(g,m,S,M=0)=>{try{return await v(g,m,M)}catch(W){if(W instanceof _e)return S();throw W}},Pn=!1,_n=g=>{if(Pn)return;Pn=!0,this.runReleases.delete(p.id),q&&clearTimeout(q),T(),d.activeTasks--;let m=d.runningTasks.findIndex(S=>S.id===p.id);m!==-1&&d.runningTasks.splice(m,1),this.runningContexts.delete(p.id),this.taskAborts.delete(p.id),b.done=!0,b.endedAt=new Date;for(let S of b.subscribers)try{S(`
|
|
136
136
|
[task finished]
|
|
137
|
-
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),pu).unref?.();try{let S=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let W=(M.responseText||M.error||"").trim();if(W){let j=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:j,at:S,ok:M.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:S.length,at:new Date().toISOString()});let W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let j of S){let ee=j.originalContext||{channel:j.channel,sender:j.sender,chatId:j.chatId};this.execute({message:j.text,agentId:e.agentId,context:ee,queuedAt:j.queuedAt??j.timestamp}).then(te=>(He(te.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw W(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(S=>{Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,_n),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:ki,selectRequestContext:Ai}=await import("./request-planner-
|
|
137
|
+
`)}catch{}b.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(p.id),pu).unref?.();try{let S=b.endedAt,M={id:p.id,agentId:e.agentId,channel:p.channel,chatId:p.chatId,sender:p.sender,message:e.message||"",startedAt:p.startedAt.toISOString(),endedAt:S.toISOString(),durationMs:S.getTime()-p.startedAt.getTime(),ok:!g?.error,error:g?.error,..._?{status:"timeout",step:_}:{},responseText:g?.content||"",transcript:b.buffer};this.persistTaskRecord(M);let W=(M.responseText||M.error||"").trim();if(W){let j=W.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:j,at:S,ok:M.ok})}}catch(S){this.log(`[${e.agentId}] task history persist failed: ${S?.message}`)}this.messageQueue.markDone(e.agentId,u,l).then(S=>{if(S.length===0)return;this.log(`[${e.agentId}] flushing ${S.length} queued message(s) after task=${p.id} chat=${u}:${l} at=${new Date().toISOString()}`);let M=Date.now();Y().emit("task:queue-flushed",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,count:S.length,at:new Date().toISOString()});let W=()=>Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:M,at:new Date().toISOString()});for(let j of S){let ee=j.originalContext||{channel:j.channel,sender:j.sender,chatId:j.chatId};this.execute({message:j.text,agentId:e.agentId,context:ee,queuedAt:j.queuedAt??j.timestamp}).then(te=>(He(te.error)||W(),this.postQueuedResponseToChannel(e.agentId,ee,te)),te=>{throw W(),te}).catch(te=>{this.log(`[${e.agentId}] queued message failed: ${te.message}`)})}}).catch(S=>{Y().emit("task:queue-ended",{agentId:e.agentId,channel:u,chatId:l,flushedAt:Date.now(),at:new Date().toISOString()}),this.log(`[${e.agentId}] queue flush failed: ${S.message}`)})};this.runReleases.set(p.id,_n),this.messageQueue.markRunning(e.agentId,u,l),this.log(`[${e.agentId}] executing task (${d.activeTasks}/${d.def.maxConcurrent}) ${w()}`);let y=e.context?.channel||"api",{evaluateRequest:ki,selectRequestContext:Ai}=await import("./request-planner-CRG3OGGG.js"),Rn=K("request-gate",()=>ki(e.message,e.agentId,y),()=>({active:!1,preprocess:!1})),Dt=!1;Rn.then(()=>{Dt=!0},()=>{Dt=!0});let A=l,Ot=e.context?.sender||"User",se=d.def.tier==="codex-cli",Ee=Fo(this.config.session,y,d.def.tier),Ze=Ho(this.config.session),De=Ee==="lean"&&Ze.contextOnDemand;e.freshSession&&(this.sessions.clearSession(e.agentId,y,A),this.log(`[${e.agentId}] freshSession=true \u2192 cleared session history for ${y}:${A}`),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:A,reason:"stale",at:new Date().toISOString()})),e.freshSession||await K("seed-history",()=>this.sessions.seedIfEmpty(e.agentId,y,A,e.seedHistory),()=>{});let $i=[...this.sessions.getSession(e.agentId,y,A).messages].reverse().find(g=>g.role==="agent")?.content;ui({agent:e.agentId,channel:y,chatId:A,message:e.message,previousReply:$i,taskId:E}),this.sessions.addUserMessage(e.agentId,y,A,Ot,e.message);let En=Date.now();Y().emit("task:started",{agentId:e.agentId,channel:y,chatId:A,messagePreview:(e.message||"").slice(0,200),fullMessage:e.message||"",requestText:e.requestText,at:new Date(En).toISOString(),taskId:E,resumeOrigin:no(e.origin??{kind:"direct",context:e.context,model:e.model,autonomy:e.autonomy}),resumeAttempt:e.resumeAttempt??0,resumedFrom:e.resumedFrom,sender:Jt(e.context),...I?{person:I}:{},humanRoot:Gt(e.context),pickup:us(e.context),operator:ls(e.context)});let V,Nt,Dn=this.classifier;if(Dn&&y!=="a2a"&&!se){x("classify");let g=Date.now();Nt=Dn.classify({text:e.message,channel:y,sender:e.context?.sender,chatId:A,agentId:e.agentId}).then(m=>{V=m||void 0,V?.path?.length&&(p.intentPath=V.path.slice()),P("classify",g,"ok")},m=>{this.log(`[classifier] classify failed for ${e.agentId}: ${m?.message||m}`),P("classify",g,"error")})}let On=async g=>{if(!Nt)return;let m;await Promise.race([Nt,new Promise(S=>{m=setTimeout(S,g),m.unref?.()})]),m&&clearTimeout(m)};await On(ou);let Oe=this.config.workflows?.matching,Se;if(this.config.workflows?.enabled&&Oe?.enabled&&!i)try{let g=new Ys({baseDir:J(process.cwd(),this.config.workflows.dir)}),m=Vs({agentId:e.agentId,channel:y,message:e.message,intentPath:V?.path},g.list());m&&m.confidence>=Oe.suggestThreshold&&(this.log(`[${e.agentId}] workflow match ${m.workflow.id} confidence=${m.confidence.toFixed(2)} mode=${Oe.mode} reasons=${m.reasons.join(",")||"n/a"}`),Oe.mode==="auto"&&m.confidence>=Oe.autoRunThreshold&&(this.workflowAutoRunner?Se={workflowId:m.workflow.id,confidence:m.confidence}:this.log(`[${e.agentId}] workflow auto-run requested but no runner wired; falling back to agent`)))}catch(g){this.log(`[${e.agentId}] workflow matcher failed (non-fatal): ${g?.message||g}`)}let Ci=this.wikiHub.getAgentWiki(e.agentId),Nn=this.memoryStore.findRelevant(e.message,e.agentId,se?3:8),Ln=this.memoryStore.buildContext(Nn),Fn=this.memoryStore.contextFacts(Nn),Mi=this.patternStore.findRelevant(e.message,e.agentId,5),Pi=this.patternStore.buildContext(Mi),Hn="";if(!se)try{let{loadLocalSkills:g,getAutoInjectSkills:m}=await import("./loader-YFVSSYSL.js"),S=await v("skills",()=>g(d.def.workspace)),M=e.personLimits?.skills??[],W=M.length?S.filter(j=>!M.some(ee=>Le(ee,j.frontmatter.name))):S;Hn=m(W,e.message)}catch{}let B=d.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,y,A):d.def.tier==="codex-cli"?this.sessions.getCodexSessionId(e.agentId,y,A):d.def.tier==="opencode"?this.sessions.getOpenCodeSessionId(e.agentId,y,A):void 0;if(B&&this.sessions.isSessionStale(e.agentId,y,A)&&(this.log(`[${e.agentId}] session stale for ${y}:${A}, starting fresh`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,B,y,A,"stale"),this.sessions.clearClaudeSessionId(e.agentId,y,A),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:A,reason:"stale",at:new Date().toISOString()}),B=void 0),B&&this.sessions.shouldRotateByTierTwo(e.agentId,y,A)){let g=this.sessions.getLastTurnContextTokens(e.agentId,y,A);this.log(`[${e.agentId}] tier-2 rotation for ${y}:${A} (last turn context: ${g} tokens \u2265 ${this.sessions.getTierTwoThresholdTokens(y)})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,B,y,A,"tier-2"),this.sessions.clearClaudeSessionId(e.agentId,y,A),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:A,reason:"tier-2",lastTurnInputTokens:g,at:new Date().toISOString()}),B=void 0}if(B&&this.sessions.shouldRotateByTurns(e.agentId,y,A)){let g=this.sessions.getTurnCount(e.agentId,y,A);this.log(`[${e.agentId}] max-turns rotation for ${y}:${A} (${g} turns \u2265 ${this.sessions.getMaxTurnsPerSession()})`),d.def.tier==="claude-code"&&this.captureRotationMemoAsync(e.agentId,d.def,B,y,A,"max-turns"),this.sessions.clearClaudeSessionId(e.agentId,y,A),Y().emit("session:rotated",{agentId:e.agentId,channel:y,chatId:A,reason:"max-turns",at:new Date().toISOString()}),B=void 0}if(B&&d.def.tier==="claude-code"){let g=B;await K("rotate",()=>this.maybeRotateForContinuity(e,d,y,A,g),()=>!1)&&(B=void 0)}try{let g=await v("compact",()=>this.sessions.compactIfNeeded(e.agentId,y,A,this.memoryStore));if(g.compacted){let m=g.qualityScore??"?",S=g.lostEntities?.length??0;if(this.log(`[${e.agentId}] session compacted for ${y}:${A} (quality: ${m}%, ${S} entities lost)`),g.lostEntities?.length&&this.log(`[${e.agentId}] lost entities: ${g.lostEntities.slice(0,5).join(", ")}`),g.drift){let M=g.drift;this.log(`[${e.agentId}] DRIFT DETECTED: score=${M.overallScore} (lexicon=${M.lexiconDecay}, tools=${M.toolShift}, semantic=${M.semanticDrift})`),M.lostWords.length&&this.log(`[${e.agentId}] lost domain words: ${M.lostWords.slice(0,5).join(", ")}`)}}}catch(g){this.log(`[${e.agentId}] compaction failed (non-fatal): ${g.message}`)}let _i=process.env.AGENTX_CONTEXT_SURGERY==="1",Ri=se?{maxMessages:8,maxChars:2400}:_i&&wi(y,d.def.tier)?{maxMessages:6,maxChars:1800}:void 0,Ei=!B&&!se?bu(Ci,e.agentId):void 0,et=!B&&!De?this.sessions.buildHistoryContext(e.agentId,y,A,Ri):void 0,Di=B?void 0:this.sessions.getRotationMemo(e.agentId,y,A)??void 0,Bn,jn=[];if(this.config.procedures?.injection?.enabled&&!B&&!se)try{let g=new ze({baseDir:J(process.cwd(),this.config.procedures.dir)}),m=In(e.message,g.list(),{limit:this.config.procedures.injection.maxProcedures,minScore:this.config.procedures.injection.minScore});if(m.length>0){Bn=Tn(m),jn=m.map(S=>({id:S.procedure.meta.id,title:S.procedure.meta.title}));for(let S of m)this.log(`[${e.agentId}] procedure match ${S.procedure.meta.id} score=${S.score.toFixed(2)} (${S.reasons.join(",")})`)}}catch(g){this.log(`[${e.agentId}] procedure matcher failed (non-fatal): ${g?.message||g}`)}if(he&&he.cat)try{let m=this.sessions.getSession(e.agentId,y,A).messages,S=m[0],M=m[m.length-1],W=et===void 0?`resume=${B?B.slice(0,8):"?"} (no rebuild)`:`fresh history=${et.length}c/${et.split(`
|
|
138
138
|
`).length}L`,j=`[${e.agentId}] ${y}:${A} ${W} | session.messages=${m.length}`+(m.length>0?` first=${S.timestamp.slice(11,19)}(${S.role}:${(S.content||"").slice(0,40).replace(/\n/g," ")}) last=${M.timestamp.slice(11,19)}(${M.role}:${(M.content||"").slice(0,40).replace(/\n/g," ")})`:"");he.cat("context",j)}catch(g){he.cat("context",`[${e.agentId}] context-diag error: ${g?.message??g}`)}let Un;if(d.def.contextReferences&&!B)try{let g=d.def.workspace,m=this.referencesCache.get(g);if(!m){let[M,W]=await v("references",()=>Promise.all([Xt(d.def.workspace),Yt(d.def.workspace)]));if(M.byId.size===0&&W.recipes.length===0){let[j,ee]=await v("references",()=>Promise.all([Xt(process.cwd()),Yt(process.cwd())]));m={refs:j,recipes:ee}}else m={refs:M,recipes:W};this.referencesCache.set(g,m)}let S=Us({agentId:e.agentId,intentTags:V?.path,message:e.message},m.recipes,m.refs);S.cards.length>0&&(Un=Bs(S.cards,500*4)),S.unresolvedIds.length>0&&this.log(`[${e.agentId}] references: unresolved ids: ${S.unresolvedIds.join(", ")}`)}catch(g){this.log(`[${e.agentId}] references resolver failed (non-fatal): ${g?.message||g}`)}let Wn=De?"":this.sessions.getCrossSessionSummary(e.agentId,y,A,e.message),qn,tt=Yr(e.message);if(tt)try{let g=this.sessions.recallTurns({agentId:e.agentId,channel:y,chatId:A,lookbackDays:tt.lookbackDays,limit:12});if(g.turns.length>0){let m=[`[Long-memory recall \u2014 last ${tt.lookbackDays}d on this chat (cue-triggered)]`],S=[...g.turns].sort((M,W)=>M.ts.localeCompare(W.ts));for(let M of S){let W=M.ts.slice(11,16)+" "+M.day,j=M.role==="user"?M.senderName||"User":M.senderName||"Agent";m.push(`${W} ${j}: ${M.content}`)}g.hasMore&&m.push(`[\u2026${g.totalScanned-g.turns.length}+ older turns available \u2014 call /recall with before=${g.oldestTs} to walk further back]`),m.push("[End of long-memory recall \u2014 respond to the latest message above]"),qn=m.join(`
|
|
139
139
|
`),this.log(`[${e.agentId}] long-memory recall fired: lookback=${tt.lookbackDays}d, turns=${g.turns.length}, scanned=${g.totalScanned}`)}}catch(g){this.log(`[${e.agentId}] long-memory recall failed (non-fatal): ${g.message}`)}let Oi=se?"layered":e.contextStrategy??d.def.contextStrategy??this.config.session.contextStrategy??"layered",Gn,Kn,Jn=!1;Dt||x("request-gate");let me=await Rn;if(me.arm==="holdout"&&this.log(`[${e.agentId}] request-gate holdout: skipping Jev preprocessing for this turn`),Oi==="planner"&&!me.active&&!De&&y!=="voice"&&y!=="desktop"){try{let{planContext:g}=await import("./context-planner-BKHPKDX5.js"),m=await v("plan-context",()=>g({agentId:e.agentId,channel:y,chatId:A,message:e.message,sessions:this.sessions,memoryStore:this.memoryStore}));m?(Jn=!0,Gn=m.sessionHistory,Ln=m.memoryContext,Fn=m.memoryFacts,Wn=m.crossChatContext,Kn=m.debug,this.log(`[${e.agentId}] planner: turns=${m.debug.recentTurns}, mem=${m.debug.memoryIncluded?"yes":"no"}, xchat=${m.debug.crossChatIncluded?"yes":"no"} (${m.debug.planLatencyMs}ms) \u2014 ${m.debug.reasoning??""}`)):this.log(`[${e.agentId}] planner returned null \u2014 falling back to layered (keeping --resume for continuity)`)}catch(g){this.log(`[${e.agentId}] planner failed (non-fatal): ${g.message} \u2014 falling back to layered (keeping --resume for continuity)`)}Jn&&B&&(this.sessions.clearClaudeSessionId(e.agentId,y,A),B=void 0)}let Lt=`${e.agentId}:${y}:${A}`,nt=ks(e.message);nt&&(nt==="default"?(this.activeSouls.delete(Lt),this.log(`[${e.agentId}] Soul reset to default`)):(this.activeSouls.set(Lt,nt),this.log(`[${e.agentId}] Soul switched to: ${nt}`)));let Ni=this.activeSouls.get(Lt),Li=Ts(d.def.workspace,Ni),Fi=vs(Li),Hi=this.agentMemory.indexMarkdown(e.agentId,this.config.session.memoryIndexMaxChars),Bi=gu(d.def.tier),ji=Tu(d.def.richMessages,y),Ui=d.def.tier==="claude-code"&&(Ee!=="lean"||Bo(Ze)),Qn="";if(d.def.workspace&&!Ui){let g=J(d.def.workspace,"CLAUDE.md");if(ne(g))try{let m=Ye(g,"utf-8");Qn=`[Project CLAUDE.md]
|
|
140
140
|
${m.length>4e3?m.slice(0,4e3)+`
|
|
@@ -146,9 +146,9 @@ ${te}`),m+=te.length}catch{}}}let Wi=Ft.length>0?Ft.join(`
|
|
|
146
146
|
|
|
147
147
|
`):"",Ht=[d.def.systemPrompt||"",Bi,ji,Qn,Wi,Fi||"",Hi||""].filter(g=>g.trim().length>0).join(`
|
|
148
148
|
|
|
149
|
-
`)||void 0,Bt={channel:y,chatId:A,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:Ot,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||De||wi(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:se?void 0:Pi||void 0,procedureContext:Bn,references:Un,skillInjection:Hn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Gn??et,memoryContext:Ln||void 0,crossChatContext:Wn||void 0,longMemoryRecall:qn||void 0,contextOnDemand:De&&!B?Go(y,A):void 0,wikiContext:Ei,handoverNote:this.buildHandoverNote(e.agentId,y,A),rotationMemo:Di,eventDigest:B?void 0:wu(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=er(y,!B,d.def.richMessages);return g?xu(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},rt=e.model?void 0:xs({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!B,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,y,A)});rt?.downgraded&&this.log(`[${e.agentId}] ${rt.reason}`);let zn=bs(d.def.tier,this.config.decisions.routing),Xn=rt?.downgraded?Promise.resolve(rt.model):!e.model&&zn&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-
|
|
149
|
+
`)||void 0,Bt={channel:y,chatId:A,channelScope:e.context?.group?"group":y==="gitlab"?"project":"personal",groupName:e.context?.group,agentId:e.agentId,agentName:d.def.name,agentHandle:this.getChannelHandle(e.agentId,y),systemPrompt:d.def.systemPrompt,sender:Ot,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,landscape:se||De||wi(y,d.def.tier)?void 0:this.landscape?.getForAgent(e.agentId),channelMeta:e.context?.channelMeta,mediaPath:e.context?.mediaPath,mediaType:e.context?.mediaType,replyToText:e.context?.replyToText,patternContext:se?void 0:Pi||void 0,procedureContext:Bn,references:Un,skillInjection:Hn||void 0,groupHistory:(e.context?.group,void 0),sessionHistory:Gn??et,memoryContext:Ln||void 0,crossChatContext:Wn||void 0,longMemoryRecall:qn||void 0,contextOnDemand:De&&!B?Go(y,A):void 0,wikiContext:Ei,handoverNote:this.buildHandoverNote(e.agentId,y,A),rotationMemo:Di,eventDigest:B?void 0:wu(e.agentId,this.config.agents[e.agentId]?.subscriptions??d.def.subscriptions),attachHint:(()=>{let g=er(y,!B,d.def.richMessages);return g?xu(d.def.workspace,g):void 0})(),intent:V?{path:V.path,pathLabel:V.pathLabel,pathId:V.pathId,axes:V.axes,leaf:V.leaf,status:V.status}:void 0,message:e.message},rt=e.model?void 0:xs({tier:d.def.tier,channel:y,eventActions:e.context?.channelMeta?.eventActions,triage:this.config.session.triage,isFollowUp:!!B,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,y,A)});rt?.downgraded&&this.log(`[${e.agentId}] ${rt.reason}`);let zn=bs(d.def.tier,this.config.decisions.routing),Xn=rt?.downgraded?Promise.resolve(rt.model):!e.model&&zn&&(!me.active||me.preprocess)?(async()=>{try{let{routeTaskModel:g}=await import("./routing-G33LLOTF.js"),m=await v("route-model",()=>g({message:e.message,agent:e.agentId,channel:y,isFollowUp:!!B,sessionIdleMs:this.sessions.sessionIdleMs(e.agentId,y,A),cheapModel:zn}));if(m.downgraded)return this.log(`[${e.agentId}] ${m.reason}`),m.model}catch{}})():Promise.resolve(void 0),Yn=!1;Xn.then(()=>{Yn=!0});let ot=me.active&&me.preprocess?await K("select-context",()=>Ai(Bt),()=>({input:Bt,excluded:[]})):{input:Bt,excluded:[]};ot.excluded.length&&this.log(`[${e.agentId}] request-context excluded: ${ot.excluded.join(", ")}`);let it=to(ot.input,se?{totalBudget:1800,layerBudgets:{channel:180,scope:100,identity:120,references:250,intent:80,artifacts:250,memory:250,history:450,"cross-chat":200,"long-memory":350,handover:120}}:void 0),qi=Os(it,{memory:Fn,procedures:jn,wikiContext:ot.input.wikiContext}),jt=(it?.length??0)+(Ht?.length??0)+(e.message?.length??0),at={history:it?.length??0,sysPrompt:Ht?.length??0,message:e.message?.length??0},Vn=Po(e.agentId,y,A);_o(Vn,jt,at);let Zn=Ro(Vn);Zn&&this.log(`[${e.agentId}] ${Zn}`),jt>16e3&&this.log(`[${e.agentId}] large context for ${y}:${A}: ${jt} bytes (history=${at.history}, sysPrompt=${at.sysPrompt}, message=${at.message})`),Yn||x("route-model");let es=await Xn,ts=d.def.tier!=="claude-code"?void 0:Ee==="lean"?Uo(d.def.workspace,Ze,void 0,y):qo(d.def.workspace);Ee==="lean"&&!B&&this.log(`[${e.agentId}] session profile for ${y}: ${Ko(Ee,Ze,y)}`);let ns=d.def.tier==="claude-code"&&!B?lr({message:e.message??"",agent:e.agentId,channel:y,agentPrompt:d.def.systemPrompt??null,taskId:E},g=>this.log(g)):void 0,Gi={...e,systemPromptAppend:Ht,...ts?{claudeArgs:ts}:{},...es?{model:es}:{}},re,ss=!1,rs=ai({agent:e.agentId,request:e.message,taskId:E,budgetMinutes:d.def.maxExecutionMinutes??20}),Ki=U;U=g=>{rs.observe(g),Ki?.(g)};try{let g=this.workflowAutoRunner;if(Se&&g){let F=Se;try{let Q=await v("workflow-auto-run",()=>g({workflowId:F.workflowId,agentId:e.agentId,channel:y,chatId:A,message:e.message,payload:{message:e.message,agentId:e.agentId,channel:y,chatId:A,senderId:e.context?.senderId,senderUsername:e.context?.senderUsername,intentPath:V?.path,matchedWorkflowId:F.workflowId,matchConfidence:F.confidence}}));return this.log(`[${e.agentId}] workflow auto-run started ${Se.workflowId} run=${Q.runId||"?"}; agent execution skipped \u2014 workflow owns the reply`),re={content:"",duration:0,metadata:{handledByWorkflow:Se.workflowId,workflowRunId:Q.runId,workflowMatchConfidence:Se.confidence}},re}catch(Q){this.log(`[${e.agentId}] workflow auto-run failed; falling back to agent: ${Q?.message||Q}`)}}let m=()=>{if(d.def.tier!=="claude-code")return null;x("dispatch-gate");let F=d.def.persistentProcess?ht():null,Q=F!=null&&F.hasLive({agentId:e.agentId,channel:y,chatId:A}),ce=!!B||Q,oe=[mo(ce),Co(ce,void 0,e.model||d.def.model)].find(ct=>ct&&ct.abort);if(oe){this.log(`[${e.agentId}] skipping cold dispatch \u2014 ${oe.reason}`);let ct={content:"",error:oe.message,duration:0};if(!t){b.buffer=`[error] ${oe.message}`;for(let Qi of b.subscribers)try{Qi(b.buffer)}catch{}}return ct}xo();let Ne=Mo();return Ne&&this.log(`[${e.agentId}] ${Ne}`),null},S=this.planCloudSession(d.def,e);if(S.route==="local"){let F=m();if(F)return d.errors++,re=F,F}let M=d.def.tier==="claude-code",W=M?t:(F,Q)=>{F&&R(F),t&&t(F,Q)},j=!1,ee=M?s:F=>{F&&(j?R(F):(R(`\u{1F4AD} ${F}`),j=!0)),s&&s(F)},te=()=>{j&&(R(`
|
|
150
150
|
`),j=!1)},Ji=M?W:W?(F,Q)=>{te(),W(F,Q)}:void 0,C=await v("agent",async()=>{if(S.route!=="local"){let F=await this.runCloudSession(d.def,e,S,E);if(F)return F;let Q=m();if(Q)return Q}return Qr(d.def,Gi,this.providers,Ji,it,B,U,k.signal,ee)},fu);if(!C.error){let F=Su(d.def.toolUseRequired,O);if(F){let Q=Array.from(O.entries()).map(([ce,dt])=>`${ce}=${dt}`).join(", ")||"none";C.error=`tool_required_not_called: ${F} (invoked: ${Q})`,C.content="",this.log(`[${e.agentId}] tool-use contract violation \u2014 required ${F}, observed ${Q}`)}}ns&&gr(ns,{toolUses:O,eventsSeen:N,error:C.error,agentId:e.agentId},F=>this.log(F));let Ut=this.interruptedRuns.get(p.id);Ut&&(C.content="",C.error=Ut,C.errorKind="interrupted"),re=C;let de=C.usage?Es(C.usage):void 0;if(ss=!0,Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:y,chatId:A,durationMs:Date.now()-En,error:C.error||void 0,errorKind:C.error?C.errorKind:void 0,interrupted:Ut?!0:void 0,inputTokens:de?.inputTokens,outputTokens:de?.outputTokens,cacheReadTokens:de?.cacheReadTokens,cacheCreateTokens:de?.cacheCreateTokens,tier2InputTokens:de?.tier2InputTokens,tier2OutputTokens:de?.tier2OutputTokens,tier2CacheReadTokens:de?.tier2CacheReadTokens,tier2CacheCreateTokens:de?.tier2CacheCreateTokens,resumed:!!B,resumeSessionId:B||void 0,jevArm:me.arm,numTurns:C.numTurns,injectedContext:qi,finalResponse:C.content||void 0,billedModel:C.billedModel||d.def.model||void 0,at:new Date().toISOString()}),!t&&(C.content||C.error)){let F=C.error?`[error] ${C.error}`:C.content;b.buffer=F;for(let Q of b.subscribers)try{Q(F)}catch{}}if(C.error)d.errors++,this.log(`[${e.agentId}] error: ${C.error}`);else{if(this.sessions.addAgentMessage(e.agentId,y,A,C.content),ci({agent:e.agentId,channel:y,chatId:A,request:e.message,reply:C.content,taskId:E}),C.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,y,A,C.claudeSessionId),C.codexSessionId&&this.sessions.setCodexSessionId(e.agentId,y,A,C.codexSessionId),C.opencodeSessionId&&this.sessions.setOpenCodeSessionId(e.agentId,y,A,C.opencodeSessionId),(C.claudeSessionId||C.codexSessionId||C.opencodeSessionId)&&C.usage&&this.sessions.recordTurnUsage(e.agentId,y,A,C.usage,C.contextTokens),C.usage){let oe=C.contextTokens,Ne=(C.usage.inputTokens||0)+(C.usage.cacheReadTokens||0)+(C.usage.cacheCreateTokens||0);(oe??Ne)>=this.sessions.getTierTwoThresholdTokens(y)&&this.log(`[${e.agentId}] TIER-2 HIT on ${y}:${A}: context=${oe??"n/a"} tokens (cumulative turn total=${Ne}) \u2014 next turn will rotate`)}if(Cs({channel:y,content:`User: ${e.message}`,responseLength:C.content.length}).capture){await On(iu);try{let oe=`${e.agentId}-${Date.now().toString(36)}`;this.wikiHub.getSharedStore().addEntry({id:oe,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:y,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
|
|
151
151
|
|
|
152
152
|
Agent: ${C.content}`,meta:yu(V,e.context)})}catch{}Ms(e.agentId,e.message,C.content,{channel:y,chatId:A,sender:Ot},this.memoryStore).catch(()=>{}),co(e.agentId,e.message,C.content,{channel:y,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=C.billedModel||e.model||d.def.model,ce=e.context?.channel,dt=ce&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${ce}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,C.duration||0,C.usage,e.message.length,C.content.length,!1,Q,ce,dt),this.log(`[${e.agentId}] completed in ${C.duration}ms`+(C.tokensUsed?` (${C.tokensUsed} tokens)`:"")+` ${w()}`)}return C}catch(g){d.errors++,this.log(`[${e.agentId}] unexpected error: ${g.message}`);let m=pt(g.message);return re={content:"",error:ft(m),errorKind:m.kind},re}finally{if(rs.stop(),!ss)try{Y().emit("task:completed",{taskId:E,agentId:e.agentId,channel:u,chatId:l,durationMs:Date.now()-p.startedAt.getTime(),error:re?.error||(k.signal.aborted?Xe(k.signal).message:"run ended before completion"),errorKind:re?.errorKind,interrupted:this.interruptedRuns.has(p.id)?!0:void 0,at:new Date().toISOString()})}catch{}_n(re)}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}runningAgentDrainSeconds(){let e=[];for(let t of this.agents.values())t.activeTasks>0&&e.push(t.def.drainTimeoutSeconds);return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),s=J(process.cwd(),Re,this.safe(e.agentId),t);ne(s)||au(s,{recursive:!0});let r=J(s,`${this.safe(e.id)}.json`);cu(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let s=Date.now(),r=this.sparklineCache.get(e);if(r&&s-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=s-t*36e5,a=J(process.cwd(),Re,this.safe(e));if(!ne(a))return this.sparklineCache.set(e,{hourly:o,at:s}),o;let c=new Date(s).toISOString().slice(0,10),d=new Date(s-864e5).toISOString().slice(0,10);new Date(s).setUTCHours(0,0,0,0);for(let l of[d,c]){let f=J(a,l);if(ne(f))try{for(let h of ae(f)){if(!h.endsWith(".json"))continue;let p=h.split("-")[0],I=parseInt(p,10);if(!Number.isFinite(I)||I<i||I>s)continue;let k=Math.floor((s-I)/36e5),b=t-1-k;b>=0&&b<t&&o[b]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:s}),o}hydrateLastSummariesFromDisk(){let e=J(process.cwd(),Re);if(!ne(e))return 0;let t=0;for(let s of ae(e)){let r=J(e,s),o;try{o=ae(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=J(r,i),c;try{c=ae(a).filter(d=>d.endsWith(".json")).sort().reverse()}catch{continue}for(let d of c)try{let u=JSON.parse(Ye(J(a,d),"utf-8")),l=(u.responseText||u.error||"").trim();if(!l)continue;let f=l.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(u.agentId,{text:f,at:new Date(u.endedAt),ok:u.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=hu){let t=J(process.cwd(),Re);if(!ne(t))return 0;let s=Date.now()-e*24*60*60*1e3,r=0;for(let o of ae(t)){let i=J(t,o),a;try{a=ae(i)}catch{continue}for(let c of a){let d=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(d)||d>=s))try{du(J(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let s=J(process.cwd(),Re,this.safe(e));if(!ne(s))return[];let r=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=J(s,i),c;try{c=ae(a).filter(d=>d.endsWith(".json"))}catch{continue}c.sort().reverse();for(let d of c){if(o.length>=t)break;try{let u=JSON.parse(Ye(J(a,d),"utf-8")),{transcript:l,responseText:f,...h}=u;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let s=J(process.cwd(),Re,this.safe(e));if(!ne(s))return null;let r=this.safe(t),o=ae(s).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=J(s,i,`${r}.json`);if(ne(a))try{return JSON.parse(Ye(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,s){let r=Xs();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||s.errorKind==="cancelled"||s.errorKind==="interrupted"||He(s.error))return;let a=s.error?`Error: ${s.error}`:(s.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let s=t.runningTasks.find(r=>r.id===e);if(s)return{agentId:t.id,channel:s.channel,chatId:s.chatId}}return null}findRunningTurn(e,t={}){let s=this.agents.get(e);if(!s)return null;let r;if(t.taskId)r=s.runningTasks.find(i=>i.id===t.taskId);else if(t.channel&&t.chatId){let i=s.runningTasks.filter(a=>{let c=Tt(a);return c.channel===t.channel&&c.chatId===t.chatId});r=i.length===1?i[0]:void 0}if(!r)return null;let o=this.runningContexts.get(r.id);return o?{taskId:r.id,context:o}:null}slotHolders(e){let t=this.agents.get(e);return t?{full:t.activeTasks>=t.def.maxConcurrent,runIds:t.runningTasks.map(s=>s.id)}:null}isChatBusy(e,t,s){return this.messageQueue.isBusy(e,t,s)}runningIntentPath(e,t,s){let r=this.agents.get(e);if(!r)return;let o;for(let i of r.runningTasks)i.channel!==t||i.chatId!==s||(!o||i.startedAt>o.startedAt)&&(o=i);return o?.intentPath?.slice()}cancelRunningTask(e,t="operator"){let s=this.taskAborts.get(e);if(!s)return null;try{s.controller.abort(new Error(t))}catch{}return this.log(`[${s.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:s.agentId,channel:s.channel,chatId:s.chatId}}interruptRunning(e){let t=0;for(let[s,r]of this.taskAborts){this.interruptedRuns.set(s,e);try{r.controller.abort(new Error(e))}catch{}this.log(`[${r.agentId}] task ${s} interrupted \u2014 ${e}`),t++}return t}cancelChatTasks(e,t,s,r="operator"){let o=0;for(let[i,a]of this.taskAborts)a.agentId===e&&a.channel===t&&a.chatId===s&&this.cancelRunningTask(i,r)&&o++;return o}queueFollowUp(e,t,s,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:d}=o,u=o.controller.signal.aborted,l=!1;u&&d&&(l=this.sessions.removeLastUserMessageIfMatches(i,a,c,d));let f=Date.now();this.messageQueue.enqueue(i,a,c,{text:t,sender:s,timestamp:f,channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:s}});let h=this.messageQueue.pendingCount(i,a,c);Y().emit("task:queued",{agentId:i,channel:a,chatId:c,at:new Date(f).toISOString(),sender:{name:s},humanRoot:!1,person:gs(this.config.people)?.id??null,messagePreview:t.slice(0,200),queuedAt:f});let p=!1;if(r.replace){let I=r.reason||`replaced by follow-up from ${s}`;try{o.controller.abort(new Error(I))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${I}`),p=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${h}${l?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:p,edited:l,pending:h}}async continueFinishedTask(e,t,s,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(d=>{let u=!1,l=f=>{u||(u=!0,d(f))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:s,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:f=>l({ok:!0,agentId:e,channel:a,chatId:c,taskId:f,queued:!1})}).then(f=>{He(f.error)?l({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):f.error?l({ok:!1,status:500,error:f.error||"run did not start"}):l({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:f.viaAttachedSession?"attached":"other"})}).catch(f=>l({ok:!1,status:500,error:f?.message??String(f)}))})}subscribeToTaskOutput(e,t){let s=this.taskOutputs.get(e);return s?s.done?{initial:s.buffer,done:!0,unsubscribe:()=>{}}:(s.subscribers.add(t),{initial:s.buffer,done:!1,unsubscribe:()=>{s.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};function Tu(n,e){return n===!1||e!=="telegram"&&e!=="whatsapp"&&e!=="app"?"":["[Rich replies]","On this chat channel you may add buttons, a poll, or media to a reply by appending ONE fenced block at the very end:","```agentx:ui",'{ "buttons": [{"label": "Open docs", "url": "https://..."}], "poll": {"question": "Ship it?", "options": ["Yes", "No"]}, "media": {"type": "image", "url": "https://..."} }',"```","All fields are optional; include only what helps. Buttons must be https URLs (tappable callback actions aren't supported yet). Use this sparingly \u2014 only when a link, choice, or image genuinely improves the reply. The block is stripped from the visible text.",...e==="app"?[`In this phone app you may also offer up to 4 short answers the user can tap instead of typing: "quickReplies": ["Yes", "Not now"] (at most 40 characters each), or a button with a reply instead of a url: {"label": "Run the tests", "reply": "Please run the tests"}. A tap sends that text as the user's next message, nothing more. Offer them only when the user is likely to answer with one of them.`]:[]].join(`
|
|
153
153
|
`)}export{yr as a,Lu as b,br as c,la as d,xr as e,yt as f,Xu as g,el as h,tl as i,il as j,Tt as k,Ra as l,Gr as m,La as n,Fa as o,Ha as p,Qr as q,vt as r,kt as s,id as t,Dl as u,Ol as v,mn as w,Y as x,uo as y,hd as z,xd as A,po as B,Vl as C,fo as D,wo as E,vo as F,gg as G,ko as H,Ct as I,yg as J,wg as K,ze as L,kc as M,Ac as N,$c as O,Cc as P,Mc as Q,In as R,lu as S,gu as T,tf as U,nf as V,yu as W,wu as X,bu as Y,Mn as Z,xi as _,Si as $,Su as aa,Ii as ba,Ti as ca,Tu as da};
|
|
154
|
-
//# sourceMappingURL=chunk-
|
|
154
|
+
//# sourceMappingURL=chunk-PVQPXZHE.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-
|
|
1
|
+
import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7S5BAX.js";import{c as Ze}from"./chunk-SZDACK6O.js";import{b as ce}from"./chunk-AFRHKA7B.js";import{b as qe,e as Ye,f as Ge,i as Qe,k as Xe,l as et,q as rt}from"./chunk-B6OXEIOF.js";import{c as Ke,e as ze,f as Je}from"./chunk-KA2UIZXG.js";import{e as He,g as Ue,h as Be,i as de}from"./chunk-GQ76J72O.js";import{a as _e,b as oe,c as se,d as Le,e as ae}from"./chunk-QD6IICK7.js";import{y as Ce,z as hn}from"./chunk-NDPU6AX2.js";import{b as Me,f as mn}from"./chunk-72SZI2UW.js";import{c as We,d as je}from"./chunk-QOYAX2FT.js";import{f as ie,n as gn}from"./chunk-UIBUZ2N3.js";import{existsSync as yn,mkdirSync as it,readFileSync as wn,writeFileSync as kn,renameSync as bn}from"fs";import{resolve as ot,dirname as vn}from"path";var st=class{filePath;log;constructor(e={}){let t=e.baseDir??ot(process.cwd(),".agentx");this.filePath=ot(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),it(t,{recursive:!0})}key(e,t,n){return`${e}::${t}::${n||"-"}`}load(){if(!yn(this.filePath))return{version:1,overrides:{}};try{let e=wn(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){it(vn(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;kn(t,JSON.stringify(e,null,2)),bn(t,this.filePath)}get(e,t,n){let o=this.load().overrides[this.key(e,t,n)];if(o&&!(o.expiresAt&&Date.parse(o.expiresAt)<Date.now()))return o}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),n={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(n.channel,n.chatId,n.accountId)]=n,this.save(t),n}remove(e,t,n){let i=this.load(),o=this.key(e,t,n);return o in i.overrides?(delete i.overrides[o],this.save(i),!0):!1}consumeSummary(e,t,n){let i=this.load(),o=i.overrides[this.key(e,t,n)];if(!o||!o.summary||o.summaryConsumedAt)return;let s=o.summary;return o.summaryConsumedAt=new Date().toISOString(),this.save(i),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(n=>!n.expiresAt||Date.parse(n.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(n=>n.toAgent===e),outgoing:t.filter(n=>n.fromAgent===e)}}};import{readFileSync as ut,writeFileSync as le,appendFileSync as Rn,mkdirSync as $n,existsSync as pt,statSync as xn}from"fs";import{resolve as U}from"path";var at="[Agent Memory \u2014 persistent facts from past conversations]",Sn=2400;function dt(r,e){return r?`UNVERIFIED (${e===null?"age unknown":`${e}d old`}) `:""}function In(r,e=Date.now()){let t=ze(r,e),n=r.undated?"UNVERIFIED (never checked) ":dt(t,He(r.verifiedAt,e));return{line:`- [wiki ${r.id}] ${n}${r.subject} \xB7 ${r.attribute}: ${r.value} (${r.source}, checked ${r.verifiedAt.slice(0,10)} by ${r.verifiedBy})`,unverified:t}}function An(r,e){let n=!r.source.chatId.startsWith("-")&&/^\d+$/.test(r.source.chatId)?"DM":r.source.chatId,i=Be(r,e);return{line:`- [${r.category}] ${dt(i,Ue(r,e))}${r.content} (${n}, ${r.source.date})`,unverified:i}}function ct(r,e=[],t=Date.now()){let n=[],i=new Set,o=at.length,s=!1;for(let a of r){let d=e.length>0?Je(a.content,e):null,c,u,p=d&&Date.parse(a.createdAt)>Date.parse(d.verifiedAt)&&!a.content.toLowerCase().includes(d.value.toLowerCase());if(d&&!p){if(i.has(d.id))continue;i.add(d.id),c=In(d,t),u=d.id}else c=An(a,t),d&&(c.line+=` [differs from wiki ${d.id}]`);let f=c.unverified&&!s?de.length:0;if(o+f+c.line.length>Sn)break;n.push({fact:a,...c,...u?{wikiRef:u}:{}}),o+=f+c.line.length,f&&(s=!0)}return n}function lt(r){if(r.length===0)return"";let e=r.some(t=>t.unverified)?[de]:[];return[at,...e,...r.map(t=>t.line),"[End Memory]"].join(`
|
|
2
2
|
`)}var ft=200,Pn=7,gt=class{memoryDir;ledger;constructor(e=process.cwd()){this.memoryDir=U(e,".agentx/memory"),this.ledger=new Ke(U(e,".agentx/wiki")),pt(this.memoryDir)||$n(this.memoryDir,{recursive:!0})}filePath(e){return U(this.memoryDir,`${e}.jsonl`)}addMemory(e,t){if(t.category==="secret"||oe(t.content))return!1;let n=t.source.trust??_e(t.source.channel),i=t.review??Le(n),o={...t,source:{...t.source,trust:n},...i?{review:i}:{},id:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,createdAt:new Date().toISOString()};return Rn(this.filePath(e),JSON.stringify(o)+`
|
|
3
3
|
`),!0}parsedCache=new Map;getAll(e){let t=this.filePath(e);if(!pt(t))return[];try{let{mtimeMs:n,size:i}=xn(t),o=this.parsedCache.get(t);if(o&&o.mtimeMs===n&&o.size===i)return o.facts.slice();let a=ut(t,"utf-8").split(`
|
|
4
4
|
`).filter(d=>d.trim()).map(d=>{try{return JSON.parse(d)}catch{return null}}).filter(d=>d!==null);return this.parsedCache.set(t,{mtimeMs:n,size:i,facts:a}),a.slice()}catch{return[]}}findRelevant(e,t,n=8){let i=this.getAll(t).filter(ae);if(i.length===0)return[];let o=i.map(g=>`${g.keywords.join(" ")} ${g.content}`),s=U(this.memoryDir,`${t}_bm25_cache.json`),a=je(o,s),d=We(e,a),c=new Map(d.map(g=>[g.docIndex,g.score])),p=i.map((g,h)=>{let m=c.get(h)??0;return g.category==="commitment"&&(m+=1),{memory:g,score:m}}).filter(g=>g.score>0);if(p.length===0)return i.slice(-n);let f=p.sort((g,h)=>h.score-g.score).slice(0,n).map(g=>g.memory);if(f.length>0)try{this.recordAccess(t,f.map(g=>g.id))}catch{}return f}buildContext(e){return lt(this.contextLines(e))}contextFacts(e){return this.contextLines(e).map(t=>t.fact)}contextLines(e){let t=[];try{t=this.ledger.list()}catch{}return ct(e,t)}recordAccess(e,t){if(t.length===0)return;let n=this.getAll(e),i=new Set(t),o=!1;for(let s of n)if(i.has(s.id)){s.accessCount=(s.accessCount||0)+1,s.lastAccessed=new Date().toISOString();let a=s.intervalDays||1;s.intervalDays=Math.min(a*2,30),s.nextReview=new Date(Date.now()+s.intervalDays*864e5).toISOString(),o=!0}o&&le(this.filePath(e),n.map(s=>JSON.stringify(s)).join(`
|
|
@@ -25,4 +25,4 @@ import{b as tt,c as nt}from"./chunk-GLQLCBJS.js";import{a as Ve}from"./chunk-GV7
|
|
|
25
25
|
`).filter(Boolean),i=[];for(let o=n.length-1;o>=0&&i.length<t;o--)try{let s=JSON.parse(n[o]);(!e||s.person===e)&&i.push(s)}catch{}return i}load(){if(Oe(this.file))try{let e=JSON.parse(Ne(this.file,"utf-8"));if(e&&Array.isArray(e.devices))return e}catch{}return{devices:[]}}save(e){Gt(Qt(this.file),{recursive:!0});let t=`${this.file}.${process.pid}.${en(4).toString("hex")}.tmp`;Zt(t,JSON.stringify(e,null,2)+`
|
|
26
26
|
`,{encoding:"utf-8",mode:384}),Vt(t,this.file)}};import{extname as ui}from"path";var nn=/<agentx-artifact>([\s\S]*?)<\/agentx-artifact>/gi,rn=/<agentx-artifact>[\s\S]*$/i;function Ps(r,e=1/0,t=!1){let n=[],i=String(r??"");if(!/<agentx-artifact>/i.test(i))return{text:i,artifacts:n};let o=i.replace(nn,(s,a)=>{try{let d=JSON.parse(a.trim());if(d&&typeof d.filename=="string"&&typeof d.mime=="string"&&n.length<e){let c=d.mime,u=c.startsWith("image/")?"image":c==="application/pdf"?"pdf":c.startsWith("text/")?"text":"file";n.push({type:u,filename:d.filename,mime:c})}}catch{}return""});return{text:(t?o.replace(rn,""):o).trim(),artifacts:n}}function Ts(r,e=!1){let t=String(r??""),n=t;if(/<agentx-artifact>/i.test(t)){let i=t.replace(nn,(o,s)=>{try{let a=JSON.parse(s.trim());return a&&typeof a.filename=="string"?a.filename:""}catch{return""}});n=(e?i.replace(rn,""):i).trim()}return n.replace(/```[\s\S]*?```|`[^`\n]*`|!\[([^\]\n]*)\]\(([^)\s]+)\)/g,(i,o,s)=>o===void 0||s===void 0?i:`[${o||s}](${s})`)}var pi={".png":{mime:"image/png",kind:"image"},".jpg":{mime:"image/jpeg",kind:"image"},".jpeg":{mime:"image/jpeg",kind:"image"},".gif":{mime:"image/gif",kind:"image"},".webp":{mime:"image/webp",kind:"image"},".svg":{mime:"image/svg+xml",kind:"file"},".pdf":{mime:"application/pdf",kind:"file"},".txt":{mime:"text/plain; charset=utf-8",kind:"file"},".md":{mime:"text/markdown; charset=utf-8",kind:"file"},".csv":{mime:"text/csv; charset=utf-8",kind:"file"},".json":{mime:"application/json",kind:"file"},".mp3":{mime:"audio/mpeg",kind:"audio"},".m4a":{mime:"audio/mp4",kind:"audio"},".wav":{mime:"audio/wav",kind:"audio"},".mp4":{mime:"video/mp4",kind:"video"},".webm":{mime:"video/webm",kind:"video"}},Os={bytes:20*1024*1024,perMessage:20,pathChars:512};function Ns(r){return pi[ui(r).toLowerCase()]??null}var fi=["[Phone app: showing files]","To show the owner a file you created (a chart, a screenshot, a PDF, a recording), save or copy it into .agentx/outbox/ in your workspace and end your reply with one line per file:",'<agentx-artifact>{"filename":".agentx/outbox/<name.ext>","mime":"<mime/type>"}</agentx-artifact>',"Files outside your workspace (/tmp, your home folder) are refused. Outbox files are removed after 7 days.","The line is removed from the text. Images show in the reply, audio and video get a player, other files an Open link. Allowed: png, jpg, gif, webp, svg, pdf, txt, md, csv, json, mp3, m4a, wav, mp4, webm; up to 20 MB and 20 files per reply.","A picture already on the web can go inline as ."].join(`
|
|
27
27
|
`);function Ds(r,e,t){return r==="app"&&e&&t!==!1?fi:void 0}import{lstatSync as Ee,mkdirSync as gi,readdirSync as mi,realpathSync as De,unlinkSync as hi}from"fs";import{join as ne,resolve as on}from"path";var sn=".agentx/outbox",yi=7*24*60*60*1e3;function wi(r,e){try{let t=De(on(e,r)),n=ne(t,sn);return De(n)===n&&Ee(n).isDirectory()?n:null}catch{return null}}function js(r,e={}){let t=e.cwd??process.cwd();if(e.create!==!1)try{let i=De(on(t,r));Ee(ne(i,".agentx"),{throwIfNoEntry:!1})?.isSymbolicLink()||gi(ne(i,sn),{recursive:!0})}catch{return 0}let n=wi(r,t);return n?an(n,(e.now??Date.now())-(e.maxAgeMs??yi)):0}function an(r,e){let t=0;for(let n of mi(r)){let i=ne(r,n);try{let o=Ee(i);o.isDirectory()?t+=an(i,e):Math.max(o.mtimeMs,o.ctimeMs)<e&&(hi(i),t++)}catch{}}return t}export{st as a,gt as b,mt as c,Fi as d,Nn as e,Wi as f,$ as g,pe as h,v as i,B as j,Bn as k,he as l,we as m,be as n,xe as o,Hr as p,qr as q,Te as r,ar as s,ai as t,tn as u,Ps as v,Ts as w,Os as x,Ns as y,Ds as z,sn as A,js as B};
|
|
28
|
-
//# sourceMappingURL=chunk-
|
|
28
|
+
//# sourceMappingURL=chunk-RJBRYUKU.js.map
|