agentix-cli 0.16.0 → 0.18.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/dist/agent-RDVGL2TW.js +2 -0
- package/dist/audit-Z47AQFFD.js +3 -0
- package/dist/audit-Z47AQFFD.js.map +1 -0
- package/dist/board-dashboard-KX2CNOSY.js +7282 -0
- package/dist/board-dashboard-KX2CNOSY.js.map +1 -0
- package/dist/chunk-34NG7UDX.js +11 -0
- package/dist/chunk-34NG7UDX.js.map +1 -0
- package/dist/{chunk-6MKAXEE5.js → chunk-4ITQP3XL.js} +2 -2
- package/dist/{chunk-6MKAXEE5.js.map → chunk-4ITQP3XL.js.map} +1 -1
- package/dist/chunk-53NRX2NA.js +2 -0
- package/dist/chunk-53NRX2NA.js.map +1 -0
- package/dist/chunk-6PPIFDOQ.js +1742 -0
- package/dist/chunk-6PPIFDOQ.js.map +1 -0
- package/dist/chunk-AFRHKA7B.js +2 -0
- package/dist/chunk-AFRHKA7B.js.map +1 -0
- package/dist/chunk-ASSJ4Z6Z.js +164 -0
- package/dist/chunk-ASSJ4Z6Z.js.map +1 -0
- package/dist/chunk-BLUXL6HR.js +854 -0
- package/dist/chunk-BLUXL6HR.js.map +1 -0
- package/dist/chunk-BTAEYL3P.js +72 -0
- package/dist/chunk-BTAEYL3P.js.map +1 -0
- package/dist/chunk-CDNWCYF7.js +2 -0
- package/dist/chunk-CDNWCYF7.js.map +1 -0
- package/dist/chunk-DJEZ2HVU.js +5 -0
- package/dist/chunk-DJEZ2HVU.js.map +1 -0
- package/dist/{chunk-FLOGK2U7.js → chunk-DSCMCVTV.js} +3 -3
- package/dist/chunk-DSCMCVTV.js.map +1 -0
- package/dist/chunk-EW27SCCC.js +2 -0
- package/dist/chunk-EW27SCCC.js.map +1 -0
- package/dist/chunk-HPDHNIA3.js +2 -0
- package/dist/chunk-IM376SD6.js +13 -0
- package/dist/chunk-IM376SD6.js.map +1 -0
- package/dist/chunk-J4WKMKTP.js +5 -0
- package/dist/{chunk-YI2T5QYB.js.map → chunk-J4WKMKTP.js.map} +1 -1
- package/dist/chunk-JGXE2YNV.js +46 -0
- package/dist/chunk-JGXE2YNV.js.map +1 -0
- package/dist/chunk-JXEPJ3YD.js +118 -0
- package/dist/chunk-JXEPJ3YD.js.map +1 -0
- package/dist/chunk-LY7JGDV7.js +6 -0
- package/dist/chunk-LY7JGDV7.js.map +1 -0
- package/dist/chunk-N67JZAXU.js +2 -0
- package/dist/chunk-N67JZAXU.js.map +1 -0
- package/dist/chunk-SR3X25TN.js +3 -0
- package/dist/chunk-SR3X25TN.js.map +1 -0
- package/dist/{chunk-7MBTMCKY.js → chunk-TRQSP67X.js} +2 -2
- package/dist/chunk-U364GNQX.js +719 -0
- package/dist/chunk-U364GNQX.js.map +1 -0
- package/dist/chunk-VJUTQAPJ.js +2 -0
- package/dist/chunk-VJUTQAPJ.js.map +1 -0
- package/dist/{chunk-HI24KAEY.js → chunk-WJXU5F4Z.js} +3 -4
- package/dist/{chunk-HI24KAEY.js.map → chunk-WJXU5F4Z.js.map} +1 -1
- package/dist/{chunk-QZP65I2H.js → chunk-ZE2YFX4K.js} +2 -2
- package/dist/cli.js +1 -320
- package/dist/cli.js.map +1 -1
- package/dist/{compaction-JBZZ7I7Y.js → compaction-S5H6DTOR.js} +6 -6
- package/dist/compaction-S5H6DTOR.js.map +1 -0
- package/dist/config-UOHEG4BW.js +2 -0
- package/dist/config-mutator-KSEBWKJH.js +2 -0
- package/dist/context-planner-2RGHJHSO.js +17 -0
- package/dist/context-planner-2RGHJHSO.js.map +1 -0
- package/dist/debug-TGAP7E7W.js +2 -0
- package/dist/discover-OATU7SHI.js +4 -0
- package/dist/discover-OATU7SHI.js.map +1 -0
- package/dist/editor-chat-FUBQLMAQ.js +137 -0
- package/dist/editor-chat-FUBQLMAQ.js.map +1 -0
- package/dist/heal-YP7QI7D3.js +2 -0
- package/dist/inbox-O5UB3YQN.js +315 -0
- package/dist/inbox-O5UB3YQN.js.map +1 -0
- package/dist/index.d.ts +3390 -1814
- package/dist/index.js +23 -53
- package/dist/index.js.map +1 -1
- package/dist/ingest-whatsapp-C3O5UPBX.js +6 -0
- package/dist/ingest-whatsapp-C3O5UPBX.js.map +1 -0
- package/dist/loader-BGWA7IRY.js +2 -0
- package/dist/loader-LBHKSXBK.js +2 -0
- package/dist/memory-extract-KKPKAOPH.js +2 -0
- package/dist/processes-7W27G3J3.js +256 -0
- package/dist/processes-7W27G3J3.js.map +1 -0
- package/dist/program-2MDELQLX.js +2 -0
- package/dist/providers-WCQSKTNP.js +2 -0
- package/dist/query-FZAL7AQD.js +2 -0
- package/dist/recipes-LZ56TA3X.js +2 -0
- package/dist/registry-ONJSILH4.js +2 -0
- package/dist/scheduler-XRM2RJIV.js +2 -0
- package/dist/slack-D27BE37Q.js +3 -0
- package/dist/slack-D27BE37Q.js.map +1 -0
- package/dist/store-4UCO56K2.js +2 -0
- package/dist/store-4UCO56K2.js.map +1 -0
- package/dist/{subagent-2SJHSSJS.js → subagent-EPOT3QDM.js} +2 -2
- package/dist/task-store-3NUWLYRY.js +2 -0
- package/dist/task-store-3NUWLYRY.js.map +1 -0
- package/dist/telegram-UWV67KWG.js +3 -0
- package/dist/telegram-UWV67KWG.js.map +1 -0
- package/dist/timers-QB4KYNAE.js +2 -0
- package/dist/timers-QB4KYNAE.js.map +1 -0
- package/dist/types-ECMEC5BZ.js +2 -0
- package/dist/types-ECMEC5BZ.js.map +1 -0
- package/dist/types-TTB6DJUE.js +2 -0
- package/dist/types-TTB6DJUE.js.map +1 -0
- package/dist/usage-dashboard-FQGPPABD.js +803 -0
- package/dist/usage-dashboard-FQGPPABD.js.map +1 -0
- package/dist/web/workflow-editor.global.js +1450 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/whatsapp-KJ2NRKKQ.js +3 -0
- package/dist/whatsapp-KJ2NRKKQ.js.map +1 -0
- package/dist/{whatsapp-state-6D6FHHD2.js → whatsapp-state-3ZVQ6MQD.js} +2 -2
- package/dist/{wiki-UDPYFJBL.js → wiki-OUYKM7MB.js} +2 -2
- package/dist/wiki-OUYKM7MB.js.map +1 -0
- package/dist/workspace-setup-6GDBEORT.js +2 -0
- package/dist/workspace-setup-6GDBEORT.js.map +1 -0
- package/package.json +19 -2
- package/dist/agent-BCDPSPKU.js +0 -2
- package/dist/board-dashboard-LA7WW56M.js +0 -5668
- package/dist/board-dashboard-LA7WW56M.js.map +0 -1
- package/dist/chunk-6U2XOQHU.js +0 -7
- package/dist/chunk-6U2XOQHU.js.map +0 -1
- package/dist/chunk-7FJQGD6U.js +0 -6
- package/dist/chunk-7FJQGD6U.js.map +0 -1
- package/dist/chunk-ABDP7TDL.js +0 -71
- package/dist/chunk-ABDP7TDL.js.map +0 -1
- package/dist/chunk-CXY2RYNI.js +0 -11
- package/dist/chunk-CXY2RYNI.js.map +0 -1
- package/dist/chunk-FIOB3MEX.js +0 -2
- package/dist/chunk-FLOGK2U7.js.map +0 -1
- package/dist/chunk-HVC6FJNP.js +0 -108
- package/dist/chunk-HVC6FJNP.js.map +0 -1
- package/dist/chunk-K7BE4E35.js +0 -138
- package/dist/chunk-K7BE4E35.js.map +0 -1
- package/dist/chunk-KXJSLLSQ.js +0 -199
- package/dist/chunk-KXJSLLSQ.js.map +0 -1
- package/dist/chunk-KXZMYLHQ.js +0 -46
- package/dist/chunk-KXZMYLHQ.js.map +0 -1
- package/dist/chunk-M7HKBG3V.js +0 -2
- package/dist/chunk-M7HKBG3V.js.map +0 -1
- package/dist/chunk-MCJUAE6V.js +0 -6
- package/dist/chunk-MCJUAE6V.js.map +0 -1
- package/dist/chunk-RB7265LO.js +0 -12
- package/dist/chunk-RB7265LO.js.map +0 -1
- package/dist/chunk-YI2T5QYB.js +0 -5
- package/dist/compaction-JBZZ7I7Y.js.map +0 -1
- package/dist/config-LN6JEHMF.js +0 -2
- package/dist/config-mutator-24TH7PHM.js +0 -2
- package/dist/debug-3MEUO2P2.js +0 -2
- package/dist/heal-WKY5I4KB.js +0 -2
- package/dist/loader-PTCXLJEX.js +0 -2
- package/dist/memory-extract-AD7KMRPC.js +0 -2
- package/dist/providers-VUIWO3ZK.js +0 -2
- package/dist/query-PKGYE5HR.js +0 -2
- package/dist/registry-ASC2QS5K.js +0 -2
- package/dist/scheduler-A3TQOCKT.js +0 -2
- package/dist/types-OIFU3KSQ.js +0 -2
- package/dist/usage-dashboard-QX3CF6KK.js +0 -404
- package/dist/usage-dashboard-QX3CF6KK.js.map +0 -1
- package/dist/workspace-setup-ZWTT42XT.js +0 -2
- /package/dist/{agent-BCDPSPKU.js.map → agent-RDVGL2TW.js.map} +0 -0
- /package/dist/{chunk-FIOB3MEX.js.map → chunk-HPDHNIA3.js.map} +0 -0
- /package/dist/{chunk-7MBTMCKY.js.map → chunk-TRQSP67X.js.map} +0 -0
- /package/dist/{chunk-QZP65I2H.js.map → chunk-ZE2YFX4K.js.map} +0 -0
- /package/dist/{config-LN6JEHMF.js.map → config-UOHEG4BW.js.map} +0 -0
- /package/dist/{config-mutator-24TH7PHM.js.map → config-mutator-KSEBWKJH.js.map} +0 -0
- /package/dist/{debug-3MEUO2P2.js.map → debug-TGAP7E7W.js.map} +0 -0
- /package/dist/{heal-WKY5I4KB.js.map → heal-YP7QI7D3.js.map} +0 -0
- /package/dist/{loader-PTCXLJEX.js.map → loader-BGWA7IRY.js.map} +0 -0
- /package/dist/{memory-extract-AD7KMRPC.js.map → loader-LBHKSXBK.js.map} +0 -0
- /package/dist/{providers-VUIWO3ZK.js.map → memory-extract-KKPKAOPH.js.map} +0 -0
- /package/dist/{query-PKGYE5HR.js.map → program-2MDELQLX.js.map} +0 -0
- /package/dist/{registry-ASC2QS5K.js.map → providers-WCQSKTNP.js.map} +0 -0
- /package/dist/{scheduler-A3TQOCKT.js.map → query-FZAL7AQD.js.map} +0 -0
- /package/dist/{types-OIFU3KSQ.js.map → recipes-LZ56TA3X.js.map} +0 -0
- /package/dist/{wiki-UDPYFJBL.js.map → registry-ONJSILH4.js.map} +0 -0
- /package/dist/{workspace-setup-ZWTT42XT.js.map → scheduler-XRM2RJIV.js.map} +0 -0
- /package/dist/{subagent-2SJHSSJS.js.map → subagent-EPOT3QDM.js.map} +0 -0
- /package/dist/{whatsapp-state-6D6FHHD2.js.map → whatsapp-state-3ZVQ6MQD.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/crons/scheduler.ts"],"sourcesContent":["import type { DaemonConfig, CronJobDef } from \"@/daemon/config\"\nimport type { AgentRegistry } from \"@/agents/registry\"\nimport type { HookRegistry } from \"@/hooks\"\nimport type { CronJobState, CronRunResult } from \"./types\"\nimport { writeFileSync, mkdirSync, existsSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { applyConfigMutation, setAtPath } from \"@/daemon/config-mutator\"\n\n// --- Cron Scheduler: lightweight cron engine with timezone support ---\n// No external dependencies — uses setTimeout-based scheduling.\n\n/**\n * Append a soft output-length cap to a cron prompt when the job configured\n * `maxOutputTokens`. Claude Code CLI has no hard flag for output length,\n * but a clear instruction at the end of the prompt is reliably honored by\n * the model. Keeps a cheap knob available for operators without us needing\n * to invent our own token counter or hack a post-response truncate.\n */\nfunction withOutputCap(prompt: string, maxOutputTokens?: number): string {\n if (!maxOutputTokens) return prompt\n const approxChars = maxOutputTokens * 4\n return `${prompt}\\n\\n[Response budget]\\nKeep your response under ~${maxOutputTokens} tokens (~${approxChars} chars). Be concise — this is automated batch work, not a conversation.`\n}\n\n/**\n * Parse a cron expression into next-fire timestamp.\n * Supports standard 5-field format: minute hour day-of-month month day-of-week\n */\nfunction parseCronField(field: string, min: number, max: number): number[] {\n const values: number[] = []\n\n for (const part of field.split(\",\")) {\n if (part === \"*\") {\n for (let i = min; i <= max; i++) values.push(i)\n } else if (part.includes(\"/\")) {\n const [range, stepStr] = part.split(\"/\")\n const step = parseInt(stepStr, 10)\n const start = range === \"*\" ? min : parseInt(range, 10)\n for (let i = start; i <= max; i += step) values.push(i)\n } else if (part.includes(\"-\")) {\n const [a, b] = part.split(\"-\").map(Number)\n for (let i = a; i <= b; i++) values.push(i)\n } else {\n values.push(parseInt(part, 10))\n }\n }\n\n return [...new Set(values)].sort((a, b) => a - b)\n}\n\nexport function getNextCronDate(expression: string, after: Date, timezone: string): Date {\n const fields = expression.trim().split(/\\s+/)\n if (fields.length !== 5) throw new Error(`Invalid cron: ${expression}`)\n\n const minutes = parseCronField(fields[0], 0, 59)\n const hours = parseCronField(fields[1], 0, 23)\n const daysOfMonth = parseCronField(fields[2], 1, 31)\n const months = parseCronField(fields[3], 1, 12)\n const daysOfWeek = parseCronField(fields[4], 0, 6)\n\n // Convert to timezone-aware date\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n })\n\n // Start searching from next minute\n const candidate = new Date(after.getTime() + 60_000)\n candidate.setSeconds(0, 0)\n\n // Search up to 1 year ahead\n const limit = new Date(candidate.getTime() + 366 * 24 * 60 * 60 * 1000)\n\n while (candidate < limit) {\n const parts = fmt.formatToParts(candidate)\n const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value || \"0\", 10)\n\n const m = get(\"minute\")\n const h = get(\"hour\")\n const dom = get(\"day\")\n const mon = get(\"month\")\n const dow = candidate.getDay()\n\n if (\n minutes.includes(m) &&\n hours.includes(h) &&\n daysOfMonth.includes(dom) &&\n months.includes(mon) &&\n daysOfWeek.includes(dow)\n ) {\n return candidate\n }\n\n // Advance by 1 minute\n candidate.setTime(candidate.getTime() + 60_000)\n }\n\n throw new Error(`No next run found for cron \"${expression}\" within 1 year`)\n}\n\n// Retry config (inspired by OpenClaw's exponential backoff)\nconst MAX_RETRIES = 5\nconst RETRY_DELAYS = [30_000, 60_000, 300_000, 900_000, 3_600_000] // 30s, 1m, 5m, 15m, 60m\n\n/** Notification callback — injected by daemon to send alerts via channels */\nexport type CronNotifyCallback = (jobId: string, agent: string, error: string, consecutiveErrors: number) => Promise<void>\n\nexport class CronScheduler {\n private jobs: Map<string, CronJobState> = new Map()\n private timers: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private registry: AgentRegistry\n private hooks?: HookRegistry\n private runsDir: string\n private lastRunFile: string\n private running = false\n private notifyCallback?: CronNotifyCallback\n private log: (...args: unknown[]) => void\n\n constructor(\n config: DaemonConfig,\n registry: AgentRegistry,\n hooks?: HookRegistry,\n log: (...args: unknown[]) => void = console.error.bind(console, \"[cron]\"),\n ) {\n this.registry = registry\n this.hooks = hooks\n this.log = log\n this.runsDir = resolve(process.cwd(), \".agentx/cron/runs\")\n this.lastRunFile = resolve(process.cwd(), \".agentx/cron/last-runs.json\")\n\n for (const [id, def] of Object.entries(config.crons)) {\n this.jobs.set(id, {\n id,\n enabled: def.enabled,\n schedule: def.schedule,\n timezone: def.timezone,\n agent: def.agent,\n prompt: def.prompt,\n timeout: def.timeout,\n model: def.model,\n maxOutputTokens: def.maxOutputTokens,\n onError: def.onError,\n consecutiveErrors: 0,\n totalRuns: 0,\n totalFailures: 0,\n })\n }\n }\n\n /**\n * Set a notification callback for failed crons.\n * Called when onError is \"notify\" or after multiple consecutive failures.\n */\n setNotifyCallback(cb: CronNotifyCallback): void {\n this.notifyCallback = cb\n }\n\n async start(): Promise<void> {\n this.running = true\n\n if (!existsSync(this.runsDir)) {\n mkdirSync(this.runsDir, { recursive: true })\n }\n\n // Detect missed runs before scheduling\n const missedRuns = this.detectMissedRuns()\n if (missedRuns.length > 0) {\n this.log(`Detected ${missedRuns.length} missed cron run(s) while daemon was down:`)\n for (const { jobId, missedAt } of missedRuns) {\n this.log(` \"${jobId}\" should have run at ${missedAt.toISOString()}`)\n }\n // Execute missed runs (fire-and-forget, don't block startup)\n this.executeMissedRuns(missedRuns).catch((e) => {\n this.log(`Error executing missed runs: ${e.message}`)\n })\n }\n\n for (const [id, job] of this.jobs) {\n if (!job.enabled) {\n this.log(`Job \"${id}\" is disabled, skipping`)\n continue\n }\n this.scheduleNext(id)\n }\n\n this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter((j) => j.enabled).length} enabled`)\n }\n\n async stop(): Promise<void> {\n this.running = false\n for (const timer of this.timers.values()) {\n clearTimeout(timer)\n }\n this.timers.clear()\n\n // Persist last run times for missed run detection on next start\n this.saveLastRuns()\n }\n\n private scheduleNext(jobId: string): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n\n // Clear any existing timer\n const existing = this.timers.get(jobId)\n if (existing) clearTimeout(existing)\n\n try {\n const nextRun = getNextCronDate(job.schedule, new Date(), job.timezone)\n job.nextRun = nextRun\n job.retryPending = false\n const delay = nextRun.getTime() - Date.now()\n\n this.log(`Job \"${jobId}\" next run: ${nextRun.toISOString()} (in ${Math.round(delay / 1000)}s)`)\n\n const timer = setTimeout(() => this.executeJob(jobId), delay)\n this.timers.set(jobId, timer)\n } catch (e: any) {\n this.log(`Failed to schedule \"${jobId}\": ${e.message}`)\n }\n }\n\n private scheduleRetry(jobId: string, attempt: number): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n if (attempt >= MAX_RETRIES) {\n this.log(`Job \"${jobId}\" exhausted all ${MAX_RETRIES} retries, scheduling next regular run`)\n this.scheduleNext(jobId)\n return\n }\n\n const delay = RETRY_DELAYS[attempt] || RETRY_DELAYS[RETRY_DELAYS.length - 1]\n job.retryPending = true\n\n this.log(`Job \"${jobId}\" retry ${attempt + 1}/${MAX_RETRIES} in ${Math.round(delay / 1000)}s`)\n\n const timer = setTimeout(() => this.executeJob(jobId, attempt + 1), delay)\n this.timers.set(jobId, timer)\n }\n\n private async executeJob(jobId: string, retryAttempt: number = 0): Promise<void> {\n const job = this.jobs.get(jobId)\n if (!job || !this.running) return\n\n const isRetry = retryAttempt > 0\n\n // Pre-hook\n if (this.hooks?.has(\"pre:cron-run\" as any)) {\n const hookResult = await this.hooks.execute(\"pre:cron-run\" as any, {\n event: \"pre:cron-run\" as any,\n jobId,\n agent: job.agent,\n prompt: job.prompt,\n })\n if (hookResult.blocked) {\n this.log(`Job \"${jobId}\" blocked by hook: ${hookResult.message}`)\n this.scheduleNext(jobId)\n return\n }\n }\n\n this.log(`${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> agent \"${job.agent}\"`)\n const startedAt = new Date()\n job.lastRun = startedAt\n job.totalRuns++\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(job.prompt, job.maxOutputTokens),\n agentId: job.agent,\n model: job.model,\n context: { channel: \"cron\" },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt,\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || Date.now() - startedAt.getTime(),\n isRetry,\n retryAttempt,\n }\n\n if (response.error) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = response.error\n this.log(`Job \"${jobId}\" failed (${job.consecutiveErrors} consecutive): ${response.error}`)\n\n // Notify on failure\n await this.notifyFailure(job, response.error)\n\n if (job.onError.includes(\"disable\") && job.consecutiveErrors >= 3) {\n job.enabled = false\n this.log(`Job \"${jobId}\" disabled after ${job.consecutiveErrors} consecutive errors`)\n // Persist to agentx.json so a daemon restart doesn't resurrect the\n // broken cron (previously this was in-memory only — a repeatedly\n // failing cron would keep burning money across restarts).\n try {\n const res = await applyConfigMutation(\n (cfg) => setAtPath(cfg, `crons.${jobId}.enabled`, false),\n { reload: false },\n )\n if (!res.success) {\n this.log(`Failed to persist disable for \"${jobId}\": ${res.error}`)\n }\n } catch (e: any) {\n this.log(`Failed to persist disable for \"${jobId}\": ${e.message}`)\n }\n await this.notifyDisabled(job)\n }\n\n // Retry\n this.logRun(result)\n this.scheduleRetry(jobId, retryAttempt)\n return\n } else {\n // Success — reset error state\n if (job.consecutiveErrors > 0) {\n this.log(`Job \"${jobId}\" recovered after ${job.consecutiveErrors} failure(s)`)\n }\n job.consecutiveErrors = 0\n job.lastSuccess = new Date()\n job.lastError = undefined\n job.retryPending = false\n this.log(`Job \"${jobId}\" completed in ${result.duration}ms`)\n }\n\n // Log run\n this.logRun(result)\n\n // Post-hook\n if (this.hooks?.has(\"post:cron-run\" as any)) {\n await this.hooks.execute(\"post:cron-run\" as any, {\n event: \"post:cron-run\" as any,\n jobId,\n success: result.success,\n duration: result.duration,\n error: result.error ? new Error(result.error) : undefined,\n })\n }\n } catch (e: any) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = e.message\n this.log(`Job \"${jobId}\" threw: ${e.message}`)\n\n await this.notifyFailure(job, e.message)\n this.scheduleRetry(jobId, retryAttempt)\n return\n }\n\n // Persist last run time\n this.saveLastRuns()\n\n // Schedule next regular run\n this.scheduleNext(jobId)\n }\n\n // --- Missed run detection ---\n\n /**\n * Detect cron jobs that should have fired while the daemon was down.\n * Compares saved last-run times against the cron schedule.\n */\n private detectMissedRuns(): Array<{ jobId: string; missedAt: Date }> {\n const missed: Array<{ jobId: string; missedAt: Date }> = []\n\n const lastRuns = this.loadLastRuns()\n if (!lastRuns) return missed // First boot — no history\n\n for (const [jobId, job] of this.jobs) {\n if (!job.enabled) continue\n\n const lastRunStr = lastRuns[jobId]\n if (!lastRunStr) continue // Never ran before\n\n const lastRun = new Date(lastRunStr)\n try {\n // What SHOULD the next run have been after the last recorded run?\n const shouldHaveRun = getNextCronDate(job.schedule, lastRun, job.timezone)\n if (shouldHaveRun.getTime() < Date.now()) {\n missed.push({ jobId, missedAt: shouldHaveRun })\n }\n } catch {\n // Invalid schedule — skip\n }\n }\n\n return missed\n }\n\n /**\n * Execute missed runs (catch-up). Runs sequentially to avoid overwhelming agents.\n */\n private async executeMissedRuns(missed: Array<{ jobId: string; missedAt: Date }>): Promise<void> {\n for (const { jobId, missedAt } of missed) {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled) continue\n\n this.log(`Running missed job \"${jobId}\" (was due at ${missedAt.toISOString()})`)\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(\n `[MISSED RUN — was scheduled for ${missedAt.toISOString()}]\\n\\n${job.prompt}`,\n job.maxOutputTokens,\n ),\n agentId: job.agent,\n context: { channel: \"cron\" },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt: new Date(),\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || 0,\n isRetry: false,\n }\n\n this.logRun(result)\n\n if (response.error) {\n this.log(`Missed job \"${jobId}\" failed: ${response.error}`)\n } else {\n this.log(`Missed job \"${jobId}\" completed`)\n job.lastSuccess = new Date()\n }\n job.lastRun = new Date()\n job.totalRuns++\n } catch (e: any) {\n this.log(`Missed job \"${jobId}\" threw: ${e.message}`)\n }\n }\n\n this.saveLastRuns()\n }\n\n // --- Notification ---\n\n private async notifyFailure(job: CronJobState, error: string): Promise<void> {\n if (!job.onError.includes(\"notify\") && job.consecutiveErrors < 2) return\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" failed (${job.consecutiveErrors}x): ${error.slice(0, 200)}`)\n return\n }\n\n try {\n await this.notifyCallback(job.id, job.agent, error, job.consecutiveErrors)\n } catch {\n // Don't fail on notification errors\n }\n }\n\n private async notifyDisabled(job: CronJobState): Promise<void> {\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" has been DISABLED after ${job.consecutiveErrors} consecutive failures`)\n return\n }\n\n try {\n await this.notifyCallback(\n job.id,\n job.agent,\n `AUTO-DISABLED after ${job.consecutiveErrors} consecutive failures. Last error: ${job.lastError || \"unknown\"}`,\n job.consecutiveErrors,\n )\n } catch {\n // Don't fail on notification errors\n }\n }\n\n // --- Persistence ---\n\n private saveLastRuns(): void {\n try {\n const data: Record<string, string> = {}\n for (const [id, job] of this.jobs) {\n if (job.lastRun) data[id] = job.lastRun.toISOString()\n }\n const dir = resolve(process.cwd(), \".agentx/cron\")\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n writeFileSync(this.lastRunFile, JSON.stringify(data, null, 2))\n } catch {\n // Best-effort\n }\n }\n\n private loadLastRuns(): Record<string, string> | null {\n try {\n if (!existsSync(this.lastRunFile)) return null\n const { readFileSync } = require(\"fs\")\n return JSON.parse(readFileSync(this.lastRunFile, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n private logRun(result: CronRunResult): void {\n try {\n const runDir = resolve(this.runsDir, result.jobId)\n if (!existsSync(runDir)) {\n mkdirSync(runDir, { recursive: true })\n }\n\n const filename = `${result.startedAt.toISOString().replace(/[:.]/g, \"-\")}.json`\n writeFileSync(\n resolve(runDir, filename),\n JSON.stringify(result, null, 2),\n )\n } catch {\n // Don't fail on logging errors\n }\n }\n\n /**\n * List all jobs and their status (including failure info).\n */\n list(): CronJobState[] {\n return Array.from(this.jobs.values())\n }\n\n /**\n * Get a health summary of cron jobs.\n */\n health(): { healthy: number; failing: number; disabled: number; missed: number; jobs: Array<{ id: string; status: string; consecutiveErrors: number; lastError?: string }> } {\n const jobs = Array.from(this.jobs.values())\n const missed = this.detectMissedRuns()\n\n return {\n healthy: jobs.filter(j => j.enabled && j.consecutiveErrors === 0).length,\n failing: jobs.filter(j => j.enabled && j.consecutiveErrors > 0).length,\n disabled: jobs.filter(j => !j.enabled).length,\n missed: missed.length,\n jobs: jobs.map(j => ({\n id: j.id,\n status: !j.enabled ? \"disabled\" : j.retryPending ? \"retrying\" : j.consecutiveErrors > 0 ? \"failing\" : \"healthy\",\n consecutiveErrors: j.consecutiveErrors,\n lastError: j.lastError,\n })),\n }\n }\n}\n"],"mappings":"kFAIA,OAAS,iBAAAA,EAAe,aAAAC,EAAW,cAAAC,MAAkB,KACrD,OAAS,WAAAC,MAAe,OAaxB,SAASC,EAAcC,EAAgBC,EAAkC,CACvE,GAAI,CAACA,EAAiB,OAAOD,EAC7B,IAAME,EAAcD,EAAkB,EACtC,MAAO,GAAGD;AAAA;AAAA;AAAA,4BAA0DC,cAA4BC,+EAClG,CAMA,SAASC,EAAeC,EAAeC,EAAaC,EAAuB,CACzE,IAAMC,EAAm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EAAO,UAAU,YAAY,EAAE,QAAQ,QAAS,GAAG,SACvEa,EACEnC,EAAQqC,EAAQC,CAAQ,EACxB,KAAK,UAAUhB,EAAQ,KAAM,CAAC,CAChC,CACF,MAAE,CAEF,CACF,CAKA,MAAuB,CACrB,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,CACtC,CAKA,QAA6K,CAC3K,IAAMiB,EAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,EACpCZ,EAAS,KAAK,iBAAiB,EAErC,MAAO,CACL,QAASY,EAAK,OAAO5B,GAAKA,EAAE,SAAWA,EAAE,oBAAsB,CAAC,EAAE,OAClE,QAAS4B,EAAK,OAAO5B,GAAKA,EAAE,SAAWA,EAAE,kBAAoB,CAAC,EAAE,OAChE,SAAU4B,EAAK,OAAO5B,GAAK,CAACA,EAAE,OAAO,EAAE,OACvC,OAAQgB,EAAO,OACf,KAAMY,EAAK,IAAI5B,IAAM,CACnB,GAAIA,EAAE,GACN,OAASA,EAAE,QAAuBA,EAAE,aAAe,WAAaA,EAAE,kBAAoB,EAAI,UAAY,UAAjF,WACrB,kBAAmBA,EAAE,kBACrB,UAAWA,EAAE,SACf,EAAE,CACJ,CACF,CACF","names":["writeFileSync","mkdirSync","existsSync","resolve","withOutputCap","prompt","maxOutputTokens","approxChars","parseCronField","field","min","max","values","part","range","stepStr","step","start","i","a","b","getNextCronDate","expression","after","timezone","fields","minutes","hours","daysOfMonth","months","daysOfWeek","fmt","candidate","limit","parts","get","type","p","m","h","dom","mon","dow","MAX_RETRIES","RETRY_DELAYS","CronScheduler","config","registry","hooks","log","resolve","id","def","cb","existsSync","mkdirSync","missedRuns","jobId","missedAt","e","job","j","timer","existing","nextRun","delay","attempt","retryAttempt","isRetry","hookResult","startedAt","response","result","res","applyConfigMutation","cfg","setAtPath","missed","lastRuns","lastRunStr","lastRun","shouldHaveRun","error","data","dir","writeFileSync","readFileSync","runDir","filename","jobs"]}
|
package/dist/chunk-HVC6FJNP.js
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
import{a as Ce,b as Se,c as ge}from"./chunk-SFQUP3BP.js";import{d as X,h as p}from"./chunk-RB7265LO.js";import{a as de,c as ue,g as me}from"./chunk-KXZMYLHQ.js";import{a as F,b as ce,f as pe}from"./chunk-M7HKBG3V.js";import{a as Te,d as fe}from"./chunk-MCJUAE6V.js";import{e as v}from"./chunk-DSYKYZMT.js";import{b as he,c as ye}from"./chunk-QOYAX2FT.js";import{z as R}from"zod";var Re=R.object({provider:R.enum(["claude-code","claude","openai","ollama","custom"]).default("claude-code"),model:R.string().optional(),apiKey:R.string().optional(),skills:R.array(R.string()).default([]),output:R.object({dir:R.string().default("./generated")}).default({}),context7:R.object({enabled:R.boolean().default(!0),apiKey:R.string().optional()}).default({}),agentic:R.object({maxIterations:R.number().default(20),enabledTools:R.array(R.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:R.array(R.string()).default([])}).default({})}),dt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],ut={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 Ye,promises as Je}from"fs";import B from"path";import Qe from"fast-glob";var Ae={"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 Me(o){let e={},t=await Qe.glob("**/*",{cwd:o,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="database"){let a=await K(B.resolve(o,l));if(a){e.database={type:i.type,content:Z(a,3e3),tables:Ve(a,i.type)};break}}}for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="api"){let a=await K(B.resolve(o,l));if(a){e.api={type:i.type,content:Z(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 K(B.resolve(o,s));i&&(e.api={type:"trpc",content:Z(i,3e3)})}}let n=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(n){let s=await K(B.resolve(o,n));s&&(e.env=Xe(s))}let r=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(r.length){e.models=[];for(let s of r.slice(0,5)){let i=await K(B.resolve(o,s));i&&e.models.push({path:s,content:Z(i,2e3),type:B.extname(s).slice(1)})}}return e}function Ve(o,e){if(e==="prisma"){let t=o.match(/model\s+(\w+)\s*\{/g);return t?t.map(n=>n.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function Xe(o){return{variables:o.split(`
|
|
2
|
-
`).filter(n=>n.trim()&&!n.trim().startsWith("#")).map(n=>{let[r]=n.split("="),s=r.trim(),i=n.includes("=")&&n.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function K(o){try{return Ye(o)?await Je.readFile(o,"utf8"):null}catch{return null}}function Z(o,e){return o.length<=e?o:o.slice(0,e)+`
|
|
3
|
-
... (truncated)`}function Ie(o){let e=[];if(o.database&&e.push(`## Database Schema (${o.database.type})
|
|
4
|
-
`+(o.database.tables?.length?`Tables: ${o.database.tables.join(", ")}
|
|
5
|
-
`:"")+"```\n"+o.database.content+"\n```"),o.api&&e.push(`## API Schema (${o.api.type})
|
|
6
|
-
\`\`\`
|
|
7
|
-
`+o.api.content+"\n```"),o.env&&e.push(`## Environment Variables
|
|
8
|
-
`+o.env.variables.map(t=>`- ${t.key}${t.required?" (required)":""}`).join(`
|
|
9
|
-
`)),o.models?.length)for(let t of o.models)e.push(`## Model: ${t.path}
|
|
10
|
-
\`\`\``+t.type+`
|
|
11
|
-
`+t.content+"\n```");return e.join(`
|
|
12
|
-
|
|
13
|
-
`)}import $e from"node-fetch";var je="https://api.context7.com/v1";async function Ze(o,e){try{let t={"Content-Type":"application/json"};e&&(t.Authorization=`Bearer ${e}`);let n=await $e(`${je}/libraries/resolve`,{method:"POST",headers:t,body:JSON.stringify({name:o})});if(!n.ok)return null;let r=await n.json();return r?.libraries?.length?r.libraries[0]:null}catch{return null}}async function et(o,e,t=5e3,n){try{let r={"Content-Type":"application/json"};n&&(r.Authorization=`Bearer ${n}`);let s=await $e(`${je}/libraries/${encodeURIComponent(o)}/docs`,{method:"POST",headers:r,body:JSON.stringify({topic:e,maxTokens:t})});return s.ok&&(await s.json())?.content||null}catch{return null}}async function Oe(o,e,t){let n=[];for(let i of o.frameworks.slice(0,3))n.push(i.name);let r=["react","vue","svelte","angular","next","nuxt","express","fastify","hono","prisma","drizzle-orm","tailwindcss","shadcn","@tanstack/react-query","zod","trpc"];for(let i of r)(o.dependencies[i]||o.devDependencies[i])&&(n.includes(i)||n.push(i));let s=[];for(let i of n.slice(0,5)){let l=await Ze(i,t);if(l){let a=await et(l.id,e,3e3,t);a&&s.push(`## ${l.name} Documentation
|
|
14
|
-
${a}`)}}return s.length?`# Relevant Library Documentation (via Context7)
|
|
15
|
-
|
|
16
|
-
${s.join(`
|
|
17
|
-
|
|
18
|
-
---
|
|
19
|
-
|
|
20
|
-
`)}`:""}var Ue={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 we(o,e){if(o&&o!=="auto")return o;let t=e.toLowerCase(),n=[[/\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[r,s]of n)if(r.test(t))return s;return"component"}import{existsSync as rt,promises as Ge}from"fs";import te from"path";import tt from"prompts";import ot from"chalk";import{z as D}from"zod";var Ee=["default","acceptEdits","plan","yolo"],De=D.enum(Ee),be=D.object({mode:De.default("default"),allow:D.array(D.string()).default([]),deny:D.array(D.string()).default([]),confirm:D.array(D.string()).default([])});function nt(o,e){let t=e.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\{\{GLOBSTAR\}\}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${t}$`).test(o)}var ee=class{mode;allowPatterns;denyPatterns;confirmPatterns;autoAllowAll=!1;constructor(e){let t=be.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,v.context("permissions",`mode set to ${e}`)}async checkFileWrite(e){if(v.context("permissions",`checking write: ${e} (mode: ${this.mode})`),this.matchesAny(e,this.denyPatterns))return v.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(n=>nt(e,n))}async promptUser(e){let{action:t}=await tt({type:"select",name:"action",message:`Write file ${ot.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"}},N=new ee;async function oe(o,e){let t={written:[],skipped:[],errors:[]};for(let n of o){let r=te.isAbsolute(n.path)?n.path:te.resolve(e.cwd,e.outputDir||"",n.path);try{let s=n.content;if(p.has("pre:file-write")){let h=await p.execute("pre:file-write",{event:"pre:file-write",file:r,fileContent:s,cwd:e.cwd});if(h.blocked){t.skipped.push(r);continue}h.modified?.fileContent&&(s=String(h.modified.fileContent))}let i=te.relative(e.cwd,r),l=await N.checkFileWrite(i);if(l==="deny"){t.skipped.push(r);continue}if(l==="skip"){t.written.push(r);continue}if(rt(r)&&!e.overwrite){t.skipped.push(r);continue}if(e.dryRun){t.written.push(r);continue}let a=te.dirname(r);await Ge.mkdir(a,{recursive:!0}),await Ge.writeFile(r,s,"utf8"),t.written.push(r),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:s,cwd:e.cwd})}catch(s){t.errors.push(`${r}: ${s.message}`)}}return t}function ne(o,e,t){if(t)return t;let n=Ue[o];if(!n)return"generated";let r=n.baseDir;return o==="component"&&(e.srcDir?r=`${e.srcDir}/components`:r="components"),o==="page"&&e.frameworks.find(i=>i.name==="nextjs")&&e.srcDir&&(r=`${e.srcDir}/app`),o==="api"&&e.frameworks.find(i=>i.name==="nextjs")&&(r=e.srcDir?`${e.srcDir}/app/api`:"app/api"),o==="test"&&(e.testing.includes("vitest")||e.testing.includes("jest"))&&(r=e.srcDir||"src"),o==="workflow"&&(r=".github/workflows"),o==="schema"&&(e.databases.includes("prisma")?r="prisma":e.srcDir&&(r=`${e.srcDir}/schemas`)),o==="email"&&(r=e.srcDir?`${e.srcDir}/emails`:"emails"),r}import st from"os";var it=st.homedir(),Y=class{constructor(e){this.cwd=e;this.userMemory=new ge(it),this.projectMemory=new ge(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),n=this.projectMemory.buildMemoryContext(e);if(!t&&!n)return"";let r=[];return n&&r.push(n),t&&r.push(t.replace("# Memory (learned from past interactions)","# Global Memory (cross-project patterns)")),r.join(`
|
|
21
|
-
|
|
22
|
-
`)}async learnPreference(e,t,n){await this.userMemory.learnPreference(e,t,n)}async recordGeneration(e){return this.projectMemory.recordGeneration(e)}getPreferences(){let e=this.userMemory.getPreferences(),t=this.projectMemory.getPreferences(),n=new Map;for(let r of e)n.set(r.key,r);for(let r of t)n.set(r.key,r);return Array.from(n.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 Fe,readFileSync as Ne}from"fs";import Le from"path";function qe(o,e){return o.replace(/@([\w./-]+)/g,(t,n)=>{let r=Le.resolve(e,n);if(Fe(r))try{return Ne(r,"utf8")}catch{return t}return t})}function ke(o){let e=["SHADXN.md","CLAUDE.md"];for(let t of e){let n=Le.join(o,t);if(Fe(n))try{let r=Ne(n,"utf8");return r=qe(r,o),r}catch{}}return""}function at(o){return Math.ceil(o.length/4)}var xe=class{sections=[];addSection(e,t,n=50){t.trim()&&this.sections.push({label:e,content:t,priority:n})}buildContext(e,t=12e3){if(this.sections.length===0)return"";let n=this.sections.map(c=>c.content),r=he(n),s=ye(e,r),i=new Map(s.map(c=>[c.docIndex,c.score])),l=this.sections.map((c,f)=>({...c,relevance:i.get(f)??0,tokens:at(c.content)}));l.sort((c,f)=>f.priority+f.relevance*100-(c.priority+c.relevance*100));let a=[],h=0;for(let c of l)h+c.tokens>t&&a.length>0||(a.push(c),h+=c.tokens);return a.map(c=>c.content).join(`
|
|
23
|
-
|
|
24
|
-
`)}};import{promises as J}from"fs";import re from"path";import{execa as lt}from"execa";import Be from"fast-glob";var Q=class{cwd;options;constructor(e,t={}){this.cwd=e,this.options=t}async execute(e){if(v.context("tool-executor",`executing: ${e.name}`),p.has("pre:tool-call")){let n=await p.execute("pre:tool-call",{event:"pre:tool-call",toolName:e.name,toolInput:e.input,cwd:this.cwd});if(n.blocked)return{tool_use_id:e.id,content:n.message||`Tool ${e.name} blocked by pre:tool-call hook`,is_error:!0}}let t;try{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(n){t={tool_use_id:e.id,content:`Error executing ${e.name}: ${n.message}`,is_error:!0}}return p.has("post:tool-call")&&await p.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||""),n=Number(e.input.max_lines)||500,r=re.resolve(this.cwd,t),s=await J.readFile(r,"utf8"),i=s.split(`
|
|
25
|
-
`),a=i.length>n?i.slice(0,n).join(`
|
|
26
|
-
`)+`
|
|
27
|
-
|
|
28
|
-
... (truncated, ${i.length-n} more lines)`:s;return{tool_use_id:e.id,content:a}}async searchFiles(e){let t=String(e.input.pattern||"**/*"),n=e.input.content_regex?String(e.input.content_regex):void 0,r=Number(e.input.max_results)||50,s=await Be(t,{cwd:this.cwd,ignore:["node_modules/**",".git/**","dist/**",".next/**"],dot:!1});if(!n){let a=s.slice(0,r);return{tool_use_id:e.id,content:a.length?a.join(`
|
|
29
|
-
`)+(s.length>r?`
|
|
30
|
-
|
|
31
|
-
... (${s.length-r} more files)`:""):"No files matched the pattern."}}let i=new RegExp(n,"gm"),l=[];for(let a of s){if(l.length>=r)break;try{let c=(await J.readFile(re.resolve(this.cwd,a),"utf8")).split(`
|
|
32
|
-
`);for(let f=0;f<c.length&&!(l.length>=r);f++)i.test(c[f])&&l.push(`${a}:${f+1}: ${c[f]}`),i.lastIndex=0}catch{}}return{tool_use_id:e.id,content:l.length?l.join(`
|
|
33
|
-
`):"No matches found."}}async listDirectory(e){let t=String(e.input.path||"."),n=!!e.input.recursive,r=Number(e.input.max_depth)||3,s=re.resolve(this.cwd,t);if(n){let h=await Be("**/*",{cwd:s,onlyFiles:!1,markDirectories:!0,deep:r,ignore:["node_modules/**",".git/**","dist/**",".next/**"]});return{tool_use_id:e.id,content:h.length?h.join(`
|
|
34
|
-
`):"Empty directory."}}let l=(await J.readdir(s,{withFileTypes:!0})).map(a=>a.isDirectory()?`${a.name}/`:a.name);return{tool_use_id:e.id,content:l.length?l.join(`
|
|
35
|
-
`):"Empty directory."}}async runCommand(e){let t=String(e.input.command||""),n=Number(e.input.timeout)||3e4;if(await N.checkCommand(t)==="deny")return{tool_use_id:e.id,content:`Command blocked by permissions (mode: ${N.getMode()}): ${t}`,is_error:!0};if(p.has("pre:command")){let a=await p.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 lt("sh",["-c",t],{cwd:this.cwd,timeout:n,reject:!1,stdin:"ignore"}),i=[s.stdout,s.stderr].filter(Boolean).join(`
|
|
36
|
-
`),l=i.length>1e4?i.slice(0,1e4)+`
|
|
37
|
-
|
|
38
|
-
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
39
|
-
${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),n=e.input.edits,r=re.resolve(this.cwd,t);if(!n||n.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await N.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(p.has("pre:file-write")){let a=await p.execute("pre:file-write",{event:"pre:file-write",file:r,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 J.readFile(r,"utf8"),l=[];for(let a of n)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await J.writeFile(r,i,"utf8"),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
40
|
-
${l.join(`
|
|
41
|
-
`)}`}}async createFiles(e){let t=e.input,n=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${n.length} file(s) for creation.`,files:n}}async spawnAgent(e){let t=String(e.input.agent_id||""),n=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!n)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-2SJHSSJS.js"),{getGlobalRegistry:i}=await import("./registry-ASC2QS5K.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let h=await new s(l).spawn({targetAgentId:t,prompt:n,parentAgentId:"orchestrator",timeout:r*1e3});return h.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(h.duration/1e3)}s):
|
|
42
|
-
|
|
43
|
-
${h.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${h.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||""),n=e.input.options,r=t;return n?.length&&(r+=`
|
|
44
|
-
Options: ${n.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function ve(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:h=!1,dryRun:c=!1,onProgress:f}=o;if(!e.generateRaw)return We(o);let x=new Q(s,{interactive:a,overwrite:h,dryRun:c}),b=de(l),$=n.filter(k=>k.role!=="system").map(k=>({role:k.role,content:k.content})),G=[],C=0,S="",O,M=0;for(;M<i;){M++,f?.({type:"iteration_start",iteration:M}),v.step(M,`Agentic loop iteration (${b.length} tools available)`);let k;try{k=await e.generateRaw($,t,b,r)}catch(y){if(y.message?.includes("not available"))return We(o);throw y}C+=k.usage.input_tokens+k.usage.output_tokens;for(let y of k.content)y.type==="text"&&(S+=y.text,f?.({type:"text_delta",text:y.text}));if(k.stop_reason==="end_turn"||k.stop_reason==="max_tokens")break;if(k.stop_reason==="tool_use"){let y=k.content.filter(_=>_.type==="tool_use");if(y.length===0)break;$.push({role:"assistant",content:k.content});let I=[];for(let _ of y){f?.({type:"tool_call",name:_.name,id:_.id,input:_.input}),v.step(M,`Tool call: ${_.name}`);let w=await x.execute({name:_.name,id:_.id,input:_.input});f?.({type:"tool_result",name:_.name,id:_.id,content:w.content.slice(0,200),is_error:w.is_error}),w.files?.length&&(G.push(...w.files),f?.({type:"files_created",files:w.files})),w.followUp&&(O=w.followUp),I.push({type:"tool_result",tool_use_id:w.tool_use_id,content:w.content,is_error:w.is_error})}if($.push({role:"user",content:I}),O)break;continue}break}return f?.({type:"complete",iterations:M,totalTokens:C}),{files:G,content:S,followUp:O,tokensUsed:C,iterations:M}}async function We(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,maxIterations:s=5}=o,l=[{role:"system",content:t+`
|
|
45
|
-
|
|
46
|
-
`+ue()},...n.filter(b=>b.role!=="system")],a=[],h=0,c="",f,x=0;for(;x<s;){x++,v.step(x,`Legacy loop step (model: ${r.model||"default"})`);let b=await e.generate(l,r);if(h+=b.tokensUsed||0,c=b.content,b.files.length&&a.push(...b.files),b.followUp){f=b.followUp;break}if(b.files.length===0&&x>1||!(b.content.includes("[CONTINUE]")||b.content.includes("Next, I'll")||b.content.includes("Now let me")||b.content.includes("I'll also generate")))break;let G=b.files.map(C=>`Created: ${C.path}${C.description?` \u2014 ${C.description}`:""}`).join(`
|
|
47
|
-
`);l.push({role:"assistant",content:b.content+(G?`
|
|
48
|
-
|
|
49
|
-
Files created:
|
|
50
|
-
${G}`:"")}),l.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:c,followUp:f,tokensUsed:h,iterations:x}}function _e(o){return typeof o.generateRaw=="function"}var se=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 ze(o,e,t){let n=Re.parse(t||{}),r=new Y(o);await r.load();let[s,i,l]=await Promise.all([Ce(o),Me(o),Te(o)]),a="";if(n.context7.enabled)try{a=await Oe(s,e,n.context7.apiKey)}catch{}let h=r.buildMemoryContext(e),c=ke(o);return v.context("memory",h?"loaded":"empty"),v.context("instructions",c?"loaded from project":"none"),{techStack:s,schemas:i,skills:l,docs:a,config:n,memoryContext:h,projectInstructions:c}}async function Uo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let u=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:prompt hook");u.modified?.task&&(c=String(u.modified.task))}if(p.has("pre:generate")){let u=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:generate hook")}F.info("Analyzing project...");let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);F.info(`Output type: ${x}`);let b=fe(f.skills,c,x);b.length&&F.info(`Loaded ${b.length} relevant skill(s): ${b.map(u=>u.skill.frontmatter.name).join(", ")}`);let $=He(f,x,b.map(u=>u.skill));if(!await pe(l))throw new Error("No credentials configured. Run `agentx model` to set up.");let C=me(s,l),S=i||ce()?.model,O=[...o.sessionMessages||[],{role:"user",content:c}];F.info("Generating...");let M=_e(C),k=o.maxSteps??(M?20:5),y=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...O],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:k,enabledTools:f.config.agentic.enabledTools.filter(u=>!f.config.agentic.disabledTools.includes(u)),interactive:h,overwrite:n,dryRun:r,onProgress:u=>{u.type==="iteration_start"&&u.iteration>1&&F.info(`Step ${u.iteration}/${k}...`),u.type==="tool_call"&&v.step(0,`Tool: ${u.name}`)}});if(y.tokensUsed){let u=S||"claude-sonnet-4-20250514",L=Math.round(y.tokensUsed*.3),ie=y.tokensUsed-L;X.recordStep(1,u,L,ie)}let{content:I}=y,{followUp:_,tokensUsed:w}=y;if(y.iterations>1&&F.info(`Completed in ${y.iterations} step(s)`),p.has("post:response")){let u=await p.execute("post:response",{event:"post:response",content:I,task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by post:response hook");u.modified?.content&&(I=String(u.modified.content))}if(_&&h)return{files:{written:[],skipped:[],errors:[]},content:I,outputType:x,followUp:_,tokensUsed:w};let U=new Map;for(let u of y.files)U.set(u.path,u);let A=ne(x,f.techStack,o.outputDir),T=await oe(Array.from(U.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:A}),j;if(o.heal!==!1&&!r&&T.written.length>0){let{HealEngine:u}=await import("./heal-WKY5I4KB.js");j=await new u(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(T.written,c),!j.healed&&j.error&&await p.execute("on:error",{event:"on:error",error:new Error(j.error),task:c,cwd:t})}return p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:I,cwd:t}),{files:T,content:I,outputType:x,tokensUsed:w,healResult:j}}async function*Eo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let d=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:prompt hook"};return}d.modified?.task&&(c=String(d.modified.task))}if(p.has("pre:generate")){let d=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:generate hook"};return}}let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);yield{type:"context_ready",outputType:x};let b=fe(f.skills,c,x),$=He(f,x,b.map(d=>d.skill));if(!await pe(l)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let C=me(s,l),S=i||ce()?.model,O=_e(C),M=o.maxSteps??(O?20:5),k=[...o.sessionMessages||[],{role:"user",content:c}];if(O){let d=new se,P,g,q=(async()=>{try{P=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...k],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:M,enabledTools:f.config.agentic.enabledTools.filter(m=>!f.config.agentic.disabledTools.includes(m)),interactive:h,overwrite:n,dryRun:r,onProgress:m=>{m.type==="text_delta"&&d.push({type:"text_delta",text:m.text}),m.type==="iteration_start"&&d.push({type:"iteration",iteration:m.iteration}),m.type==="tool_call"&&d.push({type:"tool_call",name:m.name,id:m.id}),m.type==="tool_result"&&d.push({type:"tool_result",name:m.name,id:m.id,is_error:m.is_error}),m.type==="files_created"&&d.push({type:"step_complete",step:0,filesCount:m.files.length})}})}catch(m){g=m}finally{d.close()}})();for await(let m of d)yield m;if(await q,g){yield{type:"error",error:g instanceof Error?g.message:String(g)};return}if(!P){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:P.content,files:P.files,tokensUsed:P.tokensUsed,followUp:P.followUp}};let{content:E}=P;if(p.has("post:response")){let m=await p.execute("post:response",{event:"post:response",content:E,task:c,cwd:t});if(m.blocked){yield{type:"error",error:m.message||"Blocked by post:response hook"};return}m.modified?.content&&(E=String(m.modified.content))}if(P.followUp&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:E,outputType:x,followUp:P.followUp,tokensUsed:P.tokensUsed}};return}let z=new Map;for(let m of P.files)z.set(m.path,m);let le=ne(x,f.techStack,o.outputDir),V=await oe(Array.from(z.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:le}),H;if(o.heal!==!1&&!r&&V.written.length>0){let{HealEngine:m}=await import("./heal-WKY5I4KB.js");H=await new m(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(V.written,c)}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:E,cwd:t}),yield{type:"generate_result",result:{files:V,content:E,outputType:x,tokensUsed:P.tokensUsed,healResult:H}};return}let y=[{role:"system",content:$},...k],I=[],_=0,w="",U,A=0;A++,v.step(A,`Starting generation (model: ${S||"default"})`);let T;if(C.stream){let d="",P;for await(let g of C.stream(y,{model:S,maxTokens:8192}))yield g,g.type==="text_delta"&&(d+=g.text),g.type==="done"&&(P=g.result);T=P||{content:d,files:[],tokensUsed:0}}else{let d=await C.generate(y,{model:S,maxTokens:8192});d.content&&(yield{type:"text_delta",text:d.content}),yield{type:"done",result:d},T=d}_+=T.tokensUsed||0,w=T.content;let j=T.tokensUsed||0,u=S||"claude-sonnet-4-20250514",L=Math.round(j*.3),ie=j-L;if(X.recordStep(A,u,L,ie),v.api("generate",u,j),v.step(A,`Generated ${T.files.length} file(s), ${j} tokens`),T.files.length&&I.push(...T.files),T.followUp&&(U=T.followUp),yield{type:"step_complete",step:A,filesCount:T.files.length},!U&&(w.includes("[CONTINUE]")||w.includes("Next, I'll")||w.includes("Now let me")||w.includes("I'll also generate"))&&T.files.length>0){let P=T.files.map(g=>`Created: ${g.path}${g.description?` \u2014 ${g.description}`:""}`).join(`
|
|
51
|
-
`);for(y.push({role:"assistant",content:w+(P?`
|
|
52
|
-
|
|
53
|
-
Files created:
|
|
54
|
-
${P}`:"")}),y.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."});A<M;){A++,v.step(A,`Starting generation (model: ${S||"default"})`);let g=await C.generate(y,{model:S,maxTokens:8192});_+=g.tokensUsed||0,w=g.content;let q=g.tokensUsed||0,E=S||"claude-sonnet-4-20250514",z=Math.round(q*.3),le=q-z;if(X.recordStep(A,E,z,le),v.api("generate",E,q),v.step(A,`Generated ${g.files.length} file(s), ${q} tokens`),g.files.length&&I.push(...g.files),yield{type:"step_complete",step:A,filesCount:g.files.length},g.followUp){U=g.followUp;break}if(g.files.length===0&&A>1||!(g.content.includes("[CONTINUE]")||g.content.includes("Next, I'll")||g.content.includes("Now let me")||g.content.includes("I'll also generate")))break;let H=g.files.map(m=>`Created: ${m.path}${m.description?` \u2014 ${m.description}`:""}`).join(`
|
|
55
|
-
`);y.push({role:"assistant",content:g.content+(H?`
|
|
56
|
-
|
|
57
|
-
Files created:
|
|
58
|
-
${H}`:"")}),y.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(p.has("post:response")){let d=await p.execute("post:response",{event:"post:response",content:w,task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by post:response hook"};return}d.modified?.content&&(w=String(d.modified.content))}if(U&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:w,outputType:x,followUp:U,tokensUsed:_}};return}let Pe=new Map;for(let d of I)Pe.set(d.path,d);let Ke=ne(x,f.techStack,o.outputDir),ae=await oe(Array.from(Pe.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:Ke}),W;if(o.heal!==!1&&!r&&ae.written.length>0){let{HealEngine:d}=await import("./heal-WKY5I4KB.js");W=await new d(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(ae.written,c),!W.healed&&W.error&&await p.execute("on:error",{event:"on:error",error:new Error(W.error),task:c,cwd:t})}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:w,cwd:t}),yield{type:"generate_result",result:{files:ae,content:w,outputType:x,tokensUsed:_,healResult:W}}}function He(o,e,t){let n=[];n.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
|
|
59
|
-
|
|
60
|
-
Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
|
|
61
|
-
If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
|
|
62
|
-
|
|
63
|
-
You also have tools to inspect the codebase before generating code:
|
|
64
|
-
- \`read_file\` \u2014 read existing files to understand patterns, styles, and implementations
|
|
65
|
-
- \`search_files\` \u2014 search for files by glob pattern, optionally grep content with regex
|
|
66
|
-
- \`list_directory\` \u2014 explore the project structure
|
|
67
|
-
- \`run_command\` \u2014 run shell commands (build, test, lint, etc.)
|
|
68
|
-
- \`edit_file\` \u2014 apply targeted search/replace edits to existing files
|
|
69
|
-
|
|
70
|
-
AGENTIC WORKFLOW:
|
|
71
|
-
- Before generating code, use \`read_file\` and \`search_files\` to understand the existing codebase
|
|
72
|
-
- Match the project's existing patterns, naming conventions, and code style
|
|
73
|
-
- After creating files, consider running tests or build commands to verify correctness
|
|
74
|
-
- Use \`edit_file\` for small, targeted changes instead of rewriting entire files
|
|
75
|
-
|
|
76
|
-
IMPORTANT RULES:
|
|
77
|
-
- Generate complete, working code \u2014 not stubs or placeholders
|
|
78
|
-
- Follow the project's existing patterns and conventions
|
|
79
|
-
- Use the detected tech stack to choose the right language, framework, and patterns
|
|
80
|
-
- File paths should be relative to the project root
|
|
81
|
-
- Include all necessary imports
|
|
82
|
-
- Do NOT add unnecessary dependencies
|
|
83
|
-
|
|
84
|
-
MULTI-STEP GENERATION:
|
|
85
|
-
For complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:
|
|
86
|
-
- Generate the foundational files first (schemas, types, configs)
|
|
87
|
-
- Include "[CONTINUE]" in your response text when there are more files to generate
|
|
88
|
-
- In subsequent steps, you'll see what was already created \u2014 build on it
|
|
89
|
-
- When all files are generated, do NOT include "[CONTINUE]"
|
|
90
|
-
- This enables you to generate a schema first, then an API that references it, then a UI that calls the API`),n.push(`# Project Tech Stack
|
|
91
|
-
${Se(o.techStack)}`);let r=Object.keys(o.techStack.dependencies).slice(0,30);r.length&&n.push(`# Key Dependencies
|
|
92
|
-
${r.join(", ")}`);let s=Ie(o.schemas);return s&&n.push(`# Project Schemas
|
|
93
|
-
${s}`),t.length&&n.push(`# Active Skills
|
|
94
|
-
Follow these skill instructions when applicable:
|
|
95
|
-
|
|
96
|
-
`+t.map(i=>`## Skill: ${i.frontmatter.name}
|
|
97
|
-
${i.frontmatter.description}
|
|
98
|
-
|
|
99
|
-
${i.instructions}`).join(`
|
|
100
|
-
|
|
101
|
-
---
|
|
102
|
-
|
|
103
|
-
`)),o.docs&&n.push(o.docs),o.projectInstructions&&n.push(`# Project Instructions
|
|
104
|
-
${o.projectInstructions}`),o.memoryContext&&n.push(o.memoryContext),n.push(`# Output Type: ${e}
|
|
105
|
-
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),n.join(`
|
|
106
|
-
|
|
107
|
-
`)}export{Re as a,dt as b,ut as c,Me as d,Ie as e,Oe as f,Ue as g,we as h,Ee as i,De as j,be as k,ee as l,N as m,Y as n,qe as o,ke as p,xe as q,Q as r,ze as s,Uo as t,Eo as u};
|
|
108
|
-
//# sourceMappingURL=chunk-HVC6FJNP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/providers/types.ts","../src/agent/context/schema.ts","../src/agent/context/context7.ts","../src/agent/outputs/types.ts","../src/agent/outputs/handlers.ts","../src/permissions/manager.ts","../src/permissions/types.ts","../src/memory/hierarchy.ts","../src/memory/context-builder.ts","../src/agent/tools/executor.ts","../src/agent/orchestrator.ts","../src/utils/async-queue.ts","../src/agent/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Provider abstraction ---\n\nexport interface GenerationMessage {\n role: \"user\" | \"assistant\" | \"system\"\n content: string\n}\n\nexport interface GenerationResult {\n content: string\n files: GeneratedFile[]\n followUp?: string // Agent may ask for more info\n tokensUsed?: number\n}\n\nexport interface GeneratedFile {\n path: string\n content: string\n language?: string\n description?: string\n}\n\nexport interface ProviderOptions {\n model?: string\n maxTokens?: number\n temperature?: number\n apiKey?: string\n}\n\nexport type StreamEvent =\n | { type: \"text_delta\"; text: string }\n | { type: \"tool_use_start\"; name: string; id: string }\n | { type: \"tool_use_delta\"; json: string }\n | { type: \"tool_use_end\"; name: string }\n | { type: \"done\"; result: GenerationResult }\n | { type: \"error\"; error: string }\n\n// --- Raw (agentic) API types ---\n\nexport interface AnthropicMessage {\n role: \"user\" | \"assistant\"\n content: string | ContentBlock[]\n}\n\nexport type ContentBlock =\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> }\n | { type: \"tool_result\"; tool_use_id: string; content: string; is_error?: boolean }\n\nexport interface RawGenerationResult {\n content: ContentBlock[]\n stop_reason: \"end_turn\" | \"tool_use\" | \"max_tokens\" | \"stop_sequence\"\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport interface AgentProvider {\n name: string\n generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult>\n stream?(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent>\n /** Low-level method returning raw content blocks for the agentic tool_result loop */\n generateRaw?(\n messages: AnthropicMessage[],\n systemPrompt: string,\n tools: Array<{ name: string; description: string; input_schema: Record<string, unknown> }>,\n options?: ProviderOptions\n ): Promise<RawGenerationResult>\n}\n\n// --- Agent configuration ---\n\nexport const agentConfigSchema = z.object({\n provider: z.enum([\"claude-code\", \"claude\", \"openai\", \"ollama\", \"custom\"]).default(\"claude-code\"),\n model: z.string().optional(),\n apiKey: z.string().optional(),\n skills: z.array(z.string()).default([]),\n output: z\n .object({\n dir: z.string().default(\"./generated\"),\n })\n .default({}),\n context7: z\n .object({\n enabled: z.boolean().default(true),\n apiKey: z.string().optional(),\n })\n .default({}),\n agentic: z\n .object({\n maxIterations: z.number().default(20),\n enabledTools: z.array(z.string()).default([\n \"create_files\", \"ask_user\", \"read_file\",\n \"search_files\", \"list_directory\", \"run_command\", \"edit_file\",\n ]),\n disabledTools: z.array(z.string()).default([]),\n })\n .default({}),\n})\n\nexport type AgentConfig = z.infer<typeof agentConfigSchema>\n\n// --- Output types ---\n\nexport const OUTPUT_TYPES = [\n \"component\",\n \"page\",\n \"api\",\n \"website\",\n \"document\",\n \"script\",\n \"config\",\n \"skill\",\n \"media\",\n \"report\",\n \"test\",\n \"workflow\",\n \"schema\",\n \"email\",\n \"diagram\",\n \"auto\",\n] as const\n\nexport type OutputType = (typeof OUTPUT_TYPES)[number]\n\nexport const outputTypeDescriptions: Record<OutputType, string> = {\n component: \"UI component (any framework)\",\n page: \"Full page or screen\",\n api: \"API endpoint, route handler, or service\",\n website: \"Multi-page website or app\",\n document: \"Markdown, documentation, or specification\",\n script: \"Standalone script or utility\",\n config: \"Configuration file or setup\",\n skill: \"Agent skill (SKILL.md format for skills.sh)\",\n media: \"Media generation prompt (image/audio/video description)\",\n report: \"Analysis report or audit\",\n test: \"Test suite, test fixtures, or test data\",\n workflow: \"CI/CD pipeline, GitHub Actions, or automation\",\n schema: \"Database schema, Zod validators, or GraphQL types\",\n email: \"Email template (React Email, MJML, HTML)\",\n diagram: \"Mermaid, D2, or PlantUML diagram\",\n auto: \"Auto-detect the best output type\",\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport fg from \"fast-glob\"\n\n// --- Schema awareness: detect DB schemas, API specs, env vars, configs ---\n\nexport interface ProjectSchemas {\n database?: DatabaseSchema\n api?: ApiSchema\n env?: EnvSchema\n models?: ModelFile[]\n}\n\nexport interface DatabaseSchema {\n type: string // prisma, drizzle, typeorm, etc.\n content: string\n tables?: string[]\n}\n\nexport interface ApiSchema {\n type: string // openapi, graphql, trpc, etc.\n content: string\n endpoints?: string[]\n}\n\nexport interface EnvSchema {\n variables: { key: string; description?: string; required: boolean }[]\n}\n\nexport interface ModelFile {\n path: string\n content: string\n type: string\n}\n\nconst SCHEMA_FILES: Record<string, { type: string; category: \"database\" | \"api\" | \"model\" }> = {\n \"prisma/schema.prisma\": { type: \"prisma\", category: \"database\" },\n \"drizzle/schema.ts\": { type: \"drizzle\", category: \"database\" },\n \"schema.graphql\": { type: \"graphql\", category: \"api\" },\n \"schema.gql\": { type: \"graphql\", category: \"api\" },\n \"openapi.yaml\": { type: \"openapi\", category: \"api\" },\n \"openapi.json\": { type: \"openapi\", category: \"api\" },\n \"swagger.yaml\": { type: \"openapi\", category: \"api\" },\n \"swagger.json\": { type: \"openapi\", category: \"api\" },\n}\n\nexport async function detectSchemas(cwd: string): Promise<ProjectSchemas> {\n const schemas: ProjectSchemas = {}\n\n // Find schema files\n const files = await fg.glob(\"**/*\", {\n cwd,\n deep: 4,\n ignore: [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.next/**\",\n \"**/target/**\",\n \"**/__pycache__/**\",\n \"**/vendor/**\",\n \"**/.git/**\",\n ],\n onlyFiles: true,\n })\n\n // Detect database schemas\n for (const [schemaFile, info] of Object.entries(SCHEMA_FILES)) {\n const match = files.find((f) => f.endsWith(schemaFile) || f === schemaFile)\n if (match && info.category === \"database\") {\n const content = await safeReadFile(path.resolve(cwd, match))\n if (content) {\n schemas.database = {\n type: info.type,\n content: truncate(content, 3000),\n tables: extractTableNames(content, info.type),\n }\n break\n }\n }\n }\n\n // Detect API schemas\n for (const [schemaFile, info] of Object.entries(SCHEMA_FILES)) {\n const match = files.find((f) => f.endsWith(schemaFile) || f === schemaFile)\n if (match && info.category === \"api\") {\n const content = await safeReadFile(path.resolve(cwd, match))\n if (content) {\n schemas.api = {\n type: info.type,\n content: truncate(content, 3000),\n }\n break\n }\n }\n }\n\n // Detect tRPC router\n if (!schemas.api) {\n const trpcRouter = files.find(\n (f) => f.includes(\"trpc\") && (f.endsWith(\"router.ts\") || f.endsWith(\"router.js\"))\n )\n if (trpcRouter) {\n const content = await safeReadFile(path.resolve(cwd, trpcRouter))\n if (content) {\n schemas.api = {\n type: \"trpc\",\n content: truncate(content, 3000),\n }\n }\n }\n }\n\n // Detect env variables\n const envExample = files.find(\n (f) => f === \".env.example\" || f === \".env.local.example\" || f === \".env.template\"\n )\n if (envExample) {\n const content = await safeReadFile(path.resolve(cwd, envExample))\n if (content) {\n schemas.env = parseEnvFile(content)\n }\n }\n\n // Detect model/type files\n const modelFiles = files.filter(\n (f) =>\n (f.includes(\"models\") || f.includes(\"types\") || f.includes(\"schemas\")) &&\n (f.endsWith(\".ts\") || f.endsWith(\".py\") || f.endsWith(\".rs\") || f.endsWith(\".go\"))\n )\n\n if (modelFiles.length) {\n schemas.models = []\n for (const mf of modelFiles.slice(0, 5)) {\n const content = await safeReadFile(path.resolve(cwd, mf))\n if (content) {\n schemas.models.push({\n path: mf,\n content: truncate(content, 2000),\n type: path.extname(mf).slice(1),\n })\n }\n }\n }\n\n return schemas\n}\n\nfunction extractTableNames(content: string, type: string): string[] {\n if (type === \"prisma\") {\n const matches = content.match(/model\\s+(\\w+)\\s*\\{/g)\n return matches ? matches.map((m) => m.replace(/model\\s+/, \"\").replace(/\\s*\\{/, \"\")) : []\n }\n return []\n}\n\nfunction parseEnvFile(content: string): EnvSchema {\n const lines = content.split(\"\\n\").filter((l) => l.trim() && !l.trim().startsWith(\"#\"))\n const variables = lines.map((line) => {\n const [keyPart] = line.split(\"=\")\n const key = keyPart.trim()\n const hasValue = line.includes(\"=\") && line.split(\"=\")[1]?.trim().length > 0\n return {\n key,\n required: !hasValue,\n }\n })\n return { variables }\n}\n\nasync function safeReadFile(filePath: string): Promise<string | null> {\n try {\n if (!existsSync(filePath)) return null\n return await fs.readFile(filePath, \"utf8\")\n } catch {\n return null\n }\n}\n\nfunction truncate(str: string, maxLen: number): string {\n if (str.length <= maxLen) return str\n return str.slice(0, maxLen) + \"\\n... (truncated)\"\n}\n\nexport function formatSchemas(schemas: ProjectSchemas): string {\n const sections: string[] = []\n\n if (schemas.database) {\n sections.push(\n `## Database Schema (${schemas.database.type})\\n` +\n (schemas.database.tables?.length\n ? `Tables: ${schemas.database.tables.join(\", \")}\\n`\n : \"\") +\n \"```\\n\" +\n schemas.database.content +\n \"\\n```\"\n )\n }\n\n if (schemas.api) {\n sections.push(\n `## API Schema (${schemas.api.type})\\n` + \"```\\n\" + schemas.api.content + \"\\n```\"\n )\n }\n\n if (schemas.env) {\n sections.push(\n `## Environment Variables\\n` +\n schemas.env.variables.map((v) => `- ${v.key}${v.required ? \" (required)\" : \"\"}`).join(\"\\n\")\n )\n }\n\n if (schemas.models?.length) {\n for (const model of schemas.models) {\n sections.push(\n `## Model: ${model.path}\\n` + \"```\" + model.type + \"\\n\" + model.content + \"\\n```\"\n )\n }\n }\n\n return sections.join(\"\\n\\n\")\n}\n","import fetch from \"node-fetch\"\nimport { logger } from \"@/utils/logger\"\nimport type { TechStack } from \"./tech-stack\"\n\n// --- Context7 integration: fetch up-to-date library documentation ---\n\nconst CONTEXT7_API = \"https://api.context7.com/v1\"\n\ninterface Context7Library {\n id: string\n name: string\n description?: string\n}\n\ninterface Context7Docs {\n libraryId: string\n content: string\n tokens: number\n}\n\nexport async function resolveLibraryId(\n libraryName: string,\n apiKey?: string\n): Promise<Context7Library | null> {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n }\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`\n\n const response = await fetch(`${CONTEXT7_API}/libraries/resolve`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ name: libraryName }),\n })\n\n if (!response.ok) return null\n\n const data = (await response.json()) as any\n if (data?.libraries?.length) {\n return data.libraries[0]\n }\n return null\n } catch {\n return null\n }\n}\n\nexport async function getLibraryDocs(\n libraryId: string,\n topic?: string,\n maxTokens: number = 5000,\n apiKey?: string\n): Promise<string | null> {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n }\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`\n\n const response = await fetch(`${CONTEXT7_API}/libraries/${encodeURIComponent(libraryId)}/docs`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ topic, maxTokens }),\n })\n\n if (!response.ok) return null\n\n const data = (await response.json()) as any\n return data?.content || null\n } catch {\n return null\n }\n}\n\nexport async function gatherContext7Docs(\n stack: TechStack,\n topic: string,\n apiKey?: string\n): Promise<string> {\n const relevantLibraries: string[] = []\n\n // Gather the most important frameworks and libraries\n for (const fw of stack.frameworks.slice(0, 3)) {\n relevantLibraries.push(fw.name)\n }\n\n // Add key dependencies\n const priorityDeps = [\n \"react\",\n \"vue\",\n \"svelte\",\n \"angular\",\n \"next\",\n \"nuxt\",\n \"express\",\n \"fastify\",\n \"hono\",\n \"prisma\",\n \"drizzle-orm\",\n \"tailwindcss\",\n \"shadcn\",\n \"@tanstack/react-query\",\n \"zod\",\n \"trpc\",\n ]\n\n for (const dep of priorityDeps) {\n if (stack.dependencies[dep] || stack.devDependencies[dep]) {\n if (!relevantLibraries.includes(dep)) {\n relevantLibraries.push(dep)\n }\n }\n }\n\n const docs: string[] = []\n\n for (const lib of relevantLibraries.slice(0, 5)) {\n const library = await resolveLibraryId(lib, apiKey)\n if (library) {\n const content = await getLibraryDocs(library.id, topic, 3000, apiKey)\n if (content) {\n docs.push(`## ${library.name} Documentation\\n${content}`)\n }\n }\n }\n\n if (!docs.length) {\n return \"\"\n }\n\n return `# Relevant Library Documentation (via Context7)\\n\\n${docs.join(\"\\n\\n---\\n\\n\")}`\n}\n","import type { OutputType } from \"../providers/types\"\n\n// --- Output type resolution and file path mapping ---\n\nexport interface OutputConfig {\n type: OutputType\n baseDir: string\n filePatterns: string[]\n description: string\n}\n\nexport const OUTPUT_CONFIGS: Record<string, OutputConfig> = {\n component: {\n type: \"component\",\n baseDir: \"src/components\",\n filePatterns: [\"*.tsx\", \"*.vue\", \"*.svelte\", \"*.jsx\", \"*.ts\"],\n description: \"UI component\",\n },\n page: {\n type: \"page\",\n baseDir: \"src/app\",\n filePatterns: [\"*.tsx\", \"*.vue\", \"*.svelte\", \"*.jsx\", \"*.astro\"],\n description: \"Page or screen\",\n },\n api: {\n type: \"api\",\n baseDir: \"src/api\",\n filePatterns: [\"*.ts\", \"*.js\", \"*.py\", \"*.go\", \"*.rs\"],\n description: \"API route or endpoint\",\n },\n website: {\n type: \"website\",\n baseDir: \".\",\n filePatterns: [\"*\"],\n description: \"Multi-file website\",\n },\n document: {\n type: \"document\",\n baseDir: \"docs\",\n filePatterns: [\"*.md\", \"*.mdx\", \"*.txt\", \"*.rst\"],\n description: \"Documentation\",\n },\n script: {\n type: \"script\",\n baseDir: \"scripts\",\n filePatterns: [\"*.ts\", \"*.js\", \"*.py\", \"*.sh\", \"*.go\"],\n description: \"Standalone script\",\n },\n config: {\n type: \"config\",\n baseDir: \".\",\n filePatterns: [\"*.json\", \"*.yaml\", \"*.yml\", \"*.toml\", \"*.env\"],\n description: \"Configuration file\",\n },\n skill: {\n type: \"skill\",\n baseDir: \".skills\",\n filePatterns: [\"SKILL.md\"],\n description: \"Agent skill (SKILL.md)\",\n },\n media: {\n type: \"media\",\n baseDir: \"media\",\n filePatterns: [\"*.md\", \"*.json\", \"*.txt\"],\n description: \"Media generation prompt/description\",\n },\n report: {\n type: \"report\",\n baseDir: \"reports\",\n filePatterns: [\"*.md\", \"*.html\", \"*.json\"],\n description: \"Analysis report\",\n },\n test: {\n type: \"test\",\n baseDir: \"src\",\n filePatterns: [\"*.test.ts\", \"*.test.tsx\", \"*.spec.ts\", \"*.test.js\", \"*.test.py\", \"*.test.go\"],\n description: \"Test suite or fixture\",\n },\n workflow: {\n type: \"workflow\",\n baseDir: \".github/workflows\",\n filePatterns: [\"*.yml\", \"*.yaml\"],\n description: \"CI/CD pipeline or automation\",\n },\n schema: {\n type: \"schema\",\n baseDir: \"src\",\n filePatterns: [\"*.ts\", \"*.prisma\", \"*.graphql\", \"*.gql\", \"*.py\"],\n description: \"Database schema, validators, or types\",\n },\n email: {\n type: \"email\",\n baseDir: \"src/emails\",\n filePatterns: [\"*.tsx\", \"*.jsx\", \"*.html\", \"*.mjml\"],\n description: \"Email template\",\n },\n diagram: {\n type: \"diagram\",\n baseDir: \"docs\",\n filePatterns: [\"*.md\", \"*.mmd\", \"*.d2\", \"*.puml\"],\n description: \"Architecture or data diagram\",\n },\n}\n\nexport function resolveOutputType(\n userHint: string | undefined,\n taskDescription: string\n): OutputType {\n if (userHint && userHint !== \"auto\") {\n return userHint as OutputType\n }\n\n const lower = taskDescription.toLowerCase()\n\n // Pattern matching for output type detection\n const patterns: [RegExp, OutputType][] = [\n [/\\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\\b/i, \"component\"],\n [/\\b(page|screen|view|route|layout|dashboard|landing)\\b/i, \"page\"],\n [/\\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\\b/i, \"api\"],\n [/\\b(website|site|web app|landing page|portfolio|blog)\\b/i, \"website\"],\n [/\\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\\b/i, \"document\"],\n [/\\b(script|cli|command|tool|utility|migration|seed|cron)\\b/i, \"script\"],\n [/\\b(config|configuration|setup|env|settings)\\b/i, \"config\"],\n [/\\b(skill|agent skill|skill\\.md)\\b/i, \"skill\"],\n [/\\b(video|audio|image|media|animation|thumbnail|podcast)\\b/i, \"media\"],\n [/\\b(report|audit|analysis|review|assessment|benchmark)\\b/i, \"report\"],\n [/\\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\\b/i, \"test\"],\n [/\\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\\/cd)\\b/i, \"workflow\"],\n [/\\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\\b/i, \"schema\"],\n [/\\b(email|newsletter|transactional|invite|welcome email|notification email)\\b/i, \"email\"],\n [/\\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\\b/i, \"diagram\"],\n ]\n\n for (const [pattern, type] of patterns) {\n if (pattern.test(lower)) {\n return type\n }\n }\n\n return \"component\" // Default fallback\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport type { GeneratedFile } from \"../providers/types\"\nimport type { TechStack } from \"../context/tech-stack\"\nimport { OUTPUT_CONFIGS } from \"./types\"\nimport { logger } from \"@/utils/logger\"\nimport { globalHooks } from \"@/hooks\"\nimport { globalPermissions } from \"@/permissions\"\n\n// --- Write generated files to disk ---\n\nexport interface WriteOptions {\n cwd: string\n overwrite: boolean\n dryRun: boolean\n outputDir?: string\n}\n\nexport interface WriteResult {\n written: string[]\n skipped: string[]\n errors: string[]\n}\n\nexport async function writeGeneratedFiles(\n files: GeneratedFile[],\n options: WriteOptions\n): Promise<WriteResult> {\n const result: WriteResult = { written: [], skipped: [], errors: [] }\n\n for (const file of files) {\n const filePath = path.isAbsolute(file.path)\n ? file.path\n : path.resolve(options.cwd, options.outputDir || \"\", file.path)\n\n try {\n // pre:file-write hook — can block or modify file content\n let fileContent = file.content\n if (globalHooks.has(\"pre:file-write\")) {\n const hookResult = await globalHooks.execute(\"pre:file-write\", {\n event: \"pre:file-write\",\n file: filePath,\n fileContent,\n cwd: options.cwd,\n })\n if (hookResult.blocked) {\n result.skipped.push(filePath)\n continue\n }\n if (hookResult.modified?.fileContent) {\n fileContent = String(hookResult.modified.fileContent)\n }\n }\n\n // Permissions check — can allow, deny, or skip (plan mode)\n const relativePath = path.relative(options.cwd, filePath)\n const permission = await globalPermissions.checkFileWrite(relativePath)\n if (permission === \"deny\") {\n result.skipped.push(filePath)\n continue\n }\n if (permission === \"skip\") {\n // Plan mode: record what would be written but don't write\n result.written.push(filePath)\n continue\n }\n\n if (existsSync(filePath) && !options.overwrite) {\n result.skipped.push(filePath)\n continue\n }\n\n if (options.dryRun) {\n result.written.push(filePath)\n continue\n }\n\n // Create directory structure\n const dir = path.dirname(filePath)\n await fs.mkdir(dir, { recursive: true })\n\n // Write file\n await fs.writeFile(filePath, fileContent, \"utf8\")\n result.written.push(filePath)\n\n // post:file-write hook — post-processing (format, git add, etc.)\n if (globalHooks.has(\"post:file-write\")) {\n await globalHooks.execute(\"post:file-write\", {\n event: \"post:file-write\",\n file: filePath,\n fileContent,\n cwd: options.cwd,\n })\n }\n } catch (error: any) {\n result.errors.push(`${filePath}: ${error.message}`)\n }\n }\n\n return result\n}\n\nexport function resolveOutputDir(\n outputType: string,\n stack: TechStack,\n customDir?: string\n): string {\n if (customDir) return customDir\n\n const config = OUTPUT_CONFIGS[outputType]\n if (!config) return \"generated\"\n\n // Adjust base dir based on project structure\n let baseDir = config.baseDir\n\n if (outputType === \"component\") {\n // Detect existing component directory\n if (stack.srcDir) {\n baseDir = `${stack.srcDir}/components`\n } else {\n baseDir = \"components\"\n }\n }\n\n if (outputType === \"page\") {\n // Detect app dir structure\n const hasAppDir =\n stack.frameworks.find((f) => f.name === \"nextjs\") && stack.srcDir\n if (hasAppDir) {\n baseDir = `${stack.srcDir}/app`\n }\n }\n\n if (outputType === \"api\") {\n const isNextJs = stack.frameworks.find((f) => f.name === \"nextjs\")\n if (isNextJs) {\n baseDir = stack.srcDir ? `${stack.srcDir}/app/api` : \"app/api\"\n }\n }\n\n if (outputType === \"test\") {\n if (stack.testing.includes(\"vitest\") || stack.testing.includes(\"jest\")) {\n baseDir = stack.srcDir || \"src\"\n }\n }\n\n if (outputType === \"workflow\") {\n baseDir = \".github/workflows\"\n }\n\n if (outputType === \"schema\") {\n if (stack.databases.includes(\"prisma\")) {\n baseDir = \"prisma\"\n } else if (stack.srcDir) {\n baseDir = `${stack.srcDir}/schemas`\n }\n }\n\n if (outputType === \"email\") {\n baseDir = stack.srcDir ? `${stack.srcDir}/emails` : \"emails\"\n }\n\n return baseDir\n}\n","// --- Permission Manager: checking and inline prompts for file writes ---\n\nimport prompts from \"prompts\"\nimport chalk from \"chalk\"\nimport type { PermissionMode, PermissionConfig } from \"./types\"\nimport { permissionConfigSchema } from \"./types\"\nimport { debug } from \"@/observability\"\n\nexport type PermissionAction = \"allow\" | \"deny\" | \"skip\"\n\n/**\n * Simple glob matching: supports *, **, and ? wildcards.\n */\nfunction matchGlob(filePath: string, pattern: string): boolean {\n // Convert glob pattern to regex\n let regex = pattern\n .replace(/\\./g, \"\\\\.\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \".*\")\n .replace(/\\?/g, \"[^/]\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\nexport class PermissionManager {\n private mode: PermissionMode\n private allowPatterns: string[]\n private denyPatterns: string[]\n private confirmPatterns: string[]\n private autoAllowAll = false // set when user picks \"all\" in interactive prompt\n\n constructor(config?: Partial<PermissionConfig>) {\n const parsed = permissionConfigSchema.parse(config || {})\n this.mode = parsed.mode\n this.allowPatterns = parsed.allow\n this.denyPatterns = parsed.deny\n this.confirmPatterns = parsed.confirm\n }\n\n getMode(): PermissionMode {\n return this.mode\n }\n\n setMode(mode: PermissionMode): void {\n this.mode = mode\n this.autoAllowAll = false // reset on mode change\n debug.context(\"permissions\", `mode set to ${mode}`)\n }\n\n /**\n * Check whether a file write should proceed.\n */\n async checkFileWrite(filePath: string): Promise<PermissionAction> {\n debug.context(\"permissions\", `checking write: ${filePath} (mode: ${this.mode})`)\n\n // Always deny files matching deny patterns\n if (this.matchesAny(filePath, this.denyPatterns)) {\n debug.context(\"permissions\", `denied by pattern: ${filePath}`)\n return \"deny\"\n }\n\n switch (this.mode) {\n case \"yolo\":\n return \"allow\"\n\n case \"plan\":\n return \"skip\"\n\n case \"acceptEdits\":\n return \"allow\"\n\n case \"default\":\n // If user already chose \"all\", auto-allow\n if (this.autoAllowAll) return \"allow\"\n\n // Auto-allow if matches allow patterns\n if (this.matchesAny(filePath, this.allowPatterns)) {\n return \"allow\"\n }\n\n // Must confirm if matches confirm patterns or no patterns match\n return this.promptUser(filePath)\n\n default:\n return \"allow\"\n }\n }\n\n /**\n * Check whether a command should proceed (for pre:command hook).\n */\n async checkCommand(command: string): Promise<\"allow\" | \"deny\"> {\n if (this.mode === \"yolo\") return \"allow\"\n if (this.mode === \"plan\") return \"deny\"\n // For default and acceptEdits, commands are allowed\n return \"allow\"\n }\n\n private matchesAny(filePath: string, patterns: string[]): boolean {\n return patterns.some((p) => matchGlob(filePath, p))\n }\n\n private async promptUser(filePath: string): Promise<PermissionAction> {\n const { action } = await prompts({\n type: \"select\",\n name: \"action\",\n message: `Write file ${chalk.cyan(filePath)}?`,\n choices: [\n { title: \"Yes\", value: \"allow\" },\n { title: \"No\", value: \"deny\" },\n { title: \"All (allow remaining)\", value: \"all\" },\n { title: \"Skip\", value: \"skip\" },\n ],\n initial: 0,\n })\n\n if (action === \"all\") {\n this.autoAllowAll = true\n return \"allow\"\n }\n\n return action || \"deny\"\n }\n}\n\nexport const globalPermissions = new PermissionManager()\n","// --- Permission mode definitions and config schema ---\n\nimport { z } from \"zod\"\n\nexport const PERMISSION_MODES = [\"default\", \"acceptEdits\", \"plan\", \"yolo\"] as const\nexport type PermissionMode = (typeof PERMISSION_MODES)[number]\n\nexport const permissionModeSchema = z.enum(PERMISSION_MODES)\n\nexport interface PermissionRule {\n pattern: string\n action: \"allow\" | \"deny\" | \"confirm\"\n}\n\nexport const permissionConfigSchema = z.object({\n mode: permissionModeSchema.default(\"default\"),\n allow: z.array(z.string()).default([]),\n deny: z.array(z.string()).default([]),\n confirm: z.array(z.string()).default([]),\n})\n\nexport type PermissionConfig = z.infer<typeof permissionConfigSchema>\n","// --- Memory Hierarchy: user-level + project-level layered memory ---\n\nimport os from \"os\"\nimport { Memory, type UserPreference, type MemoryEntry, type LearnedPattern, type MemoryStore } from \"@/runtime/memory\"\n\nconst USER_MEMORY_DIR = os.homedir()\n\nexport class MemoryHierarchy {\n private userMemory: Memory\n private projectMemory: Memory\n\n constructor(private cwd: string) {\n // User-level memory at ~/.agentx/memory.json\n this.userMemory = new Memory(USER_MEMORY_DIR)\n // Project-level memory at <cwd>/.agentx/memory.json\n this.projectMemory = new Memory(cwd)\n }\n\n async load(): Promise<void> {\n await Promise.all([this.userMemory.load(), this.projectMemory.load()])\n }\n\n async save(): Promise<void> {\n await Promise.all([this.userMemory.save(), this.projectMemory.save()])\n }\n\n /**\n * Build merged memory context for the agent. Project overrides user.\n */\n buildMemoryContext(task: string): string {\n const userCtx = this.userMemory.buildMemoryContext(task)\n const projectCtx = this.projectMemory.buildMemoryContext(task)\n\n if (!userCtx && !projectCtx) return \"\"\n\n const sections: string[] = []\n if (projectCtx) {\n sections.push(projectCtx)\n }\n if (userCtx) {\n // Prefix user-level context to distinguish it\n sections.push(\n userCtx.replace(\n \"# Memory (learned from past interactions)\",\n \"# Global Memory (cross-project patterns)\"\n )\n )\n }\n\n return sections.join(\"\\n\\n\")\n }\n\n /**\n * Learn a preference at user level (global).\n */\n async learnPreference(key: string, value: string, source: string): Promise<void> {\n await this.userMemory.learnPreference(key, value, source)\n }\n\n /**\n * Record a generation at project level (task-specific).\n */\n async recordGeneration(\n entry: Omit<MemoryEntry, \"id\" | \"timestamp\" | \"type\"> & { type?: MemoryEntry[\"type\"] }\n ): Promise<string> {\n return this.projectMemory.recordGeneration(entry)\n }\n\n /**\n * Get combined preferences (project overrides user for same keys).\n */\n getPreferences(): UserPreference[] {\n const userPrefs = this.userMemory.getPreferences()\n const projectPrefs = this.projectMemory.getPreferences()\n\n const merged = new Map<string, UserPreference>()\n for (const p of userPrefs) {\n merged.set(p.key, p)\n }\n for (const p of projectPrefs) {\n merged.set(p.key, p) // project overrides\n }\n return Array.from(merged.values())\n }\n\n /**\n * Get combined patterns from both levels.\n */\n getPatterns(): LearnedPattern[] {\n const userPatterns = this.userMemory.getPatterns()\n const projectPatterns = this.projectMemory.getPatterns()\n return [...projectPatterns, ...userPatterns]\n }\n\n /**\n * Get stats from both levels.\n */\n getStats(): { user: MemoryStore[\"stats\"]; project: MemoryStore[\"stats\"] } {\n return {\n user: this.userMemory.getStats(),\n project: this.projectMemory.getStats(),\n }\n }\n\n /**\n * Get recent generations from project level.\n */\n getRecentGenerations(limit = 10): MemoryEntry[] {\n return this.projectMemory.getRecentGenerations(limit)\n }\n}\n","// --- Context Builder: smart assembly with @-import resolution and relevance trimming ---\n\nimport { existsSync, readFileSync } from \"fs\"\nimport path from \"path\"\nimport { buildIndex, scoreAll } from \"./bm25\"\n\ninterface ContextSection {\n label: string\n content: string\n priority: number // higher = more important\n}\n\n/**\n * Resolve @-imports in content: replace @path/to/file with file contents.\n */\nexport function resolveAtImports(content: string, basedir: string): string {\n return content.replace(/@([\\w./-]+)/g, (match, filePath: string) => {\n const resolved = path.resolve(basedir, filePath)\n if (existsSync(resolved)) {\n try {\n return readFileSync(resolved, \"utf8\")\n } catch {\n return match // keep original if read fails\n }\n }\n return match // keep original if file doesn't exist\n })\n}\n\n/**\n * Load project instructions from SHADXN.md or CLAUDE.md.\n */\nexport function loadProjectInstructions(cwd: string): string {\n const candidates = [\"SHADXN.md\", \"CLAUDE.md\"]\n for (const name of candidates) {\n const filePath = path.join(cwd, name)\n if (existsSync(filePath)) {\n try {\n let content = readFileSync(filePath, \"utf8\")\n content = resolveAtImports(content, cwd)\n return content\n } catch {\n // skip if unreadable\n }\n }\n }\n return \"\"\n}\n\n/**\n * Estimate token count from content (rough chars-to-tokens).\n */\nfunction estimateTokens(content: string): number {\n return Math.ceil(content.length / 4)\n}\n\nexport class ContextBuilder {\n private sections: ContextSection[] = []\n\n addSection(label: string, content: string, priority = 50): void {\n if (!content.trim()) return\n this.sections.push({ label, content, priority })\n }\n\n /**\n * Build final context, trimming lowest-relevance sections if over budget.\n */\n buildContext(task: string, maxTokens = 12000): string {\n if (this.sections.length === 0) return \"\"\n\n // Score each section via BM25\n const docs = this.sections.map((s) => s.content)\n const index = buildIndex(docs)\n const bm25Results = scoreAll(task, index)\n const scoreMap = new Map(bm25Results.map((r) => [r.docIndex, r.score]))\n\n const scored = this.sections.map((s, i) => ({\n ...s,\n relevance: scoreMap.get(i) ?? 0,\n tokens: estimateTokens(s.content),\n }))\n\n // Sort by combined score (priority weight + relevance)\n scored.sort(\n (a, b) => b.priority + b.relevance * 100 - (a.priority + a.relevance * 100)\n )\n\n // Include sections until budget is exceeded\n const included: typeof scored = []\n let totalTokens = 0\n\n for (const section of scored) {\n if (totalTokens + section.tokens > maxTokens && included.length > 0) {\n // Skip this section — over budget\n continue\n }\n included.push(section)\n totalTokens += section.tokens\n }\n\n return included.map((s) => s.content).join(\"\\n\\n\")\n }\n}\n","// --- Tool Executor: runs tool calls with permission and hook integration ---\n\nimport { promises as fs } from \"fs\"\nimport path from \"path\"\nimport { execa } from \"execa\"\nimport fg from \"fast-glob\"\nimport { globalPermissions } from \"@/permissions\"\nimport { globalHooks } from \"@/hooks\"\nimport { debug } from \"@/observability\"\nimport type { GeneratedFile } from \"../providers/types\"\n\nexport interface ToolCallInput {\n name: string\n id: string\n input: Record<string, unknown>\n}\n\nexport interface ToolResult {\n tool_use_id: string\n content: string\n is_error?: boolean\n /** Files collected from create_files calls */\n files?: GeneratedFile[]\n /** Question from ask_user calls */\n followUp?: string\n}\n\nexport interface ToolExecutorOptions {\n interactive?: boolean\n overwrite?: boolean\n dryRun?: boolean\n}\n\nexport class ToolExecutor {\n private cwd: string\n private options: ToolExecutorOptions\n\n constructor(cwd: string, options: ToolExecutorOptions = {}) {\n this.cwd = cwd\n this.options = options\n }\n\n async execute(call: ToolCallInput): Promise<ToolResult> {\n debug.context(\"tool-executor\", `executing: ${call.name}`)\n\n // pre:tool-call hook\n if (globalHooks.has(\"pre:tool-call\")) {\n const hookResult = await globalHooks.execute(\"pre:tool-call\", {\n event: \"pre:tool-call\" as any,\n toolName: call.name,\n toolInput: call.input,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `Tool ${call.name} blocked by pre:tool-call hook`,\n is_error: true,\n }\n }\n }\n\n let result: ToolResult\n\n try {\n switch (call.name) {\n case \"read_file\":\n result = await this.readFile(call)\n break\n case \"search_files\":\n result = await this.searchFiles(call)\n break\n case \"list_directory\":\n result = await this.listDirectory(call)\n break\n case \"run_command\":\n result = await this.runCommand(call)\n break\n case \"edit_file\":\n result = await this.editFile(call)\n break\n case \"create_files\":\n result = await this.createFiles(call)\n break\n case \"ask_user\":\n result = await this.askUser(call)\n break\n case \"spawn_agent\":\n result = await this.spawnAgent(call)\n break\n default:\n result = {\n tool_use_id: call.id,\n content: `Unknown tool: ${call.name}`,\n is_error: true,\n }\n }\n } catch (error: any) {\n result = {\n tool_use_id: call.id,\n content: `Error executing ${call.name}: ${error.message}`,\n is_error: true,\n }\n }\n\n // post:tool-call hook\n if (globalHooks.has(\"post:tool-call\")) {\n await globalHooks.execute(\"post:tool-call\", {\n event: \"post:tool-call\" as any,\n toolName: call.name,\n toolInput: call.input,\n toolResult: result.content,\n cwd: this.cwd,\n })\n }\n\n return result\n }\n\n private async readFile(call: ToolCallInput): Promise<ToolResult> {\n const filePath = String(call.input.path || \"\")\n const maxLines = Number(call.input.max_lines) || 500\n const absPath = path.resolve(this.cwd, filePath)\n\n const content = await fs.readFile(absPath, \"utf8\")\n const lines = content.split(\"\\n\")\n const truncated = lines.length > maxLines\n const output = truncated\n ? lines.slice(0, maxLines).join(\"\\n\") + `\\n\\n... (truncated, ${lines.length - maxLines} more lines)`\n : content\n\n return {\n tool_use_id: call.id,\n content: output,\n }\n }\n\n private async searchFiles(call: ToolCallInput): Promise<ToolResult> {\n const pattern = String(call.input.pattern || \"**/*\")\n const contentRegex = call.input.content_regex ? String(call.input.content_regex) : undefined\n const maxResults = Number(call.input.max_results) || 50\n\n const files = await fg(pattern, {\n cwd: this.cwd,\n ignore: [\"node_modules/**\", \".git/**\", \"dist/**\", \".next/**\"],\n dot: false,\n })\n\n if (!contentRegex) {\n const limited = files.slice(0, maxResults)\n return {\n tool_use_id: call.id,\n content: limited.length\n ? limited.join(\"\\n\") + (files.length > maxResults ? `\\n\\n... (${files.length - maxResults} more files)` : \"\")\n : \"No files matched the pattern.\",\n }\n }\n\n // Search content within matched files\n const regex = new RegExp(contentRegex, \"gm\")\n const results: string[] = []\n\n for (const file of files) {\n if (results.length >= maxResults) break\n try {\n const content = await fs.readFile(path.resolve(this.cwd, file), \"utf8\")\n const lines = content.split(\"\\n\")\n for (let i = 0; i < lines.length; i++) {\n if (results.length >= maxResults) break\n if (regex.test(lines[i])) {\n results.push(`${file}:${i + 1}: ${lines[i]}`)\n }\n regex.lastIndex = 0\n }\n } catch {\n // Skip unreadable files\n }\n }\n\n return {\n tool_use_id: call.id,\n content: results.length\n ? results.join(\"\\n\")\n : \"No matches found.\",\n }\n }\n\n private async listDirectory(call: ToolCallInput): Promise<ToolResult> {\n const dirPath = String(call.input.path || \".\")\n const recursive = Boolean(call.input.recursive)\n const maxDepth = Number(call.input.max_depth) || 3\n const absPath = path.resolve(this.cwd, dirPath)\n\n if (recursive) {\n const pattern = \"**/*\"\n const entries = await fg(pattern, {\n cwd: absPath,\n onlyFiles: false,\n markDirectories: true,\n deep: maxDepth,\n ignore: [\"node_modules/**\", \".git/**\", \"dist/**\", \".next/**\"],\n })\n return {\n tool_use_id: call.id,\n content: entries.length ? entries.join(\"\\n\") : \"Empty directory.\",\n }\n }\n\n const entries = await fs.readdir(absPath, { withFileTypes: true })\n const formatted = entries.map((e) =>\n e.isDirectory() ? `${e.name}/` : e.name\n )\n\n return {\n tool_use_id: call.id,\n content: formatted.length ? formatted.join(\"\\n\") : \"Empty directory.\",\n }\n }\n\n private async runCommand(call: ToolCallInput): Promise<ToolResult> {\n const command = String(call.input.command || \"\")\n const timeout = Number(call.input.timeout) || 30_000\n\n // Check permissions\n const permission = await globalPermissions.checkCommand(command)\n if (permission === \"deny\") {\n return {\n tool_use_id: call.id,\n content: `Command blocked by permissions (mode: ${globalPermissions.getMode()}): ${command}`,\n is_error: true,\n }\n }\n\n // pre:command hook\n if (globalHooks.has(\"pre:command\")) {\n const hookResult = await globalHooks.execute(\"pre:command\", {\n event: \"pre:command\",\n command,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `Command blocked by pre:command hook: ${command}`,\n is_error: true,\n }\n }\n }\n\n const result = await execa(\"sh\", [\"-c\", command], {\n cwd: this.cwd,\n timeout,\n reject: false,\n stdin: \"ignore\",\n })\n\n const output = [result.stdout, result.stderr].filter(Boolean).join(\"\\n\")\n const truncated = output.length > 10_000\n ? output.slice(0, 10_000) + \"\\n\\n... (output truncated)\"\n : output\n\n if (result.exitCode !== 0) {\n return {\n tool_use_id: call.id,\n content: `Command exited with code ${result.exitCode}:\\n${truncated}`,\n is_error: true,\n }\n }\n\n return {\n tool_use_id: call.id,\n content: truncated || \"(no output)\",\n }\n }\n\n private async editFile(call: ToolCallInput): Promise<ToolResult> {\n const filePath = String(call.input.path || \"\")\n const edits = call.input.edits as Array<{ old_text: string; new_text: string }> | undefined\n const absPath = path.resolve(this.cwd, filePath)\n\n if (!edits || edits.length === 0) {\n return {\n tool_use_id: call.id,\n content: \"No edits provided.\",\n is_error: true,\n }\n }\n\n // Check write permission\n const permission = await globalPermissions.checkFileWrite(filePath)\n if (permission === \"deny\") {\n return {\n tool_use_id: call.id,\n content: `File write blocked by permissions: ${filePath}`,\n is_error: true,\n }\n }\n if (permission === \"skip\") {\n return {\n tool_use_id: call.id,\n content: `File write skipped (plan mode): ${filePath}`,\n }\n }\n\n // pre:file-write hook\n if (globalHooks.has(\"pre:file-write\")) {\n const hookResult = await globalHooks.execute(\"pre:file-write\", {\n event: \"pre:file-write\",\n file: absPath,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `File edit blocked by pre:file-write hook: ${filePath}`,\n is_error: true,\n }\n }\n }\n\n let content = await fs.readFile(absPath, \"utf8\")\n const applied: string[] = []\n\n for (const edit of edits) {\n if (content.includes(edit.old_text)) {\n content = content.replace(edit.old_text, edit.new_text)\n applied.push(`Replaced: \"${edit.old_text.slice(0, 40)}...\"`)\n } else {\n applied.push(`Not found: \"${edit.old_text.slice(0, 40)}...\"`)\n }\n }\n\n if (!this.options.dryRun) {\n await fs.writeFile(absPath, content, \"utf8\")\n }\n\n // post:file-write hook\n if (globalHooks.has(\"post:file-write\")) {\n await globalHooks.execute(\"post:file-write\", {\n event: \"post:file-write\",\n file: absPath,\n fileContent: content,\n cwd: this.cwd,\n })\n }\n\n return {\n tool_use_id: call.id,\n content: `Edited ${filePath}:\\n${applied.join(\"\\n\")}`,\n }\n }\n\n private async createFiles(call: ToolCallInput): Promise<ToolResult> {\n const input = call.input as {\n files?: GeneratedFile[]\n summary?: string\n }\n\n const files = input.files || []\n\n return {\n tool_use_id: call.id,\n content: input.summary || `Queued ${files.length} file(s) for creation.`,\n files,\n }\n }\n\n private async spawnAgent(call: ToolCallInput): Promise<ToolResult> {\n const agentId = String(call.input.agent_id || \"\")\n const prompt = String(call.input.prompt || \"\")\n const timeoutSeconds = Number(call.input.timeout_seconds) || 300\n\n if (!agentId || !prompt) {\n return {\n tool_use_id: call.id,\n content: \"agent_id and prompt are required.\",\n is_error: true,\n }\n }\n\n try {\n // Dynamically import to avoid circular dependency\n const { SubAgentManager } = await import(\"@/agents/subagent\")\n\n // Get the global registry from the daemon (if running)\n const { getGlobalRegistry } = await import(\"@/agents/registry\")\n const registry = getGlobalRegistry()\n\n if (!registry) {\n return {\n tool_use_id: call.id,\n content: \"Sub-agent spawning requires the daemon to be running.\",\n is_error: true,\n }\n }\n\n const manager = new SubAgentManager(registry)\n const result = await manager.spawn({\n targetAgentId: agentId,\n prompt,\n parentAgentId: \"orchestrator\",\n timeout: timeoutSeconds * 1000,\n })\n\n if (result.success) {\n return {\n tool_use_id: call.id,\n content: `Sub-agent \"${agentId}\" completed (${Math.round(result.duration / 1000)}s):\\n\\n${result.content}`,\n }\n } else {\n return {\n tool_use_id: call.id,\n content: `Sub-agent \"${agentId}\" failed: ${result.error}`,\n is_error: true,\n }\n }\n } catch (error: any) {\n return {\n tool_use_id: call.id,\n content: `Failed to spawn sub-agent: ${error.message}`,\n is_error: true,\n }\n }\n }\n\n private async askUser(call: ToolCallInput): Promise<ToolResult> {\n const question = String(call.input.question || \"\")\n const options = call.input.options as string[] | undefined\n\n let followUp = question\n if (options?.length) {\n followUp += `\\nOptions: ${options.join(\", \")}`\n }\n\n return {\n tool_use_id: call.id,\n content: \"Question sent to user.\",\n followUp,\n }\n }\n}\n","// --- Agentic Orchestrator: tool_result feedback loop ---\n\nimport type {\n AgentProvider,\n GenerationMessage,\n GeneratedFile,\n ProviderOptions,\n AnthropicMessage,\n ContentBlock,\n RawGenerationResult,\n} from \"./providers/types\"\nimport { ToolExecutor, type ToolResult } from \"./tools\"\nimport { getAnthropicTools, formatToolsForSystemPrompt } from \"./tools\"\nimport { debug } from \"@/observability\"\n\nexport interface AgenticLoopOptions {\n provider: AgentProvider\n systemPrompt: string\n messages: GenerationMessage[]\n providerOptions: ProviderOptions\n cwd: string\n maxIterations?: number\n enabledTools?: string[]\n interactive?: boolean\n overwrite?: boolean\n dryRun?: boolean\n onProgress?: (event: AgenticProgressEvent) => void\n}\n\nexport type AgenticProgressEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"tool_call\"; name: string; id: string; input: Record<string, unknown> }\n | { type: \"tool_result\"; name: string; id: string; content: string; is_error?: boolean }\n | { type: \"text_delta\"; text: string }\n | { type: \"files_created\"; files: GeneratedFile[] }\n | { type: \"complete\"; iterations: number; totalTokens: number }\n\nexport interface AgenticResult {\n files: GeneratedFile[]\n content: string\n followUp?: string\n tokensUsed: number\n iterations: number\n}\n\n/**\n * Run the agentic tool_result loop.\n * The LLM decides what tools to call (read files, search, edit, etc.)\n * and we feed results back until it signals completion.\n */\nexport async function runAgenticLoop(options: AgenticLoopOptions): Promise<AgenticResult> {\n const {\n provider,\n systemPrompt,\n messages: inputMessages,\n providerOptions,\n cwd,\n maxIterations = 20,\n enabledTools,\n interactive = true,\n overwrite = false,\n dryRun = false,\n onProgress,\n } = options\n\n // Check if provider supports generateRaw\n if (!provider.generateRaw) {\n return runLegacyLoop(options)\n }\n\n const executor = new ToolExecutor(cwd, { interactive, overwrite, dryRun })\n const tools = getAnthropicTools(enabledTools)\n\n // Convert GenerationMessage[] to AnthropicMessage[] (strip system messages)\n const anthropicMessages: AnthropicMessage[] = inputMessages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const allFiles: GeneratedFile[] = []\n let totalTokens = 0\n let textContent = \"\"\n let followUp: string | undefined\n let iteration = 0\n\n while (iteration < maxIterations) {\n iteration++\n onProgress?.({ type: \"iteration_start\", iteration })\n debug.step(iteration, `Agentic loop iteration (${tools.length} tools available)`)\n\n let result: RawGenerationResult\n try {\n result = await provider.generateRaw(\n anthropicMessages,\n systemPrompt,\n tools,\n providerOptions\n )\n } catch (error: any) {\n // If generateRaw fails (e.g., OAuth mode), fall back to legacy\n if (error.message?.includes(\"not available\")) {\n return runLegacyLoop(options)\n }\n throw error\n }\n\n totalTokens += result.usage.input_tokens + result.usage.output_tokens\n\n // Collect text from response\n for (const block of result.content) {\n if (block.type === \"text\") {\n textContent += block.text\n onProgress?.({ type: \"text_delta\", text: block.text })\n }\n }\n\n // If stop_reason is end_turn or max_tokens, we're done\n if (result.stop_reason === \"end_turn\" || result.stop_reason === \"max_tokens\") {\n break\n }\n\n // If stop_reason is tool_use, execute the tools\n if (result.stop_reason === \"tool_use\") {\n const toolUseBlocks = result.content.filter(\n (b): b is Extract<ContentBlock, { type: \"tool_use\" }> => b.type === \"tool_use\"\n )\n\n if (toolUseBlocks.length === 0) break\n\n // Append assistant message with the tool_use blocks\n anthropicMessages.push({\n role: \"assistant\",\n content: result.content,\n })\n\n // Execute each tool and collect results\n const toolResults: ContentBlock[] = []\n\n for (const toolBlock of toolUseBlocks) {\n onProgress?.({\n type: \"tool_call\",\n name: toolBlock.name,\n id: toolBlock.id,\n input: toolBlock.input,\n })\n\n debug.step(iteration, `Tool call: ${toolBlock.name}`)\n\n const toolResult = await executor.execute({\n name: toolBlock.name,\n id: toolBlock.id,\n input: toolBlock.input,\n })\n\n onProgress?.({\n type: \"tool_result\",\n name: toolBlock.name,\n id: toolBlock.id,\n content: toolResult.content.slice(0, 200),\n is_error: toolResult.is_error,\n })\n\n // Collect files from create_files calls\n if (toolResult.files?.length) {\n allFiles.push(...toolResult.files)\n onProgress?.({ type: \"files_created\", files: toolResult.files })\n }\n\n // Handle ask_user — surface the question to caller\n if (toolResult.followUp) {\n followUp = toolResult.followUp\n }\n\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolResult.tool_use_id,\n content: toolResult.content,\n is_error: toolResult.is_error,\n })\n }\n\n // Append user message with tool_result blocks\n anthropicMessages.push({\n role: \"user\",\n content: toolResults,\n })\n\n // If we got a follow-up question, break the loop to surface it\n if (followUp) break\n\n continue\n }\n\n // Unknown stop_reason — break\n break\n }\n\n onProgress?.({ type: \"complete\", iterations: iteration, totalTokens })\n\n return {\n files: allFiles,\n content: textContent,\n followUp,\n tokensUsed: totalTokens,\n iterations: iteration,\n }\n}\n\n/**\n * Fallback to the legacy [CONTINUE]-based multi-step loop.\n * Used when provider doesn't support generateRaw() (CLI/OAuth mode).\n * For CLI mode, we include tool descriptions in the system prompt so the\n * `claude` binary uses its own built-in tools (read, write, bash, etc.).\n */\nasync function runLegacyLoop(options: AgenticLoopOptions): Promise<AgenticResult> {\n const {\n provider,\n systemPrompt,\n messages: inputMessages,\n providerOptions,\n maxIterations = 5,\n } = options\n\n // Enhance system prompt with tool descriptions for CLI mode\n const enhancedSystemPrompt = systemPrompt + \"\\n\\n\" + formatToolsForSystemPrompt()\n\n const messages: GenerationMessage[] = [\n { role: \"system\", content: enhancedSystemPrompt },\n ...inputMessages.filter((m) => m.role !== \"system\"),\n ]\n\n const allFiles: GeneratedFile[] = []\n let totalTokens = 0\n let content = \"\"\n let followUp: string | undefined\n let step = 0\n\n while (step < maxIterations) {\n step++\n debug.step(step, `Legacy loop step (model: ${providerOptions.model || \"default\"})`)\n\n const result = await provider.generate(messages, providerOptions)\n\n totalTokens += result.tokensUsed || 0\n content = result.content\n\n if (result.files.length) {\n allFiles.push(...result.files)\n }\n\n if (result.followUp) {\n followUp = result.followUp\n break\n }\n\n if (result.files.length === 0 && step > 1) break\n\n const wantsContinuation =\n result.content.includes(\"[CONTINUE]\") ||\n result.content.includes(\"Next, I'll\") ||\n result.content.includes(\"Now let me\") ||\n result.content.includes(\"I'll also generate\")\n\n if (!wantsContinuation) break\n\n const filesSummary = result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n\n messages.push({\n role: \"assistant\",\n content: result.content + (filesSummary ? `\\n\\nFiles created:\\n${filesSummary}` : \"\"),\n })\n\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n }\n\n return {\n files: allFiles,\n content,\n followUp,\n tokensUsed: totalTokens,\n iterations: step,\n }\n}\n\n/**\n * Check if a provider supports the agentic loop (has generateRaw).\n */\nexport function supportsAgenticLoop(provider: AgentProvider): boolean {\n return typeof provider.generateRaw === \"function\"\n}\n","export class AsyncQueue<T> {\n private queue: T[] = []\n private resolvers: Array<(value: IteratorResult<T>) => void> = []\n private closed = false\n\n push(item: T): void {\n if (this.closed) return\n\n const resolver = this.resolvers.shift()\n if (resolver) {\n resolver({ value: item, done: false })\n return\n }\n this.queue.push(item)\n }\n\n close(): void {\n if (this.closed) return\n this.closed = true\n for (const resolve of this.resolvers.splice(0)) {\n resolve({ value: undefined as any, done: true })\n }\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.queue.length) {\n return { value: this.queue.shift() as T, done: false }\n }\n if (this.closed) {\n return { value: undefined as any, done: true }\n }\n return new Promise<IteratorResult<T>>((resolve) => {\n this.resolvers.push(resolve)\n })\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<T> {\n while (true) {\n const { value, done } = await this.next()\n if (done) return\n yield value\n }\n }\n}\n\n","import type { AgentProvider, GenerationMessage, GenerationResult, OutputType, StreamEvent } from \"./providers/types\"\nimport { agentConfigSchema, type AgentConfig } from \"./providers/types\"\nimport { createProvider, type ProviderName } from \"./providers\"\nimport { loadAuthConfig } from \"@/utils/auth-store\"\nimport { ensureCredentials } from \"@/utils/auth-store\"\nimport { detectTechStack, formatTechStack, type TechStack } from \"./context/tech-stack\"\nimport { detectSchemas, formatSchemas, type ProjectSchemas } from \"./context/schema\"\nimport { gatherContext7Docs } from \"./context/context7\"\nimport { loadLocalSkills, matchSkillsToTask } from \"./skills/loader\"\nimport { resolveOutputType } from \"./outputs/types\"\nimport { writeGeneratedFiles, resolveOutputDir, type WriteOptions, type WriteResult } from \"./outputs/handlers\"\nimport { logger } from \"@/utils/logger\"\nimport { globalHooks } from \"@/hooks\"\nimport { globalTracker } from \"@/observability\"\nimport { debug } from \"@/observability\"\nimport { MemoryHierarchy, ContextBuilder, loadProjectInstructions } from \"@/memory\"\nimport type { Skill } from \"./skills/types\"\nimport { runAgenticLoop, supportsAgenticLoop, type AgenticProgressEvent } from \"./orchestrator\"\nimport { AsyncQueue } from \"@/utils/async-queue\"\n\n// --- Agent Orchestrator: the brain that coordinates everything ---\n\nexport interface AgentContext {\n techStack: TechStack\n schemas: ProjectSchemas\n skills: Skill[]\n docs: string\n config: AgentConfig\n memoryContext: string\n projectInstructions: string\n}\n\nexport interface GenerateOptions {\n task: string\n outputType?: OutputType\n outputDir?: string\n overwrite?: boolean\n dryRun?: boolean\n provider?: ProviderName\n model?: string\n apiKey?: string\n cwd: string\n context7?: boolean\n interactive?: boolean\n skills?: string[] // Additional skill packages to load\n maxSteps?: number // Max agentic loop iterations (default 20 for agentic, 5 for legacy)\n sessionMessages?: GenerationMessage[] // Multi-turn context from REPL sessions\n heal?: boolean // undefined = auto (heal if files written), false = skip\n healConfig?: {\n testCommand?: string\n buildCommand?: string\n lintCommand?: string\n maxAttempts?: number\n }\n}\n\nexport interface GenerateResult {\n files: WriteResult\n content: string\n outputType: OutputType\n followUp?: string\n tokensUsed?: number\n healResult?: import(\"@/runtime/heal\").HealResult\n}\n\nexport async function createAgentContext(\n cwd: string,\n task: string,\n config?: Partial<AgentConfig>\n): Promise<AgentContext> {\n const agentConfig = agentConfigSchema.parse(config || {})\n\n // Load memory hierarchy\n const memory = new MemoryHierarchy(cwd)\n await memory.load()\n\n // Gather all context in parallel\n const [techStack, schemas, skills] = await Promise.all([\n detectTechStack(cwd),\n detectSchemas(cwd),\n loadLocalSkills(cwd),\n ])\n\n // Context7 docs (optional, can fail gracefully)\n let docs = \"\"\n if (agentConfig.context7.enabled) {\n try {\n docs = await gatherContext7Docs(techStack, task, agentConfig.context7.apiKey)\n } catch {\n // Context7 is optional, don't fail the whole flow\n }\n }\n\n // Build memory context from both user and project levels\n const memoryContext = memory.buildMemoryContext(task)\n\n // Load project instructions (SHADXN.md or CLAUDE.md) with @-import resolution\n const projectInstructions = loadProjectInstructions(cwd)\n\n debug.context(\"memory\", memoryContext ? \"loaded\" : \"empty\")\n debug.context(\"instructions\", projectInstructions ? \"loaded from project\" : \"none\")\n\n return {\n techStack,\n schemas,\n skills,\n docs,\n config: agentConfig,\n memoryContext,\n projectInstructions,\n }\n}\n\nexport async function generate(options: GenerateOptions): Promise<GenerateResult> {\n const {\n task,\n cwd,\n overwrite = false,\n dryRun = false,\n provider: providerName = \"claude-code\",\n model,\n apiKey,\n context7 = true,\n interactive = true,\n } = options\n\n // 0. pre:prompt hook — can modify or block the task prompt\n let effectiveTask = task\n if (globalHooks.has(\"pre:prompt\")) {\n const promptResult = await globalHooks.execute(\"pre:prompt\", {\n event: \"pre:prompt\",\n task,\n cwd,\n })\n if (promptResult.blocked) {\n throw new Error(promptResult.message || \"Blocked by pre:prompt hook\")\n }\n if (promptResult.modified?.task) {\n effectiveTask = String(promptResult.modified.task)\n }\n }\n\n // 0b. pre:generate hook — can block the entire generation\n if (globalHooks.has(\"pre:generate\")) {\n const genResult = await globalHooks.execute(\"pre:generate\", {\n event: \"pre:generate\",\n task: effectiveTask,\n cwd,\n })\n if (genResult.blocked) {\n throw new Error(genResult.message || \"Blocked by pre:generate hook\")\n }\n }\n\n // 1. Gather context\n logger.info(\"Analyzing project...\")\n const context = await createAgentContext(cwd, effectiveTask, {\n provider: providerName,\n context7: { enabled: context7, apiKey },\n })\n\n // 2. Resolve output type\n const outputType = resolveOutputType(options.outputType, effectiveTask)\n logger.info(`Output type: ${outputType}`)\n\n // 3. Match relevant skills\n const matchedSkills = matchSkillsToTask(context.skills, effectiveTask, outputType)\n if (matchedSkills.length) {\n logger.info(\n `Loaded ${matchedSkills.length} relevant skill(s): ${matchedSkills.map((m) => m.skill.frontmatter.name).join(\", \")}`\n )\n }\n\n // 4. Build system prompt\n const systemPrompt = buildSystemPrompt(context, outputType, matchedSkills.map((m) => m.skill))\n\n // 5. Ensure credentials exist (auto-prompt if missing)\n const hasCredentials = await ensureCredentials(apiKey)\n if (!hasCredentials) {\n throw new Error(\"No credentials configured. Run `agentx model` to set up.\")\n }\n\n // 6. Create provider\n const provider = createProvider(providerName, apiKey)\n const resolvedModel = model || loadAuthConfig()?.model\n\n // Build initial messages (without system — orchestrator handles it)\n const sessionMessages: GenerationMessage[] = [\n ...(options.sessionMessages || []),\n { role: \"user\", content: effectiveTask },\n ]\n\n logger.info(\"Generating...\")\n\n // Determine if we should use the agentic loop\n const useAgentic = supportsAgenticLoop(provider)\n const maxSteps = options.maxSteps ?? (useAgentic ? 20 : 5)\n\n // 7. Run orchestrator (agentic or legacy)\n const agenticResult = await runAgenticLoop({\n provider,\n systemPrompt,\n messages: [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ],\n providerOptions: { model: resolvedModel, maxTokens: 8192 },\n cwd,\n maxIterations: maxSteps,\n enabledTools: context.config.agentic.enabledTools.filter(\n (t) => !context.config.agentic.disabledTools.includes(t)\n ),\n interactive,\n overwrite,\n dryRun,\n onProgress: (event) => {\n if (event.type === \"iteration_start\" && event.iteration > 1) {\n logger.info(`Step ${event.iteration}/${maxSteps}...`)\n }\n if (event.type === \"tool_call\") {\n debug.step(0, `Tool: ${event.name}`)\n }\n },\n })\n\n // Track token usage\n if (agenticResult.tokensUsed) {\n const stepModel = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput = Math.round(agenticResult.tokensUsed * 0.3)\n const estOutput = agenticResult.tokensUsed - estInput\n globalTracker.recordStep(1, stepModel, estInput, estOutput)\n }\n\n let { content } = agenticResult\n const { followUp, tokensUsed: totalTokens } = agenticResult\n\n if (agenticResult.iterations > 1) {\n logger.info(`Completed in ${agenticResult.iterations} step(s)`)\n }\n\n // post:response hook — can modify or block the AI response\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n throw new Error(responseResult.message || \"Blocked by post:response hook\")\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n // Handle follow-up questions (interactive mode)\n if (followUp && interactive) {\n return {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp,\n tokensUsed: totalTokens,\n }\n }\n\n // Deduplicate files (later versions override earlier ones)\n const deduped = new Map<string, import(\"./providers/types\").GeneratedFile>()\n for (const file of agenticResult.files) {\n deduped.set(file.path, file)\n }\n\n // Write files\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n // Heal loop — verify generated code and auto-fix if needed\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n\n if (!healResult.healed && healResult.error) {\n await globalHooks.execute(\"on:error\", {\n event: \"on:error\",\n error: new Error(healResult.error),\n task: effectiveTask,\n cwd,\n })\n }\n }\n\n // post:generate hook — post-processing (format, lint, etc.)\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n return {\n files: writeResult,\n content,\n outputType,\n tokensUsed: totalTokens,\n healResult,\n }\n}\n\n// --- Streaming generation ---\n\nexport type GenerateStreamEvent =\n | StreamEvent\n | { type: \"context_ready\"; outputType: OutputType }\n | { type: \"step_complete\"; step: number; filesCount: number }\n | { type: \"tool_call\"; name: string; id: string }\n | { type: \"tool_result\"; name: string; id: string; is_error?: boolean }\n | { type: \"iteration\"; iteration: number }\n | { type: \"generate_result\"; result: GenerateResult }\n\nexport async function* generateStream(\n options: GenerateOptions\n): AsyncGenerator<GenerateStreamEvent> {\n const {\n task,\n cwd,\n overwrite = false,\n dryRun = false,\n provider: providerName = \"claude-code\",\n model,\n apiKey,\n context7 = true,\n interactive = true,\n } = options\n\n // 0. pre:prompt hook\n let effectiveTask = task\n if (globalHooks.has(\"pre:prompt\")) {\n const promptResult = await globalHooks.execute(\"pre:prompt\", {\n event: \"pre:prompt\",\n task,\n cwd,\n })\n if (promptResult.blocked) {\n yield { type: \"error\", error: promptResult.message || \"Blocked by pre:prompt hook\" }\n return\n }\n if (promptResult.modified?.task) {\n effectiveTask = String(promptResult.modified.task)\n }\n }\n\n // 0b. pre:generate hook\n if (globalHooks.has(\"pre:generate\")) {\n const genResult = await globalHooks.execute(\"pre:generate\", {\n event: \"pre:generate\",\n task: effectiveTask,\n cwd,\n })\n if (genResult.blocked) {\n yield { type: \"error\", error: genResult.message || \"Blocked by pre:generate hook\" }\n return\n }\n }\n\n // 1. Gather context\n const context = await createAgentContext(cwd, effectiveTask, {\n provider: providerName,\n context7: { enabled: context7, apiKey },\n })\n\n // 2. Resolve output type\n const outputType = resolveOutputType(options.outputType, effectiveTask)\n\n // Signal context ready so UI can stop spinner\n yield { type: \"context_ready\", outputType }\n\n // 3. Match relevant skills\n const matchedSkills = matchSkillsToTask(context.skills, effectiveTask, outputType)\n\n // 4. Build system prompt\n const systemPrompt = buildSystemPrompt(context, outputType, matchedSkills.map((m) => m.skill))\n\n // 5. Ensure credentials\n const hasCredentials = await ensureCredentials(apiKey)\n if (!hasCredentials) {\n yield { type: \"error\", error: \"No credentials configured. Run `agentx model` to set up.\" }\n return\n }\n\n // 6. Create provider\n const provider = createProvider(providerName, apiKey)\n const resolvedModel = model || loadAuthConfig()?.model\n const useAgentic = supportsAgenticLoop(provider)\n const maxSteps = options.maxSteps ?? (useAgentic ? 20 : 5)\n\n const sessionMessages: GenerationMessage[] = [\n ...(options.sessionMessages || []),\n { role: \"user\", content: effectiveTask },\n ]\n\n // For agentic mode, use the orchestrator with progress events\n if (useAgentic) {\n const q = new AsyncQueue<GenerateStreamEvent>()\n let agenticResult: Awaited<ReturnType<typeof runAgenticLoop>> | undefined\n let agenticError: unknown\n\n const agenticPromise = (async () => {\n try {\n agenticResult = await runAgenticLoop({\n provider,\n systemPrompt,\n messages: [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ],\n providerOptions: { model: resolvedModel, maxTokens: 8192 },\n cwd,\n maxIterations: maxSteps,\n enabledTools: context.config.agentic.enabledTools.filter(\n (t) => !context.config.agentic.disabledTools.includes(t)\n ),\n interactive,\n overwrite,\n dryRun,\n onProgress: (event) => {\n if (event.type === \"text_delta\") {\n q.push({ type: \"text_delta\", text: event.text })\n }\n if (event.type === \"iteration_start\") {\n q.push({ type: \"iteration\", iteration: event.iteration })\n }\n if (event.type === \"tool_call\") {\n q.push({ type: \"tool_call\", name: event.name, id: event.id })\n }\n if (event.type === \"tool_result\") {\n q.push({ type: \"tool_result\", name: event.name, id: event.id, is_error: event.is_error })\n }\n if (event.type === \"files_created\") {\n q.push({ type: \"step_complete\", step: 0, filesCount: event.files.length })\n }\n },\n })\n } catch (err) {\n agenticError = err\n } finally {\n q.close()\n }\n })()\n\n for await (const evt of q) {\n yield evt\n }\n\n await agenticPromise\n if (agenticError) {\n const msg = agenticError instanceof Error ? agenticError.message : String(agenticError)\n yield { type: \"error\", error: msg }\n return\n }\n if (!agenticResult) {\n yield { type: \"error\", error: \"Agentic loop failed without a result\" }\n return\n }\n\n yield {\n type: \"done\",\n result: {\n content: agenticResult.content,\n files: agenticResult.files,\n tokensUsed: agenticResult.tokensUsed,\n followUp: agenticResult.followUp,\n },\n }\n\n // Write files and heal\n let { content } = agenticResult\n\n // post:response hook\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n yield { type: \"error\", error: responseResult.message || \"Blocked by post:response hook\" }\n return\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n if (agenticResult.followUp && interactive) {\n yield {\n type: \"generate_result\",\n result: {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp: agenticResult.followUp,\n tokensUsed: agenticResult.tokensUsed,\n },\n }\n return\n }\n\n const deduped = new Map<string, import(\"./providers/types\").GeneratedFile>()\n for (const file of agenticResult.files) {\n deduped.set(file.path, file)\n }\n\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n }\n\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n yield {\n type: \"generate_result\",\n result: {\n files: writeResult,\n content,\n outputType,\n tokensUsed: agenticResult.tokensUsed,\n healResult,\n },\n }\n return\n }\n\n // --- Legacy streaming path (no generateRaw) ---\n\n const messages: GenerationMessage[] = [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ]\n\n const allFiles: import(\"./providers/types\").GeneratedFile[] = []\n let totalTokens = 0\n let content = \"\"\n let followUp: string | undefined\n let step = 0\n\n // --- Step 1: streamed ---\n step++\n debug.step(step, `Starting generation (model: ${resolvedModel || \"default\"})`)\n\n let step1Result: GenerationResult\n\n if (provider.stream) {\n let accumulated = \"\"\n let streamResult: GenerationResult | undefined\n\n for await (const event of provider.stream(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })) {\n yield event\n\n if (event.type === \"text_delta\") {\n accumulated += event.text\n }\n if (event.type === \"done\") {\n streamResult = event.result\n }\n }\n\n step1Result = streamResult || {\n content: accumulated,\n files: [],\n tokensUsed: 0,\n }\n } else {\n const result = await provider.generate(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })\n\n if (result.content) {\n yield { type: \"text_delta\", text: result.content }\n }\n yield { type: \"done\", result }\n step1Result = result\n }\n\n totalTokens += step1Result.tokensUsed || 0\n content = step1Result.content\n\n const step1Tokens = step1Result.tokensUsed || 0\n const step1Model = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput1 = Math.round(step1Tokens * 0.3)\n const estOutput1 = step1Tokens - estInput1\n globalTracker.recordStep(step, step1Model, estInput1, estOutput1)\n debug.api(\"generate\", step1Model, step1Tokens)\n debug.step(step, `Generated ${step1Result.files.length} file(s), ${step1Tokens} tokens`)\n\n if (step1Result.files.length) {\n allFiles.push(...step1Result.files)\n }\n\n if (step1Result.followUp) {\n followUp = step1Result.followUp\n }\n\n yield { type: \"step_complete\", step, filesCount: step1Result.files.length }\n\n // --- Steps 2-N: non-streaming continuation loop ---\n if (!followUp) {\n const wantsContinuation1 =\n content.includes(\"[CONTINUE]\") ||\n content.includes(\"Next, I'll\") ||\n content.includes(\"Now let me\") ||\n content.includes(\"I'll also generate\")\n\n if (wantsContinuation1 && step1Result.files.length > 0) {\n const filesSummary = step1Result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n messages.push({\n role: \"assistant\",\n content: content + (filesSummary ? `\\n\\nFiles created:\\n${filesSummary}` : \"\"),\n })\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n\n while (step < maxSteps) {\n step++\n debug.step(step, `Starting generation (model: ${resolvedModel || \"default\"})`)\n\n const result = await provider.generate(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })\n\n totalTokens += result.tokensUsed || 0\n content = result.content\n\n const stepTokens = result.tokensUsed || 0\n const stepModel = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput = Math.round(stepTokens * 0.3)\n const estOutput = stepTokens - estInput\n globalTracker.recordStep(step, stepModel, estInput, estOutput)\n debug.api(\"generate\", stepModel, stepTokens)\n debug.step(step, `Generated ${result.files.length} file(s), ${stepTokens} tokens`)\n\n if (result.files.length) {\n allFiles.push(...result.files)\n }\n\n yield { type: \"step_complete\", step, filesCount: result.files.length }\n\n if (result.followUp) {\n followUp = result.followUp\n break\n }\n if (result.files.length === 0 && step > 1) break\n\n const wantsContinuation =\n result.content.includes(\"[CONTINUE]\") ||\n result.content.includes(\"Next, I'll\") ||\n result.content.includes(\"Now let me\") ||\n result.content.includes(\"I'll also generate\")\n\n if (!wantsContinuation) break\n\n const filesSummary2 = result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n messages.push({\n role: \"assistant\",\n content: result.content + (filesSummary2 ? `\\n\\nFiles created:\\n${filesSummary2}` : \"\"),\n })\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n }\n }\n }\n\n // post:response hook\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n yield { type: \"error\", error: responseResult.message || \"Blocked by post:response hook\" }\n return\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n if (followUp && interactive) {\n yield {\n type: \"generate_result\",\n result: {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp,\n tokensUsed: totalTokens,\n },\n }\n return\n }\n\n const deduped = new Map<import(\"./providers/types\").GeneratedFile[\"path\"], import(\"./providers/types\").GeneratedFile>()\n for (const file of allFiles) {\n deduped.set(file.path, file)\n }\n\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n\n if (!healResult.healed && healResult.error) {\n await globalHooks.execute(\"on:error\", {\n event: \"on:error\",\n error: new Error(healResult.error),\n task: effectiveTask,\n cwd,\n })\n }\n }\n\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n yield {\n type: \"generate_result\",\n result: {\n files: writeResult,\n content,\n outputType,\n tokensUsed: totalTokens,\n healResult,\n },\n }\n}\n\nfunction buildSystemPrompt(\n context: AgentContext,\n outputType: string,\n skills: Skill[]\n): string {\n const sections: string[] = []\n\n // Identity — updated for agentic capabilities\n sections.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.\n\nYour primary tool is \\`create_files\\` — use it to output all generated code, documents, and configs as files.\nIf the request is ambiguous or you need critical information to proceed correctly, use \\`ask_user\\` to ask a clarifying question.\n\nYou also have tools to inspect the codebase before generating code:\n- \\`read_file\\` — read existing files to understand patterns, styles, and implementations\n- \\`search_files\\` — search for files by glob pattern, optionally grep content with regex\n- \\`list_directory\\` — explore the project structure\n- \\`run_command\\` — run shell commands (build, test, lint, etc.)\n- \\`edit_file\\` — apply targeted search/replace edits to existing files\n\nAGENTIC WORKFLOW:\n- Before generating code, use \\`read_file\\` and \\`search_files\\` to understand the existing codebase\n- Match the project's existing patterns, naming conventions, and code style\n- After creating files, consider running tests or build commands to verify correctness\n- Use \\`edit_file\\` for small, targeted changes instead of rewriting entire files\n\nIMPORTANT RULES:\n- Generate complete, working code — not stubs or placeholders\n- Follow the project's existing patterns and conventions\n- Use the detected tech stack to choose the right language, framework, and patterns\n- File paths should be relative to the project root\n- Include all necessary imports\n- Do NOT add unnecessary dependencies\n\nMULTI-STEP GENERATION:\nFor complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:\n- Generate the foundational files first (schemas, types, configs)\n- Include \"[CONTINUE]\" in your response text when there are more files to generate\n- In subsequent steps, you'll see what was already created — build on it\n- When all files are generated, do NOT include \"[CONTINUE]\"\n- This enables you to generate a schema first, then an API that references it, then a UI that calls the API`)\n\n // Tech stack context\n sections.push(`# Project Tech Stack\\n${formatTechStack(context.techStack)}`)\n\n // Key dependencies\n const deps = Object.keys(context.techStack.dependencies).slice(0, 30)\n if (deps.length) {\n sections.push(`# Key Dependencies\\n${deps.join(\", \")}`)\n }\n\n // Schema context\n const schemaStr = formatSchemas(context.schemas)\n if (schemaStr) {\n sections.push(`# Project Schemas\\n${schemaStr}`)\n }\n\n // Skills context\n if (skills.length) {\n sections.push(\n `# Active Skills\\nFollow these skill instructions when applicable:\\n\\n` +\n skills\n .map(\n (s) =>\n `## Skill: ${s.frontmatter.name}\\n${s.frontmatter.description}\\n\\n${s.instructions}`\n )\n .join(\"\\n\\n---\\n\\n\")\n )\n }\n\n // Context7 docs\n if (context.docs) {\n sections.push(context.docs)\n }\n\n // Project instructions (SHADXN.md / CLAUDE.md)\n if (context.projectInstructions) {\n sections.push(`# Project Instructions\\n${context.projectInstructions}`)\n }\n\n // Memory context (past generations, patterns, preferences)\n if (context.memoryContext) {\n sections.push(context.memoryContext)\n }\n\n // Output type guidance\n sections.push(`# Output Type: ${outputType}\\nGenerate output appropriate for: ${outputType}. Use the \\`create_files\\` tool to output all files.`)\n\n return sections.join(\"\\n\\n\")\n}\n\n// Re-export key types\nexport type { TechStack } from \"./context/tech-stack\"\nexport type { ProjectSchemas } from \"./context/schema\"\nexport type { Skill } from \"./skills/types\"\nexport type { AgentConfig, OutputType, GeneratedFile, StreamEvent } from \"./providers/types\"\n"],"mappings":"mWAAA,OAAS,KAAAA,MAAS,MA6EX,IAAMC,GAAoBD,EAAE,OAAO,CACxC,SAAUA,EAAE,KAAK,CAAC,cAAe,SAAU,SAAU,SAAU,QAAQ,CAAC,EAAE,QAAQ,aAAa,EAC/F,MAAOA,EAAE,OAAO,EAAE,SAAS,EAC3B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAC5B,OAAQA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,EACtC,OAAQA,EACL,OAAO,CACN,IAAKA,EAAE,OAAO,EAAE,QAAQ,aAAa,CACvC,CAAC,EACA,QAAQ,CAAC,CAAC,EACb,SAAUA,EACP,OAAO,CACN,QAASA,EAAE,QAAQ,EAAE,QAAQ,EAAI,EACjC,OAAQA,EAAE,OAAO,EAAE,SAAS,CAC9B,CAAC,EACA,QAAQ,CAAC,CAAC,EACb,QAASA,EACN,OAAO,CACN,cAAeA,EAAE,OAAO,EAAE,QAAQ,EAAE,EACpC,aAAcA,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D,EAAQ,aAAa,EAIrC2D,EAAS,KAAK,kBAAkB1D;AAAA,mCAAgDA,uDAAgE,EAEzI0D,EAAS,KAAK;AAAA;AAAA,CAAM,CAC7B","names":["z","agentConfigSchema","OUTPUT_TYPES","outputTypeDescriptions","existsSync","fs","path","fg","SCHEMA_FILES","detectSchemas","cwd","schemas","files","schemaFile","info","match","f","content","safeReadFile","truncate","extractTableNames","trpcRouter","envExample","parseEnvFile","modelFiles","mf","type","matches","m","l","line","keyPart","key","hasValue","filePath","str","maxLen","formatSchemas","sections","v","model","fetch","CONTEXT7_API","resolveLibraryId","libraryName","apiKey","headers","response","data","getLibraryDocs","libraryId","topic","maxTokens","gatherContext7Docs","stack","relevantLibraries","fw","priorityDeps","dep","docs","lib","library","content","OUTPUT_CONFIGS","resolveOutputType","userHint","taskDescription","lower","patterns","pattern","type","existsSync","fs","path","prompts","chalk","z","PERMISSION_MODES","permissionModeSchema","permissionConfigSchema","matchGlob","filePath","pattern","regex","PermissionManager","config","parsed","permissionConfigSchema","mode","debug","command","patterns","p","action","prompts","chalk","globalPermissions","writeGeneratedFiles","files","options","result","file","filePath","path","fileContent","globalHooks","hookResult","relativePath","permission","globalPermissions","existsSync","dir","fs","error","resolveOutputDir","outputType","stack","customDir","config","OUTPUT_CONFIGS","baseDir","f","os","USER_MEMORY_DIR","os","MemoryHierarchy","cwd","Memory","task","userCtx","projectCtx","sections","key","value","source","entry","userPrefs","projectPrefs","merged","p","userPatterns","limit","existsSync","readFileSync","path","resolveAtImports","content","basedir","match","filePath","resolved","path","existsSync","readFileSync","loadProjectInstructions","cwd","candidates","name","estimateTokens","ContextBuilder","label","priority","task","maxTokens","docs","s","index","buildIndex","bm25Results","scoreAll","scoreMap","r","scored","i","a","b","included","totalTokens","section","fs","path","execa","fg","ToolExecutor","cwd","options","call","debug","globalHooks","hookResult","result","error","filePath","maxLines","absPath","path","content","fs","lines","output","pattern","contentRegex","maxResults","files","fg","limited","regex","results","file","i","dirPath","recursive","maxDepth","entries","formatted","e","command","timeout","globalPermissions","execa","truncated","edits","permission","applied","edit","input","agentId","prompt","timeoutSeconds","SubAgentManager","getGlobalRegistry","registry","question","followUp","runAgenticLoop","options","provider","systemPrompt","inputMessages","providerOptions","cwd","maxIterations","enabledTools","interactive","overwrite","dryRun","onProgress","runLegacyLoop","executor","ToolExecutor","tools","getAnthropicTools","anthropicMessages","m","allFiles","totalTokens","textContent","followUp","iteration","debug","result","error","block","toolUseBlocks","b","toolResults","toolBlock","toolResult","messages","formatToolsForSystemPrompt","content","step","filesSummary","f","supportsAgenticLoop","AsyncQueue","item","resolver","resolve","value","done","createAgentContext","cwd","task","config","agentConfig","agentConfigSchema","memory","MemoryHierarchy","techStack","schemas","skills","detectTechStack","detectSchemas","loadLocalSkills","docs","gatherContext7Docs","memoryContext","projectInstructions","loadProjectInstructions","debug","generate","options","overwrite","dryRun","providerName","model","apiKey","context7","interactive","effectiveTask","globalHooks","promptResult","genResult","logger","context","outputType","resolveOutputType","matchedSkills","matchSkillsToTask","m","systemPrompt","buildSystemPrompt","ensureCredentials","provider","createProvider","resolvedModel","loadAuthConfig","sessionMessages","useAgentic","supportsAgenticLoop","maxSteps","agenticResult","runAgenticLoop","t","event","stepModel","estInput","estOutput","globalTracker","content","followUp","totalTokens","responseResult","deduped","file","outputDir","resolveOutputDir","writeResult","writeGeneratedFiles","healResult","HealEngine","generateStream","q","AsyncQueue","agenticError","agenticPromise","err","evt","messages","allFiles","step","step1Result","accumulated","streamResult","result","step1Tokens","step1Model","estInput1","estOutput1","filesSummary","f","stepTokens","filesSummary2","sections","formatTechStack","deps","schemaStr","formatSchemas","s"]}
|