bazilion 0.58.2 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +16 -1
- package/dist/cli.js.map +1 -1
- package/dist/daemon.js +211 -77
- package/dist/daemon.js.map +1 -1
- package/dist/web/client/assets/AddProviderDialog-CbBtkgU7.js +1 -0
- package/dist/web/client/assets/{AgentTemplateParts-BaeuW_3n.js → AgentTemplateParts-Tx0RJoDa.js} +1 -1
- package/dist/web/client/assets/{ConfirmDialog-D8f2wI5x.js → ConfirmDialog-Du8-95Zj.js} +1 -1
- package/dist/web/client/assets/{ConnectionsView-BUZcfBHw.js → ConnectionsView-Dg9kLuab.js} +1 -1
- package/dist/web/client/assets/{SkillsParts-jMYdOiWh.js → SkillsParts-TYzEfrVu.js} +1 -1
- package/dist/web/client/assets/{SpawnTeamModal-Dq7D3Zlc.js → SpawnTeamModal-Dr98zpUf.js} +1 -1
- package/dist/web/client/assets/{TeamForm-Crz3mvXu.js → TeamForm-DaH5H-LF.js} +1 -1
- package/dist/web/client/assets/{TeamThread-qTkvxv27.js → TeamThread-DmtbrFq1.js} +1 -1
- package/dist/web/client/assets/{UnsavedChangesGuard-DGzP-x1t.js → UnsavedChangesGuard-fvP4Xr0R.js} +1 -1
- package/dist/web/client/assets/{_id-DsZBpW5G.js → _id--1i1fY0o.js} +1 -1
- package/dist/web/client/assets/{_id-CiqTBi2Q.js → _id-C_s4pMAk.js} +1 -1
- package/dist/web/client/assets/{access-ssWsYTEU.js → access-99X0FS-H.js} +1 -1
- package/dist/web/client/assets/{agents-BmkaQvWh.js → agents-CDJMwJL1.js} +1 -1
- package/dist/web/client/assets/{agents-D3tZ58Dh.js → agents-DVAJFWJI.js} +1 -1
- package/dist/web/client/assets/{attention-ChHdu7E8.js → attention-CDzRuQGN.js} +1 -1
- package/dist/web/client/assets/{config-DPsq6Zy9.js → config-9GESe8FI.js} +1 -1
- package/dist/web/client/assets/{index-CVVVmIFC.js → index-DkK2xZ2o.js} +2 -2
- package/dist/web/client/assets/{login-B-Kpyw9o.js → login-DUmrDZjN.js} +1 -1
- package/dist/web/client/assets/{manage-Dwe9yQl9.js → manage-D6zhY8hA.js} +1 -1
- package/dist/web/client/assets/{mcp-73AMOCv3.js → mcp-ByioWHXZ.js} +1 -1
- package/dist/web/client/assets/routes-DEMmBJiz.js +85 -0
- package/dist/web/client/assets/{skills-DmYDuDbl.js → skills-a52e5W9Z.js} +1 -1
- package/dist/web/client/assets/{style-B9Vy-99n.js → style-CiyV21dp.js} +1 -1
- package/dist/web/client/assets/styles-B-X0olFi.css +2 -0
- package/dist/web/client/assets/{system-t9hcqYBg.js → system-wJXOiU47.js} +1 -1
- package/dist/web/client/assets/{teams-5B2cyDin.js → teams-vRmMRnY_.js} +1 -1
- package/dist/web/client/assets/{teams-Nk_bHpr0.js → teams-wLJHtFW_.js} +1 -1
- package/dist/web/client/assets/telegram-CUsT8ZzL.js +1 -0
- package/dist/web/client/assets/{tools-mdAuMsYJ.js → tools-NMtdwKi0.js} +1 -1
- package/dist/web/client/assets/{usage-CWu7R8ZD.js → usage-DiIpfPPk.js} +1 -1
- package/dist/web/client/assets/{welcome-BuRNFxpc.js → welcome-BWN0jtZP.js} +1 -1
- package/dist/web/server/assets/{AddProviderDialog-Bqsz5NaL.js → AddProviderDialog-CxwjFPVY.js} +3 -3
- package/dist/web/server/assets/{AgentTemplateParts-D97gKNdN.js → AgentTemplateParts-CDDoX_bG.js} +5 -5
- package/dist/web/server/assets/{ConfigPage-CrxctbtN.js → ConfigPage-DwbP35aS.js} +2 -2
- package/dist/web/server/assets/{ConfirmDialog-CuD5HXTw.js → ConfirmDialog-CR_DTRpW.js} +1 -1
- package/dist/web/server/assets/{ConnectionsView-CSf83J-v.js → ConnectionsView-CplWLHII.js} +4 -4
- package/dist/web/server/assets/{Dialog-CwAfaXpM.js → Dialog-B2ZAk0JC.js} +1 -1
- package/dist/web/server/assets/{ManagePage-DGYNJ6XG.js → ManagePage-DSzEP6tP.js} +2 -2
- package/dist/web/server/assets/{ModelMenu-DEJoYASj.js → ModelMenu-BgIvpkO0.js} +1 -1
- package/dist/web/server/assets/{SectionTabs--vMBvaUz.js → SectionTabs-B56iIxRj.js} +1 -1
- package/dist/web/server/assets/{SkillsParts-hjS9a_Ht.js → SkillsParts-Bf5aGuER.js} +5 -5
- package/dist/web/server/assets/{SpawnDialog-BjVZl7xK.js → SpawnDialog-Fsdom-ur.js} +4 -4
- package/dist/web/server/assets/{SpawnTeamModal-BmBXqfFi.js → SpawnTeamModal-Zz03rkBZ.js} +4 -4
- package/dist/web/server/assets/{TeamForm-B4702hBg.js → TeamForm-DwXwjZWb.js} +4 -4
- package/dist/web/server/assets/{UnsavedChangesGuard-Be8EqfV_.js → UnsavedChangesGuard-BEtAdwza.js} +1 -1
- package/dist/web/server/assets/{_id-VqiN2zRR.js → _id-D1USZSkO.js} +9 -9
- package/dist/web/server/assets/{_id-BWtcQovD.js → _id-Dkx7QsM_.js} +1 -1
- package/dist/web/server/assets/{_id-DBhvSxVl.js → _id-R5F7ISnu.js} +1 -1
- package/dist/web/server/assets/{_id-TT_ZsaSc.js → _id-gh-ba9YO.js} +10 -10
- package/dist/web/server/assets/{_id-CKBQM7LH.js → _id-sS3ozDuV.js} +1 -1
- package/dist/web/server/assets/{_tanstack-start-manifest_v-gHDkHqeS.js → _tanstack-start-manifest_v-Be9mOSxg.js} +57 -57
- package/dist/web/server/assets/{access-Bog7dbtP.js → access-BcKK4G_w.js} +1 -1
- package/dist/web/server/assets/{access-C5lXP5JS.js → access-CftAsKX6.js} +5 -5
- package/dist/web/server/assets/{agents-DDUHE3eY.js → agents-BAlP1gc_.js} +8 -8
- package/dist/web/server/assets/{agents-8XZAjHh0.js → agents-BBQyhQz7.js} +7 -7
- package/dist/web/server/assets/{agents-Co6S2Ml9.js → agents-Bgo3LnIL.js} +1 -1
- package/dist/web/server/assets/{agents-BepbikC0.js → agents-CSMQtQCr.js} +1 -1
- package/dist/web/server/assets/{agents-DnUK-7qJ.js → agents-CvU8ljqt.js} +1 -1
- package/dist/web/server/assets/{agents-CKkMouJX.js → agents-DlxkPC-q.js} +1 -1
- package/dist/web/server/assets/{attention-n8edCJBL.js → attention-CHqUjESP.js} +5 -5
- package/dist/web/server/assets/{attention--1dBWt0c.js → attention-rfqLfyDE.js} +1 -1
- package/dist/web/server/assets/{config-BpwsF11b.js → config-CraGjaZB.js} +1 -1
- package/dist/web/server/assets/{config-UHRqSrh4.js → config-DSBJKiDX.js} +7 -7
- package/dist/web/server/assets/{form-Bwsyt9OY.js → form-BGif16IN.js} +2 -2
- package/dist/web/server/assets/{manage-C7ss0xG5.js → manage-CfDQUV7j.js} +1 -1
- package/dist/web/server/assets/{mcp-CUoF4jIO.js → mcp-RKq9Cj-h.js} +6 -6
- package/dist/web/server/assets/{mcp-COn047tO.js → mcp-VCW2SGMk.js} +1 -1
- package/dist/web/server/assets/{parts-B0wbj_yK.js → parts-BpwHijPN.js} +1 -1
- package/dist/web/server/assets/{router-yEsciAts.js → router-BER0FKkT.js} +21 -21
- package/dist/web/server/assets/{routes-BgjikzXy.js → routes-BYmi9O0B.js} +2 -0
- package/dist/web/server/assets/{routes-Bfkccvfb.js → routes-DSIwTrHI.js} +238 -91
- package/dist/web/server/assets/{routes-CjtC0rDs.js → routes-qtTyGHXK.js} +1 -1
- package/dist/web/server/assets/{skills-D5oN5ehC.js → skills-DM_Qcvqk.js} +7 -7
- package/dist/web/server/assets/{skills-DouMCq_2.js → skills-DZI56DdW.js} +1 -1
- package/dist/web/server/assets/{style-BgFXDhAR.js → style-DuiMhwn4.js} +1 -1
- package/dist/web/server/assets/{system-4WV2pOS4.js → system-Bx-_Vfss.js} +1 -1
- package/dist/web/server/assets/{system-DtGHi7X7.js → system-C_kmuned.js} +3 -3
- package/dist/web/server/assets/{teams-BnsbH4YW.js → teams-BL_lLFPd.js} +8 -8
- package/dist/web/server/assets/{teams-Blfyu8ej.js → teams-Bd6J6rHj.js} +1 -1
- package/dist/web/server/assets/{teams-QVxXJfo7.js → teams-CRGLRUp9.js} +1 -1
- package/dist/web/server/assets/{teams-gzY3tOtu.js → teams-fQEKru2G.js} +7 -7
- package/dist/web/server/assets/{telegram-CIbuQ5-U.js → telegram-CpHjomwG.js} +1 -1
- package/dist/web/server/assets/{telegram-Ctj5dqvs.js → telegram-Do0oUOXQ.js} +6 -6
- package/dist/web/server/assets/{tools-x_DQTQtE.js → tools-CMXn8htp.js} +5 -5
- package/dist/web/server/assets/{tools-Dn6RnOFu.js → tools-Ctckgev8.js} +1 -1
- package/dist/web/server/assets/{usage-CeiyPffw.js → usage-DaV-iwEz.js} +1 -1
- package/dist/web/server/assets/{usage-Dsi2V9Wh.js → usage-sZ4SFz36.js} +3 -3
- package/dist/web/server/assets/{welcome-C71pZOQ9.js → welcome-BhfLQBOr.js} +1 -1
- package/dist/web/server/assets/{welcome-A2Koo4HI.js → welcome-Dz5zfvV2.js} +3 -3
- package/dist/web/server/server.js +6 -6
- package/dist/worker.js +71 -16
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/web/client/assets/AddProviderDialog-BsUXLr-m.js +0 -1
- package/dist/web/client/assets/routes-Lj8n-RF7.js +0 -85
- package/dist/web/client/assets/styles-DyFDuWBI.css +0 -2
- package/dist/web/client/assets/telegram-BWfL_OIt.js +0 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../package.json","../src/commands/activity.ts","../../../packages/client/src/index.ts","../src/auth-file.ts","../src/paths.ts","../src/client.ts","../src/command-helpers.ts","../src/columnize.ts","../src/repeatable-args.ts","../src/commands/agent.ts","../src/errors.ts","../src/commands/agent-browser.ts","../src/commands/agent-chat.ts","../src/question-prompt.ts","../src/commands/agent-context.ts","../src/commands/agent-learning.ts","../src/commands/agent-skills.ts","../src/commands/attention.ts","../src/commands/auth.ts","../src/commands/backup.ts","../../daemon/src/core/db/schema.ts","../../daemon/src/core/db/client.ts","../../daemon/src/lib/daemon-liveness.ts","../src/commands/completion.ts","../src/commands/config.ts","../../../packages/api-types/src/entities.ts","../../../packages/api-types/src/git-review.ts","../../../packages/api-types/src/mcp-presets.ts","../../../packages/api-types/src/profiles.ts","../../../packages/api-types/src/results.ts","../../../packages/api-types/src/usage.ts","../src/commands/conversation.ts","../src/commands/dashboard.ts","../src/commands/serve.ts","../src/commands/doctor.ts","../src/commands/inbox.ts","../src/commands/login.ts","../src/commands/mcp.ts","../src/commands/memory.ts","../src/commands/notification.ts","../src/commands/profile.ts","../src/commands/provider.ts","../src/commands/question.ts","../src/commands/queue.ts","../src/commands/result.ts","../src/commands/send.ts","../src/commands/session.ts","../src/commands/skill.ts","../src/commands/team.ts","../src/commands/team-environment.ts","../src/commands/team-messages.ts","../src/commands/team-policy.ts","../src/commands/team-review.ts","../src/commands/team-today.ts","../src/commands/team-template.ts","../src/commands/telegram.ts","../src/commands/token.ts","../src/commands/trigger.ts","../src/commands/uninstall.ts","../src/commands/usage.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage } from 'citty'\nimport pkg from '../package.json' with { type: 'json' }\nimport { activityCommand } from './commands/activity.ts'\nimport { agentCommand } from './commands/agent.ts'\nimport { attentionCommand } from './commands/attention.ts'\nimport { authCommand } from './commands/auth.ts'\nimport { backupCommand } from './commands/backup.ts'\nimport { completionCommand } from './commands/completion.ts'\nimport { configCommand } from './commands/config.ts'\nimport { conversationCommand } from './commands/conversation.ts'\nimport { dashboardCommand } from './commands/dashboard.ts'\nimport { doctorCommand } from './commands/doctor.ts'\nimport { inboxCommand } from './commands/inbox.ts'\nimport { loginCommand } from './commands/login.ts'\nimport { mcpCommand } from './commands/mcp.ts'\nimport { memoryCommand } from './commands/memory.ts'\nimport { notificationCommand } from './commands/notification.ts'\nimport { profileCommand } from './commands/profile.ts'\nimport { providerCommand } from './commands/provider.ts'\nimport { questionCommand } from './commands/question.ts'\nimport { queueCommand } from './commands/queue.ts'\nimport { resultCommand } from './commands/result.ts'\nimport { sendCommand } from './commands/send.ts'\nimport { serveCommand } from './commands/serve.ts'\nimport { sessionCommand } from './commands/session.ts'\nimport { skillCommand } from './commands/skill.ts'\nimport { teamCommand } from './commands/team.ts'\nimport { teamTemplateCommand } from './commands/team-template.ts'\nimport { telegramCommand } from './commands/telegram.ts'\nimport { tokenCommand } from './commands/token.ts'\nimport { triggerCommand } from './commands/trigger.ts'\nimport { uninstallCommand } from './commands/uninstall.ts'\nimport { usageCommand } from './commands/usage.ts'\nimport { exitCodeForError, printError } from './errors.ts'\n\nconst VERSION = pkg.version\n\nconst main = defineCommand({\n meta: {\n name: 'bazilion',\n version: VERSION,\n description: 'Multi-agent runtime',\n },\n subCommands: {\n login: loginCommand,\n profile: profileCommand,\n team: teamCommand,\n 'team-template': teamTemplateCommand,\n agent: agentCommand,\n activity: activityCommand,\n attention: attentionCommand,\n usage: usageCommand,\n result: resultCommand,\n conversation: conversationCommand,\n queue: queueCommand,\n question: questionCommand,\n notification: notificationCommand,\n skill: skillCommand,\n memory: memoryCommand,\n mcp: mcpCommand,\n provider: providerCommand,\n send: sendCommand,\n session: sessionCommand,\n inbox: inboxCommand,\n config: configCommand,\n serve: serveCommand,\n dashboard: dashboardCommand,\n doctor: doctorCommand,\n backup: backupCommand,\n trigger: triggerCommand,\n token: tokenCommand,\n auth: authCommand,\n telegram: telegramCommand,\n uninstall: uninstallCommand,\n },\n})\n\n// Mutate the command tree after definition so `completion` can introspect its\n// own siblings without a circular import. Cast is safe — citty keeps the\n// object reference on `main` after defineCommand, and we know its shape.\n;(main.subCommands as Record<string, unknown>).completion = completionCommand(main as never)\n\n// Resolve `bazilion <a> <b> --help` to the right subcommand for showUsage.\n// citty's built-in version is private, so we re-implement it for plain\n// subCommands objects (the shape we use throughout the tree).\ntype AnyCmd = Parameters<typeof showUsage>[0]\ntype CmdWithSubs = AnyCmd & { subCommands?: Record<string, AnyCmd> }\nasync function resolveSubCommand(\n cmd: CmdWithSubs,\n rawArgs: string[],\n parent?: AnyCmd,\n): Promise<[AnyCmd, AnyCmd | undefined]> {\n const subs = cmd.subCommands\n if (subs && Object.keys(subs).length > 0) {\n const idx = rawArgs.findIndex((a) => !a.startsWith('-'))\n const name = idx >= 0 ? rawArgs[idx] : undefined\n if (name && subs[name]) {\n return resolveSubCommand(subs[name] as CmdWithSubs, rawArgs.slice(idx + 1), cmd)\n }\n }\n return [cmd, parent]\n}\n\n// Top-level `bazilion --help` groups the commands by their own descriptions; `bazilion <command>\n// --help` uses citty's renderer. A command missing from these groups is listed under \"other\".\nconst HELP_GROUPS: Record<string, string[]> = {\n setup: ['serve', 'dashboard', 'doctor', 'backup', 'uninstall'],\n catalog: ['profile', 'team-template', 'team', 'skill', 'provider', 'config', 'auth', 'mcp'],\n agents: [\n 'attention',\n 'usage',\n 'agent',\n 'conversation',\n 'result',\n 'queue',\n 'question',\n 'memory',\n 'send',\n 'inbox',\n 'trigger',\n ],\n integrations: ['telegram', 'notification'],\n remote: ['login', 'token', 'session'],\n shell: ['completion'],\n}\n\nfunction printTopLevelHelp(): void {\n const commands = main.subCommands as Record<string, { meta?: { description?: string } }>\n const grouped = new Set(Object.values(HELP_GROUPS).flat())\n const other = Object.keys(commands).filter((name) => !grouped.has(name))\n console.log(`Multi-agent runtime (bazilion v${VERSION})`)\n console.log('')\n console.log('USAGE bazilion <command> [args]')\n console.log('')\n for (const [title, names] of Object.entries({ ...HELP_GROUPS, other })) {\n const listed = names.filter((name) => commands[name])\n if (listed.length === 0) continue\n console.log(` ${title}`)\n for (const name of listed) {\n console.log(` ${name.padEnd(15)}${commands[name]?.meta?.description ?? ''}`)\n }\n console.log('')\n }\n console.log('Use `bazilion <command> --help` for more information about a command.')\n}\n\nasync function entry(): Promise<void> {\n // package.json `engines` is the Node contract; this only turns another Node into a clear message.\n const [major = 0, minor = 0, patch = 0] = process.versions.node.split('.').map(Number)\n if (major !== 26 || minor < 12 || (minor === 12 && patch < 1)) {\n console.error(`bazilion requires Node.js ^26.12.1; this is ${process.versions.node}.`)\n process.exit(1)\n }\n const rawArgs = process.argv.slice(2)\n try {\n if (rawArgs.includes('--help') || rawArgs.includes('-h')) {\n // For the top-level `bazilion --help`, render our grouped layout.\n // Subcommand help still goes through citty (preserves native formatting).\n const firstPositional = rawArgs.find((a) => !a.startsWith('-'))\n if (!firstPositional) {\n printTopLevelHelp()\n process.exit(0)\n }\n const [target, parent] = await resolveSubCommand(main as CmdWithSubs, rawArgs)\n await showUsage(target, parent)\n process.exit(0)\n }\n if (rawArgs.length === 1 && (rawArgs[0] === '--version' || rawArgs[0] === '-v')) {\n console.log(VERSION)\n return\n }\n await runCommand(main, { rawArgs })\n } catch (err) {\n printError(err)\n process.exit(exitCodeForError(err))\n }\n}\n\nentry()\n","{\n \"name\": \"bazilion\",\n \"version\": \"0.58.2\",\n \"description\": \"Multi-agent runtime CLI — spawn LLM agents, manage profiles/teams/skills, and run the local daemon.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rullopat/bazilion.git\",\n \"directory\": \"apps/cli\"\n },\n \"homepage\": \"https://bazilion.com\",\n \"bugs\": {\n \"url\": \"https://github.com/rullopat/bazilion/issues\"\n },\n \"keywords\": [\n \"agent\",\n \"agents\",\n \"ai\",\n \"cli\",\n \"daemon\",\n \"llm\",\n \"local-first\",\n \"multi-agent\",\n \"openclaw\",\n \"skills\"\n ],\n \"type\": \"module\",\n \"bin\": {\n \"bazilion\": \"./dist/cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"pnpm --filter @bazilion/web build && tsup\"\n },\n \"engines\": {\n \"node\": \"^26.12.1\"\n },\n \"dependencies\": {\n \"@earendil-works/pi-ai\": \"1.6.0\",\n \"@earendil-works/pi-coding-agent\": \"1.6.0\",\n \"@earendil-works/pi-mcp\": \"1.6.0\",\n \"@hono/node-server\": \"^2.0.6\",\n \"@mozilla/readability\": \"^0.6.0\",\n \"@tanstack/react-router\": \"1.170.18\",\n \"@tobilu/qmd\": \"^2.5.3\",\n \"@xyflow/react\": \"^12.11.2\",\n \"adm-zip\": \"^0.5.17\",\n \"age-encryption\": \"0.3.0\",\n \"citty\": \"^0.2.2\",\n \"clsx\": \"^2.1.1\",\n \"dompurify\": \"^3.4.11\",\n \"grammy\": \"^1.44.0\",\n \"hono\": \"^4.12.26\",\n \"linkedom\": \"^0.18.12\",\n \"lucide-react\": \"^1.21.0\",\n \"marked\": \"^18.0.5\",\n \"playwright\": \"^1.61.0\",\n \"radix-ui\": \"^1.6.0\",\n \"react\": \"^19.2.7\",\n \"react-dom\": \"^19.2.7\",\n \"tailwind-merge\": \"^3.6.0\",\n \"tar\": \"^7.5.16\",\n \"typebox\": \"^1.3.0\",\n \"undici\": \"^8.5.0\",\n \"yaml\": \"^2.9.0\"\n },\n \"devDependencies\": {\n \"@bazilion/api-types\": \"workspace:*\",\n \"@bazilion/client\": \"workspace:*\",\n \"@types/adm-zip\": \"^0.5.8\"\n }\n}\n","import type { ActivityResponse, Agent, AgentActivity } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, terminalSafe } from '../command-helpers.ts'\n\n// `bazilion activity`: what every Agent is doing and what waits for you, as the web's rail shows it.\n\n/** One line for an Agent's state; what needs the operator comes first. */\nexport function activityState(activity: AgentActivity): string {\n if (activity.questions > 0) {\n return `waiting for you: ${activity.questions} question${activity.questions === 1 ? '' : 's'}`\n }\n if (activity.approvals > 0) {\n return `waiting for you: ${activity.approvals} command${activity.approvals === 1 ? '' : 's'} to approve`\n }\n if (activity.working) {\n if (!activity.step) return 'working'\n return activity.step.target\n ? `working: ${activity.step.tool} ${activity.step.target}`\n : `working: ${activity.step.tool}`\n }\n if (activity.queuePaused) return 'follow-ups paused'\n return 'idle'\n}\n\nexport const activityCommand = defineCommand({\n meta: {\n name: 'activity',\n description: 'Show what every Agent is doing and what waits for you',\n },\n args: {\n team: { type: 'string', description: 'Only Agents of this Team' },\n json: jsonFlag,\n },\n async run({ args }) {\n const client = createClient()\n const [activity, agents] = await Promise.all([\n client.get<ActivityResponse>('/api/activity'),\n client.get<Agent[]>('/api/agents'),\n ])\n const shown = activity.agents.filter((entry) => !args.team || entry.teamId === args.team)\n if (args.json) return printJson({ agents: shown })\n const names = new Map(agents.map((agent) => [agent.id, agent.name]))\n printRows(\n shown.map((entry) => [\n names.get(entry.agentId) ?? entry.agentId.slice(0, 8),\n entry.teamId,\n terminalSafe(activityState(entry)),\n entry.lastActivityAt ? new Date(entry.lastActivityAt).toISOString() : '',\n entry.results ? `${entry.results} file${entry.results === 1 ? '' : 's'}` : '',\n ]),\n '(no agents)',\n )\n },\n})\n","// HTTP client for the daemon (or the web gateway in front of it), used by the CLI and by the web's\n// server-side loaders.\n\nimport type {\n AgentQuestionAnswer,\n AgentQuestionListResponse,\n ApiError,\n BrowserStatus,\n CodingEnvironmentStatus,\n EnqueueUserInput,\n NotificationSettings,\n NotificationSettingsResponse,\n ReviewFeedbackRequest,\n ReviewFeedbackResponse,\n TeamCodingEnvironment,\n TeamReviewResponse,\n UserQueueItem,\n UserQueueListResponse,\n} from '@bazilion/api-types'\n\nexport interface ClientConfig {\n serverUrl: string\n /** Sent as `Authorization: Bearer <token>`; null sends none. */\n token: string | null\n /** Extra request headers, e.g. the session cookie the web's loaders forward. */\n headers?: Record<string, string>\n}\n\nexport class ApiClientError extends Error {\n status: number\n body: ApiError\n constructor(status: number, body: ApiError) {\n super(`${status}: ${body.error}`)\n this.status = status\n this.body = body\n }\n}\n\n/** A non-2xx response, carrying its status and error body. */\nasync function failure(res: Response): Promise<ApiClientError> {\n const body = (await res.json().catch(() => ({ error: res.statusText }))) as ApiError\n return new ApiClientError(res.status, body)\n}\n\nexport function createClient(cfg: ClientConfig) {\n const authHeaders: Record<string, string> = {\n ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}),\n ...cfg.headers,\n }\n\n /** A JSON request; the body, when given, is sent as JSON. */\n function send(method: string, path: string, body?: unknown): Promise<Response> {\n return fetch(`${cfg.serverUrl}${path}`, {\n method,\n headers:\n body === undefined ? authHeaders : { ...authHeaders, 'content-type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n }\n\n async function json<T>(res: Response): Promise<T> {\n if (!res.ok) throw await failure(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n return json<T>(await send(method, path, body))\n }\n\n /** Multipart POST: fetch sets the multipart content-type with its boundary itself. */\n async function postMultipart<T>(path: string, form: FormData): Promise<T> {\n return json<T>(\n await fetch(`${cfg.serverUrl}${path}`, { method: 'POST', headers: authHeaders, body: form }),\n )\n }\n\n /** An NDJSON response, one value per line. */\n async function* stream<T>(method: string, path: string, body?: unknown): AsyncGenerator<T> {\n const res = await send(method, path, body)\n if (!res.ok || !res.body) throw await failure(res)\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n if (line.trim()) yield JSON.parse(line) as T\n }\n }\n if (buffer.trim()) yield JSON.parse(buffer) as T\n }\n\n async function binary(path: string): Promise<Uint8Array> {\n const res = await fetch(`${cfg.serverUrl}${path}`, { headers: authHeaders, redirect: 'error' })\n if (!res.ok) throw await failure(res)\n return new Uint8Array(await res.arrayBuffer())\n }\n\n return {\n codingEnvironment: {\n show: (teamId: string) =>\n request<CodingEnvironmentStatus>(\n 'GET',\n `/api/teams/${encodeURIComponent(teamId)}/coding-environment`,\n ),\n set: (teamId: string, input: TeamCodingEnvironment) =>\n request<CodingEnvironmentStatus>(\n 'PUT',\n `/api/teams/${encodeURIComponent(teamId)}/coding-environment`,\n input,\n ),\n },\n /** Git change review: changes since a base, diffs, who wrote them, and review feedback. */\n repositoryReview: (teamId: string) => {\n const base = `/api/teams/${encodeURIComponent(teamId)}/review`\n return {\n changes: (\n options: { base?: string; patches?: boolean; path?: string; authors?: boolean } = {},\n ): Promise<TeamReviewResponse> => {\n const params = new URLSearchParams()\n if (options.base !== undefined) params.set('base', options.base)\n if (options.patches) params.set('patches', '1')\n if (options.path !== undefined) params.set('path', options.path)\n if (options.authors) params.set('authors', '1')\n const suffix = params.size ? `?${params}` : ''\n return request('GET', `${base}${suffix}`)\n },\n feedback: (input: ReviewFeedbackRequest): Promise<ReviewFeedbackResponse> =>\n request('POST', `${base}/feedback`, input),\n }\n },\n notifications: {\n settings: () => request<NotificationSettingsResponse>('GET', '/api/notifications'),\n configure: (input: NotificationSettings) =>\n request<NotificationSettingsResponse>('PUT', '/api/notifications', input),\n },\n questions: (agentId: string) => {\n const base = `/api/agents/${encodeURIComponent(agentId)}/questions`\n return {\n list: () => request<AgentQuestionListResponse>('GET', base),\n answer: (id: string, answer: AgentQuestionAnswer) =>\n request<{ ok: true }>('POST', `${base}/${encodeURIComponent(id)}/answer`, { answer }),\n }\n },\n queue: (agentId: string) => {\n const base = `/api/agents/${encodeURIComponent(agentId)}/queue`\n const item = (id: string) => `${base}/${encodeURIComponent(id)}`\n return {\n list: () => request<UserQueueListResponse>('GET', base),\n enqueue: (input: EnqueueUserInput) => request<UserQueueItem>('POST', base, input),\n edit: (id: string, message: string) =>\n request<UserQueueItem>('PATCH', item(id), { message }),\n remove: (id: string) => request<UserQueueItem>('DELETE', item(id)),\n pause: (paused: boolean) =>\n request<{ paused: boolean }>('POST', `${base}/control`, { paused }),\n }\n },\n /**\n * Managed browser controls. Status never launches; stop keeps the\n * profile; reset deletes it (cookies, logins), so callers confirm first.\n */\n getAgentBrowser: (agentId: string) =>\n request<BrowserStatus>('GET', `/api/agents/${encodeURIComponent(agentId)}/browser`),\n stopAgentBrowser: (agentId: string) =>\n request<void>('POST', `/api/agents/${encodeURIComponent(agentId)}/browser/stop`),\n resetAgentBrowser: (agentId: string) =>\n request<void>('DELETE', `/api/agents/${encodeURIComponent(agentId)}/browser/profile`),\n binary,\n get: <T>(p: string) => request<T>('GET', p),\n post: <T>(p: string, b?: unknown) => request<T>('POST', p, b),\n postMultipart,\n put: <T>(p: string, b?: unknown) => request<T>('PUT', p, b),\n patch: <T>(p: string, b?: unknown) => request<T>('PATCH', p, b),\n del: <T>(p: string) => request<T>('DELETE', p),\n stream,\n }\n}\n\nexport type BazilionClient = ReturnType<typeof createClient>\n","import { existsSync, readFileSync } from 'node:fs'\n\nexport interface AuthFile {\n token: string\n remote?: { server: string; token: string } | null\n}\n\nexport function readAuthFile(authFile: string): AuthFile {\n if (!existsSync(authFile)) {\n throw new Error(`${authFile} not found. Start the daemon with \\`bazilion serve\\` first.`)\n }\n const raw = readFileSync(authFile, 'utf8')\n const parsed = JSON.parse(raw) as Partial<AuthFile>\n if (typeof parsed.token !== 'string' || !parsed.token) {\n throw new Error(`${authFile} is missing the \"token\" field`)\n }\n return { token: parsed.token, remote: parsed.remote ?? null }\n}\n","import { realpathSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, dirname, join, resolve } from 'node:path'\n\ninterface CliPaths {\n home: string\n authFile: string\n}\n\nexport function resolveCliPaths(home?: string): CliPaths {\n // The daemon's resolvePaths (apps/daemon/src/core/paths.ts) spells the home the same way.\n const root = canonicalPath(requestedHome(home))\n return { home: root, authFile: join(root, 'auth.json') }\n}\n\n/** The home as given (`--home`, BAZILION_HOME or ~/.bazilion), before symlinks are resolved. */\nexport function requestedHome(home?: string): string {\n return resolve(home ?? process.env.BAZILION_HOME ?? join(homedir(), '.bazilion'))\n}\n\n/** Absolute path with symlinks resolved in every existing segment; a missing tail is kept. */\nexport function canonicalPath(path: string): string {\n let resolved = resolve(path)\n const unresolvedTail: string[] = []\n while (true) {\n try {\n resolved = realpathSync(resolved)\n break\n } catch {\n const parent = dirname(resolved)\n if (parent === resolved) break // reached the filesystem root\n unresolvedTail.unshift(basename(resolved))\n resolved = parent\n }\n }\n return join(resolved, ...unresolvedTail)\n}\n","import { type BazilionClient, createClient as createPackageClient } from '@bazilion/client'\nimport { readAuthFile } from './auth-file.ts'\nimport { resolveCliPaths } from './paths.ts'\n\nexport type { BazilionClient } from '@bazilion/client'\nexport { ApiClientError } from '@bazilion/client'\n\ninterface ClientConfig {\n serverUrl: string\n token: string\n}\n\nexport function loadClientConfig(): ClientConfig {\n const envUrl = process.env.BAZILION_SERVER\n const envToken = process.env.BAZILION_TOKEN\n if (envUrl && envToken) return { serverUrl: envUrl, token: envToken }\n\n const paths = resolveCliPaths()\n const auth = readAuthFile(paths.authFile)\n // `bazilion login` writes `remote`; when present it targets another host\n // (Tailscale, LAN). Env vars still win so CI / ad-hoc invocations can\n // override without editing auth.json.\n if (auth.remote?.server && auth.remote.token) {\n return {\n serverUrl: envUrl ?? auth.remote.server,\n token: auth.remote.token,\n }\n }\n return {\n serverUrl: envUrl ?? 'http://127.0.0.1:4321',\n token: auth.token,\n }\n}\n\nexport function createClient(): BazilionClient {\n const { serverUrl, token } = loadClientConfig()\n return createPackageClient({ serverUrl, token })\n}\n","import { readFileSync } from 'node:fs'\nimport { basename, extname } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport type { Attachment, SkillScanFinding } from '@bazilion/api-types'\nimport { columnize } from './columnize.ts'\nimport { collectFlagValues } from './repeatable-args.ts'\n\n/** A required positional argument. */\nexport function positional(description: string) {\n return { type: 'positional', required: true, description } as const\n}\n\nexport const agentArg = positional('Agent id or prefix')\nexport const teamArg = positional('Team slug')\nexport const jsonFlag = { type: 'boolean', description: 'Emit JSON' } as const\n\n/** A daemon API path from its segments, each URL-encoded: `apiPath('agents', id, 'skills')`. */\nexport function apiPath(...segments: string[]): string {\n return `/api/${segments.map(encodeURIComponent).join('/')}`\n}\n\nexport function printJson(value: unknown): void {\n console.log(JSON.stringify(value, null, 2))\n}\n\n/** Print rows as aligned columns, or `empty` when there are none. */\nexport function printRows(rows: string[][], empty: string): void {\n if (rows.length === 0) console.log(empty)\n for (const line of columnize(rows)) console.log(line)\n}\n\n/** Ask on stdin and return the trimmed answer; the end of input is an empty answer. */\nexport function ask(question: string): Promise<string> {\n process.stdout.write(question)\n const input = createInterface({ input: process.stdin })\n return new Promise((resolve) => {\n let answer = ''\n input.once('line', (line) => {\n answer = line\n input.close()\n })\n input.once('close', () => resolve(answer.trim()))\n })\n}\n\n/**\n * Ask for a secret. On a terminal nothing typed or pasted is echoed; piped input is read as one\n * line, so `bazilion provider connect anthropic < key.txt` works too.\n */\nexport function askSecret(question: string): Promise<string> {\n const { stdin, stdout } = process\n if (!stdin.isTTY) return ask(question)\n stdout.write(question)\n return new Promise((resolve, reject) => {\n let value = ''\n const finish = (error?: Error) => {\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n stdout.write('\\n')\n if (error) reject(error)\n else resolve(value.trim())\n }\n const onData = (chunk: Buffer | string) => {\n for (const character of String(chunk)) {\n if (character === '\\r' || character === '\\n') return finish()\n // Ctrl-C and Ctrl-D leave without a key.\n if (character === '\\u0003' || character === '\\u0004') return finish(new Error('cancelled'))\n if (character === '\\u007f' || character === '\\b') value = value.slice(0, -1)\n else if (character >= ' ') value += character\n }\n }\n stdin.setRawMode(true)\n stdin.resume()\n stdin.on('data', onData)\n })\n}\n\n/** Ask a yes/no question; only y or yes confirms. */\nexport async function confirm(question: string): Promise<boolean> {\n return /^y(es)?$/i.test(await ask(`${question} [y/N] `))\n}\n\n/** Show control characters (escape sequences, carriage returns, ...) as `\\xNN`. */\nexport function terminalSafe(value: string, keepTabs = false): string {\n let safe = ''\n for (const character of value) {\n const code = character.charCodeAt(0)\n const isControl =\n (code <= 31 && code !== 10 && !(keepTabs && code === 9)) || (code >= 127 && code <= 159)\n safe += isControl ? `\\\\x${code.toString(16).padStart(2, '0')}` : character\n }\n return safe\n}\n\nconst IMAGE_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n}\n\nconst FILE_TYPES: Record<string, string> = {\n '.pdf': 'application/pdf',\n '.txt': 'text/plain',\n '.md': 'text/markdown',\n '.csv': 'text/csv',\n '.json': 'application/json',\n '.html': 'text/html',\n '.zip': 'application/zip',\n}\n\nfunction attachment(path: string, mimeType: string): Attachment {\n return { name: basename(path), mimeType, data: readFileSync(path).toString('base64') }\n}\n\n/**\n * The repeatable `--image` and `--file` flags as attachments: images go to the model, files are\n * stored for the Agent to read. citty keeps only the last value of a repeated flag, so the values\n * come from the raw arguments.\n */\nexport function loadAttachments(rawArgs: string[]): Attachment[] {\n const images = collectFlagValues(rawArgs, 'image').map((path) => {\n const mimeType = IMAGE_TYPES[extname(path).toLowerCase()]\n if (!mimeType) throw new Error(`unsupported image type: ${path} (png/jpg/gif/webp only)`)\n return attachment(path, mimeType)\n })\n const files = collectFlagValues(rawArgs, 'file').map((path) =>\n attachment(path, FILE_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'),\n )\n return [...images, ...files]\n}\n\nexport function findingLines(findings: SkillScanFinding[]): string[] {\n return findings.map(\n (f) => `${f.severity}: ${f.code}${f.line ? ` line ${f.line}` : ''} - ${f.message}`,\n )\n}\n","/**\n * Render `rows` as space-aligned columns. All rows must have the same column\n * count; empty cells are treated as `\"\"` for width purposes. Column spacing is\n * two spaces — wider than a tab, tighter than tabular CSV tooling expects.\n *\n * Used by list commands so `status` / `kind` / `name` columns don't jump when\n * one row is `idle` (4) and another is `archived` (8). Does not truncate —\n * long cells win the column width. Callers that want a bounded width should\n * slice before passing.\n */\nexport function columnize(rows: string[][], gap = ' '): string[] {\n if (rows.length === 0) return []\n const colCount = rows[0]?.length ?? 0\n const widths: number[] = new Array<number>(colCount).fill(0)\n for (const row of rows) {\n for (let i = 0; i < colCount; i++) {\n const cell = row[i] ?? ''\n const prev = widths[i] ?? 0\n if (cell.length > prev) widths[i] = cell.length\n }\n }\n return rows.map((row) =>\n row\n .map((cell, i) => {\n // Don't pad the last column — trailing whitespace is pointless and\n // breaks `| wc`-style pipes.\n if (i === colCount - 1) return cell\n return (cell ?? '').padEnd(widths[i] ?? 0)\n })\n .join(gap),\n )\n}\n","/**\n * Every value of a repeatable flag (`--image a --image b`), read from the raw arguments: citty\n * parses a repeated flag last-wins. Values are taken as given, never split on commas, so paths may\n * contain them. An option value that is itself the flag name would be misread.\n */\nexport function collectFlagValues(rawArgs: readonly string[], name: string): string[] {\n const values: string[] = []\n const long = `--${name}`\n for (let i = 0; i < rawArgs.length; i++) {\n const arg = rawArgs[i]\n if (arg === undefined) continue\n // Everything after `--` is positional by convention, never a flag.\n if (arg === '--') break\n if (arg === long) {\n const next = rawArgs[i + 1]\n if (next !== undefined && next !== '--') {\n values.push(next)\n i++\n }\n continue\n }\n if (arg.startsWith(`${long}=`)) {\n const value = arg.slice(long.length + 1)\n if (value.length > 0) values.push(value)\n }\n }\n return values\n}\n","import type { Agent, MoveAgentRequest, ResolvedAgent, SpawnAgentRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, printRows, teamArg } from '../command-helpers.ts'\nimport { UsageError } from '../errors.ts'\nimport { browserCommand } from './agent-browser.ts'\nimport { chatCommand } from './agent-chat.ts'\nimport { contextCommands } from './agent-context.ts'\nimport { learningCommands } from './agent-learning.ts'\nimport { agentSkillCommand } from './agent-skills.ts'\n\nconst spawnCmd = defineCommand({\n meta: { name: 'spawn', description: 'Spawn an agent from a profile into a team' },\n args: {\n profile: { type: 'string', required: true, description: 'Profile id' },\n name: { type: 'string', description: 'Agent name (defaults to profile name)' },\n team: { type: 'string', description: \"Team to join (defaults to 'default')\" },\n model: { type: 'string', description: 'Override profile default model' },\n reasoning: {\n type: 'string',\n description: 'Reasoning level: off|minimal|low|medium|high|xhigh (default: medium)',\n },\n role: {\n type: 'string',\n description:\n 'What it is for: it starts knowing its job, without the get-to-know questions of a first conversation',\n },\n },\n async run({ args }) {\n const body: SpawnAgentRequest = {\n profileId: args.profile,\n name: args.name,\n model: args.model,\n reasoningLevel: args.reasoning as SpawnAgentRequest['reasoningLevel'],\n teamId: args.team ?? 'default',\n ...(args.role ? { role: args.role } : {}),\n }\n const { agent } = await createClient().post<{ agent: Agent }>('/api/agents', body)\n console.log(`spawned agent ${agent.id} (${agent.name})`)\n console.log(`dir: ${agent.dir}`)\n },\n})\n\nconst editCmd = defineCommand({\n meta: {\n name: 'edit',\n description: 'Edit agent settings (name, model override, reasoning level, telegram mirror)',\n },\n args: {\n id: agentArg,\n name: { type: 'string', description: 'Rename the agent' },\n model: { type: 'string', description: 'Set model override (use --model \"\" to clear)' },\n reasoning: {\n type: 'string',\n description: 'Reasoning level: off|minimal|low|medium|high|xhigh',\n },\n mirror: { type: 'string', description: 'Telegram mirror verbosity: minimal|verbose' },\n 'topic-icon': {\n type: 'string',\n description: 'Telegram topic emoji (e.g. 📚). Use --topic-icon \"\" to clear.',\n },\n },\n async run({ args }) {\n const body: Record<string, unknown> = {}\n if (args.name !== undefined) body.name = args.name\n if (args.model !== undefined) body.modelOverride = args.model === '' ? null : args.model\n if (args.reasoning !== undefined) body.reasoningLevel = args.reasoning\n if (args.mirror !== undefined) {\n if (args.mirror !== 'minimal' && args.mirror !== 'verbose') {\n throw new UsageError(\"--mirror must be 'minimal' or 'verbose'\")\n }\n body.telegramMirrorMode = args.mirror\n }\n if (args['topic-icon'] !== undefined) {\n body.telegramIconEmoji = args['topic-icon'] === '' ? null : args['topic-icon']\n }\n if (Object.keys(body).length === 0) {\n throw new UsageError(\n 'specify at least one of --name, --model, --reasoning, --mirror, --topic-icon',\n )\n }\n const agent = await createClient().patch<Agent>(apiPath('agents', args.id), body)\n console.log(`updated agent ${agent.id} (${agent.name})`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List agents' },\n args: {\n all: { type: 'boolean', description: 'Include archived agents' },\n long: { type: 'boolean', alias: 'l', description: 'Show profile + full UUID columns' },\n },\n async run({ args }) {\n const list = await createClient().get<Agent[]>(\n `/api/agents${args.all ? '?includeArchived=true' : ''}`,\n )\n printRows(\n list.map((a) =>\n // Every command accepts an id prefix, so the short listing shows the first 8 characters.\n args.long ? [a.id, a.status, a.name, a.profileId] : [a.id.slice(0, 8), a.status, a.name],\n ),\n '(no agents)',\n )\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show agent details' },\n args: { id: agentArg },\n async run({ args }) {\n const r = await createClient().get<ResolvedAgent>(apiPath('agents', args.id))\n console.log(`# ${r.agent.id}`)\n console.log(`name: ${r.agent.name}`)\n console.log(`status: ${r.agent.status}`)\n console.log(`profile: ${r.profile.id}`)\n console.log(`model: ${r.model}`)\n console.log(`dir: ${r.agent.dir}`)\n console.log(`team: ${r.team.id} ${r.team.path}`)\n console.log('skills:')\n if (r.skills.length === 0) console.log(' (none)')\n for (const s of r.skills) console.log(` ${s}`)\n },\n})\n\nconst archiveCmd = defineCommand({\n meta: { name: 'archive', description: 'Archive an agent' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().post(apiPath('agents', args.id, 'archive'))\n console.log(`archived agent ${args.id}`)\n },\n})\n\nconst unarchiveCmd = defineCommand({\n meta: { name: 'unarchive', description: 'Restore an archived agent to idle' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().post(apiPath('agents', args.id, 'unarchive'))\n console.log(`unarchived agent ${args.id}`)\n },\n})\n\nconst deleteCmd = defineCommand({\n meta: { name: 'delete', description: 'Permanently delete an agent and its data' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.id))\n console.log(`deleted agent ${args.id}`)\n },\n})\n\nconst cancelCmd = defineCommand({\n meta: {\n name: 'cancel',\n description: \"Abort the agent's running turn; waiting follow-ups are paused\",\n },\n args: { id: agentArg },\n async run({ args }) {\n const { cancelled, queuePaused } = await createClient().post<{\n cancelled: boolean\n queuePaused: boolean\n }>(apiPath('agents', args.id, 'cancel'))\n if (cancelled) console.log(`cancelled active turn for ${args.id}`)\n if (queuePaused) {\n console.log(`follow-up queue paused; resume it with: bazilion queue resume ${args.id}`)\n }\n },\n})\n\nconst moveCmd = defineCommand({\n meta: { name: 'move', description: 'Move an agent to a different team' },\n args: { agent: agentArg, team: teamArg },\n async run({ args }) {\n const body: MoveAgentRequest = { teamId: args.team }\n await createClient().patch(apiPath('agents', args.agent, 'team'), body)\n console.log(`moved ${args.agent} to team ${args.team}`)\n },\n})\n\nexport const agentCommand = defineCommand({\n meta: { name: 'agent', description: 'Manage agent instances' },\n subCommands: {\n spawn: spawnCmd,\n list: listCmd,\n show: showCmd,\n edit: editCmd,\n archive: archiveCmd,\n unarchive: unarchiveCmd,\n delete: deleteCmd,\n chat: chatCommand,\n ...contextCommands,\n cancel: cancelCmd,\n ...learningCommands,\n skill: agentSkillCommand,\n move: moveCmd,\n browser: browserCommand,\n },\n})\n","import { ApiClientError } from './client.ts'\nimport { findingLines } from './command-helpers.ts'\n\n/** A mistake in the command line itself: it exits 2, like a request the daemon finds invalid. */\nexport class UsageError extends Error {}\n\n/**\n * Rethrow a blocked skill scan as one error listing the findings and the flag that confirms them;\n * any other failure is rethrown as it is.\n */\nexport function explainScanBlock(confirmFlag: string): (err: unknown) => never {\n return (err) => {\n if (!(err instanceof ApiClientError) || err.body.code !== 'skill_scan_blocked') throw err\n const findings = findingLines(err.body.findings ?? []).map((line) => ` ${line}`)\n throw new Error(\n [\n err.body.error,\n ...(findings.length > 0 ? ['scan findings:', ...findings] : []),\n ` hint: inspect the skill, then rerun with ${confirmFlag} to confirm`,\n ].join('\\n'),\n )\n }\n}\n\n/** Print a failed command's error, with a hint for the common setup mistakes. */\nexport function printError(err: unknown): void {\n if (err instanceof ApiClientError) {\n console.error(`error: ${err.body.error}`)\n if (err.status === 401) {\n console.error(' hint: token mismatch. Check ~/.bazilion/auth.json \"token\"')\n console.error(' or re-run \"bazilion login\" for a remote server.')\n } else if (err.status === 403 && !err.body.code) {\n // A gateway origin/CSRF refusal; domain refusals (a Team Policy denial) carry a code.\n console.error(' hint: the server refused the request. Check that BAZILION_SERVER matches')\n console.error(' the server origin exactly (scheme + host + port).')\n }\n return\n }\n const msg = err instanceof Error ? err.message : String(err)\n console.error(`error: ${msg}`)\n // node's fetch wraps the syscall error, so its code is on `cause`.\n const code = err instanceof Error ? (err as { cause?: { code?: string } }).cause?.code : undefined\n if (code === 'ECONNREFUSED' || /ECONNREFUSED/.test(msg)) {\n console.error(' hint: the bazilion server is not running. Start it with \"bazilion serve\"')\n console.error(' or point BAZILION_SERVER at a running instance.')\n } else if (code === 'ENOTFOUND' || /ENOTFOUND/.test(msg)) {\n console.error(' hint: host not found. Check BAZILION_SERVER / ~/.bazilion/auth.json.')\n }\n}\n\n/** 2: invalid (a usage error, or rejected by the daemon); 3: conflict; 4: not authorized; 1: the rest. */\nexport function exitCodeForError(err: unknown): number {\n if (err instanceof UsageError) return 2\n if (!(err instanceof ApiClientError)) return 1\n if (err.status === 401 || err.status === 403) return 4\n if (err.status === 409) return 3\n return err.status === 400 || err.status === 422 ? 2 : 1\n}\n","import { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, ask, printJson } from '../command-helpers.ts'\n\nconst statusCmd = defineCommand({\n meta: { name: 'status', description: \"Show the agent's browser status (never starts it)\" },\n args: { id: agentArg },\n async run({ args }) {\n printJson(await createClient().getAgentBrowser(args.id))\n },\n})\n\nconst stopCmd = defineCommand({\n meta: { name: 'stop', description: \"Stop the agent's browser (the profile is kept)\" },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().stopAgentBrowser(args.id)\n console.log(`stopped the browser of agent ${args.id} (profile kept)`)\n },\n})\n\nconst resetCmd = defineCommand({\n meta: {\n name: 'reset',\n description: \"Stop the agent's browser and DELETE its profile (cookies, logins)\",\n },\n args: {\n id: agentArg,\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n if (!args.yes) {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw new Error('refusing to reset a browser profile noninteractively without --yes')\n }\n const answer = await ask(\n `This deletes the browser profile of ${args.id} (cookies, logins). Type the agent id to confirm: `,\n )\n if (answer !== args.id) throw new Error('confirmation did not match; nothing was changed')\n }\n await createClient().resetAgentBrowser(args.id)\n console.log(`reset the browser of agent ${args.id}: stopped, profile removed`)\n },\n})\n\nexport const browserCommand = defineCommand({\n meta: { name: 'browser', description: \"The agent's managed browser: status, stop, reset\" },\n subCommands: { status: statusCmd, stop: stopCmd, reset: resetCmd },\n})\n","import { writeFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { stdin, stdout } from 'node:process'\nimport { createInterface, type Interface } from 'node:readline/promises'\nimport type {\n Attachment,\n BashApprovalMode,\n ChatFrame,\n ChatRequest,\n CommandApproval,\n CommandApprovalDecisionRequest,\n ResolvedAgent,\n SessionEvent,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { type BazilionClient, createClient } from '../client.ts'\nimport { agentArg, apiPath, loadAttachments, terminalSafe } from '../command-helpers.ts'\nimport { printError } from '../errors.ts'\nimport { promptForQuestion, type QuestionPrompt } from '../question-prompt.ts'\n\nexport interface PrintState {\n inDeltaStream: boolean\n /** Per running tool call: the complete lines of its live output already printed. */\n progress: Map<string, string>\n}\n\n/**\n * The complete lines of a cumulative live-output tail that were not printed yet. The tail may have\n * slid forward since the last update (the daemon starts a cut tail on a line boundary), so what was\n * printed is matched against its start at each line boundary.\n */\nexport function unprintedProgress(\n printed: string,\n output: string,\n): { complete: string; fresh: string } {\n const complete = output.slice(0, output.lastIndexOf('\\n') + 1)\n for (let start = 0; start < printed.length; ) {\n const rest = printed.slice(start)\n if (complete.startsWith(rest)) return { complete, fresh: complete.slice(rest.length) }\n start = printed.indexOf('\\n', start) + 1\n if (start === 0) break\n }\n return { complete, fresh: complete }\n}\n\ntype CommandApprovalDecision = CommandApprovalDecisionRequest['decision']\n\nexport interface CommandApprovalPrompt {\n question(prompt: string): Promise<string>\n write(line: string): void\n}\n\n/** Only a real terminal can answer while the chat response stream remains open. */\nexport function bashApprovalModeForTty(\n inputIsTty: boolean | undefined,\n outputIsTty: boolean | undefined,\n): BashApprovalMode {\n return inputIsTty && outputIsTty ? 'interactive' : 'auto_deny'\n}\n\n/** Every CLI chat request states whether the caller can answer shell approvals. */\nexport function buildChatRequest(\n message: string,\n attachments: Attachment[] | undefined,\n bashApprovalMode: BashApprovalMode,\n): ChatRequest {\n return {\n message,\n bashApprovalMode,\n ...(attachments && attachments.length > 0 ? { attachments } : {}),\n }\n}\n\n/** Render one pending command; every answer except y/yes denies it. */\nexport async function promptForCommandApproval(\n approval: CommandApproval,\n prompt: CommandApprovalPrompt,\n): Promise<CommandApprovalDecision> {\n // An MCP tool that sends or changes something outside asks the same way as a risky command.\n const tool = approval.tool\n prompt.write(tool ? ' [tool approval required]' : ' [shell command approval required]')\n if (tool) prompt.write(` tool: ${terminalSafe(tool)}`)\n prompt.write(tool ? ' call:' : ' command:')\n for (const line of approval.command.split('\\n')) prompt.write(` ${terminalSafe(line)}`)\n prompt.write(' risks:')\n for (const risk of approval.risks) {\n prompt.write(` - ${terminalSafe(risk.code)}: ${terminalSafe(risk.message)}`)\n }\n try {\n const answer = (\n await prompt.question(\n tool ? ' Allow this call once? [y/N] ' : ' Allow this command once? [y/N] ',\n )\n )\n .trim()\n .toLowerCase()\n return answer === 'y' || answer === 'yes' ? 'allow' : 'deny'\n } catch {\n prompt.write(' [approval input unavailable; denying]')\n return 'deny'\n }\n}\n\n/** Post one decision for a pending approval; without a prompt it is denied at once. */\nexport async function respondToCommandApproval(\n client: { post(path: string, body?: unknown): Promise<unknown> },\n approval: CommandApproval,\n prompt?: CommandApprovalPrompt,\n): Promise<CommandApprovalDecision> {\n const decision = prompt ? await promptForCommandApproval(approval, prompt) : 'deny'\n try {\n await client.post(apiPath('shell-approvals', approval.id), { decision })\n } catch (error) {\n // Decided meanwhile in the web UI or Telegram, or timed out: the turn goes on, and its next\n // frame says how the command was decided.\n if ((error as { status?: number }).status !== 404) throw error\n console.log(` [this ${approval.tool ? 'call' : 'command'} was already decided elsewhere]`)\n }\n return decision\n}\n\nconst APPROVAL_OUTCOMES: Partial<Record<CommandApproval['status'], string>> = {\n allowed: 'allowed',\n denied: 'denied',\n auto_denied: 'auto-denied: non-interactive turn',\n expired: 'approval expired',\n cancelled: 'approval cancelled',\n}\n\n/** How a decided approval is printed: `shell command denied`, `tool call allowed`. */\nfunction approvalOutcome(approval: CommandApproval): string | undefined {\n const outcome = APPROVAL_OUTCOMES[approval.status]\n return outcome && `${approval.tool ? 'tool call' : 'shell command'} ${outcome}`\n}\n\nfunction closeDeltaLine(state: PrintState): void {\n if (!state.inDeltaStream) return\n process.stdout.write('\\n')\n state.inDeltaStream = false\n}\n\n/** Print one chat event. Tool output is shown terminal-safe: it may carry escape sequences. */\nexport function printEvent(e: SessionEvent, state: PrintState): void {\n switch (e.type) {\n case 'assistant_delta':\n process.stdout.write(e.delta)\n state.inDeltaStream = true\n break\n case 'assistant_message':\n // Streamed deltas already printed the text.\n if (state.inDeltaStream) closeDeltaLine(state)\n else console.log(e.text)\n break\n case 'tool_call':\n closeDeltaLine(state)\n console.log(` [tool: ${e.name} ${e.arguments}]`)\n break\n case 'tool_progress': {\n closeDeltaLine(state)\n const { complete, fresh } = unprintedProgress(state.progress.get(e.id) ?? '', e.output)\n state.progress.set(e.id, complete)\n for (const line of fresh.split('\\n').slice(0, -1)) {\n console.log(` | ${terminalSafe(line, true)}`)\n }\n break\n }\n case 'tool_result':\n state.progress.delete(e.id)\n console.log(` [result: ${terminalSafe(e.result.split('\\n')[0]?.slice(0, 100) ?? '', true)}]`)\n break\n case 'tool_error':\n state.progress.delete(e.id)\n console.log(` [tool error: ${e.name} — ${terminalSafe(e.error, true)}]`)\n break\n case 'error':\n closeDeltaLine(state)\n console.log(` [error: ${e.error}]`)\n break\n }\n}\n\n/** Save a file the Agent delivered into the current directory, never over an existing file. */\nasync function saveDeliveredFile(\n client: BazilionClient,\n file: { name: string; mimeType: string; result: { resultId: string } },\n): Promise<void> {\n const out = basename(file.name).replace(/[^\\w.-]/g, '_') || 'file'\n try {\n const bytes = await client.binary(apiPath('results', file.result.resultId, 'download'))\n writeFileSync(out, bytes, { flag: 'wx' })\n console.log(` [file received: saved to ./${out} (${file.mimeType})]`)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n console.log(\n ` [file not written: ./${out} already exists; saved as result ${file.result.resultId} (bazilion result download)]`,\n )\n }\n}\n\ninterface TurnPrompts {\n approval?: CommandApprovalPrompt\n question?: QuestionPrompt\n}\n\nfunction terminalPrompts(rl: Interface): TurnPrompts {\n const write = (line: string) => console.log(line)\n return {\n approval: { question: (text) => rl.question(text), write },\n question: { question: (text, signal) => rl.question(text, { signal }), write },\n }\n}\n\n/** Run one turn and print it as it streams, answering approvals and questions on the way. */\nasync function streamTurn(\n client: BazilionClient,\n agentId: string,\n request: ChatRequest,\n prompts: TurnPrompts = {},\n): Promise<void> {\n const state: PrintState = { inDeltaStream: false, progress: new Map() }\n const answeredApprovals = new Set<string>()\n const askedQuestions = new Set<string>()\n // Only a turn started with a question prompt is offered ask_user.\n const body: ChatRequest = prompts.question ? { ...request, questionMode: 'tty' } : request\n for await (const frame of client.stream<ChatFrame>(\n 'POST',\n apiPath('agents', agentId, 'chat'),\n body,\n )) {\n if (frame.kind === 'fatal') {\n closeDeltaLine(state)\n throw new Error(frame.error)\n }\n if (frame.kind !== 'event') continue\n const event = frame.event\n if (event.type === 'command_approval') {\n closeDeltaLine(state)\n const approval = event.approval\n if (approval.status !== 'pending') {\n const outcome = approvalOutcome(approval)\n if (outcome) console.log(` [${outcome}]`)\n } else if (!answeredApprovals.has(approval.id)) {\n answeredApprovals.add(approval.id)\n await respondToCommandApproval(client, approval, prompts.approval)\n }\n } else if (event.type === 'agent_question') {\n closeDeltaLine(state)\n const item = event.question\n if (!prompts.question || item.agentId !== agentId || askedQuestions.has(item.id)) continue\n askedQuestions.add(item.id)\n const answer = await promptForQuestion(item, prompts.question)\n if (!answer) continue\n await client\n .questions(agentId)\n .answer(item.id, answer)\n .catch((error: unknown) => {\n console.error(\n `Answer not accepted: ${error instanceof Error ? error.message : String(error)}`,\n )\n })\n } else if (event.type === 'file') {\n closeDeltaLine(state)\n await saveDeliveredFile(client, event)\n } else if (event.type !== 'user_message') {\n printEvent(event, state)\n // A turn that failed or was cancelled exits non-zero, so a script can tell it apart.\n if (event.type === 'error') process.exitCode = 1\n }\n }\n}\n\nexport const chatCommand = defineCommand({\n meta: {\n name: 'chat',\n description: 'Send one message to an agent, or one per line of piped input',\n },\n args: {\n id: agentArg,\n message: { type: 'string', description: 'Send a single message and exit (one-shot mode)' },\n image: {\n type: 'string',\n description:\n 'Attach an image file (png/jpg/gif/webp; repeat the flag for more). One-shot mode.',\n },\n file: {\n type: 'string',\n description:\n 'Attach any file — the agent gets a path reference (repeat the flag for more). One-shot mode.',\n },\n },\n async run({ args, rawArgs }) {\n const client = createClient()\n const resolved = await client.get<ResolvedAgent>(apiPath('agents', args.id))\n const mode = bashApprovalModeForTty(stdin.isTTY, stdout.isTTY)\n const attachments = loadAttachments(rawArgs)\n\n if (args.message || attachments.length > 0) {\n // A terminal answers shell approvals and questions while the turn streams.\n const rl = mode === 'interactive' ? createInterface({ input: stdin, output: stdout }) : null\n try {\n await streamTurn(\n client,\n resolved.agent.id,\n buildChatRequest(args.message ?? '', attachments, mode),\n rl ? terminalPrompts(rl) : {},\n )\n } finally {\n rl?.close()\n }\n return\n }\n\n // Without --message, each line of piped input is one turn; nobody can answer an approval.\n if (mode === 'interactive') {\n throw new Error(\n 'pass --message \"...\" to send one message; for a conversation, use the web UI',\n )\n }\n console.log(`chatting with ${resolved.agent.name} (${resolved.model})`)\n console.log('(type /exit to quit; input is piped, commands run with auto_deny)')\n const rl = createInterface({ input: stdin, output: stdout })\n let inputEnded = false\n rl.once('close', () => {\n inputEnded = true\n })\n try {\n rl.setPrompt('> ')\n rl.prompt()\n for await (const line of rl) {\n const message = line.trim()\n if (message === '/exit' || message === '/quit') break\n if (message) {\n try {\n await streamTurn(client, resolved.agent.id, buildChatRequest(message, undefined, mode))\n } catch (err) {\n printError(err)\n }\n }\n // Piped input usually ends during the first turn; its remaining lines are still read.\n if (!inputEnded) rl.prompt()\n }\n } finally {\n rl.close()\n }\n },\n})\n","import type { AgentQuestion, AgentQuestionAnswer } from '@bazilion/api-types'\nimport { terminalSafe } from './command-helpers.ts'\n\nexport interface QuestionPrompt {\n question(text: string, signal: AbortSignal): Promise<string>\n write(text: string): void\n}\nfunction hasAnswerControl(text: string): boolean {\n return Array.from(text).some((character) => {\n const code = character.charCodeAt(0)\n return (code < 32 && ![9, 10, 13].includes(code)) || (code >= 127 && code <= 159)\n })\n}\n/** The model-written prompt and choices as terminal lines, with control characters escaped. */\nexport function questionLines(item: AgentQuestion): string[] {\n const lines = terminalSafe(item.question.prompt).split('\\n')\n item.question.choices.forEach((choice, index) => {\n const recommended = index === item.question.recommendedIndex ? ' (recommended)' : ''\n lines.push(`${index + 1}. ${terminalSafe(choice.label)}${recommended}`)\n if (choice.description) lines.push(` ${terminalSafe(choice.description)}`)\n })\n return lines\n}\n/** Uses the chat's sole readline owner. Expiry/EOF never becomes an implicit answer. */\nexport async function promptForQuestion(\n item: AgentQuestion,\n prompt: QuestionPrompt,\n): Promise<AgentQuestionAnswer | null> {\n if (item.expiresAt <= Date.now()) return null\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), Math.max(1, item.expiresAt - Date.now()))\n timer.unref()\n try {\n prompt.write(`Question ${item.id}`)\n for (const line of questionLines(item)) prompt.write(line)\n prompt.write('Choose a number, o for Other, or s to Skip.')\n while (!controller.signal.aborted) {\n const value = (await prompt.question('Answer: ', controller.signal)).trim()\n if (controller.signal.aborted) return null\n if (value.toLowerCase() === 's') return { kind: 'skip' }\n if (/^[1-4]$/.test(value) && Number(value) <= item.question.choices.length)\n return { kind: 'choice', index: Number(value) - 1 }\n if (value.toLowerCase() === 'o') {\n const text = await prompt.question('Your answer: ', controller.signal)\n if (controller.signal.aborted) return null\n if (text.trim() && text.length <= 4096 && !hasAnswerControl(text))\n return { kind: 'text', text }\n prompt.write('Enter 1–4096 characters without control characters.')\n } else prompt.write('Choose an explicit number, o, or s; no answer is selected by default.')\n }\n return null\n } catch {\n prompt.write('Question prompt closed or expired. No answer was submitted.')\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n","import type {\n ChatCompactRequest,\n ChatCompactResponse,\n ChatContextResponse,\n TruncateChatRequest,\n TruncateChatResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, confirm, printJson } from '../command-helpers.ts'\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`\n return `${(n / (1024 * 1024)).toFixed(2)} MiB`\n}\n\nfunction estimateTokens(chars: number): number {\n return Math.ceil(Math.max(0, chars) / 4)\n}\n\nconst chatTrimCmd = defineCommand({\n meta: {\n name: 'chat-trim',\n description: \"Keep the first N messages of an agent's chat history; drop the rest\",\n },\n args: {\n id: agentArg,\n keep: { type: 'string', required: true, description: 'Number of leading messages to keep' },\n },\n async run({ args }) {\n const keepCount = Number(args.keep)\n if (!Number.isInteger(keepCount) || keepCount < 0) {\n throw new Error('--keep must be a non-negative integer')\n }\n const body: TruncateChatRequest = { keepCount }\n const res = await createClient().post<TruncateChatResponse>(\n apiPath('agents', args.id, 'chat', 'truncate'),\n body,\n )\n console.log(\n `trimmed: ${res.before} → ${res.after} messages (${res.before - res.after} dropped)`,\n )\n },\n})\n\nconst chatContextCmd = defineCommand({\n meta: {\n name: 'chat-context',\n description: \"Break down what consumes the agent's context window\",\n },\n args: {\n id: agentArg,\n detail: {\n type: 'boolean',\n description: 'Include every tool/skill entry instead of the top 30',\n },\n json: { type: 'boolean', description: 'Emit raw JSON instead of a human report' },\n },\n async run({ args }) {\n const query = args.detail || args.json ? '?detail=1' : ''\n const ctx = await createClient().get<ChatContextResponse>(\n `${apiPath('agents', args.id, 'chat', 'context')}${query}`,\n )\n if (args.json) return printJson(ctx)\n\n const fmt = (chars: number, tokens: number): string =>\n `${chars.toLocaleString()} chars (~${tokens.toLocaleString()} tok)`\n const { systemPrompt, tools, skills, team, history } = ctx\n\n console.log(`🧠 context for ${ctx.agentId}`)\n console.log(`model: ${ctx.model}`)\n console.log('')\n console.log('## system prompt')\n console.log(` total: ${fmt(systemPrompt.chars, systemPrompt.tokens)}`)\n if (systemPrompt.files.length > 0) {\n console.log(' profile files:')\n for (const f of systemPrompt.files) console.log(` - ${f.name}: ${fmt(f.chars, f.tokens)}`)\n }\n if (systemPrompt.skillsListChars > 0) {\n console.log(` skills line: ${systemPrompt.skillsListChars.toLocaleString()} chars`)\n }\n if (systemPrompt.teamListChars > 0) {\n console.log(` team block: ${systemPrompt.teamListChars.toLocaleString()} chars`)\n }\n if (systemPrompt.userMdChars > 0) {\n console.log(` user_md block: ${systemPrompt.userMdChars.toLocaleString()} chars`)\n }\n console.log(` memory hint: ${systemPrompt.memoryHintChars.toLocaleString()} chars`)\n console.log('')\n console.log('## tools')\n console.log(` count: ${tools.count}`)\n console.log(\n ` schemas (JSON): ${tools.schemaChars.toLocaleString()} chars (~${estimateTokens(tools.schemaChars).toLocaleString()} tok)`,\n )\n console.log(` list text: ${tools.listChars.toLocaleString()} chars`)\n if (tools.entries.length > 0) {\n console.log(' top tools by schema size:')\n for (const t of tools.entries) {\n const params = t.paramCount != null ? ` (${t.paramCount} params)` : ''\n console.log(` - ${t.name}: ${t.schemaChars.toLocaleString()} chars${params}`)\n }\n }\n console.log('')\n if (skills.count > 0) {\n console.log('## skills')\n console.log(` count: ${skills.count}`)\n for (const s of skills.entries) {\n console.log(` - ${s.name}: ${s.blockChars.toLocaleString()} chars`)\n }\n console.log('')\n }\n console.log('## team')\n console.log(` - ${team.id} (${team.name}): ${team.path}`)\n if (team.userMdChars > 0) console.log(` user_md: ${team.userMdChars.toLocaleString()} chars`)\n console.log('')\n console.log('## history')\n console.log(` messages: ${history.messageEntries}`)\n console.log(` compactions: ${history.compactionEntries}`)\n console.log(` total: ${fmt(history.chars, history.tokensEstimate)}`)\n console.log(` bytes: ${formatBytes(history.bytes)}`)\n console.log('')\n console.log(`TOTAL: ${fmt(ctx.totals.chars, ctx.totals.tokens)}`)\n },\n})\n\nconst chatCompactCmd = defineCommand({\n meta: {\n name: 'chat-compact',\n description: \"Summarize the head of an agent's chat log, preserving the tail verbatim\",\n },\n args: {\n id: agentArg,\n instructions: {\n type: 'string',\n description: 'Optional extra guidance prepended to the summarizer prompt',\n },\n force: { type: 'boolean', description: 'Skip the y/N prompt' },\n },\n async run({ args }) {\n const body: ChatCompactRequest = args.instructions\n ? { customInstructions: args.instructions }\n : {}\n const question = `compact chat history for ${args.id}? head turns become a summary; tail is preserved.`\n if (!args.force && !(await confirm(question))) return console.log('aborted')\n const res = await createClient().post<ChatCompactResponse>(\n apiPath('agents', args.id, 'chat', 'compact'),\n body,\n )\n console.log(\n `compacted: ${res.before} → ${res.after} entries (${res.summarized} summarized, ${res.keptTail} tail kept verbatim)`,\n )\n console.log(\n `tokens: ~${res.tokensBefore.toLocaleString()} → ~${res.tokensAfter.toLocaleString()}`,\n )\n console.log('')\n console.log('summary:')\n console.log(res.summary)\n },\n})\n\nexport const contextCommands = {\n 'chat-trim': chatTrimCmd,\n 'chat-context': chatContextCmd,\n 'chat-compact': chatCompactCmd,\n}\n","import type {\n Agent,\n AgentLessonProposal,\n AgentLessonProposalResponse,\n AgentLessonStatus,\n AgentReviewConfig,\n EnqueueAgentReviewResponse,\n ListAgentLessonProposalsResponse,\n ListAgentReviewsResponse,\n UpdateAgentReviewConfigRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst proposalArg = positional('Proposal id or prefix')\n\nconst reviewConfigCmd = defineCommand({\n meta: { name: 'review-config', description: 'Inspect or configure reviewed learning' },\n args: {\n id: agentArg,\n enable: { type: 'boolean', description: 'Enable periodic reviews' },\n disable: { type: 'boolean', description: 'Disable periodic reviews' },\n every: { type: 'string', description: 'Successful user turns between reviews (1-100)' },\n model: { type: 'string', description: \"Review model, or 'agent' to use the Agent model\" },\n reasoning: { type: 'string', description: 'Review reasoning level' },\n },\n async run({ args }) {\n if (args.enable && args.disable) throw new Error('choose either --enable or --disable')\n const body: UpdateAgentReviewConfigRequest = {}\n if (args.enable || args.disable) body.enabled = Boolean(args.enable)\n if (args.every !== undefined) {\n const value = Number(args.every)\n if (!Number.isInteger(value) || value < 1 || value > 100) {\n throw new Error('--every must be an integer from 1 to 100')\n }\n body.everyNTurns = value\n }\n if (args.model !== undefined) body.model = args.model === 'agent' ? null : args.model\n if (args.reasoning !== undefined) {\n body.reasoningLevel = args.reasoning as UpdateAgentReviewConfigRequest['reasoningLevel']\n }\n const client = createClient()\n const path = apiPath('agents', args.id, 'review-config')\n const config =\n Object.keys(body).length > 0\n ? await client.patch<AgentReviewConfig>(path, body)\n : await client.get<AgentReviewConfig>(path)\n console.log(`review: ${config.enabled ? 'enabled' : 'disabled'}`)\n console.log(`cadence: every ${config.everyNTurns} successful user turns`)\n console.log(`model: ${config.model ?? 'agent model'}`)\n console.log(`reasoning: ${config.reasoningLevel}`)\n console.log(`turns since last review: ${config.turnsSinceLast}`)\n },\n})\n\nconst reviewCmd = defineCommand({\n meta: { name: 'review', description: 'Enqueue a reviewed-learning pass' },\n args: { id: agentArg },\n async run({ args }) {\n const response = await createClient().post<EnqueueAgentReviewResponse>(\n apiPath('agents', args.id, 'reviews'),\n )\n console.log(`review ${response.review.id} ${response.review.status}`)\n },\n})\n\nconst reviewsCmd = defineCommand({\n meta: { name: 'reviews', description: 'List reviewed-learning history' },\n args: {\n id: agentArg,\n status: { type: 'string', description: 'pending|running|completed|failed|cancelled' },\n },\n async run({ args }) {\n const { reviews } = await createClient().get<ListAgentReviewsResponse>(\n apiPath('agents', args.id, 'reviews'),\n )\n printRows(\n reviews\n .filter((review) => !args.status || review.status === args.status)\n .map((review) => [\n review.id,\n review.status,\n review.trigger,\n `${review.proposalCount} proposal(s)`,\n new Date(review.createdAt).toISOString(),\n ]),\n '(no reviews)',\n )\n },\n})\n\nconst lessonsCmd = defineCommand({\n meta: { name: 'lessons', description: 'List reviewed lesson proposals' },\n args: {\n id: agentArg,\n status: { type: 'string', description: 'pending|approved|rejected|revoked' },\n },\n async run({ args }) {\n const status = args.status as AgentLessonStatus | undefined\n const query = status ? `?status=${encodeURIComponent(status)}` : ''\n const { proposals } = await createClient().get<ListAgentLessonProposalsResponse>(\n `${apiPath('agents', args.id, 'lesson-proposals')}${query}`,\n )\n printRows(\n proposals.map((proposal) => [proposal.id, proposal.status, proposal.scope, proposal.text]),\n '(no lesson proposals)',\n )\n },\n})\n\n/** A proposal is addressed by its id alone, so find the Agent it belongs to. */\nasync function locateProposal(\n id: string,\n): Promise<{ agent: Agent; proposal: AgentLessonProposal }> {\n const client = createClient()\n for (const agent of await client.get<Agent[]>('/api/agents?includeArchived=true')) {\n const { proposals } = await client.get<ListAgentLessonProposalsResponse>(\n apiPath('agents', agent.id, 'lesson-proposals'),\n )\n const proposal = proposals.find((item) => item.id === id || item.id.startsWith(id))\n if (proposal) return { agent, proposal }\n }\n throw new Error(`lesson proposal not found: ${id}`)\n}\n\nfunction lessonDecisionCmd(decision: 'approve' | 'reject' | 'revoke') {\n return defineCommand({\n meta: { name: decision, description: `${decision} a reviewed lesson proposal` },\n args: {\n id: proposalArg,\n yes: { type: 'boolean', description: `Confirm ${decision}` },\n },\n async run({ args }) {\n if (!args.yes) throw new Error(`${decision} requires --yes`)\n const { agent, proposal } = await locateProposal(args.id)\n const response = await createClient().post<AgentLessonProposalResponse>(\n apiPath('agents', agent.id, 'lesson-proposals', proposal.id, decision),\n { version: proposal.version },\n )\n console.log(`${response.proposal.status} ${response.proposal.id}`)\n },\n })\n}\n\nconst lessonEditCmd = defineCommand({\n meta: { name: 'edit', description: 'Edit a pending reviewed lesson proposal' },\n args: {\n id: proposalArg,\n text: { type: 'string', description: 'Replacement lesson text' },\n scope: { type: 'string', description: 'private|shared' },\n },\n async run({ args }) {\n if (args.text === undefined && args.scope === undefined) {\n throw new Error('lesson edit requires --text or --scope')\n }\n const { agent, proposal } = await locateProposal(args.id)\n const response = await createClient().patch<AgentLessonProposalResponse>(\n apiPath('agents', agent.id, 'lesson-proposals', proposal.id),\n { version: proposal.version, text: args.text, scope: args.scope },\n )\n console.log(`updated ${response.proposal.id} v${response.proposal.version}`)\n },\n})\n\nconst lessonCmd = defineCommand({\n meta: { name: 'lesson', description: 'Edit or decide a reviewed lesson proposal' },\n subCommands: {\n edit: lessonEditCmd,\n approve: lessonDecisionCmd('approve'),\n reject: lessonDecisionCmd('reject'),\n revoke: lessonDecisionCmd('revoke'),\n },\n})\n\nexport const learningCommands = {\n 'review-config': reviewConfigCmd,\n review: reviewCmd,\n reviews: reviewsCmd,\n lessons: lessonsCmd,\n lesson: lessonCmd,\n}\n","import type { AttachSkillRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional } from '../command-helpers.ts'\nimport { explainScanBlock } from '../errors.ts'\n\nconst skillArg = positional('Skill name')\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Attach a skill to an agent' },\n args: {\n agent: agentArg,\n skill: skillArg,\n 'allow-warnings': {\n type: 'boolean',\n description: 'Attach even when the static skill scan reports findings',\n },\n },\n async run({ args }) {\n const body: AttachSkillRequest = { skill: args.skill, allowFindings: args['allow-warnings'] }\n await createClient()\n .post(apiPath('agents', args.agent, 'skills'), body)\n .catch(explainScanBlock('--allow-warnings'))\n console.log(`attached skill ${args.skill} to ${args.agent}`)\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Detach a skill from an agent' },\n args: { agent: agentArg, skill: skillArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.agent, 'skills', args.skill))\n console.log(`detached skill ${args.skill} from ${args.agent}`)\n },\n})\n\nexport const agentSkillCommand = defineCommand({\n meta: { name: 'skill', description: 'Attach/detach skills on an agent' },\n subCommands: { add: addCmd, rm: rmCmd },\n})\n","import type { AttentionItem, AttentionListResponse, AttentionSummary } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson } from '../command-helpers.ts'\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List operator attention items' },\n args: {\n state: { type: 'string', default: 'open', description: 'open, acknowledged or all' },\n kind: { type: 'string', description: 'Only items of this kind' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ state: args.state, limit: '200' })\n if (args.kind) query.set('kind', args.kind)\n const body = await createClient().get<AttentionListResponse>(`/api/attention?${query}`)\n if (args.json) return printJson(body)\n if (!body.items.length) console.log('(nothing needs attention)')\n else\n for (const line of columnize([\n ['severity', 'kind', 'context', 'when', 'key'],\n ...body.items.map((item) => [\n item.severity,\n item.kind,\n context(item),\n new Date(item.occurredAt).toISOString(),\n item.key,\n ]),\n ]))\n console.log(line)\n for (const source of body.degraded)\n console.error(`warning: ${source.kind} unavailable: ${source.error}`)\n },\n})\n\nconst summary = defineCommand({\n meta: { name: 'summary', description: 'Summarize open attention items' },\n args: { json: jsonFlag },\n async run({ args }) {\n const body = await createClient().get<AttentionSummary>('/api/attention/summary')\n if (args.json) printJson(body)\n else\n console.log(\n `${body.openTotal} open · ${body.bySeverity.action_required} action required · ${body.bySeverity.error} errors · ${body.bySeverity.warning} warnings`,\n )\n },\n})\n\nfunction mutation(name: 'acknowledge' | 'unacknowledge') {\n return defineCommand({\n meta: { name, description: `${name} one informational attention item` },\n args: {\n key: positional('Attention item key'),\n yes: { type: 'boolean', description: 'Required confirmation' },\n json: jsonFlag,\n },\n async run({ args }) {\n if (!args.yes) throw new Error(`refusing mutation: pass --yes to ${name}`)\n const path = apiPath(\n 'attention',\n args.key,\n name === 'acknowledge' ? 'acknowledge' : 'acknowledgement',\n )\n const body =\n name === 'acknowledge'\n ? await createClient().post<{ item: AttentionItem }>(path)\n : await createClient().del<{ item: AttentionItem }>(path)\n if (args.json) printJson(body)\n else console.log(`${body.item.key}: ${body.item.acknowledgedAt ? 'acknowledged' : 'open'}`)\n },\n })\n}\n\nconst acknowledgeAll = defineCommand({\n meta: { name: 'acknowledge-all', description: 'Acknowledge all open informational items' },\n args: { yes: { type: 'boolean', description: 'Required confirmation' }, json: jsonFlag },\n async run({ args }) {\n if (!args.yes) throw new Error('refusing mutation: pass --yes to acknowledge-all')\n const body = await createClient().post<{ acknowledged: number }>(\n '/api/attention/acknowledge-all',\n )\n if (args.json) printJson(body)\n else console.log(`acknowledged ${body.acknowledged} informational item(s)`)\n },\n})\n\nfunction context(item: AttentionItem): string {\n return [item.agentName, item.teamName].filter(Boolean).join(' / ') || 'system'\n}\n\nexport const attentionCommand = defineCommand({\n meta: { name: 'attention', description: 'Inspect the operator attention center' },\n subCommands: {\n list,\n summary,\n acknowledge: mutation('acknowledge'),\n unacknowledge: mutation('unacknowledge'),\n 'acknowledge-all': acknowledgeAll,\n },\n})\n","// Import pi-ai's provider directly so the CLI bundle stays slim. The provider\n// owns its OAuth interaction; Bazilion persists the returned credential in the daemon.\nimport type { OpenAICodexStatus } from '@bazilion/api-types'\nimport type { AuthPrompt } from '@earendil-works/pi-ai'\nimport { openaiCodexProvider } from '@earendil-works/pi-ai/providers/openai-codex'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\n\ntype OpenAICodexLoginMethod = 'browser' | 'device_code'\n\nconst CLI_OPENAI_LOGIN_TIMEOUT_MS = 10 * 60_000\n\ninterface PromptInput {\n once(event: 'data', listener: (chunk: string | Buffer) => void): unknown\n once(event: 'error', listener: (error: Error) => void): unknown\n off(event: 'data', listener: (chunk: string | Buffer) => void): unknown\n off(event: 'error', listener: (error: Error) => void): unknown\n pause(): unknown\n}\n\n/**\n * Answer Pi's OpenAI login prompts in a terminal: pick the login method, or read one line (a\n * pasted redirect URL). The paste prompt ends when Pi withdraws it (the browser callback arrived\n * first) or when `login` ends; stdin is then released so it cannot keep the CLI running. The login\n * signal matters when port 1455 is taken: Pi then has no callback server and waits on this prompt\n * alone. A stdin error only stops the reading, since the browser callback may still arrive.\n */\nexport function answerCliOpenAIPrompt(\n prompt: AuthPrompt,\n loginMethod: OpenAICodexLoginMethod,\n login: AbortSignal,\n input: PromptInput = process.stdin,\n output: { write(text: string): unknown } = process.stdout,\n): Promise<string> {\n if (prompt.type === 'select') {\n return prompt.options.some((option) => option.id === loginMethod)\n ? Promise.resolve(loginMethod)\n : Promise.reject(\n new Error(\n `Pi openai-codex provider does not support ${loginMethod === 'browser' ? 'browser' : 'device-code'} login`,\n ),\n )\n }\n output.write(`${prompt.message}: `)\n const ended = prompt.signal ? AbortSignal.any([prompt.signal, login]) : login\n return new Promise<string>((resolve, reject) => {\n const stopReading = () => {\n input.off('data', onData)\n input.off('error', stopReading)\n input.pause()\n }\n const onData = (data: string | Buffer) => {\n stopReading()\n ended.removeEventListener('abort', onEnded)\n resolve(String(data).trim())\n }\n const onEnded = () => {\n stopReading()\n reject(new Error('OAuth prompt withdrawn'))\n }\n if (ended.aborted) return onEnded()\n input.once('data', onData)\n input.once('error', stopReading)\n ended.addEventListener('abort', onEnded, { once: true })\n })\n}\n\nfunction formatExpiry(ms: number | null): string {\n if (!ms) return '(unknown)'\n const d = new Date(ms)\n return d.toISOString().replace(/\\.\\d+Z$/, 'Z')\n}\n\nconst openaiLoginCmd = defineCommand({\n meta: {\n name: 'login',\n description: 'Connect your ChatGPT account via OAuth',\n },\n args: {\n 'device-code': {\n type: 'boolean',\n description: 'Use headless device-code login instead of the localhost browser callback',\n },\n },\n async run({ args }) {\n const client = createClient()\n // The loopback callback at localhost:1455 must be on the CLI user's\n // machine, so we run pi-ai's flow client-side (not via a server POST).\n // After it completes we ship the credentials to the daemon so they land\n // in the daemon-owned `secrets` table (encrypted with the bootstrap token).\n const loginMethod: OpenAICodexLoginMethod = args['device-code'] ? 'device_code' : 'browser'\n if (loginMethod === 'device_code') {\n console.log('starting OpenAI device-code sign-in...')\n } else {\n console.log('opening your browser for OpenAI sign-in...')\n console.log(\"(if it doesn't open automatically, paste the URL shown below)\")\n }\n const oauth = openaiCodexProvider().auth.oauth\n if (!oauth) throw new Error('Pi openai-codex provider does not expose OAuth')\n // A ref'd timer (unlike AbortSignal.timeout) keeps the CLI alive for the whole login window,\n // so a login nothing can finish ends with the timeout error instead of a silent exit.\n const login = new AbortController()\n const timer = setTimeout(() => login.abort(), CLI_OPENAI_LOGIN_TIMEOUT_MS)\n const creds = await oauth\n .login({\n signal: login.signal,\n notify: (event) => {\n if (event.type === 'auth_url') {\n console.log('')\n console.log(` → ${event.url}`)\n console.log('')\n } else if (event.type === 'progress' || event.type === 'info') {\n console.log(` ${event.message}`)\n } else if (event.type === 'device_code') {\n console.log(` open ${event.verificationUri} and enter ${event.userCode}`)\n }\n },\n prompt: (prompt) => answerCliOpenAIPrompt(prompt, loginMethod, login.signal),\n })\n .catch((error: unknown) => {\n throw login.signal.aborted\n ? new Error(\n 'OpenAI login timed out after 10 minutes. Try again, or use `bazilion auth openai login --device-code`.',\n )\n : error\n })\n .finally(() => clearTimeout(timer))\n const status = await client.put<OpenAICodexStatus>('/api/auth/openai', {\n refresh: creds.refresh,\n access: creds.access,\n expires: creds.expires,\n })\n console.log('')\n console.log('connected ✓')\n if (status.accountId) console.log(`account: ${status.accountId}`)\n console.log(`access token expires: ${formatExpiry(status.expiresAt)}`)\n console.log('')\n console.log('choose its models and switch it on in one step:')\n console.log(' bazilion provider connect openai-codex')\n console.log('or under Setup, Models in the web UI.')\n },\n})\n\nconst openaiLogoutCmd = defineCommand({\n meta: {\n name: 'logout',\n description: 'Forget the stored ChatGPT OAuth credentials',\n },\n async run() {\n const client = createClient()\n await client.del('/api/auth/openai')\n console.log('disconnected ChatGPT OAuth credentials')\n },\n})\n\nconst openaiStatusCmd = defineCommand({\n meta: {\n name: 'status',\n description: 'Show ChatGPT OAuth connection status',\n },\n async run() {\n const client = createClient()\n const status = await client.get<OpenAICodexStatus>('/api/auth/openai')\n if (!status.connected) {\n console.log('not connected — run `bazilion auth openai login`')\n return\n }\n console.log('connected ✓')\n if (status.accountId) console.log(`account: ${status.accountId}`)\n console.log(`access token expires: ${formatExpiry(status.expiresAt)}`)\n },\n})\n\nconst openaiCmd = defineCommand({\n meta: {\n name: 'openai',\n description: 'Manage ChatGPT (OAuth) authentication',\n },\n subCommands: {\n login: openaiLoginCmd,\n logout: openaiLogoutCmd,\n status: openaiStatusCmd,\n },\n})\n\nexport const authCommand = defineCommand({\n meta: {\n name: 'auth',\n description: 'OAuth-based provider authentication (ChatGPT account, etc.)',\n },\n subCommands: {\n openai: openaiCmd,\n },\n})\n","import { createHash } from 'node:crypto'\nimport {\n chmodSync,\n closeSync,\n copyFileSync,\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n renameSync,\n rmSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join, parse, posix, relative, resolve, sep } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { Decrypter, Encrypter } from 'age-encryption'\nimport { defineCommand } from 'citty'\nimport { extract, list } from 'tar'\nimport { type SchemaObject, schemaMatches } from '../../../daemon/src/core/db/schema.ts'\nimport { assertDaemonStopped } from '../../../daemon/src/lib/daemon-liveness.ts'\nimport { readAuthFile } from '../auth-file.ts'\nimport { loadClientConfig } from '../client.ts'\nimport { canonicalPath, resolveCliPaths } from '../paths.ts'\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Download a backup of the Bazilion home' },\n args: {\n output: {\n type: 'positional',\n required: false,\n description: 'Output file (default: bazilion-backup-<date>.tar.gz, plus .age when encrypted)',\n },\n recipient: { type: 'string', description: 'Encrypt the backup to this age recipient (age1…)' },\n },\n async run({ args }) {\n const date = new Date().toISOString().slice(0, 10)\n const suffix = args.recipient ? '.tar.gz.age' : '.tar.gz'\n const output = canonicalPath(args.output ?? `bazilion-backup-${date}${suffix}`)\n if (existsSync(output)) throw new Error(`refusing to overwrite ${output}`)\n const home = resolveCliPaths().home\n const fromHome = relative(home, output)\n if (fromHome !== '..' && !fromHome.startsWith(`..${sep}`) && !isAbsolute(fromHome)) {\n throw new Error(`write the backup outside the Bazilion home (${home})`)\n }\n // Set up first, so a mistyped recipient fails before the download starts.\n const encrypter = new Encrypter()\n if (args.recipient) encrypter.addRecipient(args.recipient)\n else console.warn('warning: this backup is not encrypted and contains every stored credential')\n\n const cfg = loadClientConfig()\n const res = await fetch(`${cfg.serverUrl}/api/backup`, {\n headers: { authorization: `Bearer ${cfg.token}`, origin: cfg.serverUrl },\n })\n if (!res.ok || !res.body) {\n const body = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(`backup failed: ${body.error ?? res.statusText}`)\n }\n const partial = `${output}.partial`\n // Created here or not at all: never write into, or follow, a file that is already there.\n const fd = openSync(partial, 'wx', 0o600)\n try {\n const [archive, check] = res.body.tee()\n const written = args.recipient ? await encrypter.encrypt(archive) : archive\n await Promise.all([\n pipeline(Readable.fromWeb(written), createWriteStream(partial, { fd })),\n // A response cut short can still end cleanly: read the archive through to its end.\n pipeline(Readable.fromWeb(check), list({ strict: true })),\n ])\n renameSync(partial, output)\n } finally {\n rmSync(partial, { force: true })\n }\n console.log(`backup written to ${output}`)\n },\n})\n\nconst AGE_HEADER = Buffer.from('age-encryption.org/v1\\n')\n\nfunction isAgeEncrypted(file: string): boolean {\n const header = Buffer.alloc(AGE_HEADER.length)\n const fd = openSync(file, 'r')\n try {\n readSync(fd, header, 0, header.length, 0)\n } finally {\n closeSync(fd)\n }\n return header.equals(AGE_HEADER)\n}\n\nasync function decrypt(file: string, output: string, identityFile: string): Promise<void> {\n const decrypter = new Decrypter()\n const identities = readFileSync(identityFile, 'utf8')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.startsWith('AGE-SECRET-KEY-'))\n if (identities.length === 0) throw new Error(`no AGE-SECRET-KEY in ${identityFile}`)\n for (const identity of identities) decrypter.addIdentity(identity)\n try {\n const plain = await decrypter.decrypt(\n Readable.toWeb(createReadStream(file)) as ReadableStream<Uint8Array>,\n )\n await pipeline(Readable.fromWeb(plain), createWriteStream(output, { mode: 0o600 }))\n } catch {\n throw new Error('could not decrypt the backup: wrong identity, or the file is damaged')\n }\n}\n\n/**\n * Refuse what restore must not write: paths leaving the home, special files, entries below a\n * symbolic link, and links leaving the home other than a linked Team (`teams/<slug>`, absolute).\n * The rest of the archive, its database included, is trusted: restore only backups you trust.\n */\nasync function checkArchive(file: string): Promise<void> {\n // Collect first: an error thrown while tar is still reading would escape as a crash.\n const raw: Array<{ path: string; type: string; linkpath: string }> = []\n await list({\n file,\n strict: true,\n onReadEntry: (entry) =>\n raw.push({ path: entry.path, type: entry.type, linkpath: entry.linkpath ?? '' }),\n })\n const entries: Array<{ path: string; type: string }> = []\n const links = new Set<string>()\n for (const entry of raw) {\n const segments = entry.path.split('/').filter((segment) => segment && segment !== '.')\n const path = segments.join('/')\n if (entry.path.startsWith('/') || segments.includes('..')) {\n throw new Error(`backup contains an unsafe path: ${entry.path}`)\n }\n if (!['File', 'Directory', 'SymbolicLink'].includes(entry.type)) {\n throw new Error(`backup contains an unsupported ${entry.type} entry: ${path}`)\n }\n if (entry.type === 'SymbolicLink') {\n const resolved = posix.normalize(posix.join(posix.dirname(path), entry.linkpath))\n const leaves = posix.isAbsolute(entry.linkpath)\n ? !/^teams\\/[^/]+$/.test(path)\n : resolved === '..' || resolved.startsWith('../')\n if (leaves) throw new Error(`backup contains a symbolic link leaving the home: ${path}`)\n links.add(path)\n }\n entries.push({ path, type: entry.type })\n }\n for (const { path } of entries) {\n const segments = path.split('/')\n for (let i = 1; i < segments.length; i++) {\n if (links.has(segments.slice(0, i).join('/'))) {\n throw new Error(`backup places ${path} below a symbolic link`)\n }\n }\n }\n for (const required of ['bazilion.db', 'auth.json']) {\n if (!entries.some((entry) => entry.path === required && entry.type === 'File')) {\n throw new Error(`backup is missing ${required}`)\n }\n }\n}\n\n/** The restored home must open on this release: intact, same schema, matching auth.json. */\nfunction checkDatabase(home: string): void {\n const token = readAuthFile(join(home, 'auth.json')).token\n // Opened read-write only so that closing it removes the -wal/-shm files a WAL database makes.\n const db = new DatabaseSync(join(home, 'bazilion.db'))\n try {\n const integrity = db.prepare('PRAGMA integrity_check').get()\n if (integrity?.integrity_check !== 'ok') throw new Error('the database is damaged')\n if (!schemaMatches((query) => db.prepare(query).all() as unknown as SchemaObject[])) {\n throw new Error('the database schema differs from this release; use a backup from it')\n }\n const bootstrap = db\n .prepare(\n \"SELECT 1 FROM web_tokens WHERE token_hash = ? AND kind = 'bootstrap' AND revoked_at IS NULL\",\n )\n .get(createHash('sha256').update(token).digest('hex'))\n if (!bootstrap) throw new Error('auth.json does not match the database')\n } catch (error) {\n throw new Error(`backup database is unusable: ${(error as Error).message}`)\n } finally {\n db.close()\n }\n}\n\n/** Swap the staged home in; the current home stays in place until the new one is. */\nexport function installRestoredHome(staged: string, home: string): void {\n if (!existsSync(home)) {\n renameSync(staged, home)\n return\n }\n const previous = `${home}.pre-restore-${Date.now()}`\n console.log(`moving the current home aside to ${previous}`)\n renameSync(home, previous)\n try {\n renameSync(staged, home)\n } catch (error) {\n renameSync(previous, home)\n throw error\n }\n try {\n rmSync(previous, { recursive: true, force: true })\n } catch {\n console.warn(`warning: could not delete the previous home at ${previous}; remove it by hand`)\n }\n}\n\nconst restoreCmd = defineCommand({\n meta: {\n name: 'restore',\n description: 'Restore a backup into the Bazilion home (stop the daemon first)',\n },\n args: {\n file: { type: 'positional', required: true, description: 'Backup file (.tar.gz or .age)' },\n home: { type: 'string', description: 'Restore into this home instead of BAZILION_HOME' },\n force: { type: 'boolean', description: 'Replace a non-empty home, deleting its current data' },\n identity: { type: 'string', description: 'age identity file of an encrypted backup' },\n },\n async run({ args }) {\n const file = resolve(args.file)\n if (!existsSync(file)) throw new Error(`backup file not found: ${file}`)\n const home = resolveCliPaths(args.home).home\n if (home === parse(home).root) throw new Error('refusing to restore over the filesystem root')\n assertDaemonStopped(home)\n if (existsSync(home) && readdirSync(home).length > 0 && !args.force) {\n throw new Error(`${home} is not empty; pass --force to replace it (its data is deleted)`)\n }\n\n mkdirSync(dirname(home), { recursive: true })\n const staging = mkdtempSync(join(dirname(home), '.bazilion-restore-'))\n try {\n // Check and extract a private copy, so the archive cannot change between the two.\n const archive = join(staging, 'backup.tar.gz')\n if (isAgeEncrypted(file)) {\n if (!args.identity) throw new Error('this backup is encrypted; pass --identity <file>')\n await decrypt(file, archive, args.identity)\n } else {\n copyFileSync(file, archive)\n }\n await checkArchive(archive)\n const staged = join(staging, 'home')\n mkdirSync(staged, { mode: 0o700 })\n // preservePaths keeps a linked Team's absolute target; checkArchive refused unsafe entries.\n await extract({ file: archive, cwd: staged, strict: true, preservePaths: true })\n // Owner-only, whatever modes the archive carried.\n chmodSync(staged, 0o700)\n for (const name of ['auth.json', 'bazilion.db']) chmodSync(join(staged, name), 0o600)\n checkDatabase(staged)\n // Again: a daemon may have started on the home while the archive was checked.\n assertDaemonStopped(home)\n installRestoredHome(staged, home)\n } finally {\n rmSync(staging, { recursive: true, force: true })\n }\n console.log(`restored ${file} to ${home}`)\n console.log('start the daemon with: bazilion serve')\n },\n})\n\nexport const backupCommand = defineCommand({\n meta: { name: 'backup', description: 'Back up and restore the Bazilion home' },\n subCommands: { create: createCmd, restore: restoreCmd },\n})\n","import { readFileSync } from 'node:fs'\nimport { type BazilionDb, inTx, openInMemoryDb } from './client.ts'\n\nexport const INCOMPATIBLE_DATABASE_MESSAGE =\n 'Bazilion cannot start because this home uses an incompatible database schema. ' +\n 'Preserve the entire Bazilion home directory as a filesystem backup first, keeping ' +\n 'bazilion.db and auth.json together. Then perform the reset with ' +\n '`bazilion uninstall --yes` (from the repository root of a source checkout: ' +\n '`pnpm tsx apps/cli/src/index.ts uninstall --yes`) and start Bazilion again. ' +\n 'Use `--all` only if you also want to remove installed skills.'\n\nexport class IncompatibleDatabaseError extends Error {\n constructor() {\n super(INCOMPATIBLE_DATABASE_MESSAGE)\n this.name = 'IncompatibleDatabaseError'\n }\n}\n\nexport type SchemaObject = { type: string; name: string; sql: string }\n/** Runs a query and returns its rows, so daemon and raw node:sqlite handles share the check. */\ntype ReadSchemaObjects = (query: string) => SchemaObject[]\n\nconst SCHEMA_OBJECTS =\n 'SELECT type, name, sql FROM sqlite_schema ' +\n \"WHERE sql IS NOT NULL AND substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name\"\n\n// SQLite stores each CREATE statement's text, comments included. Ignore comments and whitespace so\n// that documentation edits to schema.sql never make an existing home look incompatible.\nfunction fingerprint(read: ReadSchemaObjects): string {\n return read(SCHEMA_OBJECTS)\n .map((object) => {\n const sql = object.sql\n .replace(/--[^\\n]*/g, ' ')\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return `${object.type} ${object.name} ${sql}`\n })\n .join('\\n')\n}\n\nlet schemaSql: string | undefined\nfunction readSchemaSql(): string {\n schemaSql ??= readFileSync(new URL('./schema.sql', import.meta.url), 'utf8')\n return schemaSql\n}\n\nlet canonical: string | undefined\n/** True when the database's schema objects are exactly those `schema.sql` creates. */\nexport function schemaMatches(read: ReadSchemaObjects): boolean {\n if (canonical === undefined) {\n const scratch = openInMemoryDb('')\n try {\n scratch.raw.exec(readSchemaSql())\n canonical = fingerprint((query) => scratch.raw.query<SchemaObject, []>(query).all())\n } finally {\n scratch.close()\n }\n }\n return fingerprint(read) === canonical\n}\n\n/** Create the schema in an empty database; refuse, untouched, a database whose schema differs. */\nexport function initSchema(db: BazilionDb): void {\n const read: ReadSchemaObjects = (query) => db.raw.query<SchemaObject, []>(query).all()\n if (read(SCHEMA_OBJECTS).length === 0) inTx(db, () => db.raw.exec(readSchemaSql()))\n else if (!schemaMatches(read)) throw new IncompatibleDatabaseError()\n}\n","import { dirname } from 'node:path'\nimport { backup, DatabaseSync, type SQLInputValue } from 'node:sqlite'\n\nexport interface QueryStmt<RowType, ParamsType extends unknown[]> {\n get(...params: ParamsType): RowType | null\n all(...params: ParamsType): RowType[]\n run(...params: ParamsType): { changes: number; lastInsertRowid: number | bigint }\n}\n\nexport interface QueryableDatabase {\n query<RowType, ParamsType extends unknown[]>(sql: string): QueryStmt<RowType, ParamsType>\n run(sql: string, params?: unknown[]): { changes: number; lastInsertRowid: number | bigint }\n exec(sql: string): void\n transaction<T>(fn: () => T): () => T\n}\n\nexport interface BazilionDb {\n raw: QueryableDatabase\n /** The Bazilion home, where the database file lives; Agent and Profile directories derive from it. */\n home: string\n /**\n * Copy a transactionally-consistent image of the live database to `path`.\n * SQLite's online-backup API includes committed WAL contents without\n * requiring the daemon to close its connection or checkpoint the WAL.\n */\n backupTo(path: string): Promise<number>\n close(): void\n}\n\nfunction wrap(rawDb: DatabaseSync): QueryableDatabase {\n const cache = new Map<string, ReturnType<DatabaseSync['prepare']>>()\n let transactionDepth = 0\n let savepointSequence = 0\n function getStmt(sql: string) {\n let s = cache.get(sql)\n if (!s) {\n s = rawDb.prepare(sql)\n cache.set(sql, s)\n }\n return s\n }\n\n return {\n query<R, P extends unknown[]>(sql: string): QueryStmt<R, P> {\n const stmt = getStmt(sql)\n return {\n get(...params: P): R | null {\n const result = stmt.get(...(params as SQLInputValue[]))\n return (result as R | undefined) ?? null\n },\n all(...params: P): R[] {\n return stmt.all(...(params as SQLInputValue[])) as R[]\n },\n run(...params: P) {\n return stmt.run(...(params as SQLInputValue[])) as {\n changes: number\n lastInsertRowid: number | bigint\n }\n },\n }\n },\n run(sql, params) {\n const stmt = getStmt(sql)\n return stmt.run(...((params ?? []) as SQLInputValue[])) as {\n changes: number\n lastInsertRowid: number | bigint\n }\n },\n exec(sql) {\n rawDb.exec(sql)\n },\n // node:sqlite has no callable `transaction` wrapper; use manual BEGIN/COMMIT/ROLLBACK.\n transaction<T>(fn: () => T): () => T {\n return () => {\n const outermost = transactionDepth === 0\n const savepoint = outermost ? null : `bazilion_nested_${++savepointSequence}`\n if (outermost) rawDb.exec('BEGIN')\n else rawDb.exec(`SAVEPOINT ${savepoint}`)\n transactionDepth++\n try {\n const result = fn()\n if (outermost) rawDb.exec('COMMIT')\n else rawDb.exec(`RELEASE SAVEPOINT ${savepoint}`)\n return result\n } catch (err) {\n if (outermost) rawDb.exec('ROLLBACK')\n else {\n rawDb.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`)\n rawDb.exec(`RELEASE SAVEPOINT ${savepoint}`)\n }\n throw err\n } finally {\n transactionDepth--\n }\n }\n },\n }\n}\n\nfunction applyPragmas(rawDb: DatabaseSync, includeWal: boolean): void {\n if (includeWal) {\n try {\n rawDb.exec('PRAGMA journal_mode = WAL')\n } catch {\n // some sqlite builds reject WAL on :memory: — ignore\n }\n }\n rawDb.exec('PRAGMA foreign_keys = ON')\n}\n\nexport function openDb(path: string): BazilionDb {\n // Bazilion is the normal sole writer, but online backups and operator-side\n // diagnostics can briefly overlap another WAL connection. Wait for those\n // transient locks instead of turning unrelated reads/writes (including\n // token usage telemetry) into immediate SQLITE_BUSY failures.\n const raw = new DatabaseSync(path, { timeout: 5_000 })\n applyPragmas(raw, true)\n return {\n raw: wrap(raw),\n home: dirname(path),\n backupTo(path) {\n return backup(raw, path)\n },\n close() {\n raw.close()\n },\n }\n}\n\n/**\n * `home` is the Bazilion home that Agent and Profile directories derive from. Pass '' only where\n * nothing reads those directories: they would come out relative.\n */\nexport function openInMemoryDb(home: string): BazilionDb {\n const raw = new DatabaseSync(':memory:')\n applyPragmas(raw, false)\n return {\n raw: wrap(raw),\n home,\n backupTo(path) {\n return backup(raw, path)\n },\n close() {\n raw.close()\n },\n }\n}\n\nexport function inTx<T>(db: BazilionDb, fn: () => T): T {\n return db.raw.transaction(fn)()\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/** `<home>/daemon.pid` holds the PID of the daemon that owns the home. */\nexport const DAEMON_PID_FILE = 'daemon.pid'\n\n/**\n * PID of the daemon running on `home`, or null. A pidfile naming a dead process, or this process\n * (its PID reused, e.g. after a reboot), is stale.\n */\nexport function runningDaemonPid(home: string): number | null {\n let pid: number\n try {\n pid = Number.parseInt(readFileSync(join(home, DAEMON_PID_FILE), 'utf8'), 10)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw error\n }\n if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) return null\n try {\n process.kill(pid, 0)\n return pid\n } catch (error) {\n // EPERM: the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM' ? pid : null\n }\n}\n\n/** Offline commands (backup restore, uninstall) and a second daemon refuse a home in use. */\nexport function assertDaemonStopped(home: string): void {\n const pid = runningDaemonPid(home)\n if (pid !== null) {\n throw new Error(\n `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first ` +\n `(if none is running, delete ${join(home, DAEMON_PID_FILE)})`,\n )\n }\n}\n\n/** Claim `home` before bootstrap opens SQLite. Returns the function that releases it. */\nexport function claimDaemonPidFile(home: string): () => void {\n const path = join(home, DAEMON_PID_FILE)\n const content = `${process.pid}\\n`\n mkdirSync(home, { recursive: true })\n try {\n writeFileSync(path, content, { flag: 'wx', mode: 0o600 })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n assertDaemonStopped(home)\n rmSync(path, { force: true })\n writeFileSync(path, content, { flag: 'wx', mode: 0o600 })\n }\n return () => {\n // Only this daemon's own pidfile: another daemon may have written its own since.\n try {\n if (readFileSync(path, 'utf8') === content) rmSync(path)\n } catch {\n // Already gone.\n }\n }\n}\n","import { defineCommand } from 'citty'\n\ninterface CommandNode {\n subCommands?: Record<string, CommandNode | Promise<CommandNode>>\n args?: Record<string, { type?: string; alias?: string | string[] }>\n}\n\ninterface Flatten {\n /** full path e.g. [\"agent\", \"chat\"]; empty for the top-level root */\n path: string[]\n /** immediate subcommand names available at this path */\n subs: string[]\n /** flag tokens e.g. [\"--profile\", \"--name\", \"--long\", \"-l\"] */\n flags: string[]\n}\n\nasync function walk(cmd: CommandNode, path: string[], out: Flatten[]): Promise<void> {\n const subsRaw = cmd.subCommands ?? {}\n const subNames = Object.keys(subsRaw)\n const flags = flagsOf(cmd.args ?? {})\n out.push({ path, subs: subNames, flags })\n for (const name of subNames) {\n const v = subsRaw[name]\n const sub = (await Promise.resolve(v)) as CommandNode\n await walk(sub, [...path, name], out)\n }\n}\n\nfunction flagsOf(args: Record<string, { type?: string; alias?: string | string[] }>): string[] {\n const out: string[] = []\n for (const [name, def] of Object.entries(args)) {\n // Positionals don't get completed as flags.\n if (def.type === 'positional') continue\n out.push(`--${name}`)\n const aliases = Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []\n for (const a of aliases) out.push(a.length === 1 ? `-${a}` : `--${a}`)\n }\n return out\n}\n\nfunction bashScript(flat: Flatten[]): string {\n const cases = flat\n .map((f) => {\n const key = f.path.length === 0 ? '\"\"' : JSON.stringify(f.path.join(' '))\n const words = [...f.subs, ...f.flags].join(' ')\n return ` ${key})\\n COMPREPLY=($(compgen -W ${JSON.stringify(words)} -- \"$cur\"))\\n ;;`\n })\n .join('\\n')\n return `# bazilion bash completion. Install with:\n# source <(bazilion completion bash)\n# or append to ~/.bashrc / ~/.bash_profile.\n_bazilion_completion() {\n local cur prev cword\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n cword=$COMP_CWORD\n # Build the current subcommand path by walking words[1..cword-1], skipping\n # flags and their values. We don't try to parse flag arity — treating every\n # flag as standalone is a good-enough approximation for completion.\n local cmd=\"\"\n local i\n for ((i=1; i<cword; i++)); do\n local w=\"\\${COMP_WORDS[i]}\"\n [[ \"$w\" == -* ]] && continue\n cmd+=\"\\${cmd:+ }$w\"\n done\n case \"$cmd\" in\n${cases}\n *)\n COMPREPLY=()\n ;;\n esac\n}\ncomplete -F _bazilion_completion bazilion\n`\n}\n\nfunction zshScript(flat: Flatten[]): string {\n // zsh bundles a bashcompinit shim; reusing the bash script sidesteps the\n // cost of a native _arguments/_describe implementation while still giving\n // users a working completion. Ships with a tiny preamble so zsh loads the\n // bash compat helpers first.\n const bash = bashScript(flat)\n return `# bazilion zsh completion. Install with:\n# source <(bazilion completion zsh)\n# If you don't already have bashcompinit loaded, this does it for you.\nautoload -U +X compinit && compinit\nautoload -U +X bashcompinit && bashcompinit\n${bash}`\n}\n\nfunction fishScript(flat: Flatten[]): string {\n const lines: string[] = [\n '# bazilion fish completion. Install with:',\n '# bazilion completion fish | source',\n '# or write it to ~/.config/fish/completions/bazilion.fish',\n '',\n 'complete -c bazilion -f',\n ]\n for (const f of flat) {\n if (f.path.length === 0) {\n for (const s of f.subs) lines.push(`complete -c bazilion -n '__fish_use_subcommand' -a ${s}`)\n for (const fl of f.flags) {\n const long = fl.startsWith('--') ? fl.slice(2) : ''\n const short = !fl.startsWith('--') ? fl.slice(1) : ''\n const parts: string[] = [\"complete -c bazilion -n '__fish_use_subcommand'\"]\n if (short) parts.push(`-s ${short}`)\n if (long) parts.push(`-l ${long}`)\n lines.push(parts.join(' '))\n }\n } else {\n // Guard this case on the joined path being the last N tokens in\n // COMP_CWORDS — fish's __fish_seen_subcommand_from handles each token\n // independently, so we require every path segment.\n const guard = f.path.map((p) => `__fish_seen_subcommand_from ${p}`).join('; and ')\n for (const s of f.subs) {\n lines.push(`complete -c bazilion -n '${guard}' -a ${s}`)\n }\n for (const fl of f.flags) {\n const long = fl.startsWith('--') ? fl.slice(2) : ''\n const short = !fl.startsWith('--') ? fl.slice(1) : ''\n const parts: string[] = [`complete -c bazilion -n '${guard}'`]\n if (short) parts.push(`-s ${short}`)\n if (long) parts.push(`-l ${long}`)\n lines.push(parts.join(' '))\n }\n }\n }\n return `${lines.join('\\n')}\\n`\n}\n\nexport function completionCommand(main: CommandNode) {\n return defineCommand({\n meta: {\n name: 'completion',\n description: 'Print a shell completion script (bash, zsh, or fish)',\n },\n args: {\n shell: {\n type: 'positional',\n required: true,\n description: 'bash | zsh | fish',\n },\n },\n async run({ args }) {\n const flat: Flatten[] = []\n await walk(main, [], flat)\n const shell = String(args.shell).toLowerCase()\n if (shell === 'bash') console.log(bashScript(flat))\n else if (shell === 'zsh') console.log(zshScript(flat))\n else if (shell === 'fish') console.log(fishScript(flat))\n else throw new Error(`unsupported shell: ${args.shell} (want bash | zsh | fish)`)\n },\n })\n}\n","import type {\n ProviderConfigResponse,\n ServiceCard,\n ServiceFieldState,\n SetFieldRequest,\n SetFieldsRequest,\n SetFieldsResponse,\n ToolsResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nfunction displayValue(f: ServiceFieldState): string {\n const source = f.environment ? ' (from the daemon’s environment)' : ''\n if (f.kind === 'secret') return f.set ? `${f.preview ?? '(set)'}${source}` : `(unset)${source}`\n if (f.environment) return `${f.effective ?? ''}${source}`\n if (f.set) return f.value ?? '(set)'\n return f.effective ? `${f.effective} (default)` : '(unset)'\n}\n\n/** What a setting takes, when it is more specific than text. */\nfunction accepts(field: ServiceFieldState): string | undefined {\n const input = field.input\n switch (input.type) {\n case 'choice':\n return input.options.map((option) => `${option.value} (${option.label})`).join(', ')\n case 'switch':\n // Yes or no reads the same whichever way round the page shows it.\n return [input.on, input.off].includes('true')\n ? 'true or false'\n : `${input.on} or ${input.off}`\n case 'number': {\n const shown = input.scale\n ? ` (the Tools page shows ${input.unit ?? 'units'}: ${input.scale} each)`\n : ''\n return `a whole number from ${input.min} to ${input.max}${shown}`\n }\n default:\n return undefined\n }\n}\n\nconst listCmd = defineCommand({\n meta: {\n name: 'list',\n description:\n 'List every setting of providers, model functions and tools, and what is in effect',\n },\n async run() {\n const client = createClient()\n // Providers, model functions and tools all carry fields: merge and print.\n const { providers } = await client.get<ProviderConfigResponse>('/api/config/providers')\n const { tools, functions } = await client.get<ToolsResponse>('/api/config/tools')\n const cards = [...functions, ...tools]\n const all: Pick<ServiceCard, 'id' | 'fields'>[] = [...providers, ...cards]\n\n printRows(\n all.flatMap((svc) => svc.fields.map((f) => [svc.id, f.envVar, f.kind, displayValue(f)])),\n '(no fields registered)',\n )\n console.log('')\n for (const card of cards) {\n const state = [card.state?.label, card.note].filter(Boolean).join('. ')\n if (state) console.log(`${card.displayName}: ${state}`)\n for (const field of card.fields) {\n if (field.input.type !== 'choice') continue\n const chosen = field.input.options.find((option) => option.value === field.effective)\n if (chosen?.note) console.log(` ${chosen.note.text}`)\n }\n }\n console.log('')\n for (const card of cards) {\n for (const field of card.fields) {\n const takes = accepts(field)\n if (takes) console.log(`${field.envVar}: ${takes}`)\n }\n }\n },\n})\n\nconst setCmd = defineCommand({\n meta: {\n name: 'set',\n description:\n 'Set one setting (NAME value), or several that are saved together (NAME=value NAME=value)',\n },\n args: {\n envVar: positional('Setting name (e.g. ANTHROPIC_API_KEY), or NAME=value'),\n value: {\n type: 'positional',\n required: false,\n description: 'New value (an empty string clears the setting)',\n },\n },\n async run({ args }) {\n const client = createClient()\n if (!args.envVar.includes('=')) {\n if (args.value === undefined) {\n throw new Error(`give ${args.envVar} a value, or use NAME=value`)\n }\n const body: SetFieldRequest = { value: args.value }\n const state = await client.put<ServiceFieldState>(\n apiPath('config', 'fields', args.envVar),\n body,\n )\n console.log(`${state.envVar} (${state.kind}): ${displayValue(state)}`)\n return\n }\n // NAME=value pairs: checked together, and stored only when all of them pass.\n const values: Record<string, string> = {}\n for (const token of args._) {\n const at = token.indexOf('=')\n if (at <= 0) throw new Error(`expected NAME=value, got \"${token}\"`)\n values[token.slice(0, at)] = token.slice(at + 1)\n }\n const body: SetFieldsRequest = { values }\n const { fields } = await client.put<SetFieldsResponse>('/api/config/fields', body)\n for (const state of fields) {\n console.log(`${state.envVar} (${state.kind}): ${displayValue(state)}`)\n }\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Remove a setting, back to its default' },\n args: {\n envVar: positional('Setting name to clear'),\n },\n async run({ args }) {\n await createClient().del(apiPath('config', 'fields', args.envVar))\n console.log(`removed ${args.envVar}`)\n },\n})\n\nexport const configCommand = defineCommand({\n meta: {\n name: 'config',\n description: 'Settings: credentials (stored encrypted), choices, switches and addresses',\n },\n subCommands: {\n list: listCmd,\n set: setCmd,\n rm: rmCmd,\n },\n})\n","// Entity shapes: the daemon reads them from its database and sends them as they are, and the CLI\n// and the web consume them.\n\nexport type Timestamp = number\n\n/**\n * A team is a collaboration context: one filesystem root, one USER.md\n * (read-only to agents, edited by the human), one roster of member agents.\n * Every agent belongs to exactly one team.\n */\nexport interface Team {\n id: string\n name: string\n path: string\n /** Read-only context about the human for all agents in this team.\n * Injected into the system prompt; never exposed as a file on disk. */\n userMd: string\n /**\n * Optional Telegram forum-topic name template for this team's agents.\n * `null` = built-in naming (bare name for `default`, `<slug> › <name>`\n * otherwise). When set, rendered with {agent.name}, {team.name},\n * {team.slug}. Must contain {agent.name} so topics stay distinct.\n */\n telegramTopicNameFormat: string | null\n /** Who may message whom inside the Team; see TeamPolicy. */\n policyMode: TeamPolicyMode\n createdAt: Timestamp\n}\n\n/** The Team and the Profile first-run setup creates. */\nexport const DEFAULT_TEAM_ID = 'default'\n\n/** The longest Agent name, the same in the web, the CLI and the API. */\nexport const AGENT_NAME_MAX = 120\n\n/** The longest role an Agent can be given when it is added (\"What is it for?\"). */\nexport const AGENT_ROLE_MAX = 4_000\n\n/**\n * Why a name cannot be an Agent's, or null. A name is one line of visible text: it is shown in\n * every teammate's instructions, so line breaks and control or format characters are refused.\n */\nexport function agentNameProblem(name: string): string | null {\n if (!name.trim()) return 'A name cannot be empty.'\n if (name.length > AGENT_NAME_MAX) return `A name is at most ${AGENT_NAME_MAX} characters.`\n if (/[\\p{Cc}\\p{Cf}\\u2028\\u2029]/u.test(name)) {\n return 'A name is one line of text, without control characters.'\n }\n return null\n}\nexport const DEFAULT_PROFILE_ID = 'default'\n\nexport type SkillsMode = 'all' | 'selected'\n\nexport interface Profile {\n id: string\n name: string\n dir: string\n defaultModel: string\n skillsMode: SkillsMode\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\n/**\n * open: Team members may message each other freely. restricted: a member may message a\n * teammate only along an allow edge. Messages between Teams always need an edge to\n * `outside` in the sender's Team and one from `outside` in the recipient's Team.\n */\nexport type TeamPolicyMode = 'open' | 'restricted'\n\n/** Edge endpoint standing for every Agent in other Teams. */\nexport const OUTSIDE_TEAM = 'outside'\n\n/** Directed allow edge between a member Agent id and another member or `outside`. */\nexport interface TeamPolicyEdge {\n from: string\n to: string\n}\n\nexport interface TeamPolicy {\n teamId: string\n mode: TeamPolicyMode\n edges: TeamPolicyEdge[]\n /** The Team's members, archived Agents included. */\n members: Agent[]\n}\n\nexport interface TeamTemplateSlot {\n profileId: string\n agentName: string\n modelOverride: string | null\n reasoningLevel: ReasoningLevel | null\n /** Node position in the template's Flow editor. */\n layoutPosition: { x: number; y: number } | null\n}\n\n/** A slot position (index into `slots`) or `outside`. */\nexport type TeamTemplateEndpoint = number | typeof OUTSIDE_TEAM\n\nexport interface TeamTemplateEdge {\n from: TeamTemplateEndpoint\n to: TeamTemplateEndpoint\n}\n\n/** A reusable roster: spawning it creates one Agent per slot plus the edges between them. */\nexport interface TeamTemplate {\n id: string\n name: string\n userMd: string | null\n policyMode: TeamPolicyMode\n slots: TeamTemplateSlot[]\n edges: TeamTemplateEdge[]\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport type AgentStatus = 'idle' | 'archived'\n\nexport type ReasoningLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'\n\nexport const REASONING_LEVELS: ReasoningLevel[] = [\n 'off',\n 'minimal',\n 'low',\n 'medium',\n 'high',\n 'xhigh',\n]\n\n/**\n * Telegram outbound-mirror verbosity per agent.\n * 'minimal' — final assistant message only (default).\n * 'verbose' — also surfaces concise tool-call summary lines.\n */\nexport type TelegramMirrorMode = 'minimal' | 'verbose'\n\nexport interface Agent {\n id: string\n profileId: string\n name: string\n modelOverride: string | null\n reasoningLevel: ReasoningLevel\n reviewEnabled: boolean\n reviewEveryNTurns: number\n reviewModel: string | null\n reviewReasoningLevel: ReasoningLevel\n reviewTurnsSinceLast: number\n status: AgentStatus\n dir: string\n /** The team this agent belongs to. Every agent has exactly one. */\n teamId: string\n /**\n * Forum-topic id this agent is bound to in the configured Telegram\n * supergroup, or `null` when unbound. Web UI shows binding state +\n * deep-link based on this.\n */\n telegramTopicId: number | null\n /** Verbosity of the Telegram outbound mirror for this agent. */\n telegramMirrorMode: TelegramMirrorMode\n /**\n * Per-agent override of the forum-topic emoji icon (a single emoji char,\n * e.g. \"📚\"). `null` falls back to the profile-name default\n * (`BUILTIN_PROFILE_EMOJI`), then to color-only. Resolved to a Telegram\n * custom_emoji_id at topic-creation time.\n */\n telegramIconEmoji: string | null\n createdAt: Timestamp\n archivedAt: Timestamp | null\n /**\n * Structured fields parsed from the agent's own IDENTITY.md (name, emoji,\n * creature, vibe, avatar). File-derived, not a DB column — populated by the\n * agent list + detail routes, omitted (undefined) by the bare repo reads.\n * `null` once parsed means the file has no real values yet (still the\n * placeholder template). Lets the UI show avatar/creature without an extra\n * round-trip.\n */\n identity?: AgentIdentityFile | null\n}\n\nexport type AgentReviewStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'\nexport type AgentReviewTrigger = 'cadence' | 'manual'\n\nexport interface AgentReview {\n id: string\n agentId: string\n status: AgentReviewStatus\n trigger: AgentReviewTrigger\n sourceSessionId: string | null\n sourceStartOrdinal: number | null\n sourceEndOrdinal: number | null\n inputCharacters: number\n turnsReviewed: number\n proposalCount: number\n startedAt: Timestamp | null\n finishedAt: Timestamp | null\n lastError: string | null\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport type AgentLessonScope = 'private' | 'shared'\nexport type AgentLessonStatus = 'pending' | 'approved' | 'rejected' | 'revoked'\n\nexport interface AgentLessonEvidence {\n sessionId: string\n entryOrdinal: number\n /** Redacted canonical-session excerpt, populated on read and never stored with the proposal. */\n excerpt?: string\n}\n\nexport interface AgentLessonProposal {\n id: string\n reviewId: string\n agentId: string\n scope: AgentLessonScope\n text: string\n evidence: AgentLessonEvidence[]\n status: AgentLessonStatus\n version: number\n decidedAt: Timestamp | null\n revokedAt: Timestamp | null\n appliedKey: string | null\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport interface AgentSkillAttachment {\n agentId: string\n skillName: string\n attachedAt: Timestamp\n}\n\nexport type TelegramAclRole = 'owner' | 'member'\n\n/**\n * A Telegram user allowed to use the bot. Presence in this list grants\n * commands + chat. `owner` (the paired person) manages the list and can't be\n * removed; `member` can use the bot but not manage it.\n */\nexport interface TelegramAllowedUser {\n userId: number\n username: string | null\n label: string | null\n role: TelegramAclRole\n addedAt: Timestamp\n}\n\nexport interface SkillMeta {\n name: string\n source: string | null\n importedAt: Timestamp | null\n}\n\nexport interface Message {\n id: string\n fromAgentId: string\n toAgentId: string\n replyTo: string | null\n causalChainId: string\n causalHop: number\n payload: string\n createdAt: Timestamp\n readAt: Timestamp | null\n}\n\nexport interface AgentLoopBreakEvent {\n id: string\n causalChainId: string\n parentMessageId: string | null\n fromAgentId: string\n toAgentId: string\n sourceTeamId: string\n targetTeamId: string\n attemptedHop: number\n maxHops: number\n reason: string\n origin: string\n createdAt: Timestamp\n}\n\n/** Every token has full access. `expiresAt` null means it never expires. */\nexport interface WebToken {\n id: string\n label: string\n kind: 'bootstrap' | 'device'\n createdAt: Timestamp\n lastUsedAt: Timestamp | null\n expiresAt: Timestamp | null\n revokedAt: Timestamp | null\n}\n\nexport interface WebSession {\n id: string\n /** The token (bootstrap or device) the browser logged in with. */\n tokenId: string\n tokenLabel: string\n createdAt: Timestamp\n lastSeenAt: Timestamp\n /** Moves forward on every use: a session ends once unused for 30 days. */\n expiresAt: Timestamp\n current: boolean\n}\n\nexport type TriggerKind = 'interval' | 'cron'\n\nexport interface AgentTrigger {\n id: string\n agentId: string\n kind: TriggerKind\n intervalSec: number | null\n cronExpr: string | null\n message: string\n enabled: boolean\n lastFiredAt: Timestamp | null\n createdAt: Timestamp\n}\n\n/** pending waits for a free Agent; each occurrence runs at most once. */\nexport type TriggerDispatchStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled'\n\n/** One scheduled occurrence of a trigger: the trigger's run history. */\nexport interface TriggerDispatch {\n conversationId: string\n id: string\n triggerId: string\n agentId: string\n scheduledAt: Timestamp\n status: TriggerDispatchStatus\n startedAt: Timestamp | null\n finishedAt: Timestamp | null\n error: string | null\n}\n\nexport interface OpenAICodexStatus {\n connected: boolean\n /** Unix ms expiry of the current access token; null if disconnected. */\n expiresAt: number | null\n /** chatgpt_account_id extracted from the JWT, when available. */\n accountId: string | null\n}\n\nexport interface AgentIdentityFile {\n name?: string\n emoji?: string\n theme?: string\n creature?: string\n vibe?: string\n avatar?: string\n}\n\n/**\n * The name an Agent gave itself (its IDENTITY.md, usually in its first conversation), when it is\n * not the name it has in the list: \"Sales Director\" that calls itself Sally. Null otherwise.\n */\nexport function chosenName(agent: {\n name: string\n identity?: AgentIdentityFile | null\n}): string | null {\n const own = agent.identity?.name?.trim()\n // An Agent writes its IDENTITY.md itself: a name that breaks the rule for names is not shown,\n // nor put in its teammates' prompts.\n if (!own || agentNameProblem(own)) return null\n return own.toLowerCase() !== agent.name.trim().toLowerCase() ? own : null\n}\n\nexport interface ResolvedAgent {\n agent: Agent\n profile: Profile\n model: string\n reasoningLevel: ReasoningLevel\n team: Team\n skills: string[]\n /** Human-approved, agent-private reviewed lessons injected on every normal turn. */\n privateLessons: string[]\n}\n\nexport type McpTransport = 'stdio' | 'http'\n\n/** A configured MCP server. The HTTP bearer token is never returned. */\nexport interface McpServer {\n id: string\n name: string\n transport: McpTransport\n /** stdio only — executable to spawn. */\n command: string | null\n /** stdio only — arguments. */\n args: string[]\n /** Streamable HTTP only — endpoint URL. */\n url: string | null\n /** Whether an HTTP bearer token is stored for this server. */\n hasAuthToken: boolean\n /** stdio: the names of its own environment variables (a token, a client id); never the values. */\n envNames?: string[]\n /**\n * The operator's choices for single tools: true asks before each call, false never does. Every\n * other tool asks when its name says it sends, posts, shares, creates, changes or deletes\n * something.\n */\n ask?: Record<string, boolean>\n enabled: boolean\n createdAt: number\n updatedAt: number\n}\n\n/** Create/update payload for an MCP server. `authToken` is write-only. */\nexport interface McpServerInput {\n name: string\n transport: McpTransport\n command?: string | null\n args?: string[]\n url?: string | null\n /** HTTP bearer token; stored encrypted. Pass null to clear. */\n authToken?: string | null\n /** stdio: set (a value) or remove (null) its own environment variables; stored encrypted. */\n env?: Record<string, string | null>\n /** Replaces the choices of which tools ask first; null or {} goes back to the default rule. */\n ask?: Record<string, boolean> | null\n enabled?: boolean\n}\n\n/** One tool discovered on an MCP server (returned by the test/connect endpoint). */\nexport interface McpToolInfo {\n name: string\n description: string\n /** It asks the operator before each call: the operator's choice, or else the default rule. */\n asks?: boolean\n /** What the default rule says for it, from its name. */\n asksByDefault?: boolean\n}\n\nexport interface LoadedProfile {\n profile: Profile\n defaultSkills: string[]\n files: {\n soul: string\n identity: string\n bootstrap: string | null\n agents: string | null\n tools: string | null\n }\n /** Structured fields parsed from IDENTITY.md — null when no values are set. */\n identity: AgentIdentityFile | null\n}\n","// Git change review of a Team workspace: the changes since a pinned base, and file feedback.\n\nimport type { UserQueueItem } from './user-queue.ts'\n\n/** Machine-readable issue codes. Messages are for operators and never embed host paths. */\nexport type ReviewIssueCode = 'invalid_base' | 'unknown_base' | 'git_output_limit' | 'file_limit'\n\nexport interface ReviewIssue {\n code: ReviewIssueCode\n message: string\n}\n\n/** Why a path may not be captured. */\nexport type ReviewScopeReason = 'bazilion_state' | 'credential_shaped'\n\nexport interface RepositoryIdentity {\n /** Current branch name, or null when HEAD is detached. */\n branch: string | null\n /** Commit HEAD points at, or null when the branch is unborn. */\n head: string | null\n headState: 'branch' | 'detached' | 'unborn'\n}\n\n/**\n * A comparison point pinned to a concrete commit. `resolvedOid` is the only value a comparison may\n * use; `requestedRef` records what was asked for, so a moved branch tip cannot rewrite a review.\n */\nexport interface PinnedBase {\n requestedRef: string\n resolvedOid: string\n}\n\n/** Bounds applied to a review. */\nexport interface ReviewLimits {\n files: number\n fileBytes: number\n totalBytes: number\n /** Rendered patch cap per file; a longer diff is cut and marked truncated. */\n patchBytes: number\n}\n\n/** 1,000 files, 1 MiB per file diff, 16 MiB of diff text in total. */\nexport const REVIEW_LIMITS: ReviewLimits = {\n files: 1000,\n fileBytes: 1024 * 1024,\n totalBytes: 16 * 1024 * 1024,\n patchBytes: 256 * 1024,\n}\n\nexport type ReviewChangeStatus =\n | 'added'\n | 'modified'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'type_changed'\n | 'unmerged'\n | 'untracked'\n | 'unknown'\n\n/** Why an entry carries no diff text. Never a silent omission. */\nexport type ContentOmission = 'excluded' | 'binary' | 'too_large' | 'total_limit' | 'unavailable'\n\nexport interface ReviewChange {\n /** Repository-relative path, destination side for renames. */\n path: string\n /** Source path for a rename or copy, otherwise null. */\n previousPath: string | null\n status: ReviewChangeStatus\n binary: boolean\n addedLines: number | null\n deletedLines: number | null\n /** Unified diff text, or null when content was omitted or not requested. */\n patch: string | null\n patchTruncated: boolean\n contentOmitted: ContentOmission | null\n /** Set when the path was refused by scope policy. */\n excludedReason: ReviewScopeReason | null\n}\n\n/** \"Changes since baseline\": the pinned base compared against the working tree. */\nexport interface RepositoryChanges {\n base: PinnedBase\n identity: RepositoryIdentity\n changes: ReviewChange[]\n /** True when the change list itself was cut by the file limit. */\n truncated: boolean\n /** Counts of what was *not* listed or captured, so an omission is never invisible. */\n withheld: { untracked: number; excluded: number }\n issues: ReviewIssue[]\n}\n\n/**\n * The Agent whose turn last wrote a changed file with a file tool (`write`, `edit`). A change made\n * by a shell command has no author here.\n */\nexport interface ReviewChangeAuthor {\n agentId: string\n agentName: string\n /** The conversation the write happened in. */\n conversationId: string\n /** When the write happened (epoch ms). */\n at: number\n}\n\nexport interface RepositoryReviewResponse {\n teamId: string\n changes: RepositoryChanges\n /** With `authors=1`: the last Agent to write each changed path, keyed by path. */\n authors?: Record<string, ReviewChangeAuthor>\n}\n\n/** Why a Team has no review: its folder is not a Git repository, or not one that can be read. */\nexport interface ReviewUnavailableResponse {\n teamId: string\n unavailable: { code: 'not_repository' | 'unsupported_layout'; message: string }\n}\n\n/** `GET /api/teams/:id/review`: the review, or why there is none (not an error: 200 either way). */\nexport type TeamReviewResponse = RepositoryReviewResponse | ReviewUnavailableResponse\n\n/** One comment of a review: about a changed file, or about one line of it. */\nexport interface ReviewFeedbackComment {\n /** A path changed since the base. */\n path: string\n /** Line of the file as it is now (1-based). */\n line?: number\n note?: string\n}\n\n/** Queue review feedback for a Team member: every comment in one message. */\nexport interface ReviewFeedbackRequest {\n agentId: string\n comments: ReviewFeedbackComment[]\n /** A note about the review as a whole. */\n note?: string\n /** Comparison base the operator is reviewing (default HEAD). */\n base?: string\n}\n\nexport interface ReviewFeedbackResponse {\n /** The exact message that was queued for the Agent. */\n message: string\n item: UserQueueItem\n}\n","// Common connections for Setup → MCP and `bazilion mcp add --preset`: third-party MCP servers for\n// the services a business Team works in, with what each needs. They run on this computer as stdio\n// servers; their tools that send or change something ask the operator first.\n\nexport interface McpPresetField {\n /** The environment variable it fills. */\n name: string\n label: string\n hint: string\n /** A token or a secret: typed hidden, stored encrypted, never shown again. */\n secret: boolean\n}\n\nexport interface McpPresetOption {\n id: string\n label: string\n hint: string\n /** Arguments it adds to the command. */\n args?: string[]\n /** Variables it sets. */\n env?: Record<string, string>\n}\n\nexport interface McpPreset {\n /** Its id, also the server's name unless another is given. */\n id: string\n title: string\n /** What Agents can do with it. */\n does: string\n command: string\n args: string[]\n /** What it needs filled in; all of them. */\n fields: McpPresetField[]\n options: McpPresetOption[]\n /** What has to be on this computer besides Node.js, which Bazilion already uses. */\n needs?: string\n /** How it signs in to the service. */\n signIn: string\n /** Something worth knowing before relying on it. */\n caveat?: string\n /** Its own setup guide. */\n guide: string\n}\n\nexport const MCP_PRESETS: readonly McpPreset[] = [\n {\n id: 'microsoft365',\n title: 'Microsoft 365',\n does: 'Outlook mail and calendar, OneDrive and Excel; with a work or school account also Teams and SharePoint.',\n command: 'npx',\n args: ['-y', '@softeria/ms-365-mcp-server'],\n fields: [],\n options: [\n {\n id: 'org',\n label: 'A work or school account',\n hint: 'Adds Teams, SharePoint and shared mailboxes.',\n args: ['--org-mode'],\n },\n ],\n signIn:\n 'No key to paste: once it is added, ask any Agent to sign in to Microsoft 365. Its login tool gives a link and a code to enter there, and the Agent then checks the sign-in.',\n guide: 'https://github.com/Softeria/ms-365-mcp-server',\n },\n {\n id: 'google_workspace',\n title: 'Google Workspace',\n does: 'Gmail, Calendar, Drive, Docs and Sheets.',\n command: 'uvx',\n args: ['workspace-mcp', '--tool-tier', 'core'],\n fields: [\n {\n name: 'GOOGLE_OAUTH_CLIENT_ID',\n label: 'OAuth client ID',\n hint: 'From a Google Cloud OAuth client of your own, with the Gmail, Calendar and Drive APIs turned on.',\n secret: false,\n },\n {\n name: 'GOOGLE_OAUTH_CLIENT_SECRET',\n label: 'OAuth client secret',\n hint: 'The same client’s secret.',\n secret: true,\n },\n ],\n options: [],\n needs: 'uv, which provides the uvx command.',\n signIn: 'You sign in to Google in the browser; its guide shows how to make the OAuth client.',\n guide: 'https://github.com/taylorwilsdon/google_workspace_mcp',\n },\n {\n id: 'slack',\n title: 'Slack',\n does: 'Read channels, threads and messages, and search them; post messages when you allow it.',\n command: 'npx',\n args: ['-y', 'slack-mcp-server@latest', '--transport', 'stdio'],\n fields: [\n {\n name: 'SLACK_MCP_XOXP_TOKEN',\n label: 'User token',\n hint: 'Starts with xoxp-: a Slack app’s user token, with the scopes its guide lists.',\n secret: true,\n },\n ],\n options: [\n {\n id: 'post',\n label: 'Let Agents post messages',\n hint: 'Off in this server unless turned on. Each post still asks you first.',\n env: { SLACK_MCP_ADD_MESSAGE_TOOL: 'true' },\n },\n ],\n signIn: 'The token is the sign-in: Agents act as the user who made it.',\n guide: 'https://github.com/korotovsky/slack-mcp-server',\n },\n {\n id: 'notion',\n title: 'Notion',\n does: 'Search, read and write pages and databases you share with it.',\n command: 'npx',\n args: ['-y', '@notionhq/notion-mcp-server'],\n fields: [\n {\n name: 'NOTION_TOKEN',\n label: 'Integration secret',\n hint: 'Starts with ntn_: an internal integration’s secret. Share the pages it may use with that integration.',\n secret: true,\n },\n ],\n options: [],\n signIn: 'The integration secret is the sign-in; it sees only what you share with it.',\n caveat:\n 'Notion no longer maintains this server and recommends its remote one, which needs a browser sign-in Bazilion cannot do yet. It still works with an integration secret.',\n guide: 'https://github.com/makenotion/notion-mcp-server',\n },\n]\n\n/** The server a preset makes, with the options chosen and the fields filled in. */\nexport function presetServer(\n preset: McpPreset,\n options: { name?: string; chosen?: readonly string[]; values?: Record<string, string> },\n): { name: string; command: string; args: string[]; env: Record<string, string> } {\n const chosen = preset.options.filter((option) => options.chosen?.includes(option.id))\n return {\n name: options.name?.trim() || preset.id,\n command: preset.command,\n args: [...preset.args, ...chosen.flatMap((option) => option.args ?? [])],\n env: {\n ...Object.fromEntries(\n preset.fields\n .map((field) => [field.name, options.values?.[field.name]?.trim() ?? ''] as const)\n .filter(([, value]) => value !== ''),\n ),\n ...Object.assign({}, ...chosen.map((option) => option.env ?? {})),\n },\n }\n}\n","import type { Profile, SkillsMode } from './entities.ts'\n\nexport interface CreateProfileRequest {\n id: string\n name?: string\n defaultModel: string\n skillsMode?: SkillsMode\n defaultSkills?: string[]\n /** Initial SOUL.md content. Falls back to the built-in template when omitted. */\n soul?: string\n /** Initial IDENTITY.md content. Falls back to the built-in template when omitted. */\n identity?: string\n /** Initial BOOTSTRAP.md content. Omit for default; pass null to skip bootstrap entirely. */\n bootstrap?: string | null\n /** Initial AGENTS.md content. Omit for the default template; pass null to skip the file. */\n agents?: string | null\n /** Initial TOOLS.md content. Omit for the default template; pass null to skip the file. */\n tools?: string | null\n}\n\nexport interface UpdateProfileRequest {\n name?: string\n defaultModel?: string\n skillsMode?: SkillsMode\n defaultSkills?: string[]\n}\n\n/** One entry of `GET /api/profiles`. */\nexport interface ProfileSummary extends Profile {\n agentCount: number\n defaultSkills: string[]\n}\n\n/** `GET /api/profiles/_/templates`: the built-in starter text of each template file. */\nexport interface ProfileTemplates {\n soul: string\n identity: string\n bootstrap: string\n agents: string\n tools: string\n}\n\nexport type ProfileFileName = 'SOUL.md' | 'IDENTITY.md' | 'BOOTSTRAP.md' | 'AGENTS.md' | 'TOOLS.md'\n\nexport const PROFILE_FILES: ProfileFileName[] = [\n 'SOUL.md',\n 'IDENTITY.md',\n 'BOOTSTRAP.md',\n 'AGENTS.md',\n 'TOOLS.md',\n]\n\nexport interface FileContentResponse {\n content: string\n}\n\nexport interface PutFileRequest {\n content: string\n}\n","/** A file an Agent delivered or generated, saved by the daemon. */\nexport interface AgentResult {\n id: string\n teamId: string\n agentId: string\n /** The conversation it was delivered in. */\n sessionId: string\n toolCallId: string\n /** Position among the images of one image_generate call; 0 otherwise. */\n sourceIndex: number\n name: string\n mimeType: string\n byteLength: number\n sha256: string\n /** The image model that generated it; null for delivered files. */\n imageModel: string | null\n createdAt: number\n}\n\n/** Kept in the tool result of the transcript; resolved through the daemon. */\nexport interface ResultReference {\n resultId: string\n}\n\nexport interface ResultListResponse {\n results: AgentResult[]\n total: number\n offset: number\n limit: number\n}\n\n/** The most of a text file the daemon previews, in bytes. */\nexport const TEXT_PREVIEW_MAX_BYTES = 256 * 1024\n\nconst TEXT_TYPES = new Set([\n 'application/json',\n 'application/ld+json',\n 'application/xml',\n 'application/yaml',\n 'application/x-yaml',\n 'application/toml',\n 'application/javascript',\n 'application/x-sh',\n 'application/sql',\n 'application/x-ndjson',\n])\n\n/** Files sent without a text type (`application/octet-stream`) that are text by their name. */\nconst TEXT_EXTENSIONS = new Set(\n (\n 'txt md markdown csv tsv json jsonl ndjson yaml yml toml ini cfg conf log xml css scss ' +\n 'js mjs cjs jsx ts tsx py rb go rs java kt swift c h cc cpp hpp cs php sh bash zsh fish ps1 ' +\n 'sql r lua pl tex diff patch vue svelte graphql proto dockerfile makefile'\n ).split(' '),\n)\n\n/** Pages a browser would run are only ever downloaded, never shown, not even as text. */\nconst ACTIVE_TYPES = new Set(['text/html', 'application/xhtml+xml', 'image/svg+xml'])\n\n/** Whether Files can show a saved file as text: its type or its name says text, and it is small. */\nexport function isTextPreview(\n result: Pick<AgentResult, 'mimeType' | 'name' | 'byteLength'>,\n): boolean {\n if (result.byteLength > TEXT_PREVIEW_MAX_BYTES) return false\n const type = result.mimeType.toLowerCase()\n if (ACTIVE_TYPES.has(type)) return false\n if (type.startsWith('text/') || TEXT_TYPES.has(type) || /\\+(json|xml)$/.test(type)) return true\n if (type !== 'application/octet-stream') return false\n const name = result.name.toLowerCase()\n const extension = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : name\n return TEXT_EXTENSIONS.has(extension)\n}\n","/**\n * What models were used for, read from the conversations' saved history: every reply, summary and\n * cache warm-up Pi records there, with its tokens and cost.\n */\n\n/** How a provider charges: per use, through a subscription, or not at all (a server here). */\nexport type UsageBilling = 'paid' | 'plan' | 'local'\n\nexport interface UsageTotals {\n /** Model calls counted: replies, conversation summaries, cache warm-ups. */\n calls: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheWriteTokens: number\n totalTokens: number\n /**\n * US dollars spent on providers paid per use: what the provider reported it billed, otherwise\n * Pi's catalog price for the tokens.\n */\n cost: number\n /** Some of `cost` is a catalog estimate rather than a billed amount. */\n estimated: boolean\n /** Tokens used through a subscription (a ChatGPT plan, Copilot, a token plan): no cost per use. */\n planTokens: number\n /** Tokens on a model server on this computer. */\n localTokens: number\n /** Tokens on providers paid per use whose model has no price in Pi's catalog: not in `cost`. */\n unpricedTokens: number\n}\n\nexport interface UsageDay extends UsageTotals {\n /** `YYYY-MM-DD` in the report's time zone. */\n day: string\n}\n\nexport interface UsageByAgent extends UsageTotals {\n agentId: string\n agentName: string\n teamId: string\n teamName: string\n archived: boolean\n}\n\nexport interface UsageByTeam extends UsageTotals {\n teamId: string\n teamName: string\n}\n\nexport interface UsageByModel extends UsageTotals {\n /** Pi's provider id, as the history records it. */\n provider: string\n /** The provider as Setup names it. */\n providerName: string\n model: string\n billing: UsageBilling\n}\n\nexport interface UsageReport {\n /** The days counted, today included; null for everything saved. */\n days: number | null\n timeZone: string\n /** The first and last day counted (`YYYY-MM-DD`); `from` is null for everything saved. */\n from: string | null\n to: string\n totals: UsageTotals\n /** Every day of the period, oldest first (only days with use for everything saved). */\n byDay: UsageDay[]\n /** Most spent first, then most tokens. */\n byAgent: UsageByAgent[]\n byTeam: UsageByTeam[]\n byModel: UsageByModel[]\n /** Saved conversations that could not be read, and so are not counted. */\n unreadable: number\n /** The one Agent or Team counted, when the report is limited to it. */\n scope: { kind: 'agent' | 'team'; id: string; name: string } | null\n}\n\n/** One conversation's use, shown beside it in the conversation list. */\nexport interface ConversationUsage {\n calls: number\n totalTokens: number\n cost: number\n estimated: boolean\n planTokens: number\n localTokens: number\n}\n\n/** US dollars as Usage shows them: `$0.42`, `<$0.01`, `$1,234`. */\nexport function formatCost(usd: number): string {\n if (usd <= 0) return '$0.00'\n if (usd < 0.01) return '<$0.01'\n if (usd < 1000) return `$${usd.toFixed(2)}`\n return `$${Math.round(usd).toLocaleString('en-US')}`\n}\n\n/** A use in a few words: `$0.42 · 12k tokens`, `15k tokens, on a plan`, `3.1k tokens, local`. */\nexport function usageSummary(\n usage: Pick<UsageTotals, 'cost' | 'totalTokens' | 'planTokens' | 'localTokens'>,\n): string {\n const tokens = `${formatTokens(usage.totalTokens)} tokens`\n if (usage.cost > 0) return `${formatCost(usage.cost)} · ${tokens}`\n if (usage.totalTokens > 0 && usage.planTokens === usage.totalTokens) return `${tokens}, on a plan`\n if (usage.totalTokens > 0 && usage.localTokens === usage.totalTokens) return `${tokens}, local`\n return tokens\n}\n\n/** A token count in a few characters: `950`, `12.5k`, `3.4M`. */\nexport function formatTokens(tokens: number): string {\n if (tokens < 1000) return String(Math.round(tokens))\n if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(tokens < 10_000 ? 1 : 0)}k`\n return `${(tokens / 1_000_000).toFixed(tokens < 10_000_000 ? 1 : 0)}M`\n}\n","import {\n type Conversation,\n type ConversationListResponse,\n type ConversationSearchResponse,\n type ConversationUsage,\n type ProviderMessage,\n usageSummary,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport {\n agentArg,\n apiPath,\n jsonFlag,\n positional,\n printJson,\n terminalSafe,\n} from '../command-helpers.ts'\n\nconst conversationArg = positional('Conversation id')\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List conversations; the active one receives new messages' },\n args: {\n agent: agentArg,\n limit: { type: 'string', default: '20', description: 'Page size' },\n offset: { type: 'string', default: '0', description: 'Conversations to skip' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ limit: args.limit, offset: args.offset })\n const body = await createClient().get<ConversationListResponse>(\n `${apiPath('agents', args.agent, 'conversations')}?${query}`,\n )\n if (args.json) return printJson(body)\n if (!body.total) return console.log('(no conversations)')\n for (const line of columnize([\n ['id', 'title', 'active', 'used'],\n ...body.conversations.map((item) => {\n const used = body.usage[item.id]\n return [\n item.id,\n item.title,\n item.id === body.selectedId ? 'yes' : '',\n used ? usageSummary(used) : '',\n ]\n }),\n ]))\n console.log(line)\n },\n})\n\nconst search = defineCommand({\n meta: {\n name: 'search',\n description: \"Find the messages that hold every word, in every Agent's conversations\",\n },\n args: {\n query: positional('Words to find (quote several: \"launch email\")'),\n agent: { type: 'string', description: 'Only this Agent (id or name)' },\n limit: { type: 'string', default: '20', description: 'Most messages listed (up to 50)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ q: args.query, limit: args.limit })\n if (args.agent) query.set('agent', args.agent)\n const body = await createClient().get<ConversationSearchResponse>(\n `/api/conversations/search?${query}`,\n )\n if (args.json) return printJson(body)\n if (body.hits.length === 0) console.log('(no messages hold every word)')\n for (const hit of body.hits) {\n const when = hit.at ? new Date(hit.at).toISOString().slice(0, 16).replace('T', ' ') : ''\n console.log(\n terminalSafe(\n `${hit.agentName} · ${hit.conversationTitle}${hit.active ? ' (active)' : ''} · ${hit.role === 'user' ? 'you' : hit.agentName} ${when}`,\n ),\n )\n console.log(` ${terminalSafe(hit.snippet)}`)\n console.log(` bazilion conversation show ${hit.agentId.slice(0, 8)} ${hit.conversationId}`)\n }\n if (body.truncated) console.log(`Only the newest ${body.hits.length}; use --limit for more.`)\n if (body.unreadable > 0)\n console.log(\n `${body.unreadable} conversation${body.unreadable === 1 ? '' : 's'} could not be read.`,\n )\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Read a conversation without making it active' },\n args: { agent: agentArg, id: conversationArg, json: jsonFlag },\n async run({ args }) {\n const body = await createClient().get<{\n conversation: Conversation\n messages: ProviderMessage[]\n usage: ConversationUsage | null\n }>(apiPath('agents', args.agent, 'conversations', args.id))\n if (args.json) return printJson(body)\n console.log(\n body.usage\n ? `${body.conversation.title} (${usageSummary(body.usage)})`\n : body.conversation.title,\n )\n for (const message of body.messages) console.log(`[${message.role}] ${message.content}`)\n },\n})\n\nconst newConversation = defineCommand({\n meta: {\n name: 'new',\n description: 'Start a new conversation and make it active; earlier ones stay readable',\n },\n args: {\n agent: agentArg,\n title: { type: 'string', description: 'Title (default: generated)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const conversation = await createClient().post<Conversation>(\n apiPath('agents', args.agent, 'conversations'),\n args.title ? { title: args.title } : {},\n )\n if (args.json) return printJson(conversation)\n console.log(`Conversation ${conversation.id}: ${conversation.title} (active)`)\n },\n})\n\nconst rename = defineCommand({\n meta: { name: 'rename', description: 'Rename a conversation' },\n args: {\n agent: agentArg,\n id: conversationArg,\n title: positional('New title'),\n json: jsonFlag,\n },\n async run({ args }) {\n const body = await createClient().patch<{ conversation: Conversation }>(\n apiPath('agents', args.agent, 'conversations', args.id),\n { title: args.title },\n )\n if (args.json) return printJson(body)\n console.log(body.conversation.title)\n },\n})\n\nconst select = defineCommand({\n meta: {\n name: 'select',\n description: 'Switch to an earlier conversation: new messages continue it',\n },\n args: { agent: agentArg, id: conversationArg, json: jsonFlag },\n async run({ args }) {\n const body = await createClient().post<{ conversation: Conversation }>(\n apiPath('agents', args.agent, 'conversations', args.id, 'select'),\n )\n if (args.json) return printJson(body)\n console.log(`Conversation ${body.conversation.id}: ${body.conversation.title} (active)`)\n },\n})\n\nexport const conversationCommand = defineCommand({\n meta: {\n name: 'conversation',\n description: 'List, read, start, rename and switch Agent conversations',\n },\n subCommands: { list, show, new: newConversation, rename, select, search },\n})\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { connect } from 'node:net'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { resolveCliPaths } from '../paths.ts'\nimport { daemonEntry, nodeArgs } from './serve.ts'\n\nconst bundledWebServerEntry = join(import.meta.dirname, 'web-server.js')\nconst sourceWebServerEntry = join(import.meta.dirname, '..', 'web-server.ts')\nconst webServerEntry = existsSync(bundledWebServerEntry)\n ? bundledWebServerEntry\n : sourceWebServerEntry\n\nconst bundledWebDist = join(import.meta.dirname, 'web')\nconst sourceWebDist = join(import.meta.dirname, '..', '..', '..', 'web', 'dist')\nconst webDist = existsSync(bundledWebDist) ? bundledWebDist : sourceWebDist\n\nasync function responds(url: string): Promise<boolean> {\n try {\n const res = await fetch(url)\n return res.status >= 200 && res.status < 500\n } catch {\n return false\n }\n}\n\nfunction probeHost(host: string): string {\n if (host === '0.0.0.0') return '127.0.0.1'\n if (host === '::') return '::1'\n return host\n}\n\nfunction isTcpPortOpen(host: string, port: string): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = connect({ host: probeHost(host), port: Number(port) })\n const done = (open: boolean): void => {\n socket.removeAllListeners()\n socket.destroy()\n resolve(open)\n }\n socket.setTimeout(600)\n socket.once('connect', () => done(true))\n socket.once('timeout', () => done(false))\n socket.once('error', () => done(false))\n })\n}\n\nasync function bazilionDaemonRunning(url: string, port: string): Promise<boolean> {\n try {\n const res = await fetch(`${url}/api/health`)\n if (res.ok) {\n const body = (await res.json().catch(() => null)) as { ok?: unknown } | null\n if (body?.ok === true) return true\n }\n } catch {\n return false\n }\n\n throw new Error(\n `port ${port} is already serving HTTP, but it is not a healthy bazilion daemon. Re-run with --daemon-port <free-port>.`,\n )\n}\n\nasync function bazilionWebRunning(url: string, port: string): Promise<boolean> {\n try {\n const res = await fetch(url)\n if (res.status >= 200 && res.status < 500) {\n const html = await res.text()\n if (html.includes('<title>bazilion</title>') || html.includes('>bazilion<')) {\n return true\n }\n }\n } catch {\n return false\n }\n\n throw new Error(\n `port ${port} is already serving HTTP, but it is not the bazilion web UI. Re-run with --port <free-port>.`,\n )\n}\n\nasync function waitFor(url: string, label: string, timeoutMs = 20_000): Promise<void> {\n const start = Date.now()\n while (Date.now() - start < timeoutMs) {\n if (await responds(url)) return\n await new Promise((r) => setTimeout(r, 150))\n }\n throw new Error(`timed out waiting for ${label} at ${url}`)\n}\n\nfunction openBrowser(url: string): void {\n const cmd = process.platform === 'darwin' ? 'open' : process.env.BROWSER || 'xdg-open'\n spawn(cmd, [url], { detached: true, stdio: 'ignore' }).unref()\n}\n\nfunction spawnProcess(label: string, entry: string, env: NodeJS.ProcessEnv): ChildProcess {\n if (!existsSync(entry)) {\n throw new Error(`${label} entry not found at ${entry}`)\n }\n return spawn(process.execPath, nodeArgs(entry), {\n env,\n stdio: 'inherit',\n })\n}\n\nexport const dashboardCommand = defineCommand({\n meta: {\n name: 'dashboard',\n description: 'Start the bazilion daemon and bundled web UI',\n },\n args: {\n port: { type: 'string', description: 'Web UI port (default 4322)' },\n host: { type: 'string', description: 'Web UI host (default 127.0.0.1)' },\n 'daemon-port': { type: 'string', description: 'Daemon port (default 4321)' },\n 'daemon-host': { type: 'string', description: 'Daemon host (default 127.0.0.1)' },\n open: {\n type: 'boolean',\n description: 'Open the dashboard in your browser (default true)',\n default: true,\n },\n },\n async run({ args }) {\n const webHost = args.host ?? '127.0.0.1'\n const webPort = args.port ?? '4322'\n const daemonHost = args['daemon-host'] ?? '127.0.0.1'\n const daemonPort = args['daemon-port'] ?? '4321'\n const daemonUrl = `http://${daemonHost}:${daemonPort}`\n const webUrl = `http://${webHost}:${webPort}`\n const authFile = resolveCliPaths().authFile\n\n if (webHost !== '127.0.0.1' && webHost !== 'localhost' && webHost !== '::1') {\n console.error('')\n console.error(\n `warning: binding web UI to ${webHost} - the dashboard may be reachable beyond loopback.`,\n )\n console.error(' keep it behind a trusted network or a TLS proxy.')\n console.error('')\n }\n\n const children: ChildProcess[] = []\n let signalled = false\n const terminateChildren = (): void => {\n signalled = true\n for (const child of children) {\n try {\n child.kill('SIGTERM')\n } catch {}\n }\n }\n\n try {\n const daemonRunning = await bazilionDaemonRunning(daemonUrl, daemonPort)\n if (daemonRunning) {\n console.log(`using existing bazilion daemon at ${daemonUrl}`)\n } else {\n if (await isTcpPortOpen(daemonHost, daemonPort)) {\n throw new Error(\n `daemon port ${daemonPort} is already in use. Re-run with --daemon-port <free-port>.`,\n )\n }\n console.log(`starting bazilion daemon at ${daemonUrl}`)\n const daemon = spawnProcess('daemon', daemonEntry, {\n ...process.env,\n HOST: daemonHost,\n PORT: daemonPort,\n })\n children.push(daemon)\n await waitFor(`${daemonUrl}/api/health`, 'bazilion daemon')\n }\n\n const webRunning = await bazilionWebRunning(webUrl, webPort)\n if (webRunning) {\n console.log(`using existing bazilion web UI at ${webUrl}`)\n } else {\n if (await isTcpPortOpen(webHost, webPort)) {\n throw new Error(\n `web UI port ${webPort} is already in use. Re-run with --port <free-port>.`,\n )\n }\n if (!existsSync(join(webDist, 'server', 'server.js'))) {\n throw new Error(\n `bazilion web UI bundle not found at ${webDist}. Run \"pnpm --filter @bazilion/web build\" from the repository root of a source checkout, or reinstall the published package.`,\n )\n }\n console.log(`starting bazilion web UI at ${webUrl}`)\n const web = spawnProcess('web UI', webServerEntry, {\n ...process.env,\n WEB_HOST: webHost,\n WEB_PORT: webPort,\n BAZILION_DAEMON: daemonUrl,\n BAZILION_WEB_DIST: webDist,\n })\n children.push(web)\n await waitFor(webUrl, 'bazilion web UI')\n }\n\n console.log('')\n console.log(`dashboard: ${webUrl}`)\n console.log(`sign in: the token in ${authFile} (print it: bazilion token show-local)`)\n if (args.open) openBrowser(webUrl)\n } catch (err) {\n terminateChildren()\n throw err\n }\n\n if (children.length === 0) return\n\n process.on('SIGINT', terminateChildren)\n process.on('SIGTERM', terminateChildren)\n\n await new Promise<void>((resolve) => {\n let remaining = children.length\n for (const child of children) {\n child.on('close', (code) => {\n remaining--\n if (!signalled && code && code !== 0) process.exitCode = code\n if (remaining === 0) resolve()\n })\n }\n })\n\n if (signalled) process.exitCode = 0\n },\n})\n","import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\n\n// A published build has dist/daemon.js beside dist/cli.js; a source checkout runs the .ts entry.\nconst bundledDaemonEntry = join(import.meta.dirname, 'daemon.js')\nexport const daemonEntry = existsSync(bundledDaemonEntry)\n ? bundledDaemonEntry\n : join(import.meta.dirname, '..', '..', '..', 'daemon', 'src', 'index.ts')\n\n/** Arguments for `process.execPath`: a source `.ts` entry loads through tsx. */\nexport function nodeArgs(entry: string): string[] {\n return entry.endsWith('.ts') ? ['--import', import.meta.resolve('tsx/esm'), entry] : [entry]\n}\n\nexport const serveCommand = defineCommand({\n meta: {\n name: 'serve',\n description: 'Start the bazilion daemon (HTTP API)',\n },\n args: {\n port: { type: 'string', description: 'Port (default 4321)' },\n host: {\n type: 'string',\n description: 'Host (default 127.0.0.1). Put a TLS proxy in front before binding 0.0.0.0',\n },\n },\n async run({ args }) {\n if (!existsSync(daemonEntry)) throw new Error(`bazilion daemon not found at ${daemonEntry}`)\n const env: NodeJS.ProcessEnv = { ...process.env }\n if (args.port) env.PORT = args.port\n if (args.host) env.HOST = args.host\n console.log(\"web UI: run 'bazilion dashboard' (it reuses this daemon)\")\n\n // The daemon prints its own startup log and handles SIGINT/SIGTERM; Ctrl+C reaches it\n // through the foreground process group, so this process only forwards SIGTERM and waits.\n const proc = spawn(process.execPath, nodeArgs(daemonEntry), { env, stdio: 'inherit' })\n let signalled = false\n process.on('SIGINT', () => {\n signalled = true\n })\n process.on('SIGTERM', () => {\n signalled = true\n proc.kill('SIGTERM')\n })\n await new Promise<void>((resolve, reject) => {\n proc.on('error', reject)\n proc.on('close', (code) => {\n // A signalled stop exits 0, so a `pnpm tsx … serve` wrapper reports no failure.\n if (!signalled && code) process.exitCode = code\n resolve()\n })\n })\n },\n})\n","import type { HealthReport } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\n\nexport const doctorCommand = defineCommand({\n meta: { name: 'doctor', description: 'Diagnose your bazilion install' },\n async run() {\n const r = await createClient().get<HealthReport>('/api/health/details')\n const check = (label: string, condition: boolean, hint?: string) =>\n console.log(checkLine(label, condition, hint))\n\n console.log(`bazilion home: ${r.home}`)\n console.log()\n console.log('paths')\n check('home dir exists', r.paths.home)\n check('database exists', r.paths.db, 'run: bazilion serve (auto-bootstraps on first run)')\n check('auth.json exists', r.paths.auth, 'run: bazilion serve (auto-bootstraps on first run)')\n check('profiles dir exists', r.paths.profiles)\n check('agents dir exists', r.paths.agents)\n check('skills dir exists', r.paths.skills)\n\n if (r.database) {\n console.log()\n console.log('database')\n if (r.database.ok) {\n console.log(` ${r.database.profiles} profile(s)`)\n console.log(\n ` ${r.database.activeAgents} active agent(s) (${r.database.totalAgents} total)`,\n )\n console.log(` ${r.database.teams} team(s)`)\n } else {\n check('open database', false, r.database.error)\n }\n }\n\n console.log()\n console.log('skills library')\n console.log(` ${r.skills.installed} skill(s) installed`)\n if (r.skills.parseErrors > 0) {\n check('all skills parse', false, `${r.skills.parseErrors} skill(s) have errors`)\n for (const skill of r.skills.broken ?? []) console.log(` ${skill.name}: ${skill.error}`)\n }\n\n console.log()\n console.log('providers (enable one and save at least one model for chat)')\n if (r.providers.configured.length === 0) {\n console.log(' - no cloud providers configured')\n console.log(' (set e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY)')\n } else {\n for (const name of r.providers.configured) {\n console.log(` ✓ ${name}`)\n }\n }\n console.log(\n ` ✓ lmstudio: ${\n r.providers.lmstudio.customEndpointConfigured\n ? 'custom endpoint configured'\n : 'default local endpoint'\n }${r.providers.lmstudio.keyConfigured ? ' (API key configured)' : ''}`,\n )\n console.log(\n ` ✓ ollama: ${\n r.providers.ollama.customEndpointConfigured\n ? 'custom endpoint configured'\n : 'default local endpoint'\n }`,\n )\n\n console.log()\n console.log('web search')\n if (r.webSearch.braveConfigured) {\n console.log(' ✓ Brave Search configured')\n } else {\n console.log(' - Brave Search (set BRAVE_API_KEY — free at https://brave.com/search/api/)')\n }\n if (r.webSearch.searxngConfigured) {\n console.log(' ✓ SearXNG configured')\n } else {\n console.log(' - SearXNG (set SEARXNG_URL if you self-host one)')\n }\n if (!r.webSearch.braveConfigured && !r.webSearch.searxngConfigured) {\n console.log(' - no Brave/SearXNG: Agents on OpenAI/ChatGPT models use hosted search')\n console.log(' backend (BAZILION_WEB_SEARCH_ROUTE) and status: bazilion config list')\n }\n\n console.log()\n console.log('openclaw integration')\n if (r.openclaw.exists) {\n console.log(` ✓ ${r.openclaw.path} found`)\n console.log(' try: bazilion skill import --from openclaw')\n } else {\n console.log(` - ${r.openclaw.path} not found (fine if you don't use OpenClaw)`)\n }\n\n console.log()\n console.log('background jobs')\n console.log(\n ` ${r.scheduler.enabled ? '✓' : '-'} scheduler${\n r.scheduler.enabled ? ` (tick ${r.scheduler.tickMs}ms)` : ' (BAZILION_SCHEDULER=off)'\n }`,\n )\n\n console.log()\n for (const line of runtimeDoctorLines(r)) console.log(line)\n\n console.log()\n console.log('operational counts')\n console.log(` ${r.triggers.active} active trigger(s), ${r.triggers.disabled} disabled`)\n console.log(` ${r.tokens.active} active web token(s)`)\n\n const hasProfiles = (r.database?.ok ? r.database.profiles : 0) > 0\n const hasAgents = (r.database?.ok ? r.database.totalAgents : 0) > 0\n\n console.log()\n if (!r.ok) {\n console.log('installation issues found ✗')\n process.exitCode = 1\n return\n }\n console.log('install is healthy ✓')\n if (!hasProfiles || !hasAgents) {\n console.log('next steps')\n const todo: string[] = []\n if (!hasProfiles) {\n todo.push(' - connect a provider: bazilion provider connect <provider>')\n todo.push(\n ' (anthropic, openai, google, openai-codex after `bazilion auth openai login`,',\n )\n todo.push(' or a local lmstudio / ollama; `bazilion provider list --all` has the rest)')\n }\n if (!hasAgents) todo.push(' - spawn an agent: bazilion agent spawn --profile <id>')\n for (const line of todo) console.log(line)\n }\n },\n})\n\n/** Sandbox and approval apply the same way to every turn: chat, Telegram, schedules and inbox. */\nexport function runtimeDoctorLines(report: Pick<HealthReport, 'shellSecurity'>): string[] {\n const shell = report.shellSecurity\n const lines = ['agent runtime (every turn: chat, Telegram, schedules, inbox)']\n if (!shell.ok) {\n lines.push(checkLine('valid shell-security configuration', false, shell.error))\n return lines\n }\n if (shell.sandboxMode === 'docker') {\n lines.push(\n ` - sandbox: docker (${shell.sandboxImage}) — bash runs in a network-disabled container; host file tools hidden`,\n )\n if (shell.docker) {\n lines.push(\n checkLine(\n `Docker ready (${shell.docker.image})`,\n shell.docker.ready,\n shell.docker.reason ?? undefined,\n ),\n )\n if (shell.docker.remediation) lines.push(` remediation: ${shell.docker.remediation}`)\n }\n } else {\n lines.push(\n ' - sandbox: off — bash and file tools run on the host, unisolated',\n ' set BAZILION_BASH_SANDBOX=docker to sandbox bash',\n )\n }\n lines.push(\n shell.approvalMode === 'dangerous'\n ? ' - dangerous-command approval: on — chat can allow once; unattended turns auto-deny'\n : ' - dangerous-command approval: off — set BAZILION_BASH_APPROVAL=dangerous to opt in',\n )\n return lines\n}\n\nfunction checkLine(label: string, condition: boolean, hint?: string): string {\n const mark = condition ? '✓' : '✗'\n const tail = !condition && hint ? ` — ${hint}` : ''\n return ` ${mark} ${label}${tail}`\n}\n","import type { ListAgentLoopBreaksResponse, ListInboxResponse, Message } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst messageArg = positional('Message id')\n\nfunction decodeText(payload: string): string {\n try {\n const obj = JSON.parse(payload) as { text?: unknown }\n if (typeof obj.text === 'string') return obj.text\n } catch {}\n return payload\n}\n\nfunction messageRow(m: Message): string[] {\n const when = new Date(m.createdAt).toISOString()\n const state = m.readAt ? 'read' : 'NEW'\n const text = decodeText(m.payload)\n const preview = text.length > 60 ? `${text.slice(0, 60)}…` : text\n return [m.id, state, when, `from:${m.fromAgentId.slice(0, 8)}`, `\"${preview}\"`]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List messages in an agent inbox' },\n args: {\n agent: positional('Recipient agent id or prefix'),\n unread: { type: 'boolean', description: 'Only show unread messages' },\n },\n async run({ args }) {\n const { messages } = await createClient().get<ListInboxResponse>(\n `${apiPath('agents', args.agent, 'messages')}${args.unread ? '?unread=1' : ''}`,\n )\n printRows(messages.map(messageRow), args.unread ? '(no unread messages)' : '(inbox empty)')\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show a single message in full' },\n args: { id: messageArg },\n async run({ args }) {\n const m = await createClient().get<Message>(apiPath('messages', args.id))\n const when = new Date(m.createdAt).toISOString()\n const read = m.readAt ? new Date(m.readAt).toISOString() : '(unread)'\n console.log(`id: ${m.id}`)\n console.log(`from: ${m.fromAgentId}`)\n console.log(`to: ${m.toAgentId}`)\n console.log(`created: ${when}`)\n console.log(`read: ${read}`)\n if (m.replyTo) console.log(`reply_to: ${m.replyTo}`)\n console.log('')\n console.log(decodeText(m.payload))\n },\n})\n\nconst readCmd = defineCommand({\n meta: { name: 'read', description: 'Mark a message as read' },\n args: { id: messageArg },\n async run({ args }) {\n await createClient().patch<Message>(apiPath('messages', args.id), { read: true })\n console.log(`marked read: ${args.id}`)\n },\n})\n\nconst loopBreaksCmd = defineCommand({\n meta: { name: 'loop-breaks', description: 'List stopped agent-message chains' },\n args: {\n agent: agentArg,\n limit: { type: 'string', description: 'Maximum events to show (default 25)' },\n },\n async run({ args }) {\n const limit = args.limit ? `?limit=${encodeURIComponent(args.limit)}` : ''\n const { events } = await createClient().get<ListAgentLoopBreaksResponse>(\n `${apiPath('agents', args.agent, 'loop-breaks')}${limit}`,\n )\n printRows(\n events.map((event) => [\n new Date(event.createdAt).toISOString(),\n `chain:${event.causalChainId.slice(0, 8)}`,\n `${event.fromAgentId.slice(0, 8)}→${event.toAgentId.slice(0, 8)}`,\n `hop:${event.attemptedHop}/${event.maxHops}`,\n event.reason,\n ]),\n '(no agent-message chains stopped)',\n )\n },\n})\n\nexport const inboxCommand = defineCommand({\n meta: { name: 'inbox', description: 'Inspect agent inboxes' },\n subCommands: {\n list: listCmd,\n show: showCmd,\n read: readCmd,\n 'loop-breaks': loopBreaksCmd,\n },\n})\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { defineCommand } from 'citty'\nimport type { AuthFile } from '../auth-file.ts'\nimport { resolveCliPaths } from '../paths.ts'\n\nfunction normalizeServer(raw: string): string {\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n throw new Error(`invalid --server URL: ${raw}`)\n }\n if (!/^https?:$/.test(url.protocol)) {\n throw new Error(`--server must be http(s), got ${url.protocol}`)\n }\n // Strip trailing slash so `${serverUrl}${path}` never produces `//`.\n return `${url.origin}${url.pathname.replace(/\\/$/, '')}`\n}\n\nasync function verifyToken(server: string, token: string): Promise<void> {\n const res = await fetch(`${server}/api/auth/whoami`, {\n headers: { authorization: `Bearer ${token}`, origin: server },\n })\n if (res.status === 401) throw new Error('server rejected token (401)')\n if (!res.ok) throw new Error(`server returned ${res.status} from /api/auth/whoami`)\n const owner = (await res.json()) as { publicOrigin?: string | null }\n if (owner.publicOrigin && owner.publicOrigin !== new URL(server).origin) {\n throw new Error('server canonical private origin does not match --server')\n }\n}\n\nexport const loginCommand = defineCommand({\n meta: {\n name: 'login',\n description: 'Save a remote bazilion server + token pair to auth.json',\n },\n args: {\n server: { type: 'string', description: 'Remote server URL (http[s]://...)' },\n token: { type: 'string', description: 'Token issued by `bazilion token create`' },\n 'skip-verify': { type: 'boolean', description: \"Don't verify /api/auth/whoami before saving\" },\n clear: { type: 'boolean', description: 'Remove the stored remote instead of setting one' },\n },\n async run({ args }) {\n const paths = resolveCliPaths()\n if (!existsSync(paths.authFile)) {\n throw new Error(\n `${paths.authFile} not found. Start the daemon with \"bazilion serve\" first — login stores the remote there.`,\n )\n }\n const auth = JSON.parse(readFileSync(paths.authFile, 'utf8')) as AuthFile\n\n if (args.clear) {\n if (!auth.remote) {\n console.log('no remote stored — nothing to clear')\n return\n }\n delete auth.remote\n writeFileSync(paths.authFile, `${JSON.stringify(auth, null, 2)}\\n`, { mode: 0o600 })\n console.log('cleared stored remote; CLI will fall back to the local daemon')\n return\n }\n\n if (!args.server || !args.token) {\n throw new Error(\n '--server and --token are required (or pass --clear to remove the stored remote)',\n )\n }\n const server = normalizeServer(args.server)\n if (!args['skip-verify']) {\n await verifyToken(server, args.token)\n }\n auth.remote = { server, token: args.token }\n writeFileSync(paths.authFile, `${JSON.stringify(auth, null, 2)}\\n`, { mode: 0o600 })\n console.log(`saved remote: ${server}`)\n console.log('CLI will now target this server unless BAZILION_SERVER is set in the env.')\n },\n})\n","import {\n MCP_PRESETS,\n type McpServer,\n type McpServerInput,\n type McpToolInfo,\n type McpTransport,\n presetServer,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printJson, printRows } from '../command-helpers.ts'\nimport { collectFlagValues } from '../repeatable-args.ts'\n\nconst serverArg = positional('MCP server id')\n\nfunction serverRow(s: McpServer): string[] {\n const where = s.transport === 'stdio' ? `${s.command} ${s.args.join(' ')}`.trim() : (s.url ?? '')\n return [\n s.id,\n s.enabled ? 'enabled' : 'disabled',\n s.transport,\n s.hasAuthToken ? 'auth' : '-',\n s.name,\n where,\n ]\n}\n\n/** `NAME=value` flags as an object; a bare `NAME` (for --unset-env) maps to null. */\nfunction envFlags(\n raw: readonly string[],\n name: string,\n unset = false,\n): Record<string, string | null> {\n const env: Record<string, string | null> = {}\n for (const value of collectFlagValues(raw, name)) {\n if (unset) {\n env[value] = null\n continue\n }\n const at = value.indexOf('=')\n if (at <= 0) throw new Error(`--${name} takes NAME=value, not ${value}`)\n env[value.slice(0, at)] = value.slice(at + 1)\n }\n return env\n}\n\nconst toolList = (value: string) =>\n value\n .split(',')\n .map((tool) => tool.trim())\n .filter(Boolean)\n\n/**\n * `--ask send-mail --skip get-thing` → those choices, replacing the earlier ones; `--ask default`\n * → none, so every tool follows the default rule. undefined when neither flag is given.\n */\nfunction askFlags(args: {\n ask?: string\n skip?: string\n}): Record<string, boolean> | null | undefined {\n if (args.ask === undefined && args.skip === undefined) return undefined\n if (args.ask === 'default') {\n if (args.skip !== undefined) throw new Error('--ask default cannot go with --skip')\n return null\n }\n const choices: Record<string, boolean> = {}\n for (const tool of toolList(args.ask ?? '')) choices[tool] = true\n for (const tool of toolList(args.skip ?? '')) {\n if (choices[tool]) throw new Error(`${tool} is in both --ask and --skip`)\n choices[tool] = false\n }\n return choices\n}\n\nconst ASK_ARGS = {\n ask: {\n type: 'string',\n description:\n 'Tools that ask you before each call, comma-separated (by default: those whose names send, post, change or delete); \"default\" clears your choices',\n },\n skip: {\n type: 'string',\n description: 'Tools that never ask, comma-separated',\n },\n} as const\n\n/** Which tools ask first, as a line: the default rule and the operator's choices. */\nfunction asksLine(server: McpServer): string {\n const choices = Object.entries(server.ask ?? {})\n if (choices.length === 0) return 'by default'\n return `by default, except ${choices\n .map(([tool, asks]) => `${tool} (${asks ? 'asks' : 'never asks'})`)\n .join(', ')}`\n}\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Register an MCP server, or one of the common connections' },\n args: {\n name: { type: 'positional', required: true, description: 'Unique name ([a-zA-Z0-9_])' },\n preset: {\n type: 'string',\n description: `A common connection: ${MCP_PRESETS.map((preset) => preset.id).join(', ')} (see mcp presets)`,\n },\n option: { type: 'string', description: \"A preset's option, e.g. org or post (repeatable)\" },\n transport: { type: 'string', description: 'stdio | http (default stdio)' },\n command: { type: 'string', description: 'stdio: executable to run (e.g. npx)' },\n args: { type: 'string', description: 'stdio: space-separated args (quote the whole string)' },\n url: { type: 'string', description: 'http: Streamable HTTP endpoint URL' },\n token: { type: 'string', description: 'http: bearer token (stored encrypted)' },\n env: {\n type: 'string',\n description: 'stdio: a variable of its own as NAME=value, stored encrypted (repeatable)',\n },\n ...ASK_ARGS,\n disabled: { type: 'boolean', description: 'Create disabled' },\n },\n async run({ args, rawArgs }) {\n const env = envFlags(rawArgs, 'env')\n let body: McpServerInput\n if (args.preset) {\n const preset = MCP_PRESETS.find((entry) => entry.id === args.preset)\n if (!preset)\n throw new Error(`no common connection \"${args.preset}\"; see bazilion mcp presets`)\n // A preset says how the server runs: these would be ignored.\n const given = (['transport', 'command', 'args', 'url', 'token'] as const).filter(\n (flag) => args[flag] !== undefined,\n )\n if (given.length > 0)\n throw new Error(\n `--preset sets how it runs: leave out ${given.map((f) => `--${f}`).join(', ')}`,\n )\n const chosen = collectFlagValues(rawArgs, 'option')\n const unknown = chosen.filter((id) => !preset.options.some((option) => option.id === id))\n if (unknown.length > 0) {\n const known = preset.options.map((option) => option.id).join(', ')\n throw new Error(\n `${preset.title} has no option ${unknown.join(', ')}${known ? `; its options: ${known}` : ''}`,\n )\n }\n const values = Object.fromEntries(\n Object.entries(env).filter((pair): pair is [string, string] => pair[1] !== null),\n )\n const missing = preset.fields.filter((field) => !values[field.name])\n if (missing.length > 0) {\n throw new Error(\n `${preset.title} needs ${missing.map((field) => `--env ${field.name}=…`).join(' ')}`,\n )\n }\n const made = presetServer(preset, {\n name: args.name,\n chosen,\n values,\n })\n body = {\n name: made.name,\n transport: 'stdio',\n command: made.command,\n args: made.args,\n env: { ...made.env, ...env },\n enabled: !args.disabled,\n }\n } else {\n body = {\n name: args.name,\n transport: (args.transport ?? 'stdio') as McpTransport,\n command: args.command ?? null,\n args: args.args ? args.args.split(' ').filter(Boolean) : [],\n url: args.url ?? null,\n authToken: args.token ?? undefined,\n ...(Object.keys(env).length > 0 ? { env } : {}),\n enabled: !args.disabled,\n }\n }\n const ask = askFlags(args)\n if (ask !== undefined) body.ask = ask\n const { server } = await createClient().post<{ server: McpServer }>('/api/mcp-servers', body)\n console.log(`${server.id}\\t${server.name}\\t${server.transport}`)\n },\n})\n\nconst presetsCmd = defineCommand({\n meta: { name: 'presets', description: 'List the common connections mcp add --preset knows' },\n run() {\n for (const preset of MCP_PRESETS) {\n console.log(`${preset.id}\\t${preset.title}: ${preset.does}`)\n console.log(` runs: ${[preset.command, ...preset.args].join(' ')}`)\n for (const field of preset.fields) console.log(` --env ${field.name}=… ${field.hint}`)\n for (const option of preset.options) console.log(` --option ${option.id} ${option.hint}`)\n if (preset.needs) console.log(` needs: ${preset.needs}`)\n console.log(` sign-in: ${preset.signIn}`)\n if (preset.caveat) console.log(` note: ${preset.caveat}`)\n console.log(` guide: ${preset.guide}`)\n }\n },\n})\n\nconst setCmd = defineCommand({\n meta: { name: 'set', description: \"Change a server's own variables or which tools ask first\" },\n args: {\n id: serverArg,\n env: { type: 'string', description: 'Set a variable as NAME=value (repeatable)' },\n 'unset-env': { type: 'string', description: 'Remove a variable by name (repeatable)' },\n ...ASK_ARGS,\n },\n async run({ args, rawArgs }) {\n const env = { ...envFlags(rawArgs, 'env'), ...envFlags(rawArgs, 'unset-env', true) }\n const body: Partial<McpServerInput> = {}\n if (Object.keys(env).length > 0) body.env = env\n const ask = askFlags(args)\n if (ask !== undefined) body.ask = ask\n if (Object.keys(body).length === 0)\n throw new Error('nothing to change: give --env, --unset-env, --ask or --skip')\n const { server } = await createClient().patch<{ server: McpServer }>(\n apiPath('mcp-servers', args.id),\n body,\n )\n console.log(\n `${server.name}: variables ${server.envNames?.join(', ') || '(none)'}; asks first: ${asksLine(server)}`,\n )\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List MCP servers' },\n async run() {\n const { servers } = await createClient().get<{ servers: McpServer[] }>('/api/mcp-servers')\n printRows(servers.map(serverRow), '(no MCP servers)')\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show one MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n const { server } = await createClient().get<{ server: McpServer }>(\n apiPath('mcp-servers', args.id),\n )\n printJson(server)\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Delete an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().del(apiPath('mcp-servers', args.id))\n console.log(`removed MCP server ${args.id}`)\n },\n})\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Enable an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().patch(apiPath('mcp-servers', args.id), { enabled: true })\n console.log(`enabled MCP server ${args.id}`)\n },\n})\n\nconst disableCmd = defineCommand({\n meta: { name: 'disable', description: 'Disable an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().patch(apiPath('mcp-servers', args.id), { enabled: false })\n console.log(`disabled MCP server ${args.id}`)\n },\n})\n\nconst testCmd = defineCommand({\n meta: { name: 'test', description: 'Connect to a server and list its tools' },\n args: { id: serverArg },\n async run({ args }) {\n const res = await createClient().post<{ ok: boolean; tools?: McpToolInfo[]; error?: string }>(\n apiPath('mcp-servers', args.id, 'test'),\n )\n if (!res.ok) throw new Error(`connection failed: ${res.error}`)\n const tools = res.tools ?? []\n console.log(`connected — ${tools.length} tool(s):`)\n for (const t of tools)\n console.log(` ${t.asks ? '(asks first) ' : ''}${t.name}\\t${t.description}`)\n },\n})\n\nexport const mcpCommand = defineCommand({\n meta: { name: 'mcp', description: 'Manage MCP servers' },\n subCommands: {\n add: addCmd,\n list: listCmd,\n show: showCmd,\n rm: rmCmd,\n enable: enableCmd,\n disable: disableCmd,\n test: testCmd,\n set: setCmd,\n presets: presetsCmd,\n },\n})\n","import type { MemoryEntry, MemoryHit } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, teamArg } from '../command-helpers.ts'\n\nconst keyArg = positional('Memory key (path under memory/, ending in .md)')\n\n/** A key's slashes stay path separators. */\nconst entryPath = (team: string, key: string) => apiPath('teams', team, 'memory', ...key.split('/'))\n\nconst writeCmd = defineCommand({\n meta: { name: 'write', description: \"Write an entry into a team's shared memory\" },\n args: { team: teamArg, key: keyArg, content: positional('Content to write') },\n async run({ args }) {\n const entry = await createClient().put<MemoryEntry>(entryPath(args.team, args.key), {\n content: args.content,\n })\n console.log(`wrote ${entry.key} (${entry.content.length} bytes)`)\n },\n})\n\nconst readCmd = defineCommand({\n meta: { name: 'read', description: \"Read an entry from a team's shared memory\" },\n args: { team: teamArg, key: keyArg },\n async run({ args }) {\n const entry = await createClient().get<MemoryEntry>(entryPath(args.team, args.key))\n console.log(entry.content)\n },\n})\n\nconst searchCmd = defineCommand({\n meta: { name: 'search', description: \"Search a team's shared memory\" },\n args: {\n team: teamArg,\n query: positional('Search terms'),\n limit: { type: 'string', description: 'Max results (default 10)' },\n },\n async run({ args }) {\n const limit = args.limit ? Number.parseInt(args.limit, 10) : 10\n const params = new URLSearchParams({ q: args.query, limit: String(limit) })\n const hits = await createClient().get<MemoryHit[]>(\n `${apiPath('teams', args.team, 'memory', 'search')}?${params}`,\n )\n if (hits.length === 0) {\n console.log('(no matches)')\n return\n }\n for (const h of hits) {\n console.log(`${h.key}\\t${h.snippet.replaceAll('\\n', ' ')}`)\n }\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: \"List all entries in a team's shared memory\" },\n args: { team: teamArg },\n async run({ args }) {\n const all = await createClient().get<MemoryEntry[]>(apiPath('teams', args.team, 'memory'))\n if (all.length === 0) {\n console.log('(no memory entries)')\n return\n }\n for (const e of all) {\n console.log(`${e.key}\\t${e.content.length}b`)\n }\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: \"Remove an entry from a team's shared memory\" },\n args: { team: teamArg, key: keyArg },\n async run({ args }) {\n await createClient().del(entryPath(args.team, args.key))\n console.log(`removed ${args.key}`)\n },\n})\n\nexport const memoryCommand = defineCommand({\n meta: {\n name: 'memory',\n description: \"Manage a team's shared memory (BM25-indexed markdown notes)\",\n },\n subCommands: {\n write: writeCmd,\n read: readCmd,\n search: searchCmd,\n list: listCmd,\n rm: rmCmd,\n },\n})\n","import type { AttentionRecordedKind, NotificationSettingsResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson } from '../command-helpers.ts'\n\nfunction print(settings: NotificationSettingsResponse, json: boolean | undefined): void {\n if (json) {\n printJson(settings)\n return\n }\n const quiet = settings.quietHours\n ? `${settings.quietHours.start}–${settings.quietHours.end} (${settings.timezone})`\n : 'none'\n console.log(`notifications: ${settings.enabled ? 'on' : 'off'}`)\n console.log(`kinds: ${settings.kinds.join(', ')}`)\n console.log(`quiet hours: ${quiet}`)\n if (!settings.telegramReady)\n console.log('telegram: not connected — notices go out once the bot runs')\n}\n\nconst settings = defineCommand({\n meta: { name: 'settings', description: 'Show the Telegram attention notification settings' },\n args: { json: jsonFlag },\n async run({ args }) {\n print(await createClient().notifications.settings(), args.json)\n },\n})\n\nconst configure = defineCommand({\n meta: {\n name: 'configure',\n description: 'Change the settings; options left out keep their current value',\n },\n args: {\n enable: { type: 'boolean', description: 'Send new Attention items to Telegram' },\n disable: { type: 'boolean', description: 'Stop sending them' },\n kinds: { type: 'string', description: 'Comma-separated Attention kinds' },\n timezone: { type: 'string', description: 'IANA timezone, for example Europe/Warsaw' },\n 'quiet-start': { type: 'string', description: 'Start of quiet hours, HH:mm' },\n 'quiet-end': { type: 'string', description: 'End of quiet hours, HH:mm' },\n 'clear-quiet-hours': { type: 'boolean', description: 'Notify at any hour' },\n json: jsonFlag,\n },\n async run({ args }) {\n if (args.enable && args.disable) throw new Error('Choose --enable or --disable')\n if (Boolean(args['quiet-start']) !== Boolean(args['quiet-end']))\n throw new Error('Provide both --quiet-start and --quiet-end')\n if (args['clear-quiet-hours'] && args['quiet-start'])\n throw new Error('Choose a quiet window or --clear-quiet-hours')\n const api = createClient().notifications\n const current = await api.settings()\n const updated = await api.configure({\n enabled: args.enable ? true : args.disable ? false : current.enabled,\n kinds: args.kinds\n ? (args.kinds.split(',').map((kind) => kind.trim()) as AttentionRecordedKind[])\n : current.kinds,\n timezone: args.timezone ?? current.timezone,\n quietHours: args['clear-quiet-hours']\n ? null\n : args['quiet-start'] && args['quiet-end']\n ? { start: args['quiet-start'], end: args['quiet-end'] }\n : current.quietHours,\n })\n print(updated, args.json)\n },\n})\n\nexport const notificationCommand = defineCommand({\n meta: {\n name: 'notification',\n description: 'Send new Attention items to the Telegram service topic',\n },\n subCommands: { settings, configure },\n})\n","import { spawn } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport type {\n CreateProfileRequest,\n FileContentResponse,\n LoadedProfile,\n Profile,\n ProfileFileName,\n PutFileRequest,\n SkillsMode,\n UpdateProfileRequest,\n} from '@bazilion/api-types'\nimport { PROFILE_FILES } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst profileArg = positional('Profile id')\n\nfunction splitCsv(v: string | undefined): string[] | undefined {\n if (!v) return undefined\n const out = v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n return out.length > 0 ? out : undefined\n}\n\nfunction parseSkillsMode(v: string | undefined): SkillsMode | undefined {\n if (v === undefined) return undefined\n if (v === 'all' || v === 'selected') return v\n throw new Error(`--skills-mode must be 'all' or 'selected', got '${v}'`)\n}\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Create a new profile' },\n args: {\n id: positional('Profile slug'),\n name: { type: 'string', description: 'Display name (defaults to slug)' },\n model: {\n type: 'string',\n required: true,\n description: 'Default model, e.g. anthropic:claude-opus-4-8',\n },\n 'skills-mode': {\n type: 'string',\n description: \"'all' (attach every discovered skill) or 'selected' (default)\",\n },\n skills: {\n type: 'string',\n description: 'Default skills, comma-separated (skills-mode=selected)',\n },\n 'soul-file': {\n type: 'string',\n description: 'Path to custom SOUL.md content (defaults to the built-in template)',\n },\n 'identity-file': {\n type: 'string',\n description: 'Path to custom IDENTITY.md content (defaults to the built-in template)',\n },\n 'bootstrap-file': {\n type: 'string',\n description: 'Path to custom BOOTSTRAP.md content (defaults to the built-in template)',\n },\n 'skip-bootstrap': {\n type: 'boolean',\n description: 'Skip the bootstrap file entirely (no first-run intro)',\n },\n 'agents-file': {\n type: 'string',\n description: 'Path to custom AGENTS.md content (defaults to the built-in template)',\n },\n 'skip-agents': { type: 'boolean', description: 'Create the profile without an AGENTS.md' },\n 'tools-file': {\n type: 'string',\n description: 'Path to custom TOOLS.md content (defaults to the built-in template)',\n },\n 'skip-tools': { type: 'boolean', description: 'Create the profile without a TOOLS.md' },\n },\n async run({ args }) {\n const skillsMode = parseSkillsMode(args['skills-mode'])\n const readTemplate = (path: string | undefined): string | undefined =>\n path ? readFileSync(path, 'utf8') : undefined\n const body: CreateProfileRequest = {\n id: args.id,\n name: args.name,\n defaultModel: args.model,\n skillsMode,\n defaultSkills: splitCsv(args.skills),\n soul: readTemplate(args['soul-file']),\n identity: readTemplate(args['identity-file']),\n bootstrap: args['skip-bootstrap'] ? null : readTemplate(args['bootstrap-file']),\n agents: args['skip-agents'] ? null : readTemplate(args['agents-file']),\n tools: args['skip-tools'] ? null : readTemplate(args['tools-file']),\n }\n const profile = await createClient().post<Profile>('/api/profiles', body)\n console.log(`created profile ${profile.id} at ${profile.dir}`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List profiles' },\n async run() {\n const list = await createClient().get<Profile[]>('/api/profiles')\n printRows(\n list.map((p) => [p.id, p.defaultModel, p.name]),\n '(no profiles)',\n )\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show profile details' },\n args: { id: profileArg },\n async run({ args }) {\n const loaded = await createClient().get<LoadedProfile>(apiPath('profiles', args.id))\n console.log(`# ${loaded.profile.id}`)\n console.log(`name: ${loaded.profile.name}`)\n console.log(`dir: ${loaded.profile.dir}`)\n console.log(`default model: ${loaded.profile.defaultModel}`)\n console.log(`skills mode: ${loaded.profile.skillsMode}`)\n console.log(\n `default skills: ${\n loaded.defaultSkills.length === 0 ? '(none)' : loaded.defaultSkills.join(', ')\n }`,\n )\n console.log(`bootstrap: ${loaded.files.bootstrap !== null ? 'yes' : 'no'}`)\n console.log(`agents: ${loaded.files.agents !== null ? 'yes' : 'no'}`)\n console.log(`tools: ${loaded.files.tools !== null ? 'yes' : 'no'}`)\n if (loaded.identity) {\n const fields = Object.entries(loaded.identity)\n .filter(([, v]) => typeof v === 'string' && v.length > 0)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')\n if (fields) console.log(`identity: ${fields}`)\n }\n },\n})\n\nconst editCmd = defineCommand({\n meta: { name: 'edit', description: 'Open a profile file in $EDITOR' },\n args: {\n id: profileArg,\n file: {\n type: 'string',\n default: 'SOUL.md',\n description: `File: ${PROFILE_FILES.join(', ')} (default SOUL.md)`,\n },\n },\n async run({ args }) {\n if (!(PROFILE_FILES as readonly string[]).includes(args.file)) {\n throw new Error(`unsupported file: ${args.file}. Allowed: ${PROFILE_FILES.join(', ')}`)\n }\n const file = args.file as ProfileFileName\n const client = createClient()\n const path = apiPath('profiles', args.id, 'files', file)\n const { content } = await client.get<FileContentResponse>(path)\n const tmpPath = join(tmpdir(), `bazilion-${args.id}-${file}-${randomBytes(4).toString('hex')}`)\n writeFileSync(tmpPath, content)\n try {\n const editor = process.env.EDITOR ?? process.env.VISUAL ?? 'vi'\n const code: number = await new Promise((resolve, reject) => {\n const child = spawn(editor, [tmpPath], { stdio: 'inherit' })\n child.on('error', reject)\n child.on('close', (c) => resolve(c ?? 0))\n })\n if (code !== 0) throw new Error(`editor exited with code ${code}`)\n const updated = readFileSync(tmpPath, 'utf8')\n if (updated === content) {\n console.log('(no changes)')\n return\n }\n const body: PutFileRequest = { content: updated }\n await client.put(path, body)\n console.log(`saved ${file}`)\n } finally {\n rmSync(tmpPath, { force: true })\n }\n },\n})\n\nconst updateCmd = defineCommand({\n meta: {\n name: 'update',\n description: 'Update profile settings (name, model, skills-mode, skills)',\n },\n args: {\n id: profileArg,\n name: { type: 'string', description: 'New display name' },\n model: { type: 'string', description: 'New default model' },\n 'skills-mode': {\n type: 'string',\n description: \"Switch to 'all' or 'selected'\",\n },\n skills: { type: 'string', description: 'Replacement default skills, comma-separated' },\n },\n async run({ args }) {\n const body: UpdateProfileRequest = {}\n if (args.name !== undefined) body.name = args.name\n if (args.model !== undefined) body.defaultModel = args.model\n const mode = parseSkillsMode(args['skills-mode'])\n if (mode !== undefined) body.skillsMode = mode\n if (args.skills !== undefined) body.defaultSkills = splitCsv(args.skills) ?? []\n if (Object.keys(body).length === 0) {\n throw new Error(\n 'nothing to update — pass at least one of --name/--model/--skills-mode/--skills',\n )\n }\n const profile = await createClient().patch<Profile>(apiPath('profiles', args.id), body)\n console.log(`updated profile ${profile.id}`)\n },\n})\n\nconst deleteCmd = defineCommand({\n meta: { name: 'delete', description: 'Permanently delete a profile and its files' },\n args: { id: profileArg },\n async run({ args }) {\n await createClient().del(apiPath('profiles', args.id))\n console.log(`deleted profile ${args.id}`)\n },\n})\n\nexport const profileCommand = defineCommand({\n meta: { name: 'profile', description: 'Manage profiles' },\n subCommands: {\n create: createCmd,\n list: listCmd,\n show: showCmd,\n edit: editCmd,\n update: updateCmd,\n delete: deleteCmd,\n },\n})\n","import type {\n ConnectProviderRequest,\n ConnectProviderResponse,\n ProviderCatalogResponse,\n ProviderCheck,\n ProviderConfigEntry,\n ProviderConfigResponse,\n ProviderFailure,\n ProviderTestRequest,\n ProviderTestResponse,\n SetProviderEnabledResponse,\n SetProviderModelsRequest,\n SetProviderModelsResponse,\n TestProviderResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { type BazilionClient, createClient } from '../client.ts'\nimport { apiPath, askSecret, confirm, positional, printRows } from '../command-helpers.ts'\nimport { collectFlagValues } from '../repeatable-args.ts'\n\nconst providerArg = positional('Provider id (e.g. anthropic)')\n\nconst STATE: Record<ProviderConfigEntry['state'], string> = {\n working: 'working',\n failing: 'failing',\n untested: 'not tested',\n incomplete: 'needs credentials',\n off: 'off',\n}\n\nasync function loadProvider(client: BazilionClient, id: string): Promise<ProviderConfigEntry> {\n const { providers } = await client.get<ProviderConfigResponse>('/api/config/providers')\n const provider = providers.find((entry) => entry.id === id)\n if (!provider) throw new Error(`unknown provider: ${id} (see: bazilion provider list --all)`)\n return provider\n}\n\nfunction checkLine(check: ProviderCheck): string {\n const when = new Date(check.at).toISOString().replace(/\\.\\d+Z$/, 'Z')\n return check.ok\n ? `${check.model} answered in ${((check.ms ?? 0) / 1000).toFixed(1)} s (${when})`\n : `${check.failure?.title ?? 'failed'} (${when})`\n}\n\nfunction printFailure(failure: ProviderFailure): void {\n console.error(failure.title)\n console.error(failure.hint)\n if (failure.detail) console.error(`details: ${failure.detail}`)\n}\n\nconst listCmd = defineCommand({\n meta: {\n name: 'list',\n description: 'List the providers in use with their state; --all lists every provider',\n },\n args: {\n all: { type: 'boolean', description: 'Also list providers that are not set up' },\n enabled: { type: 'boolean', description: 'Show only providers that are switched on' },\n },\n async run({ args }) {\n const { providers } = await createClient().get<ProviderConfigResponse>('/api/config/providers')\n printRows(\n providers\n .filter((p) => (args.enabled ? p.enabled : args.all || p.listed))\n .map((p) => [\n p.id,\n p.listed ? STATE[p.state] : 'not set up',\n p.models.length === 1 ? '1 model' : `${p.models.length} models`,\n p.check ? checkLine(p.check) : '',\n ]),\n args.all\n ? '(no providers to show)'\n : '(no provider is set up: bazilion provider connect <id>, or list them all with --all)',\n )\n },\n})\n\nconst connectCmd = defineCommand({\n meta: {\n name: 'connect',\n description:\n 'Connect a provider in one step: save its key or address, choose models, test, switch on',\n },\n args: {\n name: providerArg,\n key: {\n type: 'string',\n description: 'API key or access token (asked for, without echo, when left out)',\n },\n url: { type: 'string', description: 'Address of a local model server' },\n set: {\n type: 'string',\n description: 'Another setting of the provider as NAME=value (repeatable)',\n },\n models: {\n type: 'string',\n description: 'Comma-separated chat models (default: the suggested ones)',\n },\n test: {\n type: 'boolean',\n default: true,\n description: 'Ask a model for a short reply before saving anything (--no-test skips it)',\n },\n },\n async run({ args, rawArgs }) {\n const client = createClient()\n const provider = await loadProvider(client, args.name)\n const fields: Record<string, string> = {}\n for (const pair of collectFlagValues(rawArgs, 'set')) {\n const at = pair.indexOf('=')\n if (at <= 0) throw new Error(`--set takes NAME=value, got \"${pair}\"`)\n fields[pair.slice(0, at)] = pair.slice(at + 1)\n }\n const main = provider.fields.filter((field) => !field.advanced)\n const secret = main.find((field) => field.kind === 'secret')\n const address = main.find((field) => field.kind === 'config')\n if (args.url) {\n if (provider.connect !== 'local' || !address) {\n throw new Error(`--url is for local model servers; ${provider.id} takes --key or --set`)\n }\n fields[address.envVar] = args.url\n }\n if (args.key) {\n const target = secret ?? provider.fields.find((field) => field.kind === 'secret')\n if (!target) throw new Error(`${provider.id} takes no key`)\n fields[target.envVar] = args.key\n } else if (secret && !provider.configured && !(secret.envVar in fields)) {\n const typed = await askSecret(`${provider.displayName} ${secret.label}: `)\n if (!typed) throw new Error('no key given')\n fields[secret.envVar] = typed\n }\n\n const models = args.models\n ?.split(',')\n .map((model) => model.trim())\n .filter(Boolean)\n if (!models && provider.models.length === 0 && provider.suggested.length === 0) {\n if (provider.connect !== 'local') {\n throw new Error(\n `choose chat models with --models (see: bazilion provider models ${provider.id})`,\n )\n }\n }\n // A local server suggests what it has loaded: ask it, with the address being connected.\n let chosen = models\n if (!chosen && provider.connect === 'local' && provider.models.length === 0) {\n const catalog = await client.post<ProviderCatalogResponse>(\n apiPath('config', 'providers', provider.id, 'catalog'),\n { fields },\n )\n chosen = catalog.models.filter((model) => model.suggested).map((model) => model.id)\n }\n\n const body: ConnectProviderRequest = {\n ...(Object.keys(fields).length > 0 ? { fields } : {}),\n ...(chosen ? { models: chosen } : {}),\n ...(args.test ? {} : { test: false }),\n }\n const result = await client.post<ConnectProviderResponse>(\n apiPath('config', 'providers', provider.id, 'connect'),\n body,\n )\n if (!result.connected) {\n printFailure(result.failure)\n console.error('Nothing was saved.')\n process.exitCode = 1\n return\n }\n console.log(`${result.provider.id}: connected`)\n if (result.check) console.log(` ${checkLine(result.check)}`)\n else console.log(' not tested')\n console.log(` models: ${result.provider.models.join(', ') || '(none)'}`)\n for (const dropped of result.dropped) console.log(` left out: ${dropped.model}`)\n for (const t of result.movedTemplates) console.log(` template ${t.id} now uses ${t.model}`)\n },\n})\n\nconst disconnectCmd = defineCommand({\n meta: {\n name: 'disconnect',\n description: 'Forget a provider: its stored key or sign-in, its chat models and its test',\n },\n args: {\n name: providerArg,\n yes: { type: 'boolean', description: 'Do not ask for confirmation' },\n },\n async run({ args }) {\n const client = createClient()\n const provider = await loadProvider(client, args.name)\n if (\n !args.yes &&\n !(await confirm(`Disconnect ${provider.displayName} and remove its stored credentials?`))\n ) {\n console.log('cancelled')\n return\n }\n const result = await client.del<SetProviderModelsResponse>(\n apiPath('config', 'providers', provider.id),\n )\n console.log(`${provider.id}: disconnected`)\n for (const t of result.movedTemplates) console.log(`template ${t.id} now uses ${t.model}`)\n },\n})\n\nconst modelsCmd = defineCommand({\n meta: {\n name: 'models',\n description: 'Show a provider’s chat models: the ones Agents may use, and what it offers',\n },\n args: { name: providerArg },\n async run({ args }) {\n const client = createClient()\n const p = await loadProvider(client, args.name)\n const catalog = await client.get<ProviderCatalogResponse>(\n apiPath('config', 'providers', p.id, 'catalog'),\n )\n console.log(`# ${p.id} (${p.listed ? STATE[p.state] : 'not set up'})`)\n if (p.hint) console.log(` ${p.hint}`)\n for (const field of p.fields) console.log(` ${field.envVar}: ${field.set ? 'set' : 'unset'}`)\n if (!p.enabled) console.log(` (connect with \\`bazilion provider connect ${p.id}\\`)`)\n\n console.log('\\n## in use')\n if (p.models.length === 0) console.log(' (none: `provider connect` or `provider models-set`)')\n else for (const m of p.models) console.log(` ${m}`)\n\n console.log('\\n## offered')\n if (catalog.listError) console.log(` (the provider's own list failed: ${catalog.listError})`)\n printRows(\n catalog.models.map((model) => [\n ` ${model.id}`,\n model.name ?? '',\n model.contextWindow ? `${Math.round(model.contextWindow / 1000)}K` : '',\n model.price ? `$${model.price.input} in, $${model.price.output} out per 1M` : '',\n model.suggested ? 'suggested' : '',\n ]),\n ' (nothing listed)',\n )\n },\n})\n\nconst modelsSetCmd = defineCommand({\n meta: {\n name: 'models-set',\n description: 'Replace the chat models Agents may use from a provider (comma-separated)',\n },\n args: {\n name: providerArg,\n models: positional('Comma-separated model list (empty string clears the list)'),\n },\n async run({ args }) {\n const models = args.models\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n const body: SetProviderModelsRequest = { models }\n const saved = await createClient().put<SetProviderModelsResponse>(\n apiPath('config', 'providers', args.name, 'models'),\n body,\n )\n console.log(`saved ${saved.models.length} model(s) for ${args.name}`)\n for (const m of saved.models) console.log(` ${m}`)\n for (const t of saved.movedTemplates) console.log(`template ${t.id} now uses ${t.model}`)\n },\n})\n\nasync function setEnabled(name: string, enabled: boolean): Promise<void> {\n const res = await createClient().put<SetProviderEnabledResponse>(\n apiPath('config', 'providers', name, 'enabled'),\n { enabled },\n )\n console.log(`${res.name}: ${res.enabled ? 'enabled' : 'disabled'}`)\n}\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Switch a connected provider back on' },\n args: { name: providerArg },\n run: ({ args }) => setEnabled(args.name, true),\n})\n\nconst disableCmd = defineCommand({\n meta: {\n name: 'disable',\n description: 'Pause a provider without removing its key; Agents on its models are refused',\n },\n args: { name: providerArg },\n run: ({ args }) => setEnabled(args.name, false),\n})\n\nconst testCmd = defineCommand({\n meta: {\n name: 'test',\n description: 'Test a provider (its cheapest model in use) or send one chat to a provider:model',\n },\n args: {\n model: positional('Provider id, or a model string such as anthropic:claude-haiku-5-5'),\n message: { type: 'string', description: 'Message text for a model string' },\n },\n async run({ args }) {\n const client = createClient()\n if (!args.model.includes(':')) {\n const { check } = await client.post<TestProviderResponse>(\n apiPath('config', 'providers', args.model, 'test'),\n )\n if (check.ok) {\n console.log(`${args.model}: ${checkLine(check)}`)\n return\n }\n if (check.failure) printFailure(check.failure)\n process.exitCode = 1\n return\n }\n const body: ProviderTestRequest = { model: args.model, message: args.message }\n console.log(`-> ${args.model}: ${args.message ?? 'say hi briefly'}`)\n const res = await client.post<ProviderTestResponse>('/api/providers/test', body)\n console.log(`<- ${res.content}`)\n if (res.usage) {\n console.log(`(${res.usage.promptTokens} in, ${res.usage.completionTokens} out)`)\n }\n },\n})\n\nexport const providerCommand = defineCommand({\n meta: { name: 'provider', description: 'Connect, test and manage LLM providers' },\n subCommands: {\n list: listCmd,\n connect: connectCmd,\n disconnect: disconnectCmd,\n test: testCmd,\n models: modelsCmd,\n 'models-set': modelsSetCmd,\n enable: enableCmd,\n disable: disableCmd,\n },\n})\n","import type { AgentQuestionAnswer } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, jsonFlag, positional, printJson } from '../command-helpers.ts'\nimport { questionLines } from '../question-prompt.ts'\n\nexport function questionAnswer(args: {\n choice?: string\n text?: string\n skip?: boolean\n}): AgentQuestionAnswer {\n const count =\n Number(args.choice !== undefined) + Number(args.text !== undefined) + Number(args.skip === true)\n if (count !== 1) throw new Error('Specify exactly one of --choice, --text, or --skip')\n if (args.skip) return { kind: 'skip' }\n if (args.text !== undefined) {\n if (!args.text.trim() || args.text.length > 4096)\n throw new Error('Answer text must be 1–4096 characters')\n return { kind: 'text', text: args.text }\n }\n if (!/^[1-4]$/.test(args.choice ?? '')) throw new Error('--choice must be a number from 1 to 4')\n return { kind: 'choice', index: Number(args.choice) - 1 }\n}\n\nexport const questionCommand = defineCommand({\n meta: { name: 'question', description: \"List and answer an Agent's waiting questions\" },\n subCommands: {\n list: defineCommand({\n meta: { name: 'list', description: 'Questions the Agent is waiting on' },\n args: { agent: agentArg, json: jsonFlag },\n async run({ args }) {\n const { questions } = await createClient().questions(args.agent).list()\n if (args.json) return printJson(questions)\n if (!questions.length) return console.log('(no waiting questions)')\n for (const item of questions) {\n console.log(`${item.id} · expires ${new Date(item.expiresAt).toLocaleTimeString()}`)\n for (const line of questionLines(item)) console.log(` ${line}`)\n }\n },\n }),\n answer: defineCommand({\n meta: { name: 'answer', description: 'Answer a waiting question' },\n args: {\n agent: agentArg,\n id: positional('Question id'),\n choice: { type: 'string', description: 'Choice number, starting at 1' },\n text: { type: 'string', description: 'Free-text answer' },\n skip: { type: 'boolean', description: 'Continue without an answer' },\n },\n async run({ args }) {\n await createClient().questions(args.agent).answer(args.id, questionAnswer(args))\n console.log(args.skip ? 'Skipped.' : 'Answered.')\n },\n }),\n },\n})\n","import { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, loadAttachments, positional, printJson } from '../command-helpers.ts'\n\nconst itemArg = positional('Follow-up id')\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'Show waiting, running and failed follow-ups, and whether a turn is running',\n },\n args: { agent: agentArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).list())\n },\n})\n\nconst add = defineCommand({\n meta: { name: 'add', description: 'Queue a follow-up; it runs after the current turn' },\n args: {\n agent: agentArg,\n message: { type: 'string', description: 'Text of the follow-up' },\n image: { type: 'string', description: 'Attach an image (repeatable)' },\n file: { type: 'string', description: 'Attach a file (repeatable)' },\n },\n async run({ args, rawArgs }) {\n printJson(\n await createClient()\n .queue(args.agent)\n .enqueue({ message: args.message ?? '', attachments: loadAttachments(rawArgs) }),\n )\n },\n})\n\nconst edit = defineCommand({\n meta: { name: 'edit', description: 'Replace the text of a waiting follow-up' },\n args: {\n agent: agentArg,\n id: itemArg,\n message: { type: 'string', required: true, description: 'New text of the follow-up' },\n },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).edit(args.id, args.message))\n },\n})\n\nconst remove = defineCommand({\n meta: { name: 'remove', description: 'Remove a follow-up that is not running' },\n args: { agent: agentArg, id: itemArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).remove(args.id))\n },\n})\n\nfunction control(paused: boolean) {\n return defineCommand({\n meta: {\n name: paused ? 'pause' : 'resume',\n description: paused ? 'Start no further follow-ups' : 'Start waiting follow-ups again',\n },\n args: { agent: agentArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).pause(paused))\n },\n })\n}\n\nexport const queueCommand = defineCommand({\n meta: { name: 'queue', description: 'Follow-ups: input that waits for the Agent’s current turn' },\n subCommands: { list, add, edit, remove, pause: control(true), resume: control(false) },\n})\n","import { closeSync, fsyncSync, openSync, unlinkSync, writeFileSync } from 'node:fs'\nimport type { AgentResult, ResultListResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson } from '../command-helpers.ts'\n\nconst idArg = positional('Result id')\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List saved results' },\n args: {\n team: { type: 'string', description: 'Only results of this Team' },\n agent: { type: 'string', description: 'Only results of this Agent' },\n conversation: { type: 'string', description: 'Only results delivered in this conversation' },\n limit: { type: 'string', default: '50', description: 'Page size' },\n offset: { type: 'string', default: '0', description: 'Results to skip' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ limit: args.limit, offset: args.offset })\n if (args.team) query.set('teamId', args.team)\n if (args.agent) query.set('agentId', args.agent)\n if (args.conversation) query.set('sessionId', args.conversation)\n const body = await createClient().get<ResultListResponse>(`/api/results?${query}`)\n if (args.json) return printJson(body)\n if (!body.results.length) return console.log('(no saved results)')\n for (const line of columnize([\n ['id', 'filename', 'bytes', 'team', 'agent', 'created'],\n ...body.results.map((r) => [\n r.id,\n r.name,\n String(r.byteLength),\n r.teamId,\n r.agentId,\n new Date(r.createdAt).toISOString(),\n ]),\n ]))\n console.log(line)\n console.log(`${body.offset + 1}–${body.offset + body.results.length} of ${body.total}`)\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Show a saved result: who saved it, where and when' },\n args: { id: idArg },\n async run({ args }) {\n const { result } = await createClient().get<{ result: AgentResult }>(\n apiPath('results', args.id),\n )\n printJson(result)\n },\n})\n\nconst download = defineCommand({\n meta: { name: 'download', description: 'Download a saved result to an explicit new file' },\n args: {\n id: idArg,\n output: {\n type: 'string',\n required: true,\n description: 'Destination path; existing files are never overwritten',\n },\n },\n async run({ args }) {\n const bytes = await createClient().binary(apiPath('results', args.id, 'download'))\n saveNew(args.output, bytes)\n console.log(`Saved ${bytes.byteLength} bytes to ${args.output}`)\n },\n})\n\n/** Write bytes to a new file; an existing file is never overwritten. */\nfunction saveNew(path: string, bytes: Uint8Array): void {\n const fd = openSync(path, 'wx', 0o600)\n try {\n writeFileSync(fd, bytes)\n fsyncSync(fd)\n } catch (error) {\n closeSync(fd)\n unlinkSync(path)\n throw error\n }\n closeSync(fd)\n}\n\nconst archive = defineCommand({\n meta: {\n name: 'archive',\n description: 'Download every saved result of a Team, an Agent or a conversation as one zip',\n },\n args: {\n team: { type: 'string', description: 'Results of this Team' },\n agent: { type: 'string', description: 'Results of this Agent' },\n conversation: { type: 'string', description: 'Results delivered in this conversation' },\n output: {\n type: 'string',\n required: true,\n description: 'Destination .zip path; existing files are never overwritten',\n },\n },\n async run({ args }) {\n const query = new URLSearchParams()\n if (args.team) query.set('teamId', args.team)\n if (args.agent) query.set('agentId', args.agent)\n if (args.conversation) query.set('sessionId', args.conversation)\n if (query.size === 0) throw new Error('Pass --team, --agent or --conversation')\n const bytes = await createClient().binary(`/api/results/archive?${query}`)\n saveNew(args.output, bytes)\n console.log(`Saved ${bytes.byteLength} bytes to ${args.output}`)\n },\n})\n\nconst rm = defineCommand({\n meta: { name: 'rm', description: 'Delete a saved result' },\n args: { id: idArg, yes: { type: 'boolean', description: 'Required confirmation' } },\n async run({ args }) {\n if (!args.yes) throw new Error('Pass --yes to permanently delete the saved file')\n await createClient().del(apiPath('results', args.id))\n console.log('Saved file deleted.')\n },\n})\n\nexport const resultCommand = defineCommand({\n meta: { name: 'result', description: 'Find, download and delete saved Agent results' },\n subCommands: {\n list,\n show,\n download,\n archive,\n rm,\n },\n})\n","import type { Message, SendMessageRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional } from '../command-helpers.ts'\n\nexport const sendCommand = defineCommand({\n meta: {\n name: 'send',\n description: 'Send a message from one agent to another',\n },\n args: {\n from: positional('Sender agent id or prefix'),\n to: positional('Recipient agent id or prefix'),\n message: positional('Message text'),\n 'reply-to': { type: 'string', description: 'Id of the message this one answers' },\n },\n async run({ args }) {\n const body: SendMessageRequest = {\n from: args.from,\n payload: { text: args.message },\n ...(args['reply-to'] ? { replyTo: args['reply-to'] } : {}),\n }\n const result = await createClient().post<Message>(apiPath('agents', args.to, 'messages'), body)\n console.log(`sent message ${result.id}`)\n },\n})\n","import type { ListSessionsResponse, WebSession } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nfunction row(session: WebSession): string[] {\n return [\n session.id,\n session.current ? 'current' : '',\n session.tokenLabel,\n `last seen: ${new Date(session.lastSeenAt).toISOString()}`,\n `expires: ${new Date(session.expiresAt).toISOString()}`,\n ]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List browser sessions' },\n async run() {\n const { sessions } = await createClient().get<ListSessionsResponse>('/api/sessions')\n printRows(sessions.map(row), '(no active browser sessions)')\n },\n})\n\nconst revokeCmd = defineCommand({\n meta: { name: 'revoke', description: 'Revoke (delete) one browser session' },\n args: { id: positional('Session id') },\n async run({ args }) {\n await createClient().del(apiPath('sessions', args.id))\n console.log(`revoked browser session ${args.id}`)\n },\n})\n\nexport const sessionCommand = defineCommand({\n meta: { name: 'session', description: 'Manage browser sessions' },\n subCommands: { list: listCmd, revoke: revokeCmd },\n})\n","import { existsSync, readFileSync, statSync } from 'node:fs'\nimport { basename, resolve } from 'node:path'\nimport type {\n ImportSkillsRequest,\n ImportSkillsResponse,\n ResolvedSkillsResponse,\n SkillInfo,\n SkillScanFinding,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, findingLines, positional, printRows } from '../command-helpers.ts'\nimport { explainScanBlock } from '../errors.ts'\n\nfunction printFindings(title: string, findings: Record<string, SkillScanFinding[]>): void {\n const flagged = Object.entries(findings).filter(([, list]) => list.length > 0)\n if (flagged.length === 0) return\n console.log('')\n console.log(title)\n for (const [name, list] of flagged) {\n console.log(`${name}:`)\n for (const line of findingLines(list)) console.log(` ${line}`)\n }\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List installed skills (or those attached to an agent)' },\n args: {\n agent: { type: 'string', description: 'Filter to skills attached to this agent' },\n },\n async run({ args }) {\n const client = createClient()\n\n if (args.agent) {\n const set = await client.get<ResolvedSkillsResponse>(apiPath('agents', args.agent, 'skills'))\n if (set.resolved.length === 0 && set.missing.length === 0) {\n console.log('(no skills attached to this agent)')\n return\n }\n for (const line of columnize(set.resolved.map((s) => [s.name, s.description]))) {\n console.log(line)\n }\n for (const m of set.missing) console.log(`(missing: ${m.name} — ${m.reason})`)\n return\n }\n\n const skills = await client.get<SkillInfo[]>('/api/skills')\n printRows(\n skills.map((s) => [s.name, s.parseError ? `(parse error: ${s.parseError})` : s.description]),\n '(no skills installed; use \"bazilion skill import\" to add some)',\n )\n printFindings(\n 'scan findings:',\n Object.fromEntries(skills.map((s) => [s.name, s.scanFindings ?? []])),\n )\n },\n})\n\nconst importCmd = defineCommand({\n meta: {\n name: 'import',\n description: 'Import skills from openclaw, a directory, or a local .zip archive',\n },\n args: {\n from: {\n type: 'string',\n required: true,\n description:\n 'Source: \"openclaw\", a filesystem path on the server, or a local .zip file to upload',\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing skills and import despite scan findings',\n },\n },\n async run({ args }) {\n const client = createClient()\n\n // Auto-detect local .zip uploads: if `--from` points at an existing local\n // file ending in .zip, stream it to the server as multipart. Otherwise\n // send the source as JSON (the server reads openclaw or a server-side path).\n const absFrom = resolve(args.from)\n const isLocalZip =\n args.from.toLowerCase().endsWith('.zip') && existsSync(absFrom) && statSync(absFrom).isFile()\n\n let request: Promise<ImportSkillsResponse>\n if (isLocalZip) {\n const form = new FormData()\n form.set(\n 'file',\n new File([readFileSync(absFrom)], basename(absFrom), { type: 'application/zip' }),\n )\n if (args.force) form.set('force', 'true')\n request = client.postMultipart<ImportSkillsResponse>('/api/skills/import', form)\n } else {\n const body: ImportSkillsRequest = { source: args.from, force: args.force }\n request = client.post<ImportSkillsResponse>('/api/skills/import', body)\n }\n const result = await request.catch(explainScanBlock('--force'))\n\n if (result.imported.length === 0 && result.skipped.length === 0) {\n console.log('(nothing to import)')\n return\n }\n for (const name of result.imported) console.log(`imported ${name}`)\n for (const s of result.skipped) console.log(`skipped ${s.name}: ${s.reason}`)\n printFindings('confirmed scan findings:', result.findings ?? {})\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Remove an installed skill' },\n args: { name: positional('Skill name') },\n async run({ args }) {\n await createClient().del(apiPath('skills', args.name))\n console.log(`removed skill ${args.name}`)\n },\n})\n\nexport const skillCommand = defineCommand({\n meta: { name: 'skill', description: 'Manage the skill library' },\n subCommands: {\n list: listCmd,\n import: importCmd,\n rm: rmCmd,\n },\n})\n","import { readFileSync } from 'node:fs'\nimport { stdin } from 'node:process'\nimport type {\n RegisterTeamRequest,\n SetTeamTopicFormatRequest,\n SetTeamUserMdRequest,\n Team,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, printRows, teamArg } from '../command-helpers.ts'\nimport { UsageError } from '../errors.ts'\nimport { teamEnvironmentCommand } from './team-environment.ts'\nimport { teamMessagesCommand } from './team-messages.ts'\nimport { teamPolicyCommand } from './team-policy.ts'\nimport { teamReviewCommand } from './team-review.ts'\nimport { teamTodayCommand } from './team-today.ts'\n\nconst addCmd = defineCommand({\n meta: {\n name: 'add',\n description:\n 'Register a team at ~/.bazilion/teams/<slug>/ (use --link to point at an existing tree)',\n },\n args: {\n id: teamArg,\n name: { type: 'string', description: 'Display name (defaults to slug)' },\n link: {\n type: 'string',\n description: 'Absolute path of an existing directory; the team slot becomes a symlink to it',\n },\n },\n async run({ args }) {\n const body: RegisterTeamRequest = {\n id: args.id,\n ...(args.name ? { name: args.name } : {}),\n ...(args.link ? { link: args.link } : {}),\n }\n const team = await createClient().post<Team>('/api/teams', body)\n console.log(`registered team ${team.id} at ${team.path}`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List teams' },\n async run() {\n const list = await createClient().get<Team[]>('/api/teams')\n printRows(\n list.map((team) => [team.id, team.path]),\n '(no teams)',\n )\n },\n})\n\nconst rmCmd = defineCommand({\n meta: {\n name: 'rm',\n description: 'Delete an empty team and its workspace directory (a --link target is kept)',\n },\n args: { id: teamArg },\n async run({ args }) {\n await createClient().del(apiPath('teams', args.id))\n console.log(`removed team ${args.id}`)\n },\n})\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of stdin) chunks.push(chunk as Buffer)\n return Buffer.concat(chunks).toString('utf8')\n}\n\nconst userMdShowCmd = defineCommand({\n meta: { name: 'show', description: \"Print the team's USER.md\" },\n args: { id: teamArg },\n async run({ args }) {\n const team = await createClient().get<Team>(apiPath('teams', args.id))\n process.stdout.write(team.userMd)\n if (team.userMd && !team.userMd.endsWith('\\n')) process.stdout.write('\\n')\n },\n})\n\nconst userMdSetCmd = defineCommand({\n meta: {\n name: 'set',\n description: \"Replace the team's USER.md (from --file, --from-stdin, or inline text)\",\n },\n args: {\n id: teamArg,\n file: { type: 'string', description: 'Read content from a file path' },\n 'from-stdin': { type: 'boolean', description: 'Read content from stdin' },\n text: { type: 'string', description: 'Inline content' },\n },\n async run({ args }) {\n let content: string\n if (args['from-stdin']) content = await readStdin()\n else if (args.file) content = readFileSync(args.file, 'utf8')\n else if (args.text !== undefined) content = args.text\n else throw new UsageError('provide --file, --from-stdin, or --text')\n const body: SetTeamUserMdRequest = { userMd: content }\n await createClient().put(apiPath('teams', args.id, 'user-md'), body)\n console.log(`updated USER.md for team ${args.id} (${content.length} bytes)`)\n },\n})\n\nconst userMdClearCmd = defineCommand({\n meta: { name: 'clear', description: \"Clear the team's USER.md to empty\" },\n args: { id: teamArg },\n async run({ args }) {\n const body: SetTeamUserMdRequest = { userMd: '' }\n await createClient().put(apiPath('teams', args.id, 'user-md'), body)\n console.log(`cleared USER.md for team ${args.id}`)\n },\n})\n\nconst userMdCmd = defineCommand({\n meta: { name: 'user-md', description: \"View or edit a team's USER.md\" },\n subCommands: {\n show: userMdShowCmd,\n set: userMdSetCmd,\n clear: userMdClearCmd,\n },\n})\n\nconst topicFormatShowCmd = defineCommand({\n meta: { name: 'show', description: \"Print the team's Telegram topic-name template\" },\n args: { id: teamArg },\n async run({ args }) {\n const team = await createClient().get<Team>(apiPath('teams', args.id))\n console.log(team.telegramTopicNameFormat ?? '(default naming)')\n },\n})\n\nconst topicFormatSetCmd = defineCommand({\n meta: {\n name: 'set',\n description:\n 'Set the topic-name template. Tokens: {agent.name} {team.name} {team.slug} (must include {agent.name})',\n },\n args: {\n id: teamArg,\n format: {\n type: 'positional',\n required: true,\n description: 'e.g. \"{team.name} / {agent.name}\"',\n },\n },\n async run({ args }) {\n const body: SetTeamTopicFormatRequest = { format: args.format }\n const team = await createClient().put<Team>(apiPath('teams', args.id, 'topic-format'), body)\n console.log(`set topic-name template for team ${args.id}: ${team.telegramTopicNameFormat}`)\n },\n})\n\nconst topicFormatClearCmd = defineCommand({\n meta: { name: 'clear', description: 'Clear the template (revert to built-in naming)' },\n args: { id: teamArg },\n async run({ args }) {\n const body: SetTeamTopicFormatRequest = { format: null }\n await createClient().put(apiPath('teams', args.id, 'topic-format'), body)\n console.log(`cleared topic-name template for team ${args.id}`)\n },\n})\n\nconst topicFormatCmd = defineCommand({\n meta: {\n name: 'topic-format',\n description: \"View or edit a team's Telegram forum-topic name template\",\n },\n subCommands: {\n show: topicFormatShowCmd,\n set: topicFormatSetCmd,\n clear: topicFormatClearCmd,\n },\n})\n\nexport const teamCommand = defineCommand({\n meta: { name: 'team', description: 'Manage teams (collaboration contexts)' },\n subCommands: {\n environment: teamEnvironmentCommand,\n review: teamReviewCommand,\n messages: teamMessagesCommand,\n today: teamTodayCommand,\n add: addCmd,\n list: listCmd,\n rm: rmCmd,\n 'user-md': userMdCmd,\n 'topic-format': topicFormatCmd,\n policy: teamPolicyCommand,\n },\n})\n","import type { CodingEnvironmentStatus } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, teamArg } from '../command-helpers.ts'\n\nfunction print(status: CodingEnvironmentStatus): void {\n console.log(\n `sandbox: ${status.sandboxMode}${status.sandboxMode === 'off' ? ' (defaults unused)' : ''}`,\n )\n console.log(`image: ${status.image ?? `${status.defaultImage} (installation default)`}`)\n console.log(`cwd: ${status.cwd}`)\n}\n\nexport const teamEnvironmentCommand = defineCommand({\n meta: {\n name: 'environment',\n description: \"A Team's Docker sandbox defaults: local image and working directory\",\n },\n subCommands: {\n show: defineCommand({\n meta: { name: 'show', description: \"Show a Team's Docker sandbox defaults\" },\n args: { team: teamArg, json: jsonFlag },\n async run({ args }) {\n const status = await createClient().codingEnvironment.show(args.team)\n if (args.json) printJson(status)\n else print(status)\n },\n }),\n set: defineCommand({\n meta: { name: 'set', description: \"Set a Team's Docker sandbox defaults\" },\n args: {\n team: teamArg,\n image: {\n type: 'string',\n description: 'Local Docker image (empty for the installation image)',\n },\n cwd: {\n type: 'string',\n description: \"Working directory inside the Team ('.' for its root)\",\n },\n },\n async run({ args }) {\n if (args.image === undefined && args.cwd === undefined)\n throw new Error('Pass --image and/or --cwd')\n const client = createClient()\n const current = await client.codingEnvironment.show(args.team)\n print(\n await client.codingEnvironment.set(args.team, {\n image: args.image === undefined ? current.image : args.image || null,\n cwd: args.cwd ?? current.cwd,\n }),\n )\n },\n }),\n },\n})\n","import type { Agent, ListTeamMessagesResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport {\n apiPath,\n jsonFlag,\n printJson,\n printRows,\n teamArg,\n terminalSafe,\n} from '../command-helpers.ts'\n\n// `bazilion team messages`: what the Team's Agents sent each other, newest first. Reading here\n// marks nothing read; `bazilion inbox` is one Agent's mailbox.\n\nfunction decodeText(payload: string): string {\n try {\n const parsed = JSON.parse(payload) as { text?: unknown }\n if (typeof parsed.text === 'string') return parsed.text\n } catch {\n // Not JSON: shown as it is.\n }\n return payload\n}\n\nexport const teamMessagesCommand = defineCommand({\n meta: {\n name: 'messages',\n description: 'List the messages the Agents of a Team sent and received, newest first',\n },\n args: {\n id: teamArg,\n limit: { type: 'string', default: '50', description: 'Messages to show (at most 500)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const client = createClient()\n const [thread, agents] = await Promise.all([\n client.get<ListTeamMessagesResponse>(\n `${apiPath('teams', args.id, 'messages')}?limit=${encodeURIComponent(args.limit)}`,\n ),\n client.get<Agent[]>('/api/agents?includeArchived=true'),\n ])\n if (args.json) return printJson(thread)\n const names = new Map(agents.map((agent) => [agent.id, agent.name]))\n const name = (id: string) => names.get(id) ?? id.slice(0, 8)\n printRows(\n thread.messages.map((message) => {\n const text = decodeText(message.payload).replace(/\\s+/g, ' ').trim()\n return [\n new Date(message.createdAt).toISOString(),\n `${name(message.fromAgentId)} -> ${name(message.toAgentId)}`,\n message.readAt ? 'read' : 'NEW',\n terminalSafe(text.length > 80 ? `${text.slice(0, 80)}…` : text),\n ]\n }),\n '(no messages between Agents yet)',\n )\n },\n})\n","import {\n OUTSIDE_TEAM,\n type TeamPolicy,\n type TeamPolicyMode,\n type UpdateTeamPolicyRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson, teamArg } from '../command-helpers.ts'\n\nfunction label(policy: TeamPolicy, endpoint: string): string {\n if (endpoint === OUTSIDE_TEAM) return 'outside'\n return policy.members.find((agent) => agent.id === endpoint)?.name ?? endpoint\n}\n\n/** `outside`, or a member's id, id prefix or name. */\nfunction resolveEndpoint(policy: TeamPolicy, value: string): string {\n if (value === OUTSIDE_TEAM) return OUTSIDE_TEAM\n const byId = policy.members.find((agent) => agent.id === value)\n if (byId) return byId.id\n for (const matches of [\n policy.members.filter((agent) => agent.name === value),\n policy.members.filter((agent) => agent.id.startsWith(value)),\n ]) {\n if (matches.length > 1) throw new Error(`${value} matches several members of ${policy.teamId}`)\n if (matches[0]) return matches[0].id\n }\n throw new Error(`${value} is not a member of Team ${policy.teamId} (or outside)`)\n}\n\nconst show = defineCommand({\n meta: { name: 'show', description: \"Show a Team's policy mode, members and allow edges\" },\n args: { team: teamArg, json: jsonFlag },\n async run({ args }) {\n const policy = await createClient().get<TeamPolicy>(apiPath('teams', args.team, 'policy'))\n if (args.json) return printJson(policy)\n console.log(`# Team ${policy.teamId} policy`)\n console.log(\n `mode: ${policy.mode}${policy.mode === 'open' ? ' (everyone can message everyone)' : ' (only along connections)'}`,\n )\n console.log(`members: ${policy.members.map((agent) => agent.name).join(', ') || '(none)'}`)\n if (!policy.edges.length) return console.log('edges: (none)')\n console.log('')\n for (const line of columnize([\n ['from', 'to'],\n ...policy.edges.map((edge) => [label(policy, edge.from), label(policy, edge.to)]),\n ]))\n console.log(line)\n },\n})\n\nconst mode = defineCommand({\n meta: {\n name: 'mode',\n description: 'Set a Team to open (members talk freely) or restricted (allow edges only)',\n },\n args: { team: teamArg, mode: positional('open | restricted') },\n async run({ args }) {\n if (args.mode !== 'open' && args.mode !== 'restricted') {\n throw new Error('mode must be open or restricted')\n }\n const body: UpdateTeamPolicyRequest = { mode: args.mode as TeamPolicyMode }\n await createClient().patch(apiPath('teams', args.team, 'policy'), body)\n console.log(`Team ${args.team} is now ${args.mode}`)\n },\n})\n\nfunction edgeCommand(name: 'allow' | 'deny') {\n return defineCommand({\n meta: {\n name,\n description:\n name === 'allow'\n ? 'Let one endpoint message another (a member name or id, or outside)'\n : 'Remove an allow edge',\n },\n args: {\n team: teamArg,\n from: positional('Sender: member or outside'),\n to: positional('Recipient: member or outside'),\n },\n async run({ args }) {\n const client = createClient()\n const policy = await client.get<TeamPolicy>(apiPath('teams', args.team, 'policy'))\n const edge = {\n from: resolveEndpoint(policy, args.from),\n to: resolveEndpoint(policy, args.to),\n }\n const shown = `${label(policy, edge.from)} -> ${label(policy, edge.to)}`\n const others = policy.edges.filter((e) => e.from !== edge.from || e.to !== edge.to)\n const exists = others.length < policy.edges.length\n if (name === 'allow' && exists) return console.log(`${shown} is already allowed`)\n if (name === 'deny' && !exists) return console.log(`no edge ${shown}; nothing changed`)\n const body: UpdateTeamPolicyRequest = {\n edges: name === 'allow' ? [...others, edge] : others,\n }\n await client.patch(apiPath('teams', args.team, 'policy'), body)\n console.log(`${name === 'allow' ? 'allowed' : 'removed'} ${shown}`)\n },\n })\n}\n\nexport const teamPolicyCommand = defineCommand({\n meta: { name: 'policy', description: 'Who may message whom inside and across a Team' },\n subCommands: {\n show,\n mode,\n allow: edgeCommand('allow'),\n deny: edgeCommand('deny'),\n },\n})\n","import type { RepositoryChanges } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, teamArg } from '../command-helpers.ts'\n\n// `bazilion team review`: `show` lists the changes since a base, with the Agent that wrote each\n// file, or prints one file's diff; `feedback` queues a comment about a changed file or one of its\n// lines for an Agent.\n\nconst base = {\n type: 'string',\n description: 'Comparison base: branch, tag, commit id or revision such as HEAD~1 (default HEAD)',\n} as const\n\nfunction printIssues(changes: RepositoryChanges): void {\n for (const issue of changes.issues) console.log(`note: ${issue.code}: ${issue.message}`)\n}\n\nconst showCmd = defineCommand({\n meta: {\n name: 'show',\n description: 'List changes since a baseline, or print one file diff (read-only)',\n },\n args: {\n id: teamArg,\n base,\n patch: {\n type: 'string',\n description: 'Print the unified diff for one changed path instead of the list',\n },\n json: { ...jsonFlag, description: 'Emit the complete review, with diffs, as JSON' },\n },\n async run({ args }) {\n const client = createClient()\n // Diffs are read only when asked for: one for --patch, all of them for --json.\n const review = await client.repositoryReview(args.id).changes({\n ...(args.base ? { base: args.base } : {}),\n ...(args.patch ? { patches: true, path: args.patch } : args.json ? { patches: true } : {}),\n authors: !args.patch,\n })\n // A folder that is not a repository has no review: said, and the command fails.\n if ('unavailable' in review) throw new Error(review.unavailable.message)\n if (args.json) return printJson(review)\n const changes = review.changes\n if (args.patch) {\n const entry = changes.changes.find((change) => change.path === args.patch)\n if (!entry) throw new Error(`no change for path: ${args.patch}`)\n if (!entry.patch) {\n console.log(\n `${entry.path}: ${entry.status}${entry.contentOmitted ? ` (${entry.contentOmitted})` : ' (no content)'}`,\n )\n return\n }\n console.log(entry.patch)\n if (entry.patchTruncated) console.log('(diff truncated at the configured patch cap)')\n return\n }\n console.log(\n `# ${changes.identity.branch ?? `detached ${changes.identity.head ?? 'unborn'}`}` +\n ` · base ${changes.base.requestedRef} (${changes.base.resolvedOid.slice(0, 12)})`,\n )\n printRows(\n changes.changes.map((change) => [\n change.status,\n change.previousPath ? `${change.previousPath} -> ${change.path}` : change.path,\n change.binary\n ? 'binary'\n : change.addedLines === null\n ? ''\n : `${change.addedLines}+ ${change.deletedLines ?? 0}-`,\n change.contentOmitted ?? '',\n review.authors?.[change.path] ? `by ${review.authors[change.path]?.agentName}` : '',\n ]),\n '(no changes since baseline)',\n )\n if (changes.truncated) console.log('note: the change list is incomplete (file limit)')\n const withheld = changes.withheld\n if (withheld.excluded + withheld.untracked > 0) {\n console.log(\n `note: ${withheld.excluded} excluded and ${withheld.untracked} untracked path(s) withheld`,\n )\n }\n printIssues(changes)\n },\n})\n\nconst feedbackCmd = defineCommand({\n meta: {\n name: 'feedback',\n description:\n 'Queue a comment about a changed file, or one of its lines, for an Agent (diff excerpt, note)',\n },\n args: {\n id: teamArg,\n path: { type: 'string', required: true, description: 'Changed path the feedback is about' },\n agent: { type: 'string', required: true, description: 'Team member to send it to' },\n note: { type: 'string', description: 'Your comment' },\n line: {\n type: 'string',\n description: 'Line of the file as it is now; the diff around it is sent instead of the top',\n },\n base,\n },\n async run({ args }) {\n const client = createClient()\n const line = args.line === undefined ? undefined : Number(args.line)\n if (line !== undefined && (!Number.isSafeInteger(line) || line < 1)) {\n throw new Error('--line must be a line number starting at 1')\n }\n const queued = await client.repositoryReview(args.id).feedback({\n agentId: args.agent,\n comments: [\n {\n path: args.path,\n ...(line === undefined ? {} : { line }),\n ...(args.note ? { note: args.note } : {}),\n },\n ],\n ...(args.base ? { base: args.base } : {}),\n })\n console.log(`queued ${queued.item.id} for ${args.agent} (${queued.item.status})`)\n console.log(queued.message)\n },\n})\n\nexport const teamReviewCommand = defineCommand({\n meta: {\n name: 'review',\n description: 'Git change review: changes since a base, diffs, and file feedback',\n },\n subCommands: {\n show: showCmd,\n feedback: feedbackCmd,\n },\n})\n","import type { TeamDayKind, TeamDayResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport {\n apiPath,\n jsonFlag,\n printJson,\n printRows,\n teamArg,\n terminalSafe,\n} from '../command-helpers.ts'\n\n// `bazilion team today`: what a Team's Agents handed to each other, delivered, worked on and wait\n// on you for today, newest first: the same list as the Team's page in the web.\n\nconst KIND: Record<TeamDayKind, string> = {\n handoff: 'handed off',\n reply: 'replied',\n file: 'delivered',\n worked: 'worked in',\n question: 'asks you',\n approval: 'waits on you',\n}\n\nexport const teamTodayCommand = defineCommand({\n meta: {\n name: 'today',\n description: \"What a Team's Agents handed off, delivered, worked on and wait on you for today\",\n },\n args: { id: teamArg, json: jsonFlag },\n async run({ args }) {\n const start = new Date()\n start.setHours(0, 0, 0, 0)\n const day = await createClient().get<TeamDayResponse>(\n `${apiPath('teams', args.id, 'today')}?since=${start.getTime()}`,\n )\n if (args.json) return printJson(day)\n printRows(\n day.events.map((event) => [\n new Date(event.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),\n event.otherAgentName ? `${event.agentName} -> ${event.otherAgentName}` : event.agentName,\n KIND[event.kind],\n terminalSafe(event.text),\n ]),\n '(nothing yet today)',\n )\n if (day.truncated) console.log('note: only the latest events are listed')\n },\n})\n","import { readFileSync } from 'node:fs'\nimport type {\n SaveTeamAsTemplateRequest,\n SpawnTeamTemplateRequest,\n SpawnTeamTemplateResponse,\n TeamTemplate,\n TeamTemplateEndpoint,\n TeamTemplateInput,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { ApiClientError, createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson, teamArg } from '../command-helpers.ts'\n\nconst templateArg = positional('Template id')\n\nfunction endpointLabel(template: TeamTemplate, end: TeamTemplateEndpoint): string {\n return end === 'outside' ? 'outside' : `${end}:${template.slots[end]?.agentName ?? '?'}`\n}\n\nfunction printTemplate(template: TeamTemplate): void {\n console.log(`# ${template.id} — ${template.name}`)\n console.log(`mode: ${template.policyMode}`)\n if (template.slots.length) {\n console.log('')\n for (const line of columnize([\n ['slot', 'profile', 'Agent name', 'model', 'reasoning'],\n ...template.slots.map((slot, index) => [\n String(index),\n slot.profileId,\n slot.agentName,\n slot.modelOverride ?? '-',\n slot.reasoningLevel ?? '-',\n ]),\n ]))\n console.log(line)\n } else console.log('slots: (none)')\n if (template.edges.length) {\n console.log('')\n for (const line of columnize([\n ['from', 'to'],\n ...template.edges.map((edge) => [\n endpointLabel(template, edge.from),\n endpointLabel(template, edge.to),\n ]),\n ]))\n console.log(line)\n }\n}\n\n/** The editable part of a template, as `export` prints and `import` reads it. */\nfunction document(template: TeamTemplate): TeamTemplateInput {\n return {\n id: template.id,\n name: template.name,\n userMd: template.userMd,\n policyMode: template.policyMode,\n slots: template.slots,\n edges: template.edges,\n }\n}\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List Team templates' },\n args: { json: jsonFlag },\n async run({ args }) {\n const rows = await createClient().get<TeamTemplate[]>('/api/team-templates')\n if (args.json) return printJson(rows)\n if (!rows.length) return console.log('(no Team templates)')\n for (const line of columnize([\n ['id', 'slots', 'mode', 'name'],\n ...rows.map((row) => [row.id, String(row.slots.length), row.policyMode, row.name]),\n ]))\n console.log(line)\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Show a Team template' },\n args: { id: templateArg, json: jsonFlag },\n async run({ args }) {\n const template = await createClient().get<TeamTemplate>(apiPath('team-templates', args.id))\n if (args.json) printJson(template)\n else printTemplate(template)\n },\n})\n\nconst create = defineCommand({\n meta: { name: 'create', description: 'Create an empty Team template' },\n args: {\n id: positional('Template slug'),\n name: { type: 'string', description: 'Display name (defaults to the slug)' },\n },\n async run({ args }) {\n const body: TeamTemplateInput = { id: args.id, name: args.name ?? args.id }\n const created = await createClient().post<TeamTemplate>('/api/team-templates', body)\n console.log(`created Team template ${created.id}`)\n },\n})\n\nconst exportCommand = defineCommand({\n meta: { name: 'export', description: 'Print a Team template as JSON for editing or import' },\n args: { id: templateArg },\n async run({ args }) {\n const template = await createClient().get<TeamTemplate>(apiPath('team-templates', args.id))\n printJson(document(template))\n },\n})\n\nconst importCommand = defineCommand({\n meta: {\n name: 'import',\n description: 'Create a Team template from JSON, or replace the one with the same id',\n },\n args: { file: positional('JSON from export') },\n async run({ args }) {\n const body = JSON.parse(readFileSync(args.file, 'utf8')) as TeamTemplateInput\n if (typeof body.id !== 'string' || !body.id) throw new Error('the JSON needs an \"id\"')\n const client = createClient()\n const exists = await client.get<TeamTemplate>(apiPath('team-templates', body.id)).then(\n () => true,\n (error: unknown) => {\n if (error instanceof ApiClientError && error.status === 404) return false\n throw error\n },\n )\n const saved = exists\n ? await client.put<TeamTemplate>(apiPath('team-templates', body.id), body)\n : await client.post<TeamTemplate>('/api/team-templates', body)\n console.log(\n `${exists ? 'replaced' : 'created'} Team template ${saved.id} (${saved.slots.length} slots, ${saved.edges.length} edges)`,\n )\n },\n})\n\nconst rm = defineCommand({\n meta: { name: 'rm', description: 'Delete a Team template (spawned Teams are unaffected)' },\n args: { id: templateArg },\n async run({ args }) {\n await createClient().del(apiPath('team-templates', args.id))\n console.log(`deleted Team template ${args.id}`)\n },\n})\n\nconst spawn = defineCommand({\n meta: {\n name: 'spawn',\n description: 'Spawn one Agent per slot into a Team; an unknown Team slug creates the Team',\n },\n args: {\n id: templateArg,\n team: positional('Target Team slug'),\n 'user-md-file': { type: 'string', description: 'USER.md for a newly created Team' },\n },\n async run({ args }) {\n const body: SpawnTeamTemplateRequest = {\n teamId: args.team,\n ...(args['user-md-file'] ? { userMd: readFileSync(args['user-md-file'], 'utf8') } : {}),\n }\n const result = await createClient().post<SpawnTeamTemplateResponse>(\n apiPath('team-templates', args.id, 'spawn'),\n body,\n )\n console.log(\n `spawned ${result.agents.length} agent(s) into Team ${result.team.teamId}: ${result.agents.map((agent) => agent.name).join(', ')}`,\n )\n },\n})\n\nconst save = defineCommand({\n meta: {\n name: 'save',\n description: \"Save a live Team's members, edges, mode and USER.md as a new template\",\n },\n args: {\n team: teamArg,\n id: positional('New template id'),\n name: { type: 'string', description: 'Display name (defaults to the id)' },\n },\n async run({ args }) {\n const body: SaveTeamAsTemplateRequest = { id: args.id, name: args.name ?? args.id }\n const saved = await createClient().post<TeamTemplate>(\n apiPath('teams', args.team, 'policy', 'save-as-template'),\n body,\n )\n console.log(`saved Team ${args.team} as template ${saved.id} (${saved.slots.length} slots)`)\n },\n})\n\nexport const teamTemplateCommand = defineCommand({\n meta: { name: 'team-template', description: 'Reusable Team rosters with their allow edges' },\n subCommands: {\n list,\n show,\n create,\n export: exportCommand,\n import: importCommand,\n rm,\n spawn,\n save,\n },\n})\n","// `bazilion telegram` — the CLI side of the web Telegram page: credentials, setup checks, owner\n// pairing, the member allowlist, the bot, and agent topic bindings.\n\nimport type {\n Agent,\n TelegramAllowedUser,\n TelegramBindResponse,\n TelegramConfigState,\n TelegramHealth,\n TelegramPairingChallenge,\n TelegramPairingStatus,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional } from '../command-helpers.ts'\n\nconst telegramUserArg = positional('Numeric Telegram user id')\n\nconst setCmd = defineCommand({\n meta: {\n name: 'set',\n description: 'Save bot token + supergroup chat ID (paired write)',\n },\n args: {\n token: { type: 'string', required: true, description: 'Bot token from @BotFather' },\n chat: { type: 'string', required: true, description: 'Numeric supergroup chat ID' },\n },\n async run({ args }) {\n const client = createClient()\n const state = await client.put<TelegramConfigState>('/api/config/telegram', {\n botToken: args.token,\n chatId: args.chat,\n })\n console.log(`saved · token ${state.botTokenPreview} · chat ${state.chatId}`)\n },\n})\n\nconst clearCmd = defineCommand({\n meta: {\n name: 'clear',\n description: 'Remove stored bot token + chat ID',\n },\n async run() {\n const client = createClient()\n await client.del('/api/config/telegram')\n console.log('cleared')\n },\n})\n\nconst showCmd = defineCommand({\n meta: {\n name: 'show',\n description: 'Show what credentials are stored (token is masked)',\n },\n async run() {\n const client = createClient()\n const state = await client.get<TelegramConfigState>('/api/config/telegram')\n if (!state.configured) {\n console.log('(no credentials saved — run `bazilion telegram config set --token … --chat …`)')\n return\n }\n console.log(`token: ${state.botTokenPreview}`)\n console.log(`chat: ${state.chatId}`)\n if (state.migratedChatId) {\n console.log(\n `⚠ supergroup migrated → ${state.migratedChatId}. Run \\`bazilion telegram reconnect\\` to apply.`,\n )\n }\n },\n})\n\nconst reconnectCmd = defineCommand({\n meta: {\n name: 'reconnect',\n description: 'Apply a pending supergroup chat-id migration + re-activate the bot',\n },\n async run() {\n const client = createClient()\n const state = await client.post<TelegramConfigState>('/api/config/telegram/reconnect')\n console.log(`reconnected · chat ${state.chatId}`)\n },\n})\n\nconst configCmd = defineCommand({\n meta: {\n name: 'config',\n description: 'Manage Telegram credentials (bot token + chat ID)',\n },\n subCommands: {\n set: setCmd,\n clear: clearCmd,\n show: showCmd,\n },\n})\n\nconst healthCmd = defineCommand({\n meta: {\n name: 'health',\n description: 'Run the four-step preflight against the Telegram Bot API',\n },\n async run() {\n const h = await createClient().get<TelegramHealth>('/api/config/telegram/health')\n // Like `bot status`, an unconfigured bridge is a status report on stdout, not an error.\n if (!h.configured) {\n console.log('not configured — run `bazilion telegram config set` first')\n process.exitCode = 1\n return\n }\n if (h.error) throw new Error(`${h.error.step} failed: ${h.error.message}`)\n if (!h.preflight) throw new Error('preflight returned no data')\n const p = h.preflight\n const line = (ok: boolean, label: string, detail: string): string =>\n `${ok ? '✓' : '✕'} ${label.padEnd(30)} ${detail}`\n console.log(line(p.botUsername.length > 0, 'bot identity', `@${p.botUsername}`))\n console.log(line(p.chatTitle.length > 0, 'supergroup reachable', p.chatTitle))\n console.log(line(p.isForum, 'forum topics enabled', String(p.isForum)))\n console.log(line(p.hasManageTopics, 'can_manage_topics', String(p.hasManageTopics)))\n console.log(line(p.privacyModeOff, 'Privacy Mode is OFF', String(p.privacyModeOff)))\n console.log(line(p.chatIsPrivate, 'supergroup is private', String(p.chatIsPrivate)))\n // Everyone in the group can read the agents' replies, so this is worth a look.\n console.log(` ${'group members'.padEnd(30)} ${p.memberCount ?? 'unknown'}`)\n if (p.ownerPresent !== null) {\n console.log(line(p.ownerPresent, 'paired owner is present', String(p.ownerPresent)))\n }\n const allOk =\n p.botUsername.length > 0 &&\n p.chatTitle.length > 0 &&\n p.isForum &&\n p.hasManageTopics &&\n p.privacyModeOff &&\n p.chatIsPrivate &&\n p.ownerPresent !== false\n if (!allOk) process.exitCode = 1\n },\n})\n\nconst botStatusCmd = defineCommand({\n meta: {\n name: 'status',\n description: 'Show polling state of the live bot',\n },\n async run() {\n const client = createClient()\n const h = await client.get<TelegramHealth>('/api/config/telegram/health')\n if (!h.polling) {\n console.log('bot: not running')\n process.exitCode = 1\n return\n }\n const p = h.polling\n const startedAt = p.startedAt ? new Date(p.startedAt).toISOString() : '(never)'\n const lastPoll = p.lastSuccessfulPollAt\n ? new Date(p.lastSuccessfulPollAt).toISOString()\n : '(never)'\n console.log(`running: ${p.running}`)\n console.log(`activated: ${p.activated}`)\n console.log(`started at: ${startedAt}`)\n console.log(`last update id: ${p.lastUpdateId ?? '(none)'}`)\n console.log(`last successful: ${lastPoll}`)\n if (p.error) console.log(`error: ${p.error}`)\n if (!p.running) process.exitCode = 1\n },\n})\n\nconst botRestartCmd = defineCommand({\n meta: {\n name: 'restart',\n description: 'Force-restart the bot (tears down + brings up from current creds)',\n },\n async run() {\n const client = createClient()\n await client.post('/api/config/telegram/restart')\n console.log('restart requested')\n },\n})\n\nconst botCmd = defineCommand({\n meta: {\n name: 'bot',\n description: 'Inspect / control the live polling bot',\n },\n subCommands: {\n status: botStatusCmd,\n restart: botRestartCmd,\n },\n})\n\nconst bindCmd = defineCommand({\n meta: {\n name: 'bind',\n description: 'Create a Telegram topic for an agent (manual fallback for /talk)',\n },\n args: { agent: agentArg },\n async run({ args }) {\n const result = await createClient().post<TelegramBindResponse>(\n apiPath('agents', args.agent, 'telegram', 'bind'),\n )\n const verb = result.created ? 'created topic' : 'already bound to'\n console.log(`${verb} #${result.topicId} for agent ${result.agent.name} (${result.agent.id})`)\n console.log(` ${result.deepLink}`)\n },\n})\n\nconst unbindCmd = defineCommand({\n meta: {\n name: 'unbind',\n description: \"Clear an agent's Telegram topic binding (topic stays in Telegram as orphan)\",\n },\n args: { agent: agentArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.agent, 'telegram', 'binding'))\n console.log(`unbound agent ${args.agent}`)\n },\n})\n\nconst listBindingsCmd = defineCommand({\n meta: {\n name: 'list',\n description: 'List agents and their Telegram topic bindings',\n },\n async run() {\n const client = createClient()\n const agents = await client.get<Agent[]>('/api/agents')\n const bound = agents.filter((a) => a.telegramTopicId !== null)\n const unbound = agents.filter((a) => a.telegramTopicId === null)\n if (bound.length === 0 && unbound.length === 0) {\n console.log('(no agents)')\n return\n }\n if (bound.length > 0) {\n console.log('bound:')\n for (const a of bound) {\n console.log(` #${a.telegramTopicId}\\t${a.name}\\t(team: ${a.teamId})`)\n }\n }\n if (unbound.length > 0) {\n console.log('unbound:')\n for (const a of unbound) {\n console.log(` —\\t${a.name}\\t(team: ${a.teamId})`)\n }\n }\n },\n})\n\nconst allowCmd = defineCommand({\n meta: { name: 'allow', description: 'Add a Telegram user id to the allowlist' },\n args: {\n userId: telegramUserArg,\n label: { type: 'string', description: 'Optional human label' },\n },\n async run({ args }) {\n const client = createClient()\n const u = await client.post<TelegramAllowedUser>('/api/config/telegram/acl', {\n userId: Number(args.userId),\n label: args.label ?? null,\n role: 'member',\n })\n console.log(`allowed ${u.userId} (${u.role})`)\n },\n})\n\nconst denyCmd = defineCommand({\n meta: { name: 'deny', description: 'Remove a Telegram user id from the allowlist' },\n args: { userId: telegramUserArg },\n async run({ args }) {\n const client = createClient()\n await client.del(`/api/config/telegram/acl/${Number(args.userId)}`)\n console.log(`removed ${args.userId}`)\n },\n})\n\nconst allowedCmd = defineCommand({\n meta: { name: 'allowed', description: 'List allowlisted Telegram users' },\n async run() {\n const client = createClient()\n const users = await client.get<TelegramAllowedUser[]>('/api/config/telegram/acl')\n if (users.length === 0) {\n console.log('(allowlist empty — unpaired and closed)')\n return\n }\n for (const u of users) {\n const who = u.label ?? (u.username ? `@${u.username}` : '—')\n console.log(`${u.userId}\\t${u.role}\\t${who}`)\n }\n },\n})\n\nconst pairingCreateCmd = defineCommand({\n meta: { name: 'create', description: 'Generate a one-time Telegram owner pairing code' },\n async run() {\n const result = await createClient().post<TelegramPairingChallenge>(\n '/api/config/telegram/pairing/challenge',\n )\n console.log(`pairing code: ${result.code}`)\n console.log(`expires: ${new Date(result.expiresAt).toISOString()}`)\n console.log('send `/pair <code>` in the configured ⚙ bazilion service topic')\n },\n})\n\nconst pairingStatusCmd = defineCommand({\n meta: { name: 'status', description: 'Show Telegram owner pairing status' },\n async run() {\n const result = await createClient().get<TelegramPairingStatus>('/api/config/telegram/pairing')\n console.log(`paired: ${result.paired}`)\n console.log(`owner: ${result.ownerUserId ?? '(none)'}`)\n console.log(`challenge active: ${result.challengeActive}`)\n if (result.challengeExpiresAt)\n console.log(`expires: ${new Date(result.challengeExpiresAt).toISOString()}`)\n },\n})\n\nconst pairingCancelCmd = defineCommand({\n meta: { name: 'cancel', description: 'Cancel the active Telegram pairing code' },\n async run() {\n await createClient().del('/api/config/telegram/pairing/challenge')\n console.log('pairing challenge cancelled')\n },\n})\n\nconst pairingResetCmd = defineCommand({\n meta: { name: 'reset', description: 'Revoke the Telegram owner and require re-pairing' },\n args: {\n yes: { type: 'boolean', description: 'Confirm destructive owner reset', required: true },\n },\n async run({ args }) {\n if (!args.yes) throw new Error('--yes is required')\n await createClient().post('/api/config/telegram/pairing/reset', { confirm: true })\n console.log('Telegram owner reset; ingress is closed until re-paired')\n },\n})\n\nconst pairingCmd = defineCommand({\n meta: { name: 'pairing', description: 'Manage single-owner Telegram pairing' },\n subCommands: {\n create: pairingCreateCmd,\n status: pairingStatusCmd,\n cancel: pairingCancelCmd,\n reset: pairingResetCmd,\n },\n})\n\nexport const telegramCommand = defineCommand({\n meta: {\n name: 'telegram',\n description: 'Telegram integration: credentials, health, bot lifecycle, bindings, access',\n },\n subCommands: {\n config: configCmd,\n health: healthCmd,\n bot: botCmd,\n reconnect: reconnectCmd,\n bind: bindCmd,\n unbind: unbindCmd,\n list: listBindingsCmd,\n allow: allowCmd,\n deny: denyCmd,\n allowed: allowedCmd,\n pairing: pairingCmd,\n },\n})\n","import type {\n CreateTokenRequest,\n CreateTokenResponse,\n ListTokensResponse,\n WebToken,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { readAuthFile } from '../auth-file.ts'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\nimport { resolveCliPaths } from '../paths.ts'\n\nfunction tokenRow(t: WebToken): string[] {\n const last = t.lastUsedAt ? new Date(t.lastUsedAt).toISOString() : '(never)'\n const expired = t.expiresAt !== null && t.expiresAt <= Date.now()\n const state = t.revokedAt ? 'revoked' : expired ? 'expired' : 'active'\n const expires = t.expiresAt ? new Date(t.expiresAt).toISOString() : '(never)'\n return [t.id, t.kind, state, t.label, `expires: ${expires}`, `last: ${last}`]\n}\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Mint a new device token with full access (shown once)' },\n args: {\n label: positional('Human-readable label'),\n 'expires-days': {\n type: 'string',\n description: 'Expire the token after this many days (default: never)',\n },\n },\n async run({ args }) {\n const client = createClient()\n const expiresInDays =\n args['expires-days'] === undefined ? undefined : Number(args['expires-days'])\n if (expiresInDays !== undefined && !(Number.isInteger(expiresInDays) && expiresInDays > 0)) {\n throw new Error('--expires-days must be a positive integer')\n }\n const body: CreateTokenRequest = { label: args.label, expiresInDays }\n const res = await client.post<CreateTokenResponse>('/api/tokens', body)\n console.log(`id: ${res.meta.id}`)\n console.log(`label: ${res.meta.label}`)\n console.log(`kind: ${res.meta.kind}`)\n console.log(\n `expires: ${res.meta.expiresAt ? new Date(res.meta.expiresAt).toISOString() : '(never)'}`,\n )\n console.log(`token: ${res.token}`)\n console.log('')\n console.log('store the token now — it is not recoverable later.')\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List web tokens' },\n args: {\n all: { type: 'boolean', description: 'Include revoked tokens' },\n },\n async run({ args }) {\n const { tokens } = await createClient().get<ListTokensResponse>(\n `/api/tokens${args.all ? '?includeRevoked=1' : ''}`,\n )\n printRows(tokens.map(tokenRow), '(no tokens)')\n },\n})\n\nconst showLocalCmd = defineCommand({\n meta: {\n name: 'show-local',\n description: 'Print the bootstrap web token stored in ~/.bazilion/auth.json',\n },\n run() {\n const paths = resolveCliPaths()\n console.log(readAuthFile(paths.authFile).token)\n },\n})\n\nconst revokeCmd = defineCommand({\n meta: { name: 'revoke', description: 'Revoke a web token and its browser sessions' },\n args: { id: positional('Token id') },\n async run({ args }) {\n await createClient().del(apiPath('tokens', args.id))\n console.log(`revoked token ${args.id}`)\n },\n})\n\nexport const tokenCommand = defineCommand({\n meta: { name: 'token', description: 'Manage web tokens for API/CLI clients' },\n subCommands: {\n create: createCmd,\n list: listCmd,\n revoke: revokeCmd,\n 'show-local': showLocalCmd,\n },\n})\n","import type {\n AgentTrigger,\n CreateTriggerRequest,\n CreateTriggerResponse,\n ListTriggerDispatchesResponse,\n ListTriggersResponse,\n UpdateTriggerRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst triggerArg = positional('Trigger id')\n\nfunction spec(t: AgentTrigger): string {\n return t.kind === 'interval' ? `every ${t.intervalSec}s` : `cron \"${t.cronExpr}\"`\n}\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Add an interval / cron trigger to an agent' },\n args: {\n agent: agentArg,\n every: {\n type: 'string',\n description: 'Interval in seconds (e.g. --every 300 = every 5 minutes)',\n },\n cron: {\n type: 'string',\n description: 'Cron expression (5 fields: minute hour dom month dow)',\n },\n message: {\n type: 'string',\n required: true,\n description: 'Message to inject when the trigger fires',\n },\n disabled: { type: 'boolean', description: 'Create in disabled state' },\n },\n async run({ args }) {\n if (!args.every === !args.cron) {\n throw new Error('specify exactly one of --every <seconds> or --cron \"<expr>\"')\n }\n const body: CreateTriggerRequest = args.every\n ? {\n kind: 'interval',\n intervalSec: Number(args.every),\n message: args.message,\n enabled: !args.disabled,\n }\n : {\n kind: 'cron',\n cronExpr: args.cron as string,\n message: args.message,\n enabled: !args.disabled,\n }\n const { trigger } = await createClient().post<CreateTriggerResponse>(\n apiPath('agents', args.agent, 'triggers'),\n body,\n )\n console.log(`${trigger.id}\\t${spec(trigger)}\\t${trigger.enabled ? 'enabled' : 'disabled'}`)\n },\n})\n\nfunction triggerRow(t: AgentTrigger, next: number | null | undefined): string[] {\n const last = t.lastFiredAt ? new Date(t.lastFiredAt).toISOString() : '(never)'\n const state = t.enabled ? 'enabled' : 'disabled'\n const msgPreview = t.message.length > 60 ? `${t.message.slice(0, 60)}…` : t.message\n const upcoming = typeof next === 'number' ? new Date(next).toISOString() : '-'\n return [t.id, state, spec(t), `next: ${upcoming}`, `last: ${last}`, `\"${msgPreview}\"`]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List triggers for an agent' },\n args: { agent: agentArg },\n async run({ args }) {\n const { triggers, nextRuns, schedulerOff } = await createClient().get<ListTriggersResponse>(\n apiPath('agents', args.agent, 'triggers'),\n )\n printRows(\n triggers.map((trigger) => triggerRow(trigger, nextRuns[trigger.id])),\n '(no triggers)',\n )\n if (schedulerOff && triggers.length > 0)\n console.log('The daemon runs no schedules: it was started with BAZILION_SCHEDULER=off.')\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Delete a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n await createClient().del(apiPath('triggers', args.id))\n console.log(`removed trigger ${args.id}`)\n },\n})\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Enable a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n const body: UpdateTriggerRequest = { enabled: true }\n await createClient().patch(apiPath('triggers', args.id), body)\n console.log(`enabled trigger ${args.id}`)\n },\n})\n\nconst disableCmd = defineCommand({\n meta: { name: 'disable', description: 'Disable a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n const body: UpdateTriggerRequest = { enabled: false }\n await createClient().patch(apiPath('triggers', args.id), body)\n console.log(`disabled trigger ${args.id}`)\n },\n})\n\nconst historyCmd = defineCommand({\n meta: { name: 'history', description: 'Show recent runs of a trigger' },\n args: {\n id: triggerArg,\n limit: { type: 'string', description: 'Maximum rows (default 20)' },\n },\n async run({ args }) {\n const limit = args.limit ? Number(args.limit) : 20\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error('--limit must be an integer from 1 to 100')\n }\n const { dispatches } = await createClient().get<ListTriggerDispatchesResponse>(\n `${apiPath('triggers', args.id, 'dispatches')}?limit=${limit}`,\n )\n printRows(\n dispatches.map((dispatch) => [\n new Date(dispatch.scheduledAt).toISOString(),\n dispatch.status,\n dispatch.error ?? '',\n ]),\n '(no dispatches)',\n )\n },\n})\n\nexport const triggerCommand = defineCommand({\n meta: { name: 'trigger', description: 'Manage scheduled agent triggers' },\n subCommands: {\n add: addCmd,\n list: listCmd,\n rm: rmCmd,\n enable: enableCmd,\n disable: disableCmd,\n history: historyCmd,\n },\n})\n","import { existsSync, lstatSync, readdirSync, rmdirSync, rmSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { assertDaemonStopped, DAEMON_PID_FILE } from '../../../daemon/src/lib/daemon-liveness.ts'\nimport { confirm } from '../command-helpers.ts'\nimport { canonicalPath, requestedHome } from '../paths.ts'\n\n// The reset deletes these and keeps installed skills; --all deletes the skills too.\nconst RESET_ENTRIES = [\n 'profiles',\n 'agents',\n 'teams',\n 'browsers',\n DAEMON_PID_FILE,\n 'bazilion.db-wal',\n 'bazilion.db-shm',\n 'bazilion.db-journal',\n 'bazilion.db',\n 'auth.json',\n]\nconst ALL_ENTRIES = [...RESET_ENTRIES, 'skills']\n\nexport const uninstallCommand = defineCommand({\n meta: {\n name: 'uninstall',\n description: 'Delete the Bazilion data in ~/.bazilion (or BAZILION_HOME)',\n },\n args: {\n home: { type: 'string', description: 'Uninstall this home instead of BAZILION_HOME' },\n yes: { type: 'boolean', description: 'Do not ask for confirmation' },\n all: { type: 'boolean', description: 'Also delete installed skills, then the emptied home' },\n },\n async run({ args }) {\n const requested = requestedHome(args.home)\n const home = canonicalPath(requested)\n if (!existsSync(home)) {\n console.log(`nothing to remove: ${home} does not exist`)\n return\n }\n if (home === canonicalPath(homedir())) {\n throw new Error(\n `refusing to uninstall your home directory ${home}; delete Bazilion's files by hand`,\n )\n }\n // A directory given by mistake is refused: a home has bazilion.db, or only Bazilion's entries.\n const unmanaged = readdirSync(home).filter((entry) => !ALL_ENTRIES.includes(entry))\n if (!existsSync(join(home, 'bazilion.db')) && unmanaged.length > 0) {\n throw new Error(\n `${home} is not a Bazilion home: no bazilion.db, and it holds ${unmanaged.join(', ')}`,\n )\n }\n assertDaemonStopped(home)\n\n const scope = args.all\n ? `all Bazilion data in ${home}, installed skills included`\n : `the database, auth.json, profiles, Agents, Teams and browser profiles in ${home}`\n if (!args.yes && !(await confirm(`delete ${scope}?`))) {\n console.log('aborted')\n return\n }\n // Again: a daemon may have started while the question was open.\n assertDaemonStopped(home)\n // Linked Team slots are symlinks: rmSync unlinks them and never touches their targets.\n for (const entry of args.all ? ALL_ENTRIES : RESET_ENTRIES) {\n rmSync(join(home, entry), { recursive: true, force: true })\n }\n if (!args.all) {\n console.log(`reset ${home}; installed skills are kept`)\n console.log(\"run 'bazilion serve' to start again with a fresh database and auth.json\")\n return\n }\n const left = readdirSync(home).sort()\n if (left.length > 0) {\n console.log(`removed the Bazilion data; kept ${home}, which also holds ${left.join(', ')}`)\n } else if (lstatSync(requested).isSymbolicLink()) {\n // Deleting the link's target would leave BAZILION_HOME dangling.\n console.log(`emptied ${home}`)\n } else {\n rmdirSync(home)\n console.log(`removed ${home}`)\n }\n },\n})\n","import {\n formatCost,\n formatTokens,\n type UsageReport,\n type UsageTotals,\n usageSummary,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, terminalSafe } from '../command-helpers.ts'\n\n// `bazilion usage`: tokens and cost per Team, Agent, model and day, as Manage → Usage shows them.\n\nexport function usageHeadline(report: UsageReport): string {\n const period =\n report.days === null\n ? 'everything saved'\n : report.days === 1\n ? `today (${report.to})`\n : `the last ${report.days} days (${report.from} to ${report.to})`\n return `Usage over ${period}, ${report.timeZone}`\n}\n\n/** The totals on a few lines: money, then tokens by how they are paid for. */\nexport function totalsLines(totals: UsageTotals): string[] {\n const lines = [\n `Spent ${formatCost(totals.cost)}${totals.estimated ? ' (estimated from catalog prices)' : ''}`,\n `Tokens ${formatTokens(totals.totalTokens)} in ${totals.calls} model call${totals.calls === 1 ? '' : 's'}`,\n ]\n if (totals.planTokens > 0) lines.push(`On a plan ${formatTokens(totals.planTokens)} tokens`)\n if (totals.localTokens > 0) lines.push(`Local ${formatTokens(totals.localTokens)} tokens`)\n if (totals.unpricedTokens > 0)\n lines.push(\n `Unpriced ${formatTokens(totals.unpricedTokens)} tokens on models the catalog has no price for (not in Spent)`,\n )\n return lines\n}\n\nexport const usageCommand = defineCommand({\n meta: {\n name: 'usage',\n description: 'Show tokens and cost per Team, Agent, model and day',\n },\n args: {\n days: { type: 'string', default: '30', description: 'Days counted, today included' },\n all: { type: 'boolean', description: 'Count everything saved' },\n agent: { type: 'string', description: 'Only this Agent (id)' },\n team: { type: 'string', description: 'Only this Team (id)' },\n daily: { type: 'boolean', description: 'Also list every day' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({\n days: args.all ? 'all' : args.days,\n tz: Intl.DateTimeFormat().resolvedOptions().timeZone,\n })\n if (args.agent) query.set('agent', args.agent)\n if (args.team) query.set('team', args.team)\n const report = await createClient().get<UsageReport>(`/api/usage?${query}`)\n if (args.json) return printJson(report)\n console.log(usageHeadline(report))\n console.log('')\n for (const line of totalsLines(report.totals)) console.log(line)\n if (report.unreadable > 0)\n console.log(\n `${report.unreadable} saved conversation${report.unreadable === 1 ? '' : 's'} could not be read and ${report.unreadable === 1 ? 'is' : 'are'} not counted.`,\n )\n if (report.totals.calls === 0) return\n const section = (title: string, rows: string[][]) => {\n console.log('')\n console.log(title)\n printRows(rows, '(none)')\n }\n section(\n 'By Team',\n report.byTeam.map((team) => [terminalSafe(team.teamName), usageSummary(team)]),\n )\n section(\n 'By Agent',\n report.byAgent.map((agent) => [\n terminalSafe(agent.agentName) + (agent.archived ? ' (archived)' : ''),\n terminalSafe(agent.teamName),\n usageSummary(agent),\n ]),\n )\n section(\n 'By model',\n report.byModel.map((model) => [\n terminalSafe(`${model.providerName} ${model.model}`),\n usageSummary(model),\n ]),\n )\n if (args.daily)\n section(\n 'By day',\n report.byDay.map((day) => [day.day, day.calls ? usageSummary(day) : '']),\n )\n },\n})\n"],"mappings":";;;AAAA,SAAS,iBAAAA,iBAAe,YAAY,iBAAiB;;;ACArD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,SAAW;AAAA,EACX,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,IACP,WAAa;AAAA,EACf;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAQ;AAAA,EACR,KAAO;AAAA,IACL,UAAY;AAAA,EACd;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,OAAS;AAAA,EACX;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,cAAgB;AAAA,IACd,yBAAyB;AAAA,IACzB,mCAAmC;AAAA,IACnC,0BAA0B;AAAA,IAC1B,qBAAqB;AAAA,IACrB,wBAAwB;AAAA,IACxB,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M,CAAC;AACpC,MAAI;AACF,QAAI,QAAQ,SAAS,QAAQ,KAAK,QAAQ,SAAS,IAAI,GAAG;AAGxD,YAAM,kBAAkB,QAAQ,KAAK,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,CAAC;AAC9D,UAAI,CAAC,iBAAiB;AACpB,0BAAkB;AAClB,gBAAQ,KAAK,CAAC;AAAA,MAChB;AACA,YAAM,CAAC,QAAQ,MAAM,IAAI,MAAM,kBAAkB,MAAqB,OAAO;AAC7E,YAAM,UAAU,QAAQ,MAAM;AAC9B,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,QAAI,QAAQ,WAAW,MAAM,QAAQ,CAAC,MAAM,eAAe,QAAQ,CAAC,MAAM,OAAO;AAC/E,cAAQ,IAAI,OAAO;AACnB;AAAA,IACF;AACA,UAAM,WAAW,MAAM,EAAE,QAAQ,CAAC;AAAA,EACpC,SAAS,KAAK;AACZ,eAAW,GAAG;AACd,YAAQ,KAAK,iBAAiB,GAAG,CAAC;AAAA,EACpC;AACF;AAEA,MAAM;","names":["defineCommand","base","createClient","readFileSync","basename","row","resolve","stdin","stdout","basename","readFileSync","createClient","entry","defineCommand","defineCommand","defineCommand","createClient","basename","createInterface","defineCommand","basename","defineCommand","createClient","mode","rl","createInterface","defineCommand","defineCommand","createClient","defineCommand","defineCommand","createClient","defineCommand","defineCommand","createClient","defineCommand","createClient","list","defineCommand","defineCommand","createClient","defineCommand","resolve","defineCommand","createClient","existsSync","mkdirSync","readFileSync","rmSync","dirname","join","resolve","DatabaseSync","defineCommand","list","readFileSync","readFileSync","readFileSync","writeFileSync","join","defineCommand","existsSync","archive","list","rmSync","readFileSync","entry","join","DatabaseSync","resolve","mkdirSync","dirname","defineCommand","main","defineCommand","listCmd","defineCommand","createClient","body","rmCmd","defineCommand","list","defineCommand","createClient","spawn","existsSync","join","defineCommand","existsSync","join","defineCommand","entry","resolve","join","existsSync","resolve","label","spawn","entry","defineCommand","defineCommand","defineCommand","createClient","label","defineCommand","listCmd","defineCommand","createClient","showCmd","existsSync","readFileSync","writeFileSync","defineCommand","defineCommand","existsSync","readFileSync","writeFileSync","defineCommand","addCmd","defineCommand","entry","ask","createClient","setCmd","listCmd","showCmd","rmCmd","defineCommand","defineCommand","entry","createClient","readCmd","listCmd","rmCmd","defineCommand","settings","defineCommand","createClient","spawn","readFileSync","rmSync","writeFileSync","join","defineCommand","createCmd","defineCommand","readFileSync","createClient","listCmd","list","showCmd","editCmd","join","writeFileSync","resolve","spawn","rmSync","mode","deleteCmd","defineCommand","entry","checkLine","failure","listCmd","defineCommand","createClient","main","enableCmd","disableCmd","testCmd","defineCommand","defineCommand","createClient","defineCommand","list","defineCommand","createClient","closeSync","openSync","writeFileSync","defineCommand","list","defineCommand","createClient","show","openSync","writeFileSync","closeSync","defineCommand","defineCommand","createClient","defineCommand","listCmd","defineCommand","createClient","existsSync","readFileSync","basename","resolve","defineCommand","list","listCmd","defineCommand","createClient","resolve","existsSync","readFileSync","basename","rmCmd","readFileSync","stdin","defineCommand","defineCommand","print","defineCommand","createClient","defineCommand","decodeText","defineCommand","createClient","defineCommand","show","defineCommand","createClient","defineCommand","showCmd","defineCommand","createClient","entry","defineCommand","defineCommand","createClient","addCmd","defineCommand","createClient","listCmd","list","rmCmd","stdin","readFileSync","readFileSync","defineCommand","list","defineCommand","createClient","row","show","readFileSync","rm","spawn","defineCommand","setCmd","defineCommand","createClient","showCmd","label","defineCommand","createCmd","defineCommand","createClient","listCmd","revokeCmd","defineCommand","addCmd","defineCommand","createClient","listCmd","rmCmd","enableCmd","disableCmd","existsSync","readdirSync","rmSync","homedir","join","defineCommand","defineCommand","existsSync","homedir","readdirSync","entry","join","rmSync","defineCommand","defineCommand","createClient","defineCommand"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../package.json","../src/commands/activity.ts","../../../packages/client/src/index.ts","../src/auth-file.ts","../src/paths.ts","../src/client.ts","../src/command-helpers.ts","../src/columnize.ts","../src/repeatable-args.ts","../src/commands/agent.ts","../src/errors.ts","../src/commands/agent-browser.ts","../src/commands/agent-chat.ts","../src/question-prompt.ts","../src/commands/agent-context.ts","../src/commands/agent-learning.ts","../src/commands/agent-skills.ts","../src/commands/attention.ts","../src/commands/auth.ts","../src/commands/backup.ts","../../daemon/src/core/db/schema.ts","../../daemon/src/core/db/client.ts","../../daemon/src/lib/daemon-liveness.ts","../src/commands/completion.ts","../src/commands/config.ts","../../../packages/api-types/src/entities.ts","../../../packages/api-types/src/git-review.ts","../../../packages/api-types/src/mcp-presets.ts","../../../packages/api-types/src/profiles.ts","../../../packages/api-types/src/results.ts","../../../packages/api-types/src/usage.ts","../src/commands/conversation.ts","../src/commands/dashboard.ts","../src/commands/serve.ts","../src/commands/doctor.ts","../src/commands/inbox.ts","../src/commands/login.ts","../src/commands/mcp.ts","../src/commands/memory.ts","../src/commands/notification.ts","../src/commands/profile.ts","../src/commands/provider.ts","../src/commands/question.ts","../src/commands/queue.ts","../src/commands/result.ts","../src/commands/send.ts","../src/commands/session.ts","../src/commands/skill.ts","../src/commands/team.ts","../src/commands/team-environment.ts","../src/commands/team-messages.ts","../src/commands/team-policy.ts","../src/commands/team-review.ts","../src/commands/team-today.ts","../src/commands/team-template.ts","../src/commands/telegram.ts","../src/commands/token.ts","../src/commands/trigger.ts","../src/commands/uninstall.ts","../src/commands/usage.ts"],"sourcesContent":["import { defineCommand, runCommand, showUsage } from 'citty'\nimport pkg from '../package.json' with { type: 'json' }\nimport { activityCommand } from './commands/activity.ts'\nimport { agentCommand } from './commands/agent.ts'\nimport { attentionCommand } from './commands/attention.ts'\nimport { authCommand } from './commands/auth.ts'\nimport { backupCommand } from './commands/backup.ts'\nimport { completionCommand } from './commands/completion.ts'\nimport { configCommand } from './commands/config.ts'\nimport { conversationCommand } from './commands/conversation.ts'\nimport { dashboardCommand } from './commands/dashboard.ts'\nimport { doctorCommand } from './commands/doctor.ts'\nimport { inboxCommand } from './commands/inbox.ts'\nimport { loginCommand } from './commands/login.ts'\nimport { mcpCommand } from './commands/mcp.ts'\nimport { memoryCommand } from './commands/memory.ts'\nimport { notificationCommand } from './commands/notification.ts'\nimport { profileCommand } from './commands/profile.ts'\nimport { providerCommand } from './commands/provider.ts'\nimport { questionCommand } from './commands/question.ts'\nimport { queueCommand } from './commands/queue.ts'\nimport { resultCommand } from './commands/result.ts'\nimport { sendCommand } from './commands/send.ts'\nimport { serveCommand } from './commands/serve.ts'\nimport { sessionCommand } from './commands/session.ts'\nimport { skillCommand } from './commands/skill.ts'\nimport { teamCommand } from './commands/team.ts'\nimport { teamTemplateCommand } from './commands/team-template.ts'\nimport { telegramCommand } from './commands/telegram.ts'\nimport { tokenCommand } from './commands/token.ts'\nimport { triggerCommand } from './commands/trigger.ts'\nimport { uninstallCommand } from './commands/uninstall.ts'\nimport { usageCommand } from './commands/usage.ts'\nimport { exitCodeForError, printError } from './errors.ts'\n\nconst VERSION = pkg.version\n\nconst main = defineCommand({\n meta: {\n name: 'bazilion',\n version: VERSION,\n description: 'Multi-agent runtime',\n },\n subCommands: {\n login: loginCommand,\n profile: profileCommand,\n team: teamCommand,\n 'team-template': teamTemplateCommand,\n agent: agentCommand,\n activity: activityCommand,\n attention: attentionCommand,\n usage: usageCommand,\n result: resultCommand,\n conversation: conversationCommand,\n queue: queueCommand,\n question: questionCommand,\n notification: notificationCommand,\n skill: skillCommand,\n memory: memoryCommand,\n mcp: mcpCommand,\n provider: providerCommand,\n send: sendCommand,\n session: sessionCommand,\n inbox: inboxCommand,\n config: configCommand,\n serve: serveCommand,\n dashboard: dashboardCommand,\n doctor: doctorCommand,\n backup: backupCommand,\n trigger: triggerCommand,\n token: tokenCommand,\n auth: authCommand,\n telegram: telegramCommand,\n uninstall: uninstallCommand,\n },\n})\n\n// Mutate the command tree after definition so `completion` can introspect its\n// own siblings without a circular import. Cast is safe — citty keeps the\n// object reference on `main` after defineCommand, and we know its shape.\n;(main.subCommands as Record<string, unknown>).completion = completionCommand(main as never)\n\n// Resolve `bazilion <a> <b> --help` to the right subcommand for showUsage.\n// citty's built-in version is private, so we re-implement it for plain\n// subCommands objects (the shape we use throughout the tree).\ntype AnyCmd = Parameters<typeof showUsage>[0]\ntype CmdWithSubs = AnyCmd & { subCommands?: Record<string, AnyCmd> }\nasync function resolveSubCommand(\n cmd: CmdWithSubs,\n rawArgs: string[],\n parent?: AnyCmd,\n): Promise<[AnyCmd, AnyCmd | undefined]> {\n const subs = cmd.subCommands\n if (subs && Object.keys(subs).length > 0) {\n const idx = rawArgs.findIndex((a) => !a.startsWith('-'))\n const name = idx >= 0 ? rawArgs[idx] : undefined\n if (name && subs[name]) {\n return resolveSubCommand(subs[name] as CmdWithSubs, rawArgs.slice(idx + 1), cmd)\n }\n }\n return [cmd, parent]\n}\n\n// Top-level `bazilion --help` groups the commands by their own descriptions; `bazilion <command>\n// --help` uses citty's renderer. A command missing from these groups is listed under \"other\".\nconst HELP_GROUPS: Record<string, string[]> = {\n setup: ['serve', 'dashboard', 'doctor', 'backup', 'uninstall'],\n catalog: ['profile', 'team-template', 'team', 'skill', 'provider', 'config', 'auth', 'mcp'],\n agents: [\n 'attention',\n 'usage',\n 'agent',\n 'conversation',\n 'result',\n 'queue',\n 'question',\n 'memory',\n 'send',\n 'inbox',\n 'trigger',\n ],\n integrations: ['telegram', 'notification'],\n remote: ['login', 'token', 'session'],\n shell: ['completion'],\n}\n\nfunction printTopLevelHelp(): void {\n const commands = main.subCommands as Record<string, { meta?: { description?: string } }>\n const grouped = new Set(Object.values(HELP_GROUPS).flat())\n const other = Object.keys(commands).filter((name) => !grouped.has(name))\n console.log(`Multi-agent runtime (bazilion v${VERSION})`)\n console.log('')\n console.log('USAGE bazilion <command> [args]')\n console.log('')\n for (const [title, names] of Object.entries({ ...HELP_GROUPS, other })) {\n const listed = names.filter((name) => commands[name])\n if (listed.length === 0) continue\n console.log(` ${title}`)\n for (const name of listed) {\n console.log(` ${name.padEnd(15)}${commands[name]?.meta?.description ?? ''}`)\n }\n console.log('')\n }\n console.log('Use `bazilion <command> --help` for more information about a command.')\n}\n\nasync function entry(): Promise<void> {\n // package.json `engines` is the Node contract; this only turns another Node into a clear message.\n const [major = 0, minor = 0, patch = 0] = process.versions.node.split('.').map(Number)\n if (major !== 26 || minor < 12 || (minor === 12 && patch < 1)) {\n console.error(`bazilion requires Node.js ^26.12.1; this is ${process.versions.node}.`)\n process.exit(1)\n }\n const rawArgs = process.argv.slice(2)\n try {\n if (rawArgs.includes('--help') || rawArgs.includes('-h')) {\n // For the top-level `bazilion --help`, render our grouped layout.\n // Subcommand help still goes through citty (preserves native formatting).\n const firstPositional = rawArgs.find((a) => !a.startsWith('-'))\n if (!firstPositional) {\n printTopLevelHelp()\n process.exit(0)\n }\n const [target, parent] = await resolveSubCommand(main as CmdWithSubs, rawArgs)\n await showUsage(target, parent)\n process.exit(0)\n }\n if (rawArgs.length === 1 && (rawArgs[0] === '--version' || rawArgs[0] === '-v')) {\n console.log(VERSION)\n return\n }\n await runCommand(main, { rawArgs })\n } catch (err) {\n printError(err)\n process.exit(exitCodeForError(err))\n }\n}\n\nentry()\n","{\n \"name\": \"bazilion\",\n \"version\": \"0.59.0\",\n \"description\": \"Multi-agent runtime CLI — spawn LLM agents, manage profiles/teams/skills, and run the local daemon.\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rullopat/bazilion.git\",\n \"directory\": \"apps/cli\"\n },\n \"homepage\": \"https://bazilion.com\",\n \"bugs\": {\n \"url\": \"https://github.com/rullopat/bazilion/issues\"\n },\n \"keywords\": [\n \"agent\",\n \"agents\",\n \"ai\",\n \"cli\",\n \"daemon\",\n \"llm\",\n \"local-first\",\n \"multi-agent\",\n \"openclaw\",\n \"skills\"\n ],\n \"type\": \"module\",\n \"bin\": {\n \"bazilion\": \"./dist/cli.js\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"pnpm --filter @bazilion/web build && tsup\"\n },\n \"engines\": {\n \"node\": \"^26.12.1\"\n },\n \"dependencies\": {\n \"@earendil-works/pi-ai\": \"1.6.0\",\n \"@earendil-works/pi-coding-agent\": \"1.6.0\",\n \"@earendil-works/pi-mcp\": \"1.6.0\",\n \"@hono/node-server\": \"^2.0.6\",\n \"@mozilla/readability\": \"^0.6.0\",\n \"@tanstack/react-router\": \"1.170.18\",\n \"@tobilu/qmd\": \"^2.5.3\",\n \"@xyflow/react\": \"^12.11.2\",\n \"adm-zip\": \"^0.5.17\",\n \"age-encryption\": \"0.3.0\",\n \"citty\": \"^0.2.2\",\n \"clsx\": \"^2.1.1\",\n \"dompurify\": \"^3.4.11\",\n \"grammy\": \"^1.44.0\",\n \"hono\": \"^4.12.26\",\n \"linkedom\": \"^0.18.12\",\n \"lucide-react\": \"^1.21.0\",\n \"marked\": \"^18.0.5\",\n \"playwright\": \"^1.61.0\",\n \"radix-ui\": \"^1.6.0\",\n \"react\": \"^19.2.7\",\n \"react-dom\": \"^19.2.7\",\n \"tailwind-merge\": \"^3.6.0\",\n \"tar\": \"^7.5.16\",\n \"typebox\": \"^1.3.0\",\n \"undici\": \"^8.5.0\",\n \"yaml\": \"^2.9.0\"\n },\n \"devDependencies\": {\n \"@bazilion/api-types\": \"workspace:*\",\n \"@bazilion/client\": \"workspace:*\",\n \"@types/adm-zip\": \"^0.5.8\"\n }\n}\n","import type { ActivityResponse, Agent, AgentActivity } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, terminalSafe } from '../command-helpers.ts'\n\n// `bazilion activity`: what every Agent is doing and what waits for you, as the web's rail shows it.\n\n/** One line for an Agent's state; what needs the operator comes first. */\nexport function activityState(activity: AgentActivity): string {\n if (activity.questions > 0) {\n return `waiting for you: ${activity.questions} question${activity.questions === 1 ? '' : 's'}`\n }\n if (activity.approvals > 0) {\n return `waiting for you: ${activity.approvals} command${activity.approvals === 1 ? '' : 's'} to approve`\n }\n if (activity.working) {\n if (!activity.step) return 'working'\n return activity.step.target\n ? `working: ${activity.step.tool} ${activity.step.target}`\n : `working: ${activity.step.tool}`\n }\n if (activity.queuePaused) return 'follow-ups paused'\n return 'idle'\n}\n\nexport const activityCommand = defineCommand({\n meta: {\n name: 'activity',\n description: 'Show what every Agent is doing and what waits for you',\n },\n args: {\n team: { type: 'string', description: 'Only Agents of this Team' },\n json: jsonFlag,\n },\n async run({ args }) {\n const client = createClient()\n const [activity, agents] = await Promise.all([\n client.get<ActivityResponse>('/api/activity'),\n client.get<Agent[]>('/api/agents'),\n ])\n const shown = activity.agents.filter((entry) => !args.team || entry.teamId === args.team)\n if (args.json) return printJson({ agents: shown })\n const names = new Map(agents.map((agent) => [agent.id, agent.name]))\n printRows(\n shown.map((entry) => [\n names.get(entry.agentId) ?? entry.agentId.slice(0, 8),\n entry.teamId,\n terminalSafe(activityState(entry)),\n entry.lastActivityAt ? new Date(entry.lastActivityAt).toISOString() : '',\n entry.results ? `${entry.results} file${entry.results === 1 ? '' : 's'}` : '',\n ]),\n '(no agents)',\n )\n },\n})\n","// HTTP client for the daemon (or the web gateway in front of it), used by the CLI and by the web's\n// server-side loaders.\n\nimport type {\n AgentQuestionAnswer,\n AgentQuestionListResponse,\n ApiError,\n BrowserStatus,\n CodingEnvironmentStatus,\n EnqueueUserInput,\n NotificationSettings,\n NotificationSettingsResponse,\n ReviewFeedbackRequest,\n ReviewFeedbackResponse,\n TeamCodingEnvironment,\n TeamReviewResponse,\n UserQueueItem,\n UserQueueListResponse,\n} from '@bazilion/api-types'\n\nexport interface ClientConfig {\n serverUrl: string\n /** Sent as `Authorization: Bearer <token>`; null sends none. */\n token: string | null\n /** Extra request headers, e.g. the session cookie the web's loaders forward. */\n headers?: Record<string, string>\n}\n\nexport class ApiClientError extends Error {\n status: number\n body: ApiError\n constructor(status: number, body: ApiError) {\n super(`${status}: ${body.error}`)\n this.status = status\n this.body = body\n }\n}\n\n/** A non-2xx response, carrying its status and error body. */\nasync function failure(res: Response): Promise<ApiClientError> {\n const body = (await res.json().catch(() => ({ error: res.statusText }))) as ApiError\n return new ApiClientError(res.status, body)\n}\n\nexport function createClient(cfg: ClientConfig) {\n const authHeaders: Record<string, string> = {\n ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}),\n ...cfg.headers,\n }\n\n /** A JSON request; the body, when given, is sent as JSON. */\n function send(method: string, path: string, body?: unknown): Promise<Response> {\n return fetch(`${cfg.serverUrl}${path}`, {\n method,\n headers:\n body === undefined ? authHeaders : { ...authHeaders, 'content-type': 'application/json' },\n body: body === undefined ? undefined : JSON.stringify(body),\n })\n }\n\n async function json<T>(res: Response): Promise<T> {\n if (!res.ok) throw await failure(res)\n if (res.status === 204) return undefined as T\n return (await res.json()) as T\n }\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n return json<T>(await send(method, path, body))\n }\n\n /** Multipart POST: fetch sets the multipart content-type with its boundary itself. */\n async function postMultipart<T>(path: string, form: FormData): Promise<T> {\n return json<T>(\n await fetch(`${cfg.serverUrl}${path}`, { method: 'POST', headers: authHeaders, body: form }),\n )\n }\n\n /** An NDJSON response, one value per line. */\n async function* stream<T>(method: string, path: string, body?: unknown): AsyncGenerator<T> {\n const res = await send(method, path, body)\n if (!res.ok || !res.body) throw await failure(res)\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n if (line.trim()) yield JSON.parse(line) as T\n }\n }\n if (buffer.trim()) yield JSON.parse(buffer) as T\n }\n\n async function binary(path: string): Promise<Uint8Array> {\n const res = await fetch(`${cfg.serverUrl}${path}`, { headers: authHeaders, redirect: 'error' })\n if (!res.ok) throw await failure(res)\n return new Uint8Array(await res.arrayBuffer())\n }\n\n return {\n codingEnvironment: {\n show: (teamId: string) =>\n request<CodingEnvironmentStatus>(\n 'GET',\n `/api/teams/${encodeURIComponent(teamId)}/coding-environment`,\n ),\n set: (teamId: string, input: TeamCodingEnvironment) =>\n request<CodingEnvironmentStatus>(\n 'PUT',\n `/api/teams/${encodeURIComponent(teamId)}/coding-environment`,\n input,\n ),\n },\n /** Git change review: changes since a base, diffs, who wrote them, and review feedback. */\n repositoryReview: (teamId: string) => {\n const base = `/api/teams/${encodeURIComponent(teamId)}/review`\n return {\n changes: (\n options: { base?: string; patches?: boolean; path?: string; authors?: boolean } = {},\n ): Promise<TeamReviewResponse> => {\n const params = new URLSearchParams()\n if (options.base !== undefined) params.set('base', options.base)\n if (options.patches) params.set('patches', '1')\n if (options.path !== undefined) params.set('path', options.path)\n if (options.authors) params.set('authors', '1')\n const suffix = params.size ? `?${params}` : ''\n return request('GET', `${base}${suffix}`)\n },\n feedback: (input: ReviewFeedbackRequest): Promise<ReviewFeedbackResponse> =>\n request('POST', `${base}/feedback`, input),\n }\n },\n notifications: {\n settings: () => request<NotificationSettingsResponse>('GET', '/api/notifications'),\n configure: (input: NotificationSettings) =>\n request<NotificationSettingsResponse>('PUT', '/api/notifications', input),\n },\n questions: (agentId: string) => {\n const base = `/api/agents/${encodeURIComponent(agentId)}/questions`\n return {\n list: () => request<AgentQuestionListResponse>('GET', base),\n answer: (id: string, answer: AgentQuestionAnswer) =>\n request<{ ok: true }>('POST', `${base}/${encodeURIComponent(id)}/answer`, { answer }),\n }\n },\n queue: (agentId: string) => {\n const base = `/api/agents/${encodeURIComponent(agentId)}/queue`\n const item = (id: string) => `${base}/${encodeURIComponent(id)}`\n return {\n list: () => request<UserQueueListResponse>('GET', base),\n enqueue: (input: EnqueueUserInput) => request<UserQueueItem>('POST', base, input),\n edit: (id: string, message: string) =>\n request<UserQueueItem>('PATCH', item(id), { message }),\n remove: (id: string) => request<UserQueueItem>('DELETE', item(id)),\n pause: (paused: boolean) =>\n request<{ paused: boolean }>('POST', `${base}/control`, { paused }),\n }\n },\n /**\n * Managed browser controls. Status never launches; stop keeps the\n * profile; reset deletes it (cookies, logins), so callers confirm first.\n */\n getAgentBrowser: (agentId: string) =>\n request<BrowserStatus>('GET', `/api/agents/${encodeURIComponent(agentId)}/browser`),\n stopAgentBrowser: (agentId: string) =>\n request<void>('POST', `/api/agents/${encodeURIComponent(agentId)}/browser/stop`),\n resetAgentBrowser: (agentId: string) =>\n request<void>('DELETE', `/api/agents/${encodeURIComponent(agentId)}/browser/profile`),\n binary,\n get: <T>(p: string) => request<T>('GET', p),\n post: <T>(p: string, b?: unknown) => request<T>('POST', p, b),\n postMultipart,\n put: <T>(p: string, b?: unknown) => request<T>('PUT', p, b),\n patch: <T>(p: string, b?: unknown) => request<T>('PATCH', p, b),\n del: <T>(p: string) => request<T>('DELETE', p),\n stream,\n }\n}\n\nexport type BazilionClient = ReturnType<typeof createClient>\n","import { existsSync, readFileSync } from 'node:fs'\n\nexport interface AuthFile {\n token: string\n remote?: { server: string; token: string } | null\n}\n\nexport function readAuthFile(authFile: string): AuthFile {\n if (!existsSync(authFile)) {\n throw new Error(`${authFile} not found. Start the daemon with \\`bazilion serve\\` first.`)\n }\n const raw = readFileSync(authFile, 'utf8')\n const parsed = JSON.parse(raw) as Partial<AuthFile>\n if (typeof parsed.token !== 'string' || !parsed.token) {\n throw new Error(`${authFile} is missing the \"token\" field`)\n }\n return { token: parsed.token, remote: parsed.remote ?? null }\n}\n","import { realpathSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { basename, dirname, join, resolve } from 'node:path'\n\ninterface CliPaths {\n home: string\n authFile: string\n}\n\nexport function resolveCliPaths(home?: string): CliPaths {\n // The daemon's resolvePaths (apps/daemon/src/core/paths.ts) spells the home the same way.\n const root = canonicalPath(requestedHome(home))\n return { home: root, authFile: join(root, 'auth.json') }\n}\n\n/** The home as given (`--home`, BAZILION_HOME or ~/.bazilion), before symlinks are resolved. */\nexport function requestedHome(home?: string): string {\n return resolve(home ?? process.env.BAZILION_HOME ?? join(homedir(), '.bazilion'))\n}\n\n/** Absolute path with symlinks resolved in every existing segment; a missing tail is kept. */\nexport function canonicalPath(path: string): string {\n let resolved = resolve(path)\n const unresolvedTail: string[] = []\n while (true) {\n try {\n resolved = realpathSync(resolved)\n break\n } catch {\n const parent = dirname(resolved)\n if (parent === resolved) break // reached the filesystem root\n unresolvedTail.unshift(basename(resolved))\n resolved = parent\n }\n }\n return join(resolved, ...unresolvedTail)\n}\n","import { type BazilionClient, createClient as createPackageClient } from '@bazilion/client'\nimport { readAuthFile } from './auth-file.ts'\nimport { resolveCliPaths } from './paths.ts'\n\nexport type { BazilionClient } from '@bazilion/client'\nexport { ApiClientError } from '@bazilion/client'\n\ninterface ClientConfig {\n serverUrl: string\n token: string\n}\n\nexport function loadClientConfig(): ClientConfig {\n const envUrl = process.env.BAZILION_SERVER\n const envToken = process.env.BAZILION_TOKEN\n if (envUrl && envToken) return { serverUrl: envUrl, token: envToken }\n\n const paths = resolveCliPaths()\n const auth = readAuthFile(paths.authFile)\n // `bazilion login` writes `remote`; when present it targets another host\n // (Tailscale, LAN). Env vars still win so CI / ad-hoc invocations can\n // override without editing auth.json.\n if (auth.remote?.server && auth.remote.token) {\n return {\n serverUrl: envUrl ?? auth.remote.server,\n token: auth.remote.token,\n }\n }\n return {\n serverUrl: envUrl ?? 'http://127.0.0.1:4321',\n token: auth.token,\n }\n}\n\nexport function createClient(): BazilionClient {\n const { serverUrl, token } = loadClientConfig()\n return createPackageClient({ serverUrl, token })\n}\n","import { readFileSync } from 'node:fs'\nimport { basename, extname } from 'node:path'\nimport { createInterface } from 'node:readline'\nimport type { Attachment, SkillScanFinding } from '@bazilion/api-types'\nimport { columnize } from './columnize.ts'\nimport { collectFlagValues } from './repeatable-args.ts'\n\n/** A required positional argument. */\nexport function positional(description: string) {\n return { type: 'positional', required: true, description } as const\n}\n\nexport const agentArg = positional('Agent id or prefix')\nexport const teamArg = positional('Team slug')\nexport const jsonFlag = { type: 'boolean', description: 'Emit JSON' } as const\n\n/** A daemon API path from its segments, each URL-encoded: `apiPath('agents', id, 'skills')`. */\nexport function apiPath(...segments: string[]): string {\n return `/api/${segments.map(encodeURIComponent).join('/')}`\n}\n\nexport function printJson(value: unknown): void {\n console.log(JSON.stringify(value, null, 2))\n}\n\n/** Print rows as aligned columns, or `empty` when there are none. */\nexport function printRows(rows: string[][], empty: string): void {\n if (rows.length === 0) console.log(empty)\n for (const line of columnize(rows)) console.log(line)\n}\n\n/** Ask on stdin and return the trimmed answer; the end of input is an empty answer. */\nexport function ask(question: string): Promise<string> {\n process.stdout.write(question)\n const input = createInterface({ input: process.stdin })\n return new Promise((resolve) => {\n let answer = ''\n input.once('line', (line) => {\n answer = line\n input.close()\n })\n input.once('close', () => resolve(answer.trim()))\n })\n}\n\n/**\n * Ask for a secret. On a terminal nothing typed or pasted is echoed; piped input is read as one\n * line, so `bazilion provider connect anthropic < key.txt` works too.\n */\nexport function askSecret(question: string): Promise<string> {\n const { stdin, stdout } = process\n if (!stdin.isTTY) return ask(question)\n stdout.write(question)\n return new Promise((resolve, reject) => {\n let value = ''\n const finish = (error?: Error) => {\n stdin.off('data', onData)\n stdin.setRawMode(false)\n stdin.pause()\n stdout.write('\\n')\n if (error) reject(error)\n else resolve(value.trim())\n }\n const onData = (chunk: Buffer | string) => {\n for (const character of String(chunk)) {\n if (character === '\\r' || character === '\\n') return finish()\n // Ctrl-C and Ctrl-D leave without a key.\n if (character === '\\u0003' || character === '\\u0004') return finish(new Error('cancelled'))\n if (character === '\\u007f' || character === '\\b') value = value.slice(0, -1)\n else if (character >= ' ') value += character\n }\n }\n stdin.setRawMode(true)\n stdin.resume()\n stdin.on('data', onData)\n })\n}\n\n/** Ask a yes/no question; only y or yes confirms. */\nexport async function confirm(question: string): Promise<boolean> {\n return /^y(es)?$/i.test(await ask(`${question} [y/N] `))\n}\n\n/** Show control characters (escape sequences, carriage returns, ...) as `\\xNN`. */\nexport function terminalSafe(value: string, keepTabs = false): string {\n let safe = ''\n for (const character of value) {\n const code = character.charCodeAt(0)\n const isControl =\n (code <= 31 && code !== 10 && !(keepTabs && code === 9)) || (code >= 127 && code <= 159)\n safe += isControl ? `\\\\x${code.toString(16).padStart(2, '0')}` : character\n }\n return safe\n}\n\nconst IMAGE_TYPES: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n}\n\nconst FILE_TYPES: Record<string, string> = {\n '.pdf': 'application/pdf',\n '.txt': 'text/plain',\n '.md': 'text/markdown',\n '.csv': 'text/csv',\n '.json': 'application/json',\n '.html': 'text/html',\n '.zip': 'application/zip',\n}\n\nfunction attachment(path: string, mimeType: string): Attachment {\n return { name: basename(path), mimeType, data: readFileSync(path).toString('base64') }\n}\n\n/**\n * The repeatable `--image` and `--file` flags as attachments: images go to the model, files are\n * stored for the Agent to read. citty keeps only the last value of a repeated flag, so the values\n * come from the raw arguments.\n */\nexport function loadAttachments(rawArgs: string[]): Attachment[] {\n const images = collectFlagValues(rawArgs, 'image').map((path) => {\n const mimeType = IMAGE_TYPES[extname(path).toLowerCase()]\n if (!mimeType) throw new Error(`unsupported image type: ${path} (png/jpg/gif/webp only)`)\n return attachment(path, mimeType)\n })\n const files = collectFlagValues(rawArgs, 'file').map((path) =>\n attachment(path, FILE_TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'),\n )\n return [...images, ...files]\n}\n\nexport function findingLines(findings: SkillScanFinding[]): string[] {\n return findings.map(\n (f) => `${f.severity}: ${f.code}${f.line ? ` line ${f.line}` : ''} - ${f.message}`,\n )\n}\n","/**\n * Render `rows` as space-aligned columns. All rows must have the same column\n * count; empty cells are treated as `\"\"` for width purposes. Column spacing is\n * two spaces — wider than a tab, tighter than tabular CSV tooling expects.\n *\n * Used by list commands so `status` / `kind` / `name` columns don't jump when\n * one row is `idle` (4) and another is `archived` (8). Does not truncate —\n * long cells win the column width. Callers that want a bounded width should\n * slice before passing.\n */\nexport function columnize(rows: string[][], gap = ' '): string[] {\n if (rows.length === 0) return []\n const colCount = rows[0]?.length ?? 0\n const widths: number[] = new Array<number>(colCount).fill(0)\n for (const row of rows) {\n for (let i = 0; i < colCount; i++) {\n const cell = row[i] ?? ''\n const prev = widths[i] ?? 0\n if (cell.length > prev) widths[i] = cell.length\n }\n }\n return rows.map((row) =>\n row\n .map((cell, i) => {\n // Don't pad the last column — trailing whitespace is pointless and\n // breaks `| wc`-style pipes.\n if (i === colCount - 1) return cell\n return (cell ?? '').padEnd(widths[i] ?? 0)\n })\n .join(gap),\n )\n}\n","/**\n * Every value of a repeatable flag (`--image a --image b`), read from the raw arguments: citty\n * parses a repeated flag last-wins. Values are taken as given, never split on commas, so paths may\n * contain them. An option value that is itself the flag name would be misread.\n */\nexport function collectFlagValues(rawArgs: readonly string[], name: string): string[] {\n const values: string[] = []\n const long = `--${name}`\n for (let i = 0; i < rawArgs.length; i++) {\n const arg = rawArgs[i]\n if (arg === undefined) continue\n // Everything after `--` is positional by convention, never a flag.\n if (arg === '--') break\n if (arg === long) {\n const next = rawArgs[i + 1]\n if (next !== undefined && next !== '--') {\n values.push(next)\n i++\n }\n continue\n }\n if (arg.startsWith(`${long}=`)) {\n const value = arg.slice(long.length + 1)\n if (value.length > 0) values.push(value)\n }\n }\n return values\n}\n","import type { Agent, MoveAgentRequest, ResolvedAgent, SpawnAgentRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, printRows, teamArg } from '../command-helpers.ts'\nimport { UsageError } from '../errors.ts'\nimport { browserCommand } from './agent-browser.ts'\nimport { chatCommand } from './agent-chat.ts'\nimport { contextCommands } from './agent-context.ts'\nimport { learningCommands } from './agent-learning.ts'\nimport { agentSkillCommand } from './agent-skills.ts'\n\nconst spawnCmd = defineCommand({\n meta: { name: 'spawn', description: 'Spawn an agent from a profile into a team' },\n args: {\n profile: { type: 'string', required: true, description: 'Profile id' },\n name: { type: 'string', description: 'Agent name (defaults to profile name)' },\n team: { type: 'string', description: \"Team to join (defaults to 'default')\" },\n model: { type: 'string', description: 'Override profile default model' },\n reasoning: {\n type: 'string',\n description: 'Reasoning level: off|minimal|low|medium|high|xhigh (default: medium)',\n },\n role: {\n type: 'string',\n description:\n 'What it is for: it starts knowing its job, without the get-to-know questions of a first conversation',\n },\n },\n async run({ args }) {\n const body: SpawnAgentRequest = {\n profileId: args.profile,\n name: args.name,\n model: args.model,\n reasoningLevel: args.reasoning as SpawnAgentRequest['reasoningLevel'],\n teamId: args.team ?? 'default',\n ...(args.role ? { role: args.role } : {}),\n }\n const { agent } = await createClient().post<{ agent: Agent }>('/api/agents', body)\n console.log(`spawned agent ${agent.id} (${agent.name})`)\n console.log(`dir: ${agent.dir}`)\n },\n})\n\nconst editCmd = defineCommand({\n meta: {\n name: 'edit',\n description: 'Edit agent settings (name, model override, reasoning level, telegram mirror)',\n },\n args: {\n id: agentArg,\n name: { type: 'string', description: 'Rename the agent' },\n model: { type: 'string', description: 'Set model override (use --model \"\" to clear)' },\n reasoning: {\n type: 'string',\n description: 'Reasoning level: off|minimal|low|medium|high|xhigh',\n },\n mirror: { type: 'string', description: 'Telegram mirror verbosity: minimal|verbose' },\n 'topic-icon': {\n type: 'string',\n description: 'Telegram topic emoji (e.g. 📚). Use --topic-icon \"\" to clear.',\n },\n },\n async run({ args }) {\n const body: Record<string, unknown> = {}\n if (args.name !== undefined) body.name = args.name\n if (args.model !== undefined) body.modelOverride = args.model === '' ? null : args.model\n if (args.reasoning !== undefined) body.reasoningLevel = args.reasoning\n if (args.mirror !== undefined) {\n if (args.mirror !== 'minimal' && args.mirror !== 'verbose') {\n throw new UsageError(\"--mirror must be 'minimal' or 'verbose'\")\n }\n body.telegramMirrorMode = args.mirror\n }\n if (args['topic-icon'] !== undefined) {\n body.telegramIconEmoji = args['topic-icon'] === '' ? null : args['topic-icon']\n }\n if (Object.keys(body).length === 0) {\n throw new UsageError(\n 'specify at least one of --name, --model, --reasoning, --mirror, --topic-icon',\n )\n }\n const agent = await createClient().patch<Agent>(apiPath('agents', args.id), body)\n console.log(`updated agent ${agent.id} (${agent.name})`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List agents' },\n args: {\n all: { type: 'boolean', description: 'Include archived agents' },\n long: { type: 'boolean', alias: 'l', description: 'Show profile + full UUID columns' },\n },\n async run({ args }) {\n const list = await createClient().get<Agent[]>(\n `/api/agents${args.all ? '?includeArchived=true' : ''}`,\n )\n printRows(\n list.map((a) =>\n // Every command accepts an id prefix, so the short listing shows the first 8 characters.\n args.long ? [a.id, a.status, a.name, a.profileId] : [a.id.slice(0, 8), a.status, a.name],\n ),\n '(no agents)',\n )\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show agent details' },\n args: { id: agentArg },\n async run({ args }) {\n const r = await createClient().get<ResolvedAgent>(apiPath('agents', args.id))\n console.log(`# ${r.agent.id}`)\n console.log(`name: ${r.agent.name}`)\n console.log(`status: ${r.agent.status}`)\n console.log(`profile: ${r.profile.id}`)\n console.log(`model: ${r.model}`)\n console.log(`dir: ${r.agent.dir}`)\n console.log(`team: ${r.team.id} ${r.team.path}`)\n console.log('skills:')\n if (r.skills.length === 0) console.log(' (none)')\n for (const s of r.skills) console.log(` ${s}`)\n },\n})\n\nconst archiveCmd = defineCommand({\n meta: { name: 'archive', description: 'Archive an agent' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().post(apiPath('agents', args.id, 'archive'))\n console.log(`archived agent ${args.id}`)\n },\n})\n\nconst unarchiveCmd = defineCommand({\n meta: { name: 'unarchive', description: 'Restore an archived agent to idle' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().post(apiPath('agents', args.id, 'unarchive'))\n console.log(`unarchived agent ${args.id}`)\n },\n})\n\nconst deleteCmd = defineCommand({\n meta: { name: 'delete', description: 'Permanently delete an agent and its data' },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.id))\n console.log(`deleted agent ${args.id}`)\n },\n})\n\nconst cancelCmd = defineCommand({\n meta: {\n name: 'cancel',\n description: \"Abort the agent's running turn; waiting follow-ups are paused\",\n },\n args: { id: agentArg },\n async run({ args }) {\n const { cancelled, queuePaused } = await createClient().post<{\n cancelled: boolean\n queuePaused: boolean\n }>(apiPath('agents', args.id, 'cancel'))\n if (cancelled) console.log(`cancelled active turn for ${args.id}`)\n if (queuePaused) {\n console.log(`follow-up queue paused; resume it with: bazilion queue resume ${args.id}`)\n }\n },\n})\n\nconst moveCmd = defineCommand({\n meta: { name: 'move', description: 'Move an agent to a different team' },\n args: { agent: agentArg, team: teamArg },\n async run({ args }) {\n const body: MoveAgentRequest = { teamId: args.team }\n await createClient().patch(apiPath('agents', args.agent, 'team'), body)\n console.log(`moved ${args.agent} to team ${args.team}`)\n },\n})\n\nexport const agentCommand = defineCommand({\n meta: { name: 'agent', description: 'Manage agent instances' },\n subCommands: {\n spawn: spawnCmd,\n list: listCmd,\n show: showCmd,\n edit: editCmd,\n archive: archiveCmd,\n unarchive: unarchiveCmd,\n delete: deleteCmd,\n chat: chatCommand,\n ...contextCommands,\n cancel: cancelCmd,\n ...learningCommands,\n skill: agentSkillCommand,\n move: moveCmd,\n browser: browserCommand,\n },\n})\n","import { ApiClientError } from './client.ts'\nimport { findingLines } from './command-helpers.ts'\n\n/** A mistake in the command line itself: it exits 2, like a request the daemon finds invalid. */\nexport class UsageError extends Error {}\n\n/**\n * Rethrow a blocked skill scan as one error listing the findings and the flag that confirms them;\n * any other failure is rethrown as it is.\n */\nexport function explainScanBlock(confirmFlag: string): (err: unknown) => never {\n return (err) => {\n if (!(err instanceof ApiClientError) || err.body.code !== 'skill_scan_blocked') throw err\n const findings = findingLines(err.body.findings ?? []).map((line) => ` ${line}`)\n throw new Error(\n [\n err.body.error,\n ...(findings.length > 0 ? ['scan findings:', ...findings] : []),\n ` hint: inspect the skill, then rerun with ${confirmFlag} to confirm`,\n ].join('\\n'),\n )\n }\n}\n\n/** Print a failed command's error, with a hint for the common setup mistakes. */\nexport function printError(err: unknown): void {\n if (err instanceof ApiClientError) {\n console.error(`error: ${err.body.error}`)\n if (err.status === 401) {\n console.error(' hint: token mismatch. Check ~/.bazilion/auth.json \"token\"')\n console.error(' or re-run \"bazilion login\" for a remote server.')\n } else if (err.status === 403 && !err.body.code) {\n // A gateway origin/CSRF refusal; domain refusals (a Team Policy denial) carry a code.\n console.error(' hint: the server refused the request. Check that BAZILION_SERVER matches')\n console.error(' the server origin exactly (scheme + host + port).')\n }\n return\n }\n const msg = err instanceof Error ? err.message : String(err)\n console.error(`error: ${msg}`)\n // node's fetch wraps the syscall error, so its code is on `cause`.\n const code = err instanceof Error ? (err as { cause?: { code?: string } }).cause?.code : undefined\n if (code === 'ECONNREFUSED' || /ECONNREFUSED/.test(msg)) {\n console.error(' hint: the bazilion server is not running. Start it with \"bazilion serve\"')\n console.error(' or point BAZILION_SERVER at a running instance.')\n } else if (code === 'ENOTFOUND' || /ENOTFOUND/.test(msg)) {\n console.error(' hint: host not found. Check BAZILION_SERVER / ~/.bazilion/auth.json.')\n }\n}\n\n/** 2: invalid (a usage error, or rejected by the daemon); 3: conflict; 4: not authorized; 1: the rest. */\nexport function exitCodeForError(err: unknown): number {\n if (err instanceof UsageError) return 2\n if (!(err instanceof ApiClientError)) return 1\n if (err.status === 401 || err.status === 403) return 4\n if (err.status === 409) return 3\n return err.status === 400 || err.status === 422 ? 2 : 1\n}\n","import { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, ask, printJson } from '../command-helpers.ts'\n\nconst statusCmd = defineCommand({\n meta: { name: 'status', description: \"Show the agent's browser status (never starts it)\" },\n args: { id: agentArg },\n async run({ args }) {\n printJson(await createClient().getAgentBrowser(args.id))\n },\n})\n\nconst stopCmd = defineCommand({\n meta: { name: 'stop', description: \"Stop the agent's browser (the profile is kept)\" },\n args: { id: agentArg },\n async run({ args }) {\n await createClient().stopAgentBrowser(args.id)\n console.log(`stopped the browser of agent ${args.id} (profile kept)`)\n },\n})\n\nconst resetCmd = defineCommand({\n meta: {\n name: 'reset',\n description: \"Stop the agent's browser and DELETE its profile (cookies, logins)\",\n },\n args: {\n id: agentArg,\n yes: { type: 'boolean', description: 'Skip the confirmation prompt' },\n },\n async run({ args }) {\n if (!args.yes) {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n throw new Error('refusing to reset a browser profile noninteractively without --yes')\n }\n const answer = await ask(\n `This deletes the browser profile of ${args.id} (cookies, logins). Type the agent id to confirm: `,\n )\n if (answer !== args.id) throw new Error('confirmation did not match; nothing was changed')\n }\n await createClient().resetAgentBrowser(args.id)\n console.log(`reset the browser of agent ${args.id}: stopped, profile removed`)\n },\n})\n\nexport const browserCommand = defineCommand({\n meta: { name: 'browser', description: \"The agent's managed browser: status, stop, reset\" },\n subCommands: { status: statusCmd, stop: stopCmd, reset: resetCmd },\n})\n","import { writeFileSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { stdin, stdout } from 'node:process'\nimport { createInterface, type Interface } from 'node:readline/promises'\nimport type {\n Attachment,\n BashApprovalMode,\n ChatFrame,\n ChatRequest,\n CommandApproval,\n CommandApprovalDecisionRequest,\n ResolvedAgent,\n SessionEvent,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { type BazilionClient, createClient } from '../client.ts'\nimport { agentArg, apiPath, loadAttachments, terminalSafe } from '../command-helpers.ts'\nimport { printError } from '../errors.ts'\nimport { promptForQuestion, type QuestionPrompt } from '../question-prompt.ts'\n\nexport interface PrintState {\n inDeltaStream: boolean\n /** Per running tool call: the complete lines of its live output already printed. */\n progress: Map<string, string>\n}\n\n/**\n * The complete lines of a cumulative live-output tail that were not printed yet. The tail may have\n * slid forward since the last update (the daemon starts a cut tail on a line boundary), so what was\n * printed is matched against its start at each line boundary.\n */\nexport function unprintedProgress(\n printed: string,\n output: string,\n): { complete: string; fresh: string } {\n const complete = output.slice(0, output.lastIndexOf('\\n') + 1)\n for (let start = 0; start < printed.length; ) {\n const rest = printed.slice(start)\n if (complete.startsWith(rest)) return { complete, fresh: complete.slice(rest.length) }\n start = printed.indexOf('\\n', start) + 1\n if (start === 0) break\n }\n return { complete, fresh: complete }\n}\n\ntype CommandApprovalDecision = CommandApprovalDecisionRequest['decision']\n\nexport interface CommandApprovalPrompt {\n question(prompt: string): Promise<string>\n write(line: string): void\n}\n\n/** Only a real terminal can answer while the chat response stream remains open. */\nexport function bashApprovalModeForTty(\n inputIsTty: boolean | undefined,\n outputIsTty: boolean | undefined,\n): BashApprovalMode {\n return inputIsTty && outputIsTty ? 'interactive' : 'auto_deny'\n}\n\n/** Every CLI chat request states whether the caller can answer shell approvals. */\nexport function buildChatRequest(\n message: string,\n attachments: Attachment[] | undefined,\n bashApprovalMode: BashApprovalMode,\n): ChatRequest {\n return {\n message,\n bashApprovalMode,\n ...(attachments && attachments.length > 0 ? { attachments } : {}),\n }\n}\n\n/** Render one pending command; every answer except y/yes denies it. */\nexport async function promptForCommandApproval(\n approval: CommandApproval,\n prompt: CommandApprovalPrompt,\n): Promise<CommandApprovalDecision> {\n // An MCP tool that sends or changes something outside asks the same way as a risky command.\n const tool = approval.tool\n prompt.write(tool ? ' [tool approval required]' : ' [shell command approval required]')\n if (tool) prompt.write(` tool: ${terminalSafe(tool)}`)\n prompt.write(tool ? ' call:' : ' command:')\n for (const line of approval.command.split('\\n')) prompt.write(` ${terminalSafe(line)}`)\n prompt.write(' risks:')\n for (const risk of approval.risks) {\n prompt.write(` - ${terminalSafe(risk.code)}: ${terminalSafe(risk.message)}`)\n }\n try {\n const answer = (\n await prompt.question(\n tool ? ' Allow this call once? [y/N] ' : ' Allow this command once? [y/N] ',\n )\n )\n .trim()\n .toLowerCase()\n return answer === 'y' || answer === 'yes' ? 'allow' : 'deny'\n } catch {\n prompt.write(' [approval input unavailable; denying]')\n return 'deny'\n }\n}\n\n/** Post one decision for a pending approval; without a prompt it is denied at once. */\nexport async function respondToCommandApproval(\n client: { post(path: string, body?: unknown): Promise<unknown> },\n approval: CommandApproval,\n prompt?: CommandApprovalPrompt,\n): Promise<CommandApprovalDecision> {\n const decision = prompt ? await promptForCommandApproval(approval, prompt) : 'deny'\n try {\n await client.post(apiPath('shell-approvals', approval.id), { decision })\n } catch (error) {\n // Decided meanwhile in the web UI or Telegram, or timed out: the turn goes on, and its next\n // frame says how the command was decided.\n if ((error as { status?: number }).status !== 404) throw error\n console.log(` [this ${approval.tool ? 'call' : 'command'} was already decided elsewhere]`)\n }\n return decision\n}\n\nconst APPROVAL_OUTCOMES: Partial<Record<CommandApproval['status'], string>> = {\n allowed: 'allowed',\n denied: 'denied',\n auto_denied: 'auto-denied: non-interactive turn',\n expired: 'approval expired',\n cancelled: 'approval cancelled',\n}\n\n/** How a decided approval is printed: `shell command denied`, `tool call allowed`. */\nfunction approvalOutcome(approval: CommandApproval): string | undefined {\n const outcome = APPROVAL_OUTCOMES[approval.status]\n return outcome && `${approval.tool ? 'tool call' : 'shell command'} ${outcome}`\n}\n\nfunction closeDeltaLine(state: PrintState): void {\n if (!state.inDeltaStream) return\n process.stdout.write('\\n')\n state.inDeltaStream = false\n}\n\n/** Print one chat event. Tool output is shown terminal-safe: it may carry escape sequences. */\nexport function printEvent(e: SessionEvent, state: PrintState): void {\n switch (e.type) {\n case 'assistant_delta':\n process.stdout.write(e.delta)\n state.inDeltaStream = true\n break\n case 'assistant_message':\n // Streamed deltas already printed the text.\n if (state.inDeltaStream) closeDeltaLine(state)\n else console.log(e.text)\n break\n case 'tool_call':\n closeDeltaLine(state)\n console.log(` [tool: ${e.name} ${e.arguments}]`)\n break\n case 'tool_progress': {\n closeDeltaLine(state)\n const { complete, fresh } = unprintedProgress(state.progress.get(e.id) ?? '', e.output)\n state.progress.set(e.id, complete)\n for (const line of fresh.split('\\n').slice(0, -1)) {\n console.log(` | ${terminalSafe(line, true)}`)\n }\n break\n }\n case 'tool_result':\n state.progress.delete(e.id)\n console.log(` [result: ${terminalSafe(e.result.split('\\n')[0]?.slice(0, 100) ?? '', true)}]`)\n break\n case 'tool_error':\n state.progress.delete(e.id)\n console.log(` [tool error: ${e.name} — ${terminalSafe(e.error, true)}]`)\n break\n case 'error':\n closeDeltaLine(state)\n console.log(` [error: ${e.error}]`)\n break\n case 'compaction':\n closeDeltaLine(state)\n console.log(\n e.state === 'running'\n ? ' [summarizing older messages to make room…]'\n : e.state === 'done'\n ? ' [older messages summarized]'\n : ` [could not summarize older messages: ${terminalSafe(e.error ?? '', true)}]`,\n )\n break\n }\n}\n\n/** Save a file the Agent delivered into the current directory, never over an existing file. */\nasync function saveDeliveredFile(\n client: BazilionClient,\n file: { name: string; mimeType: string; result: { resultId: string } },\n): Promise<void> {\n const out = basename(file.name).replace(/[^\\w.-]/g, '_') || 'file'\n try {\n const bytes = await client.binary(apiPath('results', file.result.resultId, 'download'))\n writeFileSync(out, bytes, { flag: 'wx' })\n console.log(` [file received: saved to ./${out} (${file.mimeType})]`)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n console.log(\n ` [file not written: ./${out} already exists; saved as result ${file.result.resultId} (bazilion result download)]`,\n )\n }\n}\n\ninterface TurnPrompts {\n approval?: CommandApprovalPrompt\n question?: QuestionPrompt\n}\n\nfunction terminalPrompts(rl: Interface): TurnPrompts {\n const write = (line: string) => console.log(line)\n return {\n approval: { question: (text) => rl.question(text), write },\n question: { question: (text, signal) => rl.question(text, { signal }), write },\n }\n}\n\n/** Run one turn and print it as it streams, answering approvals and questions on the way. */\nasync function streamTurn(\n client: BazilionClient,\n agentId: string,\n request: ChatRequest,\n prompts: TurnPrompts = {},\n): Promise<void> {\n const state: PrintState = { inDeltaStream: false, progress: new Map() }\n const answeredApprovals = new Set<string>()\n const askedQuestions = new Set<string>()\n // Only a turn started with a question prompt is offered ask_user.\n const body: ChatRequest = prompts.question ? { ...request, questionMode: 'tty' } : request\n for await (const frame of client.stream<ChatFrame>(\n 'POST',\n apiPath('agents', agentId, 'chat'),\n body,\n )) {\n if (frame.kind === 'fatal') {\n closeDeltaLine(state)\n throw new Error(frame.error)\n }\n if (frame.kind !== 'event') continue\n const event = frame.event\n if (event.type === 'command_approval') {\n closeDeltaLine(state)\n const approval = event.approval\n if (approval.status !== 'pending') {\n const outcome = approvalOutcome(approval)\n if (outcome) console.log(` [${outcome}]`)\n } else if (!answeredApprovals.has(approval.id)) {\n answeredApprovals.add(approval.id)\n await respondToCommandApproval(client, approval, prompts.approval)\n }\n } else if (event.type === 'agent_question') {\n closeDeltaLine(state)\n const item = event.question\n if (!prompts.question || item.agentId !== agentId || askedQuestions.has(item.id)) continue\n askedQuestions.add(item.id)\n const answer = await promptForQuestion(item, prompts.question)\n if (!answer) continue\n await client\n .questions(agentId)\n .answer(item.id, answer)\n .catch((error: unknown) => {\n console.error(\n `Answer not accepted: ${error instanceof Error ? error.message : String(error)}`,\n )\n })\n } else if (event.type === 'file') {\n closeDeltaLine(state)\n await saveDeliveredFile(client, event)\n } else if (event.type !== 'user_message') {\n printEvent(event, state)\n // A turn that failed or was cancelled exits non-zero, so a script can tell it apart.\n if (event.type === 'error') process.exitCode = 1\n }\n }\n}\n\nexport const chatCommand = defineCommand({\n meta: {\n name: 'chat',\n description: 'Send one message to an agent, or one per line of piped input',\n },\n args: {\n id: agentArg,\n message: { type: 'string', description: 'Send a single message and exit (one-shot mode)' },\n image: {\n type: 'string',\n description:\n 'Attach an image file (png/jpg/gif/webp; repeat the flag for more). One-shot mode.',\n },\n file: {\n type: 'string',\n description:\n 'Attach any file — the agent gets a path reference (repeat the flag for more). One-shot mode.',\n },\n },\n async run({ args, rawArgs }) {\n const client = createClient()\n const resolved = await client.get<ResolvedAgent>(apiPath('agents', args.id))\n const mode = bashApprovalModeForTty(stdin.isTTY, stdout.isTTY)\n const attachments = loadAttachments(rawArgs)\n\n if (args.message || attachments.length > 0) {\n // A terminal answers shell approvals and questions while the turn streams.\n const rl = mode === 'interactive' ? createInterface({ input: stdin, output: stdout }) : null\n try {\n await streamTurn(\n client,\n resolved.agent.id,\n buildChatRequest(args.message ?? '', attachments, mode),\n rl ? terminalPrompts(rl) : {},\n )\n } finally {\n rl?.close()\n }\n return\n }\n\n // Without --message, each line of piped input is one turn; nobody can answer an approval.\n if (mode === 'interactive') {\n throw new Error(\n 'pass --message \"...\" to send one message; for a conversation, use the web UI',\n )\n }\n console.log(`chatting with ${resolved.agent.name} (${resolved.model})`)\n console.log('(type /exit to quit; input is piped, commands run with auto_deny)')\n const rl = createInterface({ input: stdin, output: stdout })\n let inputEnded = false\n rl.once('close', () => {\n inputEnded = true\n })\n try {\n rl.setPrompt('> ')\n rl.prompt()\n for await (const line of rl) {\n const message = line.trim()\n if (message === '/exit' || message === '/quit') break\n if (message) {\n try {\n await streamTurn(client, resolved.agent.id, buildChatRequest(message, undefined, mode))\n } catch (err) {\n printError(err)\n }\n }\n // Piped input usually ends during the first turn; its remaining lines are still read.\n if (!inputEnded) rl.prompt()\n }\n } finally {\n rl.close()\n }\n },\n})\n","import type { AgentQuestion, AgentQuestionAnswer } from '@bazilion/api-types'\nimport { terminalSafe } from './command-helpers.ts'\n\nexport interface QuestionPrompt {\n question(text: string, signal: AbortSignal): Promise<string>\n write(text: string): void\n}\nfunction hasAnswerControl(text: string): boolean {\n return Array.from(text).some((character) => {\n const code = character.charCodeAt(0)\n return (code < 32 && ![9, 10, 13].includes(code)) || (code >= 127 && code <= 159)\n })\n}\n/** The model-written prompt and choices as terminal lines, with control characters escaped. */\nexport function questionLines(item: AgentQuestion): string[] {\n const lines = terminalSafe(item.question.prompt).split('\\n')\n item.question.choices.forEach((choice, index) => {\n const recommended = index === item.question.recommendedIndex ? ' (recommended)' : ''\n lines.push(`${index + 1}. ${terminalSafe(choice.label)}${recommended}`)\n if (choice.description) lines.push(` ${terminalSafe(choice.description)}`)\n })\n return lines\n}\n/** Uses the chat's sole readline owner. Expiry/EOF never becomes an implicit answer. */\nexport async function promptForQuestion(\n item: AgentQuestion,\n prompt: QuestionPrompt,\n): Promise<AgentQuestionAnswer | null> {\n if (item.expiresAt <= Date.now()) return null\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), Math.max(1, item.expiresAt - Date.now()))\n timer.unref()\n try {\n prompt.write(`Question ${item.id}`)\n for (const line of questionLines(item)) prompt.write(line)\n prompt.write('Choose a number, o for Other, or s to Skip.')\n while (!controller.signal.aborted) {\n const value = (await prompt.question('Answer: ', controller.signal)).trim()\n if (controller.signal.aborted) return null\n if (value.toLowerCase() === 's') return { kind: 'skip' }\n if (/^[1-4]$/.test(value) && Number(value) <= item.question.choices.length)\n return { kind: 'choice', index: Number(value) - 1 }\n if (value.toLowerCase() === 'o') {\n const text = await prompt.question('Your answer: ', controller.signal)\n if (controller.signal.aborted) return null\n if (text.trim() && text.length <= 4096 && !hasAnswerControl(text))\n return { kind: 'text', text }\n prompt.write('Enter 1–4096 characters without control characters.')\n } else prompt.write('Choose an explicit number, o, or s; no answer is selected by default.')\n }\n return null\n } catch {\n prompt.write('Question prompt closed or expired. No answer was submitted.')\n return null\n } finally {\n clearTimeout(timer)\n }\n}\n","import type {\n ChatCompactRequest,\n ChatCompactResponse,\n ChatContextResponse,\n ContextUse,\n TruncateChatRequest,\n TruncateChatResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, confirm, printJson } from '../command-helpers.ts'\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`\n return `${(n / (1024 * 1024)).toFixed(2)} MiB`\n}\n\nfunction estimateTokens(chars: number): number {\n return Math.ceil(Math.max(0, chars) / 4)\n}\n\nconst chatTrimCmd = defineCommand({\n meta: {\n name: 'chat-trim',\n description: \"Keep the first N messages of an agent's chat history; drop the rest\",\n },\n args: {\n id: agentArg,\n keep: { type: 'string', required: true, description: 'Number of leading messages to keep' },\n },\n async run({ args }) {\n const keepCount = Number(args.keep)\n if (!Number.isInteger(keepCount) || keepCount < 0) {\n throw new Error('--keep must be a non-negative integer')\n }\n const body: TruncateChatRequest = { keepCount }\n const res = await createClient().post<TruncateChatResponse>(\n apiPath('agents', args.id, 'chat', 'truncate'),\n body,\n )\n console.log(\n `trimmed: ${res.before} → ${res.after} messages (${res.before - res.after} dropped)`,\n )\n },\n})\n\n/** How full the model's window is, as the conversation bar's meter says it. */\nexport function windowLine({ tokens, window }: ContextUse): string {\n const size = window === null ? 'unknown' : window.toLocaleString()\n if (tokens === null) {\n return `${size} tokens; this conversation's size shows after the next reply`\n }\n const used = window\n ? `${tokens.toLocaleString()} of ${size} tokens used (${Math.round((tokens / window) * 100)}%)`\n : `${tokens.toLocaleString()} tokens used`\n return `${used}; older messages are summarized near the end`\n}\n\nconst chatContextCmd = defineCommand({\n meta: {\n name: 'chat-context',\n description: \"Break down what consumes the agent's context window\",\n },\n args: {\n id: agentArg,\n detail: {\n type: 'boolean',\n description: 'Include every tool/skill entry instead of the top 30',\n },\n json: { type: 'boolean', description: 'Emit raw JSON instead of a human report' },\n },\n async run({ args }) {\n const query = args.detail || args.json ? '?detail=1' : ''\n const ctx = await createClient().get<ChatContextResponse>(\n `${apiPath('agents', args.id, 'chat', 'context')}${query}`,\n )\n if (args.json) return printJson(ctx)\n\n const fmt = (chars: number, tokens: number): string =>\n `${chars.toLocaleString()} chars (~${tokens.toLocaleString()} tok)`\n const { systemPrompt, tools, skills, team, history } = ctx\n\n console.log(`🧠 context for ${ctx.agentId}`)\n console.log(`model: ${ctx.model}`)\n console.log(`window: ${windowLine(ctx.window)}`)\n console.log('')\n console.log('## system prompt')\n console.log(` total: ${fmt(systemPrompt.chars, systemPrompt.tokens)}`)\n if (systemPrompt.files.length > 0) {\n console.log(' profile files:')\n for (const f of systemPrompt.files) console.log(` - ${f.name}: ${fmt(f.chars, f.tokens)}`)\n }\n if (systemPrompt.skillsListChars > 0) {\n console.log(` skills line: ${systemPrompt.skillsListChars.toLocaleString()} chars`)\n }\n if (systemPrompt.teamListChars > 0) {\n console.log(` team block: ${systemPrompt.teamListChars.toLocaleString()} chars`)\n }\n if (systemPrompt.userMdChars > 0) {\n console.log(` user_md block: ${systemPrompt.userMdChars.toLocaleString()} chars`)\n }\n console.log(` memory hint: ${systemPrompt.memoryHintChars.toLocaleString()} chars`)\n console.log('')\n console.log('## tools')\n console.log(` count: ${tools.count}`)\n console.log(\n ` schemas (JSON): ${tools.schemaChars.toLocaleString()} chars (~${estimateTokens(tools.schemaChars).toLocaleString()} tok)`,\n )\n console.log(` list text: ${tools.listChars.toLocaleString()} chars`)\n if (tools.entries.length > 0) {\n console.log(' top tools by schema size:')\n for (const t of tools.entries) {\n const params = t.paramCount != null ? ` (${t.paramCount} params)` : ''\n console.log(` - ${t.name}: ${t.schemaChars.toLocaleString()} chars${params}`)\n }\n }\n console.log('')\n if (skills.count > 0) {\n console.log('## skills')\n console.log(` count: ${skills.count}`)\n for (const s of skills.entries) {\n console.log(` - ${s.name}: ${s.blockChars.toLocaleString()} chars`)\n }\n console.log('')\n }\n console.log('## team')\n console.log(` - ${team.id} (${team.name}): ${team.path}`)\n if (team.userMdChars > 0) console.log(` user_md: ${team.userMdChars.toLocaleString()} chars`)\n console.log('')\n console.log('## history')\n console.log(` messages: ${history.messageEntries}`)\n console.log(` compactions: ${history.compactionEntries}`)\n console.log(` total: ${fmt(history.chars, history.tokensEstimate)}`)\n console.log(` bytes: ${formatBytes(history.bytes)}`)\n console.log('')\n console.log(`TOTAL: ${fmt(ctx.totals.chars, ctx.totals.tokens)}`)\n },\n})\n\nconst chatCompactCmd = defineCommand({\n meta: {\n name: 'chat-compact',\n description: \"Summarize the head of an agent's chat log, preserving the tail verbatim\",\n },\n args: {\n id: agentArg,\n instructions: {\n type: 'string',\n description: 'Optional extra guidance prepended to the summarizer prompt',\n },\n force: { type: 'boolean', description: 'Skip the y/N prompt' },\n },\n async run({ args }) {\n const body: ChatCompactRequest = args.instructions\n ? { customInstructions: args.instructions }\n : {}\n const question = `compact chat history for ${args.id}? head turns become a summary; tail is preserved.`\n if (!args.force && !(await confirm(question))) return console.log('aborted')\n const res = await createClient().post<ChatCompactResponse>(\n apiPath('agents', args.id, 'chat', 'compact'),\n body,\n )\n console.log(\n `compacted: ${res.before} → ${res.after} entries (${res.summarized} summarized, ${res.keptTail} tail kept verbatim)`,\n )\n console.log(\n `tokens: ~${res.tokensBefore.toLocaleString()} → ~${res.tokensAfter.toLocaleString()}`,\n )\n console.log('')\n console.log('summary:')\n console.log(res.summary)\n },\n})\n\nexport const contextCommands = {\n 'chat-trim': chatTrimCmd,\n 'chat-context': chatContextCmd,\n 'chat-compact': chatCompactCmd,\n}\n","import type {\n Agent,\n AgentLessonProposal,\n AgentLessonProposalResponse,\n AgentLessonStatus,\n AgentReviewConfig,\n EnqueueAgentReviewResponse,\n ListAgentLessonProposalsResponse,\n ListAgentReviewsResponse,\n UpdateAgentReviewConfigRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst proposalArg = positional('Proposal id or prefix')\n\nconst reviewConfigCmd = defineCommand({\n meta: { name: 'review-config', description: 'Inspect or configure reviewed learning' },\n args: {\n id: agentArg,\n enable: { type: 'boolean', description: 'Enable periodic reviews' },\n disable: { type: 'boolean', description: 'Disable periodic reviews' },\n every: { type: 'string', description: 'Successful user turns between reviews (1-100)' },\n model: { type: 'string', description: \"Review model, or 'agent' to use the Agent model\" },\n reasoning: { type: 'string', description: 'Review reasoning level' },\n },\n async run({ args }) {\n if (args.enable && args.disable) throw new Error('choose either --enable or --disable')\n const body: UpdateAgentReviewConfigRequest = {}\n if (args.enable || args.disable) body.enabled = Boolean(args.enable)\n if (args.every !== undefined) {\n const value = Number(args.every)\n if (!Number.isInteger(value) || value < 1 || value > 100) {\n throw new Error('--every must be an integer from 1 to 100')\n }\n body.everyNTurns = value\n }\n if (args.model !== undefined) body.model = args.model === 'agent' ? null : args.model\n if (args.reasoning !== undefined) {\n body.reasoningLevel = args.reasoning as UpdateAgentReviewConfigRequest['reasoningLevel']\n }\n const client = createClient()\n const path = apiPath('agents', args.id, 'review-config')\n const config =\n Object.keys(body).length > 0\n ? await client.patch<AgentReviewConfig>(path, body)\n : await client.get<AgentReviewConfig>(path)\n console.log(`review: ${config.enabled ? 'enabled' : 'disabled'}`)\n console.log(`cadence: every ${config.everyNTurns} successful user turns`)\n console.log(`model: ${config.model ?? 'agent model'}`)\n console.log(`reasoning: ${config.reasoningLevel}`)\n console.log(`turns since last review: ${config.turnsSinceLast}`)\n },\n})\n\nconst reviewCmd = defineCommand({\n meta: { name: 'review', description: 'Enqueue a reviewed-learning pass' },\n args: { id: agentArg },\n async run({ args }) {\n const response = await createClient().post<EnqueueAgentReviewResponse>(\n apiPath('agents', args.id, 'reviews'),\n )\n console.log(`review ${response.review.id} ${response.review.status}`)\n },\n})\n\nconst reviewsCmd = defineCommand({\n meta: { name: 'reviews', description: 'List reviewed-learning history' },\n args: {\n id: agentArg,\n status: { type: 'string', description: 'pending|running|completed|failed|cancelled' },\n },\n async run({ args }) {\n const { reviews } = await createClient().get<ListAgentReviewsResponse>(\n apiPath('agents', args.id, 'reviews'),\n )\n printRows(\n reviews\n .filter((review) => !args.status || review.status === args.status)\n .map((review) => [\n review.id,\n review.status,\n review.trigger,\n `${review.proposalCount} proposal(s)`,\n new Date(review.createdAt).toISOString(),\n ]),\n '(no reviews)',\n )\n },\n})\n\nconst lessonsCmd = defineCommand({\n meta: { name: 'lessons', description: 'List reviewed lesson proposals' },\n args: {\n id: agentArg,\n status: { type: 'string', description: 'pending|approved|rejected|revoked' },\n },\n async run({ args }) {\n const status = args.status as AgentLessonStatus | undefined\n const query = status ? `?status=${encodeURIComponent(status)}` : ''\n const { proposals } = await createClient().get<ListAgentLessonProposalsResponse>(\n `${apiPath('agents', args.id, 'lesson-proposals')}${query}`,\n )\n printRows(\n proposals.map((proposal) => [proposal.id, proposal.status, proposal.scope, proposal.text]),\n '(no lesson proposals)',\n )\n },\n})\n\n/** A proposal is addressed by its id alone, so find the Agent it belongs to. */\nasync function locateProposal(\n id: string,\n): Promise<{ agent: Agent; proposal: AgentLessonProposal }> {\n const client = createClient()\n for (const agent of await client.get<Agent[]>('/api/agents?includeArchived=true')) {\n const { proposals } = await client.get<ListAgentLessonProposalsResponse>(\n apiPath('agents', agent.id, 'lesson-proposals'),\n )\n const proposal = proposals.find((item) => item.id === id || item.id.startsWith(id))\n if (proposal) return { agent, proposal }\n }\n throw new Error(`lesson proposal not found: ${id}`)\n}\n\nfunction lessonDecisionCmd(decision: 'approve' | 'reject' | 'revoke') {\n return defineCommand({\n meta: { name: decision, description: `${decision} a reviewed lesson proposal` },\n args: {\n id: proposalArg,\n yes: { type: 'boolean', description: `Confirm ${decision}` },\n },\n async run({ args }) {\n if (!args.yes) throw new Error(`${decision} requires --yes`)\n const { agent, proposal } = await locateProposal(args.id)\n const response = await createClient().post<AgentLessonProposalResponse>(\n apiPath('agents', agent.id, 'lesson-proposals', proposal.id, decision),\n { version: proposal.version },\n )\n console.log(`${response.proposal.status} ${response.proposal.id}`)\n },\n })\n}\n\nconst lessonEditCmd = defineCommand({\n meta: { name: 'edit', description: 'Edit a pending reviewed lesson proposal' },\n args: {\n id: proposalArg,\n text: { type: 'string', description: 'Replacement lesson text' },\n scope: { type: 'string', description: 'private|shared' },\n },\n async run({ args }) {\n if (args.text === undefined && args.scope === undefined) {\n throw new Error('lesson edit requires --text or --scope')\n }\n const { agent, proposal } = await locateProposal(args.id)\n const response = await createClient().patch<AgentLessonProposalResponse>(\n apiPath('agents', agent.id, 'lesson-proposals', proposal.id),\n { version: proposal.version, text: args.text, scope: args.scope },\n )\n console.log(`updated ${response.proposal.id} v${response.proposal.version}`)\n },\n})\n\nconst lessonCmd = defineCommand({\n meta: { name: 'lesson', description: 'Edit or decide a reviewed lesson proposal' },\n subCommands: {\n edit: lessonEditCmd,\n approve: lessonDecisionCmd('approve'),\n reject: lessonDecisionCmd('reject'),\n revoke: lessonDecisionCmd('revoke'),\n },\n})\n\nexport const learningCommands = {\n 'review-config': reviewConfigCmd,\n review: reviewCmd,\n reviews: reviewsCmd,\n lessons: lessonsCmd,\n lesson: lessonCmd,\n}\n","import type { AttachSkillRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional } from '../command-helpers.ts'\nimport { explainScanBlock } from '../errors.ts'\n\nconst skillArg = positional('Skill name')\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Attach a skill to an agent' },\n args: {\n agent: agentArg,\n skill: skillArg,\n 'allow-warnings': {\n type: 'boolean',\n description: 'Attach even when the static skill scan reports findings',\n },\n },\n async run({ args }) {\n const body: AttachSkillRequest = { skill: args.skill, allowFindings: args['allow-warnings'] }\n await createClient()\n .post(apiPath('agents', args.agent, 'skills'), body)\n .catch(explainScanBlock('--allow-warnings'))\n console.log(`attached skill ${args.skill} to ${args.agent}`)\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Detach a skill from an agent' },\n args: { agent: agentArg, skill: skillArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.agent, 'skills', args.skill))\n console.log(`detached skill ${args.skill} from ${args.agent}`)\n },\n})\n\nexport const agentSkillCommand = defineCommand({\n meta: { name: 'skill', description: 'Attach/detach skills on an agent' },\n subCommands: { add: addCmd, rm: rmCmd },\n})\n","import type { AttentionItem, AttentionListResponse, AttentionSummary } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson } from '../command-helpers.ts'\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List operator attention items' },\n args: {\n state: { type: 'string', default: 'open', description: 'open, acknowledged or all' },\n kind: { type: 'string', description: 'Only items of this kind' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ state: args.state, limit: '200' })\n if (args.kind) query.set('kind', args.kind)\n const body = await createClient().get<AttentionListResponse>(`/api/attention?${query}`)\n if (args.json) return printJson(body)\n if (!body.items.length) console.log('(nothing needs attention)')\n else\n for (const line of columnize([\n ['severity', 'kind', 'context', 'when', 'key'],\n ...body.items.map((item) => [\n item.severity,\n item.kind,\n context(item),\n new Date(item.occurredAt).toISOString(),\n item.key,\n ]),\n ]))\n console.log(line)\n for (const source of body.degraded)\n console.error(`warning: ${source.kind} unavailable: ${source.error}`)\n },\n})\n\nconst summary = defineCommand({\n meta: { name: 'summary', description: 'Summarize open attention items' },\n args: { json: jsonFlag },\n async run({ args }) {\n const body = await createClient().get<AttentionSummary>('/api/attention/summary')\n if (args.json) printJson(body)\n else\n console.log(\n `${body.openTotal} open · ${body.bySeverity.action_required} action required · ${body.bySeverity.error} errors · ${body.bySeverity.warning} warnings`,\n )\n },\n})\n\nfunction mutation(name: 'acknowledge' | 'unacknowledge') {\n return defineCommand({\n meta: { name, description: `${name} one informational attention item` },\n args: {\n key: positional('Attention item key'),\n yes: { type: 'boolean', description: 'Required confirmation' },\n json: jsonFlag,\n },\n async run({ args }) {\n if (!args.yes) throw new Error(`refusing mutation: pass --yes to ${name}`)\n const path = apiPath(\n 'attention',\n args.key,\n name === 'acknowledge' ? 'acknowledge' : 'acknowledgement',\n )\n const body =\n name === 'acknowledge'\n ? await createClient().post<{ item: AttentionItem }>(path)\n : await createClient().del<{ item: AttentionItem }>(path)\n if (args.json) printJson(body)\n else console.log(`${body.item.key}: ${body.item.acknowledgedAt ? 'acknowledged' : 'open'}`)\n },\n })\n}\n\nconst acknowledgeAll = defineCommand({\n meta: { name: 'acknowledge-all', description: 'Acknowledge all open informational items' },\n args: { yes: { type: 'boolean', description: 'Required confirmation' }, json: jsonFlag },\n async run({ args }) {\n if (!args.yes) throw new Error('refusing mutation: pass --yes to acknowledge-all')\n const body = await createClient().post<{ acknowledged: number }>(\n '/api/attention/acknowledge-all',\n )\n if (args.json) printJson(body)\n else console.log(`acknowledged ${body.acknowledged} informational item(s)`)\n },\n})\n\nfunction context(item: AttentionItem): string {\n return [item.agentName, item.teamName].filter(Boolean).join(' / ') || 'system'\n}\n\nexport const attentionCommand = defineCommand({\n meta: { name: 'attention', description: 'Inspect the operator attention center' },\n subCommands: {\n list,\n summary,\n acknowledge: mutation('acknowledge'),\n unacknowledge: mutation('unacknowledge'),\n 'acknowledge-all': acknowledgeAll,\n },\n})\n","// Import pi-ai's provider directly so the CLI bundle stays slim. The provider\n// owns its OAuth interaction; Bazilion persists the returned credential in the daemon.\nimport type { OpenAICodexStatus } from '@bazilion/api-types'\nimport type { AuthPrompt } from '@earendil-works/pi-ai'\nimport { openaiCodexProvider } from '@earendil-works/pi-ai/providers/openai-codex'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\n\ntype OpenAICodexLoginMethod = 'browser' | 'device_code'\n\nconst CLI_OPENAI_LOGIN_TIMEOUT_MS = 10 * 60_000\n\ninterface PromptInput {\n once(event: 'data', listener: (chunk: string | Buffer) => void): unknown\n once(event: 'error', listener: (error: Error) => void): unknown\n off(event: 'data', listener: (chunk: string | Buffer) => void): unknown\n off(event: 'error', listener: (error: Error) => void): unknown\n pause(): unknown\n}\n\n/**\n * Answer Pi's OpenAI login prompts in a terminal: pick the login method, or read one line (a\n * pasted redirect URL). The paste prompt ends when Pi withdraws it (the browser callback arrived\n * first) or when `login` ends; stdin is then released so it cannot keep the CLI running. The login\n * signal matters when port 1455 is taken: Pi then has no callback server and waits on this prompt\n * alone. A stdin error only stops the reading, since the browser callback may still arrive.\n */\nexport function answerCliOpenAIPrompt(\n prompt: AuthPrompt,\n loginMethod: OpenAICodexLoginMethod,\n login: AbortSignal,\n input: PromptInput = process.stdin,\n output: { write(text: string): unknown } = process.stdout,\n): Promise<string> {\n if (prompt.type === 'select') {\n return prompt.options.some((option) => option.id === loginMethod)\n ? Promise.resolve(loginMethod)\n : Promise.reject(\n new Error(\n `Pi openai-codex provider does not support ${loginMethod === 'browser' ? 'browser' : 'device-code'} login`,\n ),\n )\n }\n output.write(`${prompt.message}: `)\n const ended = prompt.signal ? AbortSignal.any([prompt.signal, login]) : login\n return new Promise<string>((resolve, reject) => {\n const stopReading = () => {\n input.off('data', onData)\n input.off('error', stopReading)\n input.pause()\n }\n const onData = (data: string | Buffer) => {\n stopReading()\n ended.removeEventListener('abort', onEnded)\n resolve(String(data).trim())\n }\n const onEnded = () => {\n stopReading()\n reject(new Error('OAuth prompt withdrawn'))\n }\n if (ended.aborted) return onEnded()\n input.once('data', onData)\n input.once('error', stopReading)\n ended.addEventListener('abort', onEnded, { once: true })\n })\n}\n\nfunction formatExpiry(ms: number | null): string {\n if (!ms) return '(unknown)'\n const d = new Date(ms)\n return d.toISOString().replace(/\\.\\d+Z$/, 'Z')\n}\n\nconst openaiLoginCmd = defineCommand({\n meta: {\n name: 'login',\n description: 'Connect your ChatGPT account via OAuth',\n },\n args: {\n 'device-code': {\n type: 'boolean',\n description: 'Use headless device-code login instead of the localhost browser callback',\n },\n },\n async run({ args }) {\n const client = createClient()\n // The loopback callback at localhost:1455 must be on the CLI user's\n // machine, so we run pi-ai's flow client-side (not via a server POST).\n // After it completes we ship the credentials to the daemon so they land\n // in the daemon-owned `secrets` table (encrypted with the bootstrap token).\n const loginMethod: OpenAICodexLoginMethod = args['device-code'] ? 'device_code' : 'browser'\n if (loginMethod === 'device_code') {\n console.log('starting OpenAI device-code sign-in...')\n } else {\n console.log('opening your browser for OpenAI sign-in...')\n console.log(\"(if it doesn't open automatically, paste the URL shown below)\")\n }\n const oauth = openaiCodexProvider().auth.oauth\n if (!oauth) throw new Error('Pi openai-codex provider does not expose OAuth')\n // A ref'd timer (unlike AbortSignal.timeout) keeps the CLI alive for the whole login window,\n // so a login nothing can finish ends with the timeout error instead of a silent exit.\n const login = new AbortController()\n const timer = setTimeout(() => login.abort(), CLI_OPENAI_LOGIN_TIMEOUT_MS)\n const creds = await oauth\n .login({\n signal: login.signal,\n notify: (event) => {\n if (event.type === 'auth_url') {\n console.log('')\n console.log(` → ${event.url}`)\n console.log('')\n } else if (event.type === 'progress' || event.type === 'info') {\n console.log(` ${event.message}`)\n } else if (event.type === 'device_code') {\n console.log(` open ${event.verificationUri} and enter ${event.userCode}`)\n }\n },\n prompt: (prompt) => answerCliOpenAIPrompt(prompt, loginMethod, login.signal),\n })\n .catch((error: unknown) => {\n throw login.signal.aborted\n ? new Error(\n 'OpenAI login timed out after 10 minutes. Try again, or use `bazilion auth openai login --device-code`.',\n )\n : error\n })\n .finally(() => clearTimeout(timer))\n const status = await client.put<OpenAICodexStatus>('/api/auth/openai', {\n refresh: creds.refresh,\n access: creds.access,\n expires: creds.expires,\n })\n console.log('')\n console.log('connected ✓')\n if (status.accountId) console.log(`account: ${status.accountId}`)\n console.log(`access token expires: ${formatExpiry(status.expiresAt)}`)\n console.log('')\n console.log('choose its models and switch it on in one step:')\n console.log(' bazilion provider connect openai-codex')\n console.log('or under Setup, Models in the web UI.')\n },\n})\n\nconst openaiLogoutCmd = defineCommand({\n meta: {\n name: 'logout',\n description: 'Forget the stored ChatGPT OAuth credentials',\n },\n async run() {\n const client = createClient()\n await client.del('/api/auth/openai')\n console.log('disconnected ChatGPT OAuth credentials')\n },\n})\n\nconst openaiStatusCmd = defineCommand({\n meta: {\n name: 'status',\n description: 'Show ChatGPT OAuth connection status',\n },\n async run() {\n const client = createClient()\n const status = await client.get<OpenAICodexStatus>('/api/auth/openai')\n if (!status.connected) {\n console.log('not connected — run `bazilion auth openai login`')\n return\n }\n console.log('connected ✓')\n if (status.accountId) console.log(`account: ${status.accountId}`)\n console.log(`access token expires: ${formatExpiry(status.expiresAt)}`)\n },\n})\n\nconst openaiCmd = defineCommand({\n meta: {\n name: 'openai',\n description: 'Manage ChatGPT (OAuth) authentication',\n },\n subCommands: {\n login: openaiLoginCmd,\n logout: openaiLogoutCmd,\n status: openaiStatusCmd,\n },\n})\n\nexport const authCommand = defineCommand({\n meta: {\n name: 'auth',\n description: 'OAuth-based provider authentication (ChatGPT account, etc.)',\n },\n subCommands: {\n openai: openaiCmd,\n },\n})\n","import { createHash } from 'node:crypto'\nimport {\n chmodSync,\n closeSync,\n copyFileSync,\n createReadStream,\n createWriteStream,\n existsSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n readdirSync,\n readFileSync,\n readSync,\n renameSync,\n rmSync,\n} from 'node:fs'\nimport { dirname, isAbsolute, join, parse, posix, relative, resolve, sep } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport { Decrypter, Encrypter } from 'age-encryption'\nimport { defineCommand } from 'citty'\nimport { extract, list } from 'tar'\nimport { type SchemaObject, schemaMatches } from '../../../daemon/src/core/db/schema.ts'\nimport { assertDaemonStopped } from '../../../daemon/src/lib/daemon-liveness.ts'\nimport { readAuthFile } from '../auth-file.ts'\nimport { loadClientConfig } from '../client.ts'\nimport { canonicalPath, resolveCliPaths } from '../paths.ts'\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Download a backup of the Bazilion home' },\n args: {\n output: {\n type: 'positional',\n required: false,\n description: 'Output file (default: bazilion-backup-<date>.tar.gz, plus .age when encrypted)',\n },\n recipient: { type: 'string', description: 'Encrypt the backup to this age recipient (age1…)' },\n },\n async run({ args }) {\n const date = new Date().toISOString().slice(0, 10)\n const suffix = args.recipient ? '.tar.gz.age' : '.tar.gz'\n const output = canonicalPath(args.output ?? `bazilion-backup-${date}${suffix}`)\n if (existsSync(output)) throw new Error(`refusing to overwrite ${output}`)\n const home = resolveCliPaths().home\n const fromHome = relative(home, output)\n if (fromHome !== '..' && !fromHome.startsWith(`..${sep}`) && !isAbsolute(fromHome)) {\n throw new Error(`write the backup outside the Bazilion home (${home})`)\n }\n // Set up first, so a mistyped recipient fails before the download starts.\n const encrypter = new Encrypter()\n if (args.recipient) encrypter.addRecipient(args.recipient)\n else console.warn('warning: this backup is not encrypted and contains every stored credential')\n\n const cfg = loadClientConfig()\n const res = await fetch(`${cfg.serverUrl}/api/backup`, {\n headers: { authorization: `Bearer ${cfg.token}`, origin: cfg.serverUrl },\n })\n if (!res.ok || !res.body) {\n const body = (await res.json().catch(() => ({}))) as { error?: string }\n throw new Error(`backup failed: ${body.error ?? res.statusText}`)\n }\n const partial = `${output}.partial`\n // Created here or not at all: never write into, or follow, a file that is already there.\n const fd = openSync(partial, 'wx', 0o600)\n try {\n const [archive, check] = res.body.tee()\n const written = args.recipient ? await encrypter.encrypt(archive) : archive\n await Promise.all([\n pipeline(Readable.fromWeb(written), createWriteStream(partial, { fd })),\n // A response cut short can still end cleanly: read the archive through to its end.\n pipeline(Readable.fromWeb(check), list({ strict: true })),\n ])\n renameSync(partial, output)\n } finally {\n rmSync(partial, { force: true })\n }\n console.log(`backup written to ${output}`)\n },\n})\n\nconst AGE_HEADER = Buffer.from('age-encryption.org/v1\\n')\n\nfunction isAgeEncrypted(file: string): boolean {\n const header = Buffer.alloc(AGE_HEADER.length)\n const fd = openSync(file, 'r')\n try {\n readSync(fd, header, 0, header.length, 0)\n } finally {\n closeSync(fd)\n }\n return header.equals(AGE_HEADER)\n}\n\nasync function decrypt(file: string, output: string, identityFile: string): Promise<void> {\n const decrypter = new Decrypter()\n const identities = readFileSync(identityFile, 'utf8')\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.startsWith('AGE-SECRET-KEY-'))\n if (identities.length === 0) throw new Error(`no AGE-SECRET-KEY in ${identityFile}`)\n for (const identity of identities) decrypter.addIdentity(identity)\n try {\n const plain = await decrypter.decrypt(\n Readable.toWeb(createReadStream(file)) as ReadableStream<Uint8Array>,\n )\n await pipeline(Readable.fromWeb(plain), createWriteStream(output, { mode: 0o600 }))\n } catch {\n throw new Error('could not decrypt the backup: wrong identity, or the file is damaged')\n }\n}\n\n/**\n * Refuse what restore must not write: paths leaving the home, special files, entries below a\n * symbolic link, and links leaving the home other than a linked Team (`teams/<slug>`, absolute).\n * The rest of the archive, its database included, is trusted: restore only backups you trust.\n */\nasync function checkArchive(file: string): Promise<void> {\n // Collect first: an error thrown while tar is still reading would escape as a crash.\n const raw: Array<{ path: string; type: string; linkpath: string }> = []\n await list({\n file,\n strict: true,\n onReadEntry: (entry) =>\n raw.push({ path: entry.path, type: entry.type, linkpath: entry.linkpath ?? '' }),\n })\n const entries: Array<{ path: string; type: string }> = []\n const links = new Set<string>()\n for (const entry of raw) {\n const segments = entry.path.split('/').filter((segment) => segment && segment !== '.')\n const path = segments.join('/')\n if (entry.path.startsWith('/') || segments.includes('..')) {\n throw new Error(`backup contains an unsafe path: ${entry.path}`)\n }\n if (!['File', 'Directory', 'SymbolicLink'].includes(entry.type)) {\n throw new Error(`backup contains an unsupported ${entry.type} entry: ${path}`)\n }\n if (entry.type === 'SymbolicLink') {\n const resolved = posix.normalize(posix.join(posix.dirname(path), entry.linkpath))\n const leaves = posix.isAbsolute(entry.linkpath)\n ? !/^teams\\/[^/]+$/.test(path)\n : resolved === '..' || resolved.startsWith('../')\n if (leaves) throw new Error(`backup contains a symbolic link leaving the home: ${path}`)\n links.add(path)\n }\n entries.push({ path, type: entry.type })\n }\n for (const { path } of entries) {\n const segments = path.split('/')\n for (let i = 1; i < segments.length; i++) {\n if (links.has(segments.slice(0, i).join('/'))) {\n throw new Error(`backup places ${path} below a symbolic link`)\n }\n }\n }\n for (const required of ['bazilion.db', 'auth.json']) {\n if (!entries.some((entry) => entry.path === required && entry.type === 'File')) {\n throw new Error(`backup is missing ${required}`)\n }\n }\n}\n\n/** The restored home must open on this release: intact, same schema, matching auth.json. */\nfunction checkDatabase(home: string): void {\n const token = readAuthFile(join(home, 'auth.json')).token\n // Opened read-write only so that closing it removes the -wal/-shm files a WAL database makes.\n const db = new DatabaseSync(join(home, 'bazilion.db'))\n try {\n const integrity = db.prepare('PRAGMA integrity_check').get()\n if (integrity?.integrity_check !== 'ok') throw new Error('the database is damaged')\n if (!schemaMatches((query) => db.prepare(query).all() as unknown as SchemaObject[])) {\n throw new Error('the database schema differs from this release; use a backup from it')\n }\n const bootstrap = db\n .prepare(\n \"SELECT 1 FROM web_tokens WHERE token_hash = ? AND kind = 'bootstrap' AND revoked_at IS NULL\",\n )\n .get(createHash('sha256').update(token).digest('hex'))\n if (!bootstrap) throw new Error('auth.json does not match the database')\n } catch (error) {\n throw new Error(`backup database is unusable: ${(error as Error).message}`)\n } finally {\n db.close()\n }\n}\n\n/** Swap the staged home in; the current home stays in place until the new one is. */\nexport function installRestoredHome(staged: string, home: string): void {\n if (!existsSync(home)) {\n renameSync(staged, home)\n return\n }\n const previous = `${home}.pre-restore-${Date.now()}`\n console.log(`moving the current home aside to ${previous}`)\n renameSync(home, previous)\n try {\n renameSync(staged, home)\n } catch (error) {\n renameSync(previous, home)\n throw error\n }\n try {\n rmSync(previous, { recursive: true, force: true })\n } catch {\n console.warn(`warning: could not delete the previous home at ${previous}; remove it by hand`)\n }\n}\n\nconst restoreCmd = defineCommand({\n meta: {\n name: 'restore',\n description: 'Restore a backup into the Bazilion home (stop the daemon first)',\n },\n args: {\n file: { type: 'positional', required: true, description: 'Backup file (.tar.gz or .age)' },\n home: { type: 'string', description: 'Restore into this home instead of BAZILION_HOME' },\n force: { type: 'boolean', description: 'Replace a non-empty home, deleting its current data' },\n identity: { type: 'string', description: 'age identity file of an encrypted backup' },\n },\n async run({ args }) {\n const file = resolve(args.file)\n if (!existsSync(file)) throw new Error(`backup file not found: ${file}`)\n const home = resolveCliPaths(args.home).home\n if (home === parse(home).root) throw new Error('refusing to restore over the filesystem root')\n assertDaemonStopped(home)\n if (existsSync(home) && readdirSync(home).length > 0 && !args.force) {\n throw new Error(`${home} is not empty; pass --force to replace it (its data is deleted)`)\n }\n\n mkdirSync(dirname(home), { recursive: true })\n const staging = mkdtempSync(join(dirname(home), '.bazilion-restore-'))\n try {\n // Check and extract a private copy, so the archive cannot change between the two.\n const archive = join(staging, 'backup.tar.gz')\n if (isAgeEncrypted(file)) {\n if (!args.identity) throw new Error('this backup is encrypted; pass --identity <file>')\n await decrypt(file, archive, args.identity)\n } else {\n copyFileSync(file, archive)\n }\n await checkArchive(archive)\n const staged = join(staging, 'home')\n mkdirSync(staged, { mode: 0o700 })\n // preservePaths keeps a linked Team's absolute target; checkArchive refused unsafe entries.\n await extract({ file: archive, cwd: staged, strict: true, preservePaths: true })\n // Owner-only, whatever modes the archive carried.\n chmodSync(staged, 0o700)\n for (const name of ['auth.json', 'bazilion.db']) chmodSync(join(staged, name), 0o600)\n checkDatabase(staged)\n // Again: a daemon may have started on the home while the archive was checked.\n assertDaemonStopped(home)\n installRestoredHome(staged, home)\n } finally {\n rmSync(staging, { recursive: true, force: true })\n }\n console.log(`restored ${file} to ${home}`)\n console.log('start the daemon with: bazilion serve')\n },\n})\n\nexport const backupCommand = defineCommand({\n meta: { name: 'backup', description: 'Back up and restore the Bazilion home' },\n subCommands: { create: createCmd, restore: restoreCmd },\n})\n","import { readFileSync } from 'node:fs'\nimport { type BazilionDb, inTx, openInMemoryDb } from './client.ts'\n\nexport const INCOMPATIBLE_DATABASE_MESSAGE =\n 'Bazilion cannot start because this home uses an incompatible database schema. ' +\n 'Preserve the entire Bazilion home directory as a filesystem backup first, keeping ' +\n 'bazilion.db and auth.json together. Then perform the reset with ' +\n '`bazilion uninstall --yes` (from the repository root of a source checkout: ' +\n '`pnpm tsx apps/cli/src/index.ts uninstall --yes`) and start Bazilion again. ' +\n 'Use `--all` only if you also want to remove installed skills.'\n\nexport class IncompatibleDatabaseError extends Error {\n constructor() {\n super(INCOMPATIBLE_DATABASE_MESSAGE)\n this.name = 'IncompatibleDatabaseError'\n }\n}\n\nexport type SchemaObject = { type: string; name: string; sql: string }\n/** Runs a query and returns its rows, so daemon and raw node:sqlite handles share the check. */\ntype ReadSchemaObjects = (query: string) => SchemaObject[]\n\nconst SCHEMA_OBJECTS =\n 'SELECT type, name, sql FROM sqlite_schema ' +\n \"WHERE sql IS NOT NULL AND substr(name, 1, 7) <> 'sqlite_' ORDER BY type, name\"\n\n// SQLite stores each CREATE statement's text, comments included. Ignore comments and whitespace so\n// that documentation edits to schema.sql never make an existing home look incompatible.\nfunction fingerprint(read: ReadSchemaObjects): string {\n return read(SCHEMA_OBJECTS)\n .map((object) => {\n const sql = object.sql\n .replace(/--[^\\n]*/g, ' ')\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return `${object.type} ${object.name} ${sql}`\n })\n .join('\\n')\n}\n\nlet schemaSql: string | undefined\nfunction readSchemaSql(): string {\n schemaSql ??= readFileSync(new URL('./schema.sql', import.meta.url), 'utf8')\n return schemaSql\n}\n\nlet canonical: string | undefined\n/** True when the database's schema objects are exactly those `schema.sql` creates. */\nexport function schemaMatches(read: ReadSchemaObjects): boolean {\n if (canonical === undefined) {\n const scratch = openInMemoryDb('')\n try {\n scratch.raw.exec(readSchemaSql())\n canonical = fingerprint((query) => scratch.raw.query<SchemaObject, []>(query).all())\n } finally {\n scratch.close()\n }\n }\n return fingerprint(read) === canonical\n}\n\n/** Create the schema in an empty database; refuse, untouched, a database whose schema differs. */\nexport function initSchema(db: BazilionDb): void {\n const read: ReadSchemaObjects = (query) => db.raw.query<SchemaObject, []>(query).all()\n if (read(SCHEMA_OBJECTS).length === 0) inTx(db, () => db.raw.exec(readSchemaSql()))\n else if (!schemaMatches(read)) throw new IncompatibleDatabaseError()\n}\n","import { dirname } from 'node:path'\nimport { backup, DatabaseSync, type SQLInputValue } from 'node:sqlite'\n\nexport interface QueryStmt<RowType, ParamsType extends unknown[]> {\n get(...params: ParamsType): RowType | null\n all(...params: ParamsType): RowType[]\n run(...params: ParamsType): { changes: number; lastInsertRowid: number | bigint }\n}\n\nexport interface QueryableDatabase {\n query<RowType, ParamsType extends unknown[]>(sql: string): QueryStmt<RowType, ParamsType>\n run(sql: string, params?: unknown[]): { changes: number; lastInsertRowid: number | bigint }\n exec(sql: string): void\n transaction<T>(fn: () => T): () => T\n}\n\nexport interface BazilionDb {\n raw: QueryableDatabase\n /** The Bazilion home, where the database file lives; Agent and Profile directories derive from it. */\n home: string\n /**\n * Copy a transactionally-consistent image of the live database to `path`.\n * SQLite's online-backup API includes committed WAL contents without\n * requiring the daemon to close its connection or checkpoint the WAL.\n */\n backupTo(path: string): Promise<number>\n close(): void\n}\n\nfunction wrap(rawDb: DatabaseSync): QueryableDatabase {\n const cache = new Map<string, ReturnType<DatabaseSync['prepare']>>()\n let transactionDepth = 0\n let savepointSequence = 0\n function getStmt(sql: string) {\n let s = cache.get(sql)\n if (!s) {\n s = rawDb.prepare(sql)\n cache.set(sql, s)\n }\n return s\n }\n\n return {\n query<R, P extends unknown[]>(sql: string): QueryStmt<R, P> {\n const stmt = getStmt(sql)\n return {\n get(...params: P): R | null {\n const result = stmt.get(...(params as SQLInputValue[]))\n return (result as R | undefined) ?? null\n },\n all(...params: P): R[] {\n return stmt.all(...(params as SQLInputValue[])) as R[]\n },\n run(...params: P) {\n return stmt.run(...(params as SQLInputValue[])) as {\n changes: number\n lastInsertRowid: number | bigint\n }\n },\n }\n },\n run(sql, params) {\n const stmt = getStmt(sql)\n return stmt.run(...((params ?? []) as SQLInputValue[])) as {\n changes: number\n lastInsertRowid: number | bigint\n }\n },\n exec(sql) {\n rawDb.exec(sql)\n },\n // node:sqlite has no callable `transaction` wrapper; use manual BEGIN/COMMIT/ROLLBACK.\n transaction<T>(fn: () => T): () => T {\n return () => {\n const outermost = transactionDepth === 0\n const savepoint = outermost ? null : `bazilion_nested_${++savepointSequence}`\n if (outermost) rawDb.exec('BEGIN')\n else rawDb.exec(`SAVEPOINT ${savepoint}`)\n transactionDepth++\n try {\n const result = fn()\n if (outermost) rawDb.exec('COMMIT')\n else rawDb.exec(`RELEASE SAVEPOINT ${savepoint}`)\n return result\n } catch (err) {\n if (outermost) rawDb.exec('ROLLBACK')\n else {\n rawDb.exec(`ROLLBACK TO SAVEPOINT ${savepoint}`)\n rawDb.exec(`RELEASE SAVEPOINT ${savepoint}`)\n }\n throw err\n } finally {\n transactionDepth--\n }\n }\n },\n }\n}\n\nfunction applyPragmas(rawDb: DatabaseSync, includeWal: boolean): void {\n if (includeWal) {\n try {\n rawDb.exec('PRAGMA journal_mode = WAL')\n } catch {\n // some sqlite builds reject WAL on :memory: — ignore\n }\n }\n rawDb.exec('PRAGMA foreign_keys = ON')\n}\n\nexport function openDb(path: string): BazilionDb {\n // Bazilion is the normal sole writer, but online backups and operator-side\n // diagnostics can briefly overlap another WAL connection. Wait for those\n // transient locks instead of turning unrelated reads/writes (including\n // token usage telemetry) into immediate SQLITE_BUSY failures.\n const raw = new DatabaseSync(path, { timeout: 5_000 })\n applyPragmas(raw, true)\n return {\n raw: wrap(raw),\n home: dirname(path),\n backupTo(path) {\n return backup(raw, path)\n },\n close() {\n raw.close()\n },\n }\n}\n\n/**\n * `home` is the Bazilion home that Agent and Profile directories derive from. Pass '' only where\n * nothing reads those directories: they would come out relative.\n */\nexport function openInMemoryDb(home: string): BazilionDb {\n const raw = new DatabaseSync(':memory:')\n applyPragmas(raw, false)\n return {\n raw: wrap(raw),\n home,\n backupTo(path) {\n return backup(raw, path)\n },\n close() {\n raw.close()\n },\n }\n}\n\nexport function inTx<T>(db: BazilionDb, fn: () => T): T {\n return db.raw.transaction(fn)()\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\n/** `<home>/daemon.pid` holds the PID of the daemon that owns the home. */\nexport const DAEMON_PID_FILE = 'daemon.pid'\n\n/**\n * PID of the daemon running on `home`, or null. A pidfile naming a dead process, or this process\n * (its PID reused, e.g. after a reboot), is stale.\n */\nexport function runningDaemonPid(home: string): number | null {\n let pid: number\n try {\n pid = Number.parseInt(readFileSync(join(home, DAEMON_PID_FILE), 'utf8'), 10)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw error\n }\n if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) return null\n try {\n process.kill(pid, 0)\n return pid\n } catch (error) {\n // EPERM: the process exists but belongs to another user.\n return (error as NodeJS.ErrnoException).code === 'EPERM' ? pid : null\n }\n}\n\n/** Offline commands (backup restore, uninstall) and a second daemon refuse a home in use. */\nexport function assertDaemonStopped(home: string): void {\n const pid = runningDaemonPid(home)\n if (pid !== null) {\n throw new Error(\n `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first ` +\n `(if none is running, delete ${join(home, DAEMON_PID_FILE)})`,\n )\n }\n}\n\n/** Claim `home` before bootstrap opens SQLite. Returns the function that releases it. */\nexport function claimDaemonPidFile(home: string): () => void {\n const path = join(home, DAEMON_PID_FILE)\n const content = `${process.pid}\\n`\n mkdirSync(home, { recursive: true })\n try {\n writeFileSync(path, content, { flag: 'wx', mode: 0o600 })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n assertDaemonStopped(home)\n rmSync(path, { force: true })\n writeFileSync(path, content, { flag: 'wx', mode: 0o600 })\n }\n return () => {\n // Only this daemon's own pidfile: another daemon may have written its own since.\n try {\n if (readFileSync(path, 'utf8') === content) rmSync(path)\n } catch {\n // Already gone.\n }\n }\n}\n","import { defineCommand } from 'citty'\n\ninterface CommandNode {\n subCommands?: Record<string, CommandNode | Promise<CommandNode>>\n args?: Record<string, { type?: string; alias?: string | string[] }>\n}\n\ninterface Flatten {\n /** full path e.g. [\"agent\", \"chat\"]; empty for the top-level root */\n path: string[]\n /** immediate subcommand names available at this path */\n subs: string[]\n /** flag tokens e.g. [\"--profile\", \"--name\", \"--long\", \"-l\"] */\n flags: string[]\n}\n\nasync function walk(cmd: CommandNode, path: string[], out: Flatten[]): Promise<void> {\n const subsRaw = cmd.subCommands ?? {}\n const subNames = Object.keys(subsRaw)\n const flags = flagsOf(cmd.args ?? {})\n out.push({ path, subs: subNames, flags })\n for (const name of subNames) {\n const v = subsRaw[name]\n const sub = (await Promise.resolve(v)) as CommandNode\n await walk(sub, [...path, name], out)\n }\n}\n\nfunction flagsOf(args: Record<string, { type?: string; alias?: string | string[] }>): string[] {\n const out: string[] = []\n for (const [name, def] of Object.entries(args)) {\n // Positionals don't get completed as flags.\n if (def.type === 'positional') continue\n out.push(`--${name}`)\n const aliases = Array.isArray(def.alias) ? def.alias : def.alias ? [def.alias] : []\n for (const a of aliases) out.push(a.length === 1 ? `-${a}` : `--${a}`)\n }\n return out\n}\n\nfunction bashScript(flat: Flatten[]): string {\n const cases = flat\n .map((f) => {\n const key = f.path.length === 0 ? '\"\"' : JSON.stringify(f.path.join(' '))\n const words = [...f.subs, ...f.flags].join(' ')\n return ` ${key})\\n COMPREPLY=($(compgen -W ${JSON.stringify(words)} -- \"$cur\"))\\n ;;`\n })\n .join('\\n')\n return `# bazilion bash completion. Install with:\n# source <(bazilion completion bash)\n# or append to ~/.bashrc / ~/.bash_profile.\n_bazilion_completion() {\n local cur prev cword\n COMPREPLY=()\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n cword=$COMP_CWORD\n # Build the current subcommand path by walking words[1..cword-1], skipping\n # flags and their values. We don't try to parse flag arity — treating every\n # flag as standalone is a good-enough approximation for completion.\n local cmd=\"\"\n local i\n for ((i=1; i<cword; i++)); do\n local w=\"\\${COMP_WORDS[i]}\"\n [[ \"$w\" == -* ]] && continue\n cmd+=\"\\${cmd:+ }$w\"\n done\n case \"$cmd\" in\n${cases}\n *)\n COMPREPLY=()\n ;;\n esac\n}\ncomplete -F _bazilion_completion bazilion\n`\n}\n\nfunction zshScript(flat: Flatten[]): string {\n // zsh bundles a bashcompinit shim; reusing the bash script sidesteps the\n // cost of a native _arguments/_describe implementation while still giving\n // users a working completion. Ships with a tiny preamble so zsh loads the\n // bash compat helpers first.\n const bash = bashScript(flat)\n return `# bazilion zsh completion. Install with:\n# source <(bazilion completion zsh)\n# If you don't already have bashcompinit loaded, this does it for you.\nautoload -U +X compinit && compinit\nautoload -U +X bashcompinit && bashcompinit\n${bash}`\n}\n\nfunction fishScript(flat: Flatten[]): string {\n const lines: string[] = [\n '# bazilion fish completion. Install with:',\n '# bazilion completion fish | source',\n '# or write it to ~/.config/fish/completions/bazilion.fish',\n '',\n 'complete -c bazilion -f',\n ]\n for (const f of flat) {\n if (f.path.length === 0) {\n for (const s of f.subs) lines.push(`complete -c bazilion -n '__fish_use_subcommand' -a ${s}`)\n for (const fl of f.flags) {\n const long = fl.startsWith('--') ? fl.slice(2) : ''\n const short = !fl.startsWith('--') ? fl.slice(1) : ''\n const parts: string[] = [\"complete -c bazilion -n '__fish_use_subcommand'\"]\n if (short) parts.push(`-s ${short}`)\n if (long) parts.push(`-l ${long}`)\n lines.push(parts.join(' '))\n }\n } else {\n // Guard this case on the joined path being the last N tokens in\n // COMP_CWORDS — fish's __fish_seen_subcommand_from handles each token\n // independently, so we require every path segment.\n const guard = f.path.map((p) => `__fish_seen_subcommand_from ${p}`).join('; and ')\n for (const s of f.subs) {\n lines.push(`complete -c bazilion -n '${guard}' -a ${s}`)\n }\n for (const fl of f.flags) {\n const long = fl.startsWith('--') ? fl.slice(2) : ''\n const short = !fl.startsWith('--') ? fl.slice(1) : ''\n const parts: string[] = [`complete -c bazilion -n '${guard}'`]\n if (short) parts.push(`-s ${short}`)\n if (long) parts.push(`-l ${long}`)\n lines.push(parts.join(' '))\n }\n }\n }\n return `${lines.join('\\n')}\\n`\n}\n\nexport function completionCommand(main: CommandNode) {\n return defineCommand({\n meta: {\n name: 'completion',\n description: 'Print a shell completion script (bash, zsh, or fish)',\n },\n args: {\n shell: {\n type: 'positional',\n required: true,\n description: 'bash | zsh | fish',\n },\n },\n async run({ args }) {\n const flat: Flatten[] = []\n await walk(main, [], flat)\n const shell = String(args.shell).toLowerCase()\n if (shell === 'bash') console.log(bashScript(flat))\n else if (shell === 'zsh') console.log(zshScript(flat))\n else if (shell === 'fish') console.log(fishScript(flat))\n else throw new Error(`unsupported shell: ${args.shell} (want bash | zsh | fish)`)\n },\n })\n}\n","import type {\n ProviderConfigResponse,\n ServiceCard,\n ServiceFieldState,\n SetFieldRequest,\n SetFieldsRequest,\n SetFieldsResponse,\n ToolsResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nfunction displayValue(f: ServiceFieldState): string {\n const source = f.environment ? ' (from the daemon’s environment)' : ''\n if (f.kind === 'secret') return f.set ? `${f.preview ?? '(set)'}${source}` : `(unset)${source}`\n if (f.environment) return `${f.effective ?? ''}${source}`\n if (f.set) return f.value ?? '(set)'\n return f.effective ? `${f.effective} (default)` : '(unset)'\n}\n\n/** What a setting takes, when it is more specific than text. */\nfunction accepts(field: ServiceFieldState): string | undefined {\n const input = field.input\n switch (input.type) {\n case 'choice':\n return input.options.map((option) => `${option.value} (${option.label})`).join(', ')\n case 'switch':\n // Yes or no reads the same whichever way round the page shows it.\n return [input.on, input.off].includes('true')\n ? 'true or false'\n : `${input.on} or ${input.off}`\n case 'number': {\n const shown = input.scale\n ? ` (the Tools page shows ${input.unit ?? 'units'}: ${input.scale} each)`\n : ''\n return `a whole number from ${input.min} to ${input.max}${shown}`\n }\n default:\n return undefined\n }\n}\n\nconst listCmd = defineCommand({\n meta: {\n name: 'list',\n description:\n 'List every setting of providers, model functions and tools, and what is in effect',\n },\n async run() {\n const client = createClient()\n // Providers, model functions and tools all carry fields: merge and print.\n const { providers } = await client.get<ProviderConfigResponse>('/api/config/providers')\n const { tools, functions } = await client.get<ToolsResponse>('/api/config/tools')\n const cards = [...functions, ...tools]\n const all: Pick<ServiceCard, 'id' | 'fields'>[] = [...providers, ...cards]\n\n printRows(\n all.flatMap((svc) => svc.fields.map((f) => [svc.id, f.envVar, f.kind, displayValue(f)])),\n '(no fields registered)',\n )\n console.log('')\n for (const card of cards) {\n const state = [card.state?.label, card.note].filter(Boolean).join('. ')\n if (state) console.log(`${card.displayName}: ${state}`)\n for (const field of card.fields) {\n if (field.input.type !== 'choice') continue\n const chosen = field.input.options.find((option) => option.value === field.effective)\n if (chosen?.note) console.log(` ${chosen.note.text}`)\n }\n }\n console.log('')\n for (const card of cards) {\n for (const field of card.fields) {\n const takes = accepts(field)\n if (takes) console.log(`${field.envVar}: ${takes}`)\n }\n }\n },\n})\n\nconst setCmd = defineCommand({\n meta: {\n name: 'set',\n description:\n 'Set one setting (NAME value), or several that are saved together (NAME=value NAME=value)',\n },\n args: {\n envVar: positional('Setting name (e.g. ANTHROPIC_API_KEY), or NAME=value'),\n value: {\n type: 'positional',\n required: false,\n description: 'New value (an empty string clears the setting)',\n },\n },\n async run({ args }) {\n const client = createClient()\n if (!args.envVar.includes('=')) {\n if (args.value === undefined) {\n throw new Error(`give ${args.envVar} a value, or use NAME=value`)\n }\n const body: SetFieldRequest = { value: args.value }\n const state = await client.put<ServiceFieldState>(\n apiPath('config', 'fields', args.envVar),\n body,\n )\n console.log(`${state.envVar} (${state.kind}): ${displayValue(state)}`)\n return\n }\n // NAME=value pairs: checked together, and stored only when all of them pass.\n const values: Record<string, string> = {}\n for (const token of args._) {\n const at = token.indexOf('=')\n if (at <= 0) throw new Error(`expected NAME=value, got \"${token}\"`)\n values[token.slice(0, at)] = token.slice(at + 1)\n }\n const body: SetFieldsRequest = { values }\n const { fields } = await client.put<SetFieldsResponse>('/api/config/fields', body)\n for (const state of fields) {\n console.log(`${state.envVar} (${state.kind}): ${displayValue(state)}`)\n }\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Remove a setting, back to its default' },\n args: {\n envVar: positional('Setting name to clear'),\n },\n async run({ args }) {\n await createClient().del(apiPath('config', 'fields', args.envVar))\n console.log(`removed ${args.envVar}`)\n },\n})\n\nexport const configCommand = defineCommand({\n meta: {\n name: 'config',\n description: 'Settings: credentials (stored encrypted), choices, switches and addresses',\n },\n subCommands: {\n list: listCmd,\n set: setCmd,\n rm: rmCmd,\n },\n})\n","// Entity shapes: the daemon reads them from its database and sends them as they are, and the CLI\n// and the web consume them.\n\nexport type Timestamp = number\n\n/**\n * A team is a collaboration context: one filesystem root, one USER.md\n * (read-only to agents, edited by the human), one roster of member agents.\n * Every agent belongs to exactly one team.\n */\nexport interface Team {\n id: string\n name: string\n path: string\n /** Read-only context about the human for all agents in this team.\n * Injected into the system prompt; never exposed as a file on disk. */\n userMd: string\n /**\n * Optional Telegram forum-topic name template for this team's agents.\n * `null` = built-in naming (bare name for `default`, `<slug> › <name>`\n * otherwise). When set, rendered with {agent.name}, {team.name},\n * {team.slug}. Must contain {agent.name} so topics stay distinct.\n */\n telegramTopicNameFormat: string | null\n /** Who may message whom inside the Team; see TeamPolicy. */\n policyMode: TeamPolicyMode\n createdAt: Timestamp\n}\n\n/** The Team and the Profile first-run setup creates. */\nexport const DEFAULT_TEAM_ID = 'default'\n\n/** The longest Agent name, the same in the web, the CLI and the API. */\nexport const AGENT_NAME_MAX = 120\n\n/** The longest role an Agent can be given when it is added (\"What is it for?\"). */\nexport const AGENT_ROLE_MAX = 4_000\n\n/**\n * Why a name cannot be an Agent's, or null. A name is one line of visible text: it is shown in\n * every teammate's instructions, so line breaks and control or format characters are refused.\n */\nexport function agentNameProblem(name: string): string | null {\n if (!name.trim()) return 'A name cannot be empty.'\n if (name.length > AGENT_NAME_MAX) return `A name is at most ${AGENT_NAME_MAX} characters.`\n if (/[\\p{Cc}\\p{Cf}\\u2028\\u2029]/u.test(name)) {\n return 'A name is one line of text, without control characters.'\n }\n return null\n}\nexport const DEFAULT_PROFILE_ID = 'default'\n\nexport type SkillsMode = 'all' | 'selected'\n\nexport interface Profile {\n id: string\n name: string\n dir: string\n defaultModel: string\n skillsMode: SkillsMode\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\n/**\n * open: Team members may message each other freely. restricted: a member may message a\n * teammate only along an allow edge. Messages between Teams always need an edge to\n * `outside` in the sender's Team and one from `outside` in the recipient's Team.\n */\nexport type TeamPolicyMode = 'open' | 'restricted'\n\n/** Edge endpoint standing for every Agent in other Teams. */\nexport const OUTSIDE_TEAM = 'outside'\n\n/** Directed allow edge between a member Agent id and another member or `outside`. */\nexport interface TeamPolicyEdge {\n from: string\n to: string\n}\n\nexport interface TeamPolicy {\n teamId: string\n mode: TeamPolicyMode\n edges: TeamPolicyEdge[]\n /** The Team's members, archived Agents included. */\n members: Agent[]\n}\n\nexport interface TeamTemplateSlot {\n profileId: string\n agentName: string\n modelOverride: string | null\n reasoningLevel: ReasoningLevel | null\n /** Node position in the template's Flow editor. */\n layoutPosition: { x: number; y: number } | null\n}\n\n/** A slot position (index into `slots`) or `outside`. */\nexport type TeamTemplateEndpoint = number | typeof OUTSIDE_TEAM\n\nexport interface TeamTemplateEdge {\n from: TeamTemplateEndpoint\n to: TeamTemplateEndpoint\n}\n\n/** A reusable roster: spawning it creates one Agent per slot plus the edges between them. */\nexport interface TeamTemplate {\n id: string\n name: string\n userMd: string | null\n policyMode: TeamPolicyMode\n slots: TeamTemplateSlot[]\n edges: TeamTemplateEdge[]\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport type AgentStatus = 'idle' | 'archived'\n\nexport type ReasoningLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'\n\nexport const REASONING_LEVELS: ReasoningLevel[] = [\n 'off',\n 'minimal',\n 'low',\n 'medium',\n 'high',\n 'xhigh',\n]\n\n/**\n * Telegram outbound-mirror verbosity per agent.\n * 'minimal' — final assistant message only (default).\n * 'verbose' — also surfaces concise tool-call summary lines.\n */\nexport type TelegramMirrorMode = 'minimal' | 'verbose'\n\nexport interface Agent {\n id: string\n profileId: string\n name: string\n modelOverride: string | null\n reasoningLevel: ReasoningLevel\n reviewEnabled: boolean\n reviewEveryNTurns: number\n reviewModel: string | null\n reviewReasoningLevel: ReasoningLevel\n reviewTurnsSinceLast: number\n status: AgentStatus\n dir: string\n /** The team this agent belongs to. Every agent has exactly one. */\n teamId: string\n /**\n * Forum-topic id this agent is bound to in the configured Telegram\n * supergroup, or `null` when unbound. Web UI shows binding state +\n * deep-link based on this.\n */\n telegramTopicId: number | null\n /** Verbosity of the Telegram outbound mirror for this agent. */\n telegramMirrorMode: TelegramMirrorMode\n /**\n * Per-agent override of the forum-topic emoji icon (a single emoji char,\n * e.g. \"📚\"). `null` falls back to the profile-name default\n * (`BUILTIN_PROFILE_EMOJI`), then to color-only. Resolved to a Telegram\n * custom_emoji_id at topic-creation time.\n */\n telegramIconEmoji: string | null\n createdAt: Timestamp\n archivedAt: Timestamp | null\n /**\n * Structured fields parsed from the agent's own IDENTITY.md (name, emoji,\n * creature, vibe, avatar). File-derived, not a DB column — populated by the\n * agent list + detail routes, omitted (undefined) by the bare repo reads.\n * `null` once parsed means the file has no real values yet (still the\n * placeholder template). Lets the UI show avatar/creature without an extra\n * round-trip.\n */\n identity?: AgentIdentityFile | null\n}\n\nexport type AgentReviewStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'\nexport type AgentReviewTrigger = 'cadence' | 'manual'\n\nexport interface AgentReview {\n id: string\n agentId: string\n status: AgentReviewStatus\n trigger: AgentReviewTrigger\n sourceSessionId: string | null\n sourceStartOrdinal: number | null\n sourceEndOrdinal: number | null\n inputCharacters: number\n turnsReviewed: number\n proposalCount: number\n startedAt: Timestamp | null\n finishedAt: Timestamp | null\n lastError: string | null\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport type AgentLessonScope = 'private' | 'shared'\nexport type AgentLessonStatus = 'pending' | 'approved' | 'rejected' | 'revoked'\n\nexport interface AgentLessonEvidence {\n sessionId: string\n entryOrdinal: number\n /** Redacted canonical-session excerpt, populated on read and never stored with the proposal. */\n excerpt?: string\n}\n\nexport interface AgentLessonProposal {\n id: string\n reviewId: string\n agentId: string\n scope: AgentLessonScope\n text: string\n evidence: AgentLessonEvidence[]\n status: AgentLessonStatus\n version: number\n decidedAt: Timestamp | null\n revokedAt: Timestamp | null\n appliedKey: string | null\n createdAt: Timestamp\n updatedAt: Timestamp\n}\n\nexport interface AgentSkillAttachment {\n agentId: string\n skillName: string\n attachedAt: Timestamp\n}\n\nexport type TelegramAclRole = 'owner' | 'member'\n\n/**\n * A Telegram user allowed to use the bot. Presence in this list grants\n * commands + chat. `owner` (the paired person) manages the list and can't be\n * removed; `member` can use the bot but not manage it.\n */\nexport interface TelegramAllowedUser {\n userId: number\n username: string | null\n label: string | null\n role: TelegramAclRole\n addedAt: Timestamp\n}\n\nexport interface SkillMeta {\n name: string\n source: string | null\n importedAt: Timestamp | null\n}\n\nexport interface Message {\n id: string\n fromAgentId: string\n toAgentId: string\n replyTo: string | null\n causalChainId: string\n causalHop: number\n payload: string\n createdAt: Timestamp\n readAt: Timestamp | null\n}\n\nexport interface AgentLoopBreakEvent {\n id: string\n causalChainId: string\n parentMessageId: string | null\n fromAgentId: string\n toAgentId: string\n sourceTeamId: string\n targetTeamId: string\n attemptedHop: number\n maxHops: number\n reason: string\n origin: string\n createdAt: Timestamp\n}\n\n/** Every token has full access. `expiresAt` null means it never expires. */\nexport interface WebToken {\n id: string\n label: string\n kind: 'bootstrap' | 'device'\n createdAt: Timestamp\n lastUsedAt: Timestamp | null\n expiresAt: Timestamp | null\n revokedAt: Timestamp | null\n}\n\nexport interface WebSession {\n id: string\n /** The token (bootstrap or device) the browser logged in with. */\n tokenId: string\n tokenLabel: string\n createdAt: Timestamp\n lastSeenAt: Timestamp\n /** Moves forward on every use: a session ends once unused for 30 days. */\n expiresAt: Timestamp\n current: boolean\n}\n\nexport type TriggerKind = 'interval' | 'cron'\n\nexport interface AgentTrigger {\n id: string\n agentId: string\n kind: TriggerKind\n intervalSec: number | null\n cronExpr: string | null\n message: string\n enabled: boolean\n lastFiredAt: Timestamp | null\n createdAt: Timestamp\n}\n\n/** pending waits for a free Agent; each occurrence runs at most once. */\nexport type TriggerDispatchStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled'\n\n/** One scheduled occurrence of a trigger: the trigger's run history. */\nexport interface TriggerDispatch {\n conversationId: string\n id: string\n triggerId: string\n agentId: string\n scheduledAt: Timestamp\n status: TriggerDispatchStatus\n startedAt: Timestamp | null\n finishedAt: Timestamp | null\n error: string | null\n}\n\nexport interface OpenAICodexStatus {\n connected: boolean\n /** Unix ms expiry of the current access token; null if disconnected. */\n expiresAt: number | null\n /** chatgpt_account_id extracted from the JWT, when available. */\n accountId: string | null\n}\n\nexport interface AgentIdentityFile {\n name?: string\n emoji?: string\n theme?: string\n creature?: string\n vibe?: string\n avatar?: string\n}\n\n/**\n * The name an Agent gave itself (its IDENTITY.md, usually in its first conversation), when it is\n * not the name it has in the list: \"Sales Director\" that calls itself Sally. Null otherwise.\n */\nexport function chosenName(agent: {\n name: string\n identity?: AgentIdentityFile | null\n}): string | null {\n const own = agent.identity?.name?.trim()\n // An Agent writes its IDENTITY.md itself: a name that breaks the rule for names is not shown,\n // nor put in its teammates' prompts.\n if (!own || agentNameProblem(own)) return null\n return own.toLowerCase() !== agent.name.trim().toLowerCase() ? own : null\n}\n\nexport interface ResolvedAgent {\n agent: Agent\n profile: Profile\n model: string\n reasoningLevel: ReasoningLevel\n team: Team\n skills: string[]\n /** Human-approved, agent-private reviewed lessons injected on every normal turn. */\n privateLessons: string[]\n}\n\nexport type McpTransport = 'stdio' | 'http'\n\n/** A configured MCP server. The HTTP bearer token is never returned. */\nexport interface McpServer {\n id: string\n name: string\n transport: McpTransport\n /** stdio only — executable to spawn. */\n command: string | null\n /** stdio only — arguments. */\n args: string[]\n /** Streamable HTTP only — endpoint URL. */\n url: string | null\n /** Whether an HTTP bearer token is stored for this server. */\n hasAuthToken: boolean\n /** stdio: the names of its own environment variables (a token, a client id); never the values. */\n envNames?: string[]\n /**\n * The operator's choices for single tools: true asks before each call, false never does. Every\n * other tool asks when its name says it sends, posts, shares, creates, changes or deletes\n * something.\n */\n ask?: Record<string, boolean>\n enabled: boolean\n createdAt: number\n updatedAt: number\n}\n\n/** Create/update payload for an MCP server. `authToken` is write-only. */\nexport interface McpServerInput {\n name: string\n transport: McpTransport\n command?: string | null\n args?: string[]\n url?: string | null\n /** HTTP bearer token; stored encrypted. Pass null to clear. */\n authToken?: string | null\n /** stdio: set (a value) or remove (null) its own environment variables; stored encrypted. */\n env?: Record<string, string | null>\n /** Replaces the choices of which tools ask first; null or {} goes back to the default rule. */\n ask?: Record<string, boolean> | null\n enabled?: boolean\n}\n\n/** One tool discovered on an MCP server (returned by the test/connect endpoint). */\nexport interface McpToolInfo {\n name: string\n description: string\n /** It asks the operator before each call: the operator's choice, or else the default rule. */\n asks?: boolean\n /** What the default rule says for it, from its name. */\n asksByDefault?: boolean\n}\n\nexport interface LoadedProfile {\n profile: Profile\n defaultSkills: string[]\n files: {\n soul: string\n identity: string\n bootstrap: string | null\n agents: string | null\n tools: string | null\n }\n /** Structured fields parsed from IDENTITY.md — null when no values are set. */\n identity: AgentIdentityFile | null\n}\n","// Git change review of a Team workspace: the changes since a pinned base, and file feedback.\n\nimport type { UserQueueItem } from './user-queue.ts'\n\n/** Machine-readable issue codes. Messages are for operators and never embed host paths. */\nexport type ReviewIssueCode = 'invalid_base' | 'unknown_base' | 'git_output_limit' | 'file_limit'\n\nexport interface ReviewIssue {\n code: ReviewIssueCode\n message: string\n}\n\n/** Why a path may not be captured. */\nexport type ReviewScopeReason = 'bazilion_state' | 'credential_shaped'\n\nexport interface RepositoryIdentity {\n /** Current branch name, or null when HEAD is detached. */\n branch: string | null\n /** Commit HEAD points at, or null when the branch is unborn. */\n head: string | null\n headState: 'branch' | 'detached' | 'unborn'\n}\n\n/**\n * A comparison point pinned to a concrete commit. `resolvedOid` is the only value a comparison may\n * use; `requestedRef` records what was asked for, so a moved branch tip cannot rewrite a review.\n */\nexport interface PinnedBase {\n requestedRef: string\n resolvedOid: string\n}\n\n/** Bounds applied to a review. */\nexport interface ReviewLimits {\n files: number\n fileBytes: number\n totalBytes: number\n /** Rendered patch cap per file; a longer diff is cut and marked truncated. */\n patchBytes: number\n}\n\n/** 1,000 files, 1 MiB per file diff, 16 MiB of diff text in total. */\nexport const REVIEW_LIMITS: ReviewLimits = {\n files: 1000,\n fileBytes: 1024 * 1024,\n totalBytes: 16 * 1024 * 1024,\n patchBytes: 256 * 1024,\n}\n\nexport type ReviewChangeStatus =\n | 'added'\n | 'modified'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'type_changed'\n | 'unmerged'\n | 'untracked'\n | 'unknown'\n\n/** Why an entry carries no diff text. Never a silent omission. */\nexport type ContentOmission = 'excluded' | 'binary' | 'too_large' | 'total_limit' | 'unavailable'\n\nexport interface ReviewChange {\n /** Repository-relative path, destination side for renames. */\n path: string\n /** Source path for a rename or copy, otherwise null. */\n previousPath: string | null\n status: ReviewChangeStatus\n binary: boolean\n addedLines: number | null\n deletedLines: number | null\n /** Unified diff text, or null when content was omitted or not requested. */\n patch: string | null\n patchTruncated: boolean\n contentOmitted: ContentOmission | null\n /** Set when the path was refused by scope policy. */\n excludedReason: ReviewScopeReason | null\n}\n\n/** \"Changes since baseline\": the pinned base compared against the working tree. */\nexport interface RepositoryChanges {\n base: PinnedBase\n identity: RepositoryIdentity\n changes: ReviewChange[]\n /** True when the change list itself was cut by the file limit. */\n truncated: boolean\n /** Counts of what was *not* listed or captured, so an omission is never invisible. */\n withheld: { untracked: number; excluded: number }\n issues: ReviewIssue[]\n}\n\n/**\n * The Agent whose turn last wrote a changed file with a file tool (`write`, `edit`). A change made\n * by a shell command has no author here.\n */\nexport interface ReviewChangeAuthor {\n agentId: string\n agentName: string\n /** The conversation the write happened in. */\n conversationId: string\n /** When the write happened (epoch ms). */\n at: number\n}\n\nexport interface RepositoryReviewResponse {\n teamId: string\n changes: RepositoryChanges\n /** With `authors=1`: the last Agent to write each changed path, keyed by path. */\n authors?: Record<string, ReviewChangeAuthor>\n}\n\n/** Why a Team has no review: its folder is not a Git repository, or not one that can be read. */\nexport interface ReviewUnavailableResponse {\n teamId: string\n unavailable: { code: 'not_repository' | 'unsupported_layout'; message: string }\n}\n\n/** `GET /api/teams/:id/review`: the review, or why there is none (not an error: 200 either way). */\nexport type TeamReviewResponse = RepositoryReviewResponse | ReviewUnavailableResponse\n\n/** One comment of a review: about a changed file, or about one line of it. */\nexport interface ReviewFeedbackComment {\n /** A path changed since the base. */\n path: string\n /** Line of the file as it is now (1-based). */\n line?: number\n note?: string\n}\n\n/** Queue review feedback for a Team member: every comment in one message. */\nexport interface ReviewFeedbackRequest {\n agentId: string\n comments: ReviewFeedbackComment[]\n /** A note about the review as a whole. */\n note?: string\n /** Comparison base the operator is reviewing (default HEAD). */\n base?: string\n}\n\nexport interface ReviewFeedbackResponse {\n /** The exact message that was queued for the Agent. */\n message: string\n item: UserQueueItem\n}\n","// Common connections for Setup → MCP and `bazilion mcp add --preset`: third-party MCP servers for\n// the services a business Team works in, with what each needs. They run on this computer as stdio\n// servers; their tools that send or change something ask the operator first.\n\nexport interface McpPresetField {\n /** The environment variable it fills. */\n name: string\n label: string\n hint: string\n /** A token or a secret: typed hidden, stored encrypted, never shown again. */\n secret: boolean\n}\n\nexport interface McpPresetOption {\n id: string\n label: string\n hint: string\n /** Arguments it adds to the command. */\n args?: string[]\n /** Variables it sets. */\n env?: Record<string, string>\n}\n\nexport interface McpPreset {\n /** Its id, also the server's name unless another is given. */\n id: string\n title: string\n /** What Agents can do with it. */\n does: string\n command: string\n args: string[]\n /** What it needs filled in; all of them. */\n fields: McpPresetField[]\n options: McpPresetOption[]\n /** What has to be on this computer besides Node.js, which Bazilion already uses. */\n needs?: string\n /** How it signs in to the service. */\n signIn: string\n /** Something worth knowing before relying on it. */\n caveat?: string\n /** Its own setup guide. */\n guide: string\n}\n\nexport const MCP_PRESETS: readonly McpPreset[] = [\n {\n id: 'microsoft365',\n title: 'Microsoft 365',\n does: 'Outlook mail and calendar, OneDrive and Excel; with a work or school account also Teams and SharePoint.',\n command: 'npx',\n args: ['-y', '@softeria/ms-365-mcp-server'],\n fields: [],\n options: [\n {\n id: 'org',\n label: 'A work or school account',\n hint: 'Adds Teams, SharePoint and shared mailboxes.',\n args: ['--org-mode'],\n },\n ],\n signIn:\n 'No key to paste: once it is added, ask any Agent to sign in to Microsoft 365. Its login tool gives a link and a code to enter there, and the Agent then checks the sign-in.',\n guide: 'https://github.com/Softeria/ms-365-mcp-server',\n },\n {\n id: 'google_workspace',\n title: 'Google Workspace',\n does: 'Gmail, Calendar, Drive, Docs and Sheets.',\n command: 'uvx',\n args: ['workspace-mcp', '--tool-tier', 'core'],\n fields: [\n {\n name: 'GOOGLE_OAUTH_CLIENT_ID',\n label: 'OAuth client ID',\n hint: 'From a Google Cloud OAuth client of your own, with the Gmail, Calendar and Drive APIs turned on.',\n secret: false,\n },\n {\n name: 'GOOGLE_OAUTH_CLIENT_SECRET',\n label: 'OAuth client secret',\n hint: 'The same client’s secret.',\n secret: true,\n },\n ],\n options: [],\n needs: 'uv, which provides the uvx command.',\n signIn: 'You sign in to Google in the browser; its guide shows how to make the OAuth client.',\n guide: 'https://github.com/taylorwilsdon/google_workspace_mcp',\n },\n {\n id: 'slack',\n title: 'Slack',\n does: 'Read channels, threads and messages, and search them; post messages when you allow it.',\n command: 'npx',\n args: ['-y', 'slack-mcp-server@latest', '--transport', 'stdio'],\n fields: [\n {\n name: 'SLACK_MCP_XOXP_TOKEN',\n label: 'User token',\n hint: 'Starts with xoxp-: a Slack app’s user token, with the scopes its guide lists.',\n secret: true,\n },\n ],\n options: [\n {\n id: 'post',\n label: 'Let Agents post messages',\n hint: 'Off in this server unless turned on. Each post still asks you first.',\n env: { SLACK_MCP_ADD_MESSAGE_TOOL: 'true' },\n },\n ],\n signIn: 'The token is the sign-in: Agents act as the user who made it.',\n guide: 'https://github.com/korotovsky/slack-mcp-server',\n },\n {\n id: 'notion',\n title: 'Notion',\n does: 'Search, read and write pages and databases you share with it.',\n command: 'npx',\n args: ['-y', '@notionhq/notion-mcp-server'],\n fields: [\n {\n name: 'NOTION_TOKEN',\n label: 'Integration secret',\n hint: 'Starts with ntn_: an internal integration’s secret. Share the pages it may use with that integration.',\n secret: true,\n },\n ],\n options: [],\n signIn: 'The integration secret is the sign-in; it sees only what you share with it.',\n caveat:\n 'Notion no longer maintains this server and recommends its remote one, which needs a browser sign-in Bazilion cannot do yet. It still works with an integration secret.',\n guide: 'https://github.com/makenotion/notion-mcp-server',\n },\n]\n\n/** The server a preset makes, with the options chosen and the fields filled in. */\nexport function presetServer(\n preset: McpPreset,\n options: { name?: string; chosen?: readonly string[]; values?: Record<string, string> },\n): { name: string; command: string; args: string[]; env: Record<string, string> } {\n const chosen = preset.options.filter((option) => options.chosen?.includes(option.id))\n return {\n name: options.name?.trim() || preset.id,\n command: preset.command,\n args: [...preset.args, ...chosen.flatMap((option) => option.args ?? [])],\n env: {\n ...Object.fromEntries(\n preset.fields\n .map((field) => [field.name, options.values?.[field.name]?.trim() ?? ''] as const)\n .filter(([, value]) => value !== ''),\n ),\n ...Object.assign({}, ...chosen.map((option) => option.env ?? {})),\n },\n }\n}\n","import type { Profile, SkillsMode } from './entities.ts'\n\nexport interface CreateProfileRequest {\n id: string\n name?: string\n defaultModel: string\n skillsMode?: SkillsMode\n defaultSkills?: string[]\n /** Initial SOUL.md content. Falls back to the built-in template when omitted. */\n soul?: string\n /** Initial IDENTITY.md content. Falls back to the built-in template when omitted. */\n identity?: string\n /** Initial BOOTSTRAP.md content. Omit for default; pass null to skip bootstrap entirely. */\n bootstrap?: string | null\n /** Initial AGENTS.md content. Omit for the default template; pass null to skip the file. */\n agents?: string | null\n /** Initial TOOLS.md content. Omit for the default template; pass null to skip the file. */\n tools?: string | null\n}\n\nexport interface UpdateProfileRequest {\n name?: string\n defaultModel?: string\n skillsMode?: SkillsMode\n defaultSkills?: string[]\n}\n\n/** One entry of `GET /api/profiles`. */\nexport interface ProfileSummary extends Profile {\n agentCount: number\n defaultSkills: string[]\n}\n\n/** `GET /api/profiles/_/templates`: the built-in starter text of each template file. */\nexport interface ProfileTemplates {\n soul: string\n identity: string\n bootstrap: string\n agents: string\n tools: string\n}\n\nexport type ProfileFileName = 'SOUL.md' | 'IDENTITY.md' | 'BOOTSTRAP.md' | 'AGENTS.md' | 'TOOLS.md'\n\nexport const PROFILE_FILES: ProfileFileName[] = [\n 'SOUL.md',\n 'IDENTITY.md',\n 'BOOTSTRAP.md',\n 'AGENTS.md',\n 'TOOLS.md',\n]\n\nexport interface FileContentResponse {\n content: string\n}\n\nexport interface PutFileRequest {\n content: string\n}\n","/** A file an Agent delivered or generated, saved by the daemon. */\nexport interface AgentResult {\n id: string\n teamId: string\n agentId: string\n /** The conversation it was delivered in. */\n sessionId: string\n toolCallId: string\n /** Position among the images of one image_generate call; 0 otherwise. */\n sourceIndex: number\n name: string\n mimeType: string\n byteLength: number\n sha256: string\n /** The image model that generated it; null for delivered files. */\n imageModel: string | null\n createdAt: number\n}\n\n/** Kept in the tool result of the transcript; resolved through the daemon. */\nexport interface ResultReference {\n resultId: string\n}\n\nexport interface ResultListResponse {\n results: AgentResult[]\n total: number\n offset: number\n limit: number\n}\n\n/** The most of a text file the daemon previews, in bytes. */\nexport const TEXT_PREVIEW_MAX_BYTES = 256 * 1024\n\nconst TEXT_TYPES = new Set([\n 'application/json',\n 'application/ld+json',\n 'application/xml',\n 'application/yaml',\n 'application/x-yaml',\n 'application/toml',\n 'application/javascript',\n 'application/x-sh',\n 'application/sql',\n 'application/x-ndjson',\n])\n\n/** Files sent without a text type (`application/octet-stream`) that are text by their name. */\nconst TEXT_EXTENSIONS = new Set(\n (\n 'txt md markdown csv tsv json jsonl ndjson yaml yml toml ini cfg conf log xml css scss ' +\n 'js mjs cjs jsx ts tsx py rb go rs java kt swift c h cc cpp hpp cs php sh bash zsh fish ps1 ' +\n 'sql r lua pl tex diff patch vue svelte graphql proto dockerfile makefile'\n ).split(' '),\n)\n\n/** Pages a browser would run are only ever downloaded, never shown, not even as text. */\nconst ACTIVE_TYPES = new Set(['text/html', 'application/xhtml+xml', 'image/svg+xml'])\n\n/** Whether Files can show a saved file as text: its type or its name says text, and it is small. */\nexport function isTextPreview(\n result: Pick<AgentResult, 'mimeType' | 'name' | 'byteLength'>,\n): boolean {\n if (result.byteLength > TEXT_PREVIEW_MAX_BYTES) return false\n const type = result.mimeType.toLowerCase()\n if (ACTIVE_TYPES.has(type)) return false\n if (type.startsWith('text/') || TEXT_TYPES.has(type) || /\\+(json|xml)$/.test(type)) return true\n if (type !== 'application/octet-stream') return false\n const name = result.name.toLowerCase()\n const extension = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1) : name\n return TEXT_EXTENSIONS.has(extension)\n}\n","/**\n * What models were used for, read from the conversations' saved history: every reply, summary and\n * cache warm-up Pi records there, with its tokens and cost.\n */\n\n/** How a provider charges: per use, through a subscription, or not at all (a server here). */\nexport type UsageBilling = 'paid' | 'plan' | 'local'\n\nexport interface UsageTotals {\n /** Model calls counted: replies, conversation summaries, cache warm-ups. */\n calls: number\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheWriteTokens: number\n totalTokens: number\n /**\n * US dollars spent on providers paid per use: what the provider reported it billed, otherwise\n * Pi's catalog price for the tokens.\n */\n cost: number\n /** Some of `cost` is a catalog estimate rather than a billed amount. */\n estimated: boolean\n /** Tokens used through a subscription (a ChatGPT plan, Copilot, a token plan): no cost per use. */\n planTokens: number\n /** Tokens on a model server on this computer. */\n localTokens: number\n /** Tokens on providers paid per use whose model has no price in Pi's catalog: not in `cost`. */\n unpricedTokens: number\n}\n\nexport interface UsageDay extends UsageTotals {\n /** `YYYY-MM-DD` in the report's time zone. */\n day: string\n}\n\nexport interface UsageByAgent extends UsageTotals {\n agentId: string\n agentName: string\n teamId: string\n teamName: string\n archived: boolean\n}\n\nexport interface UsageByTeam extends UsageTotals {\n teamId: string\n teamName: string\n}\n\nexport interface UsageByModel extends UsageTotals {\n /** Pi's provider id, as the history records it. */\n provider: string\n /** The provider as Setup names it. */\n providerName: string\n model: string\n billing: UsageBilling\n}\n\nexport interface UsageReport {\n /** The days counted, today included; null for everything saved. */\n days: number | null\n timeZone: string\n /** The first and last day counted (`YYYY-MM-DD`); `from` is null for everything saved. */\n from: string | null\n to: string\n totals: UsageTotals\n /** Every day of the period, oldest first (only days with use for everything saved). */\n byDay: UsageDay[]\n /** Most spent first, then most tokens. */\n byAgent: UsageByAgent[]\n byTeam: UsageByTeam[]\n byModel: UsageByModel[]\n /** Saved conversations that could not be read, and so are not counted. */\n unreadable: number\n /** The one Agent or Team counted, when the report is limited to it. */\n scope: { kind: 'agent' | 'team'; id: string; name: string } | null\n}\n\n/** One conversation's use, shown beside it in the conversation list. */\nexport interface ConversationUsage {\n calls: number\n totalTokens: number\n cost: number\n estimated: boolean\n planTokens: number\n localTokens: number\n}\n\n/** US dollars as Usage shows them: `$0.42`, `<$0.01`, `$1,234`. */\nexport function formatCost(usd: number): string {\n if (usd <= 0) return '$0.00'\n if (usd < 0.01) return '<$0.01'\n if (usd < 1000) return `$${usd.toFixed(2)}`\n return `$${Math.round(usd).toLocaleString('en-US')}`\n}\n\n/** A use in a few words: `$0.42 · 12k tokens`, `15k tokens, on a plan`, `3.1k tokens, local`. */\nexport function usageSummary(\n usage: Pick<UsageTotals, 'cost' | 'totalTokens' | 'planTokens' | 'localTokens'>,\n): string {\n const tokens = `${formatTokens(usage.totalTokens)} tokens`\n if (usage.cost > 0) return `${formatCost(usage.cost)} · ${tokens}`\n if (usage.totalTokens > 0 && usage.planTokens === usage.totalTokens) return `${tokens}, on a plan`\n if (usage.totalTokens > 0 && usage.localTokens === usage.totalTokens) return `${tokens}, local`\n return tokens\n}\n\n/** A token count in a few characters: `950`, `12.5k`, `3.4M`. */\nexport function formatTokens(tokens: number): string {\n if (tokens < 1000) return String(Math.round(tokens))\n if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(tokens < 10_000 ? 1 : 0)}k`\n return `${(tokens / 1_000_000).toFixed(tokens < 10_000_000 ? 1 : 0)}M`\n}\n","import {\n type Conversation,\n type ConversationListResponse,\n type ConversationSearchResponse,\n type ConversationUsage,\n type ProviderMessage,\n usageSummary,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport {\n agentArg,\n apiPath,\n jsonFlag,\n positional,\n printJson,\n terminalSafe,\n} from '../command-helpers.ts'\n\nconst conversationArg = positional('Conversation id')\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List conversations; the active one receives new messages' },\n args: {\n agent: agentArg,\n limit: { type: 'string', default: '20', description: 'Page size' },\n offset: { type: 'string', default: '0', description: 'Conversations to skip' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ limit: args.limit, offset: args.offset })\n const body = await createClient().get<ConversationListResponse>(\n `${apiPath('agents', args.agent, 'conversations')}?${query}`,\n )\n if (args.json) return printJson(body)\n if (!body.total) return console.log('(no conversations)')\n for (const line of columnize([\n ['id', 'title', 'active', 'used'],\n ...body.conversations.map((item) => {\n const used = body.usage[item.id]\n return [\n item.id,\n item.title,\n item.id === body.selectedId ? 'yes' : '',\n used ? usageSummary(used) : '',\n ]\n }),\n ]))\n console.log(line)\n },\n})\n\nconst search = defineCommand({\n meta: {\n name: 'search',\n description: \"Find the messages that hold every word, in every Agent's conversations\",\n },\n args: {\n query: positional('Words to find (quote several: \"launch email\")'),\n agent: { type: 'string', description: 'Only this Agent (id or name)' },\n limit: { type: 'string', default: '20', description: 'Most messages listed (up to 50)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ q: args.query, limit: args.limit })\n if (args.agent) query.set('agent', args.agent)\n const body = await createClient().get<ConversationSearchResponse>(\n `/api/conversations/search?${query}`,\n )\n if (args.json) return printJson(body)\n if (body.hits.length === 0) console.log('(no messages hold every word)')\n for (const hit of body.hits) {\n const when = hit.at ? new Date(hit.at).toISOString().slice(0, 16).replace('T', ' ') : ''\n console.log(\n terminalSafe(\n `${hit.agentName} · ${hit.conversationTitle}${hit.active ? ' (active)' : ''} · ${hit.role === 'user' ? 'you' : hit.agentName} ${when}`,\n ),\n )\n console.log(` ${terminalSafe(hit.snippet)}`)\n console.log(` bazilion conversation show ${hit.agentId.slice(0, 8)} ${hit.conversationId}`)\n }\n if (body.truncated) console.log(`Only the newest ${body.hits.length}; use --limit for more.`)\n if (body.unreadable > 0)\n console.log(\n `${body.unreadable} conversation${body.unreadable === 1 ? '' : 's'} could not be read.`,\n )\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Read a conversation without making it active' },\n args: { agent: agentArg, id: conversationArg, json: jsonFlag },\n async run({ args }) {\n const body = await createClient().get<{\n conversation: Conversation\n messages: ProviderMessage[]\n usage: ConversationUsage | null\n }>(apiPath('agents', args.agent, 'conversations', args.id))\n if (args.json) return printJson(body)\n console.log(\n body.usage\n ? `${body.conversation.title} (${usageSummary(body.usage)})`\n : body.conversation.title,\n )\n for (const message of body.messages) console.log(`[${message.role}] ${message.content}`)\n },\n})\n\nconst newConversation = defineCommand({\n meta: {\n name: 'new',\n description: 'Start a new conversation and make it active; earlier ones stay readable',\n },\n args: {\n agent: agentArg,\n title: { type: 'string', description: 'Title (default: generated)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const conversation = await createClient().post<Conversation>(\n apiPath('agents', args.agent, 'conversations'),\n args.title ? { title: args.title } : {},\n )\n if (args.json) return printJson(conversation)\n console.log(`Conversation ${conversation.id}: ${conversation.title} (active)`)\n },\n})\n\nconst rename = defineCommand({\n meta: { name: 'rename', description: 'Rename a conversation' },\n args: {\n agent: agentArg,\n id: conversationArg,\n title: positional('New title'),\n json: jsonFlag,\n },\n async run({ args }) {\n const body = await createClient().patch<{ conversation: Conversation }>(\n apiPath('agents', args.agent, 'conversations', args.id),\n { title: args.title },\n )\n if (args.json) return printJson(body)\n console.log(body.conversation.title)\n },\n})\n\nconst select = defineCommand({\n meta: {\n name: 'select',\n description: 'Switch to an earlier conversation: new messages continue it',\n },\n args: { agent: agentArg, id: conversationArg, json: jsonFlag },\n async run({ args }) {\n const body = await createClient().post<{ conversation: Conversation }>(\n apiPath('agents', args.agent, 'conversations', args.id, 'select'),\n )\n if (args.json) return printJson(body)\n console.log(`Conversation ${body.conversation.id}: ${body.conversation.title} (active)`)\n },\n})\n\nexport const conversationCommand = defineCommand({\n meta: {\n name: 'conversation',\n description: 'List, read, start, rename and switch Agent conversations',\n },\n subCommands: { list, show, new: newConversation, rename, select, search },\n})\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { connect } from 'node:net'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { resolveCliPaths } from '../paths.ts'\nimport { daemonEntry, nodeArgs } from './serve.ts'\n\nconst bundledWebServerEntry = join(import.meta.dirname, 'web-server.js')\nconst sourceWebServerEntry = join(import.meta.dirname, '..', 'web-server.ts')\nconst webServerEntry = existsSync(bundledWebServerEntry)\n ? bundledWebServerEntry\n : sourceWebServerEntry\n\nconst bundledWebDist = join(import.meta.dirname, 'web')\nconst sourceWebDist = join(import.meta.dirname, '..', '..', '..', 'web', 'dist')\nconst webDist = existsSync(bundledWebDist) ? bundledWebDist : sourceWebDist\n\nasync function responds(url: string): Promise<boolean> {\n try {\n const res = await fetch(url)\n return res.status >= 200 && res.status < 500\n } catch {\n return false\n }\n}\n\nfunction probeHost(host: string): string {\n if (host === '0.0.0.0') return '127.0.0.1'\n if (host === '::') return '::1'\n return host\n}\n\nfunction isTcpPortOpen(host: string, port: string): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = connect({ host: probeHost(host), port: Number(port) })\n const done = (open: boolean): void => {\n socket.removeAllListeners()\n socket.destroy()\n resolve(open)\n }\n socket.setTimeout(600)\n socket.once('connect', () => done(true))\n socket.once('timeout', () => done(false))\n socket.once('error', () => done(false))\n })\n}\n\nasync function bazilionDaemonRunning(url: string, port: string): Promise<boolean> {\n try {\n const res = await fetch(`${url}/api/health`)\n if (res.ok) {\n const body = (await res.json().catch(() => null)) as { ok?: unknown } | null\n if (body?.ok === true) return true\n }\n } catch {\n return false\n }\n\n throw new Error(\n `port ${port} is already serving HTTP, but it is not a healthy bazilion daemon. Re-run with --daemon-port <free-port>.`,\n )\n}\n\nasync function bazilionWebRunning(url: string, port: string): Promise<boolean> {\n try {\n const res = await fetch(url)\n if (res.status >= 200 && res.status < 500) {\n const html = await res.text()\n if (html.includes('<title>bazilion</title>') || html.includes('>bazilion<')) {\n return true\n }\n }\n } catch {\n return false\n }\n\n throw new Error(\n `port ${port} is already serving HTTP, but it is not the bazilion web UI. Re-run with --port <free-port>.`,\n )\n}\n\nasync function waitFor(url: string, label: string, timeoutMs = 20_000): Promise<void> {\n const start = Date.now()\n while (Date.now() - start < timeoutMs) {\n if (await responds(url)) return\n await new Promise((r) => setTimeout(r, 150))\n }\n throw new Error(`timed out waiting for ${label} at ${url}`)\n}\n\nfunction openBrowser(url: string): void {\n const cmd = process.platform === 'darwin' ? 'open' : process.env.BROWSER || 'xdg-open'\n spawn(cmd, [url], { detached: true, stdio: 'ignore' }).unref()\n}\n\nfunction spawnProcess(label: string, entry: string, env: NodeJS.ProcessEnv): ChildProcess {\n if (!existsSync(entry)) {\n throw new Error(`${label} entry not found at ${entry}`)\n }\n return spawn(process.execPath, nodeArgs(entry), {\n env,\n stdio: 'inherit',\n })\n}\n\nexport const dashboardCommand = defineCommand({\n meta: {\n name: 'dashboard',\n description: 'Start the bazilion daemon and bundled web UI',\n },\n args: {\n port: { type: 'string', description: 'Web UI port (default 4322)' },\n host: { type: 'string', description: 'Web UI host (default 127.0.0.1)' },\n 'daemon-port': { type: 'string', description: 'Daemon port (default 4321)' },\n 'daemon-host': { type: 'string', description: 'Daemon host (default 127.0.0.1)' },\n open: {\n type: 'boolean',\n description: 'Open the dashboard in your browser (default true)',\n default: true,\n },\n },\n async run({ args }) {\n const webHost = args.host ?? '127.0.0.1'\n const webPort = args.port ?? '4322'\n const daemonHost = args['daemon-host'] ?? '127.0.0.1'\n const daemonPort = args['daemon-port'] ?? '4321'\n const daemonUrl = `http://${daemonHost}:${daemonPort}`\n const webUrl = `http://${webHost}:${webPort}`\n const authFile = resolveCliPaths().authFile\n\n if (webHost !== '127.0.0.1' && webHost !== 'localhost' && webHost !== '::1') {\n console.error('')\n console.error(\n `warning: binding web UI to ${webHost} - the dashboard may be reachable beyond loopback.`,\n )\n console.error(' keep it behind a trusted network or a TLS proxy.')\n console.error('')\n }\n\n const children: ChildProcess[] = []\n let signalled = false\n const terminateChildren = (): void => {\n signalled = true\n for (const child of children) {\n try {\n child.kill('SIGTERM')\n } catch {}\n }\n }\n\n try {\n const daemonRunning = await bazilionDaemonRunning(daemonUrl, daemonPort)\n if (daemonRunning) {\n console.log(`using existing bazilion daemon at ${daemonUrl}`)\n } else {\n if (await isTcpPortOpen(daemonHost, daemonPort)) {\n throw new Error(\n `daemon port ${daemonPort} is already in use. Re-run with --daemon-port <free-port>.`,\n )\n }\n console.log(`starting bazilion daemon at ${daemonUrl}`)\n const daemon = spawnProcess('daemon', daemonEntry, {\n ...process.env,\n HOST: daemonHost,\n PORT: daemonPort,\n })\n children.push(daemon)\n await waitFor(`${daemonUrl}/api/health`, 'bazilion daemon')\n }\n\n const webRunning = await bazilionWebRunning(webUrl, webPort)\n if (webRunning) {\n console.log(`using existing bazilion web UI at ${webUrl}`)\n } else {\n if (await isTcpPortOpen(webHost, webPort)) {\n throw new Error(\n `web UI port ${webPort} is already in use. Re-run with --port <free-port>.`,\n )\n }\n if (!existsSync(join(webDist, 'server', 'server.js'))) {\n throw new Error(\n `bazilion web UI bundle not found at ${webDist}. Run \"pnpm --filter @bazilion/web build\" from the repository root of a source checkout, or reinstall the published package.`,\n )\n }\n console.log(`starting bazilion web UI at ${webUrl}`)\n const web = spawnProcess('web UI', webServerEntry, {\n ...process.env,\n WEB_HOST: webHost,\n WEB_PORT: webPort,\n BAZILION_DAEMON: daemonUrl,\n BAZILION_WEB_DIST: webDist,\n })\n children.push(web)\n await waitFor(webUrl, 'bazilion web UI')\n }\n\n console.log('')\n console.log(`dashboard: ${webUrl}`)\n console.log(`sign in: the token in ${authFile} (print it: bazilion token show-local)`)\n if (args.open) openBrowser(webUrl)\n } catch (err) {\n terminateChildren()\n throw err\n }\n\n if (children.length === 0) return\n\n process.on('SIGINT', terminateChildren)\n process.on('SIGTERM', terminateChildren)\n\n await new Promise<void>((resolve) => {\n let remaining = children.length\n for (const child of children) {\n child.on('close', (code) => {\n remaining--\n if (!signalled && code && code !== 0) process.exitCode = code\n if (remaining === 0) resolve()\n })\n }\n })\n\n if (signalled) process.exitCode = 0\n },\n})\n","import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\n\n// A published build has dist/daemon.js beside dist/cli.js; a source checkout runs the .ts entry.\nconst bundledDaemonEntry = join(import.meta.dirname, 'daemon.js')\nexport const daemonEntry = existsSync(bundledDaemonEntry)\n ? bundledDaemonEntry\n : join(import.meta.dirname, '..', '..', '..', 'daemon', 'src', 'index.ts')\n\n/** Arguments for `process.execPath`: a source `.ts` entry loads through tsx. */\nexport function nodeArgs(entry: string): string[] {\n return entry.endsWith('.ts') ? ['--import', import.meta.resolve('tsx/esm'), entry] : [entry]\n}\n\nexport const serveCommand = defineCommand({\n meta: {\n name: 'serve',\n description: 'Start the bazilion daemon (HTTP API)',\n },\n args: {\n port: { type: 'string', description: 'Port (default 4321)' },\n host: {\n type: 'string',\n description: 'Host (default 127.0.0.1). Put a TLS proxy in front before binding 0.0.0.0',\n },\n },\n async run({ args }) {\n if (!existsSync(daemonEntry)) throw new Error(`bazilion daemon not found at ${daemonEntry}`)\n const env: NodeJS.ProcessEnv = { ...process.env }\n if (args.port) env.PORT = args.port\n if (args.host) env.HOST = args.host\n console.log(\"web UI: run 'bazilion dashboard' (it reuses this daemon)\")\n\n // The daemon prints its own startup log and handles SIGINT/SIGTERM; Ctrl+C reaches it\n // through the foreground process group, so this process only forwards SIGTERM and waits.\n const proc = spawn(process.execPath, nodeArgs(daemonEntry), { env, stdio: 'inherit' })\n let signalled = false\n process.on('SIGINT', () => {\n signalled = true\n })\n process.on('SIGTERM', () => {\n signalled = true\n proc.kill('SIGTERM')\n })\n await new Promise<void>((resolve, reject) => {\n proc.on('error', reject)\n proc.on('close', (code) => {\n // A signalled stop exits 0, so a `pnpm tsx … serve` wrapper reports no failure.\n if (!signalled && code) process.exitCode = code\n resolve()\n })\n })\n },\n})\n","import type { HealthReport } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\n\nexport const doctorCommand = defineCommand({\n meta: { name: 'doctor', description: 'Diagnose your bazilion install' },\n async run() {\n const r = await createClient().get<HealthReport>('/api/health/details')\n const check = (label: string, condition: boolean, hint?: string) =>\n console.log(checkLine(label, condition, hint))\n\n console.log(`bazilion home: ${r.home}`)\n console.log()\n console.log('paths')\n check('home dir exists', r.paths.home)\n check('database exists', r.paths.db, 'run: bazilion serve (auto-bootstraps on first run)')\n check('auth.json exists', r.paths.auth, 'run: bazilion serve (auto-bootstraps on first run)')\n check('profiles dir exists', r.paths.profiles)\n check('agents dir exists', r.paths.agents)\n check('skills dir exists', r.paths.skills)\n\n if (r.database) {\n console.log()\n console.log('database')\n if (r.database.ok) {\n console.log(` ${r.database.profiles} profile(s)`)\n console.log(\n ` ${r.database.activeAgents} active agent(s) (${r.database.totalAgents} total)`,\n )\n console.log(` ${r.database.teams} team(s)`)\n } else {\n check('open database', false, r.database.error)\n }\n }\n\n console.log()\n console.log('skills library')\n console.log(` ${r.skills.installed} skill(s) installed`)\n if (r.skills.parseErrors > 0) {\n check('all skills parse', false, `${r.skills.parseErrors} skill(s) have errors`)\n for (const skill of r.skills.broken ?? []) console.log(` ${skill.name}: ${skill.error}`)\n }\n\n console.log()\n console.log('providers (enable one and save at least one model for chat)')\n if (r.providers.configured.length === 0) {\n console.log(' - no cloud providers configured')\n console.log(' (set e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY)')\n } else {\n for (const name of r.providers.configured) {\n console.log(` ✓ ${name}`)\n }\n }\n console.log(\n ` ✓ lmstudio: ${\n r.providers.lmstudio.customEndpointConfigured\n ? 'custom endpoint configured'\n : 'default local endpoint'\n }${r.providers.lmstudio.keyConfigured ? ' (API key configured)' : ''}`,\n )\n console.log(\n ` ✓ ollama: ${\n r.providers.ollama.customEndpointConfigured\n ? 'custom endpoint configured'\n : 'default local endpoint'\n }`,\n )\n\n console.log()\n console.log('web search')\n if (r.webSearch.braveConfigured) {\n console.log(' ✓ Brave Search configured')\n } else {\n console.log(' - Brave Search (set BRAVE_API_KEY — free at https://brave.com/search/api/)')\n }\n if (r.webSearch.searxngConfigured) {\n console.log(' ✓ SearXNG configured')\n } else {\n console.log(' - SearXNG (set SEARXNG_URL if you self-host one)')\n }\n if (!r.webSearch.braveConfigured && !r.webSearch.searxngConfigured) {\n console.log(' - no Brave/SearXNG: Agents on OpenAI/ChatGPT models use hosted search')\n console.log(' backend (BAZILION_WEB_SEARCH_ROUTE) and status: bazilion config list')\n }\n\n console.log()\n console.log('openclaw integration')\n if (r.openclaw.exists) {\n console.log(` ✓ ${r.openclaw.path} found`)\n console.log(' try: bazilion skill import --from openclaw')\n } else {\n console.log(` - ${r.openclaw.path} not found (fine if you don't use OpenClaw)`)\n }\n\n console.log()\n console.log('background jobs')\n console.log(\n ` ${r.scheduler.enabled ? '✓' : '-'} scheduler${\n r.scheduler.enabled ? ` (tick ${r.scheduler.tickMs}ms)` : ' (BAZILION_SCHEDULER=off)'\n }`,\n )\n\n console.log()\n for (const line of runtimeDoctorLines(r)) console.log(line)\n\n console.log()\n console.log('operational counts')\n console.log(` ${r.triggers.active} active trigger(s), ${r.triggers.disabled} disabled`)\n console.log(` ${r.tokens.active} active web token(s)`)\n\n const hasProfiles = (r.database?.ok ? r.database.profiles : 0) > 0\n const hasAgents = (r.database?.ok ? r.database.totalAgents : 0) > 0\n\n console.log()\n if (!r.ok) {\n console.log('installation issues found ✗')\n process.exitCode = 1\n return\n }\n console.log('install is healthy ✓')\n if (!hasProfiles || !hasAgents) {\n console.log('next steps')\n const todo: string[] = []\n if (!hasProfiles) {\n todo.push(' - connect a provider: bazilion provider connect <provider>')\n todo.push(\n ' (anthropic, openai, google, openai-codex after `bazilion auth openai login`,',\n )\n todo.push(' or a local lmstudio / ollama; `bazilion provider list --all` has the rest)')\n }\n if (!hasAgents) todo.push(' - spawn an agent: bazilion agent spawn --profile <id>')\n for (const line of todo) console.log(line)\n }\n },\n})\n\n/** Sandbox and approval apply the same way to every turn: chat, Telegram, schedules and inbox. */\nexport function runtimeDoctorLines(report: Pick<HealthReport, 'shellSecurity'>): string[] {\n const shell = report.shellSecurity\n const lines = ['agent runtime (every turn: chat, Telegram, schedules, inbox)']\n if (!shell.ok) {\n lines.push(checkLine('valid shell-security configuration', false, shell.error))\n return lines\n }\n if (shell.sandboxMode === 'docker') {\n lines.push(\n ` - sandbox: docker (${shell.sandboxImage}) — bash runs in a network-disabled container; host file tools hidden`,\n )\n if (shell.docker) {\n lines.push(\n checkLine(\n `Docker ready (${shell.docker.image})`,\n shell.docker.ready,\n shell.docker.reason ?? undefined,\n ),\n )\n if (shell.docker.remediation) lines.push(` remediation: ${shell.docker.remediation}`)\n }\n } else {\n lines.push(\n ' - sandbox: off — bash and file tools run on the host, unisolated',\n ' set BAZILION_BASH_SANDBOX=docker to sandbox bash',\n )\n }\n lines.push(\n shell.approvalMode === 'dangerous'\n ? ' - dangerous-command approval: on — chat can allow once; unattended turns auto-deny'\n : ' - dangerous-command approval: off — set BAZILION_BASH_APPROVAL=dangerous to opt in',\n )\n return lines\n}\n\nfunction checkLine(label: string, condition: boolean, hint?: string): string {\n const mark = condition ? '✓' : '✗'\n const tail = !condition && hint ? ` — ${hint}` : ''\n return ` ${mark} ${label}${tail}`\n}\n","import type { ListAgentLoopBreaksResponse, ListInboxResponse, Message } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst messageArg = positional('Message id')\n\nfunction decodeText(payload: string): string {\n try {\n const obj = JSON.parse(payload) as { text?: unknown }\n if (typeof obj.text === 'string') return obj.text\n } catch {}\n return payload\n}\n\nfunction messageRow(m: Message): string[] {\n const when = new Date(m.createdAt).toISOString()\n const state = m.readAt ? 'read' : 'NEW'\n const text = decodeText(m.payload)\n const preview = text.length > 60 ? `${text.slice(0, 60)}…` : text\n return [m.id, state, when, `from:${m.fromAgentId.slice(0, 8)}`, `\"${preview}\"`]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List messages in an agent inbox' },\n args: {\n agent: positional('Recipient agent id or prefix'),\n unread: { type: 'boolean', description: 'Only show unread messages' },\n },\n async run({ args }) {\n const { messages } = await createClient().get<ListInboxResponse>(\n `${apiPath('agents', args.agent, 'messages')}${args.unread ? '?unread=1' : ''}`,\n )\n printRows(messages.map(messageRow), args.unread ? '(no unread messages)' : '(inbox empty)')\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show a single message in full' },\n args: { id: messageArg },\n async run({ args }) {\n const m = await createClient().get<Message>(apiPath('messages', args.id))\n const when = new Date(m.createdAt).toISOString()\n const read = m.readAt ? new Date(m.readAt).toISOString() : '(unread)'\n console.log(`id: ${m.id}`)\n console.log(`from: ${m.fromAgentId}`)\n console.log(`to: ${m.toAgentId}`)\n console.log(`created: ${when}`)\n console.log(`read: ${read}`)\n if (m.replyTo) console.log(`reply_to: ${m.replyTo}`)\n console.log('')\n console.log(decodeText(m.payload))\n },\n})\n\nconst readCmd = defineCommand({\n meta: { name: 'read', description: 'Mark a message as read' },\n args: { id: messageArg },\n async run({ args }) {\n await createClient().patch<Message>(apiPath('messages', args.id), { read: true })\n console.log(`marked read: ${args.id}`)\n },\n})\n\nconst loopBreaksCmd = defineCommand({\n meta: { name: 'loop-breaks', description: 'List stopped agent-message chains' },\n args: {\n agent: agentArg,\n limit: { type: 'string', description: 'Maximum events to show (default 25)' },\n },\n async run({ args }) {\n const limit = args.limit ? `?limit=${encodeURIComponent(args.limit)}` : ''\n const { events } = await createClient().get<ListAgentLoopBreaksResponse>(\n `${apiPath('agents', args.agent, 'loop-breaks')}${limit}`,\n )\n printRows(\n events.map((event) => [\n new Date(event.createdAt).toISOString(),\n `chain:${event.causalChainId.slice(0, 8)}`,\n `${event.fromAgentId.slice(0, 8)}→${event.toAgentId.slice(0, 8)}`,\n `hop:${event.attemptedHop}/${event.maxHops}`,\n event.reason,\n ]),\n '(no agent-message chains stopped)',\n )\n },\n})\n\nexport const inboxCommand = defineCommand({\n meta: { name: 'inbox', description: 'Inspect agent inboxes' },\n subCommands: {\n list: listCmd,\n show: showCmd,\n read: readCmd,\n 'loop-breaks': loopBreaksCmd,\n },\n})\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { defineCommand } from 'citty'\nimport type { AuthFile } from '../auth-file.ts'\nimport { resolveCliPaths } from '../paths.ts'\n\nfunction normalizeServer(raw: string): string {\n let url: URL\n try {\n url = new URL(raw)\n } catch {\n throw new Error(`invalid --server URL: ${raw}`)\n }\n if (!/^https?:$/.test(url.protocol)) {\n throw new Error(`--server must be http(s), got ${url.protocol}`)\n }\n // Strip trailing slash so `${serverUrl}${path}` never produces `//`.\n return `${url.origin}${url.pathname.replace(/\\/$/, '')}`\n}\n\nasync function verifyToken(server: string, token: string): Promise<void> {\n const res = await fetch(`${server}/api/auth/whoami`, {\n headers: { authorization: `Bearer ${token}`, origin: server },\n })\n if (res.status === 401) throw new Error('server rejected token (401)')\n if (!res.ok) throw new Error(`server returned ${res.status} from /api/auth/whoami`)\n const owner = (await res.json()) as { publicOrigin?: string | null }\n if (owner.publicOrigin && owner.publicOrigin !== new URL(server).origin) {\n throw new Error('server canonical private origin does not match --server')\n }\n}\n\nexport const loginCommand = defineCommand({\n meta: {\n name: 'login',\n description: 'Save a remote bazilion server + token pair to auth.json',\n },\n args: {\n server: { type: 'string', description: 'Remote server URL (http[s]://...)' },\n token: { type: 'string', description: 'Token issued by `bazilion token create`' },\n 'skip-verify': { type: 'boolean', description: \"Don't verify /api/auth/whoami before saving\" },\n clear: { type: 'boolean', description: 'Remove the stored remote instead of setting one' },\n },\n async run({ args }) {\n const paths = resolveCliPaths()\n if (!existsSync(paths.authFile)) {\n throw new Error(\n `${paths.authFile} not found. Start the daemon with \"bazilion serve\" first — login stores the remote there.`,\n )\n }\n const auth = JSON.parse(readFileSync(paths.authFile, 'utf8')) as AuthFile\n\n if (args.clear) {\n if (!auth.remote) {\n console.log('no remote stored — nothing to clear')\n return\n }\n delete auth.remote\n writeFileSync(paths.authFile, `${JSON.stringify(auth, null, 2)}\\n`, { mode: 0o600 })\n console.log('cleared stored remote; CLI will fall back to the local daemon')\n return\n }\n\n if (!args.server || !args.token) {\n throw new Error(\n '--server and --token are required (or pass --clear to remove the stored remote)',\n )\n }\n const server = normalizeServer(args.server)\n if (!args['skip-verify']) {\n await verifyToken(server, args.token)\n }\n auth.remote = { server, token: args.token }\n writeFileSync(paths.authFile, `${JSON.stringify(auth, null, 2)}\\n`, { mode: 0o600 })\n console.log(`saved remote: ${server}`)\n console.log('CLI will now target this server unless BAZILION_SERVER is set in the env.')\n },\n})\n","import {\n MCP_PRESETS,\n type McpServer,\n type McpServerInput,\n type McpToolInfo,\n type McpTransport,\n presetServer,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printJson, printRows } from '../command-helpers.ts'\nimport { collectFlagValues } from '../repeatable-args.ts'\n\nconst serverArg = positional('MCP server id')\n\nfunction serverRow(s: McpServer): string[] {\n const where = s.transport === 'stdio' ? `${s.command} ${s.args.join(' ')}`.trim() : (s.url ?? '')\n return [\n s.id,\n s.enabled ? 'enabled' : 'disabled',\n s.transport,\n s.hasAuthToken ? 'auth' : '-',\n s.name,\n where,\n ]\n}\n\n/** `NAME=value` flags as an object; a bare `NAME` (for --unset-env) maps to null. */\nfunction envFlags(\n raw: readonly string[],\n name: string,\n unset = false,\n): Record<string, string | null> {\n const env: Record<string, string | null> = {}\n for (const value of collectFlagValues(raw, name)) {\n if (unset) {\n env[value] = null\n continue\n }\n const at = value.indexOf('=')\n if (at <= 0) throw new Error(`--${name} takes NAME=value, not ${value}`)\n env[value.slice(0, at)] = value.slice(at + 1)\n }\n return env\n}\n\nconst toolList = (value: string) =>\n value\n .split(',')\n .map((tool) => tool.trim())\n .filter(Boolean)\n\n/**\n * `--ask send-mail --skip get-thing` → those choices, replacing the earlier ones; `--ask default`\n * → none, so every tool follows the default rule. undefined when neither flag is given.\n */\nfunction askFlags(args: {\n ask?: string\n skip?: string\n}): Record<string, boolean> | null | undefined {\n if (args.ask === undefined && args.skip === undefined) return undefined\n if (args.ask === 'default') {\n if (args.skip !== undefined) throw new Error('--ask default cannot go with --skip')\n return null\n }\n const choices: Record<string, boolean> = {}\n for (const tool of toolList(args.ask ?? '')) choices[tool] = true\n for (const tool of toolList(args.skip ?? '')) {\n if (choices[tool]) throw new Error(`${tool} is in both --ask and --skip`)\n choices[tool] = false\n }\n return choices\n}\n\nconst ASK_ARGS = {\n ask: {\n type: 'string',\n description:\n 'Tools that ask you before each call, comma-separated (by default: those whose names send, post, change or delete); \"default\" clears your choices',\n },\n skip: {\n type: 'string',\n description: 'Tools that never ask, comma-separated',\n },\n} as const\n\n/** Which tools ask first, as a line: the default rule and the operator's choices. */\nfunction asksLine(server: McpServer): string {\n const choices = Object.entries(server.ask ?? {})\n if (choices.length === 0) return 'by default'\n return `by default, except ${choices\n .map(([tool, asks]) => `${tool} (${asks ? 'asks' : 'never asks'})`)\n .join(', ')}`\n}\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Register an MCP server, or one of the common connections' },\n args: {\n name: { type: 'positional', required: true, description: 'Unique name ([a-zA-Z0-9_])' },\n preset: {\n type: 'string',\n description: `A common connection: ${MCP_PRESETS.map((preset) => preset.id).join(', ')} (see mcp presets)`,\n },\n option: { type: 'string', description: \"A preset's option, e.g. org or post (repeatable)\" },\n transport: { type: 'string', description: 'stdio | http (default stdio)' },\n command: { type: 'string', description: 'stdio: executable to run (e.g. npx)' },\n args: { type: 'string', description: 'stdio: space-separated args (quote the whole string)' },\n url: { type: 'string', description: 'http: Streamable HTTP endpoint URL' },\n token: { type: 'string', description: 'http: bearer token (stored encrypted)' },\n env: {\n type: 'string',\n description: 'stdio: a variable of its own as NAME=value, stored encrypted (repeatable)',\n },\n ...ASK_ARGS,\n disabled: { type: 'boolean', description: 'Create disabled' },\n },\n async run({ args, rawArgs }) {\n const env = envFlags(rawArgs, 'env')\n let body: McpServerInput\n if (args.preset) {\n const preset = MCP_PRESETS.find((entry) => entry.id === args.preset)\n if (!preset)\n throw new Error(`no common connection \"${args.preset}\"; see bazilion mcp presets`)\n // A preset says how the server runs: these would be ignored.\n const given = (['transport', 'command', 'args', 'url', 'token'] as const).filter(\n (flag) => args[flag] !== undefined,\n )\n if (given.length > 0)\n throw new Error(\n `--preset sets how it runs: leave out ${given.map((f) => `--${f}`).join(', ')}`,\n )\n const chosen = collectFlagValues(rawArgs, 'option')\n const unknown = chosen.filter((id) => !preset.options.some((option) => option.id === id))\n if (unknown.length > 0) {\n const known = preset.options.map((option) => option.id).join(', ')\n throw new Error(\n `${preset.title} has no option ${unknown.join(', ')}${known ? `; its options: ${known}` : ''}`,\n )\n }\n const values = Object.fromEntries(\n Object.entries(env).filter((pair): pair is [string, string] => pair[1] !== null),\n )\n const missing = preset.fields.filter((field) => !values[field.name])\n if (missing.length > 0) {\n throw new Error(\n `${preset.title} needs ${missing.map((field) => `--env ${field.name}=…`).join(' ')}`,\n )\n }\n const made = presetServer(preset, {\n name: args.name,\n chosen,\n values,\n })\n body = {\n name: made.name,\n transport: 'stdio',\n command: made.command,\n args: made.args,\n env: { ...made.env, ...env },\n enabled: !args.disabled,\n }\n } else {\n body = {\n name: args.name,\n transport: (args.transport ?? 'stdio') as McpTransport,\n command: args.command ?? null,\n args: args.args ? args.args.split(' ').filter(Boolean) : [],\n url: args.url ?? null,\n authToken: args.token ?? undefined,\n ...(Object.keys(env).length > 0 ? { env } : {}),\n enabled: !args.disabled,\n }\n }\n const ask = askFlags(args)\n if (ask !== undefined) body.ask = ask\n const { server } = await createClient().post<{ server: McpServer }>('/api/mcp-servers', body)\n console.log(`${server.id}\\t${server.name}\\t${server.transport}`)\n },\n})\n\nconst presetsCmd = defineCommand({\n meta: { name: 'presets', description: 'List the common connections mcp add --preset knows' },\n run() {\n for (const preset of MCP_PRESETS) {\n console.log(`${preset.id}\\t${preset.title}: ${preset.does}`)\n console.log(` runs: ${[preset.command, ...preset.args].join(' ')}`)\n for (const field of preset.fields) console.log(` --env ${field.name}=… ${field.hint}`)\n for (const option of preset.options) console.log(` --option ${option.id} ${option.hint}`)\n if (preset.needs) console.log(` needs: ${preset.needs}`)\n console.log(` sign-in: ${preset.signIn}`)\n if (preset.caveat) console.log(` note: ${preset.caveat}`)\n console.log(` guide: ${preset.guide}`)\n }\n },\n})\n\nconst setCmd = defineCommand({\n meta: { name: 'set', description: \"Change a server's own variables or which tools ask first\" },\n args: {\n id: serverArg,\n env: { type: 'string', description: 'Set a variable as NAME=value (repeatable)' },\n 'unset-env': { type: 'string', description: 'Remove a variable by name (repeatable)' },\n ...ASK_ARGS,\n },\n async run({ args, rawArgs }) {\n const env = { ...envFlags(rawArgs, 'env'), ...envFlags(rawArgs, 'unset-env', true) }\n const body: Partial<McpServerInput> = {}\n if (Object.keys(env).length > 0) body.env = env\n const ask = askFlags(args)\n if (ask !== undefined) body.ask = ask\n if (Object.keys(body).length === 0)\n throw new Error('nothing to change: give --env, --unset-env, --ask or --skip')\n const { server } = await createClient().patch<{ server: McpServer }>(\n apiPath('mcp-servers', args.id),\n body,\n )\n console.log(\n `${server.name}: variables ${server.envNames?.join(', ') || '(none)'}; asks first: ${asksLine(server)}`,\n )\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List MCP servers' },\n async run() {\n const { servers } = await createClient().get<{ servers: McpServer[] }>('/api/mcp-servers')\n printRows(servers.map(serverRow), '(no MCP servers)')\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show one MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n const { server } = await createClient().get<{ server: McpServer }>(\n apiPath('mcp-servers', args.id),\n )\n printJson(server)\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Delete an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().del(apiPath('mcp-servers', args.id))\n console.log(`removed MCP server ${args.id}`)\n },\n})\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Enable an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().patch(apiPath('mcp-servers', args.id), { enabled: true })\n console.log(`enabled MCP server ${args.id}`)\n },\n})\n\nconst disableCmd = defineCommand({\n meta: { name: 'disable', description: 'Disable an MCP server' },\n args: { id: serverArg },\n async run({ args }) {\n await createClient().patch(apiPath('mcp-servers', args.id), { enabled: false })\n console.log(`disabled MCP server ${args.id}`)\n },\n})\n\nconst testCmd = defineCommand({\n meta: { name: 'test', description: 'Connect to a server and list its tools' },\n args: { id: serverArg },\n async run({ args }) {\n const res = await createClient().post<{ ok: boolean; tools?: McpToolInfo[]; error?: string }>(\n apiPath('mcp-servers', args.id, 'test'),\n )\n if (!res.ok) throw new Error(`connection failed: ${res.error}`)\n const tools = res.tools ?? []\n console.log(`connected — ${tools.length} tool(s):`)\n for (const t of tools)\n console.log(` ${t.asks ? '(asks first) ' : ''}${t.name}\\t${t.description}`)\n },\n})\n\nexport const mcpCommand = defineCommand({\n meta: { name: 'mcp', description: 'Manage MCP servers' },\n subCommands: {\n add: addCmd,\n list: listCmd,\n show: showCmd,\n rm: rmCmd,\n enable: enableCmd,\n disable: disableCmd,\n test: testCmd,\n set: setCmd,\n presets: presetsCmd,\n },\n})\n","import type { MemoryEntry, MemoryHit } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, teamArg } from '../command-helpers.ts'\n\nconst keyArg = positional('Memory key (path under memory/, ending in .md)')\n\n/** A key's slashes stay path separators. */\nconst entryPath = (team: string, key: string) => apiPath('teams', team, 'memory', ...key.split('/'))\n\nconst writeCmd = defineCommand({\n meta: { name: 'write', description: \"Write an entry into a team's shared memory\" },\n args: { team: teamArg, key: keyArg, content: positional('Content to write') },\n async run({ args }) {\n const entry = await createClient().put<MemoryEntry>(entryPath(args.team, args.key), {\n content: args.content,\n })\n console.log(`wrote ${entry.key} (${entry.content.length} bytes)`)\n },\n})\n\nconst readCmd = defineCommand({\n meta: { name: 'read', description: \"Read an entry from a team's shared memory\" },\n args: { team: teamArg, key: keyArg },\n async run({ args }) {\n const entry = await createClient().get<MemoryEntry>(entryPath(args.team, args.key))\n console.log(entry.content)\n },\n})\n\nconst searchCmd = defineCommand({\n meta: { name: 'search', description: \"Search a team's shared memory\" },\n args: {\n team: teamArg,\n query: positional('Search terms'),\n limit: { type: 'string', description: 'Max results (default 10)' },\n },\n async run({ args }) {\n const limit = args.limit ? Number.parseInt(args.limit, 10) : 10\n const params = new URLSearchParams({ q: args.query, limit: String(limit) })\n const hits = await createClient().get<MemoryHit[]>(\n `${apiPath('teams', args.team, 'memory', 'search')}?${params}`,\n )\n if (hits.length === 0) {\n console.log('(no matches)')\n return\n }\n for (const h of hits) {\n console.log(`${h.key}\\t${h.snippet.replaceAll('\\n', ' ')}`)\n }\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: \"List all entries in a team's shared memory\" },\n args: { team: teamArg },\n async run({ args }) {\n const all = await createClient().get<MemoryEntry[]>(apiPath('teams', args.team, 'memory'))\n if (all.length === 0) {\n console.log('(no memory entries)')\n return\n }\n for (const e of all) {\n console.log(`${e.key}\\t${e.content.length}b`)\n }\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: \"Remove an entry from a team's shared memory\" },\n args: { team: teamArg, key: keyArg },\n async run({ args }) {\n await createClient().del(entryPath(args.team, args.key))\n console.log(`removed ${args.key}`)\n },\n})\n\nexport const memoryCommand = defineCommand({\n meta: {\n name: 'memory',\n description: \"Manage a team's shared memory (BM25-indexed markdown notes)\",\n },\n subCommands: {\n write: writeCmd,\n read: readCmd,\n search: searchCmd,\n list: listCmd,\n rm: rmCmd,\n },\n})\n","import type { AttentionRecordedKind, NotificationSettingsResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson } from '../command-helpers.ts'\n\nfunction print(settings: NotificationSettingsResponse, json: boolean | undefined): void {\n if (json) {\n printJson(settings)\n return\n }\n const quiet = settings.quietHours\n ? `${settings.quietHours.start}–${settings.quietHours.end} (${settings.timezone})`\n : 'none'\n console.log(`notifications: ${settings.enabled ? 'on' : 'off'}`)\n console.log(`kinds: ${settings.kinds.join(', ')}`)\n console.log(`quiet hours: ${quiet}`)\n if (!settings.telegramReady)\n console.log('telegram: not connected — notices go out once the bot runs')\n}\n\nconst settings = defineCommand({\n meta: { name: 'settings', description: 'Show the Telegram attention notification settings' },\n args: { json: jsonFlag },\n async run({ args }) {\n print(await createClient().notifications.settings(), args.json)\n },\n})\n\nconst configure = defineCommand({\n meta: {\n name: 'configure',\n description: 'Change the settings; options left out keep their current value',\n },\n args: {\n enable: { type: 'boolean', description: 'Send new Attention items to Telegram' },\n disable: { type: 'boolean', description: 'Stop sending them' },\n kinds: { type: 'string', description: 'Comma-separated Attention kinds' },\n timezone: { type: 'string', description: 'IANA timezone, for example Europe/Warsaw' },\n 'quiet-start': { type: 'string', description: 'Start of quiet hours, HH:mm' },\n 'quiet-end': { type: 'string', description: 'End of quiet hours, HH:mm' },\n 'clear-quiet-hours': { type: 'boolean', description: 'Notify at any hour' },\n json: jsonFlag,\n },\n async run({ args }) {\n if (args.enable && args.disable) throw new Error('Choose --enable or --disable')\n if (Boolean(args['quiet-start']) !== Boolean(args['quiet-end']))\n throw new Error('Provide both --quiet-start and --quiet-end')\n if (args['clear-quiet-hours'] && args['quiet-start'])\n throw new Error('Choose a quiet window or --clear-quiet-hours')\n const api = createClient().notifications\n const current = await api.settings()\n const updated = await api.configure({\n enabled: args.enable ? true : args.disable ? false : current.enabled,\n kinds: args.kinds\n ? (args.kinds.split(',').map((kind) => kind.trim()) as AttentionRecordedKind[])\n : current.kinds,\n timezone: args.timezone ?? current.timezone,\n quietHours: args['clear-quiet-hours']\n ? null\n : args['quiet-start'] && args['quiet-end']\n ? { start: args['quiet-start'], end: args['quiet-end'] }\n : current.quietHours,\n })\n print(updated, args.json)\n },\n})\n\nexport const notificationCommand = defineCommand({\n meta: {\n name: 'notification',\n description: 'Send new Attention items to the Telegram service topic',\n },\n subCommands: { settings, configure },\n})\n","import { spawn } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport type {\n CreateProfileRequest,\n FileContentResponse,\n LoadedProfile,\n Profile,\n ProfileFileName,\n PutFileRequest,\n SkillsMode,\n UpdateProfileRequest,\n} from '@bazilion/api-types'\nimport { PROFILE_FILES } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst profileArg = positional('Profile id')\n\nfunction splitCsv(v: string | undefined): string[] | undefined {\n if (!v) return undefined\n const out = v\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n return out.length > 0 ? out : undefined\n}\n\nfunction parseSkillsMode(v: string | undefined): SkillsMode | undefined {\n if (v === undefined) return undefined\n if (v === 'all' || v === 'selected') return v\n throw new Error(`--skills-mode must be 'all' or 'selected', got '${v}'`)\n}\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Create a new profile' },\n args: {\n id: positional('Profile slug'),\n name: { type: 'string', description: 'Display name (defaults to slug)' },\n model: {\n type: 'string',\n required: true,\n description: 'Default model, e.g. anthropic:claude-opus-4-8',\n },\n 'skills-mode': {\n type: 'string',\n description: \"'all' (attach every discovered skill) or 'selected' (default)\",\n },\n skills: {\n type: 'string',\n description: 'Default skills, comma-separated (skills-mode=selected)',\n },\n 'soul-file': {\n type: 'string',\n description: 'Path to custom SOUL.md content (defaults to the built-in template)',\n },\n 'identity-file': {\n type: 'string',\n description: 'Path to custom IDENTITY.md content (defaults to the built-in template)',\n },\n 'bootstrap-file': {\n type: 'string',\n description: 'Path to custom BOOTSTRAP.md content (defaults to the built-in template)',\n },\n 'skip-bootstrap': {\n type: 'boolean',\n description: 'Skip the bootstrap file entirely (no first-run intro)',\n },\n 'agents-file': {\n type: 'string',\n description: 'Path to custom AGENTS.md content (defaults to the built-in template)',\n },\n 'skip-agents': { type: 'boolean', description: 'Create the profile without an AGENTS.md' },\n 'tools-file': {\n type: 'string',\n description: 'Path to custom TOOLS.md content (defaults to the built-in template)',\n },\n 'skip-tools': { type: 'boolean', description: 'Create the profile without a TOOLS.md' },\n },\n async run({ args }) {\n const skillsMode = parseSkillsMode(args['skills-mode'])\n const readTemplate = (path: string | undefined): string | undefined =>\n path ? readFileSync(path, 'utf8') : undefined\n const body: CreateProfileRequest = {\n id: args.id,\n name: args.name,\n defaultModel: args.model,\n skillsMode,\n defaultSkills: splitCsv(args.skills),\n soul: readTemplate(args['soul-file']),\n identity: readTemplate(args['identity-file']),\n bootstrap: args['skip-bootstrap'] ? null : readTemplate(args['bootstrap-file']),\n agents: args['skip-agents'] ? null : readTemplate(args['agents-file']),\n tools: args['skip-tools'] ? null : readTemplate(args['tools-file']),\n }\n const profile = await createClient().post<Profile>('/api/profiles', body)\n console.log(`created profile ${profile.id} at ${profile.dir}`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List profiles' },\n async run() {\n const list = await createClient().get<Profile[]>('/api/profiles')\n printRows(\n list.map((p) => [p.id, p.defaultModel, p.name]),\n '(no profiles)',\n )\n },\n})\n\nconst showCmd = defineCommand({\n meta: { name: 'show', description: 'Show profile details' },\n args: { id: profileArg },\n async run({ args }) {\n const loaded = await createClient().get<LoadedProfile>(apiPath('profiles', args.id))\n console.log(`# ${loaded.profile.id}`)\n console.log(`name: ${loaded.profile.name}`)\n console.log(`dir: ${loaded.profile.dir}`)\n console.log(`default model: ${loaded.profile.defaultModel}`)\n console.log(`skills mode: ${loaded.profile.skillsMode}`)\n console.log(\n `default skills: ${\n loaded.defaultSkills.length === 0 ? '(none)' : loaded.defaultSkills.join(', ')\n }`,\n )\n console.log(`bootstrap: ${loaded.files.bootstrap !== null ? 'yes' : 'no'}`)\n console.log(`agents: ${loaded.files.agents !== null ? 'yes' : 'no'}`)\n console.log(`tools: ${loaded.files.tools !== null ? 'yes' : 'no'}`)\n if (loaded.identity) {\n const fields = Object.entries(loaded.identity)\n .filter(([, v]) => typeof v === 'string' && v.length > 0)\n .map(([k, v]) => `${k}=${v}`)\n .join(', ')\n if (fields) console.log(`identity: ${fields}`)\n }\n },\n})\n\nconst editCmd = defineCommand({\n meta: { name: 'edit', description: 'Open a profile file in $EDITOR' },\n args: {\n id: profileArg,\n file: {\n type: 'string',\n default: 'SOUL.md',\n description: `File: ${PROFILE_FILES.join(', ')} (default SOUL.md)`,\n },\n },\n async run({ args }) {\n if (!(PROFILE_FILES as readonly string[]).includes(args.file)) {\n throw new Error(`unsupported file: ${args.file}. Allowed: ${PROFILE_FILES.join(', ')}`)\n }\n const file = args.file as ProfileFileName\n const client = createClient()\n const path = apiPath('profiles', args.id, 'files', file)\n const { content } = await client.get<FileContentResponse>(path)\n const tmpPath = join(tmpdir(), `bazilion-${args.id}-${file}-${randomBytes(4).toString('hex')}`)\n writeFileSync(tmpPath, content)\n try {\n const editor = process.env.EDITOR ?? process.env.VISUAL ?? 'vi'\n const code: number = await new Promise((resolve, reject) => {\n const child = spawn(editor, [tmpPath], { stdio: 'inherit' })\n child.on('error', reject)\n child.on('close', (c) => resolve(c ?? 0))\n })\n if (code !== 0) throw new Error(`editor exited with code ${code}`)\n const updated = readFileSync(tmpPath, 'utf8')\n if (updated === content) {\n console.log('(no changes)')\n return\n }\n const body: PutFileRequest = { content: updated }\n await client.put(path, body)\n console.log(`saved ${file}`)\n } finally {\n rmSync(tmpPath, { force: true })\n }\n },\n})\n\nconst updateCmd = defineCommand({\n meta: {\n name: 'update',\n description: 'Update profile settings (name, model, skills-mode, skills)',\n },\n args: {\n id: profileArg,\n name: { type: 'string', description: 'New display name' },\n model: { type: 'string', description: 'New default model' },\n 'skills-mode': {\n type: 'string',\n description: \"Switch to 'all' or 'selected'\",\n },\n skills: { type: 'string', description: 'Replacement default skills, comma-separated' },\n },\n async run({ args }) {\n const body: UpdateProfileRequest = {}\n if (args.name !== undefined) body.name = args.name\n if (args.model !== undefined) body.defaultModel = args.model\n const mode = parseSkillsMode(args['skills-mode'])\n if (mode !== undefined) body.skillsMode = mode\n if (args.skills !== undefined) body.defaultSkills = splitCsv(args.skills) ?? []\n if (Object.keys(body).length === 0) {\n throw new Error(\n 'nothing to update — pass at least one of --name/--model/--skills-mode/--skills',\n )\n }\n const profile = await createClient().patch<Profile>(apiPath('profiles', args.id), body)\n console.log(`updated profile ${profile.id}`)\n },\n})\n\nconst deleteCmd = defineCommand({\n meta: { name: 'delete', description: 'Permanently delete a profile and its files' },\n args: { id: profileArg },\n async run({ args }) {\n await createClient().del(apiPath('profiles', args.id))\n console.log(`deleted profile ${args.id}`)\n },\n})\n\nexport const profileCommand = defineCommand({\n meta: { name: 'profile', description: 'Manage profiles' },\n subCommands: {\n create: createCmd,\n list: listCmd,\n show: showCmd,\n edit: editCmd,\n update: updateCmd,\n delete: deleteCmd,\n },\n})\n","import type {\n ConnectProviderRequest,\n ConnectProviderResponse,\n ProviderCatalogResponse,\n ProviderCheck,\n ProviderConfigEntry,\n ProviderConfigResponse,\n ProviderFailure,\n ProviderTestRequest,\n ProviderTestResponse,\n SetProviderEnabledResponse,\n SetProviderModelsRequest,\n SetProviderModelsResponse,\n TestProviderResponse,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { type BazilionClient, createClient } from '../client.ts'\nimport { apiPath, askSecret, confirm, positional, printRows } from '../command-helpers.ts'\nimport { collectFlagValues } from '../repeatable-args.ts'\n\nconst providerArg = positional('Provider id (e.g. anthropic)')\n\nconst STATE: Record<ProviderConfigEntry['state'], string> = {\n working: 'working',\n failing: 'failing',\n untested: 'not tested',\n incomplete: 'needs credentials',\n off: 'off',\n}\n\nasync function loadProvider(client: BazilionClient, id: string): Promise<ProviderConfigEntry> {\n const { providers } = await client.get<ProviderConfigResponse>('/api/config/providers')\n const provider = providers.find((entry) => entry.id === id)\n if (!provider) throw new Error(`unknown provider: ${id} (see: bazilion provider list --all)`)\n return provider\n}\n\nfunction checkLine(check: ProviderCheck): string {\n const when = new Date(check.at).toISOString().replace(/\\.\\d+Z$/, 'Z')\n return check.ok\n ? `${check.model} answered in ${((check.ms ?? 0) / 1000).toFixed(1)} s (${when})`\n : `${check.failure?.title ?? 'failed'} (${when})`\n}\n\nfunction printFailure(failure: ProviderFailure): void {\n console.error(failure.title)\n console.error(failure.hint)\n if (failure.detail) console.error(`details: ${failure.detail}`)\n}\n\nconst listCmd = defineCommand({\n meta: {\n name: 'list',\n description: 'List the providers in use with their state; --all lists every provider',\n },\n args: {\n all: { type: 'boolean', description: 'Also list providers that are not set up' },\n enabled: { type: 'boolean', description: 'Show only providers that are switched on' },\n },\n async run({ args }) {\n const { providers } = await createClient().get<ProviderConfigResponse>('/api/config/providers')\n printRows(\n providers\n .filter((p) => (args.enabled ? p.enabled : args.all || p.listed))\n .map((p) => [\n p.id,\n p.listed ? STATE[p.state] : 'not set up',\n p.models.length === 1 ? '1 model' : `${p.models.length} models`,\n p.check ? checkLine(p.check) : '',\n ]),\n args.all\n ? '(no providers to show)'\n : '(no provider is set up: bazilion provider connect <id>, or list them all with --all)',\n )\n },\n})\n\nconst connectCmd = defineCommand({\n meta: {\n name: 'connect',\n description:\n 'Connect a provider in one step: save its key or address, choose models, test, switch on',\n },\n args: {\n name: providerArg,\n key: {\n type: 'string',\n description: 'API key or access token (asked for, without echo, when left out)',\n },\n url: { type: 'string', description: 'Address of a local model server' },\n set: {\n type: 'string',\n description: 'Another setting of the provider as NAME=value (repeatable)',\n },\n models: {\n type: 'string',\n description: 'Comma-separated chat models (default: the suggested ones)',\n },\n test: {\n type: 'boolean',\n default: true,\n description: 'Ask a model for a short reply before saving anything (--no-test skips it)',\n },\n },\n async run({ args, rawArgs }) {\n const client = createClient()\n const provider = await loadProvider(client, args.name)\n const fields: Record<string, string> = {}\n for (const pair of collectFlagValues(rawArgs, 'set')) {\n const at = pair.indexOf('=')\n if (at <= 0) throw new Error(`--set takes NAME=value, got \"${pair}\"`)\n fields[pair.slice(0, at)] = pair.slice(at + 1)\n }\n const main = provider.fields.filter((field) => !field.advanced)\n const secret = main.find((field) => field.kind === 'secret')\n const address = main.find((field) => field.kind === 'config')\n if (args.url) {\n if (provider.connect !== 'local' || !address) {\n throw new Error(`--url is for local model servers; ${provider.id} takes --key or --set`)\n }\n fields[address.envVar] = args.url\n }\n if (args.key) {\n const target = secret ?? provider.fields.find((field) => field.kind === 'secret')\n if (!target) throw new Error(`${provider.id} takes no key`)\n fields[target.envVar] = args.key\n } else if (secret && !provider.configured && !(secret.envVar in fields)) {\n const typed = await askSecret(`${provider.displayName} ${secret.label}: `)\n if (!typed) throw new Error('no key given')\n fields[secret.envVar] = typed\n }\n\n const models = args.models\n ?.split(',')\n .map((model) => model.trim())\n .filter(Boolean)\n if (!models && provider.models.length === 0 && provider.suggested.length === 0) {\n if (provider.connect !== 'local') {\n throw new Error(\n `choose chat models with --models (see: bazilion provider models ${provider.id})`,\n )\n }\n }\n // A local server suggests what it has loaded: ask it, with the address being connected.\n let chosen = models\n if (!chosen && provider.connect === 'local' && provider.models.length === 0) {\n const catalog = await client.post<ProviderCatalogResponse>(\n apiPath('config', 'providers', provider.id, 'catalog'),\n { fields },\n )\n chosen = catalog.models.filter((model) => model.suggested).map((model) => model.id)\n }\n\n const body: ConnectProviderRequest = {\n ...(Object.keys(fields).length > 0 ? { fields } : {}),\n ...(chosen ? { models: chosen } : {}),\n ...(args.test ? {} : { test: false }),\n }\n const result = await client.post<ConnectProviderResponse>(\n apiPath('config', 'providers', provider.id, 'connect'),\n body,\n )\n if (!result.connected) {\n printFailure(result.failure)\n console.error('Nothing was saved.')\n process.exitCode = 1\n return\n }\n console.log(`${result.provider.id}: connected`)\n if (result.check) console.log(` ${checkLine(result.check)}`)\n else console.log(' not tested')\n console.log(` models: ${result.provider.models.join(', ') || '(none)'}`)\n for (const dropped of result.dropped) console.log(` left out: ${dropped.model}`)\n for (const t of result.movedTemplates) console.log(` template ${t.id} now uses ${t.model}`)\n },\n})\n\nconst disconnectCmd = defineCommand({\n meta: {\n name: 'disconnect',\n description: 'Forget a provider: its stored key or sign-in, its chat models and its test',\n },\n args: {\n name: providerArg,\n yes: { type: 'boolean', description: 'Do not ask for confirmation' },\n },\n async run({ args }) {\n const client = createClient()\n const provider = await loadProvider(client, args.name)\n if (\n !args.yes &&\n !(await confirm(`Disconnect ${provider.displayName} and remove its stored credentials?`))\n ) {\n console.log('cancelled')\n return\n }\n const result = await client.del<SetProviderModelsResponse>(\n apiPath('config', 'providers', provider.id),\n )\n console.log(`${provider.id}: disconnected`)\n for (const t of result.movedTemplates) console.log(`template ${t.id} now uses ${t.model}`)\n },\n})\n\nconst modelsCmd = defineCommand({\n meta: {\n name: 'models',\n description: 'Show a provider’s chat models: the ones Agents may use, and what it offers',\n },\n args: { name: providerArg },\n async run({ args }) {\n const client = createClient()\n const p = await loadProvider(client, args.name)\n const catalog = await client.get<ProviderCatalogResponse>(\n apiPath('config', 'providers', p.id, 'catalog'),\n )\n console.log(`# ${p.id} (${p.listed ? STATE[p.state] : 'not set up'})`)\n if (p.hint) console.log(` ${p.hint}`)\n for (const field of p.fields) console.log(` ${field.envVar}: ${field.set ? 'set' : 'unset'}`)\n if (!p.enabled) console.log(` (connect with \\`bazilion provider connect ${p.id}\\`)`)\n\n console.log('\\n## in use')\n if (p.models.length === 0) console.log(' (none: `provider connect` or `provider models-set`)')\n else for (const m of p.models) console.log(` ${m}`)\n\n console.log('\\n## offered')\n if (catalog.listError) console.log(` (the provider's own list failed: ${catalog.listError})`)\n printRows(\n catalog.models.map((model) => [\n ` ${model.id}`,\n model.name ?? '',\n model.contextWindow ? `${Math.round(model.contextWindow / 1000)}K` : '',\n model.price ? `$${model.price.input} in, $${model.price.output} out per 1M` : '',\n model.suggested ? 'suggested' : '',\n ]),\n ' (nothing listed)',\n )\n },\n})\n\nconst modelsSetCmd = defineCommand({\n meta: {\n name: 'models-set',\n description: 'Replace the chat models Agents may use from a provider (comma-separated)',\n },\n args: {\n name: providerArg,\n models: positional('Comma-separated model list (empty string clears the list)'),\n },\n async run({ args }) {\n const models = args.models\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean)\n const body: SetProviderModelsRequest = { models }\n const saved = await createClient().put<SetProviderModelsResponse>(\n apiPath('config', 'providers', args.name, 'models'),\n body,\n )\n console.log(`saved ${saved.models.length} model(s) for ${args.name}`)\n for (const m of saved.models) console.log(` ${m}`)\n for (const t of saved.movedTemplates) console.log(`template ${t.id} now uses ${t.model}`)\n },\n})\n\nasync function setEnabled(name: string, enabled: boolean): Promise<void> {\n const res = await createClient().put<SetProviderEnabledResponse>(\n apiPath('config', 'providers', name, 'enabled'),\n { enabled },\n )\n console.log(`${res.name}: ${res.enabled ? 'enabled' : 'disabled'}`)\n}\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Switch a connected provider back on' },\n args: { name: providerArg },\n run: ({ args }) => setEnabled(args.name, true),\n})\n\nconst disableCmd = defineCommand({\n meta: {\n name: 'disable',\n description: 'Pause a provider without removing its key; Agents on its models are refused',\n },\n args: { name: providerArg },\n run: ({ args }) => setEnabled(args.name, false),\n})\n\nconst testCmd = defineCommand({\n meta: {\n name: 'test',\n description: 'Test a provider (its cheapest model in use) or send one chat to a provider:model',\n },\n args: {\n model: positional('Provider id, or a model string such as anthropic:claude-haiku-5-5'),\n message: { type: 'string', description: 'Message text for a model string' },\n },\n async run({ args }) {\n const client = createClient()\n if (!args.model.includes(':')) {\n const { check } = await client.post<TestProviderResponse>(\n apiPath('config', 'providers', args.model, 'test'),\n )\n if (check.ok) {\n console.log(`${args.model}: ${checkLine(check)}`)\n return\n }\n if (check.failure) printFailure(check.failure)\n process.exitCode = 1\n return\n }\n const body: ProviderTestRequest = { model: args.model, message: args.message }\n console.log(`-> ${args.model}: ${args.message ?? 'say hi briefly'}`)\n const res = await client.post<ProviderTestResponse>('/api/providers/test', body)\n console.log(`<- ${res.content}`)\n if (res.usage) {\n console.log(`(${res.usage.promptTokens} in, ${res.usage.completionTokens} out)`)\n }\n },\n})\n\nexport const providerCommand = defineCommand({\n meta: { name: 'provider', description: 'Connect, test and manage LLM providers' },\n subCommands: {\n list: listCmd,\n connect: connectCmd,\n disconnect: disconnectCmd,\n test: testCmd,\n models: modelsCmd,\n 'models-set': modelsSetCmd,\n enable: enableCmd,\n disable: disableCmd,\n },\n})\n","import type { AgentQuestionAnswer } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, jsonFlag, positional, printJson } from '../command-helpers.ts'\nimport { questionLines } from '../question-prompt.ts'\n\nexport function questionAnswer(args: {\n choice?: string\n text?: string\n skip?: boolean\n}): AgentQuestionAnswer {\n const count =\n Number(args.choice !== undefined) + Number(args.text !== undefined) + Number(args.skip === true)\n if (count !== 1) throw new Error('Specify exactly one of --choice, --text, or --skip')\n if (args.skip) return { kind: 'skip' }\n if (args.text !== undefined) {\n if (!args.text.trim() || args.text.length > 4096)\n throw new Error('Answer text must be 1–4096 characters')\n return { kind: 'text', text: args.text }\n }\n if (!/^[1-4]$/.test(args.choice ?? '')) throw new Error('--choice must be a number from 1 to 4')\n return { kind: 'choice', index: Number(args.choice) - 1 }\n}\n\nexport const questionCommand = defineCommand({\n meta: { name: 'question', description: \"List and answer an Agent's waiting questions\" },\n subCommands: {\n list: defineCommand({\n meta: { name: 'list', description: 'Questions the Agent is waiting on' },\n args: { agent: agentArg, json: jsonFlag },\n async run({ args }) {\n const { questions } = await createClient().questions(args.agent).list()\n if (args.json) return printJson(questions)\n if (!questions.length) return console.log('(no waiting questions)')\n for (const item of questions) {\n console.log(`${item.id} · expires ${new Date(item.expiresAt).toLocaleTimeString()}`)\n for (const line of questionLines(item)) console.log(` ${line}`)\n }\n },\n }),\n answer: defineCommand({\n meta: { name: 'answer', description: 'Answer a waiting question' },\n args: {\n agent: agentArg,\n id: positional('Question id'),\n choice: { type: 'string', description: 'Choice number, starting at 1' },\n text: { type: 'string', description: 'Free-text answer' },\n skip: { type: 'boolean', description: 'Continue without an answer' },\n },\n async run({ args }) {\n await createClient().questions(args.agent).answer(args.id, questionAnswer(args))\n console.log(args.skip ? 'Skipped.' : 'Answered.')\n },\n }),\n },\n})\n","import { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, loadAttachments, positional, printJson } from '../command-helpers.ts'\n\nconst itemArg = positional('Follow-up id')\n\nconst list = defineCommand({\n meta: {\n name: 'list',\n description: 'Show waiting, running and failed follow-ups, and whether a turn is running',\n },\n args: { agent: agentArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).list())\n },\n})\n\nconst add = defineCommand({\n meta: { name: 'add', description: 'Queue a follow-up; it runs after the current turn' },\n args: {\n agent: agentArg,\n message: { type: 'string', description: 'Text of the follow-up' },\n image: { type: 'string', description: 'Attach an image (repeatable)' },\n file: { type: 'string', description: 'Attach a file (repeatable)' },\n },\n async run({ args, rawArgs }) {\n printJson(\n await createClient()\n .queue(args.agent)\n .enqueue({ message: args.message ?? '', attachments: loadAttachments(rawArgs) }),\n )\n },\n})\n\nconst edit = defineCommand({\n meta: { name: 'edit', description: 'Replace the text of a waiting follow-up' },\n args: {\n agent: agentArg,\n id: itemArg,\n message: { type: 'string', required: true, description: 'New text of the follow-up' },\n },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).edit(args.id, args.message))\n },\n})\n\nconst remove = defineCommand({\n meta: { name: 'remove', description: 'Remove a follow-up that is not running' },\n args: { agent: agentArg, id: itemArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).remove(args.id))\n },\n})\n\nfunction control(paused: boolean) {\n return defineCommand({\n meta: {\n name: paused ? 'pause' : 'resume',\n description: paused ? 'Start no further follow-ups' : 'Start waiting follow-ups again',\n },\n args: { agent: agentArg },\n async run({ args }) {\n printJson(await createClient().queue(args.agent).pause(paused))\n },\n })\n}\n\nexport const queueCommand = defineCommand({\n meta: { name: 'queue', description: 'Follow-ups: input that waits for the Agent’s current turn' },\n subCommands: { list, add, edit, remove, pause: control(true), resume: control(false) },\n})\n","import { closeSync, fsyncSync, openSync, unlinkSync, writeFileSync } from 'node:fs'\nimport type { AgentResult, ResultListResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson } from '../command-helpers.ts'\n\nconst idArg = positional('Result id')\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List saved results' },\n args: {\n team: { type: 'string', description: 'Only results of this Team' },\n agent: { type: 'string', description: 'Only results of this Agent' },\n conversation: { type: 'string', description: 'Only results delivered in this conversation' },\n limit: { type: 'string', default: '50', description: 'Page size' },\n offset: { type: 'string', default: '0', description: 'Results to skip' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({ limit: args.limit, offset: args.offset })\n if (args.team) query.set('teamId', args.team)\n if (args.agent) query.set('agentId', args.agent)\n if (args.conversation) query.set('sessionId', args.conversation)\n const body = await createClient().get<ResultListResponse>(`/api/results?${query}`)\n if (args.json) return printJson(body)\n if (!body.results.length) return console.log('(no saved results)')\n for (const line of columnize([\n ['id', 'filename', 'bytes', 'team', 'agent', 'created'],\n ...body.results.map((r) => [\n r.id,\n r.name,\n String(r.byteLength),\n r.teamId,\n r.agentId,\n new Date(r.createdAt).toISOString(),\n ]),\n ]))\n console.log(line)\n console.log(`${body.offset + 1}–${body.offset + body.results.length} of ${body.total}`)\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Show a saved result: who saved it, where and when' },\n args: { id: idArg },\n async run({ args }) {\n const { result } = await createClient().get<{ result: AgentResult }>(\n apiPath('results', args.id),\n )\n printJson(result)\n },\n})\n\nconst download = defineCommand({\n meta: { name: 'download', description: 'Download a saved result to an explicit new file' },\n args: {\n id: idArg,\n output: {\n type: 'string',\n required: true,\n description: 'Destination path; existing files are never overwritten',\n },\n },\n async run({ args }) {\n const bytes = await createClient().binary(apiPath('results', args.id, 'download'))\n saveNew(args.output, bytes)\n console.log(`Saved ${bytes.byteLength} bytes to ${args.output}`)\n },\n})\n\n/** Write bytes to a new file; an existing file is never overwritten. */\nfunction saveNew(path: string, bytes: Uint8Array): void {\n const fd = openSync(path, 'wx', 0o600)\n try {\n writeFileSync(fd, bytes)\n fsyncSync(fd)\n } catch (error) {\n closeSync(fd)\n unlinkSync(path)\n throw error\n }\n closeSync(fd)\n}\n\nconst archive = defineCommand({\n meta: {\n name: 'archive',\n description: 'Download every saved result of a Team, an Agent or a conversation as one zip',\n },\n args: {\n team: { type: 'string', description: 'Results of this Team' },\n agent: { type: 'string', description: 'Results of this Agent' },\n conversation: { type: 'string', description: 'Results delivered in this conversation' },\n output: {\n type: 'string',\n required: true,\n description: 'Destination .zip path; existing files are never overwritten',\n },\n },\n async run({ args }) {\n const query = new URLSearchParams()\n if (args.team) query.set('teamId', args.team)\n if (args.agent) query.set('agentId', args.agent)\n if (args.conversation) query.set('sessionId', args.conversation)\n if (query.size === 0) throw new Error('Pass --team, --agent or --conversation')\n const bytes = await createClient().binary(`/api/results/archive?${query}`)\n saveNew(args.output, bytes)\n console.log(`Saved ${bytes.byteLength} bytes to ${args.output}`)\n },\n})\n\nconst rm = defineCommand({\n meta: { name: 'rm', description: 'Delete a saved result' },\n args: { id: idArg, yes: { type: 'boolean', description: 'Required confirmation' } },\n async run({ args }) {\n if (!args.yes) throw new Error('Pass --yes to permanently delete the saved file')\n await createClient().del(apiPath('results', args.id))\n console.log('Saved file deleted.')\n },\n})\n\nexport const resultCommand = defineCommand({\n meta: { name: 'result', description: 'Find, download and delete saved Agent results' },\n subCommands: {\n list,\n show,\n download,\n archive,\n rm,\n },\n})\n","import type { Message, SendMessageRequest } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional } from '../command-helpers.ts'\n\nexport const sendCommand = defineCommand({\n meta: {\n name: 'send',\n description: 'Send a message from one agent to another',\n },\n args: {\n from: positional('Sender agent id or prefix'),\n to: positional('Recipient agent id or prefix'),\n message: positional('Message text'),\n 'reply-to': { type: 'string', description: 'Id of the message this one answers' },\n },\n async run({ args }) {\n const body: SendMessageRequest = {\n from: args.from,\n payload: { text: args.message },\n ...(args['reply-to'] ? { replyTo: args['reply-to'] } : {}),\n }\n const result = await createClient().post<Message>(apiPath('agents', args.to, 'messages'), body)\n console.log(`sent message ${result.id}`)\n },\n})\n","import type { ListSessionsResponse, WebSession } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\n\nfunction row(session: WebSession): string[] {\n return [\n session.id,\n session.current ? 'current' : '',\n session.tokenLabel,\n `last seen: ${new Date(session.lastSeenAt).toISOString()}`,\n `expires: ${new Date(session.expiresAt).toISOString()}`,\n ]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List browser sessions' },\n async run() {\n const { sessions } = await createClient().get<ListSessionsResponse>('/api/sessions')\n printRows(sessions.map(row), '(no active browser sessions)')\n },\n})\n\nconst revokeCmd = defineCommand({\n meta: { name: 'revoke', description: 'Revoke (delete) one browser session' },\n args: { id: positional('Session id') },\n async run({ args }) {\n await createClient().del(apiPath('sessions', args.id))\n console.log(`revoked browser session ${args.id}`)\n },\n})\n\nexport const sessionCommand = defineCommand({\n meta: { name: 'session', description: 'Manage browser sessions' },\n subCommands: { list: listCmd, revoke: revokeCmd },\n})\n","import { existsSync, readFileSync, statSync } from 'node:fs'\nimport { basename, resolve } from 'node:path'\nimport type {\n ImportSkillsRequest,\n ImportSkillsResponse,\n ResolvedSkillsResponse,\n SkillInfo,\n SkillScanFinding,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, findingLines, positional, printRows } from '../command-helpers.ts'\nimport { explainScanBlock } from '../errors.ts'\n\nfunction printFindings(title: string, findings: Record<string, SkillScanFinding[]>): void {\n const flagged = Object.entries(findings).filter(([, list]) => list.length > 0)\n if (flagged.length === 0) return\n console.log('')\n console.log(title)\n for (const [name, list] of flagged) {\n console.log(`${name}:`)\n for (const line of findingLines(list)) console.log(` ${line}`)\n }\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List installed skills (or those attached to an agent)' },\n args: {\n agent: { type: 'string', description: 'Filter to skills attached to this agent' },\n },\n async run({ args }) {\n const client = createClient()\n\n if (args.agent) {\n const set = await client.get<ResolvedSkillsResponse>(apiPath('agents', args.agent, 'skills'))\n if (set.resolved.length === 0 && set.missing.length === 0) {\n console.log('(no skills attached to this agent)')\n return\n }\n for (const line of columnize(set.resolved.map((s) => [s.name, s.description]))) {\n console.log(line)\n }\n for (const m of set.missing) console.log(`(missing: ${m.name} — ${m.reason})`)\n return\n }\n\n const skills = await client.get<SkillInfo[]>('/api/skills')\n printRows(\n skills.map((s) => [s.name, s.parseError ? `(parse error: ${s.parseError})` : s.description]),\n '(no skills installed; use \"bazilion skill import\" to add some)',\n )\n printFindings(\n 'scan findings:',\n Object.fromEntries(skills.map((s) => [s.name, s.scanFindings ?? []])),\n )\n },\n})\n\nconst importCmd = defineCommand({\n meta: {\n name: 'import',\n description: 'Import skills from openclaw, a directory, or a local .zip archive',\n },\n args: {\n from: {\n type: 'string',\n required: true,\n description:\n 'Source: \"openclaw\", a filesystem path on the server, or a local .zip file to upload',\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing skills and import despite scan findings',\n },\n },\n async run({ args }) {\n const client = createClient()\n\n // Auto-detect local .zip uploads: if `--from` points at an existing local\n // file ending in .zip, stream it to the server as multipart. Otherwise\n // send the source as JSON (the server reads openclaw or a server-side path).\n const absFrom = resolve(args.from)\n const isLocalZip =\n args.from.toLowerCase().endsWith('.zip') && existsSync(absFrom) && statSync(absFrom).isFile()\n\n let request: Promise<ImportSkillsResponse>\n if (isLocalZip) {\n const form = new FormData()\n form.set(\n 'file',\n new File([readFileSync(absFrom)], basename(absFrom), { type: 'application/zip' }),\n )\n if (args.force) form.set('force', 'true')\n request = client.postMultipart<ImportSkillsResponse>('/api/skills/import', form)\n } else {\n const body: ImportSkillsRequest = { source: args.from, force: args.force }\n request = client.post<ImportSkillsResponse>('/api/skills/import', body)\n }\n const result = await request.catch(explainScanBlock('--force'))\n\n if (result.imported.length === 0 && result.skipped.length === 0) {\n console.log('(nothing to import)')\n return\n }\n for (const name of result.imported) console.log(`imported ${name}`)\n for (const s of result.skipped) console.log(`skipped ${s.name}: ${s.reason}`)\n printFindings('confirmed scan findings:', result.findings ?? {})\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Remove an installed skill' },\n args: { name: positional('Skill name') },\n async run({ args }) {\n await createClient().del(apiPath('skills', args.name))\n console.log(`removed skill ${args.name}`)\n },\n})\n\nexport const skillCommand = defineCommand({\n meta: { name: 'skill', description: 'Manage the skill library' },\n subCommands: {\n list: listCmd,\n import: importCmd,\n rm: rmCmd,\n },\n})\n","import { readFileSync } from 'node:fs'\nimport { stdin } from 'node:process'\nimport type {\n RegisterTeamRequest,\n SetTeamTopicFormatRequest,\n SetTeamUserMdRequest,\n Team,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { apiPath, printRows, teamArg } from '../command-helpers.ts'\nimport { UsageError } from '../errors.ts'\nimport { teamEnvironmentCommand } from './team-environment.ts'\nimport { teamMessagesCommand } from './team-messages.ts'\nimport { teamPolicyCommand } from './team-policy.ts'\nimport { teamReviewCommand } from './team-review.ts'\nimport { teamTodayCommand } from './team-today.ts'\n\nconst addCmd = defineCommand({\n meta: {\n name: 'add',\n description:\n 'Register a team at ~/.bazilion/teams/<slug>/ (use --link to point at an existing tree)',\n },\n args: {\n id: teamArg,\n name: { type: 'string', description: 'Display name (defaults to slug)' },\n link: {\n type: 'string',\n description: 'Absolute path of an existing directory; the team slot becomes a symlink to it',\n },\n },\n async run({ args }) {\n const body: RegisterTeamRequest = {\n id: args.id,\n ...(args.name ? { name: args.name } : {}),\n ...(args.link ? { link: args.link } : {}),\n }\n const team = await createClient().post<Team>('/api/teams', body)\n console.log(`registered team ${team.id} at ${team.path}`)\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List teams' },\n async run() {\n const list = await createClient().get<Team[]>('/api/teams')\n printRows(\n list.map((team) => [team.id, team.path]),\n '(no teams)',\n )\n },\n})\n\nconst rmCmd = defineCommand({\n meta: {\n name: 'rm',\n description: 'Delete an empty team and its workspace directory (a --link target is kept)',\n },\n args: { id: teamArg },\n async run({ args }) {\n await createClient().del(apiPath('teams', args.id))\n console.log(`removed team ${args.id}`)\n },\n})\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = []\n for await (const chunk of stdin) chunks.push(chunk as Buffer)\n return Buffer.concat(chunks).toString('utf8')\n}\n\nconst userMdShowCmd = defineCommand({\n meta: { name: 'show', description: \"Print the team's USER.md\" },\n args: { id: teamArg },\n async run({ args }) {\n const team = await createClient().get<Team>(apiPath('teams', args.id))\n process.stdout.write(team.userMd)\n if (team.userMd && !team.userMd.endsWith('\\n')) process.stdout.write('\\n')\n },\n})\n\nconst userMdSetCmd = defineCommand({\n meta: {\n name: 'set',\n description: \"Replace the team's USER.md (from --file, --from-stdin, or inline text)\",\n },\n args: {\n id: teamArg,\n file: { type: 'string', description: 'Read content from a file path' },\n 'from-stdin': { type: 'boolean', description: 'Read content from stdin' },\n text: { type: 'string', description: 'Inline content' },\n },\n async run({ args }) {\n let content: string\n if (args['from-stdin']) content = await readStdin()\n else if (args.file) content = readFileSync(args.file, 'utf8')\n else if (args.text !== undefined) content = args.text\n else throw new UsageError('provide --file, --from-stdin, or --text')\n const body: SetTeamUserMdRequest = { userMd: content }\n await createClient().put(apiPath('teams', args.id, 'user-md'), body)\n console.log(`updated USER.md for team ${args.id} (${content.length} bytes)`)\n },\n})\n\nconst userMdClearCmd = defineCommand({\n meta: { name: 'clear', description: \"Clear the team's USER.md to empty\" },\n args: { id: teamArg },\n async run({ args }) {\n const body: SetTeamUserMdRequest = { userMd: '' }\n await createClient().put(apiPath('teams', args.id, 'user-md'), body)\n console.log(`cleared USER.md for team ${args.id}`)\n },\n})\n\nconst userMdCmd = defineCommand({\n meta: { name: 'user-md', description: \"View or edit a team's USER.md\" },\n subCommands: {\n show: userMdShowCmd,\n set: userMdSetCmd,\n clear: userMdClearCmd,\n },\n})\n\nconst topicFormatShowCmd = defineCommand({\n meta: { name: 'show', description: \"Print the team's Telegram topic-name template\" },\n args: { id: teamArg },\n async run({ args }) {\n const team = await createClient().get<Team>(apiPath('teams', args.id))\n console.log(team.telegramTopicNameFormat ?? '(default naming)')\n },\n})\n\nconst topicFormatSetCmd = defineCommand({\n meta: {\n name: 'set',\n description:\n 'Set the topic-name template. Tokens: {agent.name} {team.name} {team.slug} (must include {agent.name})',\n },\n args: {\n id: teamArg,\n format: {\n type: 'positional',\n required: true,\n description: 'e.g. \"{team.name} / {agent.name}\"',\n },\n },\n async run({ args }) {\n const body: SetTeamTopicFormatRequest = { format: args.format }\n const team = await createClient().put<Team>(apiPath('teams', args.id, 'topic-format'), body)\n console.log(`set topic-name template for team ${args.id}: ${team.telegramTopicNameFormat}`)\n },\n})\n\nconst topicFormatClearCmd = defineCommand({\n meta: { name: 'clear', description: 'Clear the template (revert to built-in naming)' },\n args: { id: teamArg },\n async run({ args }) {\n const body: SetTeamTopicFormatRequest = { format: null }\n await createClient().put(apiPath('teams', args.id, 'topic-format'), body)\n console.log(`cleared topic-name template for team ${args.id}`)\n },\n})\n\nconst topicFormatCmd = defineCommand({\n meta: {\n name: 'topic-format',\n description: \"View or edit a team's Telegram forum-topic name template\",\n },\n subCommands: {\n show: topicFormatShowCmd,\n set: topicFormatSetCmd,\n clear: topicFormatClearCmd,\n },\n})\n\nexport const teamCommand = defineCommand({\n meta: { name: 'team', description: 'Manage teams (collaboration contexts)' },\n subCommands: {\n environment: teamEnvironmentCommand,\n review: teamReviewCommand,\n messages: teamMessagesCommand,\n today: teamTodayCommand,\n add: addCmd,\n list: listCmd,\n rm: rmCmd,\n 'user-md': userMdCmd,\n 'topic-format': topicFormatCmd,\n policy: teamPolicyCommand,\n },\n})\n","import type { CodingEnvironmentStatus } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, teamArg } from '../command-helpers.ts'\n\nfunction print(status: CodingEnvironmentStatus): void {\n console.log(\n `sandbox: ${status.sandboxMode}${status.sandboxMode === 'off' ? ' (defaults unused)' : ''}`,\n )\n console.log(`image: ${status.image ?? `${status.defaultImage} (installation default)`}`)\n console.log(`cwd: ${status.cwd}`)\n}\n\nexport const teamEnvironmentCommand = defineCommand({\n meta: {\n name: 'environment',\n description: \"A Team's Docker sandbox defaults: local image and working directory\",\n },\n subCommands: {\n show: defineCommand({\n meta: { name: 'show', description: \"Show a Team's Docker sandbox defaults\" },\n args: { team: teamArg, json: jsonFlag },\n async run({ args }) {\n const status = await createClient().codingEnvironment.show(args.team)\n if (args.json) printJson(status)\n else print(status)\n },\n }),\n set: defineCommand({\n meta: { name: 'set', description: \"Set a Team's Docker sandbox defaults\" },\n args: {\n team: teamArg,\n image: {\n type: 'string',\n description: 'Local Docker image (empty for the installation image)',\n },\n cwd: {\n type: 'string',\n description: \"Working directory inside the Team ('.' for its root)\",\n },\n },\n async run({ args }) {\n if (args.image === undefined && args.cwd === undefined)\n throw new Error('Pass --image and/or --cwd')\n const client = createClient()\n const current = await client.codingEnvironment.show(args.team)\n print(\n await client.codingEnvironment.set(args.team, {\n image: args.image === undefined ? current.image : args.image || null,\n cwd: args.cwd ?? current.cwd,\n }),\n )\n },\n }),\n },\n})\n","import type { Agent, ListTeamMessagesResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport {\n apiPath,\n jsonFlag,\n printJson,\n printRows,\n teamArg,\n terminalSafe,\n} from '../command-helpers.ts'\n\n// `bazilion team messages`: what the Team's Agents sent each other, newest first. Reading here\n// marks nothing read; `bazilion inbox` is one Agent's mailbox.\n\nfunction decodeText(payload: string): string {\n try {\n const parsed = JSON.parse(payload) as { text?: unknown }\n if (typeof parsed.text === 'string') return parsed.text\n } catch {\n // Not JSON: shown as it is.\n }\n return payload\n}\n\nexport const teamMessagesCommand = defineCommand({\n meta: {\n name: 'messages',\n description: 'List the messages the Agents of a Team sent and received, newest first',\n },\n args: {\n id: teamArg,\n limit: { type: 'string', default: '50', description: 'Messages to show (at most 500)' },\n json: jsonFlag,\n },\n async run({ args }) {\n const client = createClient()\n const [thread, agents] = await Promise.all([\n client.get<ListTeamMessagesResponse>(\n `${apiPath('teams', args.id, 'messages')}?limit=${encodeURIComponent(args.limit)}`,\n ),\n client.get<Agent[]>('/api/agents?includeArchived=true'),\n ])\n if (args.json) return printJson(thread)\n const names = new Map(agents.map((agent) => [agent.id, agent.name]))\n const name = (id: string) => names.get(id) ?? id.slice(0, 8)\n printRows(\n thread.messages.map((message) => {\n const text = decodeText(message.payload).replace(/\\s+/g, ' ').trim()\n return [\n new Date(message.createdAt).toISOString(),\n `${name(message.fromAgentId)} -> ${name(message.toAgentId)}`,\n message.readAt ? 'read' : 'NEW',\n terminalSafe(text.length > 80 ? `${text.slice(0, 80)}…` : text),\n ]\n }),\n '(no messages between Agents yet)',\n )\n },\n})\n","import {\n OUTSIDE_TEAM,\n type TeamPolicy,\n type TeamPolicyMode,\n type UpdateTeamPolicyRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson, teamArg } from '../command-helpers.ts'\n\nfunction label(policy: TeamPolicy, endpoint: string): string {\n if (endpoint === OUTSIDE_TEAM) return 'outside'\n return policy.members.find((agent) => agent.id === endpoint)?.name ?? endpoint\n}\n\n/** `outside`, or a member's id, id prefix or name. */\nfunction resolveEndpoint(policy: TeamPolicy, value: string): string {\n if (value === OUTSIDE_TEAM) return OUTSIDE_TEAM\n const byId = policy.members.find((agent) => agent.id === value)\n if (byId) return byId.id\n for (const matches of [\n policy.members.filter((agent) => agent.name === value),\n policy.members.filter((agent) => agent.id.startsWith(value)),\n ]) {\n if (matches.length > 1) throw new Error(`${value} matches several members of ${policy.teamId}`)\n if (matches[0]) return matches[0].id\n }\n throw new Error(`${value} is not a member of Team ${policy.teamId} (or outside)`)\n}\n\nconst show = defineCommand({\n meta: { name: 'show', description: \"Show a Team's policy mode, members and allow edges\" },\n args: { team: teamArg, json: jsonFlag },\n async run({ args }) {\n const policy = await createClient().get<TeamPolicy>(apiPath('teams', args.team, 'policy'))\n if (args.json) return printJson(policy)\n console.log(`# Team ${policy.teamId} policy`)\n console.log(\n `mode: ${policy.mode}${policy.mode === 'open' ? ' (everyone can message everyone)' : ' (only along connections)'}`,\n )\n console.log(`members: ${policy.members.map((agent) => agent.name).join(', ') || '(none)'}`)\n if (!policy.edges.length) return console.log('edges: (none)')\n console.log('')\n for (const line of columnize([\n ['from', 'to'],\n ...policy.edges.map((edge) => [label(policy, edge.from), label(policy, edge.to)]),\n ]))\n console.log(line)\n },\n})\n\nconst mode = defineCommand({\n meta: {\n name: 'mode',\n description: 'Set a Team to open (members talk freely) or restricted (allow edges only)',\n },\n args: { team: teamArg, mode: positional('open | restricted') },\n async run({ args }) {\n if (args.mode !== 'open' && args.mode !== 'restricted') {\n throw new Error('mode must be open or restricted')\n }\n const body: UpdateTeamPolicyRequest = { mode: args.mode as TeamPolicyMode }\n await createClient().patch(apiPath('teams', args.team, 'policy'), body)\n console.log(`Team ${args.team} is now ${args.mode}`)\n },\n})\n\nfunction edgeCommand(name: 'allow' | 'deny') {\n return defineCommand({\n meta: {\n name,\n description:\n name === 'allow'\n ? 'Let one endpoint message another (a member name or id, or outside)'\n : 'Remove an allow edge',\n },\n args: {\n team: teamArg,\n from: positional('Sender: member or outside'),\n to: positional('Recipient: member or outside'),\n },\n async run({ args }) {\n const client = createClient()\n const policy = await client.get<TeamPolicy>(apiPath('teams', args.team, 'policy'))\n const edge = {\n from: resolveEndpoint(policy, args.from),\n to: resolveEndpoint(policy, args.to),\n }\n const shown = `${label(policy, edge.from)} -> ${label(policy, edge.to)}`\n const others = policy.edges.filter((e) => e.from !== edge.from || e.to !== edge.to)\n const exists = others.length < policy.edges.length\n if (name === 'allow' && exists) return console.log(`${shown} is already allowed`)\n if (name === 'deny' && !exists) return console.log(`no edge ${shown}; nothing changed`)\n const body: UpdateTeamPolicyRequest = {\n edges: name === 'allow' ? [...others, edge] : others,\n }\n await client.patch(apiPath('teams', args.team, 'policy'), body)\n console.log(`${name === 'allow' ? 'allowed' : 'removed'} ${shown}`)\n },\n })\n}\n\nexport const teamPolicyCommand = defineCommand({\n meta: { name: 'policy', description: 'Who may message whom inside and across a Team' },\n subCommands: {\n show,\n mode,\n allow: edgeCommand('allow'),\n deny: edgeCommand('deny'),\n },\n})\n","import type { RepositoryChanges } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, teamArg } from '../command-helpers.ts'\n\n// `bazilion team review`: `show` lists the changes since a base, with the Agent that wrote each\n// file, or prints one file's diff; `feedback` queues a comment about a changed file or one of its\n// lines for an Agent.\n\nconst base = {\n type: 'string',\n description: 'Comparison base: branch, tag, commit id or revision such as HEAD~1 (default HEAD)',\n} as const\n\nfunction printIssues(changes: RepositoryChanges): void {\n for (const issue of changes.issues) console.log(`note: ${issue.code}: ${issue.message}`)\n}\n\nconst showCmd = defineCommand({\n meta: {\n name: 'show',\n description: 'List changes since a baseline, or print one file diff (read-only)',\n },\n args: {\n id: teamArg,\n base,\n patch: {\n type: 'string',\n description: 'Print the unified diff for one changed path instead of the list',\n },\n json: { ...jsonFlag, description: 'Emit the complete review, with diffs, as JSON' },\n },\n async run({ args }) {\n const client = createClient()\n // Diffs are read only when asked for: one for --patch, all of them for --json.\n const review = await client.repositoryReview(args.id).changes({\n ...(args.base ? { base: args.base } : {}),\n ...(args.patch ? { patches: true, path: args.patch } : args.json ? { patches: true } : {}),\n authors: !args.patch,\n })\n // A folder that is not a repository has no review: said, and the command fails.\n if ('unavailable' in review) throw new Error(review.unavailable.message)\n if (args.json) return printJson(review)\n const changes = review.changes\n if (args.patch) {\n const entry = changes.changes.find((change) => change.path === args.patch)\n if (!entry) throw new Error(`no change for path: ${args.patch}`)\n if (!entry.patch) {\n console.log(\n `${entry.path}: ${entry.status}${entry.contentOmitted ? ` (${entry.contentOmitted})` : ' (no content)'}`,\n )\n return\n }\n console.log(entry.patch)\n if (entry.patchTruncated) console.log('(diff truncated at the configured patch cap)')\n return\n }\n console.log(\n `# ${changes.identity.branch ?? `detached ${changes.identity.head ?? 'unborn'}`}` +\n ` · base ${changes.base.requestedRef} (${changes.base.resolvedOid.slice(0, 12)})`,\n )\n printRows(\n changes.changes.map((change) => [\n change.status,\n change.previousPath ? `${change.previousPath} -> ${change.path}` : change.path,\n change.binary\n ? 'binary'\n : change.addedLines === null\n ? ''\n : `${change.addedLines}+ ${change.deletedLines ?? 0}-`,\n change.contentOmitted ?? '',\n review.authors?.[change.path] ? `by ${review.authors[change.path]?.agentName}` : '',\n ]),\n '(no changes since baseline)',\n )\n if (changes.truncated) console.log('note: the change list is incomplete (file limit)')\n const withheld = changes.withheld\n if (withheld.excluded + withheld.untracked > 0) {\n console.log(\n `note: ${withheld.excluded} excluded and ${withheld.untracked} untracked path(s) withheld`,\n )\n }\n printIssues(changes)\n },\n})\n\nconst feedbackCmd = defineCommand({\n meta: {\n name: 'feedback',\n description:\n 'Queue a comment about a changed file, or one of its lines, for an Agent (diff excerpt, note)',\n },\n args: {\n id: teamArg,\n path: { type: 'string', required: true, description: 'Changed path the feedback is about' },\n agent: { type: 'string', required: true, description: 'Team member to send it to' },\n note: { type: 'string', description: 'Your comment' },\n line: {\n type: 'string',\n description: 'Line of the file as it is now; the diff around it is sent instead of the top',\n },\n base,\n },\n async run({ args }) {\n const client = createClient()\n const line = args.line === undefined ? undefined : Number(args.line)\n if (line !== undefined && (!Number.isSafeInteger(line) || line < 1)) {\n throw new Error('--line must be a line number starting at 1')\n }\n const queued = await client.repositoryReview(args.id).feedback({\n agentId: args.agent,\n comments: [\n {\n path: args.path,\n ...(line === undefined ? {} : { line }),\n ...(args.note ? { note: args.note } : {}),\n },\n ],\n ...(args.base ? { base: args.base } : {}),\n })\n console.log(`queued ${queued.item.id} for ${args.agent} (${queued.item.status})`)\n console.log(queued.message)\n },\n})\n\nexport const teamReviewCommand = defineCommand({\n meta: {\n name: 'review',\n description: 'Git change review: changes since a base, diffs, and file feedback',\n },\n subCommands: {\n show: showCmd,\n feedback: feedbackCmd,\n },\n})\n","import type { TeamDayKind, TeamDayResponse } from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport {\n apiPath,\n jsonFlag,\n printJson,\n printRows,\n teamArg,\n terminalSafe,\n} from '../command-helpers.ts'\n\n// `bazilion team today`: what a Team's Agents handed to each other, delivered, worked on and wait\n// on you for today, newest first: the same list as the Team's page in the web.\n\nconst KIND: Record<TeamDayKind, string> = {\n handoff: 'handed off',\n reply: 'replied',\n file: 'delivered',\n worked: 'worked in',\n question: 'asks you',\n approval: 'waits on you',\n}\n\nexport const teamTodayCommand = defineCommand({\n meta: {\n name: 'today',\n description: \"What a Team's Agents handed off, delivered, worked on and wait on you for today\",\n },\n args: { id: teamArg, json: jsonFlag },\n async run({ args }) {\n const start = new Date()\n start.setHours(0, 0, 0, 0)\n const day = await createClient().get<TeamDayResponse>(\n `${apiPath('teams', args.id, 'today')}?since=${start.getTime()}`,\n )\n if (args.json) return printJson(day)\n printRows(\n day.events.map((event) => [\n new Date(event.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),\n event.otherAgentName ? `${event.agentName} -> ${event.otherAgentName}` : event.agentName,\n KIND[event.kind],\n terminalSafe(event.text),\n ]),\n '(nothing yet today)',\n )\n if (day.truncated) console.log('note: only the latest events are listed')\n },\n})\n","import { readFileSync } from 'node:fs'\nimport type {\n SaveTeamAsTemplateRequest,\n SpawnTeamTemplateRequest,\n SpawnTeamTemplateResponse,\n TeamTemplate,\n TeamTemplateEndpoint,\n TeamTemplateInput,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { ApiClientError, createClient } from '../client.ts'\nimport { columnize } from '../columnize.ts'\nimport { apiPath, jsonFlag, positional, printJson, teamArg } from '../command-helpers.ts'\n\nconst templateArg = positional('Template id')\n\nfunction endpointLabel(template: TeamTemplate, end: TeamTemplateEndpoint): string {\n return end === 'outside' ? 'outside' : `${end}:${template.slots[end]?.agentName ?? '?'}`\n}\n\nfunction printTemplate(template: TeamTemplate): void {\n console.log(`# ${template.id} — ${template.name}`)\n console.log(`mode: ${template.policyMode}`)\n if (template.slots.length) {\n console.log('')\n for (const line of columnize([\n ['slot', 'profile', 'Agent name', 'model', 'reasoning'],\n ...template.slots.map((slot, index) => [\n String(index),\n slot.profileId,\n slot.agentName,\n slot.modelOverride ?? '-',\n slot.reasoningLevel ?? '-',\n ]),\n ]))\n console.log(line)\n } else console.log('slots: (none)')\n if (template.edges.length) {\n console.log('')\n for (const line of columnize([\n ['from', 'to'],\n ...template.edges.map((edge) => [\n endpointLabel(template, edge.from),\n endpointLabel(template, edge.to),\n ]),\n ]))\n console.log(line)\n }\n}\n\n/** The editable part of a template, as `export` prints and `import` reads it. */\nfunction document(template: TeamTemplate): TeamTemplateInput {\n return {\n id: template.id,\n name: template.name,\n userMd: template.userMd,\n policyMode: template.policyMode,\n slots: template.slots,\n edges: template.edges,\n }\n}\n\nconst list = defineCommand({\n meta: { name: 'list', description: 'List Team templates' },\n args: { json: jsonFlag },\n async run({ args }) {\n const rows = await createClient().get<TeamTemplate[]>('/api/team-templates')\n if (args.json) return printJson(rows)\n if (!rows.length) return console.log('(no Team templates)')\n for (const line of columnize([\n ['id', 'slots', 'mode', 'name'],\n ...rows.map((row) => [row.id, String(row.slots.length), row.policyMode, row.name]),\n ]))\n console.log(line)\n },\n})\n\nconst show = defineCommand({\n meta: { name: 'show', description: 'Show a Team template' },\n args: { id: templateArg, json: jsonFlag },\n async run({ args }) {\n const template = await createClient().get<TeamTemplate>(apiPath('team-templates', args.id))\n if (args.json) printJson(template)\n else printTemplate(template)\n },\n})\n\nconst create = defineCommand({\n meta: { name: 'create', description: 'Create an empty Team template' },\n args: {\n id: positional('Template slug'),\n name: { type: 'string', description: 'Display name (defaults to the slug)' },\n },\n async run({ args }) {\n const body: TeamTemplateInput = { id: args.id, name: args.name ?? args.id }\n const created = await createClient().post<TeamTemplate>('/api/team-templates', body)\n console.log(`created Team template ${created.id}`)\n },\n})\n\nconst exportCommand = defineCommand({\n meta: { name: 'export', description: 'Print a Team template as JSON for editing or import' },\n args: { id: templateArg },\n async run({ args }) {\n const template = await createClient().get<TeamTemplate>(apiPath('team-templates', args.id))\n printJson(document(template))\n },\n})\n\nconst importCommand = defineCommand({\n meta: {\n name: 'import',\n description: 'Create a Team template from JSON, or replace the one with the same id',\n },\n args: { file: positional('JSON from export') },\n async run({ args }) {\n const body = JSON.parse(readFileSync(args.file, 'utf8')) as TeamTemplateInput\n if (typeof body.id !== 'string' || !body.id) throw new Error('the JSON needs an \"id\"')\n const client = createClient()\n const exists = await client.get<TeamTemplate>(apiPath('team-templates', body.id)).then(\n () => true,\n (error: unknown) => {\n if (error instanceof ApiClientError && error.status === 404) return false\n throw error\n },\n )\n const saved = exists\n ? await client.put<TeamTemplate>(apiPath('team-templates', body.id), body)\n : await client.post<TeamTemplate>('/api/team-templates', body)\n console.log(\n `${exists ? 'replaced' : 'created'} Team template ${saved.id} (${saved.slots.length} slots, ${saved.edges.length} edges)`,\n )\n },\n})\n\nconst rm = defineCommand({\n meta: { name: 'rm', description: 'Delete a Team template (spawned Teams are unaffected)' },\n args: { id: templateArg },\n async run({ args }) {\n await createClient().del(apiPath('team-templates', args.id))\n console.log(`deleted Team template ${args.id}`)\n },\n})\n\nconst spawn = defineCommand({\n meta: {\n name: 'spawn',\n description: 'Spawn one Agent per slot into a Team; an unknown Team slug creates the Team',\n },\n args: {\n id: templateArg,\n team: positional('Target Team slug'),\n 'user-md-file': { type: 'string', description: 'USER.md for a newly created Team' },\n },\n async run({ args }) {\n const body: SpawnTeamTemplateRequest = {\n teamId: args.team,\n ...(args['user-md-file'] ? { userMd: readFileSync(args['user-md-file'], 'utf8') } : {}),\n }\n const result = await createClient().post<SpawnTeamTemplateResponse>(\n apiPath('team-templates', args.id, 'spawn'),\n body,\n )\n console.log(\n `spawned ${result.agents.length} agent(s) into Team ${result.team.teamId}: ${result.agents.map((agent) => agent.name).join(', ')}`,\n )\n },\n})\n\nconst save = defineCommand({\n meta: {\n name: 'save',\n description: \"Save a live Team's members, edges, mode and USER.md as a new template\",\n },\n args: {\n team: teamArg,\n id: positional('New template id'),\n name: { type: 'string', description: 'Display name (defaults to the id)' },\n },\n async run({ args }) {\n const body: SaveTeamAsTemplateRequest = { id: args.id, name: args.name ?? args.id }\n const saved = await createClient().post<TeamTemplate>(\n apiPath('teams', args.team, 'policy', 'save-as-template'),\n body,\n )\n console.log(`saved Team ${args.team} as template ${saved.id} (${saved.slots.length} slots)`)\n },\n})\n\nexport const teamTemplateCommand = defineCommand({\n meta: { name: 'team-template', description: 'Reusable Team rosters with their allow edges' },\n subCommands: {\n list,\n show,\n create,\n export: exportCommand,\n import: importCommand,\n rm,\n spawn,\n save,\n },\n})\n","// `bazilion telegram` — the CLI side of the web Telegram page: credentials, setup checks, owner\n// pairing, the member allowlist, the bot, and agent topic bindings.\n\nimport type {\n Agent,\n TelegramAllowedUser,\n TelegramBindResponse,\n TelegramConfigState,\n TelegramHealth,\n TelegramPairingChallenge,\n TelegramPairingStatus,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional } from '../command-helpers.ts'\n\nconst telegramUserArg = positional('Numeric Telegram user id')\n\nconst setCmd = defineCommand({\n meta: {\n name: 'set',\n description: 'Save bot token + supergroup chat ID (paired write)',\n },\n args: {\n token: { type: 'string', required: true, description: 'Bot token from @BotFather' },\n chat: { type: 'string', required: true, description: 'Numeric supergroup chat ID' },\n },\n async run({ args }) {\n const client = createClient()\n const state = await client.put<TelegramConfigState>('/api/config/telegram', {\n botToken: args.token,\n chatId: args.chat,\n })\n console.log(`saved · token ${state.botTokenPreview} · chat ${state.chatId}`)\n },\n})\n\nconst clearCmd = defineCommand({\n meta: {\n name: 'clear',\n description: 'Remove stored bot token + chat ID',\n },\n async run() {\n const client = createClient()\n await client.del('/api/config/telegram')\n console.log('cleared')\n },\n})\n\nconst showCmd = defineCommand({\n meta: {\n name: 'show',\n description: 'Show what credentials are stored (token is masked)',\n },\n async run() {\n const client = createClient()\n const state = await client.get<TelegramConfigState>('/api/config/telegram')\n if (!state.configured) {\n console.log('(no credentials saved — run `bazilion telegram config set --token … --chat …`)')\n return\n }\n console.log(`token: ${state.botTokenPreview}`)\n console.log(`chat: ${state.chatId}`)\n if (state.migratedChatId) {\n console.log(\n `⚠ supergroup migrated → ${state.migratedChatId}. Run \\`bazilion telegram reconnect\\` to apply.`,\n )\n }\n },\n})\n\nconst reconnectCmd = defineCommand({\n meta: {\n name: 'reconnect',\n description: 'Apply a pending supergroup chat-id migration + re-activate the bot',\n },\n async run() {\n const client = createClient()\n const state = await client.post<TelegramConfigState>('/api/config/telegram/reconnect')\n console.log(`reconnected · chat ${state.chatId}`)\n },\n})\n\nconst configCmd = defineCommand({\n meta: {\n name: 'config',\n description: 'Manage Telegram credentials (bot token + chat ID)',\n },\n subCommands: {\n set: setCmd,\n clear: clearCmd,\n show: showCmd,\n },\n})\n\nconst healthCmd = defineCommand({\n meta: {\n name: 'health',\n description: 'Run the four-step preflight against the Telegram Bot API',\n },\n async run() {\n const h = await createClient().get<TelegramHealth>('/api/config/telegram/health')\n // Like `bot status`, an unconfigured bridge is a status report on stdout, not an error.\n if (!h.configured) {\n console.log('not configured — run `bazilion telegram config set` first')\n process.exitCode = 1\n return\n }\n if (h.error) throw new Error(`${h.error.step} failed: ${h.error.message}`)\n if (!h.preflight) throw new Error('preflight returned no data')\n const p = h.preflight\n const line = (ok: boolean, label: string, detail: string): string =>\n `${ok ? '✓' : '✕'} ${label.padEnd(30)} ${detail}`\n console.log(line(p.botUsername.length > 0, 'bot identity', `@${p.botUsername}`))\n console.log(line(p.chatTitle.length > 0, 'supergroup reachable', p.chatTitle))\n console.log(line(p.isForum, 'forum topics enabled', String(p.isForum)))\n console.log(line(p.hasManageTopics, 'can_manage_topics', String(p.hasManageTopics)))\n console.log(line(p.privacyModeOff, 'Privacy Mode is OFF', String(p.privacyModeOff)))\n console.log(line(p.chatIsPrivate, 'supergroup is private', String(p.chatIsPrivate)))\n // Everyone in the group can read the agents' replies, so this is worth a look.\n console.log(` ${'group members'.padEnd(30)} ${p.memberCount ?? 'unknown'}`)\n if (p.ownerPresent !== null) {\n console.log(line(p.ownerPresent, 'paired owner is present', String(p.ownerPresent)))\n }\n const allOk =\n p.botUsername.length > 0 &&\n p.chatTitle.length > 0 &&\n p.isForum &&\n p.hasManageTopics &&\n p.privacyModeOff &&\n p.chatIsPrivate &&\n p.ownerPresent !== false\n if (!allOk) process.exitCode = 1\n },\n})\n\nconst botStatusCmd = defineCommand({\n meta: {\n name: 'status',\n description: 'Show polling state of the live bot',\n },\n async run() {\n const client = createClient()\n const h = await client.get<TelegramHealth>('/api/config/telegram/health')\n if (!h.polling) {\n console.log('bot: not running')\n process.exitCode = 1\n return\n }\n const p = h.polling\n const startedAt = p.startedAt ? new Date(p.startedAt).toISOString() : '(never)'\n const lastPoll = p.lastSuccessfulPollAt\n ? new Date(p.lastSuccessfulPollAt).toISOString()\n : '(never)'\n console.log(`running: ${p.running}`)\n console.log(`activated: ${p.activated}`)\n console.log(`started at: ${startedAt}`)\n console.log(`last update id: ${p.lastUpdateId ?? '(none)'}`)\n console.log(`last successful: ${lastPoll}`)\n if (p.error) console.log(`error: ${p.error}`)\n if (!p.running) process.exitCode = 1\n },\n})\n\nconst botRestartCmd = defineCommand({\n meta: {\n name: 'restart',\n description: 'Force-restart the bot (tears down + brings up from current creds)',\n },\n async run() {\n const client = createClient()\n await client.post('/api/config/telegram/restart')\n console.log('restart requested')\n },\n})\n\nconst botCmd = defineCommand({\n meta: {\n name: 'bot',\n description: 'Inspect / control the live polling bot',\n },\n subCommands: {\n status: botStatusCmd,\n restart: botRestartCmd,\n },\n})\n\nconst bindCmd = defineCommand({\n meta: {\n name: 'bind',\n description: 'Create a Telegram topic for an agent (manual fallback for /talk)',\n },\n args: { agent: agentArg },\n async run({ args }) {\n const result = await createClient().post<TelegramBindResponse>(\n apiPath('agents', args.agent, 'telegram', 'bind'),\n )\n const verb = result.created ? 'created topic' : 'already bound to'\n console.log(`${verb} #${result.topicId} for agent ${result.agent.name} (${result.agent.id})`)\n console.log(` ${result.deepLink}`)\n },\n})\n\nconst unbindCmd = defineCommand({\n meta: {\n name: 'unbind',\n description: \"Clear an agent's Telegram topic binding (topic stays in Telegram as orphan)\",\n },\n args: { agent: agentArg },\n async run({ args }) {\n await createClient().del(apiPath('agents', args.agent, 'telegram', 'binding'))\n console.log(`unbound agent ${args.agent}`)\n },\n})\n\nconst listBindingsCmd = defineCommand({\n meta: {\n name: 'list',\n description: 'List agents and their Telegram topic bindings',\n },\n async run() {\n const client = createClient()\n const agents = await client.get<Agent[]>('/api/agents')\n const bound = agents.filter((a) => a.telegramTopicId !== null)\n const unbound = agents.filter((a) => a.telegramTopicId === null)\n if (bound.length === 0 && unbound.length === 0) {\n console.log('(no agents)')\n return\n }\n if (bound.length > 0) {\n console.log('bound:')\n for (const a of bound) {\n console.log(` #${a.telegramTopicId}\\t${a.name}\\t(team: ${a.teamId})`)\n }\n }\n if (unbound.length > 0) {\n console.log('unbound:')\n for (const a of unbound) {\n console.log(` —\\t${a.name}\\t(team: ${a.teamId})`)\n }\n }\n },\n})\n\nconst allowCmd = defineCommand({\n meta: { name: 'allow', description: 'Add a Telegram user id to the allowlist' },\n args: {\n userId: telegramUserArg,\n label: { type: 'string', description: 'Optional human label' },\n },\n async run({ args }) {\n const client = createClient()\n const u = await client.post<TelegramAllowedUser>('/api/config/telegram/acl', {\n userId: Number(args.userId),\n label: args.label ?? null,\n role: 'member',\n })\n console.log(`allowed ${u.userId} (${u.role})`)\n },\n})\n\nconst denyCmd = defineCommand({\n meta: { name: 'deny', description: 'Remove a Telegram user id from the allowlist' },\n args: { userId: telegramUserArg },\n async run({ args }) {\n const client = createClient()\n await client.del(`/api/config/telegram/acl/${Number(args.userId)}`)\n console.log(`removed ${args.userId}`)\n },\n})\n\nconst allowedCmd = defineCommand({\n meta: { name: 'allowed', description: 'List allowlisted Telegram users' },\n async run() {\n const client = createClient()\n const users = await client.get<TelegramAllowedUser[]>('/api/config/telegram/acl')\n if (users.length === 0) {\n console.log('(allowlist empty — unpaired and closed)')\n return\n }\n for (const u of users) {\n const who = u.label ?? (u.username ? `@${u.username}` : '—')\n console.log(`${u.userId}\\t${u.role}\\t${who}`)\n }\n },\n})\n\nconst pairingCreateCmd = defineCommand({\n meta: { name: 'create', description: 'Generate a one-time Telegram owner pairing code' },\n async run() {\n const result = await createClient().post<TelegramPairingChallenge>(\n '/api/config/telegram/pairing/challenge',\n )\n console.log(`pairing code: ${result.code}`)\n console.log(`expires: ${new Date(result.expiresAt).toISOString()}`)\n console.log('send `/pair <code>` in the configured ⚙ bazilion service topic')\n },\n})\n\nconst pairingStatusCmd = defineCommand({\n meta: { name: 'status', description: 'Show Telegram owner pairing status' },\n async run() {\n const result = await createClient().get<TelegramPairingStatus>('/api/config/telegram/pairing')\n console.log(`paired: ${result.paired}`)\n console.log(`owner: ${result.ownerUserId ?? '(none)'}`)\n console.log(`challenge active: ${result.challengeActive}`)\n if (result.challengeExpiresAt)\n console.log(`expires: ${new Date(result.challengeExpiresAt).toISOString()}`)\n },\n})\n\nconst pairingCancelCmd = defineCommand({\n meta: { name: 'cancel', description: 'Cancel the active Telegram pairing code' },\n async run() {\n await createClient().del('/api/config/telegram/pairing/challenge')\n console.log('pairing challenge cancelled')\n },\n})\n\nconst pairingResetCmd = defineCommand({\n meta: { name: 'reset', description: 'Revoke the Telegram owner and require re-pairing' },\n args: {\n yes: { type: 'boolean', description: 'Confirm destructive owner reset', required: true },\n },\n async run({ args }) {\n if (!args.yes) throw new Error('--yes is required')\n await createClient().post('/api/config/telegram/pairing/reset', { confirm: true })\n console.log('Telegram owner reset; ingress is closed until re-paired')\n },\n})\n\nconst pairingCmd = defineCommand({\n meta: { name: 'pairing', description: 'Manage single-owner Telegram pairing' },\n subCommands: {\n create: pairingCreateCmd,\n status: pairingStatusCmd,\n cancel: pairingCancelCmd,\n reset: pairingResetCmd,\n },\n})\n\nexport const telegramCommand = defineCommand({\n meta: {\n name: 'telegram',\n description: 'Telegram integration: credentials, health, bot lifecycle, bindings, access',\n },\n subCommands: {\n config: configCmd,\n health: healthCmd,\n bot: botCmd,\n reconnect: reconnectCmd,\n bind: bindCmd,\n unbind: unbindCmd,\n list: listBindingsCmd,\n allow: allowCmd,\n deny: denyCmd,\n allowed: allowedCmd,\n pairing: pairingCmd,\n },\n})\n","import type {\n CreateTokenRequest,\n CreateTokenResponse,\n ListTokensResponse,\n WebToken,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { readAuthFile } from '../auth-file.ts'\nimport { createClient } from '../client.ts'\nimport { apiPath, positional, printRows } from '../command-helpers.ts'\nimport { resolveCliPaths } from '../paths.ts'\n\nfunction tokenRow(t: WebToken): string[] {\n const last = t.lastUsedAt ? new Date(t.lastUsedAt).toISOString() : '(never)'\n const expired = t.expiresAt !== null && t.expiresAt <= Date.now()\n const state = t.revokedAt ? 'revoked' : expired ? 'expired' : 'active'\n const expires = t.expiresAt ? new Date(t.expiresAt).toISOString() : '(never)'\n return [t.id, t.kind, state, t.label, `expires: ${expires}`, `last: ${last}`]\n}\n\nconst createCmd = defineCommand({\n meta: { name: 'create', description: 'Mint a new device token with full access (shown once)' },\n args: {\n label: positional('Human-readable label'),\n 'expires-days': {\n type: 'string',\n description: 'Expire the token after this many days (default: never)',\n },\n },\n async run({ args }) {\n const client = createClient()\n const expiresInDays =\n args['expires-days'] === undefined ? undefined : Number(args['expires-days'])\n if (expiresInDays !== undefined && !(Number.isInteger(expiresInDays) && expiresInDays > 0)) {\n throw new Error('--expires-days must be a positive integer')\n }\n const body: CreateTokenRequest = { label: args.label, expiresInDays }\n const res = await client.post<CreateTokenResponse>('/api/tokens', body)\n console.log(`id: ${res.meta.id}`)\n console.log(`label: ${res.meta.label}`)\n console.log(`kind: ${res.meta.kind}`)\n console.log(\n `expires: ${res.meta.expiresAt ? new Date(res.meta.expiresAt).toISOString() : '(never)'}`,\n )\n console.log(`token: ${res.token}`)\n console.log('')\n console.log('store the token now — it is not recoverable later.')\n },\n})\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List web tokens' },\n args: {\n all: { type: 'boolean', description: 'Include revoked tokens' },\n },\n async run({ args }) {\n const { tokens } = await createClient().get<ListTokensResponse>(\n `/api/tokens${args.all ? '?includeRevoked=1' : ''}`,\n )\n printRows(tokens.map(tokenRow), '(no tokens)')\n },\n})\n\nconst showLocalCmd = defineCommand({\n meta: {\n name: 'show-local',\n description: 'Print the bootstrap web token stored in ~/.bazilion/auth.json',\n },\n run() {\n const paths = resolveCliPaths()\n console.log(readAuthFile(paths.authFile).token)\n },\n})\n\nconst revokeCmd = defineCommand({\n meta: { name: 'revoke', description: 'Revoke a web token and its browser sessions' },\n args: { id: positional('Token id') },\n async run({ args }) {\n await createClient().del(apiPath('tokens', args.id))\n console.log(`revoked token ${args.id}`)\n },\n})\n\nexport const tokenCommand = defineCommand({\n meta: { name: 'token', description: 'Manage web tokens for API/CLI clients' },\n subCommands: {\n create: createCmd,\n list: listCmd,\n revoke: revokeCmd,\n 'show-local': showLocalCmd,\n },\n})\n","import type {\n AgentTrigger,\n CreateTriggerRequest,\n CreateTriggerResponse,\n ListTriggerDispatchesResponse,\n ListTriggersResponse,\n UpdateTriggerRequest,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { agentArg, apiPath, positional, printRows } from '../command-helpers.ts'\n\nconst triggerArg = positional('Trigger id')\n\nfunction spec(t: AgentTrigger): string {\n return t.kind === 'interval' ? `every ${t.intervalSec}s` : `cron \"${t.cronExpr}\"`\n}\n\nconst addCmd = defineCommand({\n meta: { name: 'add', description: 'Add an interval / cron trigger to an agent' },\n args: {\n agent: agentArg,\n every: {\n type: 'string',\n description: 'Interval in seconds (e.g. --every 300 = every 5 minutes)',\n },\n cron: {\n type: 'string',\n description: 'Cron expression (5 fields: minute hour dom month dow)',\n },\n message: {\n type: 'string',\n required: true,\n description: 'Message to inject when the trigger fires',\n },\n disabled: { type: 'boolean', description: 'Create in disabled state' },\n },\n async run({ args }) {\n if (!args.every === !args.cron) {\n throw new Error('specify exactly one of --every <seconds> or --cron \"<expr>\"')\n }\n const body: CreateTriggerRequest = args.every\n ? {\n kind: 'interval',\n intervalSec: Number(args.every),\n message: args.message,\n enabled: !args.disabled,\n }\n : {\n kind: 'cron',\n cronExpr: args.cron as string,\n message: args.message,\n enabled: !args.disabled,\n }\n const { trigger } = await createClient().post<CreateTriggerResponse>(\n apiPath('agents', args.agent, 'triggers'),\n body,\n )\n console.log(`${trigger.id}\\t${spec(trigger)}\\t${trigger.enabled ? 'enabled' : 'disabled'}`)\n },\n})\n\nfunction triggerRow(t: AgentTrigger, next: number | null | undefined): string[] {\n const last = t.lastFiredAt ? new Date(t.lastFiredAt).toISOString() : '(never)'\n const state = t.enabled ? 'enabled' : 'disabled'\n const msgPreview = t.message.length > 60 ? `${t.message.slice(0, 60)}…` : t.message\n const upcoming = typeof next === 'number' ? new Date(next).toISOString() : '-'\n return [t.id, state, spec(t), `next: ${upcoming}`, `last: ${last}`, `\"${msgPreview}\"`]\n}\n\nconst listCmd = defineCommand({\n meta: { name: 'list', description: 'List triggers for an agent' },\n args: { agent: agentArg },\n async run({ args }) {\n const { triggers, nextRuns, schedulerOff } = await createClient().get<ListTriggersResponse>(\n apiPath('agents', args.agent, 'triggers'),\n )\n printRows(\n triggers.map((trigger) => triggerRow(trigger, nextRuns[trigger.id])),\n '(no triggers)',\n )\n if (schedulerOff && triggers.length > 0)\n console.log('The daemon runs no schedules: it was started with BAZILION_SCHEDULER=off.')\n },\n})\n\nconst rmCmd = defineCommand({\n meta: { name: 'rm', description: 'Delete a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n await createClient().del(apiPath('triggers', args.id))\n console.log(`removed trigger ${args.id}`)\n },\n})\n\nconst enableCmd = defineCommand({\n meta: { name: 'enable', description: 'Enable a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n const body: UpdateTriggerRequest = { enabled: true }\n await createClient().patch(apiPath('triggers', args.id), body)\n console.log(`enabled trigger ${args.id}`)\n },\n})\n\nconst disableCmd = defineCommand({\n meta: { name: 'disable', description: 'Disable a trigger' },\n args: { id: triggerArg },\n async run({ args }) {\n const body: UpdateTriggerRequest = { enabled: false }\n await createClient().patch(apiPath('triggers', args.id), body)\n console.log(`disabled trigger ${args.id}`)\n },\n})\n\nconst historyCmd = defineCommand({\n meta: { name: 'history', description: 'Show recent runs of a trigger' },\n args: {\n id: triggerArg,\n limit: { type: 'string', description: 'Maximum rows (default 20)' },\n },\n async run({ args }) {\n const limit = args.limit ? Number(args.limit) : 20\n if (!Number.isInteger(limit) || limit < 1 || limit > 100) {\n throw new Error('--limit must be an integer from 1 to 100')\n }\n const { dispatches } = await createClient().get<ListTriggerDispatchesResponse>(\n `${apiPath('triggers', args.id, 'dispatches')}?limit=${limit}`,\n )\n printRows(\n dispatches.map((dispatch) => [\n new Date(dispatch.scheduledAt).toISOString(),\n dispatch.status,\n dispatch.error ?? '',\n ]),\n '(no dispatches)',\n )\n },\n})\n\nexport const triggerCommand = defineCommand({\n meta: { name: 'trigger', description: 'Manage scheduled agent triggers' },\n subCommands: {\n add: addCmd,\n list: listCmd,\n rm: rmCmd,\n enable: enableCmd,\n disable: disableCmd,\n history: historyCmd,\n },\n})\n","import { existsSync, lstatSync, readdirSync, rmdirSync, rmSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { defineCommand } from 'citty'\nimport { assertDaemonStopped, DAEMON_PID_FILE } from '../../../daemon/src/lib/daemon-liveness.ts'\nimport { confirm } from '../command-helpers.ts'\nimport { canonicalPath, requestedHome } from '../paths.ts'\n\n// The reset deletes these and keeps installed skills; --all deletes the skills too.\nconst RESET_ENTRIES = [\n 'profiles',\n 'agents',\n 'teams',\n 'browsers',\n DAEMON_PID_FILE,\n 'bazilion.db-wal',\n 'bazilion.db-shm',\n 'bazilion.db-journal',\n 'bazilion.db',\n 'auth.json',\n]\nconst ALL_ENTRIES = [...RESET_ENTRIES, 'skills']\n\nexport const uninstallCommand = defineCommand({\n meta: {\n name: 'uninstall',\n description: 'Delete the Bazilion data in ~/.bazilion (or BAZILION_HOME)',\n },\n args: {\n home: { type: 'string', description: 'Uninstall this home instead of BAZILION_HOME' },\n yes: { type: 'boolean', description: 'Do not ask for confirmation' },\n all: { type: 'boolean', description: 'Also delete installed skills, then the emptied home' },\n },\n async run({ args }) {\n const requested = requestedHome(args.home)\n const home = canonicalPath(requested)\n if (!existsSync(home)) {\n console.log(`nothing to remove: ${home} does not exist`)\n return\n }\n if (home === canonicalPath(homedir())) {\n throw new Error(\n `refusing to uninstall your home directory ${home}; delete Bazilion's files by hand`,\n )\n }\n // A directory given by mistake is refused: a home has bazilion.db, or only Bazilion's entries.\n const unmanaged = readdirSync(home).filter((entry) => !ALL_ENTRIES.includes(entry))\n if (!existsSync(join(home, 'bazilion.db')) && unmanaged.length > 0) {\n throw new Error(\n `${home} is not a Bazilion home: no bazilion.db, and it holds ${unmanaged.join(', ')}`,\n )\n }\n assertDaemonStopped(home)\n\n const scope = args.all\n ? `all Bazilion data in ${home}, installed skills included`\n : `the database, auth.json, profiles, Agents, Teams and browser profiles in ${home}`\n if (!args.yes && !(await confirm(`delete ${scope}?`))) {\n console.log('aborted')\n return\n }\n // Again: a daemon may have started while the question was open.\n assertDaemonStopped(home)\n // Linked Team slots are symlinks: rmSync unlinks them and never touches their targets.\n for (const entry of args.all ? ALL_ENTRIES : RESET_ENTRIES) {\n rmSync(join(home, entry), { recursive: true, force: true })\n }\n if (!args.all) {\n console.log(`reset ${home}; installed skills are kept`)\n console.log(\"run 'bazilion serve' to start again with a fresh database and auth.json\")\n return\n }\n const left = readdirSync(home).sort()\n if (left.length > 0) {\n console.log(`removed the Bazilion data; kept ${home}, which also holds ${left.join(', ')}`)\n } else if (lstatSync(requested).isSymbolicLink()) {\n // Deleting the link's target would leave BAZILION_HOME dangling.\n console.log(`emptied ${home}`)\n } else {\n rmdirSync(home)\n console.log(`removed ${home}`)\n }\n },\n})\n","import {\n formatCost,\n formatTokens,\n type UsageReport,\n type UsageTotals,\n usageSummary,\n} from '@bazilion/api-types'\nimport { defineCommand } from 'citty'\nimport { createClient } from '../client.ts'\nimport { jsonFlag, printJson, printRows, terminalSafe } from '../command-helpers.ts'\n\n// `bazilion usage`: tokens and cost per Team, Agent, model and day, as Manage → Usage shows them.\n\nexport function usageHeadline(report: UsageReport): string {\n const period =\n report.days === null\n ? 'everything saved'\n : report.days === 1\n ? `today (${report.to})`\n : `the last ${report.days} days (${report.from} to ${report.to})`\n return `Usage over ${period}, ${report.timeZone}`\n}\n\n/** The totals on a few lines: money, then tokens by how they are paid for. */\nexport function totalsLines(totals: UsageTotals): string[] {\n const lines = [\n `Spent ${formatCost(totals.cost)}${totals.estimated ? ' (estimated from catalog prices)' : ''}`,\n `Tokens ${formatTokens(totals.totalTokens)} in ${totals.calls} model call${totals.calls === 1 ? '' : 's'}`,\n ]\n if (totals.planTokens > 0) lines.push(`On a plan ${formatTokens(totals.planTokens)} tokens`)\n if (totals.localTokens > 0) lines.push(`Local ${formatTokens(totals.localTokens)} tokens`)\n if (totals.unpricedTokens > 0)\n lines.push(\n `Unpriced ${formatTokens(totals.unpricedTokens)} tokens on models the catalog has no price for (not in Spent)`,\n )\n return lines\n}\n\nexport const usageCommand = defineCommand({\n meta: {\n name: 'usage',\n description: 'Show tokens and cost per Team, Agent, model and day',\n },\n args: {\n days: { type: 'string', default: '30', description: 'Days counted, today included' },\n all: { type: 'boolean', description: 'Count everything saved' },\n agent: { type: 'string', description: 'Only this Agent (id)' },\n team: { type: 'string', description: 'Only this Team (id)' },\n daily: { type: 'boolean', description: 'Also list every day' },\n json: jsonFlag,\n },\n async run({ args }) {\n const query = new URLSearchParams({\n days: args.all ? 'all' : args.days,\n tz: Intl.DateTimeFormat().resolvedOptions().timeZone,\n })\n if (args.agent) query.set('agent', args.agent)\n if (args.team) query.set('team', args.team)\n const report = await createClient().get<UsageReport>(`/api/usage?${query}`)\n if (args.json) return printJson(report)\n console.log(usageHeadline(report))\n console.log('')\n for (const line of totalsLines(report.totals)) console.log(line)\n if (report.unreadable > 0)\n console.log(\n `${report.unreadable} saved conversation${report.unreadable === 1 ? '' : 's'} could not be read and ${report.unreadable === 1 ? 'is' : 'are'} not counted.`,\n )\n if (report.totals.calls === 0) return\n const section = (title: string, rows: string[][]) => {\n console.log('')\n console.log(title)\n printRows(rows, '(none)')\n }\n section(\n 'By Team',\n report.byTeam.map((team) => [terminalSafe(team.teamName), usageSummary(team)]),\n )\n section(\n 'By Agent',\n report.byAgent.map((agent) => [\n terminalSafe(agent.agentName) + (agent.archived ? ' (archived)' : ''),\n terminalSafe(agent.teamName),\n usageSummary(agent),\n ]),\n )\n section(\n 'By model',\n report.byModel.map((model) => [\n terminalSafe(`${model.providerName} ${model.model}`),\n usageSummary(model),\n ]),\n )\n if (args.daily)\n section(\n 'By day',\n report.byDay.map((day) => [day.day, day.calls ? usageSummary(day) : '']),\n )\n },\n})\n"],"mappings":";;;AAAA,SAAS,iBAAAA,iBAAe,YAAY,iBAAiB;;;ACArD;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;A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,QAAQ,KAAK,QAAQ,SAAS,IAAI,GAAG;AAGxD,YAAM,kBAAkB,QAAQ,KAAK,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,CAAC;AAC9D,UAAI,CAAC,iBAAiB;AACpB,0BAAkB;AAClB,gBAAQ,KAAK,CAAC;AAAA,MAChB;AACA,YAAM,CAAC,QAAQ,MAAM,IAAI,MAAM,kBAAkB,MAAqB,OAAO;AAC7E,YAAM,UAAU,QAAQ,MAAM;AAC9B,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,QAAI,QAAQ,WAAW,MAAM,QAAQ,CAAC,MAAM,eAAe,QAAQ,CAAC,MAAM,OAAO;AAC/E,cAAQ,IAAI,OAAO;AACnB;AAAA,IACF;AACA,UAAM,WAAW,MAAM,EAAE,QAAQ,CAAC;AAAA,EACpC,SAAS,KAAK;AACZ,eAAW,GAAG;AACd,YAAQ,KAAK,iBAAiB,GAAG,CAAC;AAAA,EACpC;AACF;AAEA,MAAM;","names":["defineCommand","base","createClient","readFileSync","basename","row","resolve","stdin","stdout","basename","readFileSync","createClient","entry","defineCommand","defineCommand","defineCommand","createClient","basename","createInterface","defineCommand","basename","defineCommand","createClient","mode","rl","createInterface","defineCommand","defineCommand","createClient","defineCommand","defineCommand","createClient","defineCommand","defineCommand","createClient","defineCommand","createClient","list","defineCommand","defineCommand","createClient","defineCommand","resolve","defineCommand","createClient","existsSync","mkdirSync","readFileSync","rmSync","dirname","join","resolve","DatabaseSync","defineCommand","list","readFileSync","readFileSync","readFileSync","writeFileSync","join","defineCommand","existsSync","archive","list","rmSync","readFileSync","entry","join","DatabaseSync","resolve","mkdirSync","dirname","defineCommand","main","defineCommand","listCmd","defineCommand","createClient","body","rmCmd","defineCommand","list","defineCommand","createClient","spawn","existsSync","join","defineCommand","existsSync","join","defineCommand","entry","resolve","join","existsSync","resolve","label","spawn","entry","defineCommand","defineCommand","defineCommand","createClient","label","defineCommand","listCmd","defineCommand","createClient","showCmd","existsSync","readFileSync","writeFileSync","defineCommand","defineCommand","existsSync","readFileSync","writeFileSync","defineCommand","addCmd","defineCommand","entry","ask","createClient","setCmd","listCmd","showCmd","rmCmd","defineCommand","defineCommand","entry","createClient","readCmd","listCmd","rmCmd","defineCommand","settings","defineCommand","createClient","spawn","readFileSync","rmSync","writeFileSync","join","defineCommand","createCmd","defineCommand","readFileSync","createClient","listCmd","list","showCmd","editCmd","join","writeFileSync","resolve","spawn","rmSync","mode","deleteCmd","defineCommand","entry","checkLine","failure","listCmd","defineCommand","createClient","main","enableCmd","disableCmd","testCmd","defineCommand","defineCommand","createClient","defineCommand","list","defineCommand","createClient","closeSync","openSync","writeFileSync","defineCommand","list","defineCommand","createClient","show","openSync","writeFileSync","closeSync","defineCommand","defineCommand","createClient","defineCommand","listCmd","defineCommand","createClient","existsSync","readFileSync","basename","resolve","defineCommand","list","listCmd","defineCommand","createClient","resolve","existsSync","readFileSync","basename","rmCmd","readFileSync","stdin","defineCommand","defineCommand","print","defineCommand","createClient","defineCommand","decodeText","defineCommand","createClient","defineCommand","show","defineCommand","createClient","defineCommand","showCmd","defineCommand","createClient","entry","defineCommand","defineCommand","createClient","addCmd","defineCommand","createClient","listCmd","list","rmCmd","stdin","readFileSync","readFileSync","defineCommand","list","defineCommand","createClient","row","show","readFileSync","rm","spawn","defineCommand","setCmd","defineCommand","createClient","showCmd","label","defineCommand","createCmd","defineCommand","createClient","listCmd","revokeCmd","defineCommand","addCmd","defineCommand","createClient","listCmd","rmCmd","enableCmd","disableCmd","existsSync","readdirSync","rmSync","homedir","join","defineCommand","defineCommand","existsSync","homedir","readdirSync","entry","join","rmSync","defineCommand","defineCommand","createClient","defineCommand"]}
|