create-cogitator-app 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["<define:__COGITATOR_EXAMPLES__>","<define:__COGITATOR_VERSIONS__>","../src/kit/scaffold.ts","../src/kit/errors.ts","../src/kit/package-manager.ts","../src/kit/spec.ts","../src/kit/providers.ts","../src/kit/compat.ts","../src/kit/code.ts","../src/kit/versions.ts","../src/kit/emit.ts","../src/kit/features/starter-tools.ts","../src/kit/features/base.ts","../src/kit/features/deploy.ts","../src/kit/features/a2a.ts","../src/kit/features/shared.ts","../src/kit/features/app-channels.ts","../src/kit/features/app-next.ts","../src/kit/features/app-script.ts","../src/kit/features/app-server.ts","../src/kit/features/memory.ts","../src/kit/features/app-worker.ts","../src/kit/features/coding-agents.ts","../src/kit/features/evals.ts","../src/kit/features/harness.ts","../src/kit/features/mcp.ts","../src/kit/features/observability.ts","../src/kit/features/orchestration.ts","../src/kit/features/provider.ts","../src/kit/features/rag.ts","../src/kit/features/sandbox.ts","../src/kit/features/voice.ts","../src/kit/features/index.ts","../src/kit/presets.ts","../src/kit/guide.ts","../src/kit/project.ts","../src/kit/plan.ts","../src/kit/process.ts","../src/kit/add.ts","../src/kit/diff.ts","../src/kit/merge.ts","../src/kit/suggest.ts","../src/kit/examples.ts","../src/kit/remote.ts","../src/kit/starter.ts","../src/kit/catalog.ts","../src/kit/models.ts","../src/kit/ollama.ts","../src/kit/key-check.ts","../src/kit/telemetry.ts","../src/cli/main.ts","../src/cli/args.ts","../src/cli/help.ts","../src/cli/interactive.ts","../src/cli/resolve.ts"],"sourcesContent":["[{\"name\":\"a2a/a2a-server\",\"title\":\"A2A Server\",\"entry\":\"a2a/01-a2a-server.ts\",\"files\":[\"_shared/setup.ts\",\"a2a/01-a2a-server.ts\"],\"dependencies\":{\"@cogitator-ai/a2a\":\"^0.8.3\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"express\":\"^5.2.1\"},\"devDependencies\":{\"@types/express\":\"^5.0.6\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"a2a/a2a-client\",\"title\":\"A2A Client\",\"entry\":\"a2a/02-a2a-client.ts\",\"files\":[\"_shared/setup.ts\",\"a2a/02-a2a-client.ts\"],\"dependencies\":{\"@cogitator-ai/a2a\":\"^0.8.3\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/self-modifying\",\"title\":\"Self-Modifying Agent\",\"entry\":\"advanced/01-self-modifying.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/01-self-modifying.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/self-modifying\":\"^19.4.3\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/neuro-symbolic\",\"title\":\"Neuro-Symbolic Reasoning\",\"entry\":\"advanced/02-neuro-symbolic.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/02-neuro-symbolic.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/neuro-symbolic\":\"^17.0.23\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/wasm-tools\",\"title\":\"WASM-Sandboxed Tools\",\"entry\":\"advanced/03-wasm-tools.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/03-wasm-tools.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/wasm-tools\":\"^0.7.17\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/web-scraping\",\"title\":\"Web Scraping with Browser Agent\",\"entry\":\"browser/01-web-scraping.ts\",\"files\":[\"_shared/setup.ts\",\"browser/01-web-scraping.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.13\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/form-automation\",\"title\":\"Form Automation with Browser Agent\",\"entry\":\"browser/02-form-automation.ts\",\"files\":[\"_shared/setup.ts\",\"browser/02-form-automation.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.13\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/stealth-agent\",\"title\":\"Stealth Browser Agent\",\"entry\":\"browser/03-stealth-agent.ts\",\"files\":[\"_shared/setup.ts\",\"browser/03-stealth-agent.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.13\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/bitcoin-price-scraper\",\"title\":\"Bitcoin Price Scraper (Binance)\",\"entry\":\"browser/04-bitcoin-price-scraper.ts\",\"files\":[\"_shared/setup.ts\",\"browser/04-bitcoin-price-scraper.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.13\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"channels/telegram-assistant\",\"title\":\"Telegram assistant\",\"entry\":\"channels/01-telegram-assistant.ts\",\"files\":[\"channels/01-telegram-assistant.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.9.3\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"grammy\":\"^1.46.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\",\"OWNER_TG_ID\",\"TG_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/super-assistant\",\"title\":\"Super assistant\",\"entry\":\"channels/02-super-assistant.ts\",\"files\":[\"channels/02-super-assistant.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.9.3\",\"better-sqlite3\":\"^13.0.3\",\"dotenv\":\"^18.0.5\",\"grammy\":\"^1.46.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"OWNER_TG_ID\",\"TG_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/webchat-bot\",\"title\":\"Webchat bot\",\"entry\":\"channels/03-webchat-bot.ts\",\"files\":[\"channels/03-webchat-bot.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.9.3\",\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"ws\":\"^8.22.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"@types/ws\":\"^8.18.2\",\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\",\"WEBCHAT_PORT\",\"WEBCHAT_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"core/basic-agent\",\"title\":\"Basic Agent with Custom Tools\",\"entry\":\"core/01-basic-agent.ts\",\"files\":[\"_shared/setup.ts\",\"core/01-basic-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/built-in-tools\",\"title\":\"Built-in Tools\",\"entry\":\"core/02-built-in-tools.ts\",\"files\":[\"_shared/setup.ts\",\"core/02-built-in-tools.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/tool-caching\",\"title\":\"Tool Caching with withCache\",\"entry\":\"core/03-tool-caching.ts\",\"files\":[\"_shared/setup.ts\",\"core/03-tool-caching.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/context-manager\",\"title\":\"Context Manager\",\"entry\":\"core/04-context-manager.ts\",\"files\":[\"_shared/setup.ts\",\"core/04-context-manager.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/tree-of-thought\",\"title\":\"Tree of Thought\",\"entry\":\"core/05-tree-of-thought.ts\",\"files\":[\"_shared/setup.ts\",\"core/05-tree-of-thought.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/reflection\",\"title\":\"Reflection\",\"entry\":\"core/06-reflection.ts\",\"files\":[\"_shared/setup.ts\",\"core/06-reflection.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/agent-optimizer\",\"title\":\"Agent Optimizer\",\"entry\":\"core/07-agent-optimizer.ts\",\"files\":[\"_shared/setup.ts\",\"core/07-agent-optimizer.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/time-travel\",\"title\":\"Time Travel\",\"entry\":\"core/08-time-travel.ts\",\"files\":[\"_shared/setup.ts\",\"core/08-time-travel.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/cost-routing\",\"title\":\"Cost-Aware Routing\",\"entry\":\"core/09-cost-routing.ts\",\"files\":[\"_shared/setup.ts\",\"core/09-cost-routing.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/constitutional-ai\",\"title\":\"Constitutional AI\",\"entry\":\"core/10-constitutional-ai.ts\",\"files\":[\"_shared/setup.ts\",\"core/10-constitutional-ai.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/prompt-injection\",\"title\":\"Prompt Injection Detection\",\"entry\":\"core/11-prompt-injection.ts\",\"files\":[\"_shared/setup.ts\",\"core/11-prompt-injection.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/causal-reasoning\",\"title\":\"Causal Reasoning\",\"entry\":\"core/12-causal-reasoning.ts\",\"files\":[\"_shared/setup.ts\",\"core/12-causal-reasoning.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/model-registry\",\"title\":\"Model Registry\",\"entry\":\"core/13-model-registry.ts\",\"files\":[\"_shared/setup.ts\",\"core/13-model-registry.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/models\":\"^18.3.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/approvals\",\"title\":\"Approvals: pause before a sensitive tool, resume later\",\"entry\":\"core/14-approvals.ts\",\"files\":[\"_shared/setup.ts\",\"core/14-approvals.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/handoffs\",\"title\":\"Handoffs: a triage agent passes the conversation on\",\"entry\":\"core/15-handoffs.ts\",\"files\":[\"_shared/setup.ts\",\"core/15-handoffs.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"device-tools/screenshot\",\"title\":\"Screenshot\",\"entry\":\"device-tools/01-screenshot.ts\",\"files\":[\"device-tools/01-screenshot.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/clipboard\",\"title\":\"Clipboard\",\"entry\":\"device-tools/02-clipboard.ts\",\"files\":[\"device-tools/02-clipboard.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/notify\",\"title\":\"Notify\",\"entry\":\"device-tools/03-notify.ts\",\"files\":[\"device-tools/03-notify.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/open-url\",\"title\":\"Open url\",\"entry\":\"device-tools/04-open-url.ts\",\"files\":[\"device-tools/04-open-url.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/shell-exec\",\"title\":\"Shell exec\",\"entry\":\"device-tools/05-shell-exec.ts\",\"files\":[\"device-tools/05-shell-exec.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"evals/basic-eval\",\"title\":\"Basic Evaluation\",\"entry\":\"evals/01-basic-eval.ts\",\"files\":[\"_shared/setup.ts\",\"evals/01-basic-eval.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/evals\":\"^0.6.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"evals/llm-judge\",\"title\":\"LLM-as-Judge Evaluation\",\"entry\":\"evals/02-llm-judge.ts\",\"files\":[\"_shared/setup.ts\",\"evals/02-llm-judge.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/evals\":\"^0.6.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"evals/ab-comparison\",\"title\":\"A/B Comparison\",\"entry\":\"evals/03-ab-comparison.ts\",\"files\":[\"_shared/setup.ts\",\"evals/03-ab-comparison.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/evals\":\"^0.6.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/redis-memory\",\"title\":\"Redis Memory: Persistent Conversations\",\"entry\":\"infrastructure/01-redis-memory.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/01-redis-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"REDIS_URL\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/postgres-memory\",\"title\":\"PostgreSQL Memory: Long-Term Persistence\",\"entry\":\"infrastructure/02-postgres-memory.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/02-postgres-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"DATABASE_URL\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/worker-queue\",\"title\":\"Worker Queue: Distributed Agent Execution\",\"entry\":\"infrastructure/03-worker-queue.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/03-worker-queue.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/worker\":\"^0.9.3\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"REDIS_URL\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/deploy-docker\",\"title\":\"Deploy: Docker Deployment Planning\",\"entry\":\"infrastructure/04-deploy-docker.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/04-deploy-docker.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/deploy\":\"^0.6.2\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/sandbox-execution\",\"title\":\"Sandbox Execution: Docker, WASM & Native\",\"entry\":\"infrastructure/05-sandbox-execution.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/05-sandbox-execution.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/sandbox\":\"^0.5.12\",\"@extism/extism\":\"^2.0.0-rc13\",\"dockerode\":\"^4.0.0 || ^5.0.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/express-server\",\"title\":\"Express Server Integration\",\"entry\":\"integrations/01-express-server.ts\",\"files\":[\"_shared/arithmetic.ts\",\"_shared/setup.ts\",\"integrations/01-express-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/express\":\"^0.8.3\",\"dotenv\":\"^18.0.5\",\"express\":\"^5.2.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"@types/express\":\"^5.0.6\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/fastify-server\",\"title\":\"Fastify Server Integration\",\"entry\":\"integrations/02-fastify-server.ts\",\"files\":[\"_shared/arithmetic.ts\",\"_shared/setup.ts\",\"integrations/02-fastify-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/fastify\":\"^0.7.3\",\"dotenv\":\"^18.0.5\",\"fastify\":\"^5.12.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/hono-server\",\"title\":\"Hono Server Integration\",\"entry\":\"integrations/03-hono-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/03-hono-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/hono\":\"^0.7.3\",\"@hono/node-server\":\"^2.1.3\",\"dotenv\":\"^18.0.5\",\"hono\":\"^4.13.12\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/koa-server\",\"title\":\"Koa Server Integration\",\"entry\":\"integrations/04-koa-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/04-koa-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/koa\":\"^0.7.3\",\"@koa/router\":\"^15.7.0\",\"dotenv\":\"^18.0.5\",\"koa\":\"^3.2.1\"},\"devDependencies\":{\"@types/koa\":\"^3.0.3\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/nextjs-handler\",\"title\":\"Nextjs handler\",\"entry\":\"integrations/05-nextjs-handler.ts\",\"files\":[\"integrations/05-nextjs-handler.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/next\":\"^0.8.3\",\"next\":\"^14.0.0 || ^15.0.0 || ^16.0.0\",\"react\":\"^18.2.0 || ^19.0.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/openai-compat\",\"title\":\"OpenAI-Compatible Server\",\"entry\":\"integrations/06-openai-compat.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/06-openai-compat.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/openai-compat\":\"^21.2.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/ai-sdk-adapter\",\"title\":\"Vercel AI SDK Adapter\",\"entry\":\"integrations/07-ai-sdk-adapter.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/07-ai-sdk-adapter.ts\"],\"dependencies\":{\"@cogitator-ai/ai-sdk\":\"^0.6.0\",\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/types\":\"^0.39.0\",\"ai\":\"^7.0.127\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/tetsu-server\",\"title\":\"Tetsu Server on Bun: an app with its own MCP server and agent\",\"entry\":\"integrations/08-tetsu-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/08-tetsu-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/mcp\":\"^19.3.3\",\"@cogitator-ai/tetsu\":\"^0.5.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"@tetsujs/core\":\"^0.6.1\",\"@tetsujs/openapi\":\"^0.6.1\",\"@tetsujs/sse\":\"^0.6.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"bun\"},{\"name\":\"mcp/mcp-client\",\"title\":\"MCP Client: Filesystem Server\",\"entry\":\"mcp/01-mcp-client.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/01-mcp-client.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/mcp\":\"^19.3.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/mcp-server\",\"title\":\"MCP Server: Expose Cogitator Tools over HTTP\",\"entry\":\"mcp/02-mcp-server.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/02-mcp-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/mcp\":\"^19.3.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/per-user-mcp\",\"title\":\"An Agent on Your Own MCP Server, per User\",\"entry\":\"mcp/03-per-user-mcp.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/03-per-user-mcp.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/mcp\":\"^19.3.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/agent-as-mcp-server\",\"title\":\"A Cogitator Agent as an MCP Server\",\"entry\":\"mcp/04-agent-as-mcp-server.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/04-agent-as-mcp-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/mcp\":\"^19.3.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/basic-memory\",\"title\":\"Basic Memory: Threads & Multi-Turn Conversations\",\"entry\":\"memory/01-basic-memory.ts\",\"files\":[\"_shared/setup.ts\",\"memory/01-basic-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/context-builder\",\"title\":\"Context Builder: Token-Aware Context Windows\",\"entry\":\"memory/02-context-builder.ts\",\"files\":[\"_shared/setup.ts\",\"memory/02-context-builder.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/semantic-search\",\"title\":\"Semantic Search: Hybrid BM25 + Vector Search\",\"entry\":\"memory/03-semantic-search.ts\",\"files\":[\"_shared/setup.ts\",\"memory/03-semantic-search.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"@qdrant/js-client-rest\":\"^1.10.0\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/knowledge-graph\",\"title\":\"Knowledge Graph: Entity Extraction & Graph Traversal\",\"entry\":\"memory/04-knowledge-graph.ts\",\"files\":[\"_shared/setup.ts\",\"memory/04-knowledge-graph.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"@cogitator-ai/types\":\"^0.39.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/basic-retrieval\",\"title\":\"Basic RAG Retrieval\",\"entry\":\"rag/01-basic-retrieval.ts\",\"files\":[\"_shared/setup.ts\",\"rag/01-basic-retrieval.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"@cogitator-ai/rag\":\"^0.6.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/chunking-strategies\",\"title\":\"Chunking Strategies Comparison\",\"entry\":\"rag/02-chunking-strategies.ts\",\"files\":[\"_shared/setup.ts\",\"rag/02-chunking-strategies.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"@cogitator-ai/rag\":\"^0.6.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/agent-with-rag\",\"title\":\"Agent with RAG Tools\",\"entry\":\"rag/03-agent-with-rag.ts\",\"files\":[\"_shared/setup.ts\",\"rag/03-agent-with-rag.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/memory\":\"^0.12.3\",\"@cogitator-ai/rag\":\"^0.6.3\",\"@qdrant/js-client-rest\":\"^1.10.0\",\"better-sqlite3\":\"^13.0.3\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\",\"mongodb\":\"^6.0.0 || ^7.0.0\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/debate-swarm\",\"title\":\"Debate Swarm\",\"entry\":\"swarms/01-debate-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/01-debate-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/swarms\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/pipeline-swarm\",\"title\":\"Pipeline Swarm\",\"entry\":\"swarms/02-pipeline-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/02-pipeline-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/swarms\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/hierarchical-swarm\",\"title\":\"Hierarchical Swarm\",\"entry\":\"swarms/03-hierarchical-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/03-hierarchical-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/swarms\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/negotiation-swarm\",\"title\":\"Negotiation Swarm\",\"entry\":\"swarms/04-negotiation-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/04-negotiation-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/swarms\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/pipeline\",\"title\":\"Voice Pipeline\",\"entry\":\"voice/01-pipeline.ts\",\"files\":[\"_shared/setup.ts\",\"voice/01-pipeline.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/voice\":\"^0.5.3\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/realtime\",\"title\":\"Realtime Voice Session\",\"entry\":\"voice/02-realtime.ts\",\"files\":[\"_shared/setup.ts\",\"voice/02-realtime.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/voice\":\"^0.5.3\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/voice-agent\",\"title\":\"Voice Agent (WebSocket Server)\",\"entry\":\"voice/03-voice-agent.ts\",\"files\":[\"_shared/setup.ts\",\"voice/03-voice-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/voice\":\"^0.5.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"DEEPGRAM_API_KEY\",\"ELEVENLABS_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/realtime-voice-agent\",\"title\":\"Realtime Voice Agent (Gemini Live over WebSocket)\",\"entry\":\"voice/04-realtime-voice-agent.ts\",\"files\":[\"_shared/setup.ts\",\"voice/04-realtime-voice-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/voice\":\"^0.5.3\",\"dotenv\":\"^18.0.5\",\"ws\":\"^8.22.0\"},\"devDependencies\":{\"@types/ws\":\"^8.18.2\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/basic-workflow\",\"title\":\"Basic Workflow: Code Review Pipeline\",\"entry\":\"workflows/01-basic-workflow.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/01-basic-workflow.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/workflows\":\"^0.12.3\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/human-in-loop\",\"title\":\"Human-in-the-Loop: Content Publishing Workflow\",\"entry\":\"workflows/02-human-in-loop.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/02-human-in-loop.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/workflows\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/map-reduce\",\"title\":\"Map-Reduce: Parallel Document Analysis\",\"entry\":\"workflows/03-map-reduce.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/03-map-reduce.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.37.0\",\"@cogitator-ai/workflows\":\"^0.12.3\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\"],\"runtime\":\"node\"}]","{\"@cogitator-ai/a2a\":\"0.8.3\",\"@cogitator-ai/ai-sdk\":\"0.6.0\",\"@cogitator-ai/browser\":\"0.4.13\",\"@cogitator-ai/channels\":\"0.9.3\",\"@cogitator-ai/cli\":\"0.6.4\",\"@cogitator-ai/config\":\"0.13.0\",\"@cogitator-ai/core\":\"0.37.0\",\"@cogitator-ai/deploy\":\"0.6.2\",\"@cogitator-ai/evals\":\"0.6.0\",\"@cogitator-ai/express\":\"0.8.3\",\"@cogitator-ai/fastify\":\"0.7.3\",\"@cogitator-ai/hono\":\"0.7.3\",\"@cogitator-ai/koa\":\"0.7.3\",\"@cogitator-ai/mcp\":\"19.3.3\",\"@cogitator-ai/memory\":\"0.12.3\",\"@cogitator-ai/models\":\"18.3.0\",\"@cogitator-ai/neuro-symbolic\":\"17.0.23\",\"@cogitator-ai/next\":\"0.8.3\",\"@cogitator-ai/openai-compat\":\"21.2.3\",\"@cogitator-ai/rag\":\"0.6.3\",\"@cogitator-ai/redis\":\"0.5.2\",\"@cogitator-ai/sandbox\":\"0.5.12\",\"@cogitator-ai/self-modifying\":\"19.4.3\",\"@cogitator-ai/server-shared\":\"0.5.3\",\"@cogitator-ai/studio\":\"0.1.2\",\"@cogitator-ai/swarms\":\"0.12.3\",\"@cogitator-ai/test-utils\":\"0.2.17\",\"@cogitator-ai/tetsu\":\"0.5.3\",\"@cogitator-ai/types\":\"0.39.0\",\"@cogitator-ai/voice\":\"0.5.3\",\"@cogitator-ai/wasm-tools\":\"0.7.17\",\"@cogitator-ai/worker\":\"0.9.3\",\"@cogitator-ai/workflows\":\"0.12.3\"}","import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { CodedError } from './errors.js';\nimport { installCommand, installErrorCode, packageManagerInvocation } from './package-manager.js';\nimport { planProject, type PlanOptions, type ProjectPlan } from './plan.js';\nimport { hasCommand, runCommand, tail } from './process.js';\nimport type { GeneratedFile } from './project.js';\nimport type { PackageManager } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\n/**\n * Where the scaffolder reports progress. The CLI shows it with spinners, the\n * programmatic API stays silent unless a logger is passed.\n */\nexport interface ScaffoldLogger {\n start(message: string): void;\n done(message: string): void;\n fail(message: string): void;\n warn(message: string): void;\n}\n\nexport const silentLogger: ScaffoldLogger = {\n start: () => undefined,\n done: () => undefined,\n fail: () => undefined,\n warn: () => undefined,\n};\n\n/** How an optional step went. */\nexport type StepResult =\n { status: 'done' } | { status: 'skipped'; reason: string } | { status: 'failed'; error: Error };\n\nexport interface ScaffoldOptions extends PlanOptions {\n /** The directory to create the project in. It must not exist or be empty. */\n directory: string;\n /** Run the package manager's install (default `true`). */\n install?: boolean;\n /** Initialize a git repository and commit the project (default `true`). */\n git?: boolean;\n log?: ScaffoldLogger;\n /** Show the install's output live instead of capturing it. */\n inheritOutput?: boolean;\n}\n\nexport interface ScaffoldResult {\n plan: ProjectPlan;\n directory: string;\n /** The generated files, relative to `directory`. */\n files: string[];\n install: StepResult;\n format: StepResult;\n git: StepResult;\n /** The workspace root above the project, when it was created inside one. */\n parentWorkspace?: string;\n}\n\n/** Hashes of the files the scaffolder wrote, so `cogitator add` can tell them from files the user edited. */\nexport interface ScaffoldLock {\n version: 1;\n generator: string;\n files: Record<string, string>;\n}\n\nexport const LOCK_PATH = '.cogitator/scaffold.json';\n\n/** Files the lock never tracks: they belong to the user from the first moment. */\nconst UNTRACKED = new Set(['.env']);\n\nexport function hashContent(content: string): string {\n return `sha256-${createHash('sha256').update(content).digest('hex')}`;\n}\n\nfunction failure(error: unknown): StepResult {\n return { status: 'failed', error: error instanceof Error ? error : new Error(String(error)) };\n}\n\nexport async function writeFiles(\n directory: string,\n files: readonly GeneratedFile[]\n): Promise<void> {\n for (const file of files) {\n const target = join(directory, file.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(\n target,\n file.content,\n file.mode !== undefined ? { mode: file.mode } : undefined\n );\n if (file.mode !== undefined) await chmod(target, file.mode);\n }\n}\n\nasync function saveLock(directory: string, files: Record<string, string>): Promise<void> {\n const lock: ScaffoldLock = {\n version: 1,\n generator: `create-cogitator-app@${scaffolderVersion()}`,\n files: Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))),\n };\n await mkdir(join(directory, dirname(LOCK_PATH)), { recursive: true });\n await writeFile(join(directory, LOCK_PATH), JSON.stringify(lock, null, 2) + '\\n');\n}\n\n/** Hashes `paths` as they are on disk now, `undefined` for a path that does not exist. */\nasync function hashFiles(\n directory: string,\n paths: readonly string[]\n): Promise<Map<string, string | undefined>> {\n const hashes = new Map<string, string | undefined>();\n for (const path of paths) {\n if (UNTRACKED.has(path) || path === LOCK_PATH) continue;\n const full = join(directory, path);\n hashes.set(path, existsSync(full) ? hashContent(await readFile(full, 'utf-8')) : undefined);\n }\n return hashes;\n}\n\nexport async function writeLock(directory: string, paths: readonly string[]): Promise<void> {\n const files: Record<string, string> = {};\n for (const [path, hash] of await hashFiles(directory, paths)) if (hash) files[path] = hash;\n await saveLock(directory, files);\n}\n\n/**\n * Re-hashes `paths` in the lock after `cogitator add` wrote or deleted them,\n * keeping the hashes of every other file.\n */\nexport async function updateLock(directory: string, paths: readonly string[]): Promise<void> {\n const files = { ...readLock(directory)?.files };\n for (const [path, hash] of await hashFiles(directory, paths)) {\n if (hash) files[path] = hash;\n else delete files[path];\n }\n await saveLock(directory, files);\n}\n\nexport function readLock(directory: string): ScaffoldLock | undefined {\n const path = join(directory, LOCK_PATH);\n if (!existsSync(path)) return undefined;\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('files' in parsed) ||\n typeof parsed.files !== 'object' ||\n parsed.files === null\n ) {\n throw new Error(`${LOCK_PATH} is not a scaffold lock`);\n }\n const files: Record<string, string> = {};\n for (const [file, hash] of Object.entries(parsed.files)) {\n if (typeof hash === 'string') files[file] = hash;\n }\n const generator =\n 'generator' in parsed && typeof parsed.generator === 'string' ? parsed.generator : 'unknown';\n return { version: 1, generator, files };\n}\n\n/** The local Biome binary of a project, absent before its dependencies are installed. */\nfunction biomeBinary(directory: string): string | undefined {\n const name = process.platform === 'win32' ? 'biome.cmd' : 'biome';\n const path = join(directory, 'node_modules', '.bin', name);\n return existsSync(path) ? path : undefined;\n}\n\n/**\n * Formats the generated code with the project's own Biome, so it starts clean\n * under `lint`: the whole project, or only `paths` when they are given.\n */\nexport async function formatProject(\n directory: string,\n paths: readonly string[] = ['.']\n): Promise<StepResult> {\n const biome = biomeBinary(directory);\n if (!biome) return { status: 'skipped', reason: 'Biome is not installed' };\n if (paths.length === 0) return { status: 'skipped', reason: 'nothing to format' };\n const result = await runCommand(\n biome,\n ['check', '--write', '--no-errors-on-unmatched', ...paths],\n { cwd: directory }\n );\n if (result.code !== 0)\n return failure(new Error(`biome check --write failed:\\n${tail(result.output)}`));\n return { status: 'done' };\n}\n\n/** The git work tree `directory` is inside of, if any. */\nexport async function enclosingGitRepo(directory: string): Promise<string | undefined> {\n let dir = resolve(directory);\n while (!existsSync(dir)) dir = dirname(dir);\n try {\n const result = await runCommand('git', ['rev-parse', '--show-toplevel'], { cwd: dir });\n return result.code === 0 ? result.output.trim() : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The nearest pnpm, npm, Yarn or Bun workspace root above `directory`, if any. */\nexport function enclosingWorkspace(directory: string): string | undefined {\n let dir = dirname(resolve(directory));\n for (;;) {\n if (existsSync(join(dir, 'pnpm-workspace.yaml'))) return dir;\n const manifest = join(dir, 'package.json');\n if (existsSync(manifest)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(manifest, 'utf-8'));\n if (typeof parsed === 'object' && parsed !== null && 'workspaces' in parsed) return dir;\n } catch {\n return undefined;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\nconst GIT_IDENTITY = [\n '-c',\n 'user.name=create-cogitator-app',\n '-c',\n 'user.email=create-cogitator-app@localhost',\n];\n\nasync function gitHasIdentity(cwd: string): Promise<boolean> {\n const name = await runCommand('git', ['config', 'user.name'], { cwd });\n const email = await runCommand('git', ['config', 'user.email'], { cwd });\n return (\n name.code === 0 && email.code === 0 && name.output.trim() !== '' && email.output.trim() !== ''\n );\n}\n\nexport async function initGit(directory: string): Promise<StepResult> {\n if (!(await hasCommand('git', directory)))\n return { status: 'skipped', reason: 'git is not installed' };\n const repo = await enclosingGitRepo(directory);\n if (repo) {\n return { status: 'skipped', reason: `the project is inside the git repository at ${repo}` };\n }\n for (const args of [\n ['init', '--quiet'],\n ['add', '-A'],\n ]) {\n const result = await runCommand('git', args, { cwd: directory });\n if (result.code !== 0)\n return failure(new Error(`git ${args[0]} failed:\\n${tail(result.output)}`));\n }\n const identity = (await gitHasIdentity(directory)) ? [] : GIT_IDENTITY;\n const commit = await runCommand(\n 'git',\n [...identity, 'commit', '--quiet', '-m', 'feat: initial project from create-cogitator-app'],\n { cwd: directory }\n );\n if (commit.code !== 0) return failure(new Error(`git commit failed:\\n${tail(commit.output)}`));\n return { status: 'done' };\n}\n\n/**\n * Installs the dependencies with `pm`: the one that launched the scaffolder\n * when it is `pm`, else the one on PATH. A failed install resolves with its\n * error and the code it names its cause with, it never throws.\n */\nexport async function installDependencies(\n directory: string,\n pm: PackageManager,\n inherit: boolean\n): Promise<StepResult> {\n const invocation = packageManagerInvocation(pm, ['install']);\n if (invocation.fromPath && !(await hasCommand(pm, directory))) {\n return failure(\n new CodedError(\n 'PM_NOT_FOUND',\n `${pm} is not installed, install it or pick another one with --pm`\n )\n );\n }\n try {\n const result = await runCommand(invocation.command, invocation.args, {\n cwd: directory,\n inherit,\n ...(!invocation.fromPath && { shell: false }),\n });\n if (result.code !== 0) {\n return failure(\n new CodedError(\n installErrorCode(result.output, result.code),\n `${installCommand(pm)} exited with ${result.code}:\\n${tail(result.output)}`\n )\n );\n }\n return { status: 'done' };\n } catch (error) {\n return failure(error);\n }\n}\n\nexport function assertEmptyDirectory(directory: string): void {\n if (existsSync(directory) && readdirSync(directory).length > 0) {\n throw new CodedError('DIRECTORY_NOT_EMPTY', `${directory} already exists and is not empty`);\n }\n}\n\n/**\n * Creates the project `spec` describes in `options.directory`, then installs\n * its dependencies, formats it and commits it to a new git repository. Throws\n * when the spec is invalid or the directory is taken. A failed install, format\n * or git step does not throw: the result reports it and the project stays.\n */\nexport async function scaffold(spec: unknown, options: ScaffoldOptions): Promise<ScaffoldResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n const plan = planProject(spec, options);\n assertEmptyDirectory(directory);\n\n log.start('Writing project files');\n await mkdir(directory, { recursive: true });\n await writeFiles(directory, plan.files);\n log.done(`Wrote ${plan.files.length} files`);\n\n let install: StepResult = { status: 'skipped', reason: 'install was turned off' };\n if (options.install !== false) {\n log.start(`Installing dependencies with ${plan.spec.packageManager}`);\n install = await installDependencies(\n directory,\n plan.spec.packageManager,\n options.inheritOutput ?? false\n );\n if (install.status === 'done') log.done('Installed dependencies');\n else\n log.fail(\n `Could not install dependencies, run \"${installCommand(plan.spec.packageManager)}\" yourself`\n );\n }\n\n let format: StepResult = { status: 'skipped', reason: 'dependencies are not installed' };\n if (install.status === 'done') {\n log.start('Formatting the code');\n format = await formatProject(directory);\n if (format.status === 'done') log.done('Formatted the code');\n else if (format.status === 'failed') log.warn(format.error.message);\n }\n\n await writeLock(\n directory,\n plan.files.map((file) => file.path)\n );\n\n let git: StepResult = { status: 'skipped', reason: 'git was turned off' };\n if (options.git !== false) {\n log.start('Creating a git repository');\n git = await initGit(directory);\n if (git.status === 'done') log.done('Created a git repository with the first commit');\n else if (git.status === 'skipped') log.done(`Skipped git: ${git.reason}`);\n else log.fail(git.error.message);\n }\n\n const parentWorkspace = enclosingWorkspace(directory);\n return {\n plan,\n directory,\n files: plan.files.map((file) => file.path),\n install,\n format,\n git,\n ...(parentWorkspace && { parentWorkspace }),\n };\n}\n","/**\n * A failure with a short, stable `code` that names its cause, such as\n * `HTTP_404` or `DIRECTORY_NOT_EMPTY`. The code holds no path, name or anything\n * a user typed, which is what lets telemetry report it.\n */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'CodedError';\n this.code = code;\n }\n}\n\n/** `ConnectionRefused` or `TypeError` as a code: `CONNECTION_REFUSED`, `TYPE_ERROR`. */\nexport function constantCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();\n}\n","import { existsSync } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport { PACKAGE_MANAGERS, type PackageManager } from './spec.js';\n\n/**\n * The package manager that launched the scaffolder, read from the\n * `npm_config_user_agent` it sets (`npm/10.9.8 node/v22...` under npx), or pnpm\n * when there is none.\n */\nexport function detectPackageManager(\n userAgent: string | undefined = process.env.npm_config_user_agent\n): PackageManager {\n const name = userAgent?.split('/')[0];\n return PACKAGE_MANAGERS.find((pm) => pm === name) ?? 'pnpm';\n}\n\n/**\n * The `packageManager` field for the pnpm, Yarn or Bun that runs the scaffolder,\n * e.g. `pnpm@10.26.0`, so corepack and the deploy image install with the same\n * version. Undefined for npm, which corepack leaves alone, and when the version\n * is unknown.\n */\nexport function detectPackageManagerSpec(\n pm: PackageManager,\n userAgent: string | undefined = process.env.npm_config_user_agent\n): string | undefined {\n if (pm === 'npm') return undefined;\n const match = /^(pnpm|yarn|bun)\\/(\\d+\\.\\d+\\.\\d+[^\\s]*)/.exec(userAgent?.trim() ?? '');\n return match?.[1] === pm ? `${match[1]}@${match[2]}` : undefined;\n}\n\n/** The command that runs the package.json script `script`. */\nexport function runScript(pm: PackageManager, script: string, args = ''): string {\n const base = pm === 'npm' ? `npm run ${script}` : `${pm} ${script}`;\n if (!args) return base;\n return pm === 'npm' ? `${base} -- ${args}` : `${base} ${args}`;\n}\n\n/** The command that runs a binary of an installed package. */\nexport function execCommand(pm: PackageManager, bin: string): string {\n if (pm === 'npm') return `npx ${bin}`;\n if (pm === 'bun') return `bunx ${bin}`;\n return `${pm} exec ${bin}`;\n}\n\n/** How to run a package manager: its command, and whether it is looked up on PATH. */\nexport interface PackageManagerInvocation {\n command: string;\n args: readonly string[];\n fromPath: boolean;\n}\n\n/**\n * The package manager that launched this process, from the `npm_execpath` it\n * sets, when that is `pm`: its JavaScript entry or its binary. npx sets the\n * path of npx-cli.js, whose npm-cli.js sits next to it.\n */\nfunction launchingPackageManager(pm: PackageManager, env: NodeJS.ProcessEnv): string | undefined {\n const execPath = env.npm_execpath;\n if (!execPath || env.npm_config_user_agent?.split('/')[0] !== pm) return undefined;\n const path =\n pm === 'npm' && basename(execPath) === 'npx-cli.js'\n ? join(dirname(execPath), 'npm-cli.js')\n : execPath;\n return existsSync(path) ? path : undefined;\n}\n\n/**\n * How to run `pm` with `args`: the very package manager that launched the\n * scaffolder when it is `pm`, so one that is not on PATH (a standalone binary,\n * one started by its full path) still runs, and at the version that launched\n * it. Otherwise `pm` from PATH.\n */\nexport function packageManagerInvocation(\n pm: PackageManager,\n args: readonly string[],\n env: NodeJS.ProcessEnv = process.env\n): PackageManagerInvocation {\n const launcher = launchingPackageManager(pm, env);\n if (!launcher) return { command: pm, args, fromPath: true };\n return /\\.[cm]?js$/.test(launcher)\n ? { command: process.execPath, args: [launcher, ...args], fromPath: false }\n : { command: launcher, args, fromPath: false };\n}\n\nexport function installCommand(pm: PackageManager): string {\n return `${pm} install`;\n}\n\nconst SYSTEM_CODES = [\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n 'EPROTO',\n 'EACCES',\n 'EPERM',\n 'ENOSPC',\n 'ENOENT',\n 'EINTEGRITY',\n 'ELIFECYCLE',\n] as const;\n\nconst PNPM_CODES = new Set([\n 'NO_MATCHING_VERSION',\n 'NO_MATURE_MATCHING_VERSION',\n 'NO_VERSIONS',\n 'META_FETCH_FAIL',\n 'TARBALL_INTEGRITY',\n 'BAD_TARBALL_SIZE',\n 'PEER_DEP_ISSUES',\n 'UNSUPPORTED_ENGINE',\n 'UNSUPPORTED_PLATFORM',\n 'OUTDATED_LOCKFILE',\n 'BROKEN_LOCKFILE',\n 'LOCKFILE_BREAKING_CHANGE',\n 'LOCKFILE_MISSING_DEPENDENCY',\n 'NO_OFFLINE_META',\n 'NO_OFFLINE_TARBALL',\n 'LINKING_FAILED',\n 'UNEXPECTED_STORE',\n 'STORE_BREAKING_CHANGE',\n 'SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER',\n 'IGNORED_BUILDS',\n 'INVALID_PACKAGE_NAME',\n 'PREPARE_PACKAGE',\n ...SYSTEM_CODES,\n]);\n\nconst NPM_CODES = new Set<string>([\n 'ETARGET',\n 'ENOVERSIONS',\n 'ERESOLVE',\n 'EBADENGINE',\n 'EBADPLATFORM',\n 'ENOTSUP',\n 'EJSONPARSE',\n 'EUNSUPPORTEDPROTOCOL',\n ...SYSTEM_CODES,\n]);\n\n/** Bun's names for network failures, as the Node codes npm and pnpm report. */\nconst BUN_ERRORS: Record<string, string> = {\n ConnectionRefused: 'ECONNREFUSED',\n ConnectionResetByPeer: 'ECONNRESET',\n ConnectionClosed: 'ECONNRESET',\n ConnectionTimedOut: 'ETIMEDOUT',\n Timeout: 'ETIMEDOUT',\n NetworkUnreachable: 'ENETUNREACH',\n HostUnreachable: 'EHOSTUNREACH',\n};\n\nconst HTTP_ERROR = /^[45]\\d\\d$/;\n\nconst READERS: ReadonlyArray<(output: string) => string | undefined> = [\n (output) => {\n const code = /\\bERR_PNPM_([A-Z0-9_]+)/.exec(output)?.[1];\n if (code === undefined) return undefined;\n const known = PNPM_CODES.has(code) || /^FETCH_[45]\\d\\d$/.test(code);\n return known ? `ERR_PNPM_${code}` : 'ERR_PNPM_OTHER';\n },\n (output) => {\n const code = /^npm (?:ERR!|error) code (\\S+)/m.exec(output)?.[1];\n if (code === undefined) return undefined;\n if (NPM_CODES.has(code)) return code;\n if (/^E[45]\\d\\d$/.test(code)) return code;\n return /^npm (?:ERR!|error) command failed/m.test(output) ? 'ELIFECYCLE' : 'NPM_OTHER';\n },\n (output) =>\n [...output.matchAll(/\\bYN(\\d{4}):/g)]\n .map((match) => Number(match[1]))\n .filter((code) => code > 1 && code < 100)\n .map((code) => `YN${String(code).padStart(4, '0')}`)\n .at(-1),\n (output) =>\n /^error:? (?:No version matching |Couldn't find any versions for )/m.test(output)\n ? 'NO_MATCHING_VERSION'\n : undefined,\n (output) => {\n const status = /^error: GET \\S+ - (\\d{3})$/m.exec(output)?.[1];\n return status && HTTP_ERROR.test(status) ? `HTTP_${status}` : undefined;\n },\n (output) => (/^error Error: https?:\\/\\/\\S+: Not found/m.test(output) ? 'HTTP_404' : undefined),\n (output) =>\n /^error:? (?:\\S+ script from .* exited with|Command failed with exit code) \\d+/m.test(output)\n ? 'ELIFECYCLE'\n : undefined,\n (output) => {\n const name = /^error: ([A-Za-z]+) /m.exec(output)?.[1];\n return name !== undefined && Object.hasOwn(BUN_ERRORS, name) ? BUN_ERRORS[name] : undefined;\n },\n (output) => SYSTEM_CODES.find((code) => new RegExp(`\\\\b${code}\\\\b`).test(output)),\n];\n\n/**\n * The code a failed install names its cause with, read from the package\n * manager's output: pnpm's `ERR_PNPM_*`, npm's `code E*`, Yarn's last `YN*`\n * code other than the informational `YN0000` and the generic `YN0001`, a code\n * for the messages of Bun and Yarn 1, which have none (`NO_MATCHING_VERSION`,\n * `HTTP_404`, `ELIFECYCLE`, Bun's network errors as Node codes), or a Node\n * network or file system code in the output. Else the exit code, as `EXIT_1`.\n *\n * The output is not trusted, since install scripts print into it, so every\n * code comes from a closed set: a pnpm or npm code that is not a known one\n * becomes `ERR_PNPM_OTHER` or `NPM_OTHER`, and nothing else of the output is\n * ever returned.\n */\nexport function installErrorCode(output: string, exitCode: number): string {\n for (const read of READERS) {\n const code = read(output);\n if (code !== undefined) return code;\n }\n return /\\bYN0001:/.test(output) ? 'YN0001' : `EXIT_${exitCode}`;\n}\n\n/**\n * The install command CI runs: reproducible from the lockfile. Yarn 2 and\n * later spell it `--immutable`, Yarn 1 `--frozen-lockfile`, which is also what\n * corepack runs when package.json names no Yarn version.\n */\nexport function ciInstallCommand(pm: PackageManager, packageManagerSpec?: string): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm install --frozen-lockfile';\n case 'npm':\n return 'npm ci';\n case 'yarn': {\n const major = Number.parseInt(/^yarn@(\\d+)/.exec(packageManagerSpec ?? '')?.[1] ?? '1', 10);\n return major >= 2 ? 'yarn install --immutable' : 'yarn install --frozen-lockfile';\n }\n case 'bun':\n return 'bun install --frozen-lockfile';\n }\n}\n\nexport const LOCKFILES: Record<PackageManager, string> = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n bun: 'bun.lock',\n};\n","import { z } from 'zod';\n\nexport const PROVIDERS = ['ollama', 'openai', 'anthropic', 'google'] as const;\nexport const APP_KINDS = ['script', 'server', 'next', 'channels', 'worker'] as const;\nexport const SERVERS = ['express', 'fastify', 'hono', 'koa', 'tetsu'] as const;\nexport const MEMORIES = ['none', 'memory', 'sqlite', 'postgres', 'redis', 'mongodb'] as const;\nexport const VECTOR_STORES = ['memory', 'postgres', 'qdrant'] as const;\nexport const FEATURES = [\n 'harness',\n 'mcp',\n 'rag',\n 'workflows',\n 'durable',\n 'swarms',\n 'evals',\n 'otel',\n 'langfuse',\n 'voice',\n 'sandbox',\n 'a2a',\n] as const;\nexport const DEPLOY_TARGETS = ['none', 'docker', 'fly'] as const;\nexport const CODING_AGENTS = ['claude', 'cursor', 'codex'] as const;\nexport const PACKAGE_MANAGERS = ['pnpm', 'npm', 'yarn', 'bun'] as const;\nexport const CHANNELS = ['telegram', 'discord', 'slack', 'webchat'] as const;\n\nexport type LLMProvider = (typeof PROVIDERS)[number];\nexport type AppKind = (typeof APP_KINDS)[number];\nexport type ServerFramework = (typeof SERVERS)[number];\nexport type MemoryKind = (typeof MEMORIES)[number];\nexport type VectorStore = (typeof VECTOR_STORES)[number];\nexport type FeatureId = (typeof FEATURES)[number];\nexport type DeployTarget = (typeof DEPLOY_TARGETS)[number];\nexport type CodingAgent = (typeof CODING_AGENTS)[number];\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number];\nexport type ChannelKind = (typeof CHANNELS)[number];\n\nconst PACKAGE_NAME = /^[a-z0-9][a-z0-9._-]*$/;\nconst MAX_NAME_LENGTH = 214;\n\n/**\n * Why `name` cannot be the generated package's name, or `undefined` when it can.\n * The name lands in package.json and in generated code, so it has to be a valid\n * unscoped npm package name.\n */\nexport function validateProjectName(name: string): string | undefined {\n const trimmed = name.trim();\n if (!trimmed) return 'Project name is required';\n if (trimmed.length > MAX_NAME_LENGTH) return `Use at most ${MAX_NAME_LENGTH} characters`;\n if (!PACKAGE_NAME.test(trimmed)) {\n return 'Use lowercase letters, digits, \".\", \"_\" or \"-\", starting with a letter or digit';\n }\n return undefined;\n}\n\nconst ProjectNameSchema = z.string().superRefine((value, ctx) => {\n const error = validateProjectName(value);\n if (error) ctx.addIssue({ code: 'custom', message: error });\n});\n\n/**\n * Everything that decides what a generated project contains. A spec is plain data:\n * it is stored in the project's package.json (`cogitator.spec`) so the project can\n * be regenerated and extended with `cogitator add`, and it never holds secrets.\n */\nexport const ProjectSpecSchema = z\n .object({\n name: ProjectNameSchema,\n preset: z.string().min(1).optional(),\n app: z.enum(APP_KINDS),\n server: z.enum(SERVERS).optional(),\n channels: z.array(z.enum(CHANNELS)).default([]),\n memory: z.enum(MEMORIES),\n vectorStore: z.enum(VECTOR_STORES).default('memory'),\n features: z.array(z.enum(FEATURES)).default([]),\n provider: z.enum(PROVIDERS),\n model: z.string().trim().min(1),\n deploy: z.enum(DEPLOY_TARGETS).default('none'),\n compose: z.boolean().default(true),\n packageManager: z.enum(PACKAGE_MANAGERS),\n codingAgents: z.array(z.enum(CODING_AGENTS)).default([]),\n })\n .strict();\n\nexport type ProjectSpec = z.output<typeof ProjectSpecSchema>;\nexport type ProjectSpecInput = z.input<typeof ProjectSpecSchema>;\n\n/** `items` without duplicates, in the canonical order of `order`. */\nexport function canonical<T extends string>(items: readonly T[], order: readonly T[]): T[] {\n const set = new Set(items);\n return order.filter((item) => set.has(item));\n}\n\n/**\n * Parses and normalizes a spec: lists are deduplicated and sorted the way the\n * catalogs list them, so two specs that mean the same project are equal.\n */\nexport function parseSpec(input: unknown): ProjectSpec {\n const spec = ProjectSpecSchema.parse(input);\n return {\n ...spec,\n channels: canonical(spec.channels, CHANNELS),\n features: canonical(spec.features, FEATURES),\n codingAgents: canonical(spec.codingAgents, CODING_AGENTS),\n };\n}\n\nexport function hasFeature(spec: Pick<ProjectSpec, 'features'>, feature: FeatureId): boolean {\n return spec.features.includes(feature);\n}\n\n/** The model as the runtime addresses it: `provider/model`. */\nexport function qualifiedModel(spec: Pick<ProjectSpec, 'provider' | 'model'>): string {\n const prefix = `${spec.provider}/`;\n return spec.model.startsWith(prefix) ? spec.model : `${prefix}${spec.model}`;\n}\n\n/** The model without the provider prefix, as provider APIs and `ollama pull` name it. */\nexport function bareModel(spec: Pick<ProjectSpec, 'provider' | 'model'>): string {\n const prefix = `${spec.provider}/`;\n return spec.model.startsWith(prefix) ? spec.model.slice(prefix.length) : spec.model;\n}\n\n/** What `start` runs in a script project: the assistant, the workflow, the swarm or the voice server. */\nexport type PrimaryTarget = 'agent' | 'workflow' | 'swarm' | 'voice';\n\nexport function primaryTarget(spec: Pick<ProjectSpec, 'features'>): PrimaryTarget {\n if (hasFeature(spec, 'voice')) return 'voice';\n if (hasFeature(spec, 'workflows')) return 'workflow';\n if (hasFeature(spec, 'swarms')) return 'swarm';\n return 'agent';\n}\n\n/** Whether the project runs on Bun instead of Node. */\nexport function runsOnBun(spec: Pick<ProjectSpec, 'server'>): boolean {\n return spec.server === 'tetsu';\n}\n","import type { LLMProvider } from './spec.js';\n\nexport interface ProviderInfo {\n id: LLMProvider;\n label: string;\n /** The variable the API key is read from, absent for providers without one. */\n envKey?: string;\n /** Where to create an API key. */\n keyUrl?: string;\n /** The model a new project uses unless another one is chosen. */\n defaultModel: string;\n /** The embedding model RAG uses with this provider, absent when it has none. */\n embeddingModel?: string;\n /** The dimensions of `embeddingModel`, which vector stores size their collections by. */\n embeddingDimensions?: number;\n /** Whether the provider has a realtime voice API Cogitator drives. */\n realtime: boolean;\n /** A short line for prompts and `--help`. */\n hint: string;\n}\n\nexport const PROVIDER_INFO: Record<LLMProvider, ProviderInfo> = {\n ollama: {\n id: 'ollama',\n label: 'Ollama',\n defaultModel: 'qwen3.5:9b',\n embeddingModel: 'nomic-embed-text',\n embeddingDimensions: 768,\n realtime: false,\n hint: 'local and free, needs Ollama running',\n },\n openai: {\n id: 'openai',\n label: 'OpenAI',\n envKey: 'OPENAI_API_KEY',\n keyUrl: 'https://platform.openai.com/api-keys',\n defaultModel: 'gpt-6.1-sol',\n embeddingModel: 'text-embedding-3-small',\n embeddingDimensions: 1536,\n realtime: true,\n hint: 'GPT models, needs OPENAI_API_KEY',\n },\n anthropic: {\n id: 'anthropic',\n label: 'Anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n keyUrl: 'https://console.anthropic.com/settings/keys',\n defaultModel: 'claude-sonnet-5-5',\n realtime: false,\n hint: 'Claude models, needs ANTHROPIC_API_KEY',\n },\n google: {\n id: 'google',\n label: 'Google Gemini',\n envKey: 'GOOGLE_API_KEY',\n keyUrl: 'https://aistudio.google.com/apikey',\n defaultModel: 'gemini-3.8-flash',\n embeddingModel: 'gemini-embedding-001',\n embeddingDimensions: 768,\n realtime: true,\n hint: 'Gemini models, needs GOOGLE_API_KEY',\n },\n};\n\nexport function providerInfo(provider: LLMProvider): ProviderInfo {\n return PROVIDER_INFO[provider];\n}\n\nexport function providerEnvKey(provider: LLMProvider): string | undefined {\n return PROVIDER_INFO[provider].envKey;\n}\n\nexport function defaultModel(provider: LLMProvider): string {\n return PROVIDER_INFO[provider].defaultModel;\n}\n\n/**\n * Small models with reliable tool calling that run on a laptop, offered when\n * Ollama is not reachable to list what is installed.\n */\nexport const OLLAMA_SUGGESTED_MODELS = [\n 'qwen3.5:9b',\n 'qwen3.5:4b',\n 'gemma4:e4b',\n 'llama3.1:8b',\n 'mistral-small3.2:24b',\n] as const;\n\nexport const DEFAULT_OLLAMA_URL = 'http://localhost:11434';\n","import { providerInfo } from './providers.js';\nimport { hasFeature, type ProjectSpec } from './spec.js';\n\n/** A combination the generated project could not work with, and how to fix it. */\nexport interface CompatIssue {\n message: string;\n fix: string;\n}\n\nconst A2A_SERVERS = new Set(['express', 'fastify', 'hono', 'koa']);\n\n/**\n * Every reason `spec` describes a project that would not work, empty when it is\n * consistent. Checked before any file is written, so an impossible project is\n * refused instead of generated half-broken.\n */\nexport function compatibilityIssues(spec: ProjectSpec): CompatIssue[] {\n const issues: CompatIssue[] = [];\n const provider = providerInfo(spec.provider);\n\n if (spec.app === 'server' && !spec.server) {\n issues.push({\n message: 'A server app needs a server framework',\n fix: 'pass --server hono, express, fastify, koa or tetsu',\n });\n }\n if (spec.app !== 'server' && spec.server) {\n issues.push({\n message: `--server ${spec.server} only applies to the server app`,\n fix: 'pass --app server, or leave out --server',\n });\n }\n\n if (spec.app === 'channels' && spec.channels.length === 0) {\n issues.push({\n message: 'A messaging bot needs at least one channel',\n fix: 'pass --channels webchat, telegram, discord or slack',\n });\n }\n if (spec.app !== 'channels' && spec.channels.length > 0) {\n issues.push({\n message: '--channels only applies to the messaging bot app',\n fix: 'pass --app channels, or leave out --channels',\n });\n }\n\n if (spec.server === 'tetsu' && spec.packageManager !== 'bun') {\n issues.push({\n message: 'Tetsu servers run on Bun',\n fix: 'pass --pm bun, or pick another --server',\n });\n }\n\n if (spec.server === 'tetsu' && (spec.memory === 'sqlite' || hasFeature(spec, 'harness'))) {\n issues.push({\n message:\n 'better-sqlite3, which SQLite memory and the assistant harness use, does not run on Bun',\n fix: 'use --memory memory, redis, postgres or mongodb with Tetsu, or another --server',\n });\n }\n\n if (hasFeature(spec, 'durable') && !hasFeature(spec, 'workflows')) {\n issues.push({\n message: 'Durable workflows build on the workflows feature',\n fix: 'add workflows to --features',\n });\n }\n\n if (hasFeature(spec, 'rag') && !provider.embeddingModel) {\n issues.push({\n message: `RAG needs embeddings, and ${provider.label} has no embedding API`,\n fix: 'use --provider openai, google or ollama for a RAG project',\n });\n }\n if (spec.vectorStore !== 'memory' && !hasFeature(spec, 'rag')) {\n issues.push({\n message: `--vector-store ${spec.vectorStore} only applies to RAG`,\n fix: 'add rag to --features, or leave out --vector-store',\n });\n }\n\n if (hasFeature(spec, 'voice')) {\n if (!provider.realtime) {\n issues.push({\n message: `Realtime voice needs a realtime API, and ${provider.label} has none`,\n fix: 'use --provider openai or google for a voice project',\n });\n }\n }\n if (hasFeature(spec, 'voice') && spec.app !== 'script') {\n issues.push({\n message: 'The voice feature serves its own page and WebSocket as the app',\n fix: 'use --app script for a voice agent',\n });\n }\n\n if (hasFeature(spec, 'a2a')) {\n const servable =\n spec.app === 'next' || (spec.app === 'server' && A2A_SERVERS.has(spec.server ?? ''));\n if (!servable) {\n issues.push({\n message: 'A2A serves agents over HTTP from Express, Fastify, Hono, Koa or Next.js',\n fix: 'use --app server with --server hono, express, fastify or koa, or --app next',\n });\n }\n }\n\n if (hasFeature(spec, 'mcp') && spec.app === 'next') {\n issues.push({\n message:\n 'The MCP feature starts MCP servers as child processes, which a Next.js deployment cannot',\n fix: 'use --app script, server, channels or worker for MCP',\n });\n }\n\n if (spec.app === 'next' && spec.server) {\n issues.push({ message: 'Next.js is its own server', fix: 'leave out --server' });\n }\n\n if (spec.deploy === 'fly' && spec.memory === 'mongodb') {\n issues.push({\n message: 'Fly.io has no managed MongoDB the deploy can provision',\n fix: 'use --memory postgres, redis or sqlite with --deploy fly',\n });\n }\n\n return issues;\n}\n\nexport class IncompatibleSpecError extends Error {\n readonly code = 'INCOMPATIBLE_SPEC';\n readonly issues: CompatIssue[];\n\n constructor(issues: CompatIssue[]) {\n super(\n [\n 'The chosen options do not fit together:',\n ...issues.map((i) => `- ${i.message}: ${i.fix}`),\n ].join('\\n')\n );\n this.name = 'IncompatibleSpecError';\n this.issues = issues;\n }\n}\n\nexport function assertCompatible(spec: ProjectSpec): void {\n const issues = compatibilityIssues(spec);\n if (issues.length > 0) throw new IncompatibleSpecError(issues);\n}\n","/**\n * Source text for a generated file, written as an indented template literal.\n *\n * Escapes work as in any template literal: write `\\\\n` for a backslash and an\n * `n` in the generated code, `` \\` `` for a backtick and `\\${` for `${`.\n *\n * The common indentation of the template is removed, so a template can follow the\n * indentation of the code that writes it. A multi-line value is indented to the column\n * of its placeholder, so a nested block lands where it is interpolated. `false`, `null`\n * and `undefined` render as nothing, and a line left blank by them is dropped, which\n * makes `${cond && 'line'}` an optional line. Runs of blank lines collapse to one, and\n * the result ends with exactly one newline.\n */\nexport function code(strings: TemplateStringsArray, ...values: unknown[]): string {\n const parts = Array.from(strings, (part, index) => {\n if (part === undefined)\n throw new Error(`Invalid escape sequence in code template part ${index}`);\n return part;\n });\n const dropped = new Set<number>();\n let out = '';\n\n for (let i = 0; i < parts.length; i++) {\n out += parts[i];\n if (i >= values.length) break;\n\n const value = values[i];\n if (value === false || value === null || value === undefined) {\n dropped.add(lineIndex(out));\n continue;\n }\n\n const text = String(value).replace(/\\n$/, '');\n const lineStart = out.lastIndexOf('\\n') + 1;\n const indent = /^[ \\t]*/.exec(out.slice(lineStart))?.[0] ?? '';\n out += text.replace(/\\n(?=[^\\n])/g, `\\n${indent}`);\n }\n\n const lines = out.split('\\n');\n const kept = lines.filter((line, index) => !(dropped.has(index) && line.trim() === ''));\n return finish(dedent(kept));\n}\n\nfunction lineIndex(text: string): number {\n let count = 0;\n for (const char of text) if (char === '\\n') count++;\n return count;\n}\n\nfunction dedent(lines: string[]): string[] {\n while (lines.length > 0 && lines[0].trim() === '') lines.shift();\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();\n\n let common = Infinity;\n for (const line of lines) {\n if (line.trim() === '') continue;\n common = Math.min(common, /^ */.exec(line)?.[0].length ?? 0);\n }\n if (!Number.isFinite(common) || common === 0) return lines;\n return lines.map((line) => (line.trim() === '' ? '' : line.slice(common)));\n}\n\nfunction finish(lines: string[]): string {\n const collapsed: string[] = [];\n for (const line of lines) {\n const blank = line.trim() === '';\n if (blank && collapsed.length > 0 && collapsed[collapsed.length - 1] === '') continue;\n collapsed.push(blank ? '' : line.replace(/[ \\t]+$/, ''));\n }\n return collapsed.join('\\n') + '\\n';\n}\n\n/** `value` as a single-quoted TypeScript string literal, safe for any input. */\nexport function tsString(value: string): string {\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\p{Zl}/gu, '\\\\u2028')\n .replace(/\\p{Zp}/gu, '\\\\u2029');\n return `'${escaped}'`;\n}\n\n/** `name` as a property key: bare when it is an identifier, quoted otherwise. */\nexport function tsKey(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : tsString(name);\n}\n\n/** A YAML scalar for `value`, quoted only when YAML would read it as something else. */\nexport function yamlString(value: string): string {\n if (value === '' || /^[\\s]|[\\s]$/.test(value)) return JSON.stringify(value);\n if (/^(true|false|yes|no|on|off|null|~|[-+]?\\d[\\d._:eE+-]*)$/i.test(value)) {\n return JSON.stringify(value);\n }\n if (/[:#{}[\\],&*!|>'\"%@`]|^[-?]/.test(value)) return JSON.stringify(value);\n return value;\n}\n","declare const __COGITATOR_VERSIONS__: Record<string, string> | undefined;\ndeclare const __SCAFFOLDER_VERSION__: string | undefined;\n\n/** The version of create-cogitator-app itself, inlined at build time. */\nexport function scaffolderVersion(): string {\n return typeof __SCAFFOLDER_VERSION__ === 'undefined' ? '0.0.0' : __SCAFFOLDER_VERSION__;\n}\n\n/**\n * The versions of the `@cogitator-ai/*` packages, inlined when the scaffolder is\n * built (and when its tests run) from the workspace it is released from.\n */\nfunction workspaceVersions(): Record<string, string> {\n return typeof __COGITATOR_VERSIONS__ === 'undefined' ? {} : __COGITATOR_VERSIONS__;\n}\n\nexport type CogitatorPackage = `@cogitator-ai/${string}`;\n\n/** The range a generated project depends on for `name`: a caret on the version released with the scaffolder. */\nexport function cogitatorVersion(name: CogitatorPackage): string {\n const version = workspaceVersions()[name];\n if (!version) {\n throw new Error(`${name} is not a published @cogitator-ai package, so its version is unknown`);\n }\n return `^${version}`;\n}\n\n/** Every `@cogitator-ai/*` version the scaffolder knows, for `--json` and diagnostics. */\nexport function knownCogitatorVersions(): Record<string, string> {\n return { ...workspaceVersions() };\n}\n\n/**\n * Third-party packages generated projects depend on, in one place so every\n * feature asks for the same range. Ranges follow the current majors.\n */\nexport const VERSIONS = {\n zod: '^4.6.5',\n typescript: '^7.0.2',\n typesNode: '^24.19.1',\n tsx: '^4.23.15',\n vitest: '^5.0.3',\n biome: '^2.5.15',\n express: '^5.2.1',\n typesExpress: '^5.0.6',\n fastify: '^5.12.5',\n fastifyCors: '^11.3.0',\n hono: '^4.13.13',\n honoNodeServer: '^2.1.3',\n koa: '^3.2.1',\n koaRouter: '^15.7.0',\n typesKoa: '^3.0.3',\n typesKoaRouter: '^15.0.0',\n koaCors: '^5.0.0',\n typesKoaCors: '^5.0.1',\n koaBodyparser: '^6.1.0',\n tetsuCore: '^0.6.3',\n tetsuSse: '^0.6.3',\n tetsuOpenapi: '^0.6.3',\n typesBun: '^1.4.2',\n next: '^16.4.0',\n react: '^19.3.0',\n reactDom: '^19.3.0',\n typesReact: '^19.3.0',\n typesReactDom: '^19.3.0',\n tailwind: '^4.3.3',\n tailwindPostcss: '^4.3.3',\n reactMarkdown: '^10.1.0',\n betterSqlite3: '^13.0.3',\n pg: '^8.23.1',\n ioredis: '^6.0.0',\n mongodb: '^7.7.0',\n qdrant: '^1.19.0',\n grammy: '^1.46.0',\n discord: '^14.27.0',\n slackBolt: '^5.1.0',\n ws: '^8.22.0',\n langfuse: '^3.39.2',\n modelContextProtocol: '^1.32.1',\n} as const;\n\n/** Container images compose and deploy use, pinned so a project starts the same way every time. */\nexport const IMAGES = {\n redis: 'redis:8.8-alpine',\n postgres: 'pgvector/pgvector:0.8.7-pg18-trixie',\n mongodb: 'mongo:8.3',\n qdrant: 'qdrant/qdrant:v1.19.2',\n ollama: 'ollama/ollama:0.40.0',\n jaeger: 'jaegertracing/jaeger:2.22.0',\n} as const;\n\n/** The Node.js versions generated projects support: `--env-file-if-exists` needs 22.9+. */\nexport const NODE_ENGINES = '>=22.12.0';\n\n/** The Bun version Tetsu servers need. */\nexport const BUN_ENGINES = '>=1.4.0';\n","import { code, tsKey, tsString, yamlString } from './code.js';\nimport type { ComposeService, EnvVar, ProjectBuilder, RegistryEntry } from './project.js';\nimport { DEFAULT_OLLAMA_URL } from './providers.js';\nimport { qualifiedModel, runsOnBun } from './spec.js';\nimport { BUN_ENGINES, NODE_ENGINES } from './versions.js';\n\n/** Where each script goes in package.json; the rest follow alphabetically. */\nconst SCRIPT_ORDER = [\n 'dev',\n 'ask',\n 'build',\n 'start',\n 'test',\n 'typecheck',\n 'lint',\n 'format',\n 'eval',\n 'dev:studio',\n 'doctor',\n];\n\nfunction sortedRecord(entries: Map<string, string>): Record<string, string> {\n return Object.fromEntries([...entries].sort(([a], [b]) => a.localeCompare(b)));\n}\n\nexport function orderedScripts(scripts: Map<string, string>): Record<string, string> {\n const rank = (name: string) => {\n const index = SCRIPT_ORDER.indexOf(name);\n return index === -1 ? SCRIPT_ORDER.length : index;\n };\n return Object.fromEntries(\n [...scripts].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))\n );\n}\n\nexport interface PackageJsonExtras {\n /** `name@version` of the package manager, written to `packageManager`. */\n packageManagerSpec?: string;\n /** What `cogitator add` needs to extend the project later. */\n cogitator: Record<string, unknown>;\n}\n\nexport function emitPackageJson(project: ProjectBuilder, extras: PackageJsonExtras): void {\n const { spec } = project;\n const bun = runsOnBun(spec);\n const native = [...project.nativeBuilds].sort();\n\n const pkg: Record<string, unknown> = {\n name: spec.name,\n version: '0.1.0',\n private: true,\n type: 'module',\n engines: bun ? { bun: BUN_ENGINES } : { node: NODE_ENGINES },\n ...(extras.packageManagerSpec && { packageManager: extras.packageManagerSpec }),\n scripts: orderedScripts(project.scripts),\n dependencies: sortedRecord(project.dependencies),\n devDependencies: sortedRecord(project.devDependencies),\n ...(spec.packageManager === 'bun' && native.length > 0 && { trustedDependencies: native }),\n cogitator: extras.cogitator,\n };\n\n project.file('package.json', JSON.stringify(pkg, null, 2) + '\\n');\n}\n\n/**\n * Packages with build scripts the project does not need: optional native\n * speedups of the Docker client the CLI uses (ssh2, cpu-features), a\n * protobufjs version check, and better-sqlite3, which the CLI depends on and\n * which ships prebuilt binaries, so its implicit `node-gyp rebuild` only\n * needs a compiler. Saying no to them explicitly keeps pnpm 11 from failing\n * the install over builds nobody approved, which pnpm 11.0 does even outside\n * CI. A feature that allows one of them wins.\n */\nconst SKIPPED_BUILDS = ['better-sqlite3', 'cpu-features', 'protobufjs', 'ssh2'];\n\n/**\n * pnpm runs dependency build scripts only when they are allowed, and fails\n * the install in CI on scripts nobody decided on: the `pnpm-workspace.yaml`\n * that allows the native builds a project needs and declines the rest.\n */\nexport function pnpmWorkspaceYaml(nativeBuilds: Iterable<string>): string {\n const allowed = new Set(nativeBuilds);\n const entries = [\n ...[...allowed].map((name) => [name, true] as const),\n ...SKIPPED_BUILDS.filter((name) => !allowed.has(name)).map((name) => [name, false] as const),\n ].sort(([a], [b]) => a.localeCompare(b));\n return ['allowBuilds:', ...entries.map(([name, allow]) => ` ${name}: ${allow}`), ''].join('\\n');\n}\n\nexport function emitPnpmWorkspace(project: ProjectBuilder): void {\n if (project.spec.packageManager !== 'pnpm') return;\n project.file('pnpm-workspace.yaml', pnpmWorkspaceYaml([...project.nativeBuilds, 'esbuild']));\n}\n\nfunction envExampleLine(variable: EnvVar): string[] {\n const value = variable.secret ? '' : (variable.example ?? '');\n const assignment = `${variable.name}=${value}`;\n return [`# ${variable.description}`, variable.required ? assignment : `# ${assignment}`];\n}\n\nexport function emitEnvExample(project: ProjectBuilder): void {\n const variables = [...project.env.values()];\n const lines = ['# Copy to .env and fill in. Lines starting with # are optional.', ''];\n for (const variable of variables) lines.push(...envExampleLine(variable), '');\n project.file('.env.example', lines.join('\\n').replace(/\\n+$/, '\\n'));\n}\n\n/** `.env` with the secrets given to the scaffolder, readable by the owner only. */\nexport function emitEnvFile(project: ProjectBuilder, secrets: Record<string, string>): void {\n const entries = Object.entries(secrets).filter(([, value]) => value !== '');\n if (entries.length === 0) return;\n const lines = entries.map(([name, value]) => `${name}=${formatEnvValue(value)}`);\n project.files.set('.env', { path: '.env', content: lines.join('\\n') + '\\n', mode: 0o600 });\n}\n\nexport function formatEnvValue(value: string): string {\n if (/^[A-Za-z0-9_./:@+,=-]*$/.test(value)) return value;\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t');\n return `\"${escaped}\"`;\n}\n\nfunction zodFor(variable: EnvVar): string {\n return variable.required\n ? `required(${tsString(variable.name)}, ${tsString(variable.description)})`\n : 'z.string().optional()';\n}\n\nexport function emitEnvModule(project: ProjectBuilder): void {\n const variables = [...project.env.values()];\n const fields = variables.map((v) => `${tsKey(v.name)}: ${zodFor(v)},`).join('\\n');\n const anyRequired = variables.some((v) => v.required);\n project.file(\n 'src/env.ts',\n code`\n import { z } from 'zod';\n\n ${\n anyRequired &&\n code`\n function required(name: string, description: string) {\n const message = \\`\\${name} is required: \\${description}\\`;\n return z.string({ error: message }).min(1, message);\n }\n `\n }\n\n const EnvSchema = z.object({\n ${fields || '// The project reads no environment variables yet.'}\n });\n\n export type Env = z.infer<typeof EnvSchema>;\n\n /**\n * The environment the project needs, checked at startup so a missing key fails\n * with its name and where to get it instead of as a provider error mid-run.\n */\n export function loadEnv(source: Record<string, string | undefined> = process.env): Env {\n const parsed = EnvSchema.safeParse(source);\n if (parsed.success) return parsed.data;\n const problems = parsed.error.issues.map((issue) => \\` \\${issue.path.join('.') || 'env'}: \\${issue.message}\\`);\n throw new Error(\n \\`Missing or invalid environment variables, copy .env.example to .env and fill it in:\\\\n\\${problems.join('\\\\n')}\\`\n );\n }\n `\n );\n}\n\nfunction yamlList(items: readonly string[]): string {\n return `[${items.map((item) => JSON.stringify(item)).join(', ')}]`;\n}\n\nfunction composeService(service: ComposeService): string[] {\n const lines = [` ${service.name}:`, ` image: ${service.image}`];\n if (service.ports?.length) {\n lines.push(' ports:', ...service.ports.map((port) => ` - ${JSON.stringify(port)}`));\n }\n if (service.environment) {\n lines.push(\n ' environment:',\n ...Object.entries(service.environment).map(([k, v]) => ` ${k}: ${yamlString(v)}`)\n );\n }\n if (service.volumes?.length) {\n lines.push(' volumes:', ...service.volumes.map((volume) => ` - ${volume}`));\n }\n if (service.command) lines.push(` command: ${yamlList(service.command)}`);\n if (service.entrypoint) lines.push(` entrypoint: ${yamlList(service.entrypoint)}`);\n if (service.dependsOn) {\n lines.push(' depends_on:');\n for (const [name, condition] of Object.entries(service.dependsOn)) {\n lines.push(` ${name}:`, ` condition: ${condition}`);\n }\n }\n if (service.healthcheck) {\n const h = service.healthcheck;\n lines.push(\n ' healthcheck:',\n ` test: ${yamlList(h.test)}`,\n ` interval: ${h.interval}`,\n ` timeout: ${h.timeout}`,\n ` retries: ${h.retries}`\n );\n }\n if (service.restart) lines.push(` restart: ${JSON.stringify(service.restart)}`);\n return lines;\n}\n\nexport function emitCompose(project: ProjectBuilder): void {\n if (!project.spec.compose || project.services.size === 0) return;\n const services = [...project.services.values()];\n const lines = [\n '# Services for local development: docker compose up -d',\n 'services:',\n ...services.flatMap((service, i) => [...(i > 0 ? [''] : []), ...composeService(service)]),\n ];\n if (project.volumes.size > 0) {\n lines.push('', 'volumes:', ...[...project.volumes].sort().map((volume) => ` ${volume}:`));\n }\n project.file('docker-compose.yml', lines.join('\\n') + '\\n');\n}\n\nexport function emitCogitatorYml(project: ProjectBuilder): void {\n const { spec } = project;\n const lines = [\n '# The Cogitator runtime: src/cogitator.ts loads it with loadConfig(), and',\n '# `cogitator deploy` reads it to build and ship the project. ${VAR:-default}',\n '# reads the environment, and API keys come from .env (OPENAI_API_KEY and the like).',\n '',\n 'llm:',\n ` defaultProvider: ${spec.provider}`,\n ` defaultModel: ${yamlString(qualifiedModel(spec))}`,\n ];\n if (spec.provider === 'ollama') {\n lines.push(\n ' providers:',\n ' ollama:',\n ` baseUrl: \\${OLLAMA_BASE_URL:-${DEFAULT_OLLAMA_URL}}`\n );\n }\n\n if (project.memoryYml.length > 0) {\n lines.push('', 'memory:', ...project.memoryYml.map((line) => ` ${line}`));\n }\n\n for (const [section, body] of project.ymlSections) {\n lines.push('', `${section}:`, ...body.map((line) => ` ${line}`));\n }\n\n const deploy: string[] = [];\n if (spec.deploy !== 'none') deploy.push(` target: ${spec.deploy}`);\n if (project.deploy.kind) deploy.push(` kind: ${project.deploy.kind}`);\n if (project.deploy.port) deploy.push(` port: ${project.deploy.port}`);\n if (project.deploy.healthPath) deploy.push(' health:', ` path: ${project.deploy.healthPath}`);\n const secrets = [...project.env.values()]\n .filter((v) => v.deploy ?? (v.secret && v.required))\n .map((v) => v.name);\n if (secrets.length > 0) deploy.push(' secrets:', ...secrets.map((name) => ` - ${name}`));\n if (deploy.length > 0) lines.push('', 'deploy:', ...deploy);\n\n project.file('cogitator.yml', lines.join('\\n') + '\\n');\n}\n\nfunction registryGroup(entries: RegistryEntry[], kind: RegistryEntry['kind']): string | false {\n const items = entries.filter((entry) => entry.kind === kind);\n if (items.length === 0) return false;\n const body = items.map((entry) =>\n entry.name === entry.binding ? `${entry.name},` : `${tsKey(entry.name)}: ${entry.binding},`\n );\n return `{\\n ${body.join('\\n ')}\\n}`;\n}\n\nexport function emitRegistry(project: ProjectBuilder): void {\n const entries = project.registry;\n const imports = new Map<string, string[]>();\n for (const entry of entries) {\n const bindings = imports.get(entry.from) ?? [];\n bindings.push(entry.binding);\n imports.set(entry.from, bindings);\n }\n const importLines = [...imports]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([from, bindings]) => `import { ${[...new Set(bindings)].sort().join(', ')} } from '${from}';`\n );\n\n const observed = project.files.has('src/observability.ts');\n if (observed) importLines.push(\"import { observers } from './observability.js';\");\n importLines.sort((a, b) =>\n a.slice(a.indexOf(\"from '\")).localeCompare(b.slice(b.indexOf(\"from '\")))\n );\n const agents = registryGroup(entries, 'agents');\n const workflows = registryGroup(entries, 'workflows');\n const swarms = registryGroup(entries, 'swarms');\n\n project.file(\n 'src/cogitator.ts',\n code`\n import { loadConfig } from '@cogitator-ai/config';\n import { Cogitator, type CogitatorConfig } from '@cogitator-ai/core';\n ${swarms && \"import type { SwarmConfig } from '@cogitator-ai/swarms';\"}\n ${importLines.join('\\n')}\n\n /**\n * A runtime configured by cogitator.yml and the environment. \\`overrides\\` are\n * merged over that configuration: tests pass a mock model backend here.\n */\n export function createCogitator(overrides: CogitatorConfig = {}): Cogitator {\n const config = loadConfig();\n return new Cogitator({ ...config, ${observed ? 'observers, ' : ''}...overrides, llm: { ...config.llm, ...overrides.llm } });\n }\n\n /** The runtime the project shares. */\n export const cogitator = createCogitator();\n\n /**\n * The registry: every agent${workflows ? ', workflow' : ''}${swarms ? ' and swarm' : ''} of the project by name.\n * The entry points, the tests and \\`cogitator dev\\` all find them here.\n */\n export const agents = ${agents || '{}'};\n ${workflows && `\\nexport const workflows = ${workflows};`}\n ${swarms && `\\nexport const swarms = ${swarms} satisfies Record<string, SwarmConfig>;`}\n `\n );\n}\n\nexport function emitToolsIndex(project: ProjectBuilder): void {\n const imports = [...project.tools]\n .sort((a, b) => a.from.localeCompare(b.from))\n .map((tool) => `import { ${tool.binding} } from '${tool.from}';`);\n project.file(\n 'src/tools/index.ts',\n code`\n ${imports.join('\\n')}\n\n /** The tools the assistant can call. Add a tool here to give it to the assistant. */\n export const tools = [${project.tools.map((tool) => (tool.spread ? `...${tool.binding}` : tool.binding)).join(', ')}];\n `\n );\n}\n\nexport function emitGitignore(project: ProjectBuilder): void {\n project.file('.gitignore', [...project.gitignore].join('\\n') + '\\n');\n}\n\nexport const AGENT_RULES_BEGIN = '<!-- BEGIN:cogitator-agent-rules -->';\nexport const AGENT_RULES_END = '<!-- END:cogitator-agent-rules -->';\n\n/** The managed block of AGENTS.md: the scaffolder and `cogitator add` rewrite it, nothing else. */\nexport function agentRulesBlock(project: ProjectBuilder): string {\n const sections = project.agentsMd.map(\n (section) => `## ${section.title}\\n\\n${section.body.trim()}`\n );\n return [\n AGENT_RULES_BEGIN,\n '# This is a Cogitator project',\n '',\n 'Cogitator is a TypeScript runtime for AI agents, and its APIs move faster than model training data. Before you write Cogitator code, read the docs bundled with the installed version in `node_modules/@cogitator-ai/core/docs/`, starting with `index.md`, and trust them over what you remember.',\n '',\n 'Everything the project runs is registered in `src/cogitator.ts`: the runtime (configured by `cogitator.yml` and `.env`) and the agents' +\n (project.registry.some((e) => e.kind === 'workflows') ? ', workflows' : '') +\n (project.registry.some((e) => e.kind === 'swarms') ? ' and swarms' : '') +\n ' by name. Register new ones there so the entry points, the tests and `cogitator dev` find them.',\n '',\n ...sections.flatMap((section) => [section, '']),\n AGENT_RULES_END,\n ].join('\\n');\n}\n\nexport function emitAgentsMd(project: ProjectBuilder): void {\n const nextBlock =\n project.spec.app === 'next'\n ? [\n '<!-- BEGIN:nextjs-agent-rules -->',\n '# This is NOT the Next.js you know',\n '',\n 'This version has breaking changes, so APIs, conventions and file structure may differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code, and heed deprecation notices.',\n '<!-- END:nextjs-agent-rules -->',\n '',\n ]\n : [];\n project.file(\n 'AGENTS.md',\n [\n ...nextBlock,\n agentRulesBlock(project),\n '',\n '## Project notes',\n '',\n 'Add what agents should know about this project here. The block above is managed by Cogitator.',\n '',\n ].join('\\n')\n );\n project.file('CLAUDE.md', '@AGENTS.md\\n');\n}\n\nconst RELATIVE_JS_IMPORT = /(\\bfrom\\s+|\\bimport\\s*\\(\\s*)(['\"])(\\.{1,2}\\/[^'\"]+?)\\.js\\2/g;\n\n/**\n * Next.js bundles with `moduleResolution: bundler`, which resolves relative\n * imports without an extension and does not map `./x.js` to `./x.ts`. Generated\n * code imports with `.js` for Node, so a Next.js app gets the extensions dropped.\n */\nexport function adaptImportsForBundler(project: ProjectBuilder): void {\n if (project.spec.app !== 'next') return;\n for (const file of project.files.values()) {\n if (!/\\.tsx?$/.test(file.path)) continue;\n file.content = file.content.replace(RELATIVE_JS_IMPORT, '$1$2$3$2');\n }\n}\n","import { code } from '../code.js';\n\n/** `fetch_url`: reads public web pages and JSON, refuses private networks, follows redirects hop by hop. */\nexport const FETCH_URL_TS = code`\n import { lookup } from 'node:dns/promises';\n import { BlockList, isIP } from 'node:net';\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n const TIMEOUT_MS = 15_000;\n const MAX_BYTES = 200_000;\n const MAX_REDIRECTS = 5;\n\n const privateNetworks = new BlockList();\n for (const [network, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['224.0.0.0', 4],\n ] as const) {\n privateNetworks.addSubnet(network, prefix, 'ipv4');\n }\n for (const [network, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ] as const) {\n privateNetworks.addSubnet(network, prefix, 'ipv6');\n }\n\n /** Whether \\`address\\` is loopback, link-local, private or otherwise not on the public internet. */\n export function isPrivateAddress(address: string): boolean {\n const mapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i.exec(address);\n if (mapped) return privateNetworks.check(mapped[1], 'ipv4');\n const family = isIP(address);\n if (family === 0) return true;\n return privateNetworks.check(address, family === 4 ? 'ipv4' : 'ipv6');\n }\n\n async function assertPublic(url: URL): Promise<void> {\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error(\\`Only http and https URLs can be fetched, not \\${url.protocol}\\`);\n }\n const host = url.hostname.replace(/^\\\\[|\\\\]$/g, '');\n const addresses = isIP(host) ? [host] : (await lookup(host, { all: true })).map((a) => a.address);\n const blocked = addresses.find(isPrivateAddress);\n if (blocked) {\n throw new Error(\\`\\${url.hostname} resolves to \\${blocked}, which is not on the public internet\\`);\n }\n }\n\n const ENTITIES: Record<string, string> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: ' ',\n };\n\n function decodeEntities(text: string): string {\n return text.replace(/&(#x[0-9a-f]+|#\\\\d+|[a-z]+);/gi, (entity, body: string) => {\n if (body[0] === '#') {\n const point = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : Number(body.slice(1));\n return Number.isInteger(point) && point > 0 && point <= 0x10ffff ? String.fromCodePoint(point) : entity;\n }\n return ENTITIES[body.toLowerCase()] ?? entity;\n });\n }\n\n /** The readable text of an HTML page: no scripts, styles or tags, one blank line between blocks. */\n export function htmlToText(html: string): string {\n return decodeEntities(\n html\n .replace(/<(script|style|noscript|svg|template|head)\\\\b[\\\\s\\\\S]*?<\\\\/\\\\1>/gi, ' ')\n .replace(/<br\\\\s*\\\\/?>|<\\\\/?(?:p|div|li|ul|ol|h[1-6]|tr|table|section|article|header|footer|main|nav|pre|blockquote)\\\\b[^>]*>/gi, '\\\\n')\n .replace(/<[^>]*>/g, ' ')\n )\n .replace(/[ \\\\t\\\\f\\\\v\\\\u00a0]+/g, ' ')\n .replace(/ *\\\\n */g, '\\\\n')\n .replace(/\\\\n{3,}/g, '\\\\n\\\\n')\n .trim();\n }\n\n async function readLimited(body: ReadableStream<Uint8Array>): Promise<{ text: string; truncated: boolean }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let text = '';\n let bytes = 0;\n try {\n while (bytes < MAX_BYTES) {\n const { done, value } = await reader.read();\n if (done) return { text: text + decoder.decode(), truncated: false };\n const room = MAX_BYTES - bytes;\n bytes += value.byteLength;\n text += decoder.decode(value.byteLength > room ? value.subarray(0, room) : value, { stream: true });\n }\n return { text: text + decoder.decode(), truncated: true };\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n\n export const fetchUrl = tool({\n name: 'fetch_url',\n description:\n 'Fetch a public web page or JSON document over HTTP(S) and return its text. Pages are converted to plain text and cut at 200 kB.',\n parameters: z.object({\n url: z.url({ protocol: /^https?$/ }).describe('The http or https URL to fetch'),\n }),\n sideEffects: ['network'],\n timeout: TIMEOUT_MS + 1_000,\n execute: async ({ url }, { signal }) => {\n const timeout = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]);\n let target = new URL(url);\n\n for (let hop = 0; ; hop++) {\n await assertPublic(target);\n const response = await fetch(target, {\n redirect: 'manual',\n signal: timeout,\n headers: { 'user-agent': 'cogitator-agent/1.0', accept: 'text/html,application/json,text/plain;q=0.9,*/*;q=0.5' },\n });\n\n const location = response.headers.get('location');\n if (response.status >= 300 && response.status < 400 && location) {\n await response.body?.cancel();\n if (hop >= MAX_REDIRECTS) throw new Error(\\`Stopped after \\${MAX_REDIRECTS} redirects\\`);\n target = new URL(location, target);\n continue;\n }\n\n const contentType = response.headers.get('content-type') ?? 'unknown';\n const { text, truncated } = response.body ? await readLimited(response.body) : { text: '', truncated: false };\n return {\n url: target.toString(),\n status: response.status,\n contentType,\n truncated,\n content: contentType.includes('html') ? htmlToText(text) : text,\n };\n }\n },\n });\n`;\n\n/** `current_time`: the date and time in any IANA time zone. */\nexport const CURRENT_TIME_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n function assertTimeZone(timeZone: string): void {\n try {\n new Intl.DateTimeFormat('en-US', { timeZone });\n } catch {\n throw new Error(\\`Unknown time zone \"\\${timeZone}\", use an IANA name such as Europe/Berlin\\`);\n }\n }\n\n export const currentTime = tool({\n name: 'current_time',\n description: 'The current date and time, in UTC and in a given IANA time zone.',\n parameters: z.object({\n timeZone: z\n .string()\n .optional()\n .describe('An IANA time zone such as America/New_York, the local one when left out'),\n }),\n execute: async ({ timeZone }) => {\n const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n assertTimeZone(zone);\n const now = new Date();\n return {\n utc: now.toISOString(),\n timeZone: zone,\n local: new Intl.DateTimeFormat('en-US', {\n timeZone: zone,\n dateStyle: 'full',\n timeStyle: 'long',\n }).format(now),\n };\n },\n });\n`;\n\n/** `calculator`: arithmetic through a small parser, never through `eval`. */\nexport const CALCULATOR_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n const FUNCTIONS: Record<string, (...args: number[]) => number> = {\n abs: Math.abs,\n ceil: Math.ceil,\n cos: Math.cos,\n exp: Math.exp,\n floor: Math.floor,\n ln: Math.log,\n log: Math.log10,\n max: Math.max,\n min: Math.min,\n round: Math.round,\n sin: Math.sin,\n sqrt: Math.sqrt,\n tan: Math.tan,\n };\n\n const CONSTANTS: Record<string, number> = { pi: Math.PI, e: Math.E };\n\n /**\n * Evaluates \\`+ - * / % ^\\`, parentheses, the functions in FUNCTIONS and the\n * constants pi and e. Precedence is the usual one, \\`^\\` is right-associative\n * and binds tighter than a unary minus, so \\`-2^2\\` is -4. \\`%\\` is the\n * remainder of a division, never a percentage.\n */\n class Parser {\n private position = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): number {\n const value = this.sum();\n this.skipSpace();\n if (this.position < this.source.length) {\n throw new Error(\\`Unexpected \"\\${this.source[this.position]}\" at position \\${this.position + 1}\\`);\n }\n return value;\n }\n\n private sum(): number {\n let value = this.product();\n for (;;) {\n if (this.take('+')) value += this.product();\n else if (this.take('-')) value -= this.product();\n else return value;\n }\n }\n\n private product(): number {\n let value = this.unary();\n for (;;) {\n if (this.take('*')) value *= this.unary();\n else if (this.take('/')) {\n const divisor = this.unary();\n if (divisor === 0) throw new Error('Division by zero');\n value /= divisor;\n } else if (this.take('%')) {\n if (!this.startsOperand()) {\n throw new Error(\n \\`\"%\" is the remainder of a division and needs a number after it. For a percentage divide by 100: \\${value}% is \\${value} / 100\\`\n );\n }\n value %= this.unary();\n } else return value;\n }\n }\n\n private unary(): number {\n if (this.take('-')) return -this.unary();\n if (this.take('+')) return this.unary();\n return this.power();\n }\n\n private power(): number {\n const base = this.primary();\n return this.take('^') ? base ** this.unary() : base;\n }\n\n private primary(): number {\n this.skipSpace();\n if (this.take('(')) {\n const value = this.sum();\n this.expect(')');\n return value;\n }\n\n const number = /^(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:e[+-]?\\\\d+)?/i.exec(this.rest());\n if (number) {\n this.position += number[0].length;\n return Number(number[0]);\n }\n\n const name = /^[a-z]+/i.exec(this.rest())?.[0].toLowerCase();\n if (name) {\n this.position += name.length;\n if (name in CONSTANTS) return CONSTANTS[name];\n const fn = FUNCTIONS[name];\n if (!fn) throw new Error(\\`Unknown name \"\\${name}\"\\`);\n this.expect('(');\n const args = [this.sum()];\n while (this.take(',')) args.push(this.sum());\n this.expect(')');\n return fn(...args);\n }\n\n throw new Error(\n this.position < this.source.length\n ? \\`Unexpected \"\\${this.source[this.position]}\" at position \\${this.position + 1}\\`\n : 'The expression ends too early'\n );\n }\n\n private startsOperand(): boolean {\n this.skipSpace();\n return /[\\\\d.(a-z+-]/i.test(this.source[this.position] ?? '');\n }\n\n private rest(): string {\n return this.source.slice(this.position);\n }\n\n private skipSpace(): void {\n while (/\\\\s/.test(this.source[this.position] ?? '')) this.position++;\n }\n\n private take(token: string): boolean {\n this.skipSpace();\n if (this.source[this.position] !== token) return false;\n this.position++;\n return true;\n }\n\n private expect(token: string): void {\n if (!this.take(token)) throw new Error(\\`Expected \"\\${token}\" at position \\${this.position + 1}\\`);\n }\n }\n\n export function evaluate(expression: string): number {\n const value = new Parser(expression).parse();\n if (!Number.isFinite(value)) throw new Error('The result is not a finite number');\n return value;\n }\n\n export const calculator = tool({\n name: 'calculator',\n description:\n 'Evaluate an arithmetic expression exactly. Supports + - * / ^, % as the remainder of a division (write a percentage as x / 100, so 17.5% of 2480 is 17.5 / 100 * 2480), parentheses, sqrt, abs, round, floor, ceil, min, max, log, ln, exp, sin, cos, tan, pi and e.',\n parameters: z.object({\n expression: z.string().min(1).max(500).describe('For example \"(17.5 * 4) / 3 + sqrt(2)\"'),\n }),\n execute: async ({ expression }) => ({ expression, result: evaluate(expression) }),\n });\n`;\n\n/** Unit tests for the starter tools, runnable offline. */\nexport const TOOLS_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { evaluate } from '../src/tools/calculator.js';\n import { currentTime } from '../src/tools/current-time.js';\n import { htmlToText, isPrivateAddress } from '../src/tools/fetch-url.js';\n\n describe('calculator', () => {\n it.each([\n ['1 + 2 * 3', 7],\n ['(1 + 2) * 3', 9],\n ['2 ^ 3 ^ 2', 512],\n ['-2 ^ 2', -4],\n ['sqrt(16) + abs(-3)', 7],\n ['max(1, 5, 3) % 3', 2],\n ['1.5e3 / 3', 500],\n ])('evaluates %s', (expression, expected) => {\n expect(evaluate(expression)).toBe(expected);\n });\n\n it('rejects what it cannot evaluate', () => {\n expect(() => evaluate('1 / 0')).toThrow('Division by zero');\n expect(() => evaluate('process.exit()')).toThrow();\n expect(() => evaluate('2 +')).toThrow('ends too early');\n });\n\n it('explains that % is a remainder, not a percentage', () => {\n expect(evaluate('10 % 3')).toBe(1);\n expect(evaluate('10 % -3')).toBe(1);\n expect(() => evaluate('17.5% * 2480')).toThrow('17.5% is 17.5 / 100');\n expect(() => evaluate('20 %')).toThrow('remainder of a division');\n });\n });\n\n describe('current_time', () => {\n it('answers in the requested time zone', async () => {\n const result = await currentTime.execute(\n { timeZone: 'Asia/Tokyo' },\n { agentId: 'test', runId: 'test', signal: new AbortController().signal }\n );\n expect(result.timeZone).toBe('Asia/Tokyo');\n });\n\n it('refuses an unknown time zone', async () => {\n await expect(\n currentTime.execute(\n { timeZone: 'Mars/Olympus' },\n { agentId: 'test', runId: 'test', signal: new AbortController().signal }\n )\n ).rejects.toThrow('Unknown time zone');\n });\n });\n\n describe('fetch_url', () => {\n it('keeps away from private networks', () => {\n for (const address of ['127.0.0.1', '10.1.2.3', '192.168.0.10', '169.254.169.254', '::1', '::ffff:127.0.0.1', 'fd00::1']) {\n expect(isPrivateAddress(address), address).toBe(true);\n }\n expect(isPrivateAddress('93.184.216.34')).toBe(false);\n });\n\n it('turns HTML into readable text', () => {\n const html = '<html><head><title>x</title><style>p{}</style></head><body><h1>Hello &amp; welcome</h1><p>One<br>Two</p><script>alert(1)</script></body></html>';\n expect(htmlToText(html)).toBe('Hello & welcome\\\\n\\\\nOne\\\\nTwo');\n });\n });\n`;\n","import { code, tsString } from '../code.js';\nimport { providerInfo } from '../providers.js';\nimport { ciInstallCommand, execCommand, runScript } from '../package-manager.js';\nimport { runsOnBun, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { ProjectBuilder } from '../project.js';\nimport type { FeatureModule } from './types.js';\nimport { CALCULATOR_TS, CURRENT_TIME_TS, FETCH_URL_TS, TOOLS_TEST_TS } from './starter-tools.js';\n\nconst BIOME_SCHEMA_VERSION = VERSIONS.biome.replace(/^\\^/, '');\n\nfunction tsconfig(spec: ProjectSpec): string {\n const bun = runsOnBun(spec);\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'es2023',\n lib: ['es2024'],\n module: 'nodenext',\n moduleResolution: 'nodenext',\n types: [bun ? 'bun' : 'node'],\n strict: true,\n verbatimModuleSyntax: true,\n isolatedModules: true,\n resolveJsonModule: true,\n skipLibCheck: true,\n noEmit: true,\n },\n include: ['src', 'tests', 'evals', '*.config.ts'],\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nfunction tsconfigBuild(): string {\n return (\n JSON.stringify(\n {\n extends: './tsconfig.json',\n compilerOptions: { noEmit: false, rootDir: 'src', outDir: 'dist', sourceMap: true },\n include: ['src'],\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nfunction biomeJson(spec: ProjectSpec): string {\n const ignored = ['!**/dist', '!**/data', '!**/.cogitator', '!**/node_modules'];\n if (spec.app === 'next') ignored.push('!**/.next', '!**/next-env.d.ts');\n return (\n JSON.stringify(\n {\n $schema: `https://biomejs.dev/schemas/${BIOME_SCHEMA_VERSION}/schema.json`,\n files: { includes: ['**', ...ignored] },\n formatter: { enabled: true, indentStyle: 'space', indentWidth: 2, lineWidth: 100 },\n javascript: {\n formatter: { quoteStyle: 'single', semicolons: 'always', trailingCommas: 'es5' },\n },\n linter: { enabled: true, rules: { preset: 'recommended' } },\n ...(spec.app === 'next' && { css: { parser: { tailwindDirectives: true } } }),\n assist: { actions: { source: { organizeImports: 'on' } } },\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nconst VITEST_CONFIG_TS = code`\n import { defineConfig } from 'vitest/config';\n\n export default defineConfig({\n test: {\n include: ['tests/**/*.test.ts'],\n testTimeout: 30_000,\n },\n });\n`;\n\nconst TEST_HELPERS_TS = code`\n import { loadConfig } from '@cogitator-ai/config';\n import { createMockLLMBackend, type MockChatResponse } from '@cogitator-ai/test-utils';\n import { createCogitator } from '../src/cogitator.js';\n\n /** The provider of the project's default model, the backend a mock has to stand in for. */\n function defaultProvider(): string {\n const llm = loadConfig().llm;\n return llm?.defaultModel?.split('/')[0] ?? llm?.defaultProvider ?? 'openai';\n }\n\n /**\n * A Cogitator whose model answers with \\`responses\\`, one per call, so tests run\n * offline and decide exactly what the model says. Memory stays in the process.\n */\n export function mockCogitator(...responses: MockChatResponse[]) {\n const backend = createMockLLMBackend().setResponses(responses);\n const cogitator = createCogitator({\n llm: { backends: { [defaultProvider()]: backend } },\n memory: { adapter: 'memory' },\n });\n return { backend, cogitator };\n }\n`;\n\nconst ASSISTANT_TEST_TS = code`\n import { afterEach, describe, expect, it } from 'vitest';\n import type { Cogitator } from '@cogitator-ai/core';\n import { agents } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n let cogitator: Cogitator | undefined;\n\n afterEach(async () => {\n await cogitator?.close();\n cogitator = undefined;\n });\n\n describe('assistant', () => {\n it('calls the calculator and answers with its result', async () => {\n const mock = mockCogitator(\n {\n toolCalls: [{ id: 'call-1', name: 'calculator', arguments: { expression: '6 * 7' } }],\n finishReason: 'tool_calls',\n },\n { content: '6 * 7 is 42.' }\n );\n cogitator = mock.cogitator;\n\n const result = await cogitator.run(agents.assistant, { input: 'What is 6 * 7?' });\n\n expect(result.output).toBe('6 * 7 is 42.');\n expect(result.toolCalls.map((call) => call.name)).toEqual(['calculator']);\n expect(JSON.stringify(mock.backend.getLastCall()?.messages)).toContain('42');\n });\n\n it('answers directly when no tool is needed', async () => {\n const mock = mockCogitator({ content: 'Hello!' });\n cogitator = mock.cogitator;\n\n const result = await cogitator.run(agents.assistant, { input: 'Hi' });\n\n expect(result.output).toBe('Hello!');\n expect(result.toolCalls).toEqual([]);\n });\n });\n`;\n\nfunction ciWorkflow(spec: ProjectSpec, packageManagerSpec: string | undefined): string {\n const pm = spec.packageManager;\n const setup =\n pm === 'bun'\n ? code`\n - uses: oven-sh/setup-bun@v2\n `\n : code`\n ${pm === 'pnpm' && '- uses: pnpm/action-setup@v6'}\n ${pm === 'yarn' && '- run: corepack enable'}\n - uses: actions/setup-node@v7\n with:\n node-version: 24\n cache: ${pm}\n `;\n const evals = spec.features.includes('evals');\n return code`\n name: CI\n\n on:\n push:\n branches: [main]\n pull_request:\n\n jobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v7\n ${setup}\n - run: ${ciInstallCommand(pm, packageManagerSpec)}\n - run: ${runScript(pm, 'typecheck')}\n - run: ${runScript(pm, 'lint')}\n - run: ${runScript(pm, 'test')}\n ${evals && `- run: ${runScript(pm, 'eval')}`}\n ${\n evals &&\n code`\n env:\n ${providerInfo(spec.provider).envKey ?? 'OLLAMA_BASE_URL'}: \\${{ secrets.${providerInfo(spec.provider).envKey ?? 'OLLAMA_BASE_URL'} }}\n `\n }\n `;\n}\n\nfunction assistantAgent(project: ProjectBuilder): string {\n const lines = [\n 'You are a capable, honest assistant.',\n 'Use your tools when they help: fetch_url to read web pages, calculator for arithmetic, current_time for dates and times.',\n ...project.instructions,\n 'When you are unsure, say so instead of guessing.',\n ];\n return code`\n import { Agent } from '@cogitator-ai/core';\n import { tools } from '../tools/index.js';\n\n export const assistant = new Agent({\n name: 'assistant',\n description: 'The general-purpose assistant of this project',\n instructions: [\n ${lines.map((line) => `${tsString(line)},`).join('\\n')}\n ].join('\\\\n'),\n tools,\n });\n `;\n}\n\nexport const baseFeature: FeatureModule = {\n id: 'base',\n applies: () => true,\n apply(project) {\n const { spec } = project;\n const bun = runsOnBun(spec);\n\n project\n .dependency('@cogitator-ai/core', cogitatorVersion('@cogitator-ai/core'))\n .dependency('@cogitator-ai/config', cogitatorVersion('@cogitator-ai/config'))\n .dependency('zod', VERSIONS.zod)\n .devDependency('@cogitator-ai/cli', cogitatorVersion('@cogitator-ai/cli'))\n .devDependency('@cogitator-ai/test-utils', cogitatorVersion('@cogitator-ai/test-utils'))\n .devDependency('@biomejs/biome', VERSIONS.biome)\n .devDependency('tsx', VERSIONS.tsx)\n .devDependency('vitest', VERSIONS.vitest);\n\n if (bun) {\n project.devDependency('@types/bun', VERSIONS.typesBun);\n } else {\n project.devDependency('@types/node', VERSIONS.typesNode);\n }\n\n if (spec.app !== 'next') {\n project\n .devDependency('typescript', VERSIONS.typescript)\n .file('tsconfig.json', tsconfig(spec))\n .file('tsconfig.build.json', tsconfigBuild());\n }\n\n project\n .file('src/tools/fetch-url.ts', FETCH_URL_TS)\n .file('src/tools/current-time.ts', CURRENT_TIME_TS)\n .file('src/tools/calculator.ts', CALCULATOR_TS)\n .tool('fetchUrl', './fetch-url.js')\n .tool('currentTime', './current-time.js')\n .tool('calculator', './calculator.js')\n .register({\n kind: 'agents',\n name: 'assistant',\n from: './agents/assistant.js',\n binding: 'assistant',\n })\n .file('tests/tools.test.ts', TOOLS_TEST_TS)\n .file('tests/helpers.ts', TEST_HELPERS_TS)\n .file('tests/assistant.test.ts', ASSISTANT_TEST_TS)\n .file('vitest.config.ts', VITEST_CONFIG_TS)\n .file('biome.json', biomeJson(spec))\n .file('.github/workflows/ci.yml', ciWorkflow(spec, project.packageManagerSpec))\n .script('test', 'vitest run')\n .script('typecheck', 'tsc --noEmit')\n .script('lint', 'biome check .')\n .script('format', 'biome check --write .')\n .script('doctor', 'cogitator doctor')\n .script('dev:studio', 'cogitator dev')\n .ignore('node_modules/', 'dist/', '.env', '.env.*', '!.env.example', '*.log', '*.tsbuildinfo')\n .ignore('.DS_Store', 'coverage/', '.cogitator/studio/', '.cogitator/checkpoints/');\n\n const info = providerInfo(spec.provider);\n if (info.envKey) {\n project.envVar({\n name: info.envKey,\n description: `${info.label} API key, from ${info.keyUrl}`,\n required: true,\n secret: true,\n });\n } else {\n project.envVar({\n name: 'OLLAMA_BASE_URL',\n description: 'Where Ollama listens',\n example: 'http://localhost:11434',\n required: false,\n secret: false,\n });\n }\n\n project.section(\n 'Commands',\n code`\n - \\`${runScript(spec.packageManager, 'dev')}\\`: run with reload on change\n - \\`${runScript(spec.packageManager, 'test')}\\`: offline tests, the model is mocked with \\`mockCogitator\\` from \\`tests/helpers.ts\\`\n - \\`${runScript(spec.packageManager, 'typecheck')}\\` and \\`${runScript(spec.packageManager, 'lint')}\\`: run both before you call a change done\n - \\`${runScript(spec.packageManager, 'dev:studio')}\\`: Cogitator Studio, to chat with the agents, read traces and costs, approve tool calls, run workflows and fork runs\n - \\`${runScript(spec.packageManager, 'doctor')}\\`: checks keys, services and models when something does not start\n - \\`${execCommand(spec.packageManager, 'cogitator add')} <feature>\\`: adds rag, mcp, workflows, evals and the other generated features to this project, \\`--dry-run\\` shows the diff first\n `\n );\n project.readmeSection(\n 'Cogitator Studio',\n code`\n \\`${runScript(spec.packageManager, 'dev:studio')}\\` opens a local studio for this project at http://localhost:4321: chat with every agent of \\`src/cogitator.ts\\` with streamed answers and tool calls, approve the calls that need it, read the trace of each run with its model calls, tool calls, nested agents, tokens and cost, run the workflows, and fork a run from any step with a changed input or tool result to compare both branches. It reloads when you save, and keeps the history in \\`.cogitator/studio/\\`.\n `\n );\n },\n};\n\n/** Writes `src/agents/assistant.ts` once every feature has added its instructions. */\nexport function emitAssistant(project: ProjectBuilder): void {\n project.file('src/agents/assistant.ts', assistantAgent(project));\n}\n","import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { ArtifactGenerator, ProjectAnalyzer } from '@cogitator-ai/deploy';\nimport { code } from '../code.js';\nimport { LOCKFILES, runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport type { FeatureModule } from './types.js';\n\n/** Deploy artifacts the project keeps at its root, from what @cogitator-ai/deploy generates. */\nconst ROOT_ARTIFACTS: Record<string, string> = {\n Dockerfile: 'Dockerfile',\n '.dockerignore': '.dockerignore',\n 'fly.toml': 'fly.toml',\n};\n\n/**\n * Generates the Dockerfile, `.dockerignore` and `fly.toml` with\n * `@cogitator-ai/deploy` itself: the planned project is laid out in a temporary\n * directory, analyzed the way `cogitator deploy` analyzes it, and the artifacts\n * of its generator are kept. There is one Dockerfile template, the deployer's.\n * The lockfile the install writes is stood in for, since the image installs\n * from it.\n */\nexport function emitDeployArtifacts(project: ProjectBuilder): void {\n const { spec } = project;\n if (spec.deploy === 'none') return;\n\n const dir = mkdtempSync(join(tmpdir(), 'cogitator-deploy-plan-'));\n try {\n for (const file of project.files.values()) {\n const target = join(dir, file.path);\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, file.content);\n }\n writeFileSync(join(dir, LOCKFILES[spec.packageManager]), '');\n\n const analysis = new ProjectAnalyzer().analyze(dir, { target: spec.deploy }, { env: {} });\n const { files } = new ArtifactGenerator().generate(analysis.deployConfig, analysis);\n for (const artifact of files) {\n const path = ROOT_ARTIFACTS[artifact.path];\n if (path) project.file(path, artifact.content);\n }\n for (const warning of analysis.warnings) project.warn(`deploy: ${warning}`);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\n/** A production Dockerfile and the deploy settings for Docker or Fly.io. */\nexport const deployFeature: FeatureModule = {\n id: 'deploy',\n applies: (spec) => spec.deploy !== 'none',\n apply(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n project\n .script('deploy', 'cogitator deploy')\n .script('deploy:plan', 'cogitator deploy --dry-run');\n project.readmeSection(\n 'Deploy',\n code`\n \\`Dockerfile\\` is a multi-stage production image generated by \\`@cogitator-ai/deploy\\` from \\`cogitator.yml\\`: it installs from the lockfile, builds, and runs as an unprivileged user with only production dependencies.${spec.deploy === 'fly' ? ' `fly.toml` configures the Fly.io app.' : ''}\n\n \\`\\`\\`bash\n ${runScript(pm, 'deploy:plan')} # what would be deployed, with checks for secrets and services\n ${runScript(pm, 'deploy')} # build and ${spec.deploy === 'fly' ? 'deploy to Fly.io' : 'run with Docker'}\n \\`\\`\\`\n\n Secrets listed under \\`deploy.secrets\\` in \\`cogitator.yml\\` must be set in the environment you deploy from.\n `\n );\n project.section(\n 'Deploy',\n code`\n \\`cogitator.yml\\` (\\`deploy\\`) says how the project ships: target ${spec.deploy}, the secrets a deployment needs, the health check. \\`${runScript(pm, 'deploy:plan')}\\` checks it without deploying, \\`${runScript(pm, 'deploy')}\\` deploys. \\`Dockerfile\\` and \\`.dockerignore\\` come from \\`@cogitator-ai/deploy\\`; change \\`cogitator.yml\\` rather than the Dockerfile, \\`cogitator deploy\\` generates its image from it.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type ServerFramework } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nfunction a2aServerTs(project: ProjectBuilder): string {\n return code`\n import { timingSafeEqual } from 'node:crypto';\n import type { Cogitator } from '@cogitator-ai/core';\n import { A2AServer } from '@cogitator-ai/a2a';\n import { agents, cogitator } from '../cogitator.js';\n\n function sameToken(given: string, expected: string): boolean {\n const a = Buffer.from(given);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n /**\n * Every agent of the registry over the Agent-to-Agent protocol (v0.3): other\n * frameworks discover them at /.well-known/agent-card.json and talk JSON-RPC at\n * /a2a. With \\`token\\` set, they need \\`Authorization: Bearer <token>\\`.\n */\n export function createA2AServer(runtime: Cogitator, token: string | undefined = process.env.A2A_TOKEN) {\n return new A2AServer({\n agents,\n cogitator: runtime,\n provider: { organization: ${tsString(project.spec.name)}, url: 'https://github.com/cogitator-ai/Cogitator-AI' },\n ...(token && {\n auth: { type: 'bearer' as const, validate: async (given: string) => sameToken(given, token) },\n }),\n });\n }\n\n export const a2aServer = createA2AServer(cogitator);\n `;\n}\n\nconst A2A_ASK_TS = code`\n import { A2AClient } from '@cogitator-ai/a2a';\n\n function textOf(parts: ReadonlyArray<{ kind: string; text?: string }> | undefined): string {\n return (parts ?? []).map((part) => (part.kind === 'text' ? (part.text ?? '') : '')).join('');\n }\n\n /**\n * Asks an A2A agent a question: this project's own server by default, or any\n * A2A v0.3 agent at A2A_URL, built with Cogitator or with another framework.\n */\n async function main(): Promise<void> {\n const question = process.argv.slice(2).join(' ').trim() || 'What can you do?';\n const token = process.env.A2A_TOKEN;\n const client = new A2AClient(process.env.A2A_URL ?? 'http://localhost:3000', {\n ...(token && { headers: { authorization: \\`Bearer \\${token}\\` } }),\n timeout: 120_000,\n });\n\n const card = await client.agentCard();\n console.error(\\`Asking \\${card.name}: \\${card.description}\\`);\n\n const result = await client.sendMessage({ role: 'user', parts: [{ kind: 'text', text: question }] });\n if (result.kind === 'message') {\n console.log(textOf(result.parts));\n return;\n }\n const answer =\n textOf(result.status.message?.parts) ||\n (result.artifacts ?? []).map((artifact) => textOf(artifact.parts)).join('\\\\n');\n console.log(answer || \\`The task ended as \\${result.status.state}\\`);\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst A2A_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { createA2AServer } from '../src/a2a/server.js';\n import { mockCogitator } from './helpers.js';\n\n function send(text: string) {\n return {\n jsonrpc: '2.0',\n id: 1,\n method: 'message/send',\n params: { message: { kind: 'message', messageId: 'm-1', role: 'user', parts: [{ kind: 'text', text }] } },\n };\n }\n\n describe('A2A server', () => {\n it('describes the assistant in an A2A v0.3 agent card', () => {\n const { cogitator } = mockCogitator();\n const card = createA2AServer(cogitator, undefined).getAgentCard('assistant', {\n baseUrl: 'http://localhost:3000',\n });\n expect(card.protocolVersion).toBe('0.3.0');\n expect(card.name).toBe('assistant');\n });\n\n it('answers a message with the agent', async () => {\n const { cogitator } = mockCogitator({ content: 'Hello over A2A' });\n try {\n const response = await createA2AServer(cogitator, undefined).handleJsonRpc(send('Hi'));\n expect(JSON.stringify(response)).toContain('Hello over A2A');\n } finally {\n await cogitator.close();\n }\n });\n\n it('refuses a caller without the token', async () => {\n const { cogitator } = mockCogitator({ content: 'secret' });\n const server = createA2AServer(cogitator, 'a2a-token');\n const refused = await server.handleJsonRpc(send('Hi'));\n expect(JSON.stringify(refused)).toContain('Unauthorized');\n const allowed = await server.handleJsonRpc(send('Hi'), 'a2a-token');\n expect(JSON.stringify(allowed)).toContain('secret');\n await cogitator.close();\n });\n });\n`;\n\n/** The imports and mount statements that put the A2A routes on a server's app. */\nexport function a2aMount(server: ServerFramework): { imports: string[]; mount: string } {\n switch (server) {\n case 'hono':\n return {\n imports: [\n \"import { a2aHono } from '@cogitator-ai/a2a/hono';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: \"app.route('/', a2aHono(a2aServer));\",\n };\n case 'express':\n return {\n imports: [\n \"import { a2aExpress } from '@cogitator-ai/a2a/express';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: 'app.use(a2aExpress(a2aServer));',\n };\n case 'fastify':\n return {\n imports: [\n \"import { a2aFastify } from '@cogitator-ai/a2a/fastify';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: 'await app.register(a2aFastify(a2aServer));',\n };\n case 'koa':\n return {\n imports: [\n \"import { bodyParser } from '@koa/bodyparser';\",\n \"import { a2aKoa } from '@cogitator-ai/a2a/koa';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: code`\n const a2aBody = bodyParser();\n app.use((ctx, next) => (ctx.path.startsWith('/a2a') ? a2aBody(ctx, next) : next()));\n app.use(a2aKoa(a2aServer));\n `,\n };\n case 'tetsu':\n throw new Error('A2A has no Tetsu adapter, which compatibilityIssues rules out');\n }\n}\n\n/** The agents served over the Agent-to-Agent protocol, next to the REST API. */\nexport const a2aFeature: FeatureModule = {\n id: 'feature:a2a',\n applies: (spec) => hasFeature(spec, 'a2a'),\n apply(project) {\n const { spec } = project;\n project\n .dependency('@cogitator-ai/a2a', cogitatorVersion('@cogitator-ai/a2a'))\n .file('src/a2a/server.ts', a2aServerTs(project))\n .file('src/a2a/ask.ts', A2A_ASK_TS)\n .file('tests/a2a.test.ts', A2A_TEST_TS)\n .envVar({\n name: 'A2A_TOKEN',\n description: 'Bearer token A2A callers need, open to anyone without it',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'A2A_URL',\n description: 'The A2A agent the a2a:ask script talks to',\n example: 'http://localhost:3000',\n required: false,\n secret: false,\n });\n if (spec.server === 'koa') project.dependency('@koa/bodyparser', VERSIONS.koaBodyparser);\n if (spec.app !== 'next')\n project.script('a2a:ask', 'tsx --env-file-if-exists=.env src/a2a/ask.ts');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'A2A',\n code`\n \\`src/a2a/server.ts\\` serves every agent of the registry over the Agent-to-Agent protocol v0.3, so agents built with other frameworks can call them: the card is at \\`/.well-known/agent-card.json\\`, JSON-RPC at \\`/a2a\\` (\\`/a2a/<agent>\\` for each agent). Set \\`A2A_TOKEN\\` to require a bearer token. \\`${runScript(pm, 'a2a:ask', '\"your question\"')}\\` asks an A2A agent, this project's by default or any at \\`A2A_URL\\`.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\n\n/** `src/lifecycle.ts`: graceful shutdown on SIGINT and SIGTERM for long-running processes. */\nexport const LIFECYCLE_TS = code`\n /**\n * Runs \\`close\\` once on SIGINT or SIGTERM, then exits. A shutdown that hangs,\n * for example on a stream that never ends, is cut off after \\`timeoutMs\\`.\n */\n export function onShutdown(close: () => Promise<void>, timeoutMs = 10_000): void {\n let closing = false;\n const stop = (signal: NodeJS.Signals) => {\n if (closing) return;\n closing = true;\n console.log(\\`\\${signal} received, shutting down\\`);\n setTimeout(() => {\n console.error('Shutdown took too long, exiting');\n process.exit(1);\n }, timeoutMs).unref();\n close().then(\n () => process.exit(0),\n (error: unknown) => {\n console.error(error);\n process.exit(1);\n }\n );\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n }\n`;\n\n/** The import lines of the startup steps features registered, for an entry point. */\nexport function startupImports(project: ProjectBuilder): string | false {\n return project.startup.imports.length > 0 && project.startup.imports.join('\\n');\n}\n\n/** The startup steps features registered, run before the entry point starts serving. */\nexport function startupStatements(project: ProjectBuilder): string | false {\n return project.startup.statements.length > 0 && project.startup.statements.join('\\n');\n}\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ChannelKind } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const WEBCHAT_PORT = 18789;\n\ninterface ChannelSetup {\n factory: string;\n expression: string;\n packages: Array<[string, string]>;\n env: Array<{ name: string; description: string; required: boolean }>;\n}\n\nconst CHANNEL_SETUP: Record<ChannelKind, ChannelSetup> = {\n telegram: {\n factory: 'telegramChannel',\n expression: 'telegramChannel({ token: env.TELEGRAM_BOT_TOKEN })',\n packages: [['grammy', VERSIONS.grammy]],\n env: [\n {\n name: 'TELEGRAM_BOT_TOKEN',\n description: 'Telegram bot token, from @BotFather',\n required: true,\n },\n ],\n },\n discord: {\n factory: 'discordChannel',\n expression: 'discordChannel({ token: env.DISCORD_BOT_TOKEN, mentionOnly: true })',\n packages: [['discord.js', VERSIONS.discord]],\n env: [\n {\n name: 'DISCORD_BOT_TOKEN',\n description: 'Discord bot token, from the Developer Portal',\n required: true,\n },\n ],\n },\n slack: {\n factory: 'slackChannel',\n expression: code`\n slackChannel({\n token: env.SLACK_BOT_TOKEN,\n signingSecret: env.SLACK_SIGNING_SECRET,\n appToken: env.SLACK_APP_TOKEN,\n })\n `,\n packages: [['@slack/bolt', VERSIONS.slackBolt]],\n env: [\n { name: 'SLACK_BOT_TOKEN', description: 'Slack bot token (xoxb-...)', required: true },\n { name: 'SLACK_SIGNING_SECRET', description: 'Slack signing secret', required: true },\n {\n name: 'SLACK_APP_TOKEN',\n description: 'Slack app token (xapp-...) for Socket Mode, HTTP mode without it',\n required: false,\n },\n ],\n },\n webchat: {\n factory: 'webchatChannel',\n expression: `webchatChannel({ port: Number(env.WEBCHAT_PORT ?? ${WEBCHAT_PORT}) })`,\n packages: [['ws', VERSIONS.ws]],\n env: [],\n },\n};\n\n/** A messaging bot: one Gateway that answers on every chosen channel with the assistant. */\nexport const appChannelsFeature: FeatureModule = {\n id: 'app:channels',\n applies: (spec) => spec.app === 'channels',\n apply(project) {\n const { spec } = project;\n project.dependency('@cogitator-ai/channels', cogitatorVersion('@cogitator-ai/channels'));\n\n for (const channel of spec.channels) {\n const setup = CHANNEL_SETUP[channel];\n for (const [name, version] of setup.packages) project.dependency(name, version);\n for (const variable of setup.env) project.envVar({ ...variable, secret: true });\n }\n if (spec.channels.includes('webchat')) {\n project.envVar({\n name: 'WEBCHAT_PORT',\n description: 'Port of the WebChat WebSocket',\n example: String(WEBCHAT_PORT),\n required: false,\n secret: false,\n });\n project.deploy.port = WEBCHAT_PORT;\n }\n\n project\n .file('src/lifecycle.ts', LIFECYCLE_TS)\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n project.deploy.kind = 'worker';\n\n project.instruct(\n 'You talk to people through chat apps, so keep answers short and conversational.'\n );\n },\n finalize(project) {\n const { spec } = project;\n const channels = spec.channels.map((channel) => CHANNEL_SETUP[channel]);\n const memory = spec.memory !== 'none';\n\n project.file(\n 'src/gateway.ts',\n code`\n import { Gateway, ${channels.map((c) => c.factory).join(', ')} } from '@cogitator-ai/channels';\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n const env = loadEnv();\n ${startupStatements(project)}\n ${memory && 'const memory = await cogitator.getMemory();'}\n\n /**\n * The assistant on its channels. \\`src/index.ts\\` starts it, and so do\n * \\`cogitator assistant\\` (with a live dashboard), \\`cogitator build\\` and\n * \\`cogitator daemon\\`, which look for this export.\n */\n export const gateway = new Gateway({\n cogitator,\n agent: agents.assistant,\n channels: [\n ${channels.map((c) => `${c.expression},`).join('\\n')}\n ],\n ${\n memory &&\n code`\n ...(memory && {\n memory,\n session: { compaction: { strategy: 'hybrid' as const, messageThreshold: 50, keepRecent: 10 } },\n }),\n `\n }\n stream: { flushInterval: 500, minChunkSize: 20 },\n onError: (error, message) => {\n console.error(\\`[\\${message.channelType}:\\${message.userId}] \\${error.message}\\`);\n },\n });\n `\n );\n\n const webchat = spec.channels.includes('webchat');\n project.file(\n 'src/index.ts',\n code`\n import { cogitator } from './cogitator.js';\n ${webchat && \"import { loadEnv } from './env.js';\"}\n import { gateway } from './gateway.js';\n import { onShutdown } from './lifecycle.js';\n\n await gateway.start();\n console.log(\\`The assistant is listening on \\${gateway.stats.connectedChannels.join(', ')}\\`);\n ${webchat && `console.log(\\`WebChat: ws://localhost:\\${loadEnv().WEBCHAT_PORT ?? ${WEBCHAT_PORT}}/ws\\`);`}\n\n onShutdown(async () => {\n await gateway.stop();\n await cogitator.close();\n });\n `\n );\n\n const pm = spec.packageManager;\n project.section(\n 'Bot',\n code`\n \\`src/gateway.ts\\` builds a \\`Gateway\\` from \\`@cogitator-ai/channels\\` that answers on ${spec.channels.join(', ')} with \\`agents.assistant\\`, and \\`src/index.ts\\` starts it. Each chat is its own thread${memory ? ' in memory, compacted when it grows long' : ''}. Channel tokens come from \\`.env\\`. \\`${runScript(pm, 'dev')}\\` runs it with reload on change, \\`cogitator assistant\\` with a live dashboard, \\`cogitator daemon start\\` in the background.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nconst NEXT_PORT = 3000;\n\nfunction nextConfig(project: ProjectBuilder): string {\n const cogitator = [...project.dependencies.keys()].filter(\n (name) => name.startsWith('@cogitator-ai/') && name !== '@cogitator-ai/next'\n );\n const external = [\n ...new Set([...cogitator, '@cogitator-ai/types', '@cogitator-ai/server-shared']),\n ...[...project.nativeBuilds].filter((name) => project.dependencies.has(name)),\n ].sort();\n return code`\n import type { NextConfig } from 'next';\n\n const config: NextConfig = {\n /**\n * Loaded by Node at runtime instead of bundled: they read files and native\n * modules, and one copy of each keeps \\`instanceof\\` working across packages.\n * @cogitator-ai/next stays bundled: its hooks need the app's own React.\n */\n serverExternalPackages: [${external.map((name) => tsString(name)).join(', ')}],\n };\n\n export default config;\n `;\n}\n\nconst TSCONFIG_NEXT =\n JSON.stringify(\n {\n compilerOptions: {\n target: 'es2023',\n lib: ['dom', 'dom.iterable', 'es2024'],\n allowJs: false,\n skipLibCheck: true,\n strict: true,\n noEmit: true,\n module: 'esnext',\n moduleResolution: 'bundler',\n resolveJsonModule: true,\n isolatedModules: true,\n verbatimModuleSyntax: true,\n jsx: 'react-jsx',\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./src/*'] },\n },\n include: ['next-env.d.ts', 'src', 'tests', 'evals', '*.config.ts', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2\n ) + '\\n';\n\nconst POSTCSS_CONFIG = code`\n export default {\n plugins: { '@tailwindcss/postcss': {} },\n };\n`;\n\nconst GLOBALS_CSS = code`\n @import \"tailwindcss\";\n\n @theme {\n --font-sans: ui-sans-serif, system-ui, sans-serif;\n }\n\n .prose-chat :where(p, ul, ol, pre) { margin-block: 0.5rem; }\n .prose-chat :where(ul) { list-style: disc; padding-left: 1.25rem; }\n .prose-chat :where(ol) { list-style: decimal; padding-left: 1.25rem; }\n .prose-chat :where(code) { font-size: 0.875em; }\n .prose-chat :where(pre) { overflow-x: auto; border-radius: 0.5rem; padding: 0.75rem; background: rgb(0 0 0 / 0.35); }\n .prose-chat :where(a) { text-decoration: underline; }\n`;\n\nfunction layoutTsx(project: ProjectBuilder): string {\n return code`\n import type { Metadata } from 'next';\n import type { ReactNode } from 'react';\n import './globals.css';\n\n export const metadata: Metadata = {\n title: ${tsString(project.spec.name)},\n description: 'A chat with your Cogitator agents',\n };\n\n export default function RootLayout({ children }: { children: ReactNode }) {\n return (\n <html lang=\"en\" className=\"dark\">\n <body className=\"bg-zinc-950 text-zinc-100 antialiased\">{children}</body>\n </html>\n );\n }\n `;\n}\n\nconst PAGE_TSX = code`\n import { Chat } from '@/components/chat';\n\n export default function Home() {\n return <Chat />;\n }\n`;\n\nconst SESSION_TS = code`\n import { randomUUID } from 'node:crypto';\n import { cookies } from 'next/headers';\n\n const COOKIE = 'cogitator-user';\n\n /**\n * Who is chatting: an anonymous id in an httpOnly cookie, so every browser has\n * threads of its own. Replace this with your auth (Auth.js, Clerk, your SSO)\n * by returning your user's id instead.\n */\n export async function currentUser(): Promise<string> {\n const jar = await cookies();\n const existing = jar.get(COOKIE)?.value;\n if (existing) return existing;\n const id = randomUUID();\n jar.set(COOKIE, id, { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production', path: '/' });\n return id;\n }\n`;\n\nfunction chatRouteTs(project: ProjectBuilder): string {\n return code`\n import { createChatHandler } from '@cogitator-ai/next';\n import { agents, cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n ${startupImports(project)}\n\n ${startupStatements(project)}\n\n export const POST = createChatHandler(cogitator, agents.assistant, {\n beforeRun: async () => ({ userId: await currentUser() }),\n });\n `;\n}\n\nconst RESUME_ROUTE_TS = code`\n import { createResumeHandler } from '@cogitator-ai/next';\n import { agents, cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n\n export const POST = createResumeHandler(cogitator, agents.assistant, {\n stream: true,\n beforeRun: async () => ({ userId: await currentUser() }),\n });\n`;\n\nconst THREAD_ROUTE_TS = code`\n import { assertThreadAccess, CogitatorError } from '@cogitator-ai/core';\n import type { ChatMessage } from '@cogitator-ai/next';\n import { cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n\n function text(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content.map((part: { type?: string; text?: string }) => (part.type === 'text' ? (part.text ?? '') : '')).join('');\n }\n\n /** The messages of one of the caller's threads, to show a saved conversation again. */\n export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {\n const { id } = await params;\n const memory = await cogitator.getMemory();\n if (!memory) return Response.json({ messages: [] });\n\n try {\n const thread = await assertThreadAccess(memory, id, await currentUser());\n if (!thread) return Response.json({ messages: [] });\n } catch (error) {\n if (error instanceof CogitatorError) return Response.json({ error: error.message }, { status: 403 });\n throw error;\n }\n\n const entries = await memory.getEntries({ threadId: id, includeToolCalls: true });\n if (!entries.success) return Response.json({ error: entries.error }, { status: 500 });\n\n const messages: ChatMessage[] = entries.data\n .filter((entry) => entry.message.role === 'user' || entry.message.role === 'assistant')\n .map((entry): ChatMessage => ({\n id: entry.id,\n role: entry.message.role === 'user' ? 'user' : 'assistant',\n content: text(entry.message.content),\n ...(entry.toolCalls?.length && { toolCalls: entry.toolCalls }),\n createdAt: entry.createdAt,\n }))\n .filter((message) => message.content || message.toolCalls);\n return Response.json({ messages });\n }\n`;\n\nconst HEALTH_ROUTE_TS = code`\n export function GET() {\n return Response.json({ status: 'ok' });\n }\n`;\n\nconst CHAT_TSX = code`\n 'use client';\n\n import type { ChatMessage } from '@cogitator-ai/next';\n import { useCogitatorChat } from '@cogitator-ai/next/client';\n import { type FormEvent, useEffect, useRef, useState } from 'react';\n import { Message } from './message';\n import { Threads, type SavedThread } from './threads';\n\n const THREADS_KEY = 'cogitator-threads';\n\n function loadThreads(): SavedThread[] {\n try {\n return JSON.parse(localStorage.getItem(THREADS_KEY) ?? '[]') as SavedThread[];\n } catch {\n return [];\n }\n }\n\n export function Chat() {\n const [threads, setThreads] = useState<SavedThread[]>([]);\n const [toolResults, setToolResults] = useState<Record<string, unknown>>({});\n const bottom = useRef<HTMLDivElement>(null);\n\n const chat = useCogitatorChat({\n api: '/api/chat',\n resumeApi: '/api/chat/resume',\n onToolResult: (event) => setToolResults((all) => ({ ...all, [event.toolCallId]: event.result })),\n });\n const { messages, input, setInput, send, stop, isLoading, error, threadId, pendingApprovals } = chat;\n\n useEffect(() => setThreads(loadThreads()), []);\n\n useEffect(() => {\n if (messages.length > 0) bottom.current?.scrollIntoView({ behavior: 'smooth' });\n }, [messages]);\n\n useEffect(() => {\n const first = messages.find((message) => message.role === 'user');\n if (!threadId || !first) return;\n setThreads((current) => {\n if (current.some((thread) => thread.id === threadId)) return current;\n const next = [{ id: threadId, title: first.content.slice(0, 60) }, ...current].slice(0, 50);\n localStorage.setItem(THREADS_KEY, JSON.stringify(next));\n return next;\n });\n }, [threadId, messages]);\n\n async function open(id: string) {\n const response = await fetch(\\`/api/threads/\\${encodeURIComponent(id)}\\`);\n const body = (await response.json()) as { messages?: ChatMessage[] };\n chat.setMessages(body.messages ?? []);\n chat.setThreadId(id);\n setToolResults({});\n }\n\n function startNew() {\n chat.clearMessages();\n chat.setThreadId(undefined);\n setToolResults({});\n }\n\n function submit(event: FormEvent) {\n event.preventDefault();\n if (!input.trim() || isLoading) return;\n void send();\n }\n\n return (\n <div className=\"flex h-screen\">\n <Threads threads={threads} current={threadId} onOpen={open} onNew={startNew} />\n <main className=\"flex flex-1 flex-col\">\n <div className=\"flex-1 overflow-y-auto px-4 py-6\">\n <div className=\"mx-auto flex max-w-3xl flex-col gap-4\">\n {messages.length === 0 && (\n <p className=\"mt-24 text-center text-zinc-500\">Ask anything. The assistant can browse the web, do math and tell the time.</p>\n )}\n {messages.map((message) => (\n <Message key={message.id} message={message} toolResults={toolResults} />\n ))}\n {isLoading && <p className=\"text-sm text-zinc-500\">Thinking...</p>}\n {pendingApprovals.length > 0 && (\n <div className=\"rounded-xl border border-amber-700 bg-amber-950/60 p-4 text-sm\">\n <p className=\"font-medium text-amber-200\">The assistant wants to run:</p>\n <ul className=\"mt-2 space-y-1\">\n {pendingApprovals.map((call) => (\n <li key={call.toolCallId}>\n <code>{call.toolName}</code> <code className=\"text-zinc-400\">{JSON.stringify(call.arguments)}</code>\n </li>\n ))}\n </ul>\n <div className=\"mt-3 flex gap-2\">\n <button type=\"button\" className=\"rounded-lg bg-amber-600 px-3 py-1.5 font-medium\" onClick={() => void chat.approve()}>\n Approve\n </button>\n <button type=\"button\" className=\"rounded-lg border border-zinc-600 px-3 py-1.5\" onClick={() => void chat.deny('Declined in the chat')}>\n Deny\n </button>\n </div>\n </div>\n )}\n {error && (\n <p className=\"rounded-xl border border-red-800 bg-red-950/60 px-4 py-2 text-sm text-red-200\">{error.message}</p>\n )}\n <div ref={bottom} />\n </div>\n </div>\n <form onSubmit={submit} className=\"mx-auto flex w-full max-w-3xl gap-2 px-4 pb-6\">\n <input\n value={input}\n onChange={(event) => setInput(event.target.value)}\n placeholder=\"Message the assistant\"\n className=\"flex-1 rounded-xl border border-zinc-700 bg-zinc-900 px-4 py-3 outline-none focus:border-zinc-400\"\n />\n {isLoading ? (\n <button type=\"button\" onClick={stop} className=\"rounded-xl border border-zinc-600 px-5\">\n Stop\n </button>\n ) : (\n <button type=\"submit\" disabled={!input.trim()} className=\"rounded-xl bg-zinc-100 px-5 font-medium text-zinc-900 disabled:opacity-40\">\n Send\n </button>\n )}\n </form>\n </main>\n </div>\n );\n }\n`;\n\nconst MESSAGE_TSX = code`\n import type { ChatMessage } from '@cogitator-ai/next';\n import ReactMarkdown from 'react-markdown';\n\n export function Message({ message, toolResults }: { message: ChatMessage; toolResults: Record<string, unknown> }) {\n const mine = message.role === 'user';\n return (\n <div className={\\`flex \\${mine ? 'justify-end' : 'justify-start'}\\`}>\n <div className={\\`max-w-[85%] rounded-2xl px-4 py-2 \\${mine ? 'bg-zinc-100 text-zinc-900' : 'bg-zinc-900'}\\`}>\n {message.reasoning && (\n <details className=\"mb-2 text-sm text-zinc-400\">\n <summary className=\"cursor-pointer\">Reasoning</summary>\n <p className=\"mt-1 whitespace-pre-wrap\">{message.reasoning}</p>\n </details>\n )}\n {message.toolCalls?.map((call) => (\n <details key={call.id} className=\"mb-2 rounded-lg border border-zinc-800 px-3 py-2 text-sm\">\n <summary className=\"cursor-pointer font-mono text-zinc-300\">{call.name}</summary>\n <pre className=\"mt-2 overflow-x-auto text-xs text-zinc-400\">{JSON.stringify(call.arguments, null, 2)}</pre>\n {call.id in toolResults && (\n <pre className=\"mt-2 overflow-x-auto text-xs text-zinc-300\">{JSON.stringify(toolResults[call.id], null, 2)}</pre>\n )}\n </details>\n ))}\n <div className=\"prose-chat\">\n <ReactMarkdown>{message.content}</ReactMarkdown>\n </div>\n </div>\n </div>\n );\n }\n`;\n\nconst THREADS_TSX = code`\n export interface SavedThread {\n id: string;\n title: string;\n }\n\n export function Threads({\n threads,\n current,\n onOpen,\n onNew,\n }: {\n threads: SavedThread[];\n current: string | undefined;\n onOpen: (id: string) => void;\n onNew: () => void;\n }) {\n return (\n <aside className=\"hidden w-64 flex-col border-r border-zinc-800 p-3 md:flex\">\n <button type=\"button\" onClick={onNew} className=\"mb-3 rounded-lg border border-zinc-700 px-3 py-2 text-left text-sm\">\n New chat\n </button>\n <nav className=\"flex flex-col gap-1 overflow-y-auto\">\n {threads.map((thread) => (\n <button\n key={thread.id}\n type=\"button\"\n onClick={() => onOpen(thread.id)}\n className={\\`truncate rounded-lg px-3 py-2 text-left text-sm \\${thread.id === current ? 'bg-zinc-800' : 'hover:bg-zinc-900'}\\`}\n >\n {thread.title}\n </button>\n ))}\n </nav>\n </aside>\n );\n }\n`;\n\nconst SAVE_NOTE_TS = code`\n import { appendFile, mkdir } from 'node:fs/promises';\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n /** Saves a note to data/notes.md. It changes a file, so the chat asks you to approve it first. */\n export const saveNote = tool({\n name: 'save_note',\n description: 'Save a note for the user to read later.',\n parameters: z.object({ text: z.string().min(1).max(2_000).describe('The note') }),\n sideEffects: ['filesystem'],\n requiresApproval: true,\n execute: async ({ text }) => {\n await mkdir('data', { recursive: true });\n await appendFile('data/notes.md', \\`- \\${new Date().toISOString()} \\${text}\\\\n\\`);\n return { saved: true };\n },\n });\n`;\n\n/** A Next.js chat app: streaming, tool calls, approvals and saved threads, with the agents on the server. */\nexport const appNextFeature: FeatureModule = {\n id: 'app:next',\n applies: (spec) => spec.app === 'next',\n apply(project) {\n project\n .dependency('@cogitator-ai/next', cogitatorVersion('@cogitator-ai/next'))\n .dependency('next', VERSIONS.next)\n .dependency('react', VERSIONS.react)\n .dependency('react-dom', VERSIONS.reactDom)\n .dependency('react-markdown', VERSIONS.reactMarkdown)\n .devDependency('typescript', VERSIONS.typescript)\n .devDependency('@types/react', VERSIONS.typesReact)\n .devDependency('@types/react-dom', VERSIONS.typesReactDom)\n .devDependency('tailwindcss', VERSIONS.tailwind)\n .devDependency('@tailwindcss/postcss', VERSIONS.tailwindPostcss)\n .file('tsconfig.json', TSCONFIG_NEXT)\n .file('postcss.config.mjs', POSTCSS_CONFIG)\n .file('src/app/globals.css', GLOBALS_CSS)\n .file('src/app/layout.tsx', layoutTsx(project))\n .file('src/app/page.tsx', PAGE_TSX)\n .file('src/lib/session.ts', SESSION_TS)\n .file('src/app/api/chat/resume/route.ts', RESUME_ROUTE_TS)\n .file('src/app/api/threads/[id]/route.ts', THREAD_ROUTE_TS)\n .file('src/app/api/health/route.ts', HEALTH_ROUTE_TS)\n .file('src/components/chat.tsx', CHAT_TSX)\n .file('src/components/message.tsx', MESSAGE_TSX)\n .file('src/components/threads.tsx', THREADS_TSX)\n .file('src/tools/save-note.ts', SAVE_NOTE_TS)\n .tool('saveNote', './save-note.js')\n .script('dev', 'next dev')\n .script('build', 'next build')\n .script('start', 'next start')\n .ignore('.next/', 'out/', 'next-env.d.ts', 'data/')\n .instruct(\n 'You chat in a web page that renders Markdown, so format answers with Markdown when it helps.'\n );\n project.deploy.kind = 'server';\n project.deploy.port = NEXT_PORT;\n project.deploy.healthPath = '/api/health';\n },\n finalize(project) {\n project\n .file('next.config.ts', nextConfig(project))\n .file('src/app/api/chat/route.ts', chatRouteTs(project));\n const pm = project.spec.packageManager;\n project.section(\n 'Next.js app',\n code`\n \\`src/app/api/chat/route.ts\\` streams the assistant with \\`createChatHandler\\`, \\`src/app/api/chat/resume/route.ts\\` continues a run after an approval, and \\`src/app/api/threads/[id]/route.ts\\` loads a saved conversation after checking it belongs to the caller. \\`src/lib/session.ts\\` identifies the caller with an anonymous cookie: replace it with your auth. \\`src/components/chat.tsx\\` is the client (\\`useCogitatorChat\\`): Markdown, tool calls with their results, reasoning, approvals for \\`save_note\\`, stop, and threads kept in the sidebar. \\`${runScript(pm, 'dev')}\\` serves it on http://localhost:${NEXT_PORT}.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, primaryTarget } from '../spec.js';\nimport { VERSIONS } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\n/** The terminal chat over the assistant: one-shot from argv or stdin, a REPL otherwise. */\nfunction agentEntry(project: ProjectBuilder): string {\n const { spec } = project;\n const harness = hasFeature(spec, 'harness');\n const persistent = spec.memory !== 'none';\n return code`\n import { createInterface${harness ? ', type Interface' : ''} } from 'node:readline/promises';\n import { styleText } from 'node:util';\n ${harness && \"import type { ToolApprovalDecision, ToolApprovalRequest } from '@cogitator-ai/core';\"}\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${harness && \"import { facts } from './harness/facts.js';\"}\n ${harness && \"import { startScheduler } from './harness/scheduler.js';\"}\n ${startupImports(project)}\n\n ${\n persistent\n ? code`\n /** One thread for the terminal, so the conversation carries over between runs. */\n const THREAD_ID = 'terminal';\n `\n : code`\n /** One thread per process: the project keeps no memory, so every start is a fresh conversation. */\n const THREAD_ID = \\`terminal-\\${process.pid}\\`;\n `\n }\n\n async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks).toString('utf8').trim();\n }\n\n ${\n harness &&\n code`\n /** Asks in the terminal before a tool that changes something runs; without a terminal it is declined. */\n async function approve(request: ToolApprovalRequest, rl?: Interface): Promise<ToolApprovalDecision> {\n if (!rl) return { approved: false, reason: 'Nobody is at the terminal to approve it' };\n const answer = await rl.question(\n styleText('yellow', \\` \\${request.toolName} wants to run with \\${JSON.stringify(request.arguments)}. Allow? [y/N] \\`)\n );\n return /^y(es)?$/i.test(answer.trim())\n ? { approved: true }\n : { approved: false, reason: 'Declined at the terminal' };\n }\n `\n }\n\n async function ask(input: string${harness ? ', rl?: Interface' : ''}): Promise<void> {\n let streamed = false;\n const result = await cogitator.run(agents.assistant, {\n input,\n threadId: THREAD_ID,\n stream: true,\n ${harness && 'context: { factsAboutTheUser: await facts.context() },'}\n onToken: (token) => {\n streamed = true;\n process.stdout.write(token);\n },\n onToolCall: (call) => {\n process.stderr.write(styleText('dim', \\`\\\\n > \\${call.name} \\${JSON.stringify(call.arguments)}\\\\n\\`));\n },\n ${harness && 'onApproval: (request) => approve(request, rl),'}\n });\n\n if (!streamed) process.stdout.write(result.output);\n process.stdout.write('\\\\n');\n const { totalTokens, cost, duration } = result.usage;\n process.stderr.write(\n styleText('dim', \\` \\${totalTokens} tokens, $\\${cost.toFixed(4)}, \\${(duration / 1000).toFixed(1)}s\\\\n\\`)\n );\n }\n\n async function chat(): Promise<void> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const closed = new Promise<null>((resolve) => rl.once('close', () => resolve(null)));\n rl.on('SIGINT', () => rl.close());\n ${\n harness &&\n code`\n let queue: Promise<void> = Promise.resolve();\n /** Runs one turn at a time, so a scheduled task never talks over the user. */\n const serially = (turn: () => Promise<void>) => {\n queue = queue.then(turn).catch((error: unknown) => {\n console.error(styleText('red', error instanceof Error ? error.message : String(error)));\n });\n return queue;\n };\n const scheduler = startScheduler((task) =>\n serially(async () => {\n console.log(styleText('magenta', '\\\\n[scheduled task]'));\n await ask(task, rl);\n })\n );\n `\n }\n\n console.log(\n styleText('bold', 'Chat with the assistant.') + styleText('dim', ' /exit or Ctrl+C to leave.')\n );\n try {\n for (;;) {\n const line = await Promise.race([rl.question(styleText('cyan', '> ')).catch(() => null), closed]);\n if (line === null) break;\n const input = line.trim();\n if (!input) continue;\n if (input === '/exit') break;\n ${\n harness\n ? 'await serially(() => ask(input, rl));'\n : code`\n try {\n await ask(input);\n } catch (error) {\n console.error(styleText('red', error instanceof Error ? error.message : String(error)));\n }\n `\n }\n }\n } finally {\n ${harness && 'scheduler.stop();'}\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const fromArgs = process.argv.slice(2).join(' ').trim();\n const input = fromArgs || (process.stdin.isTTY ? '' : await readStdin());\n if (input) await ask(input);\n else await chat();\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(async () => {\n ${harness && 'await facts.close();'}\n await cogitator.close();\n });\n `;\n}\n\nexport const appScriptFeature: FeatureModule = {\n id: 'app:script',\n applies: (spec) => spec.app === 'script',\n apply(project) {\n const { spec } = project;\n const target = primaryTarget(spec);\n\n project\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n if (target === 'agent') project.script('ask', 'tsx --env-file-if-exists=.env src/index.ts');\n },\n finalize(project) {\n const { spec } = project;\n const target = primaryTarget(spec);\n const pm = spec.packageManager;\n if (target === 'agent') project.file('src/index.ts', agentEntry(project));\n project.section(\n 'Running',\n target === 'agent'\n ? code`\n \\`src/index.ts\\` is a terminal chat with the assistant. \\`${runScript(pm, 'dev')}\\` opens it and restarts on change, \\`${runScript(pm, 'ask', '\"your question\"')}\\` answers once, and piped stdin works too. \\`${runScript(pm, 'build')}\\` then \\`${runScript(pm, 'start')}\\` runs the compiled build.\n `\n : code`\n \\`src/index.ts\\` runs the project's ${target}. \\`${runScript(pm, 'dev')}\\` runs it with reload on change, \\`${runScript(pm, 'build')}\\` then \\`${runScript(pm, 'start')}\\` runs the compiled build.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type ProjectSpec, type ServerFramework } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { a2aMount } from './a2a.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const SERVER_BASE_PATH = '/api';\nexport const SERVER_PORT = 3000;\n\n/** The registry exports a server mounts, by whether the project has workflows and swarms. */\nexport function registryImports(project: ProjectBuilder): { names: string[]; options: string } {\n const workflows = project.registry.some((entry) => entry.kind === 'workflows');\n const swarms = project.registry.some((entry) => entry.kind === 'swarms');\n const names = [\n 'agents',\n 'cogitator',\n ...(swarms ? ['swarms'] : []),\n ...(workflows ? ['workflows'] : []),\n ];\n const options = [\n 'cogitator',\n 'agents',\n ...(workflows ? ['workflows'] : []),\n ...(swarms ? ['swarms'] : []),\n ].join(', ');\n return { names, options };\n}\n\nconst AUTH_TS = code`\n import { timingSafeEqual } from 'node:crypto';\n\n /** Routes under ${SERVER_BASE_PATH} that answer without a token: health probes and the API docs. */\n const PUBLIC_PATHS = new Set(['/health', '/ready', '/docs', '/openapi.json']);\n\n export interface Caller {\n userId: string;\n }\n\n export class UnauthorizedError extends Error {\n readonly status = 401;\n\n constructor() {\n super('Unauthorized');\n this.name = 'UnauthorizedError';\n }\n }\n\n function isPublic(path: string): boolean {\n const bare = path.split('?')[0] ?? path;\n const local = bare.startsWith('${SERVER_BASE_PATH}/') ? bare.slice(${SERVER_BASE_PATH.length}) : bare;\n return PUBLIC_PATHS.has(local);\n }\n\n function sameToken(given: string, expected: string): boolean {\n const a = Buffer.from(given);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n /**\n * Who is calling. With API_TOKEN set, every route except the public ones needs\n * \\`Authorization: Bearer <API_TOKEN>\\`; without it (local development only) all\n * requests are one local caller. Public routes are answered for anyone.\n */\n export function authenticate(path: string, authorization: string | undefined, token: string | undefined): Caller | undefined {\n if (isPublic(path)) return undefined;\n if (!token) return { userId: 'local' };\n const given = authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;\n if (!given || !sameToken(given, token)) throw new UnauthorizedError();\n return { userId: 'api' };\n }\n`;\n\n/** The settings every server reads from the environment, checked at startup. */\nfunction settings(spec: ProjectSpec): string {\n return code`\n const env = loadEnv();\n const production = process.env.NODE_ENV === 'production';\n const port = Number(env.PORT ?? ${SERVER_PORT});\n const host = env.HOST ?? (production ? '0.0.0.0' : '127.0.0.1');\n\n if (production && !env.API_TOKEN) {\n throw new Error('Set API_TOKEN in production: every route except health and docs requires it');\n }\n ${spec.server !== 'tetsu' && \"const corsOrigins = env.CORS_ORIGIN?.split(',').map((origin) => origin.trim()).filter(Boolean);\"}\n `;\n}\n\nfunction listening(): string {\n return code`\n console.log(\\`API on http://\\${host}:\\${port}${SERVER_BASE_PATH}, docs on http://\\${host}:\\${port}${SERVER_BASE_PATH}/docs\\`);\n if (!env.API_TOKEN) console.log('API_TOKEN is not set: the API answers anyone who can reach it');\n `;\n}\n\n/** The A2A routes of a server, when the project has the a2a feature. */\nfunction a2a(project: ProjectBuilder): { imports: string | false; mount: string | false } {\n const server = project.spec.server;\n if (!hasFeature(project.spec, 'a2a') || !server || server === 'tetsu')\n return { imports: false, mount: false };\n const { imports, mount } = a2aMount(server);\n return { imports: imports.join('\\n'), mount };\n}\n\nconst NODE_HTTP_CLOSE = code`\n interface Closable {\n close(callback: (error?: Error) => void): unknown;\n closeIdleConnections?: () => void;\n }\n\n function closeServer(server: Closable): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n server.closeIdleConnections?.();\n });\n }\n`;\n\nfunction honoEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { serve } from '@hono/node-server';\n import { cogitatorApp } from '@cogitator-ai/hono';\n import { Hono } from 'hono';\n import { cors } from 'hono/cors';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = new Hono();\n if (corsOrigins?.length) app.use('${SERVER_BASE_PATH}/*', cors({ origin: corsOrigins }));\n ${a2a(project).mount}\n app.route(\n '${SERVER_BASE_PATH}',\n cogitatorApp({\n ${options},\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (c) => authenticate(c.req.path, c.req.header('authorization'), env.API_TOKEN),\n })\n );\n\n const server = serve({ fetch: app.fetch, port, hostname: host }, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction expressEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { CogitatorServer } from '@cogitator-ai/express';\n import express from 'express';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = express();\n ${a2a(project).mount}\n const api = new CogitatorServer({\n app,\n ${options},\n config: {\n basePath: '${SERVER_BASE_PATH}',\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (req) => authenticate(req.path, req.get('authorization'), env.API_TOKEN),\n ...(corsOrigins?.length ? { cors: { origin: corsOrigins } } : {}),\n },\n });\n await api.init();\n\n const server = app.listen(port, host, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction fastifyEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import cors from '@fastify/cors';\n import { cogitatorPlugin } from '@cogitator-ai/fastify';\n import Fastify from 'fastify';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = Fastify({ logger: { level: production ? 'info' : 'warn' } });\n if (corsOrigins?.length) await app.register(cors, { origin: corsOrigins });\n ${a2a(project).mount}\n await app.register(cogitatorPlugin, {\n ${options},\n prefix: '${SERVER_BASE_PATH}',\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (request) => authenticate(request.url, request.headers.authorization, env.API_TOKEN),\n });\n\n await app.listen({ port, host });\n ${listening()}\n\n onShutdown(async () => {\n await app.close();\n await cogitator.close();\n });\n `;\n}\n\nfunction koaEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import cors from '@koa/cors';\n import { cogitatorApp } from '@cogitator-ai/koa';\n import Koa from 'koa';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = new Koa();\n ${a2a(project).mount}\n if (corsOrigins?.length) {\n const allowed = new Set(corsOrigins);\n app.use(cors({ origin: (ctx) => (allowed.has(ctx.get('origin')) ? ctx.get('origin') : '') }));\n }\n\n const router = cogitatorApp({\n ${options},\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (ctx) => authenticate(ctx.path, ctx.get('authorization'), env.API_TOKEN),\n });\n router.prefix('${SERVER_BASE_PATH}');\n app.use(router.routes()).use(router.allowedMethods());\n\n const server = app.listen(port, host, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction tetsuEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { cogitatorController } from '@cogitator-ai/tetsu';\n import { createApp, group } from '@tetsujs/core';\n import { docs } from '@tetsujs/openapi';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = createApp({\n routes: [\n group('${SERVER_BASE_PATH}', {\n children: [\n cogitatorController({\n ${options},\n auth: (ctx) =>\n authenticate(new URL(ctx.req.url).pathname, ctx.req.headers.get('authorization') ?? undefined, env.API_TOKEN) ?? {},\n }),\n docs({ info: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' } }),\n ],\n }),\n ],\n });\n\n const server = Bun.serve({ ...app, port, hostname: host });\n ${listening()}\n\n onShutdown(async () => {\n await server.stop();\n await cogitator.close();\n });\n `;\n}\n\nconst ENTRIES: Record<ServerFramework, (project: ProjectBuilder) => string> = {\n hono: honoEntry,\n express: expressEntry,\n fastify: fastifyEntry,\n koa: koaEntry,\n tetsu: tetsuEntry,\n};\n\nfunction frameworkPackages(project: ProjectBuilder, server: ServerFramework): void {\n const adapter = `@cogitator-ai/${server}` as const;\n project.dependency(adapter, cogitatorVersion(adapter));\n switch (server) {\n case 'hono':\n project\n .dependency('hono', VERSIONS.hono)\n .dependency('@hono/node-server', VERSIONS.honoNodeServer);\n break;\n case 'express':\n project\n .dependency('express', VERSIONS.express)\n .devDependency('@types/express', VERSIONS.typesExpress);\n break;\n case 'fastify':\n project\n .dependency('fastify', VERSIONS.fastify)\n .dependency('@fastify/cors', VERSIONS.fastifyCors);\n break;\n case 'koa':\n project\n .dependency('koa', VERSIONS.koa)\n .dependency('@koa/router', VERSIONS.koaRouter)\n .dependency('@koa/cors', VERSIONS.koaCors)\n .devDependency('@types/koa', VERSIONS.typesKoa)\n .devDependency('@types/koa__cors', VERSIONS.typesKoaCors);\n break;\n case 'tetsu':\n project\n .dependency('@tetsujs/core', VERSIONS.tetsuCore)\n .dependency('@tetsujs/sse', VERSIONS.tetsuSse)\n .dependency('@tetsujs/openapi', VERSIONS.tetsuOpenapi);\n break;\n }\n}\n\nexport const appServerFeature: FeatureModule = {\n id: 'app:server',\n applies: (spec) => spec.app === 'server',\n apply(project) {\n const { spec } = project;\n const server = spec.server ?? 'hono';\n const bun = server === 'tetsu';\n\n frameworkPackages(project, server);\n project.file('src/auth.ts', AUTH_TS).file('src/lifecycle.ts', LIFECYCLE_TS);\n\n if (bun) {\n project.script('dev', 'bun --watch src/index.ts').script('start', 'bun src/index.ts');\n } else {\n project\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n }\n\n project\n .envVar({\n name: 'PORT',\n description: 'Port the API listens on',\n example: String(SERVER_PORT),\n required: false,\n secret: false,\n })\n .envVar({\n name: 'HOST',\n description: 'Interface to listen on: 127.0.0.1 in development, 0.0.0.0 in production',\n example: '127.0.0.1',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'API_TOKEN',\n description:\n 'Bearer token every route except health and docs requires, mandatory in production',\n required: false,\n secret: true,\n deploy: true,\n });\n if (!bun) {\n project.envVar({\n name: 'CORS_ORIGIN',\n description:\n 'Comma-separated browser origins allowed to call the API, CORS is off without it',\n example: 'http://localhost:5173',\n required: false,\n secret: false,\n });\n }\n\n project.deploy.kind = 'server';\n project.deploy.port = SERVER_PORT;\n project.deploy.healthPath = `${SERVER_BASE_PATH}/health`;\n },\n finalize(project) {\n const { spec } = project;\n const server = spec.server ?? 'hono';\n const pm = spec.packageManager;\n project.file('src/index.ts', ENTRIES[server](project));\n\n project.section(\n 'Server',\n code`\n \\`src/index.ts\\` serves the registry over HTTP with ${server === 'tetsu' ? 'Tetsu on Bun' : server}: every agent${project.registry.some((e) => e.kind === 'workflows') ? ', workflow' : ''}${project.registry.some((e) => e.kind === 'swarms') ? ' and swarm' : ''} in \\`src/cogitator.ts\\` gets REST and SSE routes under \\`${SERVER_BASE_PATH}\\`, with OpenAPI docs at \\`${SERVER_BASE_PATH}/docs\\`. \\`src/auth.ts\\` decides who may call: with \\`API_TOKEN\\` set every route but health and docs needs \\`Authorization: Bearer <token>\\`. Start it with \\`${runScript(pm, 'dev')}\\` and try:\n\n \\`\\`\\`bash\n curl -X POST http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/agents/assistant/run -H 'content-type: application/json' -d '{\"input\":\"What time is it in Tokyo?\"}'\n \\`\\`\\`\n `\n );\n project.readmeSection(\n 'API',\n code`\n \\`${runScript(pm, 'dev')}\\` starts the API on http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}, with interactive docs at http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/docs.\n\n \\`\\`\\`bash\n curl -X POST http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/agents/assistant/run \\\\\n -H 'content-type: application/json' \\\\\n -d '{\"input\":\"What time is it in Tokyo?\"}'\n \\`\\`\\`\n\n Set \\`API_TOKEN\\` in \\`.env\\` to require \\`Authorization: Bearer <token>\\` on every route but health and docs. In production (\\`NODE_ENV=production\\`) the server refuses to start without it.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, IMAGES, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nexport const DEFAULT_DATABASE_URL = 'postgresql://cogitator:cogitator@localhost:5432/cogitator';\nexport const DEFAULT_REDIS_URL = 'redis://localhost:6379';\nexport const DEFAULT_MONGODB_URI = 'mongodb://localhost:27017';\nexport const SQLITE_PATH = './data/memory.db';\n\n/** The Redis service compose starts, shared by Redis memory and the queue worker. */\nexport function addRedisService(project: ProjectBuilder): void {\n project.service(\n {\n name: 'redis',\n image: IMAGES.redis,\n ports: ['6379:6379'],\n volumes: ['redis_data:/data'],\n healthcheck: {\n test: ['CMD', 'redis-cli', 'ping'],\n interval: '5s',\n timeout: '3s',\n retries: 10,\n },\n },\n 'redis_data'\n );\n project.envVar({\n name: 'REDIS_URL',\n description: 'The Redis server',\n example: DEFAULT_REDIS_URL,\n required: false,\n secret: false,\n });\n}\n\n/** The Postgres service with pgvector compose starts, shared by Postgres memory and the pgvector store. */\nexport function addPostgresService(project: ProjectBuilder): void {\n project.service(\n {\n name: 'postgres',\n image: IMAGES.postgres,\n ports: ['5432:5432'],\n environment: {\n POSTGRES_USER: 'cogitator',\n POSTGRES_PASSWORD: 'cogitator',\n POSTGRES_DB: 'cogitator',\n },\n volumes: ['postgres_data:/var/lib/postgresql'],\n healthcheck: {\n test: ['CMD-SHELL', 'pg_isready -U cogitator -d cogitator'],\n interval: '5s',\n timeout: '3s',\n retries: 10,\n },\n },\n 'postgres_data'\n );\n project.dependency('pg', VERSIONS.pg);\n project.envVar({\n name: 'DATABASE_URL',\n description: 'The Postgres database',\n example: DEFAULT_DATABASE_URL,\n required: false,\n secret: true,\n deploy: true,\n });\n}\n\nexport const memoryFeature: FeatureModule = {\n id: 'memory',\n applies: (spec) => spec.memory !== 'none',\n apply(project) {\n const { spec } = project;\n project.dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'));\n\n switch (spec.memory) {\n case 'memory':\n project.memoryYml.push('adapter: memory');\n break;\n case 'sqlite':\n project.dependency('better-sqlite3', VERSIONS.betterSqlite3).allowBuild('better-sqlite3');\n project.memoryYml.push('adapter: sqlite', 'sqlite:', ` path: ${SQLITE_PATH}`);\n project.ignore('data/');\n break;\n case 'postgres':\n addPostgresService(project);\n project.memoryYml.push(\n 'adapter: postgres',\n 'postgres:',\n ` connectionString: \\${DATABASE_URL:-${DEFAULT_DATABASE_URL}}`\n );\n break;\n case 'redis':\n addRedisService(project);\n project\n .dependency('@cogitator-ai/redis', cogitatorVersion('@cogitator-ai/redis'))\n .dependency('ioredis', VERSIONS.ioredis);\n project.memoryYml.push(\n 'adapter: redis',\n 'redis:',\n ` url: \\${REDIS_URL:-${DEFAULT_REDIS_URL}}`\n );\n break;\n case 'mongodb':\n project.service(\n {\n name: 'mongodb',\n image: IMAGES.mongodb,\n ports: ['27017:27017'],\n volumes: ['mongodb_data:/data/db'],\n healthcheck: {\n test: ['CMD', 'mongosh', '--quiet', '--eval', \"db.adminCommand('ping')\"],\n interval: '5s',\n timeout: '5s',\n retries: 10,\n },\n },\n 'mongodb_data'\n );\n project.dependency('mongodb', VERSIONS.mongodb);\n project.envVar({\n name: 'MONGODB_URI',\n description: 'The MongoDB server',\n example: DEFAULT_MONGODB_URI,\n required: false,\n secret: true,\n deploy: true,\n });\n project.memoryYml.push(\n 'adapter: mongodb',\n 'mongodb:',\n ` uri: \\${MONGODB_URI:-${DEFAULT_MONGODB_URI}}`,\n ' database: cogitator'\n );\n break;\n case 'none':\n break;\n }\n\n const where: Record<typeof spec.memory, string> = {\n none: '',\n memory: 'in the process, so it is gone after a restart',\n sqlite: `in SQLite at \\`${SQLITE_PATH}\\``,\n postgres: 'in Postgres (`DATABASE_URL`, started by `docker compose up -d`)',\n redis: 'in Redis (`REDIS_URL`, started by `docker compose up -d`)',\n mongodb: 'in MongoDB (`MONGODB_URI`, started by `docker compose up -d`)',\n };\n project.section(\n 'Memory',\n code`\n Conversations are stored ${where[spec.memory]}. The \\`memory\\` section of \\`cogitator.yml\\` configures it, and runs with the same \\`threadId\\` continue the same conversation. Tests replace it with in-process memory.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { addRedisService, DEFAULT_REDIS_URL } from './memory.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const METRICS_PORT = 9464;\n\nconst QUEUE_TS = code`\n import { loadConfig } from '@cogitator-ai/config';\n import type { Agent } from '@cogitator-ai/core';\n import { type SerializedAgent, serializeAgent } from '@cogitator-ai/worker';\n\n /** The Redis the job queue lives in, shared by the worker and the producers. */\n export const redis = { url: process.env.REDIS_URL ?? '${DEFAULT_REDIS_URL}' };\n\n /**\n * An agent as a job carries it to a worker. Agents of this project take the\n * default model of cogitator.yml, which the job has to name explicitly.\n */\n export function forQueue(agent: Agent): SerializedAgent {\n if (agent.model) return serializeAgent(agent);\n const model = loadConfig().llm?.defaultModel;\n if (!model) throw new Error('Set llm.defaultModel in cogitator.yml or a model on the agent');\n return serializeAgent(agent.clone({ model }));\n }\n`;\n\nfunction workerEntry(project: ProjectBuilder): string {\n return code`\n import { createServer } from 'node:http';\n import { JobQueue, WorkerPool } from '@cogitator-ai/worker';\n import { cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n import { redis } from './queue.js';\n import { tools } from './tools/index.js';\n ${startupImports(project)}\n\n const env = loadEnv();\n ${startupStatements(project)}\n\n /**\n * Runs the agent jobs producers queue in Redis. Serialized agents name their\n * tools, and this worker provides the implementations of the assistant's.\n */\n const pool = new WorkerPool(\n { redis, cogitator, tools, concurrency: Number(env.WORKER_CONCURRENCY ?? 4) },\n {\n onJobStarted: (jobId, type) => console.log(\\`\\${type} job \\${jobId} started\\`),\n onJobCompleted: (jobId) => console.log(\\`job \\${jobId} completed\\`),\n onJobFailed: (jobId, error) => console.error(\\`job \\${jobId} failed: \\${error.message}\\`),\n onWorkerError: (error) => console.error(\\`worker error: \\${error.message}\\`),\n }\n );\n await pool.start();\n const queue = new JobQueue({ redis });\n\n /** Prometheus metrics of the pool on /metrics, and /health for probes. */\n const metrics = createServer(async (req, res) => {\n if (req.url === '/health') {\n res.writeHead(pool.isPoolRunning() ? 200 : 503, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: pool.isPoolRunning() ? 'ok' : 'stopped' }));\n return;\n }\n if (req.url === '/metrics') {\n res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' });\n res.end(pool.metrics.format(await pool.getMetrics(await queue.getMetrics())));\n return;\n }\n res.writeHead(404).end();\n });\n const metricsPort = Number(env.METRICS_PORT ?? ${METRICS_PORT});\n metrics.listen(metricsPort, () => console.log(\\`Worker running, metrics on http://localhost:\\${metricsPort}/metrics\\`));\n\n onShutdown(async () => {\n await pool.stop(30_000);\n await queue.close();\n await new Promise<void>((resolve) => metrics.close(() => resolve()));\n await cogitator.close();\n }, 40_000);\n `;\n}\n\nconst ENQUEUE_TS = code`\n import { JobQueue, type JobResult } from '@cogitator-ai/worker';\n import { agents } from './cogitator.js';\n import { forQueue, redis } from './queue.js';\n\n const FINISHED = new Set(['completed', 'failed']);\n\n /** Queues a question for the assistant, waits for a worker to answer it and prints the answer. */\n async function main(): Promise<void> {\n const input = process.argv.slice(2).join(' ').trim() || 'What can you do?';\n const queue = new JobQueue({ redis });\n try {\n const job = await queue.addAgentJob(forQueue(agents.assistant), input);\n console.error(\\`Queued job \\${job.id}, waiting for a worker...\\`);\n\n const deadline = Date.now() + 5 * 60_000;\n while (!FINISHED.has(await queue.getJobState(String(job.id)))) {\n if (Date.now() > deadline) throw new Error('No worker answered within 5 minutes: is one running?');\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n\n const done = await queue.getJob(String(job.id));\n if (!done || (await queue.getJobState(String(job.id))) === 'failed') {\n throw new Error(\\`The job failed: \\${done?.failedReason ?? 'unknown reason'}\\`);\n }\n const result: JobResult = done.returnvalue;\n console.log(result.type === 'agent' ? result.output : JSON.stringify(result, null, 2));\n } finally {\n await queue.close();\n }\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst WORKER_TEST_TS = code`\n import { processAgentJob } from '@cogitator-ai/worker';\n import { describe, expect, it } from 'vitest';\n import { agents } from '../src/cogitator.js';\n import { forQueue } from '../src/queue.js';\n import { tools } from '../src/tools/index.js';\n import { mockCogitator } from './helpers.js';\n\n describe('agent jobs', () => {\n it('run the serialized assistant with the worker tools', async () => {\n const { cogitator } = mockCogitator(\n {\n toolCalls: [{ id: 'call-1', name: 'calculator', arguments: { expression: '2 + 2' } }],\n finishReason: 'tool_calls',\n },\n { content: 'It is 4.' }\n );\n try {\n const result = await processAgentJob(\n { type: 'agent', jobId: 'job-1', agentConfig: forQueue(agents.assistant), input: '2 + 2?', threadId: 'thread-1' },\n { cogitator, tools }\n );\n expect(result.output).toBe('It is 4.');\n expect(result.toolCalls.map((call) => call.name)).toEqual(['calculator']);\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\n/** A queue worker: agent jobs in Redis, run by a BullMQ worker pool with metrics. */\nexport const appWorkerFeature: FeatureModule = {\n id: 'app:worker',\n applies: (spec) => spec.app === 'worker',\n apply(project) {\n addRedisService(project);\n project\n .dependency('@cogitator-ai/worker', cogitatorVersion('@cogitator-ai/worker'))\n .dependency('ioredis', VERSIONS.ioredis)\n .devDependency('tsx', VERSIONS.tsx)\n .file('src/queue.ts', QUEUE_TS)\n .file('src/lifecycle.ts', LIFECYCLE_TS)\n .file('src/enqueue.ts', ENQUEUE_TS)\n .file('tests/worker.test.ts', WORKER_TEST_TS)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js')\n .script('enqueue', 'tsx --env-file-if-exists=.env src/enqueue.ts')\n .envVar({\n name: 'WORKER_CONCURRENCY',\n description: 'How many jobs the worker runs at once',\n example: '4',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'METRICS_PORT',\n description: 'Port of the Prometheus metrics and health endpoint',\n example: String(METRICS_PORT),\n required: false,\n secret: false,\n });\n project.deploy.kind = 'worker';\n },\n finalize(project) {\n project.file('src/index.ts', workerEntry(project));\n const pm = project.spec.packageManager;\n project.section(\n 'Worker',\n code`\n \\`src/index.ts\\` is a \\`WorkerPool\\` of \\`@cogitator-ai/worker\\`: it takes agent, workflow and swarm jobs from the BullMQ queue in Redis (\\`REDIS_URL\\`) and runs them with the assistant's tools, with Prometheus metrics on \\`:${METRICS_PORT}/metrics\\`. \\`src/enqueue.ts\\` is a producer: \\`${runScript(pm, 'enqueue', '\"your question\"')}\\` queues a job for the assistant and prints the answer once a worker finished it. Start Redis with \\`docker compose up -d redis\\` and the worker with \\`${runScript(pm, 'dev')}\\`.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { execCommand, runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type CodingAgent, type PackageManager } from '../spec.js';\nimport type { FeatureModule } from './types.js';\n\nconst CLI_BIN = 'node_modules/@cogitator-ai/cli/dist/index.js';\n\n/** The command that starts `cogitator mcp` from the project directory. */\nexport function mcpLaunch(pm: PackageManager): { command: string; args: string[] } {\n switch (pm) {\n case 'npm':\n return { command: 'npx', args: ['--no', 'cogitator', 'mcp'] };\n case 'pnpm':\n return { command: 'pnpm', args: ['exec', 'cogitator', 'mcp'] };\n case 'yarn':\n return { command: 'yarn', args: ['cogitator', 'mcp'] };\n case 'bun':\n return { command: 'bunx', args: ['cogitator', 'mcp'] };\n }\n}\n\n/**\n * Cursor does not say which directory it starts a server in, so its command\n * names the project explicitly through `${workspaceFolder}`.\n */\nfunction cursorLaunch(pm: PackageManager): { command: string; args: string[] } {\n const project = ['--project', '${workspaceFolder}'];\n if (pm === 'yarn') {\n return {\n command: 'yarn',\n args: ['--cwd', '${workspaceFolder}', 'cogitator', 'mcp', ...project],\n };\n }\n return { command: 'node', args: [`\\${workspaceFolder}/${CLI_BIN}`, 'mcp', ...project] };\n}\n\nfunction mcpJson(launch: { command: string; args: string[] }): string {\n return (\n JSON.stringify({ mcpServers: { cogitator: { type: 'stdio', ...launch } } }, null, 2) + '\\n'\n );\n}\n\nfunction tomlString(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction codexConfig(pm: PackageManager): string {\n const { command, args } = mcpLaunch(pm);\n return [\n '# Codex reads this file for trusted projects: the Cogitator docs and project tools over MCP.',\n '[mcp_servers.cogitator]',\n `command = ${tomlString(command)}`,\n `args = [${args.map(tomlString).join(', ')}]`,\n '',\n ].join('\\n');\n}\n\n/** Where each coding agent looks for the MCP config and the skills of a project. */\nconst LOCATIONS: Record<CodingAgent, { mcp: string; skill: string; label: string }> = {\n claude: { mcp: '.mcp.json', skill: '.claude/skills/cogitator/SKILL.md', label: 'Claude Code' },\n cursor: { mcp: '.cursor/mcp.json', skill: '.cursor/skills/cogitator/SKILL.md', label: 'Cursor' },\n codex: { mcp: '.codex/config.toml', skill: '.agents/skills/cogitator/SKILL.md', label: 'Codex' },\n};\n\nfunction skill(project: ProjectBuilder): string {\n const { spec } = project;\n const pm = spec.packageManager;\n const kinds = (kind: 'workflows' | 'swarms') =>\n project.registry.some((entry) => entry.kind === kind);\n const recipes = [\n code`\n ### Add a tool\n\n Write it in \\`src/tools/<name>.ts\\` with \\`tool()\\` from \\`@cogitator-ai/core\\` and a Zod schema for its arguments, add it to the list in \\`src/tools/index.ts\\`, and test it in \\`tests/tools.test.ts\\` by calling \\`execute\\` directly. Mark a tool that changes something outside the process with \\`sideEffects\\`, and one a person has to allow with \\`requiresApproval\\`.\n `,\n code`\n ### Add an agent\n\n Create \\`src/agents/<name>.ts\\` exporting a \\`new Agent({ name, instructions, tools })\\`, then register it in \\`agents\\` of \\`src/cogitator.ts\\`. Leave out \\`model\\` to use \\`llm.defaultModel\\` from \\`cogitator.yml\\`.\n `,\n kinds('workflows') &&\n code`\n ### Change a workflow\n\n Workflows live in \\`src/workflows/\\` and are built with \\`WorkflowBuilder\\`. Register a new one in \\`workflows\\` of \\`src/cogitator.ts\\`.\n `,\n kinds('swarms') &&\n code`\n ### Change a swarm\n\n Swarms are \\`SwarmConfig\\` objects in \\`src/swarms/\\`, registered in \\`swarms\\` of \\`src/cogitator.ts\\`.\n `,\n code`\n ### Grow the project\n\n \\`${execCommand(pm, 'cogitator add')} <feature>\\` adds what create-cogitator-app can generate (rag, mcp, workflows, swarms, evals, otel and more, \\`--memory\\`, \\`--deploy\\`) with the same code a new project would get. Run it with \\`--dry-run\\` first: it merges into files you changed, and refuses with a diff when it cannot.\n `,\n ].filter((recipe): recipe is string => typeof recipe === 'string');\n\n return code`\n ---\n name: cogitator\n description: Build and change this Cogitator agent project (agents, tools, ${kinds('workflows') ? 'workflows, ' : ''}${kinds('swarms') ? 'swarms, ' : ''}memory, tests). Use it whenever a task touches Cogitator code or cogitator.yml.\n ---\n\n # Working on a Cogitator project\n\n Cogitator moves faster than model training data. Before writing Cogitator code, look the API up in the docs of the installed version: the \\`cogitator\\` MCP server has \\`search_docs\\` and \\`read_doc\\`, and the same pages are in \\`node_modules/@cogitator-ai/core/docs/\\` (start at \\`index.md\\`). \\`inspect_project\\` lists the agents, tools${kinds('workflows') ? ', workflows' : ''}${kinds('swarms') ? ', swarms' : ''} the project registers, and \\`check_project\\` runs \\`cogitator doctor\\`.\n\n Read \\`AGENTS.md\\` for how this project is put together. Everything it runs is registered in \\`src/cogitator.ts\\`.\n\n ${recipes.join('\\n\\n')}\n\n ### Before you call it done\n\n 1. \\`${runScript(pm, 'test')}\\`: tests run offline, \\`mockCogitator\\` from \\`tests/helpers.ts\\` scripts the model's replies, including tool calls.\n 2. \\`${runScript(pm, 'typecheck')}\\` and \\`${runScript(pm, 'lint')}\\`.\n ${hasFeature(spec, 'evals') && `3. \\`${runScript(pm, 'eval')}\\` when you changed instructions or tools: it scores the assistant on \\`evals/\\` with the real model.`}\n `;\n}\n\n/** MCP config and a skill for the coding agents the project is set up for (`--agent`). */\nexport const codingAgentsFeature: FeatureModule = {\n id: 'coding-agents',\n applies: (spec) => spec.codingAgents.length > 0,\n apply(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n for (const agent of spec.codingAgents) {\n const location = LOCATIONS[agent];\n if (agent === 'claude') project.file(location.mcp, mcpJson(mcpLaunch(pm)));\n if (agent === 'cursor') project.file(location.mcp, mcpJson(cursorLaunch(pm)));\n if (agent === 'codex') project.file(location.mcp, codexConfig(pm));\n }\n\n const configured = spec.codingAgents.map((agent) => LOCATIONS[agent]);\n project.section(\n 'Coding agents',\n code`\n The \\`cogitator\\` MCP server (\\`cogitator mcp\\`) gives coding agents \\`search_docs\\` and \\`read_doc\\` over the docs of the installed Cogitator, \\`inspect_project\\` for the registry and \\`check_project\\` for \\`cogitator doctor\\`. It is configured for ${configured.map((location) => `${location.label} in \\`${location.mcp}\\``).join(', ')}, next to the \\`cogitator\\` skill${configured.length > 1 ? 's' : ''} in ${configured.map((location) => `\\`${location.skill}\\``).join(', ')}.\n `\n );\n },\n /** The skill names the workflows and swarms, which the app and orchestration modules register. */\n finalize(project) {\n const content = skill(project);\n for (const agent of project.spec.codingAgents) project.file(LOCATIONS[agent].skill, content);\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst DATASET_JSONL = [\n { input: 'What is 17 * 23?', expected: '391' },\n { input: 'What is the square root of 1764?', expected: '42' },\n { input: 'What is 2 to the power of 10?', expected: '1024' },\n { input: 'How many days does a leap year have?', expected: '366' },\n]\n .map((line) => JSON.stringify(line))\n .join('\\n')\n .concat('\\n');\n\nconst SUITE_TS = code`\n import { fileURLToPath } from 'node:url';\n import type { Cogitator } from '@cogitator-ai/core';\n import { contains, cost, Dataset, EvalSuite, latency, threshold } from '@cogitator-ai/evals';\n import { agents, cogitator } from '../src/cogitator.js';\n\n const DATASET = fileURLToPath(new URL('./assistant.jsonl', import.meta.url));\n\n /**\n * Scores the assistant on evals/assistant.jsonl: an answer passes when it\n * contains the expected text, and the suite passes when 80% of them do.\n */\n export async function createAssistantSuite(runtime: Cogitator, options: { concurrency?: number } = {}) {\n return new EvalSuite({\n dataset: await Dataset.fromJsonl(DATASET),\n target: { agent: agents.assistant, cogitator: runtime },\n metrics: [contains()],\n statisticalMetrics: [latency(), cost()],\n assertions: [threshold('contains', 0.8)],\n concurrency: options.concurrency ?? 2,\n timeout: 60_000,\n retries: 1,\n });\n }\n\n export default await createAssistantSuite(cogitator);\n`;\n\nconst SUITE_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { createAssistantSuite } from '../evals/assistant.eval.js';\n import { mockCogitator } from './helpers.js';\n\n describe('assistant eval suite', () => {\n it('passes when the answers contain the expected text', async () => {\n const { cogitator } = mockCogitator(\n { content: '17 * 23 = 391' },\n { content: 'It is 42.' },\n { content: '1024' },\n { content: 'A leap year has 366 days.' }\n );\n try {\n const suite = await createAssistantSuite(cogitator, { concurrency: 1 });\n const result = await suite.run();\n expect(result.aggregated.contains?.mean).toBe(1);\n expect(result.assertions.every((assertion) => assertion.passed)).toBe(true);\n } finally {\n await cogitator.close();\n }\n });\n\n it('fails when the answers are wrong', async () => {\n const { cogitator } = mockCogitator({ content: 'I do not know.' });\n try {\n const suite = await createAssistantSuite(cogitator, { concurrency: 1 });\n const result = await suite.run();\n expect(result.assertions.some((assertion) => !assertion.passed)).toBe(true);\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\n/** A dataset, metrics and a threshold for the assistant, run with `cogitator eval` locally and in CI. */\nexport const evalsFeature: FeatureModule = {\n id: 'feature:evals',\n applies: (spec) => hasFeature(spec, 'evals'),\n apply(project) {\n project\n .dependency('@cogitator-ai/evals', cogitatorVersion('@cogitator-ai/evals'))\n .file('evals/assistant.jsonl', DATASET_JSONL)\n .file('evals/assistant.eval.ts', SUITE_TS)\n .file('tests/evals.test.ts', SUITE_TEST_TS)\n .script('eval', 'cogitator eval --skip-without-key')\n .ignore('eval-report.json');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'Evals',\n code`\n \\`evals/assistant.eval.ts\\` scores the assistant on \\`evals/assistant.jsonl\\` with \\`@cogitator-ai/evals\\`: \\`contains\\` checks each answer against the expected text, \\`threshold\\` fails the suite below 80%, and latency and cost are measured too. \\`${runScript(pm, 'eval')}\\` runs every \\`evals/*.eval.ts\\` with the real model and exits 1 when an assertion fails, so CI can gate on it. Without an API key it skips instead. Add a case when you fix a bug, and \\`tests/evals.test.ts\\` checks the suite itself offline.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst WORKSPACE_TS = code`\n import { mkdirSync } from 'node:fs';\n import { resolve } from 'node:path';\n import { fileDelete, fileExists, fileList, fileRead, fileWrite, restrictFileTools } from '@cogitator-ai/core';\n\n /**\n * File tools confined to \\`root\\`: paths are relative to it, nothing outside it\n * is reachable (symlinks included), and writing or deleting waits for approval.\n */\n export function createWorkspaceTools(root: string) {\n const workspace = resolve(root);\n mkdirSync(workspace, { recursive: true });\n return restrictFileTools([fileRead, fileList, fileExists, fileWrite, fileDelete], [workspace], {\n base: workspace,\n requireApproval: (tool) => tool.sideEffects?.includes('filesystem') ?? false,\n });\n }\n\n /** The directory the assistant works in: ./workspace, or WORKSPACE_DIR. */\n export const WORKSPACE_DIR = process.env.WORKSPACE_DIR ?? 'workspace';\n\n export const workspaceTools = createWorkspaceTools(WORKSPACE_DIR);\n`;\n\nconst FACTS_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { CoreFactsStore } from '@cogitator-ai/memory';\n import { z } from 'zod';\n\n /** Lasting facts about the user (name, time zone, preferences) and the tools that keep them. */\n export function createFacts(path: string) {\n const store = new CoreFactsStore({ path });\n let opened: Promise<void> | undefined;\n /** Opens the database on first use, so importing this module touches no file. */\n const ready = () => (opened ??= store.initialize());\n\n const rememberFact = tool({\n name: 'remember_fact',\n description:\n 'Remember a lasting fact about the user, such as their name, time zone or a preference. Overwrites the fact with the same key.',\n parameters: z.object({\n key: z.string().min(1).max(64).describe('A short key, e.g. \"name\" or \"timezone\"'),\n value: z.string().min(1).max(500).describe('What to remember'),\n }),\n execute: async ({ key, value }) => {\n await ready();\n await store.set(key, value);\n return { remembered: key };\n },\n });\n\n const forgetFact = tool({\n name: 'forget_fact',\n description: 'Forget a fact about the user when they ask you to or it is no longer true.',\n parameters: z.object({ key: z.string().min(1).describe('The key of the fact') }),\n execute: async ({ key }) => {\n await ready();\n await store.delete(key);\n return { forgotten: key };\n },\n });\n\n /** Every fact, as run context, so the assistant knows them from the first message of a run. */\n async function context(): Promise<Record<string, string>> {\n await ready();\n return store.getAll();\n }\n\n async function close(): Promise<void> {\n if (!opened) return;\n await opened;\n await store.close();\n }\n\n return { store, rememberFact, forgetFact, tools: [rememberFact, forgetFact], context, close };\n }\n\n export const facts = createFacts(process.env.FACTS_PATH ?? './data/facts.db');\n export const factTools = facts.tools;\n`;\n\nconst SCHEDULER_TS = code`\n import { HeartbeatScheduler, SimpleTimerStore, getNextCronMs } from '@cogitator-ai/channels';\n import { createSchedulerTools } from '@cogitator-ai/core';\n\n /** Tasks the assistant schedules for later, kept on disk so they survive a restart. */\n export const timerStore = new SimpleTimerStore({\n persistPath: process.env.TIMERS_PATH ?? './data/timers.json',\n resolveCronFiresAt: (cron, timezone) => getNextCronMs(cron, Date.now(), timezone),\n });\n\n /** schedule_task, list_tasks and cancel_task: \"remind me in 20 minutes\", \"every morning at 9\". */\n export const schedulerTools = createSchedulerTools({ store: timerStore, defaultChannel: 'terminal' });\n\n /** Calls \\`onTask\\` with each task that comes due while the process runs. */\n export function startScheduler(onTask: (task: string) => Promise<void>): HeartbeatScheduler {\n const scheduler = new HeartbeatScheduler(timerStore, {\n onFire: (message) => onTask(message.text),\n pollInterval: 10_000,\n onError: (error) => console.error(\\`Scheduled task failed: \\${error.message}\\`),\n });\n scheduler.start();\n return scheduler;\n }\n`;\n\nconst HARNESS_TEST_TS = code`\n import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { Agent } from '@cogitator-ai/core';\n import { afterEach, beforeEach, describe, expect, it } from 'vitest';\n import { createFacts } from '../src/harness/facts.js';\n import { createWorkspaceTools } from '../src/harness/workspace.js';\n import { mockCogitator } from './helpers.js';\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'harness-'));\n });\n\n afterEach(() => {\n rmSync(dir, { recursive: true, force: true });\n });\n\n const context = { agentId: 'test', runId: 'test', signal: new AbortController().signal };\n\n function writeCall(path: string) {\n return {\n toolCalls: [{ id: 'call-1', name: 'file_write', arguments: { path, content: 'hello' } }],\n finishReason: 'tool_calls' as const,\n };\n }\n\n async function runWrite(path: string, approved: boolean) {\n const workspace = join(dir, 'workspace');\n const agent = new Agent({ name: 'writer', instructions: 'Write files.', tools: createWorkspaceTools(workspace) });\n const { cogitator } = mockCogitator(writeCall(path), { content: 'Done.' });\n try {\n const result = await cogitator.run(agent, {\n input: 'Write hello to notes.md',\n onApproval: () => (approved ? { approved: true } : { approved: false, reason: 'not now' }),\n });\n return { result, workspace };\n } finally {\n await cogitator.close();\n }\n }\n\n describe('workspace tools', () => {\n it('writes relative paths into the workspace once approved', async () => {\n const { workspace } = await runWrite('notes.md', true);\n expect(readFileSync(join(workspace, 'notes.md'), 'utf8')).toBe('hello');\n });\n\n it('writes nothing when the write is declined', async () => {\n const { workspace } = await runWrite('notes.md', false);\n expect(existsSync(join(workspace, 'notes.md'))).toBe(false);\n });\n\n it('cannot reach outside the workspace, also through a symlink', async () => {\n const workspace = join(dir, 'workspace');\n const [fileRead] = createWorkspaceTools(workspace);\n symlinkSync(dir, join(workspace, 'escape'));\n\n for (const path of ['../secret.txt', '/etc/passwd', 'escape/secret.txt']) {\n const result = (await fileRead.execute({ path }, context)) as { error?: string };\n expect(result.error, path).toContain('Access denied');\n }\n });\n\n it('asks before writing and deleting, never before reading', () => {\n const tools = createWorkspaceTools(join(dir, 'workspace'));\n const needApproval = tools.filter((tool) => tool.requiresApproval).map((tool) => tool.name);\n expect(needApproval.sort()).toEqual(['file_delete', 'file_write']);\n });\n });\n\n describe('facts', () => {\n it('remembers, recalls and forgets facts across restarts', async () => {\n const path = join(dir, 'facts.db');\n const first = createFacts(path);\n await first.rememberFact.execute({ key: 'name', value: 'Ada' }, context);\n await first.close();\n\n const second = createFacts(path);\n expect(await second.context()).toEqual({ name: 'Ada' });\n await second.forgetFact.execute({ key: 'name' }, context);\n expect(await second.context()).toEqual({});\n await second.close();\n });\n });\n`;\n\n/**\n * The assistant harness: a workspace the agent can read and write with your\n * approval, facts it keeps about you, and tasks it schedules for later.\n */\nexport const harnessFeature: FeatureModule = {\n id: 'feature:harness',\n applies: (spec) => hasFeature(spec, 'harness'),\n apply(project) {\n project\n .dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'))\n .dependency('@cogitator-ai/channels', cogitatorVersion('@cogitator-ai/channels'))\n .dependency('better-sqlite3', VERSIONS.betterSqlite3)\n .allowBuild('better-sqlite3')\n .file('src/harness/workspace.ts', WORKSPACE_TS)\n .file('src/harness/facts.ts', FACTS_TS)\n .file('src/harness/scheduler.ts', SCHEDULER_TS)\n .file('tests/harness.test.ts', HARNESS_TEST_TS)\n .toolSet('workspaceTools', '../harness/workspace.js')\n .toolSet('factTools', '../harness/facts.js')\n .toolSet('schedulerTools', '../harness/scheduler.js')\n .ignore('workspace/', 'data/')\n .envVar({\n name: 'WORKSPACE_DIR',\n description: 'The directory the assistant may read and write',\n example: 'workspace',\n required: false,\n secret: false,\n })\n .instruct(\n 'You have a workspace for files: read them freely, and know that writing or deleting needs the user to approve it.'\n )\n .instruct(\n 'Remember lasting facts about the user with remember_fact, and schedule reminders and recurring work with schedule_task.'\n );\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'Assistant harness',\n code`\n - \\`src/harness/workspace.ts\\`: file tools confined to \\`workspace/\\` (\\`WORKSPACE_DIR\\`) with \\`restrictFileTools\\` from core. Paths are relative to it, symlinks out of it are refused, and \\`file_write\\` and \\`file_delete\\` need approval: the terminal chat asks before they run.\n - \\`src/harness/facts.ts\\`: \\`remember_fact\\` and \\`forget_fact\\` keep lasting facts in \\`data/facts.db\\` (\\`CoreFactsStore\\`), and every run gets them as context.\n - \\`src/harness/scheduler.ts\\`: \\`schedule_task\\`, \\`list_tasks\\` and \\`cancel_task\\`. Tasks are kept in \\`data/timers.json\\`, and while \\`${runScript(pm, 'dev')}\\` runs, a due task is handed to the assistant like a message.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst NOTES_SERVER_TS = code`\n import { mkdir, readFile, writeFile } from 'node:fs/promises';\n import { dirname } from 'node:path';\n import { tool } from '@cogitator-ai/core';\n import { serveMCPTools } from '@cogitator-ai/mcp';\n import { z } from 'zod';\n\n /**\n * A small MCP server: notes in a JSON file, served over stdio. The assistant\n * connects to it in src/mcp/client.ts, and any MCP client (Claude Desktop,\n * Cursor) can use it the same way.\n */\n const NOTES_PATH = process.env.NOTES_PATH ?? 'data/notes.json';\n\n interface Note {\n id: number;\n text: string;\n createdAt: string;\n }\n\n async function readNotes(): Promise<Note[]> {\n try {\n return JSON.parse(await readFile(NOTES_PATH, 'utf8')) as Note[];\n } catch {\n return [];\n }\n }\n\n async function writeNotes(notes: Note[]): Promise<void> {\n await mkdir(dirname(NOTES_PATH), { recursive: true });\n await writeFile(NOTES_PATH, JSON.stringify(notes, null, 2));\n }\n\n const addNote = tool({\n name: 'add_note',\n description: 'Save a short note for later.',\n parameters: z.object({ text: z.string().min(1).max(2_000).describe('The note') }),\n execute: async ({ text }) => {\n const notes = await readNotes();\n const note = { id: (notes.at(-1)?.id ?? 0) + 1, text, createdAt: new Date().toISOString() };\n await writeNotes([...notes, note]);\n return note;\n },\n });\n\n const searchNotes = tool({\n name: 'search_notes',\n description: 'Find saved notes that contain all the given words. Without words, list every note.',\n parameters: z.object({ query: z.string().default('').describe('Words to look for') }),\n execute: async ({ query }) => {\n const words = query.toLowerCase().split(/\\\\s+/).filter(Boolean);\n const notes = await readNotes();\n return notes.filter((note) => words.every((word) => note.text.toLowerCase().includes(word)));\n },\n });\n\n await serveMCPTools([addNote, searchNotes], { name: 'notes', version: '1.0.0', transport: 'stdio' });\n`;\n\nconst MCP_CLIENT_TS = code`\n import { fileURLToPath } from 'node:url';\n import type { Tool } from '@cogitator-ai/core';\n import { connectMCPServer } from '@cogitator-ai/mcp';\n\n /**\n * The command that starts src/mcp/notes-server with the runtime of this\n * process: Bun runs the sources as they are, Node needs tsx for them and\n * runs dist/ after a build.\n */\n function notesServerCommand(): { command: string; args: string[] } {\n const fromSources = import.meta.url.endsWith('.ts');\n const server = fileURLToPath(new URL(\\`./notes-server.\\${fromSources ? 'ts' : 'js'}\\`, import.meta.url));\n const loader = fromSources && !process.versions.bun ? ['--import', 'tsx'] : [];\n return { command: process.execPath, args: [...loader, server] };\n }\n\n /**\n * Starts the notes MCP server and returns its tools as Cogitator tools. Add\n * more servers the same way, for example the official filesystem server:\n * \\`connectMCPServer({ transport: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '.'] })\\`.\n */\n export async function loadNotesTools(env: Record<string, string> = {}): Promise<{ tools: Tool[]; close: () => Promise<void> }> {\n const { tools, cleanup } = await connectMCPServer({ transport: 'stdio', ...notesServerCommand(), env, timeout: 30_000 });\n return { tools, close: cleanup };\n }\n\n /**\n * The MCP tools the assistant gets. A server that does not start leaves the\n * assistant without its tools instead of stopping the project.\n */\n async function connect(): Promise<Tool[]> {\n try {\n return (await loadNotesTools()).tools;\n } catch (error) {\n console.warn(\\`The notes MCP server did not start, continuing without it: \\${error instanceof Error ? error.message : error}\\`);\n return [];\n }\n }\n\n export const mcpTools = await connect();\n`;\n\nconst MCP_SERVE_TS = code`\n import { serveAgents } from '@cogitator-ai/mcp';\n import { agents, cogitator } from '../cogitator.js';\n\n /**\n * Serves every agent of the project as an MCP tool over stdio, so Claude\n * Desktop, Cursor or Claude Code can hand them tasks.\n */\n await serveAgents(cogitator, Object.values(agents));\n`;\n\nconst MCP_TEST_TS = code`\n import { mkdtempSync, rmSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { afterAll, beforeAll, describe, expect, it } from 'vitest';\n import type { Tool } from '@cogitator-ai/core';\n import { loadNotesTools } from '../src/mcp/client.js';\n\n const context = { agentId: 'test', runId: 'test', signal: new AbortController().signal };\n let dir: string;\n let notes: { tools: Tool[]; close: () => Promise<void> };\n\n function named(name: string): Tool {\n const found = notes.tools.find((tool) => tool.name === name);\n if (!found) throw new Error(\\`The notes server has no \\${name} tool\\`);\n return found;\n }\n\n beforeAll(async () => {\n dir = mkdtempSync(join(tmpdir(), 'mcp-'));\n notes = await loadNotesTools({ NOTES_PATH: join(dir, 'notes.json') });\n });\n\n afterAll(async () => {\n await notes.close();\n rmSync(dir, { recursive: true, force: true });\n });\n\n describe('notes MCP server', () => {\n it('offers its tools to Cogitator', () => {\n expect(notes.tools.map((tool) => tool.name).sort()).toEqual(['add_note', 'search_notes']);\n });\n\n it('saves notes and finds them again', async () => {\n await named('add_note').execute({ text: 'Buy oat milk' }, context);\n await named('add_note').execute({ text: 'Call the dentist' }, context);\n\n const found = await named('search_notes').execute({ query: 'milk' }, context);\n expect(found).toEqual([expect.objectContaining({ id: 1, text: 'Buy oat milk' })]);\n });\n });\n`;\n\n/** Tools from MCP servers for the assistant, and the project's agents served over MCP. */\nexport const mcpFeature: FeatureModule = {\n id: 'feature:mcp',\n applies: (spec) => hasFeature(spec, 'mcp'),\n apply(project) {\n project\n .dependency('@cogitator-ai/mcp', cogitatorVersion('@cogitator-ai/mcp'))\n .file('src/mcp/notes-server.ts', NOTES_SERVER_TS)\n .file('src/mcp/client.ts', MCP_CLIENT_TS)\n .file('src/mcp/serve.ts', MCP_SERVE_TS)\n .file('tests/mcp.test.ts', MCP_TEST_TS)\n .toolSet('mcpTools', '../mcp/client.js')\n .script('mcp:serve', 'tsx --env-file-if-exists=.env src/mcp/serve.ts')\n .ignore('data/')\n .instruct('Keep notes for the user with add_note and find them with search_notes.');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'MCP',\n code`\n - \\`src/mcp/notes-server.ts\\` is an MCP server of its own (\\`serveMCPTools\\`): notes in \\`data/notes.json\\` over stdio.\n - \\`src/mcp/client.ts\\` starts it and hands its tools to the assistant (\\`connectMCPServer\\`). Add other servers there; a server that fails to start is skipped with a warning.\n - \\`src/mcp/serve.ts\\` serves every agent of the registry as an MCP tool (\\`serveAgents\\`): \\`${runScript(pm, 'mcp:serve')}\\`. Point Claude Desktop, Cursor or Claude Code at that command to hand your agents tasks.\n `\n );\n project.readmeSection(\n 'MCP',\n code`\n The assistant uses the tools of the notes MCP server in \\`src/mcp/notes-server.ts\\`. To use your agents from Claude Desktop, Cursor or Claude Code, add this server to their MCP settings:\n\n \\`\\`\\`json\n {\n \"mcpServers\": {\n \"${project.spec.name}\": {\n \"command\": \"${pm === 'npm' ? 'npm' : pm}\",\n \"args\": [${pm === 'npm' ? '\"run\", \"--silent\", \"mcp:serve\"' : '\"--silent\", \"mcp:serve\"'}],\n \"cwd\": \"/absolute/path/to/${project.spec.name}\"\n }\n }\n }\n \\`\\`\\`\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature } from '../spec.js';\nimport { IMAGES, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nfunction observabilityTs(project: ProjectBuilder): string {\n const otel = hasFeature(project.spec, 'otel');\n const langfuse = hasFeature(project.spec, 'langfuse');\n const imports = [\n ...(langfuse ? ['createLangfuseExporter'] : []),\n ...(otel ? ['createOTLPExporter'] : []),\n 'type RunObserver',\n ];\n return code`\n import { ${imports.join(', ')} } from '@cogitator-ai/core';\n\n ${\n otel &&\n code`\n /** \\`key=value,key=value\\`, the format of OTEL_EXPORTER_OTLP_HEADERS. */\n function parseHeaders(value: string | undefined): Record<string, string> {\n const headers: Record<string, string> = {};\n for (const pair of value?.split(',') ?? []) {\n const at = pair.indexOf('=');\n if (at > 0) headers[decodeURIComponent(pair.slice(0, at).trim())] = decodeURIComponent(pair.slice(at + 1).trim());\n }\n return headers;\n }\n\n /**\n * Spans of every run to an OpenTelemetry collector (Jaeger, Tempo, Honeycomb,\n * Datadog) at OTEL_EXPORTER_OTLP_ENDPOINT, read the standard OTel way.\n */\n function otlp(): RunObserver | undefined {\n const base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.replace(/\\\\/+$/, '');\n const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? (base && \\`\\${base}/v1/traces\\`);\n if (!endpoint) return undefined;\n const exporter = createOTLPExporter({\n endpoint,\n serviceName: process.env.OTEL_SERVICE_NAME ?? ${tsString(project.spec.name)},\n headers: parseHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS),\n enabled: true,\n });\n exporter.start();\n return exporter.observer();\n }\n `\n }\n\n ${\n langfuse &&\n code`\n /** Traces, inputs, outputs and costs of every run in Langfuse, when its keys are set. */\n async function langfuse(): Promise<RunObserver | undefined> {\n const publicKey = process.env.LANGFUSE_PUBLIC_KEY;\n const secretKey = process.env.LANGFUSE_SECRET_KEY;\n if (!publicKey || !secretKey) return undefined;\n const exporter = createLangfuseExporter({\n publicKey,\n secretKey,\n baseUrl: process.env.LANGFUSE_BASE_URL,\n enabled: true,\n });\n await exporter.init();\n return exporter.observer();\n }\n `\n }\n\n /**\n * What watches every run of the project, each switched on by its environment\n * variables. src/cogitator.ts hands them to the runtime, and closing the\n * runtime sends what they buffered.\n */\n export const observers: RunObserver[] = [${[otel && 'otlp()', langfuse && 'await langfuse()'].filter(Boolean).join(', ')}].filter(\n (observer): observer is RunObserver => observer !== undefined\n );\n `;\n}\n\n/** Traces of every run, to an OpenTelemetry collector and to Langfuse. */\nexport const observabilityFeature: FeatureModule = {\n id: 'feature:observability',\n applies: (spec) => hasFeature(spec, 'otel') || hasFeature(spec, 'langfuse'),\n apply(project) {\n const { spec } = project;\n project.file('src/observability.ts', observabilityTs(project));\n\n if (hasFeature(spec, 'otel')) {\n project\n .service({\n name: 'jaeger',\n image: IMAGES.jaeger,\n ports: ['16686:16686', '4318:4318'],\n })\n .envVar({\n name: 'OTEL_EXPORTER_OTLP_ENDPOINT',\n description:\n 'OTLP endpoint for traces; Jaeger from docker compose listens here, its UI on :16686',\n example: 'http://localhost:4318',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'OTEL_EXPORTER_OTLP_HEADERS',\n description:\n 'Headers for the collector, as key=value,key=value (API keys of hosted collectors)',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'OTEL_SERVICE_NAME',\n description: 'The service name traces carry',\n example: spec.name,\n required: false,\n secret: false,\n });\n }\n if (hasFeature(spec, 'langfuse')) {\n project\n .dependency('langfuse', VERSIONS.langfuse)\n .envVar({\n name: 'LANGFUSE_PUBLIC_KEY',\n description: 'Langfuse public key',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'LANGFUSE_SECRET_KEY',\n description: 'Langfuse secret key',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'LANGFUSE_BASE_URL',\n description: 'Langfuse server, cloud.langfuse.com unless you host it',\n example: 'https://cloud.langfuse.com',\n required: false,\n secret: false,\n });\n }\n\n const where = [\n hasFeature(spec, 'otel') &&\n 'to the OTLP collector at `OTEL_EXPORTER_OTLP_ENDPOINT` (the Jaeger of `docker compose up -d jaeger` shows them at http://localhost:16686)',\n hasFeature(spec, 'langfuse') &&\n 'to Langfuse when `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set',\n ].filter(Boolean);\n project.section(\n 'Observability',\n code`\n \\`src/observability.ts\\` builds the run observers \\`src/cogitator.ts\\` hands to the runtime (\\`CogitatorConfig.observers\\`), so every run, from a script, a route, a workflow or a swarm, sends its spans ${where.join(' and ')}. Each is off until its variables are set, and \\`cogitator.close()\\` flushes them.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature, primaryTarget } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nconst RESEARCHER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n import { currentTime } from '../tools/current-time.js';\n import { fetchUrl } from '../tools/fetch-url.js';\n\n export const researcher = new Agent({\n name: 'researcher',\n description: 'Collects facts and sources on a topic',\n instructions: [\n 'You research a topic and report the facts that matter, as short bullet points.',\n 'Read sources with fetch_url when they help, and name each source you used.',\n 'Mark anything you are not sure about.',\n ].join('\\\\n'),\n tools: [fetchUrl, currentTime],\n temperature: 0.3,\n });\n`;\n\nconst WRITER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n\n export const writer = new Agent({\n name: 'writer',\n description: 'Turns notes into clear, well-structured prose',\n instructions: [\n 'You write clear, well-structured text from the notes you are given.',\n 'Use a title, a short introduction and sections with headings. Do not invent facts.',\n ].join('\\\\n'),\n temperature: 0.7,\n });\n`;\n\nconst REVIEWER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n\n export const reviewer = new Agent({\n name: 'reviewer',\n description: 'Leads the team: delegates research and writing, then checks the result',\n instructions: [\n 'You lead a small team: a researcher and a writer.',\n 'Delegate the research first, then the writing, and check the draft for accuracy and clarity before you answer with the final text.',\n ].join('\\\\n'),\n temperature: 0.2,\n });\n`;\n\n/** The researcher and writer agents the workflow and the swarm share, added once. */\nfunction addTeamAgents(project: ProjectBuilder): void {\n if (project.files.has('src/agents/researcher.ts')) return;\n project\n .file('src/agents/researcher.ts', RESEARCHER_TS)\n .file('src/agents/writer.ts', WRITER_TS)\n .register({\n kind: 'agents',\n name: 'researcher',\n from: './agents/researcher.js',\n binding: 'researcher',\n })\n .register({ kind: 'agents', name: 'writer', from: './agents/writer.js', binding: 'writer' });\n}\n\nconst REPORT_WORKFLOW_TS = code`\n import { WorkflowBuilder, agentNode } from '@cogitator-ai/workflows';\n import { researcher } from '../agents/researcher.js';\n import { writer } from '../agents/writer.js';\n\n export type ReportState = {\n topic: string;\n notes?: string;\n report?: string;\n };\n\n const research = agentNode<ReportState>(researcher, {\n inputMapper: (state) => \\`Research this topic and list the key facts: \\${state.topic}\\`,\n stateMapper: (result) => ({ notes: result.output }),\n });\n\n const write = agentNode<ReportState>(writer, {\n inputMapper: (state) => \\`Write a short report on \"\\${state.topic}\" from these notes:\\\\n\\\\n\\${state.notes ?? ''}\\`,\n stateMapper: (result) => ({ report: result.output }),\n });\n\n /** Research a topic, then write a report from the notes: two agents in a DAG. */\n export const reportWorkflow = new WorkflowBuilder<ReportState>('report')\n .initialState({ topic: '' })\n .addNode('research', research)\n .addNode('write', write, { after: ['research'] })\n .entryPoint('research')\n .build();\n`;\n\nconst REPORT_TEST_TS = code`\n import { WorkflowExecutor } from '@cogitator-ai/workflows';\n import { describe, expect, it } from 'vitest';\n import { workflows } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n describe('report workflow', () => {\n it('researches first, then writes the report from the notes', async () => {\n const { cogitator, backend } = mockCogitator(\n { content: '- Fact one\\\\n- Fact two' },\n { content: '# Report\\\\n\\\\nFact one and fact two.' }\n );\n try {\n const result = await new WorkflowExecutor(cogitator).execute(workflows.report, { topic: 'testing' });\n\n expect(result.error).toBeUndefined();\n expect(result.state.notes).toBe('- Fact one\\\\n- Fact two');\n expect(result.state.report).toBe('# Report\\\\n\\\\nFact one and fact two.');\n expect(JSON.stringify(backend.getLastCall()?.messages)).toContain('Fact two');\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\nfunction workflowEntry(project: ProjectBuilder): string {\n return code`\n import { createInterface } from 'node:readline/promises';\n import { styleText } from 'node:util';\n import { WorkflowExecutor } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n async function topicFromUser(): Promise<string> {\n const fromArgs = process.argv.slice(2).join(' ').trim();\n if (fromArgs) return fromArgs;\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question('Topic for the report: ')).trim();\n } finally {\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const topic = await topicFromUser();\n if (!topic) throw new Error('Give the report a topic');\n\n const result = await new WorkflowExecutor(cogitator).execute(\n workflows.report,\n { topic },\n {\n onNodeStart: (node) => console.error(styleText('dim', \\`> \\${node}\\`)),\n onNodeComplete: (node, _output, duration) =>\n console.error(styleText('dim', \\` \\${node} done in \\${(duration / 1000).toFixed(1)}s\\`)),\n }\n );\n if (result.error) throw result.error;\n console.log(result.state.report);\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(() => cogitator.close());\n `;\n}\n\nexport const workflowsFeature: FeatureModule = {\n id: 'feature:workflows',\n applies: (spec) => hasFeature(spec, 'workflows'),\n apply(project) {\n addTeamAgents(project);\n project\n .dependency('@cogitator-ai/workflows', cogitatorVersion('@cogitator-ai/workflows'))\n .file('src/workflows/report.ts', REPORT_WORKFLOW_TS)\n .file('tests/report.test.ts', REPORT_TEST_TS)\n .register({\n kind: 'workflows',\n name: 'report',\n from: './workflows/report.js',\n binding: 'reportWorkflow',\n });\n },\n finalize(project) {\n const { spec } = project;\n if (\n spec.app === 'script' &&\n primaryTarget(spec) === 'workflow' &&\n !hasFeature(spec, 'durable')\n ) {\n project.file('src/index.ts', workflowEntry(project));\n }\n project.section(\n 'Workflows',\n code`\n \\`src/workflows/report.ts\\` is a DAG built with \\`WorkflowBuilder\\`: \\`research\\` runs the researcher, \\`write\\` runs the writer on its notes. Nodes are \\`agentNode\\`s (an agent) or \\`functionNode\\`s (your code), and \\`after\\` sets the order. Workflows are registered in \\`src/cogitator.ts\\`; \\`tests/report.test.ts\\` shows how to run one against a mocked model.\n `\n );\n },\n};\n\nconst PUBLISH_WORKFLOW_TS = code`\n import { mkdir, rm, writeFile, appendFile } from 'node:fs/promises';\n import { join } from 'node:path';\n import { WorkflowBuilder, agentNode, approvalNode, functionNode, humanWorkflowNode } from '@cogitator-ai/workflows';\n import { writer } from '../agents/writer.js';\n\n export type PublishState = {\n topic: string;\n draft?: string;\n approved?: boolean;\n path?: string;\n outcome?: 'published' | 'discarded';\n };\n\n /** Where published posts go; tests point it at a temporary directory. */\n export function publishDirectory(): string {\n return process.env.PUBLISH_DIR ?? 'out';\n }\n\n function slug(topic: string): string {\n return topic.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'post';\n }\n\n const draft = agentNode<PublishState>(writer, {\n inputMapper: (state) => \\`Write a short blog post about: \\${state.topic}\\`,\n stateMapper: (result) => ({ draft: result.output }),\n });\n\n /** A person approves the draft. The request survives restarts: it lives in the approval store. */\n const review = humanWorkflowNode(\n approvalNode<PublishState>('review', {\n title: 'Publish this post?',\n description: (state) => (state.draft ?? '').slice(0, 1_000),\n timeout: 24 * 60 * 60 * 1000,\n timeoutAction: 'reject',\n }),\n { stateMapper: (result) => ({ approved: result.approved }) }\n );\n\n /** Writes the post; its compensation deletes it again when a later step fails. */\n const publish = functionNode<PublishState, string>(\n 'publish',\n async (state) => {\n await mkdir(publishDirectory(), { recursive: true });\n const path = join(publishDirectory(), \\`\\${slug(state.topic)}.md\\`);\n await writeFile(path, state.draft ?? '');\n return path;\n },\n { stateMapper: (path) => ({ path }) }\n );\n\n /** Records the post in the changelog. Set FAIL_ANNOUNCE=1 to watch the saga roll back the publish. */\n const announce = functionNode<PublishState, void>('announce', async (state) => {\n if (process.env.FAIL_ANNOUNCE === '1') throw new Error('The announcement failed');\n await appendFile(join(publishDirectory(), 'CHANGELOG.md'), \\`- \\${new Date().toISOString()} \\${state.topic}\\\\n\\`);\n });\n\n const discard = functionNode<PublishState, 'discarded'>('discard', async () => 'discarded', {\n stateMapper: (outcome) => ({ outcome }),\n });\n\n /**\n * Draft, approve, publish, announce: a saga. The approval waits for a person\n * and survives restarts, and a failed announcement unpublishes the post.\n */\n export const publishWorkflow = new WorkflowBuilder<PublishState>('publish')\n .initialState({ topic: '' })\n .addNode('draft', draft)\n .addNode('review', review, { after: ['draft'] })\n .addConditional('decide', (state) => (state.approved ? 'publish' : 'discard'), { after: ['review'] })\n .addNode('publish', publish, {\n after: ['decide'],\n config: {\n compensation: {\n compensate: async (state) => {\n if (state.path) await rm(state.path, { force: true });\n },\n },\n },\n })\n .addNode('announce', announce, { after: ['publish'] })\n .addNode('discard', discard, { after: ['decide'] })\n .entryPoint('draft')\n .build();\n`;\n\nconst DURABLE_RUNTIME_TS = code`\n import type { Cogitator } from '@cogitator-ai/core';\n import { FileApprovalStore, FileCheckpointStore, createFileRunStore, createWorkflowManager } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n\n /**\n * The workflow manager with runs, checkpoints and approvals on disk under\n * \\`directory\\`: another process (\\`approve\\`) can answer an approval, and\n * \\`recoverRuns\\` continues the runs a crash interrupted.\n */\n export function createDurableRuntime(runtime: Cogitator, directory: string) {\n const approvalStore = new FileApprovalStore({ directory: \\`\\${directory}/approvals\\`, pollInterval: 500 });\n const manager = createWorkflowManager({\n cogitator: runtime,\n runStore: createFileRunStore({ directory: \\`\\${directory}/runs\\` }),\n checkpointStore: new FileCheckpointStore(\\`\\${directory}/checkpoints\\`),\n });\n manager.registerWorkflow(workflows.publish);\n return { manager, approvalStore };\n }\n\n export const { manager, approvalStore } = createDurableRuntime(cogitator, '.cogitator/workflows');\n`;\n\nfunction durableEntry(project: ProjectBuilder): string {\n return code`\n import { styleText } from 'node:util';\n import type { WorkflowRun } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n import { approvalStore, manager } from './durable.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n const FINISHED = new Set<WorkflowRun['status']>(['completed', 'failed', 'cancelled']);\n\n /** Resolves when every run in \\`runIds\\` has finished, printing each change of status. */\n function untilFinished(runIds: Set<string>): Promise<void> {\n return new Promise((resolve) => {\n if (runIds.size === 0) return resolve();\n const stop = manager.onRunStateChange((run) => {\n if (!runIds.has(run.id)) return;\n console.error(styleText('dim', \\` run \\${run.id}: \\${run.status}\\`));\n if (!FINISHED.has(run.status)) return;\n runIds.delete(run.id);\n if (runIds.size === 0) {\n stop();\n resolve();\n }\n });\n });\n }\n\n const options = {\n approvalStore,\n onApprovalRequired: () =>\n console.error(styleText('yellow', 'Waiting for approval: answer it with the approve script in another terminal')),\n onCompensationStart: (node: string) => console.error(styleText('yellow', \\`Rolling back \\${node}\\`)),\n };\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n manager.start();\n\n const recovered = await manager.recoverRuns(options);\n if (recovered.resumed.length > 0) {\n console.error(\\`Continuing \\${recovered.resumed.length} run(s) a previous process left unfinished\\`);\n }\n const waiting = untilFinished(new Set(recovered.resumed));\n\n const topic = process.argv.slice(2).join(' ').trim();\n if (topic) {\n const result = await manager.execute(workflows.publish, { topic }, options);\n if (result.error) throw result.error;\n console.log(result.state.outcome === 'discarded' ? 'The post was not approved.' : \\`Published \\${result.state.path}\\`);\n } else if (recovered.resumed.length === 0) {\n console.log('Nothing to do. Start a run with a topic: the start script followed by the topic.');\n }\n\n await waiting;\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(async () => {\n manager.dispose();\n await cogitator.close();\n });\n`;\n}\n\nconst APPROVE_TS = code`\n import { createInterface } from 'node:readline/promises';\n import { approvalStore } from './durable.js';\n\n /** Answers the approvals the publish workflow is waiting for, from any terminal. */\n async function main(): Promise<void> {\n const pending = await approvalStore.getPendingRequests();\n if (pending.length === 0) {\n console.log('No approvals are waiting.');\n return;\n }\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n for (const request of pending) {\n console.log(\\`\\\\n\\${request.title}\\\\n\\\\n\\${request.description ?? ''}\\\\n\\`);\n const answer = (await rl.question('Approve? [y/N] ')).trim();\n await approvalStore.submitResponse({\n requestId: request.id,\n decision: /^y(es)?$/i.test(answer),\n respondedBy: process.env.USER ?? 'terminal',\n respondedAt: Date.now(),\n });\n }\n } finally {\n rl.close();\n }\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst START_PUBLISH_FIXTURE_TS = code`\n import { workflows } from '../../src/cogitator.js';\n import { createDurableRuntime } from '../../src/durable.js';\n import { mockCogitator } from '../helpers.js';\n\n /** Starts a publish run on a mocked model and says WAITING once it asks for approval. The test kills it there. */\n const [stateDir = '.cogitator/workflows'] = process.argv.slice(2);\n const { cogitator } = mockCogitator({ content: '# Hello\\\\n\\\\nA post.' });\n const { manager, approvalStore } = createDurableRuntime(cogitator, stateDir);\n await manager.execute(\n workflows.publish,\n { topic: 'Hello World' },\n { approvalStore, onApprovalRequired: () => console.log('WAITING') }\n );\n`;\n\nconst PUBLISH_TEST_TS = code`\n import { spawn } from 'node:child_process';\n import { once } from 'node:events';\n import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { InMemoryApprovalStore, WorkflowExecutor } from '@cogitator-ai/workflows';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { workflows } from '../src/cogitator.js';\n import { createDurableRuntime } from '../src/durable.js';\n import { mockCogitator } from './helpers.js';\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'publish-'));\n vi.stubEnv('PUBLISH_DIR', dir);\n });\n\n afterEach(() => {\n vi.unstubAllEnvs();\n rmSync(dir, { recursive: true, force: true });\n });\n\n /** Runs the workflow and answers its approval request with \\`decision\\` as soon as it is asked. */\n async function runApproved(decision: boolean) {\n const { cogitator } = mockCogitator({ content: '# Hello\\\\n\\\\nA post.' });\n const approvalStore = new InMemoryApprovalStore();\n try {\n return await new WorkflowExecutor(cogitator).execute(\n workflows.publish,\n { topic: 'Hello World' },\n {\n approvalStore,\n onApprovalRequired: (request) => {\n void approvalStore.submitResponse({\n requestId: request.id,\n decision,\n respondedBy: 'test',\n respondedAt: Date.now(),\n });\n },\n }\n );\n } finally {\n await cogitator.close();\n }\n }\n\n describe('publish workflow', () => {\n it('publishes and announces an approved post', async () => {\n const result = await runApproved(true);\n expect(result.error).toBeUndefined();\n expect(readFileSync(join(dir, 'hello-world.md'), 'utf8')).toContain('A post.');\n expect(readFileSync(join(dir, 'CHANGELOG.md'), 'utf8')).toContain('Hello World');\n });\n\n it('discards a rejected post', async () => {\n const result = await runApproved(false);\n expect(result.state.outcome).toBe('discarded');\n expect(existsSync(join(dir, 'hello-world.md'))).toBe(false);\n });\n\n it('unpublishes the post when the announcement fails', async () => {\n vi.stubEnv('FAIL_ANNOUNCE', '1');\n const result = await runApproved(true);\n expect(result.error?.message).toContain('announcement failed');\n expect(existsSync(join(dir, 'hello-world.md'))).toBe(false);\n });\n\n it('finishes a run waiting for approval after the process that started it was killed', async () => {\n const stateDir = join(dir, 'state');\n const child = spawn(process.execPath, ['--import', 'tsx', 'tests/fixtures/start-publish.ts', stateDir], {\n env: { ...process.env, PUBLISH_DIR: dir },\n stdio: ['ignore', 'pipe', 'inherit'],\n });\n await new Promise<void>((resolve, reject) => {\n child.stdout.on('data', (chunk: Buffer) => {\n if (chunk.toString().includes('WAITING')) resolve();\n });\n child.once('exit', (code) => reject(new Error(\\`The run exited with \\${code} before asking for approval\\`)));\n });\n child.kill('SIGKILL');\n await once(child, 'exit');\n\n const { cogitator, backend } = mockCogitator({ content: 'not needed: the draft is in the checkpoint' });\n const { manager, approvalStore } = createDurableRuntime(cogitator, stateDir);\n try {\n const recovered = await manager.recoverRuns({ approvalStore });\n expect(recovered.resumed).toHaveLength(1);\n\n const [request] = await approvalStore.getPendingRequests();\n await approvalStore.submitResponse({\n requestId: request.id,\n decision: true,\n respondedBy: 'test',\n respondedAt: Date.now(),\n });\n\n await vi.waitFor(\n async () => expect((await manager.getStatus(recovered.resumed[0]))?.status).toBe('completed'),\n { timeout: 15_000, interval: 100 }\n );\n expect(readFileSync(join(dir, 'hello-world.md'), 'utf8')).toContain('A post.');\n expect(backend.getCallCount()).toBe(0);\n } finally {\n manager.dispose();\n await cogitator.close();\n }\n }, 30_000);\n });\n`;\n\nexport const durableFeature: FeatureModule = {\n id: 'feature:durable',\n applies: (spec) => hasFeature(spec, 'durable'),\n apply(project) {\n project\n .file('src/workflows/publish.ts', PUBLISH_WORKFLOW_TS)\n .file('src/durable.ts', DURABLE_RUNTIME_TS)\n .file('src/approve.ts', APPROVE_TS)\n .file('tests/publish.test.ts', PUBLISH_TEST_TS)\n .file('tests/fixtures/start-publish.ts', START_PUBLISH_FIXTURE_TS)\n .register({\n kind: 'workflows',\n name: 'publish',\n from: './workflows/publish.js',\n binding: 'publishWorkflow',\n })\n .ignore('out/');\n if (project.spec.app === 'script') {\n project.script('approve', 'tsx --env-file-if-exists=.env src/approve.ts');\n }\n },\n finalize(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n if (spec.app === 'script' && primaryTarget(spec) === 'workflow') {\n project.file('src/index.ts', durableEntry(project));\n }\n project.section(\n 'Durable workflow',\n code`\n \\`src/workflows/publish.ts\\` is a saga: \\`draft\\` writes a post, \\`review\\` waits for a person to approve it, \\`publish\\` writes it to \\`out/\\` and \\`announce\\` adds it to the changelog. If \\`announce\\` fails, the compensation of \\`publish\\` deletes the post again (try \\`FAIL_ANNOUNCE=1\\`). \\`src/durable.ts\\` keeps runs, checkpoints and approvals under \\`.cogitator/workflows/\\`, so a run waiting for approval survives a restart: \\`manager.recoverRuns()\\` picks it up. Start a run with \\`${runScript(pm, 'dev', '\"your topic\"')}\\` and answer it from another terminal with \\`${runScript(pm, 'approve')}\\`.\n `\n );\n },\n};\n\nconst TEAM_SWARM_TS = code`\n import type { SwarmConfig } from '@cogitator-ai/swarms';\n import { researcher } from '../agents/researcher.js';\n import { reviewer } from '../agents/reviewer.js';\n import { writer } from '../agents/writer.js';\n\n /** A supervisor that delegates to a researcher and a writer and checks their work. */\n export const team: SwarmConfig = {\n name: 'team',\n strategy: 'hierarchical',\n supervisor: reviewer,\n workers: [researcher, writer],\n hierarchical: { visibility: 'full', workerCommunication: true },\n resources: { maxConcurrency: 2, timeout: 300_000 },\n };\n`;\n\nconst SWARM_TEST_TS = code`\n import { Swarm } from '@cogitator-ai/swarms';\n import { describe, expect, it } from 'vitest';\n import { swarms } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n describe('team swarm', () => {\n it('answers through its supervisor', async () => {\n const { cogitator } = mockCogitator({ content: 'The final article.' });\n const team = new Swarm(cogitator, swarms.team);\n try {\n const result = await team.run({ input: 'Write about testing.' });\n expect(result.output).toContain('The final article.');\n } finally {\n await team.close();\n await cogitator.close();\n }\n });\n });\n`;\n\nfunction swarmEntry(project: ProjectBuilder): string {\n return code`\n import { createInterface } from 'node:readline/promises';\n import { styleText } from 'node:util';\n import { Swarm } from '@cogitator-ai/swarms';\n import { cogitator, swarms } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n async function taskFromUser(): Promise<string> {\n const fromArgs = process.argv.slice(2).join(' ').trim();\n if (fromArgs) return fromArgs;\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question('Task for the team: ')).trim();\n } finally {\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const input = await taskFromUser();\n if (!input) throw new Error('Give the team a task');\n\n const team = new Swarm(cogitator, swarms.team);\n try {\n const result = await team.run({\n input,\n onAgentStart: (name) => console.error(styleText('dim', \\`> \\${name}\\`)),\n onAgentComplete: (name, run) =>\n console.error(styleText('dim', \\` \\${name} done, \\${run.usage.totalTokens} tokens\\`)),\n });\n console.log(result.output);\n } finally {\n await team.close();\n }\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(() => cogitator.close());\n `;\n}\n\nexport const swarmsFeature: FeatureModule = {\n id: 'feature:swarms',\n applies: (spec) => hasFeature(spec, 'swarms'),\n apply(project) {\n addTeamAgents(project);\n project\n .dependency('@cogitator-ai/swarms', cogitatorVersion('@cogitator-ai/swarms'))\n .file('src/agents/reviewer.ts', REVIEWER_TS)\n .file('src/swarms/team.ts', TEAM_SWARM_TS)\n .file('tests/team.test.ts', SWARM_TEST_TS)\n .register({\n kind: 'agents',\n name: 'reviewer',\n from: './agents/reviewer.js',\n binding: 'reviewer',\n })\n .register({ kind: 'swarms', name: 'team', from: './swarms/team.js', binding: 'team' });\n },\n finalize(project) {\n const { spec } = project;\n if (spec.app === 'script' && primaryTarget(spec) === 'swarm') {\n project.file('src/index.ts', swarmEntry(project));\n }\n project.section(\n 'Swarm',\n code`\n \\`src/swarms/team.ts\\` configures a hierarchical swarm: the \\`reviewer\\` supervises the \\`researcher\\` and the \\`writer\\` and delegates to them with tools. \\`new Swarm(cogitator, swarms.team)\\` runs it; other strategies (\\`round-robin\\`, \\`consensus\\`, \\`debate\\`, \\`auction\\`, \\`pipeline\\`, \\`negotiation\\`) take the same agents.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { providerInfo } from '../providers.js';\nimport { bareModel, hasFeature } from '../spec.js';\nimport { IMAGES } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\n/**\n * Ollama in compose starts with an empty volume, so a one-shot `ollama-pull`\n * service downloads the models the project uses once the server is healthy.\n * Later starts find them in the volume and finish at once.\n */\nexport const providerFeature: FeatureModule = {\n id: 'provider',\n applies: () => true,\n apply(project) {\n const { spec } = project;\n const info = providerInfo(spec.provider);\n\n if (spec.provider === 'ollama') {\n const models = [bareModel(spec)];\n if (hasFeature(spec, 'rag') && info.embeddingModel) models.push(info.embeddingModel);\n\n project.service(\n {\n name: 'ollama',\n image: IMAGES.ollama,\n ports: ['11434:11434'],\n volumes: ['ollama_data:/root/.ollama'],\n healthcheck: {\n test: ['CMD', 'ollama', 'list'],\n interval: '5s',\n timeout: '5s',\n retries: 20,\n },\n },\n 'ollama_data'\n );\n project.service({\n name: 'ollama-pull',\n image: IMAGES.ollama,\n dependsOn: { ollama: 'service_healthy' },\n environment: { OLLAMA_HOST: 'http://ollama:11434' },\n entrypoint: ['/bin/sh', '-c', models.map((model) => `ollama pull ${model}`).join(' && ')],\n restart: 'no',\n });\n }\n\n project.section(\n 'Model',\n code`\n The default model is set in \\`cogitator.yml\\` (\\`llm.defaultModel\\`, as \\`provider/model\\`) and agents without a \\`model\\` of their own use it. ${\n info.envKey\n ? `The ${info.label} key is read from \\`${info.envKey}\\` in \\`.env\\`.`\n : 'Ollama runs locally: `OLLAMA_BASE_URL` points at it, `http://localhost:11434` by default.'\n }\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { providerInfo } from '../providers.js';\nimport { hasFeature, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion, IMAGES, VERSIONS } from '../versions.js';\nimport { addPostgresService, DEFAULT_DATABASE_URL } from './memory.js';\nimport type { FeatureModule } from './types.js';\n\nconst DEFAULT_QDRANT_URL = 'http://localhost:6333';\n\nconst HANDBOOK_MD = code`\n # Team handbook\n\n This file is a sample knowledge base. Replace it with your own Markdown: everything under \\`docs/\\` is indexed, and the assistant answers from it with \\`rag_search\\`.\n\n ## Deploys\n\n We deploy on Tuesdays and Thursdays between 10:00 and 15:00 Berlin time. No deploys on Fridays or before a public holiday. Every deploy needs a green CI run and one approving review.\n\n ## On-call\n\n On-call rotates weekly on Monday at 09:00. The person on call answers pages within 15 minutes and writes an incident note for every page within one working day.\n\n ## Expenses\n\n Hardware up to 500 EUR needs no approval. Anything above that needs a manager's approval in the expenses tool before you buy it.\n`;\n\nfunction embeddingService(spec: ProjectSpec): { importName: string; expression: string } {\n switch (spec.provider) {\n case 'openai':\n return {\n importName: 'OpenAIEmbeddingService',\n expression: \"new OpenAIEmbeddingService({ apiKey: process.env.OPENAI_API_KEY ?? '' })\",\n };\n case 'google':\n return {\n importName: 'GoogleEmbeddingService',\n expression:\n \"new GoogleEmbeddingService({ apiKey: process.env.GOOGLE_API_KEY ?? '', dimensions: 768 })\",\n };\n case 'ollama':\n return {\n importName: 'OllamaEmbeddingService',\n expression: `new OllamaEmbeddingService({ baseUrl: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434', model: '${providerInfo('ollama').embeddingModel}' })`,\n };\n case 'anthropic':\n throw new Error(\n 'RAG needs an embedding provider, which compatibilityIssues rules out for Anthropic'\n );\n }\n}\n\nfunction storeCode(spec: ProjectSpec): { imports: string[]; body: string } {\n switch (spec.vectorStore) {\n case 'memory':\n return {\n imports: ['InMemoryEmbeddingAdapter'],\n body: code`\n /** Vectors in the process: the docs are indexed again on every start. */\n export function createStore(): EmbeddingAdapter {\n return new InMemoryEmbeddingAdapter();\n }\n `,\n };\n case 'postgres':\n return {\n imports: ['PostgresAdapter'],\n body: code`\n /** Vectors in Postgres with pgvector, kept across restarts. */\n export function createStore(embeddings: EmbeddingService): EmbeddingAdapter {\n return lazilyConnected(\n new PostgresAdapter({\n provider: 'postgres',\n connectionString: process.env.DATABASE_URL ?? '${DEFAULT_DATABASE_URL}',\n dimensions: embeddings.dimensions,\n })\n );\n }\n `,\n };\n case 'qdrant':\n return {\n imports: ['QdrantAdapter'],\n body: code`\n /** Vectors in Qdrant, kept across restarts. */\n export function createStore(embeddings: EmbeddingService): EmbeddingAdapter {\n return lazilyConnected(\n new QdrantAdapter({\n provider: 'qdrant',\n url: process.env.QDRANT_URL ?? '${DEFAULT_QDRANT_URL}',\n collection: 'docs',\n dimensions: embeddings.dimensions,\n })\n );\n }\n `,\n };\n }\n}\n\nconst LAZY_CONNECT = code`\n /** Connects a store on first use, so importing the project opens no connection. */\n function lazilyConnected(\n store: EmbeddingAdapter & { connect(): Promise<MemoryResult<void>> }\n ): EmbeddingAdapter {\n let connected: Promise<void> | undefined;\n const ready = () =>\n (connected ??= store.connect().then((result) => {\n if (!result.success) throw new Error(\\`Cannot connect the vector store: \\${result.error}\\`);\n }));\n return {\n async addEmbedding(embedding) {\n await ready();\n return store.addEmbedding(embedding);\n },\n async search(options) {\n await ready();\n return store.search(options);\n },\n async deleteEmbedding(id) {\n await ready();\n return store.deleteEmbedding(id);\n },\n async deleteBySource(source) {\n await ready();\n return store.deleteBySource(source);\n },\n async deleteByFilter(filter) {\n await ready();\n if (!store.deleteByFilter) throw new Error('The vector store cannot delete by filter');\n return store.deleteByFilter(filter);\n },\n };\n }\n`;\n\nfunction knowledgeBaseTs(spec: ProjectSpec): string {\n const embedding = embeddingService(spec);\n const store = storeCode(spec);\n const persistent = spec.vectorStore !== 'memory';\n const memoryImports = [...store.imports, embedding.importName].sort();\n return code`\n import { tool } from '@cogitator-ai/core';\n import {\n ${memoryImports.join(',\\n')},\n type EmbeddingAdapter,\n type EmbeddingService,\n ${persistent && 'type MemoryResult,'}\n } from '@cogitator-ai/memory';\n import { MarkdownLoader, RAGPipelineBuilder, ragTools } from '@cogitator-ai/rag';\n\n /** The folder the knowledge base indexes: ./docs, or DOCS_DIR. */\n export const DOCS_DIR = process.env.DOCS_DIR ?? 'docs';\n\n /** Turns text into vectors with the project's provider. */\n export function createEmbeddings(): EmbeddingService {\n return ${embedding.expression};\n }\n\n ${persistent && LAZY_CONNECT}\n\n ${store.body}\n\n /**\n * Markdown under \\`DOCS_DIR\\`, split into overlapping chunks and searched by\n * similarity. Ingesting a source again replaces its chunks, so re-indexing\n * after an edit never duplicates anything.\n */\n export function createKnowledgeBase(embeddings: EmbeddingService = createEmbeddings(), store: EmbeddingAdapter = createStore(${persistent ? 'embeddings' : ''})) {\n return new RAGPipelineBuilder()\n .withLoader(new MarkdownLoader())\n .withEmbeddingService(embeddings)\n .withEmbeddingAdapter(store)\n .withConfig({\n chunking: { strategy: 'recursive', chunkSize: 600, chunkOverlap: 80 },\n retrieval: { strategy: 'similarity', topK: 4, threshold: 0.2 },\n })\n .build();\n }\n\n export const knowledgeBase = createKnowledgeBase();\n\n const [search] = ragTools(knowledgeBase, { allowedRoots: [DOCS_DIR], allowUrls: false });\n\n /** rag_search: the assistant looks things up in the docs before it answers. */\n export const ragSearch = tool(search);\n `;\n}\n\nconst INGEST_TS = code`\n import { DOCS_DIR, knowledgeBase } from './knowledge-base.js';\n\n /** Indexes DOCS_DIR into the vector store. Safe to run again: changed files replace their old chunks. */\n async function main(): Promise<void> {\n const { documents, chunks } = await knowledgeBase.ingest(DOCS_DIR);\n console.log(\\`Indexed \\${documents} document(s) in \\${chunks} chunk(s) from \\${DOCS_DIR}\\`);\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst RAG_TEST_TS = code`\n import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { InMemoryEmbeddingAdapter, type EmbeddingService } from '@cogitator-ai/memory';\n import { afterEach, beforeEach, describe, expect, it } from 'vitest';\n import { createKnowledgeBase } from '../src/rag/knowledge-base.js';\n\n /** Bag-of-words vectors: the same words give similar vectors, with no model and no network. */\n const embeddings: EmbeddingService = {\n model: 'test',\n dimensions: 64,\n async embed(text) {\n const vector = new Array<number>(64).fill(0);\n for (const word of text.toLowerCase().match(/[a-z]+/g) ?? []) {\n let hash = 0;\n for (const char of word) hash = (hash * 31 + char.charCodeAt(0)) % 64;\n vector[hash] += 1;\n }\n return vector;\n },\n async embedBatch(texts) {\n return Promise.all(texts.map((text) => this.embed(text)));\n },\n };\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'rag-'));\n writeFileSync(join(dir, 'deploys.md'), '# Deploys\\\\n\\\\nWe deploy on Tuesdays and Thursdays only.');\n writeFileSync(join(dir, 'lunch.md'), '# Lunch\\\\n\\\\nThe kitchen serves soup every Wednesday.');\n });\n\n afterEach(() => {\n rmSync(dir, { recursive: true, force: true });\n });\n\n describe('knowledge base', () => {\n it('finds the document that answers the question', async () => {\n const kb = createKnowledgeBase(embeddings, new InMemoryEmbeddingAdapter());\n await kb.ingest(dir);\n\n const [best] = await kb.query('Which days do we deploy?');\n expect(best?.source).toContain('deploys.md');\n });\n\n it('replaces a document on re-ingest instead of duplicating it', async () => {\n const kb = createKnowledgeBase(embeddings, new InMemoryEmbeddingAdapter());\n await kb.ingest(dir);\n writeFileSync(join(dir, 'deploys.md'), '# Deploys\\\\n\\\\nDeploys happen on Mondays now.');\n await kb.ingest(dir);\n\n const results = await kb.query('deploy days', { topK: 10, threshold: 0 });\n const deploys = results.filter((r) => r.source?.includes('deploys.md'));\n expect(deploys).toHaveLength(1);\n expect(deploys[0]?.content).toContain('Mondays');\n });\n });\n`;\n\n/** Answers grounded in the Markdown of docs/: a RAG pipeline and a search tool for the assistant. */\nexport const ragFeature: FeatureModule = {\n id: 'feature:rag',\n applies: (spec) => hasFeature(spec, 'rag'),\n apply(project) {\n const { spec } = project;\n project\n .dependency('@cogitator-ai/rag', cogitatorVersion('@cogitator-ai/rag'))\n .dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'))\n .file('docs/handbook.md', HANDBOOK_MD)\n .file('src/rag/knowledge-base.ts', knowledgeBaseTs(spec))\n .file('src/rag/ingest.ts', INGEST_TS)\n .file('tests/rag.test.ts', RAG_TEST_TS)\n .tool('ragSearch', '../rag/knowledge-base.js')\n .instruct(\n 'Before you answer a question about the project, its team or its rules, search the docs with rag_search and answer from what it finds. Say so when the docs do not cover it.'\n )\n .envVar({\n name: 'DOCS_DIR',\n description: 'The folder of Markdown the knowledge base indexes',\n example: 'docs',\n required: false,\n secret: false,\n });\n\n if (\n spec.app === 'script' ||\n spec.app === 'server' ||\n spec.app === 'channels' ||\n spec.app === 'worker'\n ) {\n project.script('ingest', 'tsx --env-file-if-exists=.env src/rag/ingest.ts');\n }\n\n if (spec.vectorStore === 'postgres') {\n addPostgresService(project);\n } else if (spec.vectorStore === 'qdrant') {\n project\n .dependency('@qdrant/js-client-rest', VERSIONS.qdrant)\n .service(\n {\n name: 'qdrant',\n image: IMAGES.qdrant,\n ports: ['6333:6333'],\n volumes: ['qdrant_data:/qdrant/storage'],\n },\n 'qdrant_data'\n )\n .envVar({\n name: 'QDRANT_URL',\n description: 'The Qdrant server',\n example: DEFAULT_QDRANT_URL,\n required: false,\n secret: false,\n });\n } else {\n project.onStartup(\n \"import { DOCS_DIR, knowledgeBase } from './rag/knowledge-base.js';\",\n 'await knowledgeBase.ingest(DOCS_DIR);'\n );\n }\n if (spec.vectorStore !== 'memory') {\n project.step({\n command: runScript(spec.packageManager, 'ingest'),\n note: 'index docs/ once, and again after edits',\n });\n }\n },\n finalize(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n project.section(\n 'RAG',\n code`\n \\`src/rag/knowledge-base.ts\\` indexes the Markdown under \\`docs/\\` with \\`@cogitator-ai/rag\\`: chunks are embedded with ${providerInfo(spec.provider).label} and stored ${spec.vectorStore === 'memory' ? 'in memory, so the project indexes them again on every start' : spec.vectorStore === 'postgres' ? 'in Postgres with pgvector' : 'in Qdrant'}. The assistant searches them with \\`rag_search\\`. ${spec.vectorStore === 'memory' ? '' : `\\`${runScript(pm, 'ingest')}\\` indexes the folder; re-running it after an edit replaces the changed files' chunks. `}\\`tests/rag.test.ts\\` runs the pipeline offline with deterministic bag-of-words embeddings.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nexport const SANDBOX_IMAGE = 'python:3.13-alpine';\n\nconst RUN_PYTHON_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n /**\n * Runs a shell command, usually \\`python3 -c '...'\\`, in a throwaway Docker\n * container: no network, 256 MB of memory, 30 seconds. Without Docker the\n * call fails instead of running on your machine, because cogitator.yml sets\n * sandbox.allowNativeFallback to false.\n */\n export const runPython = tool({\n name: 'run_python',\n description:\n 'Run Python in an isolated container without network access, for calculations, data processing and checking code. Pass a shell command such as python3 -c \"print(2 ** 100)\" and print what you need: stdout and stderr come back.',\n parameters: z.object({\n command: z.string().min(1).max(10_000).describe('The shell command to run, e.g. python3 -c \"print(1 + 1)\"'),\n }),\n sandbox: {\n type: 'docker',\n image: '${SANDBOX_IMAGE}',\n resources: { memory: '256MB', cpus: 1 },\n network: { mode: 'none' },\n timeout: 30_000,\n },\n timeout: 40_000,\n execute: async ({ command }) => command,\n });\n`;\n\nconst SANDBOX_TEST_TS = code`\n import { execFileSync } from 'node:child_process';\n import { describe, expect, it } from 'vitest';\n import { runPython } from '../src/tools/run-python.js';\n import { mockCogitator } from './helpers.js';\n\n function hasDocker(): boolean {\n try {\n execFileSync('docker', ['info'], { stdio: 'ignore', timeout: 10_000 });\n return true;\n } catch {\n return false;\n }\n }\n\n describe('run_python', () => {\n it('runs in a container without network and with limits', () => {\n expect(runPython.sandbox).toMatchObject({ type: 'docker', network: { mode: 'none' } });\n expect(runPython.sandbox?.resources?.memory).toBe('256MB');\n });\n\n it.runIf(hasDocker())('runs Python and returns its output', async () => {\n const { cogitator } = mockCogitator();\n try {\n const result = await cogitator.invokeTool(runPython, { command: 'python3 -c \"print(6 * 7)\"' });\n expect(JSON.stringify(result.result)).toContain('42');\n } finally {\n await cogitator.close();\n }\n }, 120_000);\n });\n`;\n\n/** Code the assistant writes runs in a Docker container, never on the host. */\nexport const sandboxFeature: FeatureModule = {\n id: 'feature:sandbox',\n applies: (spec) => hasFeature(spec, 'sandbox'),\n apply(project) {\n project\n .dependency('@cogitator-ai/sandbox', cogitatorVersion('@cogitator-ai/sandbox'))\n .file('src/tools/run-python.ts', RUN_PYTHON_TS)\n .file('tests/sandbox.test.ts', SANDBOX_TEST_TS)\n .tool('runPython', './run-python.js')\n .yml('sandbox', ['allowNativeFallback: false'])\n .instruct(\n 'For calculations and data work beyond the calculator, write Python and run it with run_python.'\n );\n project.section(\n 'Sandbox',\n code`\n \\`src/tools/run-python.ts\\` gives the assistant \\`run_python\\`: a command in a throwaway \\`${SANDBOX_IMAGE}\\` container without network, with 256 MB of memory and 30 seconds, through \\`@cogitator-ai/sandbox\\`. Docker has to run. Without it the call fails, since \\`sandbox.allowNativeFallback: false\\` in \\`cogitator.yml\\` keeps the code off your machine.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { providerInfo } from '../providers.js';\nimport { hasFeature, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport { LIFECYCLE_TS } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const VOICE_PORT = 3000;\n\nconst REALTIME_TOOLS_TS = code`\n import { type Cogitator, type Tool, toolToSchema } from '@cogitator-ai/core';\n import type { RealtimeTool } from '@cogitator-ai/voice';\n\n /**\n * The assistant's tools in the shape a realtime session takes. Each call runs\n * through \\`cogitator.invokeTool\\`, so arguments are validated and timeouts kept\n * the way an agent run does it. Tools that need approval are left out: a voice\n * session has nobody to click Approve.\n */\n export function realtimeTools(runtime: Cogitator, tools: readonly Tool[]): RealtimeTool[] {\n return tools\n .filter((tool) => !tool.requiresApproval)\n .map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toolToSchema(tool).parameters,\n execute: async (args) => {\n const result = await runtime.invokeTool(tool, args, { agentId: 'voice' });\n return result.error ? { error: result.error } : result.result;\n },\n }));\n }\n`;\n\nfunction voiceEntry(spec: ProjectSpec): string {\n const provider = spec.provider === 'google' ? 'gemini' : 'openai';\n const envKey = providerInfo(spec.provider).envKey ?? 'OPENAI_API_KEY';\n const inputRate = provider === 'openai' ? 24_000 : 16_000;\n return code`\n import { readFile } from 'node:fs/promises';\n import { createServer } from 'node:http';\n import { timingSafeEqual } from 'node:crypto';\n import { createCogitatorRunner, VoiceAgent } from '@cogitator-ai/voice';\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n import { tools } from './tools/index.js';\n import { realtimeTools } from './voice/tools.js';\n\n const env = loadEnv();\n const production = process.env.NODE_ENV === 'production';\n const port = Number(env.PORT ?? ${VOICE_PORT});\n const host = env.HOST ?? (production ? '0.0.0.0' : '127.0.0.1');\n if (production && !env.VOICE_TOKEN) {\n throw new Error('Set VOICE_TOKEN in production: every voice session costs realtime API time');\n }\n\n /** The browser page, from public/ next to src/ and dist/. */\n const page = await readFile(new URL('../public/index.html', import.meta.url));\n\n function allowed(token: string | null): boolean {\n if (!env.VOICE_TOKEN) return true;\n if (!token) return false;\n const a = Buffer.from(token);\n const b = Buffer.from(env.VOICE_TOKEN);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n const voice = new VoiceAgent({\n mode: 'realtime',\n agent: createCogitatorRunner(cogitator, agents.assistant),\n realtimeProvider: '${provider}',\n realtimeApiKey: env.${envKey},\n tools: realtimeTools(cogitator, tools),\n transport: {\n path: '/voice',\n maxConnections: 10,\n verifyClient: (req) => allowed(new URL(req.url ?? '/', 'http://localhost').searchParams.get('token')),\n },\n });\n voice.on('error', (error) => console.error(\\`voice: \\${error.message}\\`));\n\n const server = createServer((req, res) => {\n const path = new URL(req.url ?? '/', 'http://localhost').pathname;\n if (path === '/health') {\n res.writeHead(200, { 'content-type': 'application/json' }).end('{\"status\":\"ok\"}');\n } else if (path === '/config') {\n res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ inputSampleRate: ${inputRate} }));\n } else if (path === '/') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(page);\n } else {\n res.writeHead(404).end();\n }\n });\n voice.attach(server);\n\n server.listen(port, host, () => {\n console.log(\\`Open http://\\${host}:\\${port} and talk to the assistant\\`);\n });\n\n onShutdown(async () => {\n await voice.close();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n await cogitator.close();\n });\n `;\n}\n\nconst INDEX_HTML = code`\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Voice assistant</title>\n <style>\n :root { color-scheme: light dark; font-family: system-ui, sans-serif; }\n body { margin: 0; display: grid; place-items: center; min-height: 100vh; }\n main { width: min(40rem, 100% - 2rem); display: grid; gap: 1rem; }\n button { font: inherit; padding: 0.75rem 1.25rem; border-radius: 999px; border: 1px solid currentColor; cursor: pointer; }\n form { display: flex; gap: 0.5rem; }\n input { flex: 1; font: inherit; padding: 0.5rem 0.75rem; }\n ol { list-style: none; padding: 0; display: grid; gap: 0.5rem; }\n li b { text-transform: capitalize; }\n #status { opacity: 0.7; }\n </style>\n </head>\n <body>\n <main>\n <h1>Talk to the assistant</h1>\n <button id=\"talk\" type=\"button\">Start talking</button>\n <p id=\"status\">Not connected</p>\n <form id=\"text\"><input name=\"message\" placeholder=\"Or type a message\" autocomplete=\"off\" /><button type=\"submit\">Send</button></form>\n <ol id=\"log\"></ol>\n </main>\n <script type=\"module\">\n const OUTPUT_RATE = 24000;\n const RECORDER = \\`class Recorder extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0][0];\n if (input) {\n const pcm = new Int16Array(input.length);\n for (let i = 0; i < input.length; i++) {\n const s = Math.max(-1, Math.min(1, input[i]));\n pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff;\n }\n this.port.postMessage(pcm.buffer, [pcm.buffer]);\n }\n return true;\n }\n }\n registerProcessor('recorder', Recorder);\\`;\n\n const $ = (id) => document.getElementById(id);\n let socket, input, output, stream;\n let playhead = 0;\n const playing = new Set();\n\n const status = (text) => { $('status').textContent = text; };\n const log = (who, text) => {\n const item = document.createElement('li');\n item.innerHTML = '<b></b>: <span></span>';\n item.querySelector('b').textContent = who;\n item.querySelector('span').textContent = text;\n $('log').prepend(item);\n };\n\n function stopPlayback() {\n for (const node of playing) node.stop();\n playing.clear();\n playhead = output ? output.currentTime : 0;\n }\n\n function play(buffer) {\n const pcm = new Int16Array(buffer);\n const audio = output.createBuffer(1, pcm.length, OUTPUT_RATE);\n const channel = audio.getChannelData(0);\n for (let i = 0; i < pcm.length; i++) channel[i] = pcm[i] / 0x8000;\n const node = output.createBufferSource();\n node.buffer = audio;\n node.connect(output.destination);\n node.onended = () => playing.delete(node);\n playhead = Math.max(playhead, output.currentTime);\n node.start(playhead);\n playhead += audio.duration;\n playing.add(node);\n }\n\n function onEvent(event) {\n if (event.type === 'speech_start') stopPlayback();\n if (event.type === 'transcript' && event.isFinal !== false && event.text) log(event.role ?? 'you', event.text);\n if (event.type === 'agent_response' && event.text) log('assistant', event.text);\n }\n\n async function connect() {\n const { inputSampleRate } = await (await fetch('/config')).json();\n const token = new URLSearchParams(location.hash.slice(1)).get('token');\n const url = new URL('/voice', location.href);\n url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';\n if (token) url.searchParams.set('token', token);\n\n output = new AudioContext({ sampleRate: OUTPUT_RATE });\n input = new AudioContext({ sampleRate: inputSampleRate });\n await input.audioWorklet.addModule(URL.createObjectURL(new Blob([RECORDER], { type: 'text/javascript' })));\n stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } });\n const recorder = new AudioWorkletNode(input, 'recorder');\n input.createMediaStreamSource(stream).connect(recorder);\n\n socket = new WebSocket(url);\n socket.binaryType = 'arraybuffer';\n recorder.port.onmessage = (message) => {\n if (socket.readyState === WebSocket.OPEN) socket.send(message.data);\n };\n socket.onopen = () => status('Listening. Speak, or type below.');\n socket.onmessage = (message) => (typeof message.data === 'string' ? onEvent(JSON.parse(message.data)) : play(message.data));\n socket.onclose = (event) => {\n status(event.code === 1000 ? 'Disconnected' : \\`Disconnected: \\${event.reason || event.code}\\`);\n disconnect();\n };\n $('talk').textContent = 'Stop';\n }\n\n function disconnect() {\n stopPlayback();\n for (const track of stream?.getTracks() ?? []) track.stop();\n input?.close();\n output?.close();\n if (socket && socket.readyState === WebSocket.OPEN) socket.close(1000);\n socket = input = output = stream = undefined;\n $('talk').textContent = 'Start talking';\n }\n\n $('talk').addEventListener('click', () => (socket ? disconnect() : connect().catch((error) => status(error.message))));\n $('text').addEventListener('submit', (event) => {\n event.preventDefault();\n const field = event.target.elements.message;\n if (!socket || socket.readyState !== WebSocket.OPEN || !field.value.trim()) return;\n socket.send(JSON.stringify({ type: 'text', text: field.value }));\n log('you', field.value);\n field.value = '';\n });\n </script>\n </body>\n </html>\n`;\n\nconst VOICE_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { agents } from '../src/cogitator.js';\n import { tools } from '../src/tools/index.js';\n import { realtimeTools } from '../src/voice/tools.js';\n import { mockCogitator } from './helpers.js';\n\n describe('realtime tools', () => {\n it('offers the assistant tools as JSON Schema', () => {\n const { cogitator } = mockCogitator();\n const bridged = realtimeTools(cogitator, tools);\n const calculator = bridged.find((tool) => tool.name === 'calculator');\n expect(calculator?.parameters).toMatchObject({ type: 'object', properties: { expression: expect.any(Object) } });\n expect(agents.assistant.instructions).toBeTruthy();\n });\n\n it('runs a call through the runtime and validates its arguments', async () => {\n const { cogitator } = mockCogitator();\n const calculator = realtimeTools(cogitator, tools).find((tool) => tool.name === 'calculator');\n expect(await calculator?.execute({ expression: '6 * 7' })).toEqual({ expression: '6 * 7', result: 42 });\n expect(await calculator?.execute({ expression: 42 })).toMatchObject({ error: expect.any(String) });\n await cogitator.close();\n });\n });\n`;\n\n/** A realtime voice agent: speech in, speech out, in the browser over WebSocket. */\nexport const voiceFeature: FeatureModule = {\n id: 'feature:voice',\n applies: (spec) => hasFeature(spec, 'voice'),\n apply(project) {\n project\n .dependency('@cogitator-ai/voice', cogitatorVersion('@cogitator-ai/voice'))\n .file('src/voice/tools.ts', REALTIME_TOOLS_TS)\n .file('public/index.html', INDEX_HTML)\n .file('tests/voice.test.ts', VOICE_TEST_TS)\n .envVar({\n name: 'PORT',\n description: 'Port of the voice page and WebSocket',\n example: String(VOICE_PORT),\n required: false,\n secret: false,\n })\n .envVar({\n name: 'HOST',\n description: 'Interface to listen on: 127.0.0.1 in development, 0.0.0.0 in production',\n example: '127.0.0.1',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'VOICE_TOKEN',\n description: 'Token the voice page needs in its URL (#token=...), mandatory in production',\n required: false,\n secret: true,\n deploy: true,\n })\n .instruct('You are speaking out loud: keep answers short, plain and easy to follow by ear.');\n project.deploy.kind = 'server';\n project.deploy.port = VOICE_PORT;\n project.deploy.healthPath = '/health';\n },\n finalize(project) {\n const { spec } = project;\n if (spec.app === 'script') {\n project.file('src/index.ts', voiceEntry(spec)).file('src/lifecycle.ts', LIFECYCLE_TS);\n }\n project.section(\n 'Voice',\n code`\n \\`src/index.ts\\` serves \\`public/index.html\\` and a realtime \\`VoiceAgent\\` on \\`/voice\\` (${spec.provider === 'google' ? 'Gemini Live' : 'OpenAI Realtime'}): the page streams the microphone as PCM16, plays the answer and lets you interrupt by talking. \\`src/voice/tools.ts\\` hands the assistant's tools to the realtime session through \\`cogitator.invokeTool\\`, leaving out tools that need approval. Run \\`${runScript(spec.packageManager, 'dev')}\\` and open http://localhost:${VOICE_PORT}. In production set \\`VOICE_TOKEN\\` and open the page with \\`#token=<token>\\`.\n `\n );\n },\n};\n","import { a2aFeature } from './a2a.js';\nimport { appChannelsFeature } from './app-channels.js';\nimport { appNextFeature } from './app-next.js';\nimport { appScriptFeature } from './app-script.js';\nimport { appServerFeature } from './app-server.js';\nimport { appWorkerFeature } from './app-worker.js';\nimport { codingAgentsFeature } from './coding-agents.js';\nimport { deployFeature } from './deploy.js';\nimport { baseFeature } from './base.js';\nimport { evalsFeature } from './evals.js';\nimport { harnessFeature } from './harness.js';\nimport { mcpFeature } from './mcp.js';\nimport { observabilityFeature } from './observability.js';\nimport { memoryFeature } from './memory.js';\nimport { durableFeature, swarmsFeature, workflowsFeature } from './orchestration.js';\nimport { providerFeature } from './provider.js';\nimport { ragFeature } from './rag.js';\nimport { sandboxFeature } from './sandbox.js';\nimport { voiceFeature } from './voice.js';\nimport type { FeatureModule } from './types.js';\n\n/**\n * Every feature module in the order they run. Later modules can rely on what\n * earlier ones added: the app modules see the memory and the provider, and the\n * add-ons see the app.\n */\nexport const FEATURE_MODULES: readonly FeatureModule[] = [\n baseFeature,\n providerFeature,\n memoryFeature,\n harnessFeature,\n evalsFeature,\n ragFeature,\n mcpFeature,\n a2aFeature,\n voiceFeature,\n observabilityFeature,\n sandboxFeature,\n deployFeature,\n workflowsFeature,\n durableFeature,\n swarmsFeature,\n appScriptFeature,\n appServerFeature,\n appChannelsFeature,\n appNextFeature,\n appWorkerFeature,\n codingAgentsFeature,\n];\n","import type { ProjectSpecInput } from './spec.js';\n\n/** The parts of a spec a preset fixes: everything except the name, provider and tooling. */\nexport type PresetSpec = Pick<\n ProjectSpecInput,\n 'app' | 'server' | 'channels' | 'memory' | 'vectorStore' | 'features'\n> & { provider?: ProjectSpecInput['provider'] };\n\nexport interface Preset {\n id: string;\n label: string;\n hint: string;\n spec: PresetSpec;\n /** Earlier names of the preset that `--template` still accepts. */\n aliases?: string[];\n}\n\n/**\n * Named starting points. Every preset is a combination of the stack axes, so a\n * preset project can grow with `cogitator add` like any other.\n */\nexport const PRESETS: readonly Preset[] = [\n {\n id: 'basic',\n label: 'Basic agent',\n hint: 'one agent with real tools in your terminal, the best place to start',\n spec: { app: 'script', memory: 'none', features: [] },\n },\n {\n id: 'assistant',\n label: 'Personal assistant',\n hint: 'workspace files with approvals, long-term memory, a scheduler and evals',\n spec: { app: 'script', memory: 'sqlite', features: ['harness', 'evals'] },\n },\n {\n id: 'memory',\n label: 'Agent with memory',\n hint: 'conversations that survive restarts, in SQLite',\n spec: { app: 'script', memory: 'sqlite', features: [] },\n },\n {\n id: 'api-server',\n label: 'REST API server',\n hint: 'Express with Swagger UI, token auth and persistent threads',\n spec: { app: 'server', server: 'express', memory: 'sqlite', features: [] },\n },\n {\n id: 'hono',\n label: 'Hono server',\n hint: 'agents behind a small, fast HTTP API',\n spec: { app: 'server', server: 'hono', memory: 'sqlite', features: [] },\n },\n {\n id: 'tetsu',\n label: 'Tetsu server on Bun',\n hint: 'Bun-native controller with OpenAPI and WebSocket',\n spec: { app: 'server', server: 'tetsu', memory: 'memory', features: [] },\n },\n {\n id: 'nextjs',\n label: 'Next.js chat app',\n hint: 'streaming chat with tool calls, approvals and saved threads',\n spec: { app: 'next', memory: 'sqlite', features: [] },\n },\n {\n id: 'channels',\n label: 'Messaging bot',\n hint: 'one assistant on Telegram, Discord, Slack or WebChat',\n spec: { app: 'channels', channels: ['webchat'], memory: 'sqlite', features: [] },\n },\n {\n id: 'rag',\n label: 'RAG over your docs',\n hint: 'answers grounded in the files of docs/',\n spec: { app: 'script', memory: 'none', vectorStore: 'memory', features: ['rag'] },\n },\n {\n id: 'mcp',\n label: 'MCP tools and server',\n hint: 'tools from an MCP server, your agents served over MCP',\n spec: { app: 'script', memory: 'none', features: ['mcp'] },\n },\n {\n id: 'swarm',\n label: 'Multi-agent swarm',\n hint: 'a researcher and a writer under a reviewing supervisor',\n spec: { app: 'script', memory: 'none', features: ['swarms'] },\n },\n {\n id: 'workflow',\n label: 'DAG workflow',\n hint: 'a multi-step pipeline of agents',\n spec: { app: 'script', memory: 'none', features: ['workflows'] },\n },\n {\n id: 'durable-workflow',\n label: 'Durable workflow',\n hint: 'a saga with compensation, an approval step and crash recovery',\n spec: { app: 'script', memory: 'none', features: ['workflows', 'durable'] },\n },\n {\n id: 'a2a',\n label: 'A2A agent',\n hint: 'an agent other frameworks call over the Agent-to-Agent protocol',\n spec: { app: 'server', server: 'hono', memory: 'memory', features: ['a2a'] },\n },\n {\n id: 'voice-realtime',\n label: 'Realtime voice agent',\n hint: 'speech in, speech out over WebSocket',\n spec: { app: 'script', memory: 'none', features: ['voice'], provider: 'openai' },\n },\n {\n id: 'evals',\n label: 'Evals',\n hint: 'measure an agent on a dataset and gate CI on the score',\n spec: { app: 'script', memory: 'none', features: ['evals'] },\n },\n];\n\nexport const DEFAULT_PRESET = 'basic';\n\nexport function findPreset(idOrAlias: string): Preset | undefined {\n return PRESETS.find((preset) => preset.id === idOrAlias || preset.aliases?.includes(idOrAlias));\n}\n\nexport function presetIds(): string[] {\n return PRESETS.map((preset) => preset.id);\n}\n","import { code } from './code.js';\nimport { orderedScripts } from './emit.js';\nimport { findPreset } from './presets.js';\nimport type { NextStep, ProjectBuilder } from './project.js';\nimport { providerInfo } from './providers.js';\nimport { installCommand, runScript } from './package-manager.js';\nimport { bareModel, type ProjectSpec } from './spec.js';\n\nexport const DOCS_URL = 'https://cogitator.app/docs';\nexport const REPO_URL = 'https://github.com/cogitator-ai/Cogitator-AI';\n\n/** What is already done when the next steps are shown. */\nexport interface SetupState {\n /** Where the project is relative to the user's shell; no `cd` step when absent. */\n directory?: string;\n installed: boolean;\n /** Whether the provider key was written to `.env`. */\n keyWritten: boolean;\n /** Whether the Ollama model is known to be pulled. */\n modelReady: boolean;\n}\n\nfunction quoteDirectory(directory: string): string {\n return /^[\\w./-]+$/.test(directory) ? directory : JSON.stringify(directory);\n}\n\n/** Compose services the project needs while it runs, other than the model server. */\nfunction backingServices(project: ProjectBuilder): string[] {\n return [...project.services.keys()].filter((name) => name !== 'ollama' && name !== 'ollama-pull');\n}\n\n/** The commands that take a freshly scaffolded project to its first successful run. */\nexport function nextSteps(project: ProjectBuilder, state: SetupState): NextStep[] {\n const { spec } = project;\n const pm = spec.packageManager;\n const steps: NextStep[] = [];\n const info = providerInfo(spec.provider);\n\n if (state.directory) steps.push({ command: `cd ${quoteDirectory(state.directory)}` });\n if (!state.installed) steps.push({ command: installCommand(pm) });\n if (info.envKey && !state.keyWritten) {\n steps.push({ command: 'cp .env.example .env', note: `then set ${info.envKey} in .env` });\n }\n if (spec.provider === 'ollama' && !state.modelReady) {\n steps.push({\n command: `ollama pull ${bareModel(spec)}`,\n note: spec.compose\n ? 'or let `docker compose up -d` pull it into the Ollama container'\n : 'download the model the agents use',\n });\n }\n const services = backingServices(project);\n if (spec.compose && services.length > 0) {\n steps.push({ command: 'docker compose up -d', note: `starts ${services.join(', ')}` });\n }\n steps.push(...project.nextSteps);\n steps.push({ command: runScript(pm, 'dev') });\n return steps;\n}\n\nexport function emitReadme(project: ProjectBuilder): void {\n const { spec } = project;\n const pm = spec.packageManager;\n const preset = spec.preset ? findPreset(spec.preset) : undefined;\n const steps = nextSteps(project, {\n installed: false,\n keyWritten: false,\n modelReady: false,\n });\n const stepLines = steps.flatMap((step, i) => [\n ...(i > 0 ? [''] : []),\n ...(step.note ? [`# ${step.note}`] : []),\n step.command,\n ]);\n const sections = project.readme.map(\n (section) => `## ${section.title}\\n\\n${section.body.trim()}\\n`\n );\n\n project.file(\n 'README.md',\n code`\n # ${spec.name}\n\n ${preset ? `${preset.hint.charAt(0).toUpperCase()}${preset.hint.slice(1)}.` : 'An AI agent project.'} Built with [Cogitator](${REPO_URL}).\n\n ## Getting started\n\n \\`\\`\\`bash\n ${stepLines.join('\\n')}\n \\`\\`\\`\n\n ## Commands\n\n | Command | What it does |\n | --- | --- |\n ${Object.keys(orderedScripts(project.scripts))\n .map((script) => `| \\`${runScript(pm, script)}\\` | ${describeScript(script)} |`)\n .join('\\n')}\n\n ${sections.join('\\n')}\n\n ## Learn more\n\n - [AGENTS.md](./AGENTS.md): how this project is put together, for you and your coding agent\n - [Cogitator docs](${DOCS_URL})\n - [Cogitator on GitHub](${REPO_URL})\n `\n );\n}\n\nconst SCRIPT_DESCRIPTIONS: Record<string, string> = {\n dev: 'Run the project and restart on change',\n ask: 'Ask the assistant once: pass the question after the command',\n build: 'Compile the project',\n start: 'Run the compiled project',\n test: 'Offline tests with a mocked model',\n typecheck: 'Type-check without emitting',\n lint: 'Lint and check formatting with Biome',\n format: 'Format and fix lint issues',\n eval: 'Score the assistant on the eval dataset',\n 'dev:studio': 'Open Cogitator Studio: chat, traces, costs, approvals, workflows and forks',\n doctor: 'Check keys, services and models',\n ingest: 'Index the files in docs/ for RAG',\n 'mcp:serve': 'Serve the agents as an MCP server over stdio',\n worker: 'Start the queue worker',\n enqueue: 'Queue a job for the worker',\n};\n\nfunction describeScript(script: string): string {\n return SCRIPT_DESCRIPTIONS[script] ?? 'See package.json';\n}\n\n/** Re-creates the project with the same choices: stored in package.json for reference. */\nexport function reproducibleCommand(spec: ProjectSpec, version: string): string {\n const args = [\n `create-cogitator-app@${version}`,\n spec.name,\n ...(spec.preset ? ['--preset', spec.preset] : []),\n '--app',\n spec.app,\n ...(spec.server ? ['--server', spec.server] : []),\n ...(spec.channels.length > 0 ? ['--channels', spec.channels.join(',')] : []),\n '--memory',\n spec.memory,\n ...(spec.features.includes('rag') ? ['--vector-store', spec.vectorStore] : []),\n ...(spec.features.length > 0 ? ['--features', spec.features.join(',')] : []),\n '--provider',\n spec.provider,\n '--model',\n spec.model,\n '--deploy',\n spec.deploy,\n spec.compose ? '--docker' : '--no-docker',\n ...(spec.codingAgents.length > 0 ? ['--agent', spec.codingAgents.join(',')] : []),\n '--pm',\n spec.packageManager,\n '--yes',\n ];\n return `npx ${args.map((arg) => (/^[\\w@./:,=-]+$/.test(arg) ? arg : JSON.stringify(arg))).join(' ')}`;\n}\n","import type { ProjectSpec } from './spec.js';\n\n/** A variable the generated project reads from its environment. */\nexport interface EnvVar {\n name: string;\n /** One line for `.env.example` and the env schema. */\n description: string;\n /** The value `.env.example` shows; secrets show an empty value. */\n example?: string;\n /** Whether the project refuses to start without it. */\n required: boolean;\n /** Whether it is a credential: never logged, kept out of `.env.example` values. */\n secret: boolean;\n /**\n * Whether a deployment must provide it, listed in `cogitator.yml` as a\n * `deploy.secrets` entry. Defaults to secrets the project requires.\n */\n deploy?: boolean;\n}\n\n/** A service `docker compose up` starts for local development. */\nexport interface ComposeService {\n name: string;\n image: string;\n ports?: string[];\n environment?: Record<string, string>;\n volumes?: string[];\n command?: string[];\n entrypoint?: string[];\n dependsOn?: Record<string, 'service_started' | 'service_healthy'>;\n healthcheck?: { test: string[]; interval: string; timeout: string; retries: number };\n restart?: 'no' | 'unless-stopped';\n}\n\n/** A section of the generated AGENTS.md, which coding agents read before they touch the project. */\nexport interface AgentsMdSection {\n title: string;\n body: string;\n}\n\n/** A command that takes the project to its first run, with an optional explanation. */\nexport interface NextStep {\n command: string;\n note?: string;\n}\n\n/** Something the registry `src/cogitator.ts` exports by name. */\nexport interface RegistryEntry {\n kind: 'agents' | 'workflows' | 'swarms';\n /** The key under which the registry exposes it. */\n name: string;\n /** The module it is imported from, relative to `src/`. */\n from: string;\n /** The binding the module exports. */\n binding: string;\n}\n\n/** What `cogitator.yml` tells `cogitator deploy` about the project. */\nexport interface DeploySettings {\n kind?: 'server' | 'worker';\n port?: number;\n healthPath?: string;\n}\n\nexport interface GeneratedFile {\n path: string;\n /** Mutable until the plan is done, so a final pass can adapt every file. */\n content: string;\n /** File mode for `chmod`, used for `.env` (0600) and executable scripts. */\n mode?: number;\n}\n\n/**\n * The project as the feature modules build it up. Features add files, packages,\n * scripts, variables, services and documentation, and the emitters turn the\n * collected parts into package.json, `.env.example`, `docker-compose.yml`,\n * `cogitator.yml`, AGENTS.md and the registry once every feature has run.\n */\nexport class ProjectBuilder {\n readonly spec: ProjectSpec;\n readonly files = new Map<string, GeneratedFile>();\n readonly dependencies = new Map<string, string>();\n readonly devDependencies = new Map<string, string>();\n readonly scripts = new Map<string, string>();\n readonly env = new Map<string, EnvVar>();\n readonly services = new Map<string, ComposeService>();\n readonly volumes = new Set<string>();\n readonly agentsMd: AgentsMdSection[] = [];\n readonly readme: AgentsMdSection[] = [];\n readonly registry: RegistryEntry[] = [];\n readonly gitignore = new Set<string>();\n readonly nativeBuilds = new Set<string>();\n readonly nextSteps: NextStep[] = [];\n readonly warnings: string[] = [];\n readonly memoryYml: string[] = [];\n /** Top-level sections of cogitator.yml other features add, such as `sandbox`. */\n readonly ymlSections = new Map<string, string[]>();\n readonly deploy: DeploySettings = {};\n /** Tools the assistant gets: bindings `src/tools/index.ts` imports, `spread` for arrays of tools. */\n readonly tools: Array<{ binding: string; from: string; spread?: boolean }> = [];\n /** Imports and statements every entry point runs before it starts serving, such as indexing docs. */\n readonly startup: { imports: string[]; statements: string[] } = { imports: [], statements: [] };\n /** Lines of the assistant agent's instructions, one per feature that shapes its behavior. */\n readonly instructions: string[] = [];\n\n /** `name@version` of the package manager when it is known, such as `yarn@4.9.1`. */\n readonly packageManagerSpec?: string;\n\n constructor(spec: ProjectSpec, options: { packageManagerSpec?: string } = {}) {\n this.spec = spec;\n this.packageManagerSpec = options.packageManagerSpec;\n }\n\n file(path: string, content: string, mode?: number): this {\n if (this.files.has(path)) {\n throw new Error(`Two features generate ${path}: the feature modules overlap`);\n }\n this.files.set(path, { path, content, ...(mode !== undefined && { mode }) });\n return this;\n }\n\n /** Adds `name` at `version`. A package two features need must be asked for at one version. */\n dependency(name: string, version: string): this {\n return this.addPackage(this.dependencies, name, version);\n }\n\n devDependency(name: string, version: string): this {\n return this.addPackage(this.devDependencies, name, version);\n }\n\n private addPackage(target: Map<string, string>, name: string, version: string): this {\n const existing = target.get(name);\n if (existing !== undefined && existing !== version) {\n throw new Error(`${name} is requested at both ${existing} and ${version}`);\n }\n target.set(name, version);\n return this;\n }\n\n script(name: string, command: string): this {\n this.scripts.set(name, command);\n return this;\n }\n\n envVar(variable: EnvVar): this {\n const existing = this.env.get(variable.name);\n this.env.set(\n variable.name,\n existing ? { ...existing, required: existing.required || variable.required } : variable\n );\n return this;\n }\n\n service(service: ComposeService, volume?: string): this {\n this.services.set(service.name, service);\n if (volume) this.volumes.add(volume);\n return this;\n }\n\n section(title: string, body: string): this {\n this.agentsMd.push({ title, body });\n return this;\n }\n\n readmeSection(title: string, body: string): this {\n this.readme.push({ title, body });\n return this;\n }\n\n register(entry: RegistryEntry): this {\n if (this.registry.some((e) => e.kind === entry.kind && e.name === entry.name)) {\n throw new Error(`The registry already has ${entry.kind}.${entry.name}`);\n }\n this.registry.push(entry);\n return this;\n }\n\n tool(binding: string, from: string): this {\n this.tools.push({ binding, from });\n return this;\n }\n\n /** Gives the assistant every tool of an exported array. */\n toolSet(binding: string, from: string): this {\n this.tools.push({ binding, from, spread: true });\n return this;\n }\n\n ignore(...patterns: string[]): this {\n for (const pattern of patterns) this.gitignore.add(pattern);\n return this;\n }\n\n /** Packages with install scripts the package managers have to be allowed to run. */\n allowBuild(...packages: string[]): this {\n for (const name of packages) this.nativeBuilds.add(name);\n return this;\n }\n\n step(step: NextStep): this {\n this.nextSteps.push(step);\n return this;\n }\n\n warn(message: string): this {\n this.warnings.push(message);\n return this;\n }\n\n yml(section: string, lines: string[]): this {\n this.ymlSections.set(section, lines);\n return this;\n }\n\n onStartup(importLine: string, statement: string): this {\n if (!this.startup.imports.includes(importLine)) this.startup.imports.push(importLine);\n this.startup.statements.push(statement);\n return this;\n }\n\n instruct(line: string): this {\n this.instructions.push(line);\n return this;\n }\n}\n","import { assertCompatible } from './compat.js';\nimport {\n adaptImportsForBundler,\n emitAgentsMd,\n emitCogitatorYml,\n emitCompose,\n emitEnvExample,\n emitEnvFile,\n emitEnvModule,\n emitGitignore,\n emitPackageJson,\n emitPnpmWorkspace,\n emitRegistry,\n emitToolsIndex,\n} from './emit.js';\nimport { emitAssistant } from './features/base.js';\nimport { emitDeployArtifacts } from './features/deploy.js';\nimport { FEATURE_MODULES } from './features/index.js';\nimport { emitReadme, nextSteps, reproducibleCommand, type SetupState } from './guide.js';\nimport { ProjectBuilder, type EnvVar, type GeneratedFile, type NextStep } from './project.js';\nimport { parseSpec, type ProjectSpec } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\nexport interface PlanOptions {\n /** Values for `.env`, such as the provider key. Never written anywhere else. */\n secrets?: Record<string, string>;\n /** `name@version` of the package manager, written to package.json's `packageManager`. */\n packageManagerSpec?: string;\n}\n\n/** Everything a project consists of, computed without touching the disk. */\nexport interface ProjectPlan {\n spec: ProjectSpec;\n files: GeneratedFile[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n scripts: Record<string, string>;\n env: EnvVar[];\n /** Compose services the project starts locally. */\n services: string[];\n warnings: string[];\n /** The command that creates this project again. */\n command: string;\n /** The steps to the first run, before anything is installed. */\n nextSteps(state: SetupState): NextStep[];\n}\n\n/** What package.json records under `cogitator` so `cogitator add` can grow the project. */\nexport interface ScaffoldManifest {\n generator: string;\n spec: ProjectSpec;\n command: string;\n}\n\nexport const MANIFEST_KEY = 'cogitator';\n\n/**\n * The project `spec` describes. Throws when the spec is invalid or its parts do\n * not fit together, before anything is generated.\n */\nexport function planProject(input: unknown, options: PlanOptions = {}): ProjectPlan {\n const spec = parseSpec(input);\n assertCompatible(spec);\n\n const project = new ProjectBuilder(spec, { packageManagerSpec: options.packageManagerSpec });\n const active = FEATURE_MODULES.filter((feature) => feature.applies(spec));\n for (const feature of active) feature.apply(project);\n for (const feature of active) feature.finalize?.(project);\n\n const version = scaffolderVersion();\n const command = reproducibleCommand(spec, version);\n const manifest: ScaffoldManifest = {\n generator: `create-cogitator-app@${version}`,\n spec,\n command,\n };\n\n emitAssistant(project);\n emitToolsIndex(project);\n emitRegistry(project);\n emitEnvModule(project);\n emitEnvExample(project);\n emitEnvFile(project, options.secrets ?? {});\n emitCompose(project);\n emitCogitatorYml(project);\n emitPnpmWorkspace(project);\n emitGitignore(project);\n emitAgentsMd(project);\n emitReadme(project);\n adaptImportsForBundler(project);\n emitPackageJson(project, {\n packageManagerSpec: options.packageManagerSpec,\n cogitator: { ...manifest },\n });\n emitDeployArtifacts(project);\n\n const files = [...project.files.values()].sort((a, b) => a.path.localeCompare(b.path));\n return {\n spec,\n files,\n dependencies: Object.fromEntries(\n [...project.dependencies].sort(([a], [b]) => a.localeCompare(b))\n ),\n devDependencies: Object.fromEntries(\n [...project.devDependencies].sort(([a], [b]) => a.localeCompare(b))\n ),\n scripts: Object.fromEntries(project.scripts),\n env: [...project.env.values()],\n services: spec.compose ? [...project.services.keys()] : [],\n warnings: [...project.warnings],\n command,\n nextSteps: (state) => nextSteps(project, state),\n };\n}\n","import { spawn } from 'node:child_process';\n\nexport interface CommandResult {\n code: number;\n output: string;\n}\n\n/** The last `lines` lines of `text`, for error messages that show why a command failed. */\nexport function tail(text: string, lines = 20): string {\n return text.trimEnd().split('\\n').slice(-lines).join('\\n');\n}\n\n/**\n * Runs `command`. Output is captured, or shown live with `inherit`. A command\n * looked up on PATH goes through the shell on Windows, where package managers\n * are `.cmd` shims, unless `shell` is false for an executable given by path.\n * Resolves with the exit code instead of throwing, and rejects only when the\n * command cannot be started at all.\n */\nexport function runCommand(\n command: string,\n args: readonly string[],\n options: {\n cwd: string;\n inherit?: boolean;\n env?: NodeJS.ProcessEnv;\n timeoutMs?: number;\n shell?: boolean;\n }\n): Promise<CommandResult> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: options.env ?? process.env,\n stdio: options.inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'],\n shell: options.shell ?? process.platform === 'win32',\n timeout: options.timeoutMs,\n });\n let output = '';\n child.stdout?.on('data', (chunk: Buffer) => (output += chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => (output += chunk.toString()));\n child.once('error', reject);\n child.once('close', (code, signal) => {\n resolve({ code: code ?? (signal ? 128 : 1), output });\n });\n });\n}\n\n/** Whether `command` can be run, judged by `<command> --version`. */\nexport async function hasCommand(command: string, cwd = process.cwd()): Promise<boolean> {\n try {\n return (await runCommand(command, ['--version'], { cwd, timeoutMs: 10_000 })).code === 0;\n } catch {\n return false;\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { parseDocument } from 'yaml';\nimport { unifiedDiff } from './diff.js';\nimport { AGENT_RULES_BEGIN, AGENT_RULES_END } from './emit.js';\nimport {\n applyOps,\n applyYamlOps,\n deepEqual,\n formatPath,\n merge3,\n parseStructured,\n structuredFormat,\n type MergeOp,\n} from './merge.js';\nimport { MANIFEST_KEY, planProject, type ProjectPlan } from './plan.js';\nimport type { EnvVar } from './project.js';\nimport {\n formatProject,\n hashContent,\n installDependencies,\n readLock,\n silentLogger,\n updateLock,\n type ScaffoldLock,\n type ScaffoldLogger,\n type StepResult,\n} from './scaffold.js';\nimport {\n parseSpec,\n type ChannelKind,\n type CodingAgent,\n type DeployTarget,\n type FeatureId,\n type MemoryKind,\n type ProjectSpec,\n type VectorStore,\n} from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\n/** What `cogitator add` brings into a project. Lists are added to, the rest replaced. */\nexport interface AddChanges {\n features?: readonly FeatureId[];\n channels?: readonly ChannelKind[];\n codingAgents?: readonly CodingAgent[];\n memory?: MemoryKind;\n vectorStore?: VectorStore;\n deploy?: DeployTarget;\n}\n\n/** A file `cogitator add` writes or removes, with the diff against what is on disk. */\nexport interface FileChange {\n path: string;\n kind: 'create' | 'update' | 'delete';\n /** The new content, absent for a deletion. */\n content?: string;\n /** How the content came about: generated as a whole, or merged into the user's copy. */\n source: 'generated' | 'merged';\n diff: string;\n}\n\n/** Something the addition left as it is on purpose. */\nexport interface AddNote {\n message: string;\n path?: string;\n /** The change that was not applied, when there is one. */\n diff?: string;\n}\n\n/** A file the user changed in a way the addition cannot be merged into. */\nexport interface AddConflict {\n path: string;\n reason: string;\n /** The change the addition needs to make to the file as generated. */\n diff: string;\n}\n\nexport interface AddPlan {\n directory: string;\n from: ProjectSpec;\n to: ProjectSpec;\n /** What changes in the spec, one item per line: `feature rag`, `memory sqlite -> postgres`. */\n summary: string[];\n changes: FileChange[];\n conflicts: AddConflict[];\n /** What was left as it is on purpose, and why. */\n notes: AddNote[];\n /** Dependencies the project gains or whose version changes. */\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n /** Dependencies and dev dependencies the merged package.json no longer lists. */\n removedDependencies: string[];\n /** Environment variables the project starts reading. */\n env: EnvVar[];\n /** Compose services the project starts using. */\n services: string[];\n warnings: string[];\n /** The command that creates the project as it is after the addition. */\n command: string;\n /** Whether the project already has everything asked for. */\n upToDate: boolean;\n}\n\nexport interface AddOptions {\n /** Install when the dependencies change (default `true`). */\n install?: boolean;\n log?: ScaffoldLogger;\n /** Show the install's output live instead of capturing it. */\n inheritOutput?: boolean;\n}\n\nexport interface AddResult {\n plan: AddPlan;\n /** Files written, relative to the project. */\n written: string[];\n deleted: string[];\n install: StepResult;\n format: StepResult;\n}\n\n/** Thrown when the project is not one the scaffolder generated, so its parts are unknown. */\nexport class NotAScaffoldedProjectError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NotAScaffoldedProjectError';\n }\n}\n\n/** Thrown when an addition would overwrite changes the user made. Nothing is written. */\nexport class AddConflictError extends Error {\n readonly conflicts: AddConflict[];\n\n constructor(conflicts: AddConflict[]) {\n super(\n [\n `cogitator add would overwrite your changes to ${conflicts.length} file${conflicts.length === 1 ? '' : 's'}, so nothing was written:`,\n ...conflicts.map((conflict) => `- ${conflict.path}: ${conflict.reason}`),\n 'Apply the changes below by hand, or commit your edits elsewhere and restore the generated files, then run cogitator add again.',\n ].join('\\n')\n );\n this.name = 'AddConflictError';\n this.conflicts = conflicts;\n }\n}\n\ninterface ProjectState {\n manifest: Record<string, unknown>;\n spec: ProjectSpec;\n packageManagerSpec?: string;\n generator?: string;\n}\n\nfunction readProject(directory: string): ProjectState {\n const manifestPath = join(directory, 'package.json');\n if (!existsSync(manifestPath)) {\n throw new NotAScaffoldedProjectError(\n `There is no package.json in ${directory}: run cogitator add in the root of the project`\n );\n }\n const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n throw new NotAScaffoldedProjectError(`${manifestPath} is not a package manifest`);\n }\n const record = manifest as Record<string, unknown>;\n const stored = record[MANIFEST_KEY];\n if (typeof stored === 'object' && stored !== null && 'example' in stored && !('spec' in stored)) {\n throw new NotAScaffoldedProjectError(\n `${directory} was created from an example, not generated from a spec, so cogitator add cannot extend it. Generate a project with the features you need instead: npx create-cogitator-app`\n );\n }\n if (typeof stored !== 'object' || stored === null || !('spec' in stored)) {\n throw new NotAScaffoldedProjectError(\n `${directory} was not created by create-cogitator-app: its package.json has no \"${MANIFEST_KEY}\" field, so cogitator add cannot tell what the project contains`\n );\n }\n const spec = parseSpec(stored.spec);\n const generator =\n 'generator' in stored && typeof stored.generator === 'string' ? stored.generator : undefined;\n const packageManagerSpec =\n typeof record.packageManager === 'string' ? record.packageManager : undefined;\n return { manifest: record, spec, packageManagerSpec, generator };\n}\n\nfunction withChanges(spec: ProjectSpec, changes: AddChanges): ProjectSpec {\n return parseSpec({\n ...spec,\n features: [...spec.features, ...(changes.features ?? [])],\n channels: [...spec.channels, ...(changes.channels ?? [])],\n codingAgents: [...spec.codingAgents, ...(changes.codingAgents ?? [])],\n ...(changes.memory && { memory: changes.memory }),\n ...(changes.vectorStore && { vectorStore: changes.vectorStore }),\n ...(changes.deploy && { deploy: changes.deploy }),\n });\n}\n\nfunction describeChanges(from: ProjectSpec, to: ProjectSpec): string[] {\n const added = <T>(before: readonly T[], after: readonly T[]) =>\n after.filter((item) => !before.includes(item));\n return [\n ...added(from.features, to.features).map((feature) => `feature ${feature}`),\n ...added(from.channels, to.channels).map((channel) => `channel ${channel}`),\n ...added(from.codingAgents, to.codingAgents).map((agent) => `coding agent ${agent}`),\n ...(from.memory !== to.memory ? [`memory ${from.memory} -> ${to.memory}`] : []),\n ...(from.vectorStore !== to.vectorStore\n ? [`vector store ${from.vectorStore} -> ${to.vectorStore}`]\n : []),\n ...(from.deploy !== to.deploy ? [`deploy ${from.deploy} -> ${to.deploy}`] : []),\n ];\n}\n\nfunction changedEntries(\n before: Record<string, string>,\n after: Record<string, string>\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(after).filter(([name, value]) => before[name] !== value)\n );\n}\n\n/** Names under `dependencies` and `devDependencies` of a package.json text. */\nfunction dependencyNames(text: string | undefined): Set<string> {\n if (text === undefined) return new Set();\n try {\n const manifest = JSON.parse(text) as Record<string, unknown>;\n const names = (field: unknown) =>\n field && typeof field === 'object' && !Array.isArray(field) ? Object.keys(field) : [];\n return new Set([...names(manifest.dependencies), ...names(manifest.devDependencies)]);\n } catch {\n return new Set();\n }\n}\n\n/**\n * Whether the addition changes what the project depends on, in either\n * direction: the lockfile and the installed tree need an install either way.\n */\nexport function changesDependencies(plan: AddPlan): boolean {\n return (\n Object.keys(plan.dependencies).length > 0 ||\n Object.keys(plan.devDependencies).length > 0 ||\n plan.removedDependencies.length > 0\n );\n}\n\n/** Keys of package.json the scaffolder owns: they always take the generated value. */\nconst OWNED_MANIFEST_KEYS = new Set([MANIFEST_KEY]);\n\n/** Maps whose keys are kept sorted, the way package managers write them. */\nconst SORTED_MANIFEST_MAPS = ['dependencies', 'devDependencies', 'optionalDependencies'];\n\nfunction sortManifest(manifest: unknown): unknown {\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) return manifest;\n const record = manifest as Record<string, unknown>;\n for (const key of SORTED_MANIFEST_MAPS) {\n const map = record[key];\n if (typeof map === 'object' && map !== null && !Array.isArray(map)) {\n record[key] = Object.fromEntries(Object.entries(map).sort(([a], [b]) => a.localeCompare(b)));\n }\n }\n return record;\n}\n\nfunction withoutOwned(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;\n return Object.fromEntries(Object.entries(value).filter(([key]) => !OWNED_MANIFEST_KEYS.has(key)));\n}\n\ntype Decision =\n | { kind: 'none' }\n | { kind: 'change'; change: Omit<FileChange, 'diff'> }\n | { kind: 'conflict'; reason: string }\n | { kind: 'note'; message: string; withDiff?: boolean };\n\ninterface FileInputs {\n path: string;\n base: string | undefined;\n theirs: string | undefined;\n ours: string | undefined;\n /** Whether the file on disk is exactly what the scaffolder wrote. */\n pristine: boolean;\n}\n\nfunction textDecision({ path, base, theirs, ours, pristine }: FileInputs): Decision {\n if (theirs === undefined) {\n if (ours === undefined) return { kind: 'none' };\n if (pristine) return { kind: 'change', change: { path, kind: 'delete', source: 'generated' } };\n return { kind: 'note', message: 'no longer generated, kept because you edited it' };\n }\n if (ours === theirs) return { kind: 'none' };\n if (ours === undefined) {\n if (base === undefined) {\n return {\n kind: 'change',\n change: { path, kind: 'create', content: theirs, source: 'generated' },\n };\n }\n return { kind: 'conflict', reason: 'you deleted it, and the addition changes it' };\n }\n if (base === undefined) {\n return { kind: 'conflict', reason: 'a file of yours is in the way of a new generated file' };\n }\n if (pristine) {\n return {\n kind: 'change',\n change: { path, kind: 'update', content: theirs, source: 'generated' },\n };\n }\n return { kind: 'conflict', reason: 'you edited it, and the addition changes it' };\n}\n\nfunction structuredDecision(inputs: FileInputs): Decision | undefined {\n const { path, base, theirs, ours } = inputs;\n const format = structuredFormat(path);\n if (!format || base === undefined || theirs === undefined || ours === undefined) return undefined;\n const parsed = [base, ours, theirs].map((text) => parseStructured(format, text));\n if (parsed.some((value) => value === undefined)) return undefined;\n const [baseValue, oursValue, theirsValue] = parsed;\n\n const manifest = path === 'package.json';\n const outcome = manifest\n ? merge3(withoutOwned(baseValue), withoutOwned(oursValue), withoutOwned(theirsValue))\n : merge3(baseValue, oursValue, theirsValue);\n if (outcome.conflicts.length > 0) {\n return {\n kind: 'conflict',\n reason: `you changed ${outcome.conflicts.map(formatPath).join(', ')}, and the addition changes it differently`,\n };\n }\n const ops: MergeOp[] = [...outcome.ops];\n if (manifest && typeof theirsValue === 'object' && theirsValue !== null) {\n for (const key of OWNED_MANIFEST_KEYS) {\n const value: unknown = (theirsValue as Record<string, unknown>)[key];\n const current: unknown =\n typeof oursValue === 'object' && oursValue !== null\n ? (oursValue as Record<string, unknown>)[key]\n : undefined;\n if (!deepEqual(value, current)) ops.push({ kind: 'set', path: [key], value });\n }\n }\n if (ops.length === 0) return { kind: 'none' };\n\n let content: string;\n if (format === 'json') {\n const merged = applyOps(oursValue, ops);\n content = JSON.stringify(manifest ? sortManifest(merged) : merged, null, 2) + '\\n';\n } else {\n const doc = parseDocument(ours);\n applyYamlOps(doc, ops);\n content = doc.toString();\n }\n if (content === ours) return { kind: 'none' };\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\n/** The managed block of AGENTS.md, from its begin marker through its end marker. */\nfunction agentRules(text: string): { start: number; end: number } | undefined {\n const start = text.indexOf(AGENT_RULES_BEGIN);\n const endMarker = text.indexOf(AGENT_RULES_END, start);\n if (start === -1 || endMarker === -1) return undefined;\n return { start, end: endMarker + AGENT_RULES_END.length };\n}\n\nfunction agentsMdDecision(inputs: FileInputs): Decision {\n const { path, theirs, ours } = inputs;\n if (ours === undefined || theirs === undefined) return textDecision(inputs);\n const mine = agentRules(ours);\n const generated = agentRules(theirs);\n if (!mine || !generated) {\n return {\n kind: 'note',\n message: `the ${AGENT_RULES_BEGIN} block is gone, so the rules for coding agents were not updated`,\n withDiff: true,\n };\n }\n const content =\n ours.slice(0, mine.start) + theirs.slice(generated.start, generated.end) + ours.slice(mine.end);\n if (content === ours) return { kind: 'none' };\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\nfunction lines(text: string | undefined): string[] {\n return (text ?? '').split('\\n').filter((line) => line.trim() !== '');\n}\n\nfunction gitignoreDecision(inputs: FileInputs): Decision {\n const { path, base, theirs, ours } = inputs;\n if (ours === undefined || theirs === undefined) return textDecision(inputs);\n const present = new Set(lines(ours).map((line) => line.trim()));\n const before = new Set(lines(base).map((line) => line.trim()));\n const added = lines(theirs).filter(\n (line) => !before.has(line.trim()) && !present.has(line.trim())\n );\n if (added.length === 0) return { kind: 'none' };\n const content = `${ours.replace(/\\n*$/, '\\n')}${added.join('\\n')}\\n`;\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\n/** README.md is the user's to rewrite: an edited one is left alone with a note instead of a conflict. */\nfunction readmeDecision(inputs: FileInputs): Decision {\n const decision = textDecision(inputs);\n if (decision.kind !== 'conflict') return decision;\n return {\n kind: 'note',\n message: 'has your edits and was left as it is, the generated change is not applied',\n withDiff: true,\n };\n}\n\nfunction decide(inputs: FileInputs): Decision {\n if (inputs.pristine) return textDecision(inputs);\n if (inputs.path === 'AGENTS.md') return agentsMdDecision(inputs);\n if (inputs.path === '.gitignore') return gitignoreDecision(inputs);\n if (inputs.path === 'README.md') return readmeDecision(inputs);\n return structuredDecision(inputs) ?? textDecision(inputs);\n}\n\nfunction readText(directory: string, path: string): string | undefined {\n const full = join(directory, path);\n return existsSync(full) ? readFileSync(full, 'utf-8') : undefined;\n}\n\nfunction fileMap(plan: ProjectPlan): Map<string, string> {\n return new Map(\n plan.files.filter((file) => file.mode === undefined).map((file) => [file.path, file.content])\n );\n}\n\n/**\n * What adding `changes` to the project in `directory` would do, without\n * writing anything. The project's spec is read from package.json, both the\n * project as it is and as it would be are planned, and what the addition\n * changes between them is merged into the files on disk. A file the user\n * edited takes the change when it can be merged key by key (package.json,\n * cogitator.yml, docker-compose.yml, the managed block of AGENTS.md,\n * .gitignore), and is a conflict otherwise.\n */\nexport function planAdd(directory: string, changes: AddChanges): AddPlan {\n const root = resolve(directory);\n const project = readProject(root);\n const from = project.spec;\n const to = withChanges(from, changes);\n const options = { packageManagerSpec: project.packageManagerSpec };\n const before = planProject(from, options);\n const after = planProject(to, options);\n\n const notes: AddNote[] = [];\n const version = scaffolderVersion();\n if (project.generator && project.generator !== `create-cogitator-app@${version}`) {\n notes.push({\n message: `The project was created by ${project.generator}, the added files come from create-cogitator-app@${version}`,\n });\n }\n const lock: ScaffoldLock | undefined = readLock(root);\n if (!lock) {\n notes.push({\n message:\n 'There is no .cogitator/scaffold.json, so every existing file the addition changes counts as edited by you',\n });\n }\n\n const upToDate = deepEqual(from, to);\n const changesOut: FileChange[] = [];\n const conflicts: AddConflict[] = [];\n if (!upToDate) {\n const baseFiles = fileMap(before);\n const theirFiles = fileMap(after);\n const paths = [...new Set([...baseFiles.keys(), ...theirFiles.keys()])].sort();\n for (const path of paths) {\n const base = baseFiles.get(path);\n const theirs = theirFiles.get(path);\n if (base === theirs) continue;\n const ours = readText(root, path);\n const locked = lock?.files[path];\n const pristine =\n ours !== undefined &&\n (ours === base || (locked !== undefined && hashContent(ours) === locked));\n const decision = decide({ path, base, theirs, ours, pristine });\n if (decision.kind === 'change') {\n changesOut.push({\n ...decision.change,\n diff: unifiedDiff(path, ours, decision.change.content),\n });\n } else if (decision.kind === 'conflict') {\n conflicts.push({ path, reason: decision.reason, diff: unifiedDiff(path, base, theirs) });\n } else if (decision.kind === 'note') {\n notes.push({\n path,\n message: decision.message,\n ...(decision.withDiff && { diff: unifiedDiff(path, base, theirs) }),\n });\n }\n }\n }\n\n const manifest = changesOut.find((change) => change.path === 'package.json');\n const remaining = dependencyNames(manifest?.content);\n const removedDependencies = manifest\n ? [...dependencyNames(readText(root, 'package.json'))]\n .filter((name) => !remaining.has(name))\n .sort()\n : [];\n const knownEnv = new Set(before.env.map((variable) => variable.name));\n return {\n directory: root,\n from,\n to,\n summary: describeChanges(from, to),\n changes: changesOut,\n conflicts,\n notes,\n dependencies: changedEntries(before.dependencies, after.dependencies),\n devDependencies: changedEntries(before.devDependencies, after.devDependencies),\n removedDependencies,\n env: after.env.filter((variable) => !knownEnv.has(variable.name)),\n services: after.services.filter((service) => !before.services.includes(service)),\n warnings: after.warnings.filter((warning) => !before.warnings.includes(warning)),\n command: after.command,\n upToDate,\n };\n}\n\n/** Extensions Biome formats in a generated project. */\nconst FORMATTED = /\\.(?:[cm]?[jt]sx?|json|css)$/;\n\n/**\n * Adds `changes` to the project in `directory`: plans the addition, refuses\n * with an `AddConflictError` when it would overwrite the user's edits, then\n * writes the files, installs new dependencies, formats what it wrote and\n * records the new spec and file hashes. Adding what the project already has\n * changes nothing.\n */\nexport async function addToProject(\n directory: string,\n changes: AddChanges,\n options: AddOptions = {}\n): Promise<AddResult> {\n const log = options.log ?? silentLogger;\n const plan = planAdd(directory, changes);\n const skipped = (reason: string): StepResult => ({ status: 'skipped', reason });\n if (plan.upToDate) {\n return {\n plan,\n written: [],\n deleted: [],\n install: skipped('nothing was added'),\n format: skipped('nothing was added'),\n };\n }\n if (plan.conflicts.length > 0) throw new AddConflictError(plan.conflicts);\n\n log.start('Updating project files');\n const written: string[] = [];\n const deleted: string[] = [];\n for (const change of plan.changes) {\n const target = join(plan.directory, change.path);\n if (change.kind === 'delete') {\n await rm(target, { force: true });\n deleted.push(change.path);\n } else {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, change.content ?? '');\n written.push(change.path);\n }\n }\n log.done(`Updated ${written.length + deleted.length} files`);\n\n const dependenciesChanged = changesDependencies(plan);\n let install = dependenciesChanged\n ? skipped('install was turned off')\n : skipped('the dependencies did not change');\n if (dependenciesChanged && options.install !== false) {\n log.start(`Installing the dependencies with ${plan.to.packageManager}`);\n install = await installDependencies(\n plan.directory,\n plan.to.packageManager,\n options.inheritOutput ?? false\n );\n if (install.status === 'done') log.done('Installed the dependencies');\n else log.fail('Could not install the dependencies');\n }\n\n const format = await formatProject(\n plan.directory,\n written.filter((path) => FORMATTED.test(path))\n );\n if (format.status === 'failed') log.warn(format.error.message);\n\n await updateLock(plan.directory, [...written, ...deleted]);\n return { plan, written, deleted, install, format };\n}\n","/** Lines of context around each change in a unified diff. */\nconst CONTEXT = 3;\n\n/** Above this many line pairs the diff falls back to one hunk that replaces the whole file. */\nconst MAX_CELLS = 4_000_000;\n\ntype Edit = { op: ' ' | '-' | '+'; line: string };\n\nfunction splitLines(text: string): string[] {\n if (text === '') return [];\n const lines = text.split('\\n');\n if (lines.at(-1) === '') lines.pop();\n return lines;\n}\n\n/** The shortest edit script from `a` to `b`, by the longest common subsequence. */\nfunction editScript(a: readonly string[], b: readonly string[]): Edit[] {\n let start = 0;\n while (start < a.length && start < b.length && a[start] === b[start]) start++;\n let endA = a.length;\n let endB = b.length;\n while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {\n endA--;\n endB--;\n }\n const head: Edit[] = a.slice(0, start).map((line) => ({ op: ' ', line }));\n const tail: Edit[] = a.slice(endA).map((line) => ({ op: ' ', line }));\n const midA = a.slice(start, endA);\n const midB = b.slice(start, endB);\n\n if (midA.length * midB.length > MAX_CELLS) {\n return [\n ...head,\n ...midA.map((line): Edit => ({ op: '-', line })),\n ...midB.map((line): Edit => ({ op: '+', line })),\n ...tail,\n ];\n }\n\n const width = midB.length + 1;\n const lcs = new Uint32Array((midA.length + 1) * width);\n for (let i = midA.length - 1; i >= 0; i--) {\n for (let j = midB.length - 1; j >= 0; j--) {\n lcs[i * width + j] =\n midA[i] === midB[j]\n ? lcs[(i + 1) * width + j + 1] + 1\n : Math.max(lcs[(i + 1) * width + j], lcs[i * width + j + 1]);\n }\n }\n\n const middle: Edit[] = [];\n let i = 0;\n let j = 0;\n while (i < midA.length || j < midB.length) {\n if (i < midA.length && j < midB.length && midA[i] === midB[j]) {\n middle.push({ op: ' ', line: midA[i] });\n i++;\n j++;\n } else if (\n i < midA.length &&\n (j === midB.length || lcs[(i + 1) * width + j] >= lcs[i * width + j + 1])\n ) {\n middle.push({ op: '-', line: midA[i] });\n i++;\n } else {\n middle.push({ op: '+', line: midB[j] });\n j++;\n }\n }\n return [...head, ...middle, ...tail];\n}\n\n/**\n * A unified diff from `before` to `after`, as `git diff` prints it, or an\n * empty string when they are equal. A missing side is `undefined`: the file\n * is created or deleted.\n */\nexport function unifiedDiff(\n path: string,\n before: string | undefined,\n after: string | undefined\n): string {\n if (before === after) return '';\n const a = splitLines(before ?? '');\n const b = splitLines(after ?? '');\n const edits = editScript(a, b);\n\n const changed = edits.flatMap((edit, index) => (edit.op === ' ' ? [] : [index]));\n if (changed.length === 0) return '';\n\n const ranges: Array<[number, number]> = [];\n for (const index of changed) {\n const from = Math.max(0, index - CONTEXT);\n const to = Math.min(edits.length, index + CONTEXT + 1);\n const last = ranges.at(-1);\n if (last && from <= last[1]) last[1] = Math.max(last[1], to);\n else ranges.push([from, to]);\n }\n\n const out = [\n `--- ${before === undefined ? '/dev/null' : `a/${path}`}`,\n `+++ ${after === undefined ? '/dev/null' : `b/${path}`}`,\n ];\n let lineA = 1;\n let lineB = 1;\n let cursor = 0;\n for (const [from, to] of ranges) {\n for (; cursor < from; cursor++) {\n if (edits[cursor].op !== '+') lineA++;\n if (edits[cursor].op !== '-') lineB++;\n }\n const hunk = edits.slice(from, to);\n const countA = hunk.filter((edit) => edit.op !== '+').length;\n const countB = hunk.filter((edit) => edit.op !== '-').length;\n out.push(\n `@@ -${countA === 0 ? lineA - 1 : lineA},${countA} +${countB === 0 ? lineB - 1 : lineB},${countB} @@`\n );\n for (const edit of hunk) out.push(`${edit.op}${edit.line}`);\n for (; cursor < to; cursor++) {\n if (edits[cursor].op !== '+') lineA++;\n if (edits[cursor].op !== '-') lineB++;\n }\n }\n return out.join('\\n') + '\\n';\n}\n","import { isMap, parseDocument, type Document, type Pair, type Scalar } from 'yaml';\n\nexport type MergePath = ReadonlyArray<string | number>;\n\n/** One change a three-way merge applies to the user's copy. */\nexport type MergeOp =\n { kind: 'set'; path: MergePath; value: unknown } | { kind: 'delete'; path: MergePath };\n\nexport interface MergeOutcome {\n ops: MergeOp[];\n /** Paths the generator and the user changed in different ways. */\n conflicts: MergePath[];\n}\n\ntype PlainObject = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPrimitiveList(value: unknown): value is Array<string | number | boolean> {\n return (\n Array.isArray(value) &&\n value.every((item) => ['string', 'number', 'boolean'].includes(typeof item))\n );\n}\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const keys = Object.keys(a);\n return (\n keys.length === Object.keys(b).length &&\n keys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]))\n );\n }\n return false;\n}\n\n/**\n * Merges what the generator changed (`base` to `theirs`) into the user's copy\n * (`ours`), the way `git merge` treats a file, but key by key. A key the\n * generator did not change keeps the user's value, a key the user did not\n * change takes the generator's. Lists of plain values merge as sets, so a\n * dependency or a secret added on both sides is kept once. Anything else both\n * sides changed differently is a conflict.\n */\nexport function merge3(\n base: unknown,\n ours: unknown,\n theirs: unknown,\n path: MergePath = []\n): MergeOutcome {\n if (deepEqual(base, theirs) || deepEqual(ours, theirs)) return { ops: [], conflicts: [] };\n\n if ((base === undefined || isPlainObject(base)) && isPlainObject(ours) && isPlainObject(theirs)) {\n const from = base ?? {};\n const outcome: MergeOutcome = { ops: [], conflicts: [] };\n for (const key of new Set([...Object.keys(from), ...Object.keys(theirs)])) {\n const child = merge3(from[key], ours[key], theirs[key], [...path, key]);\n outcome.ops.push(...child.ops);\n outcome.conflicts.push(...child.conflicts);\n }\n return outcome;\n }\n\n if (deepEqual(ours, base)) {\n return {\n ops: [theirs === undefined ? { kind: 'delete', path } : { kind: 'set', path, value: theirs }],\n conflicts: [],\n };\n }\n\n if (\n (base === undefined || isPrimitiveList(base)) &&\n isPrimitiveList(ours) &&\n isPrimitiveList(theirs)\n ) {\n const from = base ?? [];\n const removed = from.filter((item) => !theirs.includes(item));\n const added = theirs.filter((item) => !from.includes(item) && !ours.includes(item));\n const merged = [...ours.filter((item) => !removed.includes(item)), ...added];\n return {\n ops: deepEqual(merged, ours) ? [] : [{ kind: 'set', path, value: merged }],\n conflicts: [],\n };\n }\n\n return { ops: [], conflicts: [path] };\n}\n\n/** `value` with `ops` applied, leaving `value` itself untouched. */\nexport function applyOps(value: unknown, ops: readonly MergeOp[]): unknown {\n let root: unknown = structuredClone(value);\n for (const op of ops) {\n if (op.path.length === 0) {\n root = op.kind === 'set' ? structuredClone(op.value) : undefined;\n continue;\n }\n let node: unknown = root;\n for (const key of op.path.slice(0, -1)) {\n if (!isPlainObject(node)) throw new Error(`Cannot merge into ${formatPath(op.path)}`);\n if (!isPlainObject(node[key])) node[key] = {};\n node = node[key];\n }\n if (!isPlainObject(node)) throw new Error(`Cannot merge into ${formatPath(op.path)}`);\n const last = String(op.path.at(-1));\n if (op.kind === 'set') node[last] = structuredClone(op.value);\n else delete node[last];\n }\n return root;\n}\n\nexport function formatPath(path: MergePath): string {\n return path.length === 0 ? '(the whole file)' : path.join('.');\n}\n\n/**\n * Applies `ops` to a YAML document in place, keeping the user's comments,\n * layout and key order. A new top-level section gets a blank line before it,\n * like the generator writes them.\n */\nexport function applyYamlOps(doc: Document, ops: readonly MergeOp[]): void {\n for (const op of ops) {\n if (op.kind === 'delete') {\n doc.deleteIn(op.path);\n continue;\n }\n const [first] = op.path;\n const contents = doc.contents;\n if (op.path.length === 1 && isMap(contents) && !contents.has(first)) {\n const pair = doc.createPair(first, op.value) as Pair<Scalar, unknown>;\n pair.key.spaceBefore = contents.items.length > 0;\n contents.items.push(pair);\n } else {\n doc.setIn(op.path, doc.createNode(op.value));\n }\n }\n}\n\nexport type StructuredFormat = 'json' | 'yaml';\n\nexport function structuredFormat(path: string): StructuredFormat | undefined {\n if (path.endsWith('.json')) return 'json';\n if (path.endsWith('.yml') || path.endsWith('.yaml')) return 'yaml';\n return undefined;\n}\n\n/** Parses a JSON or YAML file, or `undefined` when it does not parse. */\nexport function parseStructured(format: StructuredFormat, text: string): unknown {\n try {\n if (format === 'json') return JSON.parse(text) as unknown;\n const doc = parseDocument(text);\n return doc.errors.length > 0 ? undefined : (doc.toJS() as unknown);\n } catch {\n return undefined;\n }\n}\n","function distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0];\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const current = row[j];\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));\n previous = current;\n }\n }\n return row[b.length];\n}\n\n/** The candidate closest to `input`, when it is close enough to be a typo of it. */\nexport function closest(input: string, candidates: readonly string[]): string | undefined {\n let best: string | undefined;\n let bestDistance = Infinity;\n for (const candidate of candidates) {\n const d = distance(input.toLowerCase(), candidate.toLowerCase());\n if (d < bestDistance) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best !== undefined && bestDistance <= Math.max(2, Math.floor(input.length / 3))\n ? best\n : undefined;\n}\n","import { pnpmWorkspaceYaml } from './emit.js';\nimport { CodedError } from './errors.js';\nimport type { GeneratedFile } from './project.js';\nimport type { PackageManager } from './spec.js';\nimport { closest } from './suggest.js';\nimport { BUN_ENGINES, NODE_ENGINES, VERSIONS } from './versions.js';\n\n/** An example of the Cogitator repo, as `--example` turns it into a project. Indexed at build time. */\nexport interface ExampleEntry {\n /** `core/basic-agent`: the category and the file name without its number. */\n name: string;\n title: string;\n /** The runnable file, relative to `examples/`. */\n entry: string;\n /** Every file the project needs, relative to `examples/`. */\n files: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n /** Environment variables the files read. */\n env: string[];\n /** What runs the example: Node through tsx, or Bun for examples that use its APIs. */\n runtime: 'node' | 'bun';\n}\n\ndeclare const __COGITATOR_EXAMPLES__: ExampleEntry[] | undefined;\n\nexport const EXAMPLES_REPO = { owner: 'cogitator-ai', repo: 'Cogitator-AI' } as const;\n\n/** The examples indexed when the scaffolder was built, from the `examples/` it is released with. */\nexport function examples(): ExampleEntry[] {\n return typeof __COGITATOR_EXAMPLES__ === 'undefined' ? [] : __COGITATOR_EXAMPLES__;\n}\n\n/** The git tag the examples of a scaffolder version are fetched from. */\nexport function exampleRef(version: string): string {\n return `create-cogitator-app@${version}`;\n}\n\n/** `name#ref` as `--example` takes it. */\nexport function parseExampleArgument(value: string): { query: string; ref?: string } {\n const at = value.indexOf('#');\n if (at === -1) return { query: value.trim() };\n const ref = value.slice(at + 1).trim();\n return { query: value.slice(0, at).trim(), ...(ref && { ref }) };\n}\n\n/**\n * The example `query` names: `core/basic-agent`, its file `core/01-basic-agent`\n * or `core/01-basic-agent.ts`, or just `basic-agent` when only one category\n * has it. Throws with the closest names otherwise.\n */\nexport function findExample(\n query: string,\n index: readonly ExampleEntry[] = examples()\n): ExampleEntry {\n const normalized = query.replace(/^examples\\//, '').replace(/\\.ts$/, '');\n const exact = index.find(\n (example) => example.name === normalized || example.entry.replace(/\\.ts$/, '') === normalized\n );\n if (exact) return exact;\n const short = index.filter((example) => example.name.split('/')[1] === normalized);\n if (short.length === 1) return short[0];\n if (short.length > 1) {\n throw new CodedError(\n 'AMBIGUOUS_EXAMPLE',\n `\"${query}\" is in more than one category: ${short.map((example) => example.name).join(', ')}`\n );\n }\n const names = index.map((example) => example.name);\n const match = closest(normalized, [...names, ...names.map((name) => name.split('/')[1])]);\n const suggestion = match\n ? ` Did you mean \"${names.find((name) => name.endsWith(match)) ?? match}\"?`\n : '';\n throw new CodedError(\n 'UNKNOWN_EXAMPLE',\n `There is no example \"${query}\".${suggestion} Run with --list-examples to see them all.`\n );\n}\n\n/** Where the raw content of `examples/<path>` is at `ref`. */\nexport function exampleFileUrl(ref: string, path: string): string {\n const encodedRef = ref.split('/').map(encodeURIComponent).join('/').replace(/%40/g, '@');\n return `https://raw.githubusercontent.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/${encodedRef}/examples/${path}`;\n}\n\n/** Descriptions of the variables the examples read; anything else is described generically. */\nconst KNOWN_ENV: Record<string, { description: string; example?: string }> = {\n GOOGLE_API_KEY: {\n description:\n 'Google AI Studio key, the default provider of the examples (free tier at https://aistudio.google.com/apikey)',\n },\n OPENAI_API_KEY: { description: 'OpenAI API key, from https://platform.openai.com/api-keys' },\n ANTHROPIC_API_KEY: {\n description: 'Anthropic API key, from https://console.anthropic.com/settings/keys',\n },\n OLLAMA_URL: { description: 'Where Ollama listens', example: 'http://localhost:11434' },\n REDIS_URL: { description: 'Redis connection URL', example: 'redis://localhost:6379' },\n DATABASE_URL: {\n description: 'Postgres connection URL',\n example: 'postgresql://cogitator:cogitator@localhost:5432/cogitator',\n },\n TG_TOKEN: { description: 'Telegram bot token, from @BotFather' },\n OWNER_TG_ID: { description: 'Your Telegram user id, the owner of the bot' },\n WEBCHAT_TOKEN: { description: 'Token WebChat clients authenticate with' },\n WEBCHAT_PORT: { description: 'Port of the WebChat server', example: '8080' },\n DEEPGRAM_API_KEY: { description: 'Deepgram API key for speech to text' },\n ELEVENLABS_API_KEY: { description: 'ElevenLabs API key for text to speech' },\n};\n\n/** Packages that compile native code on install, which pnpm and Bun run only when allowed. */\nconst NATIVE_BUILDS = new Set([\n 'better-sqlite3',\n 'esbuild',\n 'protobufjs',\n 'sharp',\n 'onnxruntime-node',\n]);\n\nexport interface ExamplePlanOptions {\n name: string;\n packageManager: PackageManager;\n version: string;\n ref: string;\n /** Values for `.env`. */\n secrets?: Record<string, string>;\n}\n\nexport interface ExamplePlan {\n example: ExampleEntry;\n ref: string;\n /** Files generated around the example. */\n files: GeneratedFile[];\n /** The example's own files, fetched from GitHub, relative to `examples/`. */\n remoteFiles: string[];\n command: string;\n scripts: Record<string, string>;\n}\n\n/** Where an example file lands in the project: `src/` keeps the layout its relative imports expect. */\nexport function exampleTarget(path: string): string {\n return `src/${path}`;\n}\n\nfunction sorted(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));\n}\n\n/** The project around an example: package.json, tsconfig, .env.example, README and the rest. */\nexport function planExample(example: ExampleEntry, options: ExamplePlanOptions): ExamplePlan {\n const { name, packageManager: pm, version, ref } = options;\n const bun = example.runtime === 'bun';\n const entry = exampleTarget(example.entry);\n const scripts: Record<string, string> = bun\n ? { start: `bun ${entry}`, dev: `bun --watch ${entry}`, typecheck: 'tsc --noEmit' }\n : {\n start: `tsx --env-file-if-exists=.env ${entry}`,\n dev: `tsx watch --env-file-if-exists=.env ${entry}`,\n typecheck: 'tsc --noEmit',\n };\n const devDependencies = sorted({\n ...example.devDependencies,\n typescript: VERSIONS.typescript,\n ...(bun ? { '@types/bun': VERSIONS.typesBun } : { '@types/node': VERSIONS.typesNode }),\n });\n if (bun) delete devDependencies.tsx;\n const command = `npx create-cogitator-app@${version} ${name} --example ${example.name}${ref === exampleRef(version) ? '' : `#${ref}`}`;\n const native = [\n ...new Set([...Object.keys(example.dependencies), ...Object.keys(devDependencies), 'esbuild']),\n ]\n .filter((dep) => NATIVE_BUILDS.has(dep))\n .sort();\n\n const manifest = {\n name,\n version: '0.1.0',\n private: true,\n type: 'module',\n engines: bun ? { bun: BUN_ENGINES } : { node: NODE_ENGINES },\n scripts,\n dependencies: sorted(example.dependencies),\n devDependencies,\n ...(pm === 'bun' && { trustedDependencies: native }),\n cogitator: {\n generator: `create-cogitator-app@${version}`,\n example: { name: example.name, ref },\n command,\n },\n };\n\n const env = example.env.map((variable) => ({\n name: variable,\n ...(KNOWN_ENV[variable] ?? { description: 'Read by the example' }),\n }));\n const envExample = `${[\n '# Copy to .env and fill in what the example needs.',\n '',\n ...env.flatMap((variable) => [\n `# ${variable.description}`,\n `${variable.name}=${variable.example ?? ''}`,\n '',\n ]),\n ]\n .join('\\n')\n .trimEnd()}\\n`;\n\n const run = pm === 'npm' ? 'npm run' : pm;\n const readme = [\n `# ${example.title}`,\n '',\n `The \\`${example.name}\\` example of [Cogitator](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}), as its own project. Its code is \\`${entry}\\`, from [\\`examples/${example.entry}\\`](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/blob/${ref}/examples/${example.entry}) at \\`${ref}\\`.`,\n '',\n '## Run it',\n '',\n '```bash',\n ...(env.length > 0 ? ['cp .env.example .env # then fill in the keys', ''] : []),\n `${run} start`,\n '```',\n '',\n `\\`${run} dev\\` reruns it on change, \\`${run} typecheck\\` checks the types.`,\n ...(env.length > 0\n ? [\n '',\n '## Environment',\n '',\n ...env.map((variable) => `- \\`${variable.name}\\`: ${variable.description}`),\n ]\n : []),\n '',\n '## Learn more',\n '',\n '- [Cogitator docs](https://cogitator.app/docs)',\n `- [All examples](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/tree/${ref}/examples)`,\n '',\n ].join('\\n');\n\n const tsconfig = {\n compilerOptions: {\n target: 'ES2023',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n skipLibCheck: true,\n noEmit: true,\n types: [bun ? 'bun' : 'node'],\n },\n include: ['src'],\n };\n\n const secrets = Object.entries(options.secrets ?? {}).filter(([, value]) => value !== '');\n const files: GeneratedFile[] = [\n { path: 'package.json', content: JSON.stringify(manifest, null, 2) + '\\n' },\n { path: 'tsconfig.json', content: JSON.stringify(tsconfig, null, 2) + '\\n' },\n { path: 'README.md', content: readme },\n {\n path: '.gitignore',\n content: ['node_modules/', 'dist/', '.env', '*.log', '.DS_Store', ''].join('\\n'),\n },\n ...(env.length > 0 ? [{ path: '.env.example', content: envExample }] : []),\n ...(secrets.length > 0\n ? [\n {\n path: '.env',\n content: secrets.map(([key, value]) => `${key}=${value}`).join('\\n') + '\\n',\n mode: 0o600,\n },\n ]\n : []),\n ...(pm === 'pnpm'\n ? [\n {\n path: 'pnpm-workspace.yaml',\n content: pnpmWorkspaceYaml(native),\n },\n ]\n : []),\n ];\n\n return { example, ref, files, remoteFiles: example.files, command, scripts };\n}\n\n/** Fetches the example's own files from GitHub at the plan's ref. */\nexport async function fetchExampleFiles(\n plan: ExamplePlan,\n fetchImpl: typeof fetch = fetch\n): Promise<GeneratedFile[]> {\n return Promise.all(\n plan.remoteFiles.map(async (path) => {\n const url = exampleFileUrl(plan.ref, path);\n const response = await fetchImpl(url, { signal: AbortSignal.timeout(30_000) });\n if (response.status === 404) {\n throw new CodedError(\n 'HTTP_404',\n `examples/${path} is not at ${plan.ref} of ${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}. Pass --example ${plan.example.name}#main for the main branch.`\n );\n }\n if (!response.ok) {\n throw new CodedError(\n `HTTP_${response.status}`,\n `Could not download ${url}: HTTP ${response.status}`\n );\n }\n return { path: exampleTarget(path), content: await response.text() };\n })\n );\n}\n","import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { x as extract } from 'tar';\nimport { CodedError } from './errors.js';\nimport { LOCKFILES } from './package-manager.js';\nimport { PACKAGE_MANAGERS, type PackageManager } from './spec.js';\nimport { cogitatorVersion, type CogitatorPackage } from './versions.js';\n\n/** A template fetched from a GitHub repository instead of generated: `github:owner/repo[/path][#ref]`. */\nexport interface RemoteTemplate {\n owner: string;\n repo: string;\n path?: string;\n ref?: string;\n}\n\nexport function describeTemplate(template: RemoteTemplate): string {\n return `github:${template.owner}/${template.repo}${template.path ? `/${template.path}` : ''}${template.ref ? `#${template.ref}` : ''}`;\n}\n\n/** Above this a download is refused: a template is source, not a dataset. */\nconst MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;\n\n/**\n * Where the archive of `template` is. With a token it goes through the GitHub\n * API, which serves private repositories; without one through codeload.\n */\nexport function templateArchive(\n template: RemoteTemplate,\n token?: string\n): { url: string; headers: Record<string, string> } {\n const ref = template.ref ?? '';\n if (token) {\n return {\n url: `https://api.github.com/repos/${template.owner}/${template.repo}/tarball/${encodeURIComponent(ref)}`,\n headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json' },\n };\n }\n return {\n url: `https://codeload.github.com/${template.owner}/${template.repo}/tar.gz/${encodeURIComponent(ref || 'HEAD')}`,\n headers: {},\n };\n}\n\nexport interface DownloadResult {\n /** Files written, relative to the directory. */\n files: string[];\n /** Entries left out: links and special files, which a template has no business shipping. */\n skipped: string[];\n}\n\n/**\n * Downloads `template` and extracts it, or its `path` inside the repository,\n * into `directory`. Only regular files and directories are written, none\n * outside `directory`.\n */\nexport async function downloadTemplate(\n template: RemoteTemplate,\n directory: string,\n options: { fetch?: typeof fetch; token?: string } = {}\n): Promise<DownloadResult> {\n const { url, headers } = templateArchive(template, options.token);\n const response = await (options.fetch ?? fetch)(url, {\n headers,\n signal: AbortSignal.timeout(120_000),\n });\n if (response.status === 404) {\n throw new CodedError(\n 'HTTP_404',\n `${describeTemplate(template)} was not found: check the repository and the ref${options.token ? '' : ', and set GITHUB_TOKEN for a private repository'}`\n );\n }\n if (!response.ok) {\n throw new CodedError(\n `HTTP_${response.status}`,\n `Could not download ${describeTemplate(template)}: HTTP ${response.status}`\n );\n }\n const length = Number(response.headers.get('content-length') ?? 0);\n if (length > MAX_ARCHIVE_BYTES) {\n throw new CodedError(\n 'TEMPLATE_TOO_LARGE',\n `${describeTemplate(template)} is larger than ${MAX_ARCHIVE_BYTES / 1024 / 1024} MB`\n );\n }\n const archive = Buffer.from(await response.arrayBuffer());\n if (archive.length > MAX_ARCHIVE_BYTES) {\n throw new CodedError(\n 'TEMPLATE_TOO_LARGE',\n `${describeTemplate(template)} is larger than ${MAX_ARCHIVE_BYTES / 1024 / 1024} MB`\n );\n }\n\n const prefix = template.path ? template.path.split('/').filter(Boolean) : [];\n const files: string[] = [];\n const skipped: string[] = [];\n await mkdir(directory, { recursive: true });\n await pipeline(\n Readable.from(archive),\n extract({\n cwd: directory,\n strip: 1 + prefix.length,\n filter: (path, entry) => {\n const inside = path.split('/').slice(1);\n if (!prefix.every((segment, i) => inside[i] === segment)) return false;\n const relative = inside.slice(prefix.length).join('/');\n if (!relative) return false;\n const type = 'type' in entry ? entry.type : entry.isDirectory() ? 'Directory' : 'File';\n if (type === 'File' || type === 'OldFile' || type === 'ContiguousFile') {\n files.push(relative);\n return true;\n }\n if (type === 'Directory') return true;\n skipped.push(relative);\n return false;\n },\n })\n );\n if (files.length === 0) {\n throw new CodedError(\n 'TEMPLATE_EMPTY',\n template.path\n ? `${describeTemplate(template)} has no files under ${template.path}`\n : `${describeTemplate(template)} is empty`\n );\n }\n return { files: files.sort(), skipped: skipped.sort() };\n}\n\nexport interface PreparedTemplate {\n /** The package manager its lockfile belongs to, when it has one. */\n packageManager?: PackageManager;\n /** Dependencies rewritten from `workspace:` to published versions. */\n rewritten: string[];\n}\n\n/**\n * Makes an extracted template a project of its own: package.json gets the\n * project's name, and `workspace:` ranges of `@cogitator-ai/*` packages, which\n * templates from a monorepo carry, become the versions released with the\n * scaffolder. Other workspace and catalog ranges cannot be resolved outside\n * their monorepo and are refused.\n */\nexport function prepareTemplate(directory: string, options: { name: string }): PreparedTemplate {\n const lockfile = PACKAGE_MANAGERS.find((pm) => existsSync(join(directory, LOCKFILES[pm])));\n const manifestPath = join(directory, 'package.json');\n if (!existsSync(manifestPath)) {\n throw new CodedError(\n 'TEMPLATE_NO_MANIFEST',\n `The template has no package.json at its root (it has ${readdirSync(directory).slice(0, 8).join(', ')}): point --template at the project directory`\n );\n }\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<string, unknown>;\n manifest.name = options.name;\n const rewritten: string[] = [];\n const unresolvable: string[] = [];\n for (const field of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const deps = manifest[field];\n if (typeof deps !== 'object' || deps === null) continue;\n const record = deps as Record<string, unknown>;\n for (const [name, range] of Object.entries(record)) {\n if (typeof range !== 'string') continue;\n if (range.startsWith('workspace:') && name.startsWith('@cogitator-ai/')) {\n record[name] = cogitatorVersion(name as CogitatorPackage);\n rewritten.push(name);\n } else if (range.startsWith('workspace:') || range.startsWith('catalog:')) {\n unresolvable.push(`${name}@${range}`);\n }\n }\n }\n if (unresolvable.length > 0) {\n throw new CodedError(\n 'TEMPLATE_WORKSPACE_DEPENDENCIES',\n `The template depends on packages of its own monorepo, which cannot be installed outside it: ${unresolvable.join(', ')}`\n );\n }\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n');\n return { ...(lockfile && { packageManager: lockfile }), rewritten };\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, readdir, rm } from 'node:fs/promises';\nimport { join, relative, resolve } from 'node:path';\nimport {\n exampleRef,\n fetchExampleFiles,\n findExample,\n parseExampleArgument,\n planExample,\n type ExamplePlan,\n} from './examples.js';\nimport { installCommand, runScript } from './package-manager.js';\nimport {\n describeTemplate,\n downloadTemplate,\n prepareTemplate,\n type DownloadResult,\n type PreparedTemplate,\n type RemoteTemplate,\n} from './remote.js';\nimport {\n assertEmptyDirectory,\n initGit,\n installDependencies,\n silentLogger,\n writeFiles,\n type ScaffoldLogger,\n type StepResult,\n} from './scaffold.js';\nimport type { PackageManager } from './spec.js';\nimport type { NextStep } from './project.js';\nimport { scaffolderVersion } from './versions.js';\n\nexport interface StarterOptions {\n directory: string;\n name: string;\n packageManager: PackageManager;\n install?: boolean;\n git?: boolean;\n log?: ScaffoldLogger;\n inheritOutput?: boolean;\n fetch?: typeof fetch;\n}\n\n/** A project made from an example or a remote template instead of the generator. */\nexport interface StarterResult {\n directory: string;\n /** Where it came from: `example core/basic-agent at create-cogitator-app@0.4.0` or `github:owner/repo`. */\n source: string;\n files: string[];\n packageManager: PackageManager;\n install: StepResult;\n git: StepResult;\n /** Commands to the first run. */\n nextSteps: NextStep[];\n notes: string[];\n}\n\nasync function finish(\n directory: string,\n packageManager: PackageManager,\n options: StarterOptions\n): Promise<Pick<StarterResult, 'install' | 'git'>> {\n const log = options.log ?? silentLogger;\n let install: StepResult = { status: 'skipped', reason: 'install was turned off' };\n if (options.install !== false) {\n log.start(`Installing dependencies with ${packageManager}`);\n install = await installDependencies(directory, packageManager, options.inheritOutput ?? false);\n if (install.status === 'done') log.done('Installed dependencies');\n else\n log.fail(`Could not install dependencies, run \"${installCommand(packageManager)}\" yourself`);\n }\n let git: StepResult = { status: 'skipped', reason: 'git was turned off' };\n if (options.git !== false) {\n git = await initGit(directory);\n if (git.status === 'done') log.done('Created a git repository with the first commit');\n else if (git.status === 'failed') log.fail(git.error.message);\n }\n return { install, git };\n}\n\nfunction stepsFor(\n directory: string,\n packageManager: PackageManager,\n scripts: Record<string, string>,\n installed: boolean,\n needsEnv: boolean\n): NextStep[] {\n const where = relative(process.cwd(), directory);\n const steps: NextStep[] = where\n ? [{ command: `cd ${/^[\\w./-]+$/.test(where) ? where : JSON.stringify(where)}` }]\n : [];\n if (!installed) steps.push({ command: installCommand(packageManager) });\n if (needsEnv) steps.push({ command: 'cp .env.example .env', note: 'then fill in the keys' });\n const run = ['dev', 'start'].find((script) => scripts[script]);\n if (run) steps.push({ command: runScript(packageManager, run) });\n return steps;\n}\n\n/** The project `--example` describes, before anything is fetched or written. */\nexport function resolveExample(\n argument: string,\n options: Pick<StarterOptions, 'name' | 'packageManager'> & { secrets?: Record<string, string> }\n): ExamplePlan {\n const { query, ref } = parseExampleArgument(argument);\n const version = scaffolderVersion();\n return planExample(findExample(query), {\n name: options.name,\n packageManager: options.packageManager,\n version,\n ref: ref ?? exampleRef(version),\n secrets: options.secrets,\n });\n}\n\n/**\n * Creates a project from an example of the Cogitator repo: its files at the\n * tag of this scaffolder version (or the ref after `#`), with a package.json,\n * tsconfig, .env.example and README around them.\n */\nexport async function createFromExample(\n plan: ExamplePlan,\n options: StarterOptions\n): Promise<StarterResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n assertEmptyDirectory(directory);\n\n log.start(`Downloading the ${plan.example.name} example from ${plan.ref}`);\n const fetched = await fetchExampleFiles(plan, options.fetch);\n await mkdir(directory, { recursive: true });\n const files = [...plan.files, ...fetched];\n await writeFiles(directory, files);\n log.done(`Wrote ${files.length} files`);\n\n const { install, git } = await finish(directory, options.packageManager, options);\n return {\n directory,\n source: `example ${plan.example.name} at ${plan.ref}`,\n files: files.map((file) => file.path).sort(),\n packageManager: options.packageManager,\n install,\n git,\n nextSteps: stepsFor(\n directory,\n options.packageManager,\n plan.scripts,\n install.status === 'done',\n plan.example.env.length > 0\n ),\n notes: [],\n };\n}\n\n/**\n * Creates a project from a GitHub repository or a directory of one. The\n * repository's lockfile decides the package manager when it has one.\n * Nothing is left behind when the download fails.\n */\nexport async function createFromTemplate(\n template: RemoteTemplate,\n options: StarterOptions & { token?: string }\n): Promise<StarterResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n assertEmptyDirectory(directory);\n const existed = existsSync(directory);\n\n log.start(`Downloading ${describeTemplate(template)}`);\n let downloaded: DownloadResult;\n let prepared: PreparedTemplate;\n try {\n downloaded = await downloadTemplate(template, directory, {\n fetch: options.fetch,\n token: options.token,\n });\n prepared = prepareTemplate(directory, { name: options.name });\n } catch (error) {\n log.fail(`Could not use ${describeTemplate(template)}`);\n if (existed) {\n for (const entry of await readdir(directory)) {\n await rm(join(directory, entry), { recursive: true, force: true });\n }\n } else {\n await rm(directory, { recursive: true, force: true });\n }\n throw error;\n }\n log.done(`Wrote ${downloaded.files.length} files`);\n\n const packageManager = prepared.packageManager ?? options.packageManager;\n const notes = [\n ...(prepared.packageManager && prepared.packageManager !== options.packageManager\n ? [\n `The template has a ${prepared.packageManager} lockfile, so it uses ${prepared.packageManager}`,\n ]\n : []),\n ...(prepared.rewritten.length > 0\n ? [\n `Pinned ${prepared.rewritten.join(', ')} to the versions released with create-cogitator-app@${scaffolderVersion()}`,\n ]\n : []),\n ...(downloaded.skipped.length > 0\n ? [`Left out links and special files: ${downloaded.skipped.join(', ')}`]\n : []),\n ];\n const { install, git } = await finish(directory, packageManager, options);\n const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return {\n directory,\n source: describeTemplate(template),\n files: downloaded.files,\n packageManager,\n install,\n git,\n nextSteps: stepsFor(\n directory,\n packageManager,\n manifest.scripts ?? {},\n install.status === 'done',\n existsSync(join(directory, '.env.example'))\n ),\n notes,\n };\n}\n","import type {\n AppKind,\n ChannelKind,\n CodingAgent,\n DeployTarget,\n FeatureId,\n MemoryKind,\n ServerFramework,\n VectorStore,\n} from './spec.js';\n\nexport interface Choice<T extends string> {\n value: T;\n label: string;\n hint: string;\n}\n\nexport const APP_CHOICES: Choice<AppKind>[] = [\n { value: 'script', label: 'Script', hint: 'an agent you run from the terminal' },\n { value: 'server', label: 'HTTP server', hint: 'agents behind a REST, SSE and WebSocket API' },\n { value: 'next', label: 'Next.js app', hint: 'a streaming chat UI with server-side agents' },\n { value: 'channels', label: 'Messaging bot', hint: 'Telegram, Discord, Slack or WebChat' },\n { value: 'worker', label: 'Queue worker', hint: 'agents run as BullMQ jobs on Redis' },\n];\n\nexport const SERVER_CHOICES: Choice<ServerFramework>[] = [\n { value: 'hono', label: 'Hono', hint: 'small and fast, runs on Node' },\n { value: 'express', label: 'Express', hint: 'the classic, with Swagger UI' },\n { value: 'fastify', label: 'Fastify', hint: 'schema-first and fast' },\n { value: 'koa', label: 'Koa', hint: 'minimal middleware stack' },\n { value: 'tetsu', label: 'Tetsu', hint: 'Bun-native controller with OpenAPI, needs Bun' },\n];\n\nexport const MEMORY_CHOICES: Choice<MemoryKind>[] = [\n { value: 'sqlite', label: 'SQLite', hint: 'a local file, no setup' },\n { value: 'memory', label: 'In-memory', hint: 'forgotten on restart' },\n { value: 'postgres', label: 'Postgres', hint: 'with pgvector, runs in Docker' },\n { value: 'redis', label: 'Redis', hint: 'runs in Docker' },\n { value: 'mongodb', label: 'MongoDB', hint: 'runs in Docker' },\n { value: 'none', label: 'None', hint: 'every run starts from scratch' },\n];\n\nexport const VECTOR_STORE_CHOICES: Choice<VectorStore>[] = [\n { value: 'memory', label: 'In-memory', hint: 're-indexed on start' },\n { value: 'postgres', label: 'Postgres pgvector', hint: 'runs in Docker' },\n { value: 'qdrant', label: 'Qdrant', hint: 'runs in Docker' },\n];\n\nexport const FEATURE_CHOICES: Choice<FeatureId>[] = [\n {\n value: 'harness',\n label: 'Assistant harness',\n hint: 'workspace file tools, approvals, core facts, scheduler',\n },\n { value: 'mcp', label: 'MCP', hint: 'tools from MCP servers, agents served over MCP' },\n { value: 'rag', label: 'RAG', hint: 'answers grounded in your docs/ folder' },\n { value: 'workflows', label: 'Workflows', hint: 'a multi-step DAG pipeline' },\n {\n value: 'durable',\n label: 'Durable workflows',\n hint: 'sagas, approvals, recovery after a crash',\n },\n { value: 'swarms', label: 'Swarms', hint: 'a team of agents with a supervisor' },\n { value: 'evals', label: 'Evals', hint: 'a dataset, metrics and `pnpm eval`' },\n { value: 'otel', label: 'OpenTelemetry', hint: 'traces to any OTLP collector' },\n { value: 'langfuse', label: 'Langfuse', hint: 'traces and costs in Langfuse' },\n { value: 'voice', label: 'Realtime voice', hint: 'a WebSocket voice agent' },\n { value: 'sandbox', label: 'Sandbox', hint: 'run code in Docker or WASM isolation' },\n { value: 'a2a', label: 'A2A', hint: 'expose agents over the Agent-to-Agent protocol' },\n];\n\nexport const DEPLOY_CHOICES: Choice<DeployTarget>[] = [\n { value: 'docker', label: 'Docker', hint: 'a production Dockerfile and compose file' },\n { value: 'fly', label: 'Fly.io', hint: 'Dockerfile and fly.toml' },\n { value: 'none', label: 'None', hint: 'decide later with `cogitator deploy`' },\n];\n\nexport const CHANNEL_CHOICES: Choice<ChannelKind>[] = [\n { value: 'webchat', label: 'WebChat', hint: 'a local WebSocket chat, no setup' },\n { value: 'telegram', label: 'Telegram', hint: 'needs a bot token from @BotFather' },\n { value: 'discord', label: 'Discord', hint: 'needs a bot token' },\n { value: 'slack', label: 'Slack', hint: 'needs a bot token and signing secret' },\n];\n\nexport const CODING_AGENT_CHOICES: Choice<CodingAgent>[] = [\n { value: 'claude', label: 'Claude Code', hint: '.mcp.json and a skill in .claude/skills' },\n { value: 'cursor', label: 'Cursor', hint: '.cursor/mcp.json and a skill in .cursor/skills' },\n { value: 'codex', label: 'Codex', hint: '.codex/config.toml and a skill in .agents/skills' },\n];\n\nexport function choiceLabel<T extends string>(choices: readonly Choice<T>[], value: T): string {\n return choices.find((choice) => choice.value === value)?.label ?? value;\n}\n","import { BUILTIN_MODELS, ModelRegistry, type ModelInfo } from '@cogitator-ai/models';\nimport { listOllamaModels, hasOllamaModel, resolveOllamaUrl } from './ollama.js';\nimport { OLLAMA_SUGGESTED_MODELS, defaultModel } from './providers.js';\nimport type { LLMProvider } from './spec.js';\n\nexport interface ModelChoice {\n /** The model id without the provider prefix. */\n value: string;\n label: string;\n hint?: string;\n}\n\n/** Where the choices came from: the live catalogue, the built-in list, the local Ollama, or a fallback. */\nexport type ModelSource = 'catalog' | 'builtin' | 'ollama' | 'suggested';\n\nexport interface ModelChoices {\n choices: ModelChoice[];\n source: ModelSource;\n}\n\n/** How many models of a cloud provider to offer; the rest are reachable by typing an id. */\nconst MAX_CHOICES = 8;\nconst CATALOG_TIMEOUT_MS = 4_000;\n\nfunction formatPrice(perMillion: number): string {\n return perMillion >= 1\n ? `$${perMillion.toFixed(perMillion % 1 === 0 ? 0 : 2)}`\n : `$${perMillion.toFixed(3).replace(/0+$/, '')}`;\n}\n\nfunction formatContext(tokens: number): string {\n if (tokens >= 1_000_000) return `${+(tokens / 1_000_000).toFixed(1)}M`;\n return `${Math.round(tokens / 1_000)}k`;\n}\n\n/** `$2 in / $10 out per 1M tokens, 1M context`, the line a model choice shows. */\nexport function describeModel(model: Pick<ModelInfo, 'pricing' | 'contextWindow'>): string {\n const { input, output } = model.pricing;\n return `${formatPrice(input)} in / ${formatPrice(output)} out per 1M tokens, ${formatContext(model.contextWindow)} context`;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n timer.unref();\n });\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * The current models of a cloud provider: its built-in lineup from\n * `@cogitator-ai/models`, with prices and context windows refreshed from the\n * live catalogue when it answers in time. The provider's default comes first.\n */\nexport async function cloudModelChoices(\n provider: Exclude<LLMProvider, 'ollama'>,\n options: { timeoutMs?: number; registry?: Pick<ModelRegistry, 'initialize' | 'getModel'> } = {}\n): Promise<ModelChoices> {\n const registry =\n options.registry ?? new ModelRegistry({ cache: { ttl: 24 * 60 * 60 * 1000, storage: 'file' } });\n const loaded = await withTimeout(\n registry.initialize().then(\n () => true,\n () => false\n ),\n options.timeoutMs ?? CATALOG_TIMEOUT_MS\n );\n\n const lineup = BUILTIN_MODELS.filter(\n (model) =>\n model.provider === provider &&\n !model.deprecated &&\n model.capabilities?.supportsTools !== false\n );\n const preferred = defaultModel(provider);\n lineup.sort((a, b) => Number(b.id === preferred) - Number(a.id === preferred));\n\n const choices = lineup.slice(0, MAX_CHOICES).map((builtin) => {\n const model = (loaded && registry.getModel(`${provider}/${builtin.id}`)) || builtin;\n return {\n value: builtin.id,\n label: builtin.displayName,\n hint: `${builtin.id === preferred ? 'recommended, ' : ''}${describeModel(model)}`,\n };\n });\n return { choices, source: loaded ? 'catalog' : 'builtin' };\n}\n\nfunction formatSize(bytes: number): string | undefined {\n return bytes > 0 ? `${(bytes / 1e9).toFixed(1)} GB` : undefined;\n}\n\n/**\n * The models of the local Ollama, with the recommended one first and marked as\n * installed or not. When Ollama does not answer, a list of small models with\n * reliable tool calling to pull.\n */\nexport async function ollamaModelChoices(\n baseUrl: string = resolveOllamaUrl()\n): Promise<ModelChoices> {\n const recommended = defaultModel('ollama');\n const installed = await listOllamaModels(baseUrl);\n if (!installed) {\n return {\n source: 'suggested',\n choices: OLLAMA_SUGGESTED_MODELS.map((name) => ({\n value: name,\n label: name,\n hint: name === recommended ? 'recommended, Ollama is not running' : 'not installed',\n })),\n };\n }\n const others = installed.filter((model) => !hasOllamaModel([model], recommended));\n return {\n source: 'ollama',\n choices: [\n {\n value: recommended,\n label: recommended,\n hint: hasOllamaModel(installed, recommended)\n ? 'recommended, installed'\n : 'recommended, not installed yet',\n },\n ...others.map((model) => ({\n value: model.name,\n label: model.name,\n hint: formatSize(model.size),\n })),\n ],\n };\n}\n\nexport function modelChoices(provider: LLMProvider): Promise<ModelChoices> {\n return provider === 'ollama' ? ollamaModelChoices() : cloudModelChoices(provider);\n}\n","import { DEFAULT_OLLAMA_URL } from './providers.js';\n\nexport interface OllamaModel {\n name: string;\n size: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `value` without the slashes it ends with, in linear time, unlike `replace(/\\/+$/, '')`. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === '/') end--;\n return value.slice(0, end);\n}\n\n/**\n * The Ollama server the generated code talks to: `OLLAMA_BASE_URL`, which it\n * reads, then `OLLAMA_HOST`, which the Ollama CLI reads, then the local default.\n */\nexport function resolveOllamaUrl(env: Record<string, string | undefined> = process.env): string {\n const raw = env.OLLAMA_BASE_URL?.trim() || env.OLLAMA_HOST?.trim();\n if (!raw) return DEFAULT_OLLAMA_URL;\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `http://${raw}`;\n return trimTrailingSlashes(withScheme);\n}\n\n/** The models installed in the Ollama at `baseUrl`, or `undefined` when it does not answer. */\nexport async function listOllamaModels(\n baseUrl: string,\n timeoutMs = 2000\n): Promise<OllamaModel[] | undefined> {\n try {\n const res = await fetch(`${baseUrl}/api/tags`, { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) return undefined;\n const data: unknown = await res.json();\n if (!isRecord(data) || !Array.isArray(data.models)) return undefined;\n return data.models.flatMap((model: unknown) =>\n isRecord(model) && typeof model.name === 'string'\n ? [{ name: model.name, size: typeof model.size === 'number' ? model.size : 0 }]\n : []\n );\n } catch {\n return undefined;\n }\n}\n\nfunction withTag(name: string): string {\n return name.includes(':') ? name : `${name}:latest`;\n}\n\n/** Whether `model` is among `installed`, treating a name without a tag as `:latest` like Ollama does. */\nexport function hasOllamaModel(installed: readonly OllamaModel[], model: string): boolean {\n const wanted = withTag(model);\n return installed.some((m) => withTag(m.name) === wanted);\n}\n\nfunction describeProgress(event: Record<string, unknown>, status: string): string {\n const { completed, total } = event;\n if (typeof completed === 'number' && typeof total === 'number' && total > 0) {\n return `${status} ${Math.floor((completed / total) * 100)}%`;\n }\n return status;\n}\n\nasync function* ndjson(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newline = buffer.indexOf('\\n');\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line) yield JSON.parse(line) as unknown;\n newline = buffer.indexOf('\\n');\n }\n }\n const rest = (buffer + decoder.decode()).trim();\n if (rest) yield JSON.parse(rest) as unknown;\n } finally {\n reader.releaseLock();\n }\n}\n\n/** Pulls `model` into the Ollama at `baseUrl`, reporting each status line; throws when the pull fails. */\nexport async function pullOllamaModel(\n baseUrl: string,\n model: string,\n onStatus: (status: string) => void\n): Promise<void> {\n const res = await fetch(`${baseUrl}/api/pull`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ model, stream: true }),\n });\n if (!res.ok || !res.body) {\n const detail = await res.text().catch(() => '');\n throw new Error(`Failed to pull ${model}: HTTP ${res.status}${detail ? ` ${detail}` : ''}`);\n }\n\n let succeeded = false;\n for await (const event of ndjson(res.body)) {\n if (!isRecord(event)) continue;\n if (typeof event.error === 'string') throw new Error(`Failed to pull ${model}: ${event.error}`);\n if (typeof event.status !== 'string') continue;\n if (event.status === 'success') succeeded = true;\n onStatus(describeProgress(event, event.status));\n }\n\n if (!succeeded) {\n throw new Error(`Failed to pull ${model}: the download stopped before it finished`);\n }\n}\n","import type { LLMProvider } from './spec.js';\n\n/** What checking an API key found out. The key itself never appears in it. */\nexport type KeyCheck =\n | { status: 'valid' }\n | { status: 'rate-limited' }\n | { status: 'invalid'; httpStatus: number }\n | { status: 'unreachable'; reason: string }\n | { status: 'unexpected'; httpStatus: number };\n\ninterface KeyProbe {\n url: string;\n headers(key: string): Record<string, string>;\n}\n\n/**\n * The cheapest authenticated call of each provider: listing models costs no\n * tokens, and the key travels in a header, never in the URL.\n */\nconst PROBES: Record<Exclude<LLMProvider, 'ollama'>, KeyProbe> = {\n openai: {\n url: 'https://api.openai.com/v1/models',\n headers: (key) => ({ authorization: `Bearer ${key}` }),\n },\n anthropic: {\n url: 'https://api.anthropic.com/v1/models?limit=1',\n headers: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),\n },\n google: {\n url: 'https://generativelanguage.googleapis.com/v1beta/models?pageSize=1',\n headers: (key) => ({ 'x-goog-api-key': key }),\n },\n};\n\n/** Checks that `key` is accepted by `provider`, within `timeoutMs`. */\nexport async function checkApiKey(\n provider: Exclude<LLMProvider, 'ollama'>,\n key: string,\n options: { timeoutMs?: number; fetch?: typeof fetch } = {}\n): Promise<KeyCheck> {\n const probe = PROBES[provider];\n const request = options.fetch ?? fetch;\n let response: Response;\n try {\n response = await request(probe.url, {\n headers: probe.headers(key),\n signal: AbortSignal.timeout(options.timeoutMs ?? 8_000),\n });\n } catch (error) {\n const reason =\n error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')\n ? 'the request timed out'\n : 'the provider could not be reached';\n return { status: 'unreachable', reason };\n }\n await response.body?.cancel().catch(() => undefined);\n\n if (response.ok) return { status: 'valid' };\n if (response.status === 401 || response.status === 403) {\n return { status: 'invalid', httpStatus: response.status };\n }\n if (response.status === 429) return { status: 'rate-limited' };\n return { status: 'unexpected', httpStatus: response.status };\n}\n\n/** One line for the user about a key check. */\nexport function describeKeyCheck(envKey: string, check: KeyCheck): string {\n switch (check.status) {\n case 'valid':\n return `${envKey} works`;\n case 'rate-limited':\n return `${envKey} is accepted, but the provider is rate limiting it right now`;\n case 'invalid':\n return `${envKey} was rejected (HTTP ${check.httpStatus}): check the key in .env`;\n case 'unreachable':\n return `Could not check ${envKey}: ${check.reason}`;\n case 'unexpected':\n return `Could not check ${envKey}: the provider answered HTTP ${check.httpStatus}`;\n }\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { constantCase } from './errors.js';\nimport type { StepResult } from './scaffold.js';\nimport type { ProjectSpec } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\ndeclare const __TELEMETRY_WEBSITE_ID__: string | undefined;\n\n/** Where the events go: the Umami instance of the Cogitator project. */\nexport const TELEMETRY_HOST = 'https://analytics.el1fe.com';\nexport const TELEMETRY_DOCS = 'https://cogitator.app/docs/getting-started/telemetry';\nconst SEND_TIMEOUT_MS = 1500;\n\n/**\n * The Umami website the events are counted under, set when the scaffolder is\n * built for a release (`COGITATOR_UMAMI_WEBSITE_ID`). A build without it sends\n * nothing.\n */\nexport function telemetryWebsiteId(): string {\n return typeof __TELEMETRY_WEBSITE_ID__ === 'undefined' ? '' : __TELEMETRY_WEBSITE_ID__;\n}\n\n/**\n * Everything one event carries, and nothing else: no project name, path,\n * model, key or anything a user typed.\n */\nexport interface TelemetryPayload {\n version: string;\n /** The preset, `custom` for a stack picked by hand, `example` or `template` for copied projects. */\n preset: string;\n provider: string;\n memory: string;\n /** The add-ons, comma-separated in catalog order. */\n features: string;\n packageManager: string;\n /** The major version of Node, such as `24`. */\n node: string;\n /** `darwin`, `linux` or `win32`. */\n os: string;\n outcome: 'success' | 'failure';\n /** Where a failure stopped, `none` on success. */\n failedStep: FailedStep | 'none';\n /**\n * Why it stopped, as a code such as `ERR_PNPM_NO_MATCHING_VERSION`,\n * `ENOTFOUND` or `HTTP_404` (see `telemetryErrorCode`), `none` on success.\n */\n errorCode: string;\n}\n\n/**\n * Where a scaffold failed: `create` while making the project (its options,\n * the directory, writing or downloading files), `install` while installing\n * its dependencies.\n */\nexport type FailedStep = 'create' | 'install';\n\n/** A failed scaffold: the step it stopped at and the error it stopped with. */\nexport interface ScaffoldFailure {\n step: FailedStep;\n error: unknown;\n}\n\nexport const PAYLOAD_FIELDS: ReadonlyArray<keyof TelemetryPayload> = [\n 'version',\n 'preset',\n 'provider',\n 'memory',\n 'features',\n 'packageManager',\n 'node',\n 'os',\n 'outcome',\n 'failedStep',\n 'errorCode',\n];\n\nconst VALUE = z.string().regex(/^[\\w.,-]{0,100}$/);\n\n/**\n * An event exactly: the fields above and no other, each a short value of\n * letters, digits and `._,-`. `sendTelemetry` is exported, so anything can be\n * handed to it, and only what passes this is ever sent.\n */\nconst PAYLOAD_SCHEMA: z.ZodType<TelemetryPayload> = z.strictObject({\n version: VALUE,\n preset: VALUE,\n provider: VALUE,\n memory: VALUE,\n features: VALUE,\n packageManager: VALUE,\n node: VALUE,\n os: VALUE,\n outcome: z.enum(['success', 'failure']),\n failedStep: z.enum(['none', 'create', 'install']),\n errorCode: VALUE,\n});\n\nconst SAFE_CODE = /^[A-Z][A-Z0-9_]{1,63}$/;\n\n/**\n * A code for why `error` happened that is safe to send: the `code` of the\n * error or of one of its causes (Node's `ENOTFOUND`, a package manager's\n * `ERR_PNPM_NO_MATCHING_VERSION`, the scaffolder's own `HTTP_404` or\n * `DIRECTORY_NOT_EMPTY`), else the kind of error (`TYPE_ERROR`), else\n * `UNKNOWN`. Never the message, which can hold paths and names.\n */\nexport function telemetryErrorCode(error: unknown): string {\n let kind: string | undefined;\n let current = error;\n for (let depth = 0; depth < 5 && typeof current === 'object' && current !== null; depth++) {\n if ('code' in current && typeof current.code === 'string' && SAFE_CODE.test(current.code))\n return current.code;\n if (\n !kind &&\n current instanceof Error &&\n current.name !== 'Error' &&\n /^[A-Za-z]+$/.test(current.name)\n )\n kind = constantCase(current.name);\n current = 'cause' in current ? current.cause : undefined;\n }\n return kind ?? 'UNKNOWN';\n}\n\n/** The failure of a scaffold whose install step failed, `undefined` when it did not. */\nexport function installFailure(result: { install: StepResult }): ScaffoldFailure | undefined {\n return result.install.status === 'failed'\n ? { step: 'install', error: result.install.error }\n : undefined;\n}\n\n/** The event of a scaffold of `spec`: failed with `failure`, successful without one. */\nexport function payloadFor(\n spec:\n Pick<ProjectSpec, 'preset' | 'provider' | 'memory' | 'features' | 'packageManager'> | undefined,\n failure?: ScaffoldFailure,\n kind: 'generated' | 'example' | 'template' = 'generated'\n): TelemetryPayload {\n return {\n version: scaffolderVersion(),\n preset: kind !== 'generated' ? kind : (spec?.preset ?? 'custom'),\n provider: spec?.provider ?? 'none',\n memory: spec?.memory ?? 'none',\n features: spec?.features.join(',') ?? '',\n packageManager: spec?.packageManager ?? 'unknown',\n node: process.versions.node.split('.')[0],\n os: process.platform,\n outcome: failure ? 'failure' : 'success',\n failedStep: failure?.step ?? 'none',\n errorCode: failure ? telemetryErrorCode(failure.error) : 'none',\n };\n}\n\n/** Why no event is sent, or `undefined` when one is. */\nexport function telemetryDisabledReason(options: {\n flag?: boolean;\n dryRun?: boolean;\n env?: NodeJS.ProcessEnv;\n websiteId?: string;\n}): string | undefined {\n const env = options.env ?? process.env;\n const on = (value: string | undefined) => {\n const normalized = value?.trim().toLowerCase();\n return (\n normalized !== undefined && normalized !== '' && normalized !== '0' && normalized !== 'false'\n );\n };\n if (options.flag === false) return '--no-telemetry';\n if (on(env.COGITATOR_TELEMETRY_DISABLED)) return 'COGITATOR_TELEMETRY_DISABLED';\n if (on(env.DO_NOT_TRACK)) return 'DO_NOT_TRACK';\n if (on(env.CI)) return 'CI';\n if (options.dryRun) return '--dry-run';\n if (!(options.websiteId ?? telemetryWebsiteId())) return 'this build has no telemetry configured';\n return undefined;\n}\n\nfunction configDir(env: NodeJS.ProcessEnv): string {\n if (process.platform === 'win32' && env.APPDATA) return join(env.APPDATA, 'cogitator');\n return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'cogitator');\n}\n\n/**\n * The one line about telemetry shown the first time it is on, or `undefined`\n * when it was shown before. Showing it is remembered in the user's config\n * directory.\n */\nexport function firstRunNotice(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const marker = join(configDir(env), 'telemetry-notice');\n if (existsSync(marker)) return undefined;\n try {\n mkdirSync(configDir(env), { recursive: true });\n writeFileSync(marker, `${new Date().toISOString()}\\n`);\n } catch {\n return undefined;\n }\n return `Cogitator sends one anonymous event per scaffolded project (version, preset, provider, memory, add-ons, package manager, Node major, OS, and where and why it failed if it did). Turn it off with --no-telemetry or COGITATOR_TELEMETRY_DISABLED=1: ${TELEMETRY_DOCS}`;\n}\n\n/** How browsers name each platform, which is what Umami reads the OS from. */\nconst UA_PLATFORMS: Record<string, string> = {\n darwin: 'Macintosh; Intel Mac OS X 10_15_7',\n linux: 'X11; Linux x86_64',\n win32: 'Windows NT 10.0; Win64; x64',\n};\n\n/**\n * The User-Agent of an event. Umami silently drops requests its bot filter\n * (`isbot`) recognizes, and a `Node/` token is one of them, so the Node version\n * travels in the payload only.\n */\nexport function telemetryUserAgent(payload: Pick<TelemetryPayload, 'os' | 'version'>): string {\n return `Mozilla/5.0 (${UA_PLATFORMS[payload.os] ?? payload.os}) create-cogitator-app/${payload.version}`;\n}\n\n/**\n * Sends the event to Umami. It never throws and never takes longer than its\n * timeout: a slow or failing network changes nothing for the scaffolder. A\n * payload that is not exactly an event (another field, a value with a path or\n * a space in it) sends nothing.\n */\nexport async function sendTelemetry(\n payload: TelemetryPayload,\n options: { fetch?: typeof fetch; websiteId?: string; host?: string; timeoutMs?: number } = {}\n): Promise<boolean> {\n const website = options.websiteId ?? telemetryWebsiteId();\n if (!website) return false;\n const parsed = PAYLOAD_SCHEMA.safeParse(payload);\n if (!parsed.success) return false;\n const data = parsed.data;\n const body = {\n type: 'event',\n payload: {\n website,\n hostname: 'create-cogitator-app',\n url: `/scaffold/${data.preset}`,\n name: 'scaffold',\n data,\n },\n };\n try {\n const response = await (options.fetch ?? fetch)(`${options.host ?? TELEMETRY_HOST}/api/send`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'user-agent': telemetryUserAgent(data),\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? SEND_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n","import { relative } from 'node:path';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { IncompatibleSpecError } from '../kit/compat.js';\nimport { checkApiKey, describeKeyCheck } from '../kit/key-check.js';\nimport {\n hasOllamaModel,\n listOllamaModels,\n pullOllamaModel,\n resolveOllamaUrl,\n} from '../kit/ollama.js';\nimport {\n detectPackageManager,\n detectPackageManagerSpec,\n runScript,\n} from '../kit/package-manager.js';\nimport { planProject, type ProjectPlan } from '../kit/plan.js';\nimport { PRESETS } from '../kit/presets.js';\nimport { providerInfo } from '../kit/providers.js';\nimport {\n scaffold,\n type ScaffoldLogger,\n type ScaffoldResult,\n type StepResult,\n} from '../kit/scaffold.js';\nimport { bareModel, parseSpec, type ProjectSpec } from '../kit/spec.js';\nimport {\n firstRunNotice,\n installFailure,\n payloadFor,\n sendTelemetry,\n telemetryDisabledReason,\n type TelemetryPayload,\n} from '../kit/telemetry.js';\nimport { scaffolderVersion } from '../kit/versions.js';\nimport { DOCS_URL } from '../kit/guide.js';\nimport { examples, exampleTarget } from '../kit/examples.js';\nimport { describeTemplate } from '../kit/remote.js';\nimport {\n createFromExample,\n createFromTemplate,\n resolveExample,\n type StarterResult,\n} from '../kit/starter.js';\nimport { CliError, isInteractive, parseCliArgs, type CliArgs } from './args.js';\nimport { exampleList, helpText, presetList } from './help.js';\nimport { askDirectory, askMissing, CancelledError } from './interactive.js';\nimport { DEFAULT_DIRECTORY, resolveDirectory, specFromArgs } from './resolve.js';\n\ninterface Io {\n stdout: (text: string) => void;\n stderr: (text: string) => void;\n}\n\nconst defaultIo: Io = {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n};\n\nfunction banner(version: string): string {\n return `\\n ${pc.bold(pc.cyan('create-cogitator-app'))} ${pc.dim(`v${version}`)} ${pc.dim('Build AI agents in minutes')}\\n`;\n}\n\nfunction clackLogger(): ScaffoldLogger {\n const spinner = p.spinner();\n return {\n start: (message) => spinner.start(message),\n done: (message) => spinner.stop(message),\n fail: (message) => spinner.error(message),\n warn: (message) => p.log.warn(message),\n };\n}\n\nfunction stepJson(step: StepResult): Record<string, string> {\n if (step.status === 'failed') return { status: 'failed', error: step.error.message };\n if (step.status === 'skipped') return { status: 'skipped', reason: step.reason };\n return { status: 'done' };\n}\n\nfunction planJson(plan: ProjectPlan, directory: string) {\n return {\n directory,\n spec: plan.spec,\n command: plan.command,\n files: plan.files.map((file) => file.path),\n dependencies: plan.dependencies,\n devDependencies: plan.devDependencies,\n scripts: plan.scripts,\n services: plan.services,\n env: plan.env.map(({ name, required, secret, description }) => ({\n name,\n required,\n secret,\n description,\n })),\n warnings: plan.warnings,\n };\n}\n\nfunction fileTree(paths: readonly string[]): string {\n return paths\n .map(\n (path) =>\n ` ${pc.dim(path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '')}${path.slice(path.lastIndexOf('/') + 1)}`\n )\n .join('\\n');\n}\n\nfunction describeDryRun(plan: ProjectPlan, directory: string): string {\n const deps = Object.entries(plan.dependencies).map(\n ([name, range]) => ` ${name} ${pc.dim(range)}`\n );\n const devDeps = Object.entries(plan.devDependencies).map(\n ([name, range]) => ` ${name} ${pc.dim(range)}`\n );\n return [\n `${pc.bold('Dry run:')} nothing was written. ${directory} would get:`,\n '',\n pc.bold(`Files (${plan.files.length})`),\n fileTree(plan.files.map((file) => file.path)),\n '',\n pc.bold('Dependencies'),\n ...deps,\n '',\n pc.bold('Dev dependencies'),\n ...devDeps,\n ...(plan.services.length > 0\n ? ['', pc.bold('Compose services'), ` ${plan.services.join(', ')}`]\n : []),\n ...(plan.env.length > 0\n ? [\n '',\n pc.bold('Environment'),\n ...plan.env.map((v) => ` ${v.name}${v.required ? '' : pc.dim(' (optional)')}`),\n ]\n : []),\n '',\n pc.bold('Recreate with'),\n ` ${plan.command}`,\n '',\n ].join('\\n');\n}\n\n/** Pulls the project's Ollama model when it is missing and the user agrees, or reports it. */\nasync function prepareOllama(plan: ProjectPlan, interactive: boolean): Promise<boolean> {\n const model = bareModel(plan.spec);\n const baseUrl = resolveOllamaUrl();\n const installed = await listOllamaModels(baseUrl);\n if (!installed) {\n if (interactive)\n p.log.warn(\n `Ollama is not running at ${baseUrl}. Start it and pull ${model} before the first run.`\n );\n return false;\n }\n if (hasOllamaModel(installed, model)) return true;\n if (!interactive) return false;\n\n const pull = await p.confirm({\n message: `${model} is not in your Ollama yet. Pull it now?`,\n initialValue: true,\n });\n if (p.isCancel(pull) || !pull) return false;\n const spinner = p.spinner();\n spinner.start(`Pulling ${model}`);\n try {\n await pullOllamaModel(baseUrl, model, (status) =>\n spinner.message(`Pulling ${model}: ${status}`)\n );\n spinner.stop(`Pulled ${model}`);\n return true;\n } catch (error) {\n spinner.error(error instanceof Error ? error.message : `Could not pull ${model}`);\n return false;\n }\n}\n\nfunction outro(result: ScaffoldResult, args: CliArgs, modelReady: boolean): string {\n const directory = relative(process.cwd(), result.directory);\n const steps = result.plan.nextSteps({\n directory: directory || undefined,\n installed: result.install.status === 'done',\n keyWritten: args.apiKey !== undefined,\n modelReady,\n });\n return [\n `${pc.green('Your project is ready.')} Next:`,\n '',\n ...steps.map(\n (step) => ` ${pc.cyan(step.command)}${step.note ? pc.dim(` # ${step.note}`) : ''}`\n ),\n '',\n pc.dim(\n `If something does not start, ${runScript(result.plan.spec.packageManager, 'doctor')} says what is missing.`\n ),\n `Try the agents in Cogitator Studio: ${pc.cyan(runScript(result.plan.spec.packageManager, 'dev:studio'))}`,\n pc.dim(`Read AGENTS.md for how it fits together. Docs: ${DOCS_URL}`),\n ].join('\\n');\n}\n\n/** What `run` reaches the network and the environment with, replaceable in tests. */\nexport interface RunDeps {\n fetch?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Where telemetry goes, the release's Umami website by default. */\n telemetry?: { websiteId?: string; host?: string; fetch?: typeof fetch };\n}\n\n/** Sends the run's one telemetry event, waiting at most its timeout. */\nasync function report(enabled: boolean, deps: RunDeps, payload: TelemetryPayload): Promise<void> {\n if (!enabled) return;\n await sendTelemetry(payload, {\n ...(deps.telemetry?.websiteId !== undefined && { websiteId: deps.telemetry.websiteId }),\n ...(deps.telemetry?.host && { host: deps.telemetry.host }),\n ...(deps.telemetry?.fetch && { fetch: deps.telemetry.fetch }),\n });\n}\n\n/** Runs the scaffolder for `argv` and resolves with the exit code. */\nexport async function run(\n argv: readonly string[],\n io: Io = defaultIo,\n deps: RunDeps = {}\n): Promise<number> {\n const version = scaffolderVersion();\n let args: CliArgs;\n try {\n args = parseCliArgs(argv);\n } catch (error) {\n return reportError(error, argv.includes('--json'), io);\n }\n\n if (args.help) {\n io.stdout(helpText(version));\n return 0;\n }\n if (args.version) {\n io.stdout(`${version}\\n`);\n return 0;\n }\n if (args.listTemplates) {\n io.stdout(args.json ? `${JSON.stringify(PRESETS, null, 2)}\\n` : presetList());\n return 0;\n }\n if (args.listExamples) {\n const list = examples().map(({ name, title, entry, runtime }) => ({\n name,\n title,\n entry,\n runtime,\n }));\n io.stdout(args.json ? `${JSON.stringify(list, null, 2)}\\n` : exampleList());\n return 0;\n }\n\n const interactive = isInteractive(args);\n const env = deps.env ?? process.env;\n const telemetry =\n telemetryDisabledReason({\n flag: args.telemetry,\n dryRun: args.dryRun,\n env,\n ...(deps.telemetry?.websiteId !== undefined && { websiteId: deps.telemetry.websiteId }),\n }) === undefined;\n if (telemetry) {\n const notice = firstRunNotice(env);\n if (notice) io.stderr(`${pc.dim(notice)}\\n`);\n }\n\n if (args.example !== undefined || args.remote) {\n const kind = args.example !== undefined ? 'example' : 'template';\n try {\n const created = await runStarter(args, interactive, io, deps);\n if (created)\n await report(telemetry, deps, payloadFor(undefined, installFailure(created), kind));\n return 0;\n } catch (error) {\n if (error instanceof CancelledError) {\n p.cancel('Cancelled, nothing was created.');\n return 1;\n }\n await report(telemetry, deps, payloadFor(undefined, { step: 'create', error }, kind));\n return reportError(error, args.json, io);\n }\n }\n let resolvedSpec: ProjectSpec | undefined;\n let reported = false;\n try {\n if (interactive) {\n io.stderr(banner(version));\n p.intro(pc.cyan(\"Let's build something with agents\"));\n args = await askMissing(args);\n }\n\n const { path: directory, name } = resolveDirectory(args.directory ?? DEFAULT_DIRECTORY);\n const packageManager = args.packageManager ?? detectPackageManager();\n const spec = specFromArgs(args, { name, packageManager });\n resolvedSpec = parseSpec(spec);\n const envKey = providerInfo(spec.provider).envKey;\n const secrets = envKey && args.apiKey ? { [envKey]: args.apiKey } : {};\n const planOptions = {\n secrets,\n packageManagerSpec: detectPackageManagerSpec(spec.packageManager),\n };\n\n if (args.dryRun) {\n const plan = planProject(spec, planOptions);\n if (args.json)\n io.stdout(\n `${JSON.stringify({ ok: true, dryRun: true, ...planJson(plan, directory) }, null, 2)}\\n`\n );\n else io.stdout(describeDryRun(plan, directory));\n return 0;\n }\n\n const result = await scaffold(spec, {\n ...planOptions,\n directory,\n install: args.install ?? true,\n git: args.git ?? true,\n log: args.json ? undefined : clackLogger(),\n });\n\n reported = true;\n await report(telemetry, deps, payloadFor(result.plan.spec, installFailure(result)));\n\n const modelReady =\n result.plan.spec.provider === 'ollama' ? await prepareOllama(result.plan, interactive) : true;\n\n const key = envKey ? (args.apiKey ?? process.env[envKey]) : undefined;\n const provider = result.plan.spec.provider;\n let keyCheck: string | undefined;\n if (envKey && key && provider !== 'ollama') {\n keyCheck = describeKeyCheck(envKey, await checkApiKey(provider, key, { fetch: deps.fetch }));\n }\n\n if (args.json) {\n io.stdout(\n `${JSON.stringify(\n {\n ok: true,\n dryRun: false,\n ...planJson(result.plan, result.directory),\n steps: {\n install: stepJson(result.install),\n format: stepJson(result.format),\n git: stepJson(result.git),\n },\n modelReady,\n ...(keyCheck && { keyCheck }),\n ...(result.parentWorkspace && { parentWorkspace: result.parentWorkspace }),\n },\n null,\n 2\n )}\\n`\n );\n return 0;\n }\n\n if (keyCheck) p.log.info(keyCheck);\n if (result.parentWorkspace) {\n p.log.info(\n `The project is inside the workspace at ${result.parentWorkspace}. Add ${relative(result.parentWorkspace, result.directory)} to its workspace packages to share one install.`\n );\n }\n for (const warning of result.plan.warnings) p.log.warn(warning);\n if (interactive) p.outro(outro(result, args, modelReady));\n else io.stderr(`${outro(result, args, modelReady)}\\n`);\n return 0;\n } catch (error) {\n if (error instanceof CancelledError) {\n p.cancel('Cancelled, nothing was created.');\n return 1;\n }\n if (resolvedSpec && !reported)\n await report(telemetry, deps, payloadFor(resolvedSpec, { step: 'create', error }));\n return reportError(error, args.json, io);\n }\n}\n\nfunction starterOutro(result: StarterResult): string {\n return [\n `${pc.green('Your project is ready.')} ${pc.dim(`From ${result.source}.`)} Next:`,\n '',\n ...result.nextSteps.map(\n (step) => ` ${pc.cyan(step.command)}${step.note ? pc.dim(` # ${step.note}`) : ''}`\n ),\n '',\n pc.dim(`Docs: ${DOCS_URL}`),\n ].join('\\n');\n}\n\n/**\n * `--example` and remote `--template`: a project copied from source instead of\n * generated. Resolves with what was created, `undefined` on a dry run.\n */\nasync function runStarter(\n args: CliArgs,\n interactive: boolean,\n io: Io,\n deps: RunDeps\n): Promise<StarterResult | undefined> {\n const ignored = (\n [\n ['--app', args.app],\n ['--server', args.server],\n ['--channels', args.channels],\n ['--memory', args.memory],\n ['--vector-store', args.vectorStore],\n ['--features', args.features],\n ['--deploy', args.deploy],\n ['--model', args.model],\n ['--agent', args.codingAgents],\n ['--[no-]docker', args.compose],\n ] as const\n )\n .filter(([, value]) => value !== undefined)\n .map(([flag]) => flag);\n if (ignored.length > 0) {\n throw new CliError(\n `${args.example !== undefined ? '--example' : 'A github: --template'} copies a project as it is, so ${ignored.join(', ')} do not apply: leave them out.`\n );\n }\n if (interactive) {\n io.stderr(banner(scaffolderVersion()));\n p.intro(pc.cyan(\"Let's build something with agents\"));\n }\n const directoryArg = args.directory ?? (interactive ? await askDirectory() : DEFAULT_DIRECTORY);\n const { path: directory, name } = resolveDirectory(directoryArg);\n const packageManager = args.packageManager ?? detectPackageManager();\n const options = {\n directory,\n name,\n packageManager,\n install: args.install ?? true,\n git: args.git ?? true,\n log: args.json ? undefined : clackLogger(),\n fetch: deps.fetch,\n };\n\n let result: StarterResult;\n if (args.example !== undefined) {\n const envKey = providerInfo(args.provider ?? 'google').envKey;\n const secrets = envKey && args.apiKey ? { [envKey]: args.apiKey } : {};\n const plan = resolveExample(args.example, { name, packageManager, secrets });\n if (args.dryRun) {\n const files = [\n ...plan.files.map((file) => file.path),\n ...plan.remoteFiles.map(exampleTarget),\n ].sort();\n if (args.json) {\n io.stdout(\n `${JSON.stringify({ ok: true, dryRun: true, directory, example: plan.example, ref: plan.ref, command: plan.command, files }, null, 2)}\\n`\n );\n } else {\n io.stdout(\n [\n `${pc.bold('Dry run:')} nothing was written. ${directory} would get the ${plan.example.name} example from ${plan.ref}:`,\n '',\n fileTree(files),\n '',\n pc.bold('Dependencies'),\n ...Object.entries(plan.example.dependencies).map(\n ([dep, range]) => ` ${dep} ${pc.dim(range)}`\n ),\n '',\n ].join('\\n')\n );\n }\n return undefined;\n }\n result = await createFromExample(plan, options);\n } else if (args.remote) {\n if (args.dryRun) {\n const message = `${directory} would get ${describeTemplate(args.remote)}`;\n io.stdout(\n args.json\n ? `${JSON.stringify({ ok: true, dryRun: true, directory, template: args.remote }, null, 2)}\\n`\n : `${pc.bold('Dry run:')} nothing was written. ${message}.\\n`\n );\n return undefined;\n }\n result = await createFromTemplate(args.remote, {\n ...options,\n token: process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN,\n });\n } else {\n throw new CliError('Pass --example or a github: --template');\n }\n\n if (args.json) {\n io.stdout(\n `${JSON.stringify(\n {\n ok: true,\n dryRun: false,\n directory: result.directory,\n source: result.source,\n files: result.files,\n packageManager: result.packageManager,\n steps: { install: stepJson(result.install), git: stepJson(result.git) },\n nextSteps: result.nextSteps,\n notes: result.notes,\n },\n null,\n 2\n )}\\n`\n );\n return result;\n }\n for (const note of result.notes) p.log.info(note);\n if (interactive) p.outro(starterOutro(result));\n else io.stderr(`${starterOutro(result)}\\n`);\n return result;\n}\n\nfunction reportError(error: unknown, json: boolean, io: Io): number {\n const message = error instanceof Error ? error.message : String(error);\n if (json) {\n const issues = error instanceof IncompatibleSpecError ? error.issues : undefined;\n io.stdout(\n `${JSON.stringify({ ok: false, error: { message, ...(issues && { issues }) } }, null, 2)}\\n`\n );\n } else if (error instanceof CliError || error instanceof IncompatibleSpecError) {\n io.stderr(`${pc.red('Error:')} ${message}\\n`);\n } else {\n io.stderr(`${pc.red('Error:')} ${message}\\n`);\n if (process.env.DEBUG && error instanceof Error && error.stack) io.stderr(`${error.stack}\\n`);\n }\n return 1;\n}\n","import { parseArgs, type ParseArgsConfig } from 'node:util';\nimport { presetIds, findPreset } from '../kit/presets.js';\nimport {\n APP_KINDS,\n CHANNELS,\n CODING_AGENTS,\n DEPLOY_TARGETS,\n FEATURES,\n MEMORIES,\n PACKAGE_MANAGERS,\n PROVIDERS,\n SERVERS,\n VECTOR_STORES,\n type AppKind,\n type ChannelKind,\n type CodingAgent,\n type DeployTarget,\n type FeatureId,\n type LLMProvider,\n type MemoryKind,\n type PackageManager,\n type ServerFramework,\n type VectorStore,\n} from '../kit/spec.js';\nimport type { RemoteTemplate } from '../kit/remote.js';\nimport { closest } from '../kit/suggest.js';\n\nexport { closest };\n\n/** A usage mistake: shown without a stack trace, exits with code 1. */\nexport class CliError extends Error {\n readonly code = 'INVALID_ARGS';\n\n constructor(message: string) {\n super(message);\n this.name = 'CliError';\n }\n}\n\nexport type { RemoteTemplate };\n\nexport interface CliArgs {\n directory?: string;\n preset?: string;\n remote?: RemoteTemplate;\n example?: string;\n app?: AppKind;\n server?: ServerFramework;\n channels?: ChannelKind[];\n memory?: MemoryKind;\n vectorStore?: VectorStore;\n features?: FeatureId[];\n deploy?: DeployTarget;\n compose?: boolean;\n provider?: LLMProvider;\n model?: string;\n apiKey?: string;\n packageManager?: PackageManager;\n codingAgents?: CodingAgent[];\n git?: boolean;\n install?: boolean;\n telemetry?: boolean;\n yes: boolean;\n dryRun: boolean;\n json: boolean;\n help: boolean;\n version: boolean;\n listTemplates: boolean;\n listExamples: boolean;\n}\n\nconst OPTIONS = {\n preset: { type: 'string', short: 't' },\n template: { type: 'string' },\n example: { type: 'string' },\n app: { type: 'string' },\n server: { type: 'string' },\n channels: { type: 'string', multiple: true },\n memory: { type: 'string' },\n 'vector-store': { type: 'string' },\n features: { type: 'string', multiple: true },\n with: { type: 'string', multiple: true },\n deploy: { type: 'string' },\n docker: { type: 'boolean' },\n provider: { type: 'string', short: 'p' },\n model: { type: 'string', short: 'm' },\n 'api-key': { type: 'string' },\n pm: { type: 'string' },\n agent: { type: 'string', multiple: true },\n git: { type: 'boolean' },\n install: { type: 'boolean' },\n telemetry: { type: 'boolean' },\n yes: { type: 'boolean', short: 'y' },\n 'dry-run': { type: 'boolean' },\n json: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n 'list-templates': { type: 'boolean' },\n 'list-presets': { type: 'boolean' },\n 'list-examples': { type: 'boolean' },\n} as const satisfies NonNullable<ParseArgsConfig['options']>;\n\nconst OPTION_NAMES = Object.keys(OPTIONS);\n\nfunction suggestion(input: string, candidates: readonly string[]): string {\n const match = closest(input, candidates);\n return match ? ` Did you mean \"${match}\"?` : '';\n}\n\nfunction oneOf<T extends string>(flag: string, value: string, allowed: readonly T[]): T {\n const found = allowed.find((candidate) => candidate === value);\n if (found) return found;\n throw new CliError(\n `Invalid --${flag} \"${value}\".${suggestion(value, allowed)} Use one of: ${allowed.join(', ')}.`\n );\n}\n\n/** Values of a list option, given repeated (`--x a --x b`) or comma separated (`--x a,b`). */\nfunction listOf<T extends string>(\n flag: string,\n values: readonly string[],\n allowed: readonly T[]\n): T[] {\n const items = values\n .flatMap((value) => value.split(','))\n .map((item) => item.trim())\n .filter(Boolean);\n return [...new Set(items.map((item) => oneOf(flag, item, allowed)))];\n}\n\n/** Parses `github:owner/repo`, `github:owner/repo/sub/dir` and an optional `#ref`. */\nexport function parseRemoteTemplate(value: string): RemoteTemplate {\n const match =\n /^(?:github:|https:\\/\\/github\\.com\\/)([\\w.-]+)\\/([\\w.-]+?)(?:\\.git)?(?:\\/((?:[\\w.-]+\\/)*[\\w.-]+)\\/?)?(?:#([^\\s~^:?*[\\\\]+))?$/.exec(\n value\n );\n if (!match) {\n throw new CliError(\n `Invalid remote template \"${value}\". Use github:owner/repo, github:owner/repo/path or github:owner/repo#ref.`\n );\n }\n const [, owner, repo, path, ref] = match;\n return {\n owner,\n repo,\n ...(path && { path: path.replace(/\\/$/, '') }),\n ...(ref && { ref }),\n };\n}\n\nfunction isRemote(value: string): boolean {\n return value.startsWith('github:') || value.startsWith('https://github.com/');\n}\n\n/**\n * Parses the command line. Unknown options and invalid values are errors,\n * also with `--yes`: a typo never silently becomes a default.\n */\nexport function parseCliArgs(argv: readonly string[]): CliArgs {\n let parsed;\n try {\n parsed = parseArgs({\n args: [...argv],\n options: OPTIONS,\n allowPositionals: true,\n allowNegative: true,\n strict: true,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const unknown = /Unknown option '(--?[\\w-]+)'/.exec(message)?.[1];\n if (unknown) {\n const name = unknown.replace(/^--?/, '');\n const hint = closest(name, OPTION_NAMES);\n throw new CliError(\n `Unknown option ${unknown}.${hint ? ` Did you mean --${hint}?` : ''} Run with --help for the options.`\n );\n }\n throw new CliError(`${message.replace(/\\.$/, '')}. Run with --help for the options.`);\n }\n\n const { values, positionals } = parsed;\n if (positionals.length > 1) {\n throw new CliError(\n `Expected one project directory, got ${positionals.length}: ${positionals.join(' ')}. Quote a path with spaces.`\n );\n }\n\n const presetValue = values.preset ?? values.template;\n if (\n values.preset !== undefined &&\n values.template !== undefined &&\n values.preset !== values.template\n ) {\n throw new CliError('--preset and --template name different presets, pass only one of them.');\n }\n\n let preset: string | undefined;\n let remote: RemoteTemplate | undefined;\n if (presetValue !== undefined) {\n if (isRemote(presetValue)) {\n remote = parseRemoteTemplate(presetValue);\n } else {\n const found = findPreset(presetValue);\n if (!found) {\n throw new CliError(\n `Unknown preset \"${presetValue}\".${suggestion(presetValue, presetIds())} Run with --list-templates to see them all.`\n );\n }\n preset = found.id;\n }\n }\n if (remote && values.example !== undefined) {\n throw new CliError('--example and a remote --template cannot be combined.');\n }\n if (values.example !== undefined && preset) {\n throw new CliError('--example replaces the preset, pass only one of --example and --preset.');\n }\n\n const features = [...(values.features ?? []), ...(values.with ?? [])];\n const apiKey = values['api-key'];\n if (apiKey !== undefined && !apiKey.trim()) throw new CliError('--api-key is empty.');\n const model = values.model?.trim();\n if (values.model !== undefined && !model) throw new CliError('--model is empty.');\n\n return {\n ...(positionals[0] !== undefined && { directory: positionals[0] }),\n ...(preset && { preset }),\n ...(remote && { remote }),\n ...(values.example !== undefined && { example: values.example }),\n ...(values.app !== undefined && { app: oneOf('app', values.app, APP_KINDS) }),\n ...(values.server !== undefined && { server: oneOf('server', values.server, SERVERS) }),\n ...(values.channels && { channels: listOf('channels', values.channels, CHANNELS) }),\n ...(values.memory !== undefined && { memory: oneOf('memory', values.memory, MEMORIES) }),\n ...(values['vector-store'] !== undefined && {\n vectorStore: oneOf('vector-store', values['vector-store'], VECTOR_STORES),\n }),\n ...(features.length > 0 && { features: listOf('features', features, FEATURES) }),\n ...(values.deploy !== undefined && { deploy: oneOf('deploy', values.deploy, DEPLOY_TARGETS) }),\n ...(values.docker !== undefined && { compose: values.docker }),\n ...(values.provider !== undefined && {\n provider: oneOf('provider', values.provider, PROVIDERS),\n }),\n ...(model && { model }),\n ...(apiKey !== undefined && { apiKey: apiKey.trim() }),\n ...(values.pm !== undefined && { packageManager: oneOf('pm', values.pm, PACKAGE_MANAGERS) }),\n ...(values.agent && {\n codingAgents: listOf(\n 'agent',\n values.agent.filter((a) => a !== 'none'),\n CODING_AGENTS\n ),\n }),\n ...(values.git !== undefined && { git: values.git }),\n ...(values.install !== undefined && { install: values.install }),\n ...(values.telemetry !== undefined && { telemetry: values.telemetry }),\n yes: values.yes ?? false,\n dryRun: values['dry-run'] ?? false,\n json: values.json ?? false,\n help: values.help ?? false,\n version: values.version ?? false,\n listTemplates: (values['list-templates'] ?? false) || (values['list-presets'] ?? false),\n listExamples: values['list-examples'] ?? false,\n };\n}\n\n/**\n * Whether to ask questions: only at a terminal, and never with `--yes`,\n * `--json` or in CI, where nobody can answer.\n */\nexport function isInteractive(\n args: Pick<CliArgs, 'yes' | 'json'>,\n env: NodeJS.ProcessEnv = process.env,\n stdin: { isTTY?: boolean } = process.stdin\n): boolean {\n if (args.yes || args.json) return false;\n if (env.CI && env.CI !== 'false' && env.CI !== '0') return false;\n return stdin.isTTY === true;\n}\n","import pc from 'picocolors';\nimport {\n APP_CHOICES,\n CHANNEL_CHOICES,\n CODING_AGENT_CHOICES,\n DEPLOY_CHOICES,\n FEATURE_CHOICES,\n MEMORY_CHOICES,\n SERVER_CHOICES,\n VECTOR_STORE_CHOICES,\n type Choice,\n} from '../kit/catalog.js';\nimport { DEFAULT_PRESET, PRESETS } from '../kit/presets.js';\nimport { examples } from '../kit/examples.js';\nimport { PACKAGE_MANAGERS, PROVIDERS } from '../kit/spec.js';\n\nfunction values(choices: readonly Choice<string>[]): string {\n return choices.map((choice) => choice.value).join(', ');\n}\n\nfunction row(flag: string, description: string): string {\n return ` ${pc.cyan(flag.padEnd(28))} ${description}`;\n}\n\nexport function helpText(version: string): string {\n return [\n `${pc.bold('create-cogitator-app')} ${pc.dim(`v${version}`)}`,\n '',\n 'Create a Cogitator AI agent project.',\n '',\n `${pc.bold('Usage')}`,\n ' npx create-cogitator-app [directory] [options]',\n '',\n `${pc.bold('Stack')}`,\n row(\n '-t, --preset <name>',\n `a named starting point (default ${DEFAULT_PRESET}), see --list-templates`\n ),\n row(\n ' --template <name|repo>',\n 'a preset, or github:owner/repo[/path][#ref] to copy a repository'\n ),\n row(\n ' --example <name[#ref]>',\n 'a runnable example of the Cogitator repo, see --list-examples'\n ),\n row(' --app <kind>', values(APP_CHOICES)),\n row(' --server <framework>', values(SERVER_CHOICES)),\n row(' --channels <list>', values(CHANNEL_CHOICES)),\n row(' --memory <kind>', values(MEMORY_CHOICES)),\n row(' --vector-store <store>', `for RAG: ${values(VECTOR_STORE_CHOICES)}`),\n row(' --features <list>', `added to the preset's: ${values(FEATURE_CHOICES)}`),\n row(' --deploy <target>', values(DEPLOY_CHOICES)),\n row(' --[no-]docker', 'write docker-compose.yml for local services (default yes)'),\n '',\n `${pc.bold('Model')}`,\n row('-p, --provider <name>', PROVIDERS.join(', ')),\n row(\n '-m, --model <id>',\n \"the model id at the provider, e.g. gpt-6.1-sol, default: the provider's\"\n ),\n row(' --api-key <key>', 'written to .env (mode 600) and never printed'),\n '',\n `${pc.bold('Tooling')}`,\n row(' --pm <name>', `${PACKAGE_MANAGERS.join(', ')} (default: the one running this)`),\n row(' --agent <list>', `coding agent setup: ${values(CODING_AGENT_CHOICES)}, none`),\n row(' --[no-]git', 'create a git repository with the first commit (default yes)'),\n row(' --[no-]install', 'install dependencies (default yes)'),\n row(' --no-telemetry', 'send no anonymous usage event, see the docs'),\n '',\n `${pc.bold('Output')}`,\n row('-y, --yes', 'ask nothing, use defaults for whatever the flags leave out'),\n row(' --dry-run', 'show the files and dependencies without writing anything'),\n row(' --json', 'print the result as JSON, implies --yes'),\n row(' --list-templates', 'list the presets'),\n row(' --list-examples', 'list the examples --example takes'),\n row('-h, --help', 'show this help'),\n row('-v, --version', 'show the version'),\n '',\n `${pc.bold('Examples')}`,\n ' npx create-cogitator-app my-bot --preset channels --channels telegram',\n ' npx create-cogitator-app api --app server --server fastify --memory postgres --features rag,evals',\n ' npx create-cogitator-app . --provider anthropic --api-key \"$ANTHROPIC_API_KEY\" --yes',\n ' npx create-cogitator-app demo --preset nextjs --dry-run --json',\n ' npx create-cogitator-app tutor --example core/basic-agent',\n ' npx create-cogitator-app bot --template github:acme/agent-templates/support-bot#v2',\n '',\n 'Without a TTY or with CI set, nothing is asked: flags and defaults decide everything.',\n '',\n ].join('\\n');\n}\n\nexport function presetList(): string {\n const width = Math.max(...PRESETS.map((preset) => preset.id.length));\n return (\n PRESETS.map(\n (preset) => ` ${pc.cyan(preset.id.padEnd(width))} ${preset.label}: ${pc.dim(preset.hint)}`\n ).join('\\n') + '\\n'\n );\n}\n\nexport function exampleList(): string {\n const all = examples();\n const width = Math.max(...all.map((example) => example.name.length));\n return (\n all\n .map((example) => ` ${pc.cyan(example.name.padEnd(width))} ${pc.dim(example.title)}`)\n .join('\\n') + '\\n'\n );\n}\n","import { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n APP_CHOICES,\n CHANNEL_CHOICES,\n CODING_AGENT_CHOICES,\n DEPLOY_CHOICES,\n FEATURE_CHOICES,\n MEMORY_CHOICES,\n SERVER_CHOICES,\n VECTOR_STORE_CHOICES,\n} from '../kit/catalog.js';\nimport { modelChoices } from '../kit/models.js';\nimport { DEFAULT_PRESET, PRESETS } from '../kit/presets.js';\nimport { PROVIDER_INFO, providerInfo } from '../kit/providers.js';\nimport { PROVIDERS, validateProjectName, type CodingAgent } from '../kit/spec.js';\nimport type { CliArgs } from './args.js';\nimport { DEFAULT_DIRECTORY, projectNameFromDirectory } from './resolve.js';\n\nexport class CancelledError extends Error {\n constructor() {\n super('Cancelled');\n this.name = 'CancelledError';\n }\n}\n\n/** The answer to a prompt, or a CancelledError when the user pressed Ctrl+C. */\nfunction answer<T>(value: T): Exclude<T, symbol> {\n if (p.isCancel(value)) throw new CancelledError();\n return value as Exclude<T, symbol>;\n}\n\nconst CUSTOM = '__custom__';\nconst OTHER_MODEL = '__other__';\n\n/** Coding agents whose config directory exists in the home directory, offered preselected. */\nexport function detectCodingAgents(home: string = homedir()): CodingAgent[] {\n const markers: Record<CodingAgent, string> = {\n claude: '.claude',\n cursor: '.cursor',\n codex: '.codex',\n };\n return CODING_AGENT_CHOICES.map((choice) => choice.value).filter((agent) =>\n existsSync(join(home, markers[agent]))\n );\n}\n\n/**\n * Asks for everything the flags left open and returns the flags completed with\n * the answers. Anything given as a flag is not asked again.\n */\n/** Asks where the project goes. */\nexport async function askDirectory(): Promise<string> {\n return answer(\n await p.text({\n message: 'Where should the project go?',\n placeholder: `./${DEFAULT_DIRECTORY}`,\n defaultValue: DEFAULT_DIRECTORY,\n validate: (value) =>\n value?.trim() ? validateProjectName(projectNameFromDirectory(value)) : undefined,\n })\n ).trim();\n}\n\nexport async function askMissing(args: CliArgs): Promise<CliArgs> {\n const next: CliArgs = { ...args };\n\n if (next.directory === undefined) next.directory = await askDirectory();\n\n if (next.preset === undefined && next.app === undefined) {\n const choice = answer(\n await p.select<string>({\n message: 'What do you want to build?',\n options: [\n ...PRESETS.map((preset) => ({\n value: preset.id,\n label: preset.label,\n hint: preset.hint,\n })),\n {\n value: CUSTOM,\n label: 'Custom stack',\n hint: 'pick the app, memory and features yourself',\n },\n ],\n initialValue: DEFAULT_PRESET,\n maxItems: 10,\n })\n );\n if (choice === CUSTOM) Object.assign(next, await askStack(next));\n else next.preset = choice;\n }\n\n const presetProvider = PRESETS.find((preset) => preset.id === next.preset)?.spec.provider;\n if (next.provider === undefined) {\n next.provider = answer(\n await p.select({\n message: 'Which model provider?',\n options: PROVIDERS.map((id) => ({\n value: id,\n label: PROVIDER_INFO[id].label,\n hint: PROVIDER_INFO[id].hint,\n })),\n initialValue: presetProvider ?? 'ollama',\n })\n );\n }\n const provider = next.provider;\n\n if (next.model === undefined) {\n const spinner = p.spinner();\n spinner.start('Looking up models');\n const { choices, source } = await modelChoices(provider);\n spinner.stop(\n source === 'ollama'\n ? 'Found the models in your Ollama'\n : source === 'suggested'\n ? 'Ollama is not running, so here are good small models to pull'\n : `Found the current ${providerInfo(provider).label} models`\n );\n const picked = answer(\n await p.select<string>({\n message: 'Which model?',\n options: [...choices, { value: OTHER_MODEL, label: 'Another model', hint: 'type its id' }],\n initialValue: choices[0]?.value,\n maxItems: 10,\n })\n );\n next.model =\n picked === OTHER_MODEL\n ? answer(\n await p.text({\n message: `Model id at ${providerInfo(provider).label}`,\n validate: (value) => (value?.trim() ? undefined : 'Type a model id'),\n })\n ).trim()\n : picked;\n }\n\n const envKey = providerInfo(provider).envKey;\n if (envKey && next.apiKey === undefined) {\n const fromShell = process.env[envKey]?.trim();\n if (fromShell) {\n const copy = answer(\n await p.confirm({\n message: `Copy ${envKey} from your shell into the project's .env?`,\n initialValue: true,\n })\n );\n if (copy) next.apiKey = fromShell;\n } else {\n const key = answer(\n await p.password({\n message: `${envKey} (leave empty to add it to .env later)`,\n mask: '*',\n })\n ).trim();\n if (key) next.apiKey = key;\n }\n }\n\n if (next.codingAgents === undefined) {\n const detected = detectCodingAgents();\n next.codingAgents = answer(\n await p.multiselect<CodingAgent>({\n message: 'Set the project up for your coding agent? (AGENTS.md is always written)',\n options: CODING_AGENT_CHOICES,\n initialValues: detected,\n required: false,\n })\n );\n }\n\n return next;\n}\n\n/** The stack questions of a custom project. */\nasync function askStack(args: CliArgs): Promise<Partial<CliArgs>> {\n const app =\n args.app ??\n answer(\n await p.select({\n message: 'Which kind of app?',\n options: APP_CHOICES,\n initialValue: 'script',\n })\n );\n const result: Partial<CliArgs> = { app };\n\n if (app === 'server' && args.server === undefined) {\n result.server = answer(\n await p.select({\n message: 'Which server framework?',\n options: SERVER_CHOICES,\n initialValue: 'hono',\n })\n );\n }\n if (app === 'channels' && args.channels === undefined) {\n result.channels = answer(\n await p.multiselect({\n message: 'Which channels?',\n options: CHANNEL_CHOICES,\n initialValues: ['webchat'],\n required: true,\n })\n );\n }\n if (args.memory === undefined) {\n result.memory = answer(\n await p.select({\n message: 'Where should conversations be stored?',\n options: MEMORY_CHOICES,\n initialValue: 'sqlite',\n })\n );\n }\n if (args.features === undefined) {\n const features = answer(\n await p.multiselect({\n message: 'Which features? (space to toggle)',\n options: FEATURE_CHOICES,\n required: false,\n })\n );\n if (features.includes('durable') && !features.includes('workflows')) features.push('workflows');\n result.features = features;\n if (features.includes('rag') && args.vectorStore === undefined) {\n result.vectorStore = answer(\n await p.select({\n message: 'Where should RAG keep its vectors?',\n options: VECTOR_STORE_CHOICES,\n initialValue: 'memory',\n })\n );\n }\n }\n if (args.deploy === undefined) {\n result.deploy = answer(\n await p.select({\n message: 'How will you deploy it?',\n options: DEPLOY_CHOICES,\n initialValue: 'docker',\n })\n );\n }\n return result;\n}\n","import { basename, resolve } from 'node:path';\nimport { DEFAULT_PRESET, findPreset } from '../kit/presets.js';\nimport { defaultModel } from '../kit/providers.js';\nimport { validateProjectName, type ProjectSpecInput, type PackageManager } from '../kit/spec.js';\nimport { CliError, type CliArgs } from './args.js';\n\nexport const DEFAULT_DIRECTORY = 'my-agents';\n\n/** The package name for a project created in `directory`: its last path segment, so `.` takes the current directory's name. */\nexport function projectNameFromDirectory(directory: string, cwd: string = process.cwd()): string {\n return basename(resolve(cwd, directory.trim()));\n}\n\nexport function resolveDirectory(\n directory: string,\n cwd: string = process.cwd()\n): { path: string; name: string } {\n const name = projectNameFromDirectory(directory, cwd);\n const error = validateProjectName(name);\n if (error) throw new CliError(`Invalid project name \"${name}\": ${error}`);\n return { path: resolve(cwd, directory.trim()), name };\n}\n\n/**\n * The spec the flags describe, on top of the preset they name (or the default\n * one). Flags win over the preset, and `--features` adds to the preset's\n * features instead of replacing them.\n */\nexport function specFromArgs(\n args: CliArgs,\n context: { name: string; packageManager: PackageManager }\n): ProjectSpecInput {\n const custom = args.app !== undefined && args.preset === undefined;\n const preset = custom ? undefined : findPreset(args.preset ?? DEFAULT_PRESET);\n if (!custom && !preset) throw new CliError(`Unknown preset \"${args.preset}\"`);\n\n const base = preset?.spec;\n const app = args.app ?? base?.app ?? 'script';\n const provider = args.provider ?? base?.provider ?? 'ollama';\n const server =\n args.server ?? (app === 'server' ? (base?.app === 'server' ? base.server : 'hono') : undefined);\n const channels = args.channels ?? (app === 'channels' ? (base?.channels ?? ['webchat']) : []);\n const features = [...new Set([...(base?.features ?? []), ...(args.features ?? [])])];\n\n return {\n name: context.name,\n ...(preset && { preset: preset.id }),\n app,\n ...(server && { server }),\n channels,\n memory: args.memory ?? base?.memory ?? 'none',\n vectorStore: args.vectorStore ?? base?.vectorStore ?? 'memory',\n features,\n provider,\n model: args.model ?? defaultModel(provider),\n deploy: args.deploy ?? 'none',\n compose: args.compose ?? true,\n packageManager: args.packageManager ?? (server === 'tetsu' ? 'bun' : context.packageManager),\n codingAgents: args.codingAgents ?? [],\n };\n}\n"],"mappings":";AAAA,yCAAC,EAAC,MAAO,kBAAiB,OAAQ,cAAa,OAAQ,wBAAuB,OAAQ,CAAC,oBAAmB,sBAAsB,GAAE,cAAe,EAAC,qBAAoB,UAAS,sBAAqB,WAAU,QAAS,WAAU,SAAU,SAAQ,GAAE,iBAAkB,EAAC,kBAAiB,UAAS,KAAM,WAAU,GAAE,KAAM,CAAC,qBAAoB,kBAAiB,cAAa,gBAAgB,GAAE,SAAU,OAAM,GAAE,EAAC,MAAO,kBAAiB,OAAQ,cAAa,OAAQ,wBAAuB,OAAQ,CAAC,oBAAmB,sBAAsB,GAAE,cAAe,EAAC,qBAAoB,UAAS,sBAAqB,WAAU,QAAS,UA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AM,SAAS;AACvE,OAAG;AAAA,MACD,GAAG,KAAK,UAAU,EAAE,IAAI,OAAO,OAAO,EAAE,SAAS,GAAI,UAAU,EAAE,OAAO,EAAG,EAAE,GAAG,MAAM,CAAC,CAAC;AAAA;AAAA,IAC1F;AAAA,EACF,WAAW,iBAAiB,YAAY,iBAAiB,uBAAuB;AAC9E,OAAG,OAAO,GAAGA,IAAG,IAAI,QAAQ,CAAC,IAAI,OAAO;AAAA,CAAI;AAAA,EAC9C,OAAO;AACL,OAAG,OAAO,GAAGA,IAAG,IAAI,QAAQ,CAAC,IAAI,OAAO;AAAA,CAAI;AAC5C,QAAI,QAAQ,IAAI,SAAS,iBAAiB,SAAS,MAAM,MAAO,IAAG,OAAO,GAAG,MAAM,KAAK;AAAA,CAAI;AAAA,EAC9F;AACA,SAAO;AACT;","names":["existsSync","dirname","join","code","code","values","text","lines","lines","lines","dirname","join","join","dirname","lines","text","lines","resolve","code","join","dirname","existsSync","log","existsSync","readFileSync","mkdir","writeFile","dirname","join","resolve","parseDocument","text","lines","tail","i","j","text","join","existsSync","readFileSync","text","parseDocument","resolve","log","mkdir","dirname","writeFile","row","suggestion","run","tsconfig","existsSync","readFileSync","readdirSync","writeFileSync","mkdir","join","mkdir","relative","existsSync","join","readdirSync","readFileSync","writeFileSync","existsSync","readFileSync","mkdir","rm","join","resolve","finish","log","run","resolve","mkdir","existsSync","rm","join","readFileSync","resolve","existsSync","mkdirSync","writeFileSync","join","z","z","failure","join","existsSync","mkdirSync","writeFileSync","relative","p","pc","values","existsSync","homedir","join","basename","resolve","basename","resolve","homedir","existsSync","join","spinner","text","pc","spinner","outro","relative"]}
1
+ {"version":3,"sources":["<define:__COGITATOR_EXAMPLES__>","<define:__COGITATOR_VERSIONS__>","../src/kit/scaffold.ts","../src/kit/errors.ts","../src/kit/package-manager.ts","../src/kit/spec.ts","../src/kit/providers.ts","../src/kit/compat.ts","../src/kit/code.ts","../src/kit/versions.ts","../src/kit/emit.ts","../src/kit/features/starter-tools.ts","../src/kit/features/base.ts","../src/kit/features/deploy.ts","../src/kit/features/a2a.ts","../src/kit/features/shared.ts","../src/kit/features/app-channels.ts","../src/kit/features/app-next.ts","../src/kit/features/app-script.ts","../src/kit/features/app-server.ts","../src/kit/features/memory.ts","../src/kit/features/app-worker.ts","../src/kit/features/coding-agents.ts","../src/kit/features/evals.ts","../src/kit/features/harness.ts","../src/kit/features/mcp.ts","../src/kit/features/observability.ts","../src/kit/features/orchestration.ts","../src/kit/features/provider.ts","../src/kit/features/rag.ts","../src/kit/features/sandbox.ts","../src/kit/features/voice.ts","../src/kit/features/index.ts","../src/kit/presets.ts","../src/kit/guide.ts","../src/kit/project.ts","../src/kit/plan.ts","../src/kit/process.ts","../src/kit/add.ts","../src/kit/diff.ts","../src/kit/merge.ts","../src/kit/suggest.ts","../src/kit/examples.ts","../src/kit/remote.ts","../src/kit/starter.ts","../src/kit/catalog.ts","../src/kit/models.ts","../src/kit/ollama.ts","../src/kit/key-check.ts","../src/kit/telemetry.ts","../src/cli/main.ts","../src/cli/args.ts","../src/cli/help.ts","../src/cli/interactive.ts","../src/cli/resolve.ts"],"sourcesContent":["[{\"name\":\"a2a/a2a-server\",\"title\":\"A2A Server\",\"entry\":\"a2a/01-a2a-server.ts\",\"files\":[\"_shared/setup.ts\",\"a2a/01-a2a-server.ts\"],\"dependencies\":{\"@cogitator-ai/a2a\":\"^0.8.6\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"express\":\"^5.2.1\"},\"devDependencies\":{\"@types/express\":\"^5.0.6\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"a2a/a2a-client\",\"title\":\"A2A Client\",\"entry\":\"a2a/02-a2a-client.ts\",\"files\":[\"_shared/setup.ts\",\"a2a/02-a2a-client.ts\"],\"dependencies\":{\"@cogitator-ai/a2a\":\"^0.8.6\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/self-modifying\",\"title\":\"Self-Modifying Agent\",\"entry\":\"advanced/01-self-modifying.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/01-self-modifying.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/self-modifying\":\"^19.4.6\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/neuro-symbolic\",\"title\":\"Neuro-Symbolic Reasoning\",\"entry\":\"advanced/02-neuro-symbolic.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/02-neuro-symbolic.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/neuro-symbolic\":\"^17.0.26\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"advanced/wasm-tools\",\"title\":\"WASM-Sandboxed Tools\",\"entry\":\"advanced/03-wasm-tools.ts\",\"files\":[\"_shared/setup.ts\",\"advanced/03-wasm-tools.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/wasm-tools\":\"^0.7.20\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/web-scraping\",\"title\":\"Web Scraping with Browser Agent\",\"entry\":\"browser/01-web-scraping.ts\",\"files\":[\"_shared/setup.ts\",\"browser/01-web-scraping.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.16\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/form-automation\",\"title\":\"Form Automation with Browser Agent\",\"entry\":\"browser/02-form-automation.ts\",\"files\":[\"_shared/setup.ts\",\"browser/02-form-automation.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.16\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/stealth-agent\",\"title\":\"Stealth Browser Agent\",\"entry\":\"browser/03-stealth-agent.ts\",\"files\":[\"_shared/setup.ts\",\"browser/03-stealth-agent.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.16\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"browser/bitcoin-price-scraper\",\"title\":\"Bitcoin Price Scraper (Binance)\",\"entry\":\"browser/04-bitcoin-price-scraper.ts\",\"files\":[\"_shared/setup.ts\",\"browser/04-bitcoin-price-scraper.ts\"],\"dependencies\":{\"@cogitator-ai/browser\":\"^0.4.16\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"channels/telegram-assistant\",\"title\":\"Telegram assistant\",\"entry\":\"channels/01-telegram-assistant.ts\",\"files\":[\"channels/01-telegram-assistant.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.11.2\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"grammy\":\"^1.46.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\",\"OWNER_TG_ID\",\"TG_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/super-assistant\",\"title\":\"Super assistant\",\"entry\":\"channels/02-super-assistant.ts\",\"files\":[\"channels/02-super-assistant.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.11.2\",\"better-sqlite3\":\"^13.0.3\",\"dotenv\":\"^18.0.5\",\"grammy\":\"^1.46.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"OWNER_TG_ID\",\"TG_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/webchat-bot\",\"title\":\"Webchat bot\",\"entry\":\"channels/03-webchat-bot.ts\",\"files\":[\"channels/03-webchat-bot.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.11.2\",\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"ws\":\"^8.22.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"@types/ws\":\"^8.18.2\",\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\",\"WEBCHAT_PORT\",\"WEBCHAT_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/social-publisher\",\"title\":\"Social publisher\",\"entry\":\"channels/04-social-publisher.ts\",\"files\":[\"channels/04-social-publisher.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.11.2\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"BLUESKY_APP_PASSWORD\",\"BLUESKY_HANDLE\",\"PUBLISH\",\"THREADS_ACCESS_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"channels/social-bot\",\"title\":\"Social bot\",\"entry\":\"channels/05-social-bot.ts\",\"files\":[\"channels/05-social-bot.ts\",\"channels/cogitator.yml\",\"channels/webchat-client.html\"],\"dependencies\":{\"@cogitator-ai/channels\":\"^0.11.2\",\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"BLUESKY_APP_PASSWORD\",\"BLUESKY_HANDLE\",\"GOOGLE_API_KEY\",\"THREADS_ACCESS_TOKEN\"],\"runtime\":\"node\"},{\"name\":\"core/basic-agent\",\"title\":\"Basic Agent with Custom Tools\",\"entry\":\"core/01-basic-agent.ts\",\"files\":[\"_shared/setup.ts\",\"core/01-basic-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/built-in-tools\",\"title\":\"Built-in Tools\",\"entry\":\"core/02-built-in-tools.ts\",\"files\":[\"_shared/setup.ts\",\"core/02-built-in-tools.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/tool-caching\",\"title\":\"Tool Caching with withCache\",\"entry\":\"core/03-tool-caching.ts\",\"files\":[\"_shared/setup.ts\",\"core/03-tool-caching.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/context-manager\",\"title\":\"Context Manager\",\"entry\":\"core/04-context-manager.ts\",\"files\":[\"_shared/setup.ts\",\"core/04-context-manager.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/tree-of-thought\",\"title\":\"Tree of Thought\",\"entry\":\"core/05-tree-of-thought.ts\",\"files\":[\"_shared/setup.ts\",\"core/05-tree-of-thought.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/reflection\",\"title\":\"Reflection\",\"entry\":\"core/06-reflection.ts\",\"files\":[\"_shared/setup.ts\",\"core/06-reflection.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/agent-optimizer\",\"title\":\"Agent Optimizer\",\"entry\":\"core/07-agent-optimizer.ts\",\"files\":[\"_shared/setup.ts\",\"core/07-agent-optimizer.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/time-travel\",\"title\":\"Time Travel\",\"entry\":\"core/08-time-travel.ts\",\"files\":[\"_shared/setup.ts\",\"core/08-time-travel.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/cost-routing\",\"title\":\"Cost-Aware Routing\",\"entry\":\"core/09-cost-routing.ts\",\"files\":[\"_shared/setup.ts\",\"core/09-cost-routing.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/constitutional-ai\",\"title\":\"Constitutional AI\",\"entry\":\"core/10-constitutional-ai.ts\",\"files\":[\"_shared/setup.ts\",\"core/10-constitutional-ai.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/prompt-injection\",\"title\":\"Prompt Injection Detection\",\"entry\":\"core/11-prompt-injection.ts\",\"files\":[\"_shared/setup.ts\",\"core/11-prompt-injection.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/causal-reasoning\",\"title\":\"Causal Reasoning\",\"entry\":\"core/12-causal-reasoning.ts\",\"files\":[\"_shared/setup.ts\",\"core/12-causal-reasoning.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/model-registry\",\"title\":\"Model Registry\",\"entry\":\"core/13-model-registry.ts\",\"files\":[\"_shared/setup.ts\",\"core/13-model-registry.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/models\":\"^18.4.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/approvals\",\"title\":\"Approvals: pause before a sensitive tool, resume later\",\"entry\":\"core/14-approvals.ts\",\"files\":[\"_shared/setup.ts\",\"core/14-approvals.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/handoffs\",\"title\":\"Handoffs: a triage agent passes the conversation on\",\"entry\":\"core/15-handoffs.ts\",\"files\":[\"_shared/setup.ts\",\"core/15-handoffs.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"core/decisions\",\"title\":\"Decision models: typed answers with probabilities\",\"entry\":\"core/16-decisions.ts\",\"files\":[\"_shared/setup.ts\",\"core/16-decisions.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"device-tools/screenshot\",\"title\":\"Screenshot\",\"entry\":\"device-tools/01-screenshot.ts\",\"files\":[\"device-tools/01-screenshot.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/clipboard\",\"title\":\"Clipboard\",\"entry\":\"device-tools/02-clipboard.ts\",\"files\":[\"device-tools/02-clipboard.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/notify\",\"title\":\"Notify\",\"entry\":\"device-tools/03-notify.ts\",\"files\":[\"device-tools/03-notify.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/open-url\",\"title\":\"Open url\",\"entry\":\"device-tools/04-open-url.ts\",\"files\":[\"device-tools/04-open-url.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"device-tools/shell-exec\",\"title\":\"Shell exec\",\"entry\":\"device-tools/05-shell-exec.ts\",\"files\":[\"device-tools/05-shell-exec.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[],\"runtime\":\"node\"},{\"name\":\"evals/basic-eval\",\"title\":\"Basic Evaluation\",\"entry\":\"evals/01-basic-eval.ts\",\"files\":[\"_shared/setup.ts\",\"evals/01-basic-eval.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/evals\":\"^0.6.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"evals/llm-judge\",\"title\":\"LLM-as-Judge Evaluation\",\"entry\":\"evals/02-llm-judge.ts\",\"files\":[\"_shared/setup.ts\",\"evals/02-llm-judge.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/evals\":\"^0.6.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"evals/ab-comparison\",\"title\":\"A/B Comparison\",\"entry\":\"evals/03-ab-comparison.ts\",\"files\":[\"_shared/setup.ts\",\"evals/03-ab-comparison.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/evals\":\"^0.6.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/redis-memory\",\"title\":\"Redis Memory: Persistent Conversations\",\"entry\":\"infrastructure/01-redis-memory.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/01-redis-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\",\"REDIS_URL\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/postgres-memory\",\"title\":\"PostgreSQL Memory: Long-Term Persistence\",\"entry\":\"infrastructure/02-postgres-memory.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/02-postgres-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"DATABASE_URL\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/worker-queue\",\"title\":\"Worker Queue: Distributed Agent Execution\",\"entry\":\"infrastructure/03-worker-queue.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/03-worker-queue.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/worker\":\"^0.9.6\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\",\"REDIS_URL\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/deploy-docker\",\"title\":\"Deploy: Docker Deployment Planning\",\"entry\":\"infrastructure/04-deploy-docker.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/04-deploy-docker.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/deploy\":\"^0.6.5\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"infrastructure/sandbox-execution\",\"title\":\"Sandbox Execution: Docker, WASM & Native\",\"entry\":\"infrastructure/05-sandbox-execution.ts\",\"files\":[\"_shared/setup.ts\",\"infrastructure/05-sandbox-execution.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/sandbox\":\"^0.5.15\",\"@extism/extism\":\"^2.0.0-rc13\",\"dockerode\":\"^4.0.0 || ^5.0.0\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/express-server\",\"title\":\"Express Server Integration\",\"entry\":\"integrations/01-express-server.ts\",\"files\":[\"_shared/arithmetic.ts\",\"_shared/setup.ts\",\"integrations/01-express-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/express\":\"^0.8.6\",\"dotenv\":\"^18.0.5\",\"express\":\"^5.2.1\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"@types/express\":\"^5.0.6\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/fastify-server\",\"title\":\"Fastify Server Integration\",\"entry\":\"integrations/02-fastify-server.ts\",\"files\":[\"_shared/arithmetic.ts\",\"_shared/setup.ts\",\"integrations/02-fastify-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/fastify\":\"^0.7.6\",\"dotenv\":\"^18.0.5\",\"fastify\":\"^5.12.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/hono-server\",\"title\":\"Hono Server Integration\",\"entry\":\"integrations/03-hono-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/03-hono-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/hono\":\"^0.7.6\",\"@hono/node-server\":\"^2.1.3\",\"dotenv\":\"^18.0.5\",\"hono\":\"^4.13.12\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/koa-server\",\"title\":\"Koa Server Integration\",\"entry\":\"integrations/04-koa-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/04-koa-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/koa\":\"^0.7.6\",\"@koa/router\":\"^15.7.0\",\"dotenv\":\"^18.0.5\",\"koa\":\"^3.2.1\"},\"devDependencies\":{\"@types/koa\":\"^3.0.3\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/nextjs-handler\",\"title\":\"Nextjs handler\",\"entry\":\"integrations/05-nextjs-handler.ts\",\"files\":[\"integrations/05-nextjs-handler.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/next\":\"^0.8.6\",\"next\":\"^14.0.0 || ^15.0.0 || ^16.0.0\",\"react\":\"^18.2.0 || ^19.0.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"GOOGLE_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/openai-compat\",\"title\":\"OpenAI-Compatible Server\",\"entry\":\"integrations/06-openai-compat.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/06-openai-compat.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/openai-compat\":\"^21.2.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/ai-sdk-adapter\",\"title\":\"Vercel AI SDK Adapter\",\"entry\":\"integrations/07-ai-sdk-adapter.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/07-ai-sdk-adapter.ts\"],\"dependencies\":{\"@cogitator-ai/ai-sdk\":\"^0.6.1\",\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/types\":\"^0.41.1\",\"ai\":\"^7.0.127\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"integrations/tetsu-server\",\"title\":\"Tetsu Server on Bun: an app with its own MCP server and agent\",\"entry\":\"integrations/08-tetsu-server.ts\",\"files\":[\"_shared/setup.ts\",\"integrations/08-tetsu-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/mcp\":\"^19.3.6\",\"@cogitator-ai/tetsu\":\"^0.5.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"@tetsujs/core\":\"^0.6.1\",\"@tetsujs/openapi\":\"^0.6.1\",\"@tetsujs/sse\":\"^0.6.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"bun\"},{\"name\":\"mcp/mcp-client\",\"title\":\"MCP Client: Filesystem Server\",\"entry\":\"mcp/01-mcp-client.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/01-mcp-client.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/mcp\":\"^19.3.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/mcp-server\",\"title\":\"MCP Server: Expose Cogitator Tools over HTTP\",\"entry\":\"mcp/02-mcp-server.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/02-mcp-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/mcp\":\"^19.3.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/per-user-mcp\",\"title\":\"An Agent on Your Own MCP Server, per User\",\"entry\":\"mcp/03-per-user-mcp.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/03-per-user-mcp.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/mcp\":\"^19.3.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"mcp/agent-as-mcp-server\",\"title\":\"A Cogitator Agent as an MCP Server\",\"entry\":\"mcp/04-agent-as-mcp-server.ts\",\"files\":[\"_shared/setup.ts\",\"mcp/04-agent-as-mcp-server.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/mcp\":\"^19.3.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/basic-memory\",\"title\":\"Basic Memory: Threads & Multi-Turn Conversations\",\"entry\":\"memory/01-basic-memory.ts\",\"files\":[\"_shared/setup.ts\",\"memory/01-basic-memory.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/context-builder\",\"title\":\"Context Builder: Token-Aware Context Windows\",\"entry\":\"memory/02-context-builder.ts\",\"files\":[\"_shared/setup.ts\",\"memory/02-context-builder.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/semantic-search\",\"title\":\"Semantic Search: Hybrid BM25 + Vector Search\",\"entry\":\"memory/03-semantic-search.ts\",\"files\":[\"_shared/setup.ts\",\"memory/03-semantic-search.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"@qdrant/js-client-rest\":\"^1.10.0\",\"dotenv\":\"^18.0.5\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"memory/knowledge-graph\",\"title\":\"Knowledge Graph: Entity Extraction & Graph Traversal\",\"entry\":\"memory/04-knowledge-graph.ts\",\"files\":[\"_shared/setup.ts\",\"memory/04-knowledge-graph.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"@cogitator-ai/types\":\"^0.41.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/basic-retrieval\",\"title\":\"Basic RAG Retrieval\",\"entry\":\"rag/01-basic-retrieval.ts\",\"files\":[\"_shared/setup.ts\",\"rag/01-basic-retrieval.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"@cogitator-ai/rag\":\"^0.7.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/chunking-strategies\",\"title\":\"Chunking Strategies Comparison\",\"entry\":\"rag/02-chunking-strategies.ts\",\"files\":[\"_shared/setup.ts\",\"rag/02-chunking-strategies.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"@cogitator-ai/rag\":\"^0.7.1\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"rag/agent-with-rag\",\"title\":\"Agent with RAG Tools\",\"entry\":\"rag/03-agent-with-rag.ts\",\"files\":[\"_shared/setup.ts\",\"rag/03-agent-with-rag.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/memory\":\"^0.12.6\",\"@cogitator-ai/rag\":\"^0.7.1\",\"@qdrant/js-client-rest\":\"^1.10.0\",\"better-sqlite3\":\"^13.0.3\",\"dotenv\":\"^18.0.5\",\"ioredis\":\"^5.0.0 || ^6.0.0\",\"mongodb\":\"^6.0.0 || ^7.0.0\",\"pg\":\"^8.23.1\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/debate-swarm\",\"title\":\"Debate Swarm\",\"entry\":\"swarms/01-debate-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/01-debate-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/swarms\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/pipeline-swarm\",\"title\":\"Pipeline Swarm\",\"entry\":\"swarms/02-pipeline-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/02-pipeline-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/swarms\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/hierarchical-swarm\",\"title\":\"Hierarchical Swarm\",\"entry\":\"swarms/03-hierarchical-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/03-hierarchical-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/swarms\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"swarms/negotiation-swarm\",\"title\":\"Negotiation Swarm\",\"entry\":\"swarms/04-negotiation-swarm.ts\",\"files\":[\"_shared/setup.ts\",\"swarms/04-negotiation-swarm.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/swarms\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/pipeline\",\"title\":\"Voice Pipeline\",\"entry\":\"voice/01-pipeline.ts\",\"files\":[\"_shared/setup.ts\",\"voice/01-pipeline.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/voice\":\"^0.5.6\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/realtime\",\"title\":\"Realtime Voice Session\",\"entry\":\"voice/02-realtime.ts\",\"files\":[\"_shared/setup.ts\",\"voice/02-realtime.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/voice\":\"^0.5.6\",\"dotenv\":\"^18.0.5\",\"openai\":\"^7.25.0\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/voice-agent\",\"title\":\"Voice Agent (WebSocket Server)\",\"entry\":\"voice/03-voice-agent.ts\",\"files\":[\"_shared/setup.ts\",\"voice/03-voice-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/voice\":\"^0.5.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"DEEPGRAM_API_KEY\",\"ELEVENLABS_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"voice/realtime-voice-agent\",\"title\":\"Realtime Voice Agent (Gemini Live over WebSocket)\",\"entry\":\"voice/04-realtime-voice-agent.ts\",\"files\":[\"_shared/setup.ts\",\"voice/04-realtime-voice-agent.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/voice\":\"^0.5.6\",\"dotenv\":\"^18.0.5\",\"ws\":\"^8.22.0\"},\"devDependencies\":{\"@types/ws\":\"^8.18.2\",\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/basic-workflow\",\"title\":\"Basic Workflow: Code Review Pipeline\",\"entry\":\"workflows/01-basic-workflow.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/01-basic-workflow.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/workflows\":\"^0.12.6\",\"dotenv\":\"^18.0.5\",\"zod\":\"^4.6.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/human-in-loop\",\"title\":\"Human-in-the-Loop: Content Publishing Workflow\",\"entry\":\"workflows/02-human-in-loop.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/02-human-in-loop.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/workflows\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"},{\"name\":\"workflows/map-reduce\",\"title\":\"Map-Reduce: Parallel Document Analysis\",\"entry\":\"workflows/03-map-reduce.ts\",\"files\":[\"_shared/setup.ts\",\"workflows/03-map-reduce.ts\"],\"dependencies\":{\"@cogitator-ai/core\":\"^0.39.1\",\"@cogitator-ai/workflows\":\"^0.12.6\",\"dotenv\":\"^18.0.5\"},\"devDependencies\":{\"tsx\":\"^4.23.15\"},\"env\":[\"ANTHROPIC_API_KEY\",\"GOOGLE_API_KEY\",\"OLLAMA_URL\",\"OPENAI_API_KEY\",\"OPENROUTER_API_KEY\"],\"runtime\":\"node\"}]","{\"@cogitator-ai/a2a\":\"0.8.6\",\"@cogitator-ai/ai-sdk\":\"0.6.1\",\"@cogitator-ai/browser\":\"0.4.16\",\"@cogitator-ai/channels\":\"0.11.2\",\"@cogitator-ai/cli\":\"0.7.4\",\"@cogitator-ai/config\":\"0.14.2\",\"@cogitator-ai/core\":\"0.39.1\",\"@cogitator-ai/deploy\":\"0.6.5\",\"@cogitator-ai/evals\":\"0.6.1\",\"@cogitator-ai/express\":\"0.8.6\",\"@cogitator-ai/fastify\":\"0.7.6\",\"@cogitator-ai/hono\":\"0.7.6\",\"@cogitator-ai/koa\":\"0.7.6\",\"@cogitator-ai/mcp\":\"19.3.6\",\"@cogitator-ai/memory\":\"0.12.6\",\"@cogitator-ai/models\":\"18.4.1\",\"@cogitator-ai/neuro-symbolic\":\"17.0.26\",\"@cogitator-ai/next\":\"0.8.6\",\"@cogitator-ai/openai-compat\":\"21.2.6\",\"@cogitator-ai/rag\":\"0.7.1\",\"@cogitator-ai/redis\":\"0.5.3\",\"@cogitator-ai/sandbox\":\"0.5.15\",\"@cogitator-ai/self-modifying\":\"19.4.6\",\"@cogitator-ai/server-shared\":\"0.5.6\",\"@cogitator-ai/studio\":\"0.1.6\",\"@cogitator-ai/swarms\":\"0.12.6\",\"@cogitator-ai/test-utils\":\"0.2.20\",\"@cogitator-ai/tetsu\":\"0.5.6\",\"@cogitator-ai/types\":\"0.41.1\",\"@cogitator-ai/voice\":\"0.5.6\",\"@cogitator-ai/wasm-tools\":\"0.7.20\",\"@cogitator-ai/worker\":\"0.9.6\",\"@cogitator-ai/workflows\":\"0.12.6\"}","import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { CodedError } from './errors.js';\nimport { installCommand, installErrorCode, packageManagerInvocation } from './package-manager.js';\nimport { planProject, type PlanOptions, type ProjectPlan } from './plan.js';\nimport { hasCommand, runCommand, tail } from './process.js';\nimport type { GeneratedFile } from './project.js';\nimport type { PackageManager } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\n/**\n * Where the scaffolder reports progress. The CLI shows it with spinners, the\n * programmatic API stays silent unless a logger is passed.\n */\nexport interface ScaffoldLogger {\n start(message: string): void;\n done(message: string): void;\n fail(message: string): void;\n warn(message: string): void;\n}\n\nexport const silentLogger: ScaffoldLogger = {\n start: () => undefined,\n done: () => undefined,\n fail: () => undefined,\n warn: () => undefined,\n};\n\n/** How an optional step went. */\nexport type StepResult =\n { status: 'done' } | { status: 'skipped'; reason: string } | { status: 'failed'; error: Error };\n\nexport interface ScaffoldOptions extends PlanOptions {\n /** The directory to create the project in. It must not exist or be empty. */\n directory: string;\n /** Run the package manager's install (default `true`). */\n install?: boolean;\n /** Initialize a git repository and commit the project (default `true`). */\n git?: boolean;\n log?: ScaffoldLogger;\n /** Show the install's output live instead of capturing it. */\n inheritOutput?: boolean;\n}\n\nexport interface ScaffoldResult {\n plan: ProjectPlan;\n directory: string;\n /** The generated files, relative to `directory`. */\n files: string[];\n install: StepResult;\n format: StepResult;\n git: StepResult;\n /** The workspace root above the project, when it was created inside one. */\n parentWorkspace?: string;\n}\n\n/** Hashes of the files the scaffolder wrote, so `cogitator add` can tell them from files the user edited. */\nexport interface ScaffoldLock {\n version: 1;\n generator: string;\n files: Record<string, string>;\n}\n\nexport const LOCK_PATH = '.cogitator/scaffold.json';\n\n/** Files the lock never tracks: they belong to the user from the first moment. */\nconst UNTRACKED = new Set(['.env']);\n\nexport function hashContent(content: string): string {\n return `sha256-${createHash('sha256').update(content).digest('hex')}`;\n}\n\nfunction failure(error: unknown): StepResult {\n return { status: 'failed', error: error instanceof Error ? error : new Error(String(error)) };\n}\n\nexport async function writeFiles(\n directory: string,\n files: readonly GeneratedFile[]\n): Promise<void> {\n for (const file of files) {\n const target = join(directory, file.path);\n await mkdir(dirname(target), { recursive: true });\n await writeFile(\n target,\n file.content,\n file.mode !== undefined ? { mode: file.mode } : undefined\n );\n if (file.mode !== undefined) await chmod(target, file.mode);\n }\n}\n\nasync function saveLock(directory: string, files: Record<string, string>): Promise<void> {\n const lock: ScaffoldLock = {\n version: 1,\n generator: `create-cogitator-app@${scaffolderVersion()}`,\n files: Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))),\n };\n await mkdir(join(directory, dirname(LOCK_PATH)), { recursive: true });\n await writeFile(join(directory, LOCK_PATH), JSON.stringify(lock, null, 2) + '\\n');\n}\n\n/** Hashes `paths` as they are on disk now, `undefined` for a path that does not exist. */\nasync function hashFiles(\n directory: string,\n paths: readonly string[]\n): Promise<Map<string, string | undefined>> {\n const hashes = new Map<string, string | undefined>();\n for (const path of paths) {\n if (UNTRACKED.has(path) || path === LOCK_PATH) continue;\n const full = join(directory, path);\n hashes.set(path, existsSync(full) ? hashContent(await readFile(full, 'utf-8')) : undefined);\n }\n return hashes;\n}\n\nexport async function writeLock(directory: string, paths: readonly string[]): Promise<void> {\n const files: Record<string, string> = {};\n for (const [path, hash] of await hashFiles(directory, paths)) if (hash) files[path] = hash;\n await saveLock(directory, files);\n}\n\n/**\n * Re-hashes `paths` in the lock after `cogitator add` wrote or deleted them,\n * keeping the hashes of every other file.\n */\nexport async function updateLock(directory: string, paths: readonly string[]): Promise<void> {\n const files = { ...readLock(directory)?.files };\n for (const [path, hash] of await hashFiles(directory, paths)) {\n if (hash) files[path] = hash;\n else delete files[path];\n }\n await saveLock(directory, files);\n}\n\nexport function readLock(directory: string): ScaffoldLock | undefined {\n const path = join(directory, LOCK_PATH);\n if (!existsSync(path)) return undefined;\n const parsed: unknown = JSON.parse(readFileSync(path, 'utf-8'));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('files' in parsed) ||\n typeof parsed.files !== 'object' ||\n parsed.files === null\n ) {\n throw new Error(`${LOCK_PATH} is not a scaffold lock`);\n }\n const files: Record<string, string> = {};\n for (const [file, hash] of Object.entries(parsed.files)) {\n if (typeof hash === 'string') files[file] = hash;\n }\n const generator =\n 'generator' in parsed && typeof parsed.generator === 'string' ? parsed.generator : 'unknown';\n return { version: 1, generator, files };\n}\n\n/** The local Biome binary of a project, absent before its dependencies are installed. */\nfunction biomeBinary(directory: string): string | undefined {\n const name = process.platform === 'win32' ? 'biome.cmd' : 'biome';\n const path = join(directory, 'node_modules', '.bin', name);\n return existsSync(path) ? path : undefined;\n}\n\n/**\n * Formats the generated code with the project's own Biome, so it starts clean\n * under `lint`: the whole project, or only `paths` when they are given.\n */\nexport async function formatProject(\n directory: string,\n paths: readonly string[] = ['.']\n): Promise<StepResult> {\n const biome = biomeBinary(directory);\n if (!biome) return { status: 'skipped', reason: 'Biome is not installed' };\n if (paths.length === 0) return { status: 'skipped', reason: 'nothing to format' };\n const result = await runCommand(\n biome,\n ['check', '--write', '--no-errors-on-unmatched', ...paths],\n { cwd: directory }\n );\n if (result.code !== 0)\n return failure(new Error(`biome check --write failed:\\n${tail(result.output)}`));\n return { status: 'done' };\n}\n\n/** The git work tree `directory` is inside of, if any. */\nexport async function enclosingGitRepo(directory: string): Promise<string | undefined> {\n let dir = resolve(directory);\n while (!existsSync(dir)) dir = dirname(dir);\n try {\n const result = await runCommand('git', ['rev-parse', '--show-toplevel'], { cwd: dir });\n return result.code === 0 ? result.output.trim() : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The nearest pnpm, npm, Yarn or Bun workspace root above `directory`, if any. */\nexport function enclosingWorkspace(directory: string): string | undefined {\n let dir = dirname(resolve(directory));\n for (;;) {\n if (existsSync(join(dir, 'pnpm-workspace.yaml'))) return dir;\n const manifest = join(dir, 'package.json');\n if (existsSync(manifest)) {\n try {\n const parsed: unknown = JSON.parse(readFileSync(manifest, 'utf-8'));\n if (typeof parsed === 'object' && parsed !== null && 'workspaces' in parsed) return dir;\n } catch {\n return undefined;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\nconst GIT_IDENTITY = [\n '-c',\n 'user.name=create-cogitator-app',\n '-c',\n 'user.email=create-cogitator-app@localhost',\n];\n\nasync function gitHasIdentity(cwd: string): Promise<boolean> {\n const name = await runCommand('git', ['config', 'user.name'], { cwd });\n const email = await runCommand('git', ['config', 'user.email'], { cwd });\n return (\n name.code === 0 && email.code === 0 && name.output.trim() !== '' && email.output.trim() !== ''\n );\n}\n\nexport async function initGit(directory: string): Promise<StepResult> {\n if (!(await hasCommand('git', directory)))\n return { status: 'skipped', reason: 'git is not installed' };\n const repo = await enclosingGitRepo(directory);\n if (repo) {\n return { status: 'skipped', reason: `the project is inside the git repository at ${repo}` };\n }\n for (const args of [\n ['init', '--quiet'],\n ['add', '-A'],\n ]) {\n const result = await runCommand('git', args, { cwd: directory });\n if (result.code !== 0)\n return failure(new Error(`git ${args[0]} failed:\\n${tail(result.output)}`));\n }\n const identity = (await gitHasIdentity(directory)) ? [] : GIT_IDENTITY;\n const commit = await runCommand(\n 'git',\n [...identity, 'commit', '--quiet', '-m', 'feat: initial project from create-cogitator-app'],\n { cwd: directory }\n );\n if (commit.code !== 0) return failure(new Error(`git commit failed:\\n${tail(commit.output)}`));\n return { status: 'done' };\n}\n\n/**\n * Installs the dependencies with `pm`: the one that launched the scaffolder\n * when it is `pm`, else the one on PATH. A failed install resolves with its\n * error and the code it names its cause with, it never throws.\n */\nexport async function installDependencies(\n directory: string,\n pm: PackageManager,\n inherit: boolean\n): Promise<StepResult> {\n const invocation = packageManagerInvocation(pm, ['install']);\n if (invocation.fromPath && !(await hasCommand(pm, directory))) {\n return failure(\n new CodedError(\n 'PM_NOT_FOUND',\n `${pm} is not installed, install it or pick another one with --pm`\n )\n );\n }\n try {\n const result = await runCommand(invocation.command, invocation.args, {\n cwd: directory,\n inherit,\n ...(!invocation.fromPath && { shell: false }),\n });\n if (result.code !== 0) {\n return failure(\n new CodedError(\n installErrorCode(result.output, result.code),\n `${installCommand(pm)} exited with ${result.code}:\\n${tail(result.output)}`\n )\n );\n }\n return { status: 'done' };\n } catch (error) {\n return failure(error);\n }\n}\n\nexport function assertEmptyDirectory(directory: string): void {\n if (existsSync(directory) && readdirSync(directory).length > 0) {\n throw new CodedError('DIRECTORY_NOT_EMPTY', `${directory} already exists and is not empty`);\n }\n}\n\n/**\n * Creates the project `spec` describes in `options.directory`, then installs\n * its dependencies, formats it and commits it to a new git repository. Throws\n * when the spec is invalid or the directory is taken. A failed install, format\n * or git step does not throw: the result reports it and the project stays.\n */\nexport async function scaffold(spec: unknown, options: ScaffoldOptions): Promise<ScaffoldResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n const plan = planProject(spec, options);\n assertEmptyDirectory(directory);\n\n log.start('Writing project files');\n await mkdir(directory, { recursive: true });\n await writeFiles(directory, plan.files);\n log.done(`Wrote ${plan.files.length} files`);\n\n let install: StepResult = { status: 'skipped', reason: 'install was turned off' };\n if (options.install !== false) {\n log.start(`Installing dependencies with ${plan.spec.packageManager}`);\n install = await installDependencies(\n directory,\n plan.spec.packageManager,\n options.inheritOutput ?? false\n );\n if (install.status === 'done') log.done('Installed dependencies');\n else\n log.fail(\n `Could not install dependencies, run \"${installCommand(plan.spec.packageManager)}\" yourself`\n );\n }\n\n let format: StepResult = { status: 'skipped', reason: 'dependencies are not installed' };\n if (install.status === 'done') {\n log.start('Formatting the code');\n format = await formatProject(directory);\n if (format.status === 'done') log.done('Formatted the code');\n else if (format.status === 'failed') log.warn(format.error.message);\n }\n\n await writeLock(\n directory,\n plan.files.map((file) => file.path)\n );\n\n let git: StepResult = { status: 'skipped', reason: 'git was turned off' };\n if (options.git !== false) {\n log.start('Creating a git repository');\n git = await initGit(directory);\n if (git.status === 'done') log.done('Created a git repository with the first commit');\n else if (git.status === 'skipped') log.done(`Skipped git: ${git.reason}`);\n else log.fail(git.error.message);\n }\n\n const parentWorkspace = enclosingWorkspace(directory);\n return {\n plan,\n directory,\n files: plan.files.map((file) => file.path),\n install,\n format,\n git,\n ...(parentWorkspace && { parentWorkspace }),\n };\n}\n","/**\n * A failure with a short, stable `code` that names its cause, such as\n * `HTTP_404` or `DIRECTORY_NOT_EMPTY`. The code holds no path, name or anything\n * a user typed, which is what lets telemetry report it.\n */\nexport class CodedError extends Error {\n readonly code: string;\n\n constructor(code: string, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'CodedError';\n this.code = code;\n }\n}\n\n/** `ConnectionRefused` or `TypeError` as a code: `CONNECTION_REFUSED`, `TYPE_ERROR`. */\nexport function constantCase(name: string): string {\n return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase();\n}\n","import { existsSync } from 'node:fs';\nimport { basename, dirname, join } from 'node:path';\nimport { PACKAGE_MANAGERS, type PackageManager } from './spec.js';\n\n/**\n * The package manager that launched the scaffolder, read from the\n * `npm_config_user_agent` it sets (`npm/10.9.8 node/v22...` under npx), or pnpm\n * when there is none.\n */\nexport function detectPackageManager(\n userAgent: string | undefined = process.env.npm_config_user_agent\n): PackageManager {\n const name = userAgent?.split('/')[0];\n return PACKAGE_MANAGERS.find((pm) => pm === name) ?? 'pnpm';\n}\n\n/**\n * The `packageManager` field for the pnpm, Yarn or Bun that runs the scaffolder,\n * e.g. `pnpm@10.26.0`, so corepack and the deploy image install with the same\n * version. Undefined for npm, which corepack leaves alone, and when the version\n * is unknown.\n */\nexport function detectPackageManagerSpec(\n pm: PackageManager,\n userAgent: string | undefined = process.env.npm_config_user_agent\n): string | undefined {\n if (pm === 'npm') return undefined;\n const match = /^(pnpm|yarn|bun)\\/(\\d+\\.\\d+\\.\\d+[^\\s]*)/.exec(userAgent?.trim() ?? '');\n return match?.[1] === pm ? `${match[1]}@${match[2]}` : undefined;\n}\n\n/** The command that runs the package.json script `script`. */\nexport function runScript(pm: PackageManager, script: string, args = ''): string {\n const base = pm === 'npm' ? `npm run ${script}` : `${pm} ${script}`;\n if (!args) return base;\n return pm === 'npm' ? `${base} -- ${args}` : `${base} ${args}`;\n}\n\n/** The command that runs a binary of an installed package. */\nexport function execCommand(pm: PackageManager, bin: string): string {\n if (pm === 'npm') return `npx ${bin}`;\n if (pm === 'bun') return `bunx ${bin}`;\n return `${pm} exec ${bin}`;\n}\n\n/** How to run a package manager: its command, and whether it is looked up on PATH. */\nexport interface PackageManagerInvocation {\n command: string;\n args: readonly string[];\n fromPath: boolean;\n}\n\n/**\n * The package manager that launched this process, from the `npm_execpath` it\n * sets, when that is `pm`: its JavaScript entry or its binary. npx sets the\n * path of npx-cli.js, whose npm-cli.js sits next to it.\n */\nfunction launchingPackageManager(pm: PackageManager, env: NodeJS.ProcessEnv): string | undefined {\n const execPath = env.npm_execpath;\n if (!execPath || env.npm_config_user_agent?.split('/')[0] !== pm) return undefined;\n const path =\n pm === 'npm' && basename(execPath) === 'npx-cli.js'\n ? join(dirname(execPath), 'npm-cli.js')\n : execPath;\n return existsSync(path) ? path : undefined;\n}\n\n/**\n * How to run `pm` with `args`: the very package manager that launched the\n * scaffolder when it is `pm`, so one that is not on PATH (a standalone binary,\n * one started by its full path) still runs, and at the version that launched\n * it. Otherwise `pm` from PATH.\n */\nexport function packageManagerInvocation(\n pm: PackageManager,\n args: readonly string[],\n env: NodeJS.ProcessEnv = process.env\n): PackageManagerInvocation {\n const launcher = launchingPackageManager(pm, env);\n if (!launcher) return { command: pm, args, fromPath: true };\n return /\\.[cm]?js$/.test(launcher)\n ? { command: process.execPath, args: [launcher, ...args], fromPath: false }\n : { command: launcher, args, fromPath: false };\n}\n\nexport function installCommand(pm: PackageManager): string {\n return `${pm} install`;\n}\n\nconst SYSTEM_CODES = [\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n 'EPROTO',\n 'EACCES',\n 'EPERM',\n 'ENOSPC',\n 'ENOENT',\n 'EINTEGRITY',\n 'ELIFECYCLE',\n] as const;\n\nconst PNPM_CODES = new Set([\n 'NO_MATCHING_VERSION',\n 'NO_MATURE_MATCHING_VERSION',\n 'NO_VERSIONS',\n 'META_FETCH_FAIL',\n 'TARBALL_INTEGRITY',\n 'BAD_TARBALL_SIZE',\n 'PEER_DEP_ISSUES',\n 'UNSUPPORTED_ENGINE',\n 'UNSUPPORTED_PLATFORM',\n 'OUTDATED_LOCKFILE',\n 'BROKEN_LOCKFILE',\n 'LOCKFILE_BREAKING_CHANGE',\n 'LOCKFILE_MISSING_DEPENDENCY',\n 'NO_OFFLINE_META',\n 'NO_OFFLINE_TARBALL',\n 'LINKING_FAILED',\n 'UNEXPECTED_STORE',\n 'STORE_BREAKING_CHANGE',\n 'SPEC_NOT_SUPPORTED_BY_ANY_RESOLVER',\n 'IGNORED_BUILDS',\n 'INVALID_PACKAGE_NAME',\n 'PREPARE_PACKAGE',\n ...SYSTEM_CODES,\n]);\n\nconst NPM_CODES = new Set<string>([\n 'ETARGET',\n 'ENOVERSIONS',\n 'ERESOLVE',\n 'EBADENGINE',\n 'EBADPLATFORM',\n 'ENOTSUP',\n 'EJSONPARSE',\n 'EUNSUPPORTEDPROTOCOL',\n ...SYSTEM_CODES,\n]);\n\n/** Bun's names for network failures, as the Node codes npm and pnpm report. */\nconst BUN_ERRORS: Record<string, string> = {\n ConnectionRefused: 'ECONNREFUSED',\n ConnectionResetByPeer: 'ECONNRESET',\n ConnectionClosed: 'ECONNRESET',\n ConnectionTimedOut: 'ETIMEDOUT',\n Timeout: 'ETIMEDOUT',\n NetworkUnreachable: 'ENETUNREACH',\n HostUnreachable: 'EHOSTUNREACH',\n};\n\nconst HTTP_ERROR = /^[45]\\d\\d$/;\n\nconst READERS: ReadonlyArray<(output: string) => string | undefined> = [\n (output) => {\n const code = /\\bERR_PNPM_([A-Z0-9_]+)/.exec(output)?.[1];\n if (code === undefined) return undefined;\n const known = PNPM_CODES.has(code) || /^FETCH_[45]\\d\\d$/.test(code);\n return known ? `ERR_PNPM_${code}` : 'ERR_PNPM_OTHER';\n },\n (output) => {\n const code = /^npm (?:ERR!|error) code (\\S+)/m.exec(output)?.[1];\n if (code === undefined) return undefined;\n if (NPM_CODES.has(code)) return code;\n if (/^E[45]\\d\\d$/.test(code)) return code;\n return /^npm (?:ERR!|error) command failed/m.test(output) ? 'ELIFECYCLE' : 'NPM_OTHER';\n },\n (output) =>\n [...output.matchAll(/\\bYN(\\d{4}):/g)]\n .map((match) => Number(match[1]))\n .filter((code) => code > 1 && code < 100)\n .map((code) => `YN${String(code).padStart(4, '0')}`)\n .at(-1),\n (output) =>\n /^error:? (?:No version matching |Couldn't find any versions for )/m.test(output)\n ? 'NO_MATCHING_VERSION'\n : undefined,\n (output) => {\n const status = /^error: GET \\S+ - (\\d{3})$/m.exec(output)?.[1];\n return status && HTTP_ERROR.test(status) ? `HTTP_${status}` : undefined;\n },\n (output) => (/^error Error: https?:\\/\\/\\S+: Not found/m.test(output) ? 'HTTP_404' : undefined),\n (output) =>\n /^error:? (?:\\S+ script from .* exited with|Command failed with exit code) \\d+/m.test(output)\n ? 'ELIFECYCLE'\n : undefined,\n (output) => {\n const name = /^error: ([A-Za-z]+) /m.exec(output)?.[1];\n return name !== undefined && Object.hasOwn(BUN_ERRORS, name) ? BUN_ERRORS[name] : undefined;\n },\n (output) => SYSTEM_CODES.find((code) => new RegExp(`\\\\b${code}\\\\b`).test(output)),\n];\n\n/**\n * The code a failed install names its cause with, read from the package\n * manager's output: pnpm's `ERR_PNPM_*`, npm's `code E*`, Yarn's last `YN*`\n * code other than the informational `YN0000` and the generic `YN0001`, a code\n * for the messages of Bun and Yarn 1, which have none (`NO_MATCHING_VERSION`,\n * `HTTP_404`, `ELIFECYCLE`, Bun's network errors as Node codes), or a Node\n * network or file system code in the output. Else the exit code, as `EXIT_1`.\n *\n * The output is not trusted, since install scripts print into it, so every\n * code comes from a closed set: a pnpm or npm code that is not a known one\n * becomes `ERR_PNPM_OTHER` or `NPM_OTHER`, and nothing else of the output is\n * ever returned.\n */\nexport function installErrorCode(output: string, exitCode: number): string {\n for (const read of READERS) {\n const code = read(output);\n if (code !== undefined) return code;\n }\n return /\\bYN0001:/.test(output) ? 'YN0001' : `EXIT_${exitCode}`;\n}\n\n/**\n * The install command CI runs: reproducible from the lockfile. Yarn 2 and\n * later spell it `--immutable`, Yarn 1 `--frozen-lockfile`, which is also what\n * corepack runs when package.json names no Yarn version.\n */\nexport function ciInstallCommand(pm: PackageManager, packageManagerSpec?: string): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm install --frozen-lockfile';\n case 'npm':\n return 'npm ci';\n case 'yarn': {\n const major = Number.parseInt(/^yarn@(\\d+)/.exec(packageManagerSpec ?? '')?.[1] ?? '1', 10);\n return major >= 2 ? 'yarn install --immutable' : 'yarn install --frozen-lockfile';\n }\n case 'bun':\n return 'bun install --frozen-lockfile';\n }\n}\n\nexport const LOCKFILES: Record<PackageManager, string> = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n bun: 'bun.lock',\n};\n","import { z } from 'zod';\n\nexport const PROVIDERS = ['ollama', 'openai', 'anthropic', 'google'] as const;\nexport const APP_KINDS = ['script', 'server', 'next', 'channels', 'worker'] as const;\nexport const SERVERS = ['express', 'fastify', 'hono', 'koa', 'tetsu'] as const;\nexport const MEMORIES = ['none', 'memory', 'sqlite', 'postgres', 'redis', 'mongodb'] as const;\nexport const VECTOR_STORES = ['memory', 'postgres', 'qdrant'] as const;\nexport const FEATURES = [\n 'harness',\n 'mcp',\n 'rag',\n 'workflows',\n 'durable',\n 'swarms',\n 'evals',\n 'otel',\n 'langfuse',\n 'voice',\n 'sandbox',\n 'a2a',\n] as const;\nexport const DEPLOY_TARGETS = ['none', 'docker', 'fly'] as const;\nexport const CODING_AGENTS = ['claude', 'cursor', 'codex'] as const;\nexport const PACKAGE_MANAGERS = ['pnpm', 'npm', 'yarn', 'bun'] as const;\nexport const CHANNELS = ['telegram', 'discord', 'slack', 'webchat', 'bluesky', 'threads'] as const;\n\nexport type LLMProvider = (typeof PROVIDERS)[number];\nexport type AppKind = (typeof APP_KINDS)[number];\nexport type ServerFramework = (typeof SERVERS)[number];\nexport type MemoryKind = (typeof MEMORIES)[number];\nexport type VectorStore = (typeof VECTOR_STORES)[number];\nexport type FeatureId = (typeof FEATURES)[number];\nexport type DeployTarget = (typeof DEPLOY_TARGETS)[number];\nexport type CodingAgent = (typeof CODING_AGENTS)[number];\nexport type PackageManager = (typeof PACKAGE_MANAGERS)[number];\nexport type ChannelKind = (typeof CHANNELS)[number];\n\nconst PACKAGE_NAME = /^[a-z0-9][a-z0-9._-]*$/;\nconst MAX_NAME_LENGTH = 214;\n\n/**\n * Why `name` cannot be the generated package's name, or `undefined` when it can.\n * The name lands in package.json and in generated code, so it has to be a valid\n * unscoped npm package name.\n */\nexport function validateProjectName(name: string): string | undefined {\n const trimmed = name.trim();\n if (!trimmed) return 'Project name is required';\n if (trimmed.length > MAX_NAME_LENGTH) return `Use at most ${MAX_NAME_LENGTH} characters`;\n if (!PACKAGE_NAME.test(trimmed)) {\n return 'Use lowercase letters, digits, \".\", \"_\" or \"-\", starting with a letter or digit';\n }\n return undefined;\n}\n\nconst ProjectNameSchema = z.string().superRefine((value, ctx) => {\n const error = validateProjectName(value);\n if (error) ctx.addIssue({ code: 'custom', message: error });\n});\n\n/**\n * Everything that decides what a generated project contains. A spec is plain data:\n * it is stored in the project's package.json (`cogitator.spec`) so the project can\n * be regenerated and extended with `cogitator add`, and it never holds secrets.\n */\nexport const ProjectSpecSchema = z\n .object({\n name: ProjectNameSchema,\n preset: z.string().min(1).optional(),\n app: z.enum(APP_KINDS),\n server: z.enum(SERVERS).optional(),\n channels: z.array(z.enum(CHANNELS)).default([]),\n memory: z.enum(MEMORIES),\n vectorStore: z.enum(VECTOR_STORES).default('memory'),\n features: z.array(z.enum(FEATURES)).default([]),\n provider: z.enum(PROVIDERS),\n model: z.string().trim().min(1),\n deploy: z.enum(DEPLOY_TARGETS).default('none'),\n compose: z.boolean().default(true),\n packageManager: z.enum(PACKAGE_MANAGERS),\n codingAgents: z.array(z.enum(CODING_AGENTS)).default([]),\n })\n .strict();\n\nexport type ProjectSpec = z.output<typeof ProjectSpecSchema>;\nexport type ProjectSpecInput = z.input<typeof ProjectSpecSchema>;\n\n/** `items` without duplicates, in the canonical order of `order`. */\nexport function canonical<T extends string>(items: readonly T[], order: readonly T[]): T[] {\n const set = new Set(items);\n return order.filter((item) => set.has(item));\n}\n\n/**\n * Parses and normalizes a spec: lists are deduplicated and sorted the way the\n * catalogs list them, so two specs that mean the same project are equal.\n */\nexport function parseSpec(input: unknown): ProjectSpec {\n const spec = ProjectSpecSchema.parse(input);\n return {\n ...spec,\n channels: canonical(spec.channels, CHANNELS),\n features: canonical(spec.features, FEATURES),\n codingAgents: canonical(spec.codingAgents, CODING_AGENTS),\n };\n}\n\nexport function hasFeature(spec: Pick<ProjectSpec, 'features'>, feature: FeatureId): boolean {\n return spec.features.includes(feature);\n}\n\n/** The model as the runtime addresses it: `provider/model`. */\nexport function qualifiedModel(spec: Pick<ProjectSpec, 'provider' | 'model'>): string {\n const prefix = `${spec.provider}/`;\n return spec.model.startsWith(prefix) ? spec.model : `${prefix}${spec.model}`;\n}\n\n/** The model without the provider prefix, as provider APIs and `ollama pull` name it. */\nexport function bareModel(spec: Pick<ProjectSpec, 'provider' | 'model'>): string {\n const prefix = `${spec.provider}/`;\n return spec.model.startsWith(prefix) ? spec.model.slice(prefix.length) : spec.model;\n}\n\n/** What `start` runs in a script project: the assistant, the workflow, the swarm or the voice server. */\nexport type PrimaryTarget = 'agent' | 'workflow' | 'swarm' | 'voice';\n\nexport function primaryTarget(spec: Pick<ProjectSpec, 'features'>): PrimaryTarget {\n if (hasFeature(spec, 'voice')) return 'voice';\n if (hasFeature(spec, 'workflows')) return 'workflow';\n if (hasFeature(spec, 'swarms')) return 'swarm';\n return 'agent';\n}\n\n/** Whether the project runs on Bun instead of Node. */\nexport function runsOnBun(spec: Pick<ProjectSpec, 'server'>): boolean {\n return spec.server === 'tetsu';\n}\n","import type { LLMProvider } from './spec.js';\n\nexport interface ProviderInfo {\n id: LLMProvider;\n label: string;\n /** The variable the API key is read from, absent for providers without one. */\n envKey?: string;\n /** Where to create an API key. */\n keyUrl?: string;\n /** The model a new project uses unless another one is chosen. */\n defaultModel: string;\n /** The embedding model RAG uses with this provider, absent when it has none. */\n embeddingModel?: string;\n /** The dimensions of `embeddingModel`, which vector stores size their collections by. */\n embeddingDimensions?: number;\n /** Whether the provider has a realtime voice API Cogitator drives. */\n realtime: boolean;\n /** A short line for prompts and `--help`. */\n hint: string;\n}\n\nexport const PROVIDER_INFO: Record<LLMProvider, ProviderInfo> = {\n ollama: {\n id: 'ollama',\n label: 'Ollama',\n defaultModel: 'qwen3.5:9b',\n embeddingModel: 'nomic-embed-text',\n embeddingDimensions: 768,\n realtime: false,\n hint: 'local and free, needs Ollama running',\n },\n openai: {\n id: 'openai',\n label: 'OpenAI',\n envKey: 'OPENAI_API_KEY',\n keyUrl: 'https://platform.openai.com/api-keys',\n defaultModel: 'gpt-6.1-sol',\n embeddingModel: 'text-embedding-3-small',\n embeddingDimensions: 1536,\n realtime: true,\n hint: 'GPT models, needs OPENAI_API_KEY',\n },\n anthropic: {\n id: 'anthropic',\n label: 'Anthropic',\n envKey: 'ANTHROPIC_API_KEY',\n keyUrl: 'https://console.anthropic.com/settings/keys',\n defaultModel: 'claude-sonnet-5-5',\n realtime: false,\n hint: 'Claude models, needs ANTHROPIC_API_KEY',\n },\n google: {\n id: 'google',\n label: 'Google Gemini',\n envKey: 'GOOGLE_API_KEY',\n keyUrl: 'https://aistudio.google.com/apikey',\n defaultModel: 'gemini-3.8-flash',\n embeddingModel: 'gemini-embedding-001',\n embeddingDimensions: 768,\n realtime: true,\n hint: 'Gemini models, needs GOOGLE_API_KEY',\n },\n};\n\nexport function providerInfo(provider: LLMProvider): ProviderInfo {\n return PROVIDER_INFO[provider];\n}\n\nexport function providerEnvKey(provider: LLMProvider): string | undefined {\n return PROVIDER_INFO[provider].envKey;\n}\n\nexport function defaultModel(provider: LLMProvider): string {\n return PROVIDER_INFO[provider].defaultModel;\n}\n\n/**\n * Small models with reliable tool calling that run on a laptop, offered when\n * Ollama is not reachable to list what is installed.\n */\nexport const OLLAMA_SUGGESTED_MODELS = [\n 'qwen3.5:9b',\n 'qwen3.5:4b',\n 'gemma4:e4b',\n 'llama3.1:8b',\n 'mistral-small3.2:24b',\n] as const;\n\nexport const DEFAULT_OLLAMA_URL = 'http://localhost:11434';\n","import { providerInfo } from './providers.js';\nimport { hasFeature, type ProjectSpec } from './spec.js';\n\n/** A combination the generated project could not work with, and how to fix it. */\nexport interface CompatIssue {\n message: string;\n fix: string;\n}\n\nconst A2A_SERVERS = new Set(['express', 'fastify', 'hono', 'koa']);\n\n/**\n * Every reason `spec` describes a project that would not work, empty when it is\n * consistent. Checked before any file is written, so an impossible project is\n * refused instead of generated half-broken.\n */\nexport function compatibilityIssues(spec: ProjectSpec): CompatIssue[] {\n const issues: CompatIssue[] = [];\n const provider = providerInfo(spec.provider);\n\n if (spec.app === 'server' && !spec.server) {\n issues.push({\n message: 'A server app needs a server framework',\n fix: 'pass --server hono, express, fastify, koa or tetsu',\n });\n }\n if (spec.app !== 'server' && spec.server) {\n issues.push({\n message: `--server ${spec.server} only applies to the server app`,\n fix: 'pass --app server, or leave out --server',\n });\n }\n\n if (spec.app === 'channels' && spec.channels.length === 0) {\n issues.push({\n message: 'A messaging bot needs at least one channel',\n fix: 'pass --channels webchat, telegram, discord, slack, bluesky or threads',\n });\n }\n if (spec.app !== 'channels' && spec.channels.length > 0) {\n issues.push({\n message: '--channels only applies to the messaging bot app',\n fix: 'pass --app channels, or leave out --channels',\n });\n }\n\n if (spec.server === 'tetsu' && spec.packageManager !== 'bun') {\n issues.push({\n message: 'Tetsu servers run on Bun',\n fix: 'pass --pm bun, or pick another --server',\n });\n }\n\n if (spec.server === 'tetsu' && (spec.memory === 'sqlite' || hasFeature(spec, 'harness'))) {\n issues.push({\n message:\n 'better-sqlite3, which SQLite memory and the assistant harness use, does not run on Bun',\n fix: 'use --memory memory, redis, postgres or mongodb with Tetsu, or another --server',\n });\n }\n\n if (hasFeature(spec, 'durable') && !hasFeature(spec, 'workflows')) {\n issues.push({\n message: 'Durable workflows build on the workflows feature',\n fix: 'add workflows to --features',\n });\n }\n\n if (hasFeature(spec, 'rag') && !provider.embeddingModel) {\n issues.push({\n message: `RAG needs embeddings, and ${provider.label} has no embedding API`,\n fix: 'use --provider openai, google or ollama for a RAG project',\n });\n }\n if (spec.vectorStore !== 'memory' && !hasFeature(spec, 'rag')) {\n issues.push({\n message: `--vector-store ${spec.vectorStore} only applies to RAG`,\n fix: 'add rag to --features, or leave out --vector-store',\n });\n }\n\n if (hasFeature(spec, 'voice')) {\n if (!provider.realtime) {\n issues.push({\n message: `Realtime voice needs a realtime API, and ${provider.label} has none`,\n fix: 'use --provider openai or google for a voice project',\n });\n }\n }\n if (hasFeature(spec, 'voice') && spec.app !== 'script') {\n issues.push({\n message: 'The voice feature serves its own page and WebSocket as the app',\n fix: 'use --app script for a voice agent',\n });\n }\n\n if (hasFeature(spec, 'a2a')) {\n const servable =\n spec.app === 'next' || (spec.app === 'server' && A2A_SERVERS.has(spec.server ?? ''));\n if (!servable) {\n issues.push({\n message: 'A2A serves agents over HTTP from Express, Fastify, Hono, Koa or Next.js',\n fix: 'use --app server with --server hono, express, fastify or koa, or --app next',\n });\n }\n }\n\n if (hasFeature(spec, 'mcp') && spec.app === 'next') {\n issues.push({\n message:\n 'The MCP feature starts MCP servers as child processes, which a Next.js deployment cannot',\n fix: 'use --app script, server, channels or worker for MCP',\n });\n }\n\n if (spec.app === 'next' && spec.server) {\n issues.push({ message: 'Next.js is its own server', fix: 'leave out --server' });\n }\n\n if (spec.deploy === 'fly' && spec.memory === 'mongodb') {\n issues.push({\n message: 'Fly.io has no managed MongoDB the deploy can provision',\n fix: 'use --memory postgres, redis or sqlite with --deploy fly',\n });\n }\n\n return issues;\n}\n\nexport class IncompatibleSpecError extends Error {\n readonly code = 'INCOMPATIBLE_SPEC';\n readonly issues: CompatIssue[];\n\n constructor(issues: CompatIssue[]) {\n super(\n [\n 'The chosen options do not fit together:',\n ...issues.map((i) => `- ${i.message}: ${i.fix}`),\n ].join('\\n')\n );\n this.name = 'IncompatibleSpecError';\n this.issues = issues;\n }\n}\n\nexport function assertCompatible(spec: ProjectSpec): void {\n const issues = compatibilityIssues(spec);\n if (issues.length > 0) throw new IncompatibleSpecError(issues);\n}\n","/**\n * Source text for a generated file, written as an indented template literal.\n *\n * Escapes work as in any template literal: write `\\\\n` for a backslash and an\n * `n` in the generated code, `` \\` `` for a backtick and `\\${` for `${`.\n *\n * The common indentation of the template is removed, so a template can follow the\n * indentation of the code that writes it. A multi-line value is indented to the column\n * of its placeholder, so a nested block lands where it is interpolated. `false`, `null`\n * and `undefined` render as nothing, and a line left blank by them is dropped, which\n * makes `${cond && 'line'}` an optional line. Runs of blank lines collapse to one, and\n * the result ends with exactly one newline.\n */\nexport function code(strings: TemplateStringsArray, ...values: unknown[]): string {\n const parts = Array.from(strings, (part, index) => {\n if (part === undefined)\n throw new Error(`Invalid escape sequence in code template part ${index}`);\n return part;\n });\n const dropped = new Set<number>();\n let out = '';\n\n for (let i = 0; i < parts.length; i++) {\n out += parts[i];\n if (i >= values.length) break;\n\n const value = values[i];\n if (value === false || value === null || value === undefined) {\n dropped.add(lineIndex(out));\n continue;\n }\n\n const text = String(value).replace(/\\n$/, '');\n const lineStart = out.lastIndexOf('\\n') + 1;\n const indent = /^[ \\t]*/.exec(out.slice(lineStart))?.[0] ?? '';\n out += text.replace(/\\n(?=[^\\n])/g, `\\n${indent}`);\n }\n\n const lines = out.split('\\n');\n const kept = lines.filter((line, index) => !(dropped.has(index) && line.trim() === ''));\n return finish(dedent(kept));\n}\n\nfunction lineIndex(text: string): number {\n let count = 0;\n for (const char of text) if (char === '\\n') count++;\n return count;\n}\n\nfunction dedent(lines: string[]): string[] {\n while (lines.length > 0 && lines[0].trim() === '') lines.shift();\n while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();\n\n let common = Infinity;\n for (const line of lines) {\n if (line.trim() === '') continue;\n common = Math.min(common, /^ */.exec(line)?.[0].length ?? 0);\n }\n if (!Number.isFinite(common) || common === 0) return lines;\n return lines.map((line) => (line.trim() === '' ? '' : line.slice(common)));\n}\n\nfunction finish(lines: string[]): string {\n const collapsed: string[] = [];\n for (const line of lines) {\n const blank = line.trim() === '';\n if (blank && collapsed.length > 0 && collapsed[collapsed.length - 1] === '') continue;\n collapsed.push(blank ? '' : line.replace(/[ \\t]+$/, ''));\n }\n return collapsed.join('\\n') + '\\n';\n}\n\n/** `value` as a single-quoted TypeScript string literal, safe for any input. */\nexport function tsString(value: string): string {\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\r/g, '\\\\r')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\p{Zl}/gu, '\\\\u2028')\n .replace(/\\p{Zp}/gu, '\\\\u2029');\n return `'${escaped}'`;\n}\n\n/** `name` as a property key: bare when it is an identifier, quoted otherwise. */\nexport function tsKey(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : tsString(name);\n}\n\n/** A YAML scalar for `value`, quoted only when YAML would read it as something else. */\nexport function yamlString(value: string): string {\n if (value === '' || /^[\\s]|[\\s]$/.test(value)) return JSON.stringify(value);\n if (/^(true|false|yes|no|on|off|null|~|[-+]?\\d[\\d._:eE+-]*)$/i.test(value)) {\n return JSON.stringify(value);\n }\n if (/[:#{}[\\],&*!|>'\"%@`]|^[-?]/.test(value)) return JSON.stringify(value);\n return value;\n}\n","declare const __COGITATOR_VERSIONS__: Record<string, string> | undefined;\ndeclare const __SCAFFOLDER_VERSION__: string | undefined;\n\n/** The version of create-cogitator-app itself, inlined at build time. */\nexport function scaffolderVersion(): string {\n return typeof __SCAFFOLDER_VERSION__ === 'undefined' ? '0.0.0' : __SCAFFOLDER_VERSION__;\n}\n\n/**\n * The versions of the `@cogitator-ai/*` packages, inlined when the scaffolder is\n * built (and when its tests run) from the workspace it is released from.\n */\nfunction workspaceVersions(): Record<string, string> {\n return typeof __COGITATOR_VERSIONS__ === 'undefined' ? {} : __COGITATOR_VERSIONS__;\n}\n\nexport type CogitatorPackage = `@cogitator-ai/${string}`;\n\n/** The range a generated project depends on for `name`: a caret on the version released with the scaffolder. */\nexport function cogitatorVersion(name: CogitatorPackage): string {\n const version = workspaceVersions()[name];\n if (!version) {\n throw new Error(`${name} is not a published @cogitator-ai package, so its version is unknown`);\n }\n return `^${version}`;\n}\n\n/** Every `@cogitator-ai/*` version the scaffolder knows, for `--json` and diagnostics. */\nexport function knownCogitatorVersions(): Record<string, string> {\n return { ...workspaceVersions() };\n}\n\n/**\n * Third-party packages generated projects depend on, in one place so every\n * feature asks for the same range. Ranges follow the current majors.\n */\nexport const VERSIONS = {\n zod: '^4.6.5',\n typescript: '^7.0.2',\n typesNode: '^24.19.1',\n tsx: '^4.23.15',\n vitest: '^5.0.3',\n biome: '^2.5.15',\n express: '^5.2.1',\n typesExpress: '^5.0.6',\n fastify: '^5.12.5',\n fastifyCors: '^11.3.0',\n hono: '^4.13.13',\n honoNodeServer: '^2.1.3',\n koa: '^3.2.1',\n koaRouter: '^15.7.0',\n typesKoa: '^3.0.3',\n typesKoaRouter: '^15.0.0',\n koaCors: '^5.0.0',\n typesKoaCors: '^5.0.1',\n koaBodyparser: '^6.1.0',\n tetsuCore: '^0.6.3',\n tetsuSse: '^0.6.3',\n tetsuOpenapi: '^0.6.3',\n typesBun: '^1.4.2',\n next: '^16.4.0',\n react: '^19.3.0',\n reactDom: '^19.3.0',\n typesReact: '^19.3.0',\n typesReactDom: '^19.3.0',\n tailwind: '^4.3.3',\n tailwindPostcss: '^4.3.3',\n reactMarkdown: '^10.1.0',\n betterSqlite3: '^13.0.3',\n pg: '^8.23.1',\n ioredis: '^6.0.0',\n mongodb: '^7.7.0',\n qdrant: '^1.19.0',\n grammy: '^1.46.0',\n discord: '^14.27.0',\n slackBolt: '^5.1.0',\n ws: '^8.22.0',\n atprotoApi: '^0.24.0',\n langfuse: '^3.39.2',\n modelContextProtocol: '^1.32.1',\n} as const;\n\n/** Container images compose and deploy use, pinned so a project starts the same way every time. */\nexport const IMAGES = {\n redis: 'redis:8.8-alpine',\n postgres: 'pgvector/pgvector:0.8.7-pg18-trixie',\n mongodb: 'mongo:8.3',\n qdrant: 'qdrant/qdrant:v1.19.2',\n ollama: 'ollama/ollama:0.40.0',\n jaeger: 'jaegertracing/jaeger:2.22.0',\n} as const;\n\n/** The Node.js versions generated projects support: `--env-file-if-exists` needs 22.9+. */\nexport const NODE_ENGINES = '>=22.12.0';\n\n/** The Bun version Tetsu servers need. */\nexport const BUN_ENGINES = '>=1.4.0';\n","import { code, tsKey, tsString, yamlString } from './code.js';\nimport type { ComposeService, EnvVar, ProjectBuilder, RegistryEntry } from './project.js';\nimport { DEFAULT_OLLAMA_URL } from './providers.js';\nimport { qualifiedModel, runsOnBun } from './spec.js';\nimport { BUN_ENGINES, NODE_ENGINES } from './versions.js';\n\n/** Where each script goes in package.json; the rest follow alphabetically. */\nconst SCRIPT_ORDER = [\n 'dev',\n 'ask',\n 'build',\n 'start',\n 'test',\n 'typecheck',\n 'lint',\n 'format',\n 'eval',\n 'dev:studio',\n 'doctor',\n];\n\nfunction sortedRecord(entries: Map<string, string>): Record<string, string> {\n return Object.fromEntries([...entries].sort(([a], [b]) => a.localeCompare(b)));\n}\n\nexport function orderedScripts(scripts: Map<string, string>): Record<string, string> {\n const rank = (name: string) => {\n const index = SCRIPT_ORDER.indexOf(name);\n return index === -1 ? SCRIPT_ORDER.length : index;\n };\n return Object.fromEntries(\n [...scripts].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b))\n );\n}\n\nexport interface PackageJsonExtras {\n /** `name@version` of the package manager, written to `packageManager`. */\n packageManagerSpec?: string;\n /** What `cogitator add` needs to extend the project later. */\n cogitator: Record<string, unknown>;\n}\n\nexport function emitPackageJson(project: ProjectBuilder, extras: PackageJsonExtras): void {\n const { spec } = project;\n const bun = runsOnBun(spec);\n const native = [...project.nativeBuilds].sort();\n\n const pkg: Record<string, unknown> = {\n name: spec.name,\n version: '0.1.0',\n private: true,\n type: 'module',\n engines: bun ? { bun: BUN_ENGINES } : { node: NODE_ENGINES },\n ...(extras.packageManagerSpec && { packageManager: extras.packageManagerSpec }),\n scripts: orderedScripts(project.scripts),\n dependencies: sortedRecord(project.dependencies),\n devDependencies: sortedRecord(project.devDependencies),\n ...(spec.packageManager === 'bun' && native.length > 0 && { trustedDependencies: native }),\n cogitator: extras.cogitator,\n };\n\n project.file('package.json', JSON.stringify(pkg, null, 2) + '\\n');\n}\n\n/**\n * Packages with build scripts the project does not need: optional native\n * speedups of the Docker client the CLI uses (ssh2, cpu-features), a\n * protobufjs version check, and better-sqlite3, which the CLI depends on and\n * which ships prebuilt binaries, so its implicit `node-gyp rebuild` only\n * needs a compiler. Saying no to them explicitly keeps pnpm 11 from failing\n * the install over builds nobody approved, which pnpm 11.0 does even outside\n * CI. A feature that allows one of them wins.\n */\nconst SKIPPED_BUILDS = ['better-sqlite3', 'cpu-features', 'protobufjs', 'ssh2'];\n\n/**\n * pnpm runs dependency build scripts only when they are allowed, and fails\n * the install in CI on scripts nobody decided on: the `pnpm-workspace.yaml`\n * that allows the native builds a project needs and declines the rest.\n */\nexport function pnpmWorkspaceYaml(nativeBuilds: Iterable<string>): string {\n const allowed = new Set(nativeBuilds);\n const entries = [\n ...[...allowed].map((name) => [name, true] as const),\n ...SKIPPED_BUILDS.filter((name) => !allowed.has(name)).map((name) => [name, false] as const),\n ].sort(([a], [b]) => a.localeCompare(b));\n return ['allowBuilds:', ...entries.map(([name, allow]) => ` ${name}: ${allow}`), ''].join('\\n');\n}\n\nexport function emitPnpmWorkspace(project: ProjectBuilder): void {\n if (project.spec.packageManager !== 'pnpm') return;\n project.file('pnpm-workspace.yaml', pnpmWorkspaceYaml([...project.nativeBuilds, 'esbuild']));\n}\n\nfunction envExampleLine(variable: EnvVar): string[] {\n const value = variable.secret ? '' : (variable.example ?? '');\n const assignment = `${variable.name}=${value}`;\n return [`# ${variable.description}`, variable.required ? assignment : `# ${assignment}`];\n}\n\nexport function emitEnvExample(project: ProjectBuilder): void {\n const variables = [...project.env.values()];\n const lines = ['# Copy to .env and fill in. Lines starting with # are optional.', ''];\n for (const variable of variables) lines.push(...envExampleLine(variable), '');\n project.file('.env.example', lines.join('\\n').replace(/\\n+$/, '\\n'));\n}\n\n/** `.env` with the secrets given to the scaffolder, readable by the owner only. */\nexport function emitEnvFile(project: ProjectBuilder, secrets: Record<string, string>): void {\n const entries = Object.entries(secrets).filter(([, value]) => value !== '');\n if (entries.length === 0) return;\n const lines = entries.map(([name, value]) => `${name}=${formatEnvValue(value)}`);\n project.files.set('.env', { path: '.env', content: lines.join('\\n') + '\\n', mode: 0o600 });\n}\n\nexport function formatEnvValue(value: string): string {\n if (/^[A-Za-z0-9_./:@+,=-]*$/.test(value)) return value;\n const escaped = value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t');\n return `\"${escaped}\"`;\n}\n\nfunction zodFor(variable: EnvVar): string {\n return variable.required\n ? `required(${tsString(variable.name)}, ${tsString(variable.description)})`\n : 'z.string().optional()';\n}\n\nexport function emitEnvModule(project: ProjectBuilder): void {\n const variables = [...project.env.values()];\n const fields = variables.map((v) => `${tsKey(v.name)}: ${zodFor(v)},`).join('\\n');\n const anyRequired = variables.some((v) => v.required);\n project.file(\n 'src/env.ts',\n code`\n import { z } from 'zod';\n\n ${\n anyRequired &&\n code`\n function required(name: string, description: string) {\n const message = \\`\\${name} is required: \\${description}\\`;\n return z.string({ error: message }).min(1, message);\n }\n `\n }\n\n const EnvSchema = z.object({\n ${fields || '// The project reads no environment variables yet.'}\n });\n\n export type Env = z.infer<typeof EnvSchema>;\n\n /**\n * The environment the project needs, checked at startup so a missing key fails\n * with its name and where to get it instead of as a provider error mid-run.\n */\n export function loadEnv(source: Record<string, string | undefined> = process.env): Env {\n const parsed = EnvSchema.safeParse(source);\n if (parsed.success) return parsed.data;\n const problems = parsed.error.issues.map((issue) => \\` \\${issue.path.join('.') || 'env'}: \\${issue.message}\\`);\n throw new Error(\n \\`Missing or invalid environment variables, copy .env.example to .env and fill it in:\\\\n\\${problems.join('\\\\n')}\\`\n );\n }\n `\n );\n}\n\nfunction yamlList(items: readonly string[]): string {\n return `[${items.map((item) => JSON.stringify(item)).join(', ')}]`;\n}\n\nfunction composeService(service: ComposeService): string[] {\n const lines = [` ${service.name}:`, ` image: ${service.image}`];\n if (service.ports?.length) {\n lines.push(' ports:', ...service.ports.map((port) => ` - ${JSON.stringify(port)}`));\n }\n if (service.environment) {\n lines.push(\n ' environment:',\n ...Object.entries(service.environment).map(([k, v]) => ` ${k}: ${yamlString(v)}`)\n );\n }\n if (service.volumes?.length) {\n lines.push(' volumes:', ...service.volumes.map((volume) => ` - ${volume}`));\n }\n if (service.command) lines.push(` command: ${yamlList(service.command)}`);\n if (service.entrypoint) lines.push(` entrypoint: ${yamlList(service.entrypoint)}`);\n if (service.dependsOn) {\n lines.push(' depends_on:');\n for (const [name, condition] of Object.entries(service.dependsOn)) {\n lines.push(` ${name}:`, ` condition: ${condition}`);\n }\n }\n if (service.healthcheck) {\n const h = service.healthcheck;\n lines.push(\n ' healthcheck:',\n ` test: ${yamlList(h.test)}`,\n ` interval: ${h.interval}`,\n ` timeout: ${h.timeout}`,\n ` retries: ${h.retries}`\n );\n }\n if (service.restart) lines.push(` restart: ${JSON.stringify(service.restart)}`);\n return lines;\n}\n\nexport function emitCompose(project: ProjectBuilder): void {\n if (!project.spec.compose || project.services.size === 0) return;\n const services = [...project.services.values()];\n const lines = [\n '# Services for local development: docker compose up -d',\n 'services:',\n ...services.flatMap((service, i) => [...(i > 0 ? [''] : []), ...composeService(service)]),\n ];\n if (project.volumes.size > 0) {\n lines.push('', 'volumes:', ...[...project.volumes].sort().map((volume) => ` ${volume}:`));\n }\n project.file('docker-compose.yml', lines.join('\\n') + '\\n');\n}\n\nexport function emitCogitatorYml(project: ProjectBuilder): void {\n const { spec } = project;\n const lines = [\n '# The Cogitator runtime: src/cogitator.ts loads it with loadConfig(), and',\n '# `cogitator deploy` reads it to build and ship the project. ${VAR:-default}',\n '# reads the environment, and API keys come from .env (OPENAI_API_KEY and the like).',\n '',\n 'llm:',\n ` defaultProvider: ${spec.provider}`,\n ` defaultModel: ${yamlString(qualifiedModel(spec))}`,\n ];\n if (spec.provider === 'ollama') {\n lines.push(\n ' providers:',\n ' ollama:',\n ` baseUrl: \\${OLLAMA_BASE_URL:-${DEFAULT_OLLAMA_URL}}`\n );\n }\n\n if (project.memoryYml.length > 0) {\n lines.push('', 'memory:', ...project.memoryYml.map((line) => ` ${line}`));\n }\n\n for (const [section, body] of project.ymlSections) {\n lines.push('', `${section}:`, ...body.map((line) => ` ${line}`));\n }\n\n const deploy: string[] = [];\n if (spec.deploy !== 'none') deploy.push(` target: ${spec.deploy}`);\n if (project.deploy.kind) deploy.push(` kind: ${project.deploy.kind}`);\n if (project.deploy.port) deploy.push(` port: ${project.deploy.port}`);\n if (project.deploy.healthPath) deploy.push(' health:', ` path: ${project.deploy.healthPath}`);\n const secrets = [...project.env.values()]\n .filter((v) => v.deploy ?? (v.secret && v.required))\n .map((v) => v.name);\n if (secrets.length > 0) deploy.push(' secrets:', ...secrets.map((name) => ` - ${name}`));\n if (deploy.length > 0) lines.push('', 'deploy:', ...deploy);\n\n project.file('cogitator.yml', lines.join('\\n') + '\\n');\n}\n\nfunction registryGroup(entries: RegistryEntry[], kind: RegistryEntry['kind']): string | false {\n const items = entries.filter((entry) => entry.kind === kind);\n if (items.length === 0) return false;\n const body = items.map((entry) =>\n entry.name === entry.binding ? `${entry.name},` : `${tsKey(entry.name)}: ${entry.binding},`\n );\n return `{\\n ${body.join('\\n ')}\\n}`;\n}\n\nexport function emitRegistry(project: ProjectBuilder): void {\n const entries = project.registry;\n const imports = new Map<string, string[]>();\n for (const entry of entries) {\n const bindings = imports.get(entry.from) ?? [];\n bindings.push(entry.binding);\n imports.set(entry.from, bindings);\n }\n const importLines = [...imports]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([from, bindings]) => `import { ${[...new Set(bindings)].sort().join(', ')} } from '${from}';`\n );\n\n const observed = project.files.has('src/observability.ts');\n if (observed) importLines.push(\"import { observers } from './observability.js';\");\n importLines.sort((a, b) =>\n a.slice(a.indexOf(\"from '\")).localeCompare(b.slice(b.indexOf(\"from '\")))\n );\n const agents = registryGroup(entries, 'agents');\n const workflows = registryGroup(entries, 'workflows');\n const swarms = registryGroup(entries, 'swarms');\n\n project.file(\n 'src/cogitator.ts',\n code`\n import { loadConfig } from '@cogitator-ai/config';\n import { Cogitator, type CogitatorConfig } from '@cogitator-ai/core';\n ${swarms && \"import type { SwarmConfig } from '@cogitator-ai/swarms';\"}\n ${importLines.join('\\n')}\n\n /**\n * A runtime configured by cogitator.yml and the environment. \\`overrides\\` are\n * merged over that configuration: tests pass a mock model backend here.\n */\n export function createCogitator(overrides: CogitatorConfig = {}): Cogitator {\n const config = loadConfig();\n return new Cogitator({ ...config, ${observed ? 'observers, ' : ''}...overrides, llm: { ...config.llm, ...overrides.llm } });\n }\n\n /** The runtime the project shares. */\n export const cogitator = createCogitator();\n\n /**\n * The registry: every agent${workflows ? ', workflow' : ''}${swarms ? ' and swarm' : ''} of the project by name.\n * The entry points, the tests and \\`cogitator dev\\` all find them here.\n */\n export const agents = ${agents || '{}'};\n ${workflows && `\\nexport const workflows = ${workflows};`}\n ${swarms && `\\nexport const swarms = ${swarms} satisfies Record<string, SwarmConfig>;`}\n `\n );\n}\n\nexport function emitToolsIndex(project: ProjectBuilder): void {\n const imports = [...project.tools]\n .sort((a, b) => a.from.localeCompare(b.from))\n .map((tool) => `import { ${tool.binding} } from '${tool.from}';`);\n project.file(\n 'src/tools/index.ts',\n code`\n ${imports.join('\\n')}\n\n /** The tools the assistant can call. Add a tool here to give it to the assistant. */\n export const tools = [${project.tools.map((tool) => (tool.spread ? `...${tool.binding}` : tool.binding)).join(', ')}];\n `\n );\n}\n\nexport function emitGitignore(project: ProjectBuilder): void {\n project.file('.gitignore', [...project.gitignore].join('\\n') + '\\n');\n}\n\nexport const AGENT_RULES_BEGIN = '<!-- BEGIN:cogitator-agent-rules -->';\nexport const AGENT_RULES_END = '<!-- END:cogitator-agent-rules -->';\n\n/** The managed block of AGENTS.md: the scaffolder and `cogitator add` rewrite it, nothing else. */\nexport function agentRulesBlock(project: ProjectBuilder): string {\n const sections = project.agentsMd.map(\n (section) => `## ${section.title}\\n\\n${section.body.trim()}`\n );\n return [\n AGENT_RULES_BEGIN,\n '# This is a Cogitator project',\n '',\n 'Cogitator is a TypeScript runtime for AI agents, and its APIs move faster than model training data. Before you write Cogitator code, read the docs bundled with the installed version in `node_modules/@cogitator-ai/core/docs/`, starting with `index.md`, and trust them over what you remember.',\n '',\n 'Everything the project runs is registered in `src/cogitator.ts`: the runtime (configured by `cogitator.yml` and `.env`) and the agents' +\n (project.registry.some((e) => e.kind === 'workflows') ? ', workflows' : '') +\n (project.registry.some((e) => e.kind === 'swarms') ? ' and swarms' : '') +\n ' by name. Register new ones there so the entry points, the tests and `cogitator dev` find them.',\n '',\n ...sections.flatMap((section) => [section, '']),\n AGENT_RULES_END,\n ].join('\\n');\n}\n\nexport function emitAgentsMd(project: ProjectBuilder): void {\n const nextBlock =\n project.spec.app === 'next'\n ? [\n '<!-- BEGIN:nextjs-agent-rules -->',\n '# This is NOT the Next.js you know',\n '',\n 'This version has breaking changes, so APIs, conventions and file structure may differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code, and heed deprecation notices.',\n '<!-- END:nextjs-agent-rules -->',\n '',\n ]\n : [];\n project.file(\n 'AGENTS.md',\n [\n ...nextBlock,\n agentRulesBlock(project),\n '',\n '## Project notes',\n '',\n 'Add what agents should know about this project here. The block above is managed by Cogitator.',\n '',\n ].join('\\n')\n );\n project.file('CLAUDE.md', '@AGENTS.md\\n');\n}\n\nconst RELATIVE_JS_IMPORT = /(\\bfrom\\s+|\\bimport\\s*\\(\\s*)(['\"])(\\.{1,2}\\/[^'\"]+?)\\.js\\2/g;\n\n/**\n * Next.js bundles with `moduleResolution: bundler`, which resolves relative\n * imports without an extension and does not map `./x.js` to `./x.ts`. Generated\n * code imports with `.js` for Node, so a Next.js app gets the extensions dropped.\n */\nexport function adaptImportsForBundler(project: ProjectBuilder): void {\n if (project.spec.app !== 'next') return;\n for (const file of project.files.values()) {\n if (!/\\.tsx?$/.test(file.path)) continue;\n file.content = file.content.replace(RELATIVE_JS_IMPORT, '$1$2$3$2');\n }\n}\n","import { code } from '../code.js';\n\n/** `fetch_url`: reads public web pages and JSON, refuses private networks, follows redirects hop by hop. */\nexport const FETCH_URL_TS = code`\n import { lookup } from 'node:dns/promises';\n import { BlockList, isIP } from 'node:net';\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n const TIMEOUT_MS = 15_000;\n const MAX_BYTES = 200_000;\n const MAX_REDIRECTS = 5;\n\n const privateNetworks = new BlockList();\n for (const [network, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['224.0.0.0', 4],\n ] as const) {\n privateNetworks.addSubnet(network, prefix, 'ipv4');\n }\n for (const [network, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ] as const) {\n privateNetworks.addSubnet(network, prefix, 'ipv6');\n }\n\n /** Whether \\`address\\` is loopback, link-local, private or otherwise not on the public internet. */\n export function isPrivateAddress(address: string): boolean {\n const mapped = /^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/i.exec(address);\n if (mapped) return privateNetworks.check(mapped[1], 'ipv4');\n const family = isIP(address);\n if (family === 0) return true;\n return privateNetworks.check(address, family === 4 ? 'ipv4' : 'ipv6');\n }\n\n async function assertPublic(url: URL): Promise<void> {\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new Error(\\`Only http and https URLs can be fetched, not \\${url.protocol}\\`);\n }\n const host = url.hostname.replace(/^\\\\[|\\\\]$/g, '');\n const addresses = isIP(host) ? [host] : (await lookup(host, { all: true })).map((a) => a.address);\n const blocked = addresses.find(isPrivateAddress);\n if (blocked) {\n throw new Error(\\`\\${url.hostname} resolves to \\${blocked}, which is not on the public internet\\`);\n }\n }\n\n const ENTITIES: Record<string, string> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: ' ',\n };\n\n function decodeEntities(text: string): string {\n return text.replace(/&(#x[0-9a-f]+|#\\\\d+|[a-z]+);/gi, (entity, body: string) => {\n if (body[0] === '#') {\n const point = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : Number(body.slice(1));\n return Number.isInteger(point) && point > 0 && point <= 0x10ffff ? String.fromCodePoint(point) : entity;\n }\n return ENTITIES[body.toLowerCase()] ?? entity;\n });\n }\n\n /** The readable text of an HTML page: no scripts, styles or tags, one blank line between blocks. */\n export function htmlToText(html: string): string {\n return decodeEntities(\n html\n .replace(/<(script|style|noscript|svg|template|head)\\\\b[\\\\s\\\\S]*?<\\\\/\\\\1>/gi, ' ')\n .replace(/<br\\\\s*\\\\/?>|<\\\\/?(?:p|div|li|ul|ol|h[1-6]|tr|table|section|article|header|footer|main|nav|pre|blockquote)\\\\b[^>]*>/gi, '\\\\n')\n .replace(/<[^>]*>/g, ' ')\n )\n .replace(/[ \\\\t\\\\f\\\\v\\\\u00a0]+/g, ' ')\n .replace(/ *\\\\n */g, '\\\\n')\n .replace(/\\\\n{3,}/g, '\\\\n\\\\n')\n .trim();\n }\n\n async function readLimited(body: ReadableStream<Uint8Array>): Promise<{ text: string; truncated: boolean }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let text = '';\n let bytes = 0;\n try {\n while (bytes < MAX_BYTES) {\n const { done, value } = await reader.read();\n if (done) return { text: text + decoder.decode(), truncated: false };\n const room = MAX_BYTES - bytes;\n bytes += value.byteLength;\n text += decoder.decode(value.byteLength > room ? value.subarray(0, room) : value, { stream: true });\n }\n return { text: text + decoder.decode(), truncated: true };\n } finally {\n await reader.cancel().catch(() => undefined);\n }\n }\n\n export const fetchUrl = tool({\n name: 'fetch_url',\n description:\n 'Fetch a public web page or JSON document over HTTP(S) and return its text. Pages are converted to plain text and cut at 200 kB.',\n parameters: z.object({\n url: z.url({ protocol: /^https?$/ }).describe('The http or https URL to fetch'),\n }),\n sideEffects: ['network'],\n timeout: TIMEOUT_MS + 1_000,\n execute: async ({ url }, { signal }) => {\n const timeout = AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]);\n let target = new URL(url);\n\n for (let hop = 0; ; hop++) {\n await assertPublic(target);\n const response = await fetch(target, {\n redirect: 'manual',\n signal: timeout,\n headers: { 'user-agent': 'cogitator-agent/1.0', accept: 'text/html,application/json,text/plain;q=0.9,*/*;q=0.5' },\n });\n\n const location = response.headers.get('location');\n if (response.status >= 300 && response.status < 400 && location) {\n await response.body?.cancel();\n if (hop >= MAX_REDIRECTS) throw new Error(\\`Stopped after \\${MAX_REDIRECTS} redirects\\`);\n target = new URL(location, target);\n continue;\n }\n\n const contentType = response.headers.get('content-type') ?? 'unknown';\n const { text, truncated } = response.body ? await readLimited(response.body) : { text: '', truncated: false };\n return {\n url: target.toString(),\n status: response.status,\n contentType,\n truncated,\n content: contentType.includes('html') ? htmlToText(text) : text,\n };\n }\n },\n });\n`;\n\n/** `current_time`: the date and time in any IANA time zone. */\nexport const CURRENT_TIME_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n function assertTimeZone(timeZone: string): void {\n try {\n new Intl.DateTimeFormat('en-US', { timeZone });\n } catch {\n throw new Error(\\`Unknown time zone \"\\${timeZone}\", use an IANA name such as Europe/Berlin\\`);\n }\n }\n\n export const currentTime = tool({\n name: 'current_time',\n description: 'The current date and time, in UTC and in a given IANA time zone.',\n parameters: z.object({\n timeZone: z\n .string()\n .optional()\n .describe('An IANA time zone such as America/New_York, the local one when left out'),\n }),\n execute: async ({ timeZone }) => {\n const zone = timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n assertTimeZone(zone);\n const now = new Date();\n return {\n utc: now.toISOString(),\n timeZone: zone,\n local: new Intl.DateTimeFormat('en-US', {\n timeZone: zone,\n dateStyle: 'full',\n timeStyle: 'long',\n }).format(now),\n };\n },\n });\n`;\n\n/** `calculator`: arithmetic through a small parser, never through `eval`. */\nexport const CALCULATOR_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n const FUNCTIONS: Record<string, (...args: number[]) => number> = {\n abs: Math.abs,\n ceil: Math.ceil,\n cos: Math.cos,\n exp: Math.exp,\n floor: Math.floor,\n ln: Math.log,\n log: Math.log10,\n max: Math.max,\n min: Math.min,\n round: Math.round,\n sin: Math.sin,\n sqrt: Math.sqrt,\n tan: Math.tan,\n };\n\n const CONSTANTS: Record<string, number> = { pi: Math.PI, e: Math.E };\n\n /**\n * Evaluates \\`+ - * / % ^\\`, parentheses, the functions in FUNCTIONS and the\n * constants pi and e. Precedence is the usual one, \\`^\\` is right-associative\n * and binds tighter than a unary minus, so \\`-2^2\\` is -4. \\`%\\` is the\n * remainder of a division, never a percentage.\n */\n class Parser {\n private position = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): number {\n const value = this.sum();\n this.skipSpace();\n if (this.position < this.source.length) {\n throw new Error(\\`Unexpected \"\\${this.source[this.position]}\" at position \\${this.position + 1}\\`);\n }\n return value;\n }\n\n private sum(): number {\n let value = this.product();\n for (;;) {\n if (this.take('+')) value += this.product();\n else if (this.take('-')) value -= this.product();\n else return value;\n }\n }\n\n private product(): number {\n let value = this.unary();\n for (;;) {\n if (this.take('*')) value *= this.unary();\n else if (this.take('/')) {\n const divisor = this.unary();\n if (divisor === 0) throw new Error('Division by zero');\n value /= divisor;\n } else if (this.take('%')) {\n if (!this.startsOperand()) {\n throw new Error(\n \\`\"%\" is the remainder of a division and needs a number after it. For a percentage divide by 100: \\${value}% is \\${value} / 100\\`\n );\n }\n value %= this.unary();\n } else return value;\n }\n }\n\n private unary(): number {\n if (this.take('-')) return -this.unary();\n if (this.take('+')) return this.unary();\n return this.power();\n }\n\n private power(): number {\n const base = this.primary();\n return this.take('^') ? base ** this.unary() : base;\n }\n\n private primary(): number {\n this.skipSpace();\n if (this.take('(')) {\n const value = this.sum();\n this.expect(')');\n return value;\n }\n\n const number = /^(?:\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)(?:e[+-]?\\\\d+)?/i.exec(this.rest());\n if (number) {\n this.position += number[0].length;\n return Number(number[0]);\n }\n\n const name = /^[a-z]+/i.exec(this.rest())?.[0].toLowerCase();\n if (name) {\n this.position += name.length;\n if (name in CONSTANTS) return CONSTANTS[name];\n const fn = FUNCTIONS[name];\n if (!fn) throw new Error(\\`Unknown name \"\\${name}\"\\`);\n this.expect('(');\n const args = [this.sum()];\n while (this.take(',')) args.push(this.sum());\n this.expect(')');\n return fn(...args);\n }\n\n throw new Error(\n this.position < this.source.length\n ? \\`Unexpected \"\\${this.source[this.position]}\" at position \\${this.position + 1}\\`\n : 'The expression ends too early'\n );\n }\n\n private startsOperand(): boolean {\n this.skipSpace();\n return /[\\\\d.(a-z+-]/i.test(this.source[this.position] ?? '');\n }\n\n private rest(): string {\n return this.source.slice(this.position);\n }\n\n private skipSpace(): void {\n while (/\\\\s/.test(this.source[this.position] ?? '')) this.position++;\n }\n\n private take(token: string): boolean {\n this.skipSpace();\n if (this.source[this.position] !== token) return false;\n this.position++;\n return true;\n }\n\n private expect(token: string): void {\n if (!this.take(token)) throw new Error(\\`Expected \"\\${token}\" at position \\${this.position + 1}\\`);\n }\n }\n\n export function evaluate(expression: string): number {\n const value = new Parser(expression).parse();\n if (!Number.isFinite(value)) throw new Error('The result is not a finite number');\n return value;\n }\n\n export const calculator = tool({\n name: 'calculator',\n description:\n 'Evaluate an arithmetic expression exactly. Supports + - * / ^, % as the remainder of a division (write a percentage as x / 100, so 17.5% of 2480 is 17.5 / 100 * 2480), parentheses, sqrt, abs, round, floor, ceil, min, max, log, ln, exp, sin, cos, tan, pi and e.',\n parameters: z.object({\n expression: z.string().min(1).max(500).describe('For example \"(17.5 * 4) / 3 + sqrt(2)\"'),\n }),\n execute: async ({ expression }) => ({ expression, result: evaluate(expression) }),\n });\n`;\n\n/** Unit tests for the starter tools, runnable offline. */\nexport const TOOLS_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { evaluate } from '../src/tools/calculator.js';\n import { currentTime } from '../src/tools/current-time.js';\n import { htmlToText, isPrivateAddress } from '../src/tools/fetch-url.js';\n\n describe('calculator', () => {\n it.each([\n ['1 + 2 * 3', 7],\n ['(1 + 2) * 3', 9],\n ['2 ^ 3 ^ 2', 512],\n ['-2 ^ 2', -4],\n ['sqrt(16) + abs(-3)', 7],\n ['max(1, 5, 3) % 3', 2],\n ['1.5e3 / 3', 500],\n ])('evaluates %s', (expression, expected) => {\n expect(evaluate(expression)).toBe(expected);\n });\n\n it('rejects what it cannot evaluate', () => {\n expect(() => evaluate('1 / 0')).toThrow('Division by zero');\n expect(() => evaluate('process.exit()')).toThrow();\n expect(() => evaluate('2 +')).toThrow('ends too early');\n });\n\n it('explains that % is a remainder, not a percentage', () => {\n expect(evaluate('10 % 3')).toBe(1);\n expect(evaluate('10 % -3')).toBe(1);\n expect(() => evaluate('17.5% * 2480')).toThrow('17.5% is 17.5 / 100');\n expect(() => evaluate('20 %')).toThrow('remainder of a division');\n });\n });\n\n describe('current_time', () => {\n it('answers in the requested time zone', async () => {\n const result = await currentTime.execute(\n { timeZone: 'Asia/Tokyo' },\n { agentId: 'test', runId: 'test', signal: new AbortController().signal }\n );\n expect(result.timeZone).toBe('Asia/Tokyo');\n });\n\n it('refuses an unknown time zone', async () => {\n await expect(\n currentTime.execute(\n { timeZone: 'Mars/Olympus' },\n { agentId: 'test', runId: 'test', signal: new AbortController().signal }\n )\n ).rejects.toThrow('Unknown time zone');\n });\n });\n\n describe('fetch_url', () => {\n it('keeps away from private networks', () => {\n for (const address of ['127.0.0.1', '10.1.2.3', '192.168.0.10', '169.254.169.254', '::1', '::ffff:127.0.0.1', 'fd00::1']) {\n expect(isPrivateAddress(address), address).toBe(true);\n }\n expect(isPrivateAddress('93.184.216.34')).toBe(false);\n });\n\n it('turns HTML into readable text', () => {\n const html = '<html><head><title>x</title><style>p{}</style></head><body><h1>Hello &amp; welcome</h1><p>One<br>Two</p><script>alert(1)</script></body></html>';\n expect(htmlToText(html)).toBe('Hello & welcome\\\\n\\\\nOne\\\\nTwo');\n });\n });\n`;\n","import { code, tsString } from '../code.js';\nimport { providerInfo } from '../providers.js';\nimport { ciInstallCommand, execCommand, runScript } from '../package-manager.js';\nimport { runsOnBun, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { ProjectBuilder } from '../project.js';\nimport type { FeatureModule } from './types.js';\nimport { CALCULATOR_TS, CURRENT_TIME_TS, FETCH_URL_TS, TOOLS_TEST_TS } from './starter-tools.js';\n\nconst BIOME_SCHEMA_VERSION = VERSIONS.biome.replace(/^\\^/, '');\n\nfunction tsconfig(spec: ProjectSpec): string {\n const bun = runsOnBun(spec);\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'es2023',\n lib: ['es2024'],\n module: 'nodenext',\n moduleResolution: 'nodenext',\n types: [bun ? 'bun' : 'node'],\n strict: true,\n verbatimModuleSyntax: true,\n isolatedModules: true,\n resolveJsonModule: true,\n skipLibCheck: true,\n noEmit: true,\n },\n include: ['src', 'tests', 'evals', '*.config.ts'],\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nfunction tsconfigBuild(): string {\n return (\n JSON.stringify(\n {\n extends: './tsconfig.json',\n compilerOptions: { noEmit: false, rootDir: 'src', outDir: 'dist', sourceMap: true },\n include: ['src'],\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nfunction biomeJson(spec: ProjectSpec): string {\n const ignored = ['!**/dist', '!**/data', '!**/.cogitator', '!**/node_modules'];\n if (spec.app === 'next') ignored.push('!**/.next', '!**/next-env.d.ts');\n return (\n JSON.stringify(\n {\n $schema: `https://biomejs.dev/schemas/${BIOME_SCHEMA_VERSION}/schema.json`,\n files: { includes: ['**', ...ignored] },\n formatter: { enabled: true, indentStyle: 'space', indentWidth: 2, lineWidth: 100 },\n javascript: {\n formatter: { quoteStyle: 'single', semicolons: 'always', trailingCommas: 'es5' },\n },\n linter: { enabled: true, rules: { preset: 'recommended' } },\n ...(spec.app === 'next' && { css: { parser: { tailwindDirectives: true } } }),\n assist: { actions: { source: { organizeImports: 'on' } } },\n },\n null,\n 2\n ) + '\\n'\n );\n}\n\nconst VITEST_CONFIG_TS = code`\n import { defineConfig } from 'vitest/config';\n\n export default defineConfig({\n test: {\n include: ['tests/**/*.test.ts'],\n testTimeout: 30_000,\n },\n });\n`;\n\nconst TEST_HELPERS_TS = code`\n import { loadConfig } from '@cogitator-ai/config';\n import { createMockLLMBackend, type MockChatResponse } from '@cogitator-ai/test-utils';\n import { createCogitator } from '../src/cogitator.js';\n\n /** The provider of the project's default model, the backend a mock has to stand in for. */\n function defaultProvider(): string {\n const llm = loadConfig().llm;\n return llm?.defaultModel?.split('/')[0] ?? llm?.defaultProvider ?? 'openai';\n }\n\n /**\n * A Cogitator whose model answers with \\`responses\\`, one per call, so tests run\n * offline and decide exactly what the model says. Memory stays in the process.\n */\n export function mockCogitator(...responses: MockChatResponse[]) {\n const backend = createMockLLMBackend().setResponses(responses);\n const cogitator = createCogitator({\n llm: { backends: { [defaultProvider()]: backend } },\n memory: { adapter: 'memory' },\n });\n return { backend, cogitator };\n }\n`;\n\nconst ASSISTANT_TEST_TS = code`\n import { afterEach, describe, expect, it } from 'vitest';\n import type { Cogitator } from '@cogitator-ai/core';\n import { agents } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n let cogitator: Cogitator | undefined;\n\n afterEach(async () => {\n await cogitator?.close();\n cogitator = undefined;\n });\n\n describe('assistant', () => {\n it('calls the calculator and answers with its result', async () => {\n const mock = mockCogitator(\n {\n toolCalls: [{ id: 'call-1', name: 'calculator', arguments: { expression: '6 * 7' } }],\n finishReason: 'tool_calls',\n },\n { content: '6 * 7 is 42.' }\n );\n cogitator = mock.cogitator;\n\n const result = await cogitator.run(agents.assistant, { input: 'What is 6 * 7?' });\n\n expect(result.output).toBe('6 * 7 is 42.');\n expect(result.toolCalls.map((call) => call.name)).toEqual(['calculator']);\n expect(JSON.stringify(mock.backend.getLastCall()?.messages)).toContain('42');\n });\n\n it('answers directly when no tool is needed', async () => {\n const mock = mockCogitator({ content: 'Hello!' });\n cogitator = mock.cogitator;\n\n const result = await cogitator.run(agents.assistant, { input: 'Hi' });\n\n expect(result.output).toBe('Hello!');\n expect(result.toolCalls).toEqual([]);\n });\n });\n`;\n\nfunction ciWorkflow(spec: ProjectSpec, packageManagerSpec: string | undefined): string {\n const pm = spec.packageManager;\n const setup =\n pm === 'bun'\n ? code`\n - uses: oven-sh/setup-bun@v2\n `\n : code`\n ${pm === 'pnpm' && '- uses: pnpm/action-setup@v6'}\n ${pm === 'yarn' && '- run: corepack enable'}\n - uses: actions/setup-node@v7\n with:\n node-version: 24\n cache: ${pm}\n `;\n const evals = spec.features.includes('evals');\n return code`\n name: CI\n\n on:\n push:\n branches: [main]\n pull_request:\n\n jobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v7\n ${setup}\n - run: ${ciInstallCommand(pm, packageManagerSpec)}\n - run: ${runScript(pm, 'typecheck')}\n - run: ${runScript(pm, 'lint')}\n - run: ${runScript(pm, 'test')}\n ${evals && `- run: ${runScript(pm, 'eval')}`}\n ${\n evals &&\n code`\n env:\n ${providerInfo(spec.provider).envKey ?? 'OLLAMA_BASE_URL'}: \\${{ secrets.${providerInfo(spec.provider).envKey ?? 'OLLAMA_BASE_URL'} }}\n `\n }\n `;\n}\n\nfunction assistantAgent(project: ProjectBuilder): string {\n const lines = [\n 'You are a capable, honest assistant.',\n 'Use your tools when they help: fetch_url to read web pages, calculator for arithmetic, current_time for dates and times.',\n ...project.instructions,\n 'When you are unsure, say so instead of guessing.',\n ];\n return code`\n import { Agent } from '@cogitator-ai/core';\n import { tools } from '../tools/index.js';\n\n export const assistant = new Agent({\n name: 'assistant',\n description: 'The general-purpose assistant of this project',\n instructions: [\n ${lines.map((line) => `${tsString(line)},`).join('\\n')}\n ].join('\\\\n'),\n tools,\n });\n `;\n}\n\nexport const baseFeature: FeatureModule = {\n id: 'base',\n applies: () => true,\n apply(project) {\n const { spec } = project;\n const bun = runsOnBun(spec);\n\n project\n .dependency('@cogitator-ai/core', cogitatorVersion('@cogitator-ai/core'))\n .dependency('@cogitator-ai/config', cogitatorVersion('@cogitator-ai/config'))\n .dependency('zod', VERSIONS.zod)\n .devDependency('@cogitator-ai/cli', cogitatorVersion('@cogitator-ai/cli'))\n .devDependency('@cogitator-ai/test-utils', cogitatorVersion('@cogitator-ai/test-utils'))\n .devDependency('@biomejs/biome', VERSIONS.biome)\n .devDependency('tsx', VERSIONS.tsx)\n .devDependency('vitest', VERSIONS.vitest);\n\n if (bun) {\n project.devDependency('@types/bun', VERSIONS.typesBun);\n } else {\n project.devDependency('@types/node', VERSIONS.typesNode);\n }\n\n if (spec.app !== 'next') {\n project\n .devDependency('typescript', VERSIONS.typescript)\n .file('tsconfig.json', tsconfig(spec))\n .file('tsconfig.build.json', tsconfigBuild());\n }\n\n project\n .file('src/tools/fetch-url.ts', FETCH_URL_TS)\n .file('src/tools/current-time.ts', CURRENT_TIME_TS)\n .file('src/tools/calculator.ts', CALCULATOR_TS)\n .tool('fetchUrl', './fetch-url.js')\n .tool('currentTime', './current-time.js')\n .tool('calculator', './calculator.js')\n .register({\n kind: 'agents',\n name: 'assistant',\n from: './agents/assistant.js',\n binding: 'assistant',\n })\n .file('tests/tools.test.ts', TOOLS_TEST_TS)\n .file('tests/helpers.ts', TEST_HELPERS_TS)\n .file('tests/assistant.test.ts', ASSISTANT_TEST_TS)\n .file('vitest.config.ts', VITEST_CONFIG_TS)\n .file('biome.json', biomeJson(spec))\n .file('.github/workflows/ci.yml', ciWorkflow(spec, project.packageManagerSpec))\n .script('test', 'vitest run')\n .script('typecheck', 'tsc --noEmit')\n .script('lint', 'biome check .')\n .script('format', 'biome check --write .')\n .script('doctor', 'cogitator doctor')\n .script('dev:studio', 'cogitator dev')\n .ignore('node_modules/', 'dist/', '.env', '.env.*', '!.env.example', '*.log', '*.tsbuildinfo')\n .ignore('.DS_Store', 'coverage/', '.cogitator/studio/', '.cogitator/checkpoints/');\n\n const info = providerInfo(spec.provider);\n if (info.envKey) {\n project.envVar({\n name: info.envKey,\n description: `${info.label} API key, from ${info.keyUrl}`,\n required: true,\n secret: true,\n });\n } else {\n project.envVar({\n name: 'OLLAMA_BASE_URL',\n description: 'Where Ollama listens',\n example: 'http://localhost:11434',\n required: false,\n secret: false,\n });\n }\n\n project.section(\n 'Commands',\n code`\n - \\`${runScript(spec.packageManager, 'dev')}\\`: run with reload on change\n - \\`${runScript(spec.packageManager, 'test')}\\`: offline tests, the model is mocked with \\`mockCogitator\\` from \\`tests/helpers.ts\\`\n - \\`${runScript(spec.packageManager, 'typecheck')}\\` and \\`${runScript(spec.packageManager, 'lint')}\\`: run both before you call a change done\n - \\`${runScript(spec.packageManager, 'dev:studio')}\\`: Cogitator Studio, to chat with the agents, read traces and costs, approve tool calls, run workflows and fork runs\n - \\`${runScript(spec.packageManager, 'doctor')}\\`: checks keys, services and models when something does not start\n - \\`${execCommand(spec.packageManager, 'cogitator add')} <feature>\\`: adds rag, mcp, workflows, evals and the other generated features to this project, \\`--dry-run\\` shows the diff first\n `\n );\n project.readmeSection(\n 'Cogitator Studio',\n code`\n \\`${runScript(spec.packageManager, 'dev:studio')}\\` opens a local studio for this project at http://localhost:4321: chat with every agent of \\`src/cogitator.ts\\` with streamed answers and tool calls, approve the calls that need it, read the trace of each run with its model calls, tool calls, nested agents, tokens and cost, run the workflows, and fork a run from any step with a changed input or tool result to compare both branches. It reloads when you save, and keeps the history in \\`.cogitator/studio/\\`.\n `\n );\n },\n};\n\n/** Writes `src/agents/assistant.ts` once every feature has added its instructions. */\nexport function emitAssistant(project: ProjectBuilder): void {\n project.file('src/agents/assistant.ts', assistantAgent(project));\n}\n","import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { ArtifactGenerator, ProjectAnalyzer } from '@cogitator-ai/deploy';\nimport { code } from '../code.js';\nimport { LOCKFILES, runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport type { FeatureModule } from './types.js';\n\n/** Deploy artifacts the project keeps at its root, from what @cogitator-ai/deploy generates. */\nconst ROOT_ARTIFACTS: Record<string, string> = {\n Dockerfile: 'Dockerfile',\n '.dockerignore': '.dockerignore',\n 'fly.toml': 'fly.toml',\n};\n\n/**\n * Generates the Dockerfile, `.dockerignore` and `fly.toml` with\n * `@cogitator-ai/deploy` itself: the planned project is laid out in a temporary\n * directory, analyzed the way `cogitator deploy` analyzes it, and the artifacts\n * of its generator are kept. There is one Dockerfile template, the deployer's.\n * The lockfile the install writes is stood in for, since the image installs\n * from it.\n */\nexport function emitDeployArtifacts(project: ProjectBuilder): void {\n const { spec } = project;\n if (spec.deploy === 'none') return;\n\n const dir = mkdtempSync(join(tmpdir(), 'cogitator-deploy-plan-'));\n try {\n for (const file of project.files.values()) {\n const target = join(dir, file.path);\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, file.content);\n }\n writeFileSync(join(dir, LOCKFILES[spec.packageManager]), '');\n\n const analysis = new ProjectAnalyzer().analyze(dir, { target: spec.deploy }, { env: {} });\n const { files } = new ArtifactGenerator().generate(analysis.deployConfig, analysis);\n for (const artifact of files) {\n const path = ROOT_ARTIFACTS[artifact.path];\n if (path) project.file(path, artifact.content);\n }\n for (const warning of analysis.warnings) project.warn(`deploy: ${warning}`);\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\n/** A production Dockerfile and the deploy settings for Docker or Fly.io. */\nexport const deployFeature: FeatureModule = {\n id: 'deploy',\n applies: (spec) => spec.deploy !== 'none',\n apply(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n project\n .script('deploy', 'cogitator deploy')\n .script('deploy:plan', 'cogitator deploy --dry-run');\n project.readmeSection(\n 'Deploy',\n code`\n \\`Dockerfile\\` is a multi-stage production image generated by \\`@cogitator-ai/deploy\\` from \\`cogitator.yml\\`: it installs from the lockfile, builds, and runs as an unprivileged user with only production dependencies.${spec.deploy === 'fly' ? ' `fly.toml` configures the Fly.io app.' : ''}\n\n \\`\\`\\`bash\n ${runScript(pm, 'deploy:plan')} # what would be deployed, with checks for secrets and services\n ${runScript(pm, 'deploy')} # build and ${spec.deploy === 'fly' ? 'deploy to Fly.io' : 'run with Docker'}\n \\`\\`\\`\n\n Secrets listed under \\`deploy.secrets\\` in \\`cogitator.yml\\` must be set in the environment you deploy from.\n `\n );\n project.section(\n 'Deploy',\n code`\n \\`cogitator.yml\\` (\\`deploy\\`) says how the project ships: target ${spec.deploy}, the secrets a deployment needs, the health check. \\`${runScript(pm, 'deploy:plan')}\\` checks it without deploying, \\`${runScript(pm, 'deploy')}\\` deploys. \\`Dockerfile\\` and \\`.dockerignore\\` come from \\`@cogitator-ai/deploy\\`; change \\`cogitator.yml\\` rather than the Dockerfile, \\`cogitator deploy\\` generates its image from it.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type ServerFramework } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nfunction a2aServerTs(project: ProjectBuilder): string {\n return code`\n import { timingSafeEqual } from 'node:crypto';\n import type { Cogitator } from '@cogitator-ai/core';\n import { A2AServer } from '@cogitator-ai/a2a';\n import { agents, cogitator } from '../cogitator.js';\n\n function sameToken(given: string, expected: string): boolean {\n const a = Buffer.from(given);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n /**\n * Every agent of the registry over the Agent-to-Agent protocol (v0.3): other\n * frameworks discover them at /.well-known/agent-card.json and talk JSON-RPC at\n * /a2a. With \\`token\\` set, they need \\`Authorization: Bearer <token>\\`.\n */\n export function createA2AServer(runtime: Cogitator, token: string | undefined = process.env.A2A_TOKEN) {\n return new A2AServer({\n agents,\n cogitator: runtime,\n provider: { organization: ${tsString(project.spec.name)}, url: 'https://github.com/cogitator-ai/Cogitator-AI' },\n ...(token && {\n auth: { type: 'bearer' as const, validate: async (given: string) => sameToken(given, token) },\n }),\n });\n }\n\n export const a2aServer = createA2AServer(cogitator);\n `;\n}\n\nconst A2A_ASK_TS = code`\n import { A2AClient } from '@cogitator-ai/a2a';\n\n function textOf(parts: ReadonlyArray<{ kind: string; text?: string }> | undefined): string {\n return (parts ?? []).map((part) => (part.kind === 'text' ? (part.text ?? '') : '')).join('');\n }\n\n /**\n * Asks an A2A agent a question: this project's own server by default, or any\n * A2A v0.3 agent at A2A_URL, built with Cogitator or with another framework.\n */\n async function main(): Promise<void> {\n const question = process.argv.slice(2).join(' ').trim() || 'What can you do?';\n const token = process.env.A2A_TOKEN;\n const client = new A2AClient(process.env.A2A_URL ?? 'http://localhost:3000', {\n ...(token && { headers: { authorization: \\`Bearer \\${token}\\` } }),\n timeout: 120_000,\n });\n\n const card = await client.agentCard();\n console.error(\\`Asking \\${card.name}: \\${card.description}\\`);\n\n const result = await client.sendMessage({ role: 'user', parts: [{ kind: 'text', text: question }] });\n if (result.kind === 'message') {\n console.log(textOf(result.parts));\n return;\n }\n const answer =\n textOf(result.status.message?.parts) ||\n (result.artifacts ?? []).map((artifact) => textOf(artifact.parts)).join('\\\\n');\n console.log(answer || \\`The task ended as \\${result.status.state}\\`);\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst A2A_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { createA2AServer } from '../src/a2a/server.js';\n import { mockCogitator } from './helpers.js';\n\n function send(text: string) {\n return {\n jsonrpc: '2.0',\n id: 1,\n method: 'message/send',\n params: { message: { kind: 'message', messageId: 'm-1', role: 'user', parts: [{ kind: 'text', text }] } },\n };\n }\n\n describe('A2A server', () => {\n it('describes the assistant in an A2A v0.3 agent card', () => {\n const { cogitator } = mockCogitator();\n const card = createA2AServer(cogitator, undefined).getAgentCard('assistant', {\n baseUrl: 'http://localhost:3000',\n });\n expect(card.protocolVersion).toBe('0.3.0');\n expect(card.name).toBe('assistant');\n });\n\n it('answers a message with the agent', async () => {\n const { cogitator } = mockCogitator({ content: 'Hello over A2A' });\n try {\n const response = await createA2AServer(cogitator, undefined).handleJsonRpc(send('Hi'));\n expect(JSON.stringify(response)).toContain('Hello over A2A');\n } finally {\n await cogitator.close();\n }\n });\n\n it('refuses a caller without the token', async () => {\n const { cogitator } = mockCogitator({ content: 'secret' });\n const server = createA2AServer(cogitator, 'a2a-token');\n const refused = await server.handleJsonRpc(send('Hi'));\n expect(JSON.stringify(refused)).toContain('Unauthorized');\n const allowed = await server.handleJsonRpc(send('Hi'), 'a2a-token');\n expect(JSON.stringify(allowed)).toContain('secret');\n await cogitator.close();\n });\n });\n`;\n\n/** The imports and mount statements that put the A2A routes on a server's app. */\nexport function a2aMount(server: ServerFramework): { imports: string[]; mount: string } {\n switch (server) {\n case 'hono':\n return {\n imports: [\n \"import { a2aHono } from '@cogitator-ai/a2a/hono';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: \"app.route('/', a2aHono(a2aServer));\",\n };\n case 'express':\n return {\n imports: [\n \"import { a2aExpress } from '@cogitator-ai/a2a/express';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: 'app.use(a2aExpress(a2aServer));',\n };\n case 'fastify':\n return {\n imports: [\n \"import { a2aFastify } from '@cogitator-ai/a2a/fastify';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: 'await app.register(a2aFastify(a2aServer));',\n };\n case 'koa':\n return {\n imports: [\n \"import { bodyParser } from '@koa/bodyparser';\",\n \"import { a2aKoa } from '@cogitator-ai/a2a/koa';\",\n \"import { a2aServer } from './a2a/server.js';\",\n ],\n mount: code`\n const a2aBody = bodyParser();\n app.use((ctx, next) => (ctx.path.startsWith('/a2a') ? a2aBody(ctx, next) : next()));\n app.use(a2aKoa(a2aServer));\n `,\n };\n case 'tetsu':\n throw new Error('A2A has no Tetsu adapter, which compatibilityIssues rules out');\n }\n}\n\n/** The agents served over the Agent-to-Agent protocol, next to the REST API. */\nexport const a2aFeature: FeatureModule = {\n id: 'feature:a2a',\n applies: (spec) => hasFeature(spec, 'a2a'),\n apply(project) {\n const { spec } = project;\n project\n .dependency('@cogitator-ai/a2a', cogitatorVersion('@cogitator-ai/a2a'))\n .file('src/a2a/server.ts', a2aServerTs(project))\n .file('src/a2a/ask.ts', A2A_ASK_TS)\n .file('tests/a2a.test.ts', A2A_TEST_TS)\n .envVar({\n name: 'A2A_TOKEN',\n description: 'Bearer token A2A callers need, open to anyone without it',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'A2A_URL',\n description: 'The A2A agent the a2a:ask script talks to',\n example: 'http://localhost:3000',\n required: false,\n secret: false,\n });\n if (spec.server === 'koa') project.dependency('@koa/bodyparser', VERSIONS.koaBodyparser);\n if (spec.app !== 'next')\n project.script('a2a:ask', 'tsx --env-file-if-exists=.env src/a2a/ask.ts');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'A2A',\n code`\n \\`src/a2a/server.ts\\` serves every agent of the registry over the Agent-to-Agent protocol v0.3, so agents built with other frameworks can call them: the card is at \\`/.well-known/agent-card.json\\`, JSON-RPC at \\`/a2a\\` (\\`/a2a/<agent>\\` for each agent). Set \\`A2A_TOKEN\\` to require a bearer token. \\`${runScript(pm, 'a2a:ask', '\"your question\"')}\\` asks an A2A agent, this project's by default or any at \\`A2A_URL\\`.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\n\n/** `src/lifecycle.ts`: graceful shutdown on SIGINT and SIGTERM for long-running processes. */\nexport const LIFECYCLE_TS = code`\n /**\n * Runs \\`close\\` once on SIGINT or SIGTERM, then exits. A shutdown that hangs,\n * for example on a stream that never ends, is cut off after \\`timeoutMs\\`.\n */\n export function onShutdown(close: () => Promise<void>, timeoutMs = 10_000): void {\n let closing = false;\n const stop = (signal: NodeJS.Signals) => {\n if (closing) return;\n closing = true;\n console.log(\\`\\${signal} received, shutting down\\`);\n setTimeout(() => {\n console.error('Shutdown took too long, exiting');\n process.exit(1);\n }, timeoutMs).unref();\n close().then(\n () => process.exit(0),\n (error: unknown) => {\n console.error(error);\n process.exit(1);\n }\n );\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n }\n`;\n\n/** The import lines of the startup steps features registered, for an entry point. */\nexport function startupImports(project: ProjectBuilder): string | false {\n return project.startup.imports.length > 0 && project.startup.imports.join('\\n');\n}\n\n/** The startup steps features registered, run before the entry point starts serving. */\nexport function startupStatements(project: ProjectBuilder): string | false {\n return project.startup.statements.length > 0 && project.startup.statements.join('\\n');\n}\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ChannelKind } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const WEBCHAT_PORT = 18789;\n\n/** Where Bluesky sessions and Threads tokens are kept, out of git. */\nconst TOKENS_PATH = '.cogitator/tokens.json';\n\ninterface ChannelSetup {\n factory: string;\n /** Other names the gateway imports from `@cogitator-ai/channels`. */\n imports?: string[];\n expression: string;\n packages: Array<[string, string]>;\n env: Array<{ name: string; description: string; required: boolean }>;\n}\n\nconst CHANNEL_SETUP: Record<ChannelKind, ChannelSetup> = {\n telegram: {\n factory: 'telegramChannel',\n expression: 'telegramChannel({ token: env.TELEGRAM_BOT_TOKEN })',\n packages: [['grammy', VERSIONS.grammy]],\n env: [\n {\n name: 'TELEGRAM_BOT_TOKEN',\n description: 'Telegram bot token, from @BotFather',\n required: true,\n },\n ],\n },\n discord: {\n factory: 'discordChannel',\n expression: 'discordChannel({ token: env.DISCORD_BOT_TOKEN, mentionOnly: true })',\n packages: [['discord.js', VERSIONS.discord]],\n env: [\n {\n name: 'DISCORD_BOT_TOKEN',\n description: 'Discord bot token, from the Developer Portal',\n required: true,\n },\n ],\n },\n slack: {\n factory: 'slackChannel',\n expression: code`\n slackChannel({\n token: env.SLACK_BOT_TOKEN,\n signingSecret: env.SLACK_SIGNING_SECRET,\n appToken: env.SLACK_APP_TOKEN,\n })\n `,\n packages: [['@slack/bolt', VERSIONS.slackBolt]],\n env: [\n { name: 'SLACK_BOT_TOKEN', description: 'Slack bot token (xoxb-...)', required: true },\n { name: 'SLACK_SIGNING_SECRET', description: 'Slack signing secret', required: true },\n {\n name: 'SLACK_APP_TOKEN',\n description: 'Slack app token (xapp-...) for Socket Mode, HTTP mode without it',\n required: false,\n },\n ],\n },\n webchat: {\n factory: 'webchatChannel',\n expression: `webchatChannel({ port: Number(env.WEBCHAT_PORT ?? ${WEBCHAT_PORT}) })`,\n packages: [['ws', VERSIONS.ws]],\n env: [],\n },\n bluesky: {\n factory: 'blueskyChannel',\n imports: ['FileTokenStore'],\n expression: code`\n blueskyChannel({\n identifier: env.BLUESKY_HANDLE,\n appPassword: env.BLUESKY_APP_PASSWORD,\n store: new FileTokenStore({ path: '${TOKENS_PATH}' }),\n })\n `,\n packages: [['@atproto/api', VERSIONS.atprotoApi]],\n env: [\n {\n name: 'BLUESKY_HANDLE',\n description: 'Bluesky handle of the bot account, such as yourbot.bsky.social',\n required: true,\n },\n {\n name: 'BLUESKY_APP_PASSWORD',\n description:\n 'Bluesky app password (Settings, Privacy and security, App passwords), with direct messages allowed',\n required: true,\n },\n ],\n },\n threads: {\n factory: 'threadsChannel',\n imports: ['FileTokenStore'],\n expression: code`\n threadsChannel({\n accessToken: env.THREADS_ACCESS_TOKEN,\n store: new FileTokenStore({ path: '${TOKENS_PATH}' }),\n })\n `,\n packages: [],\n env: [\n {\n name: 'THREADS_ACCESS_TOKEN',\n description:\n 'Threads long-lived access token; it is renewed automatically and kept in .cogitator/tokens.json',\n required: true,\n },\n ],\n },\n};\n\n/** A messaging bot: one Gateway that answers on every chosen channel with the assistant. */\nexport const appChannelsFeature: FeatureModule = {\n id: 'app:channels',\n applies: (spec) => spec.app === 'channels',\n apply(project) {\n const { spec } = project;\n project.dependency('@cogitator-ai/channels', cogitatorVersion('@cogitator-ai/channels'));\n\n for (const channel of spec.channels) {\n const setup = CHANNEL_SETUP[channel];\n for (const [name, version] of setup.packages) project.dependency(name, version);\n for (const variable of setup.env) project.envVar({ ...variable, secret: true });\n }\n if (\n spec.channels.some((channel) => CHANNEL_SETUP[channel].imports?.includes('FileTokenStore'))\n ) {\n project.ignore(TOKENS_PATH);\n }\n if (spec.channels.includes('webchat')) {\n project.envVar({\n name: 'WEBCHAT_PORT',\n description: 'Port of the WebChat WebSocket',\n example: String(WEBCHAT_PORT),\n required: false,\n secret: false,\n });\n project.deploy.port = WEBCHAT_PORT;\n }\n\n project\n .file('src/lifecycle.ts', LIFECYCLE_TS)\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n project.deploy.kind = 'worker';\n\n project.instruct(\n 'You talk to people through chat apps, so keep answers short and conversational.'\n );\n },\n finalize(project) {\n const { spec } = project;\n const channels = spec.channels.map((channel) => CHANNEL_SETUP[channel]);\n const memory = spec.memory !== 'none';\n\n project.file(\n 'src/gateway.ts',\n code`\n import { Gateway, ${[...new Set(channels.flatMap((c) => [c.factory, ...(c.imports ?? [])]))].join(', ')} } from '@cogitator-ai/channels';\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n const env = loadEnv();\n ${startupStatements(project)}\n ${memory && 'const memory = await cogitator.getMemory();'}\n\n /**\n * The assistant on its channels. \\`src/index.ts\\` starts it, and so do\n * \\`cogitator assistant\\` (with a live dashboard), \\`cogitator build\\` and\n * \\`cogitator daemon\\`, which look for this export.\n */\n export const gateway = new Gateway({\n cogitator,\n agent: agents.assistant,\n channels: [\n ${channels.map((c) => `${c.expression},`).join('\\n')}\n ],\n ${\n memory &&\n code`\n ...(memory && {\n memory,\n session: { compaction: { strategy: 'hybrid' as const, messageThreshold: 50, keepRecent: 10 } },\n }),\n `\n }\n stream: { flushInterval: 500, minChunkSize: 20 },\n onError: (error, message) => {\n console.error(\\`[\\${message.channelType}:\\${message.userId}] \\${error.message}\\`);\n },\n });\n `\n );\n\n const webchat = spec.channels.includes('webchat');\n project.file(\n 'src/index.ts',\n code`\n import { cogitator } from './cogitator.js';\n ${webchat && \"import { loadEnv } from './env.js';\"}\n import { gateway } from './gateway.js';\n import { onShutdown } from './lifecycle.js';\n\n await gateway.start();\n console.log(\\`The assistant is listening on \\${gateway.stats.connectedChannels.join(', ')}\\`);\n ${webchat && `console.log(\\`WebChat: ws://localhost:\\${loadEnv().WEBCHAT_PORT ?? ${WEBCHAT_PORT}}/ws\\`);`}\n\n onShutdown(async () => {\n await gateway.stop();\n await cogitator.close();\n });\n `\n );\n\n const pm = spec.packageManager;\n project.section(\n 'Bot',\n code`\n \\`src/gateway.ts\\` builds a \\`Gateway\\` from \\`@cogitator-ai/channels\\` that answers on ${spec.channels.join(', ')} with \\`agents.assistant\\`, and \\`src/index.ts\\` starts it. Each chat is its own thread${memory ? ' in memory, compacted when it grows long' : ''}. Channel tokens come from \\`.env\\`. \\`${runScript(pm, 'dev')}\\` runs it with reload on change, \\`cogitator assistant\\` with a live dashboard, \\`cogitator daemon start\\` in the background.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nconst NEXT_PORT = 3000;\n\nfunction nextConfig(project: ProjectBuilder): string {\n const cogitator = [...project.dependencies.keys()].filter(\n (name) => name.startsWith('@cogitator-ai/') && name !== '@cogitator-ai/next'\n );\n const external = [\n ...new Set([...cogitator, '@cogitator-ai/types', '@cogitator-ai/server-shared']),\n ...[...project.nativeBuilds].filter((name) => project.dependencies.has(name)),\n ].sort();\n return code`\n import type { NextConfig } from 'next';\n\n const config: NextConfig = {\n /**\n * Loaded by Node at runtime instead of bundled: they read files and native\n * modules, and one copy of each keeps \\`instanceof\\` working across packages.\n * @cogitator-ai/next stays bundled: its hooks need the app's own React.\n */\n serverExternalPackages: [${external.map((name) => tsString(name)).join(', ')}],\n };\n\n export default config;\n `;\n}\n\nconst TSCONFIG_NEXT =\n JSON.stringify(\n {\n compilerOptions: {\n target: 'es2023',\n lib: ['dom', 'dom.iterable', 'es2024'],\n allowJs: false,\n skipLibCheck: true,\n strict: true,\n noEmit: true,\n module: 'esnext',\n moduleResolution: 'bundler',\n resolveJsonModule: true,\n isolatedModules: true,\n verbatimModuleSyntax: true,\n jsx: 'react-jsx',\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./src/*'] },\n },\n include: ['next-env.d.ts', 'src', 'tests', 'evals', '*.config.ts', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2\n ) + '\\n';\n\nconst POSTCSS_CONFIG = code`\n export default {\n plugins: { '@tailwindcss/postcss': {} },\n };\n`;\n\nconst GLOBALS_CSS = code`\n @import \"tailwindcss\";\n\n @theme {\n --font-sans: ui-sans-serif, system-ui, sans-serif;\n }\n\n .prose-chat :where(p, ul, ol, pre) { margin-block: 0.5rem; }\n .prose-chat :where(ul) { list-style: disc; padding-left: 1.25rem; }\n .prose-chat :where(ol) { list-style: decimal; padding-left: 1.25rem; }\n .prose-chat :where(code) { font-size: 0.875em; }\n .prose-chat :where(pre) { overflow-x: auto; border-radius: 0.5rem; padding: 0.75rem; background: rgb(0 0 0 / 0.35); }\n .prose-chat :where(a) { text-decoration: underline; }\n`;\n\nfunction layoutTsx(project: ProjectBuilder): string {\n return code`\n import type { Metadata } from 'next';\n import type { ReactNode } from 'react';\n import './globals.css';\n\n export const metadata: Metadata = {\n title: ${tsString(project.spec.name)},\n description: 'A chat with your Cogitator agents',\n };\n\n export default function RootLayout({ children }: { children: ReactNode }) {\n return (\n <html lang=\"en\" className=\"dark\">\n <body className=\"bg-zinc-950 text-zinc-100 antialiased\">{children}</body>\n </html>\n );\n }\n `;\n}\n\nconst PAGE_TSX = code`\n import { Chat } from '@/components/chat';\n\n export default function Home() {\n return <Chat />;\n }\n`;\n\nconst SESSION_TS = code`\n import { randomUUID } from 'node:crypto';\n import { cookies } from 'next/headers';\n\n const COOKIE = 'cogitator-user';\n\n /**\n * Who is chatting: an anonymous id in an httpOnly cookie, so every browser has\n * threads of its own. Replace this with your auth (Auth.js, Clerk, your SSO)\n * by returning your user's id instead.\n */\n export async function currentUser(): Promise<string> {\n const jar = await cookies();\n const existing = jar.get(COOKIE)?.value;\n if (existing) return existing;\n const id = randomUUID();\n jar.set(COOKIE, id, { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production', path: '/' });\n return id;\n }\n`;\n\nfunction chatRouteTs(project: ProjectBuilder): string {\n return code`\n import { createChatHandler } from '@cogitator-ai/next';\n import { agents, cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n ${startupImports(project)}\n\n ${startupStatements(project)}\n\n export const POST = createChatHandler(cogitator, agents.assistant, {\n beforeRun: async () => ({ userId: await currentUser() }),\n });\n `;\n}\n\nconst RESUME_ROUTE_TS = code`\n import { createResumeHandler } from '@cogitator-ai/next';\n import { agents, cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n\n export const POST = createResumeHandler(cogitator, agents.assistant, {\n stream: true,\n beforeRun: async () => ({ userId: await currentUser() }),\n });\n`;\n\nconst THREAD_ROUTE_TS = code`\n import { assertThreadAccess, CogitatorError } from '@cogitator-ai/core';\n import type { ChatMessage } from '@cogitator-ai/next';\n import { cogitator } from '@/cogitator';\n import { currentUser } from '@/lib/session';\n\n function text(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content.map((part: { type?: string; text?: string }) => (part.type === 'text' ? (part.text ?? '') : '')).join('');\n }\n\n /** The messages of one of the caller's threads, to show a saved conversation again. */\n export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {\n const { id } = await params;\n const memory = await cogitator.getMemory();\n if (!memory) return Response.json({ messages: [] });\n\n try {\n const thread = await assertThreadAccess(memory, id, await currentUser());\n if (!thread) return Response.json({ messages: [] });\n } catch (error) {\n if (error instanceof CogitatorError) return Response.json({ error: error.message }, { status: 403 });\n throw error;\n }\n\n const entries = await memory.getEntries({ threadId: id, includeToolCalls: true });\n if (!entries.success) return Response.json({ error: entries.error }, { status: 500 });\n\n const messages: ChatMessage[] = entries.data\n .filter((entry) => entry.message.role === 'user' || entry.message.role === 'assistant')\n .map((entry): ChatMessage => ({\n id: entry.id,\n role: entry.message.role === 'user' ? 'user' : 'assistant',\n content: text(entry.message.content),\n ...(entry.toolCalls?.length && { toolCalls: entry.toolCalls }),\n createdAt: entry.createdAt,\n }))\n .filter((message) => message.content || message.toolCalls);\n return Response.json({ messages });\n }\n`;\n\nconst HEALTH_ROUTE_TS = code`\n export function GET() {\n return Response.json({ status: 'ok' });\n }\n`;\n\nconst CHAT_TSX = code`\n 'use client';\n\n import type { ChatMessage } from '@cogitator-ai/next';\n import { useCogitatorChat } from '@cogitator-ai/next/client';\n import { type FormEvent, useEffect, useRef, useState } from 'react';\n import { Message } from './message';\n import { Threads, type SavedThread } from './threads';\n\n const THREADS_KEY = 'cogitator-threads';\n\n function loadThreads(): SavedThread[] {\n try {\n return JSON.parse(localStorage.getItem(THREADS_KEY) ?? '[]') as SavedThread[];\n } catch {\n return [];\n }\n }\n\n export function Chat() {\n const [threads, setThreads] = useState<SavedThread[]>([]);\n const [toolResults, setToolResults] = useState<Record<string, unknown>>({});\n const bottom = useRef<HTMLDivElement>(null);\n\n const chat = useCogitatorChat({\n api: '/api/chat',\n resumeApi: '/api/chat/resume',\n onToolResult: (event) => setToolResults((all) => ({ ...all, [event.toolCallId]: event.result })),\n });\n const { messages, input, setInput, send, stop, isLoading, error, threadId, pendingApprovals } = chat;\n\n useEffect(() => setThreads(loadThreads()), []);\n\n useEffect(() => {\n if (messages.length > 0) bottom.current?.scrollIntoView({ behavior: 'smooth' });\n }, [messages]);\n\n useEffect(() => {\n const first = messages.find((message) => message.role === 'user');\n if (!threadId || !first) return;\n setThreads((current) => {\n if (current.some((thread) => thread.id === threadId)) return current;\n const next = [{ id: threadId, title: first.content.slice(0, 60) }, ...current].slice(0, 50);\n localStorage.setItem(THREADS_KEY, JSON.stringify(next));\n return next;\n });\n }, [threadId, messages]);\n\n async function open(id: string) {\n const response = await fetch(\\`/api/threads/\\${encodeURIComponent(id)}\\`);\n const body = (await response.json()) as { messages?: ChatMessage[] };\n chat.setMessages(body.messages ?? []);\n chat.setThreadId(id);\n setToolResults({});\n }\n\n function startNew() {\n chat.clearMessages();\n chat.setThreadId(undefined);\n setToolResults({});\n }\n\n function submit(event: FormEvent) {\n event.preventDefault();\n if (!input.trim() || isLoading) return;\n void send();\n }\n\n return (\n <div className=\"flex h-screen\">\n <Threads threads={threads} current={threadId} onOpen={open} onNew={startNew} />\n <main className=\"flex flex-1 flex-col\">\n <div className=\"flex-1 overflow-y-auto px-4 py-6\">\n <div className=\"mx-auto flex max-w-3xl flex-col gap-4\">\n {messages.length === 0 && (\n <p className=\"mt-24 text-center text-zinc-500\">Ask anything. The assistant can browse the web, do math and tell the time.</p>\n )}\n {messages.map((message) => (\n <Message key={message.id} message={message} toolResults={toolResults} />\n ))}\n {isLoading && <p className=\"text-sm text-zinc-500\">Thinking...</p>}\n {pendingApprovals.length > 0 && (\n <div className=\"rounded-xl border border-amber-700 bg-amber-950/60 p-4 text-sm\">\n <p className=\"font-medium text-amber-200\">The assistant wants to run:</p>\n <ul className=\"mt-2 space-y-1\">\n {pendingApprovals.map((call) => (\n <li key={call.toolCallId}>\n <code>{call.toolName}</code> <code className=\"text-zinc-400\">{JSON.stringify(call.arguments)}</code>\n </li>\n ))}\n </ul>\n <div className=\"mt-3 flex gap-2\">\n <button type=\"button\" className=\"rounded-lg bg-amber-600 px-3 py-1.5 font-medium\" onClick={() => void chat.approve()}>\n Approve\n </button>\n <button type=\"button\" className=\"rounded-lg border border-zinc-600 px-3 py-1.5\" onClick={() => void chat.deny('Declined in the chat')}>\n Deny\n </button>\n </div>\n </div>\n )}\n {error && (\n <p className=\"rounded-xl border border-red-800 bg-red-950/60 px-4 py-2 text-sm text-red-200\">{error.message}</p>\n )}\n <div ref={bottom} />\n </div>\n </div>\n <form onSubmit={submit} className=\"mx-auto flex w-full max-w-3xl gap-2 px-4 pb-6\">\n <input\n value={input}\n onChange={(event) => setInput(event.target.value)}\n placeholder=\"Message the assistant\"\n className=\"flex-1 rounded-xl border border-zinc-700 bg-zinc-900 px-4 py-3 outline-none focus:border-zinc-400\"\n />\n {isLoading ? (\n <button type=\"button\" onClick={stop} className=\"rounded-xl border border-zinc-600 px-5\">\n Stop\n </button>\n ) : (\n <button type=\"submit\" disabled={!input.trim()} className=\"rounded-xl bg-zinc-100 px-5 font-medium text-zinc-900 disabled:opacity-40\">\n Send\n </button>\n )}\n </form>\n </main>\n </div>\n );\n }\n`;\n\nconst MESSAGE_TSX = code`\n import type { ChatMessage } from '@cogitator-ai/next';\n import ReactMarkdown from 'react-markdown';\n\n export function Message({ message, toolResults }: { message: ChatMessage; toolResults: Record<string, unknown> }) {\n const mine = message.role === 'user';\n return (\n <div className={\\`flex \\${mine ? 'justify-end' : 'justify-start'}\\`}>\n <div className={\\`max-w-[85%] rounded-2xl px-4 py-2 \\${mine ? 'bg-zinc-100 text-zinc-900' : 'bg-zinc-900'}\\`}>\n {message.reasoning && (\n <details className=\"mb-2 text-sm text-zinc-400\">\n <summary className=\"cursor-pointer\">Reasoning</summary>\n <p className=\"mt-1 whitespace-pre-wrap\">{message.reasoning}</p>\n </details>\n )}\n {message.toolCalls?.map((call) => (\n <details key={call.id} className=\"mb-2 rounded-lg border border-zinc-800 px-3 py-2 text-sm\">\n <summary className=\"cursor-pointer font-mono text-zinc-300\">{call.name}</summary>\n <pre className=\"mt-2 overflow-x-auto text-xs text-zinc-400\">{JSON.stringify(call.arguments, null, 2)}</pre>\n {call.id in toolResults && (\n <pre className=\"mt-2 overflow-x-auto text-xs text-zinc-300\">{JSON.stringify(toolResults[call.id], null, 2)}</pre>\n )}\n </details>\n ))}\n <div className=\"prose-chat\">\n <ReactMarkdown>{message.content}</ReactMarkdown>\n </div>\n </div>\n </div>\n );\n }\n`;\n\nconst THREADS_TSX = code`\n export interface SavedThread {\n id: string;\n title: string;\n }\n\n export function Threads({\n threads,\n current,\n onOpen,\n onNew,\n }: {\n threads: SavedThread[];\n current: string | undefined;\n onOpen: (id: string) => void;\n onNew: () => void;\n }) {\n return (\n <aside className=\"hidden w-64 flex-col border-r border-zinc-800 p-3 md:flex\">\n <button type=\"button\" onClick={onNew} className=\"mb-3 rounded-lg border border-zinc-700 px-3 py-2 text-left text-sm\">\n New chat\n </button>\n <nav className=\"flex flex-col gap-1 overflow-y-auto\">\n {threads.map((thread) => (\n <button\n key={thread.id}\n type=\"button\"\n onClick={() => onOpen(thread.id)}\n className={\\`truncate rounded-lg px-3 py-2 text-left text-sm \\${thread.id === current ? 'bg-zinc-800' : 'hover:bg-zinc-900'}\\`}\n >\n {thread.title}\n </button>\n ))}\n </nav>\n </aside>\n );\n }\n`;\n\nconst SAVE_NOTE_TS = code`\n import { appendFile, mkdir } from 'node:fs/promises';\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n /** Saves a note to data/notes.md. It changes a file, so the chat asks you to approve it first. */\n export const saveNote = tool({\n name: 'save_note',\n description: 'Save a note for the user to read later.',\n parameters: z.object({ text: z.string().min(1).max(2_000).describe('The note') }),\n sideEffects: ['filesystem'],\n requiresApproval: true,\n execute: async ({ text }) => {\n await mkdir('data', { recursive: true });\n await appendFile('data/notes.md', \\`- \\${new Date().toISOString()} \\${text}\\\\n\\`);\n return { saved: true };\n },\n });\n`;\n\n/** A Next.js chat app: streaming, tool calls, approvals and saved threads, with the agents on the server. */\nexport const appNextFeature: FeatureModule = {\n id: 'app:next',\n applies: (spec) => spec.app === 'next',\n apply(project) {\n project\n .dependency('@cogitator-ai/next', cogitatorVersion('@cogitator-ai/next'))\n .dependency('next', VERSIONS.next)\n .dependency('react', VERSIONS.react)\n .dependency('react-dom', VERSIONS.reactDom)\n .dependency('react-markdown', VERSIONS.reactMarkdown)\n .devDependency('typescript', VERSIONS.typescript)\n .devDependency('@types/react', VERSIONS.typesReact)\n .devDependency('@types/react-dom', VERSIONS.typesReactDom)\n .devDependency('tailwindcss', VERSIONS.tailwind)\n .devDependency('@tailwindcss/postcss', VERSIONS.tailwindPostcss)\n .file('tsconfig.json', TSCONFIG_NEXT)\n .file('postcss.config.mjs', POSTCSS_CONFIG)\n .file('src/app/globals.css', GLOBALS_CSS)\n .file('src/app/layout.tsx', layoutTsx(project))\n .file('src/app/page.tsx', PAGE_TSX)\n .file('src/lib/session.ts', SESSION_TS)\n .file('src/app/api/chat/resume/route.ts', RESUME_ROUTE_TS)\n .file('src/app/api/threads/[id]/route.ts', THREAD_ROUTE_TS)\n .file('src/app/api/health/route.ts', HEALTH_ROUTE_TS)\n .file('src/components/chat.tsx', CHAT_TSX)\n .file('src/components/message.tsx', MESSAGE_TSX)\n .file('src/components/threads.tsx', THREADS_TSX)\n .file('src/tools/save-note.ts', SAVE_NOTE_TS)\n .tool('saveNote', './save-note.js')\n .script('dev', 'next dev')\n .script('build', 'next build')\n .script('start', 'next start')\n .ignore('.next/', 'out/', 'next-env.d.ts', 'data/')\n .instruct(\n 'You chat in a web page that renders Markdown, so format answers with Markdown when it helps.'\n );\n project.deploy.kind = 'server';\n project.deploy.port = NEXT_PORT;\n project.deploy.healthPath = '/api/health';\n },\n finalize(project) {\n project\n .file('next.config.ts', nextConfig(project))\n .file('src/app/api/chat/route.ts', chatRouteTs(project));\n const pm = project.spec.packageManager;\n project.section(\n 'Next.js app',\n code`\n \\`src/app/api/chat/route.ts\\` streams the assistant with \\`createChatHandler\\`, \\`src/app/api/chat/resume/route.ts\\` continues a run after an approval, and \\`src/app/api/threads/[id]/route.ts\\` loads a saved conversation after checking it belongs to the caller. \\`src/lib/session.ts\\` identifies the caller with an anonymous cookie: replace it with your auth. \\`src/components/chat.tsx\\` is the client (\\`useCogitatorChat\\`): Markdown, tool calls with their results, reasoning, approvals for \\`save_note\\`, stop, and threads kept in the sidebar. \\`${runScript(pm, 'dev')}\\` serves it on http://localhost:${NEXT_PORT}.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, primaryTarget } from '../spec.js';\nimport { VERSIONS } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\n/** The terminal chat over the assistant: one-shot from argv or stdin, a REPL otherwise. */\nfunction agentEntry(project: ProjectBuilder): string {\n const { spec } = project;\n const harness = hasFeature(spec, 'harness');\n const persistent = spec.memory !== 'none';\n return code`\n import { createInterface${harness ? ', type Interface' : ''} } from 'node:readline/promises';\n import { styleText } from 'node:util';\n ${harness && \"import type { ToolApprovalDecision, ToolApprovalRequest } from '@cogitator-ai/core';\"}\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${harness && \"import { facts } from './harness/facts.js';\"}\n ${harness && \"import { startScheduler } from './harness/scheduler.js';\"}\n ${startupImports(project)}\n\n ${\n persistent\n ? code`\n /** One thread for the terminal, so the conversation carries over between runs. */\n const THREAD_ID = 'terminal';\n `\n : code`\n /** One thread per process: the project keeps no memory, so every start is a fresh conversation. */\n const THREAD_ID = \\`terminal-\\${process.pid}\\`;\n `\n }\n\n async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));\n return Buffer.concat(chunks).toString('utf8').trim();\n }\n\n ${\n harness &&\n code`\n /** Asks in the terminal before a tool that changes something runs; without a terminal it is declined. */\n async function approve(request: ToolApprovalRequest, rl?: Interface): Promise<ToolApprovalDecision> {\n if (!rl) return { approved: false, reason: 'Nobody is at the terminal to approve it' };\n const answer = await rl.question(\n styleText('yellow', \\` \\${request.toolName} wants to run with \\${JSON.stringify(request.arguments)}. Allow? [y/N] \\`)\n );\n return /^y(es)?$/i.test(answer.trim())\n ? { approved: true }\n : { approved: false, reason: 'Declined at the terminal' };\n }\n `\n }\n\n async function ask(input: string${harness ? ', rl?: Interface' : ''}): Promise<void> {\n let streamed = false;\n const result = await cogitator.run(agents.assistant, {\n input,\n threadId: THREAD_ID,\n stream: true,\n ${harness && 'context: { factsAboutTheUser: await facts.context() },'}\n onToken: (token) => {\n streamed = true;\n process.stdout.write(token);\n },\n onToolCall: (call) => {\n process.stderr.write(styleText('dim', \\`\\\\n > \\${call.name} \\${JSON.stringify(call.arguments)}\\\\n\\`));\n },\n ${harness && 'onApproval: (request) => approve(request, rl),'}\n });\n\n if (!streamed) process.stdout.write(result.output);\n process.stdout.write('\\\\n');\n const { totalTokens, cost, duration } = result.usage;\n process.stderr.write(\n styleText('dim', \\` \\${totalTokens} tokens, $\\${cost.toFixed(4)}, \\${(duration / 1000).toFixed(1)}s\\\\n\\`)\n );\n }\n\n async function chat(): Promise<void> {\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n const closed = new Promise<null>((resolve) => rl.once('close', () => resolve(null)));\n rl.on('SIGINT', () => rl.close());\n ${\n harness &&\n code`\n let queue: Promise<void> = Promise.resolve();\n /** Runs one turn at a time, so a scheduled task never talks over the user. */\n const serially = (turn: () => Promise<void>) => {\n queue = queue.then(turn).catch((error: unknown) => {\n console.error(styleText('red', error instanceof Error ? error.message : String(error)));\n });\n return queue;\n };\n const scheduler = startScheduler((task) =>\n serially(async () => {\n console.log(styleText('magenta', '\\\\n[scheduled task]'));\n await ask(task, rl);\n })\n );\n `\n }\n\n console.log(\n styleText('bold', 'Chat with the assistant.') + styleText('dim', ' /exit or Ctrl+C to leave.')\n );\n try {\n for (;;) {\n const line = await Promise.race([rl.question(styleText('cyan', '> ')).catch(() => null), closed]);\n if (line === null) break;\n const input = line.trim();\n if (!input) continue;\n if (input === '/exit') break;\n ${\n harness\n ? 'await serially(() => ask(input, rl));'\n : code`\n try {\n await ask(input);\n } catch (error) {\n console.error(styleText('red', error instanceof Error ? error.message : String(error)));\n }\n `\n }\n }\n } finally {\n ${harness && 'scheduler.stop();'}\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const fromArgs = process.argv.slice(2).join(' ').trim();\n const input = fromArgs || (process.stdin.isTTY ? '' : await readStdin());\n if (input) await ask(input);\n else await chat();\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(async () => {\n ${harness && 'await facts.close();'}\n await cogitator.close();\n });\n `;\n}\n\nexport const appScriptFeature: FeatureModule = {\n id: 'app:script',\n applies: (spec) => spec.app === 'script',\n apply(project) {\n const { spec } = project;\n const target = primaryTarget(spec);\n\n project\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n if (target === 'agent') project.script('ask', 'tsx --env-file-if-exists=.env src/index.ts');\n },\n finalize(project) {\n const { spec } = project;\n const target = primaryTarget(spec);\n const pm = spec.packageManager;\n if (target === 'agent') project.file('src/index.ts', agentEntry(project));\n project.section(\n 'Running',\n target === 'agent'\n ? code`\n \\`src/index.ts\\` is a terminal chat with the assistant. \\`${runScript(pm, 'dev')}\\` opens it and restarts on change, \\`${runScript(pm, 'ask', '\"your question\"')}\\` answers once, and piped stdin works too. \\`${runScript(pm, 'build')}\\` then \\`${runScript(pm, 'start')}\\` runs the compiled build.\n `\n : code`\n \\`src/index.ts\\` runs the project's ${target}. \\`${runScript(pm, 'dev')}\\` runs it with reload on change, \\`${runScript(pm, 'build')}\\` then \\`${runScript(pm, 'start')}\\` runs the compiled build.\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type ProjectSpec, type ServerFramework } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { a2aMount } from './a2a.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const SERVER_BASE_PATH = '/api';\nexport const SERVER_PORT = 3000;\n\n/** The registry exports a server mounts, by whether the project has workflows and swarms. */\nexport function registryImports(project: ProjectBuilder): { names: string[]; options: string } {\n const workflows = project.registry.some((entry) => entry.kind === 'workflows');\n const swarms = project.registry.some((entry) => entry.kind === 'swarms');\n const names = [\n 'agents',\n 'cogitator',\n ...(swarms ? ['swarms'] : []),\n ...(workflows ? ['workflows'] : []),\n ];\n const options = [\n 'cogitator',\n 'agents',\n ...(workflows ? ['workflows'] : []),\n ...(swarms ? ['swarms'] : []),\n ].join(', ');\n return { names, options };\n}\n\nconst AUTH_TS = code`\n import { timingSafeEqual } from 'node:crypto';\n\n /** Routes under ${SERVER_BASE_PATH} that answer without a token: health probes and the API docs. */\n const PUBLIC_PATHS = new Set(['/health', '/ready', '/docs', '/openapi.json']);\n\n export interface Caller {\n userId: string;\n }\n\n export class UnauthorizedError extends Error {\n readonly status = 401;\n\n constructor() {\n super('Unauthorized');\n this.name = 'UnauthorizedError';\n }\n }\n\n function isPublic(path: string): boolean {\n const bare = path.split('?')[0] ?? path;\n const local = bare.startsWith('${SERVER_BASE_PATH}/') ? bare.slice(${SERVER_BASE_PATH.length}) : bare;\n return PUBLIC_PATHS.has(local);\n }\n\n function sameToken(given: string, expected: string): boolean {\n const a = Buffer.from(given);\n const b = Buffer.from(expected);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n /**\n * Who is calling. With API_TOKEN set, every route except the public ones needs\n * \\`Authorization: Bearer <API_TOKEN>\\`; without it (local development only) all\n * requests are one local caller. Public routes are answered for anyone.\n */\n export function authenticate(path: string, authorization: string | undefined, token: string | undefined): Caller | undefined {\n if (isPublic(path)) return undefined;\n if (!token) return { userId: 'local' };\n const given = authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;\n if (!given || !sameToken(given, token)) throw new UnauthorizedError();\n return { userId: 'api' };\n }\n`;\n\n/** The settings every server reads from the environment, checked at startup. */\nfunction settings(spec: ProjectSpec): string {\n return code`\n const env = loadEnv();\n const production = process.env.NODE_ENV === 'production';\n const port = Number(env.PORT ?? ${SERVER_PORT});\n const host = env.HOST ?? (production ? '0.0.0.0' : '127.0.0.1');\n\n if (production && !env.API_TOKEN) {\n throw new Error('Set API_TOKEN in production: every route except health and docs requires it');\n }\n ${spec.server !== 'tetsu' && \"const corsOrigins = env.CORS_ORIGIN?.split(',').map((origin) => origin.trim()).filter(Boolean);\"}\n `;\n}\n\nfunction listening(): string {\n return code`\n console.log(\\`API on http://\\${host}:\\${port}${SERVER_BASE_PATH}, docs on http://\\${host}:\\${port}${SERVER_BASE_PATH}/docs\\`);\n if (!env.API_TOKEN) console.log('API_TOKEN is not set: the API answers anyone who can reach it');\n `;\n}\n\n/** The A2A routes of a server, when the project has the a2a feature. */\nfunction a2a(project: ProjectBuilder): { imports: string | false; mount: string | false } {\n const server = project.spec.server;\n if (!hasFeature(project.spec, 'a2a') || !server || server === 'tetsu')\n return { imports: false, mount: false };\n const { imports, mount } = a2aMount(server);\n return { imports: imports.join('\\n'), mount };\n}\n\nconst NODE_HTTP_CLOSE = code`\n interface Closable {\n close(callback: (error?: Error) => void): unknown;\n closeIdleConnections?: () => void;\n }\n\n function closeServer(server: Closable): Promise<void> {\n return new Promise((resolve, reject) => {\n server.close((error) => (error ? reject(error) : resolve()));\n server.closeIdleConnections?.();\n });\n }\n`;\n\nfunction honoEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { serve } from '@hono/node-server';\n import { cogitatorApp } from '@cogitator-ai/hono';\n import { Hono } from 'hono';\n import { cors } from 'hono/cors';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = new Hono();\n if (corsOrigins?.length) app.use('${SERVER_BASE_PATH}/*', cors({ origin: corsOrigins }));\n ${a2a(project).mount}\n app.route(\n '${SERVER_BASE_PATH}',\n cogitatorApp({\n ${options},\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (c) => authenticate(c.req.path, c.req.header('authorization'), env.API_TOKEN),\n })\n );\n\n const server = serve({ fetch: app.fetch, port, hostname: host }, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction expressEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { CogitatorServer } from '@cogitator-ai/express';\n import express from 'express';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = express();\n ${a2a(project).mount}\n const api = new CogitatorServer({\n app,\n ${options},\n config: {\n basePath: '${SERVER_BASE_PATH}',\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (req) => authenticate(req.path, req.get('authorization'), env.API_TOKEN),\n ...(corsOrigins?.length ? { cors: { origin: corsOrigins } } : {}),\n },\n });\n await api.init();\n\n const server = app.listen(port, host, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction fastifyEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import cors from '@fastify/cors';\n import { cogitatorPlugin } from '@cogitator-ai/fastify';\n import Fastify from 'fastify';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = Fastify({ logger: { level: production ? 'info' : 'warn' } });\n if (corsOrigins?.length) await app.register(cors, { origin: corsOrigins });\n ${a2a(project).mount}\n await app.register(cogitatorPlugin, {\n ${options},\n prefix: '${SERVER_BASE_PATH}',\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (request) => authenticate(request.url, request.headers.authorization, env.API_TOKEN),\n });\n\n await app.listen({ port, host });\n ${listening()}\n\n onShutdown(async () => {\n await app.close();\n await cogitator.close();\n });\n `;\n}\n\nfunction koaEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import cors from '@koa/cors';\n import { cogitatorApp } from '@cogitator-ai/koa';\n import Koa from 'koa';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = new Koa();\n ${a2a(project).mount}\n if (corsOrigins?.length) {\n const allowed = new Set(corsOrigins);\n app.use(cors({ origin: (ctx) => (allowed.has(ctx.get('origin')) ? ctx.get('origin') : '') }));\n }\n\n const router = cogitatorApp({\n ${options},\n enableSwagger: true,\n swagger: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' },\n auth: (ctx) => authenticate(ctx.path, ctx.get('authorization'), env.API_TOKEN),\n });\n router.prefix('${SERVER_BASE_PATH}');\n app.use(router.routes()).use(router.allowedMethods());\n\n const server = app.listen(port, host, () => {\n ${listening()}\n });\n\n ${NODE_HTTP_CLOSE}\n\n onShutdown(async () => {\n await closeServer(server);\n await cogitator.close();\n });\n `;\n}\n\nfunction tetsuEntry(project: ProjectBuilder): string {\n const { names, options } = registryImports(project);\n return code`\n import { cogitatorController } from '@cogitator-ai/tetsu';\n import { createApp, group } from '@tetsujs/core';\n import { docs } from '@tetsujs/openapi';\n import { authenticate } from './auth.js';\n import { ${names.join(', ')} } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n ${startupImports(project)}\n ${a2a(project).imports}\n\n ${settings(project.spec)}\n ${startupStatements(project)}\n\n const app = createApp({\n routes: [\n group('${SERVER_BASE_PATH}', {\n children: [\n cogitatorController({\n ${options},\n auth: (ctx) =>\n authenticate(new URL(ctx.req.url).pathname, ctx.req.headers.get('authorization') ?? undefined, env.API_TOKEN) ?? {},\n }),\n docs({ info: { title: ${tsString(`${project.spec.name} API`)}, version: '0.1.0' } }),\n ],\n }),\n ],\n });\n\n const server = Bun.serve({ ...app, port, hostname: host });\n ${listening()}\n\n onShutdown(async () => {\n await server.stop();\n await cogitator.close();\n });\n `;\n}\n\nconst ENTRIES: Record<ServerFramework, (project: ProjectBuilder) => string> = {\n hono: honoEntry,\n express: expressEntry,\n fastify: fastifyEntry,\n koa: koaEntry,\n tetsu: tetsuEntry,\n};\n\nfunction frameworkPackages(project: ProjectBuilder, server: ServerFramework): void {\n const adapter = `@cogitator-ai/${server}` as const;\n project.dependency(adapter, cogitatorVersion(adapter));\n switch (server) {\n case 'hono':\n project\n .dependency('hono', VERSIONS.hono)\n .dependency('@hono/node-server', VERSIONS.honoNodeServer);\n break;\n case 'express':\n project\n .dependency('express', VERSIONS.express)\n .devDependency('@types/express', VERSIONS.typesExpress);\n break;\n case 'fastify':\n project\n .dependency('fastify', VERSIONS.fastify)\n .dependency('@fastify/cors', VERSIONS.fastifyCors);\n break;\n case 'koa':\n project\n .dependency('koa', VERSIONS.koa)\n .dependency('@koa/router', VERSIONS.koaRouter)\n .dependency('@koa/cors', VERSIONS.koaCors)\n .devDependency('@types/koa', VERSIONS.typesKoa)\n .devDependency('@types/koa__cors', VERSIONS.typesKoaCors);\n break;\n case 'tetsu':\n project\n .dependency('@tetsujs/core', VERSIONS.tetsuCore)\n .dependency('@tetsujs/sse', VERSIONS.tetsuSse)\n .dependency('@tetsujs/openapi', VERSIONS.tetsuOpenapi);\n break;\n }\n}\n\nexport const appServerFeature: FeatureModule = {\n id: 'app:server',\n applies: (spec) => spec.app === 'server',\n apply(project) {\n const { spec } = project;\n const server = spec.server ?? 'hono';\n const bun = server === 'tetsu';\n\n frameworkPackages(project, server);\n project.file('src/auth.ts', AUTH_TS).file('src/lifecycle.ts', LIFECYCLE_TS);\n\n if (bun) {\n project.script('dev', 'bun --watch src/index.ts').script('start', 'bun src/index.ts');\n } else {\n project\n .devDependency('tsx', VERSIONS.tsx)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js');\n }\n\n project\n .envVar({\n name: 'PORT',\n description: 'Port the API listens on',\n example: String(SERVER_PORT),\n required: false,\n secret: false,\n })\n .envVar({\n name: 'HOST',\n description: 'Interface to listen on: 127.0.0.1 in development, 0.0.0.0 in production',\n example: '127.0.0.1',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'API_TOKEN',\n description:\n 'Bearer token every route except health and docs requires, mandatory in production',\n required: false,\n secret: true,\n deploy: true,\n });\n if (!bun) {\n project.envVar({\n name: 'CORS_ORIGIN',\n description:\n 'Comma-separated browser origins allowed to call the API, CORS is off without it',\n example: 'http://localhost:5173',\n required: false,\n secret: false,\n });\n }\n\n project.deploy.kind = 'server';\n project.deploy.port = SERVER_PORT;\n project.deploy.healthPath = `${SERVER_BASE_PATH}/health`;\n },\n finalize(project) {\n const { spec } = project;\n const server = spec.server ?? 'hono';\n const pm = spec.packageManager;\n project.file('src/index.ts', ENTRIES[server](project));\n\n project.section(\n 'Server',\n code`\n \\`src/index.ts\\` serves the registry over HTTP with ${server === 'tetsu' ? 'Tetsu on Bun' : server}: every agent${project.registry.some((e) => e.kind === 'workflows') ? ', workflow' : ''}${project.registry.some((e) => e.kind === 'swarms') ? ' and swarm' : ''} in \\`src/cogitator.ts\\` gets REST and SSE routes under \\`${SERVER_BASE_PATH}\\`, with OpenAPI docs at \\`${SERVER_BASE_PATH}/docs\\`. \\`src/auth.ts\\` decides who may call: with \\`API_TOKEN\\` set every route but health and docs needs \\`Authorization: Bearer <token>\\`. Start it with \\`${runScript(pm, 'dev')}\\` and try:\n\n \\`\\`\\`bash\n curl -X POST http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/agents/assistant/run -H 'content-type: application/json' -d '{\"input\":\"What time is it in Tokyo?\"}'\n \\`\\`\\`\n `\n );\n project.readmeSection(\n 'API',\n code`\n \\`${runScript(pm, 'dev')}\\` starts the API on http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}, with interactive docs at http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/docs.\n\n \\`\\`\\`bash\n curl -X POST http://localhost:${SERVER_PORT}${SERVER_BASE_PATH}/agents/assistant/run \\\\\n -H 'content-type: application/json' \\\\\n -d '{\"input\":\"What time is it in Tokyo?\"}'\n \\`\\`\\`\n\n Set \\`API_TOKEN\\` in \\`.env\\` to require \\`Authorization: Bearer <token>\\` on every route but health and docs. In production (\\`NODE_ENV=production\\`) the server refuses to start without it.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, IMAGES, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nexport const DEFAULT_DATABASE_URL = 'postgresql://cogitator:cogitator@localhost:5432/cogitator';\nexport const DEFAULT_REDIS_URL = 'redis://localhost:6379';\nexport const DEFAULT_MONGODB_URI = 'mongodb://localhost:27017';\nexport const SQLITE_PATH = './data/memory.db';\n\n/** The Redis service compose starts, shared by Redis memory and the queue worker. */\nexport function addRedisService(project: ProjectBuilder): void {\n project.service(\n {\n name: 'redis',\n image: IMAGES.redis,\n ports: ['6379:6379'],\n volumes: ['redis_data:/data'],\n healthcheck: {\n test: ['CMD', 'redis-cli', 'ping'],\n interval: '5s',\n timeout: '3s',\n retries: 10,\n },\n },\n 'redis_data'\n );\n project.envVar({\n name: 'REDIS_URL',\n description: 'The Redis server',\n example: DEFAULT_REDIS_URL,\n required: false,\n secret: false,\n });\n}\n\n/** The Postgres service with pgvector compose starts, shared by Postgres memory and the pgvector store. */\nexport function addPostgresService(project: ProjectBuilder): void {\n project.service(\n {\n name: 'postgres',\n image: IMAGES.postgres,\n ports: ['5432:5432'],\n environment: {\n POSTGRES_USER: 'cogitator',\n POSTGRES_PASSWORD: 'cogitator',\n POSTGRES_DB: 'cogitator',\n },\n volumes: ['postgres_data:/var/lib/postgresql'],\n healthcheck: {\n test: ['CMD-SHELL', 'pg_isready -U cogitator -d cogitator'],\n interval: '5s',\n timeout: '3s',\n retries: 10,\n },\n },\n 'postgres_data'\n );\n project.dependency('pg', VERSIONS.pg);\n project.envVar({\n name: 'DATABASE_URL',\n description: 'The Postgres database',\n example: DEFAULT_DATABASE_URL,\n required: false,\n secret: true,\n deploy: true,\n });\n}\n\nexport const memoryFeature: FeatureModule = {\n id: 'memory',\n applies: (spec) => spec.memory !== 'none',\n apply(project) {\n const { spec } = project;\n project.dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'));\n\n switch (spec.memory) {\n case 'memory':\n project.memoryYml.push('adapter: memory');\n break;\n case 'sqlite':\n project.dependency('better-sqlite3', VERSIONS.betterSqlite3).allowBuild('better-sqlite3');\n project.memoryYml.push('adapter: sqlite', 'sqlite:', ` path: ${SQLITE_PATH}`);\n project.ignore('data/');\n break;\n case 'postgres':\n addPostgresService(project);\n project.memoryYml.push(\n 'adapter: postgres',\n 'postgres:',\n ` connectionString: \\${DATABASE_URL:-${DEFAULT_DATABASE_URL}}`\n );\n break;\n case 'redis':\n addRedisService(project);\n project\n .dependency('@cogitator-ai/redis', cogitatorVersion('@cogitator-ai/redis'))\n .dependency('ioredis', VERSIONS.ioredis);\n project.memoryYml.push(\n 'adapter: redis',\n 'redis:',\n ` url: \\${REDIS_URL:-${DEFAULT_REDIS_URL}}`\n );\n break;\n case 'mongodb':\n project.service(\n {\n name: 'mongodb',\n image: IMAGES.mongodb,\n ports: ['27017:27017'],\n volumes: ['mongodb_data:/data/db'],\n healthcheck: {\n test: ['CMD', 'mongosh', '--quiet', '--eval', \"db.adminCommand('ping')\"],\n interval: '5s',\n timeout: '5s',\n retries: 10,\n },\n },\n 'mongodb_data'\n );\n project.dependency('mongodb', VERSIONS.mongodb);\n project.envVar({\n name: 'MONGODB_URI',\n description: 'The MongoDB server',\n example: DEFAULT_MONGODB_URI,\n required: false,\n secret: true,\n deploy: true,\n });\n project.memoryYml.push(\n 'adapter: mongodb',\n 'mongodb:',\n ` uri: \\${MONGODB_URI:-${DEFAULT_MONGODB_URI}}`,\n ' database: cogitator'\n );\n break;\n case 'none':\n break;\n }\n\n const where: Record<typeof spec.memory, string> = {\n none: '',\n memory: 'in the process, so it is gone after a restart',\n sqlite: `in SQLite at \\`${SQLITE_PATH}\\``,\n postgres: 'in Postgres (`DATABASE_URL`, started by `docker compose up -d`)',\n redis: 'in Redis (`REDIS_URL`, started by `docker compose up -d`)',\n mongodb: 'in MongoDB (`MONGODB_URI`, started by `docker compose up -d`)',\n };\n project.section(\n 'Memory',\n code`\n Conversations are stored ${where[spec.memory]}. The \\`memory\\` section of \\`cogitator.yml\\` configures it, and runs with the same \\`threadId\\` continue the same conversation. Tests replace it with in-process memory.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport { addRedisService, DEFAULT_REDIS_URL } from './memory.js';\nimport { LIFECYCLE_TS, startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const METRICS_PORT = 9464;\n\nconst QUEUE_TS = code`\n import { loadConfig } from '@cogitator-ai/config';\n import type { Agent } from '@cogitator-ai/core';\n import { type SerializedAgent, serializeAgent } from '@cogitator-ai/worker';\n\n /** The Redis the job queue lives in, shared by the worker and the producers. */\n export const redis = { url: process.env.REDIS_URL ?? '${DEFAULT_REDIS_URL}' };\n\n /**\n * An agent as a job carries it to a worker. Agents of this project take the\n * default model of cogitator.yml, which the job has to name explicitly.\n */\n export function forQueue(agent: Agent): SerializedAgent {\n if (agent.model) return serializeAgent(agent);\n const model = loadConfig().llm?.defaultModel;\n if (!model) throw new Error('Set llm.defaultModel in cogitator.yml or a model on the agent');\n return serializeAgent(agent.clone({ model }));\n }\n`;\n\nfunction workerEntry(project: ProjectBuilder): string {\n return code`\n import { createServer } from 'node:http';\n import { JobQueue, WorkerPool } from '@cogitator-ai/worker';\n import { cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n import { redis } from './queue.js';\n import { tools } from './tools/index.js';\n ${startupImports(project)}\n\n const env = loadEnv();\n ${startupStatements(project)}\n\n /**\n * Runs the agent jobs producers queue in Redis. Serialized agents name their\n * tools, and this worker provides the implementations of the assistant's.\n */\n const pool = new WorkerPool(\n { redis, cogitator, tools, concurrency: Number(env.WORKER_CONCURRENCY ?? 4) },\n {\n onJobStarted: (jobId, type) => console.log(\\`\\${type} job \\${jobId} started\\`),\n onJobCompleted: (jobId) => console.log(\\`job \\${jobId} completed\\`),\n onJobFailed: (jobId, error) => console.error(\\`job \\${jobId} failed: \\${error.message}\\`),\n onWorkerError: (error) => console.error(\\`worker error: \\${error.message}\\`),\n }\n );\n await pool.start();\n const queue = new JobQueue({ redis });\n\n /** Prometheus metrics of the pool on /metrics, and /health for probes. */\n const metrics = createServer(async (req, res) => {\n if (req.url === '/health') {\n res.writeHead(pool.isPoolRunning() ? 200 : 503, { 'content-type': 'application/json' });\n res.end(JSON.stringify({ status: pool.isPoolRunning() ? 'ok' : 'stopped' }));\n return;\n }\n if (req.url === '/metrics') {\n res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4' });\n res.end(pool.metrics.format(await pool.getMetrics(await queue.getMetrics())));\n return;\n }\n res.writeHead(404).end();\n });\n const metricsPort = Number(env.METRICS_PORT ?? ${METRICS_PORT});\n metrics.listen(metricsPort, () => console.log(\\`Worker running, metrics on http://localhost:\\${metricsPort}/metrics\\`));\n\n onShutdown(async () => {\n await pool.stop(30_000);\n await queue.close();\n await new Promise<void>((resolve) => metrics.close(() => resolve()));\n await cogitator.close();\n }, 40_000);\n `;\n}\n\nconst ENQUEUE_TS = code`\n import { JobQueue, type JobResult } from '@cogitator-ai/worker';\n import { agents } from './cogitator.js';\n import { forQueue, redis } from './queue.js';\n\n const FINISHED = new Set(['completed', 'failed']);\n\n /** Queues a question for the assistant, waits for a worker to answer it and prints the answer. */\n async function main(): Promise<void> {\n const input = process.argv.slice(2).join(' ').trim() || 'What can you do?';\n const queue = new JobQueue({ redis });\n try {\n const job = await queue.addAgentJob(forQueue(agents.assistant), input);\n console.error(\\`Queued job \\${job.id}, waiting for a worker...\\`);\n\n const deadline = Date.now() + 5 * 60_000;\n while (!FINISHED.has(await queue.getJobState(String(job.id)))) {\n if (Date.now() > deadline) throw new Error('No worker answered within 5 minutes: is one running?');\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n\n const done = await queue.getJob(String(job.id));\n if (!done || (await queue.getJobState(String(job.id))) === 'failed') {\n throw new Error(\\`The job failed: \\${done?.failedReason ?? 'unknown reason'}\\`);\n }\n const result: JobResult = done.returnvalue;\n console.log(result.type === 'agent' ? result.output : JSON.stringify(result, null, 2));\n } finally {\n await queue.close();\n }\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst WORKER_TEST_TS = code`\n import { processAgentJob } from '@cogitator-ai/worker';\n import { describe, expect, it } from 'vitest';\n import { agents } from '../src/cogitator.js';\n import { forQueue } from '../src/queue.js';\n import { tools } from '../src/tools/index.js';\n import { mockCogitator } from './helpers.js';\n\n describe('agent jobs', () => {\n it('run the serialized assistant with the worker tools', async () => {\n const { cogitator } = mockCogitator(\n {\n toolCalls: [{ id: 'call-1', name: 'calculator', arguments: { expression: '2 + 2' } }],\n finishReason: 'tool_calls',\n },\n { content: 'It is 4.' }\n );\n try {\n const result = await processAgentJob(\n { type: 'agent', jobId: 'job-1', agentConfig: forQueue(agents.assistant), input: '2 + 2?', threadId: 'thread-1' },\n { cogitator, tools }\n );\n expect(result.output).toBe('It is 4.');\n expect(result.toolCalls.map((call) => call.name)).toEqual(['calculator']);\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\n/** A queue worker: agent jobs in Redis, run by a BullMQ worker pool with metrics. */\nexport const appWorkerFeature: FeatureModule = {\n id: 'app:worker',\n applies: (spec) => spec.app === 'worker',\n apply(project) {\n addRedisService(project);\n project\n .dependency('@cogitator-ai/worker', cogitatorVersion('@cogitator-ai/worker'))\n .dependency('ioredis', VERSIONS.ioredis)\n .devDependency('tsx', VERSIONS.tsx)\n .file('src/queue.ts', QUEUE_TS)\n .file('src/lifecycle.ts', LIFECYCLE_TS)\n .file('src/enqueue.ts', ENQUEUE_TS)\n .file('tests/worker.test.ts', WORKER_TEST_TS)\n .script('dev', 'tsx watch --env-file-if-exists=.env src/index.ts')\n .script('build', 'tsc -p tsconfig.build.json')\n .script('start', 'node --env-file-if-exists=.env dist/index.js')\n .script('enqueue', 'tsx --env-file-if-exists=.env src/enqueue.ts')\n .envVar({\n name: 'WORKER_CONCURRENCY',\n description: 'How many jobs the worker runs at once',\n example: '4',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'METRICS_PORT',\n description: 'Port of the Prometheus metrics and health endpoint',\n example: String(METRICS_PORT),\n required: false,\n secret: false,\n });\n project.deploy.kind = 'worker';\n },\n finalize(project) {\n project.file('src/index.ts', workerEntry(project));\n const pm = project.spec.packageManager;\n project.section(\n 'Worker',\n code`\n \\`src/index.ts\\` is a \\`WorkerPool\\` of \\`@cogitator-ai/worker\\`: it takes agent, workflow and swarm jobs from the BullMQ queue in Redis (\\`REDIS_URL\\`) and runs them with the assistant's tools, with Prometheus metrics on \\`:${METRICS_PORT}/metrics\\`. \\`src/enqueue.ts\\` is a producer: \\`${runScript(pm, 'enqueue', '\"your question\"')}\\` queues a job for the assistant and prints the answer once a worker finished it. Start Redis with \\`docker compose up -d redis\\` and the worker with \\`${runScript(pm, 'dev')}\\`.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { execCommand, runScript } from '../package-manager.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature, type CodingAgent, type PackageManager } from '../spec.js';\nimport type { FeatureModule } from './types.js';\n\nconst CLI_BIN = 'node_modules/@cogitator-ai/cli/dist/index.js';\n\n/** The command that starts `cogitator mcp` from the project directory. */\nexport function mcpLaunch(pm: PackageManager): { command: string; args: string[] } {\n switch (pm) {\n case 'npm':\n return { command: 'npx', args: ['--no', 'cogitator', 'mcp'] };\n case 'pnpm':\n return { command: 'pnpm', args: ['exec', 'cogitator', 'mcp'] };\n case 'yarn':\n return { command: 'yarn', args: ['cogitator', 'mcp'] };\n case 'bun':\n return { command: 'bunx', args: ['cogitator', 'mcp'] };\n }\n}\n\n/**\n * Cursor does not say which directory it starts a server in, so its command\n * names the project explicitly through `${workspaceFolder}`.\n */\nfunction cursorLaunch(pm: PackageManager): { command: string; args: string[] } {\n const project = ['--project', '${workspaceFolder}'];\n if (pm === 'yarn') {\n return {\n command: 'yarn',\n args: ['--cwd', '${workspaceFolder}', 'cogitator', 'mcp', ...project],\n };\n }\n return { command: 'node', args: [`\\${workspaceFolder}/${CLI_BIN}`, 'mcp', ...project] };\n}\n\nfunction mcpJson(launch: { command: string; args: string[] }): string {\n return (\n JSON.stringify({ mcpServers: { cogitator: { type: 'stdio', ...launch } } }, null, 2) + '\\n'\n );\n}\n\nfunction tomlString(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction codexConfig(pm: PackageManager): string {\n const { command, args } = mcpLaunch(pm);\n return [\n '# Codex reads this file for trusted projects: the Cogitator docs and project tools over MCP.',\n '[mcp_servers.cogitator]',\n `command = ${tomlString(command)}`,\n `args = [${args.map(tomlString).join(', ')}]`,\n '',\n ].join('\\n');\n}\n\n/** Where each coding agent looks for the MCP config and the skills of a project. */\nconst LOCATIONS: Record<CodingAgent, { mcp: string; skill: string; label: string }> = {\n claude: { mcp: '.mcp.json', skill: '.claude/skills/cogitator/SKILL.md', label: 'Claude Code' },\n cursor: { mcp: '.cursor/mcp.json', skill: '.cursor/skills/cogitator/SKILL.md', label: 'Cursor' },\n codex: { mcp: '.codex/config.toml', skill: '.agents/skills/cogitator/SKILL.md', label: 'Codex' },\n};\n\nfunction skill(project: ProjectBuilder): string {\n const { spec } = project;\n const pm = spec.packageManager;\n const kinds = (kind: 'workflows' | 'swarms') =>\n project.registry.some((entry) => entry.kind === kind);\n const recipes = [\n code`\n ### Add a tool\n\n Write it in \\`src/tools/<name>.ts\\` with \\`tool()\\` from \\`@cogitator-ai/core\\` and a Zod schema for its arguments, add it to the list in \\`src/tools/index.ts\\`, and test it in \\`tests/tools.test.ts\\` by calling \\`execute\\` directly. Mark a tool that changes something outside the process with \\`sideEffects\\`, and one a person has to allow with \\`requiresApproval\\`.\n `,\n code`\n ### Add an agent\n\n Create \\`src/agents/<name>.ts\\` exporting a \\`new Agent({ name, instructions, tools })\\`, then register it in \\`agents\\` of \\`src/cogitator.ts\\`. Leave out \\`model\\` to use \\`llm.defaultModel\\` from \\`cogitator.yml\\`.\n `,\n kinds('workflows') &&\n code`\n ### Change a workflow\n\n Workflows live in \\`src/workflows/\\` and are built with \\`WorkflowBuilder\\`. Register a new one in \\`workflows\\` of \\`src/cogitator.ts\\`.\n `,\n kinds('swarms') &&\n code`\n ### Change a swarm\n\n Swarms are \\`SwarmConfig\\` objects in \\`src/swarms/\\`, registered in \\`swarms\\` of \\`src/cogitator.ts\\`.\n `,\n code`\n ### Grow the project\n\n \\`${execCommand(pm, 'cogitator add')} <feature>\\` adds what create-cogitator-app can generate (rag, mcp, workflows, swarms, evals, otel and more, \\`--memory\\`, \\`--deploy\\`) with the same code a new project would get. Run it with \\`--dry-run\\` first: it merges into files you changed, and refuses with a diff when it cannot.\n `,\n ].filter((recipe): recipe is string => typeof recipe === 'string');\n\n return code`\n ---\n name: cogitator\n description: Build and change this Cogitator agent project (agents, tools, ${kinds('workflows') ? 'workflows, ' : ''}${kinds('swarms') ? 'swarms, ' : ''}memory, tests). Use it whenever a task touches Cogitator code or cogitator.yml.\n ---\n\n # Working on a Cogitator project\n\n Cogitator moves faster than model training data. Before writing Cogitator code, look the API up in the docs of the installed version: the \\`cogitator\\` MCP server has \\`search_docs\\` and \\`read_doc\\`, and the same pages are in \\`node_modules/@cogitator-ai/core/docs/\\` (start at \\`index.md\\`). \\`inspect_project\\` lists the agents, tools${kinds('workflows') ? ', workflows' : ''}${kinds('swarms') ? ', swarms' : ''} the project registers, and \\`check_project\\` runs \\`cogitator doctor\\`.\n\n Read \\`AGENTS.md\\` for how this project is put together. Everything it runs is registered in \\`src/cogitator.ts\\`.\n\n ${recipes.join('\\n\\n')}\n\n ### Before you call it done\n\n 1. \\`${runScript(pm, 'test')}\\`: tests run offline, \\`mockCogitator\\` from \\`tests/helpers.ts\\` scripts the model's replies, including tool calls.\n 2. \\`${runScript(pm, 'typecheck')}\\` and \\`${runScript(pm, 'lint')}\\`.\n ${hasFeature(spec, 'evals') && `3. \\`${runScript(pm, 'eval')}\\` when you changed instructions or tools: it scores the assistant on \\`evals/\\` with the real model.`}\n `;\n}\n\n/** MCP config and a skill for the coding agents the project is set up for (`--agent`). */\nexport const codingAgentsFeature: FeatureModule = {\n id: 'coding-agents',\n applies: (spec) => spec.codingAgents.length > 0,\n apply(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n for (const agent of spec.codingAgents) {\n const location = LOCATIONS[agent];\n if (agent === 'claude') project.file(location.mcp, mcpJson(mcpLaunch(pm)));\n if (agent === 'cursor') project.file(location.mcp, mcpJson(cursorLaunch(pm)));\n if (agent === 'codex') project.file(location.mcp, codexConfig(pm));\n }\n\n const configured = spec.codingAgents.map((agent) => LOCATIONS[agent]);\n project.section(\n 'Coding agents',\n code`\n The \\`cogitator\\` MCP server (\\`cogitator mcp\\`) gives coding agents \\`search_docs\\` and \\`read_doc\\` over the docs of the installed Cogitator, \\`inspect_project\\` for the registry and \\`check_project\\` for \\`cogitator doctor\\`. It is configured for ${configured.map((location) => `${location.label} in \\`${location.mcp}\\``).join(', ')}, next to the \\`cogitator\\` skill${configured.length > 1 ? 's' : ''} in ${configured.map((location) => `\\`${location.skill}\\``).join(', ')}.\n `\n );\n },\n /** The skill names the workflows and swarms, which the app and orchestration modules register. */\n finalize(project) {\n const content = skill(project);\n for (const agent of project.spec.codingAgents) project.file(LOCATIONS[agent].skill, content);\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst DATASET_JSONL = [\n { input: 'What is 17 * 23?', expected: '391' },\n { input: 'What is the square root of 1764?', expected: '42' },\n { input: 'What is 2 to the power of 10?', expected: '1024' },\n { input: 'How many days does a leap year have?', expected: '366' },\n]\n .map((line) => JSON.stringify(line))\n .join('\\n')\n .concat('\\n');\n\nconst SUITE_TS = code`\n import { fileURLToPath } from 'node:url';\n import type { Cogitator } from '@cogitator-ai/core';\n import { contains, cost, Dataset, EvalSuite, latency, threshold } from '@cogitator-ai/evals';\n import { agents, cogitator } from '../src/cogitator.js';\n\n const DATASET = fileURLToPath(new URL('./assistant.jsonl', import.meta.url));\n\n /**\n * Scores the assistant on evals/assistant.jsonl: an answer passes when it\n * contains the expected text, and the suite passes when 80% of them do.\n */\n export async function createAssistantSuite(runtime: Cogitator, options: { concurrency?: number } = {}) {\n return new EvalSuite({\n dataset: await Dataset.fromJsonl(DATASET),\n target: { agent: agents.assistant, cogitator: runtime },\n metrics: [contains()],\n statisticalMetrics: [latency(), cost()],\n assertions: [threshold('contains', 0.8)],\n concurrency: options.concurrency ?? 2,\n timeout: 60_000,\n retries: 1,\n });\n }\n\n export default await createAssistantSuite(cogitator);\n`;\n\nconst SUITE_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { createAssistantSuite } from '../evals/assistant.eval.js';\n import { mockCogitator } from './helpers.js';\n\n describe('assistant eval suite', () => {\n it('passes when the answers contain the expected text', async () => {\n const { cogitator } = mockCogitator(\n { content: '17 * 23 = 391' },\n { content: 'It is 42.' },\n { content: '1024' },\n { content: 'A leap year has 366 days.' }\n );\n try {\n const suite = await createAssistantSuite(cogitator, { concurrency: 1 });\n const result = await suite.run();\n expect(result.aggregated.contains?.mean).toBe(1);\n expect(result.assertions.every((assertion) => assertion.passed)).toBe(true);\n } finally {\n await cogitator.close();\n }\n });\n\n it('fails when the answers are wrong', async () => {\n const { cogitator } = mockCogitator({ content: 'I do not know.' });\n try {\n const suite = await createAssistantSuite(cogitator, { concurrency: 1 });\n const result = await suite.run();\n expect(result.assertions.some((assertion) => !assertion.passed)).toBe(true);\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\n/** A dataset, metrics and a threshold for the assistant, run with `cogitator eval` locally and in CI. */\nexport const evalsFeature: FeatureModule = {\n id: 'feature:evals',\n applies: (spec) => hasFeature(spec, 'evals'),\n apply(project) {\n project\n .dependency('@cogitator-ai/evals', cogitatorVersion('@cogitator-ai/evals'))\n .file('evals/assistant.jsonl', DATASET_JSONL)\n .file('evals/assistant.eval.ts', SUITE_TS)\n .file('tests/evals.test.ts', SUITE_TEST_TS)\n .script('eval', 'cogitator eval --skip-without-key')\n .ignore('eval-report.json');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'Evals',\n code`\n \\`evals/assistant.eval.ts\\` scores the assistant on \\`evals/assistant.jsonl\\` with \\`@cogitator-ai/evals\\`: \\`contains\\` checks each answer against the expected text, \\`threshold\\` fails the suite below 80%, and latency and cost are measured too. \\`${runScript(pm, 'eval')}\\` runs every \\`evals/*.eval.ts\\` with the real model and exits 1 when an assertion fails, so CI can gate on it. Without an API key it skips instead. Add a case when you fix a bug, and \\`tests/evals.test.ts\\` checks the suite itself offline.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst WORKSPACE_TS = code`\n import { mkdirSync } from 'node:fs';\n import { resolve } from 'node:path';\n import { fileDelete, fileExists, fileList, fileRead, fileWrite, restrictFileTools } from '@cogitator-ai/core';\n\n /**\n * File tools confined to \\`root\\`: paths are relative to it, nothing outside it\n * is reachable (symlinks included), and writing or deleting waits for approval.\n */\n export function createWorkspaceTools(root: string) {\n const workspace = resolve(root);\n mkdirSync(workspace, { recursive: true });\n return restrictFileTools([fileRead, fileList, fileExists, fileWrite, fileDelete], [workspace], {\n base: workspace,\n requireApproval: (tool) => tool.sideEffects?.includes('filesystem') ?? false,\n });\n }\n\n /** The directory the assistant works in: ./workspace, or WORKSPACE_DIR. */\n export const WORKSPACE_DIR = process.env.WORKSPACE_DIR ?? 'workspace';\n\n export const workspaceTools = createWorkspaceTools(WORKSPACE_DIR);\n`;\n\nconst FACTS_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { CoreFactsStore } from '@cogitator-ai/memory';\n import { z } from 'zod';\n\n /** Lasting facts about the user (name, time zone, preferences) and the tools that keep them. */\n export function createFacts(path: string) {\n const store = new CoreFactsStore({ path });\n let opened: Promise<void> | undefined;\n /** Opens the database on first use, so importing this module touches no file. */\n const ready = () => (opened ??= store.initialize());\n\n const rememberFact = tool({\n name: 'remember_fact',\n description:\n 'Remember a lasting fact about the user, such as their name, time zone or a preference. Overwrites the fact with the same key.',\n parameters: z.object({\n key: z.string().min(1).max(64).describe('A short key, e.g. \"name\" or \"timezone\"'),\n value: z.string().min(1).max(500).describe('What to remember'),\n }),\n execute: async ({ key, value }) => {\n await ready();\n await store.set(key, value);\n return { remembered: key };\n },\n });\n\n const forgetFact = tool({\n name: 'forget_fact',\n description: 'Forget a fact about the user when they ask you to or it is no longer true.',\n parameters: z.object({ key: z.string().min(1).describe('The key of the fact') }),\n execute: async ({ key }) => {\n await ready();\n await store.delete(key);\n return { forgotten: key };\n },\n });\n\n /** Every fact, as run context, so the assistant knows them from the first message of a run. */\n async function context(): Promise<Record<string, string>> {\n await ready();\n return store.getAll();\n }\n\n async function close(): Promise<void> {\n if (!opened) return;\n await opened;\n await store.close();\n }\n\n return { store, rememberFact, forgetFact, tools: [rememberFact, forgetFact], context, close };\n }\n\n export const facts = createFacts(process.env.FACTS_PATH ?? './data/facts.db');\n export const factTools = facts.tools;\n`;\n\nconst SCHEDULER_TS = code`\n import { HeartbeatScheduler, SimpleTimerStore, getNextCronMs } from '@cogitator-ai/channels';\n import { createSchedulerTools } from '@cogitator-ai/core';\n\n /** Tasks the assistant schedules for later, kept on disk so they survive a restart. */\n export const timerStore = new SimpleTimerStore({\n persistPath: process.env.TIMERS_PATH ?? './data/timers.json',\n resolveCronFiresAt: (cron, timezone) => getNextCronMs(cron, Date.now(), timezone),\n });\n\n /** schedule_task, list_tasks and cancel_task: \"remind me in 20 minutes\", \"every morning at 9\". */\n export const schedulerTools = createSchedulerTools({ store: timerStore, defaultChannel: 'terminal' });\n\n /** Calls \\`onTask\\` with each task that comes due while the process runs. */\n export function startScheduler(onTask: (task: string) => Promise<void>): HeartbeatScheduler {\n const scheduler = new HeartbeatScheduler(timerStore, {\n onFire: (message) => onTask(message.text),\n pollInterval: 10_000,\n onError: (error) => console.error(\\`Scheduled task failed: \\${error.message}\\`),\n });\n scheduler.start();\n return scheduler;\n }\n`;\n\nconst HARNESS_TEST_TS = code`\n import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { Agent } from '@cogitator-ai/core';\n import { afterEach, beforeEach, describe, expect, it } from 'vitest';\n import { createFacts } from '../src/harness/facts.js';\n import { createWorkspaceTools } from '../src/harness/workspace.js';\n import { mockCogitator } from './helpers.js';\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'harness-'));\n });\n\n afterEach(() => {\n rmSync(dir, { recursive: true, force: true });\n });\n\n const context = { agentId: 'test', runId: 'test', signal: new AbortController().signal };\n\n function writeCall(path: string) {\n return {\n toolCalls: [{ id: 'call-1', name: 'file_write', arguments: { path, content: 'hello' } }],\n finishReason: 'tool_calls' as const,\n };\n }\n\n async function runWrite(path: string, approved: boolean) {\n const workspace = join(dir, 'workspace');\n const agent = new Agent({ name: 'writer', instructions: 'Write files.', tools: createWorkspaceTools(workspace) });\n const { cogitator } = mockCogitator(writeCall(path), { content: 'Done.' });\n try {\n const result = await cogitator.run(agent, {\n input: 'Write hello to notes.md',\n onApproval: () => (approved ? { approved: true } : { approved: false, reason: 'not now' }),\n });\n return { result, workspace };\n } finally {\n await cogitator.close();\n }\n }\n\n describe('workspace tools', () => {\n it('writes relative paths into the workspace once approved', async () => {\n const { workspace } = await runWrite('notes.md', true);\n expect(readFileSync(join(workspace, 'notes.md'), 'utf8')).toBe('hello');\n });\n\n it('writes nothing when the write is declined', async () => {\n const { workspace } = await runWrite('notes.md', false);\n expect(existsSync(join(workspace, 'notes.md'))).toBe(false);\n });\n\n it('cannot reach outside the workspace, also through a symlink', async () => {\n const workspace = join(dir, 'workspace');\n const [fileRead] = createWorkspaceTools(workspace);\n symlinkSync(dir, join(workspace, 'escape'));\n\n for (const path of ['../secret.txt', '/etc/passwd', 'escape/secret.txt']) {\n const result = (await fileRead.execute({ path }, context)) as { error?: string };\n expect(result.error, path).toContain('Access denied');\n }\n });\n\n it('asks before writing and deleting, never before reading', () => {\n const tools = createWorkspaceTools(join(dir, 'workspace'));\n const needApproval = tools.filter((tool) => tool.requiresApproval).map((tool) => tool.name);\n expect(needApproval.sort()).toEqual(['file_delete', 'file_write']);\n });\n });\n\n describe('facts', () => {\n it('remembers, recalls and forgets facts across restarts', async () => {\n const path = join(dir, 'facts.db');\n const first = createFacts(path);\n await first.rememberFact.execute({ key: 'name', value: 'Ada' }, context);\n await first.close();\n\n const second = createFacts(path);\n expect(await second.context()).toEqual({ name: 'Ada' });\n await second.forgetFact.execute({ key: 'name' }, context);\n expect(await second.context()).toEqual({});\n await second.close();\n });\n });\n`;\n\n/**\n * The assistant harness: a workspace the agent can read and write with your\n * approval, facts it keeps about you, and tasks it schedules for later.\n */\nexport const harnessFeature: FeatureModule = {\n id: 'feature:harness',\n applies: (spec) => hasFeature(spec, 'harness'),\n apply(project) {\n project\n .dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'))\n .dependency('@cogitator-ai/channels', cogitatorVersion('@cogitator-ai/channels'))\n .dependency('better-sqlite3', VERSIONS.betterSqlite3)\n .allowBuild('better-sqlite3')\n .file('src/harness/workspace.ts', WORKSPACE_TS)\n .file('src/harness/facts.ts', FACTS_TS)\n .file('src/harness/scheduler.ts', SCHEDULER_TS)\n .file('tests/harness.test.ts', HARNESS_TEST_TS)\n .toolSet('workspaceTools', '../harness/workspace.js')\n .toolSet('factTools', '../harness/facts.js')\n .toolSet('schedulerTools', '../harness/scheduler.js')\n .ignore('workspace/', 'data/')\n .envVar({\n name: 'WORKSPACE_DIR',\n description: 'The directory the assistant may read and write',\n example: 'workspace',\n required: false,\n secret: false,\n })\n .instruct(\n 'You have a workspace for files: read them freely, and know that writing or deleting needs the user to approve it.'\n )\n .instruct(\n 'Remember lasting facts about the user with remember_fact, and schedule reminders and recurring work with schedule_task.'\n );\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'Assistant harness',\n code`\n - \\`src/harness/workspace.ts\\`: file tools confined to \\`workspace/\\` (\\`WORKSPACE_DIR\\`) with \\`restrictFileTools\\` from core. Paths are relative to it, symlinks out of it are refused, and \\`file_write\\` and \\`file_delete\\` need approval: the terminal chat asks before they run.\n - \\`src/harness/facts.ts\\`: \\`remember_fact\\` and \\`forget_fact\\` keep lasting facts in \\`data/facts.db\\` (\\`CoreFactsStore\\`), and every run gets them as context.\n - \\`src/harness/scheduler.ts\\`: \\`schedule_task\\`, \\`list_tasks\\` and \\`cancel_task\\`. Tasks are kept in \\`data/timers.json\\`, and while \\`${runScript(pm, 'dev')}\\` runs, a due task is handed to the assistant like a message.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nconst NOTES_SERVER_TS = code`\n import { mkdir, readFile, writeFile } from 'node:fs/promises';\n import { dirname } from 'node:path';\n import { tool } from '@cogitator-ai/core';\n import { serveMCPTools } from '@cogitator-ai/mcp';\n import { z } from 'zod';\n\n /**\n * A small MCP server: notes in a JSON file, served over stdio. The assistant\n * connects to it in src/mcp/client.ts, and any MCP client (Claude Desktop,\n * Cursor) can use it the same way.\n */\n const NOTES_PATH = process.env.NOTES_PATH ?? 'data/notes.json';\n\n interface Note {\n id: number;\n text: string;\n createdAt: string;\n }\n\n async function readNotes(): Promise<Note[]> {\n try {\n return JSON.parse(await readFile(NOTES_PATH, 'utf8')) as Note[];\n } catch {\n return [];\n }\n }\n\n async function writeNotes(notes: Note[]): Promise<void> {\n await mkdir(dirname(NOTES_PATH), { recursive: true });\n await writeFile(NOTES_PATH, JSON.stringify(notes, null, 2));\n }\n\n const addNote = tool({\n name: 'add_note',\n description: 'Save a short note for later.',\n parameters: z.object({ text: z.string().min(1).max(2_000).describe('The note') }),\n execute: async ({ text }) => {\n const notes = await readNotes();\n const note = { id: (notes.at(-1)?.id ?? 0) + 1, text, createdAt: new Date().toISOString() };\n await writeNotes([...notes, note]);\n return note;\n },\n });\n\n const searchNotes = tool({\n name: 'search_notes',\n description: 'Find saved notes that contain all the given words. Without words, list every note.',\n parameters: z.object({ query: z.string().default('').describe('Words to look for') }),\n execute: async ({ query }) => {\n const words = query.toLowerCase().split(/\\\\s+/).filter(Boolean);\n const notes = await readNotes();\n return notes.filter((note) => words.every((word) => note.text.toLowerCase().includes(word)));\n },\n });\n\n await serveMCPTools([addNote, searchNotes], { name: 'notes', version: '1.0.0', transport: 'stdio' });\n`;\n\nconst MCP_CLIENT_TS = code`\n import { fileURLToPath } from 'node:url';\n import type { Tool } from '@cogitator-ai/core';\n import { connectMCPServer } from '@cogitator-ai/mcp';\n\n /**\n * The command that starts src/mcp/notes-server with the runtime of this\n * process: Bun runs the sources as they are, Node needs tsx for them and\n * runs dist/ after a build.\n */\n function notesServerCommand(): { command: string; args: string[] } {\n const fromSources = import.meta.url.endsWith('.ts');\n const server = fileURLToPath(new URL(\\`./notes-server.\\${fromSources ? 'ts' : 'js'}\\`, import.meta.url));\n const loader = fromSources && !process.versions.bun ? ['--import', 'tsx'] : [];\n return { command: process.execPath, args: [...loader, server] };\n }\n\n /**\n * Starts the notes MCP server and returns its tools as Cogitator tools. Add\n * more servers the same way, for example the official filesystem server:\n * \\`connectMCPServer({ transport: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '.'] })\\`.\n */\n export async function loadNotesTools(env: Record<string, string> = {}): Promise<{ tools: Tool[]; close: () => Promise<void> }> {\n const { tools, cleanup } = await connectMCPServer({ transport: 'stdio', ...notesServerCommand(), env, timeout: 30_000 });\n return { tools, close: cleanup };\n }\n\n /**\n * The MCP tools the assistant gets. A server that does not start leaves the\n * assistant without its tools instead of stopping the project.\n */\n async function connect(): Promise<Tool[]> {\n try {\n return (await loadNotesTools()).tools;\n } catch (error) {\n console.warn(\\`The notes MCP server did not start, continuing without it: \\${error instanceof Error ? error.message : error}\\`);\n return [];\n }\n }\n\n export const mcpTools = await connect();\n`;\n\nconst MCP_SERVE_TS = code`\n import { serveAgents } from '@cogitator-ai/mcp';\n import { agents, cogitator } from '../cogitator.js';\n\n /**\n * Serves every agent of the project as an MCP tool over stdio, so Claude\n * Desktop, Cursor or Claude Code can hand them tasks.\n */\n await serveAgents(cogitator, Object.values(agents));\n`;\n\nconst MCP_TEST_TS = code`\n import { mkdtempSync, rmSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { afterAll, beforeAll, describe, expect, it } from 'vitest';\n import type { Tool } from '@cogitator-ai/core';\n import { loadNotesTools } from '../src/mcp/client.js';\n\n const context = { agentId: 'test', runId: 'test', signal: new AbortController().signal };\n let dir: string;\n let notes: { tools: Tool[]; close: () => Promise<void> };\n\n function named(name: string): Tool {\n const found = notes.tools.find((tool) => tool.name === name);\n if (!found) throw new Error(\\`The notes server has no \\${name} tool\\`);\n return found;\n }\n\n beforeAll(async () => {\n dir = mkdtempSync(join(tmpdir(), 'mcp-'));\n notes = await loadNotesTools({ NOTES_PATH: join(dir, 'notes.json') });\n });\n\n afterAll(async () => {\n await notes.close();\n rmSync(dir, { recursive: true, force: true });\n });\n\n describe('notes MCP server', () => {\n it('offers its tools to Cogitator', () => {\n expect(notes.tools.map((tool) => tool.name).sort()).toEqual(['add_note', 'search_notes']);\n });\n\n it('saves notes and finds them again', async () => {\n await named('add_note').execute({ text: 'Buy oat milk' }, context);\n await named('add_note').execute({ text: 'Call the dentist' }, context);\n\n const found = await named('search_notes').execute({ query: 'milk' }, context);\n expect(found).toEqual([expect.objectContaining({ id: 1, text: 'Buy oat milk' })]);\n });\n });\n`;\n\n/** Tools from MCP servers for the assistant, and the project's agents served over MCP. */\nexport const mcpFeature: FeatureModule = {\n id: 'feature:mcp',\n applies: (spec) => hasFeature(spec, 'mcp'),\n apply(project) {\n project\n .dependency('@cogitator-ai/mcp', cogitatorVersion('@cogitator-ai/mcp'))\n .file('src/mcp/notes-server.ts', NOTES_SERVER_TS)\n .file('src/mcp/client.ts', MCP_CLIENT_TS)\n .file('src/mcp/serve.ts', MCP_SERVE_TS)\n .file('tests/mcp.test.ts', MCP_TEST_TS)\n .toolSet('mcpTools', '../mcp/client.js')\n .script('mcp:serve', 'tsx --env-file-if-exists=.env src/mcp/serve.ts')\n .ignore('data/')\n .instruct('Keep notes for the user with add_note and find them with search_notes.');\n },\n finalize(project) {\n const pm = project.spec.packageManager;\n project.section(\n 'MCP',\n code`\n - \\`src/mcp/notes-server.ts\\` is an MCP server of its own (\\`serveMCPTools\\`): notes in \\`data/notes.json\\` over stdio.\n - \\`src/mcp/client.ts\\` starts it and hands its tools to the assistant (\\`connectMCPServer\\`). Add other servers there; a server that fails to start is skipped with a warning.\n - \\`src/mcp/serve.ts\\` serves every agent of the registry as an MCP tool (\\`serveAgents\\`): \\`${runScript(pm, 'mcp:serve')}\\`. Point Claude Desktop, Cursor or Claude Code at that command to hand your agents tasks.\n `\n );\n project.readmeSection(\n 'MCP',\n code`\n The assistant uses the tools of the notes MCP server in \\`src/mcp/notes-server.ts\\`. To use your agents from Claude Desktop, Cursor or Claude Code, add this server to their MCP settings:\n\n \\`\\`\\`json\n {\n \"mcpServers\": {\n \"${project.spec.name}\": {\n \"command\": \"${pm === 'npm' ? 'npm' : pm}\",\n \"args\": [${pm === 'npm' ? '\"run\", \"--silent\", \"mcp:serve\"' : '\"--silent\", \"mcp:serve\"'}],\n \"cwd\": \"/absolute/path/to/${project.spec.name}\"\n }\n }\n }\n \\`\\`\\`\n `\n );\n },\n};\n","import { code, tsString } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { hasFeature } from '../spec.js';\nimport { IMAGES, VERSIONS } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nfunction observabilityTs(project: ProjectBuilder): string {\n const otel = hasFeature(project.spec, 'otel');\n const langfuse = hasFeature(project.spec, 'langfuse');\n const imports = [\n ...(langfuse ? ['createLangfuseExporter'] : []),\n ...(otel ? ['createOTLPExporter'] : []),\n 'type RunObserver',\n ];\n return code`\n import { ${imports.join(', ')} } from '@cogitator-ai/core';\n\n ${\n otel &&\n code`\n /** \\`key=value,key=value\\`, the format of OTEL_EXPORTER_OTLP_HEADERS. */\n function parseHeaders(value: string | undefined): Record<string, string> {\n const headers: Record<string, string> = {};\n for (const pair of value?.split(',') ?? []) {\n const at = pair.indexOf('=');\n if (at > 0) headers[decodeURIComponent(pair.slice(0, at).trim())] = decodeURIComponent(pair.slice(at + 1).trim());\n }\n return headers;\n }\n\n /**\n * Spans of every run to an OpenTelemetry collector (Jaeger, Tempo, Honeycomb,\n * Datadog) at OTEL_EXPORTER_OTLP_ENDPOINT, read the standard OTel way.\n */\n function otlp(): RunObserver | undefined {\n const base = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.replace(/\\\\/+$/, '');\n const endpoint = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT ?? (base && \\`\\${base}/v1/traces\\`);\n if (!endpoint) return undefined;\n const exporter = createOTLPExporter({\n endpoint,\n serviceName: process.env.OTEL_SERVICE_NAME ?? ${tsString(project.spec.name)},\n headers: parseHeaders(process.env.OTEL_EXPORTER_OTLP_HEADERS),\n enabled: true,\n });\n exporter.start();\n return exporter.observer();\n }\n `\n }\n\n ${\n langfuse &&\n code`\n /** Traces, inputs, outputs and costs of every run in Langfuse, when its keys are set. */\n async function langfuse(): Promise<RunObserver | undefined> {\n const publicKey = process.env.LANGFUSE_PUBLIC_KEY;\n const secretKey = process.env.LANGFUSE_SECRET_KEY;\n if (!publicKey || !secretKey) return undefined;\n const exporter = createLangfuseExporter({\n publicKey,\n secretKey,\n baseUrl: process.env.LANGFUSE_BASE_URL,\n enabled: true,\n });\n await exporter.init();\n return exporter.observer();\n }\n `\n }\n\n /**\n * What watches every run of the project, each switched on by its environment\n * variables. src/cogitator.ts hands them to the runtime, and closing the\n * runtime sends what they buffered.\n */\n export const observers: RunObserver[] = [${[otel && 'otlp()', langfuse && 'await langfuse()'].filter(Boolean).join(', ')}].filter(\n (observer): observer is RunObserver => observer !== undefined\n );\n `;\n}\n\n/** Traces of every run, to an OpenTelemetry collector and to Langfuse. */\nexport const observabilityFeature: FeatureModule = {\n id: 'feature:observability',\n applies: (spec) => hasFeature(spec, 'otel') || hasFeature(spec, 'langfuse'),\n apply(project) {\n const { spec } = project;\n project.file('src/observability.ts', observabilityTs(project));\n\n if (hasFeature(spec, 'otel')) {\n project\n .service({\n name: 'jaeger',\n image: IMAGES.jaeger,\n ports: ['16686:16686', '4318:4318'],\n })\n .envVar({\n name: 'OTEL_EXPORTER_OTLP_ENDPOINT',\n description:\n 'OTLP endpoint for traces; Jaeger from docker compose listens here, its UI on :16686',\n example: 'http://localhost:4318',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'OTEL_EXPORTER_OTLP_HEADERS',\n description:\n 'Headers for the collector, as key=value,key=value (API keys of hosted collectors)',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'OTEL_SERVICE_NAME',\n description: 'The service name traces carry',\n example: spec.name,\n required: false,\n secret: false,\n });\n }\n if (hasFeature(spec, 'langfuse')) {\n project\n .dependency('langfuse', VERSIONS.langfuse)\n .envVar({\n name: 'LANGFUSE_PUBLIC_KEY',\n description: 'Langfuse public key',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'LANGFUSE_SECRET_KEY',\n description: 'Langfuse secret key',\n required: false,\n secret: true,\n })\n .envVar({\n name: 'LANGFUSE_BASE_URL',\n description: 'Langfuse server, cloud.langfuse.com unless you host it',\n example: 'https://cloud.langfuse.com',\n required: false,\n secret: false,\n });\n }\n\n const where = [\n hasFeature(spec, 'otel') &&\n 'to the OTLP collector at `OTEL_EXPORTER_OTLP_ENDPOINT` (the Jaeger of `docker compose up -d jaeger` shows them at http://localhost:16686)',\n hasFeature(spec, 'langfuse') &&\n 'to Langfuse when `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set',\n ].filter(Boolean);\n project.section(\n 'Observability',\n code`\n \\`src/observability.ts\\` builds the run observers \\`src/cogitator.ts\\` hands to the runtime (\\`CogitatorConfig.observers\\`), so every run, from a script, a route, a workflow or a swarm, sends its spans ${where.join(' and ')}. Each is off until its variables are set, and \\`cogitator.close()\\` flushes them.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport type { ProjectBuilder } from '../project.js';\nimport { runScript } from '../package-manager.js';\nimport { hasFeature, primaryTarget } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport { startupImports, startupStatements } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nconst RESEARCHER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n import { currentTime } from '../tools/current-time.js';\n import { fetchUrl } from '../tools/fetch-url.js';\n\n export const researcher = new Agent({\n name: 'researcher',\n description: 'Collects facts and sources on a topic',\n instructions: [\n 'You research a topic and report the facts that matter, as short bullet points.',\n 'Read sources with fetch_url when they help, and name each source you used.',\n 'Mark anything you are not sure about.',\n ].join('\\\\n'),\n tools: [fetchUrl, currentTime],\n temperature: 0.3,\n });\n`;\n\nconst WRITER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n\n export const writer = new Agent({\n name: 'writer',\n description: 'Turns notes into clear, well-structured prose',\n instructions: [\n 'You write clear, well-structured text from the notes you are given.',\n 'Use a title, a short introduction and sections with headings. Do not invent facts.',\n ].join('\\\\n'),\n temperature: 0.7,\n });\n`;\n\nconst REVIEWER_TS = code`\n import { Agent } from '@cogitator-ai/core';\n\n export const reviewer = new Agent({\n name: 'reviewer',\n description: 'Leads the team: delegates research and writing, then checks the result',\n instructions: [\n 'You lead a small team: a researcher and a writer.',\n 'Delegate the research first, then the writing, and check the draft for accuracy and clarity before you answer with the final text.',\n ].join('\\\\n'),\n temperature: 0.2,\n });\n`;\n\n/** The researcher and writer agents the workflow and the swarm share, added once. */\nfunction addTeamAgents(project: ProjectBuilder): void {\n if (project.files.has('src/agents/researcher.ts')) return;\n project\n .file('src/agents/researcher.ts', RESEARCHER_TS)\n .file('src/agents/writer.ts', WRITER_TS)\n .register({\n kind: 'agents',\n name: 'researcher',\n from: './agents/researcher.js',\n binding: 'researcher',\n })\n .register({ kind: 'agents', name: 'writer', from: './agents/writer.js', binding: 'writer' });\n}\n\nconst REPORT_WORKFLOW_TS = code`\n import { WorkflowBuilder, agentNode } from '@cogitator-ai/workflows';\n import { researcher } from '../agents/researcher.js';\n import { writer } from '../agents/writer.js';\n\n export type ReportState = {\n topic: string;\n notes?: string;\n report?: string;\n };\n\n const research = agentNode<ReportState>(researcher, {\n inputMapper: (state) => \\`Research this topic and list the key facts: \\${state.topic}\\`,\n stateMapper: (result) => ({ notes: result.output }),\n });\n\n const write = agentNode<ReportState>(writer, {\n inputMapper: (state) => \\`Write a short report on \"\\${state.topic}\" from these notes:\\\\n\\\\n\\${state.notes ?? ''}\\`,\n stateMapper: (result) => ({ report: result.output }),\n });\n\n /** Research a topic, then write a report from the notes: two agents in a DAG. */\n export const reportWorkflow = new WorkflowBuilder<ReportState>('report')\n .initialState({ topic: '' })\n .addNode('research', research)\n .addNode('write', write, { after: ['research'] })\n .entryPoint('research')\n .build();\n`;\n\nconst REPORT_TEST_TS = code`\n import { WorkflowExecutor } from '@cogitator-ai/workflows';\n import { describe, expect, it } from 'vitest';\n import { workflows } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n describe('report workflow', () => {\n it('researches first, then writes the report from the notes', async () => {\n const { cogitator, backend } = mockCogitator(\n { content: '- Fact one\\\\n- Fact two' },\n { content: '# Report\\\\n\\\\nFact one and fact two.' }\n );\n try {\n const result = await new WorkflowExecutor(cogitator).execute(workflows.report, { topic: 'testing' });\n\n expect(result.error).toBeUndefined();\n expect(result.state.notes).toBe('- Fact one\\\\n- Fact two');\n expect(result.state.report).toBe('# Report\\\\n\\\\nFact one and fact two.');\n expect(JSON.stringify(backend.getLastCall()?.messages)).toContain('Fact two');\n } finally {\n await cogitator.close();\n }\n });\n });\n`;\n\nfunction workflowEntry(project: ProjectBuilder): string {\n return code`\n import { createInterface } from 'node:readline/promises';\n import { styleText } from 'node:util';\n import { WorkflowExecutor } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n async function topicFromUser(): Promise<string> {\n const fromArgs = process.argv.slice(2).join(' ').trim();\n if (fromArgs) return fromArgs;\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question('Topic for the report: ')).trim();\n } finally {\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const topic = await topicFromUser();\n if (!topic) throw new Error('Give the report a topic');\n\n const result = await new WorkflowExecutor(cogitator).execute(\n workflows.report,\n { topic },\n {\n onNodeStart: (node) => console.error(styleText('dim', \\`> \\${node}\\`)),\n onNodeComplete: (node, _output, duration) =>\n console.error(styleText('dim', \\` \\${node} done in \\${(duration / 1000).toFixed(1)}s\\`)),\n }\n );\n if (result.error) throw result.error;\n console.log(result.state.report);\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(() => cogitator.close());\n `;\n}\n\nexport const workflowsFeature: FeatureModule = {\n id: 'feature:workflows',\n applies: (spec) => hasFeature(spec, 'workflows'),\n apply(project) {\n addTeamAgents(project);\n project\n .dependency('@cogitator-ai/workflows', cogitatorVersion('@cogitator-ai/workflows'))\n .file('src/workflows/report.ts', REPORT_WORKFLOW_TS)\n .file('tests/report.test.ts', REPORT_TEST_TS)\n .register({\n kind: 'workflows',\n name: 'report',\n from: './workflows/report.js',\n binding: 'reportWorkflow',\n });\n },\n finalize(project) {\n const { spec } = project;\n if (\n spec.app === 'script' &&\n primaryTarget(spec) === 'workflow' &&\n !hasFeature(spec, 'durable')\n ) {\n project.file('src/index.ts', workflowEntry(project));\n }\n project.section(\n 'Workflows',\n code`\n \\`src/workflows/report.ts\\` is a DAG built with \\`WorkflowBuilder\\`: \\`research\\` runs the researcher, \\`write\\` runs the writer on its notes. Nodes are \\`agentNode\\`s (an agent) or \\`functionNode\\`s (your code), and \\`after\\` sets the order. Workflows are registered in \\`src/cogitator.ts\\`; \\`tests/report.test.ts\\` shows how to run one against a mocked model.\n `\n );\n },\n};\n\nconst PUBLISH_WORKFLOW_TS = code`\n import { mkdir, rm, writeFile, appendFile } from 'node:fs/promises';\n import { join } from 'node:path';\n import { WorkflowBuilder, agentNode, approvalNode, functionNode, humanWorkflowNode } from '@cogitator-ai/workflows';\n import { writer } from '../agents/writer.js';\n\n export type PublishState = {\n topic: string;\n draft?: string;\n approved?: boolean;\n path?: string;\n outcome?: 'published' | 'discarded';\n };\n\n /** Where published posts go; tests point it at a temporary directory. */\n export function publishDirectory(): string {\n return process.env.PUBLISH_DIR ?? 'out';\n }\n\n function slug(topic: string): string {\n return topic.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'post';\n }\n\n const draft = agentNode<PublishState>(writer, {\n inputMapper: (state) => \\`Write a short blog post about: \\${state.topic}\\`,\n stateMapper: (result) => ({ draft: result.output }),\n });\n\n /** A person approves the draft. The request survives restarts: it lives in the approval store. */\n const review = humanWorkflowNode(\n approvalNode<PublishState>('review', {\n title: 'Publish this post?',\n description: (state) => (state.draft ?? '').slice(0, 1_000),\n timeout: 24 * 60 * 60 * 1000,\n timeoutAction: 'reject',\n }),\n { stateMapper: (result) => ({ approved: result.approved }) }\n );\n\n /** Writes the post; its compensation deletes it again when a later step fails. */\n const publish = functionNode<PublishState, string>(\n 'publish',\n async (state) => {\n await mkdir(publishDirectory(), { recursive: true });\n const path = join(publishDirectory(), \\`\\${slug(state.topic)}.md\\`);\n await writeFile(path, state.draft ?? '');\n return path;\n },\n { stateMapper: (path) => ({ path }) }\n );\n\n /** Records the post in the changelog. Set FAIL_ANNOUNCE=1 to watch the saga roll back the publish. */\n const announce = functionNode<PublishState, void>('announce', async (state) => {\n if (process.env.FAIL_ANNOUNCE === '1') throw new Error('The announcement failed');\n await appendFile(join(publishDirectory(), 'CHANGELOG.md'), \\`- \\${new Date().toISOString()} \\${state.topic}\\\\n\\`);\n });\n\n const discard = functionNode<PublishState, 'discarded'>('discard', async () => 'discarded', {\n stateMapper: (outcome) => ({ outcome }),\n });\n\n /**\n * Draft, approve, publish, announce: a saga. The approval waits for a person\n * and survives restarts, and a failed announcement unpublishes the post.\n */\n export const publishWorkflow = new WorkflowBuilder<PublishState>('publish')\n .initialState({ topic: '' })\n .addNode('draft', draft)\n .addNode('review', review, { after: ['draft'] })\n .addConditional('decide', (state) => (state.approved ? 'publish' : 'discard'), { after: ['review'] })\n .addNode('publish', publish, {\n after: ['decide'],\n config: {\n compensation: {\n compensate: async (state) => {\n if (state.path) await rm(state.path, { force: true });\n },\n },\n },\n })\n .addNode('announce', announce, { after: ['publish'] })\n .addNode('discard', discard, { after: ['decide'] })\n .entryPoint('draft')\n .build();\n`;\n\nconst DURABLE_RUNTIME_TS = code`\n import type { Cogitator } from '@cogitator-ai/core';\n import { FileApprovalStore, FileCheckpointStore, createFileRunStore, createWorkflowManager } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n\n /**\n * The workflow manager with runs, checkpoints and approvals on disk under\n * \\`directory\\`: another process (\\`approve\\`) can answer an approval, and\n * \\`recoverRuns\\` continues the runs a crash interrupted.\n */\n export function createDurableRuntime(runtime: Cogitator, directory: string) {\n const approvalStore = new FileApprovalStore({ directory: \\`\\${directory}/approvals\\`, pollInterval: 500 });\n const manager = createWorkflowManager({\n cogitator: runtime,\n runStore: createFileRunStore({ directory: \\`\\${directory}/runs\\` }),\n checkpointStore: new FileCheckpointStore(\\`\\${directory}/checkpoints\\`),\n });\n manager.registerWorkflow(workflows.publish);\n return { manager, approvalStore };\n }\n\n export const { manager, approvalStore } = createDurableRuntime(cogitator, '.cogitator/workflows');\n`;\n\nfunction durableEntry(project: ProjectBuilder): string {\n return code`\n import { styleText } from 'node:util';\n import type { WorkflowRun } from '@cogitator-ai/workflows';\n import { cogitator, workflows } from './cogitator.js';\n import { approvalStore, manager } from './durable.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n const FINISHED = new Set<WorkflowRun['status']>(['completed', 'failed', 'cancelled']);\n\n /** Resolves when every run in \\`runIds\\` has finished, printing each change of status. */\n function untilFinished(runIds: Set<string>): Promise<void> {\n return new Promise((resolve) => {\n if (runIds.size === 0) return resolve();\n const stop = manager.onRunStateChange((run) => {\n if (!runIds.has(run.id)) return;\n console.error(styleText('dim', \\` run \\${run.id}: \\${run.status}\\`));\n if (!FINISHED.has(run.status)) return;\n runIds.delete(run.id);\n if (runIds.size === 0) {\n stop();\n resolve();\n }\n });\n });\n }\n\n const options = {\n approvalStore,\n onApprovalRequired: () =>\n console.error(styleText('yellow', 'Waiting for approval: answer it with the approve script in another terminal')),\n onCompensationStart: (node: string) => console.error(styleText('yellow', \\`Rolling back \\${node}\\`)),\n };\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n manager.start();\n\n const recovered = await manager.recoverRuns(options);\n if (recovered.resumed.length > 0) {\n console.error(\\`Continuing \\${recovered.resumed.length} run(s) a previous process left unfinished\\`);\n }\n const waiting = untilFinished(new Set(recovered.resumed));\n\n const topic = process.argv.slice(2).join(' ').trim();\n if (topic) {\n const result = await manager.execute(workflows.publish, { topic }, options);\n if (result.error) throw result.error;\n console.log(result.state.outcome === 'discarded' ? 'The post was not approved.' : \\`Published \\${result.state.path}\\`);\n } else if (recovered.resumed.length === 0) {\n console.log('Nothing to do. Start a run with a topic: the start script followed by the topic.');\n }\n\n await waiting;\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(async () => {\n manager.dispose();\n await cogitator.close();\n });\n`;\n}\n\nconst APPROVE_TS = code`\n import { createInterface } from 'node:readline/promises';\n import { approvalStore } from './durable.js';\n\n /** Answers the approvals the publish workflow is waiting for, from any terminal. */\n async function main(): Promise<void> {\n const pending = await approvalStore.getPendingRequests();\n if (pending.length === 0) {\n console.log('No approvals are waiting.');\n return;\n }\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n for (const request of pending) {\n console.log(\\`\\\\n\\${request.title}\\\\n\\\\n\\${request.description ?? ''}\\\\n\\`);\n const answer = (await rl.question('Approve? [y/N] ')).trim();\n await approvalStore.submitResponse({\n requestId: request.id,\n decision: /^y(es)?$/i.test(answer),\n respondedBy: process.env.USER ?? 'terminal',\n respondedAt: Date.now(),\n });\n }\n } finally {\n rl.close();\n }\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst START_PUBLISH_FIXTURE_TS = code`\n import { workflows } from '../../src/cogitator.js';\n import { createDurableRuntime } from '../../src/durable.js';\n import { mockCogitator } from '../helpers.js';\n\n /** Starts a publish run on a mocked model and says WAITING once it asks for approval. The test kills it there. */\n const [stateDir = '.cogitator/workflows'] = process.argv.slice(2);\n const { cogitator } = mockCogitator({ content: '# Hello\\\\n\\\\nA post.' });\n const { manager, approvalStore } = createDurableRuntime(cogitator, stateDir);\n await manager.execute(\n workflows.publish,\n { topic: 'Hello World' },\n { approvalStore, onApprovalRequired: () => console.log('WAITING') }\n );\n`;\n\nconst PUBLISH_TEST_TS = code`\n import { spawn } from 'node:child_process';\n import { once } from 'node:events';\n import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { InMemoryApprovalStore, WorkflowExecutor } from '@cogitator-ai/workflows';\n import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\n import { workflows } from '../src/cogitator.js';\n import { createDurableRuntime } from '../src/durable.js';\n import { mockCogitator } from './helpers.js';\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'publish-'));\n vi.stubEnv('PUBLISH_DIR', dir);\n });\n\n afterEach(() => {\n vi.unstubAllEnvs();\n rmSync(dir, { recursive: true, force: true });\n });\n\n /** Runs the workflow and answers its approval request with \\`decision\\` as soon as it is asked. */\n async function runApproved(decision: boolean) {\n const { cogitator } = mockCogitator({ content: '# Hello\\\\n\\\\nA post.' });\n const approvalStore = new InMemoryApprovalStore();\n try {\n return await new WorkflowExecutor(cogitator).execute(\n workflows.publish,\n { topic: 'Hello World' },\n {\n approvalStore,\n onApprovalRequired: (request) => {\n void approvalStore.submitResponse({\n requestId: request.id,\n decision,\n respondedBy: 'test',\n respondedAt: Date.now(),\n });\n },\n }\n );\n } finally {\n await cogitator.close();\n }\n }\n\n describe('publish workflow', () => {\n it('publishes and announces an approved post', async () => {\n const result = await runApproved(true);\n expect(result.error).toBeUndefined();\n expect(readFileSync(join(dir, 'hello-world.md'), 'utf8')).toContain('A post.');\n expect(readFileSync(join(dir, 'CHANGELOG.md'), 'utf8')).toContain('Hello World');\n });\n\n it('discards a rejected post', async () => {\n const result = await runApproved(false);\n expect(result.state.outcome).toBe('discarded');\n expect(existsSync(join(dir, 'hello-world.md'))).toBe(false);\n });\n\n it('unpublishes the post when the announcement fails', async () => {\n vi.stubEnv('FAIL_ANNOUNCE', '1');\n const result = await runApproved(true);\n expect(result.error?.message).toContain('announcement failed');\n expect(existsSync(join(dir, 'hello-world.md'))).toBe(false);\n });\n\n it('finishes a run waiting for approval after the process that started it was killed', async () => {\n const stateDir = join(dir, 'state');\n const child = spawn(process.execPath, ['--import', 'tsx', 'tests/fixtures/start-publish.ts', stateDir], {\n env: { ...process.env, PUBLISH_DIR: dir },\n stdio: ['ignore', 'pipe', 'inherit'],\n });\n await new Promise<void>((resolve, reject) => {\n child.stdout.on('data', (chunk: Buffer) => {\n if (chunk.toString().includes('WAITING')) resolve();\n });\n child.once('exit', (code) => reject(new Error(\\`The run exited with \\${code} before asking for approval\\`)));\n });\n child.kill('SIGKILL');\n await once(child, 'exit');\n\n const { cogitator, backend } = mockCogitator({ content: 'not needed: the draft is in the checkpoint' });\n const { manager, approvalStore } = createDurableRuntime(cogitator, stateDir);\n try {\n const recovered = await manager.recoverRuns({ approvalStore });\n expect(recovered.resumed).toHaveLength(1);\n\n const [request] = await approvalStore.getPendingRequests();\n await approvalStore.submitResponse({\n requestId: request.id,\n decision: true,\n respondedBy: 'test',\n respondedAt: Date.now(),\n });\n\n await vi.waitFor(\n async () => expect((await manager.getStatus(recovered.resumed[0]))?.status).toBe('completed'),\n { timeout: 15_000, interval: 100 }\n );\n expect(readFileSync(join(dir, 'hello-world.md'), 'utf8')).toContain('A post.');\n expect(backend.getCallCount()).toBe(0);\n } finally {\n manager.dispose();\n await cogitator.close();\n }\n }, 30_000);\n });\n`;\n\nexport const durableFeature: FeatureModule = {\n id: 'feature:durable',\n applies: (spec) => hasFeature(spec, 'durable'),\n apply(project) {\n project\n .file('src/workflows/publish.ts', PUBLISH_WORKFLOW_TS)\n .file('src/durable.ts', DURABLE_RUNTIME_TS)\n .file('src/approve.ts', APPROVE_TS)\n .file('tests/publish.test.ts', PUBLISH_TEST_TS)\n .file('tests/fixtures/start-publish.ts', START_PUBLISH_FIXTURE_TS)\n .register({\n kind: 'workflows',\n name: 'publish',\n from: './workflows/publish.js',\n binding: 'publishWorkflow',\n })\n .ignore('out/');\n if (project.spec.app === 'script') {\n project.script('approve', 'tsx --env-file-if-exists=.env src/approve.ts');\n }\n },\n finalize(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n if (spec.app === 'script' && primaryTarget(spec) === 'workflow') {\n project.file('src/index.ts', durableEntry(project));\n }\n project.section(\n 'Durable workflow',\n code`\n \\`src/workflows/publish.ts\\` is a saga: \\`draft\\` writes a post, \\`review\\` waits for a person to approve it, \\`publish\\` writes it to \\`out/\\` and \\`announce\\` adds it to the changelog. If \\`announce\\` fails, the compensation of \\`publish\\` deletes the post again (try \\`FAIL_ANNOUNCE=1\\`). \\`src/durable.ts\\` keeps runs, checkpoints and approvals under \\`.cogitator/workflows/\\`, so a run waiting for approval survives a restart: \\`manager.recoverRuns()\\` picks it up. Start a run with \\`${runScript(pm, 'dev', '\"your topic\"')}\\` and answer it from another terminal with \\`${runScript(pm, 'approve')}\\`.\n `\n );\n },\n};\n\nconst TEAM_SWARM_TS = code`\n import type { SwarmConfig } from '@cogitator-ai/swarms';\n import { researcher } from '../agents/researcher.js';\n import { reviewer } from '../agents/reviewer.js';\n import { writer } from '../agents/writer.js';\n\n /** A supervisor that delegates to a researcher and a writer and checks their work. */\n export const team: SwarmConfig = {\n name: 'team',\n strategy: 'hierarchical',\n supervisor: reviewer,\n workers: [researcher, writer],\n hierarchical: { visibility: 'full', workerCommunication: true },\n resources: { maxConcurrency: 2, timeout: 300_000 },\n };\n`;\n\nconst SWARM_TEST_TS = code`\n import { Swarm } from '@cogitator-ai/swarms';\n import { describe, expect, it } from 'vitest';\n import { swarms } from '../src/cogitator.js';\n import { mockCogitator } from './helpers.js';\n\n describe('team swarm', () => {\n it('answers through its supervisor', async () => {\n const { cogitator } = mockCogitator({ content: 'The final article.' });\n const team = new Swarm(cogitator, swarms.team);\n try {\n const result = await team.run({ input: 'Write about testing.' });\n expect(result.output).toContain('The final article.');\n } finally {\n await team.close();\n await cogitator.close();\n }\n });\n });\n`;\n\nfunction swarmEntry(project: ProjectBuilder): string {\n return code`\n import { createInterface } from 'node:readline/promises';\n import { styleText } from 'node:util';\n import { Swarm } from '@cogitator-ai/swarms';\n import { cogitator, swarms } from './cogitator.js';\n import { loadEnv } from './env.js';\n ${startupImports(project)}\n\n async function taskFromUser(): Promise<string> {\n const fromArgs = process.argv.slice(2).join(' ').trim();\n if (fromArgs) return fromArgs;\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question('Task for the team: ')).trim();\n } finally {\n rl.close();\n }\n }\n\n async function main(): Promise<void> {\n loadEnv();\n ${startupStatements(project)}\n const input = await taskFromUser();\n if (!input) throw new Error('Give the team a task');\n\n const team = new Swarm(cogitator, swarms.team);\n try {\n const result = await team.run({\n input,\n onAgentStart: (name) => console.error(styleText('dim', \\`> \\${name}\\`)),\n onAgentComplete: (name, run) =>\n console.error(styleText('dim', \\` \\${name} done, \\${run.usage.totalTokens} tokens\\`)),\n });\n console.log(result.output);\n } finally {\n await team.close();\n }\n }\n\n main()\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n })\n .finally(() => cogitator.close());\n `;\n}\n\nexport const swarmsFeature: FeatureModule = {\n id: 'feature:swarms',\n applies: (spec) => hasFeature(spec, 'swarms'),\n apply(project) {\n addTeamAgents(project);\n project\n .dependency('@cogitator-ai/swarms', cogitatorVersion('@cogitator-ai/swarms'))\n .file('src/agents/reviewer.ts', REVIEWER_TS)\n .file('src/swarms/team.ts', TEAM_SWARM_TS)\n .file('tests/team.test.ts', SWARM_TEST_TS)\n .register({\n kind: 'agents',\n name: 'reviewer',\n from: './agents/reviewer.js',\n binding: 'reviewer',\n })\n .register({ kind: 'swarms', name: 'team', from: './swarms/team.js', binding: 'team' });\n },\n finalize(project) {\n const { spec } = project;\n if (spec.app === 'script' && primaryTarget(spec) === 'swarm') {\n project.file('src/index.ts', swarmEntry(project));\n }\n project.section(\n 'Swarm',\n code`\n \\`src/swarms/team.ts\\` configures a hierarchical swarm: the \\`reviewer\\` supervises the \\`researcher\\` and the \\`writer\\` and delegates to them with tools. \\`new Swarm(cogitator, swarms.team)\\` runs it; other strategies (\\`round-robin\\`, \\`consensus\\`, \\`debate\\`, \\`auction\\`, \\`pipeline\\`, \\`negotiation\\`) take the same agents.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { providerInfo } from '../providers.js';\nimport { bareModel, hasFeature } from '../spec.js';\nimport { IMAGES } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\n/**\n * Ollama in compose starts with an empty volume, so a one-shot `ollama-pull`\n * service downloads the models the project uses once the server is healthy.\n * Later starts find them in the volume and finish at once.\n */\nexport const providerFeature: FeatureModule = {\n id: 'provider',\n applies: () => true,\n apply(project) {\n const { spec } = project;\n const info = providerInfo(spec.provider);\n\n if (spec.provider === 'ollama') {\n const models = [bareModel(spec)];\n if (hasFeature(spec, 'rag') && info.embeddingModel) models.push(info.embeddingModel);\n\n project.service(\n {\n name: 'ollama',\n image: IMAGES.ollama,\n ports: ['11434:11434'],\n volumes: ['ollama_data:/root/.ollama'],\n healthcheck: {\n test: ['CMD', 'ollama', 'list'],\n interval: '5s',\n timeout: '5s',\n retries: 20,\n },\n },\n 'ollama_data'\n );\n project.service({\n name: 'ollama-pull',\n image: IMAGES.ollama,\n dependsOn: { ollama: 'service_healthy' },\n environment: { OLLAMA_HOST: 'http://ollama:11434' },\n entrypoint: ['/bin/sh', '-c', models.map((model) => `ollama pull ${model}`).join(' && ')],\n restart: 'no',\n });\n }\n\n project.section(\n 'Model',\n code`\n The default model is set in \\`cogitator.yml\\` (\\`llm.defaultModel\\`, as \\`provider/model\\`) and agents without a \\`model\\` of their own use it. ${\n info.envKey\n ? `The ${info.label} key is read from \\`${info.envKey}\\` in \\`.env\\`.`\n : 'Ollama runs locally: `OLLAMA_BASE_URL` points at it, `http://localhost:11434` by default.'\n }\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { providerInfo } from '../providers.js';\nimport { hasFeature, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion, IMAGES, VERSIONS } from '../versions.js';\nimport { addPostgresService, DEFAULT_DATABASE_URL } from './memory.js';\nimport type { FeatureModule } from './types.js';\n\nconst DEFAULT_QDRANT_URL = 'http://localhost:6333';\n\nconst HANDBOOK_MD = code`\n # Team handbook\n\n This file is a sample knowledge base. Replace it with your own Markdown: everything under \\`docs/\\` is indexed, and the assistant answers from it with \\`rag_search\\`.\n\n ## Deploys\n\n We deploy on Tuesdays and Thursdays between 10:00 and 15:00 Berlin time. No deploys on Fridays or before a public holiday. Every deploy needs a green CI run and one approving review.\n\n ## On-call\n\n On-call rotates weekly on Monday at 09:00. The person on call answers pages within 15 minutes and writes an incident note for every page within one working day.\n\n ## Expenses\n\n Hardware up to 500 EUR needs no approval. Anything above that needs a manager's approval in the expenses tool before you buy it.\n`;\n\nfunction embeddingService(spec: ProjectSpec): { importName: string; expression: string } {\n switch (spec.provider) {\n case 'openai':\n return {\n importName: 'OpenAIEmbeddingService',\n expression: \"new OpenAIEmbeddingService({ apiKey: process.env.OPENAI_API_KEY ?? '' })\",\n };\n case 'google':\n return {\n importName: 'GoogleEmbeddingService',\n expression:\n \"new GoogleEmbeddingService({ apiKey: process.env.GOOGLE_API_KEY ?? '', dimensions: 768 })\",\n };\n case 'ollama':\n return {\n importName: 'OllamaEmbeddingService',\n expression: `new OllamaEmbeddingService({ baseUrl: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434', model: '${providerInfo('ollama').embeddingModel}' })`,\n };\n case 'anthropic':\n throw new Error(\n 'RAG needs an embedding provider, which compatibilityIssues rules out for Anthropic'\n );\n }\n}\n\nfunction storeCode(spec: ProjectSpec): { imports: string[]; body: string } {\n switch (spec.vectorStore) {\n case 'memory':\n return {\n imports: ['InMemoryEmbeddingAdapter'],\n body: code`\n /** Vectors in the process: the docs are indexed again on every start. */\n export function createStore(): EmbeddingAdapter {\n return new InMemoryEmbeddingAdapter();\n }\n `,\n };\n case 'postgres':\n return {\n imports: ['PostgresAdapter'],\n body: code`\n /** Vectors in Postgres with pgvector, kept across restarts. */\n export function createStore(embeddings: EmbeddingService): EmbeddingAdapter {\n return lazilyConnected(\n new PostgresAdapter({\n provider: 'postgres',\n connectionString: process.env.DATABASE_URL ?? '${DEFAULT_DATABASE_URL}',\n dimensions: embeddings.dimensions,\n })\n );\n }\n `,\n };\n case 'qdrant':\n return {\n imports: ['QdrantAdapter'],\n body: code`\n /** Vectors in Qdrant, kept across restarts. */\n export function createStore(embeddings: EmbeddingService): EmbeddingAdapter {\n return lazilyConnected(\n new QdrantAdapter({\n provider: 'qdrant',\n url: process.env.QDRANT_URL ?? '${DEFAULT_QDRANT_URL}',\n collection: 'docs',\n dimensions: embeddings.dimensions,\n })\n );\n }\n `,\n };\n }\n}\n\nconst LAZY_CONNECT = code`\n /** Connects a store on first use, so importing the project opens no connection. */\n function lazilyConnected(\n store: EmbeddingAdapter & { connect(): Promise<MemoryResult<void>> }\n ): EmbeddingAdapter {\n let connected: Promise<void> | undefined;\n const ready = () =>\n (connected ??= store.connect().then((result) => {\n if (!result.success) throw new Error(\\`Cannot connect the vector store: \\${result.error}\\`);\n }));\n return {\n async addEmbedding(embedding) {\n await ready();\n return store.addEmbedding(embedding);\n },\n async search(options) {\n await ready();\n return store.search(options);\n },\n async deleteEmbedding(id) {\n await ready();\n return store.deleteEmbedding(id);\n },\n async deleteBySource(source) {\n await ready();\n return store.deleteBySource(source);\n },\n async deleteByFilter(filter) {\n await ready();\n if (!store.deleteByFilter) throw new Error('The vector store cannot delete by filter');\n return store.deleteByFilter(filter);\n },\n };\n }\n`;\n\nfunction knowledgeBaseTs(spec: ProjectSpec): string {\n const embedding = embeddingService(spec);\n const store = storeCode(spec);\n const persistent = spec.vectorStore !== 'memory';\n const memoryImports = [...store.imports, embedding.importName].sort();\n return code`\n import { tool } from '@cogitator-ai/core';\n import {\n ${memoryImports.join(',\\n')},\n type EmbeddingAdapter,\n type EmbeddingService,\n ${persistent && 'type MemoryResult,'}\n } from '@cogitator-ai/memory';\n import { MarkdownLoader, RAGPipelineBuilder, ragTools } from '@cogitator-ai/rag';\n\n /** The folder the knowledge base indexes: ./docs, or DOCS_DIR. */\n export const DOCS_DIR = process.env.DOCS_DIR ?? 'docs';\n\n /** Turns text into vectors with the project's provider. */\n export function createEmbeddings(): EmbeddingService {\n return ${embedding.expression};\n }\n\n ${persistent && LAZY_CONNECT}\n\n ${store.body}\n\n /**\n * Markdown under \\`DOCS_DIR\\`, split into overlapping chunks and searched by\n * similarity. Ingesting a source again replaces its chunks, so re-indexing\n * after an edit never duplicates anything.\n */\n export function createKnowledgeBase(embeddings: EmbeddingService = createEmbeddings(), store: EmbeddingAdapter = createStore(${persistent ? 'embeddings' : ''})) {\n return new RAGPipelineBuilder()\n .withLoader(new MarkdownLoader())\n .withEmbeddingService(embeddings)\n .withEmbeddingAdapter(store)\n .withConfig({\n chunking: { strategy: 'recursive', chunkSize: 600, chunkOverlap: 80 },\n retrieval: { strategy: 'similarity', topK: 4, threshold: 0.2 },\n })\n .build();\n }\n\n export const knowledgeBase = createKnowledgeBase();\n\n const [search] = ragTools(knowledgeBase, { allowedRoots: [DOCS_DIR], allowUrls: false });\n\n /** rag_search: the assistant looks things up in the docs before it answers. */\n export const ragSearch = tool(search);\n `;\n}\n\nconst INGEST_TS = code`\n import { DOCS_DIR, knowledgeBase } from './knowledge-base.js';\n\n /** Indexes DOCS_DIR into the vector store. Safe to run again: changed files replace their old chunks. */\n async function main(): Promise<void> {\n const { documents, chunks } = await knowledgeBase.ingest(DOCS_DIR);\n console.log(\\`Indexed \\${documents} document(s) in \\${chunks} chunk(s) from \\${DOCS_DIR}\\`);\n }\n\n main().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exitCode = 1;\n });\n`;\n\nconst RAG_TEST_TS = code`\n import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';\n import { tmpdir } from 'node:os';\n import { join } from 'node:path';\n import { InMemoryEmbeddingAdapter, type EmbeddingService } from '@cogitator-ai/memory';\n import { afterEach, beforeEach, describe, expect, it } from 'vitest';\n import { createKnowledgeBase } from '../src/rag/knowledge-base.js';\n\n /** Bag-of-words vectors: the same words give similar vectors, with no model and no network. */\n const embeddings: EmbeddingService = {\n model: 'test',\n dimensions: 64,\n async embed(text) {\n const vector = new Array<number>(64).fill(0);\n for (const word of text.toLowerCase().match(/[a-z]+/g) ?? []) {\n let hash = 0;\n for (const char of word) hash = (hash * 31 + char.charCodeAt(0)) % 64;\n vector[hash] += 1;\n }\n return vector;\n },\n async embedBatch(texts) {\n return Promise.all(texts.map((text) => this.embed(text)));\n },\n };\n\n let dir: string;\n\n beforeEach(() => {\n dir = mkdtempSync(join(tmpdir(), 'rag-'));\n writeFileSync(join(dir, 'deploys.md'), '# Deploys\\\\n\\\\nWe deploy on Tuesdays and Thursdays only.');\n writeFileSync(join(dir, 'lunch.md'), '# Lunch\\\\n\\\\nThe kitchen serves soup every Wednesday.');\n });\n\n afterEach(() => {\n rmSync(dir, { recursive: true, force: true });\n });\n\n describe('knowledge base', () => {\n it('finds the document that answers the question', async () => {\n const kb = createKnowledgeBase(embeddings, new InMemoryEmbeddingAdapter());\n await kb.ingest(dir);\n\n const [best] = await kb.query('Which days do we deploy?');\n expect(best?.source).toContain('deploys.md');\n });\n\n it('replaces a document on re-ingest instead of duplicating it', async () => {\n const kb = createKnowledgeBase(embeddings, new InMemoryEmbeddingAdapter());\n await kb.ingest(dir);\n writeFileSync(join(dir, 'deploys.md'), '# Deploys\\\\n\\\\nDeploys happen on Mondays now.');\n await kb.ingest(dir);\n\n const results = await kb.query('deploy days', { topK: 10, threshold: 0 });\n const deploys = results.filter((r) => r.source?.includes('deploys.md'));\n expect(deploys).toHaveLength(1);\n expect(deploys[0]?.content).toContain('Mondays');\n });\n });\n`;\n\n/** Answers grounded in the Markdown of docs/: a RAG pipeline and a search tool for the assistant. */\nexport const ragFeature: FeatureModule = {\n id: 'feature:rag',\n applies: (spec) => hasFeature(spec, 'rag'),\n apply(project) {\n const { spec } = project;\n project\n .dependency('@cogitator-ai/rag', cogitatorVersion('@cogitator-ai/rag'))\n .dependency('@cogitator-ai/memory', cogitatorVersion('@cogitator-ai/memory'))\n .file('docs/handbook.md', HANDBOOK_MD)\n .file('src/rag/knowledge-base.ts', knowledgeBaseTs(spec))\n .file('src/rag/ingest.ts', INGEST_TS)\n .file('tests/rag.test.ts', RAG_TEST_TS)\n .tool('ragSearch', '../rag/knowledge-base.js')\n .instruct(\n 'Before you answer a question about the project, its team or its rules, search the docs with rag_search and answer from what it finds. Say so when the docs do not cover it.'\n )\n .envVar({\n name: 'DOCS_DIR',\n description: 'The folder of Markdown the knowledge base indexes',\n example: 'docs',\n required: false,\n secret: false,\n });\n\n if (\n spec.app === 'script' ||\n spec.app === 'server' ||\n spec.app === 'channels' ||\n spec.app === 'worker'\n ) {\n project.script('ingest', 'tsx --env-file-if-exists=.env src/rag/ingest.ts');\n }\n\n if (spec.vectorStore === 'postgres') {\n addPostgresService(project);\n } else if (spec.vectorStore === 'qdrant') {\n project\n .dependency('@qdrant/js-client-rest', VERSIONS.qdrant)\n .service(\n {\n name: 'qdrant',\n image: IMAGES.qdrant,\n ports: ['6333:6333'],\n volumes: ['qdrant_data:/qdrant/storage'],\n },\n 'qdrant_data'\n )\n .envVar({\n name: 'QDRANT_URL',\n description: 'The Qdrant server',\n example: DEFAULT_QDRANT_URL,\n required: false,\n secret: false,\n });\n } else {\n project.onStartup(\n \"import { DOCS_DIR, knowledgeBase } from './rag/knowledge-base.js';\",\n 'await knowledgeBase.ingest(DOCS_DIR);'\n );\n }\n if (spec.vectorStore !== 'memory') {\n project.step({\n command: runScript(spec.packageManager, 'ingest'),\n note: 'index docs/ once, and again after edits',\n });\n }\n },\n finalize(project) {\n const { spec } = project;\n const pm = spec.packageManager;\n project.section(\n 'RAG',\n code`\n \\`src/rag/knowledge-base.ts\\` indexes the Markdown under \\`docs/\\` with \\`@cogitator-ai/rag\\`: chunks are embedded with ${providerInfo(spec.provider).label} and stored ${spec.vectorStore === 'memory' ? 'in memory, so the project indexes them again on every start' : spec.vectorStore === 'postgres' ? 'in Postgres with pgvector' : 'in Qdrant'}. The assistant searches them with \\`rag_search\\`. ${spec.vectorStore === 'memory' ? '' : `\\`${runScript(pm, 'ingest')}\\` indexes the folder; re-running it after an edit replaces the changed files' chunks. `}\\`tests/rag.test.ts\\` runs the pipeline offline with deterministic bag-of-words embeddings.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { hasFeature } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport type { FeatureModule } from './types.js';\n\nexport const SANDBOX_IMAGE = 'python:3.13-alpine';\n\nconst RUN_PYTHON_TS = code`\n import { tool } from '@cogitator-ai/core';\n import { z } from 'zod';\n\n /**\n * Runs a shell command, usually \\`python3 -c '...'\\`, in a throwaway Docker\n * container: no network, 256 MB of memory, 30 seconds. Without Docker the\n * call fails instead of running on your machine, because cogitator.yml sets\n * sandbox.allowNativeFallback to false.\n */\n export const runPython = tool({\n name: 'run_python',\n description:\n 'Run Python in an isolated container without network access, for calculations, data processing and checking code. Pass a shell command such as python3 -c \"print(2 ** 100)\" and print what you need: stdout and stderr come back.',\n parameters: z.object({\n command: z.string().min(1).max(10_000).describe('The shell command to run, e.g. python3 -c \"print(1 + 1)\"'),\n }),\n sandbox: {\n type: 'docker',\n image: '${SANDBOX_IMAGE}',\n resources: { memory: '256MB', cpus: 1 },\n network: { mode: 'none' },\n timeout: 30_000,\n },\n timeout: 40_000,\n execute: async ({ command }) => command,\n });\n`;\n\nconst SANDBOX_TEST_TS = code`\n import { execFileSync } from 'node:child_process';\n import { describe, expect, it } from 'vitest';\n import { runPython } from '../src/tools/run-python.js';\n import { mockCogitator } from './helpers.js';\n\n function hasDocker(): boolean {\n try {\n execFileSync('docker', ['info'], { stdio: 'ignore', timeout: 10_000 });\n return true;\n } catch {\n return false;\n }\n }\n\n describe('run_python', () => {\n it('runs in a container without network and with limits', () => {\n expect(runPython.sandbox).toMatchObject({ type: 'docker', network: { mode: 'none' } });\n expect(runPython.sandbox?.resources?.memory).toBe('256MB');\n });\n\n it.runIf(hasDocker())('runs Python and returns its output', async () => {\n const { cogitator } = mockCogitator();\n try {\n const result = await cogitator.invokeTool(runPython, { command: 'python3 -c \"print(6 * 7)\"' });\n expect(JSON.stringify(result.result)).toContain('42');\n } finally {\n await cogitator.close();\n }\n }, 120_000);\n });\n`;\n\n/** Code the assistant writes runs in a Docker container, never on the host. */\nexport const sandboxFeature: FeatureModule = {\n id: 'feature:sandbox',\n applies: (spec) => hasFeature(spec, 'sandbox'),\n apply(project) {\n project\n .dependency('@cogitator-ai/sandbox', cogitatorVersion('@cogitator-ai/sandbox'))\n .file('src/tools/run-python.ts', RUN_PYTHON_TS)\n .file('tests/sandbox.test.ts', SANDBOX_TEST_TS)\n .tool('runPython', './run-python.js')\n .yml('sandbox', ['allowNativeFallback: false'])\n .instruct(\n 'For calculations and data work beyond the calculator, write Python and run it with run_python.'\n );\n project.section(\n 'Sandbox',\n code`\n \\`src/tools/run-python.ts\\` gives the assistant \\`run_python\\`: a command in a throwaway \\`${SANDBOX_IMAGE}\\` container without network, with 256 MB of memory and 30 seconds, through \\`@cogitator-ai/sandbox\\`. Docker has to run. Without it the call fails, since \\`sandbox.allowNativeFallback: false\\` in \\`cogitator.yml\\` keeps the code off your machine.\n `\n );\n },\n};\n","import { code } from '../code.js';\nimport { runScript } from '../package-manager.js';\nimport { providerInfo } from '../providers.js';\nimport { hasFeature, type ProjectSpec } from '../spec.js';\nimport { cogitatorVersion } from '../versions.js';\nimport { LIFECYCLE_TS } from './shared.js';\nimport type { FeatureModule } from './types.js';\n\nexport const VOICE_PORT = 3000;\n\nconst REALTIME_TOOLS_TS = code`\n import { type Cogitator, type Tool, toolToSchema } from '@cogitator-ai/core';\n import type { RealtimeTool } from '@cogitator-ai/voice';\n\n /**\n * The assistant's tools in the shape a realtime session takes. Each call runs\n * through \\`cogitator.invokeTool\\`, so arguments are validated and timeouts kept\n * the way an agent run does it. Tools that need approval are left out: a voice\n * session has nobody to click Approve.\n */\n export function realtimeTools(runtime: Cogitator, tools: readonly Tool[]): RealtimeTool[] {\n return tools\n .filter((tool) => !tool.requiresApproval)\n .map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toolToSchema(tool).parameters,\n execute: async (args) => {\n const result = await runtime.invokeTool(tool, args, { agentId: 'voice' });\n return result.error ? { error: result.error } : result.result;\n },\n }));\n }\n`;\n\nfunction voiceEntry(spec: ProjectSpec): string {\n const provider = spec.provider === 'google' ? 'gemini' : 'openai';\n const envKey = providerInfo(spec.provider).envKey ?? 'OPENAI_API_KEY';\n const inputRate = provider === 'openai' ? 24_000 : 16_000;\n return code`\n import { readFile } from 'node:fs/promises';\n import { createServer } from 'node:http';\n import { timingSafeEqual } from 'node:crypto';\n import { createCogitatorRunner, VoiceAgent } from '@cogitator-ai/voice';\n import { agents, cogitator } from './cogitator.js';\n import { loadEnv } from './env.js';\n import { onShutdown } from './lifecycle.js';\n import { tools } from './tools/index.js';\n import { realtimeTools } from './voice/tools.js';\n\n const env = loadEnv();\n const production = process.env.NODE_ENV === 'production';\n const port = Number(env.PORT ?? ${VOICE_PORT});\n const host = env.HOST ?? (production ? '0.0.0.0' : '127.0.0.1');\n if (production && !env.VOICE_TOKEN) {\n throw new Error('Set VOICE_TOKEN in production: every voice session costs realtime API time');\n }\n\n /** The browser page, from public/ next to src/ and dist/. */\n const page = await readFile(new URL('../public/index.html', import.meta.url));\n\n function allowed(token: string | null): boolean {\n if (!env.VOICE_TOKEN) return true;\n if (!token) return false;\n const a = Buffer.from(token);\n const b = Buffer.from(env.VOICE_TOKEN);\n return a.length === b.length && timingSafeEqual(a, b);\n }\n\n const voice = new VoiceAgent({\n mode: 'realtime',\n agent: createCogitatorRunner(cogitator, agents.assistant),\n realtimeProvider: '${provider}',\n realtimeApiKey: env.${envKey},\n tools: realtimeTools(cogitator, tools),\n transport: {\n path: '/voice',\n maxConnections: 10,\n verifyClient: (req) => allowed(new URL(req.url ?? '/', 'http://localhost').searchParams.get('token')),\n },\n });\n voice.on('error', (error) => console.error(\\`voice: \\${error.message}\\`));\n\n const server = createServer((req, res) => {\n const path = new URL(req.url ?? '/', 'http://localhost').pathname;\n if (path === '/health') {\n res.writeHead(200, { 'content-type': 'application/json' }).end('{\"status\":\"ok\"}');\n } else if (path === '/config') {\n res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ inputSampleRate: ${inputRate} }));\n } else if (path === '/') {\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end(page);\n } else {\n res.writeHead(404).end();\n }\n });\n voice.attach(server);\n\n server.listen(port, host, () => {\n console.log(\\`Open http://\\${host}:\\${port} and talk to the assistant\\`);\n });\n\n onShutdown(async () => {\n await voice.close();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n await cogitator.close();\n });\n `;\n}\n\nconst INDEX_HTML = code`\n <!doctype html>\n <html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Voice assistant</title>\n <style>\n :root { color-scheme: light dark; font-family: system-ui, sans-serif; }\n body { margin: 0; display: grid; place-items: center; min-height: 100vh; }\n main { width: min(40rem, 100% - 2rem); display: grid; gap: 1rem; }\n button { font: inherit; padding: 0.75rem 1.25rem; border-radius: 999px; border: 1px solid currentColor; cursor: pointer; }\n form { display: flex; gap: 0.5rem; }\n input { flex: 1; font: inherit; padding: 0.5rem 0.75rem; }\n ol { list-style: none; padding: 0; display: grid; gap: 0.5rem; }\n li b { text-transform: capitalize; }\n #status { opacity: 0.7; }\n </style>\n </head>\n <body>\n <main>\n <h1>Talk to the assistant</h1>\n <button id=\"talk\" type=\"button\">Start talking</button>\n <p id=\"status\">Not connected</p>\n <form id=\"text\"><input name=\"message\" placeholder=\"Or type a message\" autocomplete=\"off\" /><button type=\"submit\">Send</button></form>\n <ol id=\"log\"></ol>\n </main>\n <script type=\"module\">\n const OUTPUT_RATE = 24000;\n const RECORDER = \\`class Recorder extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0][0];\n if (input) {\n const pcm = new Int16Array(input.length);\n for (let i = 0; i < input.length; i++) {\n const s = Math.max(-1, Math.min(1, input[i]));\n pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff;\n }\n this.port.postMessage(pcm.buffer, [pcm.buffer]);\n }\n return true;\n }\n }\n registerProcessor('recorder', Recorder);\\`;\n\n const $ = (id) => document.getElementById(id);\n let socket, input, output, stream;\n let playhead = 0;\n const playing = new Set();\n\n const status = (text) => { $('status').textContent = text; };\n const log = (who, text) => {\n const item = document.createElement('li');\n item.innerHTML = '<b></b>: <span></span>';\n item.querySelector('b').textContent = who;\n item.querySelector('span').textContent = text;\n $('log').prepend(item);\n };\n\n function stopPlayback() {\n for (const node of playing) node.stop();\n playing.clear();\n playhead = output ? output.currentTime : 0;\n }\n\n function play(buffer) {\n const pcm = new Int16Array(buffer);\n const audio = output.createBuffer(1, pcm.length, OUTPUT_RATE);\n const channel = audio.getChannelData(0);\n for (let i = 0; i < pcm.length; i++) channel[i] = pcm[i] / 0x8000;\n const node = output.createBufferSource();\n node.buffer = audio;\n node.connect(output.destination);\n node.onended = () => playing.delete(node);\n playhead = Math.max(playhead, output.currentTime);\n node.start(playhead);\n playhead += audio.duration;\n playing.add(node);\n }\n\n function onEvent(event) {\n if (event.type === 'speech_start') stopPlayback();\n if (event.type === 'transcript' && event.isFinal !== false && event.text) log(event.role ?? 'you', event.text);\n if (event.type === 'agent_response' && event.text) log('assistant', event.text);\n }\n\n async function connect() {\n const { inputSampleRate } = await (await fetch('/config')).json();\n const token = new URLSearchParams(location.hash.slice(1)).get('token');\n const url = new URL('/voice', location.href);\n url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';\n if (token) url.searchParams.set('token', token);\n\n output = new AudioContext({ sampleRate: OUTPUT_RATE });\n input = new AudioContext({ sampleRate: inputSampleRate });\n await input.audioWorklet.addModule(URL.createObjectURL(new Blob([RECORDER], { type: 'text/javascript' })));\n stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true } });\n const recorder = new AudioWorkletNode(input, 'recorder');\n input.createMediaStreamSource(stream).connect(recorder);\n\n socket = new WebSocket(url);\n socket.binaryType = 'arraybuffer';\n recorder.port.onmessage = (message) => {\n if (socket.readyState === WebSocket.OPEN) socket.send(message.data);\n };\n socket.onopen = () => status('Listening. Speak, or type below.');\n socket.onmessage = (message) => (typeof message.data === 'string' ? onEvent(JSON.parse(message.data)) : play(message.data));\n socket.onclose = (event) => {\n status(event.code === 1000 ? 'Disconnected' : \\`Disconnected: \\${event.reason || event.code}\\`);\n disconnect();\n };\n $('talk').textContent = 'Stop';\n }\n\n function disconnect() {\n stopPlayback();\n for (const track of stream?.getTracks() ?? []) track.stop();\n input?.close();\n output?.close();\n if (socket && socket.readyState === WebSocket.OPEN) socket.close(1000);\n socket = input = output = stream = undefined;\n $('talk').textContent = 'Start talking';\n }\n\n $('talk').addEventListener('click', () => (socket ? disconnect() : connect().catch((error) => status(error.message))));\n $('text').addEventListener('submit', (event) => {\n event.preventDefault();\n const field = event.target.elements.message;\n if (!socket || socket.readyState !== WebSocket.OPEN || !field.value.trim()) return;\n socket.send(JSON.stringify({ type: 'text', text: field.value }));\n log('you', field.value);\n field.value = '';\n });\n </script>\n </body>\n </html>\n`;\n\nconst VOICE_TEST_TS = code`\n import { describe, expect, it } from 'vitest';\n import { agents } from '../src/cogitator.js';\n import { tools } from '../src/tools/index.js';\n import { realtimeTools } from '../src/voice/tools.js';\n import { mockCogitator } from './helpers.js';\n\n describe('realtime tools', () => {\n it('offers the assistant tools as JSON Schema', () => {\n const { cogitator } = mockCogitator();\n const bridged = realtimeTools(cogitator, tools);\n const calculator = bridged.find((tool) => tool.name === 'calculator');\n expect(calculator?.parameters).toMatchObject({ type: 'object', properties: { expression: expect.any(Object) } });\n expect(agents.assistant.instructions).toBeTruthy();\n });\n\n it('runs a call through the runtime and validates its arguments', async () => {\n const { cogitator } = mockCogitator();\n const calculator = realtimeTools(cogitator, tools).find((tool) => tool.name === 'calculator');\n expect(await calculator?.execute({ expression: '6 * 7' })).toEqual({ expression: '6 * 7', result: 42 });\n expect(await calculator?.execute({ expression: 42 })).toMatchObject({ error: expect.any(String) });\n await cogitator.close();\n });\n });\n`;\n\n/** A realtime voice agent: speech in, speech out, in the browser over WebSocket. */\nexport const voiceFeature: FeatureModule = {\n id: 'feature:voice',\n applies: (spec) => hasFeature(spec, 'voice'),\n apply(project) {\n project\n .dependency('@cogitator-ai/voice', cogitatorVersion('@cogitator-ai/voice'))\n .file('src/voice/tools.ts', REALTIME_TOOLS_TS)\n .file('public/index.html', INDEX_HTML)\n .file('tests/voice.test.ts', VOICE_TEST_TS)\n .envVar({\n name: 'PORT',\n description: 'Port of the voice page and WebSocket',\n example: String(VOICE_PORT),\n required: false,\n secret: false,\n })\n .envVar({\n name: 'HOST',\n description: 'Interface to listen on: 127.0.0.1 in development, 0.0.0.0 in production',\n example: '127.0.0.1',\n required: false,\n secret: false,\n })\n .envVar({\n name: 'VOICE_TOKEN',\n description: 'Token the voice page needs in its URL (#token=...), mandatory in production',\n required: false,\n secret: true,\n deploy: true,\n })\n .instruct('You are speaking out loud: keep answers short, plain and easy to follow by ear.');\n project.deploy.kind = 'server';\n project.deploy.port = VOICE_PORT;\n project.deploy.healthPath = '/health';\n },\n finalize(project) {\n const { spec } = project;\n if (spec.app === 'script') {\n project.file('src/index.ts', voiceEntry(spec)).file('src/lifecycle.ts', LIFECYCLE_TS);\n }\n project.section(\n 'Voice',\n code`\n \\`src/index.ts\\` serves \\`public/index.html\\` and a realtime \\`VoiceAgent\\` on \\`/voice\\` (${spec.provider === 'google' ? 'Gemini Live' : 'OpenAI Realtime'}): the page streams the microphone as PCM16, plays the answer and lets you interrupt by talking. \\`src/voice/tools.ts\\` hands the assistant's tools to the realtime session through \\`cogitator.invokeTool\\`, leaving out tools that need approval. Run \\`${runScript(spec.packageManager, 'dev')}\\` and open http://localhost:${VOICE_PORT}. In production set \\`VOICE_TOKEN\\` and open the page with \\`#token=<token>\\`.\n `\n );\n },\n};\n","import { a2aFeature } from './a2a.js';\nimport { appChannelsFeature } from './app-channels.js';\nimport { appNextFeature } from './app-next.js';\nimport { appScriptFeature } from './app-script.js';\nimport { appServerFeature } from './app-server.js';\nimport { appWorkerFeature } from './app-worker.js';\nimport { codingAgentsFeature } from './coding-agents.js';\nimport { deployFeature } from './deploy.js';\nimport { baseFeature } from './base.js';\nimport { evalsFeature } from './evals.js';\nimport { harnessFeature } from './harness.js';\nimport { mcpFeature } from './mcp.js';\nimport { observabilityFeature } from './observability.js';\nimport { memoryFeature } from './memory.js';\nimport { durableFeature, swarmsFeature, workflowsFeature } from './orchestration.js';\nimport { providerFeature } from './provider.js';\nimport { ragFeature } from './rag.js';\nimport { sandboxFeature } from './sandbox.js';\nimport { voiceFeature } from './voice.js';\nimport type { FeatureModule } from './types.js';\n\n/**\n * Every feature module in the order they run. Later modules can rely on what\n * earlier ones added: the app modules see the memory and the provider, and the\n * add-ons see the app.\n */\nexport const FEATURE_MODULES: readonly FeatureModule[] = [\n baseFeature,\n providerFeature,\n memoryFeature,\n harnessFeature,\n evalsFeature,\n ragFeature,\n mcpFeature,\n a2aFeature,\n voiceFeature,\n observabilityFeature,\n sandboxFeature,\n deployFeature,\n workflowsFeature,\n durableFeature,\n swarmsFeature,\n appScriptFeature,\n appServerFeature,\n appChannelsFeature,\n appNextFeature,\n appWorkerFeature,\n codingAgentsFeature,\n];\n","import type { ProjectSpecInput } from './spec.js';\n\n/** The parts of a spec a preset fixes: everything except the name, provider and tooling. */\nexport type PresetSpec = Pick<\n ProjectSpecInput,\n 'app' | 'server' | 'channels' | 'memory' | 'vectorStore' | 'features'\n> & { provider?: ProjectSpecInput['provider'] };\n\nexport interface Preset {\n id: string;\n label: string;\n hint: string;\n spec: PresetSpec;\n /** Earlier names of the preset that `--template` still accepts. */\n aliases?: string[];\n}\n\n/**\n * Named starting points. Every preset is a combination of the stack axes, so a\n * preset project can grow with `cogitator add` like any other.\n */\nexport const PRESETS: readonly Preset[] = [\n {\n id: 'basic',\n label: 'Basic agent',\n hint: 'one agent with real tools in your terminal, the best place to start',\n spec: { app: 'script', memory: 'none', features: [] },\n },\n {\n id: 'assistant',\n label: 'Personal assistant',\n hint: 'workspace files with approvals, long-term memory, a scheduler and evals',\n spec: { app: 'script', memory: 'sqlite', features: ['harness', 'evals'] },\n },\n {\n id: 'memory',\n label: 'Agent with memory',\n hint: 'conversations that survive restarts, in SQLite',\n spec: { app: 'script', memory: 'sqlite', features: [] },\n },\n {\n id: 'api-server',\n label: 'REST API server',\n hint: 'Express with Swagger UI, token auth and persistent threads',\n spec: { app: 'server', server: 'express', memory: 'sqlite', features: [] },\n },\n {\n id: 'hono',\n label: 'Hono server',\n hint: 'agents behind a small, fast HTTP API',\n spec: { app: 'server', server: 'hono', memory: 'sqlite', features: [] },\n },\n {\n id: 'tetsu',\n label: 'Tetsu server on Bun',\n hint: 'Bun-native controller with OpenAPI and WebSocket',\n spec: { app: 'server', server: 'tetsu', memory: 'memory', features: [] },\n },\n {\n id: 'nextjs',\n label: 'Next.js chat app',\n hint: 'streaming chat with tool calls, approvals and saved threads',\n spec: { app: 'next', memory: 'sqlite', features: [] },\n },\n {\n id: 'channels',\n label: 'Messaging bot',\n hint: 'one assistant on Telegram, Discord, Slack, WebChat, Bluesky or Threads',\n spec: { app: 'channels', channels: ['webchat'], memory: 'sqlite', features: [] },\n },\n {\n id: 'rag',\n label: 'RAG over your docs',\n hint: 'answers grounded in the files of docs/',\n spec: { app: 'script', memory: 'none', vectorStore: 'memory', features: ['rag'] },\n },\n {\n id: 'mcp',\n label: 'MCP tools and server',\n hint: 'tools from an MCP server, your agents served over MCP',\n spec: { app: 'script', memory: 'none', features: ['mcp'] },\n },\n {\n id: 'swarm',\n label: 'Multi-agent swarm',\n hint: 'a researcher and a writer under a reviewing supervisor',\n spec: { app: 'script', memory: 'none', features: ['swarms'] },\n },\n {\n id: 'workflow',\n label: 'DAG workflow',\n hint: 'a multi-step pipeline of agents',\n spec: { app: 'script', memory: 'none', features: ['workflows'] },\n },\n {\n id: 'durable-workflow',\n label: 'Durable workflow',\n hint: 'a saga with compensation, an approval step and crash recovery',\n spec: { app: 'script', memory: 'none', features: ['workflows', 'durable'] },\n },\n {\n id: 'a2a',\n label: 'A2A agent',\n hint: 'an agent other frameworks call over the Agent-to-Agent protocol',\n spec: { app: 'server', server: 'hono', memory: 'memory', features: ['a2a'] },\n },\n {\n id: 'voice-realtime',\n label: 'Realtime voice agent',\n hint: 'speech in, speech out over WebSocket',\n spec: { app: 'script', memory: 'none', features: ['voice'], provider: 'openai' },\n },\n {\n id: 'evals',\n label: 'Evals',\n hint: 'measure an agent on a dataset and gate CI on the score',\n spec: { app: 'script', memory: 'none', features: ['evals'] },\n },\n];\n\nexport const DEFAULT_PRESET = 'basic';\n\nexport function findPreset(idOrAlias: string): Preset | undefined {\n return PRESETS.find((preset) => preset.id === idOrAlias || preset.aliases?.includes(idOrAlias));\n}\n\nexport function presetIds(): string[] {\n return PRESETS.map((preset) => preset.id);\n}\n","import { code } from './code.js';\nimport { orderedScripts } from './emit.js';\nimport { findPreset } from './presets.js';\nimport type { NextStep, ProjectBuilder } from './project.js';\nimport { providerInfo } from './providers.js';\nimport { installCommand, runScript } from './package-manager.js';\nimport { bareModel, type ProjectSpec } from './spec.js';\n\nexport const DOCS_URL = 'https://cogitator.app/docs';\nexport const REPO_URL = 'https://github.com/cogitator-ai/Cogitator-AI';\n\n/** What is already done when the next steps are shown. */\nexport interface SetupState {\n /** Where the project is relative to the user's shell; no `cd` step when absent. */\n directory?: string;\n installed: boolean;\n /** Whether the provider key was written to `.env`. */\n keyWritten: boolean;\n /** Whether the Ollama model is known to be pulled. */\n modelReady: boolean;\n}\n\nfunction quoteDirectory(directory: string): string {\n return /^[\\w./-]+$/.test(directory) ? directory : JSON.stringify(directory);\n}\n\n/** Compose services the project needs while it runs, other than the model server. */\nfunction backingServices(project: ProjectBuilder): string[] {\n return [...project.services.keys()].filter((name) => name !== 'ollama' && name !== 'ollama-pull');\n}\n\n/** The commands that take a freshly scaffolded project to its first successful run. */\nexport function nextSteps(project: ProjectBuilder, state: SetupState): NextStep[] {\n const { spec } = project;\n const pm = spec.packageManager;\n const steps: NextStep[] = [];\n const info = providerInfo(spec.provider);\n\n if (state.directory) steps.push({ command: `cd ${quoteDirectory(state.directory)}` });\n if (!state.installed) steps.push({ command: installCommand(pm) });\n if (info.envKey && !state.keyWritten) {\n steps.push({ command: 'cp .env.example .env', note: `then set ${info.envKey} in .env` });\n }\n if (spec.provider === 'ollama' && !state.modelReady) {\n steps.push({\n command: `ollama pull ${bareModel(spec)}`,\n note: spec.compose\n ? 'or let `docker compose up -d` pull it into the Ollama container'\n : 'download the model the agents use',\n });\n }\n const services = backingServices(project);\n if (spec.compose && services.length > 0) {\n steps.push({ command: 'docker compose up -d', note: `starts ${services.join(', ')}` });\n }\n steps.push(...project.nextSteps);\n steps.push({ command: runScript(pm, 'dev') });\n return steps;\n}\n\nexport function emitReadme(project: ProjectBuilder): void {\n const { spec } = project;\n const pm = spec.packageManager;\n const preset = spec.preset ? findPreset(spec.preset) : undefined;\n const steps = nextSteps(project, {\n installed: false,\n keyWritten: false,\n modelReady: false,\n });\n const stepLines = steps.flatMap((step, i) => [\n ...(i > 0 ? [''] : []),\n ...(step.note ? [`# ${step.note}`] : []),\n step.command,\n ]);\n const sections = project.readme.map(\n (section) => `## ${section.title}\\n\\n${section.body.trim()}\\n`\n );\n\n project.file(\n 'README.md',\n code`\n # ${spec.name}\n\n ${preset ? `${preset.hint.charAt(0).toUpperCase()}${preset.hint.slice(1)}.` : 'An AI agent project.'} Built with [Cogitator](${REPO_URL}).\n\n ## Getting started\n\n \\`\\`\\`bash\n ${stepLines.join('\\n')}\n \\`\\`\\`\n\n ## Commands\n\n | Command | What it does |\n | --- | --- |\n ${Object.keys(orderedScripts(project.scripts))\n .map((script) => `| \\`${runScript(pm, script)}\\` | ${describeScript(script)} |`)\n .join('\\n')}\n\n ${sections.join('\\n')}\n\n ## Learn more\n\n - [AGENTS.md](./AGENTS.md): how this project is put together, for you and your coding agent\n - [Cogitator docs](${DOCS_URL})\n - [Cogitator on GitHub](${REPO_URL})\n `\n );\n}\n\nconst SCRIPT_DESCRIPTIONS: Record<string, string> = {\n dev: 'Run the project and restart on change',\n ask: 'Ask the assistant once: pass the question after the command',\n build: 'Compile the project',\n start: 'Run the compiled project',\n test: 'Offline tests with a mocked model',\n typecheck: 'Type-check without emitting',\n lint: 'Lint and check formatting with Biome',\n format: 'Format and fix lint issues',\n eval: 'Score the assistant on the eval dataset',\n 'dev:studio': 'Open Cogitator Studio: chat, traces, costs, approvals, workflows and forks',\n doctor: 'Check keys, services and models',\n ingest: 'Index the files in docs/ for RAG',\n 'mcp:serve': 'Serve the agents as an MCP server over stdio',\n worker: 'Start the queue worker',\n enqueue: 'Queue a job for the worker',\n};\n\nfunction describeScript(script: string): string {\n return SCRIPT_DESCRIPTIONS[script] ?? 'See package.json';\n}\n\n/** Re-creates the project with the same choices: stored in package.json for reference. */\nexport function reproducibleCommand(spec: ProjectSpec, version: string): string {\n const args = [\n `create-cogitator-app@${version}`,\n spec.name,\n ...(spec.preset ? ['--preset', spec.preset] : []),\n '--app',\n spec.app,\n ...(spec.server ? ['--server', spec.server] : []),\n ...(spec.channels.length > 0 ? ['--channels', spec.channels.join(',')] : []),\n '--memory',\n spec.memory,\n ...(spec.features.includes('rag') ? ['--vector-store', spec.vectorStore] : []),\n ...(spec.features.length > 0 ? ['--features', spec.features.join(',')] : []),\n '--provider',\n spec.provider,\n '--model',\n spec.model,\n '--deploy',\n spec.deploy,\n spec.compose ? '--docker' : '--no-docker',\n ...(spec.codingAgents.length > 0 ? ['--agent', spec.codingAgents.join(',')] : []),\n '--pm',\n spec.packageManager,\n '--yes',\n ];\n return `npx ${args.map((arg) => (/^[\\w@./:,=-]+$/.test(arg) ? arg : JSON.stringify(arg))).join(' ')}`;\n}\n","import type { ProjectSpec } from './spec.js';\n\n/** A variable the generated project reads from its environment. */\nexport interface EnvVar {\n name: string;\n /** One line for `.env.example` and the env schema. */\n description: string;\n /** The value `.env.example` shows; secrets show an empty value. */\n example?: string;\n /** Whether the project refuses to start without it. */\n required: boolean;\n /** Whether it is a credential: never logged, kept out of `.env.example` values. */\n secret: boolean;\n /**\n * Whether a deployment must provide it, listed in `cogitator.yml` as a\n * `deploy.secrets` entry. Defaults to secrets the project requires.\n */\n deploy?: boolean;\n}\n\n/** A service `docker compose up` starts for local development. */\nexport interface ComposeService {\n name: string;\n image: string;\n ports?: string[];\n environment?: Record<string, string>;\n volumes?: string[];\n command?: string[];\n entrypoint?: string[];\n dependsOn?: Record<string, 'service_started' | 'service_healthy'>;\n healthcheck?: { test: string[]; interval: string; timeout: string; retries: number };\n restart?: 'no' | 'unless-stopped';\n}\n\n/** A section of the generated AGENTS.md, which coding agents read before they touch the project. */\nexport interface AgentsMdSection {\n title: string;\n body: string;\n}\n\n/** A command that takes the project to its first run, with an optional explanation. */\nexport interface NextStep {\n command: string;\n note?: string;\n}\n\n/** Something the registry `src/cogitator.ts` exports by name. */\nexport interface RegistryEntry {\n kind: 'agents' | 'workflows' | 'swarms';\n /** The key under which the registry exposes it. */\n name: string;\n /** The module it is imported from, relative to `src/`. */\n from: string;\n /** The binding the module exports. */\n binding: string;\n}\n\n/** What `cogitator.yml` tells `cogitator deploy` about the project. */\nexport interface DeploySettings {\n kind?: 'server' | 'worker';\n port?: number;\n healthPath?: string;\n}\n\nexport interface GeneratedFile {\n path: string;\n /** Mutable until the plan is done, so a final pass can adapt every file. */\n content: string;\n /** File mode for `chmod`, used for `.env` (0600) and executable scripts. */\n mode?: number;\n}\n\n/**\n * The project as the feature modules build it up. Features add files, packages,\n * scripts, variables, services and documentation, and the emitters turn the\n * collected parts into package.json, `.env.example`, `docker-compose.yml`,\n * `cogitator.yml`, AGENTS.md and the registry once every feature has run.\n */\nexport class ProjectBuilder {\n readonly spec: ProjectSpec;\n readonly files = new Map<string, GeneratedFile>();\n readonly dependencies = new Map<string, string>();\n readonly devDependencies = new Map<string, string>();\n readonly scripts = new Map<string, string>();\n readonly env = new Map<string, EnvVar>();\n readonly services = new Map<string, ComposeService>();\n readonly volumes = new Set<string>();\n readonly agentsMd: AgentsMdSection[] = [];\n readonly readme: AgentsMdSection[] = [];\n readonly registry: RegistryEntry[] = [];\n readonly gitignore = new Set<string>();\n readonly nativeBuilds = new Set<string>();\n readonly nextSteps: NextStep[] = [];\n readonly warnings: string[] = [];\n readonly memoryYml: string[] = [];\n /** Top-level sections of cogitator.yml other features add, such as `sandbox`. */\n readonly ymlSections = new Map<string, string[]>();\n readonly deploy: DeploySettings = {};\n /** Tools the assistant gets: bindings `src/tools/index.ts` imports, `spread` for arrays of tools. */\n readonly tools: Array<{ binding: string; from: string; spread?: boolean }> = [];\n /** Imports and statements every entry point runs before it starts serving, such as indexing docs. */\n readonly startup: { imports: string[]; statements: string[] } = { imports: [], statements: [] };\n /** Lines of the assistant agent's instructions, one per feature that shapes its behavior. */\n readonly instructions: string[] = [];\n\n /** `name@version` of the package manager when it is known, such as `yarn@4.9.1`. */\n readonly packageManagerSpec?: string;\n\n constructor(spec: ProjectSpec, options: { packageManagerSpec?: string } = {}) {\n this.spec = spec;\n this.packageManagerSpec = options.packageManagerSpec;\n }\n\n file(path: string, content: string, mode?: number): this {\n if (this.files.has(path)) {\n throw new Error(`Two features generate ${path}: the feature modules overlap`);\n }\n this.files.set(path, { path, content, ...(mode !== undefined && { mode }) });\n return this;\n }\n\n /** Adds `name` at `version`. A package two features need must be asked for at one version. */\n dependency(name: string, version: string): this {\n return this.addPackage(this.dependencies, name, version);\n }\n\n devDependency(name: string, version: string): this {\n return this.addPackage(this.devDependencies, name, version);\n }\n\n private addPackage(target: Map<string, string>, name: string, version: string): this {\n const existing = target.get(name);\n if (existing !== undefined && existing !== version) {\n throw new Error(`${name} is requested at both ${existing} and ${version}`);\n }\n target.set(name, version);\n return this;\n }\n\n script(name: string, command: string): this {\n this.scripts.set(name, command);\n return this;\n }\n\n envVar(variable: EnvVar): this {\n const existing = this.env.get(variable.name);\n this.env.set(\n variable.name,\n existing ? { ...existing, required: existing.required || variable.required } : variable\n );\n return this;\n }\n\n service(service: ComposeService, volume?: string): this {\n this.services.set(service.name, service);\n if (volume) this.volumes.add(volume);\n return this;\n }\n\n section(title: string, body: string): this {\n this.agentsMd.push({ title, body });\n return this;\n }\n\n readmeSection(title: string, body: string): this {\n this.readme.push({ title, body });\n return this;\n }\n\n register(entry: RegistryEntry): this {\n if (this.registry.some((e) => e.kind === entry.kind && e.name === entry.name)) {\n throw new Error(`The registry already has ${entry.kind}.${entry.name}`);\n }\n this.registry.push(entry);\n return this;\n }\n\n tool(binding: string, from: string): this {\n this.tools.push({ binding, from });\n return this;\n }\n\n /** Gives the assistant every tool of an exported array. */\n toolSet(binding: string, from: string): this {\n this.tools.push({ binding, from, spread: true });\n return this;\n }\n\n ignore(...patterns: string[]): this {\n for (const pattern of patterns) this.gitignore.add(pattern);\n return this;\n }\n\n /** Packages with install scripts the package managers have to be allowed to run. */\n allowBuild(...packages: string[]): this {\n for (const name of packages) this.nativeBuilds.add(name);\n return this;\n }\n\n step(step: NextStep): this {\n this.nextSteps.push(step);\n return this;\n }\n\n warn(message: string): this {\n this.warnings.push(message);\n return this;\n }\n\n yml(section: string, lines: string[]): this {\n this.ymlSections.set(section, lines);\n return this;\n }\n\n onStartup(importLine: string, statement: string): this {\n if (!this.startup.imports.includes(importLine)) this.startup.imports.push(importLine);\n this.startup.statements.push(statement);\n return this;\n }\n\n instruct(line: string): this {\n this.instructions.push(line);\n return this;\n }\n}\n","import { assertCompatible } from './compat.js';\nimport {\n adaptImportsForBundler,\n emitAgentsMd,\n emitCogitatorYml,\n emitCompose,\n emitEnvExample,\n emitEnvFile,\n emitEnvModule,\n emitGitignore,\n emitPackageJson,\n emitPnpmWorkspace,\n emitRegistry,\n emitToolsIndex,\n} from './emit.js';\nimport { emitAssistant } from './features/base.js';\nimport { emitDeployArtifacts } from './features/deploy.js';\nimport { FEATURE_MODULES } from './features/index.js';\nimport { emitReadme, nextSteps, reproducibleCommand, type SetupState } from './guide.js';\nimport { ProjectBuilder, type EnvVar, type GeneratedFile, type NextStep } from './project.js';\nimport { parseSpec, type ProjectSpec } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\nexport interface PlanOptions {\n /** Values for `.env`, such as the provider key. Never written anywhere else. */\n secrets?: Record<string, string>;\n /** `name@version` of the package manager, written to package.json's `packageManager`. */\n packageManagerSpec?: string;\n}\n\n/** Everything a project consists of, computed without touching the disk. */\nexport interface ProjectPlan {\n spec: ProjectSpec;\n files: GeneratedFile[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n scripts: Record<string, string>;\n env: EnvVar[];\n /** Compose services the project starts locally. */\n services: string[];\n warnings: string[];\n /** The command that creates this project again. */\n command: string;\n /** The steps to the first run, before anything is installed. */\n nextSteps(state: SetupState): NextStep[];\n}\n\n/** What package.json records under `cogitator` so `cogitator add` can grow the project. */\nexport interface ScaffoldManifest {\n generator: string;\n spec: ProjectSpec;\n command: string;\n}\n\nexport const MANIFEST_KEY = 'cogitator';\n\n/**\n * The project `spec` describes. Throws when the spec is invalid or its parts do\n * not fit together, before anything is generated.\n */\nexport function planProject(input: unknown, options: PlanOptions = {}): ProjectPlan {\n const spec = parseSpec(input);\n assertCompatible(spec);\n\n const project = new ProjectBuilder(spec, { packageManagerSpec: options.packageManagerSpec });\n const active = FEATURE_MODULES.filter((feature) => feature.applies(spec));\n for (const feature of active) feature.apply(project);\n for (const feature of active) feature.finalize?.(project);\n\n const version = scaffolderVersion();\n const command = reproducibleCommand(spec, version);\n const manifest: ScaffoldManifest = {\n generator: `create-cogitator-app@${version}`,\n spec,\n command,\n };\n\n emitAssistant(project);\n emitToolsIndex(project);\n emitRegistry(project);\n emitEnvModule(project);\n emitEnvExample(project);\n emitEnvFile(project, options.secrets ?? {});\n emitCompose(project);\n emitCogitatorYml(project);\n emitPnpmWorkspace(project);\n emitGitignore(project);\n emitAgentsMd(project);\n emitReadme(project);\n adaptImportsForBundler(project);\n emitPackageJson(project, {\n packageManagerSpec: options.packageManagerSpec,\n cogitator: { ...manifest },\n });\n emitDeployArtifacts(project);\n\n const files = [...project.files.values()].sort((a, b) => a.path.localeCompare(b.path));\n return {\n spec,\n files,\n dependencies: Object.fromEntries(\n [...project.dependencies].sort(([a], [b]) => a.localeCompare(b))\n ),\n devDependencies: Object.fromEntries(\n [...project.devDependencies].sort(([a], [b]) => a.localeCompare(b))\n ),\n scripts: Object.fromEntries(project.scripts),\n env: [...project.env.values()],\n services: spec.compose ? [...project.services.keys()] : [],\n warnings: [...project.warnings],\n command,\n nextSteps: (state) => nextSteps(project, state),\n };\n}\n","import { spawn } from 'node:child_process';\n\nexport interface CommandResult {\n code: number;\n output: string;\n}\n\n/** The last `lines` lines of `text`, for error messages that show why a command failed. */\nexport function tail(text: string, lines = 20): string {\n return text.trimEnd().split('\\n').slice(-lines).join('\\n');\n}\n\n/**\n * Runs `command`. Output is captured, or shown live with `inherit`. A command\n * looked up on PATH goes through the shell on Windows, where package managers\n * are `.cmd` shims, unless `shell` is false for an executable given by path.\n * Resolves with the exit code instead of throwing, and rejects only when the\n * command cannot be started at all.\n */\nexport function runCommand(\n command: string,\n args: readonly string[],\n options: {\n cwd: string;\n inherit?: boolean;\n env?: NodeJS.ProcessEnv;\n timeoutMs?: number;\n shell?: boolean;\n }\n): Promise<CommandResult> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: options.env ?? process.env,\n stdio: options.inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'],\n shell: options.shell ?? process.platform === 'win32',\n timeout: options.timeoutMs,\n });\n let output = '';\n child.stdout?.on('data', (chunk: Buffer) => (output += chunk.toString()));\n child.stderr?.on('data', (chunk: Buffer) => (output += chunk.toString()));\n child.once('error', reject);\n child.once('close', (code, signal) => {\n resolve({ code: code ?? (signal ? 128 : 1), output });\n });\n });\n}\n\n/** Whether `command` can be run, judged by `<command> --version`. */\nexport async function hasCommand(command: string, cwd = process.cwd()): Promise<boolean> {\n try {\n return (await runCommand(command, ['--version'], { cwd, timeoutMs: 10_000 })).code === 0;\n } catch {\n return false;\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { parseDocument } from 'yaml';\nimport { unifiedDiff } from './diff.js';\nimport { AGENT_RULES_BEGIN, AGENT_RULES_END } from './emit.js';\nimport {\n applyOps,\n applyYamlOps,\n deepEqual,\n formatPath,\n merge3,\n parseStructured,\n structuredFormat,\n type MergeOp,\n} from './merge.js';\nimport { MANIFEST_KEY, planProject, type ProjectPlan } from './plan.js';\nimport type { EnvVar } from './project.js';\nimport {\n formatProject,\n hashContent,\n installDependencies,\n readLock,\n silentLogger,\n updateLock,\n type ScaffoldLock,\n type ScaffoldLogger,\n type StepResult,\n} from './scaffold.js';\nimport {\n parseSpec,\n type ChannelKind,\n type CodingAgent,\n type DeployTarget,\n type FeatureId,\n type MemoryKind,\n type ProjectSpec,\n type VectorStore,\n} from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\n/** What `cogitator add` brings into a project. Lists are added to, the rest replaced. */\nexport interface AddChanges {\n features?: readonly FeatureId[];\n channels?: readonly ChannelKind[];\n codingAgents?: readonly CodingAgent[];\n memory?: MemoryKind;\n vectorStore?: VectorStore;\n deploy?: DeployTarget;\n}\n\n/** A file `cogitator add` writes or removes, with the diff against what is on disk. */\nexport interface FileChange {\n path: string;\n kind: 'create' | 'update' | 'delete';\n /** The new content, absent for a deletion. */\n content?: string;\n /** How the content came about: generated as a whole, or merged into the user's copy. */\n source: 'generated' | 'merged';\n diff: string;\n}\n\n/** Something the addition left as it is on purpose. */\nexport interface AddNote {\n message: string;\n path?: string;\n /** The change that was not applied, when there is one. */\n diff?: string;\n}\n\n/** A file the user changed in a way the addition cannot be merged into. */\nexport interface AddConflict {\n path: string;\n reason: string;\n /** The change the addition needs to make to the file as generated. */\n diff: string;\n}\n\nexport interface AddPlan {\n directory: string;\n from: ProjectSpec;\n to: ProjectSpec;\n /** What changes in the spec, one item per line: `feature rag`, `memory sqlite -> postgres`. */\n summary: string[];\n changes: FileChange[];\n conflicts: AddConflict[];\n /** What was left as it is on purpose, and why. */\n notes: AddNote[];\n /** Dependencies the project gains or whose version changes. */\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n /** Dependencies and dev dependencies the merged package.json no longer lists. */\n removedDependencies: string[];\n /** Environment variables the project starts reading. */\n env: EnvVar[];\n /** Compose services the project starts using. */\n services: string[];\n warnings: string[];\n /** The command that creates the project as it is after the addition. */\n command: string;\n /** Whether the project already has everything asked for. */\n upToDate: boolean;\n}\n\nexport interface AddOptions {\n /** Install when the dependencies change (default `true`). */\n install?: boolean;\n log?: ScaffoldLogger;\n /** Show the install's output live instead of capturing it. */\n inheritOutput?: boolean;\n}\n\nexport interface AddResult {\n plan: AddPlan;\n /** Files written, relative to the project. */\n written: string[];\n deleted: string[];\n install: StepResult;\n format: StepResult;\n}\n\n/** Thrown when the project is not one the scaffolder generated, so its parts are unknown. */\nexport class NotAScaffoldedProjectError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NotAScaffoldedProjectError';\n }\n}\n\n/** Thrown when an addition would overwrite changes the user made. Nothing is written. */\nexport class AddConflictError extends Error {\n readonly conflicts: AddConflict[];\n\n constructor(conflicts: AddConflict[]) {\n super(\n [\n `cogitator add would overwrite your changes to ${conflicts.length} file${conflicts.length === 1 ? '' : 's'}, so nothing was written:`,\n ...conflicts.map((conflict) => `- ${conflict.path}: ${conflict.reason}`),\n 'Apply the changes below by hand, or commit your edits elsewhere and restore the generated files, then run cogitator add again.',\n ].join('\\n')\n );\n this.name = 'AddConflictError';\n this.conflicts = conflicts;\n }\n}\n\ninterface ProjectState {\n manifest: Record<string, unknown>;\n spec: ProjectSpec;\n packageManagerSpec?: string;\n generator?: string;\n}\n\nfunction readProject(directory: string): ProjectState {\n const manifestPath = join(directory, 'package.json');\n if (!existsSync(manifestPath)) {\n throw new NotAScaffoldedProjectError(\n `There is no package.json in ${directory}: run cogitator add in the root of the project`\n );\n }\n const manifest: unknown = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n throw new NotAScaffoldedProjectError(`${manifestPath} is not a package manifest`);\n }\n const record = manifest as Record<string, unknown>;\n const stored = record[MANIFEST_KEY];\n if (typeof stored === 'object' && stored !== null && 'example' in stored && !('spec' in stored)) {\n throw new NotAScaffoldedProjectError(\n `${directory} was created from an example, not generated from a spec, so cogitator add cannot extend it. Generate a project with the features you need instead: npx create-cogitator-app`\n );\n }\n if (typeof stored !== 'object' || stored === null || !('spec' in stored)) {\n throw new NotAScaffoldedProjectError(\n `${directory} was not created by create-cogitator-app: its package.json has no \"${MANIFEST_KEY}\" field, so cogitator add cannot tell what the project contains`\n );\n }\n const spec = parseSpec(stored.spec);\n const generator =\n 'generator' in stored && typeof stored.generator === 'string' ? stored.generator : undefined;\n const packageManagerSpec =\n typeof record.packageManager === 'string' ? record.packageManager : undefined;\n return { manifest: record, spec, packageManagerSpec, generator };\n}\n\nfunction withChanges(spec: ProjectSpec, changes: AddChanges): ProjectSpec {\n return parseSpec({\n ...spec,\n features: [...spec.features, ...(changes.features ?? [])],\n channels: [...spec.channels, ...(changes.channels ?? [])],\n codingAgents: [...spec.codingAgents, ...(changes.codingAgents ?? [])],\n ...(changes.memory && { memory: changes.memory }),\n ...(changes.vectorStore && { vectorStore: changes.vectorStore }),\n ...(changes.deploy && { deploy: changes.deploy }),\n });\n}\n\nfunction describeChanges(from: ProjectSpec, to: ProjectSpec): string[] {\n const added = <T>(before: readonly T[], after: readonly T[]) =>\n after.filter((item) => !before.includes(item));\n return [\n ...added(from.features, to.features).map((feature) => `feature ${feature}`),\n ...added(from.channels, to.channels).map((channel) => `channel ${channel}`),\n ...added(from.codingAgents, to.codingAgents).map((agent) => `coding agent ${agent}`),\n ...(from.memory !== to.memory ? [`memory ${from.memory} -> ${to.memory}`] : []),\n ...(from.vectorStore !== to.vectorStore\n ? [`vector store ${from.vectorStore} -> ${to.vectorStore}`]\n : []),\n ...(from.deploy !== to.deploy ? [`deploy ${from.deploy} -> ${to.deploy}`] : []),\n ];\n}\n\nfunction changedEntries(\n before: Record<string, string>,\n after: Record<string, string>\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(after).filter(([name, value]) => before[name] !== value)\n );\n}\n\n/** Names under `dependencies` and `devDependencies` of a package.json text. */\nfunction dependencyNames(text: string | undefined): Set<string> {\n if (text === undefined) return new Set();\n try {\n const manifest = JSON.parse(text) as Record<string, unknown>;\n const names = (field: unknown) =>\n field && typeof field === 'object' && !Array.isArray(field) ? Object.keys(field) : [];\n return new Set([...names(manifest.dependencies), ...names(manifest.devDependencies)]);\n } catch {\n return new Set();\n }\n}\n\n/**\n * Whether the addition changes what the project depends on, in either\n * direction: the lockfile and the installed tree need an install either way.\n */\nexport function changesDependencies(plan: AddPlan): boolean {\n return (\n Object.keys(plan.dependencies).length > 0 ||\n Object.keys(plan.devDependencies).length > 0 ||\n plan.removedDependencies.length > 0\n );\n}\n\n/** Keys of package.json the scaffolder owns: they always take the generated value. */\nconst OWNED_MANIFEST_KEYS = new Set([MANIFEST_KEY]);\n\n/** Maps whose keys are kept sorted, the way package managers write them. */\nconst SORTED_MANIFEST_MAPS = ['dependencies', 'devDependencies', 'optionalDependencies'];\n\nfunction sortManifest(manifest: unknown): unknown {\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) return manifest;\n const record = manifest as Record<string, unknown>;\n for (const key of SORTED_MANIFEST_MAPS) {\n const map = record[key];\n if (typeof map === 'object' && map !== null && !Array.isArray(map)) {\n record[key] = Object.fromEntries(Object.entries(map).sort(([a], [b]) => a.localeCompare(b)));\n }\n }\n return record;\n}\n\nfunction withoutOwned(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;\n return Object.fromEntries(Object.entries(value).filter(([key]) => !OWNED_MANIFEST_KEYS.has(key)));\n}\n\ntype Decision =\n | { kind: 'none' }\n | { kind: 'change'; change: Omit<FileChange, 'diff'> }\n | { kind: 'conflict'; reason: string }\n | { kind: 'note'; message: string; withDiff?: boolean };\n\ninterface FileInputs {\n path: string;\n base: string | undefined;\n theirs: string | undefined;\n ours: string | undefined;\n /** Whether the file on disk is exactly what the scaffolder wrote. */\n pristine: boolean;\n}\n\nfunction textDecision({ path, base, theirs, ours, pristine }: FileInputs): Decision {\n if (theirs === undefined) {\n if (ours === undefined) return { kind: 'none' };\n if (pristine) return { kind: 'change', change: { path, kind: 'delete', source: 'generated' } };\n return { kind: 'note', message: 'no longer generated, kept because you edited it' };\n }\n if (ours === theirs) return { kind: 'none' };\n if (ours === undefined) {\n if (base === undefined) {\n return {\n kind: 'change',\n change: { path, kind: 'create', content: theirs, source: 'generated' },\n };\n }\n return { kind: 'conflict', reason: 'you deleted it, and the addition changes it' };\n }\n if (base === undefined) {\n return { kind: 'conflict', reason: 'a file of yours is in the way of a new generated file' };\n }\n if (pristine) {\n return {\n kind: 'change',\n change: { path, kind: 'update', content: theirs, source: 'generated' },\n };\n }\n return { kind: 'conflict', reason: 'you edited it, and the addition changes it' };\n}\n\nfunction structuredDecision(inputs: FileInputs): Decision | undefined {\n const { path, base, theirs, ours } = inputs;\n const format = structuredFormat(path);\n if (!format || base === undefined || theirs === undefined || ours === undefined) return undefined;\n const parsed = [base, ours, theirs].map((text) => parseStructured(format, text));\n if (parsed.some((value) => value === undefined)) return undefined;\n const [baseValue, oursValue, theirsValue] = parsed;\n\n const manifest = path === 'package.json';\n const outcome = manifest\n ? merge3(withoutOwned(baseValue), withoutOwned(oursValue), withoutOwned(theirsValue))\n : merge3(baseValue, oursValue, theirsValue);\n if (outcome.conflicts.length > 0) {\n return {\n kind: 'conflict',\n reason: `you changed ${outcome.conflicts.map(formatPath).join(', ')}, and the addition changes it differently`,\n };\n }\n const ops: MergeOp[] = [...outcome.ops];\n if (manifest && typeof theirsValue === 'object' && theirsValue !== null) {\n for (const key of OWNED_MANIFEST_KEYS) {\n const value: unknown = (theirsValue as Record<string, unknown>)[key];\n const current: unknown =\n typeof oursValue === 'object' && oursValue !== null\n ? (oursValue as Record<string, unknown>)[key]\n : undefined;\n if (!deepEqual(value, current)) ops.push({ kind: 'set', path: [key], value });\n }\n }\n if (ops.length === 0) return { kind: 'none' };\n\n let content: string;\n if (format === 'json') {\n const merged = applyOps(oursValue, ops);\n content = JSON.stringify(manifest ? sortManifest(merged) : merged, null, 2) + '\\n';\n } else {\n const doc = parseDocument(ours);\n applyYamlOps(doc, ops);\n content = doc.toString();\n }\n if (content === ours) return { kind: 'none' };\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\n/** The managed block of AGENTS.md, from its begin marker through its end marker. */\nfunction agentRules(text: string): { start: number; end: number } | undefined {\n const start = text.indexOf(AGENT_RULES_BEGIN);\n const endMarker = text.indexOf(AGENT_RULES_END, start);\n if (start === -1 || endMarker === -1) return undefined;\n return { start, end: endMarker + AGENT_RULES_END.length };\n}\n\nfunction agentsMdDecision(inputs: FileInputs): Decision {\n const { path, theirs, ours } = inputs;\n if (ours === undefined || theirs === undefined) return textDecision(inputs);\n const mine = agentRules(ours);\n const generated = agentRules(theirs);\n if (!mine || !generated) {\n return {\n kind: 'note',\n message: `the ${AGENT_RULES_BEGIN} block is gone, so the rules for coding agents were not updated`,\n withDiff: true,\n };\n }\n const content =\n ours.slice(0, mine.start) + theirs.slice(generated.start, generated.end) + ours.slice(mine.end);\n if (content === ours) return { kind: 'none' };\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\nfunction lines(text: string | undefined): string[] {\n return (text ?? '').split('\\n').filter((line) => line.trim() !== '');\n}\n\nfunction gitignoreDecision(inputs: FileInputs): Decision {\n const { path, base, theirs, ours } = inputs;\n if (ours === undefined || theirs === undefined) return textDecision(inputs);\n const present = new Set(lines(ours).map((line) => line.trim()));\n const before = new Set(lines(base).map((line) => line.trim()));\n const added = lines(theirs).filter(\n (line) => !before.has(line.trim()) && !present.has(line.trim())\n );\n if (added.length === 0) return { kind: 'none' };\n const content = `${ours.replace(/\\n*$/, '\\n')}${added.join('\\n')}\\n`;\n return { kind: 'change', change: { path, kind: 'update', content, source: 'merged' } };\n}\n\n/** README.md is the user's to rewrite: an edited one is left alone with a note instead of a conflict. */\nfunction readmeDecision(inputs: FileInputs): Decision {\n const decision = textDecision(inputs);\n if (decision.kind !== 'conflict') return decision;\n return {\n kind: 'note',\n message: 'has your edits and was left as it is, the generated change is not applied',\n withDiff: true,\n };\n}\n\nfunction decide(inputs: FileInputs): Decision {\n if (inputs.pristine) return textDecision(inputs);\n if (inputs.path === 'AGENTS.md') return agentsMdDecision(inputs);\n if (inputs.path === '.gitignore') return gitignoreDecision(inputs);\n if (inputs.path === 'README.md') return readmeDecision(inputs);\n return structuredDecision(inputs) ?? textDecision(inputs);\n}\n\nfunction readText(directory: string, path: string): string | undefined {\n const full = join(directory, path);\n return existsSync(full) ? readFileSync(full, 'utf-8') : undefined;\n}\n\nfunction fileMap(plan: ProjectPlan): Map<string, string> {\n return new Map(\n plan.files.filter((file) => file.mode === undefined).map((file) => [file.path, file.content])\n );\n}\n\n/**\n * What adding `changes` to the project in `directory` would do, without\n * writing anything. The project's spec is read from package.json, both the\n * project as it is and as it would be are planned, and what the addition\n * changes between them is merged into the files on disk. A file the user\n * edited takes the change when it can be merged key by key (package.json,\n * cogitator.yml, docker-compose.yml, the managed block of AGENTS.md,\n * .gitignore), and is a conflict otherwise.\n */\nexport function planAdd(directory: string, changes: AddChanges): AddPlan {\n const root = resolve(directory);\n const project = readProject(root);\n const from = project.spec;\n const to = withChanges(from, changes);\n const options = { packageManagerSpec: project.packageManagerSpec };\n const before = planProject(from, options);\n const after = planProject(to, options);\n\n const notes: AddNote[] = [];\n const version = scaffolderVersion();\n if (project.generator && project.generator !== `create-cogitator-app@${version}`) {\n notes.push({\n message: `The project was created by ${project.generator}, the added files come from create-cogitator-app@${version}`,\n });\n }\n const lock: ScaffoldLock | undefined = readLock(root);\n if (!lock) {\n notes.push({\n message:\n 'There is no .cogitator/scaffold.json, so every existing file the addition changes counts as edited by you',\n });\n }\n\n const upToDate = deepEqual(from, to);\n const changesOut: FileChange[] = [];\n const conflicts: AddConflict[] = [];\n if (!upToDate) {\n const baseFiles = fileMap(before);\n const theirFiles = fileMap(after);\n const paths = [...new Set([...baseFiles.keys(), ...theirFiles.keys()])].sort();\n for (const path of paths) {\n const base = baseFiles.get(path);\n const theirs = theirFiles.get(path);\n if (base === theirs) continue;\n const ours = readText(root, path);\n const locked = lock?.files[path];\n const pristine =\n ours !== undefined &&\n (ours === base || (locked !== undefined && hashContent(ours) === locked));\n const decision = decide({ path, base, theirs, ours, pristine });\n if (decision.kind === 'change') {\n changesOut.push({\n ...decision.change,\n diff: unifiedDiff(path, ours, decision.change.content),\n });\n } else if (decision.kind === 'conflict') {\n conflicts.push({ path, reason: decision.reason, diff: unifiedDiff(path, base, theirs) });\n } else if (decision.kind === 'note') {\n notes.push({\n path,\n message: decision.message,\n ...(decision.withDiff && { diff: unifiedDiff(path, base, theirs) }),\n });\n }\n }\n }\n\n const manifest = changesOut.find((change) => change.path === 'package.json');\n const remaining = dependencyNames(manifest?.content);\n const removedDependencies = manifest\n ? [...dependencyNames(readText(root, 'package.json'))]\n .filter((name) => !remaining.has(name))\n .sort()\n : [];\n const knownEnv = new Set(before.env.map((variable) => variable.name));\n return {\n directory: root,\n from,\n to,\n summary: describeChanges(from, to),\n changes: changesOut,\n conflicts,\n notes,\n dependencies: changedEntries(before.dependencies, after.dependencies),\n devDependencies: changedEntries(before.devDependencies, after.devDependencies),\n removedDependencies,\n env: after.env.filter((variable) => !knownEnv.has(variable.name)),\n services: after.services.filter((service) => !before.services.includes(service)),\n warnings: after.warnings.filter((warning) => !before.warnings.includes(warning)),\n command: after.command,\n upToDate,\n };\n}\n\n/** Extensions Biome formats in a generated project. */\nconst FORMATTED = /\\.(?:[cm]?[jt]sx?|json|css)$/;\n\n/**\n * Adds `changes` to the project in `directory`: plans the addition, refuses\n * with an `AddConflictError` when it would overwrite the user's edits, then\n * writes the files, installs new dependencies, formats what it wrote and\n * records the new spec and file hashes. Adding what the project already has\n * changes nothing.\n */\nexport async function addToProject(\n directory: string,\n changes: AddChanges,\n options: AddOptions = {}\n): Promise<AddResult> {\n const log = options.log ?? silentLogger;\n const plan = planAdd(directory, changes);\n const skipped = (reason: string): StepResult => ({ status: 'skipped', reason });\n if (plan.upToDate) {\n return {\n plan,\n written: [],\n deleted: [],\n install: skipped('nothing was added'),\n format: skipped('nothing was added'),\n };\n }\n if (plan.conflicts.length > 0) throw new AddConflictError(plan.conflicts);\n\n log.start('Updating project files');\n const written: string[] = [];\n const deleted: string[] = [];\n for (const change of plan.changes) {\n const target = join(plan.directory, change.path);\n if (change.kind === 'delete') {\n await rm(target, { force: true });\n deleted.push(change.path);\n } else {\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, change.content ?? '');\n written.push(change.path);\n }\n }\n log.done(`Updated ${written.length + deleted.length} files`);\n\n const dependenciesChanged = changesDependencies(plan);\n let install = dependenciesChanged\n ? skipped('install was turned off')\n : skipped('the dependencies did not change');\n if (dependenciesChanged && options.install !== false) {\n log.start(`Installing the dependencies with ${plan.to.packageManager}`);\n install = await installDependencies(\n plan.directory,\n plan.to.packageManager,\n options.inheritOutput ?? false\n );\n if (install.status === 'done') log.done('Installed the dependencies');\n else log.fail('Could not install the dependencies');\n }\n\n const format = await formatProject(\n plan.directory,\n written.filter((path) => FORMATTED.test(path))\n );\n if (format.status === 'failed') log.warn(format.error.message);\n\n await updateLock(plan.directory, [...written, ...deleted]);\n return { plan, written, deleted, install, format };\n}\n","/** Lines of context around each change in a unified diff. */\nconst CONTEXT = 3;\n\n/** Above this many line pairs the diff falls back to one hunk that replaces the whole file. */\nconst MAX_CELLS = 4_000_000;\n\ntype Edit = { op: ' ' | '-' | '+'; line: string };\n\nfunction splitLines(text: string): string[] {\n if (text === '') return [];\n const lines = text.split('\\n');\n if (lines.at(-1) === '') lines.pop();\n return lines;\n}\n\n/** The shortest edit script from `a` to `b`, by the longest common subsequence. */\nfunction editScript(a: readonly string[], b: readonly string[]): Edit[] {\n let start = 0;\n while (start < a.length && start < b.length && a[start] === b[start]) start++;\n let endA = a.length;\n let endB = b.length;\n while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {\n endA--;\n endB--;\n }\n const head: Edit[] = a.slice(0, start).map((line) => ({ op: ' ', line }));\n const tail: Edit[] = a.slice(endA).map((line) => ({ op: ' ', line }));\n const midA = a.slice(start, endA);\n const midB = b.slice(start, endB);\n\n if (midA.length * midB.length > MAX_CELLS) {\n return [\n ...head,\n ...midA.map((line): Edit => ({ op: '-', line })),\n ...midB.map((line): Edit => ({ op: '+', line })),\n ...tail,\n ];\n }\n\n const width = midB.length + 1;\n const lcs = new Uint32Array((midA.length + 1) * width);\n for (let i = midA.length - 1; i >= 0; i--) {\n for (let j = midB.length - 1; j >= 0; j--) {\n lcs[i * width + j] =\n midA[i] === midB[j]\n ? lcs[(i + 1) * width + j + 1] + 1\n : Math.max(lcs[(i + 1) * width + j], lcs[i * width + j + 1]);\n }\n }\n\n const middle: Edit[] = [];\n let i = 0;\n let j = 0;\n while (i < midA.length || j < midB.length) {\n if (i < midA.length && j < midB.length && midA[i] === midB[j]) {\n middle.push({ op: ' ', line: midA[i] });\n i++;\n j++;\n } else if (\n i < midA.length &&\n (j === midB.length || lcs[(i + 1) * width + j] >= lcs[i * width + j + 1])\n ) {\n middle.push({ op: '-', line: midA[i] });\n i++;\n } else {\n middle.push({ op: '+', line: midB[j] });\n j++;\n }\n }\n return [...head, ...middle, ...tail];\n}\n\n/**\n * A unified diff from `before` to `after`, as `git diff` prints it, or an\n * empty string when they are equal. A missing side is `undefined`: the file\n * is created or deleted.\n */\nexport function unifiedDiff(\n path: string,\n before: string | undefined,\n after: string | undefined\n): string {\n if (before === after) return '';\n const a = splitLines(before ?? '');\n const b = splitLines(after ?? '');\n const edits = editScript(a, b);\n\n const changed = edits.flatMap((edit, index) => (edit.op === ' ' ? [] : [index]));\n if (changed.length === 0) return '';\n\n const ranges: Array<[number, number]> = [];\n for (const index of changed) {\n const from = Math.max(0, index - CONTEXT);\n const to = Math.min(edits.length, index + CONTEXT + 1);\n const last = ranges.at(-1);\n if (last && from <= last[1]) last[1] = Math.max(last[1], to);\n else ranges.push([from, to]);\n }\n\n const out = [\n `--- ${before === undefined ? '/dev/null' : `a/${path}`}`,\n `+++ ${after === undefined ? '/dev/null' : `b/${path}`}`,\n ];\n let lineA = 1;\n let lineB = 1;\n let cursor = 0;\n for (const [from, to] of ranges) {\n for (; cursor < from; cursor++) {\n if (edits[cursor].op !== '+') lineA++;\n if (edits[cursor].op !== '-') lineB++;\n }\n const hunk = edits.slice(from, to);\n const countA = hunk.filter((edit) => edit.op !== '+').length;\n const countB = hunk.filter((edit) => edit.op !== '-').length;\n out.push(\n `@@ -${countA === 0 ? lineA - 1 : lineA},${countA} +${countB === 0 ? lineB - 1 : lineB},${countB} @@`\n );\n for (const edit of hunk) out.push(`${edit.op}${edit.line}`);\n for (; cursor < to; cursor++) {\n if (edits[cursor].op !== '+') lineA++;\n if (edits[cursor].op !== '-') lineB++;\n }\n }\n return out.join('\\n') + '\\n';\n}\n","import { isMap, parseDocument, type Document, type Pair, type Scalar } from 'yaml';\n\nexport type MergePath = ReadonlyArray<string | number>;\n\n/** One change a three-way merge applies to the user's copy. */\nexport type MergeOp =\n { kind: 'set'; path: MergePath; value: unknown } | { kind: 'delete'; path: MergePath };\n\nexport interface MergeOutcome {\n ops: MergeOp[];\n /** Paths the generator and the user changed in different ways. */\n conflicts: MergePath[];\n}\n\ntype PlainObject = Record<string, unknown>;\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPrimitiveList(value: unknown): value is Array<string | number | boolean> {\n return (\n Array.isArray(value) &&\n value.every((item) => ['string', 'number', 'boolean'].includes(typeof item))\n );\n}\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const keys = Object.keys(a);\n return (\n keys.length === Object.keys(b).length &&\n keys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]))\n );\n }\n return false;\n}\n\n/**\n * Merges what the generator changed (`base` to `theirs`) into the user's copy\n * (`ours`), the way `git merge` treats a file, but key by key. A key the\n * generator did not change keeps the user's value, a key the user did not\n * change takes the generator's. Lists of plain values merge as sets, so a\n * dependency or a secret added on both sides is kept once. Anything else both\n * sides changed differently is a conflict.\n */\nexport function merge3(\n base: unknown,\n ours: unknown,\n theirs: unknown,\n path: MergePath = []\n): MergeOutcome {\n if (deepEqual(base, theirs) || deepEqual(ours, theirs)) return { ops: [], conflicts: [] };\n\n if ((base === undefined || isPlainObject(base)) && isPlainObject(ours) && isPlainObject(theirs)) {\n const from = base ?? {};\n const outcome: MergeOutcome = { ops: [], conflicts: [] };\n for (const key of new Set([...Object.keys(from), ...Object.keys(theirs)])) {\n const child = merge3(from[key], ours[key], theirs[key], [...path, key]);\n outcome.ops.push(...child.ops);\n outcome.conflicts.push(...child.conflicts);\n }\n return outcome;\n }\n\n if (deepEqual(ours, base)) {\n return {\n ops: [theirs === undefined ? { kind: 'delete', path } : { kind: 'set', path, value: theirs }],\n conflicts: [],\n };\n }\n\n if (\n (base === undefined || isPrimitiveList(base)) &&\n isPrimitiveList(ours) &&\n isPrimitiveList(theirs)\n ) {\n const from = base ?? [];\n const removed = from.filter((item) => !theirs.includes(item));\n const added = theirs.filter((item) => !from.includes(item) && !ours.includes(item));\n const merged = [...ours.filter((item) => !removed.includes(item)), ...added];\n return {\n ops: deepEqual(merged, ours) ? [] : [{ kind: 'set', path, value: merged }],\n conflicts: [],\n };\n }\n\n return { ops: [], conflicts: [path] };\n}\n\n/** `value` with `ops` applied, leaving `value` itself untouched. */\nexport function applyOps(value: unknown, ops: readonly MergeOp[]): unknown {\n let root: unknown = structuredClone(value);\n for (const op of ops) {\n if (op.path.length === 0) {\n root = op.kind === 'set' ? structuredClone(op.value) : undefined;\n continue;\n }\n let node: unknown = root;\n for (const key of op.path.slice(0, -1)) {\n if (!isPlainObject(node)) throw new Error(`Cannot merge into ${formatPath(op.path)}`);\n if (!isPlainObject(node[key])) node[key] = {};\n node = node[key];\n }\n if (!isPlainObject(node)) throw new Error(`Cannot merge into ${formatPath(op.path)}`);\n const last = String(op.path.at(-1));\n if (op.kind === 'set') node[last] = structuredClone(op.value);\n else delete node[last];\n }\n return root;\n}\n\nexport function formatPath(path: MergePath): string {\n return path.length === 0 ? '(the whole file)' : path.join('.');\n}\n\n/**\n * Applies `ops` to a YAML document in place, keeping the user's comments,\n * layout and key order. A new top-level section gets a blank line before it,\n * like the generator writes them.\n */\nexport function applyYamlOps(doc: Document, ops: readonly MergeOp[]): void {\n for (const op of ops) {\n if (op.kind === 'delete') {\n doc.deleteIn(op.path);\n continue;\n }\n const [first] = op.path;\n const contents = doc.contents;\n if (op.path.length === 1 && isMap(contents) && !contents.has(first)) {\n const pair = doc.createPair(first, op.value) as Pair<Scalar, unknown>;\n pair.key.spaceBefore = contents.items.length > 0;\n contents.items.push(pair);\n } else {\n doc.setIn(op.path, doc.createNode(op.value));\n }\n }\n}\n\nexport type StructuredFormat = 'json' | 'yaml';\n\nexport function structuredFormat(path: string): StructuredFormat | undefined {\n if (path.endsWith('.json')) return 'json';\n if (path.endsWith('.yml') || path.endsWith('.yaml')) return 'yaml';\n return undefined;\n}\n\n/** Parses a JSON or YAML file, or `undefined` when it does not parse. */\nexport function parseStructured(format: StructuredFormat, text: string): unknown {\n try {\n if (format === 'json') return JSON.parse(text) as unknown;\n const doc = parseDocument(text);\n return doc.errors.length > 0 ? undefined : (doc.toJS() as unknown);\n } catch {\n return undefined;\n }\n}\n","function distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let previous = row[0];\n row[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const current = row[j];\n row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));\n previous = current;\n }\n }\n return row[b.length];\n}\n\n/** The candidate closest to `input`, when it is close enough to be a typo of it. */\nexport function closest(input: string, candidates: readonly string[]): string | undefined {\n let best: string | undefined;\n let bestDistance = Infinity;\n for (const candidate of candidates) {\n const d = distance(input.toLowerCase(), candidate.toLowerCase());\n if (d < bestDistance) {\n best = candidate;\n bestDistance = d;\n }\n }\n return best !== undefined && bestDistance <= Math.max(2, Math.floor(input.length / 3))\n ? best\n : undefined;\n}\n","import { pnpmWorkspaceYaml } from './emit.js';\nimport { CodedError } from './errors.js';\nimport type { GeneratedFile } from './project.js';\nimport type { PackageManager } from './spec.js';\nimport { closest } from './suggest.js';\nimport { BUN_ENGINES, NODE_ENGINES, VERSIONS } from './versions.js';\n\n/** An example of the Cogitator repo, as `--example` turns it into a project. Indexed at build time. */\nexport interface ExampleEntry {\n /** `core/basic-agent`: the category and the file name without its number. */\n name: string;\n title: string;\n /** The runnable file, relative to `examples/`. */\n entry: string;\n /** Every file the project needs, relative to `examples/`. */\n files: string[];\n dependencies: Record<string, string>;\n devDependencies: Record<string, string>;\n /** Environment variables the files read. */\n env: string[];\n /** What runs the example: Node through tsx, or Bun for examples that use its APIs. */\n runtime: 'node' | 'bun';\n}\n\ndeclare const __COGITATOR_EXAMPLES__: ExampleEntry[] | undefined;\n\nexport const EXAMPLES_REPO = { owner: 'cogitator-ai', repo: 'Cogitator-AI' } as const;\n\n/** The examples indexed when the scaffolder was built, from the `examples/` it is released with. */\nexport function examples(): ExampleEntry[] {\n return typeof __COGITATOR_EXAMPLES__ === 'undefined' ? [] : __COGITATOR_EXAMPLES__;\n}\n\n/** The git tag the examples of a scaffolder version are fetched from. */\nexport function exampleRef(version: string): string {\n return `create-cogitator-app@${version}`;\n}\n\n/** `name#ref` as `--example` takes it. */\nexport function parseExampleArgument(value: string): { query: string; ref?: string } {\n const at = value.indexOf('#');\n if (at === -1) return { query: value.trim() };\n const ref = value.slice(at + 1).trim();\n return { query: value.slice(0, at).trim(), ...(ref && { ref }) };\n}\n\n/**\n * The example `query` names: `core/basic-agent`, its file `core/01-basic-agent`\n * or `core/01-basic-agent.ts`, or just `basic-agent` when only one category\n * has it. Throws with the closest names otherwise.\n */\nexport function findExample(\n query: string,\n index: readonly ExampleEntry[] = examples()\n): ExampleEntry {\n const normalized = query.replace(/^examples\\//, '').replace(/\\.ts$/, '');\n const exact = index.find(\n (example) => example.name === normalized || example.entry.replace(/\\.ts$/, '') === normalized\n );\n if (exact) return exact;\n const short = index.filter((example) => example.name.split('/')[1] === normalized);\n if (short.length === 1) return short[0];\n if (short.length > 1) {\n throw new CodedError(\n 'AMBIGUOUS_EXAMPLE',\n `\"${query}\" is in more than one category: ${short.map((example) => example.name).join(', ')}`\n );\n }\n const names = index.map((example) => example.name);\n const match = closest(normalized, [...names, ...names.map((name) => name.split('/')[1])]);\n const suggestion = match\n ? ` Did you mean \"${names.find((name) => name.endsWith(match)) ?? match}\"?`\n : '';\n throw new CodedError(\n 'UNKNOWN_EXAMPLE',\n `There is no example \"${query}\".${suggestion} Run with --list-examples to see them all.`\n );\n}\n\n/** Where the raw content of `examples/<path>` is at `ref`. */\nexport function exampleFileUrl(ref: string, path: string): string {\n const encodedRef = ref.split('/').map(encodeURIComponent).join('/').replace(/%40/g, '@');\n return `https://raw.githubusercontent.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/${encodedRef}/examples/${path}`;\n}\n\n/** Descriptions of the variables the examples read; anything else is described generically. */\nconst KNOWN_ENV: Record<string, { description: string; example?: string }> = {\n GOOGLE_API_KEY: {\n description:\n 'Google AI Studio key, the default provider of the examples (free tier at https://aistudio.google.com/apikey)',\n },\n OPENAI_API_KEY: { description: 'OpenAI API key, from https://platform.openai.com/api-keys' },\n ANTHROPIC_API_KEY: {\n description: 'Anthropic API key, from https://console.anthropic.com/settings/keys',\n },\n OLLAMA_URL: { description: 'Where Ollama listens', example: 'http://localhost:11434' },\n REDIS_URL: { description: 'Redis connection URL', example: 'redis://localhost:6379' },\n DATABASE_URL: {\n description: 'Postgres connection URL',\n example: 'postgresql://cogitator:cogitator@localhost:5432/cogitator',\n },\n TG_TOKEN: { description: 'Telegram bot token, from @BotFather' },\n OWNER_TG_ID: { description: 'Your Telegram user id, the owner of the bot' },\n WEBCHAT_TOKEN: { description: 'Token WebChat clients authenticate with' },\n WEBCHAT_PORT: { description: 'Port of the WebChat server', example: '8080' },\n OPENROUTER_API_KEY: {\n description:\n 'OpenRouter API key, for decision models and models of every provider (https://openrouter.ai/keys)',\n },\n BLUESKY_HANDLE: {\n description: 'Bluesky handle of the bot account',\n example: 'yourbot.bsky.social',\n },\n BLUESKY_APP_PASSWORD: {\n description: 'Bluesky app password (Settings, Privacy and security, App passwords)',\n },\n THREADS_ACCESS_TOKEN: { description: 'Threads long-lived access token, renewed automatically' },\n PUBLISH: { description: 'Set to 1 to publish for real instead of a dry run', example: '0' },\n DEEPGRAM_API_KEY: { description: 'Deepgram API key for speech to text' },\n ELEVENLABS_API_KEY: { description: 'ElevenLabs API key for text to speech' },\n};\n\n/** Packages that compile native code on install, which pnpm and Bun run only when allowed. */\nconst NATIVE_BUILDS = new Set([\n 'better-sqlite3',\n 'esbuild',\n 'protobufjs',\n 'sharp',\n 'onnxruntime-node',\n]);\n\nexport interface ExamplePlanOptions {\n name: string;\n packageManager: PackageManager;\n version: string;\n ref: string;\n /** Values for `.env`. */\n secrets?: Record<string, string>;\n}\n\nexport interface ExamplePlan {\n example: ExampleEntry;\n ref: string;\n /** Files generated around the example. */\n files: GeneratedFile[];\n /** The example's own files, fetched from GitHub, relative to `examples/`. */\n remoteFiles: string[];\n command: string;\n scripts: Record<string, string>;\n}\n\n/** Where an example file lands in the project: `src/` keeps the layout its relative imports expect. */\nexport function exampleTarget(path: string): string {\n return `src/${path}`;\n}\n\nfunction sorted(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));\n}\n\n/** The project around an example: package.json, tsconfig, .env.example, README and the rest. */\nexport function planExample(example: ExampleEntry, options: ExamplePlanOptions): ExamplePlan {\n const { name, packageManager: pm, version, ref } = options;\n const bun = example.runtime === 'bun';\n const entry = exampleTarget(example.entry);\n const scripts: Record<string, string> = bun\n ? { start: `bun ${entry}`, dev: `bun --watch ${entry}`, typecheck: 'tsc --noEmit' }\n : {\n start: `tsx --env-file-if-exists=.env ${entry}`,\n dev: `tsx watch --env-file-if-exists=.env ${entry}`,\n typecheck: 'tsc --noEmit',\n };\n const devDependencies = sorted({\n ...example.devDependencies,\n typescript: VERSIONS.typescript,\n ...(bun ? { '@types/bun': VERSIONS.typesBun } : { '@types/node': VERSIONS.typesNode }),\n });\n if (bun) delete devDependencies.tsx;\n const command = `npx create-cogitator-app@${version} ${name} --example ${example.name}${ref === exampleRef(version) ? '' : `#${ref}`}`;\n const native = [\n ...new Set([...Object.keys(example.dependencies), ...Object.keys(devDependencies), 'esbuild']),\n ]\n .filter((dep) => NATIVE_BUILDS.has(dep))\n .sort();\n\n const manifest = {\n name,\n version: '0.1.0',\n private: true,\n type: 'module',\n engines: bun ? { bun: BUN_ENGINES } : { node: NODE_ENGINES },\n scripts,\n dependencies: sorted(example.dependencies),\n devDependencies,\n ...(pm === 'bun' && { trustedDependencies: native }),\n cogitator: {\n generator: `create-cogitator-app@${version}`,\n example: { name: example.name, ref },\n command,\n },\n };\n\n const env = example.env.map((variable) => ({\n name: variable,\n ...(KNOWN_ENV[variable] ?? { description: 'Read by the example' }),\n }));\n const envExample = `${[\n '# Copy to .env and fill in what the example needs.',\n '',\n ...env.flatMap((variable) => [\n `# ${variable.description}`,\n `${variable.name}=${variable.example ?? ''}`,\n '',\n ]),\n ]\n .join('\\n')\n .trimEnd()}\\n`;\n\n const run = pm === 'npm' ? 'npm run' : pm;\n const readme = [\n `# ${example.title}`,\n '',\n `The \\`${example.name}\\` example of [Cogitator](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}), as its own project. Its code is \\`${entry}\\`, from [\\`examples/${example.entry}\\`](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/blob/${ref}/examples/${example.entry}) at \\`${ref}\\`.`,\n '',\n '## Run it',\n '',\n '```bash',\n ...(env.length > 0 ? ['cp .env.example .env # then fill in the keys', ''] : []),\n `${run} start`,\n '```',\n '',\n `\\`${run} dev\\` reruns it on change, \\`${run} typecheck\\` checks the types.`,\n ...(env.length > 0\n ? [\n '',\n '## Environment',\n '',\n ...env.map((variable) => `- \\`${variable.name}\\`: ${variable.description}`),\n ]\n : []),\n '',\n '## Learn more',\n '',\n '- [Cogitator docs](https://cogitator.app/docs)',\n `- [All examples](https://github.com/${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}/tree/${ref}/examples)`,\n '',\n ].join('\\n');\n\n const tsconfig = {\n compilerOptions: {\n target: 'ES2023',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n skipLibCheck: true,\n noEmit: true,\n types: [bun ? 'bun' : 'node'],\n },\n include: ['src'],\n };\n\n const secrets = Object.entries(options.secrets ?? {}).filter(([, value]) => value !== '');\n const files: GeneratedFile[] = [\n { path: 'package.json', content: JSON.stringify(manifest, null, 2) + '\\n' },\n { path: 'tsconfig.json', content: JSON.stringify(tsconfig, null, 2) + '\\n' },\n { path: 'README.md', content: readme },\n {\n path: '.gitignore',\n content: ['node_modules/', 'dist/', '.env', '*.log', '.DS_Store', ''].join('\\n'),\n },\n ...(env.length > 0 ? [{ path: '.env.example', content: envExample }] : []),\n ...(secrets.length > 0\n ? [\n {\n path: '.env',\n content: secrets.map(([key, value]) => `${key}=${value}`).join('\\n') + '\\n',\n mode: 0o600,\n },\n ]\n : []),\n ...(pm === 'pnpm'\n ? [\n {\n path: 'pnpm-workspace.yaml',\n content: pnpmWorkspaceYaml(native),\n },\n ]\n : []),\n ];\n\n return { example, ref, files, remoteFiles: example.files, command, scripts };\n}\n\n/** Fetches the example's own files from GitHub at the plan's ref. */\nexport async function fetchExampleFiles(\n plan: ExamplePlan,\n fetchImpl: typeof fetch = fetch\n): Promise<GeneratedFile[]> {\n return Promise.all(\n plan.remoteFiles.map(async (path) => {\n const url = exampleFileUrl(plan.ref, path);\n const response = await fetchImpl(url, { signal: AbortSignal.timeout(30_000) });\n if (response.status === 404) {\n throw new CodedError(\n 'HTTP_404',\n `examples/${path} is not at ${plan.ref} of ${EXAMPLES_REPO.owner}/${EXAMPLES_REPO.repo}. Pass --example ${plan.example.name}#main for the main branch.`\n );\n }\n if (!response.ok) {\n throw new CodedError(\n `HTTP_${response.status}`,\n `Could not download ${url}: HTTP ${response.status}`\n );\n }\n return { path: exampleTarget(path), content: await response.text() };\n })\n );\n}\n","import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { x as extract } from 'tar';\nimport { CodedError } from './errors.js';\nimport { LOCKFILES } from './package-manager.js';\nimport { PACKAGE_MANAGERS, type PackageManager } from './spec.js';\nimport { cogitatorVersion, type CogitatorPackage } from './versions.js';\n\n/** A template fetched from a GitHub repository instead of generated: `github:owner/repo[/path][#ref]`. */\nexport interface RemoteTemplate {\n owner: string;\n repo: string;\n path?: string;\n ref?: string;\n}\n\nexport function describeTemplate(template: RemoteTemplate): string {\n return `github:${template.owner}/${template.repo}${template.path ? `/${template.path}` : ''}${template.ref ? `#${template.ref}` : ''}`;\n}\n\n/** Above this a download is refused: a template is source, not a dataset. */\nconst MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;\n\n/**\n * Where the archive of `template` is. With a token it goes through the GitHub\n * API, which serves private repositories; without one through codeload.\n */\nexport function templateArchive(\n template: RemoteTemplate,\n token?: string\n): { url: string; headers: Record<string, string> } {\n const ref = template.ref ?? '';\n if (token) {\n return {\n url: `https://api.github.com/repos/${template.owner}/${template.repo}/tarball/${encodeURIComponent(ref)}`,\n headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json' },\n };\n }\n return {\n url: `https://codeload.github.com/${template.owner}/${template.repo}/tar.gz/${encodeURIComponent(ref || 'HEAD')}`,\n headers: {},\n };\n}\n\nexport interface DownloadResult {\n /** Files written, relative to the directory. */\n files: string[];\n /** Entries left out: links and special files, which a template has no business shipping. */\n skipped: string[];\n}\n\n/**\n * Downloads `template` and extracts it, or its `path` inside the repository,\n * into `directory`. Only regular files and directories are written, none\n * outside `directory`.\n */\nexport async function downloadTemplate(\n template: RemoteTemplate,\n directory: string,\n options: { fetch?: typeof fetch; token?: string } = {}\n): Promise<DownloadResult> {\n const { url, headers } = templateArchive(template, options.token);\n const response = await (options.fetch ?? fetch)(url, {\n headers,\n signal: AbortSignal.timeout(120_000),\n });\n if (response.status === 404) {\n throw new CodedError(\n 'HTTP_404',\n `${describeTemplate(template)} was not found: check the repository and the ref${options.token ? '' : ', and set GITHUB_TOKEN for a private repository'}`\n );\n }\n if (!response.ok) {\n throw new CodedError(\n `HTTP_${response.status}`,\n `Could not download ${describeTemplate(template)}: HTTP ${response.status}`\n );\n }\n const length = Number(response.headers.get('content-length') ?? 0);\n if (length > MAX_ARCHIVE_BYTES) {\n throw new CodedError(\n 'TEMPLATE_TOO_LARGE',\n `${describeTemplate(template)} is larger than ${MAX_ARCHIVE_BYTES / 1024 / 1024} MB`\n );\n }\n const archive = Buffer.from(await response.arrayBuffer());\n if (archive.length > MAX_ARCHIVE_BYTES) {\n throw new CodedError(\n 'TEMPLATE_TOO_LARGE',\n `${describeTemplate(template)} is larger than ${MAX_ARCHIVE_BYTES / 1024 / 1024} MB`\n );\n }\n\n const prefix = template.path ? template.path.split('/').filter(Boolean) : [];\n const files: string[] = [];\n const skipped: string[] = [];\n await mkdir(directory, { recursive: true });\n await pipeline(\n Readable.from(archive),\n extract({\n cwd: directory,\n strip: 1 + prefix.length,\n filter: (path, entry) => {\n const inside = path.split('/').slice(1);\n if (!prefix.every((segment, i) => inside[i] === segment)) return false;\n const relative = inside.slice(prefix.length).join('/');\n if (!relative) return false;\n const type = 'type' in entry ? entry.type : entry.isDirectory() ? 'Directory' : 'File';\n if (type === 'File' || type === 'OldFile' || type === 'ContiguousFile') {\n files.push(relative);\n return true;\n }\n if (type === 'Directory') return true;\n skipped.push(relative);\n return false;\n },\n })\n );\n if (files.length === 0) {\n throw new CodedError(\n 'TEMPLATE_EMPTY',\n template.path\n ? `${describeTemplate(template)} has no files under ${template.path}`\n : `${describeTemplate(template)} is empty`\n );\n }\n return { files: files.sort(), skipped: skipped.sort() };\n}\n\nexport interface PreparedTemplate {\n /** The package manager its lockfile belongs to, when it has one. */\n packageManager?: PackageManager;\n /** Dependencies rewritten from `workspace:` to published versions. */\n rewritten: string[];\n}\n\n/**\n * Makes an extracted template a project of its own: package.json gets the\n * project's name, and `workspace:` ranges of `@cogitator-ai/*` packages, which\n * templates from a monorepo carry, become the versions released with the\n * scaffolder. Other workspace and catalog ranges cannot be resolved outside\n * their monorepo and are refused.\n */\nexport function prepareTemplate(directory: string, options: { name: string }): PreparedTemplate {\n const lockfile = PACKAGE_MANAGERS.find((pm) => existsSync(join(directory, LOCKFILES[pm])));\n const manifestPath = join(directory, 'package.json');\n if (!existsSync(manifestPath)) {\n throw new CodedError(\n 'TEMPLATE_NO_MANIFEST',\n `The template has no package.json at its root (it has ${readdirSync(directory).slice(0, 8).join(', ')}): point --template at the project directory`\n );\n }\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<string, unknown>;\n manifest.name = options.name;\n const rewritten: string[] = [];\n const unresolvable: string[] = [];\n for (const field of [\n 'dependencies',\n 'devDependencies',\n 'optionalDependencies',\n 'peerDependencies',\n ]) {\n const deps = manifest[field];\n if (typeof deps !== 'object' || deps === null) continue;\n const record = deps as Record<string, unknown>;\n for (const [name, range] of Object.entries(record)) {\n if (typeof range !== 'string') continue;\n if (range.startsWith('workspace:') && name.startsWith('@cogitator-ai/')) {\n record[name] = cogitatorVersion(name as CogitatorPackage);\n rewritten.push(name);\n } else if (range.startsWith('workspace:') || range.startsWith('catalog:')) {\n unresolvable.push(`${name}@${range}`);\n }\n }\n }\n if (unresolvable.length > 0) {\n throw new CodedError(\n 'TEMPLATE_WORKSPACE_DEPENDENCIES',\n `The template depends on packages of its own monorepo, which cannot be installed outside it: ${unresolvable.join(', ')}`\n );\n }\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n');\n return { ...(lockfile && { packageManager: lockfile }), rewritten };\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, readdir, rm } from 'node:fs/promises';\nimport { join, relative, resolve } from 'node:path';\nimport {\n exampleRef,\n fetchExampleFiles,\n findExample,\n parseExampleArgument,\n planExample,\n type ExamplePlan,\n} from './examples.js';\nimport { installCommand, runScript } from './package-manager.js';\nimport {\n describeTemplate,\n downloadTemplate,\n prepareTemplate,\n type DownloadResult,\n type PreparedTemplate,\n type RemoteTemplate,\n} from './remote.js';\nimport {\n assertEmptyDirectory,\n initGit,\n installDependencies,\n silentLogger,\n writeFiles,\n type ScaffoldLogger,\n type StepResult,\n} from './scaffold.js';\nimport type { PackageManager } from './spec.js';\nimport type { NextStep } from './project.js';\nimport { scaffolderVersion } from './versions.js';\n\nexport interface StarterOptions {\n directory: string;\n name: string;\n packageManager: PackageManager;\n install?: boolean;\n git?: boolean;\n log?: ScaffoldLogger;\n inheritOutput?: boolean;\n fetch?: typeof fetch;\n}\n\n/** A project made from an example or a remote template instead of the generator. */\nexport interface StarterResult {\n directory: string;\n /** Where it came from: `example core/basic-agent at create-cogitator-app@0.4.0` or `github:owner/repo`. */\n source: string;\n files: string[];\n packageManager: PackageManager;\n install: StepResult;\n git: StepResult;\n /** Commands to the first run. */\n nextSteps: NextStep[];\n notes: string[];\n}\n\nasync function finish(\n directory: string,\n packageManager: PackageManager,\n options: StarterOptions\n): Promise<Pick<StarterResult, 'install' | 'git'>> {\n const log = options.log ?? silentLogger;\n let install: StepResult = { status: 'skipped', reason: 'install was turned off' };\n if (options.install !== false) {\n log.start(`Installing dependencies with ${packageManager}`);\n install = await installDependencies(directory, packageManager, options.inheritOutput ?? false);\n if (install.status === 'done') log.done('Installed dependencies');\n else\n log.fail(`Could not install dependencies, run \"${installCommand(packageManager)}\" yourself`);\n }\n let git: StepResult = { status: 'skipped', reason: 'git was turned off' };\n if (options.git !== false) {\n git = await initGit(directory);\n if (git.status === 'done') log.done('Created a git repository with the first commit');\n else if (git.status === 'failed') log.fail(git.error.message);\n }\n return { install, git };\n}\n\nfunction stepsFor(\n directory: string,\n packageManager: PackageManager,\n scripts: Record<string, string>,\n installed: boolean,\n needsEnv: boolean\n): NextStep[] {\n const where = relative(process.cwd(), directory);\n const steps: NextStep[] = where\n ? [{ command: `cd ${/^[\\w./-]+$/.test(where) ? where : JSON.stringify(where)}` }]\n : [];\n if (!installed) steps.push({ command: installCommand(packageManager) });\n if (needsEnv) steps.push({ command: 'cp .env.example .env', note: 'then fill in the keys' });\n const run = ['dev', 'start'].find((script) => scripts[script]);\n if (run) steps.push({ command: runScript(packageManager, run) });\n return steps;\n}\n\n/** The project `--example` describes, before anything is fetched or written. */\nexport function resolveExample(\n argument: string,\n options: Pick<StarterOptions, 'name' | 'packageManager'> & { secrets?: Record<string, string> }\n): ExamplePlan {\n const { query, ref } = parseExampleArgument(argument);\n const version = scaffolderVersion();\n return planExample(findExample(query), {\n name: options.name,\n packageManager: options.packageManager,\n version,\n ref: ref ?? exampleRef(version),\n secrets: options.secrets,\n });\n}\n\n/**\n * Creates a project from an example of the Cogitator repo: its files at the\n * tag of this scaffolder version (or the ref after `#`), with a package.json,\n * tsconfig, .env.example and README around them.\n */\nexport async function createFromExample(\n plan: ExamplePlan,\n options: StarterOptions\n): Promise<StarterResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n assertEmptyDirectory(directory);\n\n log.start(`Downloading the ${plan.example.name} example from ${plan.ref}`);\n const fetched = await fetchExampleFiles(plan, options.fetch);\n await mkdir(directory, { recursive: true });\n const files = [...plan.files, ...fetched];\n await writeFiles(directory, files);\n log.done(`Wrote ${files.length} files`);\n\n const { install, git } = await finish(directory, options.packageManager, options);\n return {\n directory,\n source: `example ${plan.example.name} at ${plan.ref}`,\n files: files.map((file) => file.path).sort(),\n packageManager: options.packageManager,\n install,\n git,\n nextSteps: stepsFor(\n directory,\n options.packageManager,\n plan.scripts,\n install.status === 'done',\n plan.example.env.length > 0\n ),\n notes: [],\n };\n}\n\n/**\n * Creates a project from a GitHub repository or a directory of one. The\n * repository's lockfile decides the package manager when it has one.\n * Nothing is left behind when the download fails.\n */\nexport async function createFromTemplate(\n template: RemoteTemplate,\n options: StarterOptions & { token?: string }\n): Promise<StarterResult> {\n const log = options.log ?? silentLogger;\n const directory = resolve(options.directory);\n assertEmptyDirectory(directory);\n const existed = existsSync(directory);\n\n log.start(`Downloading ${describeTemplate(template)}`);\n let downloaded: DownloadResult;\n let prepared: PreparedTemplate;\n try {\n downloaded = await downloadTemplate(template, directory, {\n fetch: options.fetch,\n token: options.token,\n });\n prepared = prepareTemplate(directory, { name: options.name });\n } catch (error) {\n log.fail(`Could not use ${describeTemplate(template)}`);\n if (existed) {\n for (const entry of await readdir(directory)) {\n await rm(join(directory, entry), { recursive: true, force: true });\n }\n } else {\n await rm(directory, { recursive: true, force: true });\n }\n throw error;\n }\n log.done(`Wrote ${downloaded.files.length} files`);\n\n const packageManager = prepared.packageManager ?? options.packageManager;\n const notes = [\n ...(prepared.packageManager && prepared.packageManager !== options.packageManager\n ? [\n `The template has a ${prepared.packageManager} lockfile, so it uses ${prepared.packageManager}`,\n ]\n : []),\n ...(prepared.rewritten.length > 0\n ? [\n `Pinned ${prepared.rewritten.join(', ')} to the versions released with create-cogitator-app@${scaffolderVersion()}`,\n ]\n : []),\n ...(downloaded.skipped.length > 0\n ? [`Left out links and special files: ${downloaded.skipped.join(', ')}`]\n : []),\n ];\n const { install, git } = await finish(directory, packageManager, options);\n const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return {\n directory,\n source: describeTemplate(template),\n files: downloaded.files,\n packageManager,\n install,\n git,\n nextSteps: stepsFor(\n directory,\n packageManager,\n manifest.scripts ?? {},\n install.status === 'done',\n existsSync(join(directory, '.env.example'))\n ),\n notes,\n };\n}\n","import type {\n AppKind,\n ChannelKind,\n CodingAgent,\n DeployTarget,\n FeatureId,\n MemoryKind,\n ServerFramework,\n VectorStore,\n} from './spec.js';\n\nexport interface Choice<T extends string> {\n value: T;\n label: string;\n hint: string;\n}\n\nexport const APP_CHOICES: Choice<AppKind>[] = [\n { value: 'script', label: 'Script', hint: 'an agent you run from the terminal' },\n { value: 'server', label: 'HTTP server', hint: 'agents behind a REST, SSE and WebSocket API' },\n { value: 'next', label: 'Next.js app', hint: 'a streaming chat UI with server-side agents' },\n {\n value: 'channels',\n label: 'Messaging bot',\n hint: 'Telegram, Discord, Slack, WebChat, Bluesky or Threads',\n },\n { value: 'worker', label: 'Queue worker', hint: 'agents run as BullMQ jobs on Redis' },\n];\n\nexport const SERVER_CHOICES: Choice<ServerFramework>[] = [\n { value: 'hono', label: 'Hono', hint: 'small and fast, runs on Node' },\n { value: 'express', label: 'Express', hint: 'the classic, with Swagger UI' },\n { value: 'fastify', label: 'Fastify', hint: 'schema-first and fast' },\n { value: 'koa', label: 'Koa', hint: 'minimal middleware stack' },\n { value: 'tetsu', label: 'Tetsu', hint: 'Bun-native controller with OpenAPI, needs Bun' },\n];\n\nexport const MEMORY_CHOICES: Choice<MemoryKind>[] = [\n { value: 'sqlite', label: 'SQLite', hint: 'a local file, no setup' },\n { value: 'memory', label: 'In-memory', hint: 'forgotten on restart' },\n { value: 'postgres', label: 'Postgres', hint: 'with pgvector, runs in Docker' },\n { value: 'redis', label: 'Redis', hint: 'runs in Docker' },\n { value: 'mongodb', label: 'MongoDB', hint: 'runs in Docker' },\n { value: 'none', label: 'None', hint: 'every run starts from scratch' },\n];\n\nexport const VECTOR_STORE_CHOICES: Choice<VectorStore>[] = [\n { value: 'memory', label: 'In-memory', hint: 're-indexed on start' },\n { value: 'postgres', label: 'Postgres pgvector', hint: 'runs in Docker' },\n { value: 'qdrant', label: 'Qdrant', hint: 'runs in Docker' },\n];\n\nexport const FEATURE_CHOICES: Choice<FeatureId>[] = [\n {\n value: 'harness',\n label: 'Assistant harness',\n hint: 'workspace file tools, approvals, core facts, scheduler',\n },\n { value: 'mcp', label: 'MCP', hint: 'tools from MCP servers, agents served over MCP' },\n { value: 'rag', label: 'RAG', hint: 'answers grounded in your docs/ folder' },\n { value: 'workflows', label: 'Workflows', hint: 'a multi-step DAG pipeline' },\n {\n value: 'durable',\n label: 'Durable workflows',\n hint: 'sagas, approvals, recovery after a crash',\n },\n { value: 'swarms', label: 'Swarms', hint: 'a team of agents with a supervisor' },\n { value: 'evals', label: 'Evals', hint: 'a dataset, metrics and `pnpm eval`' },\n { value: 'otel', label: 'OpenTelemetry', hint: 'traces to any OTLP collector' },\n { value: 'langfuse', label: 'Langfuse', hint: 'traces and costs in Langfuse' },\n { value: 'voice', label: 'Realtime voice', hint: 'a WebSocket voice agent' },\n { value: 'sandbox', label: 'Sandbox', hint: 'run code in Docker or WASM isolation' },\n { value: 'a2a', label: 'A2A', hint: 'expose agents over the Agent-to-Agent protocol' },\n];\n\nexport const DEPLOY_CHOICES: Choice<DeployTarget>[] = [\n { value: 'docker', label: 'Docker', hint: 'a production Dockerfile and compose file' },\n { value: 'fly', label: 'Fly.io', hint: 'Dockerfile and fly.toml' },\n { value: 'none', label: 'None', hint: 'decide later with `cogitator deploy`' },\n];\n\nexport const CHANNEL_CHOICES: Choice<ChannelKind>[] = [\n { value: 'webchat', label: 'WebChat', hint: 'a local WebSocket chat, no setup' },\n { value: 'telegram', label: 'Telegram', hint: 'needs a bot token from @BotFather' },\n { value: 'discord', label: 'Discord', hint: 'needs a bot token' },\n { value: 'slack', label: 'Slack', hint: 'needs a bot token and signing secret' },\n { value: 'bluesky', label: 'Bluesky', hint: 'mentions, replies and DMs; needs an app password' },\n { value: 'threads', label: 'Threads', hint: 'replies and mentions; needs a long-lived token' },\n];\n\nexport const CODING_AGENT_CHOICES: Choice<CodingAgent>[] = [\n { value: 'claude', label: 'Claude Code', hint: '.mcp.json and a skill in .claude/skills' },\n { value: 'cursor', label: 'Cursor', hint: '.cursor/mcp.json and a skill in .cursor/skills' },\n { value: 'codex', label: 'Codex', hint: '.codex/config.toml and a skill in .agents/skills' },\n];\n\nexport function choiceLabel<T extends string>(choices: readonly Choice<T>[], value: T): string {\n return choices.find((choice) => choice.value === value)?.label ?? value;\n}\n","import { BUILTIN_MODELS, ModelRegistry, type ModelInfo } from '@cogitator-ai/models';\nimport { listOllamaModels, hasOllamaModel, resolveOllamaUrl } from './ollama.js';\nimport { OLLAMA_SUGGESTED_MODELS, defaultModel } from './providers.js';\nimport type { LLMProvider } from './spec.js';\n\nexport interface ModelChoice {\n /** The model id without the provider prefix. */\n value: string;\n label: string;\n hint?: string;\n}\n\n/** Where the choices came from: the live catalogue, the built-in list, the local Ollama, or a fallback. */\nexport type ModelSource = 'catalog' | 'builtin' | 'ollama' | 'suggested';\n\nexport interface ModelChoices {\n choices: ModelChoice[];\n source: ModelSource;\n}\n\n/** How many models of a cloud provider to offer; the rest are reachable by typing an id. */\nconst MAX_CHOICES = 8;\nconst CATALOG_TIMEOUT_MS = 4_000;\n\nfunction formatPrice(perMillion: number): string {\n return perMillion >= 1\n ? `$${perMillion.toFixed(perMillion % 1 === 0 ? 0 : 2)}`\n : `$${perMillion.toFixed(3).replace(/0+$/, '')}`;\n}\n\nfunction formatContext(tokens: number): string {\n if (tokens >= 1_000_000) return `${+(tokens / 1_000_000).toFixed(1)}M`;\n return `${Math.round(tokens / 1_000)}k`;\n}\n\n/** `$2 in / $10 out per 1M tokens, 1M context`, the line a model choice shows. */\nexport function describeModel(model: Pick<ModelInfo, 'pricing' | 'contextWindow'>): string {\n const { input, output } = model.pricing;\n return `${formatPrice(input)} in / ${formatPrice(output)} out per 1M tokens, ${formatContext(model.contextWindow)} context`;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n timer.unref();\n });\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * The current models of a cloud provider: its built-in lineup from\n * `@cogitator-ai/models`, with prices and context windows refreshed from the\n * live catalogue when it answers in time. The provider's default comes first.\n */\nexport async function cloudModelChoices(\n provider: Exclude<LLMProvider, 'ollama'>,\n options: { timeoutMs?: number; registry?: Pick<ModelRegistry, 'initialize' | 'getModel'> } = {}\n): Promise<ModelChoices> {\n const registry =\n options.registry ?? new ModelRegistry({ cache: { ttl: 24 * 60 * 60 * 1000, storage: 'file' } });\n const loaded = await withTimeout(\n registry.initialize().then(\n () => true,\n () => false\n ),\n options.timeoutMs ?? CATALOG_TIMEOUT_MS\n );\n\n const lineup = BUILTIN_MODELS.filter(\n (model) =>\n model.provider === provider &&\n !model.deprecated &&\n model.capabilities?.supportsTools !== false\n );\n const preferred = defaultModel(provider);\n lineup.sort((a, b) => Number(b.id === preferred) - Number(a.id === preferred));\n\n const choices = lineup.slice(0, MAX_CHOICES).map((builtin) => {\n const model = (loaded && registry.getModel(`${provider}/${builtin.id}`)) || builtin;\n return {\n value: builtin.id,\n label: builtin.displayName,\n hint: `${builtin.id === preferred ? 'recommended, ' : ''}${describeModel(model)}`,\n };\n });\n return { choices, source: loaded ? 'catalog' : 'builtin' };\n}\n\nfunction formatSize(bytes: number): string | undefined {\n return bytes > 0 ? `${(bytes / 1e9).toFixed(1)} GB` : undefined;\n}\n\n/**\n * The models of the local Ollama, with the recommended one first and marked as\n * installed or not. When Ollama does not answer, a list of small models with\n * reliable tool calling to pull.\n */\nexport async function ollamaModelChoices(\n baseUrl: string = resolveOllamaUrl()\n): Promise<ModelChoices> {\n const recommended = defaultModel('ollama');\n const installed = await listOllamaModels(baseUrl);\n if (!installed) {\n return {\n source: 'suggested',\n choices: OLLAMA_SUGGESTED_MODELS.map((name) => ({\n value: name,\n label: name,\n hint: name === recommended ? 'recommended, Ollama is not running' : 'not installed',\n })),\n };\n }\n const others = installed.filter((model) => !hasOllamaModel([model], recommended));\n return {\n source: 'ollama',\n choices: [\n {\n value: recommended,\n label: recommended,\n hint: hasOllamaModel(installed, recommended)\n ? 'recommended, installed'\n : 'recommended, not installed yet',\n },\n ...others.map((model) => ({\n value: model.name,\n label: model.name,\n hint: formatSize(model.size),\n })),\n ],\n };\n}\n\nexport function modelChoices(provider: LLMProvider): Promise<ModelChoices> {\n return provider === 'ollama' ? ollamaModelChoices() : cloudModelChoices(provider);\n}\n","import { DEFAULT_OLLAMA_URL } from './providers.js';\n\nexport interface OllamaModel {\n name: string;\n size: number;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** `value` without the slashes it ends with, in linear time, unlike `replace(/\\/+$/, '')`. */\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === '/') end--;\n return value.slice(0, end);\n}\n\n/**\n * The Ollama server the generated code talks to: `OLLAMA_BASE_URL`, which it\n * reads, then `OLLAMA_HOST`, which the Ollama CLI reads, then the local default.\n */\nexport function resolveOllamaUrl(env: Record<string, string | undefined> = process.env): string {\n const raw = env.OLLAMA_BASE_URL?.trim() || env.OLLAMA_HOST?.trim();\n if (!raw) return DEFAULT_OLLAMA_URL;\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `http://${raw}`;\n return trimTrailingSlashes(withScheme);\n}\n\n/** The models installed in the Ollama at `baseUrl`, or `undefined` when it does not answer. */\nexport async function listOllamaModels(\n baseUrl: string,\n timeoutMs = 2000\n): Promise<OllamaModel[] | undefined> {\n try {\n const res = await fetch(`${baseUrl}/api/tags`, { signal: AbortSignal.timeout(timeoutMs) });\n if (!res.ok) return undefined;\n const data: unknown = await res.json();\n if (!isRecord(data) || !Array.isArray(data.models)) return undefined;\n return data.models.flatMap((model: unknown) =>\n isRecord(model) && typeof model.name === 'string'\n ? [{ name: model.name, size: typeof model.size === 'number' ? model.size : 0 }]\n : []\n );\n } catch {\n return undefined;\n }\n}\n\nfunction withTag(name: string): string {\n return name.includes(':') ? name : `${name}:latest`;\n}\n\n/** Whether `model` is among `installed`, treating a name without a tag as `:latest` like Ollama does. */\nexport function hasOllamaModel(installed: readonly OllamaModel[], model: string): boolean {\n const wanted = withTag(model);\n return installed.some((m) => withTag(m.name) === wanted);\n}\n\nfunction describeProgress(event: Record<string, unknown>, status: string): string {\n const { completed, total } = event;\n if (typeof completed === 'number' && typeof total === 'number' && total > 0) {\n return `${status} ${Math.floor((completed / total) * 100)}%`;\n }\n return status;\n}\n\nasync function* ndjson(stream: ReadableStream<Uint8Array>): AsyncGenerator<unknown> {\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let newline = buffer.indexOf('\\n');\n while (newline >= 0) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n if (line) yield JSON.parse(line) as unknown;\n newline = buffer.indexOf('\\n');\n }\n }\n const rest = (buffer + decoder.decode()).trim();\n if (rest) yield JSON.parse(rest) as unknown;\n } finally {\n reader.releaseLock();\n }\n}\n\n/** Pulls `model` into the Ollama at `baseUrl`, reporting each status line; throws when the pull fails. */\nexport async function pullOllamaModel(\n baseUrl: string,\n model: string,\n onStatus: (status: string) => void\n): Promise<void> {\n const res = await fetch(`${baseUrl}/api/pull`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ model, stream: true }),\n });\n if (!res.ok || !res.body) {\n const detail = await res.text().catch(() => '');\n throw new Error(`Failed to pull ${model}: HTTP ${res.status}${detail ? ` ${detail}` : ''}`);\n }\n\n let succeeded = false;\n for await (const event of ndjson(res.body)) {\n if (!isRecord(event)) continue;\n if (typeof event.error === 'string') throw new Error(`Failed to pull ${model}: ${event.error}`);\n if (typeof event.status !== 'string') continue;\n if (event.status === 'success') succeeded = true;\n onStatus(describeProgress(event, event.status));\n }\n\n if (!succeeded) {\n throw new Error(`Failed to pull ${model}: the download stopped before it finished`);\n }\n}\n","import type { LLMProvider } from './spec.js';\n\n/** What checking an API key found out. The key itself never appears in it. */\nexport type KeyCheck =\n | { status: 'valid' }\n | { status: 'rate-limited' }\n | { status: 'invalid'; httpStatus: number }\n | { status: 'unreachable'; reason: string }\n | { status: 'unexpected'; httpStatus: number };\n\ninterface KeyProbe {\n url: string;\n headers(key: string): Record<string, string>;\n}\n\n/**\n * The cheapest authenticated call of each provider: listing models costs no\n * tokens, and the key travels in a header, never in the URL.\n */\nconst PROBES: Record<Exclude<LLMProvider, 'ollama'>, KeyProbe> = {\n openai: {\n url: 'https://api.openai.com/v1/models',\n headers: (key) => ({ authorization: `Bearer ${key}` }),\n },\n anthropic: {\n url: 'https://api.anthropic.com/v1/models?limit=1',\n headers: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),\n },\n google: {\n url: 'https://generativelanguage.googleapis.com/v1beta/models?pageSize=1',\n headers: (key) => ({ 'x-goog-api-key': key }),\n },\n};\n\n/** Checks that `key` is accepted by `provider`, within `timeoutMs`. */\nexport async function checkApiKey(\n provider: Exclude<LLMProvider, 'ollama'>,\n key: string,\n options: { timeoutMs?: number; fetch?: typeof fetch } = {}\n): Promise<KeyCheck> {\n const probe = PROBES[provider];\n const request = options.fetch ?? fetch;\n let response: Response;\n try {\n response = await request(probe.url, {\n headers: probe.headers(key),\n signal: AbortSignal.timeout(options.timeoutMs ?? 8_000),\n });\n } catch (error) {\n const reason =\n error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')\n ? 'the request timed out'\n : 'the provider could not be reached';\n return { status: 'unreachable', reason };\n }\n await response.body?.cancel().catch(() => undefined);\n\n if (response.ok) return { status: 'valid' };\n if (response.status === 401 || response.status === 403) {\n return { status: 'invalid', httpStatus: response.status };\n }\n if (response.status === 429) return { status: 'rate-limited' };\n return { status: 'unexpected', httpStatus: response.status };\n}\n\n/** One line for the user about a key check. */\nexport function describeKeyCheck(envKey: string, check: KeyCheck): string {\n switch (check.status) {\n case 'valid':\n return `${envKey} works`;\n case 'rate-limited':\n return `${envKey} is accepted, but the provider is rate limiting it right now`;\n case 'invalid':\n return `${envKey} was rejected (HTTP ${check.httpStatus}): check the key in .env`;\n case 'unreachable':\n return `Could not check ${envKey}: ${check.reason}`;\n case 'unexpected':\n return `Could not check ${envKey}: the provider answered HTTP ${check.httpStatus}`;\n }\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { z } from 'zod';\nimport { constantCase } from './errors.js';\nimport type { StepResult } from './scaffold.js';\nimport type { ProjectSpec } from './spec.js';\nimport { scaffolderVersion } from './versions.js';\n\ndeclare const __TELEMETRY_WEBSITE_ID__: string | undefined;\n\n/** Where the events go: the Umami instance of the Cogitator project. */\nexport const TELEMETRY_HOST = 'https://analytics.el1fe.com';\nexport const TELEMETRY_DOCS = 'https://cogitator.app/docs/getting-started/telemetry';\nconst SEND_TIMEOUT_MS = 1500;\n\n/**\n * The Umami website the events are counted under, set when the scaffolder is\n * built for a release (`COGITATOR_UMAMI_WEBSITE_ID`). A build without it sends\n * nothing.\n */\nexport function telemetryWebsiteId(): string {\n return typeof __TELEMETRY_WEBSITE_ID__ === 'undefined' ? '' : __TELEMETRY_WEBSITE_ID__;\n}\n\n/**\n * Everything one event carries, and nothing else: no project name, path,\n * model, key or anything a user typed.\n */\nexport interface TelemetryPayload {\n version: string;\n /** The preset, `custom` for a stack picked by hand, `example` or `template` for copied projects. */\n preset: string;\n provider: string;\n memory: string;\n /** The add-ons, comma-separated in catalog order. */\n features: string;\n packageManager: string;\n /** The major version of Node, such as `24`. */\n node: string;\n /** `darwin`, `linux` or `win32`. */\n os: string;\n outcome: 'success' | 'failure';\n /** Where a failure stopped, `none` on success. */\n failedStep: FailedStep | 'none';\n /**\n * Why it stopped, as a code such as `ERR_PNPM_NO_MATCHING_VERSION`,\n * `ENOTFOUND` or `HTTP_404` (see `telemetryErrorCode`), `none` on success.\n */\n errorCode: string;\n}\n\n/**\n * Where a scaffold failed: `create` while making the project (its options,\n * the directory, writing or downloading files), `install` while installing\n * its dependencies.\n */\nexport type FailedStep = 'create' | 'install';\n\n/** A failed scaffold: the step it stopped at and the error it stopped with. */\nexport interface ScaffoldFailure {\n step: FailedStep;\n error: unknown;\n}\n\nexport const PAYLOAD_FIELDS: ReadonlyArray<keyof TelemetryPayload> = [\n 'version',\n 'preset',\n 'provider',\n 'memory',\n 'features',\n 'packageManager',\n 'node',\n 'os',\n 'outcome',\n 'failedStep',\n 'errorCode',\n];\n\nconst VALUE = z.string().regex(/^[\\w.,-]{0,100}$/);\n\n/**\n * An event exactly: the fields above and no other, each a short value of\n * letters, digits and `._,-`. `sendTelemetry` is exported, so anything can be\n * handed to it, and only what passes this is ever sent.\n */\nconst PAYLOAD_SCHEMA: z.ZodType<TelemetryPayload> = z.strictObject({\n version: VALUE,\n preset: VALUE,\n provider: VALUE,\n memory: VALUE,\n features: VALUE,\n packageManager: VALUE,\n node: VALUE,\n os: VALUE,\n outcome: z.enum(['success', 'failure']),\n failedStep: z.enum(['none', 'create', 'install']),\n errorCode: VALUE,\n});\n\nconst SAFE_CODE = /^[A-Z][A-Z0-9_]{1,63}$/;\n\n/**\n * A code for why `error` happened that is safe to send: the `code` of the\n * error or of one of its causes (Node's `ENOTFOUND`, a package manager's\n * `ERR_PNPM_NO_MATCHING_VERSION`, the scaffolder's own `HTTP_404` or\n * `DIRECTORY_NOT_EMPTY`), else the kind of error (`TYPE_ERROR`), else\n * `UNKNOWN`. Never the message, which can hold paths and names.\n */\nexport function telemetryErrorCode(error: unknown): string {\n let kind: string | undefined;\n let current = error;\n for (let depth = 0; depth < 5 && typeof current === 'object' && current !== null; depth++) {\n if ('code' in current && typeof current.code === 'string' && SAFE_CODE.test(current.code))\n return current.code;\n if (\n !kind &&\n current instanceof Error &&\n current.name !== 'Error' &&\n /^[A-Za-z]+$/.test(current.name)\n )\n kind = constantCase(current.name);\n current = 'cause' in current ? current.cause : undefined;\n }\n return kind ?? 'UNKNOWN';\n}\n\n/** The failure of a scaffold whose install step failed, `undefined` when it did not. */\nexport function installFailure(result: { install: StepResult }): ScaffoldFailure | undefined {\n return result.install.status === 'failed'\n ? { step: 'install', error: result.install.error }\n : undefined;\n}\n\n/** The event of a scaffold of `spec`: failed with `failure`, successful without one. */\nexport function payloadFor(\n spec:\n Pick<ProjectSpec, 'preset' | 'provider' | 'memory' | 'features' | 'packageManager'> | undefined,\n failure?: ScaffoldFailure,\n kind: 'generated' | 'example' | 'template' = 'generated'\n): TelemetryPayload {\n return {\n version: scaffolderVersion(),\n preset: kind !== 'generated' ? kind : (spec?.preset ?? 'custom'),\n provider: spec?.provider ?? 'none',\n memory: spec?.memory ?? 'none',\n features: spec?.features.join(',') ?? '',\n packageManager: spec?.packageManager ?? 'unknown',\n node: process.versions.node.split('.')[0],\n os: process.platform,\n outcome: failure ? 'failure' : 'success',\n failedStep: failure?.step ?? 'none',\n errorCode: failure ? telemetryErrorCode(failure.error) : 'none',\n };\n}\n\n/** Why no event is sent, or `undefined` when one is. */\nexport function telemetryDisabledReason(options: {\n flag?: boolean;\n dryRun?: boolean;\n env?: NodeJS.ProcessEnv;\n websiteId?: string;\n}): string | undefined {\n const env = options.env ?? process.env;\n const on = (value: string | undefined) => {\n const normalized = value?.trim().toLowerCase();\n return (\n normalized !== undefined && normalized !== '' && normalized !== '0' && normalized !== 'false'\n );\n };\n if (options.flag === false) return '--no-telemetry';\n if (on(env.COGITATOR_TELEMETRY_DISABLED)) return 'COGITATOR_TELEMETRY_DISABLED';\n if (on(env.DO_NOT_TRACK)) return 'DO_NOT_TRACK';\n if (on(env.CI)) return 'CI';\n if (options.dryRun) return '--dry-run';\n if (!(options.websiteId ?? telemetryWebsiteId())) return 'this build has no telemetry configured';\n return undefined;\n}\n\nfunction configDir(env: NodeJS.ProcessEnv): string {\n if (process.platform === 'win32' && env.APPDATA) return join(env.APPDATA, 'cogitator');\n return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'cogitator');\n}\n\n/**\n * The one line about telemetry shown the first time it is on, or `undefined`\n * when it was shown before. Showing it is remembered in the user's config\n * directory.\n */\nexport function firstRunNotice(env: NodeJS.ProcessEnv = process.env): string | undefined {\n const marker = join(configDir(env), 'telemetry-notice');\n if (existsSync(marker)) return undefined;\n try {\n mkdirSync(configDir(env), { recursive: true });\n writeFileSync(marker, `${new Date().toISOString()}\\n`);\n } catch {\n return undefined;\n }\n return `Cogitator sends one anonymous event per scaffolded project (version, preset, provider, memory, add-ons, package manager, Node major, OS, and where and why it failed if it did). Turn it off with --no-telemetry or COGITATOR_TELEMETRY_DISABLED=1: ${TELEMETRY_DOCS}`;\n}\n\n/** How browsers name each platform, which is what Umami reads the OS from. */\nconst UA_PLATFORMS: Record<string, string> = {\n darwin: 'Macintosh; Intel Mac OS X 10_15_7',\n linux: 'X11; Linux x86_64',\n win32: 'Windows NT 10.0; Win64; x64',\n};\n\n/**\n * The User-Agent of an event. Umami silently drops requests its bot filter\n * (`isbot`) recognizes, and a `Node/` token is one of them, so the Node version\n * travels in the payload only.\n */\nexport function telemetryUserAgent(payload: Pick<TelemetryPayload, 'os' | 'version'>): string {\n return `Mozilla/5.0 (${UA_PLATFORMS[payload.os] ?? payload.os}) create-cogitator-app/${payload.version}`;\n}\n\n/**\n * Sends the event to Umami. It never throws and never takes longer than its\n * timeout: a slow or failing network changes nothing for the scaffolder. A\n * payload that is not exactly an event (another field, a value with a path or\n * a space in it) sends nothing.\n */\nexport async function sendTelemetry(\n payload: TelemetryPayload,\n options: { fetch?: typeof fetch; websiteId?: string; host?: string; timeoutMs?: number } = {}\n): Promise<boolean> {\n const website = options.websiteId ?? telemetryWebsiteId();\n if (!website) return false;\n const parsed = PAYLOAD_SCHEMA.safeParse(payload);\n if (!parsed.success) return false;\n const data = parsed.data;\n const body = {\n type: 'event',\n payload: {\n website,\n hostname: 'create-cogitator-app',\n url: `/scaffold/${data.preset}`,\n name: 'scaffold',\n data,\n },\n };\n try {\n const response = await (options.fetch ?? fetch)(`${options.host ?? TELEMETRY_HOST}/api/send`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'user-agent': telemetryUserAgent(data),\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? SEND_TIMEOUT_MS),\n });\n return response.ok;\n } catch {\n return false;\n }\n}\n","import { relative } from 'node:path';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { IncompatibleSpecError } from '../kit/compat.js';\nimport { checkApiKey, describeKeyCheck } from '../kit/key-check.js';\nimport {\n hasOllamaModel,\n listOllamaModels,\n pullOllamaModel,\n resolveOllamaUrl,\n} from '../kit/ollama.js';\nimport {\n detectPackageManager,\n detectPackageManagerSpec,\n runScript,\n} from '../kit/package-manager.js';\nimport { planProject, type ProjectPlan } from '../kit/plan.js';\nimport { PRESETS } from '../kit/presets.js';\nimport { providerInfo } from '../kit/providers.js';\nimport {\n scaffold,\n type ScaffoldLogger,\n type ScaffoldResult,\n type StepResult,\n} from '../kit/scaffold.js';\nimport { bareModel, parseSpec, type ProjectSpec } from '../kit/spec.js';\nimport {\n firstRunNotice,\n installFailure,\n payloadFor,\n sendTelemetry,\n telemetryDisabledReason,\n type TelemetryPayload,\n} from '../kit/telemetry.js';\nimport { scaffolderVersion } from '../kit/versions.js';\nimport { DOCS_URL } from '../kit/guide.js';\nimport { examples, exampleTarget } from '../kit/examples.js';\nimport { describeTemplate } from '../kit/remote.js';\nimport {\n createFromExample,\n createFromTemplate,\n resolveExample,\n type StarterResult,\n} from '../kit/starter.js';\nimport { CliError, isInteractive, parseCliArgs, type CliArgs } from './args.js';\nimport { exampleList, helpText, presetList } from './help.js';\nimport { askDirectory, askMissing, CancelledError } from './interactive.js';\nimport { DEFAULT_DIRECTORY, resolveDirectory, specFromArgs } from './resolve.js';\n\ninterface Io {\n stdout: (text: string) => void;\n stderr: (text: string) => void;\n}\n\nconst defaultIo: Io = {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n};\n\nfunction banner(version: string): string {\n return `\\n ${pc.bold(pc.cyan('create-cogitator-app'))} ${pc.dim(`v${version}`)} ${pc.dim('Build AI agents in minutes')}\\n`;\n}\n\nfunction clackLogger(): ScaffoldLogger {\n const spinner = p.spinner();\n return {\n start: (message) => spinner.start(message),\n done: (message) => spinner.stop(message),\n fail: (message) => spinner.error(message),\n warn: (message) => p.log.warn(message),\n };\n}\n\nfunction stepJson(step: StepResult): Record<string, string> {\n if (step.status === 'failed') return { status: 'failed', error: step.error.message };\n if (step.status === 'skipped') return { status: 'skipped', reason: step.reason };\n return { status: 'done' };\n}\n\nfunction planJson(plan: ProjectPlan, directory: string) {\n return {\n directory,\n spec: plan.spec,\n command: plan.command,\n files: plan.files.map((file) => file.path),\n dependencies: plan.dependencies,\n devDependencies: plan.devDependencies,\n scripts: plan.scripts,\n services: plan.services,\n env: plan.env.map(({ name, required, secret, description }) => ({\n name,\n required,\n secret,\n description,\n })),\n warnings: plan.warnings,\n };\n}\n\nfunction fileTree(paths: readonly string[]): string {\n return paths\n .map(\n (path) =>\n ` ${pc.dim(path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '')}${path.slice(path.lastIndexOf('/') + 1)}`\n )\n .join('\\n');\n}\n\nfunction describeDryRun(plan: ProjectPlan, directory: string): string {\n const deps = Object.entries(plan.dependencies).map(\n ([name, range]) => ` ${name} ${pc.dim(range)}`\n );\n const devDeps = Object.entries(plan.devDependencies).map(\n ([name, range]) => ` ${name} ${pc.dim(range)}`\n );\n return [\n `${pc.bold('Dry run:')} nothing was written. ${directory} would get:`,\n '',\n pc.bold(`Files (${plan.files.length})`),\n fileTree(plan.files.map((file) => file.path)),\n '',\n pc.bold('Dependencies'),\n ...deps,\n '',\n pc.bold('Dev dependencies'),\n ...devDeps,\n ...(plan.services.length > 0\n ? ['', pc.bold('Compose services'), ` ${plan.services.join(', ')}`]\n : []),\n ...(plan.env.length > 0\n ? [\n '',\n pc.bold('Environment'),\n ...plan.env.map((v) => ` ${v.name}${v.required ? '' : pc.dim(' (optional)')}`),\n ]\n : []),\n '',\n pc.bold('Recreate with'),\n ` ${plan.command}`,\n '',\n ].join('\\n');\n}\n\n/** Pulls the project's Ollama model when it is missing and the user agrees, or reports it. */\nasync function prepareOllama(plan: ProjectPlan, interactive: boolean): Promise<boolean> {\n const model = bareModel(plan.spec);\n const baseUrl = resolveOllamaUrl();\n const installed = await listOllamaModels(baseUrl);\n if (!installed) {\n if (interactive)\n p.log.warn(\n `Ollama is not running at ${baseUrl}. Start it and pull ${model} before the first run.`\n );\n return false;\n }\n if (hasOllamaModel(installed, model)) return true;\n if (!interactive) return false;\n\n const pull = await p.confirm({\n message: `${model} is not in your Ollama yet. Pull it now?`,\n initialValue: true,\n });\n if (p.isCancel(pull) || !pull) return false;\n const spinner = p.spinner();\n spinner.start(`Pulling ${model}`);\n try {\n await pullOllamaModel(baseUrl, model, (status) =>\n spinner.message(`Pulling ${model}: ${status}`)\n );\n spinner.stop(`Pulled ${model}`);\n return true;\n } catch (error) {\n spinner.error(error instanceof Error ? error.message : `Could not pull ${model}`);\n return false;\n }\n}\n\nfunction outro(result: ScaffoldResult, args: CliArgs, modelReady: boolean): string {\n const directory = relative(process.cwd(), result.directory);\n const steps = result.plan.nextSteps({\n directory: directory || undefined,\n installed: result.install.status === 'done',\n keyWritten: args.apiKey !== undefined,\n modelReady,\n });\n return [\n `${pc.green('Your project is ready.')} Next:`,\n '',\n ...steps.map(\n (step) => ` ${pc.cyan(step.command)}${step.note ? pc.dim(` # ${step.note}`) : ''}`\n ),\n '',\n pc.dim(\n `If something does not start, ${runScript(result.plan.spec.packageManager, 'doctor')} says what is missing.`\n ),\n `Try the agents in Cogitator Studio: ${pc.cyan(runScript(result.plan.spec.packageManager, 'dev:studio'))}`,\n pc.dim(`Read AGENTS.md for how it fits together. Docs: ${DOCS_URL}`),\n ].join('\\n');\n}\n\n/** What `run` reaches the network and the environment with, replaceable in tests. */\nexport interface RunDeps {\n fetch?: typeof fetch;\n env?: NodeJS.ProcessEnv;\n /** Where telemetry goes, the release's Umami website by default. */\n telemetry?: { websiteId?: string; host?: string; fetch?: typeof fetch };\n}\n\n/** Sends the run's one telemetry event, waiting at most its timeout. */\nasync function report(enabled: boolean, deps: RunDeps, payload: TelemetryPayload): Promise<void> {\n if (!enabled) return;\n await sendTelemetry(payload, {\n ...(deps.telemetry?.websiteId !== undefined && { websiteId: deps.telemetry.websiteId }),\n ...(deps.telemetry?.host && { host: deps.telemetry.host }),\n ...(deps.telemetry?.fetch && { fetch: deps.telemetry.fetch }),\n });\n}\n\n/** Runs the scaffolder for `argv` and resolves with the exit code. */\nexport async function run(\n argv: readonly string[],\n io: Io = defaultIo,\n deps: RunDeps = {}\n): Promise<number> {\n const version = scaffolderVersion();\n let args: CliArgs;\n try {\n args = parseCliArgs(argv);\n } catch (error) {\n return reportError(error, argv.includes('--json'), io);\n }\n\n if (args.help) {\n io.stdout(helpText(version));\n return 0;\n }\n if (args.version) {\n io.stdout(`${version}\\n`);\n return 0;\n }\n if (args.listTemplates) {\n io.stdout(args.json ? `${JSON.stringify(PRESETS, null, 2)}\\n` : presetList());\n return 0;\n }\n if (args.listExamples) {\n const list = examples().map(({ name, title, entry, runtime }) => ({\n name,\n title,\n entry,\n runtime,\n }));\n io.stdout(args.json ? `${JSON.stringify(list, null, 2)}\\n` : exampleList());\n return 0;\n }\n\n const interactive = isInteractive(args);\n const env = deps.env ?? process.env;\n const telemetry =\n telemetryDisabledReason({\n flag: args.telemetry,\n dryRun: args.dryRun,\n env,\n ...(deps.telemetry?.websiteId !== undefined && { websiteId: deps.telemetry.websiteId }),\n }) === undefined;\n if (telemetry) {\n const notice = firstRunNotice(env);\n if (notice) io.stderr(`${pc.dim(notice)}\\n`);\n }\n\n if (args.example !== undefined || args.remote) {\n const kind = args.example !== undefined ? 'example' : 'template';\n try {\n const created = await runStarter(args, interactive, io, deps);\n if (created)\n await report(telemetry, deps, payloadFor(undefined, installFailure(created), kind));\n return 0;\n } catch (error) {\n if (error instanceof CancelledError) {\n p.cancel('Cancelled, nothing was created.');\n return 1;\n }\n await report(telemetry, deps, payloadFor(undefined, { step: 'create', error }, kind));\n return reportError(error, args.json, io);\n }\n }\n let resolvedSpec: ProjectSpec | undefined;\n let reported = false;\n try {\n if (interactive) {\n io.stderr(banner(version));\n p.intro(pc.cyan(\"Let's build something with agents\"));\n args = await askMissing(args);\n }\n\n const { path: directory, name } = resolveDirectory(args.directory ?? DEFAULT_DIRECTORY);\n const packageManager = args.packageManager ?? detectPackageManager();\n const spec = specFromArgs(args, { name, packageManager });\n resolvedSpec = parseSpec(spec);\n const envKey = providerInfo(spec.provider).envKey;\n const secrets = envKey && args.apiKey ? { [envKey]: args.apiKey } : {};\n const planOptions = {\n secrets,\n packageManagerSpec: detectPackageManagerSpec(spec.packageManager),\n };\n\n if (args.dryRun) {\n const plan = planProject(spec, planOptions);\n if (args.json)\n io.stdout(\n `${JSON.stringify({ ok: true, dryRun: true, ...planJson(plan, directory) }, null, 2)}\\n`\n );\n else io.stdout(describeDryRun(plan, directory));\n return 0;\n }\n\n const result = await scaffold(spec, {\n ...planOptions,\n directory,\n install: args.install ?? true,\n git: args.git ?? true,\n log: args.json ? undefined : clackLogger(),\n });\n\n reported = true;\n await report(telemetry, deps, payloadFor(result.plan.spec, installFailure(result)));\n\n const modelReady =\n result.plan.spec.provider === 'ollama' ? await prepareOllama(result.plan, interactive) : true;\n\n const key = envKey ? (args.apiKey ?? process.env[envKey]) : undefined;\n const provider = result.plan.spec.provider;\n let keyCheck: string | undefined;\n if (envKey && key && provider !== 'ollama') {\n keyCheck = describeKeyCheck(envKey, await checkApiKey(provider, key, { fetch: deps.fetch }));\n }\n\n if (args.json) {\n io.stdout(\n `${JSON.stringify(\n {\n ok: true,\n dryRun: false,\n ...planJson(result.plan, result.directory),\n steps: {\n install: stepJson(result.install),\n format: stepJson(result.format),\n git: stepJson(result.git),\n },\n modelReady,\n ...(keyCheck && { keyCheck }),\n ...(result.parentWorkspace && { parentWorkspace: result.parentWorkspace }),\n },\n null,\n 2\n )}\\n`\n );\n return 0;\n }\n\n if (keyCheck) p.log.info(keyCheck);\n if (result.parentWorkspace) {\n p.log.info(\n `The project is inside the workspace at ${result.parentWorkspace}. Add ${relative(result.parentWorkspace, result.directory)} to its workspace packages to share one install.`\n );\n }\n for (const warning of result.plan.warnings) p.log.warn(warning);\n if (interactive) p.outro(outro(result, args, modelReady));\n else io.stderr(`${outro(result, args, modelReady)}\\n`);\n return 0;\n } catch (error) {\n if (error instanceof CancelledError) {\n p.cancel('Cancelled, nothing was created.');\n return 1;\n }\n if (resolvedSpec && !reported)\n await report(telemetry, deps, payloadFor(resolvedSpec, { step: 'create', error }));\n return reportError(error, args.json, io);\n }\n}\n\nfunction starterOutro(result: StarterResult): string {\n return [\n `${pc.green('Your project is ready.')} ${pc.dim(`From ${result.source}.`)} Next:`,\n '',\n ...result.nextSteps.map(\n (step) => ` ${pc.cyan(step.command)}${step.note ? pc.dim(` # ${step.note}`) : ''}`\n ),\n '',\n pc.dim(`Docs: ${DOCS_URL}`),\n ].join('\\n');\n}\n\n/**\n * `--example` and remote `--template`: a project copied from source instead of\n * generated. Resolves with what was created, `undefined` on a dry run.\n */\nasync function runStarter(\n args: CliArgs,\n interactive: boolean,\n io: Io,\n deps: RunDeps\n): Promise<StarterResult | undefined> {\n const ignored = (\n [\n ['--app', args.app],\n ['--server', args.server],\n ['--channels', args.channels],\n ['--memory', args.memory],\n ['--vector-store', args.vectorStore],\n ['--features', args.features],\n ['--deploy', args.deploy],\n ['--model', args.model],\n ['--agent', args.codingAgents],\n ['--[no-]docker', args.compose],\n ] as const\n )\n .filter(([, value]) => value !== undefined)\n .map(([flag]) => flag);\n if (ignored.length > 0) {\n throw new CliError(\n `${args.example !== undefined ? '--example' : 'A github: --template'} copies a project as it is, so ${ignored.join(', ')} do not apply: leave them out.`\n );\n }\n if (interactive) {\n io.stderr(banner(scaffolderVersion()));\n p.intro(pc.cyan(\"Let's build something with agents\"));\n }\n const directoryArg = args.directory ?? (interactive ? await askDirectory() : DEFAULT_DIRECTORY);\n const { path: directory, name } = resolveDirectory(directoryArg);\n const packageManager = args.packageManager ?? detectPackageManager();\n const options = {\n directory,\n name,\n packageManager,\n install: args.install ?? true,\n git: args.git ?? true,\n log: args.json ? undefined : clackLogger(),\n fetch: deps.fetch,\n };\n\n let result: StarterResult;\n if (args.example !== undefined) {\n const envKey = providerInfo(args.provider ?? 'google').envKey;\n const secrets = envKey && args.apiKey ? { [envKey]: args.apiKey } : {};\n const plan = resolveExample(args.example, { name, packageManager, secrets });\n if (args.dryRun) {\n const files = [\n ...plan.files.map((file) => file.path),\n ...plan.remoteFiles.map(exampleTarget),\n ].sort();\n if (args.json) {\n io.stdout(\n `${JSON.stringify({ ok: true, dryRun: true, directory, example: plan.example, ref: plan.ref, command: plan.command, files }, null, 2)}\\n`\n );\n } else {\n io.stdout(\n [\n `${pc.bold('Dry run:')} nothing was written. ${directory} would get the ${plan.example.name} example from ${plan.ref}:`,\n '',\n fileTree(files),\n '',\n pc.bold('Dependencies'),\n ...Object.entries(plan.example.dependencies).map(\n ([dep, range]) => ` ${dep} ${pc.dim(range)}`\n ),\n '',\n ].join('\\n')\n );\n }\n return undefined;\n }\n result = await createFromExample(plan, options);\n } else if (args.remote) {\n if (args.dryRun) {\n const message = `${directory} would get ${describeTemplate(args.remote)}`;\n io.stdout(\n args.json\n ? `${JSON.stringify({ ok: true, dryRun: true, directory, template: args.remote }, null, 2)}\\n`\n : `${pc.bold('Dry run:')} nothing was written. ${message}.\\n`\n );\n return undefined;\n }\n result = await createFromTemplate(args.remote, {\n ...options,\n token: process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN,\n });\n } else {\n throw new CliError('Pass --example or a github: --template');\n }\n\n if (args.json) {\n io.stdout(\n `${JSON.stringify(\n {\n ok: true,\n dryRun: false,\n directory: result.directory,\n source: result.source,\n files: result.files,\n packageManager: result.packageManager,\n steps: { install: stepJson(result.install), git: stepJson(result.git) },\n nextSteps: result.nextSteps,\n notes: result.notes,\n },\n null,\n 2\n )}\\n`\n );\n return result;\n }\n for (const note of result.notes) p.log.info(note);\n if (interactive) p.outro(starterOutro(result));\n else io.stderr(`${starterOutro(result)}\\n`);\n return result;\n}\n\nfunction reportError(error: unknown, json: boolean, io: Io): number {\n const message = error instanceof Error ? error.message : String(error);\n if (json) {\n const issues = error instanceof IncompatibleSpecError ? error.issues : undefined;\n io.stdout(\n `${JSON.stringify({ ok: false, error: { message, ...(issues && { issues }) } }, null, 2)}\\n`\n );\n } else if (error instanceof CliError || error instanceof IncompatibleSpecError) {\n io.stderr(`${pc.red('Error:')} ${message}\\n`);\n } else {\n io.stderr(`${pc.red('Error:')} ${message}\\n`);\n if (process.env.DEBUG && error instanceof Error && error.stack) io.stderr(`${error.stack}\\n`);\n }\n return 1;\n}\n","import { parseArgs, type ParseArgsConfig } from 'node:util';\nimport { presetIds, findPreset } from '../kit/presets.js';\nimport {\n APP_KINDS,\n CHANNELS,\n CODING_AGENTS,\n DEPLOY_TARGETS,\n FEATURES,\n MEMORIES,\n PACKAGE_MANAGERS,\n PROVIDERS,\n SERVERS,\n VECTOR_STORES,\n type AppKind,\n type ChannelKind,\n type CodingAgent,\n type DeployTarget,\n type FeatureId,\n type LLMProvider,\n type MemoryKind,\n type PackageManager,\n type ServerFramework,\n type VectorStore,\n} from '../kit/spec.js';\nimport type { RemoteTemplate } from '../kit/remote.js';\nimport { closest } from '../kit/suggest.js';\n\nexport { closest };\n\n/** A usage mistake: shown without a stack trace, exits with code 1. */\nexport class CliError extends Error {\n readonly code = 'INVALID_ARGS';\n\n constructor(message: string) {\n super(message);\n this.name = 'CliError';\n }\n}\n\nexport type { RemoteTemplate };\n\nexport interface CliArgs {\n directory?: string;\n preset?: string;\n remote?: RemoteTemplate;\n example?: string;\n app?: AppKind;\n server?: ServerFramework;\n channels?: ChannelKind[];\n memory?: MemoryKind;\n vectorStore?: VectorStore;\n features?: FeatureId[];\n deploy?: DeployTarget;\n compose?: boolean;\n provider?: LLMProvider;\n model?: string;\n apiKey?: string;\n packageManager?: PackageManager;\n codingAgents?: CodingAgent[];\n git?: boolean;\n install?: boolean;\n telemetry?: boolean;\n yes: boolean;\n dryRun: boolean;\n json: boolean;\n help: boolean;\n version: boolean;\n listTemplates: boolean;\n listExamples: boolean;\n}\n\nconst OPTIONS = {\n preset: { type: 'string', short: 't' },\n template: { type: 'string' },\n example: { type: 'string' },\n app: { type: 'string' },\n server: { type: 'string' },\n channels: { type: 'string', multiple: true },\n memory: { type: 'string' },\n 'vector-store': { type: 'string' },\n features: { type: 'string', multiple: true },\n with: { type: 'string', multiple: true },\n deploy: { type: 'string' },\n docker: { type: 'boolean' },\n provider: { type: 'string', short: 'p' },\n model: { type: 'string', short: 'm' },\n 'api-key': { type: 'string' },\n pm: { type: 'string' },\n agent: { type: 'string', multiple: true },\n git: { type: 'boolean' },\n install: { type: 'boolean' },\n telemetry: { type: 'boolean' },\n yes: { type: 'boolean', short: 'y' },\n 'dry-run': { type: 'boolean' },\n json: { type: 'boolean' },\n help: { type: 'boolean', short: 'h' },\n version: { type: 'boolean', short: 'v' },\n 'list-templates': { type: 'boolean' },\n 'list-presets': { type: 'boolean' },\n 'list-examples': { type: 'boolean' },\n} as const satisfies NonNullable<ParseArgsConfig['options']>;\n\nconst OPTION_NAMES = Object.keys(OPTIONS);\n\nfunction suggestion(input: string, candidates: readonly string[]): string {\n const match = closest(input, candidates);\n return match ? ` Did you mean \"${match}\"?` : '';\n}\n\nfunction oneOf<T extends string>(flag: string, value: string, allowed: readonly T[]): T {\n const found = allowed.find((candidate) => candidate === value);\n if (found) return found;\n throw new CliError(\n `Invalid --${flag} \"${value}\".${suggestion(value, allowed)} Use one of: ${allowed.join(', ')}.`\n );\n}\n\n/** Values of a list option, given repeated (`--x a --x b`) or comma separated (`--x a,b`). */\nfunction listOf<T extends string>(\n flag: string,\n values: readonly string[],\n allowed: readonly T[]\n): T[] {\n const items = values\n .flatMap((value) => value.split(','))\n .map((item) => item.trim())\n .filter(Boolean);\n return [...new Set(items.map((item) => oneOf(flag, item, allowed)))];\n}\n\n/** Parses `github:owner/repo`, `github:owner/repo/sub/dir` and an optional `#ref`. */\nexport function parseRemoteTemplate(value: string): RemoteTemplate {\n const match =\n /^(?:github:|https:\\/\\/github\\.com\\/)([\\w.-]+)\\/([\\w.-]+?)(?:\\.git)?(?:\\/((?:[\\w.-]+\\/)*[\\w.-]+)\\/?)?(?:#([^\\s~^:?*[\\\\]+))?$/.exec(\n value\n );\n if (!match) {\n throw new CliError(\n `Invalid remote template \"${value}\". Use github:owner/repo, github:owner/repo/path or github:owner/repo#ref.`\n );\n }\n const [, owner, repo, path, ref] = match;\n return {\n owner,\n repo,\n ...(path && { path: path.replace(/\\/$/, '') }),\n ...(ref && { ref }),\n };\n}\n\nfunction isRemote(value: string): boolean {\n return value.startsWith('github:') || value.startsWith('https://github.com/');\n}\n\n/**\n * Parses the command line. Unknown options and invalid values are errors,\n * also with `--yes`: a typo never silently becomes a default.\n */\nexport function parseCliArgs(argv: readonly string[]): CliArgs {\n let parsed;\n try {\n parsed = parseArgs({\n args: [...argv],\n options: OPTIONS,\n allowPositionals: true,\n allowNegative: true,\n strict: true,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const unknown = /Unknown option '(--?[\\w-]+)'/.exec(message)?.[1];\n if (unknown) {\n const name = unknown.replace(/^--?/, '');\n const hint = closest(name, OPTION_NAMES);\n throw new CliError(\n `Unknown option ${unknown}.${hint ? ` Did you mean --${hint}?` : ''} Run with --help for the options.`\n );\n }\n throw new CliError(`${message.replace(/\\.$/, '')}. Run with --help for the options.`);\n }\n\n const { values, positionals } = parsed;\n if (positionals.length > 1) {\n throw new CliError(\n `Expected one project directory, got ${positionals.length}: ${positionals.join(' ')}. Quote a path with spaces.`\n );\n }\n\n const presetValue = values.preset ?? values.template;\n if (\n values.preset !== undefined &&\n values.template !== undefined &&\n values.preset !== values.template\n ) {\n throw new CliError('--preset and --template name different presets, pass only one of them.');\n }\n\n let preset: string | undefined;\n let remote: RemoteTemplate | undefined;\n if (presetValue !== undefined) {\n if (isRemote(presetValue)) {\n remote = parseRemoteTemplate(presetValue);\n } else {\n const found = findPreset(presetValue);\n if (!found) {\n throw new CliError(\n `Unknown preset \"${presetValue}\".${suggestion(presetValue, presetIds())} Run with --list-templates to see them all.`\n );\n }\n preset = found.id;\n }\n }\n if (remote && values.example !== undefined) {\n throw new CliError('--example and a remote --template cannot be combined.');\n }\n if (values.example !== undefined && preset) {\n throw new CliError('--example replaces the preset, pass only one of --example and --preset.');\n }\n\n const features = [...(values.features ?? []), ...(values.with ?? [])];\n const apiKey = values['api-key'];\n if (apiKey !== undefined && !apiKey.trim()) throw new CliError('--api-key is empty.');\n const model = values.model?.trim();\n if (values.model !== undefined && !model) throw new CliError('--model is empty.');\n\n return {\n ...(positionals[0] !== undefined && { directory: positionals[0] }),\n ...(preset && { preset }),\n ...(remote && { remote }),\n ...(values.example !== undefined && { example: values.example }),\n ...(values.app !== undefined && { app: oneOf('app', values.app, APP_KINDS) }),\n ...(values.server !== undefined && { server: oneOf('server', values.server, SERVERS) }),\n ...(values.channels && { channels: listOf('channels', values.channels, CHANNELS) }),\n ...(values.memory !== undefined && { memory: oneOf('memory', values.memory, MEMORIES) }),\n ...(values['vector-store'] !== undefined && {\n vectorStore: oneOf('vector-store', values['vector-store'], VECTOR_STORES),\n }),\n ...(features.length > 0 && { features: listOf('features', features, FEATURES) }),\n ...(values.deploy !== undefined && { deploy: oneOf('deploy', values.deploy, DEPLOY_TARGETS) }),\n ...(values.docker !== undefined && { compose: values.docker }),\n ...(values.provider !== undefined && {\n provider: oneOf('provider', values.provider, PROVIDERS),\n }),\n ...(model && { model }),\n ...(apiKey !== undefined && { apiKey: apiKey.trim() }),\n ...(values.pm !== undefined && { packageManager: oneOf('pm', values.pm, PACKAGE_MANAGERS) }),\n ...(values.agent && {\n codingAgents: listOf(\n 'agent',\n values.agent.filter((a) => a !== 'none'),\n CODING_AGENTS\n ),\n }),\n ...(values.git !== undefined && { git: values.git }),\n ...(values.install !== undefined && { install: values.install }),\n ...(values.telemetry !== undefined && { telemetry: values.telemetry }),\n yes: values.yes ?? false,\n dryRun: values['dry-run'] ?? false,\n json: values.json ?? false,\n help: values.help ?? false,\n version: values.version ?? false,\n listTemplates: (values['list-templates'] ?? false) || (values['list-presets'] ?? false),\n listExamples: values['list-examples'] ?? false,\n };\n}\n\n/**\n * Whether to ask questions: only at a terminal, and never with `--yes`,\n * `--json` or in CI, where nobody can answer.\n */\nexport function isInteractive(\n args: Pick<CliArgs, 'yes' | 'json'>,\n env: NodeJS.ProcessEnv = process.env,\n stdin: { isTTY?: boolean } = process.stdin\n): boolean {\n if (args.yes || args.json) return false;\n if (env.CI && env.CI !== 'false' && env.CI !== '0') return false;\n return stdin.isTTY === true;\n}\n","import pc from 'picocolors';\nimport {\n APP_CHOICES,\n CHANNEL_CHOICES,\n CODING_AGENT_CHOICES,\n DEPLOY_CHOICES,\n FEATURE_CHOICES,\n MEMORY_CHOICES,\n SERVER_CHOICES,\n VECTOR_STORE_CHOICES,\n type Choice,\n} from '../kit/catalog.js';\nimport { DEFAULT_PRESET, PRESETS } from '../kit/presets.js';\nimport { examples } from '../kit/examples.js';\nimport { PACKAGE_MANAGERS, PROVIDERS } from '../kit/spec.js';\n\nfunction values(choices: readonly Choice<string>[]): string {\n return choices.map((choice) => choice.value).join(', ');\n}\n\nfunction row(flag: string, description: string): string {\n return ` ${pc.cyan(flag.padEnd(28))} ${description}`;\n}\n\nexport function helpText(version: string): string {\n return [\n `${pc.bold('create-cogitator-app')} ${pc.dim(`v${version}`)}`,\n '',\n 'Create a Cogitator AI agent project.',\n '',\n `${pc.bold('Usage')}`,\n ' npx create-cogitator-app [directory] [options]',\n '',\n `${pc.bold('Stack')}`,\n row(\n '-t, --preset <name>',\n `a named starting point (default ${DEFAULT_PRESET}), see --list-templates`\n ),\n row(\n ' --template <name|repo>',\n 'a preset, or github:owner/repo[/path][#ref] to copy a repository'\n ),\n row(\n ' --example <name[#ref]>',\n 'a runnable example of the Cogitator repo, see --list-examples'\n ),\n row(' --app <kind>', values(APP_CHOICES)),\n row(' --server <framework>', values(SERVER_CHOICES)),\n row(' --channels <list>', values(CHANNEL_CHOICES)),\n row(' --memory <kind>', values(MEMORY_CHOICES)),\n row(' --vector-store <store>', `for RAG: ${values(VECTOR_STORE_CHOICES)}`),\n row(' --features <list>', `added to the preset's: ${values(FEATURE_CHOICES)}`),\n row(' --deploy <target>', values(DEPLOY_CHOICES)),\n row(' --[no-]docker', 'write docker-compose.yml for local services (default yes)'),\n '',\n `${pc.bold('Model')}`,\n row('-p, --provider <name>', PROVIDERS.join(', ')),\n row(\n '-m, --model <id>',\n \"the model id at the provider, e.g. gpt-6.1-sol, default: the provider's\"\n ),\n row(' --api-key <key>', 'written to .env (mode 600) and never printed'),\n '',\n `${pc.bold('Tooling')}`,\n row(' --pm <name>', `${PACKAGE_MANAGERS.join(', ')} (default: the one running this)`),\n row(' --agent <list>', `coding agent setup: ${values(CODING_AGENT_CHOICES)}, none`),\n row(' --[no-]git', 'create a git repository with the first commit (default yes)'),\n row(' --[no-]install', 'install dependencies (default yes)'),\n row(' --no-telemetry', 'send no anonymous usage event, see the docs'),\n '',\n `${pc.bold('Output')}`,\n row('-y, --yes', 'ask nothing, use defaults for whatever the flags leave out'),\n row(' --dry-run', 'show the files and dependencies without writing anything'),\n row(' --json', 'print the result as JSON, implies --yes'),\n row(' --list-templates', 'list the presets'),\n row(' --list-examples', 'list the examples --example takes'),\n row('-h, --help', 'show this help'),\n row('-v, --version', 'show the version'),\n '',\n `${pc.bold('Examples')}`,\n ' npx create-cogitator-app my-bot --preset channels --channels telegram',\n ' npx create-cogitator-app api --app server --server fastify --memory postgres --features rag,evals',\n ' npx create-cogitator-app . --provider anthropic --api-key \"$ANTHROPIC_API_KEY\" --yes',\n ' npx create-cogitator-app demo --preset nextjs --dry-run --json',\n ' npx create-cogitator-app tutor --example core/basic-agent',\n ' npx create-cogitator-app bot --template github:acme/agent-templates/support-bot#v2',\n '',\n 'Without a TTY or with CI set, nothing is asked: flags and defaults decide everything.',\n '',\n ].join('\\n');\n}\n\nexport function presetList(): string {\n const width = Math.max(...PRESETS.map((preset) => preset.id.length));\n return (\n PRESETS.map(\n (preset) => ` ${pc.cyan(preset.id.padEnd(width))} ${preset.label}: ${pc.dim(preset.hint)}`\n ).join('\\n') + '\\n'\n );\n}\n\nexport function exampleList(): string {\n const all = examples();\n const width = Math.max(...all.map((example) => example.name.length));\n return (\n all\n .map((example) => ` ${pc.cyan(example.name.padEnd(width))} ${pc.dim(example.title)}`)\n .join('\\n') + '\\n'\n );\n}\n","import { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport * as p from '@clack/prompts';\nimport {\n APP_CHOICES,\n CHANNEL_CHOICES,\n CODING_AGENT_CHOICES,\n DEPLOY_CHOICES,\n FEATURE_CHOICES,\n MEMORY_CHOICES,\n SERVER_CHOICES,\n VECTOR_STORE_CHOICES,\n} from '../kit/catalog.js';\nimport { modelChoices } from '../kit/models.js';\nimport { DEFAULT_PRESET, PRESETS } from '../kit/presets.js';\nimport { PROVIDER_INFO, providerInfo } from '../kit/providers.js';\nimport { PROVIDERS, validateProjectName, type CodingAgent } from '../kit/spec.js';\nimport type { CliArgs } from './args.js';\nimport { DEFAULT_DIRECTORY, projectNameFromDirectory } from './resolve.js';\n\nexport class CancelledError extends Error {\n constructor() {\n super('Cancelled');\n this.name = 'CancelledError';\n }\n}\n\n/** The answer to a prompt, or a CancelledError when the user pressed Ctrl+C. */\nfunction answer<T>(value: T): Exclude<T, symbol> {\n if (p.isCancel(value)) throw new CancelledError();\n return value as Exclude<T, symbol>;\n}\n\nconst CUSTOM = '__custom__';\nconst OTHER_MODEL = '__other__';\n\n/** Coding agents whose config directory exists in the home directory, offered preselected. */\nexport function detectCodingAgents(home: string = homedir()): CodingAgent[] {\n const markers: Record<CodingAgent, string> = {\n claude: '.claude',\n cursor: '.cursor',\n codex: '.codex',\n };\n return CODING_AGENT_CHOICES.map((choice) => choice.value).filter((agent) =>\n existsSync(join(home, markers[agent]))\n );\n}\n\n/**\n * Asks for everything the flags left open and returns the flags completed with\n * the answers. Anything given as a flag is not asked again.\n */\n/** Asks where the project goes. */\nexport async function askDirectory(): Promise<string> {\n return answer(\n await p.text({\n message: 'Where should the project go?',\n placeholder: `./${DEFAULT_DIRECTORY}`,\n defaultValue: DEFAULT_DIRECTORY,\n validate: (value) =>\n value?.trim() ? validateProjectName(projectNameFromDirectory(value)) : undefined,\n })\n ).trim();\n}\n\nexport async function askMissing(args: CliArgs): Promise<CliArgs> {\n const next: CliArgs = { ...args };\n\n if (next.directory === undefined) next.directory = await askDirectory();\n\n if (next.preset === undefined && next.app === undefined) {\n const choice = answer(\n await p.select<string>({\n message: 'What do you want to build?',\n options: [\n ...PRESETS.map((preset) => ({\n value: preset.id,\n label: preset.label,\n hint: preset.hint,\n })),\n {\n value: CUSTOM,\n label: 'Custom stack',\n hint: 'pick the app, memory and features yourself',\n },\n ],\n initialValue: DEFAULT_PRESET,\n maxItems: 10,\n })\n );\n if (choice === CUSTOM) Object.assign(next, await askStack(next));\n else next.preset = choice;\n }\n\n const presetProvider = PRESETS.find((preset) => preset.id === next.preset)?.spec.provider;\n if (next.provider === undefined) {\n next.provider = answer(\n await p.select({\n message: 'Which model provider?',\n options: PROVIDERS.map((id) => ({\n value: id,\n label: PROVIDER_INFO[id].label,\n hint: PROVIDER_INFO[id].hint,\n })),\n initialValue: presetProvider ?? 'ollama',\n })\n );\n }\n const provider = next.provider;\n\n if (next.model === undefined) {\n const spinner = p.spinner();\n spinner.start('Looking up models');\n const { choices, source } = await modelChoices(provider);\n spinner.stop(\n source === 'ollama'\n ? 'Found the models in your Ollama'\n : source === 'suggested'\n ? 'Ollama is not running, so here are good small models to pull'\n : `Found the current ${providerInfo(provider).label} models`\n );\n const picked = answer(\n await p.select<string>({\n message: 'Which model?',\n options: [...choices, { value: OTHER_MODEL, label: 'Another model', hint: 'type its id' }],\n initialValue: choices[0]?.value,\n maxItems: 10,\n })\n );\n next.model =\n picked === OTHER_MODEL\n ? answer(\n await p.text({\n message: `Model id at ${providerInfo(provider).label}`,\n validate: (value) => (value?.trim() ? undefined : 'Type a model id'),\n })\n ).trim()\n : picked;\n }\n\n const envKey = providerInfo(provider).envKey;\n if (envKey && next.apiKey === undefined) {\n const fromShell = process.env[envKey]?.trim();\n if (fromShell) {\n const copy = answer(\n await p.confirm({\n message: `Copy ${envKey} from your shell into the project's .env?`,\n initialValue: true,\n })\n );\n if (copy) next.apiKey = fromShell;\n } else {\n const key = answer(\n await p.password({\n message: `${envKey} (leave empty to add it to .env later)`,\n mask: '*',\n })\n ).trim();\n if (key) next.apiKey = key;\n }\n }\n\n if (next.codingAgents === undefined) {\n const detected = detectCodingAgents();\n next.codingAgents = answer(\n await p.multiselect<CodingAgent>({\n message: 'Set the project up for your coding agent? (AGENTS.md is always written)',\n options: CODING_AGENT_CHOICES,\n initialValues: detected,\n required: false,\n })\n );\n }\n\n return next;\n}\n\n/** The stack questions of a custom project. */\nasync function askStack(args: CliArgs): Promise<Partial<CliArgs>> {\n const app =\n args.app ??\n answer(\n await p.select({\n message: 'Which kind of app?',\n options: APP_CHOICES,\n initialValue: 'script',\n })\n );\n const result: Partial<CliArgs> = { app };\n\n if (app === 'server' && args.server === undefined) {\n result.server = answer(\n await p.select({\n message: 'Which server framework?',\n options: SERVER_CHOICES,\n initialValue: 'hono',\n })\n );\n }\n if (app === 'channels' && args.channels === undefined) {\n result.channels = answer(\n await p.multiselect({\n message: 'Which channels?',\n options: CHANNEL_CHOICES,\n initialValues: ['webchat'],\n required: true,\n })\n );\n }\n if (args.memory === undefined) {\n result.memory = answer(\n await p.select({\n message: 'Where should conversations be stored?',\n options: MEMORY_CHOICES,\n initialValue: 'sqlite',\n })\n );\n }\n if (args.features === undefined) {\n const features = answer(\n await p.multiselect({\n message: 'Which features? (space to toggle)',\n options: FEATURE_CHOICES,\n required: false,\n })\n );\n if (features.includes('durable') && !features.includes('workflows')) features.push('workflows');\n result.features = features;\n if (features.includes('rag') && args.vectorStore === undefined) {\n result.vectorStore = answer(\n await p.select({\n message: 'Where should RAG keep its vectors?',\n options: VECTOR_STORE_CHOICES,\n initialValue: 'memory',\n })\n );\n }\n }\n if (args.deploy === undefined) {\n result.deploy = answer(\n await p.select({\n message: 'How will you deploy it?',\n options: DEPLOY_CHOICES,\n initialValue: 'docker',\n })\n );\n }\n return result;\n}\n","import { basename, resolve } from 'node:path';\nimport { DEFAULT_PRESET, findPreset } from '../kit/presets.js';\nimport { defaultModel } from '../kit/providers.js';\nimport { validateProjectName, type ProjectSpecInput, type PackageManager } from '../kit/spec.js';\nimport { CliError, type CliArgs } from './args.js';\n\nexport const DEFAULT_DIRECTORY = 'my-agents';\n\n/** The package name for a project created in `directory`: its last path segment, so `.` takes the current directory's name. */\nexport function projectNameFromDirectory(directory: string, cwd: string = process.cwd()): string {\n return basename(resolve(cwd, directory.trim()));\n}\n\nexport function resolveDirectory(\n directory: string,\n cwd: string = process.cwd()\n): { path: string; name: string } {\n const name = projectNameFromDirectory(directory, cwd);\n const error = validateProjectName(name);\n if (error) throw new CliError(`Invalid project name \"${name}\": ${error}`);\n return { path: resolve(cwd, directory.trim()), name };\n}\n\n/**\n * The spec the flags describe, on top of the preset they name (or the default\n * one). Flags win over the preset, and `--features` adds to the preset's\n * features instead of replacing them.\n */\nexport function specFromArgs(\n args: CliArgs,\n context: { name: string; packageManager: PackageManager }\n): ProjectSpecInput {\n const custom = args.app !== undefined && args.preset === undefined;\n const preset = custom ? undefined : findPreset(args.preset ?? DEFAULT_PRESET);\n if (!custom && !preset) throw new CliError(`Unknown preset \"${args.preset}\"`);\n\n const base = preset?.spec;\n const app = args.app ?? base?.app ?? 'script';\n const provider = args.provider ?? base?.provider ?? 'ollama';\n const server =\n args.server ?? (app === 'server' ? (base?.app === 'server' ? base.server : 'hono') : undefined);\n const channels = args.channels ?? (app === 'channels' ? (base?.channels ?? ['webchat']) : []);\n const features = [...new Set([...(base?.features ?? []), ...(args.features ?? [])])];\n\n return {\n name: context.name,\n ...(preset && { preset: preset.id }),\n app,\n ...(server && { server }),\n channels,\n memory: args.memory ?? base?.memory ?? 'none',\n vectorStore: args.vectorStore ?? base?.vectorStore ?? 'memory',\n features,\n provider,\n model: args.model ?? defaultModel(provider),\n deploy: args.deploy ?? 'none',\n compose: args.compose ?? true,\n packageManager: args.packageManager ?? (server === 'tetsu' ? 'bun' : context.packageManager),\n codingAgents: args.codingAgents ?? [],\n };\n}\n"],"mappings":";AAAA,yCAAC,EAAC,MAAO,kBAAiB,OAAQ,cAAa,OAAQ,wBAAuB,OAAQ,CAAC,oBAAmB,sBAAsB,GAAE,cAAe,EAAC,qBAAoB,UAAS,sBAAqB,WAAU,QAAS,WAAU,SAAU,SAAQ,GAAE,iBAAkB,EAAC,kBAAiB,UAAS,KAAM,WAAU,GAAE,KAAM,CAAC,qBAAoB,kBAAiB,cAAa,kBAAiB,oBAAoB,GAAE,SAAU,OAAM,GAAE,EAAC,MAAO,kBAAiB,OAAQ,cAAa,OAAQ,wBAAuB,OAAQ,CAAC,oBAAmB,sBAAsB,GAAE,cAAe,EAAC,qBAAoB,UAAS,sBAAqB,WAAU,QAAS,UAAS,GAAE,iBAAkB,EAAC,KAAM,WAAU,GAAE,KAAM,CAAC,qBAAoB,kBAAiB,cAAa,kBAAiB,oBAAoB,GAAE,SAAU,OAAM,GAAE,EAAC,MAAO,2BAA0B,OAAQ,wBAAuB,OAAQ,iCAAgC,OAAQ,CAAC,oBAAmB,+BAA+B,GAAE,cAAe,EAAC,sBAAqB,WAAU,gCAA+B,WAAU,QAAS,WAAU,KAAM,SAAQ,GAAE,iBAAkB,EAAC,KAAM,WAAU,GAAE,KAAM,CAAC,qBAAoB,kBAAiB,cAAa,kBAAiB,oBAAoB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,OAAO;AAAA,CAAI;AAAA,EAC9C,OAAO;AACL,OAAG,OAAO,GAAGA,IAAG,IAAI,QAAQ,CAAC,IAAI,OAAO;AAAA,CAAI;AAC5C,QAAI,QAAQ,IAAI,SAAS,iBAAiB,SAAS,MAAM,MAAO,IAAG,OAAO,GAAG,MAAM,KAAK;AAAA,CAAI;AAAA,EAC9F;AACA,SAAO;AACT;","names":["existsSync","dirname","join","code","code","values","text","lines","lines","lines","dirname","join","join","dirname","lines","text","lines","resolve","code","join","dirname","existsSync","log","existsSync","readFileSync","mkdir","writeFile","dirname","join","resolve","parseDocument","text","lines","tail","i","j","text","join","existsSync","readFileSync","text","parseDocument","resolve","log","mkdir","dirname","writeFile","row","suggestion","run","tsconfig","existsSync","readFileSync","readdirSync","writeFileSync","mkdir","join","mkdir","relative","existsSync","join","readdirSync","readFileSync","writeFileSync","existsSync","readFileSync","mkdir","rm","join","resolve","finish","log","run","resolve","mkdir","existsSync","rm","join","readFileSync","resolve","existsSync","mkdirSync","writeFileSync","join","z","z","failure","join","existsSync","mkdirSync","writeFileSync","relative","p","pc","values","existsSync","homedir","join","basename","resolve","basename","resolve","homedir","existsSync","join","spinner","text","pc","spinner","outro","relative"]}