agentix-cli 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +102 -103
- package/agentx.example.json +9 -3
- package/dist/App-6Y7B3YQH.js +8 -0
- package/dist/App-6Y7B3YQH.js.map +1 -0
- package/dist/ChatApp-KIEUJ2DS.js +7 -0
- package/dist/ChatApp-KIEUJ2DS.js.map +1 -0
- package/dist/{agent-FSE4KRLX.js → agent-QGZIAZMY.js} +2 -2
- package/dist/architect-SEPWMWS4.js +2 -0
- package/dist/{board-dashboard-PUACKWAN.js → board-dashboard-CQ5F4GPD.js} +3756 -1010
- package/dist/board-dashboard-CQ5F4GPD.js.map +1 -0
- package/dist/builtin-FRKAQMFS.js +2 -0
- package/dist/chunk-2WVX3LEC.js +2 -0
- package/dist/chunk-2WVX3LEC.js.map +1 -0
- package/dist/chunk-3WQFCIB6.js +24 -0
- package/dist/chunk-3WQFCIB6.js.map +1 -0
- package/dist/chunk-53GCFZPR.js +116 -0
- package/dist/chunk-53GCFZPR.js.map +1 -0
- package/dist/{chunk-IKBHHTIT.js → chunk-5U35WAZF.js} +2 -2
- package/dist/chunk-67Q4DCPS.js +54 -0
- package/dist/chunk-67Q4DCPS.js.map +1 -0
- package/dist/chunk-76Z4VHDX.js +8 -0
- package/dist/chunk-76Z4VHDX.js.map +1 -0
- package/dist/{chunk-7P5QRX5W.js → chunk-BFXONUUN.js} +2 -2
- package/dist/{chunk-DXTIG5YV.js → chunk-FDMWOPEL.js} +2 -2
- package/dist/chunk-FDWOECJY.js +54 -0
- package/dist/chunk-FDWOECJY.js.map +1 -0
- package/dist/chunk-G57RZCXM.js +5 -0
- package/dist/chunk-G57RZCXM.js.map +1 -0
- package/dist/{chunk-NOF4HSGK.js → chunk-H5D7ATXS.js} +2 -2
- package/dist/chunk-HA3XI7Z2.js +155 -0
- package/dist/chunk-HA3XI7Z2.js.map +1 -0
- package/dist/chunk-HR4JSRZS.js +3 -0
- package/dist/{chunk-A6BKSZQA.js.map → chunk-HR4JSRZS.js.map} +1 -1
- package/dist/chunk-I3SIXTJO.js +44 -0
- package/dist/chunk-I3SIXTJO.js.map +1 -0
- package/dist/chunk-ISEBLHWX.js +118 -0
- package/dist/chunk-ISEBLHWX.js.map +1 -0
- package/dist/{chunk-4ITQP3XL.js → chunk-JP5IEXR7.js} +2 -2
- package/dist/chunk-JXWAGMI2.js +13 -0
- package/dist/chunk-JXWAGMI2.js.map +1 -0
- package/dist/chunk-KUCCW2VG.js +431 -0
- package/dist/chunk-KUCCW2VG.js.map +1 -0
- package/dist/chunk-LDHPMJ7M.js +257 -0
- package/dist/chunk-LDHPMJ7M.js.map +1 -0
- package/dist/{chunk-KWUWZQGV.js → chunk-LNXCJWOU.js} +29 -30
- package/dist/chunk-LNXCJWOU.js.map +1 -0
- package/dist/chunk-M4AMWP3H.js +178 -0
- package/dist/chunk-M4AMWP3H.js.map +1 -0
- package/dist/chunk-NGSIRE4X.js +126 -0
- package/dist/chunk-NGSIRE4X.js.map +1 -0
- package/dist/{chunk-CNNLREHD.js → chunk-P4VWIVKN.js} +268 -410
- package/dist/chunk-P4VWIVKN.js.map +1 -0
- package/dist/chunk-Q6YO7LYE.js +47 -0
- package/dist/chunk-Q6YO7LYE.js.map +1 -0
- package/dist/chunk-TMKLHTCG.js +971 -0
- package/dist/chunk-TMKLHTCG.js.map +1 -0
- package/dist/chunk-TRJTTBE2.js +7 -0
- package/dist/chunk-TRJTTBE2.js.map +1 -0
- package/dist/chunk-U2CKL755.js +4 -0
- package/dist/chunk-U2CKL755.js.map +1 -0
- package/dist/chunk-UCQ2N3KO.js +9 -0
- package/dist/chunk-UCQ2N3KO.js.map +1 -0
- package/dist/chunk-W4YR2RO2.js +2 -0
- package/dist/chunk-W4YR2RO2.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-GGVVLOOF.js +2 -0
- package/dist/{compaction-BTUJJ3LJ.js → compaction-NWEMOSHA.js} +3 -3
- package/dist/config-7FSZFRTQ.js +2 -0
- package/dist/config-mutator-POCOYYJ4.js +2 -0
- package/dist/{context-planner-I7ID7XF3.js → context-planner-45GEWKGL.js} +2 -2
- package/dist/doctor-DHLBEKA4.js +2 -0
- package/dist/heal-HZ3EQD52.js +2 -0
- package/dist/index.d.ts +1193 -225
- package/dist/index.js +12 -12
- package/dist/index.js.map +1 -1
- package/dist/memory-extract-AENFVVO5.js +2 -0
- package/dist/processes-UIC4XXA6.js +2 -0
- package/dist/program-WVAVJFND.js +2 -0
- package/dist/projects-api-KRME2YKZ.js +2 -0
- package/dist/projects-api-KRME2YKZ.js.map +1 -0
- package/dist/projects-mutate-3NHVG437.js +7 -0
- package/dist/projects-mutate-3NHVG437.js.map +1 -0
- package/dist/providers-L27BJ5A6.js +2 -0
- package/dist/registry-T36ZIAWV.js +2 -0
- package/dist/rotation-memo-B3EXXSEH.js +13 -0
- package/dist/rotation-memo-B3EXXSEH.js.map +1 -0
- package/dist/scheduler-GH7TIKYS.js +2 -0
- package/dist/surface-usage-PRL6Z4U3.js +2 -0
- package/dist/wiki-M6YNRFC4.js +2 -0
- package/dist/workflows/templates/branching.yaml +75 -0
- package/dist/workflows/templates/extract.yaml +59 -0
- package/dist/workflows/templates/linear.yaml +37 -0
- package/dist/workflows/templates/retry.yaml +61 -0
- package/dist/workspace-setup-TBQAHYHJ.js +2 -0
- package/package.json +10 -3
- package/dist/board-dashboard-PUACKWAN.js.map +0 -1
- package/dist/builtin-TQKMR42Z.js +0 -2
- package/dist/chunk-3SHMHYPD.js +0 -450
- package/dist/chunk-3SHMHYPD.js.map +0 -1
- package/dist/chunk-4INOOHND.js +0 -6
- package/dist/chunk-4INOOHND.js.map +0 -1
- package/dist/chunk-5F3J55LG.js +0 -2
- package/dist/chunk-5F3J55LG.js.map +0 -1
- package/dist/chunk-72PAN7UI.js +0 -103
- package/dist/chunk-72PAN7UI.js.map +0 -1
- package/dist/chunk-A6BKSZQA.js +0 -3
- package/dist/chunk-BHSPAP4U.js +0 -44
- package/dist/chunk-BHSPAP4U.js.map +0 -1
- package/dist/chunk-BOUKM2PS.js +0 -163
- package/dist/chunk-BOUKM2PS.js.map +0 -1
- package/dist/chunk-CDNWCYF7.js +0 -2
- package/dist/chunk-CDNWCYF7.js.map +0 -1
- package/dist/chunk-CNNLREHD.js.map +0 -1
- package/dist/chunk-EK37JHJI.js +0 -13
- package/dist/chunk-EK37JHJI.js.map +0 -1
- package/dist/chunk-EQPUB7CZ.js +0 -685
- package/dist/chunk-EQPUB7CZ.js.map +0 -1
- package/dist/chunk-EW27SCCC.js +0 -2
- package/dist/chunk-EW27SCCC.js.map +0 -1
- package/dist/chunk-GOLZ6NEL.js +0 -111
- package/dist/chunk-GOLZ6NEL.js.map +0 -1
- package/dist/chunk-JGXE2YNV.js +0 -46
- package/dist/chunk-JGXE2YNV.js.map +0 -1
- package/dist/chunk-KWUWZQGV.js.map +0 -1
- package/dist/chunk-MTRWXRFF.js +0 -380
- package/dist/chunk-MTRWXRFF.js.map +0 -1
- package/dist/chunk-N67JZAXU.js +0 -2
- package/dist/chunk-N67JZAXU.js.map +0 -1
- package/dist/chunk-PD5Q7D6Z.js +0 -7
- package/dist/chunk-PD5Q7D6Z.js.map +0 -1
- package/dist/chunk-Q6CAFGXT.js +0 -118
- package/dist/chunk-Q6CAFGXT.js.map +0 -1
- package/dist/chunk-WJXU5F4Z.js +0 -53
- package/dist/chunk-WJXU5F4Z.js.map +0 -1
- package/dist/chunk-ZZFXI3CS.js +0 -8
- package/dist/chunk-ZZFXI3CS.js.map +0 -1
- package/dist/config-ADS54KLC.js +0 -2
- package/dist/config-mutator-WTRMBZTO.js +0 -2
- package/dist/doctor-T6RB4Q5X.js +0 -2
- package/dist/editor-chat-RVLCKKB7.js +0 -137
- package/dist/editor-chat-RVLCKKB7.js.map +0 -1
- package/dist/heal-YEQYWX2L.js +0 -2
- package/dist/inbox-BIN2S5XN.js +0 -2
- package/dist/memory-extract-KRCHD3OP.js +0 -2
- package/dist/processes-RJ6RDP32.js +0 -2
- package/dist/program-V7NGFB2R.js +0 -2
- package/dist/providers-WVCMIW67.js +0 -2
- package/dist/registry-42HEWCLA.js +0 -2
- package/dist/rotation-memo-GMTZPMNE.js +0 -13
- package/dist/rotation-memo-GMTZPMNE.js.map +0 -1
- package/dist/scheduler-C56ABAVP.js +0 -2
- package/dist/slack-6P7ZJ32Y.js +0 -3
- package/dist/slack-6P7ZJ32Y.js.map +0 -1
- package/dist/store-BAPDZHXE.js +0 -2
- package/dist/task-store-RHISEU6V.js +0 -2
- package/dist/telegram-PIYDRM46.js +0 -3
- package/dist/telegram-PIYDRM46.js.map +0 -1
- package/dist/types-ZRLHHCGB.js +0 -2
- package/dist/web/workflow-editor.global.js +0 -1452
- package/dist/web/workflow-editor.global.js.map +0 -1
- package/dist/whatsapp-PFRDMUMT.js +0 -3
- package/dist/whatsapp-PFRDMUMT.js.map +0 -1
- package/dist/wiki-53W5NLZV.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js +0 -2
- package/dist/workspace-setup-DQCZX2NE.js.map +0 -1
- /package/dist/{agent-FSE4KRLX.js.map → agent-QGZIAZMY.js.map} +0 -0
- /package/dist/{builtin-TQKMR42Z.js.map → architect-SEPWMWS4.js.map} +0 -0
- /package/dist/{config-ADS54KLC.js.map → builtin-FRKAQMFS.js.map} +0 -0
- /package/dist/{chunk-IKBHHTIT.js.map → chunk-5U35WAZF.js.map} +0 -0
- /package/dist/{chunk-7P5QRX5W.js.map → chunk-BFXONUUN.js.map} +0 -0
- /package/dist/{chunk-DXTIG5YV.js.map → chunk-FDMWOPEL.js.map} +0 -0
- /package/dist/{chunk-NOF4HSGK.js.map → chunk-H5D7ATXS.js.map} +0 -0
- /package/dist/{chunk-4ITQP3XL.js.map → chunk-JP5IEXR7.js.map} +0 -0
- /package/dist/{config-mutator-WTRMBZTO.js.map → client-GGVVLOOF.js.map} +0 -0
- /package/dist/{compaction-BTUJJ3LJ.js.map → compaction-NWEMOSHA.js.map} +0 -0
- /package/dist/{doctor-T6RB4Q5X.js.map → config-7FSZFRTQ.js.map} +0 -0
- /package/dist/{heal-YEQYWX2L.js.map → config-mutator-POCOYYJ4.js.map} +0 -0
- /package/dist/{context-planner-I7ID7XF3.js.map → context-planner-45GEWKGL.js.map} +0 -0
- /package/dist/{inbox-BIN2S5XN.js.map → doctor-DHLBEKA4.js.map} +0 -0
- /package/dist/{memory-extract-KRCHD3OP.js.map → heal-HZ3EQD52.js.map} +0 -0
- /package/dist/{processes-RJ6RDP32.js.map → memory-extract-AENFVVO5.js.map} +0 -0
- /package/dist/{program-V7NGFB2R.js.map → processes-UIC4XXA6.js.map} +0 -0
- /package/dist/{providers-WVCMIW67.js.map → program-WVAVJFND.js.map} +0 -0
- /package/dist/{registry-42HEWCLA.js.map → providers-L27BJ5A6.js.map} +0 -0
- /package/dist/{scheduler-C56ABAVP.js.map → registry-T36ZIAWV.js.map} +0 -0
- /package/dist/{store-BAPDZHXE.js.map → scheduler-GH7TIKYS.js.map} +0 -0
- /package/dist/{task-store-RHISEU6V.js.map → surface-usage-PRL6Z4U3.js.map} +0 -0
- /package/dist/{types-ZRLHHCGB.js.map → wiki-M6YNRFC4.js.map} +0 -0
- /package/dist/{wiki-53W5NLZV.js.map → workspace-setup-TBQAHYHJ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/sqlite.ts"],"sourcesContent":["import type Database from \"better-sqlite3\"\nimport { createRequire } from \"module\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\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\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\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}\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\n // Reclaim the freelist pages so the file shrinks. WAL writes still\n // checkpoint independently.\n if (taskHistory + rotations + routeTraces + taskTraces > 0) {\n try { db.pragma(\"incremental_vacuum\") } catch { /* best-effort */ }\n }\n\n return { taskHistory, rotations, routeTraces, taskTraces }\n}\n"],"mappings":"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","names":["createRequire","mkdirSync","dirname","resolve","require","_db","_Database","betterSqlite3Fix","error","msg","abi","hint","loadDatabaseCtor","quiet","e","openDb","opts","path","Database","db","runMigrations","runMigrations","db","current","steps","txn","step","insertTaskQueue","db","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"]}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import{a as He,b as De,c as ve}from"./chunk-SFQUP3BP.js";import{a as X,c as Ue,e as ye,f as we,h as ke,m as be}from"./chunk-FDWOECJY.js";import{a as R}from"./chunk-VJUTQAPJ.js";import{a as Ge,d as xe}from"./chunk-DJEZ2HVU.js";import{e as b}from"./chunk-DSYKYZMT.js";import{b as _e,c as Te}from"./chunk-QOYAX2FT.js";import{z as M}from"zod";var Fe=M.object({provider:M.enum(["claude-code","claude","openai","deepseek","ollama","demo","custom"]).default("claude-code"),model:M.string().optional(),apiKey:M.string().optional(),skills:M.array(M.string()).default([]),output:M.object({dir:M.string().default("./generated")}).default({}),context7:M.object({enabled:M.boolean().default(!0),apiKey:M.string().optional()}).default({}),agentic:M.object({maxIterations:M.number().default(20),enabledTools:M.array(M.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:M.array(M.string()).default([])}).default({})}),Wt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],zt={component:"UI component (any framework)",page:"Full page or screen",api:"API endpoint, route handler, or service",website:"Multi-page website or app",document:"Markdown, documentation, or specification",script:"Standalone script or utility",config:"Configuration file or setup",skill:"Agent skill (SKILL.md format for skills.sh)",media:"Media generation prompt (image/audio/video description)",report:"Analysis report or audit",test:"Test suite, test fixtures, or test data",workflow:"CI/CD pipeline, GitHub Actions, or automation",schema:"Database schema, Zod validators, or GraphQL types",email:"Email template (React Email, MJML, HTML)",diagram:"Mermaid, D2, or PlantUML diagram",auto:"Auto-detect the best output type"};import{existsSync as mt,promises as ft}from"fs";import K from"path";import gt from"fast-glob";var Le={"prisma/schema.prisma":{type:"prisma",category:"database"},"drizzle/schema.ts":{type:"drizzle",category:"database"},"schema.graphql":{type:"graphql",category:"api"},"schema.gql":{type:"graphql",category:"api"},"openapi.yaml":{type:"openapi",category:"api"},"openapi.json":{type:"openapi",category:"api"},"swagger.yaml":{type:"openapi",category:"api"},"swagger.json":{type:"openapi",category:"api"}};async function qe(r){let e={},t=await gt.glob("**/*",{cwd:r,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Le)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="database"){let a=await Z(K.resolve(r,c));if(a){e.database={type:i.type,content:ce(a,3e3),tables:ht(a,i.type)};break}}}for(let[s,i]of Object.entries(Le)){let c=t.find(a=>a.endsWith(s)||a===s);if(c&&i.category==="api"){let a=await Z(K.resolve(r,c));if(a){e.api={type:i.type,content:ce(a,3e3)};break}}}if(!e.api){let s=t.find(i=>i.includes("trpc")&&(i.endsWith("router.ts")||i.endsWith("router.js")));if(s){let i=await Z(K.resolve(r,s));i&&(e.api={type:"trpc",content:ce(i,3e3)})}}let o=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(o){let s=await Z(K.resolve(r,o));s&&(e.env=yt(s))}let n=t.filter(s=>(s.includes("models")||s.includes("types")||s.includes("schemas"))&&(s.endsWith(".ts")||s.endsWith(".py")||s.endsWith(".rs")||s.endsWith(".go")));if(n.length){e.models=[];for(let s of n.slice(0,5)){let i=await Z(K.resolve(r,s));i&&e.models.push({path:s,content:ce(i,2e3),type:K.extname(s).slice(1)})}}return e}function ht(r,e){if(e==="prisma"){let t=r.match(/model\s+(\w+)\s*\{/g);return t?t.map(o=>o.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function yt(r){return{variables:r.split(`
|
|
2
|
+
`).filter(o=>o.trim()&&!o.trim().startsWith("#")).map(o=>{let[n]=o.split("="),s=n.trim(),i=o.includes("=")&&o.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function Z(r){try{return mt(r)?await ft.readFile(r,"utf8"):null}catch{return null}}function ce(r,e){return r.length<=e?r:r.slice(0,e)+`
|
|
3
|
+
... (truncated)`}function Be(r){let e=[];if(r.database&&e.push(`## Database Schema (${r.database.type})
|
|
4
|
+
`+(r.database.tables?.length?`Tables: ${r.database.tables.join(", ")}
|
|
5
|
+
`:"")+"```\n"+r.database.content+"\n```"),r.api&&e.push(`## API Schema (${r.api.type})
|
|
6
|
+
\`\`\`
|
|
7
|
+
`+r.api.content+"\n```"),r.env&&e.push(`## Environment Variables
|
|
8
|
+
`+r.env.variables.map(t=>`- ${t.key}${t.required?" (required)":""}`).join(`
|
|
9
|
+
`)),r.models?.length)for(let t of r.models)e.push(`## Model: ${t.path}
|
|
10
|
+
\`\`\``+t.type+`
|
|
11
|
+
`+t.content+"\n```");return e.join(`
|
|
12
|
+
|
|
13
|
+
`)}import We from"node-fetch";var ze="https://api.context7.com/v1";async function wt(r,e){try{let t={"Content-Type":"application/json"};e&&(t.Authorization=`Bearer ${e}`);let o=await We(`${ze}/libraries/resolve`,{method:"POST",headers:t,body:JSON.stringify({name:r})});if(!o.ok)return null;let n=await o.json();return n?.libraries?.length?n.libraries[0]:null}catch{return null}}async function kt(r,e,t=5e3,o){try{let n={"Content-Type":"application/json"};o&&(n.Authorization=`Bearer ${o}`);let s=await We(`${ze}/libraries/${encodeURIComponent(r)}/docs`,{method:"POST",headers:n,body:JSON.stringify({topic:e,maxTokens:t})});return s.ok&&(await s.json())?.content||null}catch{return null}}async function Je(r,e,t){let o=[];for(let i of r.frameworks.slice(0,3))o.push(i.name);let n=["react","vue","svelte","angular","next","nuxt","express","fastify","hono","prisma","drizzle-orm","tailwindcss","shadcn","@tanstack/react-query","zod","trpc"];for(let i of n)(r.dependencies[i]||r.devDependencies[i])&&(o.includes(i)||o.push(i));let s=[];for(let i of o.slice(0,5)){let c=await wt(i,t);if(c){let a=await kt(c.id,e,3e3,t);a&&s.push(`## ${c.name} Documentation
|
|
14
|
+
${a}`)}}return s.length?`# Relevant Library Documentation (via Context7)
|
|
15
|
+
|
|
16
|
+
${s.join(`
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
`)}`:""}var Ke={component:{type:"component",baseDir:"src/components",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.ts"],description:"UI component"},page:{type:"page",baseDir:"src/app",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.astro"],description:"Page or screen"},api:{type:"api",baseDir:"src/api",filePatterns:["*.ts","*.js","*.py","*.go","*.rs"],description:"API route or endpoint"},website:{type:"website",baseDir:".",filePatterns:["*"],description:"Multi-file website"},document:{type:"document",baseDir:"docs",filePatterns:["*.md","*.mdx","*.txt","*.rst"],description:"Documentation"},script:{type:"script",baseDir:"scripts",filePatterns:["*.ts","*.js","*.py","*.sh","*.go"],description:"Standalone script"},config:{type:"config",baseDir:".",filePatterns:["*.json","*.yaml","*.yml","*.toml","*.env"],description:"Configuration file"},skill:{type:"skill",baseDir:".skills",filePatterns:["SKILL.md"],description:"Agent skill (SKILL.md)"},media:{type:"media",baseDir:"media",filePatterns:["*.md","*.json","*.txt"],description:"Media generation prompt/description"},report:{type:"report",baseDir:"reports",filePatterns:["*.md","*.html","*.json"],description:"Analysis report"},test:{type:"test",baseDir:"src",filePatterns:["*.test.ts","*.test.tsx","*.spec.ts","*.test.js","*.test.py","*.test.go"],description:"Test suite or fixture"},workflow:{type:"workflow",baseDir:".github/workflows",filePatterns:["*.yml","*.yaml"],description:"CI/CD pipeline or automation"},schema:{type:"schema",baseDir:"src",filePatterns:["*.ts","*.prisma","*.graphql","*.gql","*.py"],description:"Database schema, validators, or types"},email:{type:"email",baseDir:"src/emails",filePatterns:["*.tsx","*.jsx","*.html","*.mjml"],description:"Email template"},diagram:{type:"diagram",baseDir:"docs",filePatterns:["*.md","*.mmd","*.d2","*.puml"],description:"Architecture or data diagram"}};function Se(r,e){if(r&&r!=="auto")return r;let t=e.toLowerCase(),o=[[/\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\b/i,"component"],[/\b(page|screen|view|route|layout|dashboard|landing)\b/i,"page"],[/\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\b/i,"api"],[/\b(website|site|web app|landing page|portfolio|blog)\b/i,"website"],[/\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\b/i,"document"],[/\b(script|cli|command|tool|utility|migration|seed|cron)\b/i,"script"],[/\b(config|configuration|setup|env|settings)\b/i,"config"],[/\b(skill|agent skill|skill\.md)\b/i,"skill"],[/\b(video|audio|image|media|animation|thumbnail|podcast)\b/i,"media"],[/\b(report|audit|analysis|review|assessment|benchmark)\b/i,"report"],[/\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\b/i,"test"],[/\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\/cd)\b/i,"workflow"],[/\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\b/i,"schema"],[/\b(email|newsletter|transactional|invite|welcome email|notification email)\b/i,"email"],[/\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\b/i,"diagram"]];for(let[n,s]of o)if(n.test(t))return s;return"component"}import{existsSync as Ot,promises as et}from"fs";import ue from"path";import{execa as vt}from"execa";import{z as D}from"zod";var ee=["pre:generate","post:generate","pre:file-write","post:file-write","pre:prompt","post:response","pre:command","on:error","pre:tool-call","post:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run","post:cron-run","on:gitlab-pipeline","on:gitlab-issue","on:gitlab-mr","on:gitlab-note","on:github-issue","on:github-pr","on:github-push","on:stripe-event","on:sentry-issue","on:vercel-deployment","on:odoo-event","on:hubspot-event"],Pe=["pre:generate","pre:file-write","pre:prompt","post:response","pre:command","pre:tool-call","pre:channel-message","post:channel-message","pre:a2a-task","pre:cron-run"],Qe=D.object({name:D.string(),type:D.enum(["command","prompt","script"]),command:D.string().optional(),prompt:D.string().optional(),provider:D.enum(["claude-code","claude","openai","deepseek","ollama","custom"]).optional(),model:D.string().optional(),script:D.string().optional(),priority:D.number().default(100),enabled:D.boolean().default(!0)});var Ve={"claude-sonnet":{input:3,output:15},"claude-opus":{input:15,output:75},"claude-haiku":{input:.25,output:1.25}};function bt(r){let e=r.toLowerCase();return e.includes("opus")?"claude-opus":e.includes("haiku")?"claude-haiku":"claude-sonnet"}var le=class{steps=[];models=new Map;recordStep(e,t,o,n){let s=bt(t),i=Ve[s]||Ve["claude-sonnet"],c=o/1e6*i.input+n/1e6*i.output;this.steps.push({step:e,model:t,inputTokens:o,outputTokens:n,cost:c,timestamp:Date.now()});let a=this.models.get(t)||{inputTokens:0,outputTokens:0,cost:0,steps:0};a.inputTokens+=o,a.outputTokens+=n,a.cost+=c,a.steps++,this.models.set(t,a)}getSummary(){let e=0,t=0,o=0;for(let s of this.steps)e+=s.inputTokens,t+=s.outputTokens,o+=s.cost;let n={};for(let[s,i]of this.models)n[s]={...i};return{totalInputTokens:e,totalOutputTokens:t,totalTokens:e+t,totalCost:o,steps:[...this.steps],models:n}}reset(){this.steps=[],this.models.clear()}},te=new le;function xt(r,e){let t=[];if(t.push(`# Session: ${r.id}`),t.push(""),t.push(`- **Created**: ${r.createdAt}`),t.push(`- **Updated**: ${r.updatedAt}`),t.push(`- **CWD**: ${r.cwd}`),t.push(`- **Messages**: ${r.messages.length}`),t.push(`- **Tokens**: ${r.tokensUsed.toLocaleString()}`),t.push(""),r.filesGenerated.length){t.push("## Files Generated"),t.push("");for(let o of r.filesGenerated)t.push(`- \`${o}\``);t.push("")}if(r.messages.length){t.push("## Conversation"),t.push("");for(let o of r.messages){if(o.role==="system")continue;let n=o.role==="user"?"**User**":"**Assistant**";t.push(`### ${n}`),t.push(""),o.role,t.push(o.content),t.push("")}}if(e){if(t.push("## Cost Summary"),t.push(""),t.push(`- **Total tokens**: ${e.totalTokens.toLocaleString()}`),t.push(` - Input: ${e.totalInputTokens.toLocaleString()}`),t.push(` - Output: ${e.totalOutputTokens.toLocaleString()}`),t.push(`- **Total cost**: $${e.totalCost.toFixed(4)}`),t.push(""),Object.keys(e.models).length){t.push("### Per Model"),t.push(""),t.push("| Model | Input | Output | Cost | Steps |"),t.push("|-------|-------|--------|------|-------|");for(let[o,n]of Object.entries(e.models))t.push(`| ${o} | ${n.inputTokens.toLocaleString()} | ${n.outputTokens.toLocaleString()} | $${n.cost.toFixed(4)} | ${n.steps} |`);t.push("")}if(e.steps.length){t.push("### Per Step"),t.push(""),t.push("| Step | Model | Input | Output | Cost |"),t.push("|------|-------|-------|--------|------|");for(let o of e.steps)t.push(`| ${o.step} | ${o.model} | ${o.inputTokens.toLocaleString()} | ${o.outputTokens.toLocaleString()} | $${o.cost.toFixed(4)} |`);t.push("")}}return t.join(`
|
|
21
|
+
`)}var oe=class{hooks=new Map;register(e,t){if(!t.enabled)return;let o=this.createHandler(t),n={event:e,definition:t,handler:o},s=this.hooks.get(e)||[];s.push(n),s.sort((i,c)=>i.definition.priority-c.definition.priority),this.hooks.set(e,s)}async execute(e,t){let o=this.hooks.get(e);if(!o?.length)return{};let n=Pe.includes(e),s={};for(let i of o){let c=Date.now();try{let a=await i.handler({...t,...s}),p=Date.now()-c;if(a.modified&&(s={...s,...a.modified}),n&&a.blocked)return b.hook(i.definition.name,p,"blocked"),{blocked:!0,message:a.message||`Blocked by hook: ${i.definition.name}`,modified:s};b.hook(i.definition.name,p,"ok")}catch(a){let p=Date.now()-c;if(b.hook(i.definition.name,p,`error: ${a.message}`),R.warn(`Hook "${i.definition.name}" failed: ${a.message}`),n)return{blocked:!0,message:`Hook "${i.definition.name}" errored: ${a.message}`}}}return{modified:Object.keys(s).length?s:void 0}}registerHandler(e,t,o,n=100){let i={event:e,definition:{name:t,type:"script",priority:n,enabled:!0},handler:o},c=this.hooks.get(e)||[];c.push(i),c.sort((a,p)=>a.definition.priority-p.definition.priority),this.hooks.set(e,c)}has(e){return!!this.hooks.get(e)?.length}clear(){this.hooks.clear()}size(){let e=0;for(let t of this.hooks.values())e+=t.length;return e}createHandler(e){switch(e.type){case"command":return this.createCommandHandler(e);case"script":return this.createScriptHandler(e);case"prompt":return this.createPromptHandler(e);default:throw new Error(`Unknown hook type: ${e.type}`)}}createCommandHandler(e){return async t=>{if(!e.command)return{};let o=e.command;o=o.replace(/\{\{(\w+)\}\}/g,(s,i)=>String(t[i]??""));let n=await vt("sh",["-c",o],{cwd:t.cwd||process.cwd(),reject:!1,timeout:6e4,env:process.env});return n.exitCode!==0?{blocked:!0,message:n.stderr||n.stdout||`Command hook "${e.name}" failed`}:{}}}createScriptHandler(e){return async t=>{if(!e.script)return{};let n=await import(e.script.startsWith("/")?e.script:`${t.cwd||process.cwd()}/${e.script}`),s=n.default||n.handler||n;return typeof s=="function"?await s(t):{}}}createPromptHandler(e){return async t=>{if(!e.prompt)return{};let o=e.provider||X()?.provider||"claude-code",n=Ue();if(!n&&o!=="claude-code")return R.warn(`Prompt hook "${e.name}" skipped: no credentials available for provider "${o}"`),{};try{let{createProvider:s}=await import("./providers-L27BJ5A6.js"),i=s(o,n?.token),c=e.prompt;c=c.replace(/\{\{(\w+)\}\}/g,(m,I)=>String(t[I]??""));let a=`You are a hook validator for agentx. Analyze the following context and respond with ONLY a JSON object (no markdown, no code fences).
|
|
22
|
+
|
|
23
|
+
Response format:
|
|
24
|
+
{"action": "allow", "message": "optional explanation"}
|
|
25
|
+
OR
|
|
26
|
+
{"action": "block", "message": "reason for blocking"}
|
|
27
|
+
OR
|
|
28
|
+
{"action": "allow", "message": "optional", "modified": {"key": "new value"}}
|
|
29
|
+
|
|
30
|
+
The "modified" field is optional and can contain updated values to pass forward.`,d=(await i.generate([{role:"system",content:a},{role:"user",content:c}],{model:e.model,maxTokens:1024})).content.trim().match(/\{[\s\S]*\}/);if(!d)return R.warn(`Prompt hook "${e.name}": LLM response was not valid JSON, allowing`),{};let u=JSON.parse(d[0]);return u.action==="block"?{blocked:!0,message:u.message||`Blocked by prompt hook: ${e.name}`}:u.modified?{modified:u.modified}:{}}catch(s){return R.warn(`Prompt hook "${e.name}" failed: ${s.message}`),{}}}}};import{existsSync as Ye,readFileSync as _t,readdirSync as Tt}from"fs";import pe from"path";function St(r,e){Pt(r,e),Ct(r,e)}function Pt(r,e){let t=pe.join(r,"agentx.config.json");if(Ye(t))try{let o=JSON.parse(_t(t,"utf8"));if(!o.hooks)return;for(let[n,s]of Object.entries(o.hooks)){if(!ee.includes(n)){R.warn(`Unknown hook event in config: ${n}`);continue}let i=n;if(Array.isArray(s))for(let c of s)try{let a=Qe.parse(c);e.register(i,a)}catch(a){R.warn(`Invalid hook definition for ${i}: ${a.message}`)}}}catch(o){R.warn(`Failed to load hooks from config: ${o.message}`)}}function Ct(r,e){let t=pe.join(r,".agentx","hooks");if(Ye(t))try{let o=Tt(t).filter(n=>n.endsWith(".ts")||n.endsWith(".js")||n.endsWith(".mjs"));for(let n of o){let s=n.replace(/\.(ts|js|mjs)$/,"").split(".");if(s.length<2){R.warn(`Hook file "${n}" should be named <event>.<name>.<ext>`);continue}let i=s[0],c=s.slice(1).join("."),a=i.replace(/-/g,":");if(!ee.includes(a)){let p=i.replace("-",":");if(!ee.includes(p)){R.warn(`Unknown hook event in filename: ${n}`);continue}e.register(p,{name:c,type:"script",script:pe.join(t,n),priority:100,enabled:!0});continue}e.register(a,{name:c,type:"script",script:pe.join(t,n),priority:100,enabled:!0})}}catch(o){R.warn(`Failed to load hooks from directory: ${o.message}`)}}var f=new oe;import Rt from"prompts";import $t from"chalk";import{z as q}from"zod";var Xe=["default","acceptEdits","plan","yolo"],Ze=q.enum(Xe),Ce=q.object({mode:Ze.default("default"),allow:q.array(q.string()).default([]),deny:q.array(q.string()).default([]),confirm:q.array(q.string()).default([])});function Mt(r,e){let t=e.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\{\{GLOBSTAR\}\}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${t}$`).test(r)}var de=class{mode;allowPatterns;denyPatterns;confirmPatterns;autoAllowAll=!1;constructor(e){let t=Ce.parse(e||{});this.mode=t.mode,this.allowPatterns=t.allow,this.denyPatterns=t.deny,this.confirmPatterns=t.confirm}getMode(){return this.mode}setMode(e){this.mode=e,this.autoAllowAll=!1,b.context("permissions",`mode set to ${e}`)}async checkFileWrite(e){if(b.context("permissions",`checking write: ${e} (mode: ${this.mode})`),this.matchesAny(e,this.denyPatterns))return b.context("permissions",`denied by pattern: ${e}`),"deny";switch(this.mode){case"yolo":return"allow";case"plan":return"skip";case"acceptEdits":return"allow";case"default":return this.autoAllowAll||this.matchesAny(e,this.allowPatterns)?"allow":this.promptUser(e);default:return"allow"}}async checkCommand(e){return this.mode==="yolo"?"allow":this.mode==="plan"?"deny":"allow"}matchesAny(e,t){return t.some(o=>Mt(e,o))}async promptUser(e){let{action:t}=await Rt({type:"select",name:"action",message:`Write file ${$t.cyan(e)}?`,choices:[{title:"Yes",value:"allow"},{title:"No",value:"deny"},{title:"All (allow remaining)",value:"all"},{title:"Skip",value:"skip"}],initial:0});return t==="all"?(this.autoAllowAll=!0,"allow"):t||"deny"}},W=new de;async function me(r,e){let t={written:[],skipped:[],errors:[]};for(let o of r){let n=ue.isAbsolute(o.path)?o.path:ue.resolve(e.cwd,e.outputDir||"",o.path);try{let s=o.content;if(f.has("pre:file-write")){let p=await f.execute("pre:file-write",{event:"pre:file-write",file:n,fileContent:s,cwd:e.cwd});if(p.blocked){t.skipped.push(n);continue}p.modified?.fileContent&&(s=String(p.modified.fileContent))}let i=ue.relative(e.cwd,n),c=await W.checkFileWrite(i);if(c==="deny"){t.skipped.push(n);continue}if(c==="skip"){t.written.push(n);continue}if(Ot(n)&&!e.overwrite){t.skipped.push(n);continue}if(e.dryRun){t.written.push(n);continue}let a=ue.dirname(n);await et.mkdir(a,{recursive:!0}),await et.writeFile(n,s,"utf8"),t.written.push(n),f.has("post:file-write")&&await f.execute("post:file-write",{event:"post:file-write",file:n,fileContent:s,cwd:e.cwd})}catch(s){t.errors.push(`${n}: ${s.message}`)}}return t}function fe(r,e,t){if(t)return t;let o=Ke[r];if(!o)return"generated";let n=o.baseDir;return r==="component"&&(e.srcDir?n=`${e.srcDir}/components`:n="components"),r==="page"&&e.frameworks.find(i=>i.name==="nextjs")&&e.srcDir&&(n=`${e.srcDir}/app`),r==="api"&&e.frameworks.find(i=>i.name==="nextjs")&&(n=e.srcDir?`${e.srcDir}/app/api`:"app/api"),r==="test"&&(e.testing.includes("vitest")||e.testing.includes("jest"))&&(n=e.srcDir||"src"),r==="workflow"&&(n=".github/workflows"),r==="schema"&&(e.databases.includes("prisma")?n="prisma":e.srcDir&&(n=`${e.srcDir}/schemas`)),r==="email"&&(n=e.srcDir?`${e.srcDir}/emails`:"emails"),n}import Et from"os";var At=Et.homedir(),ne=class{constructor(e){this.cwd=e;this.userMemory=new ve(At),this.projectMemory=new ve(e)}userMemory;projectMemory;async load(){await Promise.all([this.userMemory.load(),this.projectMemory.load()])}async save(){await Promise.all([this.userMemory.save(),this.projectMemory.save()])}buildMemoryContext(e){let t=this.userMemory.buildMemoryContext(e),o=this.projectMemory.buildMemoryContext(e);if(!t&&!o)return"";let n=[];return o&&n.push(o),t&&n.push(t.replace("# Memory (learned from past interactions)","# Global Memory (cross-project patterns)")),n.join(`
|
|
31
|
+
|
|
32
|
+
`)}async learnPreference(e,t,o){await this.userMemory.learnPreference(e,t,o)}async recordGeneration(e){return this.projectMemory.recordGeneration(e)}getPreferences(){let e=this.userMemory.getPreferences(),t=this.projectMemory.getPreferences(),o=new Map;for(let n of e)o.set(n.key,n);for(let n of t)o.set(n.key,n);return Array.from(o.values())}getPatterns(){let e=this.userMemory.getPatterns();return[...this.projectMemory.getPatterns(),...e]}getStats(){return{user:this.userMemory.getStats(),project:this.projectMemory.getStats()}}getRecentGenerations(e=10){return this.projectMemory.getRecentGenerations(e)}};import{existsSync as tt,readFileSync as ot}from"fs";import nt from"path";function rt(r,e){return r.replace(/@([\w./-]+)/g,(t,o)=>{let n=nt.resolve(e,o);if(tt(n))try{return ot(n,"utf8")}catch{return t}return t})}function $e(r){let e=["SHADXN.md","CLAUDE.md"];for(let t of e){let o=nt.join(r,t);if(tt(o))try{let n=ot(o,"utf8");return n=rt(n,r),n}catch{}}return""}function jt(r){return Math.ceil(r.length/4)}var Re=class{sections=[];addSection(e,t,o=50){t.trim()&&this.sections.push({label:e,content:t,priority:o})}buildContext(e,t=12e3){if(this.sections.length===0)return"";let o=this.sections.map(l=>l.content),n=_e(o),s=Te(e,n),i=new Map(s.map(l=>[l.docIndex,l.score])),c=this.sections.map((l,d)=>({...l,relevance:i.get(d)??0,tokens:jt(l.content)}));c.sort((l,d)=>d.priority+d.relevance*100-(l.priority+l.relevance*100));let a=[],p=0;for(let l of c)p+l.tokens>t&&a.length>0||(a.push(l),p+=l.tokens);return a.map(l=>l.content).join(`
|
|
33
|
+
|
|
34
|
+
`)}};import{promises as re}from"fs";import ge from"path";import{execa as Nt}from"execa";import ct from"fast-glob";var It=["list_projects","get_project","create_task","update_task","add_deliverable","list_attachments","get_credit_balance"],st=[{name:"list_projects",description:"List the noqta.tn user's active projects with per-project task counts. Use when the user asks 'what am I working on' or wants a project overview.",input_schema:{type:"object",properties:{},additionalProperties:!1},permission:"none"},{name:"get_project",description:"Get a single project with its tasks and recent conversations. Use after list_projects when the user picks one.",input_schema:{type:"object",properties:{project_id:{type:"string",description:"Project UUID from list_projects."}},required:["project_id"],additionalProperties:!1},permission:"none"},{name:"create_task",description:"Queue a new task for the user. Use when they ask you to build, fix, or work on something. CONFIRM the summary verbally first.",input_schema:{type:"object",properties:{summary:{type:"string",description:"Short task description (one sentence)."},project_id:{type:"string",description:"Optional \u2014 bind to a project."},conversation_id:{type:"string",description:"Optional \u2014 bind to the on-site conversation id (from [Context])."}},required:["summary"],additionalProperties:!1},permission:"none"},{name:"update_task",description:"Update a task's state (mark completed, cancel, record hours, write a result_summary). Status: queued|active|completed|cancelled.",input_schema:{type:"object",properties:{task_id:{type:"string"},status:{type:"string",enum:["queued","active","completed","cancelled"]},summary:{type:"string"},result_summary:{type:"string"},hours_spent:{type:"number"}},required:["task_id"],additionalProperties:!1},permission:"none"},{name:"add_deliverable",description:"Record a shipped artefact against a task (repo URL, preview URL, design file, document, etc.). type: repo|preview|design|artifact|document|screenshot|figma|spreadsheet|presentation|video|audio|image|other.",input_schema:{type:"object",properties:{task_id:{type:"string"},type:{type:"string",enum:["repo","preview","design","artifact","document","screenshot","figma","spreadsheet","presentation","video","audio","image","other"]},label:{type:"string",description:"Human label, e.g. 'Staging \u2014 workspace v2'."},url:{type:"string",description:"Public URL of the artefact."},file_size:{type:"number"}},required:["task_id","type","label","url"],additionalProperties:!1},permission:"none"},{name:"list_attachments",description:"List files the user has uploaded to the workspace. Filter by project_id and/or task_id.",input_schema:{type:"object",properties:{project_id:{type:"string"},task_id:{type:"string"}},additionalProperties:!1},permission:"none"},{name:"get_credit_balance",description:"Get the user's live credit balance and 7-day burn rate. Use when the user asks 'how much do I have left' or before starting a big task.",input_schema:{type:"object",properties:{},additionalProperties:!1},permission:"none"}];async function it(r,e,t){let o=process.env.NOQTA_AGENT_TOOLS_SECRET||process.env.AGENTX_TOOLS_SECRET||process.env.TELEGRAM_BOT_API_SECRET;if(!o)return{content:JSON.stringify({ok:!1,error:"NOQTA_AGENT_TOOLS_SECRET not set on this host"}),is_error:!0};let s=`${(t.apiUrl||process.env.NOQTA_API_URL||"https://noqta.tn").replace(/\/$/,"")}/api/agent/tools`,i={tool:r,user_id:t.userId,...e||{}},c=Number(process.env.NOQTA_TOOL_TIMEOUT_MS||3e4),a=new AbortController,p=setTimeout(()=>a.abort(),c);try{let l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,"X-Agent-Id":t.agentId||"noqta-public"},body:JSON.stringify(i),signal:a.signal}),d=await l.text(),u=4*1024,m=d.length>u?d.slice(0,u)+"\u2026(truncated)":d;return l.ok?{content:m,is_error:!1}:{content:m,is_error:!0}}catch(l){let d=l?.name==="AbortError";return{content:JSON.stringify({ok:!1,error:d?`noqta tool RPC timed out after ${c}ms`:"noqta tool RPC failed",detail:l?.message||"unknown"}),is_error:!0}}finally{clearTimeout(p)}}function at(r){return It.includes(r)}var se=class{cwd;options;constructor(e,t={}){this.cwd=e,this.options=t}async execute(e){if(b.context("tool-executor",`executing: ${e.name}`),this.options.abortSignal?.aborted)return{tool_use_id:e.id,content:"Task cancelled before tool dispatch.",is_error:!0};if(f.has("pre:tool-call")){let o=await f.execute("pre:tool-call",{event:"pre:tool-call",toolName:e.name,toolInput:e.input,cwd:this.cwd});if(o.blocked)return{tool_use_id:e.id,content:o.message||`Tool ${e.name} blocked by pre:tool-call hook`,is_error:!0}}let t;try{if(this.options.noqtaContext&&at(e.name)){let o=await it(e.name,e.input,this.options.noqtaContext);t={tool_use_id:e.id,content:o.content,is_error:o.is_error}}else switch(e.name){case"read_file":t=await this.readFile(e);break;case"search_files":t=await this.searchFiles(e);break;case"list_directory":t=await this.listDirectory(e);break;case"run_command":t=await this.runCommand(e);break;case"edit_file":t=await this.editFile(e);break;case"create_files":t=await this.createFiles(e);break;case"ask_user":t=await this.askUser(e);break;case"spawn_agent":t=await this.spawnAgent(e);break;default:t={tool_use_id:e.id,content:`Unknown tool: ${e.name}`,is_error:!0}}}catch(o){t={tool_use_id:e.id,content:`Error executing ${e.name}: ${o.message}`,is_error:!0}}return f.has("post:tool-call")&&await f.execute("post:tool-call",{event:"post:tool-call",toolName:e.name,toolInput:e.input,toolResult:t.content,cwd:this.cwd}),t}async readFile(e){let t=String(e.input.path||""),o=Number(e.input.max_lines)||500,n=ge.resolve(this.cwd,t),s=await re.readFile(n,"utf8"),i=s.split(`
|
|
35
|
+
`),a=i.length>o?i.slice(0,o).join(`
|
|
36
|
+
`)+`
|
|
37
|
+
|
|
38
|
+
... (truncated, ${i.length-o} more lines)`:s;return{tool_use_id:e.id,content:a}}async searchFiles(e){let t=String(e.input.pattern||"**/*"),o=e.input.content_regex?String(e.input.content_regex):void 0,n=Number(e.input.max_results)||50,s=await ct(t,{cwd:this.cwd,ignore:["node_modules/**",".git/**","dist/**",".next/**"],dot:!1});if(!o){let a=s.slice(0,n);return{tool_use_id:e.id,content:a.length?a.join(`
|
|
39
|
+
`)+(s.length>n?`
|
|
40
|
+
|
|
41
|
+
... (${s.length-n} more files)`:""):"No files matched the pattern."}}let i=new RegExp(o,"gm"),c=[];for(let a of s){if(c.length>=n)break;try{let l=(await re.readFile(ge.resolve(this.cwd,a),"utf8")).split(`
|
|
42
|
+
`);for(let d=0;d<l.length&&!(c.length>=n);d++)i.test(l[d])&&c.push(`${a}:${d+1}: ${l[d]}`),i.lastIndex=0}catch{}}return{tool_use_id:e.id,content:c.length?c.join(`
|
|
43
|
+
`):"No matches found."}}async listDirectory(e){let t=String(e.input.path||"."),o=!!e.input.recursive,n=Number(e.input.max_depth)||3,s=ge.resolve(this.cwd,t);if(o){let p=await ct("**/*",{cwd:s,onlyFiles:!1,markDirectories:!0,deep:n,ignore:["node_modules/**",".git/**","dist/**",".next/**"]});return{tool_use_id:e.id,content:p.length?p.join(`
|
|
44
|
+
`):"Empty directory."}}let c=(await re.readdir(s,{withFileTypes:!0})).map(a=>a.isDirectory()?`${a.name}/`:a.name);return{tool_use_id:e.id,content:c.length?c.join(`
|
|
45
|
+
`):"Empty directory."}}async runCommand(e){let t=String(e.input.command||""),o=Number(e.input.timeout)||3e4;if(await W.checkCommand(t)==="deny")return{tool_use_id:e.id,content:`Command blocked by permissions (mode: ${W.getMode()}): ${t}`,is_error:!0};if(f.has("pre:command")){let a=await f.execute("pre:command",{event:"pre:command",command:t,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`Command blocked by pre:command hook: ${t}`,is_error:!0}}let s=await Nt("sh",["-c",t],{cwd:this.cwd,timeout:o,reject:!1,stdin:"ignore",signal:this.options.abortSignal}),i=[s.stdout,s.stderr].filter(Boolean).join(`
|
|
46
|
+
`),c=i.length>1e4?i.slice(0,1e4)+`
|
|
47
|
+
|
|
48
|
+
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
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
|
+
${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-WV7QKQ3L.js"),{getGlobalRegistry:i}=await import("./registry-T36ZIAWV.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
|
+
|
|
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
|
+
Options: ${o.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:n}}};async function Me(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 lt(r);let I=new se(s,{interactive:a,overwrite:p,dryRun:l,noqtaContext:r.noqtaContext,abortSignal:u}),H=we(c);if(r.noqtaContext)for(let g of st)H.push({name:g.name,description:g.description,input_schema:g.input_schema});let O=new Set;if(r.mcpTools?.length)for(let g of r.mcpTools)H.push({name:g.name,description:g.description,input_schema:g.input_schema}),O.add(g.name);let P=o.filter(g=>g.role!=="system").map(g=>({role:g.role,content:g.content})),B=[],G=0,F=0,E=0,A="",j,_=0;for(;_<i;){if(_++,u?.aborted)throw new Error("cancelled");d?.({type:"iteration_start",iteration:_}),b.step(_,`Agentic loop iteration (${H.length} tools available)`);let g,$=!!e.generateRawStream&&!!d;try{if($){let S=null,N=null,v="";for await(let x of e.generateRawStream(P,t,H,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"?S=x.result:x.type==="error"&&(N=x.error);if(N&&!S)throw new Error(N);if(!S)throw new Error("generateRawStream returned no raw_result event");g=S,g._streamedText=v}else g=await e.generateRaw(P,t,H,m)}catch(S){if(S.message?.includes("not available"))return lt(r);throw S}G+=g.usage.input_tokens+g.usage.output_tokens,F+=g.usage.input_tokens,E+=g.usage.output_tokens;let C=g._streamedText;for(let S of g.content)S.type==="text"&&(A+=S.text,C===void 0&&d?.({type:"text_delta",text:S.text}));if(C!==void 0&&delete g._streamedText,g.stop_reason==="end_turn"||g.stop_reason==="max_tokens")break;if(g.stop_reason==="tool_use"){let S=g.content.filter(v=>v.type==="tool_use");if(S.length===0)break;P.push({role:"assistant",content:g.content});let N=[];for(let v of S){d?.({type:"tool_call",name:v.name,id:v.id,input:v.input}),b.step(_,`Tool call: ${v.name}`);let x;if(O.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),N.push({type:"tool_result",tool_use_id:x.tool_use_id,content:x.content,is_error:x.is_error})}if(P.push({role:"user",content:N}),j)break;continue}break}return d?.({type:"complete",iterations:_,totalTokens:G}),{files:B,content:A,followUp:j,tokensUsed:G,inputTokens:F||void 0,outputTokens:E||void 0,iterations:_}}async function lt(r){let{provider:e,systemPrompt:t,messages:o,providerOptions:n,maxIterations:s=5}=r,c=[{role:"system",content:t+`
|
|
55
|
+
|
|
56
|
+
`+ke()},...o.filter(m=>m.role!=="system")],a=[],p=0,l="",d,u=0;for(;u<s;){u++,b.step(u,`Legacy loop step (model: ${n.model||"default"})`);let m=await e.generate(c,n);if(p+=m.tokensUsed||0,l=m.content,m.files.length&&a.push(...m.files),m.followUp){d=m.followUp;break}if(m.files.length===0&&u>1||!(m.content.includes("[CONTINUE]")||m.content.includes("Next, I'll")||m.content.includes("Now let me")||m.content.includes("I'll also generate")))break;let H=m.files.map(O=>`Created: ${O.path}${O.description?` \u2014 ${O.description}`:""}`).join(`
|
|
57
|
+
`);c.push({role:"assistant",content:m.content+(H?`
|
|
58
|
+
|
|
59
|
+
Files created:
|
|
60
|
+
${H}`:"")}),c.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}return{files:a,content:l,followUp:d,tokensUsed:p,iterations:u}}function Oe(r){return typeof r.generateRaw=="function"}import{spawn as Ut}from"child_process";var Ht="2024-11-05",pt=15e3,Dt=12e4,Gt="mcp__";function Ft(r){return r.type==="http"}var Ee=class{constructor(e,t){this.name=e;this.proc=Ut(t.command,t.args??[],{stdio:["pipe","pipe","pipe"],env:{...process.env,...t.env??{}}}),this.proc.stdout.setEncoding("utf-8"),this.proc.stdout.on("data",o=>this.onData(o)),this.proc.stderr.setEncoding("utf-8"),this.proc.stderr.on("data",o=>b.context("mcp",`${e} stderr: ${o.trimEnd()}`)),this.proc.on("exit",o=>{this.closed=!0,b.context("mcp",`${e}: exited (code=${o})`);for(let[,n]of this.pending)clearTimeout(n.timer),n.reject(new Error(`mcp server "${e}" exited`));this.pending.clear()}),this.proc.on("error",o=>{b.context("mcp",`${e}: spawn error: ${o.message}`)})}proc;buffer="";nextId=1;pending=new Map;closed=!1;request(e,t,o){if(this.closed)return Promise.reject(new Error(`mcp server "${this.name}" is closed`));let n=this.nextId++,s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t})+`
|
|
61
|
+
`;return new Promise((i,c)=>{let a=setTimeout(()=>{this.pending.delete(n),c(new Error(`mcp "${this.name}" ${e} timeout after ${o}ms`))},o);this.pending.set(n,{resolve:i,reject:c,timer:a});try{this.proc.stdin.write(s)}catch(p){clearTimeout(a),this.pending.delete(n),c(new Error(`mcp "${this.name}" write failed: ${p.message}`))}})}notify(e,t){if(this.closed)return;let o=JSON.stringify({jsonrpc:"2.0",method:e,params:t??{}})+`
|
|
62
|
+
`;try{this.proc.stdin.write(o)}catch{}}close(){if(!this.closed){this.closed=!0;try{this.proc.kill("SIGTERM")}catch{}}}onData(e){for(this.buffer+=e;;){let t=this.buffer.indexOf(`
|
|
63
|
+
`);if(t<0)break;let o=this.buffer.slice(0,t).trim();if(this.buffer=this.buffer.slice(t+1),!o)continue;let n;try{n=JSON.parse(o)}catch(s){b.context("mcp",`${this.name}: parse error: ${s.message} (line: ${o.slice(0,200)})`);continue}if(typeof n.id=="number"&&this.pending.has(n.id)){let s=this.pending.get(n.id);this.pending.delete(n.id),clearTimeout(s.timer),n.error?s.reject(new Error(`${n.error.code}: ${n.error.message}`)):s.resolve(n.result)}}}},Ae=class{constructor(e,t){this.name=e;this.spec=t}nextId=1;sessionId=null;closed=!1;async request(e,t,o){if(this.closed)throw new Error(`mcp server "${this.name}" is closed`);let n=this.nextId++,s=JSON.stringify({jsonrpc:"2.0",id:n,method:e,params:t}),i={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.spec.headers??{}};this.sessionId&&(i["Mcp-Session-Id"]=this.sessionId);let c=new AbortController,a=setTimeout(()=>c.abort(new Error(`timeout after ${o}ms`)),o);a.unref?.();let p;try{p=await fetch(this.spec.url,{method:"POST",headers:i,body:s,signal:c.signal})}catch(m){throw clearTimeout(a),m?.name==="AbortError"?new Error(`mcp "${this.name}" ${e} timeout after ${o}ms`):new Error(`mcp "${this.name}" ${e} fetch failed: ${m?.message??m}`)}let l=p.headers.get("mcp-session-id");if(l&&(this.sessionId=l),!p.ok){clearTimeout(a);let m=await p.text().catch(()=>"");throw new Error(`mcp "${this.name}" HTTP ${p.status}: ${m.slice(0,300)}`)}let d=(p.headers.get("content-type")||"").toLowerCase(),u;try{d.includes("text/event-stream")?u=await Lt(p,n):u=await p.json()}catch(m){throw clearTimeout(a),new Error(`mcp "${this.name}" ${e} response parse failed: ${m?.message??m}`)}finally{clearTimeout(a)}if(!u||typeof u!="object")throw new Error(`mcp "${this.name}" ${e} returned non-object body`);if(u.error)throw new Error(`${u.error.code}: ${u.error.message}`);return u.result}notify(e,t){if(this.closed)return;let o={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.spec.headers??{}};this.sessionId&&(o["Mcp-Session-Id"]=this.sessionId),fetch(this.spec.url,{method:"POST",headers:o,body:JSON.stringify({jsonrpc:"2.0",method:e,params:t??{}})}).catch(n=>{b.context("mcp",`${this.name}: notify ${e} failed: ${n?.message??n}`)})}close(){if(!this.closed&&(this.closed=!0,this.sessionId)){let e={"Mcp-Session-Id":this.sessionId,...this.spec.headers??{}};fetch(this.spec.url,{method:"DELETE",headers:e}).catch(()=>{})}}};async function Lt(r,e){let t=r.body?.getReader();if(!t)throw new Error("SSE response had no body");let o=new TextDecoder,n="";try{for(;;){let{done:s,value:i}=await t.read();if(s)break;n+=o.decode(i,{stream:!0});let c;for(;(c=n.indexOf(`
|
|
64
|
+
|
|
65
|
+
`))>=0;){let a=n.slice(0,c);n=n.slice(c+2);let p=[];for(let u of a.split(`
|
|
66
|
+
`)){let m=u.replace(/\r$/,"");m.startsWith("data:")&&p.push(m.slice(5).trim())}if(!p.length)continue;let l=p.join(`
|
|
67
|
+
`);if(!l||l==="[DONE]")continue;let d;try{d=JSON.parse(l)}catch{continue}if(d&&d.id===e)return d}}}finally{try{t.cancel().catch(()=>{})}catch{}}throw new Error(`SSE stream ended without a response for id=${e}`)}var je=class{constructor(e,t){this.name=e;this.transport=Ft(t)?new Ae(e,t):new Ee(e,t)}transport;async initialize(){await this.transport.request("initialize",{protocolVersion:Ht,capabilities:{},clientInfo:{name:"agentx-orchestrator",version:"0.1.0"}},pt),this.transport.notify("notifications/initialized")}async listTools(){return((await this.transport.request("tools/list",{},pt)).tools??[]).map(t=>({name:t.name,description:t.description??"",input_schema:t.inputSchema??{type:"object",properties:{}}}))}async callTool(e,t){let o=await this.transport.request("tools/call",{name:e,arguments:t??{}},Dt),n=[];for(let s of o.content??[])s?.type==="text"&&typeof s.text=="string"?n.push(s.text):n.push(JSON.stringify(s));return{content:n.join(`
|
|
68
|
+
`)||"(no output)",isError:o.isError}}close(){this.transport.close()}};async function Ie(r){let e=new Map,t=[],o=new Map;for(let[n,s]of Object.entries(r)){let i=new je(n,s);try{await i.initialize();let c=await i.listTools();for(let a of c){let p=`${Gt}${n}__${a.name}`;t.push({name:p,description:a.description||`${n}.${a.name}`,input_schema:a.input_schema}),o.set(p,{client:i,remote:a.name})}e.set(n,i)}catch(c){b.context("mcp",`${n}: skipped \u2014 ${c.message}`),i.close()}}return{tools:t,async dispatch(n,s){let i=o.get(n);if(!i)return{content:`Unknown MCP tool: ${n}`,isError:!0};try{return await i.client.callTool(i.remote,s)}catch(c){return{content:`MCP call failed: ${c.message}`,isError:!0}}},close(){for(let n of e.values())n.close()}}}var he=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function dt(r,e,t){let o=Fe.parse(t||{}),n=new ne(r);await n.load();let[s,i,c]=await Promise.all([He(r),qe(r),Ge(r)]),a="";if(o.context7.enabled)try{a=await Je(s,e,o.context7.apiKey)}catch{}let p=n.buildMemoryContext(e),l=$e(r);return b.context("memory",p?"loaded":"empty"),b.context("instructions",l?"loaded from project":"none"),{techStack:s,schemas:i,skills:c,docs:a,config:o,memoryContext:p,projectInstructions:l}}async function Qn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let h=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:prompt hook");h.modified?.task&&(l=String(h.modified.task))}if(f.has("pre:generate")){let h=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by pre:generate hook")}R.info("Analyzing project...");let d=await dt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Se(r.outputType,l);R.info(`Output type: ${u}`);let m=xe(d.skills,l,u);m.length&&R.info(`Loaded ${m.length} relevant skill(s): ${m.map(h=>h.skill.frontmatter.name).join(", ")}`);let I=ut(d,u,m.map(h=>h.skill));if(!await ye(c))throw new Error("No credentials configured. Run `agentx model` to set up.");let O=be(s,c,r.providerOpts||{}),P=i||X()?.model,B=[...r.sessionMessages||[],{role:"user",content:l}];R.info("Generating...");let G=Oe(O),F=r.maxSteps??(G?20:5),E=r.mcpServers&&Object.keys(r.mcpServers).length>0?await Ie(r.mcpServers):void 0,A;try{A=await Me({provider:O,systemPrompt:I,messages:[{role:"system",content:I},...B],providerOptions:{model:P,maxTokens:8192},cwd:t,maxIterations:F,enabledTools:d.config.agentic.enabledTools.filter(h=>!d.config.agentic.disabledTools.includes(h)),interactive:p,overwrite:o,dryRun:n,noqtaContext:r.noqtaContext,abortSignal:r.abortSignal,mcpTools:E?.tools,mcpDispatch:E?E.dispatch.bind(E):void 0,onProgress:h=>{h.type==="iteration_start"&&h.iteration>1&&R.info(`Step ${h.iteration}/${F}...`),h.type==="tool_call"&&b.step(0,`Tool: ${h.name}`)}})}finally{E?.close()}if(A.tokensUsed){let h=P||"claude-sonnet-4-20250514",Q=Math.round(A.tokensUsed*.3),V=A.tokensUsed-Q;te.recordStep(1,h,Q,V)}let{content:j}=A,{followUp:_,tokensUsed:g,inputTokens:$,outputTokens:C}=A;if(A.iterations>1&&R.info(`Completed in ${A.iterations} step(s)`),f.has("post:response")){let h=await f.execute("post:response",{event:"post:response",content:j,task:l,cwd:t});if(h.blocked)throw new Error(h.message||"Blocked by post:response hook");h.modified?.content&&(j=String(h.modified.content))}if(_&&p)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:u,followUp:_,tokensUsed:g,inputTokens:$,outputTokens:C};let S=new Map;for(let h of A.files)S.set(h.path,h);let N=fe(u,d.techStack,r.outputDir),v=await me(Array.from(S.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:N}),x;if(r.heal!==!1&&!n&&v.written.length>0){let{HealEngine:h}=await import("./heal-HZ3EQD52.js");x=await new h(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:P,apiKey:c}).detectAndHeal(v.written,l),!x.healed&&x.error&&await f.execute("on:error",{event:"on:error",error:new Error(x.error),task:l,cwd:t})}return f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:j,cwd:t}),{files:v,content:j,outputType:u,tokensUsed:g,inputTokens:$,outputTokens:C,healResult:x}}async function*Vn(r){let{task:e,cwd:t,overwrite:o=!1,dryRun:n=!1,provider:s="claude-code",model:i,apiKey:c,context7:a=!0,interactive:p=!0}=r,l=e;if(f.has("pre:prompt")){let y=await f.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:prompt hook"};return}y.modified?.task&&(l=String(y.modified.task))}if(f.has("pre:generate")){let y=await f.execute("pre:generate",{event:"pre:generate",task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by pre:generate hook"};return}}let d=await dt(t,l,{provider:s,context7:{enabled:a,apiKey:c}}),u=Se(r.outputType,l);yield{type:"context_ready",outputType:u};let m=xe(d.skills,l,u),I=ut(d,u,m.map(y=>y.skill));if(!await ye(c)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let O=be(s,c,r.providerOpts||{}),P=i||X()?.model,B=Oe(O),G=r.maxSteps??(B?20:5),F=[...r.sessionMessages||[],{role:"user",content:l}];if(B){let y=new he,T,k,U;if(r.mcpServers&&Object.keys(r.mcpServers).length>0)try{U=await Ie(r.mcpServers)}catch(w){yield{type:"error",error:`MCP pool startup failed: ${w.message}`};return}let ie=(async()=>{try{T=await Me({provider:O,systemPrompt:I,messages:[{role:"system",content:I},...F],providerOptions:{model:P,maxTokens:8192},cwd:t,maxIterations:G,abortSignal:r.abortSignal,enabledTools:d.config.agentic.enabledTools.filter(w=>!d.config.agentic.disabledTools.includes(w)),interactive:p,overwrite:o,dryRun:n,noqtaContext:r.noqtaContext,mcpTools:U?.tools,mcpDispatch:U?U.dispatch.bind(U):void 0,onProgress:w=>{w.type==="text_delta"&&y.push({type:"text_delta",text:w.text}),w.type==="thinking_delta"&&y.push({type:"thinking_delta",text:w.text}),w.type==="iteration_start"&&y.push({type:"iteration",iteration:w.iteration}),w.type==="tool_call"&&y.push({type:"tool_call",name:w.name,id:w.id}),w.type==="tool_result"&&y.push({type:"tool_result",name:w.name,id:w.id,is_error:w.is_error}),w.type==="files_created"&&y.push({type:"step_complete",step:0,filesCount:w.files.length})}})}catch(w){k=w}finally{U?.close(),y.close()}})();for await(let w of y)yield w;if(await ie,k){yield{type:"error",error:k instanceof Error?k.message:String(k)};return}if(!T){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:T.content,files:T.files,tokensUsed:T.tokensUsed,followUp:T.followUp}};let{content:L}=T;if(f.has("post:response")){let w=await f.execute("post:response",{event:"post:response",content:L,task:l,cwd:t});if(w.blocked){yield{type:"error",error:w.message||"Blocked by post:response hook"};return}w.modified?.content&&(L=String(w.modified.content))}if(T.followUp&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:L,outputType:u,followUp:T.followUp,tokensUsed:T.tokensUsed,inputTokens:T.inputTokens,outputTokens:T.outputTokens}};return}let ae=new Map;for(let w of T.files)ae.set(w.path,w);let Ne=fe(u,d.techStack,r.outputDir),z=await me(Array.from(ae.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:Ne}),J;if(r.heal!==!1&&!n&&z.written.length>0){let{HealEngine:w}=await import("./heal-HZ3EQD52.js");J=await new w(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:P,apiKey:c}).detectAndHeal(z.written,l)}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:L,cwd:t}),yield{type:"generate_result",result:{files:z,content:L,outputType:u,tokensUsed:T.tokensUsed,inputTokens:T.inputTokens,outputTokens:T.outputTokens,healResult:J}};return}let E=[{role:"system",content:I},...F],A=[],j=0,_="",g,$=0;$++,b.step($,`Starting generation (model: ${P||"default"})`);let C;if(O.stream){let y="",T;for await(let k of O.stream(E,{model:P,maxTokens:8192}))yield k,k.type==="text_delta"&&(y+=k.text),k.type==="done"&&(T=k.result);C=T||{content:y,files:[],tokensUsed:0}}else{let y=await O.generate(E,{model:P,maxTokens:8192});y.content&&(yield{type:"text_delta",text:y.content}),yield{type:"done",result:y},C=y}j+=C.tokensUsed||0,_=C.content;let S=C.tokensUsed||0,N=P||"claude-sonnet-4-20250514",v=Math.round(S*.3),x=S-v;if(te.recordStep($,N,v,x),b.api("generate",N,S),b.step($,`Generated ${C.files.length} file(s), ${S} tokens`),C.files.length&&A.push(...C.files),C.followUp&&(g=C.followUp),yield{type:"step_complete",step:$,filesCount:C.files.length},!g&&(_.includes("[CONTINUE]")||_.includes("Next, I'll")||_.includes("Now let me")||_.includes("I'll also generate"))&&C.files.length>0){let T=C.files.map(k=>`Created: ${k.path}${k.description?` \u2014 ${k.description}`:""}`).join(`
|
|
69
|
+
`);for(E.push({role:"assistant",content:_+(T?`
|
|
70
|
+
|
|
71
|
+
Files created:
|
|
72
|
+
${T}`:"")}),E.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."});$<G;){$++,b.step($,`Starting generation (model: ${P||"default"})`);let k=await O.generate(E,{model:P,maxTokens:8192});j+=k.tokensUsed||0,_=k.content;let U=k.tokensUsed||0,ie=P||"claude-sonnet-4-20250514",L=Math.round(U*.3),ae=U-L;if(te.recordStep($,ie,L,ae),b.api("generate",ie,U),b.step($,`Generated ${k.files.length} file(s), ${U} tokens`),k.files.length&&A.push(...k.files),yield{type:"step_complete",step:$,filesCount:k.files.length},k.followUp){g=k.followUp;break}if(k.files.length===0&&$>1||!(k.content.includes("[CONTINUE]")||k.content.includes("Next, I'll")||k.content.includes("Now let me")||k.content.includes("I'll also generate")))break;let z=k.files.map(J=>`Created: ${J.path}${J.description?` \u2014 ${J.description}`:""}`).join(`
|
|
73
|
+
`);E.push({role:"assistant",content:k.content+(z?`
|
|
74
|
+
|
|
75
|
+
Files created:
|
|
76
|
+
${z}`:"")}),E.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(f.has("post:response")){let y=await f.execute("post:response",{event:"post:response",content:_,task:l,cwd:t});if(y.blocked){yield{type:"error",error:y.message||"Blocked by post:response hook"};return}y.modified?.content&&(_=String(y.modified.content))}if(g&&p){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:_,outputType:u,followUp:g,tokensUsed:j}};return}let h=new Map;for(let y of A)h.set(y.path,y);let Q=fe(u,d.techStack,r.outputDir),V=await me(Array.from(h.values()),{cwd:t,overwrite:o,dryRun:n,outputDir:Q}),Y;if(r.heal!==!1&&!n&&V.written.length>0){let{HealEngine:y}=await import("./heal-HZ3EQD52.js");Y=await new y(t,{enabled:!0,testCommand:r.healConfig?.testCommand,buildCommand:r.healConfig?.buildCommand,lintCommand:r.healConfig?.lintCommand,maxAttempts:r.healConfig?.maxAttempts??3,provider:s,model:P,apiKey:c}).detectAndHeal(V.written,l),!Y.healed&&Y.error&&await f.execute("on:error",{event:"on:error",error:new Error(Y.error),task:l,cwd:t})}f.has("post:generate")&&await f.execute("post:generate",{event:"post:generate",task:l,content:_,cwd:t}),yield{type:"generate_result",result:{files:V,content:_,outputType:u,tokensUsed:j,healResult:Y}}}function ut(r,e,t){let o=[];o.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
|
|
77
|
+
|
|
78
|
+
Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
|
|
79
|
+
If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
|
|
80
|
+
|
|
81
|
+
You also have tools to inspect the codebase before generating code:
|
|
82
|
+
- \`read_file\` \u2014 read existing files to understand patterns, styles, and implementations
|
|
83
|
+
- \`search_files\` \u2014 search for files by glob pattern, optionally grep content with regex
|
|
84
|
+
- \`list_directory\` \u2014 explore the project structure
|
|
85
|
+
- \`run_command\` \u2014 run shell commands (build, test, lint, etc.)
|
|
86
|
+
- \`edit_file\` \u2014 apply targeted search/replace edits to existing files
|
|
87
|
+
|
|
88
|
+
AGENTIC WORKFLOW:
|
|
89
|
+
- Before generating code, use \`read_file\` and \`search_files\` to understand the existing codebase
|
|
90
|
+
- Match the project's existing patterns, naming conventions, and code style
|
|
91
|
+
- After creating files, consider running tests or build commands to verify correctness
|
|
92
|
+
- Use \`edit_file\` for small, targeted changes instead of rewriting entire files
|
|
93
|
+
|
|
94
|
+
IMPORTANT RULES:
|
|
95
|
+
- Generate complete, working code \u2014 not stubs or placeholders
|
|
96
|
+
- Follow the project's existing patterns and conventions
|
|
97
|
+
- Use the detected tech stack to choose the right language, framework, and patterns
|
|
98
|
+
- File paths should be relative to the project root
|
|
99
|
+
- Include all necessary imports
|
|
100
|
+
- Do NOT add unnecessary dependencies
|
|
101
|
+
|
|
102
|
+
MULTI-STEP GENERATION:
|
|
103
|
+
For complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:
|
|
104
|
+
- Generate the foundational files first (schemas, types, configs)
|
|
105
|
+
- Include "[CONTINUE]" in your response text when there are more files to generate
|
|
106
|
+
- In subsequent steps, you'll see what was already created \u2014 build on it
|
|
107
|
+
- When all files are generated, do NOT include "[CONTINUE]"
|
|
108
|
+
- This enables you to generate a schema first, then an API that references it, then a UI that calls the API`),o.push(`# Project Tech Stack
|
|
109
|
+
${De(r.techStack)}`);let n=Object.keys(r.techStack.dependencies).slice(0,30);n.length&&o.push(`# Key Dependencies
|
|
110
|
+
${n.join(", ")}`);let s=Be(r.schemas);return s&&o.push(`# Project Schemas
|
|
111
|
+
${s}`),t.length&&o.push(`# Active Skills
|
|
112
|
+
Follow these skill instructions when applicable:
|
|
113
|
+
|
|
114
|
+
`+t.map(i=>`## Skill: ${i.frontmatter.name}
|
|
115
|
+
${i.frontmatter.description}
|
|
116
|
+
|
|
117
|
+
${i.instructions}`).join(`
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
`)),r.docs&&o.push(r.docs),r.projectInstructions&&o.push(`# Project Instructions
|
|
122
|
+
${r.projectInstructions}`),r.memoryContext&&o.push(r.memoryContext),o.push(`# Output Type: ${e}
|
|
123
|
+
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),o.join(`
|
|
124
|
+
|
|
125
|
+
`)}export{Fe as a,Wt as b,zt as c,qe as d,Be as e,Je as f,Ke as g,Se as h,ee as i,Pe as j,le as k,te as l,xt as m,oe as n,St as o,f as p,Xe as q,Ze as r,Ce as s,de as t,W as u,ne as v,rt as w,$e as x,Re as y,se as z,dt as A,Qn as B,Vn as C};
|
|
126
|
+
//# sourceMappingURL=chunk-NGSIRE4X.js.map
|