agentix-cli 0.80.1 → 0.81.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/apps/mac-voice/Sources/AgentXVoice/CallModel.swift +11 -0
- package/apps/mac-voice/Sources/AgentXVoice/Calls.swift +7 -4
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +15 -3
- package/dist/{App-KVH5POXZ.js → App-HF6W6CV2.js} +2 -2
- package/dist/{App-KVH5POXZ.js.map → App-HF6W6CV2.js.map} +1 -1
- package/dist/ChatApp-74VBWP7R.js +7 -0
- package/dist/{ChatApp-LD4TXJWP.js.map → ChatApp-74VBWP7R.js.map} +1 -1
- package/dist/{agent-FUMJM6OW.js → agent-75URYGWI.js} +2 -2
- package/dist/{board-dashboard-OS5J3F73.js → board-dashboard-TWEF5XVE.js} +186 -169
- package/dist/board-dashboard-TWEF5XVE.js.map +1 -0
- package/dist/{chunk-MYRSNJJ4.js → chunk-3FCYKGU6.js} +2 -2
- package/dist/{chunk-R42S57G6.js → chunk-4KJ3PCAI.js} +2 -2
- package/dist/{chunk-PE55MMLK.js → chunk-5GXCOHDM.js} +2 -2
- package/dist/{chunk-PE55MMLK.js.map → chunk-5GXCOHDM.js.map} +1 -1
- package/dist/{chunk-BJPIRNP6.js → chunk-74FSHUB3.js} +2 -2
- package/dist/{chunk-H7253EHW.js → chunk-ATXE3EMV.js} +2 -2
- package/dist/{chunk-TEFMZY6B.js → chunk-BB3ESU74.js} +2 -2
- package/dist/{chunk-XESESMKN.js → chunk-BDM4VTBR.js} +39 -39
- package/dist/{chunk-XESESMKN.js.map → chunk-BDM4VTBR.js.map} +1 -1
- package/dist/chunk-BYD5B3P3.js +9 -0
- package/dist/{chunk-Z3IP66SL.js.map → chunk-BYD5B3P3.js.map} +1 -1
- package/dist/chunk-ES7Z64Z5.js +22 -0
- package/dist/chunk-ES7Z64Z5.js.map +1 -0
- package/dist/{chunk-WP6KLXTP.js → chunk-GLQLCBJS.js} +4 -4
- package/dist/chunk-GLQLCBJS.js.map +1 -0
- package/dist/{chunk-UB63NQQL.js → chunk-GUAJNZIX.js} +2 -2
- package/dist/{chunk-UXSYVMPK.js → chunk-HUQRPEDP.js} +2 -2
- package/dist/chunk-JG3O5GL6.js +5 -0
- package/dist/{chunk-MOQNLS5Z.js.map → chunk-JG3O5GL6.js.map} +1 -1
- package/dist/chunk-JXF54PT7.js +2 -0
- package/dist/chunk-JXF54PT7.js.map +1 -0
- package/dist/chunk-LLNPKE7H.js +11 -0
- package/dist/chunk-LLNPKE7H.js.map +1 -0
- package/dist/chunk-LTHQXWZN.js +51 -0
- package/dist/chunk-LTHQXWZN.js.map +1 -0
- package/dist/{chunk-ZR3NZLJL.js → chunk-LUL4ILAQ.js} +2 -2
- package/dist/{chunk-N6EWZGIX.js → chunk-PN6XHTG5.js} +6 -6
- package/dist/{chunk-N6EWZGIX.js.map → chunk-PN6XHTG5.js.map} +1 -1
- package/dist/{chunk-BEHC3X42.js → chunk-R64DAHBH.js} +242 -211
- package/dist/chunk-R64DAHBH.js.map +1 -0
- package/dist/{chunk-7IGSJGXI.js → chunk-TW4L6RP2.js} +2 -2
- package/dist/chunk-UCKKAWLZ.js +2 -0
- package/dist/chunk-UCKKAWLZ.js.map +1 -0
- package/dist/chunk-V4GXHBOH.js +152 -0
- package/dist/chunk-V4GXHBOH.js.map +1 -0
- package/dist/{chunk-3UN6CXRL.js → chunk-VVW4JYV6.js} +24 -24
- package/dist/chunk-VVW4JYV6.js.map +1 -0
- package/dist/{chunk-BVZFYBBP.js → chunk-WWU2D65N.js} +2 -2
- package/dist/chunk-XF65CDNS.js +5 -0
- package/dist/{chunk-UR3ZIDMA.js.map → chunk-XF65CDNS.js.map} +1 -1
- package/dist/{chunk-YCI3KUYF.js → chunk-XQ7MVPWP.js} +7 -7
- package/dist/chunk-XQ7MVPWP.js.map +1 -0
- package/dist/{chunk-Z3XUGXPD.js → chunk-ZUAV3PTL.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-JDY2FZUF.js +2 -0
- package/dist/config-JCETBKWT.js +2 -0
- package/dist/config-mutator-YQWTY47O.js +2 -0
- package/dist/doctor-6EWW7NC2.js +2 -0
- package/dist/{facts-U7BUYRXN.js → facts-5T5GRUTG.js} +6 -6
- package/dist/{facts-U7BUYRXN.js.map → facts-5T5GRUTG.js.map} +1 -1
- package/dist/{failure-candidates-RIXA3Y6D.js → failure-candidates-PBPF45GN.js} +2 -2
- package/dist/index.d.ts +619 -499
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/{chunk-AF46YOLU.js → program-7UH4FCA3.js} +194 -184
- package/dist/program-7UH4FCA3.js.map +1 -0
- package/dist/promote-ZZWMGVO2.js +2 -0
- package/dist/query-OQBB7EFS.js +2 -0
- package/dist/registry-MDWD7EAO.js +2 -0
- package/dist/request-planner-HX44G2SX.js +2 -0
- package/dist/{request-planner-H74KHFGJ.js.map → request-planner-HX44G2SX.js.map} +1 -1
- package/dist/review-candidates-FBDLPU6H.js +4 -0
- package/dist/{review-candidates-IPJWEXR2.js.map → review-candidates-FBDLPU6H.js.map} +1 -1
- package/dist/routing-3SZHWHUA.js +2 -0
- package/dist/schedule-tool-5FULSHWJ.js +2 -0
- package/dist/scheduler-ITOKSMYT.js +2 -0
- package/dist/seat-2HJG3UNW.js +2 -0
- package/dist/select-UKAOL7QB.js +2 -0
- package/dist/{select-BUWOD47K.js.map → select-UKAOL7QB.js.map} +1 -1
- package/dist/set-enabled-ADFSNG5A.js +2 -0
- package/dist/{set-enabled-XWSFTICB.js.map → set-enabled-ADFSNG5A.js.map} +1 -1
- package/dist/signal-exit-WL7G3EEZ.js +2 -0
- package/dist/signal-exit-WL7G3EEZ.js.map +1 -0
- package/dist/{surface-usage-HVVP22SA.js → surface-usage-O5L4KLGS.js} +2 -2
- package/dist/{tool-VOA4HSVP.js → tool-GPCJM7U5.js} +2 -2
- package/dist/{tool-VOA4HSVP.js.map → tool-GPCJM7U5.js.map} +1 -1
- package/dist/{tool-GUINJ2BQ.js → tool-VKQIDEG7.js} +2 -2
- package/dist/{tool-GUINJ2BQ.js.map → tool-VKQIDEG7.js.map} +1 -1
- package/dist/wiki-QUVWB4IN.js +2 -0
- package/package.json +1 -1
- package/dist/ChatApp-LD4TXJWP.js +0 -7
- package/dist/board-dashboard-OS5J3F73.js.map +0 -1
- package/dist/chunk-3UN6CXRL.js.map +0 -1
- package/dist/chunk-42Y3BXXS.js +0 -15
- package/dist/chunk-42Y3BXXS.js.map +0 -1
- package/dist/chunk-6JJ3GODZ.js +0 -57
- package/dist/chunk-6JJ3GODZ.js.map +0 -1
- package/dist/chunk-AF46YOLU.js.map +0 -1
- package/dist/chunk-API4IZZG.js +0 -2
- package/dist/chunk-API4IZZG.js.map +0 -1
- package/dist/chunk-BEHC3X42.js.map +0 -1
- package/dist/chunk-MOQNLS5Z.js +0 -5
- package/dist/chunk-NOAAK2XI.js +0 -152
- package/dist/chunk-NOAAK2XI.js.map +0 -1
- package/dist/chunk-OVN5LVJY.js +0 -11
- package/dist/chunk-OVN5LVJY.js.map +0 -1
- package/dist/chunk-UR3ZIDMA.js +0 -5
- package/dist/chunk-WP6KLXTP.js.map +0 -1
- package/dist/chunk-YCI3KUYF.js.map +0 -1
- package/dist/chunk-Z3IP66SL.js +0 -9
- package/dist/client-TJ5YZOEE.js +0 -2
- package/dist/config-4WZ7Y34V.js +0 -2
- package/dist/config-mutator-5Z7EEB5N.js +0 -2
- package/dist/doctor-7K3NRBNN.js +0 -2
- package/dist/program-KMQNX6YK.js +0 -2
- package/dist/promote-NDC3X54P.js +0 -2
- package/dist/query-F7BD3JPE.js +0 -2
- package/dist/registry-5NBHBVY3.js +0 -2
- package/dist/request-planner-H74KHFGJ.js +0 -2
- package/dist/review-candidates-IPJWEXR2.js +0 -4
- package/dist/routing-3RSG7SKW.js +0 -2
- package/dist/schedule-tool-7NYAK43U.js +0 -2
- package/dist/scheduler-24O7PADJ.js +0 -2
- package/dist/seat-TOM2WHQR.js +0 -2
- package/dist/select-BUWOD47K.js +0 -2
- package/dist/set-enabled-XWSFTICB.js +0 -2
- package/dist/wiki-VFME4T2H.js +0 -2
- package/dist/wiki-VFME4T2H.js.map +0 -1
- /package/dist/{agent-FUMJM6OW.js.map → agent-75URYGWI.js.map} +0 -0
- /package/dist/{chunk-MYRSNJJ4.js.map → chunk-3FCYKGU6.js.map} +0 -0
- /package/dist/{chunk-R42S57G6.js.map → chunk-4KJ3PCAI.js.map} +0 -0
- /package/dist/{chunk-BJPIRNP6.js.map → chunk-74FSHUB3.js.map} +0 -0
- /package/dist/{chunk-H7253EHW.js.map → chunk-ATXE3EMV.js.map} +0 -0
- /package/dist/{chunk-TEFMZY6B.js.map → chunk-BB3ESU74.js.map} +0 -0
- /package/dist/{chunk-UB63NQQL.js.map → chunk-GUAJNZIX.js.map} +0 -0
- /package/dist/{chunk-UXSYVMPK.js.map → chunk-HUQRPEDP.js.map} +0 -0
- /package/dist/{chunk-ZR3NZLJL.js.map → chunk-LUL4ILAQ.js.map} +0 -0
- /package/dist/{chunk-7IGSJGXI.js.map → chunk-TW4L6RP2.js.map} +0 -0
- /package/dist/{chunk-BVZFYBBP.js.map → chunk-WWU2D65N.js.map} +0 -0
- /package/dist/{chunk-Z3XUGXPD.js.map → chunk-ZUAV3PTL.js.map} +0 -0
- /package/dist/{client-TJ5YZOEE.js.map → client-JDY2FZUF.js.map} +0 -0
- /package/dist/{config-4WZ7Y34V.js.map → config-JCETBKWT.js.map} +0 -0
- /package/dist/{config-mutator-5Z7EEB5N.js.map → config-mutator-YQWTY47O.js.map} +0 -0
- /package/dist/{doctor-7K3NRBNN.js.map → doctor-6EWW7NC2.js.map} +0 -0
- /package/dist/{failure-candidates-RIXA3Y6D.js.map → failure-candidates-PBPF45GN.js.map} +0 -0
- /package/dist/{program-KMQNX6YK.js.map → promote-ZZWMGVO2.js.map} +0 -0
- /package/dist/{promote-NDC3X54P.js.map → query-OQBB7EFS.js.map} +0 -0
- /package/dist/{query-F7BD3JPE.js.map → registry-MDWD7EAO.js.map} +0 -0
- /package/dist/{registry-5NBHBVY3.js.map → routing-3SZHWHUA.js.map} +0 -0
- /package/dist/{routing-3RSG7SKW.js.map → schedule-tool-5FULSHWJ.js.map} +0 -0
- /package/dist/{schedule-tool-7NYAK43U.js.map → scheduler-ITOKSMYT.js.map} +0 -0
- /package/dist/{scheduler-24O7PADJ.js.map → seat-2HJG3UNW.js.map} +0 -0
- /package/dist/{seat-TOM2WHQR.js.map → surface-usage-O5L4KLGS.js.map} +0 -0
- /package/dist/{surface-usage-HVVP22SA.js.map → wiki-QUVWB4IN.js.map} +0 -0
|
@@ -3,9 +3,9 @@ import{a as i,b as c}from"./chunk-FCPTN6NF.js";var m="[Institutional Wiki";funct
|
|
|
3
3
|
task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,
|
|
4
4
|
workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,
|
|
5
5
|
model, status, started_at, message_preview, original_message,
|
|
6
|
-
resume_origin, resume_attempt, resumed_from
|
|
7
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?)
|
|
8
|
-
`).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null),t}function T(e,n,t){let r=Date.now();e.prepare(`
|
|
6
|
+
resume_origin, resume_attempt, resumed_from, person
|
|
7
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
+
`).run(t,n.agentId,n.channel??null,n.chatId??null,n.workflowRunId??null,n.workflowId??null,n.workflowNodeId??null,n.intentEventId??null,n.intentDecidedBy??null,n.resumeSessionId??null,n.model??null,Date.now(),n.messagePreview??null,n.originalMessage??null,n.resumeOrigin??null,n.resumeAttempt??0,n.resumedFrom??null,n.person??null),t}function T(e,n,t){let r=Date.now();e.prepare(`
|
|
9
9
|
UPDATE task_traces SET
|
|
10
10
|
status = ?,
|
|
11
11
|
final_session_id = ?,
|
|
@@ -58,4 +58,4 @@ import{a as i,b as c}from"./chunk-FCPTN6NF.js";var m="[Institutional Wiki";funct
|
|
|
58
58
|
ORDER BY started_at DESC
|
|
59
59
|
LIMIT ?
|
|
60
60
|
`;return r.push(s),e.prepare(a).all(...r).map(d)}export{p as a,h as b,T as c,E as d,g as e,b as f,R as g,C as h,S as i,A as j,D as k};
|
|
61
|
-
//# sourceMappingURL=chunk-
|
|
61
|
+
//# sourceMappingURL=chunk-GLQLCBJS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/injected-context.ts","../src/storage/traces.ts"],"sourcesContent":["import type { InjectedContext } from \"@/storage/traces\"\n\n// --- Injected lessons per task (#98) ---\n//\n// Which memory facts, procedures and wiki catalog actually reached the\n// prompt. Candidates are not enough: the request-context selector can drop\n// a whole layer, and the layer budgets in buildAgentContext can cut a layer\n// short. So a lesson counts as injected only when its text is in the\n// assembled context. Only ids are recorded, never content, and the lists\n// are capped, so the trace row stays small.\n\nexport const MAX_INJECTED_IDS = 20\nconst MAX_ID_LENGTH = 80\n\nexport interface InjectionCandidates {\n memory?: Array<{ id: string; content: string }>\n procedures?: Array<{ id: string; title: string }>\n /** The wiki catalog block offered to the prompt, if any. */\n wikiContext?: string\n}\n\n/** The first line of the wiki catalog block; see buildWikiContext. */\nconst WIKI_MARKER = \"[Institutional Wiki\"\n\nfunction capIds(ids: string[]): string[] {\n return [...new Set(ids)].slice(0, MAX_INJECTED_IDS).map((id) => id.slice(0, MAX_ID_LENGTH))\n}\n\nexport function injectedContextOf(assembled: string, candidates: InjectionCandidates): InjectedContext {\n const text = assembled ?? \"\"\n return {\n memory: capIds((candidates.memory ?? []).filter((m) => m.content && text.includes(m.content)).map((m) => m.id)),\n procedures: capIds(\n (candidates.procedures ?? []).filter((p) => text.includes(`[Known procedure: ${p.title}]`)).map((p) => p.id),\n ),\n wiki: Boolean(candidates.wikiContext) && text.includes(WIKI_MARKER),\n }\n}\n\n/** Clamp an InjectedContext from any source to the recorded bounds. */\nexport function boundInjectedContext(ctx: InjectedContext): InjectedContext {\n return { memory: capIds(ctx.memory), procedures: capIds(ctx.procedures), wiki: ctx.wiki === true }\n}\n","import type Database from \"better-sqlite3\"\nimport { newEventId } from \"@/intent/ulid\"\nimport { boundInjectedContext } from \"@/agents/injected-context\"\n\n// --- Task trace store ---\n//\n// Improvement plan #2 — per-task observability backed by SQLite. One\n// task_traces row per executeTask invocation, an append-only stream of\n// task_trace_steps inside it. The store is intentionally dumb: it stores\n// what callers give it. Callers (capture sites in src/agents/runtime.ts)\n// are responsible for byte-capping large step payloads so the daemon\n// memory stays bounded under tool-heavy turns.\n//\n// Why a separate store layer (vs writing inline in runtime.ts)?\n// - Tests can exercise the trace lifecycle against a temp SQLite without\n// spinning up the agent runtime.\n// - The HTTP endpoints (GET /task/:id/trace) read through the same\n// functions producers write through, so there's a single source of\n// truth on field names + semantics.\n// - Future capture sites (sdk tier, orchestrator tier) reuse this API\n// without copying SQL.\n//\n// Why ULID for task_id?\n// - URL-safe in HTTP routes (GET /task/:id/trace).\n// - Time-sortable, so listTraces ORDER BY started_at and ORDER BY\n// task_id agree without an explicit timestamp column index.\n// - Already in-tree (src/intent/ulid.ts); no new dep.\n//\n// Cross-DB FK note:\n// intent_event_id and intent_decided_by are logical foreign keys into\n// the intent ledger at .agentx/intent/ledger.sqlite. better-sqlite3\n// doesn't enforce cross-database FKs and we don't ATTACH the ledger\n// here on purpose — the rescue plan's append-only contract on the\n// ledger is honoured by routing all writes through src/intent/ledger.ts.\n// Joins happen at the HTTP / CLI layer when needed.\n\nexport interface TraceStartInput {\n agentId: string\n channel?: string | null\n chatId?: string | null\n messagePreview?: string | null\n /** Full untruncated user message — used by `agentx trace replay <taskId>`\n * to re-fire a recorded task against the current agent config. NULL on\n * rows from before migration v8, in which case replay falls back to\n * messagePreview (which is capped at 200 chars). */\n originalMessage?: string | null\n workflowRunId?: string | null\n workflowId?: string | null\n workflowNodeId?: string | null\n intentEventId?: string | null\n intentDecidedBy?: string | null\n resumeSessionId?: string | null\n model?: string | null\n /** How to re-enter this run after a restart (JSON, see agents/resume). */\n resumeOrigin?: string | null\n /** 0 for a fresh run; n for the n-th resume of a cut-off run. */\n resumeAttempt?: number | null\n /** The cut-off run this one continues. */\n resumedFrom?: string | null\n /** The known person who started the chain (people, #384). */\n person?: string | null\n}\n\nexport interface TraceEndInput {\n status: \"ok\" | \"error\" | \"timeout\"\n finalSessionId?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n cacheReadTokens?: number | null\n cacheCreateTokens?: number | null\n tier2InputTokens?: number | null\n tier2OutputTokens?: number | null\n tier2CacheReadTokens?: number | null\n tier2CacheCreateTokens?: number | null\n /** Whether the turn continued a provider session. The resume decision\n * is made after task:started, so it is recorded at the end. Omitted\n * leaves both resumed and resume_session_id untouched. */\n resumed?: boolean | null\n resumeSessionId?: string | null\n /** Request-gate experiment arm: \"treatment\" | \"holdout\". */\n jevArm?: string | null\n /** Runtime-reported turn count (Claude `num_turns`). */\n numTurns?: number | null\n /** Lessons injected into the prompt. See InjectedContext. */\n injectedContext?: InjectedContext | null\n error?: string | null\n /** The agent's final reply text. Stored verbatim so `replay --diff`\n * can compare original output vs the new run's output without\n * reconstructing it from the step ledger. NULL when the response\n * wasn't captured (older rows or non-text outputs). */\n finalResponse?: string | null\n}\n\n/** Ids of the lessons injected into one task's prompt. Memory facts and\n * procedures are matched per message, so their ids are recorded; the wiki\n * is injected as a whole catalog, so only its presence is. */\nexport interface InjectedContext {\n memory: string[]\n procedures: string[]\n wiki: boolean\n}\n\nexport interface TraceStepInput {\n /** Coarse step kind. Conventional values: \"tool_use\" | \"tool_result\" |\n * \"llm_message\" | \"session_rotation\" | \"error\" | \"preflight\". Free-form\n * strings allowed so future capture sites don't need a schema bump. */\n name: string\n /** Fine-grained name within the kind. For \"tool_use\", this is the tool\n * name (e.g. \"Bash\", \"Edit\"). Optional. */\n action?: string | null\n status?: \"ok\" | \"error\" | \"in-flight\" | null\n /** JSON-stringified input or human-readable summary. Caller-byte-capped. */\n inputSummary?: string | null\n outputSummary?: string | null\n error?: string | null\n /** Step duration when known. Optional — many step kinds are point-in-time. */\n ms?: number | null\n}\n\nexport interface TraceRecord {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n workflowId: string | null\n workflowNodeId: string | null\n intentEventId: string | null\n intentDecidedBy: string | null\n resumeSessionId: string | null\n finalSessionId: string | null\n model: string | null\n status: string\n startedAt: number\n finishedAt: number | null\n durationMs: number | null\n inputTokens: number | null\n outputTokens: number | null\n cacheReadTokens: number | null\n cacheCreateTokens: number | null\n tier2InputTokens: number | null\n tier2OutputTokens: number | null\n tier2CacheReadTokens: number | null\n tier2CacheCreateTokens: number | null\n /** NULL on rows recorded before migration v12. */\n resumed: boolean | null\n /** NULL when the request gate was not active (or before migration v13). */\n jevArm: string | null\n /** NULL on rows recorded before lesson-impact capture (#98) or when the\n * runtime does not report a turn count. */\n numTurns: number | null\n /** NULL on rows recorded before lesson-impact capture (#98). */\n injectedContext: InjectedContext | null\n error: string | null\n messagePreview: string | null\n /** Full untruncated user message — populated for traces from migration v8\n * onward. NULL on older rows; consumers should fall back to messagePreview. */\n originalMessage: string | null\n /** Agent's final reply text — populated for traces from migration v8\n * onward when the executor records it on end. */\n finalResponse: string | null\n}\n\nexport interface TraceStepRecord {\n taskId: string\n seq: number\n name: string\n action: string | null\n status: string | null\n inputSummary: string | null\n outputSummary: string | null\n error: string | null\n ms: number | null\n startedAt: number\n}\n\nexport interface ListTracesFilters {\n agentId?: string\n channel?: string\n chatId?: string\n workflowRunId?: string\n status?: string\n /** ms epoch */\n since?: number\n /** ms epoch */\n until?: number\n /** Default 100, capped at 1000. */\n limit?: number\n}\n\n/**\n * Insert an in-flight trace row and return its ULID. Callers thread the\n * returned id through the executor and call recordTraceEnd at finish time.\n *\n * `taskId` is optional — when supplied, the caller has already allocated\n * a ULID upstream (e.g. registry.execute generating it before the bus\n * event so the runtime can capture per-step rows under the same id).\n * When omitted, a fresh ULID is allocated here.\n */\nexport function recordTraceStart(\n db: Database.Database,\n input: TraceStartInput,\n taskId: string = newEventId(),\n): string {\n db.prepare(`\n INSERT INTO task_traces (\n task_id, agent_id, channel, chat_id, workflow_run_id, workflow_id,\n workflow_node_id, intent_event_id, intent_decided_by, resume_session_id,\n model, status, started_at, message_preview, original_message,\n resume_origin, resume_attempt, resumed_from, person\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'in-flight', ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n input.agentId,\n input.channel ?? null,\n input.chatId ?? null,\n input.workflowRunId ?? null,\n input.workflowId ?? null,\n input.workflowNodeId ?? null,\n input.intentEventId ?? null,\n input.intentDecidedBy ?? null,\n input.resumeSessionId ?? null,\n input.model ?? null,\n Date.now(),\n input.messagePreview ?? null,\n input.originalMessage ?? null,\n input.resumeOrigin ?? null,\n input.resumeAttempt ?? 0,\n input.resumedFrom ?? null,\n input.person ?? null,\n )\n return taskId\n}\n\n/**\n * Finalize a trace. duration_ms is computed from finished_at - started_at\n * inside the UPDATE so the two columns can never disagree. Idempotent —\n * calling twice on the same task_id overwrites the prior end values; the\n * second call's status wins. (Soft-overwrite is intentional: timeout\n * handlers may write before a late stream-completion arrives.)\n */\nexport function recordTraceEnd(db: Database.Database, taskId: string, input: TraceEndInput): void {\n const finishedAt = Date.now()\n db.prepare(`\n UPDATE task_traces SET\n status = ?,\n final_session_id = ?,\n input_tokens = ?,\n output_tokens = ?,\n cache_read_tokens = ?,\n cache_create_tokens = ?,\n tier2_input_tokens = ?,\n tier2_output_tokens = ?,\n tier2_cache_read_tokens = ?,\n tier2_cache_create_tokens = ?,\n resumed = COALESCE(?, resumed),\n resume_session_id = COALESCE(?, resume_session_id),\n jev_arm = COALESCE(?, jev_arm),\n num_turns = COALESCE(?, num_turns),\n injected_context = COALESCE(?, injected_context),\n error = ?,\n final_response = COALESCE(?, final_response),\n finished_at = ?,\n duration_ms = ? - started_at\n WHERE task_id = ?\n `).run(\n input.status,\n input.finalSessionId ?? null,\n input.inputTokens ?? null,\n input.outputTokens ?? null,\n input.cacheReadTokens ?? null,\n input.cacheCreateTokens ?? null,\n input.tier2InputTokens ?? null,\n input.tier2OutputTokens ?? null,\n input.tier2CacheReadTokens ?? null,\n input.tier2CacheCreateTokens ?? null,\n input.resumed == null ? null : input.resumed ? 1 : 0,\n input.resumeSessionId ?? null,\n input.jevArm ?? null,\n input.numTurns ?? null,\n input.injectedContext ? JSON.stringify(boundInjectedContext(input.injectedContext)) : null,\n input.error ?? null,\n input.finalResponse ?? null,\n finishedAt,\n finishedAt,\n taskId,\n )\n}\n\n/**\n * Append a step. seq is auto-allocated as MAX(seq)+1 within a transaction\n * so concurrent step writes for the same task_id can't collide. Returns\n * the assigned seq, useful for downstream correlation.\n */\nexport function recordTraceStep(db: Database.Database, taskId: string, input: TraceStepInput): number {\n const startedAt = Date.now()\n const allocateAndInsert = db.transaction((): number => {\n const row = db\n .prepare(\"SELECT MAX(seq) AS max_seq FROM task_trace_steps WHERE task_id = ?\")\n .get(taskId) as { max_seq: number | null } | undefined\n const seq = ((row?.max_seq ?? -1) as number) + 1\n db.prepare(`\n INSERT INTO task_trace_steps (\n task_id, seq, name, action, status, input_summary, output_summary, error, ms, started_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n taskId,\n seq,\n input.name,\n input.action ?? null,\n input.status ?? null,\n input.inputSummary ?? null,\n input.outputSummary ?? null,\n input.error ?? null,\n input.ms ?? null,\n startedAt,\n )\n return seq\n })\n return allocateAndInsert()\n}\n\nexport function parseInjectedContext(raw: unknown): InjectedContext | null {\n if (typeof raw !== \"string\") return null\n try {\n const v = JSON.parse(raw)\n if (!v || typeof v !== \"object\") return null\n const ids = (x: unknown) => (Array.isArray(x) ? x.filter((i): i is string => typeof i === \"string\") : [])\n return { memory: ids(v.memory), procedures: ids(v.procedures), wiki: v.wiki === true }\n } catch {\n return null\n }\n}\n\nfunction rowToTrace(row: Record<string, unknown>): TraceRecord {\n return {\n taskId: row.task_id as string,\n agentId: row.agent_id as string,\n channel: (row.channel as string) ?? null,\n chatId: (row.chat_id as string) ?? null,\n workflowRunId: (row.workflow_run_id as string) ?? null,\n workflowId: (row.workflow_id as string) ?? null,\n workflowNodeId: (row.workflow_node_id as string) ?? null,\n intentEventId: (row.intent_event_id as string) ?? null,\n intentDecidedBy: (row.intent_decided_by as string) ?? null,\n resumeSessionId: (row.resume_session_id as string) ?? null,\n finalSessionId: (row.final_session_id as string) ?? null,\n model: (row.model as string) ?? null,\n status: row.status as string,\n startedAt: row.started_at as number,\n finishedAt: (row.finished_at as number) ?? null,\n durationMs: (row.duration_ms as number) ?? null,\n inputTokens: (row.input_tokens as number) ?? null,\n outputTokens: (row.output_tokens as number) ?? null,\n cacheReadTokens: (row.cache_read_tokens as number) ?? null,\n cacheCreateTokens: (row.cache_create_tokens as number) ?? null,\n tier2InputTokens: (row.tier2_input_tokens as number) ?? null,\n tier2OutputTokens: (row.tier2_output_tokens as number) ?? null,\n tier2CacheReadTokens: (row.tier2_cache_read_tokens as number) ?? null,\n tier2CacheCreateTokens: (row.tier2_cache_create_tokens as number) ?? null,\n resumed: row.resumed == null ? null : row.resumed === 1,\n jevArm: (row.jev_arm as string) ?? null,\n numTurns: (row.num_turns as number) ?? null,\n injectedContext: parseInjectedContext(row.injected_context),\n error: (row.error as string) ?? null,\n messagePreview: (row.message_preview as string) ?? null,\n originalMessage: (row.original_message as string) ?? null,\n finalResponse: (row.final_response as string) ?? null,\n }\n}\n\nfunction rowToStep(row: Record<string, unknown>): TraceStepRecord {\n return {\n taskId: row.task_id as string,\n seq: row.seq as number,\n name: row.name as string,\n action: (row.action as string) ?? null,\n status: (row.status as string) ?? null,\n inputSummary: (row.input_summary as string) ?? null,\n outputSummary: (row.output_summary as string) ?? null,\n error: (row.error as string) ?? null,\n ms: (row.ms as number) ?? null,\n startedAt: row.started_at as number,\n }\n}\n\n/** Fetch a trace + its ordered steps. Returns null if no such task_id. */\nexport function getTrace(\n db: Database.Database,\n taskId: string,\n): { task: TraceRecord; steps: TraceStepRecord[] } | null {\n const row = db.prepare(\"SELECT * FROM task_traces WHERE task_id = ?\").get(taskId) as\n | Record<string, unknown>\n | undefined\n if (!row) return null\n const stepRows = db\n .prepare(\"SELECT * FROM task_trace_steps WHERE task_id = ? ORDER BY seq\")\n .all(taskId) as Record<string, unknown>[]\n return { task: rowToTrace(row), steps: stepRows.map(rowToStep) }\n}\n\n/**\n * Cancel any in-flight trace rows left over from a previous daemon\n * lifetime. Mirrors the intent ledger's startup cleanup (rescue plan\n * Phase 1 commit a8514d9): a hard-killed daemon never gets to fire\n * task:completed, so the row sits \"in-flight\" forever and contaminates\n * triage queries (`agentx trace list --status in-flight`) with stale\n * orphans. Run once at daemon boot before subscribers attach.\n *\n * Returns the number of rows updated. duration_ms is intentionally NOT\n * computed — we don't know when the task actually ended; preserving\n * NULL there is more honest than backdating to \"now\".\n */\nexport function cleanupOrphanedTraces(db: Database.Database): number {\n const now = Date.now()\n const r = db.prepare(`\n UPDATE task_traces\n SET status = 'canceled',\n error = 'daemon-restart (orphaned in-flight)',\n finished_at = ?\n WHERE status = 'in-flight'\n `).run(now)\n return (r.changes ?? 0) as number\n}\n\n// --- Resume after restart (#103) -------------------------------------------\n\n/** A run that was still going when the previous daemon stopped. */\nexport interface InterruptedRun {\n taskId: string\n agentId: string\n channel: string | null\n chatId: string | null\n workflowRunId: string | null\n startedAt: number\n originalMessage: string | null\n resumeOrigin: string | null\n resumeAttempt: number\n /** Tool calls it had made, in order, for the resume note. */\n toolCalls: Array<{ action: string | null; inputSummary: string | null }>\n}\n\n/** Close every run left in flight by the previous daemon, marking it\n * `interrupted` for the resume planner, and return them. One transaction,\n * so a second process booting on the same database gets nothing. */\nexport function takeInterruptedRuns(db: Database.Database, now = Date.now()): InterruptedRun[] {\n const take = db.transaction(() => {\n const rows = db.prepare(`\n SELECT task_id, agent_id, channel, chat_id, workflow_run_id, started_at,\n original_message, resume_origin, resume_attempt\n FROM task_traces WHERE status = 'in-flight' ORDER BY started_at\n `).all() as Array<Record<string, any>>\n db.prepare(`\n UPDATE task_traces\n SET status = 'canceled', error = 'daemon-restart (interrupted)',\n finished_at = ?, resume_decision = 'interrupted'\n WHERE status = 'in-flight'\n `).run(now)\n return rows\n })\n const steps = db.prepare(`\n SELECT action, input_summary FROM task_trace_steps\n WHERE task_id = ? AND name = 'tool_use' ORDER BY seq\n `)\n return take().map((r) => ({\n taskId: r.task_id,\n agentId: r.agent_id,\n channel: r.channel ?? null,\n chatId: r.chat_id ?? null,\n workflowRunId: r.workflow_run_id ?? null,\n startedAt: r.started_at,\n originalMessage: r.original_message ?? null,\n resumeOrigin: r.resume_origin ?? null,\n resumeAttempt: r.resume_attempt ?? 0,\n toolCalls: (steps.all(r.task_id) as Array<Record<string, any>>).map((s) => ({\n action: s.action ?? null, inputSummary: s.input_summary ?? null,\n })),\n }))\n}\n\n/** Claim an interrupted run before deciding what to do with it. Returns\n * false when another process already claimed or decided it, so a run is\n * never resumed — or its chat told — twice. */\nexport function claimResume(db: Database.Database, taskId: string): boolean {\n const r = db.prepare(`\n UPDATE task_traces SET resume_decision = 'deciding'\n WHERE task_id = ? AND resume_decision = 'interrupted'\n `).run(taskId)\n return (r.changes ?? 0) === 1\n}\n\nexport type ResumeDecision = \"resumed\" | \"reported\" | \"skipped\" | \"resume-failed\"\n\nexport function recordResumeDecision(\n db: Database.Database, taskId: string, decision: ResumeDecision, reason: string,\n): void {\n db.prepare(\"UPDATE task_traces SET resume_decision = ?, resume_reason = ? WHERE task_id = ?\")\n .run(decision, reason.slice(0, 500), taskId)\n}\n\n/** Triage / dashboard surface — list traces newest-first, filtered. */\nexport function listTraces(db: Database.Database, filters: ListTracesFilters = {}): TraceRecord[] {\n const where: string[] = []\n const params: unknown[] = []\n if (filters.agentId) { where.push(\"agent_id = ?\"); params.push(filters.agentId) }\n if (filters.channel) { where.push(\"channel = ?\"); params.push(filters.channel) }\n if (filters.chatId) { where.push(\"chat_id = ?\"); params.push(filters.chatId) }\n if (filters.workflowRunId) { where.push(\"workflow_run_id = ?\"); params.push(filters.workflowRunId) }\n if (filters.status) { where.push(\"status = ?\"); params.push(filters.status) }\n if (filters.since !== undefined) { where.push(\"started_at >= ?\"); params.push(filters.since) }\n if (filters.until !== undefined) { where.push(\"started_at <= ?\"); params.push(filters.until) }\n\n const limit = Math.max(1, Math.min(filters.limit ?? 100, 1000))\n const sql = `\n SELECT * FROM task_traces\n ${where.length > 0 ? \"WHERE \" + where.join(\" AND \") : \"\"}\n ORDER BY started_at DESC\n LIMIT ?\n `\n params.push(limit)\n return (db.prepare(sql).all(...params) as Record<string, unknown>[]).map(rowToTrace)\n}\n"],"mappings":"+CAsBA,IAAMA,EAAc,sBAEpB,SAASC,EAAOC,EAAyB,CACvC,MAAO,CAAC,GAAG,IAAI,IAAIA,CAAG,CAAC,EAAE,MAAM,EAAG,EAAgB,EAAE,IAAKC,GAAOA,EAAG,MAAM,EAAG,EAAa,CAAC,CAC5F,CAEO,SAASC,EAAkBC,EAAmBC,EAAkD,CACrG,IAAMC,EAAOF,GAAa,GAC1B,MAAO,CACL,OAAQJ,GAAQK,EAAW,QAAU,CAAC,GAAG,OAAQE,GAAMA,EAAE,SAAWD,EAAK,SAASC,EAAE,OAAO,CAAC,EAAE,IAAKA,GAAMA,EAAE,EAAE,CAAC,EAC9G,WAAYP,GACTK,EAAW,YAAc,CAAC,GAAG,OAAQG,GAAMF,EAAK,SAAS,qBAAqBE,EAAE,QAAQ,CAAC,EAAE,IAAKA,GAAMA,EAAE,EAAE,CAC7G,EAC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,SAAS+B,EAAWjC,EAAuBkC,EAA6B,CAAC,EAAkB,CAChG,IAAMC,EAAkB,CAAC,EACnBC,EAAoB,CAAC,EACvBF,EAAQ,UAAWC,EAAM,KAAK,cAAc,EAAGC,EAAO,KAAKF,EAAQ,OAAO,GAC1EA,EAAQ,UAAWC,EAAM,KAAK,aAAa,EAAGC,EAAO,KAAKF,EAAQ,OAAO,GACzEA,EAAQ,SAAUC,EAAM,KAAK,aAAa,EAAGC,EAAO,KAAKF,EAAQ,MAAM,GACvEA,EAAQ,gBAAiBC,EAAM,KAAK,qBAAqB,EAAGC,EAAO,KAAKF,EAAQ,aAAa,GAC7FA,EAAQ,SAAUC,EAAM,KAAK,YAAY,EAAGC,EAAO,KAAKF,EAAQ,MAAM,GACtEA,EAAQ,QAAU,SAAaC,EAAM,KAAK,iBAAiB,EAAGC,EAAO,KAAKF,EAAQ,KAAK,GACvFA,EAAQ,QAAU,SAAaC,EAAM,KAAK,iBAAiB,EAAGC,EAAO,KAAKF,EAAQ,KAAK,GAE3F,IAAMG,EAAQ,KAAK,IAAI,EAAG,KAAK,IAAIH,EAAQ,OAAS,IAAK,GAAI,CAAC,EACxDI,EAAM;AAAA;AAAA,MAERH,EAAM,OAAS,EAAI,SAAWA,EAAM,KAAK,OAAO,EAAI;AAAA;AAAA;AAAA,IAIxD,OAAAC,EAAO,KAAKC,CAAK,EACTrC,EAAG,QAAQsC,CAAG,EAAE,IAAI,GAAGF,CAAM,EAAgC,IAAIpB,CAAU,CACrF","names":["WIKI_MARKER","capIds","ids","id","injectedContextOf","assembled","candidates","text","m","p","boundInjectedContext","ctx","init_ulid","recordTraceStart","db","input","taskId","newEventId","recordTraceEnd","finishedAt","boundInjectedContext","recordTraceStep","startedAt","seq","parseInjectedContext","raw","v","ids","x","i","rowToTrace","row","rowToStep","getTrace","stepRows","cleanupOrphanedTraces","now","takeInterruptedRuns","take","rows","steps","r","s","claimResume","recordResumeDecision","decision","reason","listTraces","filters","where","params","limit","sql"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-PE55MMLK.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),F(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
1
|
+
import{a as O,b as $,c as U,d as T,e as j}from"./chunk-WPNRDEHW.js";import{t as R,v as E,w as W}from"./chunk-5GXCOHDM.js";import{a as z,b as C,f as V}from"./chunk-72SZI2UW.js";import{a as B,b as re}from"./chunk-FX3D7YON.js";import{o as J,p as te}from"./chunk-5MUJZODV.js";V();var we="wiki-rerank",be=30,se=900;function xe(a){let e=a.excerptChars??se;return{query:a.query,candidates:a.candidates.map(t=>({id:t.id,title:t.title,tags:t.tags?.length?t.tags.join(", "):null,excerpt:ne(t.excerpt,e)}))}}function Se(a){let e={};for(let t of a)e[t.id]=t.title;return{best:C(e,"Which candidate answers the query?"),answerable:z("Do any of the candidates answer the query?")}}function Ne(a,e){let t=a.best,r={};for(let i of e)r[i.id]=t.probabilities[i.id]??0;let n=new Map(e.map((i,s)=>[i.id,s]));return{ranked:[...e.map(i=>i.id)].sort((i,s)=>{let c=r[s]-r[i];return c!==0?c:(n.get(i)??0)-(n.get(s)??0)}),scores:r,answerable:a.answerable.noul,confidence:t.confidence}}function ne(a,e){let t=String(a??"").replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e):t}var x={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},G=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as I,writeFileSync as M,appendFileSync as ie,existsSync as S,mkdirSync as F,renameSync as oe,statSync as Q}from"fs";import{resolve as A,dirname as X}from"path";import{createHash as ae}from"crypto";var _=class{baseDir;log;parsed=new Map;constructor(e={}){this.baseDir=e.baseDir??A(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),F(this.baseDir,{recursive:!0})}schemaPath(){return A(this.baseDir,"schema.json")}nodesPath(){return A(this.baseDir,"nodes.json")}indexPath(){return A(this.baseDir,"index.json")}classificationsPath(){return A(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!S(e))return this.saveSchema(x),this.log("seeded starter schema at",e),x;let t=I(e,"utf-8"),r=O.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);if((r.data.version??1)<(x.version??2)){let n=e.replace(/\.json$/,`.v${r.data.version??1}.bak.json`);try{M(n,t),this.log(`migrated graph schema v${r.data.version??1} -> v${x.version}; old saved at ${n}`)}catch(i){this.log(`could not back up old schema: ${i?.message??i}`)}this.saveSchema(x);let o=this.nodesPath();if(S(o)){let i=o.replace(/\.json$/,".v1.bak.json");try{M(i,I(o,"utf-8")),this.log(`archived v1 nodes.json -> ${i}`)}catch(s){this.log(`could not back up old nodes: ${s?.message??s}`)}try{let s=K();this.saveNodes(s)}catch(s){this.log(`could not seed v2 nodes: ${s?.message??s}`)}}return x}return r.data}saveSchema(e){let t=O.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(r=>r.message).join("; ")}`);Y(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!S(e)){let t=K();return this.saveNodes(t),t}return structuredClone(this.readParsed(e,t=>{let r=T.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}))}saveNodes(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.nodesPath(),t.data)}readParsed(e,t){let{mtimeMs:r,size:n}=Q(e),o=this.parsed.get(e);if(o&&o.mtimeMs===r&&o.size===n)return o.data;let i=t(I(e,"utf-8"));return this.parsed.set(e,{mtimeMs:r,size:n,data:i}),i}writeParsed(e,t){this.parsed.delete(e),Y(e,t);let{mtimeMs:r,size:n}=Q(e);this.parsed.set(e,{mtimeMs:r,size:n,data:t})}validateNode(e,t,r){let n=t.levels.find(s=>s.id===e.level);if(!n)throw new Error(`Unknown level: "${e.level}"`);let o=n.axes.filter(s=>!s.optional).filter(s=>!(s.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(s=>s.name).join(", ")}`);for(let s of n.axes){let c=e.axes[s.name];if(c!=null){if(s.type==="enum"&&s.values&&!s.values.includes(c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" not in enum ${JSON.stringify(s.values)}`);if(s.type==="ref"){if(!r.some(l=>l.id===c))throw new Error(`Node ${e.id}: axis ${s.name}="${c}" refers to unknown node`);if(s.refLevel){let l=r.find(h=>h.id===c);if(l.level!==s.refLevel)throw new Error(`Node ${e.id}: axis ${s.name} expected level "${s.refLevel}" but got "${l.level}"`)}}}}let i=t.levels.findIndex(s=>s.id===e.level);if(i===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let s=r.find(l=>l.id===e.parentId);if(!s)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let c=t.levels.findIndex(l=>l.id===s.level);if(c<0||c>=i)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${s.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,r,n){let o=[],i=[],s=new Date().toISOString();for(let c=0;c<e.length;c++){let l=e[c],h=this.loadNodes().nodes;if(h.find(p=>p.id===l)){i.push(l);continue}let g=0;for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(w=>w.id===y)||o.find(w=>w.id===y);if(N){g=r.levels.findIndex(w=>w.id===N.level)+1;break}}let m=t[l]??{},d=null;for(let p=g;p<r.levels.length;p++){let y=r.levels[p];if(y.axes.filter(w=>!w.optional).filter(w=>!(w.name in m)).length===0){d=y.id,g=p+1;break}}if(!d&&g<r.levels.length&&(d=r.levels[g].id,g++),!d)throw new Error(`Can't place node ${l} \u2014 no schema level left (cursor=${g}, levels=${r.levels.length})`);let f=null,v=r.levels.findIndex(p=>p.id===d);for(let p=c-1;p>=0;p--){let y=e[p],N=h.find(k=>k.id===y)||o.find(k=>k.id===y);if(!N)continue;let w=r.levels.findIndex(k=>k.id===N.level);if(w>=0&&w<v){f=y;break}}let u={id:l,level:d,parentId:f,axes:m,createdAt:s,createdBy:n};this.addNode(u),o.push(u)}return{added:o,skipped:i}}addNode(e){let t=this.loadSchema(),r=this.loadNodes();if(r.nodes.some(n=>n.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...r.nodes,e]),r.nodes.push(e),this.saveNodes(r),e}appendClassification(e){let t=$.safeParse(e);if(!t.success){let o=t.error.issues.map(i=>`${i.path.join(".")}: ${i.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let r=JSON.stringify(t.data)+`
|
|
2
2
|
`,n=this.classificationsPath();return S(n)||F(X(n),{recursive:!0}),ie(n,r),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(n=>n.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!S(e))return[];let r=I(e,"utf-8").split(`
|
|
3
3
|
`).filter(Boolean),n=new Map;for(let o of r)try{let i=$.safeParse(JSON.parse(o));if(!i.success)continue;n.set(i.data.msgHash,i.data)}catch{}return Array.from(n.values()).sort((o,i)=>o.ts<i.ts?1:-1)}updateClassificationStatus(e,t){let n=this.readAllCollapsed().find(i=>i.msgHash===e);if(!n)return null;let o={...n,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let i=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((n.preview||"")+i).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!S(t))return[];let n=I(t,"utf-8").split(`
|
|
4
4
|
`).filter(Boolean),o=[];for(let i=n.length-1;i>=0&&o.length<e;i--)try{let s=$.safeParse(JSON.parse(n[i]));s.success&&o.push(s.data)}catch{}return o}fingerprint(e){let r=[ce(e.text),e.channel??""].join("");return ae("sha256").update(r).digest("hex").slice(0,32)}loadIndex(){return structuredClone(this.index())}saveIndex(e){let t=j.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(r=>r.message).join("; ")}`);this.writeParsed(this.indexPath(),t.data)}index(){let e=this.indexPath();return S(e)?this.readParsed(e,t=>{let r=j.safeParse(JSON.parse(t));if(!r.success)throw new Error(`Invalid ${e}: ${r.error.issues.map(n=>n.message).join("; ")}`);return r.data}):{version:1,entries:{}}}getFingerprint(e){let t=this.index().entries[e];return t&&structuredClone(t)}setFingerprint(e,t){let r=U.safeParse({...t,fingerprint:e,updatedAt:new Date().toISOString()});if(!r.success)throw new Error(`Refusing to save invalid index entry: ${r.error.issues.map(o=>o.message).join("; ")}`);let n=this.index();this.writeParsed(this.indexPath(),{...n,entries:{...n.entries,[e]:r.data}})}updateNodeAxes(e,t){let r=this.loadSchema(),n=this.loadNodes(),o=n.nodes.find(s=>s.id===e);if(!o)throw new Error(`Node not found: ${e}`);let i={...o,axes:t};return this.validateNode(i,r,n.nodes.map(s=>s.id===e?i:s)),n.nodes=n.nodes.map(s=>s.id===e?i:s),this.saveNodes(n),i}deleteNode(e){let t=this.loadNodes(),r=t.nodes.find(o=>o.parentId===e);if(r)throw new Error(`Cannot delete "${e}" \u2014 child node "${r.id}" still points to it`);let n=t.nodes.find(o=>Object.values(o.axes).some(i=>i===e));if(n)throw new Error(`Cannot delete "${e}" \u2014 node "${n.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),r=new Set(this.loadNodes().nodes.map(n=>n.id));for(let n=0;n<e.path.length;n++){let o=e.path[n];if(r.has(o))continue;let i=t.levels[n]?.id;if(!i)break;let s=e.proposedAxes?.[o]??{},c=n===0?null:e.path[n-1];this.addNode({id:o,level:i,parentId:c,axes:s,createdAt:new Date().toISOString(),createdBy:e.agentId}),r.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function Y(a,e){F(X(a),{recursive:!0});let t=`${a}.tmp-${process.pid}`;M(t,JSON.stringify(e,null,2)),oe(t,a)}function K(){let a=new Date().toISOString(),e=[],t=new Set;for(let r of G)t.has(r.category)||(e.push({id:r.category,level:"category",parentId:null,axes:{kind:r.category},createdAt:a,createdBy:"starter"}),t.add(r.category));for(let r of G)e.push({id:r.verb,level:"verb",parentId:r.category,axes:{name:r.verb,...r.description?{description:r.description}:{}},createdAt:a,createdBy:"starter"});return{version:1,nodes:e}}function ce(a){return a.toLowerCase().replace(/https?:\/\/\S+/g," url ").replace(/[@#][\w.\/-]+/g," ref ").replace(/\b[0-9a-f]{7,}\b/g," id ").replace(/\d+/g," num ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim().slice(0,400)}re();te();W();import{createHash as me}from"crypto";V();W();var P="intent-path",de=.5,le=.3;function pe(a){return{message:fe(a.message,2e3),channel:a.channel??null,sender:a.sender??null,agent:a.agent??null}}function Z(a,e){let t={};for(let r of a)t[r.id]=he(r);return C(t,e)}function ge(a){return{category:Z(a,"Which category of work does this message ask for or report on? Pick the one a reviewer would file it under.")}}function ue(a){return{verb:Z(a,"Within that category, which specific action does the message ask for or report on? Prefer the most specific verb that fits; a casual or ambiguous message belongs to the most general one.")}}async function D(a,e,t={}){if(R(P)==="off")return null;let r=e.filter(m=>m.parentId===null);if(r.length<2)return null;let n=pe(a),o={agent:a.agent??"unknown",channel:a.channel??"unknown"},i=a.agent?[{kind:"agent",id:a.agent}]:void 0,s=await E(P,n,ge(r),{incumbent:t.incumbent?.[0]?{category:t.incumbent[0]}:void 0,features:{...o,stage:"category"},links:i});if(!s)return null;let c=s.answers.category,l=c.pMax,h=c.pMax>=de,b=[c.choice],g=e.filter(m=>m.parentId===c.choice);if(g.length>=2){let m=t.incumbent?.[0]===c.choice,d=await E(P,{...n,category:c.choice},ue(g),{incumbent:m&&t.incumbent?.[1]?{verb:t.incumbent[1]}:void 0,features:{...o,stage:"verb",category:c.choice},links:i});if(!d)return null;let f=d.answers.verb;l=Math.min(l,f.pMax),h=h&&f.pMax>=le,b.push(f.choice)}else g.length===1&&b.push(g[0].id);return{path:b,confidence:l,confident:h,mode:s.mode}}function he(a){let e=a.axes?.description?.trim()||void 0,t=a.axes?.name?.trim(),r=t&&t!==a.id?t:void 0;return e&&r?`${r}: ${e}`:e??r??null}function fe(a,e){return a.length>e?`${a.slice(0,e)}\u2026`:a}var L=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=J(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),r=this.store.getFingerprint(t);if(r)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:r.path,proposedAxes:{},leaf:r.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:r.path,pathId:H(r.path),pathLabel:q(r.path,this.store.loadNodes().nodes),axes:{},leaf:r.leaf,source:"cache",status:"approved"};let n=this.store.loadSchema(),o=this.store.loadNodes().nodes,i=await this.propose(e,n,o);if(!i)return null;let{path:s,proposedAxes:c,confidence:l,leaf:h}=i;if(s.length===0)return null;let b={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,chatId:e.chatId,path:s,proposedAxes:c,leaf:h,source:i.source,status:"pending",confidence:l,preview:e.text.slice(0,200)},g=new Set(o.map(u=>u.id)),m=s.map((u,p)=>g.has(u)?-1:p).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=m.length===0,p=m.length===1&&m[0]===s.length-1;d=u||p}let f=l!==void 0&&l>=this.autoApprove,v="pending";if(d||f)try{this.commitNewNodes(s,c,n,o,e.sender),this.store.setFingerprint(t,{path:s,leaf:h}),v="approved"}catch(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(s)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return b.status=v,this.store.appendClassification(b),{path:s,pathId:H(s),pathLabel:q(s,this.store.loadNodes().nodes),axes:c,leaf:h,source:i.source,status:v,confidence:l}}async propose(e,t,r){let n=R(P),o={message:e.text,channel:e.channel,sender:e.sender,agent:e.agentId};if(n==="active"){let s=await D(o,r).catch(c=>(this.log("intent-path seat failed:",c?.message||c),null));if(s?.confident)return{path:s.path,proposedAxes:{},leaf:{},confidence:s.confidence,source:"seat"}}let i=await this.proposePath(e,t,r).catch(s=>(this.log("LLM proposal failed:",s?.message||s),null));return n==="shadow"&&i&&D(o,r,{incumbent:i.path}).catch(()=>{}),i?{...i,source:"llm"}:null}async proposePath(e,t,r){let n=r.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(n,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
5
|
`),i=await this.callProvider(o),s=B(i);if(!s||!Array.isArray(s.path))return null;let c=/^[a-z0-9][a-z0-9._-]*$/,l=new Map,h=s.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let f=d.trim(),v=ee(f);return f!==v&&l.set(f,v),v}).filter(d=>c.test(d));if(h.length===0)return null;let b={};if(s.proposedAxes&&typeof s.proposedAxes=="object")for(let[d,f]of Object.entries(s.proposedAxes)){if(!f||typeof f!="object")continue;let v=l.get(d)??ee(d);if(!v)continue;let u={};for(let[p,y]of Object.entries(f))typeof y=="string"&&(u[p]=y);!u.name&&d!==v&&(u.name=d.trim()),b[v]=u}let g={};s.leaf&&typeof s.leaf=="object"&&(typeof s.leaf.input=="string"&&(g.input=s.leaf.input),typeof s.leaf.output=="string"&&(g.output=s.leaf.output));let m=typeof s.confidence=="number"?Math.max(0,Math.min(1,s.confidence)):void 0;return{path:h,proposedAxes:b,confidence:m,leaf:g}}commitNewNodes(e,t,r,n,o){this.store.commitNodesAlongPath(e,t,r,o)}async callProvider(e){let t=this.getProvider(),r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800,abortSignal:r.signal,bare:!0})).content||""}finally{clearTimeout(n)}}};function ee(a){let e=a.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function H(a){return me("sha1").update(a.join("")).digest("hex").slice(0,16)}function q(a,e){return a.map(t=>{let r=e.find(o=>o.id===t);return r&&(r.axes?.name||r.axes?.what)||t}).join(" \u203A ")}function ve(a,e){if(a.length===0||e.length===0)return 0;let t=0;for(let n=0;n<Math.min(a.length,e.length)&&a[n]===e[n];n++)t++;if(t===0)return 0;let r=Math.max(a.length,e.length);return t/r}export{we as a,be as b,xe as c,Se as d,Ne as e,x as f,_ as g,L as h,q as i,ve as j};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-GUAJNZIX.js.map
|
|
@@ -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-GUAJNZIX.js";import{b as R}from"./chunk-2GIDVZ4H.js";import{v as C,w as I}from"./chunk-5GXCOHDM.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-HUQRPEDP.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{aa as m,da as b}from"./chunk-LTHQXWZN.js";b();function w(t){let e=typeof t.node=="string"?t.node:"",n=typeof t.token=="string"?t.token:"";if(!e||!n)try{let o=m(t.config);e||(e=o.dashboard?.daemonUrl||""),n||(n=o.dashboard?.token||"")}catch{}return e||(e="http://localhost:18800"),{baseUrl:e.replace(/\/+$/,""),token:n}}async function d(t,e,n){let o={Accept:"application/json"};t.token&&(o.Authorization=`Bearer ${t.token}`);let r=await fetch(`${t.baseUrl}${e}`,{headers:o,signal:n});if(!r.ok)throw new Error(`GET ${e} \u2192 HTTP ${r.status}`);return await r.json()}function R(t,e){return d(t,"/agents",e)}async function S(t,e){return(await d(t,"/api/processes",e)).processes??[]}function P(t,e){return d(t,"/crons",e)}async function h(t,e,n,o){let r={Accept:"application/json","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}${e}`,{method:"POST",headers:r,body:JSON.stringify(n),signal:o}),a=await s.text(),i;try{i=a?JSON.parse(a):{}}catch{i={raw:a}}if(!s.ok)throw new Error(i?.error||`POST ${e} \u2192 HTTP ${s.status}`);return i}function A(t,e,n="tui"){return h(t,"/api/processes/kill",{...e,reason:n})}function C(t,e,n,o){return h(t,"/task",{agent:e,message:n,context:o??{channel:"tui",chatId:"tui:operator"}})}async function $(t,e,n,o={}){let r={Accept:"text/event-stream","Content-Type":"application/json"};t.token&&(r.Authorization=`Bearer ${t.token}`);let s=await fetch(`${t.baseUrl}/task`,{method:"POST",headers:r,body:JSON.stringify({agent:e,message:n,stream:!0,context:{channel:o.channel??"chat-cli",chatId:o.chatId??"chat-cli:operator"}}),signal:o.signal});if(!s.ok||!s.body){let g=await s.text().catch(()=>"");throw new Error(`POST /task (stream) \u2192 HTTP ${s.status}${g?`: ${g.slice(0,200)}`:""}`)}let a=s.body.getReader(),i=new TextDecoder,u={content:""},c="";try{for(;;){let{done:g,value:p}=await a.read();if(g)break;c+=i.decode(p,{stream:!0});let l;for(;(l=c.indexOf(`
|
|
2
|
+
|
|
3
|
+
`))>=0;){let k=c.slice(0,l);c=c.slice(l+2);let f=x(k);f&&T(f,o,u)}}}finally{try{a.releaseLock()}catch{}}return u}function T(t,e,n){let{event:o,data:r}=t;switch(o){case"text":r?.text&&(n.content+=r.text,e.onText?.(r.text));break;case"thinking":r?.text&&e.onThinking?.(r.text);break;case"tool":e.onTool?.(r);break;case"done":typeof r?.content=="string"&&(n.content=r.content),n.usage=r?.usage,n.duration=r?.duration;break;case"error":n.error=r?.error,n.errorKind=r?.errorKind;break}}function x(t){let e="message",n="";for(let r of t.split(`
|
|
4
|
+
`))r.startsWith("event: ")?e=r.slice(7).trim():r.startsWith("data: ")&&(n=r.slice(6));if(!n)return null;let o;try{o=JSON.parse(n)}catch{o=n}return{event:e,data:o}}export{w as a,R as b,S as c,P as d,A as e,C as f,$ as g};
|
|
5
|
+
//# sourceMappingURL=chunk-JG3O5GL6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tui/client.ts"],"sourcesContent":["import { loadDaemonConfig } from \"@/daemon/config\"\n\n// Resolved connection details for the daemon, derived from --node/--token\n// CLI flags first, then daemon config's `dashboard` block, then localhost.\nexport interface DaemonConn {\n baseUrl: string\n token: string\n}\n\nexport function resolveConn(opts: { node?: string; token?: string; config?: string }): DaemonConn {\n let baseUrl = typeof opts.node === \"string\" ? opts.node : \"\"\n let token = typeof opts.token === \"string\" ? opts.token : \"\"\n if (!baseUrl || !token) {\n try {\n const cfg = loadDaemonConfig(opts.config)\n if (!baseUrl) baseUrl = cfg.dashboard?.daemonUrl || \"\"\n if (!token) token = cfg.dashboard?.token || \"\"\n } catch {\n // No config — fall back to localhost.\n }\n }\n if (!baseUrl) baseUrl = \"http://localhost:18800\"\n return { baseUrl: baseUrl.replace(/\\/+$/, \"\"), token }\n}\n\nasync function get<T>(conn: DaemonConn, path: string, signal?: AbortSignal): Promise<T> {\n const headers: Record<string, string> = { Accept: \"application/json\" }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n const res = await fetch(`${conn.baseUrl}${path}`, { headers, signal })\n if (!res.ok) throw new Error(`GET ${path} → HTTP ${res.status}`)\n return (await res.json()) as T\n}\n\nexport interface AgentRow {\n id: string\n name: string\n tier: string\n model?: string\n workspace: string\n active: number\n total: number\n errors: number\n lastActive?: string\n}\n\nexport interface ProcessRow {\n key: { agentId: string; channel: string; chatId: string }\n pid: number | null\n state: string\n spawnedAt: number\n lastTurnAt: number\n turnCount: number\n}\n\nexport interface CronRow {\n id: string\n enabled: boolean\n schedule: string\n agent: string\n nextRun?: string\n lastError?: string\n consecutiveErrors: number\n}\n\nexport function fetchAgents(conn: DaemonConn, signal?: AbortSignal): Promise<AgentRow[]> {\n return get<AgentRow[]>(conn, \"/agents\", signal)\n}\n\nexport async function fetchProcesses(conn: DaemonConn, signal?: AbortSignal): Promise<ProcessRow[]> {\n const r = await get<{ processes: ProcessRow[] }>(conn, \"/api/processes\", signal)\n return r.processes ?? []\n}\n\nexport function fetchCrons(conn: DaemonConn, signal?: AbortSignal): Promise<CronRow[]> {\n return get<CronRow[]>(conn, \"/crons\", signal)\n}\n\nasync function post<T>(conn: DaemonConn, path: string, body: any, signal?: AbortSignal): Promise<T> {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n const res = await fetch(`${conn.baseUrl}${path}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal,\n })\n const text = await res.text()\n let parsed: any\n try { parsed = text ? JSON.parse(text) : {} } catch { parsed = { raw: text } }\n if (!res.ok) throw new Error(parsed?.error || `POST ${path} → HTTP ${res.status}`)\n return parsed as T\n}\n\nexport function killProcess(\n conn: DaemonConn,\n key: { agentId: string; channel: string; chatId: string },\n reason = \"tui\",\n): Promise<{ killed: { agentId: string; channel: string; chatId: string } }> {\n return post(conn, \"/api/processes/kill\", { ...key, reason })\n}\n\nexport interface TaskResponse {\n content?: string\n error?: string\n [k: string]: any\n}\n\nexport function sendTask(\n conn: DaemonConn,\n agentId: string,\n message: string,\n context?: { channel?: string; chatId?: string },\n): Promise<TaskResponse> {\n return post<TaskResponse>(conn, \"/task\", {\n agent: agentId,\n message,\n context: context ?? { channel: \"tui\", chatId: \"tui:operator\" },\n })\n}\n\n/** Live task events surfaced to a streaming client. Mirrors the daemon's\n * `POST /task` SSE wire (src/daemon/index.ts): `text` deltas, `thinking`\n * deltas, and `tool` badges (start/result). */\nexport interface StreamTaskHandlers {\n onText?: (text: string) => void\n onThinking?: (text: string) => void\n onTool?: (t: { status: \"start\" | \"result\"; id?: string; name?: string; error?: boolean; arg?: string }) => void\n}\n\nexport interface StreamTaskResult {\n content: string\n usage?: Record<string, number>\n duration?: number\n error?: string\n errorKind?: string\n}\n\n/**\n * Stream a task turn over SSE. POSTs `/task` with `Accept: text/event-stream`,\n * parses `event:/data:` frames, and invokes the handlers as tokens and tool\n * events arrive. Resolves with the final `done` payload (or an `error`).\n * Reuses the same (channel, chatId) warm-process semantics as sendTask.\n */\nexport async function streamTask(\n conn: DaemonConn,\n agentId: string,\n message: string,\n opts: { channel?: string; chatId?: string; signal?: AbortSignal } & StreamTaskHandlers = {},\n): Promise<StreamTaskResult> {\n const headers: Record<string, string> = {\n Accept: \"text/event-stream\",\n \"Content-Type\": \"application/json\",\n }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n\n const res = await fetch(`${conn.baseUrl}/task`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n agent: agentId,\n message,\n stream: true,\n context: { channel: opts.channel ?? \"chat-cli\", chatId: opts.chatId ?? \"chat-cli:operator\" },\n }),\n signal: opts.signal,\n })\n if (!res.ok || !res.body) {\n const body = await res.text().catch(() => \"\")\n throw new Error(`POST /task (stream) → HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : \"\"}`)\n }\n\n const reader = res.body.getReader()\n const dec = new TextDecoder()\n const result: StreamTaskResult = { content: \"\" }\n let buf = \"\"\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buf += dec.decode(value, { stream: true })\n let idx: number\n while ((idx = buf.indexOf(\"\\n\\n\")) >= 0) {\n const frame = buf.slice(0, idx)\n buf = buf.slice(idx + 2)\n const parsed = parseSseFrame(frame)\n if (!parsed) continue\n applyFrame(parsed, opts, result)\n }\n }\n } finally {\n try { reader.releaseLock() } catch { /* noop */ }\n }\n return result\n}\n\nfunction applyFrame(\n frame: { event: string; data: any },\n handlers: StreamTaskHandlers,\n result: StreamTaskResult,\n): void {\n const { event, data } = frame\n switch (event) {\n case \"text\":\n if (data?.text) { result.content += data.text; handlers.onText?.(data.text) }\n break\n case \"thinking\":\n if (data?.text) handlers.onThinking?.(data.text)\n break\n case \"tool\":\n handlers.onTool?.(data)\n break\n case \"done\":\n if (typeof data?.content === \"string\") result.content = data.content\n result.usage = data?.usage\n result.duration = data?.duration\n break\n case \"error\":\n result.error = data?.error\n result.errorKind = data?.errorKind\n break\n }\n}\n\n/** Parse one `event:/data:` SSE frame. Ignores comment/heartbeat lines. */\nfunction parseSseFrame(frame: string): { event: string; data: any } | null {\n let event = \"message\"\n let data = \"\"\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"event: \")) event = line.slice(7).trim()\n else if (line.startsWith(\"data: \")) data = line.slice(6)\n }\n if (!data) return null\n let payload: any\n try { payload = JSON.parse(data) } catch { payload = data }\n return { event, data: payload }\n}\n"],"mappings":"+CAAAA,IASO,SAASC,EAAYC,EAAsE,CAChG,IAAIC,EAAU,O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AAS,EAAGF,EAAQE,EAAK,MAAM,CAAC,EAAE,KAAK,EAClDA,EAAK,WAAW,QAAQ,IAAGD,EAAOC,EAAK,MAAM,CAAC,GAEzD,GAAI,CAACD,EAAM,OAAO,KAClB,IAAIE,EACJ,GAAI,CAAEA,EAAU,KAAK,MAAMF,CAAI,CAAE,MAAE,CAAQE,EAAUF,CAAK,CAC1D,MAAO,CAAE,MAAAD,EAAO,KAAMG,CAAQ,CAChC","names":["init_config","resolveConn","opts","baseUrl","token","cfg","loadDaemonConfig","get","conn","path","signal","headers","res","fetchAgents","fetchProcesses","fetchCrons","post","body","text","parsed","killProcess","key","reason","sendTask","agentId","message","context","streamTask","reader","dec","result","buf","done","value","idx","frame","parseSseFrame","applyFrame","handlers","event","data","line","payload"]}
|
|
1
|
+
{"version":3,"sources":["../src/tui/client.ts"],"sourcesContent":["import { loadDaemonConfig } from \"@/daemon/config\"\n\n// Resolved connection details for the daemon, derived from --node/--token\n// CLI flags first, then daemon config's `dashboard` block, then localhost.\nexport interface DaemonConn {\n baseUrl: string\n token: string\n}\n\nexport function resolveConn(opts: { node?: string; token?: string; config?: string }): DaemonConn {\n let baseUrl = typeof opts.node === \"string\" ? opts.node : \"\"\n let token = typeof opts.token === \"string\" ? opts.token : \"\"\n if (!baseUrl || !token) {\n try {\n const cfg = loadDaemonConfig(opts.config)\n if (!baseUrl) baseUrl = cfg.dashboard?.daemonUrl || \"\"\n if (!token) token = cfg.dashboard?.token || \"\"\n } catch {\n // No config — fall back to localhost.\n }\n }\n if (!baseUrl) baseUrl = \"http://localhost:18800\"\n return { baseUrl: baseUrl.replace(/\\/+$/, \"\"), token }\n}\n\nasync function get<T>(conn: DaemonConn, path: string, signal?: AbortSignal): Promise<T> {\n const headers: Record<string, string> = { Accept: \"application/json\" }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n const res = await fetch(`${conn.baseUrl}${path}`, { headers, signal })\n if (!res.ok) throw new Error(`GET ${path} → HTTP ${res.status}`)\n return (await res.json()) as T\n}\n\nexport interface AgentRow {\n id: string\n name: string\n tier: string\n model?: string\n workspace: string\n active: number\n total: number\n errors: number\n lastActive?: string\n}\n\nexport interface ProcessRow {\n key: { agentId: string; channel: string; chatId: string }\n pid: number | null\n state: string\n spawnedAt: number\n lastTurnAt: number\n turnCount: number\n}\n\nexport interface CronRow {\n id: string\n enabled: boolean\n schedule: string\n agent: string\n nextRun?: string\n lastError?: string\n consecutiveErrors: number\n}\n\nexport function fetchAgents(conn: DaemonConn, signal?: AbortSignal): Promise<AgentRow[]> {\n return get<AgentRow[]>(conn, \"/agents\", signal)\n}\n\nexport async function fetchProcesses(conn: DaemonConn, signal?: AbortSignal): Promise<ProcessRow[]> {\n const r = await get<{ processes: ProcessRow[] }>(conn, \"/api/processes\", signal)\n return r.processes ?? []\n}\n\nexport function fetchCrons(conn: DaemonConn, signal?: AbortSignal): Promise<CronRow[]> {\n return get<CronRow[]>(conn, \"/crons\", signal)\n}\n\nasync function post<T>(conn: DaemonConn, path: string, body: any, signal?: AbortSignal): Promise<T> {\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n const res = await fetch(`${conn.baseUrl}${path}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal,\n })\n const text = await res.text()\n let parsed: any\n try { parsed = text ? JSON.parse(text) : {} } catch { parsed = { raw: text } }\n if (!res.ok) throw new Error(parsed?.error || `POST ${path} → HTTP ${res.status}`)\n return parsed as T\n}\n\nexport function killProcess(\n conn: DaemonConn,\n key: { agentId: string; channel: string; chatId: string },\n reason = \"tui\",\n): Promise<{ killed: { agentId: string; channel: string; chatId: string } }> {\n return post(conn, \"/api/processes/kill\", { ...key, reason })\n}\n\nexport interface TaskResponse {\n content?: string\n error?: string\n [k: string]: any\n}\n\nexport function sendTask(\n conn: DaemonConn,\n agentId: string,\n message: string,\n context?: { channel?: string; chatId?: string },\n): Promise<TaskResponse> {\n return post<TaskResponse>(conn, \"/task\", {\n agent: agentId,\n message,\n context: context ?? { channel: \"tui\", chatId: \"tui:operator\" },\n })\n}\n\n/** Live task events surfaced to a streaming client. Mirrors the daemon's\n * `POST /task` SSE wire (src/daemon/index.ts): `text` deltas, `thinking`\n * deltas, and `tool` badges (start/result). */\nexport interface StreamTaskHandlers {\n onText?: (text: string) => void\n onThinking?: (text: string) => void\n onTool?: (t: { status: \"start\" | \"result\"; id?: string; name?: string; error?: boolean; arg?: string }) => void\n}\n\nexport interface StreamTaskResult {\n content: string\n usage?: Record<string, number>\n duration?: number\n error?: string\n errorKind?: string\n}\n\n/**\n * Stream a task turn over SSE. POSTs `/task` with `Accept: text/event-stream`,\n * parses `event:/data:` frames, and invokes the handlers as tokens and tool\n * events arrive. Resolves with the final `done` payload (or an `error`).\n * Reuses the same (channel, chatId) warm-process semantics as sendTask.\n */\nexport async function streamTask(\n conn: DaemonConn,\n agentId: string,\n message: string,\n opts: { channel?: string; chatId?: string; signal?: AbortSignal } & StreamTaskHandlers = {},\n): Promise<StreamTaskResult> {\n const headers: Record<string, string> = {\n Accept: \"text/event-stream\",\n \"Content-Type\": \"application/json\",\n }\n if (conn.token) headers[\"Authorization\"] = `Bearer ${conn.token}`\n\n const res = await fetch(`${conn.baseUrl}/task`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n agent: agentId,\n message,\n stream: true,\n context: { channel: opts.channel ?? \"chat-cli\", chatId: opts.chatId ?? \"chat-cli:operator\" },\n }),\n signal: opts.signal,\n })\n if (!res.ok || !res.body) {\n const body = await res.text().catch(() => \"\")\n throw new Error(`POST /task (stream) → HTTP ${res.status}${body ? `: ${body.slice(0, 200)}` : \"\"}`)\n }\n\n const reader = res.body.getReader()\n const dec = new TextDecoder()\n const result: StreamTaskResult = { content: \"\" }\n let buf = \"\"\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buf += dec.decode(value, { stream: true })\n let idx: number\n while ((idx = buf.indexOf(\"\\n\\n\")) >= 0) {\n const frame = buf.slice(0, idx)\n buf = buf.slice(idx + 2)\n const parsed = parseSseFrame(frame)\n if (!parsed) continue\n applyFrame(parsed, opts, result)\n }\n }\n } finally {\n try { reader.releaseLock() } catch { /* noop */ }\n }\n return result\n}\n\nfunction applyFrame(\n frame: { event: string; data: any },\n handlers: StreamTaskHandlers,\n result: StreamTaskResult,\n): void {\n const { event, data } = frame\n switch (event) {\n case \"text\":\n if (data?.text) { result.content += data.text; handlers.onText?.(data.text) }\n break\n case \"thinking\":\n if (data?.text) handlers.onThinking?.(data.text)\n break\n case \"tool\":\n handlers.onTool?.(data)\n break\n case \"done\":\n if (typeof data?.content === \"string\") result.content = data.content\n result.usage = data?.usage\n result.duration = data?.duration\n break\n case \"error\":\n result.error = data?.error\n result.errorKind = data?.errorKind\n break\n }\n}\n\n/** Parse one `event:/data:` SSE frame. Ignores comment/heartbeat lines. */\nfunction parseSseFrame(frame: string): { event: string; data: any } | null {\n let event = \"message\"\n let data = \"\"\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"event: \")) event = line.slice(7).trim()\n else if (line.startsWith(\"data: \")) data = line.slice(6)\n }\n if (!data) return null\n let payload: any\n try { payload = JSON.parse(data) } catch { payload = data }\n return { event, data: payload }\n}\n"],"mappings":"iDAAAA,IASO,SAASC,EAAYC,EAAsE,CAChG,IAAIC,EAAU,OAAOD,EAAK,MAAS,SAAWA,EAAK,KAAO,GACtDE,EAAQ,OAAOF,EAAK,OAAU,SAAWA,EAAK,MAAQ,GAC1D,GAAI,CAACC,GAAW,CAACC,EACf,GAAI,CACF,IAAMC,EAAMC,EAAiBJ,EAAK,MAAM,EACnCC,IAASA,EAAUE,EAAI,WAAW,WAAa,IAC/CD,IAAOA,EAAQC,EAAI,WAAW,OAAS,GAC9C,MAAE,CAEF,CAEF,OAAKF,IAASA,EAAU,0BACjB,CAAE,QAASA,EAAQ,QAAQ,OAAQ,EAAE,EAAG,MAAAC,CAAM,CACvD,CA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QJ,EAAI,MAAM,EAAGG,CAAG,EAC9BH,EAAMA,EAAI,MAAMG,EAAM,CAAC,EACvB,IAAMf,EAASiB,EAAcD,CAAK,EAC7BhB,GACLkB,EAAWlB,EAAQjB,EAAM4B,CAAM,GAGrC,QAAE,CACA,GAAI,CAAEF,EAAO,YAAY,CAAE,MAAE,CAAmB,CAClD,CACA,OAAOE,CACT,CAEA,SAASO,EACPF,EACAG,EACAR,EACM,CACN,GAAM,CAAE,MAAAS,EAAO,KAAAC,CAAK,EAAIL,EACxB,OAAQI,EAAO,CACb,IAAK,OACCC,GAAM,OAAQV,EAAO,SAAWU,EAAK,KAAMF,EAAS,SAASE,EAAK,IAAI,GAC1E,MACF,IAAK,WACCA,GAAM,MAAMF,EAAS,aAAaE,EAAK,IAAI,EAC/C,MACF,IAAK,OACHF,EAAS,SAASE,CAAI,EACtB,MACF,IAAK,OACC,OAAOA,GAAM,SAAY,WAAUV,EAAO,QAAUU,EAAK,SAC7DV,EAAO,MAAQU,GAAM,MACrBV,EAAO,SAAWU,GAAM,SACxB,MACF,IAAK,QACHV,EAAO,MAAQU,GAAM,MACrBV,EAAO,UAAYU,GAAM,UACzB,KACJ,CACF,CAGA,SAASJ,EAAcD,EAAoD,CACzE,IAAII,EAAQ,UACRC,EAAO,GACX,QAAWC,KAAQN,EAAM,MAAM;AAAA,CAAI,EAC7BM,EAAK,WAAW,SAAS,EAAGF,EAAQE,EAAK,MAAM,CAAC,EAAE,KAAK,EAClDA,EAAK,WAAW,QAAQ,IAAGD,EAAOC,EAAK,MAAM,CAAC,GAEzD,GAAI,CAACD,EAAM,OAAO,KAClB,IAAIE,EACJ,GAAI,CAAEA,EAAU,KAAK,MAAMF,CAAI,CAAE,MAAE,CAAQE,EAAUF,CAAK,CAC1D,MAAO,CAAE,MAAAD,EAAO,KAAMG,CAAQ,CAChC","names":["init_config","resolveConn","opts","baseUrl","token","cfg","loadDaemonConfig","get","conn","path","signal","headers","res","fetchAgents","fetchProcesses","fetchCrons","post","body","text","parsed","killProcess","key","reason","sendTask","agentId","message","context","streamTask","reader","dec","result","buf","done","value","idx","frame","parseSseFrame","applyFrame","handlers","event","data","line","payload"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/node-version.ts"],"sourcesContent":["// No imports here: src/cli.ts runs this before it loads anything else.\n\n// Keep in step with package.json \"engines\": undici 8 needs 22.19, and\n// better-sqlite3 ships prebuilt binaries up to Node 26.\nexport function nodeVersionSupported(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number)\n return (major === 22 && minor >= 19) || (major >= 23 && major <= 26)\n}\n\nexport function unsupportedNodeMessage(version: string): string | null {\n if (nodeVersionSupported(version)) return null\n return `AgentX needs Node.js 22.19 or newer, up to 26. This is Node.js ${version}.`\n}\n"],"mappings":"AAIO,SAASA,EAAqBC,EAA0B,CAC7D,GAAM,CAACC,EAAOC,CAAK,EAAIF,EAAQ,MAAM,GAAG,EAAE,IAAI,MAAM,EACpD,OAAQC,IAAU,IAAMC,GAAS,IAAQD,GAAS,IAAMA,GAAS,EACnE,CAEO,SAASE,EAAuBH,EAAgC,CACrE,OAAID,EAAqBC,CAAO,EAAU,KACnC,kEAAkEA,IAC3E","names":["nodeVersionSupported","version","major","minor","unsupportedNodeMessage"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a as h,b as m}from"./chunk-SHEUCITK.js";import{randomUUID as C}from"crypto";var w=["ringing","answered","later"],p=`id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,
|
|
2
|
+
ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,
|
|
3
|
+
ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`,f=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS calls (
|
|
4
|
+
id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,
|
|
5
|
+
urgency TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL,
|
|
6
|
+
ringing_since INTEGER, answered_at INTEGER, ended_at INTEGER,
|
|
7
|
+
ring_again_at INTEGER, note TEXT, summary TEXT);
|
|
8
|
+
CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`);let s=new Set(e.prepare("PRAGMA table_info(calls)").all().map(n=>n.name));s.has("kind")||e.exec("ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'"),s.has("channel")||e.exec("ALTER TABLE calls ADD COLUMN channel TEXT"),s.has("chat_id")||e.exec("ALTER TABLE calls ADD COLUMN chat_id TEXT")}insert(e){this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,
|
|
9
|
+
answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(e.id,e.agentId,e.kind,e.reason,e.urgency,e.status,e.createdAt,e.ringingSince,e.answeredAt,e.endedAt,e.ringAgainAt,e.note,e.summary,e.channel,e.chatId)}get(e){return this.db.prepare(`SELECT ${p} FROM calls WHERE id=?`).get(e)}update(e,s){let n={reason:"reason",urgency:"urgency",status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},t=Object.keys(s).filter(i=>i in n);if(t.length){let i=t.map(r=>`${n[r]}=?`).join(", ");this.db.prepare(`UPDATE calls SET ${i} WHERE id=?`).run(...t.map(r=>s[r]??null),e)}return this.get(e)}transition(e,s,n){let t=Array.isArray(s)?s:[s],i={status:"status",ringingSince:"ringing_since",answeredAt:"answered_at",endedAt:"ended_at",ringAgainAt:"ring_again_at",note:"note",summary:"summary"},r=Object.keys(n).filter(o=>o in i),l=r.map(o=>`${i[o]}=?`).join(", "),g=t.map(()=>"?").join(",");return this.db.prepare(`UPDATE calls SET ${l} WHERE id=? AND status IN (${g})`).run(...r.map(o=>n[o]??null),e,...t).changes?this.get(e):void 0}list(e={}){let s=Math.min(Math.max(e.limit??50,1),200),n=[],t=[];e.status?.length&&(n.push(`status IN (${e.status.map(()=>"?").join(",")})`),t.push(...e.status)),e.kind&&(n.push("kind=?"),t.push(e.kind));let i=n.length?`WHERE ${n.join(" AND ")}`:"";return this.db.prepare(`SELECT ${p} FROM calls ${i} ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(...t,s)}countSince(e,s){return this.db.prepare("SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?").get(e,s).n}};var A=200,S=1e4,k=10*6e4,_=10,y=240;function v(a=process.env){return a.AGENTX_TASK_ID?{"X-AgentX-Task":a.AGENTX_TASK_ID}:a.AGENTX_CHANNEL&&a.AGENTX_CHAT_ID?{"X-AgentX-Channel":a.AGENTX_CHANNEL,"X-AgentX-Chat":a.AGENTX_CHAT_ID}:{}}function I(a){return`[Call answered] The owner just picked up the voice call you asked for. You called because: "${a.reason}". Speak first: greet them in a few words and say why you called, then let them answer.`}var x="[Call ended] The owner hung up. In two or three plain sentences, summarise what was said and decided on this call, for your records. Reply with the summary only.",T=class{constructor(e){this.deps=e}widgetSeenAt=0;waiting=new Map;now(){return this.deps.now?.()??Date.now()}name(e){return this.deps.agentName(e)??e}async request(e,s={}){let n=String(e.agentId??"").trim(),t=String(e.reason??"").replace(/\s+/g," ").trim(),i=e.urgency==="urgent"?"urgent":"normal",r=e.kind==="camera"?"camera":"voice";if(e.kind!==void 0&&e.kind!=="voice"&&e.kind!=="camera")return{ok:!1,status:400,error:"kind must be voice or camera"};if(!n||!t)return{ok:!1,status:400,error:"Required: agentId and reason"};if(t.length>A)return{ok:!1,status:413,error:`reason is over ${A} characters; keep it to one line`};if(this.deps.agentName(n)===null)return{ok:!1,status:404,error:`Unknown agent: ${n}`};if(!this.deps.isRunningTurn(n,s))return{ok:!1,status:403,error:`No running turn of ${n} placed this call. An agent calls from inside its own run.`};let l=this.deps.config();if(!l.allow.includes("*")&&!l.allow.includes(n))return{ok:!1,status:403,error:`${n} ${r==="camera"?"may not ask to see through the owner's camera":"may not call the owner"}. Add it to calls.allow in agentx.json (or: agentx call allow ${n}).`};if(await this.sweep(),this.deps.store.list({status:w,limit:200}).some(u=>u.agentId===n))return{ok:!1,status:409,error:`${n} already has a call in progress`};let g=this.now();if(this.deps.store.countSince(n,g-36e5)>=l.maxPerHour)return{ok:!1,status:429,error:`${n} has placed ${l.maxPerHour} calls in the last hour (calls.maxPerHour)`};let d=r==="camera"?this.deps.turnSession?.(n,s)??s:{},o={id:`call-${C().slice(0,8)}`,agentId:n,kind:r,reason:t,urgency:i,status:"ringing",createdAt:g,ringingSince:g,answeredAt:null,endedAt:null,ringAgainAt:null,note:null,summary:null,channel:d.channel&&d.chatId?d.channel:null,chatId:d.channel&&d.chatId?d.chatId:null};this.deps.store.insert(o),this.deps.log?.(`[calls] ${n} asks ${r==="camera"?"to see":"for a call"} (${i}): ${t}`);let E=await this.ring(o);return{ok:!0,call:this.deps.store.get(o.id),rang:E}}async ring(e){let s=(this.deps.focus??h)();return s.active&&e.urgency!=="urgent"?(this.deps.store.transition(e.id,"ringing",{status:"missed",ringingSince:null,note:m(s)})&&await this.notice(e,this.missedTitle(e)),!1):e.kind==="camera"?(await this.notice(e,`${this.name(e.agentId)} wants to see through your camera`,`Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`),"notify"):this.widgetAlive()?"widget":(await this.notice(e,`${this.name(e.agentId)} is calling`,`Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`),"notify")}async notice(e,s,n){try{await this.deps.alert({title:s,message:n?`${e.reason}
|
|
10
|
+
${n}`:e.reason,urgent:e.urgency==="urgent",from:e.agentId})}catch(t){this.deps.log?.(`[calls] notice for ${e.id} failed: ${t?.message??t}`)}}missedTitle(e){return e.kind==="camera"?`${this.name(e.agentId)} asked to see through your camera`:`Missed call from ${this.name(e.agentId)}`}widgetAlive(){return this.now()-this.widgetSeenAt<S}async ringing(e={}){return this.widgetSeenAt=this.now(),await this.hold(e),await this.sweep(),this.deps.store.list({status:["ringing"],kind:"voice",limit:20}).reverse()}async hold(e){let s=this.now(),n=this.deps.store.list({status:["ringing"],kind:"voice",limit:20});for(let t of this.waiting.keys())n.some(i=>i.id===t)||this.waiting.delete(t);for(let t of n){if(t.id===e.showing){this.waiting.delete(t.id)&&this.deps.store.transition(t.id,"ringing",{ringingSince:s});continue}if(!e.busy)continue;let i=this.waiting.get(t.id);i!==void 0&&s-i>=k||!this.deps.store.transition(t.id,"ringing",{ringingSince:s})||i!==void 0||(this.waiting.set(t.id,s),this.deps.log?.(`[calls] ${t.id} from ${t.agentId} waits: the widget is busy`),await this.notice(t,`${this.name(t.agentId)} is calling`,"AgentX Voice is busy. The call rings when it is free."))}}async asking(){return await this.sweep(),this.deps.store.list({status:["ringing"],kind:"camera",limit:20}).reverse()}async sweep(){let e=this.now(),s=this.deps.config().ringSeconds*1e3,n=this.deps.config().maxCallMinutes*6e4;for(let t of this.deps.store.list({status:["ringing","later","answered"],limit:200}))if(t.status==="ringing"&&t.ringingSince!==null&&e-t.ringingSince>=s){if(!this.deps.store.transition(t.id,"ringing",{status:"missed",ringingSince:null,note:this.waiting.has(t.id)?"widget busy":"not answered"}))continue;this.deps.log?.(`[calls] ${t.id} from ${t.agentId} missed`),await this.notice(t,this.missedTitle(t))}else if(t.status==="answered"&&t.answeredAt!==null&&e-t.answeredAt>=n){if(!this.deps.store.transition(t.id,"answered",{status:"ended",endedAt:e,note:"no hang-up"}))continue;this.deps.log?.(`[calls] ${t.id} from ${t.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)}else if(t.status==="later"&&t.ringAgainAt!==null&&e>=t.ringAgainAt){let i=this.deps.store.transition(t.id,"later",{status:"ringing",ringingSince:e,ringAgainAt:null});i&&await this.ring(i)}}answer(e){let s=this.deps.store.get(e);if(!s)return c(e);let n=this.deps.store.transition(e,"ringing",{status:"answered",answeredAt:this.now(),ringingSince:null});return n?(this.deps.log?.(`[calls] ${e} answered (${s.agentId})`),n.kind==="camera"?{ok:!0,call:n}:{ok:!0,call:n,opener:I(n)}):{ok:!1,status:409,error:`call is ${this.deps.store.get(e)?.status}, not ringing`}}decline(e){if(!this.deps.store.get(e))return c(e);let n=this.deps.store.transition(e,["ringing","later"],{status:"declined",endedAt:this.now(),ringingSince:null,ringAgainAt:null});return n?{ok:!0,call:n}:{ok:!1,status:409,error:`call is ${this.deps.store.get(e)?.status}`}}later(e,s){if(!this.deps.store.get(e))return c(e);let t=s===void 0?_:Number(s);if(!Number.isInteger(t)||t<1||t>y)return{ok:!1,status:400,error:`minutes must be a whole number from 1 to ${y}`};let i=this.deps.store.transition(e,"ringing",{status:"later",ringingSince:null,ringAgainAt:this.now()+t*6e4});return i?{ok:!0,call:i}:{ok:!1,status:409,error:`call is ${this.deps.store.get(e)?.status}, not ringing`}}hangup(e){let s=this.deps.store.get(e);if(!s)return c(e);let n=this.deps.store.transition(e,"answered",{status:"ended",endedAt:this.now()});if(!n)return{ok:!1,status:409,error:`call is ${s.status}, not answered`};this.deps.log?.(`[calls] ${e} ended (${s.agentId})`);let t=this.deps.summarize;if(n.kind==="camera"||!this.deps.config().summary||!t)return{ok:!0,call:n};let i=(async()=>{try{let r=(await t(n))?.trim();if(!r)return;let l=this.deps.store.update(e,{summary:r});this.deps.file?.(l,r)}catch(r){this.deps.log?.(`[calls] summary for ${e} failed: ${r?.message??r}`)}})();return{ok:!0,call:n,summarized:i}}endCamera(e,s){let n=this.deps.store.get(e);if(!n||n.kind!=="camera")return!1;let t=this.deps.store.transition(e,"answered",{status:"ended",endedAt:this.now(),note:s??null});return t&&this.deps.log?.(`[calls] ${e} ended (${n.agentId}): ${s??"share over"}`),!!t}get(e){return this.deps.store.get(e)}list(e={}){return this.deps.store.list(e)}},c=a=>({ok:!1,status:404,error:`No such call: ${a}`});export{f as a,v as b,x as c,T as d};
|
|
11
|
+
//# sourceMappingURL=chunk-LLNPKE7H.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/calls/service.ts","../src/calls/store.ts"],"sourcesContent":["// --- An agent rings the owner (#321) ---\n//\n// An agent that needs the owner directly asks for a call. It rings on the\n// desktop widget (AgentX Voice), which polls `ringing()`. Answering starts\n// the widget's hands-free conversation with that agent, which opens with\n// its reason. When the widget is not running, `notify` stands in. While\n// the widget is busy (a turn, the microphone, another call) the call waits\n// for it: its ring time does not run, and the owner is told once (#408).\n//\n// Checked before anything rings, in this order:\n// 0. the caller is that agent: a turn of it is running now, named by its\n// task id or by its channel and chat (see CallerProof),\n// 1. the owner allows this agent (calls.allow; empty allows nobody),\n// 2. the agent has no other call in progress,\n// 3. it is under calls.maxPerHour,\n// 4. Focus: a non-urgent call does not ring. It becomes a missed call,\n// and its notice goes through notify, which holds it until Focus\n// ends. Urgent calls ring through, as `notify --urgent` does.\n//\n// A camera ask (#325 phase 3, kind \"camera\") goes through the same checks\n// and the same table. It never rings the widget: the notice goes to the\n// phone through notify, and the phone app polls `asking()` to show a\n// Show / Decline bar. Answering it is the owner tapping Show; the camera\n// opens only then, and the share ends the ask (see camera-api.ts).\n\nimport { randomUUID } from \"crypto\"\nimport { focusLabel, readFocus, type FocusState } from \"@/notify/focus\"\nimport type { CallsConfig } from \"@/daemon/config\"\nimport { LIVE, type Call, type CallKind, type CallStore, type CallUrgency } from \"./store\"\n\nexport const REASON_MAX = 200\n/** The widget polls every 2 s; missing this long means it is not running. */\nexport const WIDGET_FRESH_MS = 10_000\n/** The longest a call waits for a busy widget before its ring time runs. */\nexport const BUSY_WAIT_MAX_MS = 10 * 60_000\nexport const LATER_DEFAULT_MINUTES = 10\nexport const LATER_MAX_MINUTES = 240\n\nexport type CallResult =\n | { ok: true; call: Call }\n | { ok: false; status: number; error: string }\n\n/** What the request says about the turn placing it: the run's\n * AGENTX_TASK_ID, or, for a warm process that has none, its\n * AGENTX_CHANNEL and AGENTX_CHAT_ID. Loopback is not an identity. */\nexport interface CallerProof {\n taskId?: string\n channel?: string\n chatId?: string\n}\n\n/** The proof headers for a call placed from inside an agent's run. */\nexport function callerHeaders(env: NodeJS.ProcessEnv = process.env): Record<string, string> {\n if (env.AGENTX_TASK_ID) return { \"X-AgentX-Task\": env.AGENTX_TASK_ID }\n if (env.AGENTX_CHANNEL && env.AGENTX_CHAT_ID) {\n return { \"X-AgentX-Channel\": env.AGENTX_CHANNEL, \"X-AgentX-Chat\": env.AGENTX_CHAT_ID }\n }\n return {}\n}\n\n/** What the widget says with its poll. A widget from before #408 says nothing. */\nexport interface WidgetState {\n /** It cannot ring a new call now. */\n busy?: boolean\n /** The call ringing on it. */\n showing?: string\n}\n\nexport interface CallDeps {\n store: CallStore\n config: () => CallsConfig\n /** The agent's display name, or null when there is no such agent here. */\n agentName: (agentId: string) => string | null\n /** True when `proof` names a running turn of `agentId`. */\n isRunningTurn: (agentId: string, proof: CallerProof) => boolean\n /** The channel and chat of that running turn, when it has one, so a\n * camera ask is answered where it was asked. Unset: only a proof that\n * names them itself is kept. */\n turnSession?: (agentId: string, proof: CallerProof) => { channel?: string; chatId?: string } | null\n /** Tell the owner through notify. `urgent` passes Focus, like notify --urgent. */\n alert: (notice: { title: string; message: string; urgent: boolean; from: string }) => Promise<void>\n /** Ask the agent, in its voice session, to summarise the call. */\n summarize?: (call: Call) => Promise<string | null>\n /** File a finished summary where the dashboard shows it. */\n file?: (call: Call, summary: string) => void\n focus?: () => FocusState\n now?: () => number\n log?: (m: string) => void\n}\n\n/** What the widget sends through /ask when the owner answers, so the\n * agent speaks first and says why it called. */\nexport function openerPrompt(call: Pick<Call, \"reason\">): string {\n return \"[Call answered] The owner just picked up the voice call you asked for. \" +\n `You called because: \"${call.reason}\". Speak first: greet them in a few words ` +\n \"and say why you called, then let them answer.\"\n}\n\nexport const SUMMARY_PROMPT =\n \"[Call ended] The owner hung up. In two or three plain sentences, summarise what \" +\n \"was said and decided on this call, for your records. Reply with the summary only.\"\n\nexport class CallService {\n private widgetSeenAt = 0\n /** Calls waiting for a busy widget, and since when. */\n private waiting = new Map<string, number>()\n\n constructor(private deps: CallDeps) {}\n\n private now(): number { return this.deps.now?.() ?? Date.now() }\n private name(agentId: string): string { return this.deps.agentName(agentId) ?? agentId }\n\n /** An agent asks for a call, or to see (kind \"camera\"). 201 ringing,\n * 202 held as missed (Focus). */\n async request(input: { agentId?: unknown; reason?: unknown; urgency?: unknown; kind?: unknown }, proof: CallerProof = {}): Promise<CallResult & { rang?: \"widget\" | \"notify\" | false }> {\n const agentId = String(input.agentId ?? \"\").trim()\n const reason = String(input.reason ?? \"\").replace(/\\s+/g, \" \").trim()\n const urgency: CallUrgency = input.urgency === \"urgent\" ? \"urgent\" : \"normal\"\n const kind: CallKind = input.kind === \"camera\" ? \"camera\" : \"voice\"\n if (input.kind !== undefined && input.kind !== \"voice\" && input.kind !== \"camera\") return { ok: false, status: 400, error: \"kind must be voice or camera\" }\n if (!agentId || !reason) return { ok: false, status: 400, error: \"Required: agentId and reason\" }\n if (reason.length > REASON_MAX) return { ok: false, status: 413, error: `reason is over ${REASON_MAX} characters; keep it to one line` }\n if (this.deps.agentName(agentId) === null) return { ok: false, status: 404, error: `Unknown agent: ${agentId}` }\n if (!this.deps.isRunningTurn(agentId, proof)) {\n return { ok: false, status: 403, error: `No running turn of ${agentId} placed this call. An agent calls from inside its own run.` }\n }\n\n const cfg = this.deps.config()\n if (!cfg.allow.includes(\"*\") && !cfg.allow.includes(agentId)) {\n const verb = kind === \"camera\" ? \"may not ask to see through the owner's camera\" : \"may not call the owner\"\n return { ok: false, status: 403, error: `${agentId} ${verb}. Add it to calls.allow in agentx.json (or: agentx call allow ${agentId}).` }\n }\n await this.sweep()\n if (this.deps.store.list({ status: LIVE, limit: 200 }).some((c) => c.agentId === agentId)) {\n return { ok: false, status: 409, error: `${agentId} already has a call in progress` }\n }\n const now = this.now()\n if (this.deps.store.countSince(agentId, now - 3_600_000) >= cfg.maxPerHour) {\n return { ok: false, status: 429, error: `${agentId} has placed ${cfg.maxPerHour} calls in the last hour (calls.maxPerHour)` }\n }\n\n // Where the ask came from, for kind \"camera\": the turn's own chat, or\n // the one the proof names. A task run has neither.\n const session: { channel?: string; chatId?: string } = kind === \"camera\" ? (this.deps.turnSession?.(agentId, proof) ?? proof) : {}\n const call: Call = {\n id: `call-${randomUUID().slice(0, 8)}`, agentId, kind, reason, urgency, status: \"ringing\", createdAt: now,\n ringingSince: now, answeredAt: null, endedAt: null, ringAgainAt: null, note: null, summary: null,\n channel: session.channel && session.chatId ? session.channel : null,\n chatId: session.channel && session.chatId ? session.chatId : null,\n }\n this.deps.store.insert(call)\n this.deps.log?.(`[calls] ${agentId} asks ${kind === \"camera\" ? \"to see\" : \"for a call\"} (${urgency}): ${reason}`)\n const rang = await this.ring(call)\n const saved = this.deps.store.get(call.id)!\n return { ok: true, call: saved, rang }\n }\n\n /** Ring now, or hold as missed in Focus. Returns how it rang. */\n private async ring(call: Call): Promise<\"widget\" | \"notify\" | false> {\n const focus = (this.deps.focus ?? readFocus)()\n if (focus.active && call.urgency !== \"urgent\") {\n if (!this.deps.store.transition(call.id, \"ringing\", { status: \"missed\", ringingSince: null, note: focusLabel(focus) })) return false\n await this.notice(call, this.missedTitle(call))\n return false\n }\n // A camera ask is answered on the phone, never on the widget.\n if (call.kind === \"camera\") {\n await this.notice(call, `${this.name(call.agentId)} wants to see through your camera`,\n `Open the phone app and tap Show within ${this.deps.config().ringSeconds} s.`)\n return \"notify\"\n }\n if (this.widgetAlive()) return \"widget\"\n await this.notice(call, `${this.name(call.agentId)} is calling`,\n `Open AgentX Voice to answer within ${this.deps.config().ringSeconds} s.`)\n return \"notify\"\n }\n\n private async notice(call: Call, title: string, extra?: string): Promise<void> {\n try {\n await this.deps.alert({\n title, message: extra ? `${call.reason}\\n${extra}` : call.reason,\n urgent: call.urgency === \"urgent\", from: call.agentId,\n })\n } catch (e: any) {\n this.deps.log?.(`[calls] notice for ${call.id} failed: ${e?.message ?? e}`)\n }\n }\n\n private missedTitle(call: Call): string {\n return call.kind === \"camera\" ? `${this.name(call.agentId)} asked to see through your camera` : `Missed call from ${this.name(call.agentId)}`\n }\n\n /** True when the widget polled recently. */\n widgetAlive(): boolean {\n return this.now() - this.widgetSeenAt < WIDGET_FRESH_MS\n }\n\n /** The widget's poll: voice calls ringing now, oldest first. Marks it alive. */\n async ringing(widget: WidgetState = {}): Promise<Call[]> {\n this.widgetSeenAt = this.now()\n await this.hold(widget)\n await this.sweep()\n return this.deps.store.list({ status: [\"ringing\"], kind: \"voice\", limit: 20 }).reverse()\n }\n\n /** A busy widget cannot ring: the ring time of each call it is not\n * showing starts over at every poll, for BUSY_WAIT_MAX_MS at most, and\n * the owner is told once that the call waits. It starts over once more\n * when the widget first shows a call that waited. */\n private async hold(widget: WidgetState): Promise<void> {\n const now = this.now()\n const live = this.deps.store.list({ status: [\"ringing\"], kind: \"voice\", limit: 20 })\n for (const id of this.waiting.keys()) if (!live.some((c) => c.id === id)) this.waiting.delete(id)\n for (const call of live) {\n if (call.id === widget.showing) {\n if (this.waiting.delete(call.id)) this.deps.store.transition(call.id, \"ringing\", { ringingSince: now })\n continue\n }\n if (!widget.busy) continue\n const since = this.waiting.get(call.id)\n if (since !== undefined && now - since >= BUSY_WAIT_MAX_MS) continue\n if (!this.deps.store.transition(call.id, \"ringing\", { ringingSince: now }) || since !== undefined) continue\n this.waiting.set(call.id, now)\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} waits: the widget is busy`)\n await this.notice(call, `${this.name(call.agentId)} is calling`, \"AgentX Voice is busy. The call rings when it is free.\")\n }\n }\n\n /** The phone app's poll: camera asks waiting for the owner, oldest first.\n * Does not count as the widget being up. */\n async asking(): Promise<Call[]> {\n await this.sweep()\n return this.deps.store.list({ status: [\"ringing\"], kind: \"camera\", limit: 20 }).reverse()\n }\n\n /** Unanswered calls become missed; \"later\" calls that came due ring\n * again; answered calls nobody hung up end after calls.maxCallMinutes. */\n async sweep(): Promise<void> {\n const now = this.now()\n const ringFor = this.deps.config().ringSeconds * 1000\n const talkFor = this.deps.config().maxCallMinutes * 60_000\n for (const call of this.deps.store.list({ status: [\"ringing\", \"later\", \"answered\"], limit: 200 })) {\n // The list was read before any await below: each move re-checks the\n // status in the store, so a call answered meanwhile is left alone.\n if (call.status === \"ringing\" && call.ringingSince !== null && now - call.ringingSince >= ringFor) {\n if (!this.deps.store.transition(call.id, \"ringing\", { status: \"missed\", ringingSince: null, note: this.waiting.has(call.id) ? \"widget busy\" : \"not answered\" })) continue\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} missed`)\n await this.notice(call, this.missedTitle(call))\n } else if (call.status === \"answered\" && call.answeredAt !== null && now - call.answeredAt >= talkFor) {\n if (!this.deps.store.transition(call.id, \"answered\", { status: \"ended\", endedAt: now, note: \"no hang-up\" })) continue\n this.deps.log?.(`[calls] ${call.id} from ${call.agentId} ended: no hang-up in ${this.deps.config().maxCallMinutes} min`)\n } else if (call.status === \"later\" && call.ringAgainAt !== null && now >= call.ringAgainAt) {\n const again = this.deps.store.transition(call.id, \"later\", { status: \"ringing\", ringingSince: now, ringAgainAt: null })\n if (again) await this.ring(again)\n }\n }\n }\n\n /** The owner picked up, or tapped Show. Returns the call and, for a\n * voice call, the opener for /ask. */\n answer(id: string): CallResult & { opener?: string } {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const answered = this.deps.store.transition(id, \"ringing\", { status: \"answered\", answeredAt: this.now(), ringingSince: null })\n if (!answered) return { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}, not ringing` }\n this.deps.log?.(`[calls] ${id} answered (${call.agentId})`)\n return answered.kind === \"camera\" ? { ok: true, call: answered } : { ok: true, call: answered, opener: openerPrompt(answered) }\n }\n\n decline(id: string): CallResult {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const declined = this.deps.store.transition(id, [\"ringing\", \"later\"], { status: \"declined\", endedAt: this.now(), ringingSince: null, ringAgainAt: null })\n return declined ? { ok: true, call: declined } : { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}` }\n }\n\n /** \"Call back in N min\": it rings again then. */\n later(id: string, minutes?: unknown): CallResult {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const n = minutes === undefined ? LATER_DEFAULT_MINUTES : Number(minutes)\n if (!Number.isInteger(n) || n < 1 || n > LATER_MAX_MINUTES) {\n return { ok: false, status: 400, error: `minutes must be a whole number from 1 to ${LATER_MAX_MINUTES}` }\n }\n const later = this.deps.store.transition(id, \"ringing\", { status: \"later\", ringingSince: null, ringAgainAt: this.now() + n * 60_000 })\n return later ? { ok: true, call: later } : { ok: false, status: 409, error: `call is ${this.deps.store.get(id)?.status}, not ringing` }\n }\n\n /** End an answered call. The summary is written in the background;\n * `summarized` settles when it is filed (tests wait on it). */\n hangup(id: string): CallResult & { summarized?: Promise<void> } {\n const call = this.deps.store.get(id)\n if (!call) return unknown(id)\n const ended = this.deps.store.transition(id, \"answered\", { status: \"ended\", endedAt: this.now() })\n if (!ended) return { ok: false, status: 409, error: `call is ${call.status}, not answered` }\n this.deps.log?.(`[calls] ${id} ended (${call.agentId})`)\n const summarize = this.deps.summarize\n // What the agent saw is already its answer; only a voice call is summarised.\n if (ended.kind === \"camera\" || !this.deps.config().summary || !summarize) return { ok: true, call: ended }\n const summarized = (async () => {\n try {\n const text = (await summarize(ended))?.trim()\n if (!text) return\n const done = this.deps.store.update(id, { summary: text })!\n this.deps.file?.(done, text)\n } catch (e: any) {\n this.deps.log?.(`[calls] summary for ${id} failed: ${e?.message ?? e}`)\n }\n })()\n return { ok: true, call: ended, summarized }\n }\n\n /** A camera ask ends when the share ends; no summary. Only an answered\n * ask ends this way, so a stop before Show leaves it ringing. */\n endCamera(id: string, note?: string): boolean {\n const call = this.deps.store.get(id)\n if (!call || call.kind !== \"camera\") return false\n const ended = this.deps.store.transition(id, \"answered\", { status: \"ended\", endedAt: this.now(), note: note ?? null })\n if (ended) this.deps.log?.(`[calls] ${id} ended (${call.agentId}): ${note ?? \"share over\"}`)\n return !!ended\n }\n\n get(id: string): Call | undefined { return this.deps.store.get(id) }\n\n list(opts: Parameters<CallStore[\"list\"]>[0] = {}): Call[] { return this.deps.store.list(opts) }\n}\n\nconst unknown = (id: string): CallResult => ({ ok: false, status: 404, error: `No such call: ${id}` })\n","// --- Calls an agent placed to the owner, kept in SQLite ---\n//\n// One row per call, so a missed call is still there after a restart and\n// the dashboard can list them. Nothing else reads this table. A camera\n// ask (#325 phase 3: \"show me\") is a call of kind \"camera\": same\n// allowlist, same hourly limit, same lifecycle, answered on the phone\n// instead of the voice widget.\n\nimport type Database from \"better-sqlite3\"\n\nexport type CallStatus = \"ringing\" | \"answered\" | \"ended\" | \"declined\" | \"missed\" | \"later\"\nexport type CallUrgency = \"normal\" | \"urgent\"\n/** \"voice\": a live voice call on the widget. \"camera\": the agent asks to see through the phone camera. */\nexport type CallKind = \"voice\" | \"camera\"\n\nexport interface Call {\n id: string\n agentId: string\n kind: CallKind\n reason: string\n urgency: CallUrgency\n status: CallStatus\n /** The channel and chat the asking turn ran in, so what the agent sees\n * is answered there; null when the turn had none (a task run). */\n channel: string | null\n chatId: string | null\n /** When the agent asked, ms since the epoch. */\n createdAt: number\n /** When it last started ringing: at the request, or when \"later\" came due. */\n ringingSince: number | null\n answeredAt: number | null\n endedAt: number | null\n /** Status \"later\": when it rings again. */\n ringAgainAt: number | null\n /** Why it ended the way it did, in a few words (\"in Focus\", \"not answered\"). */\n note: string | null\n /** The agent's own summary, written after hang-up. */\n summary: string | null\n}\n\n/** Calls still in progress: an agent has at most one of these. */\nexport const LIVE: CallStatus[] = [\"ringing\", \"answered\", \"later\"]\n\nconst COLUMNS = `id, agent_id AS agentId, kind, reason, urgency, status, created_at AS createdAt,\n ringing_since AS ringingSince, answered_at AS answeredAt, ended_at AS endedAt,\n ring_again_at AS ringAgainAt, note, summary, channel, chat_id AS chatId`\n\nexport class CallStore {\n constructor(private db: Database.Database) {\n db.exec(`CREATE TABLE IF NOT EXISTS calls (\n id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, reason TEXT NOT NULL,\n urgency TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL,\n ringing_since INTEGER, answered_at INTEGER, ended_at INTEGER,\n ring_again_at INTEGER, note TEXT, summary TEXT);\n CREATE INDEX IF NOT EXISTS calls_recent ON calls(created_at DESC);`)\n // Columns added since the table first shipped (#325 phase 3). A row\n // from before is a voice call from a turn whose chat was not kept.\n const have = new Set((db.prepare(\"PRAGMA table_info(calls)\").all() as Array<{ name: string }>).map((c) => c.name))\n if (!have.has(\"kind\")) db.exec(\"ALTER TABLE calls ADD COLUMN kind TEXT NOT NULL DEFAULT 'voice'\")\n if (!have.has(\"channel\")) db.exec(\"ALTER TABLE calls ADD COLUMN channel TEXT\")\n if (!have.has(\"chat_id\")) db.exec(\"ALTER TABLE calls ADD COLUMN chat_id TEXT\")\n }\n\n insert(call: Call): void {\n this.db.prepare(`INSERT INTO calls (id, agent_id, kind, reason, urgency, status, created_at, ringing_since,\n answered_at, ended_at, ring_again_at, note, summary, channel, chat_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(\n call.id, call.agentId, call.kind, call.reason, call.urgency, call.status, call.createdAt,\n call.ringingSince, call.answeredAt, call.endedAt, call.ringAgainAt, call.note, call.summary, call.channel, call.chatId)\n }\n\n get(id: string): Call | undefined {\n return this.db.prepare(`SELECT ${COLUMNS} FROM calls WHERE id=?`).get(id) as Call | undefined\n }\n\n /** Write the changed fields of one call. */\n update(id: string, patch: Partial<Omit<Call, \"id\" | \"agentId\" | \"createdAt\">>): Call | undefined {\n const cols: Record<string, string> = {\n reason: \"reason\", urgency: \"urgency\", status: \"status\", ringingSince: \"ringing_since\",\n answeredAt: \"answered_at\", endedAt: \"ended_at\", ringAgainAt: \"ring_again_at\", note: \"note\", summary: \"summary\",\n }\n const keys = Object.keys(patch).filter((k) => k in cols)\n if (keys.length) {\n const set = keys.map((k) => `${cols[k]}=?`).join(\", \")\n this.db.prepare(`UPDATE calls SET ${set} WHERE id=?`).run(...keys.map((k) => (patch as any)[k] ?? null), id)\n }\n return this.get(id)\n }\n\n /** Change a call only if it is still `from`: the check and the write are\n * one statement, so two sweeps, or a sweep and the owner answering,\n * cannot both move the same call. Undefined when it had moved on. */\n transition(id: string, from: CallStatus | CallStatus[], patch: Partial<Omit<Call, \"id\" | \"agentId\" | \"createdAt\">>): Call | undefined {\n const statuses = Array.isArray(from) ? from : [from]\n const cols: Record<string, string> = {\n status: \"status\", ringingSince: \"ringing_since\", answeredAt: \"answered_at\", endedAt: \"ended_at\",\n ringAgainAt: \"ring_again_at\", note: \"note\", summary: \"summary\",\n }\n const keys = Object.keys(patch).filter((k) => k in cols)\n const set = keys.map((k) => `${cols[k]}=?`).join(\", \")\n const marks = statuses.map(() => \"?\").join(\",\")\n const changed = this.db.prepare(`UPDATE calls SET ${set} WHERE id=? AND status IN (${marks})`)\n .run(...keys.map((k) => (patch as any)[k] ?? null), id, ...statuses).changes\n return changed ? this.get(id) : undefined\n }\n\n /** Newest first; only these statuses, and only this kind, when given. */\n list(opts: { status?: CallStatus[]; kind?: CallKind; limit?: number } = {}): Call[] {\n const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200)\n const where: string[] = []\n const args: unknown[] = []\n if (opts.status?.length) {\n where.push(`status IN (${opts.status.map(() => \"?\").join(\",\")})`)\n args.push(...opts.status)\n }\n if (opts.kind) { where.push(\"kind=?\"); args.push(opts.kind) }\n const filter = where.length ? `WHERE ${where.join(\" AND \")}` : \"\"\n return this.db.prepare(`SELECT ${COLUMNS} FROM calls ${filter} ORDER BY created_at DESC, rowid DESC LIMIT ?`)\n .all(...args, limit) as Call[]\n }\n\n /** Calls this agent placed after `since` (ms), for the hourly limit. */\n countSince(agentId: string, since: number): number {\n return (this.db.prepare(\"SELECT COUNT(*) AS n FROM calls WHERE agent_id=? AND created_at>?\")\n .get(agentId, since) as { n: number }).n\n }\n}\n"],"mappings":"+CAyBA,OAAS,cAAAA,MAAkB,SCgBpB,IAAMC,EAAqB,CAAC,UAAW,WAAY,OAAO,EAE3DC,EAA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,WAAAE,CAAW,CAC7C,CAIA,UAAUb,EAAYgB,EAAwB,CAC5C,IAAMzC,EAAO,KAAK,KAAK,MAAM,IAAIyB,CAAE,EACnC,GAAI,CAACzB,GAAQA,EAAK,OAAS,SAAU,MAAO,GAC5C,IAAMoC,EAAQ,KAAK,KAAK,MAAM,WAAWX,EAAI,WAAY,CAAE,OAAQ,QAAS,QAAS,KAAK,IAAI,EAAG,KAAMgB,GAAQ,IAAK,CAAC,EACrH,OAAIL,GAAO,KAAK,KAAK,MAAM,WAAWX,YAAazB,EAAK,aAAayC,GAAQ,cAAc,EACpF,CAAC,CAACL,CACX,CAEA,IAAIX,EAA8B,CAAE,OAAO,KAAK,KAAK,MAAM,IAAIA,CAAE,CAAE,CAEnE,KAAKiB,EAAyC,CAAC,EAAW,CAAE,OAAO,KAAK,KAAK,MAAM,KAAKA,CAAI,CAAE,CAChG,EAEMZ,EAAWL,IAA4B,CAAE,GAAI,GAAO,OAAQ,IAAK,MAAO,iBAAiBA,GAAK","names":["randomUUID","LIVE","COLUMNS","CallStore","db","have","c","call","id","patch","cols","keys","k","set","from","statuses","marks","opts","limit","where","args","filter","agentId","since","REASON_MAX","WIDGET_FRESH_MS","BUSY_WAIT_MAX_MS","LATER_DEFAULT_MINUTES","LATER_MAX_MINUTES","callerHeaders","env","openerPrompt","call","SUMMARY_PROMPT","CallService","deps","agentId","input","proof","reason","urgency","kind","cfg","LIVE","c","now","session","randomUUID","rang","focus","readFocus","focusLabel","title","extra","e","widget","live","id","since","ringFor","talkFor","again","unknown","answered","declined","minutes","n","later","ended","summarize","summarized","text","done","note","opts"]}
|