agentix-cli 0.164.0 → 0.165.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/dist/{App-4PQX4N6S.js → App-NV2JJMHN.js} +2 -2
- package/dist/{ChatApp-NHB5VPUE.js → ChatApp-CIGDPS3A.js} +2 -2
- package/dist/{absorb-eval-PWLEKRFA.js → absorb-eval-VPAASHZG.js} +2 -2
- package/dist/{agent-USWAFKWO.js → agent-UFMIPTQZ.js} +2 -2
- package/dist/{board-dashboard-F2TCMJCZ.js → board-dashboard-NUEVGTM7.js} +551 -385
- package/dist/board-dashboard-NUEVGTM7.js.map +1 -0
- package/dist/{chunk-K7ZUE7SG.js → chunk-4SJ2VFVI.js} +2 -2
- package/dist/{chunk-EGCWS56X.js → chunk-6Y53LLIX.js} +2 -2
- package/dist/{chunk-H4DQGVUG.js → chunk-73SESASJ.js} +2 -2
- package/dist/{chunk-AM2DYH7Y.js → chunk-A3GDFLFB.js} +2 -2
- package/dist/{chunk-MYEEWFXP.js → chunk-AXDNFXYU.js} +2 -2
- package/dist/{chunk-EJFJBYDJ.js → chunk-BC7VOHNH.js} +2 -2
- package/dist/{chunk-3S2BNZHX.js → chunk-CDPQQAK6.js} +2 -2
- package/dist/{chunk-QLN4W2KV.js → chunk-CGE5EAWC.js} +2 -2
- package/dist/{chunk-C65BZPUE.js → chunk-CRUNUMVO.js} +2 -2
- package/dist/{chunk-CLHIE4UW.js → chunk-DAWJHJKD.js} +10 -10
- package/dist/{chunk-CLHIE4UW.js.map → chunk-DAWJHJKD.js.map} +1 -1
- package/dist/{chunk-KDDCIOS7.js → chunk-EXJGRK2N.js} +2 -2
- package/dist/{chunk-IMERQYQ6.js → chunk-FK2TJZNJ.js} +2 -2
- package/dist/{chunk-JCOLQ6MO.js → chunk-GJ4SQRAE.js} +2 -2
- package/dist/{chunk-6JFGNRC3.js → chunk-ILHTAVZZ.js} +6 -6
- package/dist/{chunk-6JFGNRC3.js.map → chunk-ILHTAVZZ.js.map} +1 -1
- package/dist/{chunk-KKOULF3I.js → chunk-IVTO54EM.js} +2 -2
- package/dist/{chunk-GJMXUROS.js → chunk-KTJ6234K.js} +268 -268
- package/dist/chunk-KTJ6234K.js.map +1 -0
- package/dist/{chunk-TW2PBGYA.js → chunk-KVSHZKAL.js} +2 -2
- package/dist/{chunk-CR55SCRE.js → chunk-NCEYJFF5.js} +2 -2
- package/dist/{chunk-UD3WIY2B.js → chunk-ON7Y3JSP.js} +3 -3
- package/dist/{chunk-HGQKZKXL.js → chunk-PSTEWKR3.js} +2 -2
- package/dist/{chunk-I53O35TO.js → chunk-QT63Q6C5.js} +2 -2
- package/dist/{chunk-Z5JVYKVH.js → chunk-RUB4HZEG.js} +2 -2
- package/dist/{chunk-UY64KKNE.js → chunk-S6ZZKRDB.js} +2 -2
- package/dist/{chunk-BRNAE6ET.js → chunk-T5IGXFSW.js} +2 -2
- package/dist/{chunk-OO7T7E4O.js → chunk-TADIDWYZ.js} +2 -2
- package/dist/{chunk-XG5FRD7G.js → chunk-UEEB3UTU.js} +9 -8
- package/dist/{chunk-XG5FRD7G.js.map → chunk-UEEB3UTU.js.map} +1 -1
- package/dist/{chunk-MK3H5LQT.js → chunk-V7R5AJVN.js} +2 -2
- package/dist/{chunk-DLTJCOEN.js → chunk-Y6JSB5II.js} +2 -2
- package/dist/{chunk-343WTR6F.js → chunk-YUGYKMY6.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/{client-3JLER5ZO.js → client-D3CYQPUD.js} +2 -2
- package/dist/{config-HHNGJKVW.js → config-OTO56OCX.js} +2 -2
- package/dist/config-mutate-5KKGQHC6.js +2 -0
- package/dist/config-mutator-XBUGJZER.js +2 -0
- package/dist/{contributions-6M3TIP57.js → contributions-SMSYSHPU.js} +2 -2
- package/dist/{doctor-TOLXE6QQ.js → doctor-5PFLKGNU.js} +2 -2
- package/dist/{follow-up-tool-Q44GNGWF.js → follow-up-tool-ME4DV7HT.js} +2 -2
- package/dist/hub-WGUNZ2D5.js +2 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +1 -1
- package/dist/{program-PMD6BM3U.js → program-GBPLSXFF.js} +23 -23
- package/dist/{promote-JLFDSQFH.js → promote-TQ3OZ7EC.js} +2 -2
- package/dist/{query-KNZ3EMHA.js → query-M4VWXBHF.js} +2 -2
- package/dist/{query-settings-XRNZOOWV.js → query-settings-Y4PWFLYK.js} +2 -2
- package/dist/{registry-EHLXMVUV.js → registry-GLNCV3KP.js} +2 -2
- package/dist/{request-planner-T5GKPGQT.js → request-planner-FE3C2QFQ.js} +2 -2
- package/dist/{review-candidates-HSKH2UGT.js → review-candidates-R7QKVGMQ.js} +2 -2
- package/dist/routing-6J4OHUJS.js +2 -0
- package/dist/schedule-tool-FE3TWOGS.js +2 -0
- package/dist/scheduler-XDLJAWGC.js +2 -0
- package/dist/{seat-OSYVYKBK.js → seat-35AZG54F.js} +2 -2
- package/dist/{select-I5JLTJKJ.js → select-6PC26YUI.js} +2 -2
- package/dist/{set-enabled-Q5EPYA33.js → set-enabled-UJOLDPZV.js} +2 -2
- package/dist/{surface-usage-W33HGXMP.js → surface-usage-Y7D5W52I.js} +2 -2
- package/dist/{tool-SM3FPKK6.js → tool-LAMDUPTX.js} +2 -2
- package/dist/{tool-ZDGA6CTA.js → tool-QLIJQQ7W.js} +2 -2
- package/dist/wiki-W7L5EJTZ.js +2 -0
- package/dist/wiki-enrich-3ZCL5TEC.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-F2TCMJCZ.js.map +0 -1
- package/dist/chunk-GJMXUROS.js.map +0 -1
- package/dist/config-mutate-CP2TIY2J.js +0 -2
- package/dist/config-mutator-ZSW4PTO5.js +0 -2
- package/dist/hub-H4AW5H7E.js +0 -2
- package/dist/routing-C66W2E3P.js +0 -2
- package/dist/schedule-tool-3Z45TBN6.js +0 -2
- package/dist/scheduler-TZJJGRAE.js +0 -2
- package/dist/wiki-NAE25PMF.js +0 -2
- package/dist/wiki-enrich-3XXN4XCV.js +0 -2
- /package/dist/{App-4PQX4N6S.js.map → App-NV2JJMHN.js.map} +0 -0
- /package/dist/{ChatApp-NHB5VPUE.js.map → ChatApp-CIGDPS3A.js.map} +0 -0
- /package/dist/{absorb-eval-PWLEKRFA.js.map → absorb-eval-VPAASHZG.js.map} +0 -0
- /package/dist/{agent-USWAFKWO.js.map → agent-UFMIPTQZ.js.map} +0 -0
- /package/dist/{chunk-K7ZUE7SG.js.map → chunk-4SJ2VFVI.js.map} +0 -0
- /package/dist/{chunk-EGCWS56X.js.map → chunk-6Y53LLIX.js.map} +0 -0
- /package/dist/{chunk-H4DQGVUG.js.map → chunk-73SESASJ.js.map} +0 -0
- /package/dist/{chunk-AM2DYH7Y.js.map → chunk-A3GDFLFB.js.map} +0 -0
- /package/dist/{chunk-MYEEWFXP.js.map → chunk-AXDNFXYU.js.map} +0 -0
- /package/dist/{chunk-EJFJBYDJ.js.map → chunk-BC7VOHNH.js.map} +0 -0
- /package/dist/{chunk-3S2BNZHX.js.map → chunk-CDPQQAK6.js.map} +0 -0
- /package/dist/{chunk-QLN4W2KV.js.map → chunk-CGE5EAWC.js.map} +0 -0
- /package/dist/{chunk-C65BZPUE.js.map → chunk-CRUNUMVO.js.map} +0 -0
- /package/dist/{chunk-KDDCIOS7.js.map → chunk-EXJGRK2N.js.map} +0 -0
- /package/dist/{chunk-IMERQYQ6.js.map → chunk-FK2TJZNJ.js.map} +0 -0
- /package/dist/{chunk-JCOLQ6MO.js.map → chunk-GJ4SQRAE.js.map} +0 -0
- /package/dist/{chunk-KKOULF3I.js.map → chunk-IVTO54EM.js.map} +0 -0
- /package/dist/{chunk-TW2PBGYA.js.map → chunk-KVSHZKAL.js.map} +0 -0
- /package/dist/{chunk-CR55SCRE.js.map → chunk-NCEYJFF5.js.map} +0 -0
- /package/dist/{chunk-UD3WIY2B.js.map → chunk-ON7Y3JSP.js.map} +0 -0
- /package/dist/{chunk-HGQKZKXL.js.map → chunk-PSTEWKR3.js.map} +0 -0
- /package/dist/{chunk-I53O35TO.js.map → chunk-QT63Q6C5.js.map} +0 -0
- /package/dist/{chunk-Z5JVYKVH.js.map → chunk-RUB4HZEG.js.map} +0 -0
- /package/dist/{chunk-UY64KKNE.js.map → chunk-S6ZZKRDB.js.map} +0 -0
- /package/dist/{chunk-BRNAE6ET.js.map → chunk-T5IGXFSW.js.map} +0 -0
- /package/dist/{chunk-OO7T7E4O.js.map → chunk-TADIDWYZ.js.map} +0 -0
- /package/dist/{chunk-MK3H5LQT.js.map → chunk-V7R5AJVN.js.map} +0 -0
- /package/dist/{chunk-DLTJCOEN.js.map → chunk-Y6JSB5II.js.map} +0 -0
- /package/dist/{chunk-343WTR6F.js.map → chunk-YUGYKMY6.js.map} +0 -0
- /package/dist/{client-3JLER5ZO.js.map → client-D3CYQPUD.js.map} +0 -0
- /package/dist/{config-HHNGJKVW.js.map → config-OTO56OCX.js.map} +0 -0
- /package/dist/{config-mutate-CP2TIY2J.js.map → config-mutate-5KKGQHC6.js.map} +0 -0
- /package/dist/{config-mutator-ZSW4PTO5.js.map → config-mutator-XBUGJZER.js.map} +0 -0
- /package/dist/{contributions-6M3TIP57.js.map → contributions-SMSYSHPU.js.map} +0 -0
- /package/dist/{doctor-TOLXE6QQ.js.map → doctor-5PFLKGNU.js.map} +0 -0
- /package/dist/{follow-up-tool-Q44GNGWF.js.map → follow-up-tool-ME4DV7HT.js.map} +0 -0
- /package/dist/{hub-H4AW5H7E.js.map → hub-WGUNZ2D5.js.map} +0 -0
- /package/dist/{program-PMD6BM3U.js.map → program-GBPLSXFF.js.map} +0 -0
- /package/dist/{promote-JLFDSQFH.js.map → promote-TQ3OZ7EC.js.map} +0 -0
- /package/dist/{query-KNZ3EMHA.js.map → query-M4VWXBHF.js.map} +0 -0
- /package/dist/{query-settings-XRNZOOWV.js.map → query-settings-Y4PWFLYK.js.map} +0 -0
- /package/dist/{registry-EHLXMVUV.js.map → registry-GLNCV3KP.js.map} +0 -0
- /package/dist/{request-planner-T5GKPGQT.js.map → request-planner-FE3C2QFQ.js.map} +0 -0
- /package/dist/{review-candidates-HSKH2UGT.js.map → review-candidates-R7QKVGMQ.js.map} +0 -0
- /package/dist/{routing-C66W2E3P.js.map → routing-6J4OHUJS.js.map} +0 -0
- /package/dist/{schedule-tool-3Z45TBN6.js.map → schedule-tool-FE3TWOGS.js.map} +0 -0
- /package/dist/{scheduler-TZJJGRAE.js.map → scheduler-XDLJAWGC.js.map} +0 -0
- /package/dist/{seat-OSYVYKBK.js.map → seat-35AZG54F.js.map} +0 -0
- /package/dist/{select-I5JLTJKJ.js.map → select-6PC26YUI.js.map} +0 -0
- /package/dist/{set-enabled-Q5EPYA33.js.map → set-enabled-UJOLDPZV.js.map} +0 -0
- /package/dist/{surface-usage-W33HGXMP.js.map → surface-usage-Y7D5W52I.js.map} +0 -0
- /package/dist/{tool-SM3FPKK6.js.map → tool-LAMDUPTX.js.map} +0 -0
- /package/dist/{tool-ZDGA6CTA.js.map → tool-QLIJQQ7W.js.map} +0 -0
- /package/dist/{wiki-NAE25PMF.js.map → wiki-W7L5EJTZ.js.map} +0 -0
- /package/dist/{wiki-enrich-3XXN4XCV.js.map → wiki-enrich-3ZCL5TEC.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/queued-messages.ts","../src/storage/forge-comments.ts","../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\n\n// --- Messages waiting in line behind a busy agent (#443) ---\n//\n// The registry keeps the line itself in memory (agents/message-queue.ts).\n// This table mirrors what is waiting right now, with the person who sent\n// each message, so the member page, which runs in the dashboard and reads\n// the database only, can tell a teammate how many messages are ahead of\n// theirs. A row lives from the moment the message is queued to the moment\n// the line is handed over to a new turn; nothing waits here for long, and\n// the daemon empties the table when it boots, since the line it mirrors\n// did not survive the restart.\n//\n// The preview is the first 200 characters of the message. The member page\n// shows it only to the person who sent it; of anyone else's message it\n// reads the count alone.\n\nexport const QUEUED_PREVIEW_MAX = 200\n\nexport interface QueuedMessageRow {\n id: number\n agentId: string\n channel: string\n chatId: string\n /** The person who sent it (people, #384), when known. */\n person: string | null\n sender: string | null\n messagePreview: string | null\n queuedAt: number\n}\n\nexport function ensureQueuedMessagesTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS queued_messages (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n person TEXT,\n sender TEXT,\n message_preview TEXT,\n queued_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_queued_messages_agent ON queued_messages(agent_id, queued_at);\n `)\n}\n\nexport function insertQueuedMessage(db: Database.Database, m: {\n agentId: string; channel: string; chatId: string\n person?: string | null; sender?: string | null; messagePreview?: string | null; queuedAt: number\n}): void {\n db.prepare(`\n INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(\n m.agentId, m.channel, m.chatId, m.person ?? null, m.sender?.slice(0, 120) ?? null,\n m.messagePreview == null ? null : String(m.messagePreview).replace(/\\s+/g, \" \").trim().slice(0, QUEUED_PREVIEW_MAX),\n m.queuedAt,\n )\n}\n\n/** The line of one chat was handed over to a new turn: the messages queued\n * up to `flushedAt` are no longer waiting. One queued again after that\n * moment (the slot was taken meanwhile) has a newer row and stays. */\nexport function flushQueuedMessages(db: Database.Database, agentId: string, channel: string, chatId: string, flushedAt: number): number {\n const r = db.prepare(\n \"DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?\",\n ).run(agentId, channel, chatId, flushedAt)\n return r.changes ?? 0\n}\n\n/** The daemon starts: the line it kept in memory is gone, so is its mirror. */\nexport function clearQueuedMessages(db: Database.Database): number {\n return db.prepare(\"DELETE FROM queued_messages\").run().changes ?? 0\n}\n\n/** Everything waiting now, oldest first. Small: a line holds a handful of\n * messages, and only while an agent is busy. */\nexport function listQueuedMessages(db: Database.Database): QueuedMessageRow[] {\n const rows = db.prepare(\n \"SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500\",\n ).all() as Array<Record<string, any>>\n return rows.map((r) => ({\n id: r.id, agentId: r.agent_id, channel: r.channel, chatId: r.chat_id,\n person: r.person ?? null, sender: r.sender ?? null, messagePreview: r.message_preview ?? null, queuedAt: r.queued_at,\n }))\n}\n","import type Database from \"better-sqlite3\"\n\n// --- Agent comments on GitHub and GitLab, by id (#1184) ---\n//\n// When the daemon posts an agent's comment on an issue, pull request or\n// merge request, the forge answers with the comment's id. That id is kept\n// here with the chat it went to, so the Wall can link to the exact\n// comment, not only to the issue. Ids and chats only: never the text.\n\nexport const FORGE_COMMENT_CHANNELS = [\"github\", \"gitlab\"] as const\n\nexport interface ForgeCommentRow {\n channel: string\n chatId: string\n commentId: string\n agentId: string | null\n at: number\n}\n\nexport function ensureForgeCommentsTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS forge_comments (\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n comment_id TEXT NOT NULL,\n agent_id TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (channel, chat_id, comment_id)\n );\n CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);\n `)\n}\n\nexport function insertForgeComment(db: Database.Database, c: ForgeCommentRow): void {\n db.prepare(\n \"INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)\",\n ).run(c.channel, c.chatId, c.commentId.slice(0, 64), c.agentId?.slice(0, 120) ?? null, c.at)\n}\n\n/** The newest comments on one forge chat in [from, to], newest first. */\nexport function forgeCommentsOn(db: Database.Database, channel: string, chatId: string, from: number, to: number, limit = 5): ForgeCommentRow[] {\n return db.prepare(\n `SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments\n WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`,\n ).all(channel, chatId, from, to, limit) as ForgeCommentRow[]\n}\n","import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { ensureQueuedMessagesTable } from \"./queued-messages\"\nimport { ensureForgeCommentsTable } from \"./forge-comments\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n ensureColumns(db, \"task_traces\", COST_COLUMNS)\n // A person's latest turns, read by the member page every 30 s (#448).\n // Without it that read walks every run on record. Partial: most runs\n // carry no person, and those rows stay out of the index.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL\")\n // Messages waiting behind a busy agent, with who sent them (#443). By\n // name, not by version number, for the same reason as the columns above.\n ensureQueuedMessagesTable(db)\n // Agent comment ids on GitHub and GitLab (#1184), by name too.\n ensureForgeCommentsTable(db)\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n forgeComments: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n // forge_comments (#1184) also uses ms-epoch INTEGERs on `at`.\n const forgeComments = (db\n .prepare(`DELETE FROM forge_comments WHERE at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces + forgeComments > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces, forgeComments }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** What a run cost in USD, summed per agent per month for the budget (#1162). */\nexport const COST_COLUMNS: Array<[string, string]> = [[\"cost_usd\", \"REAL\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"wCA+BO,SAASA,EAA0BC,EAA6B,CACrEA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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EAAA,kBAIAC,IACAC,IAuBMxD,EAAUZ,EAAc,YAAY,GAAG,EAkmBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC,EAG7DC,EAAwC,CAAC,CAAC,WAAY,MAAM,CAAC","names":["ensureQueuedMessagesTable","db","insertQueuedMessage","m","flushQueuedMessages","agentId","channel","chatId","flushedAt","clearQueuedMessages","listQueuedMessages","r","init_queued_messages","__esmMin","ensureForgeCommentsTable","db","insertForgeComment","c","forgeCommentsOn","channel","chatId","from","to","limit","init_forge_comments","__esmMin","createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","COST_COLUMNS","ensureQueuedMessagesTable","ensureForgeCommentsTable","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","i","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","forgeComments","table","columns","have","c","name","type","init_sqlite","__esmMin","init_queued_messages","init_forge_comments"]}
|
|
1
|
+
{"version":3,"sources":["../src/storage/queued-messages.ts","../src/storage/forge-comments.ts","../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\n\n// --- Messages waiting in line behind a busy agent (#443) ---\n//\n// The registry keeps the line itself in memory (agents/message-queue.ts).\n// This table mirrors what is waiting right now, with the person who sent\n// each message, so the member page, which runs in the dashboard and reads\n// the database only, can tell a teammate how many messages are ahead of\n// theirs. A row lives from the moment the message is queued to the moment\n// the line is handed over to a new turn; nothing waits here for long, and\n// the daemon empties the table when it boots, since the line it mirrors\n// did not survive the restart.\n//\n// The preview is the first 200 characters of the message. The member page\n// shows it only to the person who sent it; of anyone else's message it\n// reads the count alone.\n\nexport const QUEUED_PREVIEW_MAX = 200\n\nexport interface QueuedMessageRow {\n id: number\n agentId: string\n channel: string\n chatId: string\n /** The person who sent it (people, #384), when known. */\n person: string | null\n sender: string | null\n messagePreview: string | null\n queuedAt: number\n}\n\nexport function ensureQueuedMessagesTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS queued_messages (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n person TEXT,\n sender TEXT,\n message_preview TEXT,\n queued_at INTEGER NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_queued_messages_agent ON queued_messages(agent_id, queued_at);\n `)\n}\n\nexport function insertQueuedMessage(db: Database.Database, m: {\n agentId: string; channel: string; chatId: string\n person?: string | null; sender?: string | null; messagePreview?: string | null; queuedAt: number\n}): void {\n db.prepare(`\n INSERT INTO queued_messages (agent_id, channel, chat_id, person, sender, message_preview, queued_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(\n m.agentId, m.channel, m.chatId, m.person ?? null, m.sender?.slice(0, 120) ?? null,\n m.messagePreview == null ? null : String(m.messagePreview).replace(/\\s+/g, \" \").trim().slice(0, QUEUED_PREVIEW_MAX),\n m.queuedAt,\n )\n}\n\n/** The line of one chat was handed over to a new turn: the messages queued\n * up to `flushedAt` are no longer waiting. One queued again after that\n * moment (the slot was taken meanwhile) has a newer row and stays. */\nexport function flushQueuedMessages(db: Database.Database, agentId: string, channel: string, chatId: string, flushedAt: number): number {\n const r = db.prepare(\n \"DELETE FROM queued_messages WHERE agent_id = ? AND channel = ? AND chat_id = ? AND queued_at <= ?\",\n ).run(agentId, channel, chatId, flushedAt)\n return r.changes ?? 0\n}\n\n/** The daemon starts: the line it kept in memory is gone, so is its mirror. */\nexport function clearQueuedMessages(db: Database.Database): number {\n return db.prepare(\"DELETE FROM queued_messages\").run().changes ?? 0\n}\n\n/** Everything waiting now, oldest first. Small: a line holds a handful of\n * messages, and only while an agent is busy. */\nexport function listQueuedMessages(db: Database.Database): QueuedMessageRow[] {\n const rows = db.prepare(\n \"SELECT id, agent_id, channel, chat_id, person, sender, message_preview, queued_at FROM queued_messages ORDER BY queued_at, id LIMIT 500\",\n ).all() as Array<Record<string, any>>\n return rows.map((r) => ({\n id: r.id, agentId: r.agent_id, channel: r.channel, chatId: r.chat_id,\n person: r.person ?? null, sender: r.sender ?? null, messagePreview: r.message_preview ?? null, queuedAt: r.queued_at,\n }))\n}\n","import type Database from \"better-sqlite3\"\n\n// --- Agent comments on GitHub and GitLab, by id (#1184) ---\n//\n// When the daemon posts an agent's comment on an issue, pull request or\n// merge request, the forge answers with the comment's id. That id is kept\n// here with the chat it went to, so the Wall can link to the exact\n// comment, not only to the issue. Ids and chats only: never the text.\n\nexport const FORGE_COMMENT_CHANNELS = [\"github\", \"gitlab\"] as const\n\nexport interface ForgeCommentRow {\n channel: string\n chatId: string\n commentId: string\n agentId: string | null\n at: number\n}\n\nexport function ensureForgeCommentsTable(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS forge_comments (\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n comment_id TEXT NOT NULL,\n agent_id TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (channel, chat_id, comment_id)\n );\n CREATE INDEX IF NOT EXISTS idx_forge_comments_chat ON forge_comments(channel, chat_id, at);\n `)\n}\n\nexport function insertForgeComment(db: Database.Database, c: ForgeCommentRow): void {\n db.prepare(\n \"INSERT OR IGNORE INTO forge_comments (channel, chat_id, comment_id, agent_id, at) VALUES (?, ?, ?, ?, ?)\",\n ).run(c.channel, c.chatId, c.commentId.slice(0, 64), c.agentId?.slice(0, 120) ?? null, c.at)\n}\n\n/** Every comment on these chats of one channel, newest first. */\nexport function forgeCommentsOnChats(db: Database.Database, channel: string, chatIds: string[]): ForgeCommentRow[] {\n if (chatIds.length === 0) return []\n return db.prepare(\n `SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments\n WHERE channel = ? AND chat_id IN (${chatIds.map(() => \"?\").join(\",\")}) ORDER BY at DESC`,\n ).all(channel, ...chatIds) as ForgeCommentRow[]\n}\n\n/** The newest comments on one forge chat in [from, to], newest first. */\nexport function forgeCommentsOn(db: Database.Database, channel: string, chatId: string, from: number, to: number, limit = 5): ForgeCommentRow[] {\n return db.prepare(\n `SELECT channel, chat_id AS chatId, comment_id AS commentId, agent_id AS agentId, at FROM forge_comments\n WHERE channel = ? AND chat_id = ? AND at >= ? AND at <= ? ORDER BY at DESC LIMIT ?`,\n ).all(channel, chatId, from, to, limit) as ForgeCommentRow[]\n}\n","import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { ensureQueuedMessagesTable } from \"./queued-messages\"\nimport { ensureForgeCommentsTable } from \"./forge-comments\"\n\n// --- SQLite storage layer ---\n//\n// Move 2 of the architectural review (docs/architecture/hexabot-vs-agentx.md).\n// SQLite for the operational tables — task_history, usage, dedup, sessions —\n// where queryable, indexed access has user-visible value (dashboards,\n// retention, analytics). Workflow definitions, wiki, agent-memory, and\n// references stay as files: they're git-diffable, human-readable, and don't\n// need queries.\n//\n// Approach: subscribe to the event bus (src/events/bus.ts) and write to\n// SQLite from the subscribers. Existing JSON writes are not touched —\n// SQLite runs alongside as a parallel pipeline. Once we have a query API\n// the dashboard depends on, we can deprecate the JSON path. Until then,\n// SQLite is observability-grade only.\n//\n// Synchronous API: better-sqlite3 is sync, no callbacks. The daemon's\n// event loop is the single writer; multiple readers (dashboard) use WAL\n// mode for concurrent read while we write.\n\ntype DatabaseConstructor = typeof Database\n\nconst require = createRequire(import.meta.url)\nlet _db: Database.Database | undefined\nlet _Database: DatabaseConstructor | undefined\n\nfunction betterSqlite3Fix(error: any): string {\n const msg = String(error?.message ?? error)\n const abi = process.versions.modules\n const node = process.version\n const hint = `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${node}, modules ${abi}).`\n if (/NODE_MODULE_VERSION|was compiled against|Module version mismatch|invalid ELF|mach-o/i.test(msg)) {\n return `${msg} ${hint}`\n }\n return `${msg} ${hint}`\n}\n\nfunction loadDatabaseCtor(quiet = false): DatabaseConstructor | null {\n if (_Database) return _Database\n try {\n _Database = require(\"better-sqlite3\") as DatabaseConstructor\n return _Database\n } catch (e: any) {\n if (!quiet) {\n console.error(`[storage/sqlite] better-sqlite3 native binding failed to load: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\nexport interface OpenOptions {\n /** Resolved relative to cwd. Default: .agentx/db.sqlite */\n path?: string\n /** When true, SQLite writes are skipped (used by tests + opt-out). */\n disabled?: boolean\n /** Suppress the open-failure log. For best-effort callers whose whole\n * contract is \"do nothing if unavailable\" — telemetry, mainly. Without\n * this, a native-binding ABI mismatch prints a paragraph of node-gyp\n * advice on EVERY CLI invocation, which is worse than the thing it\n * is warning about. Load-bearing callers must never pass it. */\n quiet?: boolean\n}\n\n/**\n * Open the per-process SQLite database. Idempotent — repeated calls\n * return the same handle. The file is created on first open; the schema\n * is migrated forward to the latest version.\n *\n * Returns null when disabled — every subscriber should check for null\n * before issuing a write so the daemon stays runnable without SQLite if\n * someone's environment can't compile the native binding.\n */\nexport function openDb(opts: OpenOptions = {}): Database.Database | null {\n if (opts.disabled) return null\n if (_db) return _db\n const path = resolve(process.cwd(), opts.path ?? \".agentx/db.sqlite\")\n const Database = loadDatabaseCtor(opts.quiet)\n if (!Database) return null\n try {\n mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n // WAL keeps readers (dashboard) unblocked while the daemon writes.\n // Synchronous=NORMAL is the SQLite-recommended balance for WAL: the\n // db is durable on power-loss, but a crash within the last few ms can\n // lose the most recent commit. For our use (observability), that's fine.\n db.pragma(\"journal_mode = WAL\")\n db.pragma(\"synchronous = NORMAL\")\n db.pragma(\"foreign_keys = ON\")\n runMigrations(db)\n _db = db\n return _db\n } catch (e: any) {\n // Native binding missing, file unwritable, etc. Surface by default — the\n // alternative was a silent no-op, which makes the \"SQLite not opened\"\n // message in the daemon log impossible to debug. `quiet` callers have\n // explicitly opted out because doing nothing is their correct behavior.\n if (!opts.quiet) {\n console.error(`[storage/sqlite] openDb failed at ${path}: ${betterSqlite3Fix(e)}`)\n }\n return null\n }\n}\n\n/** Close the global handle. Test-only — production never closes. */\nexport function closeDb(): void {\n if (_db) {\n _db.close()\n _db = undefined\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration —\n * never mutate an old one. Run on every open(); each step is idempotent\n * because it CREATE TABLE IF NOT EXISTS. SQLite has no concurrent\n * migration issue here (single writer process).\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n const steps: Array<{ v: number; sql: string }> = [\n {\n v: 1,\n sql: `\n CREATE TABLE task_history (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n status TEXT NOT NULL, -- 'ok' | 'error' | 'timeout'\n message_preview TEXT,\n error TEXT,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n started_at TEXT NOT NULL,\n finished_at TEXT NOT NULL\n );\n CREATE INDEX idx_task_history_agent_started\n ON task_history(agent_id, started_at);\n CREATE INDEX idx_task_history_status\n ON task_history(status, started_at);\n `,\n },\n {\n v: 2,\n sql: `\n CREATE TABLE usage_daily (\n agent_id TEXT NOT NULL,\n model TEXT NOT NULL,\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n input_tokens INTEGER DEFAULT 0,\n output_tokens INTEGER DEFAULT 0,\n cache_read_tokens INTEGER DEFAULT 0,\n cache_create_tokens INTEGER DEFAULT 0,\n tasks INTEGER DEFAULT 0,\n PRIMARY KEY (agent_id, model, day)\n );\n CREATE INDEX idx_usage_day ON usage_daily(day);\n `,\n },\n {\n v: 3,\n sql: `\n CREATE TABLE rotations (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n agent_id TEXT NOT NULL,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n reason TEXT NOT NULL, -- 'stale' | 'tier-2' | 'max-turns'\n last_turn_input_tokens INTEGER,\n rotated_at TEXT NOT NULL\n );\n CREATE INDEX idx_rotations_agent_at\n ON rotations(agent_id, rotated_at);\n `,\n },\n {\n v: 4,\n sql: `\n CREATE TABLE route_traces (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n channel TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n msg_id TEXT NOT NULL,\n account_id TEXT,\n kind TEXT NOT NULL, -- 'match' | 'drop'\n deciding_stage TEXT,\n agent_id TEXT,\n reason TEXT,\n at TEXT NOT NULL\n );\n CREATE INDEX idx_route_traces_channel_at\n ON route_traces(channel, at);\n `,\n },\n {\n // Move A — tier-2 token buckets on usage_daily. The per-request tier\n // split is decided at record time by TokenTracker (it's a function of\n // the live cumulative input, not the row totals), so we cannot\n // reconstruct it on read. Adding columns is additive and idempotent;\n // existing rows default to 0.\n v: 5,\n sql: `\n ALTER TABLE usage_daily ADD COLUMN tier2_input_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_output_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_read_tokens INTEGER DEFAULT 0;\n ALTER TABLE usage_daily ADD COLUMN tier2_cache_create_tokens INTEGER DEFAULT 0;\n `,\n },\n {\n // task_traces — per-execution observability surface (improvement plan\n // #2). One row per executeTask invocation, keyed by a ULID task_id so\n // it's URL-safe + monotonically sortable. Workflow context columns let\n // pattern queries group runs by workflow (\"agent-managed workflow as\n // the program\" framing); intent_event_id cross-links into the rescue\n // plan's intent ledger so a dispatch decision joins to the execution\n // it produced. Tokens snapshot the final usage at finish time.\n v: 6,\n sql: `\n CREATE TABLE task_traces (\n task_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n channel TEXT,\n chat_id TEXT,\n workflow_run_id TEXT,\n workflow_id TEXT,\n workflow_node_id TEXT,\n intent_event_id TEXT,\n intent_decided_by TEXT,\n resume_session_id TEXT,\n final_session_id TEXT,\n model TEXT,\n status TEXT NOT NULL,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n duration_ms INTEGER,\n input_tokens INTEGER,\n output_tokens INTEGER,\n cache_read_tokens INTEGER,\n cache_create_tokens INTEGER,\n error TEXT,\n message_preview TEXT\n );\n CREATE INDEX idx_traces_agent_started ON task_traces(agent_id, started_at);\n CREATE INDEX idx_traces_workflow_run ON task_traces(workflow_run_id);\n CREATE INDEX idx_traces_intent_event ON task_traces(intent_event_id);\n CREATE INDEX idx_traces_status_started ON task_traces(status, started_at);\n `,\n },\n {\n // task_trace_steps — append-only step ledger inside one task. Sequence\n // numbers are 0-based and unique per task_id; ON DELETE CASCADE so\n // pruning task_traces removes children atomically. The (input|output)_\n // summary columns are TEXT — callers cap byte-size at the call site,\n // not in the schema, because the right cap depends on the step kind\n // (a tool_use's args vs a tool_result's stdout have very different\n // typical sizes).\n v: 7,\n sql: `\n CREATE TABLE task_trace_steps (\n task_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n name TEXT NOT NULL,\n action TEXT,\n status TEXT,\n input_summary TEXT,\n output_summary TEXT,\n error TEXT,\n ms INTEGER,\n started_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, seq),\n FOREIGN KEY (task_id) REFERENCES task_traces(task_id) ON DELETE CASCADE\n );\n CREATE INDEX idx_trace_steps_name ON task_trace_steps(name, started_at);\n `,\n },\n {\n // task replay support (handoff item #11). Capture the full original\n // user message AND the agent's final response so 'agentx trace replay\n // <taskId> --diff' can show side-by-side without reconstructing from\n // the step ledger. message_preview stays for cheap listing UX (200\n // chars); original_message holds the untruncated input. final_response\n // mirrors the agent's reply text. Both NULLABLE — old rows have NULL\n // and the replay command falls back to the preview gracefully.\n v: 8,\n sql: `\n ALTER TABLE task_traces ADD COLUMN original_message TEXT;\n ALTER TABLE task_traces ADD COLUMN final_response TEXT;\n `,\n },\n {\n // task_queue — persistent chat-initiated work queue (Phase 2).\n // Each row represents a task an agent queued during a /chat turn.\n // status: 'active' = currently running; 'queued' = waiting;\n // 'done' = completed; 'error' = failed.\n // position is 1-based rank among queued rows (null when active/done/error).\n v: 9,\n sql: `\n CREATE TABLE task_queue (\n id TEXT PRIMARY KEY,\n conversation_id TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n summary TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'queued',\n position INTEGER,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n finished_at INTEGER\n );\n CREATE INDEX idx_task_queue_status ON task_queue(status, created_at);\n CREATE INDEX idx_task_queue_convo ON task_queue(conversation_id, created_at);\n `,\n },\n {\n // guardrail_decisions — audit trail for the destructive-action guard\n // (PRD R7). One row per PreToolUse guard verdict, written by the\n // short-lived `agentx guard check` hook process. `verdict` is the\n // policy's decision (allow|deny|escalate|warn); `effective_action` is\n // what was actually enforced after the mode downgrade (in warn mode a\n // deny is recorded as verdict=deny, effective_action=allow). task_id is\n // a logical link to task_traces when the guard can resolve it (often\n // null — the hook doesn't always know the AgentX task id). `approver`\n // is reserved for Phase 2 escalation (human who approved/denied).\n v: 10,\n sql: `\n CREATE TABLE guardrail_decisions (\n id TEXT PRIMARY KEY,\n ts INTEGER NOT NULL,\n agent_id TEXT,\n task_id TEXT,\n tool TEXT NOT NULL,\n command TEXT,\n resolved_target TEXT,\n matched_rule TEXT,\n verdict TEXT NOT NULL,\n effective_action TEXT NOT NULL,\n mode TEXT,\n severity TEXT,\n approver TEXT,\n ms INTEGER\n );\n CREATE INDEX idx_guardrail_ts ON guardrail_decisions(ts);\n CREATE INDEX idx_guardrail_verdict ON guardrail_decisions(verdict, ts);\n CREATE INDEX idx_guardrail_agent ON guardrail_decisions(agent_id, ts);\n `,\n },\n {\n // Which operator surfaces actually get used. task_history records agent\n // dispatches and says nothing about which of the ~46 CLI commands or 16\n // dashboard pages anyone opens — the two biggest surfaces by count, and\n // the ones the surface-reduction work needs evidence for.\n //\n // Deliberately NOT folded into usage_daily: that table is keyed by\n // (agent_id, model, day) and is about token cost. Surface counts share\n // none of that shape, and mixing them would corrupt cost reporting.\n //\n // Names only — never arguments, paths, or payloads. This counts which\n // door was opened, not what was carried through it.\n v: 11,\n sql: `\n CREATE TABLE surface_usage (\n kind TEXT NOT NULL, -- 'cli' | 'page'\n name TEXT NOT NULL, -- 'guard log' | '/live'\n day TEXT NOT NULL, -- 'YYYY-MM-DD' UTC\n count INTEGER NOT NULL DEFAULT 0,\n last_at TEXT,\n PRIMARY KEY (kind, name, day)\n );\n CREATE INDEX idx_surface_day ON surface_usage(day);\n `,\n },\n {\n // Per-turn token accounting that a with/without comparison can trust.\n // task_traces only carried the tier-1 buckets, and tier-2 turns are\n // where 90%+ of prompt tokens land, so most big turns read as zero.\n // `resumed` is explicit rather than inferred from resume_session_id:\n // NULL means \"not recorded\" (older rows), 0 a fresh session.\n v: 12,\n sql: `\n ALTER TABLE task_traces ADD COLUMN tier2_input_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_output_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_read_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN tier2_cache_create_tokens INTEGER;\n ALTER TABLE task_traces ADD COLUMN resumed INTEGER;\n `,\n },\n {\n // Request-gate experiment arm: 'treatment' (asked Jev), 'holdout'\n // (randomly skipped it), or NULL when the gate was not active. The\n // with/without-Jev comparison groups turns on this column.\n v: 13,\n sql: `\n ALTER TABLE task_traces ADD COLUMN jev_arm TEXT;\n CREATE INDEX idx_task_traces_jev_arm ON task_traces(jev_arm, started_at);\n `,\n },\n ]\n\n const txn = db.transaction((step: { v: number; sql: string }) => {\n db.exec(step.sql)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (?)\").run(step.v)\n })\n\n for (const step of steps) {\n if (step.v > current) txn(step)\n }\n\n // Columns added by name, not by version number. Several branches can each\n // claim the next migration number; a database that already recorded that\n // number from another branch would silently skip ours. Checking the\n // table itself makes these columns appear on every database.\n ensureColumns(db, \"task_traces\", RESUME_COLUMNS)\n ensureColumns(db, \"task_traces\", LESSON_IMPACT_COLUMNS)\n ensureColumns(db, \"task_traces\", PERSON_COLUMNS)\n ensureColumns(db, \"task_history\", PERSON_COLUMNS)\n ensureColumns(db, \"task_traces\", COST_COLUMNS)\n // A person's latest turns, read by the member page every 30 s (#448).\n // Without it that read walks every run on record. Partial: most runs\n // carry no person, and those rows stay out of the index.\n db.exec(\"CREATE INDEX IF NOT EXISTS idx_traces_person_started ON task_traces(person, started_at) WHERE person IS NOT NULL\")\n // Messages waiting behind a busy agent, with who sent them (#443). By\n // name, not by version number, for the same reason as the columns above.\n ensureQueuedMessagesTable(db)\n // Agent comment ids on GitHub and GitLab (#1184), by name too.\n ensureForgeCommentsTable(db)\n}\n\n/** Schema version check for tests. */\nexport function getSchemaVersion(db: Database.Database): number {\n return (db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }).v ?? 0\n}\n\n// --- task_queue helpers (Phase 2 chat-initiated work queue) ---\n\nexport interface TaskQueueEntry {\n id: string\n conversationId: string\n agentId: string\n summary: string\n status: \"active\" | \"queued\" | \"done\" | \"error\"\n position: number | null\n createdAt: number\n startedAt: number | null\n finishedAt: number | null\n}\n\nexport interface InsertTaskQueueResult {\n id: string\n status: \"active\" | \"queued\"\n position: number | null\n}\n\n/**\n * Insert a new task into the queue. Respects maxConcurrent — if the number\n * of 'active' rows is below the limit the new task is inserted as 'active';\n * otherwise it is 'queued' with a 1-based position.\n */\nexport function insertTaskQueue(\n db: Database.Database,\n entry: { id: string; conversationId: string; agentId: string; summary: string },\n maxConcurrent: number,\n): InsertTaskQueueResult {\n const now = Date.now()\n const activeCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'active'\")\n .get() as { n: number }).n\n\n const isActive = activeCount < maxConcurrent\n let position: number | null = null\n if (!isActive) {\n const queuedCount = (db\n .prepare(\"SELECT COUNT(*) AS n FROM task_queue WHERE status = 'queued'\")\n .get() as { n: number }).n\n position = queuedCount + 1\n }\n\n db.prepare(`\n INSERT INTO task_queue (id, conversation_id, agent_id, summary, status, position, created_at, started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `).run(\n entry.id,\n entry.conversationId,\n entry.agentId,\n entry.summary,\n isActive ? \"active\" : \"queued\",\n position,\n now,\n isActive ? now : null,\n )\n\n return { id: entry.id, status: isActive ? \"active\" : \"queued\", position }\n}\n\n/**\n * Mark a task done/error and promote the next queued task (if any) to active.\n */\nexport function completeTaskQueue(\n db: Database.Database,\n id: string,\n status: \"done\" | \"error\" = \"done\",\n): void {\n const now = Date.now()\n db.prepare(`\n UPDATE task_queue SET status = ?, finished_at = ?, position = NULL WHERE id = ?\n `).run(status, now, id)\n\n // Promote oldest queued task to active\n const next = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC LIMIT 1\n `).get() as { id: string } | undefined\n if (next) {\n db.prepare(`\n UPDATE task_queue SET status = 'active', position = NULL, started_at = ? WHERE id = ?\n `).run(now, next.id)\n // Resequence remaining queued positions\n const remaining = db.prepare(`\n SELECT id FROM task_queue WHERE status = 'queued' ORDER BY created_at ASC\n `).all() as Array<{ id: string }>\n const upd = db.prepare(\"UPDATE task_queue SET position = ? WHERE id = ?\")\n for (let i = 0; i < remaining.length; i++) {\n upd.run(i + 1, remaining[i].id)\n }\n }\n}\n\n/** Look up a single task_queue row. */\nexport function getTaskQueue(\n db: Database.Database,\n id: string,\n): TaskQueueEntry | null {\n const row = db.prepare(\"SELECT * FROM task_queue WHERE id = ?\").get(id) as Record<string, unknown> | undefined\n if (!row) return null\n return {\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }\n}\n\n/** List task_queue rows for a conversation, newest first. */\nexport function listTaskQueueByConversation(\n db: Database.Database,\n conversationId: string,\n limit = 20,\n): TaskQueueEntry[] {\n const rows = db.prepare(`\n SELECT * FROM task_queue WHERE conversation_id = ?\n ORDER BY created_at DESC LIMIT ?\n `).all(conversationId, limit) as Array<Record<string, unknown>>\n return rows.map((row) => ({\n id: row.id as string,\n conversationId: row.conversation_id as string,\n agentId: row.agent_id as string,\n summary: row.summary as string,\n status: row.status as TaskQueueEntry[\"status\"],\n position: row.position as number | null,\n createdAt: row.created_at as number,\n startedAt: row.started_at as number | null,\n finishedAt: row.finished_at as number | null,\n }))\n}\n\nexport interface PruneResult {\n taskHistory: number\n rotations: number\n routeTraces: number\n taskTraces: number\n forgeComments: number\n}\n\n/**\n * Drop rows older than `retentionDays` from the operational tables that grow\n * unbounded over time. `usage_daily` is bounded by (agent, model, day) and\n * doesn't need pruning; the caller decides whether to keep aggregates beyond\n * the retention window.\n *\n * Mirrors the file-based `pruneTaskHistory` sweep that runs at daemon\n * startup. Cheap — three indexed deletes plus an incremental_vacuum.\n */\nexport function pruneSqliteTables(\n db: Database.Database,\n retentionDays: number,\n): PruneResult {\n const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000\n const cutoffIso = new Date(cutoffMs).toISOString()\n\n const taskHistory = (db\n .prepare(`DELETE FROM task_history WHERE started_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const rotations = (db\n .prepare(`DELETE FROM rotations WHERE rotated_at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n const routeTraces = (db\n .prepare(`DELETE FROM route_traces WHERE at < ?`)\n .run(cutoffIso).changes ?? 0) as number\n // task_traces uses ms-epoch INTEGERs (not ISO strings) on started_at.\n // task_trace_steps cascades automatically via ON DELETE CASCADE.\n const taskTraces = (db\n .prepare(`DELETE FROM task_traces WHERE started_at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n // forge_comments (#1184) also uses ms-epoch INTEGERs on `at`.\n const forgeComments = (db\n .prepare(`DELETE FROM forge_comments WHERE at < ?`)\n .run(cutoffMs).changes ?? 0) as number\n\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces + forgeComments > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces, forgeComments }\n}\n\n/** Resume after restart (#103): how to re-enter a run (JSON), its attempt\n * number, the cut-off run it continues, and the boot decision made for it. */\nconst RESUME_COLUMNS: Array<[string, string]> = [\n [\"resume_origin\", \"TEXT\"],\n [\"resume_attempt\", \"INTEGER NOT NULL DEFAULT 0\"],\n [\"resumed_from\", \"TEXT\"],\n [\"resume_decision\", \"TEXT\"],\n [\"resume_reason\", \"TEXT\"],\n]\n\n/** Lesson impact (#98): the memory facts and procedures injected into a turn,\n * as JSON {memory: ids, procedures: ids, wiki: bool}, plus the runtime's turn\n * count. `agentx trace lessons` compares a repeated task before and after\n * each lesson on these columns. */\nconst LESSON_IMPACT_COLUMNS: Array<[string, string]> = [\n [\"num_turns\", \"INTEGER\"],\n [\"injected_context\", \"TEXT\"],\n]\n\n/** People (#384): the id of the known person who started the run. NULL for\n * an unknown sender, for turns software starts, and on older rows. */\nexport const PERSON_COLUMNS: Array<[string, string]> = [[\"person\", \"TEXT\"]]\n\n/** What a run cost in USD, summed per agent per month for the budget (#1162). */\nexport const COST_COLUMNS: Array<[string, string]> = [[\"cost_usd\", \"REAL\"]]\n\n/** Add any of `columns` the table lacks. Idempotent. */\nexport function ensureColumns(db: Database.Database, table: string, columns: Array<[string, string]>): void {\n const have = new Set((db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name))\n for (const [name, type] of columns) {\n if (have.has(name)) continue\n try {\n db.exec(`ALTER TABLE ${table} ADD COLUMN ${name} ${type}`)\n } catch (e: any) {\n // Two processes starting on one database: the slower one read the\n // table before the faster one added the column. Already there is fine.\n if (!/duplicate column name/i.test(String(e?.message))) throw e\n }\n }\n}\n"],"mappings":"wCA+BO,SAASA,EAA0BC,EAA6B,CACrEA,EAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAYP,CACH,CAEO,SAASC,EAAoBD,EAAuBE,EAGlD,CACPF,EAAG,QAAQ;AAAA;AAAA;AAAA,GAGV,EAAE,IACDE,EAAE,QAASA,EAAE,QAASA,EAAE,OAAQA,EAAE,QAAU,KAAMA,EAAE,QAAQ,MAAM,EAAG,GAAG,GAAK,KAC7EA,EAAE,gBAAkB,KAAO,KAAO,OAAOA,EAAE,cAAc,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAG,GAAkB,EAClHA,EAAE,QACJ,CACF,CAKO,SAASC,EAAoBH,EAAuBI,EAAiBC,EAAiBC,EAAgBC,EAA2B,CAItI,OAHUP,EAAG,QACX,mGACF,EAAE,IAAII,EAASC,EAASC,EAAQC,CAAS,EAChC,SAAW,CACtB,CAGO,SAASC,EAAoBR,EAA+B,CACjE,OAAOA,EAAG,QAAQ,6BAA6B,EAAE,IAAI,EAAE,SAAW,CACpE,CAIO,SAASS,EAAmBT,EAA2C,CAI5E,OAHaA,EAAG,QACd,yIACF,EAAE,IAAI,EACM,IAAKU,IAAO,CACtB,GAAIA,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AAyC,EACjD,IAAIiC,CAAQ,EAAE,SAAW,EAI5B,GAAIE,EAAcC,EAAYC,EAAcC,EAAaC,EAAgB,EACvE,GAAI,CAAEvC,EAAG,OAAO,oBAAoB,CAAE,MAAE,CAA0B,CAGpE,MAAO,CAAE,YAAAmC,EAAa,UAAAC,EAAW,YAAAC,EAAa,WAAAC,EAAY,cAAAC,CAAc,CAC1E,CA6BO,SAASjC,EAAcN,EAAuBwC,EAAeC,EAAwC,CAC1G,IAAMC,EAAO,IAAI,IAAK1C,EAAG,QAAQ,qBAAqBwC,IAAQ,EAAE,IAAI,EAA8B,IAAKG,GAAMA,EAAE,IAAI,CAAC,EACpH,OAAW,CAACC,EAAMC,CAAI,IAAKJ,EACzB,GAAI,CAAAC,EAAK,IAAIE,CAAI,EACjB,GAAI,CACF5C,EAAG,KAAK,eAAewC,gBAAoBI,KAAQC,GAAM,CAC3D,OAASnD,EAAP,CAGA,GAAI,CAAC,yBAAyB,KAAK,OAAOA,GAAG,OAAO,CAAC,EAAG,MAAMA,CAChE,CAEJ,CAnqBA,IA4BMD,EACFI,EACAL,EAgmBEe,EAYAC,EAOOC,EAGAC,EAppBboC,EAAAC,EAAA,kBAIAC,IACAC,IAuBMxD,EAAUZ,EAAc,YAAY,GAAG,EAkmBvC0B,EAA0C,CAC9C,CAAC,gBAAiB,MAAM,EACxB,CAAC,iBAAkB,4BAA4B,EAC/C,CAAC,eAAgB,MAAM,EACvB,CAAC,kBAAmB,MAAM,EAC1B,CAAC,gBAAiB,MAAM,CAC1B,EAMMC,EAAiD,CACrD,CAAC,YAAa,SAAS,EACvB,CAAC,mBAAoB,MAAM,CAC7B,EAIaC,EAA0C,CAAC,CAAC,SAAU,MAAM,CAAC,EAG7DC,EAAwC,CAAC,CAAC,WAAY,MAAM,CAAC","names":["ensureQueuedMessagesTable","db","insertQueuedMessage","m","flushQueuedMessages","agentId","channel","chatId","flushedAt","clearQueuedMessages","listQueuedMessages","r","init_queued_messages","__esmMin","ensureForgeCommentsTable","db","insertForgeComment","c","forgeCommentsOnChats","channel","chatIds","forgeCommentsOn","chatId","from","to","limit","init_forge_comments","__esmMin","createRequire","mkdirSync","dirname","resolve","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","_Database","require","e","openDb","opts","_db","path","Database","db","runMigrations","current","steps","txn","step","ensureColumns","RESUME_COLUMNS","LESSON_IMPACT_COLUMNS","PERSON_COLUMNS","COST_COLUMNS","ensureQueuedMessagesTable","ensureForgeCommentsTable","insertTaskQueue","entry","maxConcurrent","now","isActive","position","completeTaskQueue","id","status","next","remaining","upd","i","getTaskQueue","row","listTaskQueueByConversation","conversationId","limit","pruneSqliteTables","retentionDays","cutoffMs","cutoffIso","taskHistory","rotations","routeTraces","taskTraces","forgeComments","table","columns","have","c","name","type","init_sqlite","__esmMin","init_queued_messages","init_forge_comments"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{y as l,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{y as l,z as T}from"./chunk-QT63Q6C5.js";import{a,f as w}from"./chunk-72SZI2UW.js";T();w();var d="task-tier";function u(e){return{task:b(e.message,2e3),agent:e.agent,channel:e.channel??null,continuesExistingSession:e.isFollowUp??!1,...e.toolsAvailable?{toolsAvailable:e.toolsAvailable}:{}}}var c={needsFlagship:a("This task needs the strongest available model to be done correctly.",{true:"Doing it well takes real reasoning: writing or reviewing code, diagnosing a failure, planning work across several steps, weighing a judgement, handling money, touching production or anything irreversible, following a long or ambiguous instruction, or work where being subtly wrong would not be noticed. Anything where a weaker model would produce something that LOOKS right belongs here.",false:"It is mechanical and its result is obvious on sight: acknowledging or confirming a message, restating or formatting something already written, a greeting, a status echo, reading one file and reporting what it says, a lookup with one right answer, a scheduled heartbeat with nothing to decide."})};function g(e){return e.needsFlagship.noul}function b(e,n){return e.length>n?`${e.slice(0,n)}\u2026`:e}var h=.2;function p(e){return e==="voice"||e==="desktop"||e==="opencode"}var f=60*60*1e3;function M(e,n){if(e==="claude-code"){let t=n?.cheapModels?.[e]??n?.cheapModel;return t&&/^(claude-|haiku$|sonnet$|opus$)/.test(t)?t:void 0}if(e==="codex-cli"){let t=n?.cheapModels?.[e];return t&&/^(gpt-|o\d)/.test(t)?t:void 0}}async function v(e){let n=(s,r=null)=>({downgraded:!1,needsFlagship:r,reason:s});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);if(!e.cheapModel)return n("no cheaper model configured");if(e.isFollowUp){let s=e.sessionIdleMs??0,r=e.cacheTtlMs??f;if(s<r)return n(`follow-up on a warm cache (idle ${Math.round(s/1e3)}s) \u2014 swapping would cost more than it saves`)}let t;try{t=await l(d,u(e),c,{incumbent:{needsFlagship:1},features:{agent:e.agent,channel:e.channel??"unknown"},timeoutMs:1500})}catch{return n("routing seat threw \u2014 keeping the flagship")}if(!t)return n("routing seat unavailable \u2014 keeping the flagship");let o=g(t.answers);if(t.mode!=="active")return n(`shadow \u2014 would ${o<(e.threshold??h)?"downgrade":"keep"} (${o.toFixed(2)})`,o);let i=e.threshold??h;return o>=i?n(`needs the flagship (${o.toFixed(2)})`,o):{model:e.cheapModel,downgraded:!0,needsFlagship:o,reason:`mechanical task (${o.toFixed(2)} below ${i}) \u2192 ${e.cheapModel}`}}var A=["labeled","unlabeled","closed"];function y(e){let n=r=>({downgraded:!1,needsFlagship:null,reason:r});if(p(e.channel))return n(`${e.channel} requests retain the configured model`);let t=e.eventActions??[];if(!t.length)return n("not started by a platform event");let o=e.triage?.actions??A,i=t.find(r=>!o.includes(r));if(i)return n(`"${i}" is not a triage action`);let s=M(e.tier,{cheapModels:e.triage?.models});if(!s)return n(`no triage model set for ${e.tier}`);if(e.isFollowUp){let r=e.sessionIdleMs??0,m=e.cacheTtlMs??f;if(r<m)return n(`follow-up on a warm cache (idle ${Math.round(r/1e3)}s) \u2014 keeping the session's model`)}return{model:s,downgraded:!0,needsFlagship:null,reason:`triage event (${t.join(", ")}) \u2192 ${s}`}}export{h as a,p as b,M as c,v as d,A as e,y as f};
|
|
2
|
+
//# sourceMappingURL=chunk-V7R5AJVN.js.map
|
|
@@ -48,7 +48,7 @@ The "modified" field is optional and can contain updated values to pass forward.
|
|
|
48
48
|
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
49
49
|
${c}`,is_error:!0}:{tool_use_id:e.id,content:c||"(no output)"}}async editFile(e){let t=String(e.input.path||""),o=e.input.edits,n=ge.resolve(this.cwd,t);if(!o||o.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await W.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(f.has("pre:file-write")){let a=await f.execute("pre:file-write",{event:"pre:file-write",file:n,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await re.readFile(n,"utf8"),c=[];for(let a of o)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),c.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):c.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await re.writeFile(n,i,"utf8"),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
50
50
|
${c.join(`
|
|
51
|
-
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-
|
|
51
|
+
`)}`}}async createFiles(e){let t=e.input,o=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${o.length} file(s) for creation.`,files:o}}async spawnAgent(e){let t=String(e.input.agent_id||""),o=String(e.input.prompt||""),n=Number(e.input.timeout_seconds)||300;if(!t||!o)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-XY5N7TUU.js"),{getGlobalRegistry:i}=await import("./registry-GLNCV3KP.js"),c=i();if(!c)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let p=await new s(c).spawn({targetAgentId:t,prompt:o,parentAgentId:"orchestrator",timeout:n*1e3});return p.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(p.duration/1e3)}s):
|
|
52
52
|
|
|
53
53
|
${p.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${p.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),o=e.input.options,n=t;return o?.length&&(n+=`
|
|
54
54
|
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Ae(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,cwd:s,maxIterations:i=20,enabledTools:c,interactive:a=!0,overwrite:p=!1,dryRun:l=!1,onProgress:d,abortSignal:u}=r,m=u?{...n,abortSignal:u}:n;if(!e.generateRaw)return dt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,acmeContext:r.acmeContext,abortSignal:u}),D=be(c);if(r.acmeContext)for(let g of at)D.push({name:g.name,description:g.description,input_schema:g.input_schema});let E=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)D.push({name:g.name,description:g.description,input_schema:g.input_schema}),E.add(g.name);let C=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,A=0,O="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${D.length} tools available)`);let g,M=!!e.generateRawStream&&!!d;try{if(M){let T=null,U=null,v="";for await(let x of e.generateRawStream(C,t,D,m))x.type==="text_delta"?(v+=x.text,d?.({type:"text_delta",text:x.text})):x.type==="thinking_delta"?d?.({type:"thinking_delta",text:x.text}):x.type==="raw_result"?T=x.result:x.type==="error"&&(U=x.error);if(U&&!T)throw new Error(U);if(!T)throw new Error("generateRawStream returned no raw_result event");g=T,g._streamedText=v}else g=await e.generateRaw(C,t,D,m)}catch(T){if(T.message?.includes("not available"))return dt(r);throw T}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,A+=g.usage.output_tokens;let P=g._streamedText;for(let T of g.content)T.type==="text"&&(O+=T.text,P===void 0&&d?.({type:"text_delta",text:T.text}));if(P!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let T=g.content.filter(v=>v.type==="tool_use");if(T.length===0)break;C.push({role:"assistant",content:g.content});let U=[];for(let v of T){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(E.has(v.name)&&r.mcpDispatch){let h=await r.mcpDispatch(v.name,v.input);x={tool_use_id:v.id,content:h.content,is_error:h.isError}}else x=await I.execute({name:v.name,id:v.id,input:v.input});d?.({type:"tool_result",name:v.name,id:v.id,content:x.content.slice(0,200),is_error:x.is_error}),x.files?.length&&(B.push(...x.files),d?.({type:"files_created",files:x.files})),x.followUp&&(j=x.followUp),U.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(C.push({role:"user",content:U}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:O,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:A||void 0,iterations:_}}async function dt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
@@ -123,4 +123,4 @@ ${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Ou
|
|
|
123
123
|
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
124
|
|
|
125
125
|
`)}export{qe as a,Vt as b,Yt as c,We as d,ze as e,Ve as f,Ye as g,Pe as h,ee as i,Re as j,le as k,te as l,Tt as m,oe as n,Mt as o,f as p,et as q,tt as r,Me as s,de as t,W as u,ne as v,it as w,Ee as x,$e as y,se as z,mt as A,Zn as B,er as C};
|
|
126
|
-
//# sourceMappingURL=chunk-
|
|
126
|
+
//# sourceMappingURL=chunk-Y6JSB5II.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-
|
|
1
|
+
import{c as P,d as N}from"./chunk-OWNQ2FD4.js";import{b as I}from"./chunk-KEXBEUSU.js";import{a as B}from"./chunk-ROLSSYXE.js";import{a as M,b as E,c as R,d as T,e as j,j as O}from"./chunk-BC7VOHNH.js";import{y as C,z as K}from"./chunk-QT63Q6C5.js";import{c as _,d as x}from"./chunk-QOYAX2FT.js";import{readFileSync as $,writeFileSync as b,appendFileSync as V,existsSync as w,mkdirSync as L,readdirSync as D,statSync as F}from"fs";import{resolve as h,join as Y,relative as k,dirname as z}from"path";K();function U(A){return B.includes(A)}function G(A){if(!A)return;let t;try{t=JSON.parse(A)}catch{return}if(!Array.isArray(t))return;let e=t.filter(s=>typeof s=="object"&&s!==null&&typeof s.property=="string"&&s.property!==""&&typeof s.value=="string"&&s.value!=="");return e.length?e:void 0}function H(A,t){let e=a=>{let o=/^(.*Z)(?:-(\d+))?\.md$/.exec(a);return o?[o[1],o[2]?Number(o[2]):0]:[a,0]},[s,i]=e(A),[n,r]=e(t);return s<n?-1:s>n?1:i-r}var J=class{baseDir;rawDir;log;lockWaitMs=5e3;constructor(t=h(process.cwd(),".agentx/wiki"),e=console.error.bind(console,"[wiki]")){this.baseDir=t,this.rawDir=h(t,"raw/entries"),this.log=e,L(this.rawDir,{recursive:!0}),L(h(t,"raw"),{recursive:!0}),this.ensureSchema()}canRead(t,e){return t.access==="public"?!0:e?!!(t.owner===e||t.access==="shared"&&t.sharedWith?.includes(e)):!1}canWrite(t,e){return t.owner===e}addEntry(t){let e=`${t.date}_${t.id}.md`,s=h(this.rawDir,e),i=["---",`id: ${t.id}`,`date: ${t.date}`,`agent: ${t.agentId}`,`source: ${t.source}`];if(t.sourceContext&&i.push(`context: ${t.sourceContext}`),t.meta)for(let[n,r]of Object.entries(t.meta))i.push(`${n}: ${JSON.stringify(r)}`);return i.push("---","",t.content),b(s,i.join(`
|
|
2
2
|
`)),this.appendLog("ingest",`${t.id} from ${t.agentId} via ${t.source}`),e}readEntries(t){if(t.length===0||!w(this.rawDir))return[];let e=new Set(t),s=[];for(let i of D(this.rawDir)){let n=i.replace(/\.md$/,"").replace(/^\d{4}-\d{2}-\d{2}_/,"");if(!e.has(n))continue;let r=this.parseEntry($(h(this.rawDir,i),"utf-8"),i);r&&s.push(r)}return s}listEntries(t){if(!w(this.rawDir))return[];let e=D(this.rawDir).filter(i=>i.endsWith(".md")).sort(),s=[];for(let i of e){let n=$(h(this.rawDir,i),"utf-8"),r=this.parseEntry(n,i);r&&(t?.agentId&&r.agentId!==t.agentId||t?.after&&r.date<t.after||t?.before&&r.date>t.before||s.push(r))}return s}parseEntry(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=c=>i.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",a=new Set(["id","date","agent","source","context"]),o={};for(let c of i.split(`
|
|
3
3
|
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||a.has(l[1])))try{o[l[1]]=JSON.parse(l[2])}catch{o[l[1]]=l[2].trim()}}return{id:r("id")||e.replace(".md",""),date:r("date"),agentId:r("agent"),source:r("source"),sourceContext:r("context")||void 0,content:n,meta:Object.keys(o).length>0?o:void 0}}withArticleLock(t,e){let s=`${h(this.baseDir,"_locks",t)}.lock`;return N(h(this.baseDir,t),e,{lock:s,what:`wiki page ${t}`,timeoutMs:this.lockWaitMs,staleMs:1e4})}writeArticle(t,e,s,i){try{return this.withArticleLock(t,()=>this.writeArticleLocked(t,e,s,i))}catch(n){if(!(n instanceof P))throw n;return this.log(n.message),!1}}writeArticleLocked(t,e,s,i){let n=this.readArticle(t);if(n&&!this.canWrite(n.meta,i))return this.log(`Permission denied: "${i}" cannot write "${t}" (owner: ${n.meta.owner})`),!1;e.type&&!I(e.type)&&(this.log(`Dropping invalid article type "${e.type}" for "${t}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),e={...e,type:void 0});let r=h(this.baseDir,t);n&&this.saveVersion(t,r),L(z(r),{recursive:!0});let a=["---",`title: "${e.title}"`];e.type&&a.push(`type: ${e.type}`),e.related?.length&&a.push(`related: [${e.related.map(c=>`"${c}"`).join(", ")}]`),a.push(`tags: [${(e.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${e.owner}`,`access: ${e.access}`),e.sharedWith?.length&&a.push(`shared_with: [${e.sharedWith.map(c=>`"${c}"`).join(", ")}]`),a.push(`created: ${e.created}`,`last_updated: ${e.lastUpdated}`,`sources: [${e.sources.map(c=>`"${c}"`).join(", ")}]`),e.graphPath?.length&&a.push(`graph_path: [${e.graphPath.map(c=>`"${c}"`).join(", ")}]`),e.class&&a.push(`class: ${e.class}`),e.importance&&a.push(`importance: ${e.importance}`),e.importanceProposed&&a.push(`importance_proposed: ${e.importanceProposed}`),e.date&&a.push(`date: ${e.date}`),e.rolledUpInto&&a.push(`rolled_up_into: ${JSON.stringify(e.rolledUpInto)}`),e.aliases?.length&&a.push(`aliases: ${JSON.stringify(e.aliases)}`),e.statements?.length&&a.push(`statements: ${JSON.stringify(e.statements)}`),a.push("---","",s),b(r,a.join(`
|
|
4
4
|
`));let o=n?"update":"create";return this.appendLog(o,`${e.title} [${(e.tags||[]).slice(0,5).join(", ")}] by ${i} at ${t}`),!0}saveVersion(t,e){try{if(!w(e))return;let s=$(e,"utf-8"),i=new Date().toISOString().replace(/[:.]/g,"-"),n=h(this.baseDir,"_versions",t.replace(/\.md$/,""));L(n,{recursive:!0});for(let r=0;;r++)try{b(h(n,`${r?`${i}-${r}`:i}.md`),s,{flag:"wx"});return}catch(a){if(a.code!=="EEXIST")throw a}}catch{}}getVersions(t){let e=h(this.baseDir,"_versions",t.replace(/\.md$/,""));if(!w(e))return[];try{return D(e).filter(s=>s.endsWith(".md")).sort(H).reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(i,n)=>n<19?n===10?"T":n===13||n===16?":":"-":i),path:h(e,s)}))}catch{return[]}}restoreVersion(t,e){let s=this.getVersions(t),i=s.find(n=>n.timestamp===e)??s.find(n=>n.timestamp.startsWith(e));return i?this.withArticleLock(t,()=>this.restoreLocked(t,i.path,e)):!1}restoreLocked(t,e,s){try{let i=$(e,"utf-8"),n=h(this.baseDir,t);return this.saveVersion(t,n),b(n,i),this.appendLog("restore",`${t} restored to ${s}`),!0}catch{return!1}}readArticle(t){let e=h(this.baseDir,t);if(!w(e))return null;let s=$(e,"utf-8");return this.parseArticle(s,t)}readArticleAs(t,e){let s=this.readArticle(t);return!s||!this.canRead(s.meta,e)?null:s}parseArticle(t,e){let s=t.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let i=s[1],n=s[2].trim(),r=W=>i.match(new RegExp(`^${W}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",a=W=>{let v=i.match(new RegExp(`^${W}:\\s*\\[(.*)\\]$`,"m"));return v?[...v[1].matchAll(/\s*(?:"(.*?)"(?=\s*(?:,|$))|([^,]+))/g)].map(S=>(S[1]??S[2]).trim()).filter(Boolean):[]},o=r("type")||r("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(o)?o:void 0,g=a("tags").filter((W,v,S)=>W&&S.indexOf(W)===v),d=a("related"),p=a("graph_path"),m=a("aliases"),u=r("importance"),f=r("importance_proposed"),y=r("date");return{meta:{title:r("title"),type:l,related:d.length?d:void 0,tags:g,owner:r("owner"),access:r("access")||"public",sharedWith:a("shared_with"),created:r("created"),lastUpdated:r("last_updated"),sources:a("sources"),graphPath:p.length?p:void 0,class:/^[a-z][a-z0-9_]*$/.test(r("class"))?r("class"):void 0,importance:U(u)?u:void 0,importanceProposed:U(f)?f:void 0,date:/^\d{4}-\d{2}-\d{2}/.test(y)?y.slice(0,10):void 0,rolledUpInto:r("rolled_up_into")||void 0,aliases:m.length?m:void 0,statements:G(r("statements"))},content:n,path:e}}listCache=new Map;listArticles(t){return this.listCached(t)}listAllArticles(){return this.listCached(null)}listCached(t){let e=[],s=[];this.walkDir(this.baseDir,(o,c)=>{if(!o.endsWith(".md"))return;let l=k(this.baseDir,o);l.startsWith("raw/")||l.startsWith("_")||(e.push(l),s.push(`${l}:${c?.mtimeMs??"?"}:${c?.size??"?"}`))});let i=s.join("|"),n=t??"\0all",r=this.listCache.get(n);if(r&&r.signature===i)return r.articles.slice();let a=[];for(let o of e){let c=this.readArticle(o);c&&(t===null||this.canRead(c.meta,t))&&a.push(c)}return this.listCache.set(n,{signature:i,articles:a}),a.slice()}search(t,e,s=10){let i=t.toLowerCase(),n=[];if(this.walkDir(this.baseDir,d=>{if(!d.endsWith(".md"))return;let p=k(this.baseDir,d);if(p.startsWith("raw/")||p.startsWith("_"))return;let m=this.readArticle(p);!m||!this.canRead(m.meta,e)||n.push(m)}),n.length===0)return[];let r=n.map(d=>d.content),a=h(this.baseDir,"_bm25_cache.json"),o=x(r,a),c=_(t,o),l=new Map(c.map(d=>[d.docIndex,d.score]));return n.map((d,p)=>{let m=l.get(p)??0;return d.meta.title.toLowerCase().includes(i)&&(m+=10),d.meta.tags?.some(u=>u.toLowerCase().includes(i))&&(m+=5),{article:d,score:m}}).filter(d=>d.score>0).sort((d,p)=>p.score-d.score).slice(0,s).map(d=>d.article)}async findRelevantReranked(t,e,s=10,i={}){let n=Math.max(s,i.shortlist??E),r=this.findRelevant(t,e,n);if(r.length<2)return r.slice(0,s);let a=r.map((l,g)=>({id:`c${g}`,title:l.meta.title||`(untitled ${g})`,tags:l.meta.tags,excerpt:l.content})),o=await C(M,R({query:t,candidates:a,excerptChars:i.excerptChars}),T(a),{incumbent:{best:a[0].id},features:{agent:e??"unknown"}});return!o||o.mode!=="active"?r.slice(0,s):j(o.answers,a).ranked.map(l=>r[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(t,e,s=3,i,n={graph:.6,bm25:.4}){let r=[];if(this.walkDir(this.baseDir,u=>{if(!u.endsWith(".md"))return;let f=k(this.baseDir,u);if(f.startsWith("raw/")||f.startsWith("_"))return;let y=this.readArticle(f);!y||!this.canRead(y.meta,e)||r.push(y)}),r.length===0)return[];let a=r.map(u=>`${u.meta.title} ${(u.meta.tags||[]).join(" ")} ${u.content}`),o=h(this.baseDir,"_bm25_relevance_cache.json"),c=x(a,o),l=_(t,c),g=l.reduce((u,f)=>Math.max(u,f.score),0)||1,d=new Map(l.map(u=>[u.docIndex,u.score/g])),p=!!(i&&i.length>0);return r.map((u,f)=>{let y=d.get(f)??0,W=0;p&&u.meta.graphPath?.length&&(W=O(i,u.meta.graphPath));let v=p?n.graph*W+n.bm25*y:y;return{article:u,score:v}}).filter(u=>u.score>0).sort((u,f)=>f.score-u.score).slice(0,s).map(u=>u.article)}buildContext(t,e=4e3){if(t.length===0)return"";let s=["[Wiki Knowledge]"],i=0;for(let n of t){let r=`
|
|
@@ -102,4 +102,4 @@ We use GitLab for version control.
|
|
|
102
102
|
There are ${e.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
103
103
|
|
|
104
104
|
${s}`}walkDir(t,e){if(w(t))for(let s of D(t)){let i=Y(t,s),n=F(i);n.isDirectory()?this.walkDir(i,e):e(i,n)}}};export{J as a};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
105
|
+
//# sourceMappingURL=chunk-YUGYKMY6.js.map
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-OSH2PEBH.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-GBPLSXFF.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=client-
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-CGE5EAWC.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as fetchAgents,d as fetchCrons,c as fetchProcesses,e as killProcess,a as resolveConn,f as sendTask,g as streamTask};
|
|
2
|
+
//# sourceMappingURL=client-D3CYQPUD.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$a as h,Ua as a,Va as b,Wa as c,Xa as d,Ya as e,Za as f,_a as g,ab as i,bb as j,cb as k,db as l,eb as m,fb as n,gb as o,hb as p,ib as q,jb as r,kb as s,lb as t,mb as u,nb as v,ob as w,pb as x,qb as y,rb as z,tb as A}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=config-
|
|
1
|
+
import{$a as h,Ua as a,Va as b,Wa as c,Xa as d,Ya as e,Za as f,_a as g,ab as i,bb as j,cb as k,db as l,eb as m,fb as n,gb as o,hb as p,ib as q,jb as r,kb as s,lb as t,mb as u,nb as v,ob as w,pb as x,qb as y,rb as z,tb as A}from"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";A();export{a as INTEGRATION_KINDS,v as WIKI_CONTRIBUTE_JOB,w as WIKI_CONTRIBUTE_MERGE_JOB,y as WIKI_SUMMARIZE_JOB,o as approvalsConfigSchema,e as callsSchema,c as cameraBotSchema,t as crossFieldProblems,q as daemonConfigSchema,b as eventSubscriptionSchema,r as expandEnvVars,d as isCronExpression,s as loadDaemonConfig,l as membersConfigSchema,g as mergePolicyConfigSchema,k as peopleConfigSchema,j as personSchema,n as qualityReportConfigSchema,m as requestStatusConfigSchema,i as requestsConfigSchema,f as reviewGateConfigSchema,u as validateWorkspaces,p as wallConfigSchema,h as watchersConfigSchema,x as withContributionJobs,z as withSummariesJob};
|
|
2
|
+
//# sourceMappingURL=config-OTO56OCX.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b}from"./chunk-KVSHZKAL.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{a as mutateAgentxConfig,b as writeAgentxConfig};
|
|
2
|
+
//# sourceMappingURL=config-mutate-5KKGQHC6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-CRUNUMVO.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{b as applyConfigMutation,a as findConfigPath,d as getAtPath,c as setAtPath,e as unsetAtPath};
|
|
2
|
+
//# sourceMappingURL=config-mutator-XBUGJZER.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ee}from"./chunk-
|
|
1
|
+
import{a as ee}from"./chunk-FK2TJZNJ.js";import"./chunk-GJ4SQRAE.js";import{f as Q,k as V}from"./chunk-VL74KOR7.js";import{b as O}from"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-OWNQ2FD4.js";import{b as X}from"./chunk-KEXBEUSU.js";import"./chunk-ON7Y3JSP.js";import"./chunk-JTFCU5LH.js";import"./chunk-BC7VOHNH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-QT63Q6C5.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QUFIUXMQ.js";import"./chunk-BERWTVG2.js";import{b as N,c as H}from"./chunk-QOYAX2FT.js";import"./chunk-6QLRRSKU.js";import"./chunk-7I7IEX4S.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{createHash as le}from"crypto";import{existsSync as z,mkdirSync as ne,readdirSync as re,readFileSync as ge,renameSync as se,writeFileSync as pe}from"fs";import{resolve as w}from"path";var _={maxPatches:30,maxCostUsd:.5,maxItems:60},he=12,fe=2e3,me=1500,M=8,U=300,be=12,B="## Checked facts";function S(n){return w(n,"_contributions")}function E(n,r){if(!z(n))return r;try{return JSON.parse(ge(n,"utf-8"))}catch(t){throw new Error(`${n} is not valid JSON: ${t.message}`)}}function L(n,r){ne(w(n,".."),{recursive:!0});let t=`${n}.${process.pid}.tmp`;pe(t,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`),se(t,n)}function ie(n){return{agents:E(w(S(n),"state.json"),{agents:{}}).agents??{}}}function ye(n){let r=w(S(n),"pending");return z(r)?re(r).filter(t=>t.endsWith(".json")).sort().map(t=>E(w(r,t),null)).filter(t=>!!t):[]}function G(n){return w(S(n),"held.json")}function K(n,r={}){let t=E(G(n),[]);return r.all?t:t.filter(a=>a.status==="held")}function _e(n){let r=w(S(n),"reports");if(!z(r))return null;let t=re(r).filter(a=>a.endsWith(".json")).sort().pop();return t?E(w(r,t),null):null}function ke(n,r,t,a={}){let o=ie(r).agents[t],c=a.now??Date.now(),e=a.since??o?.lastRunAt??new Date(c-864e5).toISOString(),d=e.slice(0,10),u=new Set(o?.processed??[]),s=[];for(let g of n.getAgentEntries(t))g.date<d||u.has(g.id)||s.push({id:g.id,at:g.date,kind:"chat",title:[g.source,g.sourceContext].filter(Boolean).join(" \xB7 "),text:g.content});if(a.db){let g=Date.parse(e);for(let l of V(a.db,{agentId:t,since:Number.isFinite(g)?g:void 0,limit:500})){if(l.status==="in-flight"||u.has(l.taskId))continue;let k=(Q(a.db,l.taskId)?.steps??[]).filter(b=>b.name==="tool_use"||b.action).slice(0,be).map(b=>`- ${b.action??b.name}${b.inputSummary?` ${x(b.inputSummary,160)}`:""}${b.outputSummary?` \u2192 ${x(b.outputSummary,240)}`:""}${b.error?` \u2717 ${x(b.error,120)}`:""}`),y=[`Request: ${x(l.originalMessage??l.messagePreview??"",600)}`,k.length?`Tool calls:
|
|
3
3
|
${k.join(`
|
|
4
4
|
`)}`:"",l.finalResponse?`Reply: ${x(l.finalResponse,800)}`:""].filter(Boolean).join(`
|
|
@@ -54,4 +54,4 @@ _Sources: ${t.sources.join("; ")}._`,a);return n.writeArticle(r,{title:t.title,.
|
|
|
54
54
|
`).replace(/\n{3,}/g,`
|
|
55
55
|
|
|
56
56
|
`).trim(),superseded:d}}function Ce(n){let r=n.previous?` (previously: ${n.previous})`:"";return`- **${n.attribute}:** ${n.value} \u2014 ${n.source}; checked ${n.checkedAt.slice(0,10)} by ${n.by}${r}`}function Re(n){let r=n.match(/^- \*\*.+?:\*\* (.*?) — .*?; checked (\S+) by \S+(?: \(previously: (.*)\))?$/);return r?{value:r[1],checkedAt:r[2],...r[3]?{previous:r[3]}:{}}:void 0}function J(n,r){return`contribution:${n}@${r.slice(0,10)}`}var Te={person:"people",project:"projects",place:"places",concept:"concepts",event:"events",decision:"decisions",pattern:"patterns"};function de(n,r,t){let a=r.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"page",o=t?Te[t]:"contributions",c=`${o}/${a}.md`;for(let e=2;n.readArticle(c);e++)c=`${o}/${a}-${e}.md`;return c}export{_ as DEFAULT_CONTRIBUTION_LIMITS,B as FACTS_HEADING,ue as applyFactLines,De as approveHeld,xe as buildContributionPrompt,S as contributionsDir,_e as latestReport,K as listHeld,ye as listPendingBatches,Be as mergeContributions,W as pageKey,Ae as parseContributionPatches,ke as pendingWork,Se as possibleDuplicate,Fe as rejectHeld,ce as replaceOnce,Me as runContribution};
|
|
57
|
-
//# sourceMappingURL=contributions-
|
|
57
|
+
//# sourceMappingURL=contributions-SMSYSHPU.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=doctor-
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i}from"./chunk-S6ZZKRDB.js";import"./chunk-T5IGXFSW.js";import"./chunk-IMLAPB7G.js";import"./chunk-LQS27HSV.js";import"./chunk-MNG2AMKZ.js";import"./chunk-QPABR72X.js";import"./chunk-KP7KDLZ2.js";import"./chunk-OSH2PEBH.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";export{i as daemonVoiceCheck,b as doctor,g as meshPeerTokenChecks,h as meshTokenChecksFromConfig,a as runDoctorChecks,e as runMirrorChecks,d as runNativeChecks,c as runNotificationChecks,f as runReminderChecks};
|
|
2
|
+
//# sourceMappingURL=doctor-5PFLKGNU.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{b as h}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-RUB4HZEG.js";import"./chunk-RKPAVWXF.js";import"./chunk-CDPQQAK6.js";import{b as I}from"./chunk-PYHR4HXO.js";import"./chunk-KP7KDLZ2.js";import"./chunk-PSTEWKR3.js";import"./chunk-CRUNUMVO.js";import"./chunk-3UOTLMXD.js";import"./chunk-FCPTN6NF.js";import"./chunk-7I7IEX4S.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-QIJLFPWE.js";var p=t=>typeof t=="string"?t.trim():"";function $(t){return[`Run ${t.runId} "${t.title}" [${t.status}] on step ${t.step}: waiting on ${t.waitingOn}.`,t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",...(t.steps??[]).slice(-8).map(s=>`- ${String(s.at).slice(0,16).replace("T"," ")} ${s.step} ${s.status}${s.note?`: ${s.note}`:""}`)].filter(Boolean).join(`
|
|
2
2
|
`)}async function T(t,c){let s=c.fetch??fetch,m=c.daemonUrl.replace(/\/$/,""),r=(p(t.action)||"list").toLowerCase(),f=c.env??process.env,w=async i=>{let l=await s(`${m}${i}`,{signal:AbortSignal.timeout(1e4)}),n=await l.json().catch(()=>({}));return{ok:l.ok,status:l.status,data:n}};try{if(r==="list"){let e=await w("/follow-up");if(!e.ok)return`Error: ${e.data?.error||`HTTP ${e.status}`}`;let o=e.data.groups??[];return o.length?o.map(d=>[`${d.tag}:`,...d.rows.map(a=>`- ${a.runId} "${a.title}" on ${a.step}: waiting on ${a.waitingOn} (since ${String(a.since).slice(0,16).replace("T"," ")} UTC)`)].join(`
|
|
3
3
|
`)).join(`
|
|
4
4
|
`):"No follow-up workflows are running."}if(r==="match"){let e=p(t.request)||p(t.title);if(!e)return"Error: match needs `request`: the owner's request in their words.";let o=h(t,f),d=await w(`/follow-up/match?q=${encodeURIComponent(e)}${o?`&agentId=${encodeURIComponent(o.agentId)}`:""}`);if(!d.ok)return`Error: ${d.data?.error||`HTTP ${d.status}`}`;let a=d.data.matches??[];return a.length?["Saved workflows, best fit first (confidence 0-1):",...a.map(u=>`- ${u.workflowId} "${u.title}" (${u.confidence}${u.autoStart?", starts without asking":""}): ${u.steps.map(k=>k.id).join(" \u2192 ")}`),'Start one with {action:"start", workflowId:"<id>", title:"\u2026", tags:["client:<name>"]}. Run its steps through the workflow, not by hand.'].join(`
|
|
5
5
|
`):"No saved workflow fits. If the request has several steps, build one: start with title and steps."}if(r==="status"){let e=p(t.runId);if(!e)return"Error: status needs runId.";let o=await w(`/follow-up/${encodeURIComponent(e)}`);return o.ok?$(o.data.run):`Error: ${o.data?.error||`HTTP ${o.status}`}`}let i=h(t,f);if(!i)return"Error: couldn't tell which agent you are. Pass callerAgentId.";let l=await s(`${m}/follow-up`,{method:"POST",headers:{"Content-Type":"application/json",...I(f)},body:JSON.stringify({action:r,agentId:i.agentId,workflowId:t.workflowId,title:t.title,description:t.description,tags:t.tags,inputs:t.inputs,steps:t.steps,edges:t.edges,approval:t.approval,autoStart:t.autoStart,requestId:t.requestId,runId:t.runId,step:t.step,evidence:t.evidence,note:t.note,reason:t.reason,fromRun:t.fromRun,status:t.status}),signal:AbortSignal.timeout(2e4)}),n=await l.json().catch(()=>({}));if(!l.ok)return`Error: ${n?.error||`HTTP ${l.status}`}`;if(r==="start"){let e=n.run;return[`Started run ${e.runId} "${e.title}"${n.built?" (built from the steps you gave; propose it with fromRun to keep it)":""}.`,n.awaitingApproval?"It waits for the owner's approval before the first step.":`It is on step ${e.step}: ${e.waitingOn}.`,"AgentX follows it from here: it starts each step, reminds whoever is slow, and tells the owner when it ends. Do not run its steps by hand.",...n.warning?[`Note: ${n.warning}`]:[]].join(" ")}return r==="plan"?[`Plan recorded on run ${n.run?.runId??t.runId}:`,...(n.plan??[]).map(e=>`- ${e.id} ${e.title}`),'Report each step with {action:"step", runId, step:"<id>", status:"started"|"done"|"failed"}.'].join(`
|
|
6
6
|
`):r==="step"?`Step recorded. ${n.run?$(n.run):""}`.trim():r==="done"?`Step recorded as done. ${n.run?$(n.run):""}`.trim():r==="blocked"?"The step is marked blocked and the owner is told. Nothing more happens on it until it is sorted.":`Saved ${n.workflowId} switched off, and asked the owner (card ${n.cardId}) whether to keep it as a reusable workflow.`}catch(i){return`Error: couldn't reach the daemon (${i?.message??i}).`}}export{T as runWorkflowTool};
|
|
7
|
-
//# sourceMappingURL=follow-up-tool-
|
|
7
|
+
//# sourceMappingURL=follow-up-tool-ME4DV7HT.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a}from"./chunk-NCEYJFF5.js";import"./chunk-YUGYKMY6.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-BC7VOHNH.js";import"./chunk-WPNRDEHW.js";import"./chunk-QT63Q6C5.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-QOYAX2FT.js";import"./chunk-6QLRRSKU.js";import"./chunk-7I7IEX4S.js";import"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{a as WikiHub};
|
|
2
|
+
//# sourceMappingURL=hub-WGUNZ2D5.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -12941,6 +12941,23 @@ declare class AgentXDaemon {
|
|
|
12941
12941
|
* board-dashboard routes), but no transitions fire. */
|
|
12942
12942
|
private bootWorkflowEngine;
|
|
12943
12943
|
private startHttpApi;
|
|
12944
|
+
/**
|
|
12945
|
+
* POST /send/agent, and POST /send on an a2a chat (#1251).
|
|
12946
|
+
*
|
|
12947
|
+
* Explicit A2A send: route to another agent via mesh (or local
|
|
12948
|
+
* dispatch when the target lives on this daemon). This is the
|
|
12949
|
+
* deterministic path for "agent A asks agent B to do X" — no
|
|
12950
|
+
* contact-directory fallback, no name fuzzy-matching. Caller
|
|
12951
|
+
* must pass an exact agentId.
|
|
12952
|
+
*
|
|
12953
|
+
* retro:01M4DJTC01FK0BVCMFKT5K4SRQ (#847) — answers 202
|
|
12954
|
+
* {accepted, taskId, status: "queued"} as soon as the work is
|
|
12955
|
+
* handed off, local or mesh; the target's turn runs in the
|
|
12956
|
+
* background. A repeat of the same message from the same sender
|
|
12957
|
+
* within the dedupe window gets the first task id back. Only
|
|
12958
|
+
* `"async": false` still waits for the answer.
|
|
12959
|
+
*/
|
|
12960
|
+
private sendToAgent;
|
|
12944
12961
|
/**
|
|
12945
12962
|
* #277 — the gate every agent-to-agent request on this node goes through.
|
|
12946
12963
|
*
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Fa as Tt,Ga as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-
|
|
1
|
+
import{Fa as Tt,Ga as Mt,a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt}from"./chunk-KTJ6234K.js";import"./chunk-EXJGRK2N.js";import"./chunk-GTJIKXDB.js";import"./chunk-6Y53LLIX.js";import"./chunk-T5IGXFSW.js";import"./chunk-VUEQ4SL5.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-BNOGNRAM.js";import"./chunk-LQS27HSV.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-73SESASJ.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import"./chunk-UKUH662W.js";import"./chunk-6V5JBHUN.js";import"./chunk-2VDO2HEK.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-MNG2AMKZ.js";import"./chunk-X7UQY7CH.js";import"./chunk-QPABR72X.js";import"./chunk-CDPQQAK6.js";import"./chunk-PYHR4HXO.js";import"./chunk-KP7KDLZ2.js";import"./chunk-A5GYG56I.js";import{m as lt,n as ct,o as dt,p as mt,q as pt,ra as yt}from"./chunk-ILHTAVZZ.js";import"./chunk-AXDNFXYU.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-TCC56PYX.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-Y6JSB5II.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-6TTGRTDO.js";import"./chunk-SZDACK6O.js";import"./chunk-VE3SSOQX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-VL74KOR7.js";import{s as ut}from"./chunk-PSTEWKR3.js";import"./chunk-CRUNUMVO.js";import"./chunk-3UOTLMXD.js";import"./chunk-XIRM45DH.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-NCEYJFF5.js";import{a as ht}from"./chunk-YUGYKMY6.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-ON7Y3JSP.js";import"./chunk-JTFCU5LH.js";import{f as gt,g as ft}from"./chunk-BC7VOHNH.js";import"./chunk-WPNRDEHW.js";import"./chunk-LUOW2YHY.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-V7R5AJVN.js";import{j as it,k as rt,l as at}from"./chunk-QT63Q6C5.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-QUFIUXMQ.js";import"./chunk-AV7T3SYT.js";import"./chunk-TM2TPQKH.js";import"./chunk-BERWTVG2.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-6QLRRSKU.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{ib as tt,kb as st,mb as ot,tb as nt}from"./chunk-IVTO54EM.js";import"./chunk-BRK6M6LA.js";import"./chunk-UEEB3UTU.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|