Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Feat/mercury cloud (#111)
Salman Qureshie5dc012bd031
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ca996cb3..e9a47d75 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -115,6 +115,8 @@ jobs:export PATH="$PWD/node_modules/.bin:$PATH"node node_modules/tsup/dist/cli-default.jsnode scripts/post-build.cjs+ node -e "try { const Database = require('better-sqlite3'); const db = new Database(':memory:'); db.prepare('select 1').get(); db.close(); console.log('better-sqlite3 OK'); } catch (e) { console.log('better-sqlite3 unavailable (optional on Termux):', e.message); }"+ node -e "const { spawnSync } = require('node:child_process'); const r = spawnSync(process.execPath, ['dist/index.js', '--help'], { encoding: 'utf8' }); if (r.status !== 0 || !r.stdout.includes('Usage:')) process.exit(1)"node node_modules/vitest/vitest.mjs runCI_SCRIPTchmod +x /tmp/termux-ci.sh@@ -162,4 +164,4 @@ jobs:fi- run: npm publish --access public --provenanceenv:- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}\ No newline at end of file+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/README.md b/README.mdindex 52e275a8..836c0cab 100644--- a/README.md+++ b/README.md@@ -390,9 +390,10 @@ Mercury can be compiled into a single self-contained binary using `bun build --c```bashnpm run build:bin # host platform only-npm run build:bin:all # all 5 targets (macOS arm64/x64, Linux x64/arm64, Windows x64)+npm run build:bin:all # clean release: all 5 targets plus web archive and checksumsnpm run build:bin:force # rebuild (overwrite existing binary for the same version)-npm run build:bin:all:force # rebuild all targets+npm run build:bin:all:force # replace an existing release directory, then rebuild all targets+node scripts/verify-standalone-release.cjs # verify an already-built publishable release```Output is **versioned** so older builds are never overwritten:@@ -406,13 +407,15 @@ release/│ ├── mercury-linux-x64│ ├── mercury-linux-arm64│ ├── mercury-win-x64.exe-│ └── checksums.txt (SHA-256 for every binary)+│ ├── web.tar.gz+│ └── checksums.txt (SHA-256 for downloadable binaries and web.tar.gz)+├── smoke/v1.2.0/ (host-only local builds; never publish)└── v1.2.0/ …```-The version is read from `package.json` — bump it before building to produce a fresh folder. Re-running for the same version skips already-built targets unless `--force` is passed.+The version is read from `package.json`. Host-only smoke builds are isolated from publishable releases. `build:bin:all` refuses to reuse a non-empty version directory; use `build:bin:all:force` to delete and recreate it so assets from different revisions cannot be mixed.-**Cross-compilation**: Bun produces binaries for every target from a single host. Native modules (`better-sqlite3`) can't cross-compile, but Mercury gracefully falls back to `sql.js` (pure JS + wasm) so the cross-compiled binaries still work end-to-end.+**Cross-compilation**: Bun produces the JavaScript binaries for every target from a single host. Native addons such as `better-sqlite3` still require target-compatible packaging. `sql.js` is used by a narrow web API fallback; it is not a general substitute for all `better-sqlite3`-backed features.**macOS Gatekeeper**: unsigned binaries trigger a warning on first launch. For distribution, sign with `codesign --sign "Developer ID" release/v<version>/mercury-macos-arm64` and notarize.diff --git a/package-lock.json b/package-lock.jsonindex 2948a6ab..a7576130 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.1.12",+ "version": "1.2.1","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "@cosmicstack/mercury-agent",- "version": "1.1.12",+ "version": "1.2.1","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^3.0.71",@@ -15,6 +15,7 @@"@grammyjs/auto-retry": "^2.0.2","@hono/node-server": "^2.0.0","@slack/bolt": "^4.7.3",+ "@types/ws": "^8.18.1","ai": "^6.0.168","bcryptjs": "^3.0.3","chalk": "^5.4.0",@@ -31,6 +32,7 @@"qrcode-terminal": "^0.12.0","react": "^18.3.1","sql.js": "^1.14.1",+ "ws": "^8.21.0","yaml": "^2.7.0","zod": "^3.25.76"},@@ -5569,9 +5571,10 @@"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="},"node_modules/ws": {- "version": "8.20.1",- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",- "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",+ "version": "8.21.1",+ "resolved": "https://registry.npmmirror.com/ws/-/ws-8.21.1.tgz",+ "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",+ "license": "MIT","engines": {"node": ">=10.0.0"},@@ -9035,9 +9038,9 @@"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="},"ws": {- "version": "8.20.1",- "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",- "integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",+ "version": "8.21.1",+ "resolved": "https://registry.npmmirror.com/ws/-/ws-8.21.1.tgz",+ "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==","requires": {}},"yaml": {diff --git a/package.json b/package.jsonindex 6a02951b..cf687065 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.1.13",+ "version": "1.2.1","description": "Soul-driven AI agent with Second Brain memory, permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.","type": "module","main": "dist/index.js",@@ -66,6 +66,7 @@"@grammyjs/auto-retry": "^2.0.2","@hono/node-server": "^2.0.0","@slack/bolt": "^4.7.3",+ "@types/ws": "^8.18.1","ai": "^6.0.168","bcryptjs": "^3.0.3","chalk": "^5.4.0",@@ -82,6 +83,7 @@"qrcode-terminal": "^0.12.0","react": "^18.3.1","sql.js": "^1.14.1",+ "ws": "^8.21.0","yaml": "^2.7.0","zod": "^3.25.76"},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlnew file mode 100644index 00000000..43e915eb--- /dev/null+++ b/pnpm-lock.yaml@@ -0,0 +1,3927 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@ai-sdk/anthropic':+ specifier: ^3.0.71+ version: 3.0.96([email protected])+ '@ai-sdk/deepseek':+ specifier: ^2.0.29+ version: 2.0.47([email protected])+ '@ai-sdk/openai':+ specifier: ^3.0.53+ version: 3.0.84([email protected])+ '@grammyjs/auto-retry':+ specifier: ^2.0.2+ version: 2.0.2([email protected])+ '@hono/node-server':+ specifier: ^2.0.0+ version: 2.0.8([email protected])+ '@slack/bolt':+ specifier: ^4.7.3+ version: 4.7.3(@types/[email protected])+ '@types/ws':+ specifier: ^8.18.1+ version: 8.18.1+ ai:+ specifier: ^6.0.168+ version: 6.0.224([email protected])+ bcryptjs:+ specifier: ^3.0.3+ version: 3.0.3+ chalk:+ specifier: ^5.4.0+ version: 5.6.2+ commander:+ specifier: ^12.1.0+ version: 12.1.0+ discord.js:+ specifier: ^14.26.4+ version: 14.26.5+ dotenv:+ specifier: ^16.4.7+ version: 16.6.1+ grammy:+ specifier: ^1.42.0+ version: 1.44.0+ hono:+ specifier: ^4.12.15+ version: 4.12.30+ ink:+ specifier: ^5.2.1+ marked:+ specifier: ^14.1.4+ version: 14.1.4+ node-cron:+ specifier: ^3.0.3+ version: 3.0.3+ ollama-ai-provider:+ specifier: ^1.2.0+ version: 1.2.0([email protected])+ pino:+ specifier: ^10.3.1+ version: 10.3.1+ qrcode-terminal:+ specifier: ^0.12.0+ version: 0.12.0+ react:+ specifier: ^18.3.1+ version: 18.3.1+ sql.js:+ specifier: ^1.14.1+ version: 1.14.1+ ws:+ specifier: ^8.21.0+ version: 8.21.0+ yaml:+ specifier: ^2.7.0+ version: 2.9.0+ zod:+ specifier: ^3.25.76+ version: 3.25.76+ optionalDependencies:+ better-sqlite3:+ specifier: ^12.9.0+ version: 12.11.1+ devDependencies:+ '@types/bcryptjs':+ specifier: ^3.0.0+ version: 3.0.0+ '@types/better-sqlite3':+ specifier: ^7.6.13+ version: 7.6.13+ '@types/node':+ specifier: ^22.13.0+ version: 22.20.1+ '@types/node-cron':+ specifier: ^3.0.11+ version: 3.0.11+ '@types/qrcode-terminal':+ specifier: ^0.12.2+ version: 0.12.2+ '@types/react':+ specifier: ^18.3.28+ version: 18.3.31+ react-devtools-core:+ specifier: ^4.28.5+ version: 4.28.5+ tsup:+ specifier: ^8.4.0+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ vitest:+ specifier: ^3.0.0+ version: 3.2.7(@types/[email protected])([email protected])++packages:++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-6VQzaXQdm5FkX6NWOyKzV5GB11C8IqkgsKZE91lg/bdwyvnQJLDwal2qkE0+fC8CCGeW5d+VV8Mw/+H+OcDC1A==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-MzcQ321JO8OY+TVLFI81A7cIIuoeLLxrLCDD+8C1E3Ro6UFyfMtRXo9bw9OhTMRSDMo6hgSDOo4Fekz8aJtQYQ==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-C/mTeSdmhu8dAnH3vZaRXffD8Oewo1r4QEGxvCdR8eC9b4PKPs2CLsbg3DVJH/X3Bea5fAu87Ob7P3fSS+oq/g==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-cmgbeJL0bbY0yTJH4/AdmP5E7MjWRL9G8UdhIi0JlV/So03o82ORJofW8OzwCZPTORVQblFbpZXYGDcUd9NdUQ==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.23.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-/HHGmtKllqjg1OLc023v9w9kK3laW7Z6TzfZukYQWCsGBbzB9p60zTvvpXFVcs44NZBVXL3viOa1HRKUbeee8g==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}+ engines: {node: '>=18'}++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-5X1k57JBJ4H7H1QjX7CnJYAB1I19r/trVZTMcSms7/kLNZ8RaU4Nt2agcwZzv82Hfx6Q7/TOLU7agAKeFfc8cA==}+ engines: {node: '>=18'}++ '@alcalzone/[email protected]':+ resolution: {integrity: sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==}+ engines: {node: '>=14.13.1'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==}+ engines: {node: '>=16.11.0'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==}+ engines: {node: '>=16.11.0'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==}+ engines: {node: '>=18'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==}+ engines: {node: '>=16.11.0'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==}+ engines: {node: '>=18'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==}+ engines: {node: '>=18'}++ '@discordjs/[email protected]':+ resolution: {integrity: sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==}+ engines: {node: '>=16.11.0'}++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@grammyjs/[email protected]':+ resolution: {integrity: sha512-b4A4p5jlYDiQtW0c0FXYe11WMkYoiW+5rvOaDMCOk1h7Pu2SDl7B7gmFF8cthWCx2+M2nWLOsBxAgbBG4kKWYg==}+ engines: {node: '>=12.20.0 || >=14.13.1'}+ peerDependencies:+ grammy: ^1.10.0++ '@grammyjs/[email protected]':+ resolution: {integrity: sha512-4JvXCdxRZHCje0M4gHzLwtB4bLno3WD28xd8CNfk4POWIu73BFnSvGeW6OQ5gPem4eYTEwkD9yDaXssixl6tMQ==}++ '@hono/[email protected]':+ resolution: {integrity: sha512-GuCWzLxwg218fy1JaHculFsdcuY12hxit83V+algozTPnwhNjLrRL/Alg9OYjLZLoUZ1rw/S4CdTMsnkSKCmFA==}+ engines: {node: '>=20'}+ peerDependencies:+ hono: ^4++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@opentelemetry/[email protected]':+ resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}+ engines: {node: '>=8.0.0'}++ '@pinojs/[email protected]':+ resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg==}+ cpu: [arm]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA==}+ cpu: [arm]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA==}+ cpu: [arm64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ==}+ cpu: [arm64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg==}+ cpu: [loong64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ==}+ cpu: [loong64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A==}+ cpu: [ppc64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w==}+ cpu: [ppc64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg==}+ cpu: [riscv64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q==}+ cpu: [riscv64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg==}+ cpu: [s390x]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A==}+ cpu: [x64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg==}+ cpu: [x64]+ os: [linux]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA==}+ cpu: [x64]+ os: [win32]++ '@sapphire/[email protected]':+ resolution: {integrity: sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==}+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}++ '@sapphire/[email protected]':+ resolution: {integrity: sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==}+ engines: {node: '>=v16'}++ '@sapphire/[email protected]':+ resolution: {integrity: sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==}+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}++ '@sapphire/[email protected]':+ resolution: {integrity: sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==}+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}++ '@slack/[email protected]':+ resolution: {integrity: sha512-bODs8q/yNDWUPoxmQhFrRqLMA5vhB/PDizYWqb6CkQhLWEUo5JFtfJcmeU4ElGl6qSt++OKjSYNa4MPc77CleQ==}+ engines: {node: '>=18', npm: '>=8.6.0'}+ peerDependencies:+ '@types/express': ^5.0.0++ '@slack/[email protected]':+ resolution: {integrity: sha512-6cmdPrV/RYfd2U0mDGiMK8S7OJqpCTm7enMLRR3edccsPX8j7zXTLnaEF4fhxxJJTAIOil6+qZrnUPTuaLvwrQ==}+ engines: {node: '>= 18', npm: '>= 8.6.0'}++ '@slack/[email protected]':+ resolution: {integrity: sha512-exqFQySKhNDptWYSWhvRUJ4/+ndu2gayIy7vg/JfmJq3wGtGdHk531P96fAZyBm5c1Le3yaPYqv92rL4COlU3A==}+ engines: {node: '>=18', npm: '>=8.6.0'}++ '@slack/[email protected]':+ resolution: {integrity: sha512-qYy07je71WnEHgRwmw12DlAnZLi5HXmdlI2WUzUK2LH/rYXQpP6uEg462S5CwfE8FoCKUdIigHtYnOOfzZH1lQ==}+ engines: {node: '>= 18', npm: '>= 8.6.0'}++ '@slack/[email protected]':+ resolution: {integrity: sha512-sZ9lIgJhPX2qft/tKWiklFlc0o1FWeI7QtciZJfW1+ErH1eGGHvOZ8e73sleTCFEFJp1q/R0WeS8Oa7AsiDprg==}+ engines: {node: '>= 12.13.0', npm: '>= 6.12.0'}++ '@slack/[email protected]':+ resolution: {integrity: sha512-ItjyjEZml+LDH8CjcCLRLJHh7VZtevPKExrRN3l5KWyBliyDnGAeoO4Y+K+fFBmRpKLYVPgqWMX4THldv2HVtA==}+ engines: {node: '>= 18', npm: '>= 8.6.0'}++ '@standard-schema/[email protected]':+ resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}++ '@types/[email protected]':+ resolution: {integrity: sha512-WRZOuCuaz8UcZZE4R5HXTco2goQSI2XxjGY3hbM/xDvwmqFWd4ivooImsMx65OKM6CtNKbnZ5YL+YwAwK7c1dg==}+ deprecated: This is a stub types definition. bcryptjs provides its own type definitions, so you do not need this installed.++ '@types/[email protected]':+ resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==}++ '@types/[email protected]':+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}++ '@types/[email protected]':+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-d3KvEXBSo/lOAMc2u6fkyDHBvetBHeqD7wm/AcXfLpSOQwlmG9D/aQ0SFswVjv05p7ullQS7Mjohj6/VdbZuTg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GZHUBZR9hckSUhrxmp1nG6NwdpM9fCunJwyThLW1X3AyHgd9IlHb6VANpQQqDr2o/qQp6McZ3y/IA2rVzKzSbw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}++ '@vercel/[email protected]':+ resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==}+ engines: {node: '>= 20'}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true++ '@vitest/[email protected]':+ resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==}++ '@vladfrangu/[email protected]':+ resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==}+ engines: {node: '>=v14.0.0', npm: '>=7.0.0'}++ resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}+ engines: {node: '>=6.5'}++ resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==}+ engines: {node: '>=0.4.0'}+ hasBin: true++ resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}+ engines: {node: '>= 6.0.0'}++ resolution: {integrity: sha512-plo+hHwMANM+P6FjX8RN6W8c8so5NVZGwvDGCWGWwIbvI5tc0ZV1zhr9v/Kq78zyxKZWE50YCSYbqGiPFEhGww==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.25.76 || ^4.1.8++ resolution: {integrity: sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}++ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}++ resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==}+ engines: {node: '>=8.0.0'}++ resolution: {integrity: sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}++ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}++ resolution: {integrity: sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==}+ hasBin: true++ resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==}+ engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}++ resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}++ resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}++ resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}++ resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}++ resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+ peerDependencies:+ esbuild: '>=0.18'++ resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==}+ engines: {node: ^12.17.0 || ^14.13 || >=16.0.0}++ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}+ engines: {node: '>= 16'}++ resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}+ engines: {node: '>= 14.16.0'}++ resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}++ resolution: {integrity: sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==}++ resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}+ engines: {node: ^14.18.0 || >=16.10.0}++ resolution: {integrity: sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}+ engines: {node: '>=6.6.0'}++ resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}+ engines: {node: '>=4.0.0'}++ resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}+ engines: {node: '>=0.4.0'}++ resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-XnqcWmnFZFAE8ZM8SHAw9DIV8D3Or00rMQ8iQLotrEA2PmXhl+ykaf6L6q4l474hrSUH1JaYcv+iOMRWp2p6Tg==}++ resolution: {integrity: sha512-SGYgjiAs0o8ZzMC97XmFXKONyairJ9YzVda+LvoSKs9YYh2gPtQhY+liaV6H/w72jxYbu9ggiSqAXoF3FLOH4A==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}++ resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}++ resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}++ resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}++ resolution: {integrity: sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}++ resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-G5iZ6Pc/FNRY/soKZHC+TxGDD83rHUDXxzaWhGCX44vAv/tMs56WMusnm/KMNK+luUPsgA9U28cGr4RDlSzL2g==}++ resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}++ resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}++ resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}++ resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}++ resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}++ resolution: {integrity: sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==}+ engines: {node: '>= 18.0.0'}++ resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}++ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}+ engines: {node: '>=4.0'}+ peerDependencies:+ debug: '*'+ peerDependenciesMeta:+ debug:+ optional: true++ resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}++ resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==}++ resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-gGVykS5+c5f1tPV97LuU6IDRMawE2NzpwM9pNz58HQ35IZXDnYL3VOLvNzYognPSeBIOSzQXRu5w96V0aY8y8A==}+ engines: {node: ^12.20.0 || >=14.13.1}++ resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-emn+JoJjrN9YTpRDS5it/UI2SO9BAE37T6I3d963RxcZ81G9A4pr2SZTEiiaiKbzx+NKRg5BZ89fCL7gCJCUog==}+ engines: {node: '>=16.9.0'}++ resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}++ resolution: {integrity: sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}++ resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}++ resolution: {integrity: sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==}+ engines: {node: '>=18'}+ peerDependencies:+ '@types/react': '>=18.0.0'+ react: '>=18.0.0'+ react-devtools-core: ^4.19.1+ peerDependenciesMeta:+ '@types/react':+ optional: true+ react-devtools-core:+ optional: true++ resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-FO/Rhvz5tuw4MCWkpMzHFKWD2LsfHzIb7i6MdPYZ/KW7AlxawyLkqdy+jPZP1WubqEADE3O4FUENlJHDfQASRg==}++ resolution: {integrity: sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==}++ resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}++ resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==}++ resolution: {integrity: sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==}+ engines: {node: '>=12', npm: '>=6'}++ resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==}++ resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}++ resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}++ resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==}++ resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}++ resolution: {integrity: sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==}++ resolution: {integrity: sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==}++ resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}++ resolution: {integrity: sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==}++ resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}++ resolution: {integrity: sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==}++ resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}++ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}+ hasBin: true++ resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}++ resolution: {integrity: sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==}++ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}++ resolution: {integrity: sha512-vkVZ8ONmUdPnjCKc5uTRvmkRbx4EAi2OkTOXmfTDhZz3OFqMNBM1oTTWwTr4HY4uAEojhzPf+Fy8F1DWa3Sndg==}+ engines: {node: '>= 18'}+ hasBin: true++ resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}++ resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}++ resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}++ resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}++ resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==}+ engines: {node: '>=6.0.0'}++ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}+ engines: {node: 4.x || >=6.0.0}+ peerDependencies:+ encoding: ^0.1.0+ peerDependenciesMeta:+ encoding:+ optional: true++ resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-jTNFruwe3O/ruJeppI/quoOUxG7NA6blG3ZyQj3lei4+NnJo7bi3eIRWqlVpRlu/mbzbFXeJSBuYQWF6pzGKww==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.0.0+ peerDependenciesMeta:+ zod:+ optional: true++ resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}++ resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==}++ resolution: {integrity: sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}+ engines: {node: '>= 14.16'}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==}++ resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==}++ resolution: {integrity: sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==}+ hasBin: true++ resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}++ resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}+ engines: {node: '>= 18'}+ peerDependencies:+ jiti: '>=1.21.0'+ postcss: '>=8.0.9'+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ jiti:+ optional: true+ postcss:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-xdB1oSLHbz1vRWgCDalrCqEFTWzFlhqFC5tIHLMOSUIjhm3XXQ1qrFy8S/ESr1JYRRXqM3c1QFiMZUJdUTqyMQ==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}+ engines: {node: '>=10'}+ deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.+ hasBin: true++ resolution: {integrity: sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==}++ resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}++ resolution: {integrity: sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==}+ hasBin: true++ resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==}+ engines: {node: '>=0.6'}++ resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==}++ resolution: {integrity: sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}+ engines: {node: '>= 0.10'}++ resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}+ hasBin: true++ resolution: {integrity: sha512-cq/o30z9W2Wb4rzBefjv5fBalHU0rJGZCHAkf/RHSBWSSYwh8PlQTqqOJmgIIbBtpj27T6FIPXeomIjZtCNVqA==}++ resolution: {integrity: sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==}+ engines: {node: '>=0.10.0'}+ peerDependencies:+ react: ^18.3.1++ resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}+ engines: {node: '>= 14.18.0'}++ resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==}+ engines: {node: '>= 12.13.0'}++ resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==}++ resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}++ resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}++ resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}++ resolution: {integrity: sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==}++ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}++ resolution: {integrity: sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}++ resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}++ resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}++ resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}++ resolution: {integrity: sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}+ engines: {node: '>= 10.x'}++ resolution: {integrity: sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A==}++ resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}++ resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}++ resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}++ resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}++ resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}+ engines: {node: '>=16 || 14 >=14.17'}+ hasBin: true++ resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==}++ resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}+ engines: {node: '>=0.8'}++ resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}++ resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}++ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}+ engines: {node: ^18.0.0 || >=20.0.0}++ resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}+ engines: {node: '>=0.6'}++ resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}++ resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}+ hasBin: true++ resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}++ resolution: {integrity: sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==}+ engines: {node: '>=0.6.x'}++ resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==}+ engines: {node: '>=18'}+ hasBin: true+ peerDependencies:+ '@microsoft/api-extractor': ^7.36.0+ '@swc/core': ^1+ postcss: ^8.4.12+ typescript: '>=4.5.0'+ peerDependenciesMeta:+ '@microsoft/api-extractor':+ optional: true+ '@swc/core':+ optional: true+ postcss:+ optional: true+ typescript:+ optional: true++ resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}++ resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}+ engines: {node: '>=16'}++ resolution: {integrity: sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==}++ resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}++ resolution: {integrity: sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==}+ engines: {node: '>=18.17'}++ resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}++ resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).+ hasBin: true++ resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true++ resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ lightningcss: ^1.21.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ lightningcss:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@types/debug': ^4.1.12+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0+ '@vitest/browser': 3.2.7+ '@vitest/ui': 3.2.7+ happy-dom: '*'+ jsdom: '*'+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@types/debug':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true++ resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}++ resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}++ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}+ engines: {node: '>=8'}+ hasBin: true++ resolution: {integrity: sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}++ resolution: {integrity: sha512-zS54Oen9bITtp7kp2XM3AydrCIq1D+HwJOuH+c+e4LfpL/lotP5osijd+UoMnxwAam1GN8R4KtLAyIrIcBNpiA==}+ engines: {node: '>=8.3.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: ^5.0.2+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true++ resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==}+ engines: {node: '>= 14.6'}+ hasBin: true++ resolution: {integrity: sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==}++ resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}++snapshots:++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.14+ '@ai-sdk/provider-utils': 4.0.38([email protected])+ zod: 3.25.76++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.14+ '@ai-sdk/provider-utils': 4.0.38([email protected])+ zod: 3.25.76++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.14+ '@ai-sdk/provider-utils': 4.0.38([email protected])+ '@vercel/oidc': 3.2.0+ zod: 3.25.76++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.14+ '@ai-sdk/provider-utils': 4.0.38([email protected])+ zod: 3.25.76++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 1.1.3+ nanoid: 3.3.16+ secure-json-parse: 2.7.0+ zod: 3.25.76++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 3.0.14+ '@standard-schema/spec': 1.1.0+ eventsource-parser: 3.1.0+ zod: 3.25.76++ '@ai-sdk/[email protected]':+ dependencies:+ json-schema: 0.4.0++ '@ai-sdk/[email protected]':+ dependencies:+ json-schema: 0.4.0++ '@alcalzone/[email protected]':+ dependencies:+ ansi-styles: 6.2.3+ is-fullwidth-code-point: 4.0.0++ '@discordjs/[email protected]':+ dependencies:+ '@discordjs/formatters': 0.6.2+ '@discordjs/util': 1.2.0+ '@sapphire/shapeshift': 4.0.0+ discord-api-types: 0.38.49+ fast-deep-equal: 3.1.3+ ts-mixer: 6.0.4+ tslib: 2.8.1++ '@discordjs/[email protected]': {}++ '@discordjs/[email protected]': {}++ '@discordjs/[email protected]':+ dependencies:+ discord-api-types: 0.38.49++ '@discordjs/[email protected]':+ dependencies:+ '@discordjs/collection': 2.1.1+ '@discordjs/util': 1.2.0+ '@sapphire/async-queue': 1.5.5+ '@sapphire/snowflake': 3.5.5+ '@vladfrangu/async_event_emitter': 2.4.7+ discord-api-types: 0.38.49+ magic-bytes.js: 1.13.0+ tslib: 2.8.1+ undici: 6.24.1++ '@discordjs/[email protected]':+ dependencies:+ discord-api-types: 0.38.49++ '@discordjs/[email protected]':+ dependencies:+ '@discordjs/collection': 2.1.1+ '@discordjs/rest': 2.6.1+ '@discordjs/util': 1.2.0+ '@sapphire/async-queue': 1.5.5+ '@types/ws': 8.18.1+ '@vladfrangu/async_event_emitter': 2.4.7+ discord-api-types: 0.38.49+ tslib: 2.8.1+ ws: 8.21.0+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@grammyjs/[email protected]([email protected])':+ dependencies:+ debug: 4.4.3+ grammy: 1.44.0+ transitivePeerDependencies:+ - supports-color++ '@grammyjs/[email protected]': {}++ '@hono/[email protected]([email protected])':+ dependencies:+ hono: 4.12.30++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.5.5++ '@opentelemetry/[email protected]': {}++ '@pinojs/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@sapphire/[email protected]': {}++ '@sapphire/[email protected]':+ dependencies:+ fast-deep-equal: 3.1.3+ lodash: 4.18.1++ '@sapphire/[email protected]': {}++ '@sapphire/[email protected]': {}++ '@slack/[email protected](@types/[email protected])':+ dependencies:+ '@slack/logger': 4.0.1+ '@slack/oauth': 3.0.5+ '@slack/socket-mode': 2.0.7+ '@slack/types': 2.22.0+ '@slack/web-api': 7.19.0+ '@types/express': 5.0.6+ axios: 1.18.1+ express: 5.2.1+ path-to-regexp: 8.4.2+ raw-body: 3.0.2+ tsscmp: 1.0.6+ transitivePeerDependencies:+ - bufferutil+ - debug+ - supports-color+ - utf-8-validate++ '@slack/[email protected]':+ dependencies:+ '@types/node': 22.20.1++ '@slack/[email protected]':+ dependencies:+ '@slack/logger': 4.0.1+ '@slack/web-api': 7.19.0+ '@types/jsonwebtoken': 9.0.10+ '@types/node': 22.20.1+ jsonwebtoken: 9.0.3+ transitivePeerDependencies:+ - debug+ - supports-color++ '@slack/[email protected]':+ dependencies:+ '@slack/logger': 4.0.1+ '@slack/web-api': 7.19.0+ '@types/node': 22.20.1+ '@types/ws': 8.18.1+ eventemitter3: 5.0.4+ ws: 8.21.0+ transitivePeerDependencies:+ - bufferutil+ - debug+ - supports-color+ - utf-8-validate++ '@slack/[email protected]': {}++ '@slack/[email protected]':+ dependencies:+ '@slack/logger': 4.0.1+ '@slack/types': 2.22.0+ '@types/node': 22.20.1+ '@types/retry': 0.12.0+ axios: 1.18.1+ eventemitter3: 5.0.4+ form-data: 4.0.6+ is-electron: 2.2.2+ is-stream: 2.0.1+ p-queue: 6.6.2+ p-retry: 4.6.2+ retry: 0.13.1+ transitivePeerDependencies:+ - debug+ - supports-color++ '@standard-schema/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ bcryptjs: 3.0.3++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.1++ '@types/[email protected]':+ dependencies:+ '@types/connect': 3.4.38+ '@types/node': 22.20.1++ '@types/[email protected]':+ dependencies:+ '@types/deep-eql': 4.0.2+ assertion-error: 2.0.1++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.1++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.1+ '@types/qs': 6.15.1+ '@types/range-parser': 1.2.7+ '@types/send': 1.2.1++ '@types/[email protected]':+ dependencies:+ '@types/body-parser': 1.19.6+ '@types/express-serve-static-core': 5.1.2+ '@types/serve-static': 2.2.0++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/ms': 2.1.0+ '@types/node': 22.20.1++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 6.21.0++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/prop-types': 15.7.15+ csstype: 3.2.3++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.1++ '@types/[email protected]':+ dependencies:+ '@types/http-errors': 2.0.5+ '@types/node': 22.20.1++ '@types/[email protected]':+ dependencies:+ '@types/node': 22.20.1++ '@vercel/[email protected]': {}++ '@vitest/[email protected]':+ dependencies:+ '@types/chai': 5.2.3+ '@vitest/spy': 3.2.7+ '@vitest/utils': 3.2.7+ chai: 5.3.3+ tinyrainbow: 2.0.0++ dependencies:+ '@vitest/spy': 3.2.7+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+ vite: 7.3.6(@types/[email protected])([email protected])++ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 2.0.0++ '@vitest/[email protected]':+ dependencies:+ '@vitest/utils': 3.2.7+ pathe: 2.0.3+ strip-literal: 3.1.0++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.7+ magic-string: 0.30.21+ pathe: 2.0.3++ '@vitest/[email protected]':+ dependencies:+ tinyspy: 4.0.4++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.7+ loupe: 3.2.1+ tinyrainbow: 2.0.0++ '@vladfrangu/[email protected]': {}++ dependencies:+ event-target-shim: 5.0.1++ dependencies:+ mime-types: 3.0.2+ negotiator: 1.0.0++ [email protected]: {}++ dependencies:+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@ai-sdk/gateway': 3.0.148([email protected])+ '@ai-sdk/provider': 3.0.14+ '@ai-sdk/provider-utils': 4.0.38([email protected])+ '@opentelemetry/api': 1.9.1+ zod: 3.25.76++ dependencies:+ environment: 1.1.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ follow-redirects: 1.16.0+ form-data: 4.0.6+ https-proxy-agent: 5.0.1+ proxy-from-env: 2.1.0+ transitivePeerDependencies:+ - debug+ - supports-color++ optional: true++ [email protected]: {}++ dependencies:+ bindings: 1.5.0+ prebuild-install: 7.1.3+ optional: true++ dependencies:+ file-uri-to-path: 1.0.0+ optional: true++ dependencies:+ buffer: 5.7.1+ inherits: 2.0.4+ readable-stream: 3.6.2+ optional: true++ dependencies:+ bytes: 3.1.2+ content-type: 2.0.0+ debug: 4.4.3+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ on-finished: 2.4.1+ qs: 6.15.3+ raw-body: 3.0.2+ type-is: 2.1.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ base64-js: 1.5.1+ ieee754: 1.2.1+ optional: true++ dependencies:+ esbuild: 0.27.7+ load-tsconfig: 0.2.5++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ function-bind: 1.1.2++ dependencies:+ call-bind-apply-helpers: 1.0.2+ get-intrinsic: 1.3.0++ dependencies:+ assertion-error: 2.0.1+ check-error: 2.1.3+ deep-eql: 5.0.2+ loupe: 3.2.1+ pathval: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ readdirp: 4.1.2++ optional: true++ [email protected]: {}++ dependencies:+ restore-cursor: 4.0.0++ dependencies:+ slice-ansi: 5.0.0+ string-width: 7.2.0++ dependencies:+ convert-to-spaces: 2.0.1++ dependencies:+ delayed-stream: 1.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ms: 2.1.3++ dependencies:+ mimic-response: 3.1.0+ optional: true++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ '@discordjs/builders': 1.14.1+ '@discordjs/collection': 1.5.3+ '@discordjs/formatters': 0.6.2+ '@discordjs/rest': 2.6.1+ '@discordjs/util': 1.2.0+ '@discordjs/ws': 1.2.3+ '@sapphire/snowflake': 3.5.3+ discord-api-types: 0.38.49+ fast-deep-equal: 3.1.3+ lodash.snakecase: 4.1.1+ magic-bytes.js: 1.13.0+ tslib: 2.8.1+ undici: 6.24.1+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-errors: 1.3.0+ gopd: 1.2.0++ dependencies:+ safe-buffer: 5.2.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ once: 1.4.0+ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0++ dependencies:+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ has-tostringtag: 1.0.2+ hasown: 2.0.4++ [email protected]: {}++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.27.7+ '@esbuild/android-arm': 0.27.7+ '@esbuild/android-arm64': 0.27.7+ '@esbuild/android-x64': 0.27.7+ '@esbuild/darwin-arm64': 0.27.7+ '@esbuild/darwin-x64': 0.27.7+ '@esbuild/freebsd-arm64': 0.27.7+ '@esbuild/freebsd-x64': 0.27.7+ '@esbuild/linux-arm': 0.27.7+ '@esbuild/linux-arm64': 0.27.7+ '@esbuild/linux-ia32': 0.27.7+ '@esbuild/linux-loong64': 0.27.7+ '@esbuild/linux-mips64el': 0.27.7+ '@esbuild/linux-ppc64': 0.27.7+ '@esbuild/linux-riscv64': 0.27.7+ '@esbuild/linux-s390x': 0.27.7+ '@esbuild/linux-x64': 0.27.7+ '@esbuild/netbsd-arm64': 0.27.7+ '@esbuild/netbsd-x64': 0.27.7+ '@esbuild/openbsd-arm64': 0.27.7+ '@esbuild/openbsd-x64': 0.27.7+ '@esbuild/openharmony-arm64': 0.27.7+ '@esbuild/sunos-x64': 0.27.7+ '@esbuild/win32-arm64': 0.27.7+ '@esbuild/win32-ia32': 0.27.7+ '@esbuild/win32-x64': 0.27.7++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.28.1+ '@esbuild/android-arm': 0.28.1+ '@esbuild/android-arm64': 0.28.1+ '@esbuild/android-x64': 0.28.1+ '@esbuild/darwin-arm64': 0.28.1+ '@esbuild/darwin-x64': 0.28.1+ '@esbuild/freebsd-arm64': 0.28.1+ '@esbuild/freebsd-x64': 0.28.1+ '@esbuild/linux-arm': 0.28.1+ '@esbuild/linux-arm64': 0.28.1+ '@esbuild/linux-ia32': 0.28.1+ '@esbuild/linux-loong64': 0.28.1+ '@esbuild/linux-mips64el': 0.28.1+ '@esbuild/linux-ppc64': 0.28.1+ '@esbuild/linux-riscv64': 0.28.1+ '@esbuild/linux-s390x': 0.28.1+ '@esbuild/linux-x64': 0.28.1+ '@esbuild/netbsd-arm64': 0.28.1+ '@esbuild/netbsd-x64': 0.28.1+ '@esbuild/openbsd-arm64': 0.28.1+ '@esbuild/openbsd-x64': 0.28.1+ '@esbuild/openharmony-arm64': 0.28.1+ '@esbuild/sunos-x64': 0.28.1+ '@esbuild/win32-arm64': 0.28.1+ '@esbuild/win32-ia32': 0.28.1+ '@esbuild/win32-x64': 0.28.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ accepts: 2.0.0+ body-parser: 2.3.0+ content-disposition: 1.1.0+ content-type: 1.0.5+ cookie: 0.7.2+ cookie-signature: 1.2.2+ debug: 4.4.3+ depd: 2.0.0+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ finalhandler: 2.1.1+ fresh: 2.0.0+ http-errors: 2.0.1+ merge-descriptors: 2.0.0+ mime-types: 3.0.2+ on-finished: 2.4.1+ once: 1.4.0+ parseurl: 1.3.3+ proxy-addr: 2.0.7+ qs: 6.15.3+ range-parser: 1.3.0+ router: 2.2.0+ send: 1.2.1+ serve-static: 2.2.1+ statuses: 2.0.2+ type-is: 2.1.0+ vary: 1.1.2+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ optionalDependencies:+ picomatch: 4.0.5++ optional: true++ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ on-finished: 2.4.1+ parseurl: 1.3.3+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ magic-string: 0.30.21+ mlly: 1.8.2+ rollup: 4.62.2++ [email protected]: {}++ dependencies:+ asynckit: 0.4.0+ combined-stream: 1.0.8+ es-set-tostringtag: 2.1.0+ hasown: 2.0.4+ mime-types: 2.1.35++ [email protected]: {}++ [email protected]: {}++ optional: true++ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-define-property: 1.0.1+ es-errors: 1.3.0+ es-object-atoms: 1.1.2+ function-bind: 1.1.2+ get-proto: 1.0.1+ gopd: 1.2.0+ has-symbols: 1.1.0+ hasown: 2.0.4+ math-intrinsics: 1.1.0++ dependencies:+ dunder-proto: 1.0.1+ es-object-atoms: 1.1.2++ optional: true++ [email protected]: {}++ dependencies:+ '@grammyjs/types': 3.28.0+ abort-controller: 3.0.0+ debug: 4.4.3+ node-fetch: 2.7.0+ transitivePeerDependencies:+ - encoding+ - supports-color++ [email protected]: {}++ dependencies:+ has-symbols: 1.1.0++ dependencies:+ function-bind: 1.1.2++ [email protected]: {}++ dependencies:+ depd: 2.0.0+ inherits: 2.0.4+ setprototypeof: 1.2.0+ statuses: 2.0.2+ toidentifier: 1.0.1++ dependencies:+ agent-base: 6.0.2+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ safer-buffer: 2.1.2++ optional: true++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ '@alcalzone/ansi-tokenize': 0.1.3+ ansi-escapes: 7.3.0+ ansi-styles: 6.2.3+ auto-bind: 5.0.1+ chalk: 5.6.2+ cli-boxes: 3.0.0+ cli-cursor: 4.0.0+ cli-truncate: 4.0.0+ code-excerpt: 4.0.0+ es-toolkit: 1.49.0+ indent-string: 5.0.0+ is-in-ci: 1.0.0+ patch-console: 2.0.0+ react: 18.3.1+ react-reconciler: 0.29.2([email protected])+ scheduler: 0.23.2+ signal-exit: 3.0.7+ slice-ansi: 7.1.2+ stack-utils: 2.0.6+ string-width: 7.2.0+ type-fest: 4.41.0+ widest-line: 5.0.0+ wrap-ansi: 9.0.2+ ws: 8.21.0+ yoga-layout: 3.2.1+ optionalDependencies:+ '@types/react': 18.3.31+ react-devtools-core: 4.28.5+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ get-east-asian-width: 1.6.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ jws: 4.0.1+ lodash.includes: 4.3.0+ lodash.isboolean: 3.0.3+ lodash.isinteger: 4.0.4+ lodash.isnumber: 3.0.3+ lodash.isplainobject: 4.0.6+ lodash.isstring: 4.0.1+ lodash.once: 4.1.1+ ms: 2.1.3+ semver: 7.8.5++ dependencies:+ buffer-equal-constant-time: 1.0.1+ ecdsa-sig-formatter: 1.0.11+ safe-buffer: 5.2.1++ dependencies:+ jwa: 2.0.1+ safe-buffer: 5.2.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ js-tokens: 4.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ mime-db: 1.52.0++ dependencies:+ mime-db: 1.54.0++ [email protected]: {}++ optional: true++ optional: true++ optional: true++ dependencies:+ acorn: 8.17.0+ pathe: 2.0.3+ pkg-types: 1.3.1+ ufo: 1.6.4++ [email protected]: {}++ dependencies:+ any-promise: 1.3.0+ object-assign: 4.1.1+ thenify-all: 1.6.0++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ semver: 7.8.5+ optional: true++ dependencies:+ uuid: 8.3.2++ dependencies:+ whatwg-url: 5.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@ai-sdk/provider': 1.1.3+ '@ai-sdk/provider-utils': 2.2.8([email protected])+ partial-json: 0.1.7+ optionalDependencies:+ zod: 3.25.76++ [email protected]: {}++ dependencies:+ ee-first: 1.1.1++ dependencies:+ wrappy: 1.0.2++ dependencies:+ mimic-fn: 2.1.0++ [email protected]: {}++ dependencies:+ eventemitter3: 4.0.7+ p-timeout: 3.2.0++ dependencies:+ '@types/retry': 0.12.0+ retry: 0.13.1++ dependencies:+ p-finally: 1.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ split2: 4.2.0++ [email protected]: {}++ dependencies:+ '@pinojs/redact': 0.4.0+ atomic-sleep: 1.0.0+ on-exit-leak-free: 2.1.2+ pino-abstract-transport: 3.0.0+ pino-std-serializers: 7.1.0+ process-warning: 5.0.0+ quick-format-unescaped: 4.0.4+ real-require: 0.2.0+ safe-stable-stringify: 2.5.0+ sonic-boom: 4.2.1+ thread-stream: 4.2.0++ [email protected]: {}++ dependencies:+ confbox: 0.1.8+ mlly: 1.8.2+ pathe: 2.0.3++ dependencies:+ lilconfig: 3.1.3+ optionalDependencies:+ postcss: 8.5.18+ yaml: 2.9.0++ dependencies:+ nanoid: 3.3.16+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ detect-libc: 2.1.2+ expand-template: 2.0.3+ github-from-package: 0.0.0+ minimist: 1.2.8+ mkdirp-classic: 0.5.3+ napi-build-utils: 2.0.0+ node-abi: 3.94.0+ pump: 3.0.4+ rc: 1.2.8+ simple-get: 4.0.1+ tar-fs: 2.1.5+ tunnel-agent: 0.6.0+ optional: true++ [email protected]: {}++ dependencies:+ forwarded: 0.2.0+ ipaddr.js: 1.9.1++ [email protected]: {}++ dependencies:+ end-of-stream: 1.4.5+ once: 1.4.0+ optional: true++ [email protected]: {}++ dependencies:+ es-define-property: 1.0.1+ side-channel: 1.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ bytes: 3.1.2+ http-errors: 2.0.1+ iconv-lite: 0.7.3+ unpipe: 1.0.0++ dependencies:+ deep-extend: 0.6.0+ ini: 1.3.8+ minimist: 1.2.8+ strip-json-comments: 2.0.1+ optional: true++ dependencies:+ shell-quote: 1.10.0+ ws: 7.5.11+ transitivePeerDependencies:+ - bufferutil+ - utf-8-validate++ dependencies:+ loose-envify: 1.4.0+ react: 18.3.1+ scheduler: 0.23.2++ dependencies:+ loose-envify: 1.4.0++ dependencies:+ inherits: 2.0.4+ string_decoder: 1.3.0+ util-deprecate: 1.0.2+ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ onetime: 5.1.2+ signal-exit: 3.0.7++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.9+ optionalDependencies:+ '@rollup/rollup-android-arm-eabi': 4.62.2+ '@rollup/rollup-android-arm64': 4.62.2+ '@rollup/rollup-darwin-arm64': 4.62.2+ '@rollup/rollup-darwin-x64': 4.62.2+ '@rollup/rollup-freebsd-arm64': 4.62.2+ '@rollup/rollup-freebsd-x64': 4.62.2+ '@rollup/rollup-linux-arm-gnueabihf': 4.62.2+ '@rollup/rollup-linux-arm-musleabihf': 4.62.2+ '@rollup/rollup-linux-arm64-gnu': 4.62.2+ '@rollup/rollup-linux-arm64-musl': 4.62.2+ '@rollup/rollup-linux-loong64-gnu': 4.62.2+ '@rollup/rollup-linux-loong64-musl': 4.62.2+ '@rollup/rollup-linux-ppc64-gnu': 4.62.2+ '@rollup/rollup-linux-ppc64-musl': 4.62.2+ '@rollup/rollup-linux-riscv64-gnu': 4.62.2+ '@rollup/rollup-linux-riscv64-musl': 4.62.2+ '@rollup/rollup-linux-s390x-gnu': 4.62.2+ '@rollup/rollup-linux-x64-gnu': 4.62.2+ '@rollup/rollup-linux-x64-musl': 4.62.2+ '@rollup/rollup-openbsd-x64': 4.62.2+ '@rollup/rollup-openharmony-arm64': 4.62.2+ '@rollup/rollup-win32-arm64-msvc': 4.62.2+ '@rollup/rollup-win32-ia32-msvc': 4.62.2+ '@rollup/rollup-win32-x64-gnu': 4.62.2+ '@rollup/rollup-win32-x64-msvc': 4.62.2+ fsevents: 2.3.3++ dependencies:+ debug: 4.4.3+ depd: 2.0.0+ is-promise: 4.0.0+ parseurl: 1.3.3+ path-to-regexp: 8.4.2+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ loose-envify: 1.4.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ debug: 4.4.3+ encodeurl: 2.0.0+ escape-html: 1.0.3+ etag: 1.8.1+ fresh: 2.0.0+ http-errors: 2.0.1+ mime-types: 3.0.2+ ms: 2.1.3+ on-finished: 2.4.1+ range-parser: 1.3.0+ statuses: 2.0.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ encodeurl: 2.0.0+ escape-html: 1.0.3+ parseurl: 1.3.3+ send: 1.2.1+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4++ dependencies:+ call-bound: 1.0.4+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ object-inspect: 1.13.4+ side-channel-map: 1.0.1++ dependencies:+ es-errors: 1.3.0+ object-inspect: 1.13.4+ side-channel-list: 1.0.1+ side-channel-map: 1.0.1+ side-channel-weakmap: 1.0.2++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ decompress-response: 6.0.0+ once: 1.4.0+ simple-concat: 1.0.1+ optional: true++ dependencies:+ ansi-styles: 6.2.3+ is-fullwidth-code-point: 4.0.0++ dependencies:+ ansi-styles: 6.2.3+ is-fullwidth-code-point: 5.1.0++ dependencies:+ atomic-sleep: 1.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ escape-string-regexp: 2.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ emoji-regex: 10.6.0+ get-east-asian-width: 1.6.0+ strip-ansi: 7.2.0++ dependencies:+ safe-buffer: 5.2.1+ optional: true++ dependencies:+ ansi-regex: 6.2.2++ optional: true++ dependencies:+ js-tokens: 9.0.1++ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ commander: 4.1.1+ lines-and-columns: 1.2.4+ mz: 2.7.0+ pirates: 4.0.7+ tinyglobby: 0.2.17+ ts-interface-checker: 0.1.13++ dependencies:+ chownr: 1.1.4+ mkdirp-classic: 0.5.3+ pump: 3.0.4+ tar-stream: 2.2.0+ optional: true++ dependencies:+ bl: 4.1.0+ end-of-stream: 1.4.5+ fs-constants: 1.0.0+ inherits: 2.0.4+ readable-stream: 3.6.2+ optional: true++ dependencies:+ thenify: 3.3.1++ dependencies:+ any-promise: 1.3.0++ dependencies:+ real-require: 1.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.5++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ bundle-require: 5.1.0([email protected])+ cac: 6.7.14+ chokidar: 4.0.3+ consola: 3.4.2+ debug: 4.4.3+ esbuild: 0.27.7+ fix-dts-default-cjs-exports: 1.0.1+ joycon: 3.1.1+ picocolors: 1.1.1+ postcss-load-config: 6.0.1([email protected])([email protected])+ resolve-from: 5.0.0+ rollup: 4.62.2+ source-map: 0.7.6+ sucrase: 3.35.1+ tinyexec: 0.3.2+ tinyglobby: 0.2.17+ tree-kill: 1.2.2+ optionalDependencies:+ postcss: 8.5.18+ typescript: 5.9.3+ transitivePeerDependencies:+ - jiti+ - supports-color+ - tsx+ - yaml++ dependencies:+ safe-buffer: 5.2.1+ optional: true++ [email protected]: {}++ dependencies:+ content-type: 2.0.0+ media-typer: 1.1.0+ mime-types: 3.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cac: 6.7.14+ debug: 4.4.3+ es-module-lexer: 1.7.0+ pathe: 2.0.3+ vite: 7.3.6(@types/[email protected])([email protected])+ transitivePeerDependencies:+ - '@types/node'+ - jiti+ - less+ - lightningcss+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ dependencies:+ esbuild: 0.28.1+ fdir: 6.5.0([email protected])+ picomatch: 4.0.5+ postcss: 8.5.18+ rollup: 4.62.2+ tinyglobby: 0.2.17+ optionalDependencies:+ '@types/node': 22.20.1+ fsevents: 2.3.3+ yaml: 2.9.0++ dependencies:+ '@types/chai': 5.2.3+ '@vitest/expect': 3.2.7+ '@vitest/pretty-format': 3.2.7+ '@vitest/runner': 3.2.7+ '@vitest/snapshot': 3.2.7+ '@vitest/spy': 3.2.7+ '@vitest/utils': 3.2.7+ chai: 5.3.3+ debug: 4.4.3+ expect-type: 1.4.0+ magic-string: 0.30.21+ pathe: 2.0.3+ picomatch: 4.0.5+ std-env: 3.10.0+ tinybench: 2.9.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.17+ tinypool: 1.1.1+ tinyrainbow: 2.0.0+ vite: 7.3.6(@types/[email protected])([email protected])+ vite-node: 3.2.4(@types/[email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/node': 22.20.1+ transitivePeerDependencies:+ - jiti+ - less+ - lightningcss+ - msw+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ [email protected]: {}++ dependencies:+ tr46: 0.0.3+ webidl-conversions: 3.0.1++ dependencies:+ siginfo: 2.0.0+ stackback: 0.0.2++ dependencies:+ string-width: 7.2.0++ dependencies:+ ansi-styles: 6.2.3+ string-width: 7.2.0+ strip-ansi: 7.2.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}diff --git a/random_message.txt b/random_message.txtdeleted file mode 100644index de7ab117..00000000--- a/random_message.txt+++ /dev/null@@ -1,3 +0,0 @@-This is a random text file sent just for fun. 🎲--— From Mercurydiff --git a/scripts/build-bin.cjs b/scripts/build-bin.cjsindex 923a952d..9583f05b 100644--- a/scripts/build-bin.cjs+++ b/scripts/build-bin.cjs@@ -7,7 +7,7 @@* and Node SEA require CJS entry points. Bun runs ESM natively and* embeds its own JS runtime, so it sidesteps the whole problem.*- * Output layout (versioned, never clobbers older builds):+ * Output layout (versioned, never clobbers older releases):* release/* v1.1.9/* mercury-macos-arm64@@ -15,16 +15,15 @@* mercury-linux-x64* mercury-linux-arm64* mercury-win-x64.exe- * web/ ← static assets for the web dashboard- * static/...- * ui/...+ * web.tar.gz* checksums.txt* v1.2.0/ ...+ * smoke/v1.2.0/ ... ← non-publishable host-only builds* latest -> v1.2.0 (symlink to most-recent build)*- * Version is read from package.json. Bumping the version there automatically- * produces a new folder on the next build. If a binary already exists for- * the current version+target, the script skips it unless --force is passed.+ * `--all` is the release-producing mode. It refuses to mix with an existing+ * version directory unless --force is passed, in which case the directory is+ * deleted first. Host builds are isolated under release/smoke.** Usage:* node scripts/build-bin.cjs # host target only@@ -34,11 +33,10 @@** Cross-compilation:* Bun ships its own runtime per target, so cross-compile works for JS.- * Native modules (e.g. better-sqlite3) cannot cross-compile, but- * Mercury's better-sqlite3 is optional and falls back to sql.js, so- * cross-compiled binaries still work end-to-end.+ * Native addons still need target-specific packaging; sql.js is not a+ * general fallback for every better-sqlite3-backed feature.*/-const { execSync } = require('node:child_process');+const { execFileSync, execSync, spawnSync } = require('node:child_process');const crypto = require('node:crypto');const fs = require('node:fs');const path = require('node:path');@@ -51,6 +49,7 @@ const entry = path.join(root, 'dist', 'index.js');function copyDirSync(src, dest) {fs.mkdirSync(dest, { recursive: true });for (const entry of fs.readdirSync(src, { withFileTypes: true })) {+ if (entry.name === '.DS_Store' || entry.name.endsWith('.map')) continue;const srcPath = path.join(src, entry.name);const destPath = path.join(dest, entry.name);if (entry.isDirectory()) {@@ -64,7 +63,6 @@ function copyDirSync(src, dest) {// Read version straight from package.json — single source of truth.const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));const version = pkg.version;-const versionDir = path.join(releaseRoot, `v${version}`);// All Bun-supported targets we want to ship. The `out` name is the file// basename (without the version prefix — version lives in the parent folder).@@ -86,20 +84,21 @@ function hostTarget() {process.exit(1);}const id = `bun-${platMap[platform]}-${archMap[arch]}`;- // Match the same naming scheme as --all so files are predictable.- const platName = platform === 'darwin' ? 'macos' : platMap[platform];- const ext = platform === 'win32' ? '.exe' : '';- const out = `mercury-${platName}-${arch}${ext}`;- return { id, out };+ const target = ALL_TARGETS.find((candidate) => candidate.id === id);+ if (!target) {+ console.error(`Unsupported host target: ${id}`);+ process.exit(1);+ }+ return target;}function findBun() {- try {- execSync('command -v bun', { stdio: 'pipe' });- return 'bun';- } catch (_) {}- const fallback = path.join(os.homedir(), '.bun', 'bin', 'bun');- if (fs.existsSync(fallback)) return fallback;+ const executable = process.platform === 'win32' ? 'bun.exe' : 'bun';+ const candidates = [executable, path.join(os.homedir(), '.bun', 'bin', executable)];+ for (const candidate of candidates) {+ const result = spawnSync(candidate, ['--version'], { stdio: 'ignore' });+ if (!result.error && result.status === 0) return candidate;+ }console.error('ERROR: bun not found. Install it from https://bun.sh');process.exit(1);}@@ -109,13 +108,17 @@ function run(cmd) {execSync(cmd, { cwd: root, stdio: 'inherit' });}+function sleepSync(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}+function sha256(filePath) {const hash = crypto.createHash('sha256');hash.update(fs.readFileSync(filePath));return hash.digest('hex');}-function compile(bun, target, { force }) {+function compile(bun, target, { force, versionDir }) {const outPath = path.join(versionDir, target.out);if (fs.existsSync(outPath) && !force) {@@ -134,7 +137,20 @@ function compile(bun, target, { force }) {`--outfile="${outPath.replace(/\.exe$/, '')}"`,'--minify',];- run(`"${bun}" ${args.join(' ')}`);+ const command = `"${bun}" ${args.join(' ')}`;+ for (let attempt = 1; attempt <= 3; attempt++) {+ try {+ run(command);+ break;+ } catch (error) {+ fs.rmSync(outPath, { force: true });+ fs.rmSync(outPath.replace(/\.exe$/, ''), { force: true });+ if (attempt === 3) throw error;+ const delay = attempt * 2_000;+ console.warn(` ! ${target.id} compile failed; retrying in ${delay / 1000}s (${attempt}/3)`);+ sleepSync(delay);+ }+ }// Bun appends .exe for windows targets automatically — handle both names.if (!fs.existsSync(outPath)) {@@ -142,43 +158,38 @@ function compile(bun, target, { force }) {if (fs.existsSync(alt) && target.out.endsWith('.exe')) fs.renameSync(alt, outPath);}- // Copy web assets (UI + static) alongside the binary so the web dashboard- // works in standalone mode. server.ts resolves these relative to execPath- // when running as a Bun-compiled binary.- const webSrc = path.join(root, 'dist', 'web');- const webDest = path.join(versionDir, 'web');- if (fs.existsSync(webSrc)) {- copyDirSync(webSrc, webDest);- console.log(` ✓ web assets copied to ${path.relative(root, webDest)}`);- } else {- console.warn(` ⚠ dist/web/ not found — web dashboard will not work in the binary`);- console.warn(` Run \`npm run build\` first to generate web assets.`);- }-const stat = fs.statSync(outPath);const sizeMB = (stat.size / (1024 * 1024)).toFixed(1);console.log(` ✓ ${path.relative(root, outPath)} (${sizeMB} MB)\n`);return { outPath, skipped: false };}-function writeChecksums(builtPaths) {- const checksumsPath = path.join(versionDir, 'checksums.txt');- // Collect all files in versionDir (including web/ subdirectory)- const files = [];- function walk(dir, base) {- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const fullPath = path.join(dir, entry.name);- const relPath = base ? `${base}/${entry.name}` : entry.name;- if (entry.isDirectory()) {- walk(fullPath, relPath);- } else if (entry.name !== 'checksums.txt') {- files.push({ fullPath, relPath });- }- }+function createWebArchive(versionDir, { required }) {+ const webSrc = path.join(root, 'dist', 'web');+ const webDest = path.join(versionDir, 'web');+ const webTarPath = path.join(versionDir, 'web.tar.gz');+ fs.rmSync(webDest, { recursive: true, force: true });+ fs.rmSync(webTarPath, { force: true });++ if (!fs.existsSync(webSrc)) {+ const message = 'dist/web/ not found. Run `npm run build` first.';+ if (required) throw new Error(message);+ console.warn(` ⚠ ${message} Skipping web.tar.gz for this smoke build.`);+ return null;}- walk(versionDir, '');- files.sort((a, b) => a.relPath.localeCompare(b.relPath));- const lines = files.map(({ fullPath, relPath }) => `${sha256(fullPath)} ${relPath}`);++ copyDirSync(webSrc, webDest);+ execFileSync('tar', ['-czf', webTarPath, '-C', versionDir, 'web'], { cwd: root, stdio: 'pipe' });+ if (required) fs.rmSync(webDest, { recursive: true, force: true });+ const sizeKB = (fs.statSync(webTarPath).size / 1024).toFixed(0);+ console.log(` ✓ web.tar.gz (${sizeKB} KB)`);+ return webTarPath;+}++function writeChecksums(versionDir, assetPaths) {+ const checksumsPath = path.join(versionDir, 'checksums.txt');+ const files = assetPaths.filter(Boolean).sort((a, b) => path.basename(a).localeCompare(path.basename(b)));+ const lines = files.map((filePath) => `${sha256(filePath)} ${path.basename(filePath)}`);fs.writeFileSync(checksumsPath, lines.join('\n') + '\n');console.log(` ✓ checksums.txt (${files.length} file${files.length === 1 ? '' : 's'})`);}@@ -205,41 +216,49 @@ if (!fs.existsSync(entry)) {const args = process.argv.slice(2);const buildAll = args.includes('--all');const force = args.includes('--force');+const unknownArgs = args.filter((arg) => arg !== '--all' && arg !== '--force');+if (unknownArgs.length > 0) {+ console.error(`ERROR: unknown argument(s): ${unknownArgs.join(', ')}`);+ process.exit(1);+}+const versionDir = buildAll+ ? path.join(releaseRoot, `v${version}`)+ : path.join(releaseRoot, 'smoke', `v${version}`);+if (!buildAll && force) fs.rmSync(versionDir, { recursive: true, force: true });+if (buildAll && fs.existsSync(versionDir)) {+ if (!force && fs.readdirSync(versionDir).length > 0) {+ console.error(`ERROR: ${path.relative(root, versionDir)} already contains release assets.`);+ console.error('Refusing to mix revisions. Re-run with --all --force to replace the entire release directory.');+ process.exit(1);+ }+ fs.rmSync(versionDir, { recursive: true, force: true });+}fs.mkdirSync(versionDir, { recursive: true });const bun = findBun();const targets = buildAll ? ALL_TARGETS : [hostTarget()];-console.log(`\nMercury v${version} — building ${targets.length} target(s) with ${bun}`);+console.log(`\nMercury v${version} — building ${targets.length} ${buildAll ? 'release' : 'host smoke'} target(s) with ${bun}`);console.log(`Output: ${path.relative(root, versionDir)}/${force ? ' (force overwrite)' : ''}\n`);const results = [];for (const target of targets) {console.log(`→ ${target.id}`);- results.push(compile(bun, target, { force }));+ results.push(compile(bun, target, { force, versionDir }));}-writeChecksums(results.map((r) => r.outPath));+const webTarPath = createWebArchive(versionDir, { required: buildAll });+writeChecksums(versionDir, [...results.map((result) => result.outPath), webTarPath]);-// Create a web.tar.gz for GitHub release uploads so installers can fetch-// dashboard assets separately (the binary doesn't embed them).-const webDir = path.join(root, 'dist', 'web');-if (fs.existsSync(webDir)) {- const webTarPath = path.join(versionDir, 'web.tar.gz');- try {- execSync(`tar -czf "${webTarPath}" -C "${path.dirname(webDir)}" web`, { cwd: root, stdio: 'pipe' });- const sizeKB = (fs.statSync(webTarPath).size / 1024).toFixed(0);- console.log(` ✓ web.tar.gz (${sizeKB} KB)`);- } catch (e) {- console.warn(` ⚠ Failed to create web.tar.gz: ${e.message}`);- }-} else {- console.warn(' ⚠ dist/web/ not found — skipping web.tar.gz');+if (buildAll) {+ execFileSync(process.execPath, [path.join(__dirname, 'verify-standalone-release.cjs'), versionDir], {+ cwd: root,+ stdio: 'inherit',+ });+ updateLatestSymlink();}-updateLatestSymlink();-const built = results.filter((r) => !r.skipped).length;const skipped = results.length - built;console.log(`\nDone. ${built} built, ${skipped} skipped. Binaries in ${path.relative(root, versionDir)}/`);diff --git a/scripts/check-native-deps.js b/scripts/check-native-deps.jsindex 108128c6..c17c6fab 100644--- a/scripts/check-native-deps.js+++ b/scripts/check-native-deps.js@@ -1,6 +1,6 @@#!/usr/bin/env node-const { execSync } = require('child_process');-const { platform } = require('os');+import { execFileSync } from 'node:child_process';+import { platform } from 'node:os';console.log('\u263F Checking native build prerequisites for better-sqlite3...\n');@@ -52,11 +52,10 @@ if (!missing) {function commandExists(cmd) {const isWin = platform() === 'win32';- const checkCmd = isWin ? `where ${cmd}` : `command -v ${cmd}`;try {- execSync(checkCmd, { stdio: 'pipe' });+ execFileSync(isWin ? 'where.exe' : 'sh', isWin ? [cmd] : ['-c', 'command -v "$1"', 'sh', cmd], { stdio: 'pipe' });return true;} catch {return false;}-}\ No newline at end of file+}diff --git a/scripts/install.ps1 b/scripts/install.ps1index c3063684..1ea3265c 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -41,6 +41,16 @@ function Resolve-LatestVersion {Die "Could not determine the latest Mercury version from $final"}+function Get-RequiredChecksum ([string]$Checksums, [string]$Asset) {+ $matches = @($Checksums -split "`r?`n" |+ Where-Object { $_ -match "^[a-fA-F0-9]{64}\s+$([regex]::Escape($Asset))\s*$" } |+ ForEach-Object { ($_ -split '\s+')[0] })+ if ($matches.Count -ne 1) {+ Die "checksums.txt must contain exactly one checksum for $Asset"+ }+ return $matches[0].ToLower()+}+function Update-UserPath ([string]$BinDir) {if ($env:MERCURY_NO_PATH -eq '1') { return $false }@@ -94,63 +104,72 @@ if ([string]::IsNullOrEmpty($prefix)) { $prefix = Join-Path $HOME '.mercury' }$binDir = Join-Path $prefix 'bin'$binPath = Join-Path $binDir 'mercury.exe'-New-Item -ItemType Directory -Force -Path $binDir | Out-Null+$tmpDir = Join-Path $env:TEMP ("mercury-" + [guid]::NewGuid().ToString('N'))+New-Item -ItemType Directory -Path $tmpDir | Out-Null+$binaryTmp = Join-Path $tmpDir $asset+$webTmp = Join-Path $tmpDir 'web.tar.gz'+$stageDir = Join-Path $tmpDir 'stage'-$tmp = Join-Path $env:TEMP ("mercury-" + [guid]::NewGuid().ToString('N') + '.exe')--Write-Info "Downloading $asset ..."try {- Invoke-WebRequest -Uri $url -OutFile $tmp -UseBasicParsing-}-catch {- Die @"+ $checksumsUrl = "$GhDl/v$version/checksums.txt"+ Write-Info 'Downloading checksums.txt ...'+ try {+ $checksums = (Invoke-WebRequest -Uri $checksumsUrl -UseBasicParsing).Content+ } catch {+ Die "Failed to download required checksums from $checksumsUrl"+ }+ $expectedBinary = Get-RequiredChecksum -Checksums $checksums -Asset $asset+ $expectedWeb = Get-RequiredChecksum -Checksums $checksums -Asset 'web.tar.gz'++ Write-Info "Downloading $asset ..."+ try {+ Invoke-WebRequest -Uri $url -OutFile $binaryTmp -UseBasicParsing+ } catch {+ Die @"Failed to download $urlThe binary for v$version on win-x64 may not have been published yet.Browse releases: https://github.com/$Repo/releases"@-}+ }-# Optional sha256 verification against the release's checksums.txt.-try {- $checksumsUrl = "$GhDl/v$version/checksums.txt"- $checksums = (Invoke-WebRequest -Uri $checksumsUrl -UseBasicParsing).Content- $expected = ($checksums -split "`n" |- Where-Object { $_ -match "\s+$([regex]::Escape($asset))\s*$" } |- ForEach-Object { ($_ -split '\s+')[0] } |- Select-Object -First 1)- if ($expected) {- $actual = (Get-FileHash -Algorithm SHA256 -Path $tmp).Hash.ToLower()- if ($actual -ne $expected.ToLower()) {- Remove-Item $tmp -Force -ErrorAction SilentlyContinue- Die "Checksum mismatch for $asset`n expected: $expected`n actual: $actual"- }- Write-Info 'Checksum verified (sha256)'+ $webTarUrl = "$GhDl/v$version/web.tar.gz"+ Write-Info 'Downloading web.tar.gz ...'+ Invoke-WebRequest -Uri $webTarUrl -OutFile $webTmp -UseBasicParsing++ $actualBinary = (Get-FileHash -Algorithm SHA256 -Path $binaryTmp).Hash.ToLower()+ if ($actualBinary -ne $expectedBinary) {+ Die "Checksum mismatch for $asset`n expected: $expectedBinary`n actual: $actualBinary"}-}-catch {- # checksums.txt is optional — fall through silently.-}+ $actualWeb = (Get-FileHash -Algorithm SHA256 -Path $webTmp).Hash.ToLower()+ if ($actualWeb -ne $expectedWeb) {+ Die "Checksum mismatch for web.tar.gz`n expected: $expectedWeb`n actual: $actualWeb"+ }+ Write-Info 'Checksums verified (sha256)'-# Replace any existing install (Windows can't overwrite a running .exe — let-# Move-Item surface that error if it happens, so the user knows to stop it).-if (Test-Path $binPath) { Remove-Item $binPath -Force }-Move-Item -Path $tmp -Destination $binPath -Force+ $archiveEntries = @(tar -tzf $webTmp)+ if ($LASTEXITCODE -ne 0) { Die 'Failed to inspect web.tar.gz' }+ foreach ($entry in $archiveEntries) {+ if ($entry -notmatch '^web(/|$)' -or $entry -match '(^|/)\.\.(/|$)') {+ Die "web.tar.gz contains an unsafe path: $entry"+ }+ }+ New-Item -ItemType Directory -Path $stageDir | Out-Null+ tar -xzf $webTmp -C $stageDir+ if ($LASTEXITCODE -ne 0 -or -not (Test-Path (Join-Path $stageDir 'web') -PathType Container)) {+ Die 'Failed to extract the required web directory from web.tar.gz'+ }-# Download web dashboard assets (required for the web UI).-$webTarUrl = "$GhDl/v$version/web.tar.gz"-$webTmp = Join-Path $env:TEMP ("mercury-web-" + [guid]::NewGuid().ToString('N') + '.tar.gz')-try {- Invoke-WebRequest -Uri $webTarUrl -OutFile $webTmp -UseBasicParsing+ New-Item -ItemType Directory -Force -Path $binDir | Out-Null+ # Windows cannot overwrite a running executable; surface that error.+ if (Test-Path $binPath) { Remove-Item $binPath -Force }+ Move-Item -Path $binaryTmp -Destination $binPath -Force$webDir = Join-Path $binDir 'web'- New-Item -ItemType Directory -Force -Path $webDir | Out-Null- tar -xzf $webTmp -C $binDir 2>$null+ if (Test-Path $webDir) { Remove-Item $webDir -Recurse -Force }+ Move-Item -Path (Join-Path $stageDir 'web') -Destination $webDirWrite-Info 'Web dashboard assets installed'}-catch {- Write-Warn2 'Web dashboard assets not found for v'"$version — web UI will not work"-}finally {- Remove-Item $webTmp -Force -ErrorAction SilentlyContinue+ Remove-Item $tmpDir -Recurse -Force -ErrorAction SilentlyContinue}Write-Info "Installed to $binPath"diff --git a/scripts/install.sh b/scripts/install.shindex 58062939..41ad9fd4 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -55,18 +55,6 @@ detect_arch() {esac}-# Fetch a URL to stdout. Prefers curl, falls back to wget.-fetch() {- url=$1- if have curl; then- curl -fsSL "$url"- elif have wget; then- wget -qO- "$url"- else- die "Need curl or wget to download files."- fi-}-# Fetch a URL to a file path.fetch_to() {url=$1; out=$2@@ -79,6 +67,25 @@ fetch_to() {fi}+sha256_file() {+ file=$1+ if have shasum; then+ shasum -a 256 "$file" | awk '{print $1}'+ elif have sha256sum; then+ sha256sum "$file" | awk '{print $1}'+ else+ die "Need shasum or sha256sum to verify release downloads."+ fi+}++checksum_for() {+ checksums_file=$1; asset_name=$2+ matches=$(awk -v a="$asset_name" '$2 == a { print $1 }' "$checksums_file")+ count=$(printf '%s\n' "$matches" | awk 'NF { count++ } END { print count + 0 }')+ [ "$count" = "1" ] || die "checksums.txt must contain exactly one checksum for $asset_name"+ printf '%s\n' "$matches"+}+# Resolve "latest" via the GitHub redirect (no API rate limits, no jq needed).resolve_latest_version() {# /releases/latest redirects to /releases/tag/vX.Y.Z — read Location header.@@ -148,6 +155,15 @@ main() {printf '\n%s\n' "$(c_bold '☿ Mercury installer')"printf ' Soul-driven AI agent · https://mercuryagent.sh\n\n'+ termux_prefix=0+ case "${PREFIX:-}" in *com.termux*) termux_prefix=1 ;; esac+ if [ -n "${TERMUX_VERSION:-}" ] || [ "$termux_prefix" = "1" ]; then+ die "Standalone Linux binaries use glibc and cannot run on Android/Termux.+Install the supported Node.js package instead:+ pkg install nodejs-lts git python build-essential+ npm install -g @cosmicstack/mercury-agent"+ fi+os=$(detect_os)arch=$(detect_arch)info "Detected platform: ${os}-${arch}"@@ -166,60 +182,53 @@ main() {bin_dir="$prefix/bin"bin_path="$bin_dir/mercury"- mkdir -p "$bin_dir"- tmp=$(mktemp -t mercury.XXXXXX)- # Clean tempfile on any exit path.- trap 'rm -f "$tmp"' EXIT INT TERM+ tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/mercury.XXXXXX")+ binary_tmp="$tmp_dir/$asset"+ web_tmp="$tmp_dir/web.tar.gz"+ checksums_tmp="$tmp_dir/checksums.txt"+ stage_dir="$tmp_dir/stage"+ trap 'rm -rf "$tmp_dir"' EXIT INT TERM++ checksum_url="${GITHUB_DL}/v${version}/checksums.txt"+ info "Downloading checksums.txt ..."+ fetch_to "$checksum_url" "$checksums_tmp" || die "Failed to download required checksums from $checksum_url"+ expected_binary=$(checksum_for "$checksums_tmp" "$asset")+ expected_web=$(checksum_for "$checksums_tmp" "web.tar.gz")info "Downloading $asset ..."- if ! fetch_to "$url" "$tmp"; then+ if ! fetch_to "$url" "$binary_tmp"; thendie "Failed to download $urlThe binary for v${version} on ${os}-${arch} may not have been published yet.Browse releases: https://github.com/${REPO}/releases"fi- # Optional checksum verification.- checksum_url="${GITHUB_DL}/v${version}/checksums.txt"- if checksums=$(fetch "$checksum_url" 2>/dev/null); then- expected=$(printf '%s\n' "$checksums" | awk -v a="$asset" '$2 == a { print $1 }')- if [ -n "$expected" ]; then- if have shasum; then- actual=$(shasum -a 256 "$tmp" | awk '{print $1}')- elif have sha256sum; then- actual=$(sha256sum "$tmp" | awk '{print $1}')- else- actual=""- fi- if [ -n "$actual" ]; then- if [ "$actual" = "$expected" ]; then- info "Checksum verified (sha256)"- else- die "Checksum mismatch for $asset- expected: $expected- actual: $actual"- fi- fi- fi- fi+ web_tar_url="${GITHUB_DL}/v${version}/web.tar.gz"+ info "Downloading web.tar.gz ..."+ fetch_to "$web_tar_url" "$web_tmp" || die "Failed to download required web dashboard assets from $web_tar_url"++ actual_binary=$(sha256_file "$binary_tmp")+ [ "$actual_binary" = "$expected_binary" ] || die "Checksum mismatch for $asset+ expected: $expected_binary+ actual: $actual_binary"+ actual_web=$(sha256_file "$web_tmp")+ [ "$actual_web" = "$expected_web" ] || die "Checksum mismatch for web.tar.gz+ expected: $expected_web+ actual: $actual_web"+ info "Checksums verified (sha256)"++ tar -tzf "$web_tmp" > "$tmp_dir/web-files.txt" || die "Failed to inspect web.tar.gz"+ awk '$0 !~ /^web(\/|$)/ || $0 ~ /(^|\/)\.\.(\/|$)/ { bad=1 } END { exit bad }' \+ "$tmp_dir/web-files.txt" || die "web.tar.gz contains an unsafe path"+ mkdir -p "$stage_dir"+ tar -xzf "$web_tmp" -C "$stage_dir" || die "Failed to extract web dashboard assets"+ [ -d "$stage_dir/web" ] || die "web.tar.gz does not contain the required web directory"- mv "$tmp" "$bin_path"- trap - EXIT INT TERM+ mkdir -p "$bin_dir"+ mv "$binary_tmp" "$bin_path"chmod +x "$bin_path"-- # Download web dashboard assets (required for the web UI).- web_tar_url="${GITHUB_DL}/v${version}/web.tar.gz"- web_tmp=$(mktemp -t mercury-web.XXXXXX.tar.gz)- if fetch_to "$web_tar_url" "$web_tmp" 2>/dev/null; then- mkdir -p "$bin_dir/web"- if tar -xzf "$web_tmp" -C "$bin_dir" 2>/dev/null; then- info "Web dashboard assets installed"- else- warn "Failed to extract web dashboard assets"- fi- else- warn "Web dashboard assets not found for v${version} — web UI will not work"- fi- rm -f "$web_tmp"+ rm -rf "$bin_dir/web"+ mv "$stage_dir/web" "$bin_dir/web"+ info "Web dashboard assets installed"# macOS: strip the quarantine attribute so Gatekeeper doesn't bark on# unsigned binaries downloaded via curl.@@ -229,6 +238,9 @@ main() {info "Installed to $bin_path"+ rm -rf "$tmp_dir"+ trap - EXIT INT TERM+PATH_UPDATED=0maybe_update_path "$bin_dir"diff --git a/scripts/verify-standalone-release.cjs b/scripts/verify-standalone-release.cjsnew file mode 100644index 00000000..a9a8dcdd--- /dev/null+++ b/scripts/verify-standalone-release.cjs@@ -0,0 +1,70 @@+#!/usr/bin/env node+const { execFileSync } = require('node:child_process');+const crypto = require('node:crypto');+const fs = require('node:fs');+const path = require('node:path');++const root = path.join(__dirname, '..');+const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));+const releaseDir = path.resolve(process.argv[2] || path.join(root, 'release', `v${pkg.version}`));+const assets = [+ 'mercury-macos-arm64',+ 'mercury-macos-x64',+ 'mercury-linux-x64',+ 'mercury-linux-arm64',+ 'mercury-win-x64.exe',+ 'web.tar.gz',+];++function fail(message) {+ console.error(`ERROR: ${message}`);+ process.exit(1);+}++function sha256(filePath) {+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');+}++if (!fs.existsSync(releaseDir)) fail(`release directory not found: ${releaseDir}`);++const allowedEntries = new Set([...assets, 'checksums.txt']);+for (const entry of fs.readdirSync(releaseDir)) {+ if (!allowedEntries.has(entry)) fail(`unexpected release entry: ${entry}`);+}++const checksumPath = path.join(releaseDir, 'checksums.txt');+if (!fs.existsSync(checksumPath)) fail('checksums.txt is missing');++const checksums = new Map();+for (const line of fs.readFileSync(checksumPath, 'utf8').trim().split(/\r?\n/)) {+ const match = line.match(/^([a-fA-F0-9]{64}) ([^/\\]+)$/);+ if (!match) fail(`invalid checksum line: ${line}`);+ if (checksums.has(match[2])) fail(`duplicate checksum entry: ${match[2]}`);+ checksums.set(match[2], match[1].toLowerCase());+}++if (checksums.size !== assets.length || assets.some((asset) => !checksums.has(asset))) {+ fail(`checksums.txt must contain exactly: ${assets.join(', ')}`);+}++for (const asset of assets) {+ const filePath = path.join(releaseDir, asset);+ if (!fs.statSync(filePath, { throwIfNoEntry: false })?.isFile()) fail(`${asset} is missing`);+ const actual = sha256(filePath);+ if (actual !== checksums.get(asset)) fail(`checksum mismatch for ${asset}`);+}++const archiveEntries = execFileSync('tar', ['-tzf', path.join(releaseDir, 'web.tar.gz')], {+ encoding: 'utf8',+}).trim().split(/\r?\n/);+if (!archiveEntries.some((entry) => entry === 'web' || entry === 'web/')) fail('web.tar.gz has no web/ root');+for (const entry of archiveEntries) {+ if (!/^web(?:\/|$)/.test(entry) || /(?:^|\/)\.\.(?:\/|$)/.test(entry)) {+ fail(`unsafe archive entry: ${entry}`);+ }+ if (/(?:^|\/)\.DS_Store$/.test(entry) || /\.map$/.test(entry)) {+ fail(`junk file present in web.tar.gz: ${entry}`);+ }+}++console.log(` ✓ verified ${assets.length} standalone release assets`);diff --git a/src/auth/chatgpt-auth.ts b/src/auth/chatgpt-auth.tsindex acd7bc71..fbcc456e 100644--- a/src/auth/chatgpt-auth.ts+++ b/src/auth/chatgpt-auth.ts@@ -1,5 +1,4 @@-import { exec } from 'node:child_process';-import { promisify } from 'node:util';+import { openUrl } from '../utils/open-url.js';import {loadChatGPTSession,saveChatGPTSession,@@ -17,22 +16,6 @@ import {type ChatGPTSession,} from './chatgpt-session.js';-const execAsync = promisify(exec);--// ----------------------------------------------------------------------------// Browser helper-// -----------------------------------------------------------------------------function openBrowser(url: string): void {- const cmd =- process.platform === 'darwin'- ? 'open'- : process.platform === 'win32'- ? 'start'- : 'xdg-open';- execAsync(`${cmd} "${url}"`).catch(() => {});-}-// ---------------------------------------------------------------------------// Device-flow OAuth// ---------------------------------------------------------------------------@@ -182,7 +165,7 @@ export async function loginChatGPT(): Promise<ChatGPTSession> {console.log();console.log(' Waiting for authorization (up to 5 minutes)...');- openBrowser(CHATGPT_DEVICE_UI_URL);+ void openUrl(CHATGPT_DEVICE_UI_URL);// Step 3: Pollconst { authorizationCode, codeVerifier } = await pollForAuthorization(diff --git a/src/auth/github-auth.ts b/src/auth/github-auth.tsindex 478fe432..916273cd 100644--- a/src/auth/github-auth.ts+++ b/src/auth/github-auth.ts@@ -1,5 +1,4 @@-import { exec } from 'node:child_process';-import { promisify } from 'node:util';+import { openUrl } from '../utils/open-url.js';import {loadGitHubSession,saveGitHubSession,@@ -13,22 +12,6 @@ import {type GitHubSession,} from './github-session.js';-const execAsync = promisify(exec);--// ----------------------------------------------------------------------------// Browser helper-// -----------------------------------------------------------------------------function openBrowser(url: string): void {- const cmd =- process.platform === 'darwin'- ? 'open'- : process.platform === 'win32'- ? 'start'- : 'xdg-open';- execAsync(`${cmd} "${url}"`).catch(() => {});-}-// ---------------------------------------------------------------------------// Device flow OAuth// ---------------------------------------------------------------------------@@ -171,7 +154,7 @@ export async function loginGitHub(): Promise<GitHubSession> {console.log();console.log(' Waiting for authorization (up to 15 minutes)...');- openBrowser(device.verification_uri);+ void openUrl(device.verification_uri);// Step 3: Pollconst tokens = await pollForToken(diff --git a/src/capabilities/git/git-add.ts b/src/capabilities/git/git-add.tsindex 33820047..2b14c610 100644--- a/src/capabilities/git/git-add.ts+++ b/src/capabilities/git/git-add.ts@@ -1,8 +1,9 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execSync } from 'node:child_process';+import { execFileSync } from 'node:child_process';+import type { PermissionManager } from '../permissions.js';-export function createGitAddTool(getCwd: () => string) {+export function createGitAddTool(permissions: PermissionManager, getCwd: () => string) {return tool({description: 'Add file contents to the index (staging area). Prepares files for commit.',inputSchema: zodSchema(z.object({@@ -10,12 +11,13 @@ export function createGitAddTool(getCwd: () => string) {})),execute: async ({ paths }) => {try {- const fileArgs = paths.map(p => `"${p}"`).join(' ');- const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });+ const permission = await permissions.checkShellCommand(`git add -- ${paths.join(' ')}`);+ if (!permission.allowed) return `Permission denied: ${permission.reason || 'git add requires approval'}`;+ const result = execFileSync('git', ['add', '--', ...paths], { encoding: 'utf-8', timeout: 20000, cwd: getCwd() });return `Staged ${paths.length} file(s): ${paths.join(', ')}`;} catch (err: any) {return `Error: ${err.stderr?.trim() || err.message}`;}},});-}\ No newline at end of file+}diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.tsindex da4d4272..34686a94 100644--- a/src/capabilities/git/git-commit.ts+++ b/src/capabilities/git/git-commit.ts@@ -1,12 +1,13 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';-import { execSync } from 'node:child_process';+import { execFileSync } from 'node:child_process';import { writeFileSync, unlinkSync } from 'node:fs';import { join } from 'node:path';+import type { PermissionManager } from '../permissions.js';const CO_AUTHOR = 'Mercury <[email protected]>';-export function createGitCommitTool(getCwd: () => string) {+export function createGitCommitTool(permissions: PermissionManager, getCwd: () => string) {return tool({description: 'Record changes to the repository. Creates a new commit with staged changes. Automatically includes a Co-authored-by trailer for attribution.',inputSchema: zodSchema(z.object({@@ -14,11 +15,13 @@ export function createGitCommitTool(getCwd: () => string) {})),execute: async ({ message }) => {try {+ const permission = await permissions.checkShellCommand(`git commit -m ${JSON.stringify(message)}`);+ if (!permission.allowed) return `Permission denied: ${permission.reason || 'git commit requires approval'}`;const fullMessage = `${message}\n\nCo-authored-by: ${CO_AUTHOR}`;const cwd = getCwd();const msgFilePath = join(cwd, '.git', 'MERCU_MSG');writeFileSync(msgFilePath, fullMessage, 'utf-8');- const result = execSync(`git commit -F "${msgFilePath}"`, {+ const result = execFileSync('git', ['commit', '-F', msgFilePath], {encoding: 'utf-8',timeout: 20000,cwd,@@ -35,4 +38,4 @@ export function createGitCommitTool(getCwd: () => string) {}},});-}\ No newline at end of file+}diff --git a/src/capabilities/permissions.test.ts b/src/capabilities/permissions.test.tsindex 53c44393..72202898 100644--- a/src/capabilities/permissions.test.ts+++ b/src/capabilities/permissions.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from 'vitest';-import { splitShellSegments } from './permissions.js';+import { describe, expect, it, vi } from 'vitest';+import { PermissionManager, splitShellSegments } from './permissions.js';describe('splitShellSegments', () => {it('passes simple commands through as a single segment', () => {@@ -45,3 +45,62 @@ describe('splitShellSegments', () => {expect(splitShellSegments('{ reboot now; }')).toEqual(['reboot now']);});});++describe('PermissionManager remote safety', () => {+ it('enforces hard command blocks before Local allow-all', async () => {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.shell.enabled = true;+ manifest.capabilities.shell.blocked = ['rm *'];+ permissions.setAutoApproveAll(true);++ await expect(permissions.checkShellCommand('rm -rf project')).resolves.toMatchObject({ allowed: false });+ });++ it('does not let Local CLI allow-all silently elevate a Cloud request', async () => {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.shell.enabled = true;+ manifest.capabilities.shell.blocked = [];+ const ask = vi.fn().mockResolvedValue('yes');+ permissions.onAsk(ask);+ permissions.setAutoApproveAll(true);+ permissions.setCurrentContext('web', 'cloud-request-1');++ await expect(permissions.checkShellCommand('npm install example')).resolves.toMatchObject({ allowed: true });+ expect(ask).toHaveBeenCalledOnce();+ });++ it('scopes always approval to the exact command and interaction context', async () => {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.shell.enabled = true;+ manifest.capabilities.shell.blocked = [];+ const ask = vi.fn().mockResolvedValueOnce('always').mockResolvedValue('no');+ permissions.onAsk(ask);+ permissions.setCurrentContext('web', 'cloud-request-1');++ await expect(permissions.checkShellCommand('npm install example')).resolves.toMatchObject({ allowed: true });+ await expect(permissions.checkShellCommand('npm install example')).resolves.toMatchObject({ allowed: true });+ await expect(permissions.checkShellCommand('npm install different')).resolves.toMatchObject({ allowed: false });+ expect(ask).toHaveBeenCalledTimes(2);+ });++ it('does not classify redirection or mutating read-command flags as safe reads', async () => {+ const permissions = new PermissionManager();+ const manifest = permissions.getManifest();+ manifest.capabilities.shell.enabled = true;+ manifest.capabilities.shell.blocked = [];+ const ask = vi.fn().mockResolvedValue('no');+ permissions.onAsk(ask);+ permissions.setCurrentContext('web', 'cloud-request-1');++ await expect(permissions.checkShellCommand('echo poisoned > AGENTS.md')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('echo poisoned>AGENTS.md')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('find . -delete')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('git branch -D protected')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('git branch --delete protected')).resolves.toMatchObject({ allowed: false });+ await expect(permissions.checkShellCommand('git branch new-branch')).resolves.toMatchObject({ allowed: false });+ expect(ask).toHaveBeenCalledTimes(6);+ });+});diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex c7148b5a..d55eb3cb 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -287,6 +287,9 @@ export class PermissionManager {private autoApproveAll = false;private elevatedCommands: Set<string> = new Set();private currentChannelType: string = 'cli';+ private currentChannelId: string = 'cli';+ private approvedCommandsByContext = new Map<string, Set<string>>();+ private approvedWritesByContext = new Map<string, Set<string>>();private tempScopes: FileScope[] = [];@@ -299,6 +302,11 @@ export class PermissionManager {this.currentChannelType = type;}+ setCurrentContext(type: string, id: string): void {+ this.currentChannelType = type;+ this.currentChannelId = id;+ }+getCurrentChannelType(): string {return this.currentChannelType;}@@ -307,6 +315,13 @@ export class PermissionManager {this.askHandler = handler;}+ async requestApproval(prompt: string): Promise<boolean> {+ if (this.currentChannelType === 'internal') return true;+ if (!this.askHandler) return false;+ const result = await this.askHandler(prompt);+ return result === 'yes' || result === 'always';+ }+setAutoApproveAll(value: boolean): void {this.autoApproveAll = value;}@@ -315,6 +330,12 @@ export class PermissionManager {return this.autoApproveAll;}+ private isGlobalAutoApproveActive(): boolean {+ // Web/Cloud grants are resolved per session by WebChannel; a Local CLI+ // allow-all setting must never silently elevate remote requests.+ return this.autoApproveAll && this.currentChannelType !== 'web';+ }+elevateForSkill(allowedTools: string[]): void {if (allowedTools.includes('run_command')) {this.elevatedCommands.add('run_command');@@ -402,21 +423,23 @@ export class PermissionManager {}// Write access: in auto-approve-all mode, allow if scope covers it- if (mode === 'write' && this.autoApproveAll) {+ const contextWriteApproved = this.approvedWritesByContext.get(this.currentChannelId)?.has(resolved) === true;+ if (mode === 'write' && (this.isGlobalAutoApproveActive() || contextWriteApproved)) {if (scope && scope.write) return { allowed: true };if (tempScope && tempScope.write) return { allowed: true };}// Write access in ask-me mode: ALWAYS prompt the user, even if scope exists- if (mode === 'write' && !this.autoApproveAll && this.askHandler && this.currentChannelType !== 'internal') {+ if (mode === 'write' && !this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {const scopeAllows = (scope && scope.write) || (tempScope && tempScope.write);if (scopeAllows) {// Scope allows it, but user wants to confirm — prompt with file pathconst result = await this.askHandler(`Write to file: ${resolved}`);if (result === 'yes') return { allowed: true };if (result === 'always') {- // User chose "always" — switch to auto-approve for the rest of this session- this.autoApproveAll = true;+ const approved = this.approvedWritesByContext.get(this.currentChannelId) ?? new Set<string>();+ approved.add(resolved);+ this.approvedWritesByContext.set(this.currentChannelId, approved);return { allowed: true };}return { allowed: false, reason: `User denied write to ${path}` };@@ -433,7 +456,7 @@ export class PermissionManager {return { allowed: false, reason: `Permission denied: ${mode} access to ${path}` };}- if (!this.autoApproveAll && this.askHandler && this.currentChannelType !== 'internal') {+ if (!this.isGlobalAutoApproveActive() && this.askHandler && this.currentChannelType !== 'internal') {return this.requestScopeExternal(path, mode);}@@ -456,16 +479,6 @@ export class PermissionManager {];async checkShellCommand(command: string): Promise<{ allowed: boolean; reason?: string; needsApproval: boolean }> {- if (this.autoApproveAll) {- logger.info({ cmd: command.trim() }, 'Shell command auto-approved (auto-approve-all mode)');- return { allowed: true, needsApproval: false };- }-- if (this.isShellElevated()) {- logger.info({ cmd: command.trim() }, 'Shell command auto-approved (skill elevation)');- return { allowed: true, needsApproval: false };- }-const shell = this.manifest.capabilities.shell;if (!shell.enabled) {return { allowed: false, reason: 'Shell capability is disabled', needsApproval: false };@@ -486,6 +499,21 @@ export class PermissionManager {}}+ if (this.isGlobalAutoApproveActive()) {+ logger.info({ cmd: trimmed }, 'Shell command auto-approved (Local allow-all mode)');+ return { allowed: true, needsApproval: false };+ }++ if (this.isShellElevated()) {+ logger.info({ cmd: trimmed }, 'Shell command auto-approved (skill elevation)');+ return { allowed: true, needsApproval: false };+ }++ if (this.approvedCommandsByContext.get(this.currentChannelId)?.has(trimmed)) {+ logger.info({ cmd: trimmed }, 'Shell command auto-approved for this interaction context');+ return { allowed: true, needsApproval: false };+ }+if (shell.cwdOnly) {for (const segment of segments) {const hasPathTraversal = this.hasPathBeyondCwd(segment);@@ -502,7 +530,7 @@ export class PermissionManager {// Matching the full trimmed string would let `cat foo; rm -rf ~` slip// through because `cat *` matches the entire concatenation.const allSegmentsSafeRead = segments.length > 0 && segments.every((segment) =>- PermissionManager.SAFE_READ_PATTERNS.some((p) => this.matchPattern(segment, p))+ this.isSafeReadSegment(segment));if (allSegmentsSafeRead) {logger.info({ cmd: trimmed, segments: segments.length }, 'Shell command auto-approved (safe read-only)');@@ -516,8 +544,9 @@ export class PermissionManager {return { allowed: true, needsApproval: false };}if (result === 'always') {- // User chose "always" — switch to auto-approve for the rest of this session- this.autoApproveAll = true;+ const approved = this.approvedCommandsByContext.get(this.currentChannelId) ?? new Set<string>();+ approved.add(trimmed);+ this.approvedCommandsByContext.set(this.currentChannelId, approved);return { allowed: true, needsApproval: false };}return { allowed: false, reason: `User denied: ${trimmed}`, needsApproval: false };@@ -526,6 +555,19 @@ export class PermissionManager {return { allowed: false, reason: 'Command not in auto-approve list — requires approval', needsApproval: true };}+ private isSafeReadSegment(segment: string): boolean {+ // Redirection turns otherwise read-only commands such as cat/echo into writes.+ if (/\d*(?:>{1,2}|<{1,2})|&>/.test(segment)) return false;+ if (/^find\b.*(?:^|\s)-(?:delete|exec|execdir|ok|okdir)\b/.test(segment)) return false;+ const branchArgs = segment.match(/^git\s+branch(?:\s+(.*))?$/)?.[1]?.trim();+ if (branchArgs && (+ !branchArgs.startsWith('-')+ || /(?:^|\s)(?:-[dDmMcC]\b|--(?:delete|move|copy|edit-description|set-upstream-to|unset-upstream|track)\b)/.test(branchArgs)+ )) return false;+ if (/^git\s+diff\b.*(?:--output(?:=|\s)|--no-index\b)/.test(segment)) return false;+ return PermissionManager.SAFE_READ_PATTERNS.some((pattern) => this.matchPattern(segment, pattern));+ }+isGitReadAllowed(): boolean {return this.manifest.capabilities.git.enabled && this.manifest.capabilities.git.autoApproveRead;}@@ -656,4 +698,4 @@ export class PermissionManager {},};}-}\ No newline at end of file+}diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex 00a0cdd8..12dd06c1 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -72,6 +72,8 @@ export interface ChatCommandContext {memorySetLearningPaused: (paused: boolean) => void;memoryClear: () => number;memoryGetSubconscious: (limit?: number) => import('../memory/user-memory.js').UserMemoryRecord[];+ memoryIsShareLearning: () => boolean;+ memorySetShareLearning: (enabled: boolean) => void;}export class CapabilityRegistry {@@ -89,6 +91,7 @@ export class CapabilityRegistry {private currentChannelType = 'cli';private chatCommandContext?: ChatCommandContext;private currentCwd = process.cwd();+ private researchModeGetter: (() => boolean) | null = null;constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget, supervisor?: SubAgentSupervisor, userMemory?: UserMemoryStore) {this.permissions = new PermissionManager();@@ -99,6 +102,14 @@ export class CapabilityRegistry {this.userMemory = userMemory;}+ setResearchModeGetter(getter: () => boolean): void {+ this.researchModeGetter = getter;+ }++ isResearchMode(): boolean {+ return this.researchModeGetter ? this.researchModeGetter() : false;+ }+setChatCommandContext(ctx: ChatCommandContext): void {this.chatCommandContext = ctx;}@@ -110,6 +121,7 @@ export class CapabilityRegistry {setChannelContext(channelId: string, channelType: string): void {this.currentChannelId = channelId;this.currentChannelType = channelType;+ this.permissions.setCurrentContext(channelType, channelId);}getChannelContext(): { channelId: string; channelType: string } {@@ -199,7 +211,7 @@ export class CapabilityRegistry {}if (this.scheduler) {- this.tools.schedule_task = createScheduleTaskTool(this.scheduler, () => this.getChannelContext());+ this.tools.schedule_task = createScheduleTaskTool(this.scheduler, this.permissions, () => this.getChannelContext());this.tools.list_scheduled_tasks = createListTasksTool(this.scheduler);this.tools.cancel_scheduled_task = createCancelTaskTool(this.scheduler);logger.info('Scheduler tools registered');@@ -220,8 +232,8 @@ export class CapabilityRegistry {this.tools.git_status = createGitStatusTool(() => this.getCwd());this.tools.git_diff = createGitDiffTool(() => this.getCwd());this.tools.git_log = createGitLogTool(() => this.getCwd());- this.tools.git_add = createGitAddTool(() => this.getCwd());- this.tools.git_commit = createGitCommitTool(() => this.getCwd());+ this.tools.git_add = createGitAddTool(this.permissions, () => this.getCwd());+ this.tools.git_commit = createGitCommitTool(this.permissions, () => this.getCwd());this.tools.git_push = createGitPushTool(this.permissions, () => this.getCwd());logger.info('Git tools registered');}@@ -235,7 +247,7 @@ export class CapabilityRegistry {logger.info('GitHub tools registered');}- this.tools.fetch_url = createFetchUrlTool();+ this.tools.fetch_url = createFetchUrlTool({ isResearchMode: () => this.isResearchMode() });logger.info('Web fetch tool registered');if (this.supervisor) {diff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.tsindex 7bd14ab9..656f74c4 100644--- a/src/capabilities/scheduler/schedule-task.ts+++ b/src/capabilities/scheduler/schedule-task.ts@@ -2,8 +2,9 @@ import { tool, zodSchema } from 'ai';import { z } from 'zod';import cron from 'node-cron';import type { Scheduler, ScheduledTaskManifest } from '../../core/scheduler.js';+import type { PermissionManager } from '../permissions.js';-export function createScheduleTaskTool(scheduler: Scheduler, getContext: () => { channelId: string; channelType: string }) {+export function createScheduleTaskTool(scheduler: Scheduler, permissions: PermissionManager, getContext: () => { channelId: string; channelType: string }) {return tool({description: 'Schedule a task. Use "cron" for recurring tasks (e.g. "0 9 * * *" for daily at 9am) or "delay_seconds" for one-shot delayed tasks (e.g. 15 for "remind me in 15 seconds"). Provide exactly one of cron or delay_seconds.',inputSchema: zodSchema(z.object({@@ -25,6 +26,9 @@ export function createScheduleTaskTool(scheduler: Scheduler, getContext: () => {return 'Either prompt or skill_name must be provided so the task has something to do.';}+ const approved = await permissions.requestApproval(`Create scheduled task: ${description}`);+ if (!approved) return 'Permission denied: scheduled task creation was not approved.';+const id = `task-${Date.now().toString(36)}`;const ctx = getContext();@@ -70,4 +74,4 @@ export function createScheduleTaskTool(scheduler: Scheduler, getContext: () => {return `Task "${id}" scheduled. Cron: ${cronExpr}. Will execute ${triggerType}. Description: ${description}`;},});-}\ No newline at end of file+}diff --git a/src/capabilities/web/fetch-url.ts b/src/capabilities/web/fetch-url.tsindex 40a333ea..13605aa6 100644--- a/src/capabilities/web/fetch-url.ts+++ b/src/capabilities/web/fetch-url.ts@@ -3,7 +3,20 @@ import { z } from 'zod';const MAX_CONTENT_LENGTH = 15000;-function stripHtml(html: string): string {+function resolveUrl(src: string, baseUrl: string): string {+ try {+ return new URL(src, baseUrl).href;+ } catch {+ return src;+ }+}++function extractSrcsetUrl(srcset: string): string | null {+ const first = srcset.split(',')[0]?.trim().split(/\s+/)[0];+ return first || null;+}++function stripHtml(html: string, preserveImages = false, pageUrl = ''): string {let text = html;text = text.replace(/<script[\s\S]*?<\/script>/gi, '');@@ -20,7 +33,37 @@ function stripHtml(html: string): string {text = text.replace(/<hr\s*\/?>/gi, '\n---\n');text = text.replace(/<a[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, '[$2]($1)');- text = text.replace(/<img[^>]*alt="([^"]*)"[^>]*>/gi, '[image: $1]');+ // Only preserve images as markdown when research mode is active, so normal+ // fetches stay lean. Otherwise strip to a compact text placeholder.+ if (preserveImages) {+ text = text.replace(/<img[^>]*>/gi, (match) => {+ const getAttr = (name: string): string | null => {+ const m = match.match(new RegExp(`${name}\\s*=\\s*["']([^"']*)["']`, 'i'));+ return m ? m[1] : null;+ };+ let src = getAttr('src') || getAttr('data-src') || getAttr('data-lazy-src') || '';+ if (!src) {+ const srcset = getAttr('srcset') || getAttr('data-srcset');+ if (srcset) {+ const extracted = extractSrcsetUrl(srcset);+ if (extracted) src = extracted;+ }+ }+ const alt = getAttr('alt') || '';+ if (!src || /1x1|pixel|spacer|blank/i.test(src)) return '';+ if (pageUrl) src = resolveUrl(src, pageUrl);+ return `\n\n\n\n`;+ });+ text = text.replace(/<source[^>]*srcset="([^"]*)"[^>]*>/gi, (match, srcset: string) => {+ const src = extractSrcsetUrl(srcset);+ if (!src || /1x1|pixel|spacer|blank/i.test(src)) return '';+ const resolved = pageUrl ? resolveUrl(src, pageUrl) : src;+ return `\n\n\n\n`;+ });+ } else {+ text = text.replace(/<img[^>]*alt="([^"]*)"[^>]*>/gi, '[image: $1]');+ text = text.replace(/<img[^>]*>/gi, '');+ }text = text.replace(/<code[^>]*>([\s\S]*?)<\/code>/gi, '`$1`');text = text.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, '\n```\n$1\n```\n');text = text.replace(/<strong[^>]*>([\s\S]*?)<\/strong>/gi, '**$1**');@@ -41,15 +84,16 @@ function stripHtml(html: string): string {return text;}-export function createFetchUrlTool() {+export function createFetchUrlTool(opts: { isResearchMode: () => boolean } = { isResearchMode: () => false }) {return tool({- description: 'Fetch a URL and return its content as text. Strips HTML to readable markdown-like format. Useful for reading documentation, APIs, or web pages.',+ description: 'Fetch a URL and return its content as markdown. In research mode, images from the page are preserved as  with absolute URLs so they can be embedded in research articles. Useful for reading documentation, news articles, APIs, or web pages.',inputSchema: zodSchema(z.object({url: z.string().describe('The URL to fetch'),format: z.enum(['text', 'markdown']).optional().describe('Output format (default: markdown)'),})),execute: async ({ url, format }) => {const outputFormat = format ?? 'markdown';+ const preserveImages = opts.isResearchMode();try {const controller = new AbortController();@@ -85,7 +129,7 @@ export function createFetchUrlTool() {}if (contentType.includes('text/html') && outputFormat === 'markdown') {- const text = stripHtml(body);+ const text = stripHtml(body, preserveImages, url);return text.length > MAX_CONTENT_LENGTH? text.slice(0, MAX_CONTENT_LENGTH) + '\n... (truncated)': text;@@ -102,4 +146,4 @@ export function createFetchUrlTool() {}},});-}\ No newline at end of file+}diff --git a/src/channels/cli-workspace-scroll.test.ts b/src/channels/cli-workspace-scroll.test.tsnew file mode 100644index 00000000..a62fba3c--- /dev/null+++ b/src/channels/cli-workspace-scroll.test.ts@@ -0,0 +1,91 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { CLIChannel } from './cli.js';++const cleanup: string[] = [];++afterEach(() => {+ for (const path of cleanup.splice(0)) rmSync(path, { recursive: true, force: true });+});++function channelWithWorkspace(): CLIChannel {+ const channel = new CLIChannel();+ (channel as any).state.workspace = {+ active: true,+ rootPath: '/project',+ nodes: [],+ selectedIndex: 0,+ selectedPath: null,+ openedFilePath: '/project/file.ts',+ openedFilePreview: Array.from({ length: 100 }, (_, index) => `line ${index + 1}`),+ gitFiles: [],+ stagedCount: 0,+ unstagedCount: 0,+ branch: 'main',+ ahead: 0,+ behind: 0,+ lastAction: '',+ codeScrollOffset: 0,+ focusArea: 'code',+ chatCollapsed: false,+ chatScrollOffset: 0,+ rightPanel: 'chat',+ };+ return channel;+}++describe('CLI workspace scrolling', () => {+ it('updates one stable message while streaming and finalizes it in place', async () => {+ const channel = new CLIChannel();+ let release: (() => void) | undefined;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const result = channel.stream((async function* () {+ yield 'Hello';+ await gate;+ yield ' world';+ })());++ await new Promise<void>((resolve) => setImmediate(resolve));+ const partial = (channel as any).state.chatMessages;+ expect(partial).toHaveLength(1);+ expect(partial[0]).toMatchObject({ content: 'Hello', streaming: true });++ release?.();+ await expect(result).resolves.toBe('Hello world');+ const completed = (channel as any).state.chatMessages;+ expect(completed).toHaveLength(1);+ expect(completed[0]).toMatchObject({ id: partial[0].id, content: 'Hello world', streaming: false });+ });++ it('clamps code scrolling to the last full viewport instead of the last line', () => {+ const channel = channelWithWorkspace();++ channel.scrollWorkspaceCode(1_000, 20);+ expect((channel as any).state.workspace.codeScrollOffset).toBe(80);++ channel.scrollWorkspaceCode(-1_000, 20);+ expect((channel as any).state.workspace.codeScrollOffset).toBe(0);+ });++ it('stores workspace chat scrolling as a non-negative distance from the bottom', () => {+ const channel = channelWithWorkspace();++ channel.scrollWorkspaceChat(12);+ expect((channel as any).state.workspace.chatScrollOffset).toBe(12);++ channel.scrollWorkspaceChat(-20);+ expect((channel as any).state.workspace.chatScrollOffset).toBe(0);+ });++ it('normalizes CRLF file previews before measuring terminal rows', () => {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-tui-'));+ cleanup.push(dir);+ const filePath = join(dir, 'windows.txt');+ writeFileSync(filePath, 'one\r\ntwo\r\nthree');+ const channel = new CLIChannel();++ expect((channel as any).readFilePreview(filePath)).toEqual(['one', 'two', 'three']);+ });+});diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 605af3e9..27240108 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -7,7 +7,7 @@ import type { ChannelMessage } from '../types/channel.js';import { BaseChannel, type PermissionMode } from './base.js';import { logger } from '../utils/logger.js';import { formatToolStep, formatToolResult } from '../utils/tool-label.js';-import type { ChatMessage, CompletionMeta, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, SaverInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo } from '../ui/types.js';+import type { ChatMessage, CompletionMeta, ToolStep, PermissionPromptState, CurrentSessionInfo, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, SaverInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile, BackgroundTaskInfo } from '../ui/types.js';import { TuiApp } from '../ui/App.js';export interface TuiState {@@ -35,6 +35,7 @@ export interface TuiState {lastStepLog: ToolStep[] | null;/** Elapsed ms for the last completed task. */lastStepLogElapsed: number | null;+ currentSession: CurrentSessionInfo | null;}const defaultState: TuiState = {@@ -60,6 +61,7 @@ const defaultState: TuiState = {saverInfo: null,lastStepLog: null,lastStepLogElapsed: null,+ currentSession: null,};function shallowEqualSubAgents(a: SubAgentInfo[], b: SubAgentInfo[]): boolean {@@ -95,6 +97,8 @@ export class CLIChannel extends BaseChannel {private rawModeWatchdog: NodeJS.Timeout | null = null;private statusPoller: NodeJS.Timeout | null = null;private statusPollerBusy = false;+ private rerenderQueued = false;+ private rerenderScheduled = false;private statusProviders: {tokens?: () => { used: number; budget: number; percentage: number };saver?: () => { state: import('../core/saver-mode.js').SaverModeState; savedToday: number; savedLifetime: number };@@ -182,27 +186,42 @@ export class CLIChannel extends BaseChannel {private rerender(): void {if (!this.inkInstance) return;- this.inkInstance.rerender(- React.createElement(TuiApp, {- state: this.state,- onInput: (text: string) => { this.inputHandler?.(text); },- onPermissionResolve: (value: string | boolean) => {- if (this.permissionResolver) {- this.permissionResolver(value);- this.permissionResolver = null;- }- this.update({ permissionPrompt: null });- },- onExit: () => {- this.stopRawModeWatchdog();- this.inkInstance?.unmount();- this.inkInstance = null;- this.releaseRawMode();- this.exitHandler?.();- },- spotifyClient: this.spotifyClient,- }),- );+ if (this.rerenderScheduled) {+ this.rerenderQueued = true;+ return;+ }+ this.rerenderScheduled = true;+ const flush = () => {+ this.rerenderScheduled = false;+ const inkInstance = this.inkInstance;+ if (!inkInstance) return;+ inkInstance.rerender(+ React.createElement(TuiApp, {+ state: this.state,+ onInput: (text: string) => { this.inputHandler?.(text); },+ onPermissionResolve: (value: string | boolean) => {+ if (this.permissionResolver) {+ this.permissionResolver(value);+ this.permissionResolver = null;+ }+ this.update({ permissionPrompt: null });+ },+ onExit: () => {+ this.stopRawModeWatchdog();+ this.inkInstance?.unmount();+ this.inkInstance = null;+ this.releaseRawMode();+ this.exitHandler?.();+ },+ spotifyClient: this.spotifyClient,+ }),+ );+ if (this.rerenderQueued) {+ this.rerenderQueued = false;+ flush();+ }+ };+ setImmediate(flush);}mountTUI(onInput: (text: string) => void, spotifyClient?: any, onExit?: () => void): void {@@ -252,8 +271,19 @@ export class CLIChannel extends BaseChannel {return;}if (trimmed.startsWith('/ws scroll ')) {- const delta = parseInt(trimmed.slice(11), 10);- if (!isNaN(delta)) this.scrollWorkspaceCode(delta);+ const [deltaRaw, viewportRaw] = trimmed.slice(11).trim().split(/\s+/);+ const delta = parseInt(deltaRaw, 10);+ const viewportLines = parseInt(viewportRaw, 10);+ if (!isNaN(delta)) this.scrollWorkspaceCode(delta, Number.isFinite(viewportLines) ? viewportLines : 1);+ return;+ }+ if (trimmed === '/ws scroll-home') {+ this.scrollWorkspaceCodeToBoundary('top');+ return;+ }+ if (trimmed.startsWith('/ws scroll-end ')) {+ const viewportLines = parseInt(trimmed.slice(15), 10);+ this.scrollWorkspaceCodeToBoundary('bottom', Number.isFinite(viewportLines) ? viewportLines : 1);return;}if (trimmed.startsWith('/ws focus ')) {@@ -270,6 +300,19 @@ export class CLIChannel extends BaseChannel {if (!isNaN(delta)) this.scrollWorkspaceChat(delta);return;}+ if (trimmed.startsWith('/ws chat-set ')) {+ const distance = parseInt(trimmed.slice(13), 10);+ if (Number.isFinite(distance)) this.setWorkspaceChatDistance(distance);+ return;+ }+ if (trimmed === '/ws chat-home') {+ this.setWorkspaceChatBoundary('top');+ return;+ }+ if (trimmed === '/ws chat-end') {+ this.setWorkspaceChatBoundary('bottom');+ return;+ }if (trimmed === '/menu' || trimmed === '/m') {this.update({ mode: 'menu' });return;@@ -495,62 +538,58 @@ export class CLIChannel extends BaseChannel {async stream(content: AsyncIterable<string>, _targetId?: string): Promise<string> {const msgId = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);let full = '';+ let started = false;let lastRender = 0;this.clearHeartbeat();-- const initialMsg: ChatMessage = {- id: msgId,- role: 'agent',- content: '',- timestamp: Date.now(),- streaming: true,- };-- this.update({- chatMessages: [...this.state.chatMessages, initialMsg],- isThinking: true,- });+ this.update({ isThinking: true });try {for await (const chunk of content) {full += chunk;const now = Date.now();- if (now - lastRender >= 16) {+ // Throttle streaming re-renders to ~60ms. At 16ms the live Yoga+ // tree was being recomputed on nearly every token, which — combined+ // with markdown re-parsing of the full accumulated buffer each+ // render — caused the visible "vibration"/flicker during generation.+ // 60ms is fast enough to feel live while keeping each frame's layout+ // stable.+ if (!started || now - lastRender >= 60) {+ const streamedMessage = { id: msgId, role: 'agent' as const, content: full, timestamp: now, streaming: true };this.update({- chatMessages: this.state.chatMessages.map((m) =>- m.id === msgId ? { ...m, content: full, streaming: true } : m,- ),+ chatMessages: started+ ? this.state.chatMessages.map((message) => message.id === msgId ? streamedMessage : message)+ : [...this.state.chatMessages, streamedMessage],+ isThinking: true,});+ started = true;lastRender = now;}}} catch (err) {- // Stream was interrupted (API disconnect, abort, etc.). Save- // whatever partial text we accumulated so the user doesn't lose it.logger.warn({ err, partialLen: full.length }, 'CLI stream interrupted, saving partial text');if (full.length > 0) {+ const interruptedMessage = { id: msgId, role: 'agent' as const, content: full + '\n\n⚠ Stream was interrupted. Partial response shown above.', timestamp: Date.now(), streaming: false };this.update({- chatMessages: this.state.chatMessages.map((m) =>- m.id === msgId ? { ...m, content: full + '\n\n⚠ Stream was interrupted. Partial response shown above.', streaming: false } : m,- ),+ chatMessages: started+ ? this.state.chatMessages.map((message) => message.id === msgId ? interruptedMessage : message)+ : [...this.state.chatMessages, interruptedMessage],isThinking: false,});} else {this.update({- chatMessages: this.state.chatMessages.map((m) =>- m.id === msgId ? { ...m, content: '⚠ Stream was interrupted before any response was generated.', streaming: false } : m,- ),+ chatMessages: [...this.state.chatMessages, { id: msgId, role: 'agent', content: '⚠ Stream was interrupted before any response was generated.', timestamp: Date.now(), streaming: false }],isThinking: false,});}return full;}+ const finalMessage = { id: msgId, role: 'agent' as const, content: full, timestamp: Date.now(), streaming: false };this.update({- chatMessages: this.state.chatMessages.map((m) =>- m.id === msgId ? { ...m, content: full, streaming: false } : m,- ),+ chatMessages: started+ ? this.state.chatMessages.map((message) => message.id === msgId ? finalMessage : message)+ : [...this.state.chatMessages, finalMessage],isThinking: false,});@@ -647,7 +686,7 @@ export class CLIChannel extends BaseChannel {this.permissionResolver = (val) => resolve(String(val));this.update({permissionPrompt: {- type: 'mode',+ type: 'choice',message: question,options,resolve: () => {},@@ -688,6 +727,10 @@ export class CLIChannel extends BaseChannel {this.update({ provider: { name, model, badge } });}+ setCurrentSession(session: CurrentSessionInfo | null): void {+ this.update({ currentSession: session });+ }+setTokenInfo(used: number, budget: number, percentage: number): void {this.update({ tokenInfo: { used, budget, percentage } });}@@ -1003,16 +1046,25 @@ export class CLIChannel extends BaseChannel {this.update({ workspace: { ...ws, openedFilePath: null, openedFilePreview: [], codeScrollOffset: 0, focusArea: 'explorer', lastAction: 'Closed file preview' } });}- scrollWorkspaceCode(delta: number): void {+ scrollWorkspaceCode(delta: number, viewportLines = 1): void {const ws = this.state.workspace;if (!ws?.active || !ws.openedFilePreview.length) return;- const maxOffset = Math.max(0, ws.openedFilePreview.length - 1);+ const maxOffset = Math.max(0, ws.openedFilePreview.length - Math.max(1, viewportLines));const next = Math.max(0, Math.min(maxOffset, ws.codeScrollOffset + delta));if (next !== ws.codeScrollOffset) {this.update({ workspace: { ...ws, codeScrollOffset: next } });}}+ private scrollWorkspaceCodeToBoundary(boundary: 'top' | 'bottom', viewportLines = 1): void {+ const ws = this.state.workspace;+ if (!ws?.active || !ws.openedFilePreview.length) return;+ const codeScrollOffset = boundary === 'top'+ ? 0+ : Math.max(0, ws.openedFilePreview.length - Math.max(1, viewportLines));+ this.update({ workspace: { ...ws, codeScrollOffset } });+ }+setWorkspaceFocus(area: 'explorer' | 'code' | 'git' | 'chat'): void {const ws = this.state.workspace;if (!ws?.active) return;@@ -1033,13 +1085,32 @@ export class CLIChannel extends BaseChannel {scrollWorkspaceChat(delta: number): void {const ws = this.state.workspace;if (!ws?.active) return;- const maxOffset = Math.max(0, this.state.chatMessages.length - 1);- const next = Math.max(0, Math.min(maxOffset, ws.chatScrollOffset + delta));+ const next = Math.max(0, ws.chatScrollOffset + delta);if (next !== ws.chatScrollOffset) {this.update({ workspace: { ...ws, chatScrollOffset: next } });}}+ private setWorkspaceChatBoundary(boundary: 'top' | 'bottom'): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ this.update({+ workspace: {+ ...ws,+ chatScrollOffset: boundary === 'top' ? Number.MAX_SAFE_INTEGER : 0,+ },+ });+ }++ private setWorkspaceChatDistance(distance: number): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ const chatScrollOffset = Math.max(0, distance);+ if (chatScrollOffset !== ws.chatScrollOffset) {+ this.update({ workspace: { ...ws, chatScrollOffset } });+ }+ }+private exitWorkspaceToChat(): void {const ws = this.state.workspace;const nextWorkspace = ws ? { ...ws, active: false, focusArea: 'explorer' as const, codeScrollOffset: 0, chatCollapsed: false, chatScrollOffset: 0, rightPanel: 'chat' as const, lastAction: 'Exited workspace mode' } : null;@@ -1054,7 +1125,7 @@ export class CLIChannel extends BaseChannel {private readFilePreview(filePath: string): string[] {try {const raw = fs.readFileSync(filePath, 'utf-8');- return raw.split('\n').slice(0, 500);+ return raw.replace(/\r\n?/g, '\n').split('\n').slice(0, 500);} catch {return ['(Unable to read file preview)'];}diff --git a/src/channels/discord.ts b/src/channels/discord.tsindex 827435a4..81e147f0 100644--- a/src/channels/discord.ts+++ b/src/channels/discord.ts@@ -105,9 +105,7 @@ export class DiscordChannel extends BaseChannel {popDeferredResponse(targetId?: string): string | undefined {const key = targetId || 'notification';- const text = this.deferredResponses.get(key);- this.deferredResponses.delete(key);- return text;+ return this.deferredResponses.get(key);}setOnPermissionMode(handler: (mode: PermissionMode, channelId: string) => void): void {@@ -439,8 +437,7 @@ export class DiscordChannel extends BaseChannel {async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {const channel = await this.resolveTargetChannel(targetId);if (!channel || !this.client) {- logger.warn({ targetId }, 'Discord send: no valid channel');- return;+ throw new Error(`Discord send failed: no valid channel for ${targetId || 'notification'}`);}const key = targetId || 'notification';@@ -478,8 +475,12 @@ export class DiscordChannel extends BaseChannel {await channel.send({ content: chunk, allowedMentions: { parse: [] } });} catch (err: any) {logger.error({ err: err.message, channelId: channel.id }, 'Discord send failed');+ throw err;}}+ if (this.deferredResponses.get(key) === content) {+ this.deferredResponses.delete(key);+ }}async sendFile(filePath: string, targetId?: string): Promise<void> {@@ -537,6 +538,7 @@ export class DiscordChannel extends BaseChannel {await channel.send({ content: chunk, allowedMentions: { parse: [] } });} catch (err: any) {logger.error({ err: err.message }, 'Discord stream send failed');+ throw err;}}return full;@@ -1228,7 +1230,8 @@ export class DiscordChannel extends BaseChannel {this.endTask(targetId);await this.deleteStatusMessageFromDiscord(targetId);- const deferred = this.popDeferredResponse(targetId);+ const key = targetId || 'notification';+ const deferred = this.deferredResponses.get(key);if (deferred?.trim()) {await this.send(deferred, targetId);}@@ -1271,4 +1274,4 @@ export class DiscordChannel extends BaseChannel {allowedMentions: { parse: [] },}).catch(() => {});}-}\ No newline at end of file+}diff --git a/src/channels/registry.ts b/src/channels/registry.tsindex 674da6b4..f5a49685 100644--- a/src/channels/registry.ts+++ b/src/channels/registry.ts@@ -16,18 +16,34 @@ export class ChannelRegistry {if (config.channels.telegram.enabled && config.channels.telegram.botToken) {this.register('telegram', new TelegramChannel(config));+ } else if (config.channels.telegram.botToken && !config.channels.telegram.enabled) {+ logger.warn('Telegram channel has a bot token but is disabled. Run `mercury telegram enable` to re-enable it.');+ } else if (config.channels.telegram.enabled && !config.channels.telegram.botToken) {+ logger.warn('Telegram channel is enabled but no bot token is configured. Run `mercury doctor`.');}if (config.channels.signal.enabled && config.channels.signal.phoneNumber) {this.register('signal', new SignalChannel(config));+ } else if (config.channels.signal.phoneNumber && !config.channels.signal.enabled) {+ logger.warn('Signal channel has a phone number but is disabled. Run `mercury doctor` to re-enable it.');+ } else if (config.channels.signal.enabled && !config.channels.signal.phoneNumber) {+ logger.warn('Signal channel is enabled but no phone number is configured. Run `mercury doctor`.');}if (config.channels.discord.enabled && config.channels.discord.botToken) {this.register('discord', new DiscordChannel(config));+ } else if (config.channels.discord.botToken && !config.channels.discord.enabled) {+ logger.warn('Discord channel has a bot token but is disabled. Run `mercury doctor` to re-enable it.');+ } else if (config.channels.discord.enabled && !config.channels.discord.botToken) {+ logger.warn('Discord channel is enabled but no bot token is configured. Run `mercury doctor`.');}if (config.channels.slack.enabled && config.channels.slack.botToken) {this.register('slack', new SlackChannel(config));+ } else if ((config.channels.slack.botToken || config.channels.slack.appToken) && !config.channels.slack.enabled) {+ logger.warn('Slack channel has credentials but is disabled. Run `mercury doctor` to re-enable it.');+ } else if (config.channels.slack.enabled && (!config.channels.slack.botToken || !config.channels.slack.appToken)) {+ logger.warn('Slack channel is enabled but bot/app token credentials are incomplete. Run `mercury doctor`.');}}@@ -105,4 +121,4 @@ export class ChannelRegistry {logger.debug({ from: msg.channelType, sender: msg.senderId }, 'Incoming message');this.incomingHandler?.(msg);}-}\ No newline at end of file+}diff --git a/src/channels/signal-source-filter.test.ts b/src/channels/signal-source-filter.test.tsnew file mode 100644index 00000000..1a8bbaa7--- /dev/null+++ b/src/channels/signal-source-filter.test.ts@@ -0,0 +1,175 @@+// Regression tests for the Signal source filter (private + group modes).+//+// Bug background: signal-cli emits a syncMessage.sentMessage envelope for EVERY+// message the account owner sends from a linked device — including 1:1 DMs to+// third parties. The sync→dataMessage conversion in handleEnvelopeInner forced+// effectiveSource to the account itself and discarded sentMessage.destination,+// so in private mode every DM the owner sent passed the "is it me?" filter and+// got answered in Note to Self. The fix gates the sync path on the destination+// being the account itself (Note to Self) in private mode.+import { describe, it, expect } from 'vitest';+import { SignalChannel } from './signal.js';+import type { MercuryConfig } from '../utils/config.js';+import type { ChannelMessage } from '../types/channel.js';++const OWNER = '+10000000000';+const ALICE = '+15555550123';+const GROUP_ID = 'group-abc';++function makeConfig(mode: string): MercuryConfig {+ return {+ channels: {+ signal: {+ enabled: true,+ phoneNumber: OWNER,+ mode,+ groupId: mode === 'group' ? GROUP_ID : undefined,+ groupName: mode === 'group' ? 'Mercury' : undefined,+ admins: [{ phoneNumber: OWNER, role: 'admin', pairedAt: new Date().toISOString() }],+ members: [{ phoneNumber: ALICE, role: 'member', pairedAt: new Date().toISOString() }],+ pending: [],+ },+ },+ } as unknown as MercuryConfig;+}++function makeChannel(config: MercuryConfig) {+ const ch = new SignalChannel(config);+ // Keep the in-memory fixture config instead of reading the real one from disk.+ (ch as any).reloadConfigFromDisk = () => {};+ const emitted: ChannelMessage[] = [];+ ch.onMessage((m) => emitted.push(m));+ return { ch, emitted };+}++let ts = 1718000000000;+function nextTs() {+ return ++ts;+}++// Envelope shapes mirror signal-cli JSON-RPC `receive` notifications.+function syncSentEnvelope(opts: { text: string; destination?: string; destinationNumber?: string; groupId?: string }) {+ const t = nextTs();+ return {+ source: OWNER, // sync envelopes always carry the account itself as source+ sourceUuid: 'owner-uuid',+ sourceName: 'You',+ timestamp: t,+ syncMessage: {+ sentMessage: {+ timestamp: t,+ message: opts.text,+ destination: opts.destination,+ destinationNumber: opts.destinationNumber,+ groupInfo: opts.groupId ? { groupId: opts.groupId, groupName: 'Some Group' } : undefined,+ },+ },+ };+}++function incomingEnvelope(opts: { from: string; text: string; groupId?: string }) {+ const t = nextTs();+ return {+ source: opts.from,+ sourceUuid: `${opts.from}-uuid`,+ sourceName: 'Sender',+ timestamp: t,+ dataMessage: {+ timestamp: t,+ message: opts.text,+ groupInfo: opts.groupId ? { groupId: opts.groupId, groupName: 'Some Group' } : undefined,+ },+ };+}++describe('Signal private mode — only Note to Self is processed', () => {+ it('drops a synced DM the owner sent to a third party', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'hey Alice, lunch?', destination: ALICE }));+ expect(emitted).toHaveLength(0);+ });++ it('drops a synced DM addressed by destinationNumber only', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'hey Alice', destinationNumber: ALICE }));+ expect(emitted).toHaveLength(0);+ });++ it('drops a synced message the owner sent to a group', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'hi group', groupId: GROUP_ID }));+ expect(emitted).toHaveLength(0);+ });++ it('processes a synced Note to Self (destination = own number)', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'remind me to buy milk', destination: OWNER }));+ expect(emitted).toHaveLength(1);+ expect(emitted[0].channelId).toBe(`signal:${OWNER}`);+ });++ it('processes a synced Note to Self addressed via destinationNumber', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'note', destinationNumber: OWNER }));+ expect(emitted).toHaveLength(1);+ });++ it('processes a real incoming Note to Self dataMessage (source = self)', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: OWNER, text: 'note from another device' }));+ expect(emitted).toHaveLength(1);+ expect(emitted[0].channelId).toBe(`signal:${OWNER}`);+ });++ it('drops an incoming DM from a third party', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: ALICE, text: 'hi mercury' }));+ expect(emitted).toHaveLength(0);+ });++ it('drops an incoming group message', () => {+ const { ch, emitted } = makeChannel(makeConfig('private'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: ALICE, text: 'hi all', groupId: GROUP_ID }));+ expect(emitted).toHaveLength(0);+ });+});++describe('Signal group mode — only the configured group is processed', () => {+ it('drops a synced DM the owner sent to a third party', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'hey Alice', destination: ALICE }));+ expect(emitted).toHaveLength(0);+ });++ it('drops a synced message the owner sent to a DIFFERENT group', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'wrong group', groupId: 'group-xyz' }));+ expect(emitted).toHaveLength(0);+ });++ it('processes a synced message the owner sent to the configured group', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(syncSentEnvelope({ text: 'hello mercury group', groupId: GROUP_ID }));+ expect(emitted).toHaveLength(1);+ expect(emitted[0].channelId).toBe(`signal:${GROUP_ID}`);+ });++ it('processes an incoming group message from a paired member', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: ALICE, text: 'hey mercury', groupId: GROUP_ID }));+ expect(emitted).toHaveLength(1);+ expect(emitted[0].channelId).toBe(`signal:${GROUP_ID}`);+ });++ it('drops an incoming 1:1 DM even from the admin', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: OWNER, text: 'private hello' }));+ expect(emitted).toHaveLength(0);+ });++ it('drops a message from a different group', () => {+ const { ch, emitted } = makeChannel(makeConfig('group'));+ (ch as any).handleEnvelope(incomingEnvelope({ from: ALICE, text: 'wrong place', groupId: 'group-xyz' }));+ expect(emitted).toHaveLength(0);+ });+});diff --git a/src/channels/signal.ts b/src/channels/signal.tsindex ddcedf66..ee3b6e04 100644--- a/src/channels/signal.ts+++ b/src/channels/signal.ts@@ -69,7 +69,9 @@ export class SignalChannel extends BaseChannel {private taskActive = new Map<string, boolean>();private deferredResponses = new Map<string, string>();private statusNotices = new Map<string, string[]>();+ private lastProgressSentAt = new Map<string, number>();private static readonly MAX_STATUS_NOTICES = 3;+ private static readonly PROGRESS_INTERVAL_MS = 15_000;constructor(private config: MercuryConfig) {super();@@ -116,9 +118,7 @@ export class SignalChannel extends BaseChannel {popDeferredResponse(targetId?: string): string | undefined {const key = targetId || 'notification';- const text = this.deferredResponses.get(key);- this.deferredResponses.delete(key);- return text;+ return this.deferredResponses.get(key);}setOnPermissionMode(handler: (mode: PermissionMode, source: string) => void): void {@@ -229,9 +229,18 @@ export class SignalChannel extends BaseChannel {let effectiveSource = source;let effectiveSourceUuid = envelope.sourceUuid;let effectiveSourceName = envelope.sourceName;+ // Sync envelopes carry every message the owner sends from a linked device,+ // including DMs to third parties — keep the destination so the source+ // filter below can tell Note to Self apart from conversations with others.+ let isSyncSentMessage = false;+ let syncDestination: string | undefined;+ let syncDestinationNumber: string | undefined;if (!effectiveDataMessage && envelope.syncMessage?.sentMessage) {const sent = envelope.syncMessage.sentMessage;+ isSyncSentMessage = true;+ syncDestination = sent.destination;+ syncDestinationNumber = sent.destinationNumber;effectiveDataMessage = {timestamp: sent.timestamp,message: sent.message,@@ -246,7 +255,7 @@ export class SignalChannel extends BaseChannel {effectiveSource = this.config.channels.signal.phoneNumber || source;effectiveSourceUuid = envelope.sourceUuid;effectiveSourceName = envelope.sourceName || 'You';- logger.info({ source: redactPhone(effectiveSource), message: sent.message }, 'Signal: processing syncMessage.sentMessage as dataMessage');+ logger.info({ source: redactPhone(effectiveSource), destination: syncDestination ? redactPhone(syncDestination) : (syncDestinationNumber ? redactPhone(syncDestinationNumber) : 'unknown'), message: sent.message }, 'Signal: processing syncMessage.sentMessage as dataMessage');}if (!effectiveDataMessage) {@@ -266,6 +275,19 @@ export class SignalChannel extends BaseChannel {if (groupId || effectiveSource !== this.config.channels.signal.phoneNumber) {return;}+ // Synced sends (messages the owner sent from a linked device) only+ // qualify when addressed back to this account — i.e. Note to Self.+ // Without this check every DM the owner sends passes the filter above,+ // because the sync conversion forces effectiveSource to the account+ // itself. Fail closed when the destination is missing or unclear.+ if (isSyncSentMessage) {+ const self = this.config.channels.signal.phoneNumber;+ const isNoteToSelf = syncDestination === self || syncDestinationNumber === self;+ if (!isNoteToSelf) {+ logger.debug({ destination: syncDestination ? redactPhone(syncDestination) : 'unknown' }, 'Signal: dropping synced send not addressed to self (not Note to Self)');+ return;+ }+ }} else {if (!groupId) {return;@@ -432,8 +454,7 @@ export class SignalChannel extends BaseChannel {async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {const target = this.resolveTarget(targetId);if (!target || !this.rpc) {- logger.warn({ targetId }, 'Signal send: no valid target');- return;+ throw new Error(`Signal send failed: no valid target for ${targetId || 'notification'}`);}const key = targetId || 'notification';@@ -449,6 +470,7 @@ export class SignalChannel extends BaseChannel {const truncated = fullContent.length > 80 ? fullContent.slice(0, 77) + '…' : fullContent;notices.push(truncated);this.statusNotices.set(key, notices);+ await this.sendProgress(targetId);} else {this.deferredResponses.set(key, fullContent);}@@ -463,11 +485,14 @@ export class SignalChannel extends BaseChannel {const chunks = this.splitMessage(formatted, MAX_MESSAGE_LENGTH);for (const chunk of chunks) {- await this.sendRaw(chunk, target);+ if (!await this.sendRaw(chunk, target)) throw new Error('Signal RPC rejected the message');if (chunks.length > 1) {await this.delay(INTER_MESSAGE_DELAY_MS);}}+ if (this.deferredResponses.get(key) === content) {+ this.deferredResponses.delete(key);+ }}async sendFile(filePath: string, targetId?: string): Promise<void> {@@ -827,7 +852,7 @@ export class SignalChannel extends BaseChannel {...recentHistory.map(h => `✅ ${h}`),`⏳ ${label}…`,];- await this.send(lines.join('\n'), targetId);+ await this.sendProgress(targetId, lines.join('\n'));}async sendStepDone(toolName: string, result: unknown, targetId?: string): Promise<void> {@@ -847,7 +872,24 @@ export class SignalChannel extends BaseChannel {'',...recentHistory.map(h => `✅ ${h}`),];- await this.send(lines.join('\n'), targetId);+ await this.sendProgress(targetId, lines.join('\n'));+ }++ private async sendProgress(targetId?: string, content?: string): Promise<void> {+ const key = targetId || 'notification';+ const now = Date.now();+ if (now - (this.lastProgressSentAt.get(key) || 0) < SignalChannel.PROGRESS_INTERVAL_MS) return;++ const target = this.resolveTarget(targetId);+ if (!target || !this.rpc) return;+ const notices = this.statusNotices.get(key) || [];+ const message = content || ['⚙️ *Mercury working*', ...notices.slice(-SignalChannel.MAX_STATUS_NOTICES)].join('\n');+ try {+ await this.sendRaw(mdToSignal(message), target);+ this.lastProgressSentAt.set(key, now);+ } catch (err) {+ logger.warn({ err }, 'Signal progress update failed');+ }}resetStepCounter(targetId?: string): void {@@ -855,6 +897,7 @@ export class SignalChannel extends BaseChannel {this.stepCounters.delete(key);this.stepHistory.delete(key);this.statusNotices.delete(key);+ this.lastProgressSentAt.delete(key);this.endTask(targetId);}@@ -891,7 +934,6 @@ export class SignalChannel extends BaseChannel {const deferred = this.deferredResponses.get(key);if (deferred && deferred.trim()) {- this.deferredResponses.delete(key);await this.send(deferred, targetId);}@@ -900,6 +942,7 @@ export class SignalChannel extends BaseChannel {this.stepCounters.delete(key);this.stepHistory.delete(key);this.statusNotices.delete(key);+ this.lastProgressSentAt.delete(key);}async sendGoodbyeMessage(): Promise<void> {@@ -1031,4 +1074,4 @@ export class SignalChannel extends BaseChannel {}}}-}\ No newline at end of file+}diff --git a/src/channels/slack.ts b/src/channels/slack.tsindex ff3ddb8e..ec65f0c9 100644--- a/src/channels/slack.ts+++ b/src/channels/slack.ts@@ -62,6 +62,7 @@ export class SlackChannel extends BaseChannel {beginTask(targetId?: string): void {const key = targetId || 'notification';+ if (this.taskActive.get(key)) return;this.taskActive.set(key, true);this.deferredResponses.delete(key);this.statusNotices.delete(key);@@ -69,7 +70,7 @@ export class SlackChannel extends BaseChannel {endTask(targetId?: string): void {const key = targetId || 'notification';- this.taskActive.set(key, false);+ this.taskActive.delete(key);}isTaskActive(targetId?: string): boolean {@@ -391,12 +392,26 @@ export class SlackChannel extends BaseChannel {async send(content: string, targetId?: string, _elapsedMs?: number): Promise<void> {const channel = this.resolveTargetChannel(targetId);- if (!channel) return;+ if (!channel) throw new Error(`Slack send failed: no valid channel for ${targetId || 'notification'}`);const key = targetId || 'notification';if (this.isTaskActive(targetId)) {- this.deferredResponses.set(key, content);+ const isStatusNotice = content.startsWith('☿ ') || content.startsWith('⚠') || content.startsWith(' [') || content.length < 200;+ if (isStatusNotice) {+ const notices = this.statusNotices.get(key) || [];+ notices.push(content.length > 80 ? content.slice(0, 77) + '...' : content);+ this.statusNotices.set(key, notices);+ const counter = this.stepCounters.get(key) || 0;+ const history = this.stepHistory.get(key) || [];+ const description = [+ ...history.slice(-5).map((h) => `:white_check_mark: ${h}`),+ ...notices.slice(-SlackChannel.MAX_STATUS_NOTICES),+ ].join('\n');+ await this.updateStatusBlock(key, `:gear: Mercury working (step ${counter})`, description || 'Processing...');+ } else {+ this.deferredResponses.set(key, content);+ }return;}@@ -413,8 +428,12 @@ export class SlackChannel extends BaseChannel {});} catch (e) {logger.warn({ err: e }, 'Slack send failed');+ throw e;}}+ if (this.deferredResponses.get(key) === content) {+ this.deferredResponses.delete(key);+ }}async sendFile(filePath: string, targetId?: string): Promise<void> {@@ -721,7 +740,6 @@ export class SlackChannel extends BaseChannel {const deferred = this.deferredResponses.get(key);if (deferred) {- this.deferredResponses.delete(key);await this.send(deferred, targetId);}@@ -884,4 +902,4 @@ export class SlackChannel extends BaseChannel {}private _lastMessageTs: string | undefined;-}\ No newline at end of file+}diff --git a/src/channels/telegram.ts b/src/channels/telegram.tsindex fa058df2..a639eb8b 100644--- a/src/channels/telegram.ts+++ b/src/channels/telegram.ts@@ -31,6 +31,7 @@ const ACCESS_ACTION_PREFIX = 'tg_access';const MEMORY_ACTION_PREFIX = 'tg_memory';type ApprovalResolver = () => void;+type ChoiceResolver = (value: string) => void;export class TelegramChannel extends BaseChannel {readonly type = 'telegram' as const;@@ -39,9 +40,15 @@ export class TelegramChannel extends BaseChannel {private typingInterval: NodeJS.Timeout | null = null;private chatCommandContext?: import('../capabilities/registry.js').ChatCommandContext;private pendingApprovals: Map<string, ApprovalResolver> = new Map();+ private pendingChoices: Map<string, ChoiceResolver> = new Map();+ private processedMessages = new Map<string, number>();+ private static readonly DEDUP_TTL = 5 * 60_000;+ private static readonly DEDUP_MAX_SIZE = 10_000;+ private dedupCleanupInterval: NodeJS.Timeout | null = null;private permissionModes = new Map<number, PermissionMode>();private onPermissionMode?: (mode: PermissionMode, chatId: number) => void;private statusMessageIds = new Map<string, number>();+ private statusUpdateQueues = new Map<string, Promise<void>>();private stepCounters = new Map<string, number>();private stepHistory = new Map<string, string[]>();private statusText = new Map<string, string>();@@ -88,12 +95,18 @@ export class TelegramChannel extends BaseChannel {return this.taskActive.get(key) ?? false;}- /** Get and clear deferred response text (to send after task cleanup) */+ /** Peek at deferred response text. A successful final send clears it. */popDeferredResponse(targetId?: string): string | undefined {const key = targetId || 'notification';- const text = this.deferredResponses.get(key);- this.deferredResponses.delete(key);- return text;+ return this.deferredResponses.get(key);+ }++ /** Explicitly queue the final AI response to send after progress cleanup. */+ deferResponse(targetId: string | undefined, content: string): void {+ const key = targetId || 'notification';+ if (content.trim()) {+ this.deferredResponses.set(key, content);+ }}setOnPermissionMode(handler: (mode: PermissionMode, chatId: number) => void): void {@@ -126,6 +139,16 @@ export class TelegramChannel extends BaseChannel {if (!userId) return;+ const dedupKey = `${chatId}:${ctx.message.message_id}`;+ if (this.processedMessages.has(dedupKey)) {+ logger.debug({ chatId, messageId: ctx.message.message_id }, 'Telegram: dedup skipping message');+ return;+ }+ this.processedMessages.set(dedupKey, Date.now());+ if (this.processedMessages.size > TelegramChannel.DEDUP_MAX_SIZE) {+ this.cleanupDedup();+ }+if (ctx.chat.type !== 'private') {await this.sendDirectMessage(chatId, 'This bot is only available in private one-to-one chats.');return;@@ -223,6 +246,21 @@ export class TelegramChannel extends BaseChannel {return;}+ if (data.startsWith('choice:')) {+ const [, id, value] = data.split(':');+ const resolver = id ? this.pendingChoices.get(id) : undefined;+ if (!resolver) {+ await ctx.answerCallbackQuery({ text: 'Expired' });+ return;+ }++ this.pendingChoices.delete(id);+ resolver(value ?? '');+ await ctx.answerCallbackQuery({ text: 'Selected' });+ await ctx.editMessageReplyMarkup({ reply_markup: undefined }).catch((e: any) => logger.debug({ e }, 'telegram editMessageReplyMarkup failed'));+ return;+ }+const resolver = this.pendingApprovals.get(data);if (!resolver) {await ctx.answerCallbackQuery({ text: 'Expired' });@@ -241,6 +279,8 @@ export class TelegramChannel extends BaseChannel {this.bot = bot;+ this.dedupCleanupInterval = setInterval(() => this.cleanupDedup(), 30_000);+// Start long-polling in the background.// bot.start() blocks until the first getUpdates succeeds, which can take// 30-40s on slow networks. Don't block Mercury startup — let it connect@@ -254,8 +294,14 @@ export class TelegramChannel extends BaseChannel {}).catch((err: any) => {const message = err?.description || err?.message || String(err);logger.error({ err: message }, 'Telegram bot polling stopped');- // Don't null out this.bot here — stop() will handle cleanup.- // The guard (if this.bot) prevents a second instance from being created.+ if (this.bot === bot) {+ this.bot = null;+ this.ready = false;+ if (this.dedupCleanupInterval) {+ clearInterval(this.dedupCleanupInterval);+ this.dedupCleanupInterval = null;+ }+ }});}@@ -292,15 +338,19 @@ export class TelegramChannel extends BaseChannel {async stop(): Promise<void> {this.bot?.stop();+ this.bot = null;this.ready = false;this.stopTypingLoop();+ if (this.dedupCleanupInterval) {+ clearInterval(this.dedupCleanupInterval);+ this.dedupCleanupInterval = null;+ }}async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {const chatIds = this.resolveTargetChatIds(targetId);if (chatIds.length === 0 || !this.bot) {- logger.warn({ targetId, chatIds }, 'Telegram send: no valid chat IDs');- return;+ throw new Error(`Telegram send failed: no valid chat for ${targetId || 'notification'}`);}const key = targetId || 'notification';@@ -348,10 +398,14 @@ export class TelegramChannel extends BaseChannel {await this.bot.api.sendMessage(chatId, this.stripHtml(chunk));} catch (err2: any) {logger.error({ err: err2.message, chatId }, 'Telegram send failed');+ throw err2;}}}}+ if (this.deferredResponses.get(key) === content) {+ this.deferredResponses.delete(key);+ }}async sendFile(filePath: string, targetId?: string): Promise<void> {@@ -496,12 +550,17 @@ export class TelegramChannel extends BaseChannel {// Check all task-active keys since we have chatId not targetIdconst activeKey = this.findActiveTaskKey(chatId);if (activeKey) {- let full = '';- for await (const chunk of textStream) {- full += chunk;+ this.startTypingLoop(chatId);+ try {+ let full = '';+ for await (const chunk of textStream) {+ full += chunk;+ }+ this.deferredResponses.set(activeKey, full);+ return full;+ } finally {+ this.stopTypingLoop();}- this.deferredResponses.set(activeKey, full);- return full;}const STREAM_EDIT_INTERVAL = 1500;@@ -627,6 +686,40 @@ export class TelegramChannel extends BaseChannel {});}+ async presentChoicePrompt(question: string, options: Array<{ value: string; label: string }>, targetId?: string): Promise<string> {+ const chatIds = this.resolveTargetChatIds(targetId);+ const chatId = chatIds[0];+ if (!chatId || !this.bot) return options[0]?.value || '';++ const id = `choice_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ const keyboard = new InlineKeyboard();+ for (let i = 0; i < options.length; i++) {+ const option = options[i];+ keyboard.text(option.label.slice(0, 60), `choice:${id}:${option.value}`);+ if (i < options.length - 1 && (i + 1) % 2 === 0) {+ keyboard.row();+ }+ }++ const html = mdToTelegram(question);+ try {+ const msg = await this.bot.api.sendMessage(chatId, html, { parse_mode: 'HTML', reply_markup: keyboard });+ this.trackEphemeral(targetId, msg.message_id);+ } catch {+ const msg = await this.bot.api.sendMessage(chatId, this.stripHtml(html), { reply_markup: keyboard });+ this.trackEphemeral(targetId, msg.message_id);+ }++ return new Promise((resolve) => {+ this.pendingChoices.set(id, resolve);+ setTimeout(() => {+ if (!this.pendingChoices.has(id)) return;+ this.pendingChoices.delete(id);+ resolve(options[0]?.value || '');+ }, 120_000);+ });+ }+async askToContinue(question: string, targetId?: string): Promise<boolean> {const chatIds = this.resolveTargetChatIds(targetId);const chatId = chatIds[0];@@ -1353,6 +1446,22 @@ export class TelegramChannel extends BaseChannel {}private async updateStatusMessage(text: string, targetId?: string): Promise<void> {+ const key = targetId || 'notification';+ const previous = this.statusUpdateQueues.get(key) || Promise.resolve();+ const next = previous+ .catch(() => {})+ .then(() => this.updateStatusMessageNow(text, targetId));+ this.statusUpdateQueues.set(key, next);+ try {+ await next;+ } finally {+ if (this.statusUpdateQueues.get(key) === next) {+ this.statusUpdateQueues.delete(key);+ }+ }+ }++ private async updateStatusMessageNow(text: string, targetId?: string): Promise<void> {const chatIds = this.resolveTargetChatIds(targetId);if (chatIds.length === 0 || !this.bot) return;@@ -1366,7 +1475,13 @@ export class TelegramChannel extends BaseChannel {try {await this.bot.api.editMessageText(chatId, existingMsgId, html, { parse_mode: 'HTML' });return;- } catch {+ } catch (err: any) {+ const description = err?.description || err?.message || '';+ if (String(description).includes('message is not modified')) {+ return;+ }+ await this.unpinStatusMessage(targetId);+ await this.bot.api.deleteMessage(chatId, existingMsgId).catch(() => {});this.statusMessageIds.delete(key);}}@@ -1387,6 +1502,10 @@ export class TelegramChannel extends BaseChannel {private async deleteStatusMessage(targetId?: string): Promise<void> {const key = targetId || 'notification';+ const pendingUpdate = this.statusUpdateQueues.get(key);+ if (pendingUpdate) {+ await pendingUpdate.catch(() => {});+ }const msgId = this.statusMessageIds.get(key);if (msgId && this.bot) {// Unpin before deleting if this was pinned@@ -1493,35 +1612,8 @@ export class TelegramChannel extends BaseChannel {}async sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: { provider: string; model: string; inputTokens: number; outputTokens: number; totalTokens: number; budgetUsed: number; budgetTotal: number; budgetPercentage: number }): Promise<void> {- const secs = Math.floor(elapsedMs / 1000);- const mins = Math.floor(secs / 60);- const remSecs = secs % 60;- const timeStr = mins > 0 ? `${mins}m ${remSecs}s` : `${secs}s`;- const stepsStr = stepCount > 0 ? `${stepCount} step${stepCount !== 1 ? 's' : ''}` : '';- const parts = [stepsStr, timeStr].filter(Boolean).join(' · ');-const key = targetId || 'notification';- const history = this.stepHistory.get(key) || [];- const recentHistory = history.slice(-5);-- const lines = [- `✅ **Task complete** (${parts})`,- ];-- if (meta) {- const formatTokens = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;- lines.push(`☿ ${meta.model} via ${meta.provider} · ${formatTokens(meta.totalTokens)} tokens`);- const pct = Math.round(meta.budgetPercentage);- const barLen = 15;- const filled = Math.round((pct / 100) * barLen);- const bar = '█'.repeat(filled) + '░'.repeat(barLen - filled);- lines.push(`Budget: ${bar} ${pct}% (${formatTokens(meta.budgetUsed)} / ${formatTokens(meta.budgetTotal)})`);- }-- if (recentHistory.length > 0) {- lines.push('');- lines.push(...recentHistory.map(h => ` ✓ ${h}`));- }+ logger.info({ elapsedMs, stepCount, provider: meta?.provider, model: meta?.model }, 'Telegram task complete');// Clean up: unpin + delete the status card, clean up ephemeral messagesawait this.deleteStatusMessage(targetId);@@ -1535,28 +1627,7 @@ export class TelegramChannel extends BaseChannel {// Flush deferred AI response first (the actual answer the user wants to see)const deferred = this.deferredResponses.get(key);if (deferred && deferred.trim()) {- this.deferredResponses.delete(key);- const deferredHtml = mdToTelegram(deferred);- const chunks = this.splitMessage(deferredHtml, MAX_MESSAGE_LENGTH);- for (const chatId of chatIds) {- for (const chunk of chunks) {- try {- await this.bot?.api.sendMessage(chatId, chunk, { parse_mode: 'HTML' });- } catch {- await this.bot?.api.sendMessage(chatId, this.stripHtml(chunk)).catch((e: any) => logger.warn({ e }, "telegram html send failed"));- }- }- }- }-- // Send the completion banner as a separate message- const html = mdToTelegram(lines.join('\n'));- for (const chatId of chatIds) {- try {- await this.bot?.api.sendMessage(chatId, html, { parse_mode: 'HTML' });- } catch {- await this.bot?.api.sendMessage(chatId, this.stripHtml(html)).catch((e: any) => logger.warn({ e }, "telegram html send failed"));- }+ await this.send(deferred, targetId);}this.stepCounters.delete(key);@@ -1636,4 +1707,13 @@ export class TelegramChannel extends BaseChannel {}return null;}++ private cleanupDedup(): void {+ const now = Date.now();+ for (const [key, ts] of this.processedMessages) {+ if (now - ts > TelegramChannel.DEDUP_TTL) {+ this.processedMessages.delete(key);+ }+ }+ }}diff --git a/src/channels/web.test.ts b/src/channels/web.test.tsnew file mode 100644index 00000000..78aca636--- /dev/null+++ b/src/channels/web.test.ts@@ -0,0 +1,129 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { WebChannel } from './web.js';++afterEach(() => {+ vi.useRealTimers();+});++describe('WebChannel durable streaming', () => {+ it('preserves repeated delta chunks verbatim', async () => {+ const channel = new WebChannel('Mercury');+ const chunks: string[] = [];+ channel.addSSEClient({+ enqueue(value: Uint8Array) {+ chunks.push(new TextDecoder().decode(value));+ },+ close() {},+ } as unknown as ReadableStreamDefaultController, 'request-1');++ const result = await channel.stream((async function* () {+ yield 'ha';+ yield 'ha';+ yield '!!';+ yield '!!';+ })(), 'request-1');++ expect(result).toBe('haha!!!!');+ expect(chunks.join('')).toContain('data: {"text":"ha","targetId":"request-1"}');+ expect(chunks.filter((chunk) => chunk.includes('"text":"ha"'))).toHaveLength(2);+ expect(chunks.filter((chunk) => chunk.includes('"text":"!!"'))).toHaveLength(2);+ });++ it('retains a cloud terminal handler when the socket cannot accept delivery', async () => {+ const channel = new WebChannel('Mercury');+ const handler = vi.fn(() => false);+ channel.emitCloudMessage('work', 'request-2', 'session-2', 'conversation-2', undefined, handler);++ await expect(channel.send('final answer', 'request-2')).rejects.toThrow('could not accept');+ expect(channel.hasCloudEventHandler('request-2')).toBe(true);+ });++ it('keeps a cloud request attached after a non-terminal provider status', () => {+ const channel = new WebChannel('Mercury');+ const events: Array<{ type: string; data?: Record<string, unknown> }> = [];+ channel.emitCloudMessage('work', 'request-fallback', 'session-2', 'conversation-2', undefined, (event) => {+ events.push(event);+ return true;+ });++ channel.sendHeartbeat('Provider mercuryCloud failed. Trying fallback...', 'request-fallback');++ expect(events).toContainEqual(expect.objectContaining({ type: 'heartbeat' }));+ expect(channel.hasCloudEventHandler('request-fallback')).toBe(true);+ });++ it('requires an explicit continuation decision even when permissions are bypassed', async () => {+ vi.useFakeTimers();+ const channel = new WebChannel('Mercury');+ channel.setBypassPermissions(true);+ const chunks: string[] = [];+ channel.addSSEClient({+ enqueue(value: Uint8Array) {+ chunks.push(new TextDecoder().decode(value));+ },+ close() {},+ } as unknown as ReadableStreamDefaultController, 'request-3');++ const decision = channel.askToContinue('Continue?', 'request-3');+ const event = chunks.join('').match(/"id":"([^"]+)"/);+ expect(event?.[1]).toBeTruthy();+ expect(channel.resolveApproval(event![1], 'no')).toBe(true);+ await expect(decision).resolves.toBe(false);+ });++ it('binds Cloud approvals to one request and rejects invalid values and replay', async () => {+ vi.useFakeTimers();+ const channel = new WebChannel('Mercury');+ const events: Array<{ type: string; data?: Record<string, unknown> }> = [];+ channel.emitCloudMessage('work', 'request-bound', 'session-1', 'conversation-1', undefined, (event) => {+ events.push(event);+ return true;+ });++ const decision = channel.askPermission('Write file?', 'request-bound');+ const id = events.find((event) => event.type === 'permission_request')?.data?.id as string;++ expect(channel.resolveApproval(id, 'yes', 'different-request')).toBe(false);+ expect(channel.resolveApproval(id, 'unexpected', 'request-bound')).toBe(false);+ expect(channel.resolveApproval(id, 'yes', 'request-bound')).toBe(true);+ expect(channel.resolveApproval(id, 'no', 'request-bound')).toBe(false);+ await expect(decision).resolves.toBe('yes');+ });++ it('cancels an unanswered choice instead of selecting the first option', async () => {+ vi.useFakeTimers();+ const channel = new WebChannel('Mercury');+ const decision = channel.presentChoicePrompt('Choose', [+ { value: 'dangerous', label: 'Proceed' },+ { value: 'safe', label: 'Cancel' },+ ]);++ await vi.advanceTimersByTimeAsync(120_000);++ await expect(decision).resolves.toBe('');+ });++ it('supports an explicit one-shot cancellation for a bound Cloud choice', async () => {+ const channel = new WebChannel('Mercury');+ const events: Array<{ type: string; data?: Record<string, unknown> }> = [];+ channel.emitCloudMessage('work', 'request-choice', 'session-1', 'conversation-1', undefined, (event) => {+ events.push(event);+ return true;+ });+ const decision = channel.presentChoicePrompt('Choose', [{ value: 'continue', label: 'Continue' }], 'request-choice');+ const id = events.find((event) => event.type === 'choice_prompt')?.data?.id as string;++ expect(channel.cancelInteraction(id, 'wrong-request')).toBe(false);+ expect(channel.cancelInteraction(id, 'request-choice')).toBe(true);+ expect(channel.cancelInteraction(id, 'request-choice')).toBe(false);+ await expect(decision).resolves.toBe('');+ });++ it('scopes allow-all mode to its Cloud session', async () => {+ const channel = new WebChannel('Mercury');+ channel.setSessionPermissionMode('session-allowed', 'allow-all');+ channel.emitCloudMessage('work', 'request-allowed', 'session-allowed', 'conversation-1', undefined, () => true);++ await expect(channel.askPermission('Write file?', 'request-allowed')).resolves.toBe('yes');+ });+});diff --git a/src/channels/web.ts b/src/channels/web.tsindex 8997d7db..8e4e3e32 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -1,21 +1,34 @@import { BaseChannel } from './base.js';import type { ChannelMessage } from '../types/channel.js';import { logger } from '../utils/logger.js';+import { randomUUID } from 'node:crypto';-type ApprovalResolver = () => void;+type CloudEventHandler = (event: ChatEvent) => boolean;++type PendingInteractionKind = 'permission' | 'continue' | 'mode' | 'choice';++interface PendingInteraction {+ kind: PendingInteractionKind;+ targetId?: string;+ allowedValues: Set<string>;+ resolve: (value: string) => void;+ timer: ReturnType<typeof setTimeout>;+}export interface ChatEvent {- type: 'thinking' | 'provider' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'loop_warning' | 'error';+ type: 'thinking' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error';data?: Record<string, unknown>;}class SSEClient {controller: ReadableStreamDefaultController;id: string;+ sessionId?: string;- constructor(controller: ReadableStreamDefaultController, id: string) {+ constructor(controller: ReadableStreamDefaultController, id: string, sessionId?: string) {this.controller = controller;this.id = id;+ this.sessionId = sessionId;}send(event: ChatEvent): void {@@ -37,11 +50,12 @@ class SSEClient {export class WebChannel extends BaseChannel {readonly type = 'web' as const;private sseClients: Map<string, SSEClient> = new Map();- private pendingApprovals: Map<string, ApprovalResolver> = new Map();- private pendingContinues: Map<string, ApprovalResolver> = new Map();- private pendingPermModes: Map<string, ApprovalResolver> = new Map();+ private pendingInteractions = new Map<string, PendingInteraction>();private agentName: string;private stepCounter: Map<string, number> = new Map();+ private cloudEventHandlers: Map<string, CloudEventHandler> = new Map();+ private cloudRequestSessions = new Map<string, string>();+ private permissionModes = new Map<string, 'allow-all' | 'ask-me'>();private bypassPermissions = false;private restrictUser = false;@@ -61,11 +75,16 @@ export class WebChannel extends BaseChannel {client.close();}this.sseClients.clear();+ for (const [id, interaction] of this.pendingInteractions) {+ clearTimeout(interaction.timer);+ interaction.resolve(interaction.kind === 'mode' ? 'ask-me' : interaction.kind === 'choice' ? '' : 'no');+ this.pendingInteractions.delete(id);+ }}- addSSEClient(controller: ReadableStreamDefaultController): string {+ addSSEClient(controller: ReadableStreamDefaultController, sessionId?: string): string {const id = `sse_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;- const client = new SSEClient(controller, id);+ const client = new SSEClient(controller, id, sessionId);this.sseClients.set(id, client);return id;}@@ -74,42 +93,101 @@ export class WebChannel extends BaseChannel {this.sseClients.delete(id);}- private broadcast(event: ChatEvent): void {+ private broadcast(event: ChatEvent): boolean {+ let delivered = true;+ const targetId = typeof event.data?.targetId === 'string' ? event.data.targetId : undefined;+ if (targetId) {+ const cloudHandler = this.cloudEventHandlers.get(targetId);+ if (cloudHandler) {+ delivered = cloudHandler(event);+ if (delivered && (event.type === 'text_done' || event.type === 'error')) {+ this.cloudEventHandlers.delete(targetId);+ this.cloudRequestSessions.delete(targetId);+ }+ }+ }+for (const [, client] of this.sseClients) {+ if (targetId && client.sessionId !== targetId) continue;client.send(event);}+ return delivered;}- resolveApproval(id: string, action: string): boolean {- const key = `${id}:${action}`;- const resolver = this.pendingApprovals.get(key);- if (resolver) {- this.pendingApprovals.delete(key);- resolver();- return true;- }- // also check continues- const continueResolver = this.pendingContinues.get(key);- if (continueResolver) {- this.pendingContinues.delete(key);- continueResolver();- return true;- }- // and perm modes- const modeResolver = this.pendingPermModes.get(key);- if (modeResolver) {- this.pendingPermModes.delete(key);- modeResolver();- return true;- }- return false;+ resolveApproval(id: string, action: string, targetId?: string): boolean {+ return this.resolveInteraction(id, action, targetId, ['permission', 'continue', 'mode']);+ }++ resolveChoice(id: string, value: string, targetId?: string): boolean {+ return this.resolveInteraction(id, value, targetId, ['choice']);+ }++ cancelInteraction(id: string, targetId?: string): boolean {+ const interaction = this.pendingInteractions.get(id);+ if (!interaction || (interaction.targetId && interaction.targetId !== targetId)) return false;+ this.pendingInteractions.delete(id);+ clearTimeout(interaction.timer);+ interaction.resolve(interaction.kind === 'choice' ? '' : interaction.kind === 'mode' ? 'ask-me' : 'no');+ return true;+ }++ private resolveInteraction(id: string, value: string, targetId: string | undefined, kinds: PendingInteractionKind[]): boolean {+ const interaction = this.pendingInteractions.get(id);+ if (!interaction || !kinds.includes(interaction.kind) || !interaction.allowedValues.has(value)) return false;+ if (interaction.targetId && interaction.targetId !== targetId) return false;+ this.pendingInteractions.delete(id);+ clearTimeout(interaction.timer);+ interaction.resolve(value);+ return true;+ }++ private waitForInteraction(+ id: string,+ kind: PendingInteractionKind,+ values: string[],+ targetId: string | undefined,+ fallback: string,+ ): Promise<string> {+ const boundTargetId = targetId && this.cloudEventHandlers.has(targetId) ? targetId : undefined;+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ const interaction = this.pendingInteractions.get(id);+ if (!interaction) return;+ this.pendingInteractions.delete(id);+ this.broadcast({+ type: interaction.kind === 'choice' ? 'choice_resolved' : 'permission_resolved',+ data: { id, status: 'expired', targetId: interaction.targetId },+ });+ resolve(fallback);+ }, 120_000);+ this.pendingInteractions.set(id, {+ kind,+ targetId: boundTargetId,+ allowedValues: new Set(values),+ resolve,+ timer,+ });+ });+ }++ private isPermissionBypassed(targetId?: string): boolean {+ if (this.bypassPermissions) return true;+ const sessionId = targetId ? this.cloudRequestSessions.get(targetId) : undefined;+ return !!sessionId && this.permissionModes.get(sessionId) === 'allow-all';+ }++ private hasInteractiveTarget(targetId?: string): boolean {+ if (!targetId) return this.sseClients.size > 0;+ if (this.cloudEventHandlers.has(targetId)) return true;+ return [...this.sseClients.values()].some((client) => client.sessionId === targetId);}async send(content: string, targetId?: string, elapsedMs?: number): Promise<void> {- this.broadcast({+ const delivered = this.broadcast({type: 'text_done',data: { fullText: content, elapsedMs, targetId },});+ if (!delivered) throw new Error('Cloud WebSocket could not accept the terminal response');}async sendFile(_filePath: string, _targetId?: string): Promise<void> {@@ -120,6 +198,7 @@ export class WebChannel extends BaseChannel {let fullText = '';for await (const chunk of content) {fullText += chunk;+ if (!chunk) continue;this.broadcast({type: 'text_delta',data: { text: chunk, targetId },@@ -133,72 +212,48 @@ export class WebChannel extends BaseChannel {}async askPermission(prompt: string, _targetId?: string): Promise<string> {- if (this.bypassPermissions) return 'yes';- const id = `perm_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ if (this.isPermissionBypassed(_targetId)) return 'yes';+ if (!this.hasInteractiveTarget(_targetId)) return 'no';+ const id = `perm_${randomUUID()}`;this.broadcast({type: 'permission_request',data: { id, prompt, options: ['yes', 'always', 'no'], targetId: _targetId },});- return new Promise((resolve) => {- const yesKey = `${id}:yes`;- const alwaysKey = `${id}:always`;- const noKey = `${id}:no`;- this.pendingApprovals.set(yesKey, () => resolve('yes'));- this.pendingApprovals.set(alwaysKey, () => resolve('always'));- this.pendingApprovals.set(noKey, () => resolve('no'));-- setTimeout(() => {- this.pendingApprovals.delete(yesKey);- this.pendingApprovals.delete(alwaysKey);- this.pendingApprovals.delete(noKey);- resolve('no');- }, 120_000);- });+ return this.waitForInteraction(id, 'permission', ['yes', 'always', 'no'], _targetId, 'no');}async askToContinue(question: string, _targetId?: string): Promise<boolean> {- if (this.bypassPermissions) return true;- const id = `loop_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ if (!this.hasInteractiveTarget(_targetId)) return false;+ const id = `loop_${randomUUID()}`;this.broadcast({type: 'permission_continue',data: { id, question, options: ['yes', 'no'], targetId: _targetId },});- return new Promise((resolve) => {- const yesKey = `${id}:yes`;- const noKey = `${id}:no`;- this.pendingContinues.set(yesKey, () => resolve(true));- this.pendingContinues.set(noKey, () => resolve(false));-- setTimeout(() => {- this.pendingContinues.delete(yesKey);- this.pendingContinues.delete(noKey);- resolve(false);- }, 120_000);- });+ return this.waitForInteraction(id, 'continue', ['yes', 'no'], _targetId, 'no').then((value) => value === 'yes');}askPermissionMode(): Promise<'allow-all' | 'ask-me'> {if (this.bypassPermissions) return Promise.resolve('allow-all');- const id = `mode_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ const id = `mode_${randomUUID()}`;this.broadcast({type: 'permission_mode',data: { id, options: ['ask-me', 'allow-all'] },});- return new Promise((resolve) => {- const askKey = `${id}:ask-me`;- const allowKey = `${id}:allow-all`;- this.pendingPermModes.set(askKey, () => resolve('ask-me'));- this.pendingPermModes.set(allowKey, () => resolve('allow-all'));-- setTimeout(() => {- this.pendingPermModes.delete(askKey);- this.pendingPermModes.delete(allowKey);- resolve('ask-me');- }, 120_000);+ return this.waitForInteraction(id, 'mode', ['ask-me', 'allow-all'], undefined, 'ask-me') as Promise<'allow-all' | 'ask-me'>;+ }++ async presentChoicePrompt(question: string, options: Array<{ value: string; label: string }>, targetId?: string): Promise<string> {+ if (!this.hasInteractiveTarget(targetId)) return '';+ const id = `choice_${randomUUID()}`;+ this.broadcast({+ type: 'choice_prompt',+ data: { id, question, options, targetId },});++ return this.waitForInteraction(id, 'choice', options.map((option) => option.value), targetId, '');}sendToolFeedback(toolName: string, args: Record<string, unknown>, targetId?: string): void {@@ -233,6 +288,13 @@ export class WebChannel extends BaseChannel {});}+ sendHeartbeat(message: string, targetId?: string): void {+ this.broadcast({+ type: 'heartbeat',+ data: { message, targetId },+ });+ }+sendLoopWarning(message: string, targetId?: string): void {this.broadcast({type: 'loop_warning',@@ -240,8 +302,8 @@ export class WebChannel extends BaseChannel {});}- sendError(message: string, targetId?: string): void {- this.broadcast({+ sendError(message: string, targetId?: string): boolean {+ return this.broadcast({type: 'error',data: { message, targetId },});@@ -256,7 +318,7 @@ export class WebChannel extends BaseChannel {this.emitMessageInThread(content, 'web:default');}- emitMessageInThread(content: string, threadId: string): void {+ emitMessageInThread(content: string, threadId: string, sessionId?: string, requestId?: string, externalConversationId?: string, messageId?: string): void {if (this.restrictUser) {throw new Error('Web user is restricted. Disable restrict mode to continue.');}@@ -268,14 +330,35 @@ export class WebChannel extends BaseChannel {senderName: 'You',content,timestamp: Date.now(),+ sessionId,+ metadata: {+ ...(sessionId ? { sessionId } : {}),+ ...(requestId ? { requestId } : {}),+ ...(externalConversationId ? { externalConversationId } : {}),+ ...(messageId ? { canonicalMessageId: messageId } : {}),+ },};this.emit(msg);}+ emitCloudMessage(content: string, requestId: string, sessionId: string, externalConversationId: string, messageId: string | undefined, onEvent: CloudEventHandler): void {+ this.cloudEventHandlers.set(requestId, onEvent);+ this.cloudRequestSessions.set(requestId, sessionId);+ this.emitMessageInThread(content, requestId, sessionId, requestId, externalConversationId, messageId);+ }++ hasCloudEventHandler(requestId: string): boolean {+ return this.cloudEventHandlers.has(requestId);+ }+setBypassPermissions(enabled: boolean): void {this.bypassPermissions = enabled;}+ setSessionPermissionMode(sessionId: string, mode: 'allow-all' | 'ask-me'): void {+ this.permissionModes.set(sessionId, mode);+ }+setRestrictUser(enabled: boolean): void {this.restrictUser = enabled;}diff --git a/src/cli/daemon.ts b/src/cli/daemon.tsindex e05a67dd..493476bc 100644--- a/src/cli/daemon.ts+++ b/src/cli/daemon.ts@@ -45,18 +45,43 @@ export function buildDaemonSpawnArgs(): { command: string; args: string[] } {}const PID_FILE = 'daemon.pid';+const FOREGROUND_PID_FILE = 'foreground.pid';const LOG_FILE = 'daemon.log';function pidPath(): string {return join(getMercuryHome(), PID_FILE);}+function foregroundPidPath(): string {+ return join(getMercuryHome(), FOREGROUND_PID_FILE);+}+function logPath(): string {return join(getMercuryHome(), LOG_FILE);}+export function registerRuntimeProcess(mode: 'daemon' | 'foreground'): void {+ const path = mode === 'daemon' ? pidPath() : foregroundPidPath();+ const existing = readTrackedPid(path);+ if (existing && existing !== process.pid && isProcessRunning(existing)) {+ throw new Error(`Mercury ${mode} runtime is already running (PID: ${existing})`);+ }+ const home = getMercuryHome();+ if (!existsSync(home)) mkdirSync(home, { recursive: true });+ writeFileSync(path, String(process.pid));+}++export function releaseRuntimeProcess(mode: 'daemon' | 'foreground'): void {+ const path = mode === 'daemon' ? pidPath() : foregroundPidPath();+ if (readTrackedPid(path) !== process.pid) return;+ try { unlinkSync(path); } catch {}+}+export function readPid(): number | null {- const path = pidPath();+ return readTrackedPid(pidPath());+}++function readTrackedPid(path: string): number | null {if (!existsSync(path)) return null;try {const pid = parseInt(readFileSync(path, 'utf-8').trim(), 10);@@ -67,6 +92,43 @@ export function readPid(): number | null {}}+export function getForegroundRuntimeStatus(): { running: boolean; pid: number | null } {+ const path = foregroundPidPath();+ const pid = readTrackedPid(path);+ if (!pid) return { running: false, pid: null };+ if (!isProcessRunning(pid)) {+ try { unlinkSync(path); } catch {}+ return { running: false, pid: null };+ }+ return { running: true, pid };+}++export async function stopForegroundRuntime(): Promise<boolean> {+ const status = getForegroundRuntimeStatus();+ if (!status.running || !status.pid) return true;++ try {+ process.kill(status.pid, process.platform === 'win32' ? undefined : 'SIGTERM');+ } catch {+ return false;+ }++ const deadline = Date.now() + 5_000;+ while (Date.now() < deadline && isProcessRunning(status.pid)) {+ await new Promise(resolve => setTimeout(resolve, 200));+ }+ if (isProcessRunning(status.pid)) {+ try { process.kill(status.pid, 'SIGKILL'); } catch {}+ await new Promise(resolve => setTimeout(resolve, 500));+ }+ if (isProcessRunning(status.pid)) return false;+ if (readTrackedPid(foregroundPidPath()) === status.pid) {+ try { unlinkSync(foregroundPidPath()); } catch {}+ }+ console.log(chalk.green(` Stopped foreground Mercury (PID: ${status.pid})`));+ return true;+}+function isProcessRunning(pid: number): boolean {try {process.kill(pid, 0);@@ -135,14 +197,14 @@ export function startBackground(): void {}}-export async function stopDaemon(): Promise<void> {+export async function stopDaemon(): Promise<boolean> {const status = getDaemonStatus();if (!status.pid) {console.log(chalk.yellow(' Mercury is not running as a daemon.'));killStaleSignalCliProcesses();console.log('');- return;+ return true;}if (!status.running) {@@ -150,7 +212,7 @@ export async function stopDaemon(): Promise<void> {try { unlinkSync(pidPath()); } catch {}killStaleSignalCliProcesses();console.log('');- return;+ return true;}try {@@ -161,10 +223,9 @@ export async function stopDaemon(): Promise<void> {}} catch {console.log(chalk.red(` Failed to stop PID ${status.pid}. You may need to kill it manually.`));- try { unlinkSync(pidPath()); } catch {}killStaleSignalCliProcesses();console.log('');- return;+ return false;}console.log(chalk.dim(` Stopping Mercury (PID: ${status.pid})...`));@@ -183,6 +244,10 @@ export async function stopDaemon(): Promise<void> {} catch { /* already dead */ }// Wait briefly for SIGKILL to take effectawait new Promise(resolve => setTimeout(resolve, 500));+ if (isProcessRunning(status.pid)) {+ console.log(chalk.red(` Failed to stop PID ${status.pid}. Cloud disconnect aborted.`));+ return false;+ }}try { unlinkSync(pidPath()); } catch {}@@ -191,11 +256,12 @@ export async function stopDaemon(): Promise<void> {console.log(chalk.green(` Mercury stopped (PID: ${status.pid})`));console.log('');+ return true;}export async function restartDaemon(): Promise<void> {if (getDaemonStatus().running) {- await stopDaemon();+ if (!await stopDaemon()) return;}console.log(chalk.yellow(' Starting Mercury...'));@@ -221,4 +287,4 @@ export function tryAutoDaemonize(): boolean {} catch {return false;}-}\ No newline at end of file+}diff --git a/src/cli/service.ts b/src/cli/service.tsindex caf034b7..ab0594a4 100644--- a/src/cli/service.ts+++ b/src/cli/service.ts@@ -6,6 +6,7 @@ import { execSync } from 'node:child_process';import { getMercuryHome } from '../utils/config.js';import { logger } from '../utils/logger.js';import { isStandaloneBinary } from './daemon.js';+import { isTermux } from '../utils/platform.js';const SERVICE_NAME = 'mercury';const SERVICE_DESC = 'Mercury — Soul-Driven AI Agent';@@ -14,6 +15,8 @@ const WIN_TASK_NAME = 'MercuryAgent';export function isServiceInstalled(): boolean {const platform = process.platform;+ if (isTermux()) return false;+if (platform === 'darwin') {return existsSync(join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist'));} else if (platform === 'linux') {@@ -29,6 +32,26 @@ export function isServiceInstalled(): boolean {return false;}+export function isServiceRunning(): boolean {+ if (!isServiceInstalled()) return false;+ try {+ if (process.platform === 'darwin') {+ const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;+ const output = execSync(`launchctl print ${target}`, { encoding: 'utf-8' });+ return /state\s*=\s*running/.test(output);+ }+ if (process.platform === 'linux') {+ execSync('systemctl --user is-active --quiet mercury.service', { stdio: 'pipe' });+ return true;+ }+ if (process.platform === 'win32') {+ const output = execSync(`schtasks /query /tn "${WIN_TASK_NAME}" /fo list /v`, { encoding: 'utf-8', shell: 'cmd.exe' });+ return /^Status:\s+Running\s*$/im.test(output);+ }+ } catch {}+ return false;+}+function getNodeBinPath(): string {return process.execPath;}@@ -56,6 +79,11 @@ function getServiceLaunchArgs(): string[] {export function installService(): void {const platform = process.platform;+ if (isTermux()) {+ showTermuxServiceHelp('install');+ return;+ }+if (platform === 'darwin') {installMac();} else if (platform === 'linux') {@@ -71,6 +99,11 @@ export function installService(): void {export function uninstallService(): void {const platform = process.platform;+ if (isTermux()) {+ showTermuxServiceHelp('uninstall');+ return;+ }+if (platform === 'darwin') {uninstallMac();} else if (platform === 'linux') {@@ -86,6 +119,11 @@ export function uninstallService(): void {export function showServiceStatus(): void {const platform = process.platform;+ if (isTermux()) {+ showTermuxServiceHelp('status');+ return;+ }+if (platform === 'darwin') {showMacStatus();} else if (platform === 'linux') {@@ -95,6 +133,76 @@ export function showServiceStatus(): void {}}+export function restartService(): void {+ if (!isServiceInstalled()) throw new Error('Mercury system service is not installed');++ if (process.platform === 'darwin') {+ const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;+ try {+ execSync(`launchctl kickstart -k ${target}`, { stdio: 'inherit' });+ } catch {+ const plistPath = join(homedir(), 'Library', 'LaunchAgents', 'com.cosmicstack.mercury.plist');+ execSync(`launchctl load "${plistPath}"`, { stdio: 'inherit' });+ execSync(`launchctl kickstart -k ${target}`, { stdio: 'inherit' });+ }+ return;+ }++ if (process.platform === 'linux') {+ execSync('systemctl --user restart mercury.service', { stdio: 'inherit' });+ return;+ }++ if (process.platform === 'win32') {+ try {+ execSync(`schtasks /end /tn "${WIN_TASK_NAME}"`, { stdio: 'pipe', shell: 'cmd.exe' });+ } catch {}+ execSync(`schtasks /run /tn "${WIN_TASK_NAME}"`, { stdio: 'inherit', shell: 'cmd.exe' });+ return;+ }++ throw new Error(`Unsupported platform: ${process.platform}`);+}++export function stopService(): boolean {+ if (!isServiceInstalled()) return true;++ if (process.platform === 'darwin') {+ const target = `gui/${process.getuid?.() ?? 0}/com.cosmicstack.mercury`;+ try { execSync(`launchctl kill SIGTERM ${target}`, { stdio: 'inherit' }); } catch {}+ return waitForServiceStop();+ }+ if (process.platform === 'linux') {+ execSync('systemctl --user stop mercury.service', { stdio: 'inherit' });+ return !isServiceRunning();+ }+ if (process.platform === 'win32') {+ try { execSync(`schtasks /end /tn "${WIN_TASK_NAME}"`, { stdio: 'inherit', shell: 'cmd.exe' }); } catch {}+ return waitForServiceStop();+ }+ return true;+}++function waitForServiceStop(): boolean {+ const deadline = Date.now() + 5_000;+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));+ while (Date.now() < deadline) {+ if (!isServiceRunning()) return true;+ Atomics.wait(waitBuffer, 0, 0, 100);+ }+ return !isServiceRunning();+}++function showTermuxServiceHelp(action: 'install' | 'uninstall' | 'status'): void {+ console.log('');+ console.log(chalk.yellow(` System service ${action} is not available in Termux (systemd is not present).`));+ console.log(chalk.dim(' Start Mercury with: mercury start'));+ console.log(chalk.dim(' Check it with: mercury status'));+ console.log(chalk.dim(' Stop it with: mercury stop'));+ console.log(chalk.dim(' For boot startup, use the Termux:Boot add-on and a ~/.termux/boot script.'));+ console.log('');+}+function installMac(): void {const plistDir = join(homedir(), 'Library', 'LaunchAgents');const plistPath = join(plistDir, 'com.cosmicstack.mercury.plist');@@ -389,4 +497,4 @@ function showWindowsStatus(): void {console.log(chalk.dim(' Run `mercury service install` to set it up.'));console.log('');}-}\ No newline at end of file+}diff --git a/src/cloud/client.test.ts b/src/cloud/client.test.tsnew file mode 100644index 00000000..8959e146--- /dev/null+++ b/src/cloud/client.test.ts@@ -0,0 +1,183 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { WebSocket, WebSocketServer } from 'ws';+import { logger } from '../utils/logger.js';++import { MercuryCloudClient } from './client.js';+import type { CloudTokenStore } from './token-store.js';++function makeStore(jwt = 'token', refreshTokenValue = 'refresh', agentId = 'agent'): CloudTokenStore {+ return {+ getJwt: vi.fn(() => jwt),+ getRefreshToken: vi.fn(() => refreshTokenValue),+ getAgentId: vi.fn(() => agentId),+ getApiUrl: vi.fn(() => 'https://api.example.com'),+ getAgentApiKey: vi.fn(() => 'mcapk_testkey'),+ getTokens: vi.fn(() => ({ jwt, refreshToken: refreshTokenValue })),+ isJwtNearExpiry: vi.fn(() => false),+ setTokens: vi.fn(),+ setTokensAndPersist: vi.fn(),+ rotate: vi.fn(async () => {+ const result = { jwt: 'new-token', refreshToken: 'new-refresh' };+ jwt = result.jwt;+ refreshTokenValue = result.refreshToken;+ return result;+ }),+ rotateIfExpired: vi.fn(async () => jwt),+ addListener: vi.fn(() => () => {}),+ } as unknown as CloudTokenStore;+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('MercuryCloudClient', () => {+ it('waits for open and observes rejected async message handlers', async () => {+ const server = new WebSocketServer({ port: 0 });+ await new Promise<void>((resolve) => server.once('listening', resolve));+ const address = server.address();+ if (typeof address === 'string' || address === null) throw new Error('Expected TCP WebSocket address');++ const handlerError = vi.spyOn(logger, 'error').mockImplementation(() => logger);+ const connectionChange = vi.fn();+ const client = new MercuryCloudClient(`ws://127.0.0.1:${address.port}`, makeStore(), connectionChange);+ client.on('agent.status', async () => {+ throw new Error('handler exploded');+ });+ server.on('connection', (socket) => {+ socket.send(JSON.stringify({ type: 'agent.status' }));+ });++ await client.connect();+ expect(client.isConnected()).toBe(true);+ expect(connectionChange).toHaveBeenCalledWith(true);+ await vi.waitFor(() => expect(handlerError).toHaveBeenCalledWith(+ expect.objectContaining({ err: 'handler exploded', type: 'agent.status' }),+ 'Mercury Cloud WebSocket handler failed',+ ));++ client.disconnect();+ expect(connectionChange).toHaveBeenLastCalledWith(false);+ await new Promise<void>((resolve) => server.close(() => resolve()));+ });++ it('refreshes an expired access token before the WebSocket handshake', async () => {+ const server = new WebSocketServer({ port: 0 });+ await new Promise<void>((resolve) => server.once('listening', resolve));+ const address = server.address();+ if (typeof address === 'string' || address === null) throw new Error('Expected TCP WebSocket address');+ const store = makeStore('expired-token');+ (store.rotateIfExpired as ReturnType<typeof vi.fn>).mockImplementation(async () => {+ (store.getJwt as ReturnType<typeof vi.fn>).mockReturnValue('fresh-token');+ return 'fresh-token';+ });+ const requestHeaders = new Promise<{ authorization?: string; agentApiKey?: string }>((resolve) => {+ server.once('connection', (_socket, request) => resolve({+ authorization: request.headers.authorization,+ agentApiKey: request.headers['x-agent-api-key'] as string | undefined,+ }));+ });+ const client = new MercuryCloudClient(`ws://127.0.0.1:${address.port}`, store);++ await client.connect();++ await expect(requestHeaders).resolves.toEqual({ authorization: 'Bearer fresh-token', agentApiKey: undefined });+ expect(store.rotateIfExpired).toHaveBeenCalledWith(2 * 60_000);+ client.disconnect();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ });++ it('does not open a socket after disconnect during startup token preparation', async () => {+ let finishPreparation!: () => void;+ const store = makeStore();+ (store.rotateIfExpired as ReturnType<typeof vi.fn>).mockReturnValue(new Promise<string>((resolve) => {+ finishPreparation = () => resolve('fresh-token');+ }));+ const client = new MercuryCloudClient('ws://127.0.0.1:1', store);++ const connecting = client.connect();+ client.disconnect();+ finishPreparation();+ await connecting;++ expect(client.isConnected()).toBe(false);+ expect((client as any).ws).toBeNull();+ });++ it('never throws from send and applies the buffered amount guard', () => {+ const client = new MercuryCloudClient('ws://example.test', makeStore());+ const socket = {+ readyState: WebSocket.OPEN,+ bufferedAmount: 0,+ send: vi.fn(() => { throw new Error('socket failed'); }),+ };+ (client as any).ws = socket;++ expect(client.send({ type: 'agent.status' })).toBe(false);+ socket.bufferedAmount = 1024 * 1024 + 1;+ expect(client.send({ type: 'agent.status' })).toBe(false);+ expect(socket.send).toHaveBeenCalledTimes(1);+ });++ it('sends a command ACK with the durable request ID', () => {+ const client = new MercuryCloudClient('ws://example.test', makeStore('token', 'refresh', 'agent'));+ const socket = { readyState: WebSocket.OPEN, bufferedAmount: 0, send: vi.fn() };+ (client as any).ws = socket;++ expect(client.sendCommandAck('request-1')).toBe(true);+ expect(JSON.parse(socket.send.mock.calls[0][0])).toMatchObject({+ type: 'agent.command.ack',+ agentId: 'agent',+ payload: { requestId: 'request-1' },+ });+ });++ it('does not reconnect after disconnect while refresh is in flight', async () => {+ let resolveRefresh!: (value: { jwt: string; refreshToken: string }) => void;+ const store = makeStore();+ (store.rotate as ReturnType<typeof vi.fn>).mockReturnValue(new Promise((resolve) => { resolveRefresh = resolve; }));+ const client = new MercuryCloudClient('ws://example.test', store);+ const connect = vi.spyOn(client, 'connect');++ const refreshing = (client as any).tryRefreshAndReconnect();+ client.disconnect();+ resolveRefresh({ jwt: 'new-token', refreshToken: 'new-refresh' });+ await refreshing;++ expect(connect).not.toHaveBeenCalled();+ });++ it('schedules another attempt after a transient auth refresh failure', async () => {+ const store = makeStore();+ (store.rotate as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('temporarily unavailable'));+ const client = new MercuryCloudClient('ws://example.test', store);+ (client as any).authRefreshNeeded = true;++ await (client as any).tryRefreshAndReconnect();++ expect((client as any).reconnectTimer).not.toBeNull();+ client.disconnect();+ });++ it('refreshes with the agent key when no refresh token remains', async () => {+ const store = makeStore('expired-token', '');+ const client = new MercuryCloudClient('ws://example.test', store);+ vi.spyOn(client, 'connect').mockResolvedValue();++ await (client as any).tryRefreshAndReconnect();++ expect(store.rotate).toHaveBeenCalledOnce();+ client.disconnect();+ });++ it('keeps only one reconnect timer', () => {+ vi.useFakeTimers();+ const client = new MercuryCloudClient('ws://example.test', makeStore());+ (client as any).scheduleReconnect();+ const timer = (client as any).reconnectTimer;+ (client as any).scheduleReconnect();+ expect((client as any).reconnectTimer).toBe(timer);+ client.disconnect();+ vi.useRealTimers();+ });+});diff --git a/src/cloud/client.ts b/src/cloud/client.tsnew file mode 100644index 00000000..45e4d755--- /dev/null+++ b/src/cloud/client.ts@@ -0,0 +1,372 @@+import type { WSMessage, WSMessageType } from './types.js';+import type { CloudTokenStore } from './token-store.js';+import { WebSocket } from 'ws';+import { logger } from '../utils/logger.js';++export type WSMessageHandler = (message: WSMessage) => void | Promise<void>;++const HEARTBEAT_INTERVAL_MS = 30_000;+const MAX_BUFFERED_AMOUNT = 1024 * 1024;++export class MercuryCloudClient {+ private ws: WebSocket | null = null;+ private url: string;+ private tokenStore: CloudTokenStore;+ private heartbeatInterval: ReturnType<typeof setInterval> | null = null;+ private tokenCheckInterval: ReturnType<typeof setInterval> | null = null;+ private reconnectAttempts = 0;+ private maxReconnectAttempts = 50;+ private handlers = new Map<string, WSMessageHandler[]>();+ private isConnecting = false;+ private shouldReconnect = true;+ private isRefreshing = false;+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;+ private lastRefreshFailureLogAt = 0;+ private connectedHandlers = new Set<() => void | Promise<void>>();+ private awaitingPong = false;+ private lifecycleGeneration = 0;+ private authRefreshNeeded = false;+ private connectPromise: Promise<void> | null = null;+ private tokenPreparation: Promise<string> | null = null;+ private readonly onConnectionChange?: (connected: boolean) => void;++ constructor(url: string, tokenStore: CloudTokenStore, onConnectionChange?: (connected: boolean) => void) {+ this.url = url;+ this.tokenStore = tokenStore;+ this.onConnectionChange = onConnectionChange;+ }++ async connect(): Promise<void> {+ if (this.isConnected()) return;+ if (this.connectPromise) return this.connectPromise;+ this.shouldReconnect = true;+ this.isConnecting = true;+ const generation = this.lifecycleGeneration;++ // Never attempt an authenticated handshake with a token that is already+ // expired. Refresh first so every new/reconnected socket is validated by+ // the server using current credentials.+ try {+ const preparation = this.tokenPreparation ?? this.tokenStore.rotateIfExpired(2 * 60_000);+ this.tokenPreparation = preparation;+ await preparation;+ if (this.tokenPreparation === preparation) this.tokenPreparation = null;+ } catch (error) {+ this.tokenPreparation = null;+ this.isConnecting = false;+ if (this.shouldReconnect) this.scheduleReconnect();+ throw error;+ }+ if (!this.shouldReconnect || generation !== this.lifecycleGeneration) {+ this.isConnecting = false;+ return;+ }+ if (this.isConnected()) {+ this.isConnecting = false;+ return;+ }+ if (this.connectPromise) return this.connectPromise;++ // Pass the access token via an Authorization header rather than a URL+ // query parameter so it never appears in server/proxy access logs.+ const wsUrl = `${this.url}?agentId=${this.tokenStore.getAgentId()}`;++ try {+ const headers: Record<string, string> = { Authorization: `Bearer ${this.tokenStore.getJwt()}` };+ const socket = new WebSocket(wsUrl, {+ handshakeTimeout: 15_000,+ headers,+ });+ this.ws = socket;+ this.connectPromise = new Promise<void>((resolve, reject) => {+ let opened = false;++ socket.on('open', () => {+ if (this.ws !== socket) return;+ opened = true;+ this.isConnecting = false;+ this.reconnectAttempts = 0;+ this.authRefreshNeeded = false;+ this.awaitingPong = false;+ this.startHeartbeat();+ this.startTokenCheck();+ this.onConnectionChange?.(true);+ resolve();+ for (const handler of this.connectedHandlers) {+ this.runHandler('connected', handler);+ }+ });++ socket.on('message', (data) => {+ this.awaitingPong = false;+ try {+ const message = JSON.parse(data.toString()) as WSMessage;+ for (const handler of this.handlers.get(message.type) || []) {+ this.runHandler(message.type, () => handler(message));+ }+ } catch (error) {+ logger.warn({ err: error instanceof Error ? error.message : String(error) }, 'Invalid Mercury Cloud WebSocket message');+ }+ });++ socket.on('pong', () => {+ this.awaitingPong = false;+ });++ socket.on('close', (code) => {+ if (!opened) reject(new Error(`Mercury Cloud WebSocket closed before opening (${code})`));+ if (this.ws !== socket) return;+ this.isConnecting = false;+ this.stopHeartbeat();+ this.stopTokenCheck();+ this.ws = null;+ this.connectPromise = null;+ this.onConnectionChange?.(false);++ if (!this.shouldReconnect) return;+ this.authRefreshNeeded = code === 1008;+ this.scheduleReconnect();+ });++ socket.on('error', (error) => {+ logger.warn({ err: error.message }, 'Mercury Cloud WebSocket error');+ });+ }).finally(() => {+ if (this.ws !== socket || socket.readyState === WebSocket.OPEN) this.connectPromise = null;+ });+ return await this.connectPromise;+ } catch (error) {+ this.isConnecting = false;+ this.connectPromise = null;+ if (this.shouldReconnect) this.scheduleReconnect();+ throw error;+ }+ }++ disconnect(): void {+ this.shouldReconnect = false;+ this.lifecycleGeneration++;+ this.authRefreshNeeded = false;+ this.isConnecting = false;+ this.connectPromise = null;+ this.stopHeartbeat();+ this.stopTokenCheck();+ this.onConnectionChange?.(false);+ if (this.reconnectTimer) {+ clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ if (this.ws) {+ this.ws.close();+ this.ws = null;+ }+ }++ on(type: WSMessageType, handler: WSMessageHandler): void {+ const key = type as string;+ if (!this.handlers.has(key)) {+ this.handlers.set(key, []);+ }+ this.handlers.get(key)!.push(handler);+ }++ off(type: WSMessageType, handler: WSMessageHandler): void {+ const key = type as string;+ const handlers = this.handlers.get(key);+ if (handlers) {+ const idx = handlers.indexOf(handler);+ if (idx >= 0) handlers.splice(idx, 1);+ }+ }++ onConnected(handler: () => void | Promise<void>): () => void {+ this.connectedHandlers.add(handler);+ return () => this.connectedHandlers.delete(handler);+ }++ send(message: WSMessage): boolean {+ const socket = this.ws;+ if (!socket || socket.readyState !== WebSocket.OPEN) return false;+ if (socket.bufferedAmount > MAX_BUFFERED_AMOUNT) {+ logger.warn({ bufferedAmount: socket.bufferedAmount, type: message.type }, 'Mercury Cloud WebSocket send skipped due to backpressure');+ return false;+ }+ try {+ socket.send(JSON.stringify(message), (error) => {+ if (error) logger.warn({ err: error.message, type: message.type }, 'Mercury Cloud WebSocket send failed');+ });+ return true;+ } catch (error) {+ logger.warn({ err: error instanceof Error ? error.message : String(error), type: message.type }, 'Mercury Cloud WebSocket send failed');+ return false;+ }+ }++ sendResponse(payload: { message: string; conversationId?: string; sessionId?: string; requestId?: string; inReplyTo?: string }): void {+ this.send({+ type: 'agent.response',+ agentId: this.tokenStore.getAgentId(),+ payload,+ timestamp: new Date().toISOString(),+ });+ }++ sendCommandAck(requestId: string): boolean {+ return this.send({+ type: 'agent.command.ack',+ agentId: this.tokenStore.getAgentId(),+ payload: { requestId },+ timestamp: new Date().toISOString(),+ });+ }++ sendStream(payload: { event: string; data?: Record<string, unknown>; conversationId?: string; sessionId?: string; requestId?: string }): boolean {+ return this.send({+ type: 'agent.stream',+ agentId: this.tokenStore.getAgentId(),+ payload,+ timestamp: new Date().toISOString(),+ });+ }++ sendResearchArtifact(payload: { artifactId: string; title?: string; markdown: string; conversationId?: string; sessionId?: string; requestId?: string; topic?: string }): void {+ this.send({+ type: 'research.artifact',+ agentId: this.tokenStore.getAgentId(),+ payload,+ timestamp: new Date().toISOString(),+ });+ }++ isConnected(): boolean {+ return this.ws !== null && this.ws.readyState === WebSocket.OPEN;+ }++ private startHeartbeat(): void {+ this.stopHeartbeat();+ this.heartbeatInterval = setInterval(() => {+ const socket = this.ws;+ if (!socket || socket.readyState !== WebSocket.OPEN) return;+ if (this.awaitingPong) {+ logger.warn('Mercury Cloud WebSocket heartbeat timed out; reconnecting');+ socket.terminate();+ return;+ }+ this.awaitingPong = true;+ try {+ socket.ping();+ } catch (error) {+ logger.warn({ err: error instanceof Error ? error.message : String(error) }, 'Mercury Cloud WebSocket ping failed');+ socket.terminate();+ return;+ }+ this.send({+ type: 'agent.heartbeat',+ agentId: this.tokenStore.getAgentId(),+ timestamp: new Date().toISOString(),+ });+ }, HEARTBEAT_INTERVAL_MS);+ this.heartbeatInterval.unref?.();+ }++ private stopHeartbeat(): void {+ if (this.heartbeatInterval) {+ clearInterval(this.heartbeatInterval);+ this.heartbeatInterval = null;+ }+ }++ private startTokenCheck(): void {+ this.stopTokenCheck();+ this.tokenCheckInterval = setInterval(() => {+ if (this.authRefreshNeeded || this.tokenStore.isJwtNearExpiry()) void this.tryRefreshAndReconnect();+ }, 60_000);+ this.tokenCheckInterval.unref?.();+ }++ private stopTokenCheck(): void {+ if (this.tokenCheckInterval) {+ clearInterval(this.tokenCheckInterval);+ this.tokenCheckInterval = null;+ }+ }++ private async tryRefreshAndReconnect(): Promise<void> {+ if (+ this.isRefreshing+ || (!this.tokenStore.getRefreshToken() && !this.tokenStore.getAgentApiKey())+ || !this.shouldReconnect+ ) return;+ this.isRefreshing = true;+ const generation = this.lifecycleGeneration;++ try {+ const result = await this.tokenStore.rotate();+ if (!this.shouldReconnect || generation !== this.lifecycleGeneration) return;+ this.authRefreshNeeded = false;++ // Notify the rest of the agent that the tokens changed. The shared store+ // already persisted + notified its listeners (including the provider);+ // this synthetic event keeps the legacy `token.refreshed` handler path+ // in index.ts in sync for any additional wiring.+ const refreshHandler = this.handlers.get('token.refreshed');+ if (refreshHandler) {+ for (const handler of refreshHandler) {+ const message = { type: 'token.refreshed' as WSMessageType, payload: { jwt: result.jwt, refreshToken: result.refreshToken } };+ this.runHandler('token.refreshed', () => handler(message));+ }+ }++ if (!this.isConnected()) {+ this.ws = null;+ await this.connect();+ }+ } catch (err: any) {+ // Automatic background refresh should never spam the interactive TUI.+ // Keep diagnostics in logs, rate-limited, and retry on the next check/call.+ const now = Date.now();+ if (now - this.lastRefreshFailureLogAt > 10 * 60 * 1000) {+ this.lastRefreshFailureLogAt = now;+ logger.warn({ err: err?.message || String(err) }, 'Mercury Cloud background token refresh failed; will retry later');+ }+ if (this.shouldReconnect && !this.isConnected()) this.scheduleReconnect();+ } finally {+ this.isRefreshing = false;+ }+ }++ private scheduleReconnect(): void {+ if (!this.shouldReconnect || this.reconnectTimer) return;+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {+ this.reconnectAttempts = Math.floor(this.maxReconnectAttempts / 2);+ }++ const baseDelay = Math.min(1000 * 2 ** this.reconnectAttempts, 60_000);+ const jitteredDelay = Math.round(baseDelay * (0.5 + Math.random() * 0.5));+ this.reconnectAttempts++;++ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null;+ if (this.shouldReconnect) {+ if (this.authRefreshNeeded) {+ void this.tryRefreshAndReconnect();+ } else {+ void this.connect().catch(() => {});+ }+ }+ }, jitteredDelay);+ if (this.reconnectTimer && typeof this.reconnectTimer.unref === 'function') {+ this.reconnectTimer.unref();+ }+ }++ private runHandler(type: string, handler: () => void | Promise<void>): void {+ try {+ void Promise.resolve(handler()).catch((error) => {+ logger.error({ err: error instanceof Error ? error.message : String(error), type }, 'Mercury Cloud WebSocket handler failed');+ });+ } catch (error) {+ logger.error({ err: error instanceof Error ? error.message : String(error), type }, 'Mercury Cloud WebSocket handler failed');+ }+ }+}diff --git a/src/cloud/endpoints.ts b/src/cloud/endpoints.tsnew file mode 100644index 00000000..a6d7b4d1--- /dev/null+++ b/src/cloud/endpoints.ts@@ -0,0 +1,6 @@+export const MERCURY_CLOUD_DASHBOARD_URL = 'https://cloud.mercuryagent.sh';+export const MERCURY_CLOUD_API_URL = 'https://backend.mercuryagent.sh';+export const MERCURY_CLOUD_WS_URL = 'wss://backend.mercuryagent.sh/ws';++export const LEGACY_SEED_API_URL = 'https://api.mercury.cloud';+export const LEGACY_SEED_WS_URL = 'wss://api.mercury.cloud/ws';diff --git a/src/cloud/pairing-flow.test.ts b/src/cloud/pairing-flow.test.tsnew file mode 100644index 00000000..626a1867--- /dev/null+++ b/src/cloud/pairing-flow.test.ts@@ -0,0 +1,321 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { MercuryConfig } from '../utils/config.js';++const mocks = vi.hoisted(() => ({+ loadConfig: vi.fn(),+ saveConfig: vi.fn(),+ updateConfig: vi.fn(),+ startPairingFlow: vi.fn(),+ pollPairingComplete: vi.fn(),+ refreshToken: vi.fn(),+ redeemAgentApiKey: vi.fn(),+ openUrl: vi.fn(),+ initCloudTokenStore: vi.fn(),+ getCloudTokenStore: vi.fn(),+ clearCloudTokenStore: vi.fn(),+ getDaemonStatus: vi.fn(),+ getForegroundRuntimeStatus: vi.fn(),+ stopDaemon: vi.fn(),+ stopForegroundRuntime: vi.fn(),+ startBackground: vi.fn(),+ isServiceInstalled: vi.fn(),+ isServiceRunning: vi.fn(),+ restartService: vi.fn(),+ stopService: vi.fn(),+ clearCloudRuntimeOnline: vi.fn(),+ isCloudRuntimeOnline: vi.fn(),+ waitForCloudRuntimeOnline: vi.fn(),+}));++vi.mock('../utils/config.js', () => ({+ loadConfig: mocks.loadConfig,+ saveConfig: mocks.saveConfig,+ updateConfig: mocks.updateConfig,+}));+vi.mock('./pairing.js', () => ({+ PairingFailureError: class PairingFailureError extends Error {+ constructor(message: string, public readonly details: Record<string, unknown> = {}) {+ super(message);+ }+ },+ startPairingFlow: mocks.startPairingFlow,+ pollPairingComplete: mocks.pollPairingComplete,+ refreshToken: mocks.refreshToken,+ redeemAgentApiKey: mocks.redeemAgentApiKey,+}));+vi.mock('../utils/open-url.js', () => ({ openUrl: mocks.openUrl }));+vi.mock('./token-store.js', () => ({+ initCloudTokenStore: mocks.initCloudTokenStore,+ getCloudTokenStore: mocks.getCloudTokenStore,+ clearCloudTokenStore: mocks.clearCloudTokenStore,+}));+vi.mock('../cli/daemon.js', () => ({+ getDaemonStatus: mocks.getDaemonStatus,+ getForegroundRuntimeStatus: mocks.getForegroundRuntimeStatus,+ stopDaemon: mocks.stopDaemon,+ stopForegroundRuntime: mocks.stopForegroundRuntime,+ startBackground: mocks.startBackground,+}));+vi.mock('../cli/service.js', () => ({+ isServiceInstalled: mocks.isServiceInstalled,+ isServiceRunning: mocks.isServiceRunning,+ restartService: mocks.restartService,+ stopService: mocks.stopService,+}));+vi.mock('./runtime-status.js', () => ({+ clearCloudRuntimeOnline: mocks.clearCloudRuntimeOnline,+ isCloudRuntimeOnline: mocks.isCloudRuntimeOnline,+ waitForCloudRuntimeOnline: mocks.waitForCloudRuntimeOnline,+}));++import { runCloudConnect, runCloudDisconnect, runCloudLogin, runCloudPairingFlow } from './pairing-flow.js';++function config(): MercuryConfig {+ return {+ cloud: {+ enabled: false,+ apiUrl: 'https://api.example.com',+ wsUrl: 'wss://api.example.com/ws',+ jwt: 'stale-jwt',+ refreshToken: 'stale-refresh',+ agentId: 'agent-1',+ tier: 'free',+ agentApiKey: 'mcapk_old',+ },+ providers: {+ default: 'mercuryCloud',+ mercuryCloud: {+ name: 'mercuryCloud',+ enabled: true,+ apiKey: 'stale-jwt',+ baseUrl: 'https://api.example.com',+ model: 'mercury-flash',+ },+ deepseek: {+ name: 'deepseek',+ enabled: true,+ apiKey: 'local-key',+ baseUrl: 'https://api.deepseek.com',+ model: 'deepseek-chat',+ },+ },+ } as MercuryConfig;+}++beforeEach(() => {+ for (const mock of Object.values(mocks)) mock.mockReset();+ mocks.getDaemonStatus.mockReturnValue({ running: false, pid: null });+ mocks.getForegroundRuntimeStatus.mockReturnValue({ running: false, pid: null });+ mocks.stopForegroundRuntime.mockResolvedValue(true);+ mocks.getCloudTokenStore.mockReturnValue(null);+ mocks.isServiceInstalled.mockReturnValue(false);+ mocks.isServiceRunning.mockReturnValue(false);+ mocks.waitForCloudRuntimeOnline.mockResolvedValue(true);+ mocks.isCloudRuntimeOnline.mockReturnValue(false);+ mocks.updateConfig.mockImplementation((mutator: (value: MercuryConfig) => void) => {+ const value = mocks.loadConfig();+ mutator(value);+ mocks.saveConfig(value);+ return value;+ });+ mocks.openUrl.mockResolvedValue(true);+ vi.spyOn(console, 'log').mockImplementation(() => {});+});++describe('runCloudDisconnect', () => {+ it('stops the daemon first and scrubs stale credentials even when Cloud is marked disabled', async () => {+ const current = config();+ mocks.loadConfig.mockReturnValue(current);+ mocks.getDaemonStatus.mockReturnValue({ running: true, pid: 123 });+ mocks.stopDaemon.mockResolvedValue(true);++ await runCloudDisconnect();++ expect(mocks.stopDaemon).toHaveBeenCalledOnce();+ expect(mocks.saveConfig).toHaveBeenCalledWith(expect.objectContaining({+ cloud: expect.objectContaining({+ enabled: false,+ jwt: '',+ refreshToken: '',+ agentId: '',+ agentApiKey: '',+ }),+ }));+ expect(current.providers.mercuryCloud).toMatchObject({ enabled: false, apiKey: '' });+ expect(current.providers.default).toBe('deepseek');+ expect(mocks.clearCloudTokenStore).toHaveBeenCalledOnce();+ expect(mocks.startBackground).toHaveBeenCalledOnce();+ expect(mocks.stopDaemon.mock.invocationCallOrder[0]).toBeLessThan(mocks.saveConfig.mock.invocationCallOrder[0]);+ });++ it('refuses to clear credentials while a foreground runtime still holds them', async () => {+ const current = config();+ mocks.loadConfig.mockReturnValue(current);+ mocks.getForegroundRuntimeStatus.mockReturnValue({ running: true, pid: 456 });++ await expect(runCloudDisconnect()).rejects.toThrow('running in the foreground');++ expect(mocks.saveConfig).not.toHaveBeenCalled();+ expect(mocks.clearCloudTokenStore).not.toHaveBeenCalled();+ });+});++describe('runCloudPairingFlow', () => {+ it('never carries an old agent API key into a newly paired identity', async () => {+ const current = config();+ mocks.startPairingFlow.mockResolvedValue({ code: 'pair-code', pairingUrl: 'https://pair.example.com' });+ mocks.pollPairingComplete.mockResolvedValue({+ jwt: 'new-jwt',+ refreshToken: 'new-refresh',+ agentId: 'agent-2',+ tier: 'free',+ });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [] }) }));++ const result = await runCloudPairingFlow(current);++ expect(result?.cloudConfig).toMatchObject({ agentId: 'agent-2', agentApiKey: '' });+ vi.unstubAllGlobals();+ });+});++describe('runCloudConnect runtime activation', () => {+ it('starts a detached runtime when valid Cloud credentials exist but Mercury is stopped', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));++ await runCloudConnect();++ expect(mocks.stopDaemon).not.toHaveBeenCalled();+ expect(mocks.startBackground).toHaveBeenCalledOnce();+ expect(mocks.waitForCloudRuntimeOnline).toHaveBeenCalledWith('agent-1', 20_000, 'daemon');+ vi.unstubAllGlobals();+ });++ it('does not start a duplicate daemon beside a foreground-only runtime', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.getForegroundRuntimeStatus.mockReturnValue({ running: true, pid: 456 });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));++ await expect(runCloudConnect()).rejects.toThrow('running only in the foreground');++ expect(mocks.stopForegroundRuntime).not.toHaveBeenCalled();+ expect(mocks.startBackground).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+ });++ it('accepts an already-online foreground Cloud WebSocket without starting a daemon', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.getForegroundRuntimeStatus.mockReturnValue({ running: true, pid: 456 });+ mocks.isCloudRuntimeOnline.mockReturnValue(true);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));++ await runCloudConnect();++ expect(mocks.startBackground).not.toHaveBeenCalled();+ expect(mocks.restartService).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+ });++ it('does not reuse an old foreground WebSocket after credentials rotate', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.refreshToken.mockResolvedValue({ jwt: 'fresh-jwt', refreshToken: 'fresh-refresh' });+ mocks.getForegroundRuntimeStatus.mockReturnValue({ running: true, pid: 456 });+ mocks.isCloudRuntimeOnline.mockReturnValue(true);++ await expect(runCloudLogin()).rejects.toThrow('running only in the foreground');++ expect(mocks.startBackground).not.toHaveBeenCalled();+ });++ it('does not claim online status until the Cloud WebSocket is ready', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.waitForCloudRuntimeOnline.mockResolvedValue(false);+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true }));++ await expect(runCloudConnect()).rejects.toThrow('WebSocket did not become online');+ vi.unstubAllGlobals();+ });++ it('restarts a running runtime after fresh pairing', async () => {+ const current = config();+ mocks.loadConfig.mockReturnValue(current);+ mocks.getDaemonStatus.mockReturnValue({ running: true, pid: 123 });+ mocks.stopDaemon.mockResolvedValue(true);+ mocks.startPairingFlow.mockResolvedValue({ code: 'pair-code', pairingUrl: 'https://pair.example.com' });+ mocks.pollPairingComplete.mockResolvedValue({+ jwt: 'new-jwt',+ refreshToken: 'new-refresh',+ agentId: 'agent-2',+ tier: 'free',+ });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [] }) }));++ await runCloudConnect();++ expect(mocks.stopDaemon).toHaveBeenCalledOnce();+ expect(mocks.startBackground).toHaveBeenCalledOnce();+ expect(mocks.stopDaemon.mock.invocationCallOrder[0]).toBeLessThan(mocks.startBackground.mock.invocationCallOrder[0]);+ expect(mocks.waitForCloudRuntimeOnline).toHaveBeenCalledWith('agent-2', 20_000, 'daemon');+ vi.unstubAllGlobals();+ });++ it('restarts an installed system service instead of spawning a duplicate daemon', async () => {+ const current = config();+ mocks.loadConfig.mockReturnValue(current);+ mocks.isServiceInstalled.mockReturnValue(true);+ mocks.startPairingFlow.mockResolvedValue({ code: 'pair-code', pairingUrl: 'https://pair.example.com' });+ mocks.pollPairingComplete.mockResolvedValue({+ jwt: 'new-jwt',+ refreshToken: 'new-refresh',+ agentId: 'agent-2',+ tier: 'free',+ });+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: [] }) }));++ await runCloudConnect();++ expect(mocks.restartService).toHaveBeenCalledOnce();+ expect(mocks.startBackground).not.toHaveBeenCalled();+ expect(mocks.waitForCloudRuntimeOnline).toHaveBeenCalledWith('agent-2', 20_000, 'daemon');+ vi.unstubAllGlobals();+ });+});++describe('runCloudLogin runtime activation', () => {+ it('restarts Mercury after rotating the single-use refresh token', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.refreshToken.mockResolvedValue({ jwt: 'fresh-jwt', refreshToken: 'fresh-refresh' });+ mocks.getDaemonStatus.mockReturnValue({ running: true, pid: 123 });+ mocks.stopDaemon.mockResolvedValue(true);++ await runCloudLogin();++ expect(mocks.stopDaemon).toHaveBeenCalledOnce();+ expect(mocks.startBackground).toHaveBeenCalledOnce();+ });++ it('reports runtime activation failure without retrying authentication', async () => {+ const current = config();+ current.cloud.enabled = true;+ mocks.loadConfig.mockReturnValue(current);+ mocks.refreshToken.mockResolvedValue({ jwt: 'fresh-jwt', refreshToken: 'fresh-refresh' });+ mocks.getDaemonStatus.mockReturnValue({ running: true, pid: 123 });+ mocks.stopDaemon.mockResolvedValue(false);++ await expect(runCloudLogin()).rejects.toThrow('could not be restarted');+ expect(mocks.refreshToken).toHaveBeenCalledOnce();+ });+});diff --git a/src/cloud/pairing-flow.ts b/src/cloud/pairing-flow.tsnew file mode 100644index 00000000..7385b7cc--- /dev/null+++ b/src/cloud/pairing-flow.ts@@ -0,0 +1,431 @@+import chalk from 'chalk';+import { loadConfig, saveConfig, updateConfig, type MercuryConfig } from '../utils/config.js';+import { openUrl } from '../utils/open-url.js';+import { PairingFailureError, startPairingFlow, pollPairingComplete, refreshToken, redeemAgentApiKey } from './pairing.js';+import { clearCloudTokenStore, getCloudTokenStore, initCloudTokenStore } from './token-store.js';+import type { CloudConfig } from './types.js';+import { MERCURY_CLOUD_API_URL, MERCURY_CLOUD_WS_URL } from './endpoints.js';+import { getDaemonStatus, getForegroundRuntimeStatus, startBackground, stopDaemon } from '../cli/daemon.js';+import { isServiceInstalled, isServiceRunning, restartService, stopService } from '../cli/service.js';+import { clearCloudRuntimeOnline, isCloudRuntimeOnline, waitForCloudRuntimeOnline } from './runtime-status.js';++/**+ * After fresh credentials land in `config.cloud`, sync the shared in-memory+ * token store (if one exists in this process) so the running WS client and+ * provider pick up the new tokens without a restart.+ */+function syncTokenStore(config: MercuryConfig): void {+ if (config.cloud.enabled && config.cloud.jwt && config.cloud.agentId) {+ const existing = getCloudTokenStore();+ if (existing?.matchesIdentity(config.cloud.apiUrl, config.cloud.agentId)) {+ existing.setAgentApiKey(config.cloud.agentApiKey);+ existing.setTokens(config.cloud.jwt, config.cloud.refreshToken);+ } else {+ initCloudTokenStore(config);+ }+ }+}++export async function runCloudPairingFlow(+ config: MercuryConfig+): Promise<{ cloudConfig: CloudConfig; model: string } | null> {+ const apiUrl = config.cloud.apiUrl || MERCURY_CLOUD_API_URL;++ console.log(chalk.dim(' Starting terminal pairing flow...'));+ console.log('');++ const { code, pairingUrl } = await startPairingFlow(apiUrl, undefined);++ console.log(chalk.white(' Open this URL in your browser to register and connect:'));+ console.log(chalk.cyan(` ${pairingUrl}`));+ console.log('');+ console.log(chalk.dim(` Pairing code: ${code}`));++ void tryOpenBrowser(pairingUrl);++ console.log(chalk.dim(' Waiting for approval (timeout in 5 minutes)...'));++ let result;+ try {+ result = await pollPairingComplete(apiUrl, code);+ } catch (err: any) {+ console.log('');+ console.log(chalk.red(` ✗ Pairing failed: ${err.message}`));+ if (err instanceof PairingFailureError && err.details.code === 'AGENT_LIMIT_REACHED') {+ const nextTier = err.details.nextTier ? err.details.nextTier.charAt(0).toUpperCase() + err.details.nextTier.slice(1) : null;+ if (typeof err.details.used === 'number' && typeof err.details.limit === 'number') {+ console.log(chalk.yellow(` Agent capacity: ${err.details.used} of ${err.details.limit} slots used`));+ }+ if (nextTier && err.details.upgradeUrl) {+ console.log(chalk.white(` Upgrade to ${nextTier} to connect another agent:`));+ console.log(chalk.cyan(` ${err.details.upgradeUrl}`));+ console.log(chalk.dim(' After upgrading, run `mercury cloud connect` again.'));+ } else {+ console.log(chalk.white(' Remove an existing agent from Mercury Cloud, then run `mercury cloud connect` again.'));+ }+ }+ console.log('');+ if (!(err instanceof PairingFailureError && err.details.code === 'AGENT_LIMIT_REACHED')) {+ console.log(chalk.dim(' If the browser did not open automatically, copy this URL:'));+ console.log(chalk.cyan(` ${pairingUrl}`));+ }+ return null;+ }++ const cloudConfig: CloudConfig = {+ enabled: true,+ apiUrl,+ wsUrl: config.cloud.wsUrl || MERCURY_CLOUD_WS_URL,+ jwt: result.jwt,+ refreshToken: result.refreshToken,+ agentId: result.agentId,+ tier: result.tier || 'free',+ agentApiKey: result.apiKey || '',+ };++ let model = 'mercury-flash';+ try {+ const res = await fetch(`${apiUrl}/v1/models`, {+ headers: { Authorization: `Bearer ${result.jwt}` },+ });+ if (res.ok) {+ const data = (await res.json()) as { data?: Array<{ id: string; label: string; discount_percent?: number }> };+ const models = data.data;+ if (models && models.length > 0) {+ console.log(chalk.dim(' Available models:'));+ for (let i = 0; i < models.length; i++) {+ const discount = models[i].discount_percent;+ const discountTag = discount && discount > 0 ? chalk.green(` (${discount}% off input)`) : '';+ console.log(chalk.white(` ${i + 1}. ${models[i].label} (${models[i].id})`) + discountTag);+ }+ console.log('');+ const choice = await import('readline').then(async (rl) => {+ const r = rl.createInterface({ input: process.stdin, output: process.stdout });+ return new Promise<string>((resolve) => {+ r.question(chalk.white(` Choose a model [1-${models.length}, Enter for 1]: `), (ans) => {+ r.close();+ resolve(ans || '1');+ });+ });+ });+ const idx = parseInt(choice, 10) - 1;+ if (idx >= 0 && idx < models.length) {+ model = models[idx].id;+ }+ }+ }+ } catch {+ }++ return { cloudConfig, model };+}++export async function runCloudConnect(): Promise<void> {+ const config = loadConfig();++ if (config.cloud.enabled && config.cloud.jwt) {+ // Validate the token is actually usable — don't just trust local config+ const valid = await validateCloudConnection(config);++ if (valid) {+ console.log(chalk.green(' ✓ Mercury Cloud is already connected.'));+ console.log(chalk.dim(` Agent ID: ${config.cloud.agentId}`));+ console.log(chalk.dim(` Tier: ${config.cloud.tier || 'free'}`));+ console.log(chalk.dim(` API URL: ${config.cloud.apiUrl}`));+ // Ensure a background daemon is running so the WebSocket stays alive+ // even after the user exits the foreground TUI.+ await activateCloudRuntime(config.cloud.agentId, false);+ return;+ }++ // Token is expired/invalid — try to refresh+ if (config.cloud.refreshToken) {+ console.log(chalk.yellow(' ⚠ Mercury Cloud token expired. Refreshing...'));+ let refreshed = false;+ try {+ const result = await refreshToken(config.cloud.apiUrl, config.cloud.refreshToken);+ config.cloud.jwt = result.jwt;+ config.cloud.refreshToken = result.refreshToken;+ config.providers.mercuryCloud.apiKey = result.jwt;+ saveConfig(config);+ syncTokenStore(config);++ // Re-validate with the fresh token+ const validNow = await validateCloudConnection(config);+ if (validNow) {+ console.log(chalk.green(' ✓ Mercury Cloud token refreshed successfully.'));+ console.log(chalk.dim(` Agent ID: ${config.cloud.agentId}`));+ console.log(chalk.dim(` API URL: ${config.cloud.apiUrl}`));+ refreshed = true;+ }+ } catch (err: any) {+ console.log(chalk.red(` ✗ Token refresh failed: ${err.message}`));+ }+ if (refreshed) {+ // Token refreshed — restart daemon so it picks up the new token.+ await activateCloudRuntime(config.cloud.agentId, true);+ return;+ }+ }++ // Refresh token is dead — try redeeming the long-lived agent API key+ // before forcing a full browser re-pair. This is the self-recovery path+ // that keeps remotely-deployed agents online without manual intervention.+ if (config.cloud.agentApiKey) {+ console.log(chalk.yellow(' ⚠ Trying agent API key recovery...'));+ let recovered = false;+ try {+ const result = await redeemAgentApiKey(config.cloud.apiUrl, config.cloud.agentApiKey);+ if (!result.agentId || result.agentId !== config.cloud.agentId) {+ throw new Error('Agent API key identity mismatch; browser re-pairing is required');+ }+ config.cloud.jwt = result.jwt;+ config.cloud.refreshToken = result.refreshToken;+ config.providers.mercuryCloud.apiKey = result.jwt;+ saveConfig(config);+ syncTokenStore(config);+ const validNow = await validateCloudConnection(config);+ if (validNow) {+ console.log(chalk.green(' ✓ Recovered via agent API key.'));+ console.log(chalk.dim(` Agent ID: ${config.cloud.agentId}`));+ console.log(chalk.dim(` API URL: ${config.cloud.apiUrl}`));+ recovered = true;+ }+ } catch (err: any) {+ console.log(chalk.red(` ✗ Agent API key recovery failed: ${err.message}`));+ }+ if (recovered) {+ // Recovered — restart daemon so it picks up the new token.+ await activateCloudRuntime(config.cloud.agentId, true);+ return;+ }+ }++ // Refresh + agent key both failed — re-pair+ console.log(chalk.yellow(' ⚠ Session expired. Starting re-pairing flow...'));+ config.cloud.enabled = false;+ config.cloud.jwt = '';+ config.cloud.refreshToken = '';+ }++ const result = await runCloudPairingFlow(config);+ if (!result) {+ console.log(chalk.red(' ✗ Pairing failed. See error above.'));+ return;+ }++ const previousDefault = config.providers.default;+ const pairedConfig = updateConfig((latest) => {+ latest.cloud = result.cloudConfig;+ latest.providers.mercuryCloud.apiKey = result.cloudConfig.jwt;+ latest.providers.mercuryCloud.model = result.model;+ latest.providers.mercuryCloud.enabled = true;+ latest.providers.default = 'mercuryCloud';+ });+ if (previousDefault !== 'mercuryCloud') {+ console.log(chalk.dim(` Switching default provider to Mercury Cloud (was ${previousDefault})`));+ }+ syncTokenStore(pairedConfig);++ console.log(chalk.green(' ✓ Mercury Cloud connected!'));+ console.log(chalk.dim(` Agent ID: ${result.cloudConfig.agentId}`));+ console.log(chalk.dim(` Tier: ${result.cloudConfig.tier}`));+ console.log(chalk.dim(` Model: ${result.model}`));+ console.log('');+ // Start a background daemon so the WebSocket stays alive even after the+ // user exits the foreground TUI. This is the original behavior — the daemon+ // handles failovers, message queuing, and keeps the agent online on the+ // cloud dashboard.+ await activateCloudRuntime(result.cloudConfig.agentId, true);+}++export async function runCloudDisconnect(): Promise<void> {+ const daemonWasRunning = getDaemonStatus().running;+ const foregroundWasRunning = getForegroundRuntimeStatus().running;+ const serviceWasRunning = isServiceRunning();+ const runtimeWasRunning = daemonWasRunning || foregroundWasRunning || serviceWasRunning;+ if (foregroundWasRunning) {+ throw new Error('Mercury is running in the foreground. Stop that session before disconnecting Cloud so in-memory credentials cannot remain active');+ }+ if (daemonWasRunning) {+ console.log(chalk.dim(' Stopping the running agent before clearing Cloud credentials...'));+ const stopped = await stopDaemon();+ if (!stopped) {+ throw new Error('Could not stop the running Mercury daemon; Cloud credentials were not changed');+ }+ } else if (serviceWasRunning && !stopService()) {+ throw new Error('Could not stop the Mercury system service; Cloud credentials were not changed');+ }+ clearCloudRuntimeOnline();++ let config = loadConfig();+ const hadCloudState = config.cloud.enabled+ || !!config.cloud.jwt+ || !!config.cloud.refreshToken+ || !!config.cloud.agentId+ || !!config.cloud.agentApiKey+ || config.providers.mercuryCloud.enabled+ || !!config.providers.mercuryCloud.apiKey;++ config = updateConfig((latest) => {+ latest.cloud.enabled = false;+ latest.cloud.jwt = '';+ latest.cloud.refreshToken = '';+ latest.cloud.agentId = '';+ latest.cloud.agentApiKey = '';+ latest.providers.mercuryCloud.enabled = false;+ latest.providers.mercuryCloud.apiKey = '';++ if (latest.providers.default !== 'mercuryCloud') return;+ const configured = Object.values(latest.providers)+ .filter((p): p is import('../utils/config.js').ProviderConfig =>+ typeof p === 'object' && p.name !== 'mercuryCloud' && isProviderConfiguredSafe(p)+ );+ if (configured.length > 0) {+ latest.providers.default = configured[0].name as import('../utils/config.js').ProviderName;+ console.log(chalk.dim(` Default provider switched to ${configured[0].name}`));+ } else {+ console.log(chalk.yellow(' No other providers configured. Run `mercury setup` to configure offline providers.'));+ }+ });+ clearCloudTokenStore();+ console.log(hadCloudState+ ? chalk.green(' ✓ Local Mercury Cloud credentials cleared.')+ : chalk.yellow(' Mercury Cloud was already disconnected; stale credentials were scrubbed.'));+ console.log(chalk.dim(' The cloud agent remains registered remotely. Delete it in the dashboard to revoke server-side credentials.'));++ const hasOfflineProvider = Object.values(config.providers).some((provider) =>+ typeof provider === 'object' && provider.name !== 'mercuryCloud' && isProviderConfiguredSafe(provider)+ );+ if (runtimeWasRunning && hasOfflineProvider) {+ console.log(chalk.dim(' Restarting Mercury with the configured offline provider...'));+ startManagedRuntime();+ } else if (runtimeWasRunning) {+ console.log(chalk.yellow(' Mercury remains stopped because no offline provider is configured.'));+ } else {+ console.log(chalk.dim(' Stop any foreground Mercury process to discard its in-memory Cloud session.'));+ }+}++export async function runCloudStatus(): Promise<void> {+ const config = loadConfig();++ if (!config.cloud.enabled) {+ console.log(chalk.yellow(' Mercury Cloud: not connected (offline/BYOK mode)'));+ return;+ }++ console.log(chalk.green(' Mercury Cloud: connected'));+ console.log(chalk.dim(` Agent ID: ${config.cloud.agentId}`));+ console.log(chalk.dim(` Tier: ${config.cloud.tier}`));+ console.log(chalk.dim(` API URL: ${config.cloud.apiUrl}`));+ console.log(chalk.dim(` WS URL: ${config.cloud.wsUrl}`));+ console.log(chalk.dim(` Model: ${config.providers.mercuryCloud.model}`));+ console.log(chalk.dim(` JWT: ${config.cloud.jwt.slice(0, 12)}...`));++ try {+ const res = await fetch(`${config.cloud.apiUrl}/v1/usage`, {+ headers: { Authorization: `Bearer ${config.cloud.jwt}` },+ });+ if (res.ok) {+ const usage = await res.json() as { todayTokens: number; credits: number };+ console.log(chalk.dim(` Today tokens: ${usage.todayTokens}`));+ console.log(chalk.dim(` Credits: ${usage.credits}`));+ }+ } catch {+ }+}++export async function runCloudLogin(): Promise<void> {+ const config = loadConfig();++ if (!config.cloud.refreshToken) {+ console.log(chalk.yellow(' No refresh token found. Run `mercury cloud connect` to pair.'));+ return;+ }++ try {+ const { refreshToken: doRefresh } = await import('./pairing.js');+ const result = await doRefresh(config.cloud.apiUrl, config.cloud.refreshToken);+ config.cloud.jwt = result.jwt;+ config.cloud.refreshToken = result.refreshToken;+ config.providers.mercuryCloud.apiKey = result.jwt;+ saveConfig(config);+ syncTokenStore(config);+ console.log(chalk.green(' ✓ Token refreshed successfully.'));+ } catch (err: any) {+ console.log(chalk.red(` ✗ Token refresh failed: ${err.message || err}`));+ console.log(chalk.yellow(' Run `mercury cloud connect` to re-pair.'));+ return;+ }+ // Restart daemon so it picks up the new token.+ await activateCloudRuntime(config.cloud.agentId, true);+}++async function activateCloudRuntime(agentId: string, credentialsChanged: boolean): Promise<void> {+ const foreground = getForegroundRuntimeStatus();+ const daemon = getDaemonStatus();+ const serviceRunning = isServiceRunning();+ const hadManagedRuntime = daemon.running || serviceRunning;++ if (foreground.running) {+ if (!credentialsChanged && isCloudRuntimeOnline(agentId, 'foreground')) {+ console.log(chalk.green(` Mercury Cloud WebSocket is already online in foreground PID ${foreground.pid}.`));+ return;+ }+ if (!hadManagedRuntime) {+ throw new Error('Cloud credentials were saved, but Mercury is running only in the foreground. Restart that foreground session to activate its Cloud WebSocket');+ }+ console.log(chalk.yellow(` Foreground Mercury (PID: ${foreground.pid}) keeps its local session while the managed Cloud runtime restarts.`));+ }+ clearCloudRuntimeOnline();++ if (daemon.running) {+ console.log(chalk.dim(` Restarting Mercury (PID: ${daemon.pid}) to activate Cloud...`));+ if (!await stopDaemon()) {+ throw new Error('Cloud credentials were saved, but the running Mercury process could not be restarted');+ }+ }+ startManagedRuntime();+ if (!await waitForCloudRuntimeOnline(agentId, 20_000, 'daemon')) {+ throw new Error('Mercury restarted, but its Cloud WebSocket did not become online within 20 seconds');+ }+ console.log(chalk.green(' ✓ Mercury daemon restarted with Cloud credentials.'));+}++function startManagedRuntime(): void {+ if (isServiceInstalled()) {+ restartService();+ } else {+ startBackground();+ }+}++function isProviderConfiguredSafe(p: import('../utils/config.js').ProviderConfig): boolean {+ if (!p.enabled) return false;+ if (p.name === 'ollamaLocal') return p.baseUrl.length > 0 && p.model.length > 0;+ if (p.name === 'ollamaCloud') return p.apiKey.length > 0 && p.baseUrl.length > 0;+ if (p.name === 'openaiCompat') return p.baseUrl.length > 0 && p.model.length > 0;+ if (p.name === 'chatgptWeb' || p.name === 'githubCopilot') return p.model.length > 0;+ return p.apiKey.length > 0;+}++async function tryOpenBrowser(url: string): Promise<void> {+ if (await openUrl(url)) {+ console.log(chalk.green(' ✓ Opened in browser.'));+ } else {+ console.log(chalk.dim(' Could not open browser automatically. Please open the URL manually.'));+ }+}++async function validateCloudConnection(config: MercuryConfig): Promise<boolean> {+ try {+ const res = await fetch(`${config.cloud.apiUrl}/v1/agents`, {+ headers: { Authorization: `Bearer ${config.cloud.jwt}` },+ signal: AbortSignal.timeout(10_000),+ });+ return res.ok;+ } catch {+ return false;+ }+}diff --git a/src/cloud/pairing.test.ts b/src/cloud/pairing.test.tsnew file mode 100644index 00000000..6be98956--- /dev/null+++ b/src/cloud/pairing.test.ts@@ -0,0 +1,85 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { PairingFailureError, pollPairingComplete, refreshToken } from './pairing.js';++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('refreshToken', () => {+ it('shares a single-use token rotation across concurrent consumers', async () => {+ const result = { jwt: 'new-jwt', refreshToken: 'new-refresh' };+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: async () => result,+ });+ vi.stubGlobal('fetch', fetchMock);++ const token = `old-refresh-${Date.now()}`;+ const [first, second] = await Promise.all([+ refreshToken('https://api.example.com', token),+ refreshToken('https://api.example.com', token),+ ]);++ expect(first).toEqual(result);+ expect(second).toEqual(result);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('does not cache failed refresh attempts', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce({ ok: false, status: 503 })+ .mockResolvedValueOnce({ ok: true, json: async () => ({ jwt: 'jwt', refreshToken: 'next' }) });+ vi.stubGlobal('fetch', fetchMock);++ const token = `retry-refresh-${Date.now()}`;+ await expect(refreshToken('https://api.example.com', token)).rejects.toThrow('503');+ await expect(refreshToken('https://api.example.com', token)).resolves.toEqual({ jwt: 'jwt', refreshToken: 'next' });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});++describe('pollPairingComplete', () => {+ it('rejects a failed response even when it also contains credentials', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({+ status: 200,+ json: async () => ({+ status: 'failed',+ error: 'Free tier allows one agent',+ code: 'AGENT_LIMIT_REACHED',+ jwt: 'must-not-be-used',+ refreshToken: 'must-not-be-used',+ agentId: 'hidden-agent',+ }),+ }));++ await expect(pollPairingComplete('https://api.example.com', 'code', 100, 0)).rejects.toMatchObject({+ name: 'PairingFailureError',+ details: expect.objectContaining({ code: 'AGENT_LIMIT_REACHED' }),+ });+ });++ it('preserves a structured capacity failure returned as HTTP 409', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({+ status: 409,+ json: async () => ({+ error: 'Agent limit reached',+ code: 'AGENT_LIMIT_REACHED',+ tier: 'free',+ used: 1,+ limit: 1,+ }),+ }));++ try {+ await pollPairingComplete('https://api.example.com', 'code', 100, 0);+ throw new Error('Expected pairing to fail');+ } catch (error) {+ expect(error).toBeInstanceOf(PairingFailureError);+ expect((error as PairingFailureError).details).toMatchObject({+ code: 'AGENT_LIMIT_REACHED',+ used: 1,+ limit: 1,+ });+ }+ });+});diff --git a/src/cloud/pairing.ts b/src/cloud/pairing.tsnew file mode 100644index 00000000..fcb616be--- /dev/null+++ b/src/cloud/pairing.ts@@ -0,0 +1,207 @@+import type { PairingResult, TokenRefreshResult } from './types.js';+import os from 'node:os';+import { createHash } from 'node:crypto';++let cachedMachineId: string | null = null;++export type PairingFailureDetails = {+ code?: string;+ tier?: string;+ used?: number;+ limit?: number;+ nextTier?: string | null;+ upgradeUrl?: string;+};++export class PairingFailureError extends Error {+ constructor(message: string, public readonly details: PairingFailureDetails = {}) {+ super(message);+ this.name = 'PairingFailureError';+ }+}++export function getMachineId(): string {+ if (cachedMachineId) return cachedMachineId;++ const raw = [+ os.hostname(),+ os.platform(),+ os.arch(),+ os.userInfo().username,+ ].join('|');++ cachedMachineId = createHash('sha256').update(raw).digest('hex').slice(0, 32);+ return cachedMachineId;+}++export function getHostname(): string {+ return os.hostname();+}++export async function startPairingFlow(+ apiUrl: string,+ email?: string+): Promise<{ code: string; pairingUrl: string }> {+ const machineId = getMachineId();+ const host = getHostname();++ const res = await fetch(`${apiUrl}/v1/auth/terminal/pair`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ email, machineId, hostname: host }),+ });++ if (!res.ok) {+ throw new Error(`Pairing request failed: ${res.status} ${res.statusText}`);+ }++ return (await res.json()) as { code: string; pairingUrl: string };+}++export async function pollPairingComplete(+ apiUrl: string,+ code: string,+ timeoutMs: number = 300_000,+ intervalMs: number = 1_500+): Promise<PairingResult> {+ const deadline = Date.now() + timeoutMs;+ let consecutiveErrors = 0;++ while (Date.now() < deadline) {+ try {+ const res = await fetch(`${apiUrl}/v1/auth/terminal/complete`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ code }),+ });++ if (res.status === 200) {+ consecutiveErrors = 0;+ const data = await res.json() as PairingResult & PairingFailureDetails & { status?: string; error?: string };++ // Fail closed if the server reports a terminal failure, even if a+ // malformed response also contains credentials.+ if (data.status === 'failed') {+ throw new PairingFailureError(data.error || 'Pairing was rejected', data);+ }++ // Success — has tokens and agentId+ if (data.jwt && data.refreshToken && data.agentId) {+ return data;+ }++ // 200 with pending/approved/completing — keep polling+ await sleep(intervalMs);+ continue;+ }++ if (res.status === 202) {+ // Pending — keep polling+ consecutiveErrors = 0;+ await sleep(intervalMs);+ continue;+ }++ if (res.status === 404) {+ throw new Error('Pairing code not found or expired. Run `mercury cloud connect` again.');+ }++ if (res.status === 403 || res.status === 409) {+ const data = await res.json().catch(() => ({})) as PairingFailureDetails & { error?: string; message?: string };+ throw new PairingFailureError(+ data.error || data.message || `Pairing was rejected (${res.status})`,+ data,+ );+ }++ // Non-404 error (401, 403, 500, etc.) — retry a few times, then fail+ consecutiveErrors++;+ if (consecutiveErrors >= 5) {+ const errBody = await res.json().catch(() => ({}));+ const msg = (errBody as any)?.message || `Server returned ${res.status}`;+ throw new Error(`Pairing failed after repeated errors: ${msg}`);+ }+ } catch (err) {+ // Re-throw explicit errors (not found, failed, etc.)+ if (err instanceof PairingFailureError || err instanceof Error && (err.message.includes('not found') || err.message.includes('Pairing failed'))) {+ throw err;+ }++ // Network errors — retry with backoff+ consecutiveErrors++;+ if (consecutiveErrors >= 10) {+ throw new Error(`Pairing failed: network errors — ${(err as Error).message}`);+ }+ }++ await sleep(intervalMs);+ }++ throw new Error('Pairing timed out — the browser approval was not completed in time. Run `mercury cloud connect` again.');+}++const REFRESH_RESULT_REUSE_MS = 5 * 60 * 1000;+const refreshRequests = new Map<string, { promise: Promise<TokenRefreshResult>; reusableUntil: number }>();++export function refreshToken(+ apiUrl: string,+ currentRefreshToken: string+): Promise<TokenRefreshResult> {+ const now = Date.now();+ for (const [key, entry] of refreshRequests) {+ if (entry.reusableUntil <= now) refreshRequests.delete(key);+ }++ // Refresh tokens are single-use. Every cloud consumer in this process must+ // share the same rotation result rather than racing the auth endpoint.+ const key = `${apiUrl}\0${currentRefreshToken}`;+ const existing = refreshRequests.get(key);+ if (existing) return existing.promise;++ const entry = {+ promise: performTokenRefresh(apiUrl, currentRefreshToken),+ reusableUntil: Number.POSITIVE_INFINITY,+ };+ refreshRequests.set(key, entry);+ void entry.promise.then(+ () => { entry.reusableUntil = Date.now() + REFRESH_RESULT_REUSE_MS; },+ () => { refreshRequests.delete(key); },+ );+ return entry.promise;+}++async function performTokenRefresh(apiUrl: string, currentRefreshToken: string): Promise<TokenRefreshResult> {+ const res = await fetch(`${apiUrl}/v1/auth/refresh`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ refreshToken: currentRefreshToken }),+ });++ if (!res.ok) throw new Error(`Token refresh failed: ${res.status}`);+ return (await res.json()) as TokenRefreshResult;+}++/**+ * Redeem a long-lived agent API key for a fresh JWT + refresh-token pair.+ * This is the self-recovery path used when the refresh token has expired or+ * been consumed: the agent API key never expires (only rotation via re-pair+ * or agent deletion invalidates it), so a paired agent can always come back+ * online without a browser re-pair.+ */+export async function redeemAgentApiKey(+ apiUrl: string,+ agentApiKey: string+): Promise<TokenRefreshResult & { agentId: string }> {+ const res = await fetch(`${apiUrl}/v1/auth/agent/redeem`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ apiKey: agentApiKey }),+ });++ if (!res.ok) throw new Error(`Agent key redeem failed: ${res.status}`);+ return (await res.json()) as TokenRefreshResult & { agentId: string };+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}diff --git a/src/cloud/pool-search.ts b/src/cloud/pool-search.tsnew file mode 100644index 00000000..cebd404a--- /dev/null+++ b/src/cloud/pool-search.ts@@ -0,0 +1,229 @@+import { join } from 'node:path';+import { existsSync, mkdirSync } from 'node:fs';+import { createRequire } from 'node:module';+import { getMemoryDir } from '../utils/config.js';+import { logger } from '../utils/logger.js';+import { refreshToken } from './pairing.js';++type BetterSqlite3Database = import('better-sqlite3').Database;+const require = createRequire(import.meta.url);+function loadDatabase(): typeof import('better-sqlite3') {+ return require('better-sqlite3');+}++/**+ * Cloud shared-pool search client for the agent.+ *+ * After the local second-brain retrieval, the agent calls `searchPool()` to+ * fetch additional context from the user's cloud SharedMemoryPool. Results are+ * cached in a small SQLite DB for 5 minutes per (normalized) query — chat+ * turns frequently repeat the same query shape, so this kills most of the+ * per-turn embedding + network cost.+ *+ * Fail-open: any error (network, auth, timeout) returns an empty array so the+ * agent proceeds with local-only context. A slow cloud never blocks the chat+ * turn — the request has an 800ms timeout.+ */++const CACHE_TTL_MS = 5 * 60 * 1000;+const REQUEST_TIMEOUT_MS = 800;+const MAX_CACHE_ROWS = 500;++export interface PoolSearchHit {+ id: string;+ type: string;+ categories: string[];+ summary: string;+ detail: string | null;+ confidence: number;+ importance: number;+ durability: number;+ evidenceCount: number;+ sourceAgentIds: string[];+ agentMemoryUpdatedAt: number;+ score: number;+ source: 'semantic' | 'fts';+}++export interface PoolSearchOptions {+ limit?: number;+ types?: string[];+ categories?: string[];+}++interface CacheRow {+ query_hash: string;+ query: string;+ results_json: string;+ fetched_at: number;+}++let cacheDb: BetterSqlite3Database | null = null;++function getCacheDb(): BetterSqlite3Database {+ if (cacheDb) return cacheDb;+ const dir = getMemoryDir();+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+ const dbPath = join(dir, 'pool-search-cache.db');+ cacheDb = loadDatabase()(dbPath);+ cacheDb.exec(`+ CREATE TABLE IF NOT EXISTS pool_search_cache (+ query_hash TEXT PRIMARY KEY,+ query TEXT NOT NULL,+ results_json TEXT NOT NULL,+ fetched_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_pool_search_fetched_at ON pool_search_cache(fetched_at);+ `);+ return cacheDb;+}++function hashQuery(query: string): string {+ // Simple non-crypto hash — enough for a 5-min cache key.+ let h = 0;+ for (let i = 0; i < query.length; i++) {+ h = (Math.imul(31, h) + query.charCodeAt(i)) | 0;+ }+ return (h >>> 0).toString(16);+}++function readCache(queryHash: string): PoolSearchHit[] | null {+ const db = getCacheDb();+ const row = db.prepare('SELECT results_json, fetched_at FROM pool_search_cache WHERE query_hash = ?').get(queryHash) as CacheRow | undefined;+ if (!row) return null;+ if (Date.now() - row.fetched_at > CACHE_TTL_MS) return null;+ try {+ return JSON.parse(row.results_json) as PoolSearchHit[];+ } catch {+ return null;+ }+}++function writeCache(queryHash: string, query: string, results: PoolSearchHit[]): void {+ const db = getCacheDb();+ const now = Date.now();+ db.prepare('INSERT OR REPLACE INTO pool_search_cache (query_hash, query, results_json, fetched_at) VALUES (?, ?, ?, ?)').run(+ queryHash,+ query,+ JSON.stringify(results),+ now,+ );+ // Bounded cache — drop oldest rows past MAX_CACHE_ROWS.+ db.exec(`DELETE FROM pool_search_cache WHERE query_hash NOT IN (+ SELECT query_hash FROM pool_search_cache ORDER BY fetched_at DESC LIMIT ${MAX_CACHE_ROWS}+ )`);+}++/**+ * Search the user's cloud SharedMemoryPool. Returns ranked hits or an empty+ * array on any failure (network, auth, timeout). Refreshes the JWT once if the+ * first attempt comes back 401.+ */+export async function searchPool(+ apiUrl: string,+ jwt: string,+ refreshTokenValue: string,+ query: string,+ opts: PoolSearchOptions = {},+ onTokenRefresh?: (jwt: string, refreshToken: string) => void,+): Promise<PoolSearchHit[]> {+ const trimmed = query.trim();+ if (!trimmed) return [];++ const queryHash = hashQuery(trimmed.toLowerCase());+ const cached = readCache(queryHash);+ if (cached) {+ logger.debug({ query: trimmed.slice(0, 60) }, 'pool search cache hit');+ return cached;+ }++ const body = JSON.stringify({+ query: trimmed,+ limit: opts.limit ?? 10,+ types: opts.types,+ categories: opts.categories,+ });++ const doFetch = async (token: string): Promise<Response> => {+ return fetch(`${apiUrl}/v1/ck-memory/search`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'Content-Type': 'application/json',+ },+ body,+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ };++ let res = await doFetch(jwt).catch(() => null);+ if (res && res.status === 401 && refreshTokenValue) {+ try {+ const refreshed = await refreshToken(apiUrl, refreshTokenValue);+ if (onTokenRefresh) onTokenRefresh(refreshed.jwt, refreshed.refreshToken);+ res = await doFetch(refreshed.jwt).catch(() => null);+ } catch {+ return [];+ }+ }++ if (!res || !res.ok) return [];+ let hits: PoolSearchHit[];+ try {+ hits = (await res.json()) as PoolSearchHit[];+ } catch {+ return [];+ }+ if (!Array.isArray(hits)) return [];++ writeCache(queryHash, trimmed, hits);+ return hits;+}++/**+ * Build the prompt block for pool hits, mirroring the second-brain block+ * shape used in `agent.ts`. Returns an empty string if no hits.+ */+export function formatPoolContextBlock(hits: PoolSearchHit[], maxChars: number = 1500): string {+ if (hits.length === 0) return '';+ const lines: string[] = [];+ let total = 0;+ for (const h of hits) {+ const line = `- [${h.type}] ${h.summary}${h.detail ? ` — ${h.detail}` : ''}`;+ if (total + line.length + 1 > maxChars) break;+ lines.push(line);+ total += line.length + 1;+ }+ if (lines.length === 0) return '';+ return `[Shared Pool — auto-retrieved context]\n${lines.join('\n')}\n[End auto-retrieved context]`;+}++/**+ * Drop pool hits whose summary is near-duplicate of a local hit. Uses the+ * same overlap rule the agent's memory-engine uses (≥ 0.8 token overlap) so+ * we don't double-inject the same fact the second brain already surfaced.+ */+export function dedupeAgainstLocal(+ pool: PoolSearchHit[],+ localSummaries: string[],+ threshold: number = 0.8,+): PoolSearchHit[] {+ if (localSummaries.length === 0) return pool;+ const normalize = (s: string): Set<string> => {+ const terms = s.toLowerCase().split(/[^a-z0-9]+/i).filter((t) => t.length >= 3);+ return new Set(terms);+ };+ const localSets = localSummaries.map(normalize);+ return pool.filter((h) => {+ const poolSet = normalize(h.summary);+ if (poolSet.size === 0) return true;+ for (const localSet of localSets) {+ if (localSet.size === 0) continue;+ let overlap = 0;+ for (const t of poolSet) if (localSet.has(t)) overlap++;+ const score = overlap / Math.max(poolSet.size, localSet.size);+ if (score >= threshold) return false;+ }+ return true;+ });+}\ No newline at end of filediff --git a/src/cloud/runtime-status.ts b/src/cloud/runtime-status.tsnew file mode 100644index 00000000..9d69be61--- /dev/null+++ b/src/cloud/runtime-status.ts@@ -0,0 +1,51 @@+import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';++function statusPath(): string {+ return join(getMercuryHome(), 'cloud-online.json');+}++export function markCloudRuntimeOnline(agentId: string, mode: 'daemon' | 'foreground'): void {+ writeFileSync(statusPath(), JSON.stringify({ agentId, mode, pid: process.pid, connectedAt: Date.now() }), {+ encoding: 'utf-8',+ mode: 0o600,+ });+}++export function clearCloudRuntimeOnline(ownerPid?: number): void {+ if (ownerPid !== undefined && existsSync(statusPath())) {+ try {+ const status = JSON.parse(readFileSync(statusPath(), 'utf-8')) as { pid?: number };+ if (status.pid !== ownerPid) return;+ } catch {+ return;+ }+ }+ try { unlinkSync(statusPath()); } catch {}+}++export function isCloudRuntimeOnline(agentId: string, mode?: 'daemon' | 'foreground'): boolean {+ if (!existsSync(statusPath())) return false;+ try {+ const status = JSON.parse(readFileSync(statusPath(), 'utf-8')) as { agentId?: string; mode?: string; pid?: number };+ if (status.agentId !== agentId || !status.pid || (mode && status.mode !== mode)) return false;+ process.kill(status.pid, 0);+ return true;+ } catch {+ return false;+ }+}++export async function waitForCloudRuntimeOnline(+ agentId: string,+ timeoutMs = 20_000,+ mode?: 'daemon' | 'foreground',+): Promise<boolean> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (isCloudRuntimeOnline(agentId, mode)) return true;+ await new Promise(resolve => setTimeout(resolve, 200));+ }+ return false;+}diff --git a/src/cloud/token-store.test.ts b/src/cloud/token-store.test.tsnew file mode 100644index 00000000..31cac186--- /dev/null+++ b/src/cloud/token-store.test.ts@@ -0,0 +1,117 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ loadConfig: vi.fn(),+ saveConfig: vi.fn(),+ updateConfig: vi.fn(),+ refreshToken: vi.fn(),+ redeemAgentApiKey: vi.fn(),+}));++vi.mock('../utils/config.js', () => ({+ loadConfig: mocks.loadConfig,+ saveConfig: mocks.saveConfig,+ updateConfig: mocks.updateConfig,+}));+vi.mock('./pairing.js', () => ({+ refreshToken: mocks.refreshToken,+ redeemAgentApiKey: mocks.redeemAgentApiKey,+}));++import { CloudTokenStore } from './token-store.js';+import type { MercuryConfig } from '../utils/config.js';++function config(jwt = 'old-jwt', refreshToken = 'old-refresh'): MercuryConfig {+ return {+ cloud: { enabled: true, apiUrl: 'https://api.example.com', wsUrl: 'wss://api.example.com/ws', jwt, refreshToken, agentId: 'agent-1', tier: 'free', agentApiKey: 'mcapk_agent_1' },+ providers: { mercuryCloud: { name: 'mercuryCloud', enabled: true, apiKey: jwt, baseUrl: 'https://api.example.com', model: 'mercury-flash' } },+ } as MercuryConfig;+}++beforeEach(() => {+ mocks.loadConfig.mockReset();+ mocks.saveConfig.mockReset();+ mocks.updateConfig.mockReset();+ mocks.updateConfig.mockImplementation((mutator: (value: MercuryConfig) => void) => {+ const value = mocks.loadConfig();+ mutator(value);+ mocks.saveConfig(value);+ return value;+ });+ mocks.refreshToken.mockReset();+ mocks.redeemAgentApiKey.mockReset();+});++describe('CloudTokenStore', () => {+ it('updates the live config and persists every single-use rotation', async () => {+ const live = config();+ mocks.loadConfig.mockReturnValue(config());+ mocks.refreshToken.mockResolvedValue({ jwt: 'new-jwt', refreshToken: 'new-refresh' });+ const store = new CloudTokenStore('old-jwt', 'old-refresh', live.cloud.apiUrl, live.cloud.agentId, live);++ await expect(store.rotate()).resolves.toEqual({ jwt: 'new-jwt', refreshToken: 'new-refresh' });++ expect(live.cloud).toMatchObject({ jwt: 'new-jwt', refreshToken: 'new-refresh' });+ expect(live.providers.mercuryCloud.apiKey).toBe('new-jwt');+ expect(mocks.saveConfig).toHaveBeenCalledWith(expect.objectContaining({+ cloud: expect.objectContaining({ jwt: 'new-jwt', refreshToken: 'new-refresh' }),+ }));+ });++ it('adopts credentials rotated and persisted by another process', async () => {+ const live = config();+ mocks.loadConfig+ .mockReturnValueOnce(config())+ .mockReturnValue(config('other-jwt', 'other-refresh'));+ mocks.refreshToken.mockRejectedValue(new Error('Token refresh failed: 401'));+ const store = new CloudTokenStore('old-jwt', 'old-refresh', live.cloud.apiUrl, live.cloud.agentId, live);++ await expect(store.rotate()).resolves.toEqual({ jwt: 'other-jwt', refreshToken: 'other-refresh' });+ expect(store.getTokens()).toEqual({ jwt: 'other-jwt', refreshToken: 'other-refresh' });+ expect(mocks.saveConfig).not.toHaveBeenCalled();+ });++ it('coalesces concurrent rotation requests', async () => {+ const live = config();+ mocks.loadConfig.mockReturnValue(config());+ mocks.refreshToken.mockResolvedValue({ jwt: 'new-jwt', refreshToken: 'new-refresh' });+ const store = new CloudTokenStore('old-jwt', 'old-refresh', live.cloud.apiUrl, live.cloud.agentId, live);++ await Promise.all([store.rotate(), store.rotate(), store.rotate()]);++ expect(mocks.refreshToken).toHaveBeenCalledTimes(1);+ });++ it('does not restore tokens when disconnect wins an in-flight refresh race', async () => {+ let resolveRefresh!: (tokens: { jwt: string; refreshToken: string }) => void;+ const live = config();+ const disconnected = config('', '');+ disconnected.cloud.enabled = false;+ disconnected.cloud.agentId = '';+ disconnected.providers.mercuryCloud.enabled = false;+ mocks.loadConfig.mockReturnValueOnce(config()).mockReturnValue(disconnected);+ mocks.refreshToken.mockReturnValue(new Promise((resolve) => { resolveRefresh = resolve; }));+ const store = new CloudTokenStore('old-jwt', 'old-refresh', live.cloud.apiUrl, live.cloud.agentId, live, live.cloud.agentApiKey);++ const rotating = store.rotate();+ resolveRefresh({ jwt: 'resurrected-jwt', refreshToken: 'resurrected-refresh' });++ await expect(rotating).rejects.toThrow('disconnected or re-paired');+ expect(live.cloud.jwt).toBe('old-jwt');+ expect(mocks.saveConfig).not.toHaveBeenCalled();+ expect(mocks.redeemAgentApiKey).not.toHaveBeenCalled();+ });++ it('rejects an agent API key that redeems to another agent', async () => {+ const live = config('expired-jwt', '');+ mocks.redeemAgentApiKey.mockResolvedValue({+ jwt: 'other-jwt',+ refreshToken: 'other-refresh',+ agentId: 'agent-2',+ });+ const store = new CloudTokenStore('expired-jwt', '', live.cloud.apiUrl, live.cloud.agentId, live, live.cloud.agentApiKey);++ await expect(store.rotate()).rejects.toThrow('identity mismatch');+ expect(mocks.saveConfig).not.toHaveBeenCalled();+ });+});diff --git a/src/cloud/token-store.ts b/src/cloud/token-store.tsnew file mode 100644index 00000000..b0ca6ac6--- /dev/null+++ b/src/cloud/token-store.ts@@ -0,0 +1,308 @@+import { loadConfig, saveConfig, updateConfig, type MercuryConfig } from '../utils/config.js';+import { refreshToken as rotateRefreshToken, redeemAgentApiKey } from './pairing.js';+import { logger } from '../utils/logger.js';++export interface TokenPair {+ jwt: string;+ refreshToken: string;+}++export type TokenRefreshListener = (tokens: TokenPair) => void;++/**+ * Single source of truth for the Mercury Cloud access + refresh tokens.+ *+ * Every consumer (WS client, MercuryCloud provider, pool search, chat+ * command handler) MUST read from and write back to this store. This is+ * critical because refresh tokens are single-use: once one consumer rotates+ * the token, every other consumer's cached copy is permanently invalid. The+ * old design gave each consumer its own private copy of the refresh token, so+ * the second rotation (after ~15 minutes) used an already-consumed token and+ * the WebSocket died until the user manually ran `mercury cloud connect`.+ *+ * This store keeps one in-memory copy, persists every rotation to disk, and+ * notifies listeners so the WS client and provider swap their cached JWT+ * without racing the auth endpoint.+ *+ * As a last-resort recovery, when the refresh token is dead (expired or+ * already consumed) the store redeems the long-lived agent API key (issued at+ * pairing time) for a fresh JWT + refresh-token pair — so a paired agent+ * self-recovers without forcing the user through a browser re-pair.+ */+export class CloudTokenStore {+ private jwt: string;+ private refreshTokenValue: string;+ private readonly apiUrl: string;+ private readonly agentId: string;+ private agentApiKey: string;+ private listeners = new Set<TokenRefreshListener>();+ private inflight: Promise<TokenPair> | null = null;+ private readonly liveConfig?: MercuryConfig;+ private active = true;++ constructor(jwt: string, refreshTokenValue: string, apiUrl: string, agentId: string, liveConfig?: MercuryConfig, agentApiKey?: string) {+ this.jwt = jwt;+ this.refreshTokenValue = refreshTokenValue;+ this.apiUrl = apiUrl;+ this.agentId = agentId;+ this.liveConfig = liveConfig;+ this.agentApiKey = agentApiKey ?? liveConfig?.cloud.agentApiKey ?? '';+ }++ getTokens(): TokenPair {+ return { jwt: this.jwt, refreshToken: this.refreshTokenValue };+ }++ getJwt(): string {+ return this.jwt;+ }++ getRefreshToken(): string {+ return this.refreshTokenValue;+ }++ getAgentId(): string {+ return this.agentId;+ }++ getApiUrl(): string {+ return this.apiUrl;+ }++ getAgentApiKey(): string {+ return this.agentApiKey;+ }++ matchesIdentity(apiUrl: string, agentId: string): boolean {+ return this.active && this.apiUrl === apiUrl && this.agentId === agentId;+ }++ setAgentApiKey(apiKey: string): void {+ if (!this.active) throw new Error('Mercury Cloud credentials have been invalidated');+ this.agentApiKey = apiKey;+ if (this.liveConfig) this.liveConfig.cloud.agentApiKey = apiKey;+ this.persistAgentApiKey(apiKey);+ }++ private persistAgentApiKey(apiKey: string): void {+ try {+ const config = loadConfig();+ config.cloud.agentApiKey = apiKey;+ saveConfig(config);+ } catch (err) {+ logger.warn({ err: (err as Error).message }, 'Failed to persist agent API key to config');+ }+ }++ /**+ * Update the cached tokens without persisting to disk. Use when the caller+ * has already persisted (e.g. the pairing flow writes config itself).+ */+ setTokens(jwt: string, refreshTokenValue: string): void {+ if (!this.active) throw new Error('Mercury Cloud credentials have been invalidated');+ this.jwt = jwt;+ this.refreshTokenValue = refreshTokenValue;+ if (this.liveConfig) {+ this.liveConfig.cloud.jwt = jwt;+ this.liveConfig.cloud.refreshToken = refreshTokenValue;+ this.liveConfig.providers.mercuryCloud.apiKey = jwt;+ }+ for (const listener of this.listeners) {+ try { listener({ jwt, refreshToken: refreshTokenValue }); } catch (err) {+ logger.warn({ err: (err as Error).message }, 'Cloud token store listener threw');+ }+ }+ }++ /**+ * Update the cached tokens AND persist to disk + mirror into the provider+ * config. This is the path used by background rotation.+ */+ setTokensAndPersist(jwt: string, refreshTokenValue: string): void {+ updateConfig((config) => {+ this.assertActivePersistedIdentity(config);+ config.cloud.jwt = jwt;+ config.cloud.refreshToken = refreshTokenValue;+ config.providers.mercuryCloud.apiKey = jwt;+ });+ this.setTokens(jwt, refreshTokenValue);+ }++ /**+ * Rotate the refresh token exactly once across all concurrent callers.+ * Returns the new pair and persists + notifies listeners. If the refresh+ * token is dead (expired or already consumed), falls back to redeeming the+ * long-lived agent API key so the agent self-recovers without a re-pair.+ */+ async rotate(): Promise<TokenPair> {+ if (!this.active) throw new Error('Mercury Cloud credentials have been invalidated');+ if (this.inflight) return this.inflight;+ if (!this.refreshTokenValue && !this.agentApiKey) throw new Error('No refresh token or agent API key available');++ this.inflight = (async () => {+ const tokenBeingRotated = this.refreshTokenValue;+ const persisted = this.readNewerPersistedTokens(tokenBeingRotated);+ if (persisted) return persisted;+ if (!this.active) throw new Error('Mercury Cloud was disconnected or re-paired');++ if (tokenBeingRotated) {+ try {+ const result = await rotateRefreshToken(this.apiUrl, tokenBeingRotated);+ this.setTokensAndPersist(result.jwt, result.refreshToken);+ return result;+ } catch (error) {+ if (!this.active) throw error;+ // Another Mercury process may have won the single-use rotation and+ // persisted the successor while this request was in flight.+ for (const delay of [50, 150, 300]) {+ await new Promise((resolve) => setTimeout(resolve, delay));+ const adopted = this.readNewerPersistedTokens(tokenBeingRotated);+ if (adopted) return adopted;+ }+ // Refresh token is genuinely dead. Try the long-lived agent API key+ // before giving up — this is the self-recovery path that avoids a+ // browser re-pair for remotely-deployed agents.+ if (this.agentApiKey) {+ logger.warn({ err: (error as Error).message }, 'Refresh token rotation failed; redeeming agent API key');+ return await this.redeemWithAgentKey();+ }+ throw error;+ }+ } else {+ // No refresh token at all — go straight to the agent API key.+ return await this.redeemWithAgentKey();+ }+ })().finally(() => {+ this.inflight = null;+ });++ return this.inflight;+ }++ /**+ * Redeem the long-lived agent API key for a fresh JWT + refresh-token pair.+ * On success, persists the new tokens (and keeps the same agent API key)+ * and notifies listeners. Throws if the API key is invalid/revoked.+ */+ private async redeemWithAgentKey(): Promise<TokenPair> {+ if (!this.agentApiKey) throw new Error('No agent API key available for recovery');+ const result = await redeemAgentApiKey(this.apiUrl, this.agentApiKey);+ if (!result.agentId || result.agentId !== this.agentId) {+ throw new Error('Agent API key identity mismatch; re-pair Mercury Cloud');+ }+ this.setTokensAndPersist(result.jwt, result.refreshToken);+ return { jwt: result.jwt, refreshToken: result.refreshToken };+ }++ /**+ * Rotate only if the access token is expired or within `skewMs` of expiry.+ * Returns the current (possibly newly rotated) JWT.+ */+ async rotateIfExpired(skewMs = 60_000): Promise<string> {+ if (!isTokenExpired(this.jwt, skewMs)) return this.jwt;+ const result = await this.rotate();+ return result.jwt;+ }++ /**+ * Decode the JWT and return true if it is malformed or within `skewMs` of+ * (or past) its `exp` claim.+ */+ isJwtNearExpiry(skewMs = 60_000): boolean {+ return isTokenExpired(this.jwt, skewMs);+ }++ addListener(listener: TokenRefreshListener): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ invalidate(): void {+ if (!this.active) return;+ this.active = false;+ this.jwt = '';+ this.refreshTokenValue = '';+ this.agentApiKey = '';+ for (const listener of this.listeners) {+ try { listener({ jwt: '', refreshToken: '' }); } catch {}+ }+ this.listeners.clear();+ }++ private assertActivePersistedIdentity(config: MercuryConfig): void {+ if (+ !config.cloud.enabled+ || !config.providers.mercuryCloud.enabled+ || config.cloud.agentId !== this.agentId+ || config.cloud.apiUrl !== this.apiUrl+ ) {+ this.invalidate();+ throw new Error('Mercury Cloud was disconnected or re-paired while credentials were refreshing');+ }+ }++ private readNewerPersistedTokens(comparedRefreshToken: string): TokenPair | null {+ try {+ const config = loadConfig();+ if (+ !config.cloud.enabled+ || !config.providers.mercuryCloud.enabled+ || config.cloud.agentId !== this.agentId+ || config.cloud.apiUrl !== this.apiUrl+ ) {+ this.invalidate();+ return null;+ }+ if (+ !config.cloud.jwt+ || !config.cloud.refreshToken+ || config.cloud.refreshToken === comparedRefreshToken+ ) return null;+ this.setTokens(config.cloud.jwt, config.cloud.refreshToken);+ return { jwt: config.cloud.jwt, refreshToken: config.cloud.refreshToken };+ } catch {+ return null;+ }+ }+}++function isTokenExpired(jwt: string, skewMs = 60_000): boolean {+ const parts = jwt.split('.');+ if (parts.length !== 3) return true;+ try {+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as { exp?: number };+ return typeof payload.exp !== 'number' || Date.now() >= payload.exp * 1000 - skewMs;+ } catch {+ return true;+ }+}++let store: CloudTokenStore | null = null;++/**+ * Initialize (or re-initialize) the shared token store from the current config.+ * Called once at agent startup. Subsequent calls replace the singleton so a+ * re-pair updates the store with the new credentials.+ */+export function initCloudTokenStore(config: MercuryConfig): CloudTokenStore {+ store?.invalidate();+ const next = new CloudTokenStore(+ config.cloud.jwt,+ config.cloud.refreshToken,+ config.cloud.apiUrl,+ config.cloud.agentId,+ config,+ config.cloud.agentApiKey,+ );+ store = next;+ return next;+}++export function getCloudTokenStore(): CloudTokenStore | null {+ return store;+}++export function clearCloudTokenStore(): void {+ store?.invalidate();+ store = null;+}diff --git a/src/cloud/types.ts b/src/cloud/types.tsnew file mode 100644index 00000000..31ca1143--- /dev/null+++ b/src/cloud/types.ts@@ -0,0 +1,56 @@+export interface CloudConfig {+ enabled: boolean;+ apiUrl: string;+ wsUrl: string;+ jwt: string;+ refreshToken: string;+ agentId: string;+ tier: string;+ agentApiKey: string;+}++export interface PairingResult {+ jwt: string;+ refreshToken: string;+ agentId: string;+ tier: string;+ apiKey?: string;+}++export interface TokenRefreshResult {+ jwt: string;+ refreshToken: string;+}++export type WSMessageType =+ | 'agent.restart'+ | 'agent.status'+ | 'agent.command'+ | 'agent.command.ack'+ | 'agent.event.ack'+ | 'skill.install'+ | 'skill.remove'+ | 'memory.extract'+ | 'memory.fetch'+ | 'memory.fetch.result'+ | 'memory.share-learning.toggle'+ | 'conversation.history'+ | 'conversation.sync.toggle'+ | 'agent.heartbeat'+ | 'agent.state'+ | 'skill.ack'+ | 'memory.dump'+ | 'conversation.dump'+ | 'agent.error'+ | 'agent.message.relay'+ | 'agent.response'+ | 'agent.stream'+ | 'research.artifact'+ | 'token.refreshed';++export interface WSMessage {+ type: WSMessageType;+ agentId?: string;+ payload?: Record<string, unknown>;+ timestamp?: string;+}diff --git a/src/core/agent.ts b/src/core/agent.tsindex ea18956f..5720a614 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1,20 +1,23 @@import { generateText, streamText, stepCountIs } from 'ai';import path from 'node:path';+import { existsSync } from 'node:fs';import type { ChannelMessage, ChannelType } from '../types/channel.js';import type { ProviderRegistry } from '../providers/registry.js';import type { Identity } from '../soul/identity.js';import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';import type { UserMemoryStore } from '../memory/user-memory.js';import type { ChannelRegistry } from '../channels/registry.js';-import type { MercuryConfig } from '../utils/config.js';+import type { MercuryConfig, ProviderName } from '../utils/config.js';import type { TokenBudget } from '../utils/tokens.js';import type { CapabilityRegistry } from '../capabilities/registry.js';import type { ScheduledTaskManifest } from './scheduler.js';import { DeepSeekProvider } from '../providers/deepseek.js';-import { ProviderRegistry as ProviderRegistryImpl } from '../providers/registry.js';+import { createProvider, ProviderRegistry as ProviderRegistryImpl } from '../providers/registry.js';+import type { BaseProvider } from '../providers/base.js';import { Lifecycle } from './lifecycle.js';import { Scheduler } from './scheduler.js';import { ProgrammingMode } from './programming-mode.js';+import { ResearchMode } from './research-mode.js';import { SaverMode, NORMAL_HISTORY_WINDOW } from './saver-mode.js';import { BackgroundTaskManager } from './background-tasks.js';import { SkillBatcher } from '../skills/batcher.js';@@ -31,7 +34,9 @@ import { WebChannel } from '../channels/web.js';import type { ArrowSelectOption } from '../utils/arrow-select.js';import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';import type { SpotifyClient } from '../spotify/client.js';+import { normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../spotify/ui.js';+import { getCloudTokenStore } from '../cloud/token-store.js';import {approveTelegramPendingRequest,approveTelegramPendingRequestByPairingCode,@@ -44,6 +49,7 @@ import {rejectTelegramPendingRequest,removeTelegramUser,saveConfig,+ loadConfig,getActiveProviders,getDiscordAccessSummary,hasDiscordAdmins,@@ -62,6 +68,11 @@ import {removeSlackUser,clearSlackAccess,} from '../utils/config.js';+import { fetchProviderModelCatalog, getPreferredModelsForProvider } from '../utils/provider-models.js';+import { WorkLedger, type WorkEntry } from './work-ledger.js';+import { MAX_PROVIDER_ATTEMPT_MS, needsContinuationApproval, needsRetryApproval, withAbortDeadline } from './execution-limits.js';+import { requiresFinalSend } from './response-delivery.js';+import { updateCliProviderStatus } from './provider-status.js';class ToolCallLoopDetector {private recentCalls: Array<{ tool: string; params: string; failed: boolean; timestamp: number }> = [];@@ -290,36 +301,64 @@ class ToolCallLoopDetector {}}-const MAX_STEPS = 25;+const MAX_STEPS = 75;const MAX_RESPONSE_TOKENS = 4096;const HEARTBEAT_INITIAL_MS = 20000;const HEARTBEAT_MAX_MS = 60000;const LONG_TASK_HANDOFF_SUGGEST_MS = 45000;-const MAX_FOREGROUND_WALL_MS = 10 * 60 * 1000;const MAX_STALL_MS = 4 * 60 * 1000;const MAX_SELF_CHECKS = 3; // max AI self-checks per request before hard-aborting+/**+ * Heuristic: does this message look like a deep-research request that would+ * benefit from full research mode? Conservative — false negatives just fall+ * through to a normal answer, so we prefer specificity over recall.+ */+function looksResearchy(text: string): boolean {+ const t = text.toLowerCase();+ if (t.length < 24) return false; // too short to be a research question+ if (t.startsWith('/')) return false;++ // Temporal / event research signals+ const temporal = /\b(happened|occurr?ed|took place|what (did|do) .* (say|report|find)|recent|last (week|month|year|few)|(\d+)\s*(days?|weeks?|months?|years?) (ago|back|earlier)|today'?s news|this week|this month|this year)\b/;+ // Deep / comparative / explain signals+ const deep = /\b(research|investigate|deep dive|in[- ]depth|explain in detail|comprehensive (guide|overview|analysis)|compare (and )?contrast|state of|history of|causes? of|impact of|effects? of|timeline of|breakdown of|everything about)\b/;+ // Factual lookup signals+ const factual = /\b(latest|current state|what is .* (situation|status)|what are the (options|alternatives|risks|benefits))\b/;++ return temporal.test(t) || deep.test(t) || factual.test(t);+}+export class Agent {readonly lifecycle: Lifecycle;readonly scheduler: Scheduler;readonly capabilities: CapabilityRegistry;private running = false;- private messageQueue: ChannelMessage[] = [];+ private messageQueue: Array<{ message: ChannelMessage; workKey?: string }> = [];+ private queuedWorkKeys = new Set<string>();private processing = false;private telegramStreaming: boolean;private currentMessage: ChannelMessage | null = null;private currentAbort: AbortController | null = null;+ private currentAbortReason: 'stalled' | 'time-limit' | 'backgrounded' | null = null;private lastProgressAt = 0;private currentActivity = '';private completedStepCount = 0;private stepNarrative: import('../utils/tool-label.js').NarrativeStep[] = [];private supervisor?: import('../core/supervisor.js').SubAgentSupervisor;readonly programmingMode: ProgrammingMode;+ readonly researchMode: ResearchMode;readonly saverMode: SaverMode;private spotifyClient?: SpotifyClient;private skillBatcher: SkillBatcher | null = null;private skillLoader?: SkillLoader;readonly backgroundTasks: BackgroundTaskManager;+ private titleGenerationInFlight = new Set<string>();+ private sessionSyncEnabled = false;+ private readonly workLedger: WorkLedger;+ private currentWorkKey: string | null = null;+ private outboxRetryTimer: ReturnType<typeof setInterval> | null = null;+ private replayingOutbox = false;constructor(private config: MercuryConfig,@@ -333,14 +372,19 @@ export class Agent {private tokenBudget: TokenBudget,capabilities: CapabilityRegistry,scheduler: Scheduler,+ private sessions: SessionRepository,+ private generateTitle?: (input: { userMessage: string; assistantMessage: string; providerName: string }) => Promise<string>,) {this.lifecycle = new Lifecycle();this.scheduler = scheduler;this.capabilities = capabilities;this.telegramStreaming = config.channels.telegram.streaming ?? true;this.programmingMode = new ProgrammingMode();+ this.researchMode = new ResearchMode();this.saverMode = new SaverMode(config);+ this.wireResearchModeToCapabilities();this.backgroundTasks = new BackgroundTaskManager();+ this.workLedger = new WorkLedger();this.backgroundTasks.onGlobalComplete((task) => {this.notifyBackgroundTaskComplete(task);@@ -366,6 +410,23 @@ export class Agent {}}+ setSessionSyncEnabled(enabled: boolean): void {+ this.sessionSyncEnabled = enabled;+ }++ isSessionSyncEnabled(): boolean {+ return this.sessionSyncEnabled;+ }++ acknowledgeCloudDelivery(requestId: string): void {+ const key = `request:${requestId}`;+ if (this.workLedger.get(key)) this.workLedger.markDelivered(key);+ }++ private wireResearchModeToCapabilities(): void {+ this.capabilities.setResearchModeGetter(() => this.researchMode.isActive());+ }+setSupervisor(supervisor: import('../core/supervisor.js').SubAgentSupervisor): void {this.supervisor = supervisor;if (this.skillLoader) {@@ -409,7 +470,91 @@ export class Agent {return;}- this.messageQueue.push(msg);+ let workKey: string | undefined;+ if (!trimmed.startsWith('/')) {+ msg.metadata = {+ ...msg.metadata,+ workCwd: typeof msg.metadata?.workCwd === 'string' ? msg.metadata.workCwd : this.capabilities.getCwd(),+ };+ const accepted = this.workLedger.accept(msg);+ workKey = accepted.entry.key;+ if (!accepted.accepted) {+ void this.handleDuplicateWork(accepted.entry);+ return;+ }+ }++ // Research-y message prompt: when research mode is off and the message looks+ // like a deep-research request, ask whether to run a full research pass.+ const isUserMessage = msg.channelType !== 'internal' && msg.senderId !== 'system' && !trimmed.startsWith('/');+ if (isUserMessage && !this.researchMode.isActive() && looksResearchy(trimmed)) {+ this.promptResearchMode(msg, workKey).catch((err) => {+ logger.warn({ err: err.message }, 'Research-mode prompt failed — proceeding with normal message');+ this.queueMessage(msg, workKey);+ this.processQueue();+ });+ return;+ }++ this.queueMessage(msg, workKey);+ this.processQueue();+ }++ private queueMessage(message: ChannelMessage, workKey?: string): void {+ if (workKey && this.queuedWorkKeys.has(workKey)) return;+ this.messageQueue.push({ message, workKey });+ if (workKey) this.queuedWorkKeys.add(workKey);+ }++ private async handleDuplicateWork(entry: WorkEntry): Promise<void> {+ if (entry.status === 'completed' && !entry.delivered && entry.finalResponse) {+ await this.deliverLedgerEntry(entry);+ return;+ }+ const channel = this.channels.getChannelForMessage(entry.message);+ if (!channel || entry.message.channelType === 'internal') return;+ // For the web (Cloud chat) channel, don't send duplicate-status messages+ // to the user. The Cloud dashboard already handles dedup on its end, and+ // sending "This request is already running" creates a bad UX — the user+ // sees a confusing system message instead of silence.+ if (entry.message.channelType === 'web') return;+ const status = entry.status === 'completed'+ ? 'This request already completed and its result was delivered.'+ : entry.status === 'failed'+ ? `This request previously failed: ${entry.error || 'unknown error'}`+ : `This request is already ${entry.status}${entry.attempts > 0 ? ` (attempt ${entry.attempts})` : ''}.`;+ await channel.send(status, entry.message.channelId).catch((error) => {+ logger.warn({ error, workKey: entry.key }, 'Unable to send duplicate work status');+ });+ }++ private async promptResearchMode(msg: ChannelMessage, workKey?: string): Promise<void> {+ const channel = this.channels.getChannelForMessage(msg);+ if (!channel) {+ this.queueMessage(msg, workKey);+ this.processQueue();+ return;+ }++ const explanation =+ 'Research mode will search the web, cross-check multiple sources, gather images, and produce a full research article as rich markdown. It runs longer than a quick answer and will not be killed early.';++ const choice = await this.presentChoice(+ `This looks like a research question. ${explanation}\n\nHow do you want to proceed?`,+ ['Full research mode (deep, multi-source article)', 'Quick answer (normal conversation)'],+ msg.channelId,+ msg.channelType,+ );++ if (choice.toLowerCase().startsWith('full')) {+ this.researchMode.setOn(msg.content.trim().slice(0, 120));+ if (channel instanceof WebChannel) {+ channel.sendHeartbeat('Research mode: On. Gathering sources and building the article now — this may take a while.', msg.channelId);+ } else {+ await channel.send('Research mode: **On**. Gathering sources and building the article now — this may take a while.', msg.channelId).catch(() => {});+ }+ }+ this.queueMessage(msg, workKey);this.processQueue();}@@ -422,6 +567,11 @@ export class Agent {const hasActiveAgents = activeAgents.length > 0;const busyPrefix = hasActiveAgents ? '' : '';+ if (trimmed === '/sessions' || trimmed.startsWith('/session')) {+ await this.handleSessionCommand(trimmed, msg.channelType, msg.channelId);+ return;+ }+if (trimmed === '/agents' || trimmed === '/status') {if (this.supervisor) {const agents = this.supervisor.getActiveAgents();@@ -474,7 +624,7 @@ export class Agent {}if (trimmed === '/help') {- await channel.send('Agent is busy. Available: /agents, /halt, /stop, /progress, /spotify, /code, /memory, /bg', msg.channelId);+ await channel.send('Agent is busy. Available: /sessions, /session, /agents, /halt, /stop, /progress, /spotify, /code, /research, /memory, /bg', msg.channelId);return;}@@ -501,7 +651,7 @@ export class Agent {await channel.send(`I'm busy processing${elapsedSec > 0 ? ` (${elapsedSec}s elapsed)` : ''}. Use /progress for live status or /bg current to move this task to the background.`, msg.channelId);}- this.messageQueue.push(msg);+ this.queueMessage(msg);}private async handleFastPathSpotify(trimmed: string, msg: ChannelMessage, channel: any): Promise<void> {@@ -562,6 +712,7 @@ export class Agent {const sourceChannelType = this.currentMessage.channelType as any;if (this.currentAbort) {+ this.currentAbortReason = 'backgrounded';this.currentAbort.abort();}@@ -708,6 +859,12 @@ export class Agent {})();}+ private withProviderDeadline<T>(operation: PromiseLike<T>, controller: AbortController, deadlineAt: number): Promise<T> {+ return withAbortDeadline(operation, controller, deadlineAt - Date.now(), () => {+ this.currentAbortReason = 'time-limit';+ });+ }+private startForegroundHeartbeat(msg: ChannelMessage): () => void {if (msg.channelType === 'internal') return () => {};@@ -718,20 +875,23 @@ export class Agent {const tick = () => {if (!this.processing || !this.currentMessage || this.currentMessage.id !== msg.id) return;const channel = this.channels.getChannelForMessage(msg);- if (!channel) return;const elapsedMs = Date.now() - this.currentMessage.timestamp;const stallMs = Date.now() - this.lastProgressAt;const elapsedSec = Math.round(elapsedMs / 1000);const stallSec = Math.round(stallMs / 1000);- if (stallMs >= MAX_STALL_MS && this.currentAbort && !this.currentAbort.signal.aborted) {+ if (stallMs >= MAX_STALL_MS * this.researchMode.getStallMsMultiplier() && this.currentAbort && !this.currentAbort.signal.aborted) {logger.warn({ elapsedSec, stallSec, msgId: msg.id }, 'Foreground task stalled — aborting');+ this.currentAbortReason = 'stalled';this.currentAbort.abort();- void channel.send(- `⚠ Task stalled (no progress for ${stallSec}s). Stopped to avoid hanging. You can retry or use /bg current sooner for long tasks.`,- msg.channelId,- ).catch((e) => logger.warn({ e }, 'channel send failed'));+ if (channel) {+ void channel.send(+ `Mercury detected a stalled provider after ${stallSec}s without progress. Reconnecting and retrying automatically.`,+ msg.channelId,+ ).catch((e) => logger.warn({ e }, 'channel send failed'));+ }+ timer = setTimeout(tick, HEARTBEAT_MAX_MS);return;}@@ -747,10 +907,13 @@ export class Agent {const heartbeatText = `⏳ Working... ${elapsedSec}s elapsed${stepInfo}.${narrativeBlock}${handoffHint}`;// CLI: update one message in place instead of stacking new ones.+ // Web/cloud: send a non-terminal heartbeat so the cloud response handler stays alive.// Other channels (Telegram): still send as separate messages.if (channel instanceof CLIChannel) {(channel as CLIChannel).sendHeartbeat(heartbeatText);- } else {+ } else if (channel instanceof WebChannel) {+ (channel as WebChannel).sendHeartbeat(heartbeatText, msg.channelId);+ } else if (channel) {void channel.send(heartbeatText, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}@@ -818,20 +981,154 @@ export class Agent {private async processQueue(): Promise<void> {if (this.processing) return;if (this.messageQueue.length === 0) return;+ if (!this.running) return;if (!this.lifecycle.is('idle')) return;this.processing = true;- while (this.messageQueue.length > 0) {- const msg = this.messageQueue.shift()!;+ try {+ while (this.messageQueue.length > 0) {+ const item = this.messageQueue.shift()!;+ const msg = item.message;+ if (item.workKey) this.queuedWorkKeys.delete(item.workKey);+ this.currentWorkKey = item.workKey ?? null;+ try {+ if (item.workKey) this.workLedger.markRunning(item.workKey);+ await this.handleMessage(msg);+ if (item.workKey && this.workLedger.get(item.workKey)?.status === 'running') {+ this.workLedger.markFailed(item.workKey, 'Work ended without producing a durable final response');+ }+ } catch (err) {+ if (item.workKey) {+ const entry = this.workLedger.get(item.workKey);+ if (entry?.status === 'completed') this.workLedger.markDeliveryError(item.workKey, err);+ else this.workLedger.markFailed(item.workKey, err);+ }+ logger.error({ err, msg: msg.content.slice(0, 50) }, 'Failed to handle message');+ } finally {+ this.currentWorkKey = null;+ if (!this.lifecycle.is('idle') && this.lifecycle.canTransitionTo('idle')) {+ this.lifecycle.transition('idle');+ }+ }+ }+ } finally {+ this.processing = false;+ if (this.messageQueue.length > 0) void this.processQueue();+ }+ }++ private scheduleDurableRetry(msg: ChannelMessage, workKey: string, error: unknown, continuation = false): number {+ const attempts = this.workLedger.get(workKey)?.attempts ?? 1;+ const delayMs = continuation+ ? Math.min(2_000 * 2 ** Math.min(attempts - 1, 5), 60_000)+ : Math.min(5_000 * 2 ** Math.min(attempts - 1, 6), 5 * 60_000);+ this.workLedger.markRetry(workKey, error, Date.now() + delayMs, {+ continuation,+ workCwd: this.capabilities.getCwd(),+ activity: this.currentActivity,+ summary: formatNarrative(this.stepNarrative, this.currentActivity, 8),+ });+ const timer = setTimeout(() => {+ const entry = this.workLedger.get(workKey);+ if (!entry || entry.status !== 'queued') return;+ this.queueMessage(entry.message, workKey);+ void this.processQueue();+ }, delayMs);+ timer.unref?.();+ return delayMs;+ }++ private isRetryableProviderError(error: unknown): boolean {+ const message = (error instanceof Error ? error.message : String(error)).toLowerCase();+ return /timeout|timed out|network|socket|connection|temporar|unavailable|overloaded|rate.?limit|\b429\b|\b5\d\d\b|econn|fetch failed|stalled/.test(message);+ }++ private async sendProgressNotice(msg: ChannelMessage, message: string): Promise<void> {+ const channel = this.channels.getChannelForMessage(msg);+ if (!channel || msg.channelType === 'internal') return;+ if (channel instanceof WebChannel) {+ channel.sendHeartbeat(message, msg.channelId);+ return;+ }+ if (channel instanceof CLIChannel) {+ channel.sendHeartbeat(message);+ return;+ }+ await channel.send(message, msg.channelId);+ }++ private channelProviderOverrides = new Map<string, { providerName: string; modelName: string; provider: BaseProvider }>();++ async listChatModelOptions(): Promise<Array<{ provider: string; label: string; model: string; models: string[]; selected: boolean }>> {+ const active = getActiveProviders(this.config);+ const current = this.getCurrentProvider();+ return Promise.all(active.map(async (provider) => {+ let models = [provider.model].filter(Boolean);try {- await this.handleMessage(msg);+ const catalog = await fetchProviderModelCatalog(provider.name as any, provider.name === 'mercuryCloud'+ ? {+ ...provider,+ apiKey: this.config.cloud.jwt || provider.apiKey,+ baseUrl: this.config.cloud.apiUrl || provider.baseUrl,+ }+ : provider);+ models = [...new Set([provider.model, catalog.recommendedModel, ...catalog.models].filter(Boolean))];} catch (err) {- logger.error({ err, msg: msg.content.slice(0, 50) }, 'Failed to handle message');+ logger.debug({ provider: provider.name, err }, 'Unable to fetch provider model catalog; using configured model');+ models = [...new Set([provider.model, ...getPreferredModelsForProvider(provider.name as any)].filter(Boolean))];}++ return {+ provider: provider.name,+ label: provider.name,+ model: provider.model,+ models,+ selected: provider.name === current.name,+ };+ }));+ }++ async setChannelProviderOverride(+ channelId: string,+ providerName: string,+ modelName?: string,+ options: { persist?: boolean } = {},+ ): Promise<{ ok: boolean; message: string; provider?: string; model?: string }> {+ const active = getActiveProviders(this.config);+ const config = active.find((provider) => provider.name === providerName);+ if (!config) {+ return { ok: false, message: `Provider \`${providerName}\` is not configured for this local agent.` };+ }++ const provider = await createProvider(+ { ...config, model: modelName || config.model },+ providerName === 'mercuryCloud' ? getCloudTokenStore() : undefined,+ );+ if (!provider) {+ return { ok: false, message: `Provider \`${providerName}\` is not available in the running registry.` };}- this.processing = false;+ const previousOverride = this.channelProviderOverrides.get(channelId)?.provider as (BaseProvider & { destroy?: () => void }) | undefined;+ if (previousOverride !== provider && this.providers.get(previousOverride?.name) !== previousOverride) {+ previousOverride?.destroy?.();+ }+ this.channelProviderOverrides.set(channelId, { providerName, modelName: provider.getModel(), provider });++ if (options.persist && providerName in this.config.providers) {+ const providerKey = providerName as ProviderName;+ const providerConfig = this.config.providers[providerKey];+ providerConfig.model = provider.getModel();+ providerConfig.enabled = true;+ this.config.providers.default = providerName as ProviderName;+ this.providers.set(providerName, provider);+ this.providers.setDefault(providerName);+ saveConfig(this.config);+ updateCliProviderStatus(this.channels.get('cli'), providerName, provider.getModel());+ }++ const saved = options.persist ? ' Saved as the default for future sessions.' : '';+ return { ok: true, message: `This chat will use **${providerName}** · **${provider.getModel()}**.${saved}`, provider: providerName, model: provider.getModel() };}private async switchSessionProvider(providerName: string): Promise<{ ok: boolean; message: string }> {@@ -841,14 +1138,13 @@ export class Agent {}this.config.providers.default = providerName as any;- this.providers = await ProviderRegistryImpl.create(this.config);+ const previousProviders = this.providers;+ this.providers = await ProviderRegistryImpl.create(this.config, getCloudTokenStore());+ previousProviders.destroy();const selected = this.providers.getDefault();const model = selected.getModel();- const cliChannel = this.channels.get('cli');- if (cliChannel && cliChannel instanceof CLIChannel) {- cliChannel.setProvider(providerName, model);- }+ updateCliProviderStatus(this.channels.get('cli'), providerName, model);return { ok: true, message: `Session model switched to **${providerName}** · **${model}**.` };}@@ -882,6 +1178,12 @@ export class Agent {await this.channels.startAll();this.running = true;+ const recovered = this.workLedger.recoverInterrupted();+ for (const entry of recovered) this.queueMessage(entry.message, entry.key);+ await this.replayUndeliveredResponses();+ this.startOutboxRetry();+ void this.processQueue();+const activeChannels = this.channels.getActiveChannels();const toolNames = this.capabilities.getToolNames();logger.info({ channels: activeChannels, tools: toolNames }, 'Mercury is awake');@@ -889,21 +1191,83 @@ export class Agent {async sleep(): Promise<void> {this.running = false;+ if (this.outboxRetryTimer) {+ clearInterval(this.outboxRetryTimer);+ this.outboxRetryTimer = null;+ }this.scheduler.stopAll();await this.channels.stopAll();this.lifecycle.transition('sleeping');logger.info('Mercury is sleeping');}+ private async replayUndeliveredResponses(): Promise<void> {+ if (this.replayingOutbox) return;+ this.replayingOutbox = true;+ try {+ for (const entry of this.workLedger.getUndeliveredResponses()) {+ await this.deliverLedgerEntry(entry);+ }+ } finally {+ this.replayingOutbox = false;+ }+ }++ private startOutboxRetry(): void {+ if (this.outboxRetryTimer) return;+ this.outboxRetryTimer = setInterval(() => {+ if (this.running) void this.replayUndeliveredResponses();+ }, 30_000);+ this.outboxRetryTimer.unref?.();+ }++ private async deliverLedgerEntry(entry: WorkEntry): Promise<void> {+ const channel = this.channels.getChannelForMessage(entry.message);+ if (!channel || !entry.finalResponse) return;+ const requestId = typeof entry.message.metadata?.requestId === 'string' ? entry.message.metadata.requestId : undefined;+ const isCloudRequest = channel instanceof WebChannel+ && typeof entry.message.metadata?.externalConversationId === 'string'+ && requestId;+ if (isCloudRequest && !channel.hasCloudEventHandler(requestId)) return;+ try {+ if (entry.status === 'failed' && channel instanceof WebChannel) {+ if (!channel.sendError(entry.finalResponse, entry.message.channelId)) throw new Error('Cloud WebSocket could not accept the terminal error');+ } else {+ await channel.send(entry.finalResponse, entry.message.channelId);+ }+ if (!isCloudRequest) this.workLedger.markDelivered(entry.key);+ } catch (error) {+ this.workLedger.markDeliveryError(entry.key, error);+ logger.warn({ error, workKey: entry.key }, 'Durable response replay failed');+ }+ }++ private finalizeChannelTask(msg: ChannelMessage): void {+ const channel = this.channels.getChannelForMessage(msg);+ if (channel instanceof TelegramChannel || channel instanceof SignalChannel || channel instanceof DiscordChannel || channel instanceof SlackChannel) {+ channel.endTask(msg.channelId);+ channel.resetStepCounter(msg.channelId);+ }+ }+private async handleMessage(msg: ChannelMessage): Promise<void> {this.lifecycle.transition('thinking');const startTime = Date.now();+ let loopAbortController = new AbortController();+ this.currentMessage = msg;+ this.currentAbort = loopAbortController;+ this.currentAbortReason = null;+ const durableCwd = typeof msg.metadata?.workCwd === 'string' ? msg.metadata.workCwd : undefined;+ if (durableCwd && existsSync(durableCwd)) {+ this.capabilities.setCwd(durableCwd);+ this.capabilities.permissions.addTempScope(durableCwd, true, true);+ }this.currentActivity = '';this.completedStepCount = 0;this.stepNarrative = [];- const stopHeartbeat = this.startForegroundHeartbeat(msg);this.markProgress('Starting...');- let wallTimeout: ReturnType<typeof setTimeout> | null = null;+ const stopHeartbeat = this.startForegroundHeartbeat(msg);+ let canonicalSessionId: string | undefined;if (this.supervisor && msg.channelType !== 'internal') {const activeAgents = this.supervisor.getActiveAgents();@@ -918,8 +1282,7 @@ export class Agent {}const isInternal = msg.channelType === 'internal';- const isScheduled = msg.senderId === 'system' && msg.channelType !== 'internal';- if (isInternal || isScheduled) {+ if (isInternal) {this.capabilities.permissions.setAutoApproveAll(true);this.capabilities.permissions.addTempScope('/', true, true);}@@ -1020,12 +1383,45 @@ export class Agent {}}- const systemPrompt = this.buildSystemPrompt();- const recentMemory = this.shortTerm.getRecent(msg.channelId, this.saverMode.adjustHistoryWindow(10));+ let systemPrompt = this.buildSystemPrompt();+ if (msg.metadata?.workContinuation === true) {+ const attempt = typeof msg.metadata.continuationAttempt === 'number' ? msg.metadata.continuationAttempt : 1;+ const reason = typeof msg.metadata.continuationReason === 'string' ? msg.metadata.continuationReason : 'The prior execution was interrupted.';+ const activity = typeof msg.metadata.continuationActivity === 'string' ? msg.metadata.continuationActivity : 'unknown';+ const summary = typeof msg.metadata.continuationSummary === 'string' ? msg.metadata.continuationSummary : 'No structured progress summary is available.';+ const cwd = typeof msg.metadata.workCwd === 'string' ? msg.metadata.workCwd : this.capabilities.getCwd();+ systemPrompt += `\n\n[SYSTEM: DURABLE CONTINUATION ${attempt}] Do not restart this task. Continue from the artifacts and side effects already present. First inspect the current filesystem and relevant external state, especially ${cwd}. Prior interruption: ${reason}. Last activity: ${activity}. Recorded progress: ${summary}. Do not repeat the failed strategy. If a file or tool payload was too large, use a different bounded approach: inspect what exists, generate smaller components, append or patch in small verified chunks, or generate repetitive content programmatically. Verify each existing artifact before changing it. Keep working until there is a usable final deliverable, then clearly report its location and validation result.`;+ } else if (msg.metadata?.workRecovered === true) {+ systemPrompt += '\n\n[SYSTEM: RECOVERED WORK] This request was recovered after the agent restarted or its prior run was interrupted. Inspect the current filesystem, external state, and conversation before acting. Do not repeat side effects that may already have completed. Continue from observed state, and explicitly report any ambiguity you cannot safely resolve.';+ }+ const suppliedSessionId = msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : undefined);+ const externalConversationId = msg.channelType === 'cli'+ ? 'current'+ : typeof msg.metadata?.externalConversationId === 'string' ? msg.metadata.externalConversationId : msg.channelId;+ const canonicalSession = this.sessions.getOrCreateBound(msg.channelType, externalConversationId, suppliedSessionId);+ canonicalSessionId = canonicalSession.id;+ const canonicalMessageId = typeof msg.metadata?.canonicalMessageId === 'string' ? msg.metadata.canonicalMessageId : undefined;+ const requestId = typeof msg.metadata?.requestId === 'string' ? msg.metadata.requestId : undefined;+ this.sessions.appendMessage(canonicalSession.id, {+ id: canonicalMessageId,+ role: 'user',+ content: msg.content,+ timestamp: msg.timestamp,+ externalMessageId: msg.id,+ metadata: { channelType: msg.channelType, channelId: msg.channelId, ...(requestId ? { requestId } : {}) },+ });+ if (msg.channelType === 'cli') {+ const activeSession = this.sessions.get(canonicalSession.id);+ const cliChannel = this.channels.get('cli');+ if (cliChannel instanceof CLIChannel) cliChannel.setCurrentSession(activeSession);+ }+ const recentMemory = this.sessions.get(canonicalSession.id).messages+ .filter((entry) => entry.kind === 'message' && entry.role !== 'tool')+ .slice(-this.saverMode.adjustHistoryWindow(10));const messages: any[] = [];- const recentSteps = this.shortTerm.getRecent(msg.channelId, 6);+ const recentSteps = recentMemory.slice(-6);let loopWarning: string | null = null;if (recentSteps.length >= 3) {const toolCallPattern = /\[Using: (.+?)\]/g;@@ -1075,6 +1471,47 @@ export class Agent {});messages.push({ role: 'assistant', content: 'Noted. I\'ll keep this in mind.' });}++ // Local-first, then pool: query the cloud SharedMemoryPool for additional+ // context the second brain didn't surface. Gated by config, fails open+ // (any error → proceed with local-only context). 5-min cache per query.+ const ck = this.config.memory.collaborativeKnowledge;+ const cloud = this.config.cloud;+ const tokenStore = getCloudTokenStore();+ if (ck?.poolSearch !== false && cloud?.enabled && cloud?.jwt && cloud?.apiUrl) {+ try {+ const { searchPool, formatPoolContextBlock, dedupeAgainstLocal } = await import('../cloud/pool-search.js');+ const localSummaries = memoryContext.records.map((r) => r.summary);+ const poolHits = await searchPool(+ cloud.apiUrl,+ cloud.jwt,+ cloud.refreshToken,+ msg.content,+ { limit: 10 },+ (newJwt, newRefresh) => {+ // Route every rotation through the shared store so all+ // consumers see the new tokens. Fallback to direct config+ // mutation if the store isn't initialized (older code path).+ if (tokenStore) {+ tokenStore.setTokensAndPersist(newJwt, newRefresh);+ } else {+ cloud.jwt = newJwt;+ cloud.refreshToken = newRefresh;+ this.config.providers.mercuryCloud.apiKey = newJwt;+ saveConfig(this.config);+ }+ },+ );+ const deduped = dedupeAgainstLocal(poolHits, localSummaries);+ const poolBlock = formatPoolContextBlock(deduped, 1500);+ if (poolBlock) {+ messages.push({ role: 'user', content: poolBlock });+ messages.push({ role: 'assistant', content: 'Noted. I\'ll use this shared context.' });+ }+ } catch (err) {+ logger.debug({ err: (err as Error).message }, 'pool search failed (fail-open)');+ }+ }} else {const relevantFacts = this.longTerm.search(msg.content, 3);if (relevantFacts.length > 0) {@@ -1089,13 +1526,13 @@ export class Agent {if (recentMemory.length > 0) {for (const m of recentMemory) {messages.push({- role: m.role === 'user' ? 'user' : 'assistant',+ role: m.role,content: m.content,});}}- messages.push({ role: 'user', content: msg.content });+ if (!canonicalSessionId) messages.push({ role: 'user', content: msg.content });// ── Skill Intent Routing & Batch Execution ──//@@ -1231,24 +1668,24 @@ export class Agent {this.capabilities.setChannelContext(msg.channelId, msg.channelType);this.capabilities.permissions.setCurrentChannelType(msg.channelType);- const fallbackIterator = this.providers.getFallbackIterator();+ const providerContextId = msg.sessionId ?? (typeof msg.metadata?.sessionId === 'string' ? msg.metadata.sessionId : msg.channelId);+ const channelOverride = this.channelProviderOverrides.get(providerContextId);+ const fallbackIterator = channelOverride+ ? [channelOverride.provider, ...this.providers.getFallbackIterator(channelOverride.providerName)]+ .filter((provider, index, list) => list.findIndex((item) => item.name === provider.name && item.getModel() === provider.getModel()) === index)+ [Symbol.iterator]()+ : this.providers.getFallbackIterator();let result: any = null;let usedProvider: { name: string; model: string } | null = null;let lastError: any = null;- let streamedText = '';+ let hasCompletedTool = false;+ let hasStreamedOutput = false;+ let cliResponseStreamed = false;+ let requiresContinuationApproval = false;const loopDetector = new ToolCallLoopDetector();- const loopAbortController = new AbortController();let loopWarningSent = false;let selfCheckCount = 0;- this.currentMessage = msg;- this.currentAbort = loopAbortController;- wallTimeout = setTimeout(() => {- if (!loopAbortController.signal.aborted) {- loopAbortController.abort();- }- }, MAX_FOREGROUND_WALL_MS);-const canStream = msg.channelType === 'cli' || msg.channelType === 'web' || (msg.channelType === 'telegram' && this.telegramStreaming) || msg.channelType === 'signal' || (msg.channelType === 'discord' && this.config.channels.discord.streaming) || (msg.channelType === 'slack' && this.config.channels.slack.streaming);const tgChannel = this.channels.get('telegram');@@ -1276,19 +1713,29 @@ export class Agent {// Saver-mode-aware request limits. When saver is off these resolve to// the original constants (byte-identical to pre-saver behavior).const effectiveMaxOutputTokens = this.saverMode.adjustMaxOutputTokens(MAX_RESPONSE_TOKENS);- const effectiveMaxSteps = this.saverMode.adjustMaxSteps(MAX_STEPS);+ const effectiveMaxSteps = this.saverMode.adjustMaxSteps(MAX_STEPS) * this.researchMode.getMaxStepsMultiplier();const saverWasActive = this.saverMode.isActive();- for (const provider of fallbackIterator) {+ const providersForAttempt = [...fallbackIterator];+ for (const provider of [...providersForAttempt, ...providersForAttempt]) {try {+ const providerDeadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;this.markProgress(`Calling ${provider.name}...`);+ updateCliProviderStatus(this.channels.get('cli'), provider.name, provider.getModel());const deepseekProviderOptions = provider instanceof DeepSeekProvider && provider.isReasoner? { deepseek: { thinking: { type: 'enabled' as const } } }: undefined;logger.info({ provider: provider.name, model: provider.getModel(), steps: MAX_STEPS, stream: canStream }, 'Generating agentic response');+ // Ensure Mercury Cloud token is fresh before getting model instance+ if ('ensureFreshToken' in provider && typeof (provider as any).ensureFreshToken === 'function') {+ await this.withProviderDeadline((provider as any).ensureFreshToken(), loopAbortController, providerDeadlineAt);+ }+if (canStream && channel) {+ let streamError: unknown;+ let streamAborted = false;const streamResult = streamText({model: provider.getModelInstance(),system: systemPrompt,@@ -1297,6 +1744,12 @@ export class Agent {maxOutputTokens: effectiveMaxOutputTokens,stopWhen: stepCountIs(effectiveMaxSteps),abortSignal: loopAbortController.signal,+ onError: ({ error }) => {+ streamError = error;+ },+ onAbort: () => {+ streamAborted = true;+ },...(deepseekProviderOptions ? { providerOptions: deepseekProviderOptions } : {}),onStepFinish: async ({ toolCalls, toolResults }) => {this.completedStepCount++;@@ -1310,6 +1763,7 @@ export class Agent {this.markProgress('Thinking...');}if (toolCalls && toolResults && toolCalls.length > 0) {+ if (toolResults.length > 0) hasCompletedTool = true;const names = toolCalls.map((tc: any) => tc.toolName).join(', ');logger.info({ tools: names }, 'Tool call step');for (let i = 0; i < toolCalls.length; i++) {@@ -1544,37 +1998,40 @@ export class Agent {},});- let fullText: string;-- if (msg.channelType === 'telegram') {- const tgChannel = this.channels.get('telegram');- if (tgChannel && 'sendStreamToChat' in tgChannel) {- const chatId = msg.channelId.startsWith('telegram:')- ? Number(msg.channelId.split(':')[1])- : Number(msg.channelId);- if (!isNaN(chatId)) {- fullText = await (tgChannel as any).sendStreamToChat(chatId, this.withProgressStream(streamResult.textStream));- } else {- fullText = await channel.stream(this.withProgressStream(streamResult.textStream), msg.channelId);- }- } else {- fullText = await channel.stream(this.withProgressStream(streamResult.textStream), msg.channelId);+ const trackedStream = this.withProgressStream((async function* () {+ for await (const chunk of streamResult.textStream) {+ if (chunk) hasStreamedOutput = true;+ yield chunk;}- } else {- fullText = await channel.stream(this.withProgressStream(streamResult.textStream), msg.channelId);+ })());+ const streamedText = await this.withProviderDeadline(+ channel.stream(trackedStream, msg.channelId),+ loopAbortController,+ providerDeadlineAt,+ );+ cliResponseStreamed = channel instanceof CLIChannel;++ const [usage, finishReason, streamReasoning] = await this.withProviderDeadline(+ Promise.all([+ streamResult.usage,+ streamResult.finishReason,+ streamResult.reasoning,+ ]),+ loopAbortController,+ providerDeadlineAt,+ );+ if (streamError) throw streamError;+ if (streamAborted || finishReason === 'error') {+ throw new Error(streamAborted ? 'Model stream was aborted before completion' : 'Model stream ended with an error');}-- const [usage] = await Promise.all([- streamResult.usage,- ]);-- const streamReasoning = await streamResult.reasoning;+ const fullText = finishReason === 'length'+ ? `${streamedText}\n\n[Response truncated: the model reached its output limit. Ask me to continue from this point.]`+ : streamedText;result = { text: fullText, usage, reasoning: streamReasoning };- streamedText = fullText;loopDetector.recordStepText(fullText);} else {- result = await generateText({+ result = await this.withProviderDeadline(generateText({model: provider.getModelInstance(),system: systemPrompt,messages,@@ -1595,6 +2052,7 @@ export class Agent {this.markProgress('Thinking...');}if (toolCalls && toolResults && toolCalls.length > 0) {+ if (toolResults.length > 0) hasCompletedTool = true;const names = toolCalls.map((tc: any) => tc.toolName).join(', ');logger.info({ tools: names }, 'Tool call step');for (let i = 0; i < toolCalls.length; i++) {@@ -1827,47 +2285,132 @@ export class Agent {}}},- });+ }), loopAbortController, providerDeadlineAt);+ if (result.finishReason === 'error') throw new Error('Model generation ended with an error');+ if (result.finishReason === 'length') {+ result = { ...result, text: `${result.text}\n\n[Response truncated: the model reached its output limit. Ask me to continue from this point.]` };+ }+ if (channel instanceof CLIChannel) {+ await channel.send(result.text, msg.channelId, Date.now() - startTime);+ cliResponseStreamed = true;+ }}usedProvider = { name: provider.name, model: provider.getModel() };if (channel instanceof WebChannel) {(channel as WebChannel).sendProviderInfo(usedProvider.name, usedProvider.model, msg.channelId);}- this.providers.markSuccess(provider.name);+ if (!channelOverride) {+ this.providers.markSuccess(provider.name);+ }break;} catch (err: any) {+ if (this.currentAbortReason === 'time-limit') {+ lastError = new Error(`${provider.name} exceeded the 10-minute provider-attempt limit`);+ requiresContinuationApproval = true;+ this.currentAbortReason = null;+ logger.warn({ provider: provider.name }, 'Provider attempt reached hard deadline; waiting for user decision');+ break;+ }+ if (this.currentAbortReason === 'stalled' && !hasCompletedTool) {+ lastError = new Error(`${provider.name} stalled without progress`);+ this.currentAbortReason = null;+ loopAbortController = new AbortController();+ this.currentAbort = loopAbortController;+ this.markProgress(`Retrying after ${provider.name} stalled...`);+ logger.warn({ provider: provider.name }, 'Provider stalled; retrying with another healthy attempt');+ continue;+ }+ if (this.currentAbortReason === 'backgrounded') {+ result = { text: 'This task was moved to the background and will report back when it finishes.', usage: undefined };+ break;+ }if (loopDetector.isHardAborted() || loopAbortController.signal.aborted) {- logger.info('Generation aborted due to loop detection — using partial response');- if (!result && streamedText) {- result = { text: streamedText, usage: undefined };- }- if (!result) {- const elapsedMs = Date.now() - startTime;- const timedOut = elapsedMs >= MAX_FOREGROUND_WALL_MS;- result = {- text: timedOut- ? 'I stopped because this request exceeded the foreground time limit. Please retry with a narrower scope, or move it to background with /bg current sooner.'- : 'I stopped because I detected I was stuck in a loop (repeating the same action without progress). I cannot complete this task as requested. Please let me know if you\'d like me to try a completely different approach, or if there\'s something else I can help with.',- usage: undefined,- };- }- if (usedProvider) {- this.providers.markSuccess(usedProvider.name);- }+ lastError = new Error(hasCompletedTool+ ? 'Generation was interrupted after one or more tools completed. Current side effects may be partial; inspect state before retrying.'+ : 'Generation was aborted by progress or loop safety controls.');+ logger.info({ hasCompletedTool }, 'Generation aborted; recording an explicit failed state');break;}lastError = err;- logger.warn({ provider: provider.name, err: err.message }, 'Provider failed, trying fallback');- if (channel && msg.channelType !== 'internal') {- await channel.send(` [Provider ${provider.name} failed, trying fallback...]`, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ if (hasStreamedOutput) {+ lastError = new Error(`Provider stream was interrupted after partial output; refusing fallback to avoid combining two responses. Original error: ${err?.message || String(err)}`);+ logger.error({ provider: provider.name, err }, 'Provider stream interrupted after visible output; fallback suppressed');+ break;}+ if (hasCompletedTool) {+ lastError = new Error(`Provider failed after a tool completed; refusing fallback to avoid duplicate side effects. Original error: ${err?.message || String(err)}`);+ logger.error({ provider: provider.name, err }, 'Provider interrupted after tool completion; fallback suppressed');+ break;+ }+ logger.warn({ provider: provider.name, err: err.message }, 'Provider failed, trying fallback');+ await this.sendProgressNotice(msg, `Provider ${provider.name} failed. Trying fallback...`)+ .catch((e) => logger.warn({ e }, 'channel send failed'));}}if (!result) {- const errMsg = `All LLM providers failed. Last error: ${lastError?.message || 'unknown'}`;+ let errMsg = hasCompletedTool+ ? `Work stopped in an interrupted/ambiguous state to avoid repeating completed tool side effects. ${lastError?.message || ''}`.trim()+ : `All LLM providers failed. Last error: ${lastError?.message || 'unknown'}`;logger.error({ err: lastError }, errMsg);+ if (this.currentWorkKey && (hasCompletedTool || hasStreamedOutput || requiresContinuationApproval)) {+ const continuationAttempt = typeof msg.metadata?.continuationAttempt === 'number' ? msg.metadata.continuationAttempt : 0;+ const needsApproval = needsContinuationApproval(continuationAttempt, requiresContinuationApproval);+ if (needsApproval) {+ this.markProgress('Waiting for your decision...');+ const reason = requiresContinuationApproval+ ? 'The current provider attempt reached its 10-minute hard limit.'+ : `Mercury has already made ${continuationAttempt} automatic continuation attempts.`;+ const shouldContinue = channel && msg.channelType !== 'internal'+ ? await channel.askToContinue(+ `${reason} Existing files and completed tool work have been preserved. Continue with another inspected attempt?`,+ msg.channelId,+ ).catch(() => false)+ : false;+ if (!shouldContinue) {+ errMsg = `${reason} Work is paused with existing artifacts preserved. Send "continue" when you want Mercury to inspect the current state and resume.`;+ } else {+ const delayMs = this.scheduleDurableRetry(msg, this.currentWorkKey, lastError || errMsg, true);+ await this.sendProgressNotice(+ msg,+ `Progress remains checkpointed. Mercury will inspect the existing artifacts and continue in ${Math.round(delayMs / 1000)} seconds.`,+ ).catch((error) => logger.warn({ error }, 'Unable to send continuation notice'));+ this.lifecycle.transition('idle');+ return;+ }+ } else {+ const delayMs = this.scheduleDurableRetry(msg, this.currentWorkKey, lastError || errMsg, true);+ await this.sendProgressNotice(+ msg,+ `Progress was checkpointed. Mercury will inspect the existing artifacts and continue with a different approach in ${Math.round(delayMs / 1000)} seconds.`,+ ).catch((error) => logger.warn({ error }, 'Unable to send continuation notice'));+ this.lifecycle.transition('idle');+ return;+ }+ }+ if (this.currentWorkKey && !hasCompletedTool && !hasStreamedOutput && this.isRetryableProviderError(lastError)) {+ const attempts = this.workLedger.get(this.currentWorkKey)?.attempts ?? 1;+ const shouldContinue = !needsRetryApproval(attempts) || (+ channel && msg.channelType !== 'internal'+ ? await channel.askToContinue(+ `All providers have failed ${attempts} attempts. No tool side effects were recorded. Retry again?`,+ msg.channelId,+ ).catch(() => false)+ : false+ );+ if (shouldContinue) {+ const delayMs = this.scheduleDurableRetry(msg, this.currentWorkKey, lastError);+ await this.sendProgressNotice(+ msg,+ `All providers are temporarily unavailable. This request is safely queued and will retry in ${Math.round(delayMs / 1000)} seconds.`,+ ).catch((error) => logger.warn({ error }, 'Unable to send durable retry notice'));+ this.lifecycle.transition('idle');+ return;+ }+ errMsg = `All providers failed ${attempts} attempts. Work is paused. Send "continue" when you want Mercury to try again.`;+ }+ if (this.currentWorkKey) this.workLedger.markFailed(this.currentWorkKey, errMsg, errMsg);if (channel && msg.channelType !== 'internal') {// End task before sending error so it goes through as a normal messageif (channel instanceof TelegramChannel) {@@ -1883,13 +2426,19 @@ export class Agent {(channel as SlackChannel).endTask(msg.channelId);(channel as SlackChannel).resetStepCounter(msg.channelId);}- await channel.send(errMsg, msg.channelId);+ const delivered = channel instanceof WebChannel ? channel.sendError(errMsg, msg.channelId) : true;+ if (!(channel instanceof WebChannel)) await channel.send(errMsg, msg.channelId);+ const awaitsCloudAck = msg.channelType === 'web'+ && typeof msg.metadata?.externalConversationId === 'string'+ && typeof msg.metadata?.requestId === 'string';+ if (this.currentWorkKey && delivered && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);+ if (this.currentWorkKey && !delivered) this.workLedger.markDeliveryError(this.currentWorkKey, 'Terminal error delivery was not accepted');}this.lifecycle.transition('idle');return;}- const finalText = (streamedText || result.text || '').trim() || '(no text response)';+ const finalText = (result.text || '').trim() || '(no text response)';this.markProgress('Finalizing response...');// Store plan output when in plan mode for later execution@@ -1905,6 +2454,7 @@ export class Agent {outputTokens: result.usage?.outputTokens ?? 0,totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),channelType: msg.channelType,+ agentId: this.config.cloud.agentId || undefined,});this.syncTokenInfoToCli();@@ -1924,21 +2474,33 @@ export class Agent {}}- this.shortTerm.add(msg.channelId, {- id: msg.id,- timestamp: msg.timestamp,- role: 'user',- content: msg.content,- });-- this.shortTerm.add(msg.channelId, {- id: Date.now().toString(36),- timestamp: Date.now(),- role: 'assistant',- content: finalText,- tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),- reasoning: result.reasoning || undefined,- });+ if (canonicalSessionId) {+ this.sessions.appendMessage(canonicalSessionId, {+ role: 'assistant',+ content: finalText,+ externalMessageId: `${msg.id}:assistant`,+ tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ reasoning: typeof result.reasoning === 'string'+ ? result.reasoning+ : result.reasoning+ ? JSON.stringify(result.reasoning)+ : undefined,+ metadata: {+ channelType: msg.channelType,+ channelId: msg.channelId,+ ...(typeof msg.metadata?.requestId === 'string' ? { requestId: msg.metadata.requestId } : {}),+ },+ });+ if (msg.channelType !== 'internal' && msg.senderId !== 'system' && usedProvider) {+ this.scheduleSessionTitleGeneration(canonicalSessionId, usedProvider.name);+ }+ } else {+ this.shortTerm.add(msg.channelId, { id: msg.id, timestamp: msg.timestamp, role: 'user', content: msg.content });+ this.shortTerm.add(msg.channelId, {+ id: Date.now().toString(36), timestamp: Date.now(), role: 'assistant', content: finalText,+ tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0), reasoning: result.reasoning || undefined,+ });+ }this.episodic.record({type: 'message',@@ -1952,6 +2514,8 @@ export class Agent {});}+ if (this.currentWorkKey) this.workLedger.markCompleted(this.currentWorkKey, finalText);+if (channel && msg.channelType !== 'internal') {const elapsed = Date.now() - startTime;const stepCount = this.completedStepCount;@@ -1960,7 +2524,12 @@ export class Agent {// Simple responses (greetings, quick answers) don't need a bannerconst isSubstantialTask = stepCount >= 3 && elapsed >= 30_000;if (isSubstantialTask && channel instanceof TelegramChannel) {- // For substantial Telegram tasks: sendCompletion handles endTask + deferred flush + cleanup+ // For substantial Telegram tasks: sendCompletion handles endTask + deferred flush + cleanup.+ // Always queue the final answer explicitly; streaming normally already+ // defers it, but non-streamed/fallback responses must not be dropped.+ if (finalText && finalText.trim()) {+ (channel as TelegramChannel).deferResponse(msg.channelId, finalText);+ }const completionMeta = {provider: usedProvider?.name ?? 'unknown',model: usedProvider?.model ?? 'unknown',@@ -1971,17 +2540,13 @@ export class Agent {budgetTotal: this.tokenBudget.getBudget(),budgetPercentage: this.tokenBudget.getUsagePercentage(),};- // If there's a non-streamed response that wasn't deferred, defer it now- if (!streamedText && finalText && finalText.trim()) {- // send() during active task already deferred it — nothing to do- }await (channel as TelegramChannel).sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);} else if (channel instanceof TelegramChannel) {// For non-substantial Telegram tasks: end task, flush deferred, clean up(channel as TelegramChannel).endTask(msg.channelId);// Flush deferred responseconst deferred = (channel as TelegramChannel).popDeferredResponse(msg.channelId);- const responseText = deferred || (!streamedText && finalText ? finalText : null);+ const responseText = deferred || finalText;if (responseText && responseText.trim()) {await channel.send(responseText, msg.channelId, elapsed);}@@ -1994,6 +2559,7 @@ export class Agent {// For Signal tasks: end task, flush deferred, send completion banner for substantial tasksconst sigCh = channel as SignalChannel;if (isSubstantialTask) {+ await sigCh.stream((async function* () { yield finalText; })(), msg.channelId);const completionMeta = {provider: usedProvider?.name ?? 'unknown',model: usedProvider?.model ?? 'unknown',@@ -2008,7 +2574,7 @@ export class Agent {} else {sigCh.endTask(msg.channelId);const deferred = sigCh.popDeferredResponse(msg.channelId);- const responseText = deferred || (!streamedText && finalText ? finalText : null);+ const responseText = deferred || finalText;if (responseText && responseText.trim()) {await channel.send(responseText, msg.channelId, elapsed);}@@ -2018,6 +2584,7 @@ export class Agent {} else if (channel instanceof DiscordChannel) {const dcCh = channel as DiscordChannel;if (isSubstantialTask) {+ await dcCh.stream((async function* () { yield finalText; })(), msg.channelId);const completionMeta = {provider: usedProvider?.name ?? 'unknown',model: usedProvider?.model ?? 'unknown',@@ -2032,7 +2599,7 @@ export class Agent {} else {dcCh.endTask(msg.channelId);const deferred = dcCh.popDeferredResponse(msg.channelId);- const responseText = deferred || (!streamedText && finalText ? finalText : null);+ const responseText = deferred || finalText;if (responseText && responseText.trim()) {await channel.send(responseText, msg.channelId, elapsed);}@@ -2042,6 +2609,7 @@ export class Agent {} else if (channel instanceof SlackChannel) {const slCh = channel as SlackChannel;if (isSubstantialTask) {+ await slCh.stream((async function* () { yield finalText; })(), msg.channelId);const completionMeta = {provider: usedProvider?.name ?? 'unknown',model: usedProvider?.model ?? 'unknown',@@ -2056,7 +2624,7 @@ export class Agent {} else {slCh.endTask(msg.channelId);const deferred = slCh.popDeferredResponse(msg.channelId);- const responseText = deferred || (!streamedText && finalText ? finalText : null);+ const responseText = deferred || finalText;if (responseText && responseText.trim()) {await channel.send(responseText, msg.channelId, elapsed);}@@ -2065,17 +2633,11 @@ export class Agent {}} else {// CLI or other channels — original flow- if (streamedText && streamedText.trim()) {- logger.info({ channelType: msg.channelType, elapsed }, 'Streamed response completed');- // Web channel needs text_done after streaming to reset frontend state- if (channel instanceof WebChannel) {- await channel.send(streamedText, msg.channelId, elapsed);- }- } else {- logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');+ logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending durable response');+ if (requiresFinalSend(msg.channelType, cliResponseStreamed)) {await channel.send(finalText, msg.channelId, elapsed);- this.markProgress();}+ this.markProgress();if (isSubstantialTask && channel instanceof CLIChannel) {const completionMeta = {provider: usedProvider?.name ?? 'unknown',@@ -2094,18 +2656,48 @@ export class Agent {logger.debug('Internal prompt processed, no channel response needed');}+ const awaitsCloudAck = msg.channelType === 'web'+ && typeof msg.metadata?.externalConversationId === 'string'+ && typeof msg.metadata?.requestId === 'string';+ if (this.currentWorkKey && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);+this.lifecycle.transition('idle');} catch (err) {logger.error({ err }, 'Error handling message');+ const ledgerEntry = this.currentWorkKey ? this.workLedger.get(this.currentWorkKey) : undefined;+ if (this.currentWorkKey) {+ if (ledgerEntry?.status === 'completed') this.workLedger.markDeliveryError(this.currentWorkKey, err);+ else if (ledgerEntry?.status !== 'failed') {+ const errMsg = err instanceof Error ? err.message : String(err);+ this.workLedger.markFailed(+ this.currentWorkKey,+ err,+ `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`,+ );+ }+ }+ if (ledgerEntry?.status === 'completed') {+ logger.warn({ err, workKey: this.currentWorkKey }, 'Final response persisted but delivery did not complete; retaining for replay');+ return;+ }// Always notify the user — they should never have to re-prompt// to find out their task died.const catchChannel = this.channels.getChannelForMessage(msg);if (catchChannel && msg.channelType !== 'internal') {const errMsg = err instanceof Error ? err.message : String(err);- void catchChannel.send(- `⚠ I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`,- msg.channelId,- ).catch((sendErr: any) => logger.warn({ sendErr }, 'Failed to notify user of handler error'));+ try {+ const finalError = `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`;+ const delivered = catchChannel instanceof WebChannel ? catchChannel.sendError(finalError, msg.channelId) : true;+ if (!(catchChannel instanceof WebChannel)) await catchChannel.send(finalError, msg.channelId);+ const awaitsCloudAck = msg.channelType === 'web'+ && typeof msg.metadata?.externalConversationId === 'string'+ && typeof msg.metadata?.requestId === 'string';+ if (this.currentWorkKey && delivered && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);+ if (this.currentWorkKey && !delivered) this.workLedger.markDeliveryError(this.currentWorkKey, 'Terminal error delivery was not accepted');+ } catch (sendErr) {+ if (this.currentWorkKey) this.workLedger.markDeliveryError(this.currentWorkKey, sendErr);+ logger.warn({ sendErr }, 'Failed to notify user of handler error');+ }}// Write crash flag so next startup also reports the failure.try {@@ -2120,14 +2712,15 @@ export class Agent {} catch { /* best effort */ }this.lifecycle.transition('idle');} finally {- if (wallTimeout) clearTimeout(wallTimeout);stopHeartbeat();+ this.finalizeChannelTask(msg);this.currentMessage = null;this.currentAbort = null;+ this.currentAbortReason = null;this.currentActivity = '';this.completedStepCount = 0;this.stepNarrative = [];- if (isInternal || isScheduled) {+ if (isInternal) {this.capabilities.permissions.setAutoApproveAll(false);}this.capabilities.permissions.clearElevation();@@ -2144,6 +2737,10 @@ export class Agent {if (programmingSuffix) {prompt += programmingSuffix;}+ const researchSuffix = this.researchMode.getSystemPromptSuffix();+ if (researchSuffix) {+ prompt += researchSuffix;+ }const budgetStatus = this.tokenBudget.getStatusText();prompt += '\n\n' + budgetStatus;if (this.tokenBudget.getUsagePercentage() > 70) {@@ -2341,7 +2938,7 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub usermodel: provider.getModelInstance(),system: `You extract structured memory from conversations. Output a JSON array of 0-3 memory candidates.-Each candidate: { type, summary (concise fact, 12-220 chars), detail (optional explanation), evidenceKind ("direct" if explicitly stated, "inferred" if deduced), confidence (0-1), importance (0-1), durability (0-1) }+Each candidate: { type, categories, summary (concise fact, 12-220 chars), detail (optional explanation), evidenceKind ("direct" if explicitly stated, "inferred" if deduced), confidence (0-1), importance (0-1), durability (0-1) }TYPE DEFINITIONS (pick the single most specific one):- identity: who the user IS — their name, role, job title, self-description@@ -2354,6 +2951,18 @@ TYPE DEFINITIONS (pick the single most specific one):- constraint: limitations, rules they follow, things they avoid- episode: notable one-time events worth remembering+CATEGORIES (pick 1-3 domain buckets that best fit this memory):+- personal: the user's private life, non-work+- health: medical, physical, mental wellbeing+- family: family members, family relationships+- work: job, professional, career+- finance: money, spending, investments+- technical: programming, tools, engineering+- education: learning, study, courses+- social: friends, social life, community+- travel: trips, places, geography+- general: anything that doesn't fit the above+RULES:- Each semantic fact must appear EXACTLY ONCE. Never store the same information under multiple types.- If a fact is about someone else's role/relationship to the user, use "relationship" (not "identity").@@ -2361,6 +2970,7 @@ RULES:- For relationships, always name the person: "Salman is user's co-developer" not "User works with a co-developer".- Only extract specific, durable, user-specific information.- Do NOT extract trivial observations, greetings, or assistant behavior.+- "categories" must be an array of 1-3 lowercase strings from the list above. If none fit, suggest a new single-word lowercase category.- Output pure JSON array, no markdown fences.`,messages: [{ role: 'user', content: `User: ${userMessage}\nAssistant: ${agentResponse}` },@@ -2375,6 +2985,7 @@ RULES:outputTokens: result.usage?.outputTokens ?? 0,totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),channelType: 'internal',+ agentId: this.config.cloud.agentId || undefined,});this.syncTokenInfoToCli();@@ -2383,6 +2994,7 @@ RULES:let candidates: Array<{type: string;+ categories?: string[];summary: string;detail?: string;evidenceKind?: string;@@ -2404,6 +3016,7 @@ RULES:.filter(f => f.length > 10 && f.length < 200 && !/^["{\[\]}]|":\s*"/.test(f));candidates = facts.slice(0, 3).map(f => ({type: 'preference',+ categories: ['general'],summary: f,confidence: 0.75,importance: 0.7,@@ -2416,15 +3029,27 @@ RULES:const typed = candidates.filter(c => c.summary && c.summary.length >= 12 && c.summary.length <= 220).filter(c => validTypes.includes(c.type))- .map(c => ({- type: c.type as any,- summary: c.summary,- detail: c.detail,- evidenceKind: (c.evidenceKind === 'direct' ? 'direct' : 'inferred') as 'direct' | 'inferred',- confidence: Math.min(1, Math.max(0, c.confidence ?? 0.7)),- importance: Math.min(1, Math.max(0, c.importance ?? 0.7)),- durability: Math.min(1, Math.max(0, c.durability ?? 0.7)),- }));+ .map(c => {+ // Normalise categories: must be array of strings, 1-3, lowercase, trimmed.+ let cats: string[] = ['general'];+ if (Array.isArray(c.categories) && c.categories.length > 0) {+ const cleaned = c.categories+ .map((cat: unknown) => String(cat).trim().toLowerCase())+ .filter((cat: string) => cat.length > 0)+ .slice(0, 3);+ if (cleaned.length > 0) cats = cleaned;+ }+ return {+ type: c.type as any,+ categories: cats,+ summary: c.summary,+ detail: c.detail,+ evidenceKind: (c.evidenceKind === 'direct' ? 'direct' : 'inferred') as 'direct' | 'inferred',+ confidence: Math.min(1, Math.max(0, c.confidence ?? 0.7)),+ importance: Math.min(1, Math.max(0, c.importance ?? 0.7)),+ durability: Math.min(1, Math.max(0, c.durability ?? 0.7)),+ };+ });if (typed.length > 0) {const remembered = this.userMemory.remember(typed, 'conversation');@@ -2442,6 +3067,7 @@ RULES:await this.supervisor.haltAll();}this.backgroundTasks.destroy();+ this.providers.destroy();await this.sleep();logger.info('Mercury has shut down');}@@ -2543,50 +3169,26 @@ Is this productive iteration or a stuck loop?`,return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);}- if (channelType === 'telegram' && channel instanceof TelegramChannel) {- const { InlineKeyboard } = await import('grammy');- const kb = new InlineKeyboard();- for (let i = 0; i < choices.length; i++) {- const callbackData = `choice_${Date.now()}_${i}`;- kb.text(choices[i].slice(0, 60), callbackData);- if (i < choices.length - 1 && (i + 1) % 2 === 0) {- kb.row();- }- }+ if (channelType === 'web' && channel instanceof WebChannel) {+ const options = choices.map((label, i) => ({+ value: String(i),+ label,+ }));- return new Promise<string>((resolve) => {- const timeout = setTimeout(() => {- (channel as any).pendingApprovals?.delete(`choice_timeout_${question}`);- resolve(choices[0]);- }, 120000);-- channel.send(question, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));-- const tgBot = (channel as any).bot;- if (tgBot) {- const chatId = channelId.startsWith('telegram:')- ? Number(channelId.split(':')[1])- : Number(channelId);-- tgBot.api.sendMessage(chatId, question, { reply_markup: kb }).catch((e: any) => logger.warn({ e }, 'channel send failed'));-- const handler = async (ctx: any) => {- const data = ctx.callbackQuery?.data;- if (!data || !data.startsWith('choice_')) return;- const parts = data.split('_');- if (parts.length < 3) return;- const index = parseInt(parts[2], 10);- if (isNaN(index)) return;- clearTimeout(timeout);- try { await ctx.answerCallbackQuery(); } catch {}- resolve(choices[index]);- };+ const selected = await channel.presentChoicePrompt(question, options, channelId);+ const index = parseInt(selected, 10);+ return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);+ }- if ((channel as any).pendingCallbacks) {- (channel as any).pendingCallbacks.push(handler);- }- }- });+ if (channelType === 'telegram' && channel instanceof TelegramChannel) {+ const options = choices.map((label, i) => ({+ value: String(i),+ label,+ }));++ const selected = await channel.presentChoicePrompt(question, options, channelId);+ const index = parseInt(selected, 10);+ return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);}await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));@@ -2974,6 +3576,11 @@ Is this productive iteration or a stuck loop?`,const ctx = this.capabilities.getChatCommandContext();if (!ctx) return false;+ if (cmd === '/sessions' || cmd.startsWith('/session')) {+ await this.handleSessionCommand(trimmed, channelType as ChannelType, channelId);+ return true;+ }+if (cmd === '/help') {const helpText = channelType === 'telegram' ? getTelegramHelp() : channelType === 'discord' ? getDiscordHelp() : channelType === 'slack' ? getSlackHelp() : ctx.manual();await channel.send(helpText, channelId);@@ -3111,6 +3718,146 @@ Is this productive iteration or a stuck loop?`,return true;}+ if (cmd === '/cloud' || cmd.startsWith('/cloud ')) {+ const cfg = ctx.config();+ if (!cfg.cloud.enabled || !cfg.cloud.jwt) {+ await channel.send('Mercury Cloud is not connected. Run `mercury cloud connect` to set it up.', channelId);+ return true;+ }++ const sub = trimmed.slice('/cloud'.length).trim();++ const ensureFreshToken = async (): Promise<string> => {+ try {+ const store = getCloudTokenStore();+ if (store) {+ return await store.rotateIfExpired();+ }+ const parts = cfg.cloud.jwt.split('.');+ if (parts.length === 3) {+ const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());+ const exp = payload.exp * 1000;+ if (Date.now() > exp - 60_000 && cfg.cloud.refreshToken) {+ const { refreshToken } = await import('../cloud/pairing.js');+ const result = await refreshToken(cfg.cloud.apiUrl, cfg.cloud.refreshToken);+ cfg.cloud.jwt = result.jwt;+ cfg.cloud.refreshToken = result.refreshToken;+ cfg.providers.mercuryCloud.apiKey = result.jwt;+ const { saveConfig } = await import('../utils/config.js');+ saveConfig(cfg);+ this.config = cfg;+ return result.jwt;+ }+ }+ } catch {}+ return cfg.cloud.jwt;+ };++ if (!sub || sub === 'models' || sub === 'model') {+ try {+ const jwt = await ensureFreshToken();+ const res = await fetch(`${cfg.cloud.apiUrl}/v1/models`, {+ headers: { Authorization: `Bearer ${jwt}` },+ });+ if (!res.ok) {+ await channel.send(`Failed to fetch cloud models (HTTP ${res.status}). Your token may have expired — run \`mercury cloud login\`.`, channelId);+ return true;+ }+ const data = await res.json() as { data: Array<{ id: string; label: string; tier_required: string; context_window: number; available: boolean; is_branded?: boolean; discount_percent?: number }> };+ const models = data.data || [];+ if (models.length === 0) {+ await channel.send('No models available.', channelId);+ return true;+ }++ const currentModel = cfg.providers.mercuryCloud?.model || '—';+ const branded = models.filter((m) => m.is_branded);+ const raw = models.filter((m) => !m.is_branded);++ const formatModel = (m: typeof models[0]) => {+ const marker = m.id === currentModel ? ' ← current' : '';+ const lock = m.available ? '' : ' 🔒';+ const discount = m.discount_percent && m.discount_percent > 0 ? ` (${m.discount_percent}% off input)` : '';+ return `• ${m.id} · ${m.label} (${m.tier_required})${discount}${lock}${marker}`;+ };++ const lines = [+ '**Mercury Cloud Models**',+ '',+ '**Mercury Branded**',+ ...branded.map(formatModel),+ '',+ '**Direct Models**',+ ...raw.map(formatModel),+ '',+ 'Use `/cloud use <model-id>` to switch.',+ ];+ await channel.send(lines.join('\n'), channelId);++ if (channelType === 'cli' && channel instanceof CLIChannel) {+ const availableModels = models.filter((m) => m.available);+ const choices = [+ ...availableModels.map((m) => `${m.id} · ${m.label}${m.id === currentModel ? ' (current)' : ''}`),+ 'Keep current model',+ ];+ if (availableModels.length <= 1) {+ await channel.send('Only one model available for your tier. Upgrade to unlock more.', channelId);+ return true;+ }+ const picked = await this.presentChoice('Switch cloud model?', choices, channelId, channelType);+ if (picked === 'Keep current model') return true;+ const modelId = picked.split(' · ')[0].trim();+ if (modelId) {+ cfg.providers.mercuryCloud.model = modelId;+ cfg.providers.mercuryCloud.enabled = true;+ cfg.providers.default = 'mercuryCloud';+ const { saveConfig } = await import('../utils/config.js');+ saveConfig(cfg);+ this.config = cfg;+ const provider = await createProvider(cfg.providers.mercuryCloud, getCloudTokenStore());+ this.providers.set('mercuryCloud', provider);+ this.providers.setDefault('mercuryCloud');+ updateCliProviderStatus(this.channels.get('cli'), 'mercuryCloud', modelId);+ await channel.send(`✓ Switched to **${modelId}**. Saved to config.`, channelId);+ }+ }+ } catch (err) {+ await channel.send(`Error fetching cloud models: ${(err as Error).message}`, channelId);+ }+ return true;+ }++ if (sub.startsWith('use ')) {+ const modelId = sub.slice(4).trim();+ if (!modelId) {+ await channel.send('Usage: `/cloud use <model-id>`', channelId);+ return true;+ }+ await ensureFreshToken();+ try {+ cfg.providers.mercuryCloud.model = modelId;+ cfg.providers.mercuryCloud.enabled = true;+ if (cfg.providers.default !== 'mercuryCloud') {+ cfg.providers.default = 'mercuryCloud';+ }+ const { saveConfig } = await import('../utils/config.js');+ saveConfig(cfg);+ this.config = cfg;+ const provider = await createProvider(cfg.providers.mercuryCloud, getCloudTokenStore());+ this.providers.set('mercuryCloud', provider);+ this.providers.setDefault('mercuryCloud');+ updateCliProviderStatus(this.channels.get('cli'), 'mercuryCloud', modelId);+ await channel.send(`✓ Switched to **${modelId}**. Saved to config.`, channelId);+ } catch (err) {+ await channel.send(`Error switching model: ${(err as Error).message}`, channelId);+ }+ return true;+ }++ await channel.send('Usage: `/cloud models` to list, `/cloud use <model-id>` to switch', channelId);+ return true;+ }+if (cmd === '/memory') {if (!this.userMemory) {const cfg = ctx.config();@@ -3127,6 +3874,12 @@ Is this productive iteration or a stuck loop?`,return true;}+ const choiceChannel = channel as typeof channel & { presentChoicePrompt?: (question: string, options: ArrowSelectOption[], targetId?: string) => Promise<string> };+ if (typeof choiceChannel.presentChoicePrompt === 'function') {+ await this.openMemoryChoiceMenu(choiceChannel, channelId);+ return true;+ }+await this.sendMemoryOverview(channel, channelId);return true;}@@ -3757,6 +4510,61 @@ Is this productive iteration or a stuck loop?`,return true;}+ if (cmd.startsWith('/research')) {+ const rawArgs = trimmed.slice('/research'.length).trim();++ if (!rawArgs || rawArgs.toLowerCase() === 'status') {+ await channel.send(this.researchMode.getStatusText(), channelId);+ return true;+ }++ if (rawArgs.toLowerCase() === 'on') {+ this.researchMode.setOn();+ await channel.send(+ 'Research mode: **On**\nI will perform deep, multi-source web research and produce a full markdown research article. Long tasks are expected. Use `/research off` to exit.',+ channelId,+ );+ return true;+ }++ if (rawArgs.toLowerCase() === 'off') {+ this.researchMode.setOff();+ await channel.send('Research mode: **Off**\nBack to normal conversation mode.', channelId);+ return true;+ }++ if (rawArgs.toLowerCase() === 'toggle') {+ const newState = this.researchMode.toggle();+ await channel.send(`Research mode: **${newState === 'on' ? 'On' : 'Off'}**`, channelId);+ return true;+ }++ // Treat remaining args as a topic + enable research mode+ this.researchMode.setOn(rawArgs);+ if (channel instanceof WebChannel) {+ channel.sendHeartbeat(`Research mode: On. Topic: ${rawArgs}. I will gather live sources and produce a full research article.`, channelId);+ } else {+ await channel.send(+ `Research mode: **On**\nTopic: ${rawArgs}\nI will gather live sources and produce a full research article. Use \`/research off\` to exit.`,+ channelId,+ );+ }+ // Enqueue the topic as a real user message so the agent immediately+ // begins researching it, rather than only setting mode + topic and+ // waiting for the user to repeat themselves.+ const researchTopicMsg: ChannelMessage = {+ id: `research-${Date.now().toString(36)}`,+ channelId,+ channelType: channelType as ChannelType,+ senderId: 'user',+ senderName: 'You',+ content: rawArgs,+ timestamp: Date.now(),+ };+ this.enqueueMessage(researchTopicMsg);+ return true;+ }+if (cmd.startsWith('/ws') || cmd.startsWith('/workspace')) {const cliChannel = channelType === 'cli' && channel instanceof CLIChannel ? channel : null;if (!cliChannel) {@@ -4216,6 +5024,122 @@ Is this productive iteration or a stuck loop?`,return false;}+ private async handleSessionCommand(content: string, channelType: ChannelType, channelId: string): Promise<void> {+ const channel = this.channels.get(channelType);+ if (!channel) return;+ const bindingId = channelType === 'cli' ? 'current' : channelId;+ const format = (session: { alias: string; shortId: string; title: string }) => `${session.alias} [${session.shortId}] ${session.title}`;+ const transcript = (session: ReturnType<SessionRepository['get']>) => {+ const recent = session.messages+ .filter((message) => message.kind === 'message' && (message.role === 'user' || message.role === 'assistant'))+ .slice(-8);+ if (recent.length === 0) return 'No messages yet.';+ return recent.map((message) => {+ const label = message.role === 'user' ? 'You' : 'Mercury';+ const text = message.content.replace(/\s+/g, ' ').trim();+ return `${label}: ${text.length > 280 ? `${text.slice(0, 277)}...` : text}`;+ }).join('\n');+ };+ const syncCliSession = (session: ReturnType<SessionRepository['get']>) => {+ if (channelType === 'cli' && channel instanceof CLIChannel) channel.setCurrentSession(session);+ };+ try {+ if (content.trim().toLowerCase() === '/sessions') {+ const current = this.sessions.getByBinding(channelType, bindingId);+ const sessions = this.sessions.list();+ await channel.send(sessions.length+ ? sessions.map((session) => `${session.id === current?.id ? '*' : ' '} ${format(session)}`).join('\n')+ : 'No active sessions. Use /session new.', channelId);+ return;+ }+ const argument = content.trim().slice('/session'.length).trim();+ if (argument.toLowerCase() === 'new') {+ const session = this.sessions.create();+ this.sessions.bind(session.id, channelType, bindingId);+ syncCliSession(session);+ await channel.send(`New session: ${format(session)}`, channelId);+ return;+ }+ if (!argument || argument.toLowerCase() === 'current') {+ const current = this.sessions.getByBinding(channelType, bindingId);+ await channel.send(current ? `Current session: ${format(current)}\n\n${transcript(current)}` : 'No current session. Use /session new.', channelId);+ return;+ }+ if (argument.toLowerCase().startsWith('delete ')) {+ const session = this.sessions.resolve(argument.slice('delete '.length).trim());+ const wasCurrent = this.sessions.getByBinding(channelType, bindingId)?.id === session.id;+ const confirmed = await channel.askToContinue(+ `Permanently delete ${format(session)} and all ${session.messages.length} messages everywhere? This cannot be undone.`,+ channelId,+ );+ if (!confirmed) {+ await channel.send('Session deletion cancelled.', channelId);+ return;+ }+ if (this.sessionSyncEnabled) this.sessions.markDeleted(session.id);+ else this.sessions.deletePermanently(session.id);+ const replacement = wasCurrent ? this.sessions.create({ binding: { channelType, externalConversationId: bindingId } }) : null;+ if (replacement) syncCliSession(replacement);+ await channel.send(+ `Deleted session ${session.alias} [${session.shortId}].${this.sessionSyncEnabled ? ' Cloud deletion is queued.' : ''}${replacement ? ` New session: ${format(replacement)}` : ''}`,+ channelId,+ );+ return;+ }+ if (argument.toLowerCase().startsWith('archive ')) {+ const session = this.sessions.archive(argument.slice('archive '.length).trim());+ await channel.send(`Archived: ${format(session)}`, channelId);+ return;+ }+ let session;+ try {+ session = this.sessions.resolve(argument);+ } catch (error) {+ if (channelType !== 'web' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(argument)) throw error;+ session = this.sessions.create({ id: argument });+ }+ this.sessions.bind(session.id, channelType, bindingId);+ syncCliSession(session);+ await channel.send(`Switched session: ${format(session)}\n\n${transcript(session)}`, channelId);+ } catch (error) {+ const message = error instanceof SessionResolutionError ? error.message : error instanceof Error ? error.message : String(error);+ await channel.send(message, channelId);+ }+ }++ private scheduleSessionTitleGeneration(sessionId: string, providerName: string): void {+ if (!this.generateTitle || this.titleGenerationInFlight.has(sessionId)) return;+ const session = this.sessions.get(sessionId);+ const exchange = session.messages.filter((message) => message.kind === 'message' && (message.role === 'user' || message.role === 'assistant'));+ if (session.titleSource !== 'fallback' || exchange.length !== 2 || exchange[0].role !== 'user' || exchange[1].role !== 'assistant') return;+ this.titleGenerationInFlight.add(sessionId);+ const timer = setTimeout(() => {+ void this.generateSessionTitle(sessionId, exchange[0].content, exchange[1].content, providerName).finally(() => {+ this.titleGenerationInFlight.delete(sessionId);+ });+ }, 0);+ timer.unref?.();+ }++ private async generateSessionTitle(sessionId: string, userMessage: string, assistantMessage: string, providerName: string): Promise<void> {+ try {+ const rawTitle = await this.generateTitle!({ userMessage, assistantMessage, providerName });+ const title = normalizeGeneratedSessionTitle(rawTitle);+ if (!title) {+ logger.debug({ sessionId }, 'Session title generator returned an unusable title');+ return;+ }+ if (this.sessions.get(sessionId).titleSource !== 'fallback') return;+ const session = this.sessions.updateTitle(sessionId, title, 'generated');+ const currentCliSession = this.sessions.getByBinding('cli', 'current');+ const cliChannel = this.channels.get('cli');+ if (currentCliSession?.id === session.id && cliChannel instanceof CLIChannel) cliChannel.setCurrentSession(session);+ logger.info({ sessionId, title }, 'Generated canonical session title');+ } catch (error) {+ logger.debug({ sessionId, err: error instanceof Error ? error.message : String(error) }, 'Background session title generation failed');+ }+ }+private async handleWorkspaceNaturalLanguage(content: string, channelType: string, channelId: string): Promise<boolean> {const channel = this.channels.get(channelType as any);if (!channel || channelType !== 'cli' || !(channel instanceof CLIChannel)) return false;@@ -4320,10 +5244,13 @@ Is this productive iteration or a stuck loop?`,private async sendMemoryOverview(channel: any, channelId: string): Promise<void> {if (!this.userMemory) return;const summary = this.userMemory.getSummary();+ const shareableCount = this.userMemory.countShareable();+ const shareLearning = this.userMemory.isShareLearning();const lines = [`**Memory Overview**`,`Total memories: ${summary.total}`,`Learning: ${summary.learningPaused ? 'PAUSED' : 'ACTIVE'}`,+ `Shared learning: ${shareLearning ? 'ON' : 'OFF'} (${shareableCount} shareable)`,];if (summary.profileSummary) {lines.push(`Profile: ${summary.profileSummary}`);@@ -4348,11 +5275,14 @@ Is this productive iteration or a stuck loop?`,const runMenu = async (sel: (title: string, options: ArrowSelectOption[]) => Promise<string>) => {while (true) {const learningLabel = this.userMemory!.isLearningPaused() ? 'Resume Learning' : 'Pause Learning';+ const shareLabel = this.userMemory!.isShareLearning() ? 'Shared Learning: ON' : 'Shared Learning: OFF';const action = await sel('Memory', [{ value: 'overview', label: 'Overview' },{ value: 'recent', label: 'Recent Memories' },+ { value: 'shared', label: 'Shared Memories' },{ value: 'search', label: 'Search' },{ value: 'toggle', label: learningLabel },+ { value: 'share', label: shareLabel },{ value: 'clear', label: 'Clear All Memories' },{ value: 'back', label: 'Back' },]);@@ -4381,6 +5311,23 @@ Is this productive iteration or a stuck loop?`,continue;}+ if (action === 'shared') {+ const shared = this.userMemory!.getShareable(20);+ if (shared.length === 0) {+ await channel.send('No shared memories yet. Enable shared learning to mark new memories as shareable for cloud fetch.', channelId);+ continue;+ }+ const lines = [`**Shared Memories (${shared.length}):**`, ''];+ for (const r of shared) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ const cats = r.categories.length > 0 ? ` {${r.categories.join(', ')}}` : '';+ lines.push(`${scope} [${r.type}]${cats} ${r.summary}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${r.evidenceKind} | Seen: ${r.evidenceCount}x`);+ }+ await channel.send(lines.join('\n'), channelId);+ continue;+ }+if (action === 'search') {const query = await channel.prompt('Search memories: ');if (!query) continue;@@ -4406,6 +5353,23 @@ Is this productive iteration or a stuck loop?`,continue;}+ if (action === 'share') {+ const currently = this.userMemory!.isShareLearning();+ this.userMemory!.setShareLearning(!currently);+ const cfg = loadConfig();+ if (!cfg.memory.collaborativeKnowledge) cfg.memory.collaborativeKnowledge = {};+ cfg.memory.collaborativeKnowledge.shareLearning = !currently;+ saveConfig(cfg);+ const count = this.userMemory!.countShareable();+ await channel.send(+ currently+ ? `Shared learning disabled. New memories will stay private. (${count} memories already shareable are unchanged.)`+ : `Shared learning enabled. New memories will be marked shareable for cloud fetch. (${count} memories currently shareable.)`,+ channelId,+ );+ continue;+ }+if (action === 'clear') {const confirm = await sel('Clear all memories?', [{ value: 'cancel', label: 'Cancel' },@@ -4427,6 +5391,98 @@ Is this productive iteration or a stuck loop?`,}}+ private async openMemoryChoiceMenu(channel: any, channelId: string): Promise<void> {+ if (!this.userMemory) return;++ const learningLabel = this.userMemory.isLearningPaused() ? 'Resume Learning' : 'Pause Learning';+ const shareLabel = this.userMemory.isShareLearning() ? 'Shared Learning: ON' : 'Shared Learning: OFF';+ const action = await channel.presentChoicePrompt('Memory', [+ { value: 'overview', label: 'Overview' },+ { value: 'recent', label: 'Recent Memories' },+ { value: 'shared', label: 'Shared Memories' },+ { value: 'toggle', label: learningLabel },+ { value: 'share', label: shareLabel },+ { value: 'clear', label: 'Clear All Memories' },+ { value: 'cancel', label: 'Cancel' },+ ], channelId);++ if (action === 'cancel') return;++ if (action === 'overview') {+ await this.sendMemoryOverview(channel, channelId);+ return;+ }++ if (action === 'recent') {+ const recent = this.userMemory.getRecent(10);+ if (recent.length === 0) {+ await channel.send('No memories yet.', channelId);+ return;+ }+ const lines = ['**Recent Memories:**', ''];+ for (const r of recent) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ const kind = r.evidenceKind === 'direct' ? 'direct' : r.evidenceKind === 'inferred' ? 'inferred' : r.evidenceKind;+ lines.push(`${scope} [${r.type}] ${r.summary}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${kind} | Seen: ${r.evidenceCount}x`);+ }+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ if (action === 'shared') {+ const shared = this.userMemory.getShareable(20);+ if (shared.length === 0) {+ await channel.send('No shared memories yet. Enable shared learning to mark new memories as shareable for cloud fetch.', channelId);+ return;+ }+ const lines = [`**Shared Memories (${shared.length}):**`, ''];+ for (const r of shared) {+ const scope = r.scope === 'active' ? '⏳' : '📌';+ const cats = r.categories.length > 0 ? ` {${r.categories.join(', ')}}` : '';+ lines.push(`${scope} [${r.type}]${cats} ${r.summary}`);+ lines.push(` Confidence: ${r.confidence.toFixed(2)} | Evidence: ${r.evidenceKind} | Seen: ${r.evidenceCount}x`);+ }+ await channel.send(lines.join('\n'), channelId);+ return;+ }++ if (action === 'toggle') {+ const currentlyPaused = this.userMemory.isLearningPaused();+ this.userMemory.setLearningPaused(!currentlyPaused);+ await channel.send(currentlyPaused ? 'Learning resumed. Mercury will remember new things from conversations.' : 'Learning paused. Mercury will not store new memories until resumed.', channelId);+ return;+ }++ if (action === 'share') {+ const currently = this.userMemory.isShareLearning();+ this.userMemory.setShareLearning(!currently);+ const cfg = loadConfig();+ if (!cfg.memory.collaborativeKnowledge) cfg.memory.collaborativeKnowledge = {};+ cfg.memory.collaborativeKnowledge.shareLearning = !currently;+ saveConfig(cfg);+ const count = this.userMemory.countShareable();+ await channel.send(+ currently+ ? `Shared learning disabled. New memories will stay private. (${count} memories already shareable are unchanged.)`+ : `Shared learning enabled. New memories will be marked shareable for cloud fetch. (${count} memories currently shareable.)`,+ channelId,+ );+ return;+ }++ if (action === 'clear') {+ const confirm = await channel.presentChoicePrompt('Clear all memories?', [+ { value: 'cancel', label: 'Cancel' },+ { value: 'confirm', label: 'Clear everything' },+ ], channelId);+ if (confirm === 'confirm') {+ const cleared = this.userMemory.clear();+ await channel.send(`Cleared ${cleared} memories.`, channelId);+ }+ }+ }+private async openCliTelegramMenu(channel: CLIChannel,channelId: string,diff --git a/src/core/execution-limits.test.ts b/src/core/execution-limits.test.tsnew file mode 100644index 00000000..17827035--- /dev/null+++ b/src/core/execution-limits.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { needsContinuationApproval, needsRetryApproval, withAbortDeadline } from './execution-limits.js';++afterEach(() => {+ vi.useRealTimers();+});++describe('execution limits', () => {+ it('requires user approval at the hard deadline or after two automatic continuations', () => {+ expect(needsContinuationApproval(0, false)).toBe(false);+ expect(needsContinuationApproval(1, false)).toBe(false);+ expect(needsContinuationApproval(2, false)).toBe(true);+ expect(needsContinuationApproval(0, true)).toBe(true);+ expect(needsRetryApproval(2)).toBe(false);+ expect(needsRetryApproval(3)).toBe(true);+ });++ it('rejects and aborts when an underlying provider promise never settles', async () => {+ vi.useFakeTimers();+ const controller = new AbortController();+ const onTimeout = vi.fn();+ const operation = new Promise<string>(() => {});+ const result = withAbortDeadline(operation, controller, 100, onTimeout);+ const rejection = expect(result).rejects.toThrow('hard time limit');++ await vi.advanceTimersByTimeAsync(100);++ await rejection;+ expect(onTimeout).toHaveBeenCalledOnce();+ expect(controller.signal.aborted).toBe(true);+ });++ it('clears the deadline when the provider settles normally', async () => {+ vi.useFakeTimers();+ const controller = new AbortController();+ const onTimeout = vi.fn();++ await expect(withAbortDeadline(Promise.resolve('done'), controller, 100, onTimeout)).resolves.toBe('done');+ await vi.advanceTimersByTimeAsync(100);++ expect(onTimeout).not.toHaveBeenCalled();+ expect(controller.signal.aborted).toBe(false);+ });+});diff --git a/src/core/execution-limits.ts b/src/core/execution-limits.tsnew file mode 100644index 00000000..ae45e8d7--- /dev/null+++ b/src/core/execution-limits.ts@@ -0,0 +1,41 @@+export const MAX_PROVIDER_ATTEMPT_MS = 10 * 60 * 1000;+export const MAX_AUTOMATIC_CONTINUATIONS = 2;+export const MAX_AUTOMATIC_RETRIES = 3;++export function needsContinuationApproval(continuationAttempt: number, reachedHardDeadline: boolean): boolean {+ return reachedHardDeadline || continuationAttempt >= MAX_AUTOMATIC_CONTINUATIONS;+}++export function needsRetryApproval(attempts: number): boolean {+ return attempts >= MAX_AUTOMATIC_RETRIES;+}++export function withAbortDeadline<T>(+ operation: PromiseLike<T>,+ controller: AbortController,+ remainingMs: number,+ onTimeout: () => void,+): Promise<T> {+ if (remainingMs <= 0) {+ onTimeout();+ controller.abort();+ return Promise.reject(new Error('Provider attempt exceeded its hard time limit'));+ }+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ onTimeout();+ controller.abort();+ reject(new Error('Provider attempt exceeded its hard time limit'));+ }, remainingMs);+ Promise.resolve(operation).then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ clearTimeout(timer);+ reject(error);+ },+ );+ });+}diff --git a/src/core/provider-status.test.ts b/src/core/provider-status.test.tsnew file mode 100644index 00000000..857007e3--- /dev/null+++ b/src/core/provider-status.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';+import { CLIChannel } from '../channels/cli.js';+import { updateCliProviderStatus } from './provider-status.js';++describe('live CLI provider status', () => {+ it('updates the visible provider and model without restarting the CLI', () => {+ const channel = new CLIChannel();++ updateCliProviderStatus(channel, 'openai', 'gpt-5');+ expect((channel as any).state.provider).toEqual({ name: 'openai', model: 'gpt-5', badge: undefined });++ updateCliProviderStatus(channel, 'mercuryCloud', 'mercury-flash');+ expect((channel as any).state.provider).toEqual({ name: 'Mercury Cloud', model: 'mercury-flash', badge: undefined });+ });+});diff --git a/src/core/provider-status.ts b/src/core/provider-status.tsnew file mode 100644index 00000000..3affb86c--- /dev/null+++ b/src/core/provider-status.ts@@ -0,0 +1,8 @@+import type { Channel } from '../channels/base.js';+import { CLIChannel } from '../channels/cli.js';++export function updateCliProviderStatus(channel: Channel | undefined, providerName: string, model: string): void {+ if (!(channel instanceof CLIChannel)) return;+ const label = providerName === 'mercuryCloud' ? 'Mercury Cloud' : providerName;+ channel.setProvider(label, model);+}diff --git a/src/core/research-mode.ts b/src/core/research-mode.tsnew file mode 100644index 00000000..6c9ac3ad--- /dev/null+++ b/src/core/research-mode.ts@@ -0,0 +1,101 @@+import { logger } from '../utils/logger.js';++export type ResearchModeState = 'off' | 'on';++export class ResearchMode {+ private state: ResearchModeState = 'off';+ private topic: string | null = null;++ getState(): ResearchModeState {+ return this.state;+ }++ isActive(): boolean {+ return this.state === 'on';+ }++ setOn(topic?: string): void {+ this.state = 'on';+ this.topic = topic || null;+ logger.info({ topic: this.topic }, 'Research mode: on');+ }++ setOff(): void {+ this.state = 'off';+ this.topic = null;+ logger.info('Research mode: off');+ }++ toggle(): ResearchModeState {+ if (this.state === 'off') {+ this.state = 'on';+ } else {+ this.state = 'off';+ this.topic = null;+ }+ logger.info({ state: this.state }, 'Research mode toggled');+ return this.state;+ }++ setTopic(topic: string): void {+ this.topic = topic;+ }++ getTopic(): string | null {+ return this.topic;+ }++ getStatusText(): string {+ if (this.state === 'off') return 'Research mode: Off';+ let text = 'Research mode: On';+ if (this.topic) text += ` | Topic: ${this.topic}`;+ return text;+ }++ /**+ * Multiplier applied to the per-task tool-call cap while research mode is active.+ * Research requires many fetch/search iterations; keep the hard cap but raise it.+ */+ getMaxStepsMultiplier(): number {+ return this.state === 'on' ? 3 : 1;+ }++ /**+ * Multiplier applied to the foreground stall timeout while research mode is active.+ * Research tasks run long by design; do not abort them as stalled.+ */+ getStallMsMultiplier(): number {+ return this.state === 'on' ? 4 : 1;+ }++ getSystemPromptSuffix(): string {+ if (this.state === 'off') return '';++ let suffix = '\n\n**RESEARCH MODE IS ACTIVE**';++ suffix += '\nMode: RESEARCH';+ suffix += '\nYou are performing deep research for the user. Your job is to produce a thorough, well-structured research article, not a quick chat answer.';+ suffix += '\n\nResearch workflow:';+ suffix += '\n1. Break the question into sub-questions and plan which sources to consult.';+ suffix += '\n2. ALWAYS use web_search and fetch_url to gather real, current information from the web. Do not rely on memory or prior knowledge for facts, dates, or news — verify everything live.';+ suffix += '\n3. When a page contains relevant images (infographics, diagrams, charts, photos), preserve their original image URLs in the final markdown using `` syntax so the article is rich and visual.';+ suffix += '\n4. Cross-check claims across multiple sources. Prefer primary sources, official statements, and reputable outlets.';+ suffix += '\n5. Take as many tool steps as the research genuinely requires — do not stop early. Long-running research is expected and will not be killed.';+ suffix += '\n6. After gathering sources, synthesize a single comprehensive research article in rich markdown.';+ suffix += '\n\nOutput format — produce ONE research article as rich markdown:';+ suffix += '\n- Start with a `# Title` reflecting the research question.';+ suffix += '\n- Include a short TL;DR summary near the top.';+ suffix += '\n- Use `##` section headings for sub-topics.';+ suffix += '\n- Cite sources inline as markdown links, e.g. "[according to NOAA](https://...)".';+ suffix += '\n- Embed any relevant images from sources using `` so the article feels rich.';+ suffix += '\n- Include a `## Sources` section at the end listing all URLs consulted.';+ suffix += '\n- The final markdown is treated as the research artifact and will be rendered as a full article on Mercury Cloud.';+ suffix += '\n\nIf the user asks a follow-up in the same thread, treat it as a refinement of this research: reuse the context, gather more if needed, and update or extend the article accordingly. If something is unclear, ask a short clarifying question before spending a long research pass.';++ if (this.topic) {+ suffix += `\n\nResearch topic: ${this.topic}`;+ }++ return suffix;+ }+}\ No newline at end of filediff --git a/src/core/response-delivery.test.ts b/src/core/response-delivery.test.tsnew file mode 100644index 00000000..0e2ef661--- /dev/null+++ b/src/core/response-delivery.test.ts@@ -0,0 +1,13 @@+import { describe, expect, it } from 'vitest';+import { requiresFinalSend } from './response-delivery.js';++describe('response delivery', () => {+ it('does not duplicate a response already rendered by the CLI stream', () => {+ expect(requiresFinalSend('cli', true)).toBe(false);+ expect(requiresFinalSend('cli', false)).toBe(true);+ });++ it('keeps the terminal send for web streams and their completion event', () => {+ expect(requiresFinalSend('web', true)).toBe(true);+ });+});diff --git a/src/core/response-delivery.ts b/src/core/response-delivery.tsnew file mode 100644index 00000000..7c124161--- /dev/null+++ b/src/core/response-delivery.ts@@ -0,0 +1,5 @@+import type { ChannelType } from '../types/channel.js';++export function requiresFinalSend(channelType: ChannelType, cliResponseStreamed: boolean): boolean {+ return channelType !== 'cli' || !cliResponseStreamed;+}diff --git a/src/core/sub-agent.ts b/src/core/sub-agent.tsindex bdf03e9a..c47f5578 100644--- a/src/core/sub-agent.ts+++ b/src/core/sub-agent.ts@@ -139,9 +139,6 @@ export class SubAgent {this.capabilities.setCwd(this.config.workingDirectory);}- this.capabilities.permissions.setAutoApproveAll(true);- this.capabilities.permissions.addTempScope('/', true, true);-this.capabilities.setChannelContext(this.config.sourceChannelId || 'internal',this.config.sourceChannelType || 'internal',@@ -338,7 +335,6 @@ export class SubAgent {if (this.config.workingDirectory) {this.capabilities.setCwd(originalCwd);}- this.capabilities.permissions.setAutoApproveAll(false);this.capabilities.permissions.clearElevation();this.fileLockManager.releaseAll(this.config.id);}@@ -425,4 +421,4 @@ export class SubAgent {return prompt;}-}\ No newline at end of file+}diff --git a/src/core/work-ledger.test.ts b/src/core/work-ledger.test.tsnew file mode 100644index 00000000..3fbfc89c--- /dev/null+++ b/src/core/work-ledger.test.ts@@ -0,0 +1,167 @@+import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir, platform } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import type { ChannelMessage } from '../types/channel.js';+import { getWorkKey, WorkLedger } from './work-ledger.js';++const dirs: string[] = [];++afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function setup(options: { maxTerminalEntries?: number; now?: () => number } = {}) {+ const dir = mkdtempSync(join(tmpdir(), 'mercury-work-ledger-'));+ dirs.push(dir);+ const filePath = join(dir, 'work-ledger.json');+ return { dir, filePath, ledger: new WorkLedger({ filePath, ...options }) };+}++function message(id: string, metadata?: Record<string, unknown>): ChannelMessage {+ return {+ id,+ channelId: 'chat-1',+ channelType: 'signal',+ senderId: 'user-1',+ content: `work ${id}`,+ timestamp: 100,+ metadata,+ };+}++describe('WorkLedger', () => {+ it('uses stable identifier precedence and rejects duplicate acceptance', () => {+ const { ledger } = setup();+ const msg = message('transport-id', { requestId: 'request-id', canonicalMessageId: 'canonical-id' });++ expect(getWorkKey(msg)).toBe('request:request-id');+ expect(ledger.accept(msg).accepted).toBe(true);+ expect(ledger.accept({ ...msg, content: 'duplicate payload' }).accepted).toBe(false);+ expect(ledger.get('request:request-id')?.message.content).toBe('work transport-id');+ });++ it('atomically persists owner-only state and recovers interrupted jobs', () => {+ const { filePath, ledger } = setup();+ const queued = ledger.accept(message('queued')).entry;+ const running = ledger.accept(message('running')).entry;+ ledger.markRunning(running.key);++ const recovered = new WorkLedger({ filePath }).recoverInterrupted();++ expect(recovered.map((entry) => entry.key)).toEqual([queued.key, running.key]);+ expect(recovered[0].message.metadata?.workRecovered).toBe(true);+ expect(recovered[0].message.metadata?.workWasInterrupted).toBe(false);+ expect(recovered[1].message.metadata?.workWasInterrupted).toBe(true);+ expect(recovered[1].attempts).toBe(1);+ if (platform() !== 'win32') {+ expect(statSync(filePath).mode & 0o777).toBe(0o600);+ }+ expect(JSON.parse(readFileSync(filePath, 'utf8')).version).toBe(1);+ });++ it('keeps completed responses in the outbox until delivery succeeds', () => {+ const { filePath, ledger } = setup();+ const entry = ledger.accept(message('outbox')).entry;+ ledger.markRunning(entry.key);+ ledger.markCompleted(entry.key, 'durable result');+ ledger.markDeliveryError(entry.key, new Error('offline'));++ const restarted = new WorkLedger({ filePath });+ expect(restarted.getUndeliveredResponses()).toMatchObject([+ { key: entry.key, finalResponse: 'durable result', delivered: false, deliveryError: 'offline' },+ ]);++ restarted.markDelivered(entry.key);+ expect(new WorkLedger({ filePath }).getUndeliveredResponses()).toEqual([]);+ });++ it('keeps explicit failure responses retryable until delivered', () => {+ const { ledger } = setup();+ const entry = ledger.accept(message('failed-outbox')).entry;+ ledger.markRunning(entry.key);+ ledger.markFailed(entry.key, 'provider unavailable', 'Mercury could not finish after retrying providers.');++ expect(ledger.getUndeliveredResponses()).toMatchObject([+ { key: entry.key, status: 'failed', finalResponse: 'Mercury could not finish after retrying providers.', delivered: false },+ ]);+ });++ it('persists delayed retries as queued work', () => {+ const { filePath, ledger } = setup();+ const entry = ledger.accept(message('retry')).entry;+ ledger.markRunning(entry.key);+ ledger.markRetry(entry.key, 'network unavailable', 50_000);++ const restored = new WorkLedger({ filePath }).get(entry.key);+ expect(restored).toMatchObject({ status: 'queued', attempts: 1, error: 'network unavailable', nextAttemptAt: 50_000 });+ });++ it('checkpoints continuation context instead of discarding completed tool progress', () => {+ const { filePath, ledger } = setup();+ const entry = ledger.accept(message('continuation')).entry;+ ledger.markRunning(entry.key);+ ledger.markRetry(entry.key, 'Generation was interrupted after one or more tools completed', 10_000, {+ continuation: true,+ workCwd: '/tmp/project',+ activity: 'Writing composition',+ summary: 'Screenshot and voiceover completed',+ });++ const restored = new WorkLedger({ filePath }).get(entry.key);+ expect(restored).toMatchObject({+ status: 'queued',+ message: { metadata: {+ workContinuation: true,+ continuationAttempt: 1,+ workCwd: '/tmp/project',+ continuationActivity: 'Writing composition',+ continuationSummary: 'Screenshot and voiceover completed',+ } },+ });+ expect(restored).not.toHaveProperty('finalResponse');+ });++ it('automatically revives legacy ambiguous failures after an upgrade', () => {+ const { filePath, ledger } = setup();+ const entry = ledger.accept(message('legacy-interruption')).entry;+ ledger.markRunning(entry.key);+ ledger.markFailed(entry.key, 'Work stopped in an interrupted/ambiguous state; side effects may be partial');+ ledger.markDelivered(entry.key);++ const recovered = new WorkLedger({ filePath }).recoverInterrupted();+ expect(recovered).toHaveLength(1);+ expect(recovered[0]).toMatchObject({+ status: 'queued',+ delivered: false,+ finalResponse: undefined,+ message: { metadata: { workContinuation: true, continuationAttempt: 1 } },+ });+ });++ it('quarantines invalid state and starts a valid empty ledger', () => {+ const { dir, filePath } = setup();+ writeFileSync(filePath, '{not-json', { mode: 0o600 });++ const ledger = new WorkLedger({ filePath, now: () => 1234 });++ expect(ledger.getUndeliveredResponses()).toEqual([]);+ expect(readdirSync(dir)).toContain('work-ledger.json.corrupt-1234');+ expect(JSON.parse(readFileSync(filePath, 'utf8'))).toEqual({ version: 1, entries: [] });+ });++ it('bounds terminal history without pruning active work', () => {+ let now = 1_000;+ const { ledger } = setup({ maxTerminalEntries: 1, now: () => now++ });+ const active = ledger.accept(message('active')).entry;+ const first = ledger.accept(message('first')).entry;+ ledger.markFailed(first.key, 'first failed');+ const second = ledger.accept(message('second')).entry;+ ledger.markCompleted(second.key, 'second complete');+ ledger.markDelivered(second.key);++ expect(ledger.get(active.key)?.status).toBe('queued');+ expect(ledger.get(second.key)?.status).toBe('completed');+ expect(ledger.get(first.key)).toBeUndefined();+ });+});diff --git a/src/core/work-ledger.ts b/src/core/work-ledger.tsnew file mode 100644index 00000000..28e6357c--- /dev/null+++ b/src/core/work-ledger.ts@@ -0,0 +1,287 @@+import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { z } from 'zod';+import type { ChannelMessage } from '../types/channel.js';+import { getMercuryHome } from '../utils/config.js';+import { logger } from '../utils/logger.js';++const channelMessageSchema = z.object({+ id: z.string(),+ channelId: z.string(),+ channelType: z.enum(['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp']),+ senderId: z.string(),+ senderName: z.string().optional(),+ content: z.string(),+ timestamp: z.number().finite(),+ sessionId: z.string().optional(),+ metadata: z.record(z.unknown()).optional(),+});++const workEntrySchema = z.object({+ key: z.string(),+ message: channelMessageSchema,+ status: z.enum(['queued', 'running', 'completed', 'failed']),+ attempts: z.number().int().nonnegative(),+ acceptedAt: z.number().finite(),+ updatedAt: z.number().finite(),+ startedAt: z.number().finite().optional(),+ completedAt: z.number().finite().optional(),+ finalResponse: z.string().optional(),+ error: z.string().optional(),+ delivered: z.boolean(),+ deliveryError: z.string().optional(),+ nextAttemptAt: z.number().finite().optional(),+});++const ledgerSchema = z.object({+ version: z.literal(1),+ entries: z.array(workEntrySchema),+});++export type WorkStatus = 'queued' | 'running' | 'completed' | 'failed';+export type WorkEntry = z.infer<typeof workEntrySchema>;++export interface WorkLedgerOptions {+ filePath?: string;+ maxTerminalEntries?: number;+ terminalMaxAgeMs?: number;+ now?: () => number;+}++export interface WorkContinuationContext {+ workCwd?: string;+ activity?: string;+ summary?: string;+ continuation?: boolean;+}++const DEFAULT_MAX_TERMINAL_ENTRIES = 500;+const DEFAULT_TERMINAL_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;++export function getWorkKey(message: ChannelMessage): string {+ const requestId = message.metadata?.requestId;+ if (typeof requestId === 'string' && requestId.trim()) return `request:${requestId}`;+ const canonicalMessageId = message.metadata?.canonicalMessageId;+ if (typeof canonicalMessageId === 'string' && canonicalMessageId.trim()) return `canonical:${canonicalMessageId}`;+ return `channel:${message.channelType}:${message.id}`;+}++export class WorkLedger {+ private entries = new Map<string, WorkEntry>();+ private readonly filePath: string;+ private readonly maxTerminalEntries: number;+ private readonly terminalMaxAgeMs: number;+ private readonly now: () => number;++ constructor(options: WorkLedgerOptions = {}) {+ this.filePath = options.filePath ?? join(getMercuryHome(), 'work-ledger.json');+ this.maxTerminalEntries = options.maxTerminalEntries ?? DEFAULT_MAX_TERMINAL_ENTRIES;+ this.terminalMaxAgeMs = options.terminalMaxAgeMs ?? DEFAULT_TERMINAL_MAX_AGE_MS;+ this.now = options.now ?? Date.now;+ this.load();+ }++ accept(message: ChannelMessage): { accepted: boolean; entry: WorkEntry } {+ const key = getWorkKey(message);+ const existing = this.entries.get(key);+ if (existing) return { accepted: false, entry: structuredClone(existing) };++ const now = this.now();+ const entry: WorkEntry = {+ key,+ message: channelMessageSchema.parse(JSON.parse(JSON.stringify(message))),+ status: 'queued',+ attempts: 0,+ acceptedAt: now,+ updatedAt: now,+ delivered: false,+ };+ this.entries.set(key, entry);+ this.persist();+ return { accepted: true, entry: structuredClone(entry) };+ }++ get(key: string): WorkEntry | undefined {+ const entry = this.entries.get(key);+ return entry ? structuredClone(entry) : undefined;+ }++ markRunning(key: string): WorkEntry {+ return this.update(key, (entry) => {+ entry.status = 'running';+ entry.attempts += 1;+ entry.startedAt = this.now();+ entry.error = undefined;+ entry.nextAttemptAt = undefined;+ });+ }++ markCompleted(key: string, finalResponse: string): WorkEntry {+ return this.update(key, (entry) => {+ entry.status = 'completed';+ entry.completedAt = this.now();+ entry.finalResponse = finalResponse;+ entry.error = undefined;+ entry.delivered = false;+ entry.deliveryError = undefined;+ });+ }++ markFailed(key: string, error: unknown, finalResponse?: string): WorkEntry {+ return this.update(key, (entry) => {+ entry.status = 'failed';+ entry.completedAt = this.now();+ entry.error = error instanceof Error ? error.message : String(error);+ entry.finalResponse = finalResponse ?? `I couldn't finish this request: ${entry.error}`;+ entry.delivered = false;+ });+ }++ markRetry(key: string, error: unknown, nextAttemptAt: number, context: WorkContinuationContext = {}): WorkEntry {+ return this.update(key, (entry) => {+ entry.status = 'queued';+ entry.error = error instanceof Error ? error.message : String(error);+ entry.nextAttemptAt = nextAttemptAt;+ entry.delivered = false;+ entry.completedAt = undefined;+ entry.finalResponse = undefined;+ entry.deliveryError = undefined;+ const previousContinuationAttempt = typeof entry.message.metadata?.continuationAttempt === 'number'+ ? entry.message.metadata.continuationAttempt+ : 0;+ entry.message.metadata = {+ ...entry.message.metadata,+ workRecovered: true,+ workWasInterrupted: true,+ ...(context.continuation ? { workContinuation: true, continuationAttempt: previousContinuationAttempt + 1 } : {}),+ ...(context.workCwd ? { workCwd: context.workCwd } : {}),+ ...(context.activity ? { continuationActivity: context.activity.slice(0, 300) } : {}),+ ...(context.summary ? { continuationSummary: context.summary.slice(0, 1000) } : {}),+ continuationReason: entry.error.slice(0, 1000),+ };+ });+ }++ markDelivered(key: string): WorkEntry {+ return this.update(key, (entry) => {+ entry.delivered = true;+ entry.deliveryError = undefined;+ });+ }++ markDeliveryError(key: string, error: unknown): WorkEntry {+ return this.update(key, (entry) => {+ entry.delivered = false;+ entry.deliveryError = error instanceof Error ? error.message : String(error);+ });+ }++ recoverInterrupted(): WorkEntry[] {+ const recovered: WorkEntry[] = [];+ for (const entry of this.entries.values()) {+ const recoverableFailure = entry.status === 'failed' && /interrupted\/ambiguous|side effects may be partial|after one or more tools completed|partial output/i.test(entry.error || '');+ if (entry.status !== 'queued' && entry.status !== 'running' && !recoverableFailure) continue;+ const interrupted = entry.status === 'running';+ entry.status = 'queued';+ entry.updatedAt = this.now();+ entry.completedAt = undefined;+ entry.finalResponse = undefined;+ entry.delivered = false;+ entry.message.metadata = {+ ...entry.message.metadata,+ workRecovered: true,+ workWasInterrupted: interrupted || recoverableFailure,+ ...(recoverableFailure ? {+ workContinuation: true,+ continuationAttempt: (typeof entry.message.metadata?.continuationAttempt === 'number' ? entry.message.metadata.continuationAttempt : 0) + 1,+ continuationReason: entry.error?.slice(0, 1000),+ } : {}),+ };+ recovered.push(structuredClone(entry));+ }+ if (recovered.length > 0) this.persist();+ return recovered;+ }++ getUndeliveredResponses(): WorkEntry[] {+ return [...this.entries.values()]+ .filter((entry) => (entry.status === 'completed' || entry.status === 'failed') && !entry.delivered && typeof entry.finalResponse === 'string')+ .sort((a, b) => a.acceptedAt - b.acceptedAt)+ .map((entry) => structuredClone(entry));+ }++ private update(key: string, mutate: (entry: WorkEntry) => void): WorkEntry {+ const entry = this.entries.get(key);+ if (!entry) throw new Error(`Unknown work ledger entry: ${key}`);+ mutate(entry);+ entry.updatedAt = this.now();+ this.persist();+ return structuredClone(entry);+ }++ private load(): void {+ if (!existsSync(this.filePath)) return;+ try {+ const parsed = ledgerSchema.parse(JSON.parse(readFileSync(this.filePath, 'utf8')));+ this.entries = new Map(parsed.entries.map((entry) => [entry.key, entry]));+ } catch (error) {+ const recoveryPath = `${this.filePath}.corrupt-${this.now()}`;+ try {+ renameSync(this.filePath, recoveryPath);+ } catch (renameError) {+ logger.warn({ renameError, filePath: this.filePath }, 'Unable to quarantine invalid work ledger');+ }+ this.entries.clear();+ logger.error({ error, recoveryPath }, 'Invalid work ledger quarantined; starting with an empty ledger');+ this.persist();+ }+ }++ private persist(): void {+ this.prune();+ const dir = dirname(this.filePath);+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const tempPath = `${this.filePath}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;+ const payload = JSON.stringify({ version: 1, entries: [...this.entries.values()] }, null, 2) + '\n';+ let fd: number | undefined;+ try {+ fd = openSync(tempPath, 'wx', 0o600);+ const buffer = Buffer.from(payload);+ let offset = 0;+ while (offset < buffer.length) {+ const written = writeSync(fd, buffer, offset, buffer.length - offset);+ offset += written;+ }+ fsyncSync(fd);+ closeSync(fd);+ fd = undefined;+ renameSync(tempPath, this.filePath);+ chmodSync(this.filePath, 0o600);+ let dirFd: number | undefined;+ try {+ dirFd = openSync(dir, 'r');+ fsyncSync(dirFd);+ } catch {+ // Directory fsync is not supported on every platform/filesystem.+ } finally {+ if (dirFd !== undefined) closeSync(dirFd);+ }+ } finally {+ if (fd !== undefined) closeSync(fd);+ if (existsSync(tempPath)) {+ try { unlinkSync(tempPath); } catch { /* best effort */ }+ }+ }+ }++ private prune(): void {+ const terminal = [...this.entries.values()]+ .filter((entry) => entry.status === 'failed' || (entry.status === 'completed' && entry.delivered))+ .sort((a, b) => b.updatedAt - a.updatedAt);+ const cutoff = this.now() - this.terminalMaxAgeMs;+ for (let index = 0; index < terminal.length; index++) {+ const entry = terminal[index];+ if (index >= this.maxTerminalEntries || entry.updatedAt < cutoff) this.entries.delete(entry.key);+ }+ }+}diff --git a/src/index.ts b/src/index.tsindex fc7d63f3..4ef6b5ef 100644--- a/src/index.ts+++ b/src/index.ts@@ -49,6 +49,7 @@ import { logger } from './utils/logger.js';import { redactPhone } from './utils/redact.js';import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory, migrateLegacyMemory } from './memory/store.js';+import { buildConversationHistoryPayload, CloudSessionSynchronizer, SessionRepository } from './sessions/index.js';import { UserMemoryStore } from './memory/user-memory.js';import { isBetterSqlite3Available } from './memory/second-brain-db.js';import { ProviderRegistry } from './providers/registry.js';@@ -68,13 +69,15 @@ import { CapabilityRegistry } from './capabilities/registry.js';import { SkillLoader } from './skills/loader.js';import { registerSkillsCommand } from './skills/cli.js';import { getManual } from './utils/manual.js';-import { startBackground, stopDaemon, showLogs, getDaemonStatus, restartDaemon, tryAutoDaemonize, isStandaloneBinary } from './cli/daemon.js';+import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';import { selectWithArrowKeys } from './utils/arrow-select.js';import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders } from './web/server.js';+import { initCloudTokenStore } from './cloud/token-store.js';+import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled } from './web/server.js';import { isWebAuthInitialized, setWebPassword } from './web/auth.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -142,6 +145,7 @@ function maskKey(key: string): string {}const PROVIDER_OPTIONS: Array<{ key: ProviderName; label: string }> = [+ { key: 'mercuryCloud', label: 'Mercury Cloud (hosted — no API keys needed)' },{ key: 'deepseek', label: 'DeepSeek' },{ key: 'openai', label: 'OpenAI' },{ key: 'anthropic', label: 'Anthropic' },@@ -165,6 +169,7 @@ function getConfiguredProviderNames(config: MercuryConfig): ProviderName[] {function getProviderLabel(name: ProviderName): string {if (name === 'chatgptWeb') return 'OpenAI (ChatGPT Plus/Pro)';+ if (name === 'mercuryCloud') return 'Mercury Cloud';return PROVIDER_OPTIONS.find((option) => option.key === name)?.label || name;}@@ -635,9 +640,21 @@ function printTelegramAccessState(config: MercuryConfig): void {console.log('');console.log(` Telegram Access: ${chalk.white(getTelegramAccessSummary(config))}`);+ console.log(` Enabled: ${config.channels.telegram.enabled ? chalk.green('yes') : chalk.red('no')}`);+ console.log(` Bot Token: ${config.channels.telegram.botToken ? chalk.green('configured') : chalk.red('missing')}`);console.log(` Admins: ${admins.length > 0 ? chalk.green(admins.map(formatTelegramUser).join(', ')) : chalk.dim('none')}`);console.log(` Members: ${members.length > 0 ? chalk.green(members.map(formatTelegramUser).join(', ')) : chalk.dim('none')}`);console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);++ if (!config.channels.telegram.enabled && config.channels.telegram.botToken) {+ console.log(chalk.yellow(' Warning: Telegram has a bot token but is disabled. Run `mercury telegram enable`.'));+ }+ if (config.channels.telegram.enabled && !config.channels.telegram.botToken) {+ console.log(chalk.yellow(' Warning: Telegram is enabled but has no bot token. Run `mercury doctor`.'));+ }+ if (config.channels.telegram.enabled && config.channels.telegram.botToken && admins.length === 0 && pending.length === 0) {+ console.log(chalk.yellow(' Pairing: Send /start to the bot, then run `mercury telegram approve <pairing-code>`.'));+ }}function formatDiscordUser(user: {@@ -1074,9 +1091,23 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {const agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));if (agentName) config.identity.name = agentName;} else {- const ownerName = await ask(chalk.white(' Your name: '));+ // Retry up to MAX_EMPTY_ATTEMPTS times before giving up, so an accidental+ // Enter on the first-run "Your name" prompt doesn't immediately exit+ // onboarding. Only exit after the user presses Enter with no value that+ // many times in a row.+ const MAX_EMPTY_ATTEMPTS = 3;+ let ownerName = '';+ let attempts = 0;+ while (attempts < MAX_EMPTY_ATTEMPTS) {+ ownerName = await ask(chalk.white(' Your name: '));+ if (ownerName) break;+ attempts++;+ if (attempts < MAX_EMPTY_ATTEMPTS) {+ console.log(chalk.red(` Name is required. Please enter your name (${attempts}/${MAX_EMPTY_ATTEMPTS}).`));+ }+ }if (!ownerName) {- console.log(chalk.red(' Name is required.'));+ console.log(chalk.red(' Name is required. Exiting setup — run `mercury` again to retry.'));process.exit(1);}config.identity.owner = ownerName;@@ -1089,16 +1120,65 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {hr();console.log('');- console.log(chalk.bold.white(' LLM Providers'));- if (isReconfig) {- console.log(chalk.dim(' Choose which providers to configure now. Existing values are shown where available.'));+ console.log(chalk.bold.white(' Mercury Cloud or Offline?'));+ console.log('');+ if (!isReconfig) {+ console.log(chalk.dim(' Mercury Cloud routes LLM calls through our servers — no API keys needed.'));+ console.log(chalk.dim(' Offline (BYOK) uses your own API keys stored locally.'));+ console.log('');+ }++ const cloudChoice = await selectWithArrowKeys(+ isReconfig ? 'Connection Mode' : 'Choose your mode',+ [+ { value: 'cloud', label: 'Mercury Cloud (hosted — no API keys needed)' },+ { value: 'offline', label: 'Offline / BYOK (bring your own keys)' },+ ],+ );++ let llmConfiguredByCloud = false;++ if (cloudChoice === 'cloud') {+ console.log('');+ console.log(chalk.dim(' Connecting to Mercury Cloud...'));+ console.log('');+ try {+ const { runCloudPairingFlow } = await import('./cloud/pairing-flow.js');+ const result = await runCloudPairingFlow(config);+ if (result) {+ config.cloud = result.cloudConfig;+ config.providers.mercuryCloud.apiKey = result.cloudConfig.jwt;+ config.providers.mercuryCloud.model = result.model;+ config.providers.mercuryCloud.enabled = true;+ config.providers.default = 'mercuryCloud';+ saveConfig(config);+ console.log(chalk.green(' ✓ Mercury Cloud connected!'));+ console.log(chalk.dim(` Agent ID: ${result.cloudConfig.agentId}`));+ console.log(chalk.dim(` Tier: ${result.cloudConfig.tier}`));+ console.log(chalk.dim(` Model: ${result.model}`));+ llmConfiguredByCloud = true;+ }+ } catch (err: any) {+ console.log(chalk.red(` ✗ Cloud connection failed: ${err.message || err}`));+ console.log(chalk.yellow(' Falling back to offline (BYOK) mode.'));+ }} else {- console.log(chalk.dim(' Choose one or more providers. You can skip any provider by pressing Enter.'));- console.log(chalk.dim(' Press Enter to configure DeepSeek by default (free at platform.deepseek.com).'));+ config.cloud.enabled = false;}- console.log('');- while (true) {+ if (!llmConfiguredByCloud) {+ hr();+ console.log('');+ console.log(chalk.bold.white(' LLM Providers'));+ if (isReconfig) {+ console.log(chalk.dim(' Choose which providers to configure now. Existing values are shown where available.'));+ } else {+ console.log(chalk.dim(' Choose one or more providers. You can skip any provider by pressing Enter.'));+ console.log(chalk.dim(' Press Enter to configure DeepSeek by default (free at platform.deepseek.com).'));+ }+ console.log('');++ while (true) {const selectedProviders = await chooseProvidersToConfigure(config, isReconfig);console.log('');@@ -1395,42 +1475,34 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {const configuredProviders = getConfiguredProviderNames(config);if (configuredProviders.length === 0) {+ saveConfig(config);console.log('');- console.log(chalk.yellow(' No LLM providers were configured.'));- console.log(chalk.dim(' Mercury needs at least one provider to work.'));- console.log(chalk.dim(' DeepSeek offers a free API key at platform.deepseek.com'));- console.log('');- console.log(chalk.white(' Options:'));- console.log(chalk.white(' 1. Try again — choose a provider and enter an API key'));- console.log(chalk.white(' 2. Skip for now — you can run `mercury doctor` later'));- console.log('');-- const skipChoice = await ask(chalk.white(' Press Enter to try again, or type "skip" to exit setup: '));- if (skipChoice.toLowerCase() === 'skip') {- saveConfig(config);- const home = getMercuryHome();- console.log('');- console.log(chalk.green(` ✓ Config saved to ${home}/mercury.yaml`));- console.log(chalk.yellow(' No providers configured yet. Run `mercury doctor` when ready.'));- console.log('');- process.exit(0);- }-+ console.log(chalk.yellow(' No LLM provider configured yet. Run `mercury doctor` when ready to add one.'));console.log('');- continue;+ } else {+ await chooseDefaultProvider(config);}-- await chooseDefaultProvider(config);break;}+ } else {+ console.log('');+ console.log(chalk.dim(' Continuing with shared Mercury setup: channels, integrations, budget, and web dashboard.'));+ }hr();console.log('');console.log(chalk.bold.white(' Telegram (optional)'));+ // On first run, show the how-to guide so the user knows how to get a bot+ // token. On reconfig (e.g. `mercury doctor`), skip the guide for an+ // already-configured channel — only re-show it if the user clears the+ // existing token (by entering "none" or a new value).+ const tgAlreadyConfigured = isReconfig && !!config.channels.telegram.botToken;if (isReconfig) {console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));} else {console.log(chalk.dim(' Leave empty to skip. You can add it later.'));+ }+ if (!tgAlreadyConfigured) {console.log(chalk.dim(' To create a bot token:'));console.log(chalk.dim(' 1. Open Telegram and message @BotFather'));console.log(chalk.dim(' 2. Run /newbot and follow the prompts'));@@ -1460,12 +1532,15 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {hr();console.log('');console.log(chalk.bold.white(' Signal (optional)'));+ const sigAlreadyConfigured = isReconfig && !!config.channels.signal.phoneNumber;if (isReconfig && config.channels.signal.phoneNumber) {console.log(chalk.dim(' Leave empty to keep current number. Enter "none" to disable Signal.'));console.log(chalk.dim(' Enter "reset" to start fresh (clear config, optionally delete binary).'));console.log(chalk.dim(' Enter "unregister" to unlink this device from Signal and clear all data.'));} else {console.log(chalk.dim(' Leave empty to skip. You can add it later with mercury doctor.'));+ }+ if (!sigAlreadyConfigured) {console.log(chalk.dim(' Include country code, e.g. +1 for US, +44 for UK, +91 for India.'));console.log(chalk.dim(' Signal lets you chat with Mercury through a Signal group or private chat.'));}@@ -1599,24 +1674,27 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {hr();console.log('');console.log(chalk.bold.white(' Discord (optional)'));+ const dcAlreadyConfigured = isReconfig && !!config.channels.discord.botToken;if (isReconfig) {console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));} else {console.log(chalk.dim(' Leave empty to skip. You can add it later.'));}- console.log(chalk.dim(' To create a Discord bot:'));- console.log(chalk.dim(' 1. Go to https://discord.com/developers/applications'));- console.log(chalk.dim(' 2. Click "New Application" → give it a name'));- console.log(chalk.dim(' 3. Navigate to Bot → Click "Reset Token" → Copy the token'));- console.log(chalk.dim(' 4. Enable Privileged Gateway Intents:'));- console.log(chalk.dim(' - Message Content Intent'));- console.log(chalk.dim(' 5. Go to OAuth2 → URL Generator:'));- console.log(chalk.dim(' Scopes: bot, applications.commands'));- console.log(chalk.dim(' Bot Permissions: Send Messages, Read Message History,'));- console.log(chalk.dim(' Use Slash Commands, Attach Files, Embed Links'));- console.log(chalk.dim(' 6. Open the generated URL to invite the bot to your server'));- console.log(chalk.dim(' 7. Optionally create a "Mercury Admin" role in your server'));- console.log(chalk.dim(' Guild members can chat openly. DMs require pairing (like Telegram).'));+ if (!dcAlreadyConfigured) {+ console.log(chalk.dim(' To create a Discord bot:'));+ console.log(chalk.dim(' 1. Go to https://discord.com/developers/applications'));+ console.log(chalk.dim(' 2. Click "New Application" → give it a name'));+ console.log(chalk.dim(' 3. Navigate to Bot → Click "Reset Token" → Copy the token'));+ console.log(chalk.dim(' 4. Enable Privileged Gateway Intents:'));+ console.log(chalk.dim(' - Message Content Intent'));+ console.log(chalk.dim(' 5. Go to OAuth2 → URL Generator:'));+ console.log(chalk.dim(' Scopes: bot, applications.commands'));+ console.log(chalk.dim(' Bot Permissions: Send Messages, Read Message History,'));+ console.log(chalk.dim(' Use Slash Commands, Attach Files, Embed Links'));+ console.log(chalk.dim(' 6. Open the generated URL to invite the bot to your server'));+ console.log(chalk.dim(' 7. Optionally create a "Mercury Admin" role in your server'));+ console.log(chalk.dim(' Guild members can chat openly. DMs require pairing (like Telegram).'));+ }console.log('');const dcMask = isReconfig && config.channels.discord.botToken ? ` [${maskKey(config.channels.discord.botToken)}]` : '';@@ -1673,29 +1751,32 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {hr();console.log('');console.log(chalk.bold.white(' Slack (optional)'));+ const slAlreadyConfigured = isReconfig && !!config.channels.slack.botToken;if (isReconfig) {console.log(chalk.dim(' Leave empty to keep current value. Enter "none" to disable.'));} else {console.log(chalk.dim(' Leave empty to skip. You can add it later.'));}- console.log(chalk.dim(' To create a Slack app:'));- console.log(chalk.dim(' 1. Go to https://api.slack.com/apps → Create New App → From scratch'));- console.log(chalk.dim(' 2. Under "Socket Mode", enable it and generate an App-Level Token'));- console.log(chalk.dim(' with connections:write scope → copy the xapp- token'));- console.log(chalk.dim(' 3. Under "OAuth & Permissions", add Bot Token Scopes:'));- console.log(chalk.dim(' chat:write, chat:write.public, chat:write.customize,'));- console.log(chalk.dim(' channels:history, groups:history, im:history, im:write,'));- console.log(chalk.dim(' files:write, commands, app_mentions:read'));- console.log(chalk.dim(' 4. Install app to workspace → copy Bot User OAuth Token (xoxb-)'));- console.log(chalk.dim(' 5. Under "Event Subscriptions", enable and subscribe to:'));- console.log(chalk.dim(' message.channels, message.groups, message.im, app_mention'));- console.log(chalk.dim(' 6. Under "Interactivity & Shortcuts", enable interactivity'));- console.log(chalk.dim(' 7. Under "Slash Commands", create /mercury command'));- console.log(chalk.dim(' 8. Under "App Home", check "Allow users to send Slash commands'));- console.log(chalk.dim(' and messages from the messages tab"'));- console.log(chalk.dim(' 9. Invite the bot to your channel: /invite @Mercury'));- console.log(chalk.dim(' 10. DM the bot /mercury start to become the first admin.'));- console.log(chalk.dim(' Channel members can chat openly. DMs require admin approval.'));+ if (!slAlreadyConfigured) {+ console.log(chalk.dim(' To create a Slack app:'));+ console.log(chalk.dim(' 1. Go to https://api.slack.com/apps → Create New App → From scratch'));+ console.log(chalk.dim(' 2. Under "Socket Mode", enable it and generate an App-Level Token'));+ console.log(chalk.dim(' with connections:write scope → copy the xapp- token'));+ console.log(chalk.dim(' 3. Under "OAuth & Permissions", add Bot Token Scopes:'));+ console.log(chalk.dim(' chat:write, chat:write.public, chat:write.customize,'));+ console.log(chalk.dim(' channels:history, groups:history, im:history, im:write,'));+ console.log(chalk.dim(' files:write, commands, app_mentions:read'));+ console.log(chalk.dim(' 4. Install app to workspace → copy Bot User OAuth Token (xoxb-)'));+ console.log(chalk.dim(' 5. Under "Event Subscriptions", enable and subscribe to:'));+ console.log(chalk.dim(' message.channels, message.groups, message.im, app_mention'));+ console.log(chalk.dim(' 6. Under "Interactivity & Shortcuts", enable interactivity'));+ console.log(chalk.dim(' 7. Under "Slash Commands", create /mercury command'));+ console.log(chalk.dim(' 8. Under "App Home", check "Allow users to send Slash commands'));+ console.log(chalk.dim(' and messages from the messages tab"'));+ console.log(chalk.dim(' 9. Invite the bot to your channel: /invite @Mercury'));+ console.log(chalk.dim(' 10. DM the bot /mercury start to become the first admin.'));+ console.log(chalk.dim(' Channel members can chat openly. DMs require admin approval.'));+ }const slMask = isReconfig && config.channels.slack.botToken ? ` [${maskKey(config.channels.slack.botToken)}]` : '';const slackBotToken = await ask(chalk.white(` Slack Bot Token${slMask} (starts with xoxb-): `));@@ -1993,6 +2074,8 @@ function runPlatformDoctor(): void {}async function runAgent(isDaemon: boolean = false): Promise<void> {+ const runtimeMode = isDaemon ? 'daemon' : 'foreground';+ registerRuntimeProcess(runtimeMode);let config = loadConfig();config = ensureCreatorField(config);const name = config.identity.name;@@ -2021,7 +2104,14 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {}const tokenBudget = new TokenBudget(config);- const providers = await ProviderRegistry.create(config);++ // Initialize the shared cloud token store before providers so the+ // MercuryCloud provider can read from / write back to the single source of+ // truth for the access + (single-use) refresh token.+ const cloudTokenStore = config.cloud.enabled && config.cloud.jwt && config.cloud.agentId+ ? initCloudTokenStore(config)+ : null;+ const providers = await ProviderRegistry.create(config, cloudTokenStore);if (!providers.hasProviders()) {if (isDaemon) {@@ -2061,6 +2151,8 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const identity = new Identity();migrateLegacyMemory();const shortTerm = new ShortTermMemory(config);+ const sessions = new SessionRepository();+ setWebSessions(sessions);const longTerm = new LongTermMemory(config);const episodic = new EpisodicMemory(config);@@ -2126,6 +2218,8 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {memorySetLearningPaused: (paused: boolean) => { if (userMemory) userMemory.setLearningPaused(paused); },memoryClear: () => userMemory ? userMemory.clear() : 0,memoryGetSubconscious: (limit?: number) => userMemory ? userMemory.getSubconscious(limit) : [],+ memoryIsShareLearning: () => userMemory ? userMemory.isShareLearning() : false,+ memorySetShareLearning: (enabled: boolean) => { if (userMemory) userMemory.setShareLearning(enabled); },});capabilities.setSendFileHandler(async (filePath: string, channel?: string) => {@@ -2189,7 +2283,15 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {capabilities.registerAll();const agent = new Agent(- config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler,+ config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler, sessions,+ async ({ userMessage, assistantMessage, providerName }) => {+ const provider = providers.get(providerName) ?? providers.getDefault();+ const result = await provider.generateText(+ `User: ${userMessage.slice(0, 1500)}\nAssistant: ${assistantMessage.slice(0, 1500)}`,+ 'Create a concise 3-7 word title for this conversation. Return only the title with no quotes, markdown, prefix, or punctuation.',+ );+ return result.text;+ },);agent.setSkillLoader(skillLoader);@@ -2266,6 +2368,564 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {await agent.birth();await agent.wake();+ let cloudClient: import('./cloud/client.js').MercuryCloudClient | undefined;+ let sessionSynchronizer: CloudSessionSynchronizer | undefined;+ if (config.cloud.enabled && config.cloud.jwt && config.cloud.agentId) {+ try {+ const { MercuryCloudClient } = await import('./cloud/client.js');+ cloudClient = new MercuryCloudClient(config.cloud.wsUrl, cloudTokenStore!, (connected) => {+ if (connected) markCloudRuntimeOnline(config.cloud.agentId, runtimeMode);+ else clearCloudRuntimeOnline(process.pid);+ });+ const activeSessionSynchronizer = new CloudSessionSynchronizer(sessions, () => ({+ apiUrl: config.cloud.apiUrl,+ agentId: config.cloud.agentId,+ token: cloudTokenStore!.getJwt(),+ }));+ sessionSynchronizer = activeSessionSynchronizer;++ let syncSettingReceived = false;+ let syncFallbackTimer: ReturnType<typeof setTimeout> | undefined;+ cloudClient.on('conversation.sync.toggle', (msg) => {+ syncSettingReceived = true;+ if (syncFallbackTimer) clearTimeout(syncFallbackTimer);+ const enabled = msg.payload?.enabled === true;+ logger.info({ enabled }, 'Cloud command: toggle conversation persistence');+ agent.setSessionSyncEnabled(enabled);+ if (enabled) activeSessionSynchronizer.start();+ else {+ activeSessionSynchronizer.stop();+ sessions.purgeDeleted(sessions.dump().filter((session) => session.status === 'deleted').map((session) => session.id));+ }+ });++ // The shared token store already persists rotations to disk and+ // notifies the provider via its listener. This legacy synthetic event+ // only needs to mirror the new JWT into the in-memory config object+ // used by closures above and keep the provider's apiKey in sync.+ cloudClient.on('token.refreshed' as any, (msg: any) => {+ const payload = msg.payload as { jwt: string; refreshToken: string } | undefined;+ if (payload) {+ config.cloud.jwt = payload.jwt;+ config.cloud.refreshToken = payload.refreshToken;+ config.providers.mercuryCloud.apiKey = payload.jwt;+ providers.updateApiKey('mercuryCloud', payload.jwt);+ logger.info('Mercury Cloud token refreshed and saved');+ }+ });++ cloudClient.on('agent.restart', async (msg) => {+ const reason = typeof msg.payload?.reason === 'string' ? msg.payload.reason : undefined;+ if (reason === 'server_shutdown') {+ logger.info('Mercury Cloud server is shutting down; staying alive for reconnect');+ return;+ }+ // A detached Mercury process has no parent supervisor. Exiting here+ // would turn a remote restart request into a permanent outage.+ logger.warn({ reason }, 'Cloud restart request ignored; use a process supervisor or `mercury restart` on the host');+ });++ cloudClient.on('agent.event.ack', (msg) => {+ const requestId = typeof msg.payload?.requestId === 'string' ? msg.payload.requestId : undefined;+ if (requestId) agent.acknowledgeCloudDelivery(requestId);+ });++ cloudClient.on('agent.status', () => {+ cloudClient!.send({+ type: 'agent.state',+ agentId: config.cloud.agentId,+ payload: {+ status: 'online',+ provider: getProviderLabel(config.providers.default),+ model: config.providers[config.providers.default]?.model ?? 'unknown',+ uptime: process.uptime(),+ },+ timestamp: new Date().toISOString(),+ });+ });++ cloudClient.on('skill.install', async (msg) => {+ const skillUrl = msg.payload?.skillUrl as string | undefined;+ if (skillUrl) {+ logger.info({ skillUrl }, 'Cloud command: install skill');+ try {+ await skillLoader.installFromUrl(skillUrl);+ cloudClient!.send({+ type: 'skill.ack',+ agentId: config.cloud.agentId,+ payload: { success: true, skillUrl },+ timestamp: new Date().toISOString(),+ });+ } catch (err: any) {+ cloudClient!.send({+ type: 'skill.ack',+ agentId: config.cloud.agentId,+ payload: { success: false, error: err.message },+ timestamp: new Date().toISOString(),+ });+ }+ }+ });++ cloudClient.on('skill.remove', async (msg) => {+ const skillName = msg.payload?.skillName as string | undefined;+ if (skillName) {+ logger.info({ skillName }, 'Cloud command: remove skill');+ try {+ skillLoader.deleteSkill(skillName);+ cloudClient!.send({+ type: 'skill.ack',+ agentId: config.cloud.agentId,+ payload: { success: true, action: 'remove', skillName },+ timestamp: new Date().toISOString(),+ });+ } catch (err: any) {+ cloudClient!.send({+ type: 'skill.ack',+ agentId: config.cloud.agentId,+ payload: { success: false, error: err.message },+ timestamp: new Date().toISOString(),+ });+ }+ }+ });++ cloudClient.on('memory.extract', async () => {+ logger.info('Cloud command: extract memory');+ const memData: Record<string, unknown> = {};+ const syncEntries: { type: string; content: string; metadata?: Record<string, unknown>; timestamp?: string }[] = [];++ try {+ const ltFacts = longTerm.getAll();+ memData['long-term'] = ltFacts;+ for (const fact of ltFacts) {+ syncEntries.push({+ type: 'long-term',+ content: `${fact.topic}: ${fact.fact}`,+ metadata: { topic: fact.topic, confidence: (fact as any).confidence },+ timestamp: new Date(fact.timestamp).toISOString(),+ });+ }++ const epEvents = episodic.getRecent(100);+ memData['episodic'] = epEvents;+ for (const event of epEvents) {+ syncEntries.push({+ type: 'episodic',+ content: event.summary || JSON.stringify(event),+ metadata: { type: event.type, channelType: event.channelType, important: event.metadata?.important },+ timestamp: new Date(event.timestamp).toISOString(),+ });+ }++ if (userMemory) {+ const summary = userMemory.getSummary();+ memData['second-brain'] = summary;+ const recent = userMemory.getRecent(100);+ for (const mem of recent) {+ syncEntries.push({+ type: 'second-brain',+ content: mem.summary || mem.detail || JSON.stringify(mem),+ metadata: { type: mem.type, confidence: mem.confidence, importance: mem.importance, scope: mem.scope },+ timestamp: new Date(mem.createdAt).toISOString(),+ });+ }+ }+ } catch (err: any) {+ memData['error'] = err.message;+ }++ cloudClient!.send({+ type: 'memory.dump',+ agentId: config.cloud.agentId,+ payload: memData,+ timestamp: new Date().toISOString(),+ });++ if (syncEntries.length > 0 && config.cloud.apiUrl) {+ try {+ await fetch(`${config.cloud.apiUrl}/v1/memory/sync`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${config.cloud.jwt}`,+ },+ body: JSON.stringify({ agentId: config.cloud.agentId, entries: syncEntries }),+ });+ logger.info({ count: syncEntries.length }, 'Memory synced to Mercury Cloud');+ } catch (syncErr: any) {+ logger.warn({ err: syncErr.message }, 'Failed to sync memory to cloud');+ }+ }+ });++ // Cloud → agent: fetch shareable memories newer than a cursor (incremental).+ // Returns only shareable=1, non-dismissed rows with updated_at > since.+ cloudClient.on('memory.fetch', async (msg) => {+ const since = (msg.payload?.since as number) ?? 0;+ const limit = (msg.payload?.limit as number) ?? 500;+ const requestId = (msg.payload?.requestId as string) ?? '';++ logger.info({ since, limit, requestId }, 'Cloud command: fetch shareable memories');++ try {+ const memories = userMemory+ ? userMemory.getShareableSince(since, limit).map((m) => ({+ id: m.id,+ type: m.type,+ categories: m.categories,+ summary: m.summary,+ detail: m.detail ?? null,+ scope: m.scope,+ evidenceKind: m.evidenceKind,+ source: m.source,+ confidence: m.confidence,+ importance: m.importance,+ durability: m.durability,+ evidenceCount: m.evidenceCount,+ provenance: m.provenance ?? null,+ createdAt: m.createdAt,+ updatedAt: m.updatedAt,+ }))+ : [];++ cloudClient!.send({+ type: 'memory.fetch.result',+ agentId: config.cloud.agentId,+ payload: { requestId, memories },+ timestamp: new Date().toISOString(),+ });++ logger.info({ count: memories.length, requestId }, 'Cloud fetch: sent shareable memories');+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Cloud fetch: failed to gather memories');+ cloudClient!.send({+ type: 'memory.fetch.result',+ agentId: config.cloud.agentId,+ payload: { requestId, memories: [] },+ timestamp: new Date().toISOString(),+ });+ }+ });++ // Cloud → agent: toggle shared learning on/off. When on, new memories+ // extracted via remember() are marked shareable so the cloud fetch can+ // pull them into the collaborative pool. Persisted to config on the agent.+ cloudClient.on('memory.share-learning.toggle', async (msg) => {+ const enabled = Boolean(msg.payload?.enabled);+ logger.info({ enabled }, 'Cloud command: toggle shared learning');+ if (userMemory) {+ userMemory.setShareLearning(enabled);+ try {+ if (!config.memory.collaborativeKnowledge) config.memory.collaborativeKnowledge = {};+ config.memory.collaborativeKnowledge.shareLearning = enabled;+ const { saveConfig } = await import('./utils/config.js');+ saveConfig(config);+ } catch { /* best-effort */ }+ }+ });++ cloudClient.on('conversation.history', async (msg) => {+ logger.info('Cloud command: conversation history');+ const requestId = typeof msg.payload?.requestId === 'string' ? msg.payload.requestId : '';+ try {+ const payload = buildConversationHistoryPayload(sessions, {+ requestId,+ sessionId: typeof msg.payload?.sessionId === 'string' ? msg.payload.sessionId : undefined,+ cursor: typeof msg.payload?.cursor === 'string' ? msg.payload.cursor : undefined,+ limit: typeof msg.payload?.limit === 'number' ? msg.payload.limit : undefined,+ }, config.cloud.agentId);+ cloudClient!.send({+ type: 'conversation.dump',+ agentId: config.cloud.agentId,+ payload,+ timestamp: new Date().toISOString(),+ });+ } catch (err: any) {+ cloudClient!.send({+ type: 'conversation.dump',+ agentId: config.cloud.agentId,+ payload: { requestId, error: err.message },+ timestamp: new Date().toISOString(),+ });+ }+ });++ cloudClient.on('agent.command', async (msg) => {+ const message = msg.payload?.message as string | undefined;+ const fromAgentId = msg.payload?.fromAgentId as string | undefined;+ const conversationId = msg.payload?.conversationId as string | undefined;+ const suppliedSessionId = msg.payload?.sessionId as string | undefined;+ const requestId = (msg.payload?.requestId as string | undefined) || crypto.randomUUID();+ const messageId = msg.payload?.messageId as string | undefined;+ const providerOverride = msg.payload?.provider as string | undefined;+ const controlType = msg.payload?.controlType as string | undefined;++ const allowedControlTypes = new Set([+ 'session.create', 'session.delete', 'session.archive', 'permission.resolve', 'choice.resolve',+ 'interaction.cancel', 'permission.mode', 'model.list', 'model.select',+ ]);+ if ((msg.agentId && msg.agentId !== config.cloud.agentId)+ || (controlType && (!allowedControlTypes.has(controlType) || typeof message === 'string'))+ || (!controlType && typeof message !== 'string')) {+ logger.warn({ type: controlType, agentId: msg.agentId }, 'Rejected invalid or mixed Cloud command envelope');+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'Invalid Cloud command envelope.' } });+ return;+ }++ if (controlType === 'session.delete') {+ if (!suppliedSessionId || msg.payload?.confirmation !== suppliedSessionId) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'Session deletion requires the exact session ID as confirmation.' } });+ return;+ }+ try {+ const target = sessions.get(suppliedSessionId);+ if (target.id !== suppliedSessionId) throw new Error('Session deletion requires the exact canonical session ID.');+ const deleted = sessions.deletePermanently(target.id);+ cloudClient!.sendStream({+ conversationId,+ sessionId: deleted.id,+ requestId,+ event: 'session_deleted',+ data: { sessionId: deleted.id },+ });+ } catch (error) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: error instanceof Error ? error.message : String(error) } });+ }+ return;+ }++ if (controlType === 'session.create') {+ if (!suppliedSessionId) {+ cloudClient!.sendStream({ conversationId, requestId, event: 'error', data: { message: 'Session creation requires a canonical session ID.' } });+ return;+ }+ try {+ const alias = typeof msg.payload?.alias === 'string' ? msg.payload.alias : undefined;+ const title = typeof msg.payload?.title === 'string' ? msg.payload.title : undefined;+ const titleSource = msg.payload?.titleSource === 'user' || msg.payload?.titleSource === 'generated' ? msg.payload.titleSource : 'fallback';+ const created = sessions.create({ id: suppliedSessionId, alias, title, titleSource });+ sessions.bind(created.id, 'web', `cloud:${conversationId || suppliedSessionId}`);+ cloudClient!.sendStream({+ conversationId,+ sessionId: created.id,+ requestId,+ event: 'session_created',+ data: { sessionId: created.id, alias: created.alias, title: created.title, revision: created.revision },+ });+ } catch (error) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: error instanceof Error ? error.message : String(error) } });+ }+ return;+ }++ if (controlType === 'permission.resolve' || controlType === 'choice.resolve' || controlType === 'interaction.cancel') {+ const id = msg.payload?.id as string | undefined;+ const value = controlType === 'permission.resolve'+ ? msg.payload?.action as string | undefined+ : msg.payload?.value as string | undefined;+ if (!suppliedSessionId || !id || (controlType !== 'interaction.cancel' && typeof value !== 'string')) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'Invalid or incomplete interaction resolution.' } });+ return;+ }+ const resolved = controlType === 'permission.resolve'+ ? webChannel.resolveApproval(id, value!, requestId)+ : controlType === 'choice.resolve'+ ? webChannel.resolveChoice(id, value!, requestId)+ : webChannel.cancelInteraction(id, requestId);+ const resolvedEvent = controlType === 'choice.resolve' || controlType === 'interaction.cancel' ? 'choice_resolved' : 'permission_resolved';+ cloudClient!.sendStream({+ conversationId,+ sessionId: suppliedSessionId,+ requestId,+ event: resolved ? resolvedEvent : 'error',+ data: resolved ? { id, value, cancelled: controlType === 'interaction.cancel' } : { message: 'Interaction expired, was already used, or does not belong to this request.' },+ });+ return;+ }++ if (controlType === 'permission.mode') {+ const action = msg.payload?.action;+ if (!suppliedSessionId || (action !== 'allow-all' && action !== 'ask-me')) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: 'Invalid permission mode request.' } });+ return;+ }+ webChannel.setSessionPermissionMode(suppliedSessionId, action);+ cloudClient!.sendStream({+ conversationId,+ sessionId: suppliedSessionId,+ requestId,+ event: 'permission_mode_set',+ data: { mode: action },+ });+ return;+ }++ const externalConversationId = `cloud:${conversationId || suppliedSessionId || 'default'}`;+ let cloudSession;+ try {+ cloudSession = sessions.getOrCreateBound('web', externalConversationId, suppliedSessionId);+ } catch (error) {+ cloudClient!.sendStream({ conversationId, sessionId: suppliedSessionId, requestId, event: 'error', data: { message: error instanceof Error ? error.message : String(error) } });+ return;+ }+ const sessionId = cloudSession.id;++ if (controlType === 'session.archive') {+ try {+ const archived = sessions.archive(sessionId);+ cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: 'session_archived',+ data: { sessionId: archived.id, revision: archived.revision },+ });+ } catch (error) {+ cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: 'error',+ data: { message: error instanceof Error ? error.message : String(error) },+ });+ }+ return;+ }++ if (controlType === 'model.list') {+ cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: 'model_options',+ data: {+ providers: await agent.listChatModelOptions(),+ current: agent.getCurrentProvider(),+ },+ });+ return;+ }++ if (controlType === 'model.select') {+ const provider = msg.payload?.provider as string | undefined;+ const model = msg.payload?.model as string | undefined;+ if (!provider) {+ cloudClient!.sendStream({ conversationId, sessionId, requestId, event: 'error', data: { message: 'No provider selected.' } });+ return;+ }++ const result = await agent.setChannelProviderOverride(sessionId, provider, model, { persist: true });+ cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: result.ok ? 'model_selected' : 'error',+ data: result.ok ? result : { message: result.message },+ });+ return;+ }++ if (message) {+ if (fromAgentId) {+ logger.info({ fromAgentId, messagePreview: message.slice(0, 50) }, 'Cloud relay: message from another agent');+ } else {+ logger.info({ messagePreview: message.slice(0, 50) }, 'Cloud command: send message to agent');+ }+ try {+ if (providerOverride) {+ const modelOverride = msg.payload?.model as string | undefined;+ const override = await agent.setChannelProviderOverride(sessionId, providerOverride, modelOverride);+ if (!override.ok) {+ cloudClient!.sendStream({ conversationId, sessionId, requestId, event: 'error', data: { message: override.message } });+ return;+ }+ }+ webChannel.emitCloudMessage(message, requestId, sessionId, externalConversationId, messageId, (event) => {+ const delivered = cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: event.type,+ data: event.data,+ });++ // When research mode produced a final article, also emit a+ // research.artifact message so the Cloud dashboard can render it+ // as a full research page (View Research).+ if (+ event.type === 'text_done' &&+ agent.researchMode.isActive() &&+ event.data &&+ typeof event.data.fullText === 'string' &&+ event.data.fullText.includes('# ')+ ) {+ const fullText = event.data.fullText as string;+ const titleMatch = fullText.match(/^#\s+(.+)$/m);+ cloudClient!.sendResearchArtifact({+ artifactId: `research-${conversationId || Date.now()}`,+ title: titleMatch ? titleMatch[1].trim() : undefined,+ markdown: fullText,+ conversationId,+ sessionId,+ requestId,+ topic: agent.researchMode.getTopic() || undefined,+ });+ // Research mode produced its artifact; exit research mode so+ // follow-ups in the same thread become refinements, not fresh+ // full-research passes, unless the user re-enables it.+ agent.researchMode.setOff();+ }+ return delivered;+ });+ cloudClient!.sendCommandAck(requestId);+ } catch (err: any) {+ cloudClient!.sendStream({+ conversationId,+ sessionId,+ requestId,+ event: 'error',+ data: { message: `Unable to process cloud chat message: ${err.message}` },+ });+ }+ }+ });++ cloudClient.on('agent.message.relay', async (msg) => {+ const targetAgentId = msg.payload?.targetAgentId as string | undefined;+ const relayMessage = msg.payload?.message as string | undefined;+ if (targetAgentId && relayMessage) {+ logger.info({ targetAgentId, messagePreview: relayMessage.slice(0, 50) }, 'Cloud: relaying message to another agent');+ cloudClient!.send({+ type: 'agent.message.relay',+ agentId: config.cloud.agentId,+ payload: { targetAgentId, message: relayMessage, fromAgentId: config.cloud.agentId },+ timestamp: new Date().toISOString(),+ });+ }+ });++ await cloudClient.connect();+ logger.info('Mercury Cloud WebSocket connected');++ // Fallback: if the server doesn't send conversation.sync.toggle within 5s+ // (e.g. message dropped or delayed), start sync anyway. The toggle handler+ // remains the authority and will stop it if the server says disabled.+ if (!syncSettingReceived) {+ syncFallbackTimer = setTimeout(() => {+ if (!syncSettingReceived && !activeSessionSynchronizer.isEnabled()) {+ logger.info('No conversation.sync.toggle received within 5s — starting sync as fallback');+ agent.setSessionSyncEnabled(true);+ activeSessionSynchronizer.start();+ }+ }, 5_000);+ syncFallbackTimer.unref?.();+ }+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Failed to start Mercury Cloud WS client');+ }+ }+const cliChannel = channels.get('cli') as CLIChannel | undefined;const tgChannel = channels.get('telegram') as TelegramChannel | undefined;const sigChannel = channels.get('signal') as SignalChannel | undefined;@@ -2279,6 +2939,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {}setWebWebChannel(webChannel);+ setWebSessionSyncEnabled(() => agent.isSessionSyncEnabled());setWebProgrammingMode(agent.programmingMode);setWebBgTasks(agent.backgroundTasks);setWebModelSwitch((provider) => agent.switchProvider(provider));@@ -2453,14 +3114,15 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {capabilities.permissions.onAsk(async (prompt: string) => {const channelType = capabilities.permissions.getCurrentChannelType();+ const { channelId } = capabilities.getChannelContext();if (channelType === 'telegram' && tgChannel) {- return tgChannel.askPermission(prompt);+ return tgChannel.askPermission(prompt, channelId);}if (channelType === 'signal' && channels.get('signal')) {- return (channels.get('signal') as SignalChannel).askPermission(prompt);+ return (channels.get('signal') as SignalChannel).askPermission(prompt, channelId);}if (channelType === 'web' && webChannel) {- return webChannel.askPermission(prompt);+ return webChannel.askPermission(prompt, channelId);}if (cliChannel) {return cliChannel.askPermission(prompt);@@ -2520,6 +3182,34 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {}// Keep CLI permission mode prompt, but do it after web server is live.+ if (cliChannel) {+ const current = sessions.getByBinding('cli', 'current');+ const recent = sessions.list().filter((session) => session.messages.length > 0);+ const resumable = [+ ...(current?.messages.length ? [current] : []),+ ...recent.filter((session) => session.id !== current?.id),+ ].slice(0, 5);++ let selected = current;+ if (process.stdout.isTTY && resumable.length > 0) {+ const choice = await cliChannel.presentChoicePrompt(+ 'Continue a previous session or start fresh?',+ [+ ...resumable.map((session) => ({+ value: session.id,+ label: `${session.alias} [${session.shortId}] - ${session.title} (${session.messages.length} messages)`,+ })),+ { value: 'new', label: 'Start a new session' },+ ],+ );+ selected = choice === 'new' ? sessions.create() : sessions.get(choice);+ sessions.bind(selected.id, 'cli', 'current');+ }++ selected ??= sessions.getOrCreateBound('cli', 'current');+ cliChannel.setCurrentSession(selected);+ }+const mode = cliChannel && await cliChannel.askPermissionMode?.();if (mode === 'allow-all') {capabilities.permissions.setAutoApproveAll(true);@@ -2546,29 +3236,37 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {logger.info({ channels: activeCh, tools: toolNames, web: config.web.enabled }, 'Mercury is live (daemon mode)');}- const shutdown = async () => {- if (!isDaemon) {- console.log('');- console.log(chalk.dim(` ${name} is shutting down...`));- } else {- logger.info('Mercury is shutting down (daemon mode)');- }- // Notify all channels that Mercury is stopping — users should never- // have to re-prompt to discover their task was killed mid-flight.- try {- await agent.notifyAllChannels('⚠ Mercury is shutting down. If I was working on something, it has been interrupted. Send a message after restart to continue.');- } catch { /* best effort */ }- if (userMemory) {+ let shutdownPromise: Promise<void> | undefined;+ const shutdown = (): Promise<void> => {+ if (shutdownPromise) return shutdownPromise;+ shutdownPromise = (async () => {+ cloudClient?.disconnect();+ sessionSynchronizer?.stop();+ if (!isDaemon) {+ console.log('');+ console.log(chalk.dim(` ${name} is shutting down...`));+ } else {+ logger.info('Mercury is shutting down (daemon mode)');+ }+ // Notify all channels that Mercury is stopping — users should never+ // have to re-prompt to discover their task was killed mid-flight.try {- userMemory.consolidate();- userMemory.close();- } catch {}- }- await stopWebServer();- await agent.shutdown();- process.exit(0);+ await agent.notifyAllChannels('⚠ Mercury is shutting down. If I was working on something, it has been interrupted. Send a message after restart to continue.');+ } catch { /* best effort */ }+ if (userMemory) {+ try {+ userMemory.consolidate();+ userMemory.close();+ } catch {}+ }+ await stopWebServer();+ await agent.shutdown();+ clearCloudRuntimeOnline();+ releaseRuntimeProcess(runtimeMode);+ process.exit(0);+ })();+ return shutdownPromise;};-process.on('SIGINT', shutdown);process.on('SIGTERM', shutdown);@@ -2643,9 +3341,24 @@ programprogram.command('stop')- .description('Stop a background Mercury process')+ .description('Stop a running Mercury process (daemon or foreground)').action(async () => {- await stopDaemon();+ const foreground = getForegroundRuntimeStatus();+ const daemon = getDaemonStatus();++ if (!foreground.running && !daemon.running) {+ console.log(chalk.yellow(' Mercury is not running.'));+ console.log('');+ return;+ }++ if (foreground.running) {+ await stopForegroundRuntime();+ }++ if (daemon.running) {+ await stopDaemon();+ }});program@@ -2799,6 +3512,42 @@ telegramCmdconsole.log('');});+telegramCmd+ .command('enable')+ .description('Enable Telegram channel if a bot token is configured')+ .action(() => {+ const config = loadConfig();+ if (!config.channels.telegram.botToken) {+ console.log('');+ console.log(chalk.red(' Telegram bot token is missing. Run `mercury doctor` to configure Telegram first.'));+ console.log('');+ return;+ }++ config.channels.telegram.enabled = true;+ saveConfig(config);+ console.log('');+ console.log(chalk.green(' ✓ Telegram channel enabled.'));+ if (getTelegramApprovedUsers(config).length === 0) {+ console.log(chalk.dim(' Send /start to the bot, then approve the pairing code with `mercury telegram approve <code>`.'));+ }+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });++telegramCmd+ .command('disable')+ .description('Disable Telegram channel without removing its bot token or access list')+ .action(() => {+ const config = loadConfig();+ config.channels.telegram.enabled = false;+ saveConfig(config);+ console.log('');+ console.log(chalk.green(' ✓ Telegram channel disabled.'));+ restartDaemonIfRunning('Restarting the background daemon to apply the change immediately...');+ console.log('');+ });+telegramCmd.command('approve <codeOrUserId>').description('Approve a pending Telegram access request by pairing code or user ID')@@ -3641,6 +4390,76 @@ programconsole.log('');});+const cloud = program.command('cloud').description('Manage Mercury Cloud connection');++cloud+ .command('connect')+ .description('Connect to Mercury Cloud via terminal pairing')+ .action(async () => {+ console.log('');+ const wasDaemonRunning = getDaemonStatus().running;+ try {+ const { runCloudConnect } = await import('./cloud/pairing-flow.js');+ await runCloudConnect();+ } catch (err: any) {+ console.log(chalk.red(` ✗ ${err.message || err}`));+ console.log('');+ return;+ }+ // Always launch the foreground TUI so the user can start chatting+ // immediately. The background daemon (started by runCloudConnect) keeps+ // the WebSocket alive even after the user exits the foreground.+ if (isSetupComplete()) {+ console.log(chalk.cyan('\n Launching Mercury...\n'));+ await runAgent();+ } else {+ console.log(chalk.cyan('\n Mercury daemon is running in the background. Run `mercury` to start chatting.'));+ console.log('');+ }+ });++cloud+ .command('disconnect')+ .description('Disconnect from Mercury Cloud and switch to offline (BYOK) mode')+ .action(async () => {+ console.log('');+ try {+ const { runCloudDisconnect } = await import('./cloud/pairing-flow.js');+ await runCloudDisconnect();+ } catch (err: any) {+ console.log(chalk.red(` ✗ ${err.message || err}`));+ }+ console.log('');+ });++cloud+ .command('status')+ .description('Show Mercury Cloud connection status')+ .action(async () => {+ console.log('');+ try {+ const { runCloudStatus } = await import('./cloud/pairing-flow.js');+ await runCloudStatus();+ } catch (err: any) {+ console.log(chalk.red(` ✗ ${err.message || err}`));+ }+ console.log('');+ });++cloud+ .command('login')+ .description('Refresh Mercury Cloud authentication token')+ .action(async () => {+ console.log('');+ try {+ const { runCloudLogin } = await import('./cloud/pairing-flow.js');+ await runCloudLogin();+ } catch (err: any) {+ console.log(chalk.red(` ✗ ${err.message || err}`));+ }+ console.log('');+ });+registerSkillsCommand(program);program.parse();diff --git a/src/memory/second-brain-db.ts b/src/memory/second-brain-db.tsindex 421daae8..811b96c7 100644--- a/src/memory/second-brain-db.ts+++ b/src/memory/second-brain-db.ts@@ -42,6 +42,8 @@ export interface MemoryRow {id: string;user_key: string;type: string;+ categories: string;+ shareable: number;summary: string;detail: string | null;scope: string;@@ -113,6 +115,8 @@ export class SecondBrainDB {id TEXT PRIMARY KEY,user_key TEXT NOT NULL,type TEXT NOT NULL,+ categories TEXT NOT NULL DEFAULT '[]',+ shareable INTEGER NOT NULL DEFAULT 0,summary TEXT NOT NULL,detail TEXT,scope TEXT NOT NULL DEFAULT 'durable',@@ -221,18 +225,35 @@ export class SecondBrainDB {`);this.db.pragma('foreign_keys = ON');++ // ── Migrations for existing DBs ──────────────────────────────────────────+ // Add `categories` and `shareable` columns if the table predates them.+ // Existing memories get categories='[]' and shareable=0 (private).+ const columns = this.db.prepare('PRAGMA table_info(memories)').all() as { name: string }[];+ if (!columns.some((c) => c.name === 'categories')) {+ this.db.exec("ALTER TABLE memories ADD COLUMN categories TEXT NOT NULL DEFAULT '[]'");+ logger.info('Added categories column to memories table');+ }+ if (!columns.some((c) => c.name === 'shareable')) {+ this.db.exec('ALTER TABLE memories ADD COLUMN shareable INTEGER NOT NULL DEFAULT 0');+ logger.info('Added shareable column to memories table');+ }++ // Index for incremental fetch (shareable + updated_at — the cloud pull query).+ this.db.exec('CREATE INDEX IF NOT EXISTS idx_memories_shareable_updated ON memories(shareable, updated_at)');+logger.info('Second brain database initialized');}insert(row: Omit<MemoryRow, 'rowid'> & { rowid?: never }): void {const stmt = this.db.prepare(`INSERT INTO memories (- id, user_key, type, summary, detail, scope, evidence_kind, source,+ id, user_key, type, categories, shareable, summary, detail, scope, evidence_kind, source,confidence, importance, durability, evidence_count, provenance,dismissed, superseded_by, created_at, updated_at,last_seen_at, last_used_at, last_used_query) VALUES (- @id, @user_key, @type, @summary, @detail, @scope, @evidence_kind, @source,+ @id, @user_key, @type, @categories, @shareable, @summary, @detail, @scope, @evidence_kind, @source,@confidence, @importance, @durability, @evidence_count, @provenance,@dismissed, @superseded_by, @created_at, @updated_at,@last_seen_at, @last_used_at, @last_used_query@@ -242,6 +263,8 @@ export class SecondBrainDB {id: row.id,user_key: row.user_key,type: row.type,+ categories: row.categories ?? '[]',+ shareable: row.shareable ?? 0,summary: row.summary,detail: row.detail ?? null,scope: row.scope ?? 'durable',@@ -271,6 +294,7 @@ export class SecondBrainDB {'confidence', 'importance', 'durability', 'evidence_count','provenance', 'dismissed', 'superseded_by','updated_at', 'last_seen_at', 'last_used_at', 'last_used_query',+ 'categories', 'shareable',] as const;for (const field of allowedFields) {@@ -296,6 +320,42 @@ export class SecondBrainDB {return stmt.get(id) as MemoryRow | undefined;}+ /**+ * Incremental fetch query — shareable memories newer than the cursor.+ * Used by the cloud `memory.fetch` handler to pull only memories created or+ * updated since the last fetch (watermark stored in MemorySyncState).+ * Excludes dismissed rows. Ordered by `updated_at ASC` so the cloud can+ * advance its cursor to the max `updated_at` safely.+ */+ getShareableSince(userKey: string, since: number, limit: number = 500): MemoryRow[] {+ const stmt = this.db.prepare(`+ SELECT * FROM memories+ WHERE user_key = ? AND shareable = 1 AND dismissed = 0+ AND updated_at > ?+ ORDER BY updated_at ASC+ LIMIT ?+ `);+ return stmt.all(userKey, since, limit) as MemoryRow[];+ }++ /** Count shareable memories (for display / config). */+ countShareable(userKey: string): number {+ const stmt = this.db.prepare('SELECT COUNT(*) as count FROM memories WHERE user_key = ? AND shareable = 1 AND dismissed = 0');+ return (stmt.get(userKey) as { count: number }).count;+ }++ /** List all shareable memories (for the /memory menu "Shared Memories" view). */+ getShareable(userKey: string, limit: number = 50): MemoryRow[] {+ const stmt = this.db.prepare(`SELECT * FROM memories WHERE user_key = ? AND shareable = 1 AND dismissed = 0 ORDER BY updated_at DESC LIMIT ?`);+ return stmt.all(userKey, limit) as MemoryRow[];+ }++ /** Toggle a memory's shareable flag on/off. */+ setShareable(id: string, shareable: boolean): void {+ const stmt = this.db.prepare('UPDATE memories SET shareable = ?, updated_at = ? WHERE id = ?');+ stmt.run(shareable ? 1 : 0, Date.now(), id);+ }+getByType(userKey: string, type: string): MemoryRow[] {const stmt = this.db.prepare(`SELECT * FROM memories WHERE user_key = ? AND type = ? AND dismissed = 0 AND scope IN ('active', 'durable') ORDER BY updated_at DESC`);return stmt.all(userKey, type) as MemoryRow[];diff --git a/src/memory/user-memory.test.ts b/src/memory/user-memory.test.tsindex 762285e4..633d3fcb 100644--- a/src/memory/user-memory.test.ts+++ b/src/memory/user-memory.test.ts@@ -295,6 +295,8 @@ describe('UserMemoryStore', () => {id: `mem_test_${i}`,user_key: 'user:owner',type: i % 2 === 0 ? 'preference' : 'identity',+ categories: '[]',+ shareable: 0,summary: `Distinct memory observation number ${i} with completely different content about topic ${i}.`,detail: null,scope: i % 3 === 0 ? 'active' : 'durable',diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex e96cb380..ffac1d39 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -19,6 +19,8 @@ export type UserMemoryType =export interface UserMemoryRecord {id: string;type: UserMemoryType;+ categories: string[];+ shareable: boolean;summary: string;detail?: string | null;scope: 'durable' | 'active' | 'subconscious';@@ -42,6 +44,8 @@ export interface UserMemoryCandidate {type: UserMemoryType;summary: string;detail?: string;+ categories?: string[];+ shareable?: boolean;evidenceKind?: 'direct' | 'inferred';confidence: number;importance: number;@@ -85,15 +89,27 @@ export class UserMemoryStore {private userKey: string;private consolidateThrottleMs: number;private lastConsolidateAt: number = 0;+ /** When true, new memories are marked shareable for cloud fetch. */+ private shareLearning: boolean;constructor(config: MercuryConfig, userKey: string = 'user:owner', dbPath?: string) {this.userKey = userKey;this.consolidateThrottleMs = 5 * 60 * 1000;+ this.shareLearning = config.memory.collaborativeKnowledge?.shareLearning ?? false;const resolvedDbPath = dbPath ?? join(getMemoryDir(), 'second-brain', 'second-brain.db');this.db = new SecondBrainDB(resolvedDbPath);this.db.init();}+ /** Toggle whether new memories are marked shareable. */+ setShareLearning(enabled: boolean): void {+ this.shareLearning = enabled;+ }++ isShareLearning(): boolean {+ return this.shareLearning;+ }+getSummary(): UserMemorySummary {const byType = this.db.countByType(this.userKey) as Partial<Record<UserMemoryType, number>>;return {@@ -119,6 +135,32 @@ export class UserMemoryStore {return stmt.map(row => this.toRecord(row));}+ /**+ * Incremental fetch — shareable memories newer than the cursor. Used by the+ * cloud `memory.fetch` WS handler. Returns records ordered by `updatedAt`+ * ascending so the caller can advance its watermark to the max.+ */+ getShareableSince(since: number, limit: number = 500): UserMemoryRecord[] {+ const rows = this.db.getShareableSince(this.userKey, since, limit);+ return rows.map(row => this.toRecord(row));+ }++ /** Count of shareable memories (for display). */+ countShareable(): number {+ return this.db.countShareable(this.userKey);+ }++ /** List shareable memories (for the /memory menu "Shared Memories" view). */+ getShareable(limit: number = 50): UserMemoryRecord[] {+ const rows = this.db.getShareable(this.userKey, limit);+ return rows.map(row => this.toRecord(row));+ }++ /** Toggle a memory's shareable flag. */+ setShareable(id: string, shareable: boolean): void {+ this.db.setShareable(id, shareable);+ }+search(query: string, limit: number = 10): UserMemoryRecord[] {const rows = this.db.searchFTS(this.userKey, query, limit);return rows.map(row => this.toRecord(row));@@ -249,6 +291,16 @@ export class UserMemoryStore {): UserMemoryRecord[] {if (this.isLearningPaused()) return [];+ // Stamp shareable based on the shareLearning toggle. Candidates that+ // explicitly set shareable (e.g. manual saves via the web API) keep their+ // value; others inherit the global toggle. Forward-only — existing+ // memories are never retroactively flipped.+ for (const candidate of candidates) {+ if (candidate.shareable === undefined) {+ candidate.shareable = this.shareLearning;+ }+ }+const remembered: UserMemoryRecord[] = [];for (const candidate of candidates) {@@ -384,6 +436,8 @@ export class UserMemoryStore {id,user_key: this.userKey,type: candidate.type,+ categories: JSON.stringify(candidate.categories ?? []),+ shareable: candidate.shareable ? 1 : 0,summary: candidate.summary.trim(),detail: candidate.detail?.trim() ?? null,scope,@@ -415,6 +469,8 @@ export class UserMemoryStore {id,user_key: this.userKey,type: 'reflection',+ categories: '[]',+ shareable: 0,summary: candidate.summary,detail: candidate.detail ?? null,scope: 'durable',@@ -437,6 +493,9 @@ export class UserMemoryStore {private mergeRecord(existing: MemoryRow, candidate: UserMemoryCandidate): UserMemoryRecord | null {const updatedAt = Date.now();+ // If the incoming candidate is shareable, promote the existing record to+ // shareable too (forward-only — never demotes a shareable memory).+ const promoteShareable = candidate.shareable && existing.shareable !== 1;this.db.update({id: existing.id,summary: pickBetterSummary(existing.summary, candidate.summary),@@ -447,6 +506,7 @@ export class UserMemoryStore {importance: clamp(Math.max(existing.importance, candidate.importance), 0, 1),durability: clamp(Math.max(existing.durability, candidate.durability), 0, 1),evidence_count: existing.evidence_count + 1,+ shareable: promoteShareable ? 1 : existing.shareable,updated_at: updatedAt,last_seen_at: updatedAt,});@@ -637,9 +697,16 @@ export class UserMemoryStore {}private toRecord(row: MemoryRow): UserMemoryRecord {+ let categories: string[] = [];+ try {+ const parsed = JSON.parse(row.categories ?? '[]');+ if (Array.isArray(parsed)) categories = parsed as string[];+ } catch { /* malformed */ }return {id: row.id,type: row.type as UserMemoryType,+ categories,+ shareable: row.shareable === 1,summary: row.summary,detail: row.detail,scope: row.scope as 'durable' | 'active' | 'subconscious',diff --git a/src/providers/mercury-cloud.test.ts b/src/providers/mercury-cloud.test.tsnew file mode 100644index 00000000..92c666c2--- /dev/null+++ b/src/providers/mercury-cloud.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it, vi } from 'vitest';+import type { CloudTokenStore } from '../cloud/token-store.js';++const { createOpenAIMock } = vi.hoisted(() => ({ createOpenAIMock: vi.fn() }));+vi.mock('@ai-sdk/openai', () => ({ createOpenAI: createOpenAIMock }));++import { MercuryCloudProvider } from './mercury-cloud.js';++describe('MercuryCloudProvider authentication', () => {+ it('uses the shared agent credentials and releases its token listener', () => {+ const removeListener = vi.fn();+ const store = {+ getJwt: vi.fn(() => 'jwt-1'),+ getAgentId: vi.fn(() => 'agent-1'),+ getAgentApiKey: vi.fn(() => 'mcapk_1'),+ addListener: vi.fn(() => removeListener),+ } as unknown as CloudTokenStore;+ const languageModel = vi.fn(() => ({ modelId: 'mercury-flash' }));+ createOpenAIMock.mockReturnValue({ chat: languageModel });++ const provider = new MercuryCloudProvider({+ name: 'mercuryCloud',+ apiKey: 'stale-jwt',+ baseUrl: 'https://api.example.com',+ model: 'mercury-flash',+ enabled: true,+ }, store);++ expect(createOpenAIMock).toHaveBeenCalledWith(expect.objectContaining({+ apiKey: 'jwt-1',+ headers: {+ 'X-Agent-Id': 'agent-1',+ },+ }));++ provider.destroy();+ expect(removeListener).toHaveBeenCalledOnce();+ });+});diff --git a/src/providers/mercury-cloud.ts b/src/providers/mercury-cloud.tsnew file mode 100644index 00000000..724b73f3--- /dev/null+++ b/src/providers/mercury-cloud.ts@@ -0,0 +1,182 @@+import { createOpenAI } from '@ai-sdk/openai';+import { generateText, streamText } from 'ai';+import { BaseProvider } from './base.js';+import type { ProviderConfig } from '../utils/config.js';+import type { LLMResponse, LLMStreamChunk } from './base.js';+import { logger } from '../utils/logger.js';+import type { CloudTokenStore } from '../cloud/token-store.js';++export class MercuryCloudProvider extends BaseProvider {+ readonly name: string;+ readonly model: string;+ private client: ReturnType<typeof createOpenAI>;+ private modelInstance: ReturnType<ReturnType<typeof createOpenAI>['languageModel']>;+ private tokenStore: CloudTokenStore | null;+ private removeTokenListener: (() => void) | null = null;++ constructor(config: ProviderConfig, tokenStore: CloudTokenStore | null = null) {+ super(config);+ this.name = config.name;+ this.model = config.model;+ this.tokenStore = tokenStore;++ const jwt = tokenStore?.getJwt() ?? config.apiKey ?? 'cloud-jwt-placeholder';+ this.client = createOpenAI({+ apiKey: jwt,+ baseURL: config.baseUrl?.endsWith('/v1') ? config.baseUrl : `${config.baseUrl}/v1`,+ headers: this.cloudHeaders(),+ });+ this.modelInstance = this.client.chat(config.model);++ // Swap the cached JWT whenever the shared token store rotates. This+ // replaces the old independent 3-minute proactive refresh timer, which+ // raced the WS client for the single-use refresh token and eventually+ // burned it.+ if (tokenStore) {+ this.removeTokenListener = tokenStore.addListener((tokens) => {+ this.rebuildClient(tokens.jwt);+ });+ }+ }++ private cloudHeaders(): Record<string, string> | undefined {+ if (!this.tokenStore) return undefined;+ return { 'X-Agent-Id': this.tokenStore.getAgentId() };+ }++ private rebuildClient(jwt: string): void {+ const baseUrl = this.config.baseUrl || '';+ this.client = createOpenAI({+ apiKey: jwt,+ baseURL: baseUrl.endsWith('/v1') ? baseUrl : `${baseUrl}/v1`,+ headers: this.cloudHeaders(),+ });+ this.modelInstance = this.client.chat(this.model);+ }++ destroy(): void {+ this.removeTokenListener?.();+ this.removeTokenListener = null;+ }++ async generateText(prompt: string, systemPrompt: string): Promise<LLMResponse> {+ await this.ensureFreshToken().catch(() => {});++ try {+ const result = await generateText({+ model: this.modelInstance,+ system: systemPrompt,+ prompt,+ });++ return {+ text: result.text,+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ model: this.model,+ provider: this.name,+ };+ } catch (err: any) {+ if (this.isRetryableError(err) && this.tokenStore) {+ logger.warn('Mercury Cloud 401 — refreshing token and retrying...');+ try {+ const rotated = await this.tokenStore.rotate();+ this.rebuildClient(rotated.jwt);+ } catch (rotateErr: any) {+ logger.warn({ err: rotateErr.message }, 'Mercury Cloud reactive refresh failed');+ throw err;+ }+ const result = await generateText({+ model: this.modelInstance,+ system: systemPrompt,+ prompt,+ });++ return {+ text: result.text,+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ model: this.model,+ provider: this.name,+ };+ }+ throw err;+ }+ }++ async *streamText(prompt: string, systemPrompt: string): AsyncIterable<LLMStreamChunk> {+ await this.ensureFreshToken().catch(() => {});++ try {+ const result = streamText({+ model: this.modelInstance,+ system: systemPrompt,+ prompt,+ });++ for await (const chunk of (await result).textStream) {+ yield { text: chunk, done: false };+ }+ yield { text: '', done: true };+ } catch (err: any) {+ // streamText previously had no 401-retry path, which meant a streaming+ // chat would fail where a non-streaming chat would recover. Retry once+ // after a reactive rotation.+ if (!this.isRetryableError(err) || !this.tokenStore) throw err;+ logger.warn('Mercury Cloud stream 401 — refreshing token and retrying...');+ try {+ const rotated = await this.tokenStore.rotate();+ this.rebuildClient(rotated.jwt);+ } catch (rotateErr: any) {+ logger.warn({ err: rotateErr.message }, 'Mercury Cloud reactive stream refresh failed');+ throw err;+ }+ const result = streamText({+ model: this.modelInstance,+ system: systemPrompt,+ prompt,+ });+ for await (const chunk of (await result).textStream) {+ yield { text: chunk, done: false };+ }+ yield { text: '', done: true };+ }+ }++ isAvailable(): boolean {+ return this.config.model.length > 0;+ }++ private isRetryableError(err: any): boolean {+ const status = err?.statusCode ?? err?.status ?? err?.response?.status;+ if (typeof status === 'number') return status === 401;+ const msg = err?.message || '';+ return msg.includes('401') || msg.includes('Unauthorized');+ }++ async ensureFreshToken(): Promise<void> {+ if (!this.tokenStore) return;+ try {+ const jwt = await this.tokenStore.rotateIfExpired();+ this.rebuildClient(jwt);+ } catch (err: any) {+ logger.warn({ err: err.message }, 'Mercury Cloud token refresh failed');+ }+ }++ async getModelInstanceAsync(): Promise<any> {+ await this.ensureFreshToken();+ return this.modelInstance;+ }++ getModelInstance(): any {+ if (this.tokenStore?.isJwtNearExpiry()) {+ this.tokenStore.rotateIfExpired().catch((err) => {+ logger.warn({ err: err.message }, 'Mercury Cloud token refresh failed in getModelInstance');+ });+ }+ return this.modelInstance;+ }+}diff --git a/src/providers/registry.test.ts b/src/providers/registry.test.tsnew file mode 100644index 00000000..30986aed--- /dev/null+++ b/src/providers/registry.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';+import type { BaseProvider } from './base.js';+import { ProviderRegistry } from './registry.js';++function provider(name: string, model: string): BaseProvider {+ return {+ name,+ getModel: () => model,+ } as BaseProvider;+}++describe('ProviderRegistry live default', () => {+ it('switches the runtime default immediately and clears a previous fallback winner', () => {+ const registry = new (ProviderRegistry as any)('first') as ProviderRegistry;+ registry.set('first', provider('first', 'model-a'));+ registry.set('second', provider('second', 'model-b'));+ registry.markSuccess('first');++ registry.setDefault('second');++ expect(registry.getDefault().name).toBe('second');+ expect(registry.getDefault().getModel()).toBe('model-b');+ });+});diff --git a/src/providers/registry.ts b/src/providers/registry.tsindex 2de70f09..95de5fb1 100644--- a/src/providers/registry.ts+++ b/src/providers/registry.ts@@ -3,8 +3,11 @@ import { isProviderConfigured } from '../utils/config.js';import type { BaseProvider } from './base.js';import { logger } from '../utils/logger.js';-async function createProvider(pc: ProviderConfig): Promise<BaseProvider> {- if (pc.name === 'anthropic') {+export async function createProvider(pc: ProviderConfig, tokenStore?: import('../cloud/token-store.js').CloudTokenStore | null): Promise<BaseProvider> {+ if (pc.name === 'mercuryCloud') {+ const { MercuryCloudProvider } = await import('./mercury-cloud.js');+ return new MercuryCloudProvider(pc, tokenStore ?? null);+ } else if (pc.name === 'anthropic') {const { AnthropicProvider } = await import('./anthropic.js');return new AnthropicProvider(pc);} else if (pc.name === 'deepseek') {@@ -45,10 +48,15 @@ export class ProviderRegistry {this.defaultName = defaultName;}- static async create(config: MercuryConfig): Promise<ProviderRegistry> {+ static async create(config: MercuryConfig, tokenStore?: import('../cloud/token-store.js').CloudTokenStore | null): Promise<ProviderRegistry> {const registry = new ProviderRegistry(config.providers.default);const entries: ProviderConfig[] = [+ {+ ...config.providers.mercuryCloud,+ apiKey: config.providers.mercuryCloud.apiKey || config.cloud.jwt,+ baseUrl: config.cloud.apiUrl || config.providers.mercuryCloud.baseUrl,+ },config.providers.deepseek,config.providers.openai,config.providers.anthropic,@@ -66,7 +74,7 @@ export class ProviderRegistry {const configured = entries.filter(pc => isProviderConfigured(pc));const results = await Promise.allSettled(configured.map(async (pc) => {- const provider = await createProvider(pc);+ const provider = await createProvider(pc, pc.name === 'mercuryCloud' ? tokenStore : undefined);return { name: pc.name, model: pc.model, provider };}));@@ -89,6 +97,23 @@ export class ProviderRegistry {return this.providers.get(key);}+ set(name: string, provider: BaseProvider): void {+ const existing = this.providers.get(name) as (BaseProvider & { destroy?: () => void }) | undefined;+ existing?.destroy?.();+ this.providers.set(name, provider);+ }++ setDefault(name: string): void {+ if (!this.providers.has(name)) throw new Error(`Provider is not registered: ${name}`);+ this.defaultName = name;+ this.lastSuccessful = null;+ }++ updateApiKey(name: string, apiKey: string): void {+ const provider = this.providers.get(name) as (BaseProvider & { updateToken?: (token: string) => void }) | undefined;+ provider?.updateToken?.(apiKey);+ }+getDefault(): BaseProvider {if (this.lastSuccessful) {const provider = this.providers.get(this.lastSuccessful);@@ -104,9 +129,10 @@ export class ProviderRegistry {return provider;}- getFallbackIterator(): IterableIterator<BaseProvider> {+ getFallbackIterator(preferredName?: string): IterableIterator<BaseProvider> {const ordered: BaseProvider[] = [];- const defaultProvider = this.getDefault();+ const preferredProvider = preferredName ? this.providers.get(preferredName) : undefined;+ const defaultProvider = preferredProvider || this.getDefault();ordered.push(defaultProvider);for (const [, provider] of this.providers) {if (provider !== defaultProvider) {@@ -127,4 +153,11 @@ export class ProviderRegistry {hasProviders(): boolean {return this.providers.size > 0;}++ destroy(): void {+ for (const provider of this.providers.values()) {+ (provider as BaseProvider & { destroy?: () => void }).destroy?.();+ }+ this.providers.clear();+ }}diff --git a/src/sessions/cloud-sync.test.ts b/src/sessions/cloud-sync.test.tsnew file mode 100644index 00000000..43fea9a4--- /dev/null+++ b/src/sessions/cloud-sync.test.ts@@ -0,0 +1,122 @@+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { Session } from './types.js';+import { buildSessionSyncBatches, CloudSessionSynchronizer } from './cloud-sync.js';+import { SessionRepository } from './repository.js';++afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++function makeSession(index: number, messageCount: number): Session {+ const id = `${index.toString(16).padStart(8, '0')}-1111-4111-8111-${index.toString(16).padStart(12, '0')}`;+ return {+ id,+ shortId: id.slice(0, 8),+ alias: `session-${index}`,+ title: `Session ${index}`,+ titleSource: 'generated',+ createdAt: index,+ updatedAt: index,+ status: 'active',+ revision: 1,+ bindings: [],+ messages: Array.from({ length: messageCount }, (_, sequence) => ({+ id: `${sequence.toString(16).padStart(8, '0')}-2222-4222-8222-${sequence.toString(16).padStart(12, '0')}`,+ sessionId: id,+ role: 'user' as const,+ kind: 'message' as const,+ content: String(sequence),+ timestamp: sequence,+ sequence: sequence + 1,+ })),+ };+}++describe('buildSessionSyncBatches', () => {+ it('serializes canonical timestamps and respects cloud batch limits', () => {+ const first = makeSession(1, 5_001);+ (first.messages[0] as any).reasoning = [{ type: 'reasoning', text: 'legacy shape' }];+ const batches = buildSessionSyncBatches('agent-1', [first, ...Array.from({ length: 101 }, (_, index) => makeSession(index + 2, 0))]);+ expect(batches.every((batch) => batch.sessions.length <= 100 && batch.messages.length <= 5_000)).toBe(true);+ expect(batches.flatMap((batch) => batch.messages)).toHaveLength(5_001);+ expect(new Set(batches.flatMap((batch) => batch.sessions.map((session) => session.id))).size).toBe(102);+ expect(batches[0].sessions[0].agentId).toBe('agent-1');+ expect(batches[0].sessions[0].createdAt).toMatch(/^1970-/);+ expect(batches[0].sessions[0]).not.toHaveProperty('shortId');+ expect(batches.flatMap((batch) => batch.messages)[0]).not.toHaveProperty('agentId');+ expect(batches.flatMap((batch) => batch.messages)[0].reasoning).toBe('[{"type":"reasoning","text":"legacy shape"}]');+ expect(buildSessionSyncBatches('agent-1', [])).toEqual([]);+ });++ it('syncs in the background after debounce and retries transient failures', async () => {+ vi.useFakeTimers();+ const repository = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-sync-')), autoMigrate: false });+ const session = repository.create();+ repository.appendMessage(session.id, { role: 'user', content: 'hello', externalMessageId: 'local-only-id' });+ const fetchMock = vi.fn()+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValue({ ok: true, text: async () => '' });+ vi.stubGlobal('fetch', fetchMock);+ const synchronizer = new CloudSessionSynchronizer(repository, () => ({+ apiUrl: 'https://api.example.com',+ agentId: 'aaaaaaaa-1111-4111-8111-111111111111',+ token: 'token',+ }), 50);++ expect(synchronizer.isEnabled()).toBe(false);+ await vi.advanceTimersByTimeAsync(5_000);+ expect(fetchMock).not.toHaveBeenCalled();+ synchronizer.start();+ expect(synchronizer.isEnabled()).toBe(true);+ await vi.advanceTimersByTimeAsync(0);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(fetchMock).toHaveBeenCalledTimes(2);++ repository.appendMessage(session.id, { role: 'assistant', content: 'hi' });+ await vi.advanceTimersByTimeAsync(49);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ const body = JSON.parse(fetchMock.mock.calls[2][1].body as string);+ expect(Object.keys(body).sort()).toEqual(['messages', 'sessions']);+ expect(body.messages).toHaveLength(2);+ expect(body.messages[0]).not.toHaveProperty('externalMessageId');+ synchronizer.stop();+ expect(synchronizer.isEnabled()).toBe(false);+ repository.appendMessage(session.id, { role: 'assistant', content: 'stays local' });+ await vi.advanceTimersByTimeAsync(5_000);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });++ it('aborts an in-flight sync when stopped', async () => {+ vi.useFakeTimers();+ const repository = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-sync-stop-')), autoMigrate: false });+ const session = repository.create();+ repository.appendMessage(session.id, { role: 'user', content: 'hello' });+ let requestSignal: AbortSignal | undefined;+ vi.stubGlobal('fetch', vi.fn((_url, init: RequestInit = {}) => {+ requestSignal = init.signal ?? undefined;+ return new Promise((_resolve, reject) => {+ requestSignal?.addEventListener('abort', () => reject(requestSignal?.reason), { once: true });+ });+ }));+ const synchronizer = new CloudSessionSynchronizer(repository, () => ({+ apiUrl: 'https://api.example.com',+ agentId: 'aaaaaaaa-1111-4111-8111-111111111111',+ token: 'token',+ }));++ synchronizer.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(requestSignal?.aborted).toBe(false);+ synchronizer.stop();+ await vi.advanceTimersByTimeAsync(0);+ expect(requestSignal?.aborted).toBe(true);+ expect(synchronizer.isEnabled()).toBe(false);+ });+});diff --git a/src/sessions/cloud-sync.ts b/src/sessions/cloud-sync.tsnew file mode 100644index 00000000..9f18d04a--- /dev/null+++ b/src/sessions/cloud-sync.ts@@ -0,0 +1,175 @@+import type { Session, SessionMessage } from './types.js';+import type { SessionRepository } from './repository.js';+import { logger } from '../utils/logger.js';++export interface SessionSyncConfig {+ apiUrl: string;+ agentId: string;+ token: string;+}++interface SerializedSession extends Pick<Session, 'id' | 'alias' | 'title' | 'titleSource' | 'status' | 'revision'> {+ agentId: string;+ createdAt: string;+ updatedAt: string;+}++interface SerializedMessage extends Omit<SessionMessage, 'timestamp' | 'externalMessageId'> {+ timestamp: string;+}++export interface SessionSyncBatch {+ sessions: SerializedSession[];+ messages: SerializedMessage[];+}++export function buildSessionSyncBatches(agentId: string, sessions: Session[]): SessionSyncBatch[] {+ const batches: SessionSyncBatch[] = [];+ let current: SessionSyncBatch = { sessions: [], messages: [] };++ const flush = () => {+ if (current.sessions.length || current.messages.length) batches.push(current);+ current = { sessions: [], messages: [] };+ };++ const sorted = [...sessions].sort((a, b) => b.updatedAt - a.updatedAt);+ for (const session of sorted) {+ const serializedSession: SerializedSession = {+ id: session.id,+ alias: session.alias,+ title: session.title,+ titleSource: session.titleSource,+ status: session.status,+ revision: session.revision,+ agentId,+ createdAt: new Date(session.createdAt).toISOString(),+ updatedAt: new Date(session.updatedAt).toISOString(),+ };+ const messages: SerializedMessage[] = session.messages.map(({ externalMessageId: _, ...message }) => ({+ ...message,+ reasoning: typeof message.reasoning === 'string'+ ? message.reasoning+ : message.reasoning == null+ ? undefined+ : JSON.stringify(message.reasoning),+ timestamp: new Date(message.timestamp).toISOString(),+ }));++ if (messages.length === 0) {+ if (current.sessions.length >= 100) flush();+ current.sessions.push(serializedSession);+ continue;+ }++ let offset = 0;+ while (offset < messages.length) {+ const alreadyIncluded = current.sessions.some((item) => item.id === session.id);+ if (current.messages.length >= 5000 || (!alreadyIncluded && current.sessions.length >= 100)) flush();+ if (!current.sessions.some((item) => item.id === session.id)) current.sessions.push(serializedSession);+ const capacity = 5000 - current.messages.length;+ current.messages.push(...messages.slice(offset, offset + capacity));+ offset += capacity;+ if (current.messages.length >= 5000) flush();+ }+ }+ flush();+ return batches;+}++export class CloudSessionSynchronizer {+ private timer: ReturnType<typeof setTimeout> | null = null;+ private running = false;+ private dirty = false;+ private active = false;+ private retryMs = 1_000;+ private unsubscribe?: () => void;+ private abortController: AbortController | null = null;++ constructor(+ private repository: SessionRepository,+ private getConfig: () => SessionSyncConfig,+ private debounceMs = 1_000,+ ) {}++ start(): void {+ if (this.active) {+ this.requestSync(0);+ return;+ }+ this.active = true;+ if (!this.unsubscribe) this.unsubscribe = this.repository.subscribe(() => this.requestSync());+ this.requestSync(0);+ }++ stop(): void {+ this.active = false;+ this.unsubscribe?.();+ this.unsubscribe = undefined;+ if (this.timer) clearTimeout(this.timer);+ this.timer = null;+ this.abortController?.abort();+ this.abortController = null;+ }++ isEnabled(): boolean {+ return this.active;+ }++ requestSync(delayMs = this.debounceMs): void {+ if (!this.active) return;+ this.dirty = true;+ if (this.timer || this.running) return;+ this.timer = setTimeout(() => {+ this.timer = null;+ void this.syncNow();+ }, delayMs);+ this.timer.unref?.();+ }++ private async syncNow(): Promise<void> {+ if (this.running) return;+ this.running = true;+ this.dirty = false;+ const abortController = new AbortController();+ this.abortController = abortController;+ try {+ const config = this.getConfig();+ if (!config.apiUrl || !config.agentId || !config.token) throw new Error('Cloud session sync is not configured');+ const snapshot = this.repository.dump();+ const deletedSessionIds = snapshot.filter((session) => session.status === 'deleted').map((session) => session.id);+ const batches = buildSessionSyncBatches(config.agentId, snapshot);+ let sessionCount = 0;+ let messageCount = 0;+ for (let index = 0; index < batches.length; index++) {+ const batch = batches[index];+ const response = await fetch(`${config.apiUrl.replace(/\/$/, '')}/v1/agents/${encodeURIComponent(config.agentId)}/sessions/sync`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` },+ body: JSON.stringify(batch),+ signal: AbortSignal.any([abortController.signal, AbortSignal.timeout(15_000)]),+ });+ if (!response.ok) {+ const detail = (await response.text().catch(() => '')).slice(0, 300);+ throw new Error(`HTTP ${response.status}${detail ? `: ${detail}` : ''}`);+ }+ sessionCount += batch.sessions.length;+ messageCount += batch.messages.length;+ }+ if (this.active) this.repository.purgeDeleted(deletedSessionIds);+ this.retryMs = 1_000;+ if (this.active && batches.length) logger.info({ batches: batches.length, sessions: sessionCount, messages: messageCount }, 'Canonical sessions synced to Mercury Cloud');+ } catch (error) {+ this.dirty = true;+ if (this.active) logger.warn({ err: error instanceof Error ? error.message : String(error), retryMs: this.retryMs }, 'Canonical session sync failed; local sessions remain authoritative');+ const delay = this.retryMs;+ this.retryMs = Math.min(this.retryMs * 2, 60_000);+ this.running = false;+ if (this.abortController === abortController) this.abortController = null;+ if (this.active) this.requestSync(delay);+ return;+ }+ this.running = false;+ if (this.abortController === abortController) this.abortController = null;+ if (this.active && this.dirty) this.requestSync();+ }+}diff --git a/src/sessions/index.ts b/src/sessions/index.tsnew file mode 100644index 00000000..64397c27--- /dev/null+++ b/src/sessions/index.ts@@ -0,0 +1,17 @@+export { SessionRepository, SessionResolutionError } from './repository.js';+export { CloudSessionSynchronizer, buildSessionSyncBatches } from './cloud-sync.js';+export { buildConversationHistoryPayload } from './live-history.js';+export type { ConversationHistoryRequest } from './live-history.js';+export { normalizeGeneratedSessionTitle } from './title.js';+export type { SessionSyncBatch, SessionSyncConfig } from './cloud-sync.js';+export type {+ AppendSessionMessageInput,+ CreateSessionInput,+ Session,+ SessionBinding,+ SessionMessage,+ SessionMessageKind,+ SessionMessageRole,+ SessionStatus,+ SessionTitleSource,+} from './types.js';diff --git a/src/sessions/live-history.test.ts b/src/sessions/live-history.test.tsnew file mode 100644index 00000000..1cc46a11--- /dev/null+++ b/src/sessions/live-history.test.ts@@ -0,0 +1,72 @@+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, expect, it, vi } from 'vitest';+import { buildConversationHistoryPayload } from './live-history.js';++const AGENT_ID = 'aaaaaaaa-1111-4111-8111-111111111111';+import { SessionRepository } from './repository.js';++function fixture() {+ return new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-history-')), autoMigrate: false });+}++describe('buildConversationHistoryPayload', () => {+ it('paginates active summaries in updated order without messages', () => {+ vi.useFakeTimers();+ const repository = fixture();+ vi.setSystemTime(1_000);+ const first = repository.create({ alias: 'first-session' });+ vi.setSystemTime(2_000);+ const second = repository.create({ alias: 'second-session' });+ vi.setSystemTime(3_000);+ const third = repository.create({ alias: 'third-session' });+ repository.appendMessage(third.id, { role: 'user', content: 'not in summary' });+ repository.archive(first.id);+ repository.markDeleted(second.id);++ vi.setSystemTime(4_000);+ const fourth = repository.create({ alias: 'fourth-session' });+ const fifth = repository.create({ alias: 'fifth-session' });+ const page1 = buildConversationHistoryPayload(repository, { requestId: 'request-1', limit: 2 }, AGENT_ID);+ if (!page1.sessions) throw new Error('Expected a conversation history list');++ expect(page1.sessions.map((session) => session.id)).toEqual([fourth.id, fifth.id].sort());+ expect(page1.sessions[0]).toEqual(expect.objectContaining({+ alias: expect.any(String), status: 'active', revision: 1, createdAt: expect.stringMatching(/Z$/), updatedAt: expect.stringMatching(/Z$/),+ }));+ expect(page1.sessions[0]).not.toHaveProperty('messages');+ expect(page1.nextCursor).toEqual(expect.any(String));++ const page2 = buildConversationHistoryPayload(repository, { requestId: 'request-1', cursor: page1.nextCursor!, limit: 2 }, AGENT_ID);+ if (!page2.sessions) throw new Error('Expected a conversation history list');+ expect(page2.sessions.map((session) => session.id)).toEqual([third.id]);+ expect(page2.nextCursor).toBeNull();+ vi.useRealTimers();+ });++ it('serializes full detail with ordered messages and rejects deleted sessions', () => {+ const repository = fixture();+ const session = repository.create({ alias: 'detail-session' });+ repository.appendMessage(session.id, { role: 'assistant', content: 'second', timestamp: 2_000 });+ repository.appendMessage(session.id, { role: 'user', content: 'first', timestamp: 1_000 });++ const detail = buildConversationHistoryPayload(repository, { requestId: 'detail-1', sessionId: session.id }, AGENT_ID);+ if (!detail.messages || !detail.session) throw new Error('Expected conversation history detail');+ expect(detail).toMatchObject({ requestId: 'detail-1', session: { id: session.id, alias: session.alias, status: 'active' } });+ expect(detail.messages.map((message) => message.content)).toEqual(['second', 'first']);+ expect(detail.messages.every((message) => typeof message.timestamp === 'string' && message.timestamp.endsWith('Z'))).toBe(true);+ expect(detail.session).not.toHaveProperty('messages');++ repository.markDeleted(session.id);+ expect(() => buildConversationHistoryPayload(repository, { requestId: 'detail-2', sessionId: session.id }, AGENT_ID)).toThrow(/not found/);+ });++ it('caps list limits at 50 and rejects malformed cursors', () => {+ const repository = fixture();+ for (let index = 0; index < 51; index++) repository.create();+ const result = buildConversationHistoryPayload(repository, { requestId: 'limit', limit: 100 }, AGENT_ID);+ expect('sessions' in result && result.sessions).toHaveLength(50);+ expect(() => buildConversationHistoryPayload(repository, { requestId: 'bad', cursor: 'not-a-cursor' }, AGENT_ID)).toThrow(/Invalid conversation history cursor/);+ });+});diff --git a/src/sessions/live-history.ts b/src/sessions/live-history.tsnew file mode 100644index 00000000..4e2fe93d--- /dev/null+++ b/src/sessions/live-history.ts@@ -0,0 +1,90 @@+import type { SessionRepository } from './repository.js';+import type { Session, SessionBinding, SessionMessage } from './types.js';++export interface ConversationHistoryRequest {+ requestId: string;+ sessionId?: string;+ cursor?: string;+ limit?: number;+}++function serializeBinding(binding: SessionBinding) {+ return {+ ...binding,+ createdAt: new Date(binding.createdAt).toISOString(),+ updatedAt: new Date(binding.updatedAt).toISOString(),+ };+}++function serializeMessage(message: SessionMessage) {+ return {+ ...message,+ reasoning: typeof message.reasoning === 'string'+ ? message.reasoning+ : message.reasoning == null+ ? undefined+ : JSON.stringify(message.reasoning),+ timestamp: new Date(message.timestamp).toISOString(),+ };+}++function serializeSession(session: Session, agentId: string) {+ const { messages: _, ...summary } = session;+ return {+ ...summary,+ agentId,+ createdAt: new Date(session.createdAt).toISOString(),+ updatedAt: new Date(session.updatedAt).toISOString(),+ bindings: session.bindings.map(serializeBinding),+ };+}++function encodeCursor(session: Session): string {+ return Buffer.from(JSON.stringify([session.updatedAt, session.id])).toString('base64url');+}++function decodeCursor(cursor: string): [number, string] {+ try {+ const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as unknown;+ if (!Array.isArray(parsed) || parsed.length !== 2 || !Number.isFinite(parsed[0]) || typeof parsed[1] !== 'string') throw new Error();+ return [parsed[0] as number, parsed[1]];+ } catch {+ throw new Error('Invalid conversation history cursor');+ }+}++export function buildConversationHistoryPayload(repository: SessionRepository, request: ConversationHistoryRequest, agentId: string) {+ if (request.sessionId) {+ const session = repository.get(request.sessionId);+ if (session.status === 'deleted') throw new Error(`Session not found: ${request.sessionId}`);+ const messages = [...session.messages]+ .sort((a, b) => a.sequence - b.sequence || a.timestamp - b.timestamp || a.id.localeCompare(b.id))+ .map(serializeMessage);+ return { requestId: request.requestId, session: serializeSession(session, agentId), messages };+ }++ const requestedLimit = Number.isFinite(request.limit) ? Math.trunc(request.limit!) : 20;+ const limit = Math.max(1, Math.min(50, requestedLimit));+ let active = repository.list().sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));+ if (request.cursor) {+ const [updatedAt, id] = decodeCursor(request.cursor);+ active = active.filter((session) => session.updatedAt < updatedAt || (session.updatedAt === updatedAt && session.id > id));+ }+ const page = active.slice(0, limit);+ const sessions = page.map((session) => ({+ id: session.id,+ agentId,+ alias: session.alias,+ title: session.title,+ titleSource: session.titleSource,+ status: session.status,+ revision: session.revision,+ createdAt: new Date(session.createdAt).toISOString(),+ updatedAt: new Date(session.updatedAt).toISOString(),+ }));+ return {+ requestId: request.requestId,+ sessions,+ nextCursor: active.length > limit ? encodeCursor(page[page.length - 1]) : null,+ };+}diff --git a/src/sessions/repository.test.ts b/src/sessions/repository.test.tsnew file mode 100644index 00000000..bbfaa680--- /dev/null+++ b/src/sessions/repository.test.ts@@ -0,0 +1,176 @@+import { mkdtempSync, readFileSync, readdirSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { describe, expect, it } from 'vitest';+import { SessionRepository, SessionResolutionError } from './repository.js';++function fixture() {+ const root = mkdtempSync(join(tmpdir(), 'mercury-sessions-'));+ return { root, repository: new SessionRepository({ rootDir: join(root, 'sessions'), autoMigrate: false }) };+}++describe('SessionRepository', () => {+ it('creates, lists, gets, and reloads atomically persisted sessions', () => {+ const { root, repository } = fixture();+ const created = repository.create({ title: 'Test session', alias: 'amber-comet' });+ repository.appendMessage(created.id, { role: 'user', content: 'hello' });+ const reloaded = new SessionRepository({ rootDir: join(root, 'sessions'), autoMigrate: false });+ expect(reloaded.list()).toHaveLength(1);+ expect(reloaded.get(created.id).messages[0]).toMatchObject({ content: 'hello', sequence: 1, sessionId: created.id });+ expect(readdirSync(join(root, 'sessions')).some((file) => file.endsWith('.tmp'))).toBe(false);+ expect(JSON.parse(readFileSync(join(root, 'sessions', 'index.json'), 'utf8')).sessions[0].alias).toBe('amber-comet');+ });++ it('quarantines a malformed index and rebuilds sessions and bindings', () => {+ const { root, repository } = fixture();+ const session = repository.create({ binding: { channelType: 'cli', externalConversationId: 'current' } });+ const sessionsDir = join(root, 'sessions');+ writeFileSync(join(sessionsDir, 'index.json'), '{not json');+ writeFileSync(join(sessionsDir, `${session.id}.json.123.tmp`), 'ignored');++ const recovered = new SessionRepository({ rootDir: sessionsDir, autoMigrate: false });++ expect(recovered.getByBinding('cli', 'current')?.id).toBe(session.id);+ expect(recovered.list()).toHaveLength(1);+ const files = readdirSync(sessionsDir);+ expect(files.some((file) => /^index\.json\.invalid-/.test(file))).toBe(true);+ expect(files).toContain(`${session.id}.json.123.tmp`);+ });++ it('rebuilds an index that references a missing session', () => {+ const { root, repository } = fixture();+ const present = repository.create({ alias: 'present-session' });+ const missing = repository.create({ alias: 'missing-session' });+ const sessionsDir = join(root, 'sessions');+ unlinkSync(join(sessionsDir, `${missing.id}.json`));++ const recovered = new SessionRepository({ rootDir: sessionsDir, autoMigrate: false });++ expect(recovered.dump().map((session) => session.id)).toEqual([present.id]);+ expect(() => recovered.get(missing.id)).toThrow(/not found/);+ expect(readdirSync(sessionsDir).some((file) => /^index\.json\.invalid-/.test(file))).toBe(true);+ });++ it('quarantines a corrupt individual session while retaining valid sessions', () => {+ const { root, repository } = fixture();+ const valid = repository.create({ alias: 'valid-session' });+ const corrupt = repository.create({ alias: 'corrupt-session' });+ const sessionsDir = join(root, 'sessions');+ writeFileSync(join(sessionsDir, `${corrupt.id}.json`), JSON.stringify({ id: corrupt.id, messages: null }));++ const recovered = new SessionRepository({ rootDir: sessionsDir, autoMigrate: false });++ expect(recovered.dump().map((session) => session.id)).toEqual([valid.id]);+ const quarantined = readdirSync(sessionsDir).find((file) => file.startsWith(`${corrupt.id}.json.invalid-`));+ expect(quarantined).toBeDefined();+ expect(JSON.parse(readFileSync(join(sessionsDir, quarantined!), 'utf8'))).toEqual({ id: corrupt.id, messages: null });+ });++ it('resolves UUID prefixes and aliases without guessing ambiguity', () => {+ const { repository } = fixture();+ const first = repository.create({ id: 'aaaaaaaa-1111-4111-8111-111111111111', alias: 'silver-star' });+ repository.create({ id: 'aaaabbbb-2222-4222-8222-222222222222', alias: 'silver-signal' });+ expect(repository.resolve(first.shortId).id).toBe(first.id);+ expect(repository.resolve('silver-star').id).toBe(first.id);+ expect(repository.resolve('SILVER-ST').id).toBe(first.id);+ expect(() => repository.resolve('aaaa')).toThrow(SessionResolutionError);+ expect(() => repository.resolve('silver-s')).toThrow(/silver-star.*silver-signal/);+ });++ it('maintains one mutable binding and adopts canonical UUIDs', () => {+ const { repository } = fixture();+ const first = repository.getOrCreateBound('cli', 'current');+ const adopted = repository.getOrCreateBound('web', 'browser-thread', 'bbbbbbbb-1111-4111-8111-111111111111');+ expect(repository.getByBinding('cli', 'current')?.id).toBe(first.id);+ repository.bind(adopted.id, 'cli', 'current');+ expect(repository.getByBinding('cli', 'current')?.id).toBe(adopted.id);+ expect(repository.get(first.id).bindings).toHaveLength(0);+ expect(repository.getByBinding('web', 'browser-thread')?.id).toBe(adopted.id);+ });++ it('deduplicates messages by external ID and archives sessions', () => {+ const { repository } = fixture();+ const session = repository.create();+ const first = repository.appendMessage(session.id, { role: 'user', content: 'once', externalMessageId: 'transport-1' });+ const duplicate = repository.appendMessage(session.id, { role: 'user', content: 'changed', externalMessageId: 'transport-1' });+ expect(duplicate.id).toBe(first.id);+ expect(repository.get(session.id).messages).toHaveLength(1);+ repository.archive(session.id);+ expect(repository.list()).toHaveLength(0);+ expect(repository.list({ includeArchived: true })[0].status).toBe('archived');+ });++ it('keeps a message-free deletion tombstone until it is purged after sync', () => {+ const { root, repository } = fixture();+ const session = repository.create({ binding: { channelType: 'cli', externalConversationId: 'current' } });+ repository.appendMessage(session.id, { role: 'user', content: 'private transcript' });+ const deleted = repository.markDeleted(session.id);+ expect(deleted).toMatchObject({ status: 'deleted', messages: [], bindings: [] });+ expect(repository.list()).toHaveLength(0);+ expect(repository.dump()).toHaveLength(1);+ expect(repository.getByBinding('cli', 'current')).toBeNull();+ repository.purgeDeleted([session.id]);+ expect(repository.dump()).toHaveLength(0);+ expect(() => repository.get(session.id)).toThrow(/not found/);+ expect(readdirSync(join(root, 'sessions'))).not.toContain(`${session.id}.json`);+ });++ it('permanently deletes the session file, index entry, and every binding', () => {+ const { root, repository } = fixture();+ const session = repository.create({ binding: { channelType: 'cli', externalConversationId: 'current' } });+ repository.bind(session.id, 'web', 'thread-1');+ repository.appendMessage(session.id, { role: 'user', content: 'erase me' });++ const deleted = repository.deletePermanently(session.alias);++ expect(deleted.id).toBe(session.id);+ expect(repository.list({ includeArchived: true, includeDeleted: true })).toEqual([]);+ expect(repository.getByBinding('cli', 'current')).toBeNull();+ expect(repository.getByBinding('web', 'thread-1')).toBeNull();+ expect(readdirSync(join(root, 'sessions'))).not.toContain(`${session.id}.json`);+ const index = JSON.parse(readFileSync(join(root, 'sessions', 'index.json'), 'utf8'));+ expect(index.sessions).toEqual([]);+ expect(index.bindings).toEqual({});+ expect(() => repository.deletePermanently(session.id)).toThrow(/not found/);+ });++ it('updates titles, revisions, and mutation subscribers idempotently', () => {+ const { repository } = fixture();+ const session = repository.create();+ let mutations = 0;+ const unsubscribe = repository.subscribe(() => mutations++);+ const updated = repository.updateTitle(session.id, ' Canonical Session Title ', 'generated');+ expect(updated).toMatchObject({ title: 'Canonical Session Title', titleSource: 'generated' });+ expect(updated.revision).toBeGreaterThan(session.revision);+ repository.updateTitle(session.id, 'Canonical Session Title', 'generated');+ expect(mutations).toBe(1);+ unsubscribe();+ repository.archive(session.id);+ expect(mutations).toBe(1);+ expect(() => repository.updateTitle(session.id, ' '.repeat(2))).toThrow(/required/);+ });++ it('imports legacy web and short-term JSON idempotently without deleting sources', () => {+ const root = mkdtempSync(join(tmpdir(), 'mercury-migration-'));+ const web = join(root, 'web-chat-history');+ const short = join(root, 'short-term');+ mkdirSync(web);+ mkdirSync(short);+ writeFileSync(join(web, 'thread.json'), JSON.stringify({+ id: 'thread-1', title: 'Legacy thread', createdAt: 1, updatedAt: 3, messages: [+ { id: 'u1', role: 'user', content: 'same', timestamp: 1 },+ { id: 'u2', role: 'user', content: 'same', timestamp: 2 },+ { id: 'a1', role: 'assistant', content: 'answer', timestamp: 3 },+ ],+ }));+ writeFileSync(join(short, 'cli.json'), JSON.stringify([{ id: 'c1', role: 'user', content: 'cli legacy', timestamp: 4 }]));+ const options = { rootDir: join(root, 'sessions'), legacyWebChatDir: web, legacyShortTermDir: short };+ const repository = new SessionRepository(options);+ expect(repository.getByBinding('web', 'thread-1')).toMatchObject({ createdAt: 1, updatedAt: 3 });+ expect(repository.getByBinding('web', 'thread-1')?.messages).toHaveLength(2);+ expect(repository.getByBinding('cli', 'cli')?.messages[0].content).toBe('cli legacy');+ expect(new SessionRepository(options).dump()).toHaveLength(2);+ expect(readdirSync(web)).toContain('thread.json');+ expect(readdirSync(short)).toContain('cli.json');+ });+});diff --git a/src/sessions/repository.ts b/src/sessions/repository.tsnew file mode 100644index 00000000..74957baa--- /dev/null+++ b/src/sessions/repository.ts@@ -0,0 +1,594 @@+import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { basename, join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { getMercuryHome, getMemoryDir } from '../utils/config.js';+import type { ChannelType } from '../types/channel.js';+import type { AppendSessionMessageInput, CreateSessionInput, Session, SessionBinding, SessionMessage } from './types.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;+const ID_PREFIX_RE = /^[0-9a-f]{4,32}$/i;+const ALIAS_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/i;+const CHANNEL_TYPES: ChannelType[] = ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp'];+const TITLE_SOURCES: Session['titleSource'][] = ['fallback', 'generated', 'user'];+const SESSION_STATUSES: Session['status'][] = ['active', 'archived', 'deleted'];+const MESSAGE_ROLES: SessionMessage['role'][] = ['user', 'assistant', 'system', 'tool'];+const MESSAGE_KINDS: SessionMessage['kind'][] = ['message', 'command', 'error', 'permission', 'progress', 'tool-call', 'tool-result'];++const ADJECTIVES = ['amber', 'brisk', 'calm', 'clear', 'cosmic', 'eager', 'gentle', 'lucky', 'quiet', 'rapid', 'silver', 'warm'];+const NOUNS = ['comet', 'falcon', 'forest', 'harbor', 'meteor', 'orbit', 'otter', 'planet', 'river', 'rocket', 'signal', 'star'];++interface SessionIndexEntry {+ id: string;+ shortId: string;+ alias: string;+ title: string;+ titleSource: Session['titleSource'];+ createdAt: number;+ updatedAt: number;+ status: Session['status'];+ revision: number;+}++interface SessionIndex {+ version: 1;+ sessions: SessionIndexEntry[];+ bindings: Record<string, string>;+ importedSources: string[];+}++export interface SessionRepositoryOptions {+ rootDir?: string;+ legacyWebChatDir?: string;+ legacyShortTermDir?: string;+ autoMigrate?: boolean;+}++export class SessionResolutionError extends Error {+ constructor(message: string, readonly matches: Array<Pick<Session, 'id' | 'shortId' | 'alias' | 'title'>>) {+ super(message);+ this.name = 'SessionResolutionError';+ }+}++export class SessionRepository {+ readonly rootDir: string;+ private readonly indexPath: string;+ private index: SessionIndex;+ private listeners = new Set<() => void>();++ constructor(options: SessionRepositoryOptions = {}) {+ this.rootDir = options.rootDir ?? join(getMercuryHome(), 'sessions');+ this.indexPath = join(this.rootDir, 'index.json');+ mkdirSync(this.rootDir, { recursive: true });+ this.index = this.loadIndex();+ if (options.autoMigrate !== false) {+ this.importLegacy(options.legacyWebChatDir ?? join(getMercuryHome(), 'web-chat-history'), options.legacyShortTermDir ?? join(getMemoryDir(), 'short-term'));+ }+ }++ create(input: CreateSessionInput = {}): Session {+ const id = (input.id ?? randomUUID()).toLowerCase();+ this.assertUuid(id);+ const existing = this.tryGetExact(id);+ if (existing) {+ if (input.binding) this.bind(existing.id, input.binding.channelType, input.binding.externalConversationId);+ return this.get(existing.id);+ }+ const alias = input.alias ? input.alias.toLowerCase() : this.generateAlias(id);+ this.assertAlias(alias);+ if (this.index.sessions.some((entry) => entry.alias.toLowerCase() === alias)) throw new Error(`Session alias already exists: ${alias}`);+ const now = Date.now();+ const title = input.title?.trim() || 'New session';+ const session: Session = {+ id,+ shortId: id.replaceAll('-', '').slice(0, 8),+ alias,+ title,+ titleSource: input.titleSource ?? (input.title ? 'user' : 'fallback'),+ createdAt: now,+ updatedAt: now,+ status: 'active',+ revision: 1,+ bindings: [],+ messages: [],+ };+ this.writeSession(session);+ this.index.sessions.push(this.toIndexEntry(session));+ this.writeIndex();+ if (input.binding) this.bind(id, input.binding.channelType, input.binding.externalConversationId);+ else this.notifyMutation();+ return this.get(id);+ }++ list(options: { includeArchived?: boolean; includeDeleted?: boolean } = {}): Session[] {+ return this.index.sessions+ .filter((entry) => entry.status === 'active' || (options.includeArchived && entry.status === 'archived') || (options.includeDeleted && entry.status === 'deleted'))+ .sort((a, b) => b.updatedAt - a.updatedAt)+ .map((entry) => this.readSession(entry.id));+ }++ get(ref: string): Session {+ const entry = this.resolveEntry(ref);+ return this.readSession(entry.id);+ }++ resolve(ref: string): Session {+ return this.get(ref);+ }++ getByBinding(channelType: ChannelType, externalConversationId: string): Session | null {+ const key = this.bindingKey(channelType, externalConversationId);+ const id = this.index.bindings[key];+ if (!id) return null;+ try {+ return this.get(id);+ } catch {+ return null;+ }+ }++ getOrCreateBound(channelType: ChannelType, externalConversationId: string, canonicalId?: string): Session {+ if (canonicalId) {+ this.assertUuid(canonicalId);+ const adopted = this.create({ id: canonicalId });+ this.bind(adopted.id, channelType, externalConversationId);+ return this.get(adopted.id);+ }+ const bound = this.getByBinding(channelType, externalConversationId);+ return bound?.status === 'active' ? bound : this.create({ binding: { channelType, externalConversationId } });+ }++ bind(sessionRef: string, channelType: ChannelType, externalConversationId: string): Session {+ if (!externalConversationId || externalConversationId.length > 512) throw new Error('Invalid external conversation ID');+ const session = this.get(sessionRef);+ const key = this.bindingKey(channelType, externalConversationId);+ const oldId = this.index.bindings[key];+ const existing = session.bindings.find((binding) => this.bindingKey(binding.channelType, binding.externalConversationId) === key);+ if (oldId === session.id && existing) return session;+ const now = Date.now();+ if (oldId && oldId !== session.id) {+ const old = this.tryGetExact(oldId);+ if (old) {+ old.bindings = old.bindings.filter((binding) => this.bindingKey(binding.channelType, binding.externalConversationId) !== key);+ this.touchAndWrite(old);+ }+ }+ if (existing) existing.updatedAt = now;+ else session.bindings.push({ channelType, externalConversationId, createdAt: now, updatedAt: now });+ this.index.bindings[key] = session.id;+ this.touchAndWrite(session);+ this.writeIndex();+ this.notifyMutation();+ return this.get(session.id);+ }++ appendMessage(sessionRef: string, input: AppendSessionMessageInput): SessionMessage {+ const session = this.get(sessionRef);+ if (!input.content || typeof input.content !== 'string') throw new Error('Message content is required');+ if (input.externalMessageId) {+ const existing = session.messages.find((message) => message.externalMessageId === input.externalMessageId);+ if (existing) return existing;+ }+ if (input.id) {+ this.assertUuid(input.id);+ const existing = session.messages.find((message) => message.id === input.id);+ if (existing) return existing;+ }+ const message: SessionMessage = {+ id: (input.id ?? randomUUID()).toLowerCase(),+ sessionId: session.id,+ role: input.role,+ kind: input.kind ?? 'message',+ content: input.content,+ timestamp: input.timestamp ?? Date.now(),+ sequence: (session.messages.at(-1)?.sequence ?? 0) + 1,+ ...(input.metadata ? { metadata: input.metadata } : {}),+ ...(input.tokenCount !== undefined ? { tokenCount: input.tokenCount } : {}),+ ...(input.reasoning !== undefined ? { reasoning: input.reasoning } : {}),+ ...(input.externalMessageId ? { externalMessageId: input.externalMessageId } : {}),+ };+ this.assertUuid(message.id);+ session.messages.push(message);+ if (session.messages.length === 1 && message.role === 'user' && session.titleSource === 'fallback') {+ session.title = this.fallbackTitle(message.content);+ }+ this.touchAndWrite(session, message.timestamp);+ this.writeIndex();+ this.notifyMutation();+ return message;+ }++ updateTitle(ref: string, title: string, titleSource: Session['titleSource'] = 'user'): Session {+ const normalized = title.replace(/\s+/g, ' ').trim();+ if (!normalized) throw new Error('Session title is required');+ if (normalized.length > 120) throw new Error('Session title must be 120 characters or fewer');+ const session = this.get(ref);+ if (session.title === normalized && session.titleSource === titleSource) return session;+ session.title = normalized;+ session.titleSource = titleSource;+ this.touchAndWrite(session);+ this.writeIndex();+ this.notifyMutation();+ return this.get(session.id);+ }++ archive(ref: string): Session {+ const session = this.get(ref);+ if (session.status !== 'archived') {+ session.status = 'archived';+ this.touchAndWrite(session);+ this.writeIndex();+ this.notifyMutation();+ }+ return this.get(session.id);+ }++ markDeleted(ref: string): Session {+ const session = this.get(ref);+ if (session.status !== 'deleted') {+ session.status = 'deleted';+ session.messages = [];+ session.bindings = [];+ for (const [key, id] of Object.entries(this.index.bindings)) {+ if (id === session.id) delete this.index.bindings[key];+ }+ this.touchAndWrite(session);+ this.writeIndex();+ this.notifyMutation();+ }+ return this.get(session.id);+ }++ deletePermanently(ref: string): Session {+ const session = this.get(ref);+ const previousSessions = this.index.sessions;+ const previousBindings = this.index.bindings;+ this.index.sessions = this.index.sessions.filter((entry) => entry.id !== session.id);+ this.index.bindings = Object.fromEntries(+ Object.entries(this.index.bindings).filter(([, id]) => id !== session.id),+ );+ try {+ // Publish the index first so readers can never resolve a removed session file.+ this.writeIndex();+ } catch (error) {+ this.index.sessions = previousSessions;+ this.index.bindings = previousBindings;+ throw error;+ }+ const path = join(this.rootDir, `${session.id}.json`);+ if (existsSync(path)) unlinkSync(path);+ this.notifyMutation();+ return session;+ }++ purgeDeleted(sessionIds: string[]): void {+ for (const id of new Set(sessionIds)) {+ const entry = this.index.sessions.find((session) => session.id === id);+ if (entry?.status === 'deleted') this.deletePermanently(id);+ }+ }++ dump(): Session[] {+ return this.list({ includeArchived: true, includeDeleted: true });+ }++ subscribe(listener: () => void): () => void {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ }++ importLegacy(webChatDir: string, shortTermDir: string): { sessions: number; messages: number } {+ let sessions = 0;+ let messages = 0;+ for (const [sourceType, dir] of [['web', webChatDir], ['short-term', shortTermDir]] as const) {+ if (!existsSync(dir)) continue;+ for (const file of readdirSync(dir).filter((name) => name.endsWith('.json'))) {+ const source = `${sourceType}:${join(dir, file)}`;+ if (this.index.importedSources.includes(source)) continue;+ try {+ const parsed = JSON.parse(readFileSync(join(dir, file), 'utf8')) as any;+ const records: any[] = sourceType === 'web' ? (Array.isArray(parsed.messages) ? parsed.messages : []) : (Array.isArray(parsed) ? parsed : []);+ const externalId = sourceType === 'web' ? String(parsed.id || basename(file, '.json')) : basename(file, '.json');+ const channelType: ChannelType = sourceType === 'web' ? 'web' : this.legacyChannelType(externalId);+ const session = this.getByBinding(channelType, externalId) ?? this.create({+ title: sourceType === 'web' && parsed.title ? String(parsed.title) : undefined,+ titleSource: sourceType === 'web' && parsed.title ? 'user' : 'fallback',+ binding: { channelType, externalConversationId: externalId },+ });+ if (session.messages.length === 0) sessions++;+ const seen = new Set(session.messages.map((message) => `${message.role}\0${message.content}`));+ for (const record of records) {+ const role = record?.role;+ const content = typeof record?.content === 'string' ? record.content : '';+ if (!['user', 'assistant', 'system', 'tool'].includes(role) || !content) continue;+ const fingerprint = `${role}\0${content}`;+ if (seen.has(fingerprint)) continue;+ this.appendMessage(session.id, {+ role,+ content,+ timestamp: Number(record.timestamp) || Date.now(),+ tokenCount: typeof record.tokenCount === 'number' ? record.tokenCount : undefined,+ reasoning: typeof record.reasoning === 'string' ? record.reasoning : undefined,+ externalMessageId: typeof record.id === 'string' ? `legacy:${source}:${record.id}` : undefined,+ metadata: { importedFrom: source },+ });+ seen.add(fingerprint);+ messages++;+ }+ const imported = this.get(session.id);+ const sourceCreatedAt = Number(parsed.createdAt) || Number(records[0]?.timestamp);+ const sourceUpdatedAt = Number(parsed.updatedAt) || Number(records.at(-1)?.timestamp);+ if (Number.isFinite(sourceCreatedAt)) imported.createdAt = sourceCreatedAt;+ if (Number.isFinite(sourceUpdatedAt)) imported.updatedAt = Math.max(imported.createdAt, sourceUpdatedAt);+ this.writeSession(imported);+ const importedIndex = this.index.sessions.findIndex((entry) => entry.id === imported.id);+ if (importedIndex >= 0) this.index.sessions[importedIndex] = this.toIndexEntry(imported);+ this.index.importedSources.push(source);+ this.writeIndex();+ } catch {+ // A malformed legacy file remains untouched and can be retried after repair.+ }+ }+ }+ return { sessions, messages };+ }++ private resolveEntry(rawRef: string): SessionIndexEntry {+ const ref = rawRef.trim();+ if (!ref || ref.length > 128) throw new Error('Invalid session reference');+ if (UUID_RE.test(ref)) {+ const exact = this.index.sessions.find((entry) => entry.id === ref.toLowerCase());+ if (!exact) throw new Error(`Session not found: ${ref}`);+ return exact;+ }+ const compact = ref.replaceAll('-', '').toLowerCase();+ if (ID_PREFIX_RE.test(compact)) {+ const idMatches = this.index.sessions.filter((entry) => entry.id.replaceAll('-', '').startsWith(compact));+ if (idMatches.length === 1) return idMatches[0];+ if (idMatches.length > 1) throw this.ambiguous(ref, idMatches);+ }+ const exactAlias = this.index.sessions.find((entry) => entry.alias === ref);+ if (exactAlias) return exactAlias;+ const aliasMatches = this.index.sessions.filter((entry) => entry.alias.toLowerCase().startsWith(ref.toLowerCase()));+ if (aliasMatches.length === 1) return aliasMatches[0];+ if (aliasMatches.length > 1) throw this.ambiguous(ref, aliasMatches);+ throw new Error(`Session not found: ${ref}`);+ }++ private ambiguous(ref: string, entries: SessionIndexEntry[]): SessionResolutionError {+ const matches = entries.map(({ id, shortId, alias, title }) => ({ id, shortId, alias, title }));+ return new SessionResolutionError(`Ambiguous session reference "${ref}": ${matches.map((match) => `${match.alias} (${match.shortId})`).join(', ')}`, matches);+ }++ private generateAlias(id: string): string {+ const seed = Number.parseInt(id.replaceAll('-', '').slice(0, 8), 16);+ for (let offset = 0; offset < ADJECTIVES.length * NOUNS.length; offset++) {+ const alias = `${ADJECTIVES[(seed + offset) % ADJECTIVES.length]}-${NOUNS[(Math.floor(seed / ADJECTIVES.length) + offset) % NOUNS.length]}`;+ if (!this.index.sessions.some((entry) => entry.alias === alias)) return alias;+ }+ return `session-${id.replaceAll('-', '').slice(0, 8)}`;+ }++ private fallbackTitle(content: string): string {+ const normalized = content.replace(/\s+/g, ' ').trim();+ return normalized.length > 60 ? `${normalized.slice(0, 57)}...` : normalized || 'New session';+ }++ private touchAndWrite(session: Session, timestamp = Date.now()): void {+ session.updatedAt = Math.max(session.updatedAt, timestamp);+ session.revision++;+ this.writeSession(session);+ const index = this.index.sessions.findIndex((entry) => entry.id === session.id);+ if (index >= 0) this.index.sessions[index] = this.toIndexEntry(session);+ }++ private toIndexEntry(session: Session): SessionIndexEntry {+ const { id, shortId, alias, title, titleSource, createdAt, updatedAt, status, revision } = session;+ return { id, shortId, alias, title, titleSource, createdAt, updatedAt, status, revision };+ }++ private loadIndex(): SessionIndex {+ let parsed: unknown;+ if (existsSync(this.indexPath)) {+ try {+ parsed = JSON.parse(readFileSync(this.indexPath, 'utf8'));+ } catch {+ parsed = undefined;+ }+ }++ const sessionFiles = this.sessionFileNames();+ if (this.isValidIndex(parsed, sessionFiles)) return parsed;+ if (!existsSync(this.indexPath) && sessionFiles.length === 0) return this.emptyIndex();++ if (existsSync(this.indexPath)) this.quarantine(this.indexPath);+ const sessions: Session[] = [];+ for (const file of sessionFiles) {+ const path = join(this.rootDir, file);+ try {+ const session = JSON.parse(readFileSync(path, 'utf8')) as unknown;+ if (!this.isValidSession(session, basename(file, '.json'))) throw new Error('Invalid session');+ sessions.push(session);+ } catch {+ this.quarantine(path);+ }+ }+ sessions.sort((a, b) => a.id.localeCompare(b.id));+ const validIds = new Set(sessions.map((session) => session.id));+ const bindings: Record<string, string> = {};+ const recoveredBindings = this.recordValue(parsed, 'bindings');+ if (recoveredBindings) {+ for (const key of Object.keys(recoveredBindings).sort()) {+ const id = recoveredBindings[key];+ if (typeof id === 'string' && validIds.has(id) && this.isValidBindingKey(key)) bindings[key] = id;+ }+ }+ for (const session of sessions) {+ for (const binding of session.bindings) {+ const key = this.bindingKey(binding.channelType, binding.externalConversationId);+ bindings[key] ??= session.id;+ }+ }+ const importedSources = this.arrayValue(parsed, 'importedSources')?.filter((source): source is string => typeof source === 'string') ?? [];+ const recovered: SessionIndex = { version: 1, sessions: sessions.map((session) => this.toIndexEntry(session)), bindings, importedSources };+ this.index = recovered;+ this.writeIndex();+ return recovered;+ }++ private readSession(id: string): Session {+ this.assertUuid(id);+ return JSON.parse(readFileSync(join(this.rootDir, `${id}.json`), 'utf8')) as Session;+ }++ private tryGetExact(id: string): Session | null {+ if (!this.index.sessions.some((entry) => entry.id === id.toLowerCase())) return null;+ return this.readSession(id.toLowerCase());+ }++ private writeSession(session: Session): void {+ this.atomicWrite(join(this.rootDir, `${session.id}.json`), session);+ }++ private writeIndex(): void {+ this.atomicWrite(this.indexPath, this.index);+ }++ private atomicWrite(path: string, value: unknown): void {+ const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });+ renameSync(temp, path);+ }++ private emptyIndex(): SessionIndex {+ return { version: 1, sessions: [], bindings: {}, importedSources: [] };+ }++ private sessionFileNames(): string[] {+ return readdirSync(this.rootDir)+ .filter((file) => file.endsWith('.json') && UUID_RE.test(basename(file, '.json')))+ .sort();+ }++ private quarantine(path: string): void {+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');+ let destination: string;+ do {+ destination = `${path}.invalid-${timestamp}-${randomUUID()}`;+ } while (existsSync(destination));+ renameSync(path, destination);+ }++ private isValidIndex(value: unknown, sessionFiles: string[]): value is SessionIndex {+ if (!this.isRecord(value) || value.version !== 1 || !Array.isArray(value.sessions) || !this.isRecord(value.bindings)+ || !Array.isArray(value.importedSources) || !value.importedSources.every((source) => typeof source === 'string')) return false;+ const fileIds = sessionFiles.map((file) => basename(file, '.json'));+ const entryIds: string[] = [];+ for (const entry of value.sessions) {+ if (!this.isValidIndexEntry(entry)) return false;+ entryIds.push(entry.id);+ try {+ const session = JSON.parse(readFileSync(join(this.rootDir, `${entry.id}.json`), 'utf8')) as unknown;+ if (!this.isValidSession(session, entry.id)) return false;+ const canonicalEntry = this.toIndexEntry(session);+ if (Object.entries(canonicalEntry).some(([key, value]) => entry[key as keyof SessionIndexEntry] !== value)) return false;+ } catch {+ return false;+ }+ }+ if (entryIds.length !== fileIds.length || [...new Set(entryIds)].sort().join('\0') !== fileIds.join('\0')) return false;+ return Object.entries(value.bindings).every(([key, id]) => typeof id === 'string' && entryIds.includes(id) && this.isValidBindingKey(key));+ }++ private isValidIndexEntry(value: unknown): value is SessionIndexEntry {+ return this.isRecord(value)+ && typeof value.id === 'string' && UUID_RE.test(value.id) && value.id === value.id.toLowerCase()+ && typeof value.shortId === 'string' && value.shortId === value.id.replaceAll('-', '').slice(0, 8)+ && typeof value.alias === 'string' && ALIAS_RE.test(value.alias) && value.alias.length <= 64+ && typeof value.title === 'string'+ && TITLE_SOURCES.includes(value.titleSource as Session['titleSource'])+ && this.isFiniteNumber(value.createdAt) && this.isFiniteNumber(value.updatedAt)+ && SESSION_STATUSES.includes(value.status as Session['status'])+ && Number.isInteger(value.revision) && (value.revision as number) >= 1;+ }++ private isValidSession(value: unknown, expectedId: string): value is Session {+ if (!this.isRecord(value) || !this.isValidIndexEntry(value) || value.id !== expectedId+ || !Array.isArray(value.bindings) || !Array.isArray(value.messages)) return false;+ if (!value.bindings.every((binding) => this.isValidBinding(binding))) return false;+ return value.messages.every((message) => this.isValidMessage(message, value.id));+ }++ private isValidBinding(value: unknown): value is SessionBinding {+ return this.isRecord(value)+ && CHANNEL_TYPES.includes(value.channelType as ChannelType)+ && typeof value.externalConversationId === 'string' && value.externalConversationId.length > 0 && value.externalConversationId.length <= 512+ && this.isFiniteNumber(value.createdAt) && this.isFiniteNumber(value.updatedAt);+ }++ private isValidMessage(value: unknown, sessionId: string): value is SessionMessage {+ return this.isRecord(value)+ && typeof value.id === 'string' && UUID_RE.test(value.id)+ && value.sessionId === sessionId+ && MESSAGE_ROLES.includes(value.role as SessionMessage['role'])+ && MESSAGE_KINDS.includes(value.kind as SessionMessage['kind'])+ && typeof value.content === 'string'+ && this.isFiniteNumber(value.timestamp)+ && Number.isInteger(value.sequence) && (value.sequence as number) >= 1+ && (value.metadata === undefined || this.isRecord(value.metadata))+ && (value.tokenCount === undefined || this.isFiniteNumber(value.tokenCount))+ && (value.reasoning === undefined || typeof value.reasoning === 'string')+ && (value.externalMessageId === undefined || typeof value.externalMessageId === 'string');+ }++ private isValidBindingKey(key: string): boolean {+ const separator = key.indexOf('\0');+ return separator > 0+ && CHANNEL_TYPES.includes(key.slice(0, separator) as ChannelType)+ && key.slice(separator + 1).length > 0+ && key.slice(separator + 1).length <= 512;+ }++ private isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+ }++ private recordValue(value: unknown, key: string): Record<string, unknown> | undefined {+ return this.isRecord(value) && this.isRecord(value[key]) ? value[key] : undefined;+ }++ private arrayValue(value: unknown, key: string): unknown[] | undefined {+ return this.isRecord(value) && Array.isArray(value[key]) ? value[key] : undefined;+ }++ private isFiniteNumber(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value);+ }++ private notifyMutation(): void {+ for (const listener of this.listeners) {+ try {+ listener();+ } catch {+ // Persistence is authoritative; observers must never fail local writes.+ }+ }+ }++ private bindingKey(channelType: ChannelType, externalConversationId: string): string {+ return `${channelType}\0${externalConversationId}`;+ }++ private legacyChannelType(id: string): ChannelType {+ const prefix = id.split(':', 1)[0];+ return ['cli', 'telegram', 'web', 'internal', 'signal', 'discord', 'slack', 'whatsapp'].includes(prefix) ? prefix as ChannelType : 'internal';+ }++ private assertUuid(id: string): void {+ if (!UUID_RE.test(id)) throw new Error(`Invalid UUID: ${id}`);+ }++ private assertAlias(alias: string): void {+ if (!ALIAS_RE.test(alias) || alias.length > 64) throw new Error(`Invalid session alias: ${alias}`);+ }+}diff --git a/src/sessions/title.test.ts b/src/sessions/title.test.tsnew file mode 100644index 00000000..7adf6d75--- /dev/null+++ b/src/sessions/title.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';+import { normalizeGeneratedSessionTitle } from './title.js';++describe('normalizeGeneratedSessionTitle', () => {+ it('removes wrappers and keeps a concise single-line title', () => {+ expect(normalizeGeneratedSessionTitle(' Title: “Canonical Session Sync”\nExtra explanation')).toBe('Canonical Session Sync');+ expect(normalizeGeneratedSessionTitle('one two')).toBeNull();+ });++ it('limits generated titles to seven words and 80 characters', () => {+ const title = normalizeGeneratedSessionTitle('extraordinary synchronization architecture handles canonical conversation histories safely today');+ expect(title).toBe('extraordinary synchronization architecture handles canonical conversation');+ expect(title!.length).toBeLessThanOrEqual(80);+ expect(title!.split(' ').length).toBeLessThanOrEqual(7);+ });+});diff --git a/src/sessions/title.ts b/src/sessions/title.tsnew file mode 100644index 00000000..26deb21d--- /dev/null+++ b/src/sessions/title.ts@@ -0,0 +1,18 @@+export function normalizeGeneratedSessionTitle(raw: string): string | null {+ const firstLine = raw.split(/\r?\n/, 1)[0]+ .replace(/^\s*(?:title\s*:\s*)?/i, '')+ .replace(/^[`*_"'“”‘’]+|[`*_"'“”‘’]+$/g, '')+ .replace(/[.!?,;:]+$/g, '')+ .replace(/\s+/g, ' ')+ .trim();+ const words = firstLine.split(' ').filter(Boolean).slice(0, 7);+ if (words.length < 3) return null;+ let title = '';+ for (const word of words) {+ const candidate = title ? `${title} ${word}` : word;+ if (candidate.length > 80) break;+ title = candidate;+ }+ if (title.split(' ').length < 3) title = words.join(' ').slice(0, 80).trim();+ return title || null;+}diff --git a/src/sessions/types.ts b/src/sessions/types.tsnew file mode 100644index 00000000..5183b3d3--- /dev/null+++ b/src/sessions/types.ts@@ -0,0 +1,61 @@+import type { ChannelType } from '../types/channel.js';++export type SessionTitleSource = 'fallback' | 'generated' | 'user';+export type SessionStatus = 'active' | 'archived' | 'deleted';+export type SessionMessageRole = 'user' | 'assistant' | 'system' | 'tool';+export type SessionMessageKind = 'message' | 'command' | 'error' | 'permission' | 'progress' | 'tool-call' | 'tool-result';++export interface SessionBinding {+ channelType: ChannelType;+ externalConversationId: string;+ createdAt: number;+ updatedAt: number;+}++export interface SessionMessage {+ id: string;+ sessionId: string;+ role: SessionMessageRole;+ kind: SessionMessageKind;+ content: string;+ timestamp: number;+ sequence: number;+ metadata?: Record<string, unknown>;+ tokenCount?: number;+ reasoning?: string;+ externalMessageId?: string;+}++export interface Session {+ id: string;+ shortId: string;+ alias: string;+ title: string;+ titleSource: SessionTitleSource;+ createdAt: number;+ updatedAt: number;+ status: SessionStatus;+ revision: number;+ bindings: SessionBinding[];+ messages: SessionMessage[];+}++export interface CreateSessionInput {+ id?: string;+ title?: string;+ titleSource?: SessionTitleSource;+ alias?: string;+ binding?: Pick<SessionBinding, 'channelType' | 'externalConversationId'>;+}++export interface AppendSessionMessageInput {+ id?: string;+ role: SessionMessageRole;+ kind?: SessionMessageKind;+ content: string;+ timestamp?: number;+ metadata?: Record<string, unknown>;+ tokenCount?: number;+ reasoning?: string;+ externalMessageId?: string;+}diff --git a/src/signal/binary.test.ts b/src/signal/binary.test.tsnew file mode 100644index 00000000..d32bc2ee--- /dev/null+++ b/src/signal/binary.test.ts@@ -0,0 +1,10 @@+import { describe, expect, it } from 'vitest';+import { isNativeAvailable } from './binary.js';++describe('Signal native binary platform selection', () => {+ it('supports glibc Linux targets but excludes Termux', () => {+ expect(isNativeAvailable({}, 'linux', 'x64')).toBe(true);+ expect(isNativeAvailable({ TERMUX_VERSION: '0.119' }, 'linux', 'x64')).toBe(false);+ expect(isNativeAvailable({ PREFIX: '/data/data/com.termux/files/usr' }, 'linux', 'arm64')).toBe(false);+ });+});diff --git a/src/signal/binary.ts b/src/signal/binary.tsindex 3fd821e2..75668126 100644--- a/src/signal/binary.ts+++ b/src/signal/binary.ts@@ -6,6 +6,7 @@ import { Readable } from 'node:stream';import { homedir } from 'node:os';import chalk from 'chalk';import { logger } from '../utils/logger.js';+import { isTermux } from '../utils/platform.js';const SIGNAL_CLI_VERSION = '0.14.5';const MERCURY_HOME = () => process.env.MERCURY_HOME || path.join(homedir(), '.mercury');@@ -16,12 +17,19 @@ const NATIVE_PLATFORMS: Record<string, string> = {'linux-x64': `signal-cli-${SIGNAL_CLI_VERSION}-Linux-native.tar.gz`,};-function getPlatformKey(): string {- return `${process.platform}-${process.arch}`;+function getPlatformKey(+ platform: NodeJS.Platform = process.platform,+ arch: NodeJS.Architecture = process.arch,+): string {+ return `${platform}-${arch}`;}-export function isNativeAvailable(): boolean {- return getPlatformKey() in NATIVE_PLATFORMS;+export function isNativeAvailable(+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform,+ arch: NodeJS.Architecture = process.arch,+): boolean {+ return !isTermux(env, platform) && getPlatformKey(platform, arch) in NATIVE_PLATFORMS;}function getNativeArchiveName(): string | null {@@ -44,9 +52,37 @@ function getJarPath(): string {return path.join(SIGNAL_CLI_DIR(), 'lib', `signal-cli-${SIGNAL_CLI_VERSION}.jar`);}+function isScript(pathname: string): boolean {+ let fd: number | undefined;+ try {+ fd = fs.openSync(pathname, 'r');+ const header = Buffer.alloc(2);+ fs.readSync(fd, header, 0, header.length, 0);+ return header.toString() === '#!';+ } catch {+ return false;+ } finally {+ if (fd !== undefined) fs.closeSync(fd);+ }+}++function makeExecutable(pathname: string): boolean {+ try {+ fs.chmodSync(pathname, 0o755);+ fs.accessSync(pathname, fs.constants.X_OK);+ return true;+ } catch {+ return false;+ }+}++function isUsableManagedLauncher(pathname: string): boolean {+ return existsSync(pathname) && (!isTermux() || isScript(pathname)) && makeExecutable(pathname);+}+export function findSignalCli(): string | null {const binaryPath = getBinaryPath();- if (existsSync(binaryPath)) {+ if (isUsableManagedLauncher(binaryPath)) {return binaryPath;}@@ -58,7 +94,7 @@ export function findSignalCli(): string | null {const whichCmd = process.platform === 'win32' ? 'where' : 'which';try {const systemPath = execSync(`${whichCmd} signal-cli 2>/dev/null`, { encoding: 'utf-8', stdio: 'pipe' }).trim();- if (systemPath) return systemPath;+ if (systemPath && (!isTermux() || getSignalCliVersion(systemPath))) return systemPath;} catch { /* not on PATH */ }return null;@@ -209,7 +245,7 @@ export async function downloadSignalCli(preferNative: boolean = true): Promise<smkdirSync(dir, { recursive: true });}- if (existsSync(expectedBinary)) {+ if (isUsableManagedLauncher(expectedBinary) && getSignalCliVersion(expectedBinary)) {logger.info({ path: expectedBinary }, 'Signal CLI native binary already exists');return expectedBinary;}@@ -233,7 +269,12 @@ export async function downloadSignalCli(preferNative: boolean = true): Promise<sif (!existsSync(binaryPath)) {throw new Error(`Native binary not found after extraction at ${binaryPath}`);}- try { fs.chmodSync(binaryPath, 0o755); } catch { /* ignore */ }+ if (!makeExecutable(binaryPath)) {+ throw new Error(`Native binary is not executable at ${binaryPath}`);+ }+ if (!getSignalCliVersion(binaryPath)) {+ throw new Error('Native binary failed its version check');+ }logger.info({ path: binaryPath }, 'Signal CLI native binary installed');return binaryPath;} catch (nativeErr: any) {@@ -248,9 +289,10 @@ export async function downloadSignalCli(preferNative: boolean = true): Promise<sif (!checkJavaAvailable()) {throw new Error('Signal CLI requires Java (JRE 17+) on this platform.\n' +- 'No native binary is available for macOS/Windows, and Java was not found.\n' +- 'Install Java: https://adoptium.net/ or `brew install openjdk`\n' +- 'Then run: mercury doctor'+ 'No compatible native binary is available, and Java was not found.\n' ++ (isTermux()+ ? 'Install Java with `pkg install openjdk-17`, then run: mercury doctor'+ : 'Install Java: https://adoptium.net/ or `brew install openjdk`\nThen run: mercury doctor'));}@@ -269,7 +311,9 @@ export async function downloadSignalCli(preferNative: boolean = true): Promise<s// Prefer the wrapper script which handles classpath and JAVA_HOMEconst binaryPath = getBinaryPath();if (existsSync(binaryPath)) {- try { fs.chmodSync(binaryPath, 0o755); } catch { /* ignore */ }+ if (!makeExecutable(binaryPath)) {+ throw new Error(`signal-cli wrapper is not executable at ${binaryPath}`);+ }logger.info({ path: binaryPath }, 'Signal CLI installed (wrapper script + JAR)');return binaryPath;}@@ -361,4 +405,4 @@ export function getSignalCliVersion(binaryPath: string): string | null {export function getSignalCliDir(): string {return SIGNAL_CLI_DIR();-}\ No newline at end of file+}diff --git a/src/skills/cli.ts b/src/skills/cli.tsindex 4057f2f3..1a1e1cd2 100644--- a/src/skills/cli.ts+++ b/src/skills/cli.ts@@ -5,16 +5,16 @@* print human-readable, chalk-colored output by default and structured JSON* when `--json` is passed.*/-import { spawn } from 'node:child_process';import { existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { homedir, platform } from 'node:os';+import { homedir } from 'node:os';import { Command } from 'commander';import chalk from 'chalk';import { RegistryClient, RegistryError, searchFeed, type RegistrySkillSummary, type ScoredSkill } from './registry.js';import { SkillStore, isValidSkillId } from './store.js';import { renderMarkdown } from '../utils/markdown.js';import { getMercuryHome } from '../utils/config.js';+import { openUrl } from '../utils/open-url.js';interface GlobalSkillFlags {json?: boolean;@@ -373,9 +373,7 @@ async function loadBodyFromSource(source: string): Promise<string> {}async function openInBrowser(url: string): Promise<void> {- const cmd = platform() === 'darwin' ? 'open' : platform() === 'win32' ? 'start' : 'xdg-open';- const args = platform() === 'win32' ? ['', url] : [url];- spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();+ await openUrl(url);}// ---------- public registration ----------diff --git a/src/spotify/client.ts b/src/spotify/client.tsindex 091160db..a498fdc0 100644--- a/src/spotify/client.ts+++ b/src/spotify/client.ts@@ -1,12 +1,9 @@import { readFileSync, writeFileSync, existsSync } from 'node:fs';import { createServer, IncomingMessage, ServerResponse } from 'node:http';-import { exec } from 'node:child_process';-import { promisify } from 'node:util';import { getMercuryHome, saveConfig } from '../utils/config.js';import type { MercuryConfig } from '../utils/config.js';import { logger } from '../utils/logger.js';--const execAsync = promisify(exec);+import { openUrl } from '../utils/open-url.js';const SPOTIFY_AUTH_URL = 'https://accounts.spotify.com/authorize';const SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token';@@ -137,9 +134,8 @@ export class SpotifyClient {console.log(` Opening browser for Spotify login...`);console.log(` If browser doesn't open, visit:\n ${callbackUrl}\n`);console.log(` ${'─'.repeat(50)}\n`);- const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';- execAsync(`${cmd} "${callbackUrl}"`).catch(() => {- console.log(` Could not auto-open browser. Visit:\n ${callbackUrl}\n`);+ void openUrl(callbackUrl).then((opened) => {+ if (!opened) console.log(` Could not auto-open browser. Visit:\n ${callbackUrl}\n`);});});@@ -537,4 +533,4 @@ export class SpotifyClient {const s = seconds % 60;return `${m}:${s.toString().padStart(2, '0')}`;}-}\ No newline at end of file+}diff --git a/src/types/channel.ts b/src/types/channel.tsindex 4ee477e0..5bf79e9d 100644--- a/src/types/channel.ts+++ b/src/types/channel.ts@@ -26,6 +26,8 @@ export interface ChannelMessage {senderName?: string;content: string;timestamp: number;+ /** Canonical local session identity; channelId remains transport-specific. */+ sessionId?: string;metadata?: Record<string, unknown>;}diff --git a/src/types/index.ts b/src/types/index.tsindex f21c63b1..8aec38d8 100644--- a/src/types/index.ts+++ b/src/types/index.ts@@ -9,3 +9,4 @@ export type {} from './channel.js';export type { MessageRole, Message, SystemMessage, UserMessage, AssistantMessage, MessageSummary } from './message.js';export type { AgentState, AgentMode, AgentIdentity, AgentContext, TokenUsage, HeartbeatState } from './agent.js';+export type { Session, SessionBinding, SessionMessage, CreateSessionInput, AppendSessionMessageInput } from '../sessions/index.js';diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 7d67091e..5fac718e 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -1,5 +1,5 @@import React from 'react';-import { Box, Text, Spacer, useApp, useInput, useStdout } from 'ink';+import { Box, Text, Spacer, Static, useApp, useInput, useStdout } from 'ink';import type { TuiState } from '../channels/cli.js';import type { AppMode, ChatMessage, ToolStep, SubAgentInfo, PermissionPromptState, SidebarSection, BackgroundTaskInfo, WorkspaceState } from './types.js';import type { PermissionMode } from '../channels/base.js';@@ -8,6 +8,7 @@ import { renderMarkdown } from '../utils/markdown.js';import { PLAYER_CONTROLS, formatNowPlaying } from '../spotify/ui.js';import type { SpotifyClient } from '../spotify/client.js';import type { SubAgentStatus } from '../types/agent.js';+import { getViewportWindow, normalizeTerminalText } from './terminal-viewport.js';const MERCURY_LOGO = [' __ _____________ ________ ________ __',@@ -78,6 +79,7 @@ export interface TuiAppProps {export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyClient }: TuiAppProps) {const { exit } = useApp();+ const terminalSize = useTerminalSize();const [input, setInput] = React.useState('');const [cursorPos, setCursorPos] = React.useState(0);const setInputAndCursor = (text: string, pos?: number) => {@@ -99,12 +101,16 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCliconst [inputHistory, setInputHistory] = React.useState<string[]>([]);const [historyIndex, setHistoryIndex] = React.useState<number>(-1);const [historyDraft, setHistoryDraft] = React.useState<string>('');- const [workspacePane, setWorkspacePane] = React.useState<'files' | 'details' | 'git'>('files');- const [detailCursor, setDetailCursor] = React.useState(0);const [gitCursor, setGitCursor] = React.useState(0);const slashCommands = React.useMemo(() => ['/help',+ '/sessions',+ '/session new',+ '/session current',+ '/session ',+ '/session archive ',+ '/session delete ','/status','/progress','/menu',@@ -117,12 +123,20 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli'/code agent ','/code off','/code toggle',+ '/research',+ '/research on',+ '/research off',+ '/research toggle',+ '/research ','/spotify','/budget','/permissions','/memory','/models','/models use ',+ '/cloud',+ '/cloud models',+ '/cloud use ','/agents','/agents stop ','/agents pause ',@@ -209,6 +223,8 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyClisetSkillSelIdx(0);}, [skillSuggestions.length, input]);+ const showInput = !state.permissionPrompt && (state.mode === 'chat' || state.mode === 'coding' || state.mode === 'workspace');+const completeSkillSelection = React.useCallback(() => {const picked = skillSuggestions[skillSelIdx];if (!picked) return false;@@ -403,7 +419,8 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCliconst selected = options[permIdxRef.current] || options[0];if (selected) resolvePermissionAndMaybeContinue(selected.value);} else if (key.escape) {- resolvePermissionAndMaybeContinue(state.permissionPrompt.type === 'mode' ? 'ask-me' : 'no');+ if (state.permissionPrompt.type === 'mode') resolvePermissionAndMaybeContinue('ask-me');+ else if (state.permissionPrompt.type !== 'choice') resolvePermissionAndMaybeContinue('no');}return;}@@ -542,7 +559,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli// Tab cycles focus: explorer → code → right panel (chat or git)if (key.tab) {- const showRight = (process.stdout.columns || 80) >= 100;+ const showRight = terminalSize.cols >= 100;const rightFocus = rightPanel === 'chat' ? 'chat' : 'git';const cycle = showRight ? ['explorer', 'code', rightFocus] : ['explorer', 'code'];const nextIdx = (cycle.indexOf(focusArea) + 1) % cycle.length;@@ -563,12 +580,15 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli}if (focusArea === 'code') {- if (key.upArrow) { onInput('/ws scroll -1'); return; }- if (key.downArrow) { onInput('/ws scroll 1'); return; }- if (key.pageUp) { onInput('/ws scroll -15'); return; }- if (key.pageDown) { onInput('/ws scroll 15'); return; }- if (key.ctrl && (ch === 'u' || ch === 'U')) { onInput('/ws scroll -10'); return; }- if (key.ctrl && (ch === 'd' || ch === 'D')) { onInput('/ws scroll 10'); return; }+ const viewerLines = Math.max(1, (terminalSize.rows - 11));+ if (key.upArrow) { onInput(`/ws scroll -1 ${viewerLines}`); return; }+ if (key.downArrow) { onInput(`/ws scroll 1 ${viewerLines}`); return; }+ if (key.pageUp) { onInput(`/ws scroll ${-viewerLines} ${viewerLines}`); return; }+ if (key.pageDown) { onInput(`/ws scroll ${viewerLines} ${viewerLines}`); return; }+ if (key.ctrl && (ch === 'u' || ch === 'U')) { onInput(`/ws scroll ${-viewerLines} ${viewerLines}`); return; }+ if (key.ctrl && (ch === 'd' || ch === 'D')) { onInput(`/ws scroll ${viewerLines} ${viewerLines}`); return; }+ if ((key as any).home) { onInput('/ws scroll-home'); return; }+ if ((key as any).end) { onInput(`/ws scroll-end ${viewerLines}`); return; }}if (focusArea === 'git') {@@ -582,12 +602,14 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli}if (focusArea === 'chat') {- if (key.upArrow) { onInput('/ws chat-scroll -1'); return; }- if (key.downArrow) { onInput('/ws chat-scroll 1'); return; }- if (key.pageUp) { onInput('/ws chat-scroll -10'); return; }- if (key.pageDown) { onInput('/ws chat-scroll 10'); return; }- if (key.ctrl && (ch === 'u' || ch === 'U')) { onInput('/ws chat-scroll -8'); return; }- if (key.ctrl && (ch === 'd' || ch === 'D')) { onInput('/ws chat-scroll 8'); return; }+ if (key.upArrow) { onInput('/ws chat-scroll 1'); return; }+ if (key.downArrow) { onInput('/ws chat-scroll -1'); return; }+ if (key.pageUp) { onInput('/ws chat-scroll 10'); return; }+ if (key.pageDown) { onInput('/ws chat-scroll -10'); return; }+ if (key.ctrl && (ch === 'u' || ch === 'U')) { onInput('/ws chat-scroll 10'); return; }+ if (key.ctrl && (ch === 'd' || ch === 'D')) { onInput('/ws chat-scroll -10'); return; }+ if ((key as any).home) { onInput('/ws chat-home'); return; }+ if ((key as any).end) { onInput('/ws chat-end'); return; }}}}@@ -784,17 +806,17 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli);}- const showInput = !state.permissionPrompt && (state.mode === 'chat' || state.mode === 'coding' || state.mode === 'workspace');-return (<Box flexDirection="column" flexGrow={1}>- <StatusBarView state={state} />{state.backgroundTasks.length > 0 && <BackgroundBarView tasks={state.backgroundTasks} />}{state.mode === 'spotify' ? <SpotifyBody activeIdx={spotifyIdx} nowPlaying={spotifyNow} status={spotifyStatus} volume={spotifyVolume} albumArtAnsi={spotifyArtAnsi} /> : null}{state.mode === 'menu' ? <MenuBody menuIdx={menuIdx} /> : null}- {state.mode === 'coding' ? <CodingBody state={state} /> : null}- {(state.mode === 'workspace' || state.mode === 'chat') ? (- <ChatBody state={state} />+ {state.mode === 'coding' ? <CodingBody state={state} maxDynamicLines={Math.max(3, terminalSize.rows - 14)} /> : null}+ {state.mode === 'workspace' ? (+ <WorkspaceBody state={state} gitCursor={gitCursor} height={Math.max(8, terminalSize.rows - 6)} cols={terminalSize.cols} onInput={onInput} />+ ) : null}+ {state.mode === 'chat' ? (+ <ChatBody state={state} maxDynamicLines={Math.max(3, terminalSize.rows - 14)} />) : null}{state.permissionPrompt && (<PermPromptView prompt={state.permissionPrompt} activeIdx={permIdx} />@@ -827,7 +849,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli))}</Box>)}- <TokenBarView state={state} />+ <TokenBarView state={state} cols={terminalSize.cols} /></Box>);}@@ -847,7 +869,7 @@ function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {const more = tasks.length > 3 ? ` +${tasks.length - 3} more` : '';return (- <Box paddingX={1} paddingBottom={0}>+ <Box paddingX={1} paddingBottom={0} flexShrink={0}><Text color="gray">{'─'.repeat(50)}</Text><Box flexDirection="column" width="100%"><Box>@@ -865,44 +887,16 @@ function BackgroundBarView({ tasks }: { tasks: BackgroundTaskInfo[] }) {);}-function StatusBarView({ state }: { state: TuiState }) {- const modeColor = state.programmingMode === 'execute' ? 'green' : state.programmingMode === 'plan' ? 'yellow' : 'gray';- const modeLabel = state.programmingMode === 'off' ? '' : ` ${state.programmingMode.toUpperCase()}`;- const providerBadge = state.provider ? `⚡ ${state.provider.name} · ${state.provider.model}` : '⚡ No provider';- const viewLabel = state.viewMode === 'balanced' ? 'minimal' : 'detailed';-- // Dynamic subtitle based on thinking state- const runningStep = [...state.toolSteps].reverse().find((s) => s.status === 'running');- const doneSteps = state.toolSteps.filter((s) => s.status === 'done').length;- let subtitle: React.ReactNode;- if (state.isThinking) {- const activity = runningStep ? runningStep.label : 'Processing';- const stepCount = doneSteps > 0 ? `step ${doneSteps + 1}` : 'step 1';- subtitle = <Text color="green">● {stepCount} · {activity}</Text>;- } else {- subtitle = <Text color={BRAND.subtitle}> · Your soul-driven AI agent</Text>;- }+const HEADER_SENTINEL_ID = '__mercury_header__';+function HeaderBanner(): React.ReactNode {return (- <Box flexDirection="column">+ <Box flexDirection="column" flexShrink={0}><Box paddingX={1}><Text color={BRAND.logo}>☿</Text><Text> </Text><Text bold color={BRAND.title}>MERCURY</Text>- {subtitle}- </Box>- <Box paddingX={1} paddingBottom={0}>- <Box flexGrow={1}>- <Text bold color="cyan">{state.agentName}</Text>- {state.programmingMode !== 'off' && <Text> <Text color={modeColor} bold>{modeLabel}</Text></Text>}- {state.saverInfo && state.saverInfo.state !== 'off' && (- <Text> <Text color="gray">|</Text> <Text color={state.saverInfo.state === 'auto' ? 'yellow' : 'green'} bold>{`⚡SAVER${state.saverInfo.state === 'auto' ? ' (auto)' : ''}`}</Text></Text>- )}- {state.projectContext && <Text> <Text color="gray">|</Text> <Text color="blue">{state.projectContext}</Text></Text>}- <Text> <Text color="gray">|</Text> <Text color="yellow">View: {viewLabel}</Text></Text>- <Text> <Text color="gray">|</Text> <Text color="green">{state.permissionMode === 'allow-all' ? '🔓' : '🔒'}</Text></Text>- </Box>- <Text color="magenta">{providerBadge}</Text>+ <Text color={BRAND.subtitle}> · Your soul-driven AI agent</Text></Box><Box paddingX={1}><Text color="gray">{'─'.repeat(50)}</Text>@@ -911,105 +905,121 @@ function StatusBarView({ state }: { state: TuiState }) {);}-function TokenBarView({ state }: { state: TuiState }) {- if (!state.tokenInfo && !state.provider) return null;+function TokenBarView({ state, cols }: { state: TuiState; cols: number }) {+ if (!state.tokenInfo && !state.provider && !state.currentSession) return null;const saverActive = !!(state.saverInfo && state.saverInfo.state !== 'off');const saverColor = state.saverInfo?.state === 'auto' ? 'yellow' : 'green';-- // Color the percentage based on usage thresholds (or saver state if active)const pct = state.tokenInfo?.percentage ?? 0;- const pctColor = saverActive- ? saverColor- : pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'cyan';+ const pctColor = saverActive ? saverColor : pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'cyan';- // Sub-agent count (running only)const runningAgents = state.subAgents.filter((a) => a.status === 'running' || a.status === 'paused').length;- // Background task count (running only)const runningBg = state.backgroundTasks.filter((t) => t.status === 'running').length;-const isWorkspace = state.mode === 'workspace' && state.workspace;- return (- <Box flexDirection="column">- <Box paddingX={1}>- <Text color="gray">{'─'.repeat(50)}</Text>- </Box>- <Box paddingX={1} paddingBottom={0}>- {state.tokenInfo && (- <>- {saverActive && (- <Text color={saverColor} bold>⚡ </Text>- )}- <Text color={pctColor}>{pct < 25 ? '○' : pct < 50 ? '◔' : pct < 75 ? '◑' : pct < 100 ? '◕' : '●'} </Text>- <Text color={pctColor}>- [{'█'.repeat(Math.min(10, Math.round(pct / 10)))}{'░'.repeat(10 - Math.min(10, Math.round(pct / 10)))}]- </Text>- <Text color={pctColor} bold> {pct}%</Text>- {saverActive && state.saverInfo!.savedToday > 0 && (- <Text color="green"> · saved ~{formatCompact(state.saverInfo!.savedToday)}</Text>- )}- {saverActive && state.saverInfo!.savedToday === 0 && (- <Text color={saverColor}> · SAVER</Text>- )}- </>- )}+ // Build colored segments — each has {text, color}. Rendered inline with │.+ const segments: { text: string; color: string }[] = [];- {state.provider && (- <>- <Text color="gray"> │ </Text>- <Text color="magenta">{state.provider.model}</Text>- </>- )}+ // 1. Token bar+ if (state.tokenInfo) {+ if (saverActive) segments.push({ text: '⚡', color: saverColor });+ segments.push({+ text: `${pct < 25 ? '○' : pct < 50 ? '◔' : pct < 75 ? '◑' : pct < 100 ? '◕' : '●'}[${'█'.repeat(Math.min(10, Math.round(pct / 10)))}${'░'.repeat(10 - Math.min(10, Math.round(pct / 10)))}] ${pct}%`,+ color: pctColor,+ });+ if (saverActive && state.saverInfo!.savedToday > 0) {+ segments.push({ text: `~${formatCompact(state.saverInfo!.savedToday)}`, color: 'green' });+ }+ }- {isWorkspace && (- <>- <Text color="gray"> │ </Text>- <Text color="blue">⎇ {state.workspace!.branch}</Text>- {(state.workspace!.ahead > 0 || state.workspace!.behind > 0) && (- <Text color="yellow">- {state.workspace!.ahead > 0 ? ` ↑${state.workspace!.ahead}` : ''}- {state.workspace!.behind > 0 ? ` ↓${state.workspace!.behind}` : ''}- </Text>- )}- {(state.workspace!.stagedCount > 0 || state.workspace!.unstagedCount > 0) && (- <Text color="gray">- {state.workspace!.stagedCount > 0 ? <Text color="green"> S{state.workspace!.stagedCount}</Text> : null}- {state.workspace!.unstagedCount > 0 ? <Text color="yellow"> M{state.workspace!.unstagedCount}</Text> : null}- </Text>- )}- </>- )}+ // 2. Provider+ if (state.provider) {+ segments.push({ text: `${state.provider.name} · ${state.provider.model}`, color: 'magenta' });+ }- {!isWorkspace && runningBg > 0 && (- <>- <Text color="gray"> │ </Text>- <Text color="cyan">⏳ {runningBg} bg</Text>- </>- )}- {!isWorkspace && runningAgents > 0 && (- <>- <Text color="gray"> │ </Text>- <Text color="magenta">🤖 {runningAgents} agent{runningAgents !== 1 ? 's' : ''}</Text>- </>- )}+ // 3. Session+ if (state.currentSession) {+ segments.push({ text: `${state.currentSession.alias} [${state.currentSession.shortId}]`, color: 'cyan' });+ }++ // 4. Workspace+ if (isWorkspace && state.workspace) {+ const ws = state.workspace;+ let wsStr = `⎇ ${ws.branch}`;+ if (ws.ahead > 0) wsStr += ` ↑${ws.ahead}`;+ if (ws.behind > 0) wsStr += ` ↓${ws.behind}`;+ if (ws.stagedCount > 0) wsStr += ` S${ws.stagedCount}`;+ if (ws.unstagedCount > 0) wsStr += ` M${ws.unstagedCount}`;+ segments.push({ text: wsStr, color: 'blue' });+ }++ // 5. Background tasks+ if (!isWorkspace && runningBg > 0) {+ segments.push({ text: `⏳ ${runningBg}bg`, color: 'cyan' });+ }++ // 6. Sub-agents+ if (!isWorkspace && runningAgents > 0) {+ segments.push({ text: `🤖 ${runningAgents}agent${runningAgents !== 1 ? 's' : ''}`, color: 'magenta' });+ }++ // Calculate total width and drop segments from the right if they don't fit+ const sepStr = ' │ ';+ const maxLen = Math.max(20, cols - 2);+ let totalLen = segments.reduce((sum, s, i) => sum + s.text.length + (i > 0 ? sepStr.length : 0), 0);+ const visible = [...segments];+ while (totalLen > maxLen && visible.length > 1) {+ const removed = visible.pop()!;+ totalLen -= removed.text.length + sepStr.length;+ }+ if (totalLen > maxLen && visible.length > 0) {+ const last = visible[visible.length - 1];+ const excess = totalLen - maxLen;+ last.text = last.text.slice(0, Math.max(1, last.text.length - excess - 1)) + '…';+ }++ return (+ <Box flexDirection="column" flexShrink={0}>+ <Box paddingX={1}>+ <Text color="gray">{'─'.repeat(Math.max(20, cols - 2))}</Text>+ </Box>+ <Box paddingX={1} paddingBottom={0} height={1} overflow="hidden">+ {visible.map((seg, i) => (+ <React.Fragment key={i}>+ {i > 0 && <Text color="gray">{sepStr}</Text>}+ <Text color={seg.color} wrap="truncate">{seg.text}</Text>+ </React.Fragment>+ ))}</Box></Box>);}+function truncateStr(text: string, maxLen: number): string {+ if (text.length <= maxLen) return text;+ return text.slice(0, Math.max(1, maxLen - 1)) + '…';+}+function formatCompact(n: number): string {if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;return String(n);}-function ChatBody({ state }: { state: TuiState }) {+function ChatBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines: number }) {+ const staticMessages = state.chatMessages.filter((message) => !message.streaming && !message.id.startsWith('heartbeat-'));+ const dynamicMessages = state.chatMessages.filter((message) => message.streaming || message.id.startsWith('heartbeat-'));+ const staticItems: Array<string | ChatMessage> = [HEADER_SENTINEL_ID, ...staticMessages];return (<Box flexDirection="row" flexGrow={1}>{state.sidebarSections.length > 0 && <SidebarView sections={state.sidebarSections} />}<Box flexDirection="column" flexGrow={1}>- <ChatMessagesView messages={state.chatMessages} agentName={state.agentName} />+ <Static items={staticItems}>+ {(item) => typeof item === 'string'+ ? <HeaderBanner key={item} />+ : <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}+ </Static>+ <ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} />}{state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}@@ -1018,7 +1028,7 @@ function ChatBody({ state }: { state: TuiState }) {);}-function CodingBody({ state }: { state: TuiState }) {+function CodingBody({ state, maxDynamicLines }: { state: TuiState; maxDynamicLines: number }) {const modeLabels: Record<ProgrammingModeState, { label: string; color: string }> = {off: { label: 'OFF', color: 'gray' },plan: { label: 'PLAN', color: 'yellow' },@@ -1026,6 +1036,9 @@ function CodingBody({ state }: { state: TuiState }) {};const modeInfo = modeLabels[state.programmingMode];const fileSection = state.sidebarSections.find((s) => s.title === 'Files');+ const staticMessages = state.chatMessages.filter((message) => !message.streaming && !message.id.startsWith('heartbeat-'));+ const dynamicMessages = state.chatMessages.filter((message) => message.streaming || message.id.startsWith('heartbeat-'));+ const staticItems: Array<string | ChatMessage> = [HEADER_SENTINEL_ID, ...staticMessages];return (<Box flexDirection="row" flexGrow={1}>@@ -1048,7 +1061,12 @@ function CodingBody({ state }: { state: TuiState }) {{state.subAgents.length > 0 && <AgentPanelView agents={state.subAgents} />}</Box><Box flexDirection="column" flexGrow={1}>- <ChatMessagesView messages={state.chatMessages} agentName={state.agentName} />+ <Static items={staticItems}>+ {(item) => typeof item === 'string'+ ? <HeaderBanner key={item} />+ : <ChatMessagesView key={item.id} messages={[item]} agentName={state.agentName} />}+ </Static>+ <ChatMessagesView messages={dynamicMessages} agentName={state.agentName} maxLines={maxDynamicLines} />{state.toolSteps.length > 0 && !state.isThinking && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} idle />}{state.isThinking && <ThinkingIndicator agentName={state.agentName} steps={state.toolSteps} mode={state.mode} />}<Box paddingX={1} marginTop={1}>@@ -1067,7 +1085,12 @@ function useTerminalSize(): { rows: number; cols: number } {React.useEffect(() => {const onResize = () => setSize({ rows: stdout.rows || 24, cols: stdout.columns || 80 });stdout.on('resize', onResize);- return () => { stdout.off('resize', onResize); };+ const fallback = setInterval(onResize, 500);+ fallback.unref?.();+ return () => {+ stdout.off('resize', onResize);+ clearInterval(fallback);+ };}, [stdout]);return size;}@@ -1117,7 +1140,7 @@ function ExplorerPanel({panelHeight: number;isFocused: boolean;}) {- const windowSize = Math.max(1, panelHeight - 2); // leave room for header + footer+ const windowSize = Math.max(1, panelHeight - 3); // border + headerconst explorerStart = Math.max(0, Math.min(ws.selectedIndex - Math.floor(windowSize / 2), Math.max(0, ws.nodes.length - windowSize)));const visible = ws.nodes.slice(explorerStart, explorerStart + windowSize);@@ -1167,14 +1190,15 @@ function CodeViewerPanel({panelHeight: number;isFocused: boolean;}) {- const viewerLines = Math.max(1, panelHeight - 3); // header + separator + footer+ const viewerLines = Math.max(1, panelHeight - 4); // border + header + footerconst preview = ws.openedFilePreview;- const offset = ws.codeScrollOffset;const totalLines = preview.length;+ const maxOffset = Math.max(0, totalLines - viewerLines);+ const offset = Math.max(0, Math.min(maxOffset, ws.codeScrollOffset));const visibleLines = preview.slice(offset, offset + viewerLines);const lineNumWidth = Math.max(3, String(offset + viewerLines).length);const fileName = ws.openedFilePath- ? ws.openedFilePath.replace(ws.rootPath + '/', '')+ ? ws.openedFilePath.slice(ws.rootPath.length).replace(/^[/\\]+/, '') || ws.openedFilePath: '';return (@@ -1241,7 +1265,7 @@ function GitPanel({isFocused: boolean;gitCursor: number;}) {- const listHeight = Math.max(1, panelHeight - 6); // header + branch + staged/unstaged labels + footer + border+ const listHeight = Math.max(1, panelHeight - 5); // border + header + stats + footerconst gitStart = Math.max(0, Math.min(gitCursor - Math.floor(listHeight / 2), Math.max(0, ws.gitFiles.length - listHeight)));const visible = ws.gitFiles.slice(gitStart, gitStart + listHeight);@@ -1297,13 +1321,15 @@ function AgentOutputPanel({panelHeight,isFocused,scrollOffset,+ onScrollClamp,}: {state: TuiState;panelHeight: number;isFocused: boolean;scrollOffset: number;+ onScrollClamp: (distance: number) => void;}) {- const viewLines = Math.max(1, panelHeight - 4); // header + thinking + footer + border+ const viewLines = Math.max(1, panelHeight - 5 - (state.isThinking ? 1 : 0)); // border + header + status + footer// Build a flat array of rendered lines from messagesconst allLines: Array<{ key: string; node: React.ReactNode }> = [];@@ -1311,7 +1337,7 @@ function AgentOutputPanel({for (const msg of state.chatMessages) {const roleColor = msg.role === 'user' ? 'yellow' : msg.role === 'system' ? 'gray' : 'cyan';const prefix = msg.role === 'user' ? 'You' : msg.role === 'system' ? 'Sys' : state.agentName;- const contentLines = msg.content.split('\n');+ const contentLines = normalizeTerminalText(msg.content).split('\n');// First line with role prefixallLines.push({@@ -1344,15 +1370,14 @@ function AgentOutputPanel({});}- // Auto-scroll to bottom if no manual offset, or use scrollOffsetconst totalLines = allLines.length;- const effectiveOffset = scrollOffset === 0- ? Math.max(0, totalLines - viewLines) // auto-scroll to bottom- : Math.max(0, Math.min(scrollOffset, totalLines - viewLines));-- const visibleLines = allLines.slice(effectiveOffset, effectiveOffset + viewLines);- const hiddenAbove = effectiveOffset;- const hiddenBelow = Math.max(0, totalLines - effectiveOffset - viewLines);+ const viewport = getViewportWindow(totalLines, viewLines, scrollOffset);+ React.useEffect(() => {+ if (viewport.distanceFromBottom !== scrollOffset) onScrollClamp(viewport.distanceFromBottom);+ }, [onScrollClamp, scrollOffset, viewport.distanceFromBottom]);+ const visibleLines = allLines.slice(viewport.start, viewport.end);+ const hiddenAbove = viewport.start;+ const hiddenBelow = Math.max(0, totalLines - viewport.end);return (<Box@@ -1367,9 +1392,6 @@ function AgentOutputPanel({<Spacer /><Text dimColor>{state.chatMessages.length} msg{state.chatMessages.length !== 1 ? 's' : ''}</Text></Box>- {hiddenAbove > 0 && (- <Box paddingX={1}><Text dimColor>↑ {hiddenAbove} line{hiddenAbove !== 1 ? 's' : ''} above</Text></Box>- )}{visibleLines.length === 0 ? (<Box flexDirection="column" flexGrow={1} alignItems="center" justifyContent="center"><Text dimColor>No messages yet.</Text>@@ -1381,8 +1403,8 @@ function AgentOutputPanel({)))}{/* Fill remaining space */}- {visibleLines.length > 0 && visibleLines.length < viewLines - (hiddenAbove > 0 ? 1 : 0) && (- Array.from({ length: viewLines - visibleLines.length - (hiddenAbove > 0 ? 1 : 0) }, (_, i) => (+ {visibleLines.length > 0 && visibleLines.length < viewLines && (+ Array.from({ length: viewLines - visibleLines.length }, (_, i) => (<Box key={`apad-${i}`}><Text> </Text></Box>)))}@@ -1397,16 +1419,18 @@ function AgentOutputPanel({})()}</Text></Box>)}+ <Box paddingX={1} height={1}>+ <Text dimColor>↑{hiddenAbove} · {viewport.start + (totalLines > 0 ? 1 : 0)}-{viewport.end}/{totalLines} · ↓{hiddenBelow}</Text>+ </Box><Box paddingX={1}>- <Text dimColor>{isFocused ? '↑↓ scroll · Ctrl+G git · Esc back' : 'Ctrl+J focus'}</Text>+ <Text dimColor>{isFocused ? '↑↓ · PgUp/PgDn · Home/End · Esc back' : 'Ctrl+J focus'}</Text></Box></Box>);}-function WorkspaceBody({ state, workspacePane, detailCursor, gitCursor }: { state: TuiState; workspacePane: 'files' | 'details' | 'git'; detailCursor: number; gitCursor: number }) {+function WorkspaceBody({ state, gitCursor, height, cols, onInput }: { state: TuiState; gitCursor: number; height: number; cols: number; onInput: (text: string) => void }) {const ws = state.workspace;- const { rows, cols } = useTerminalSize();if (!ws?.active) {return (@@ -1420,10 +1444,7 @@ function WorkspaceBody({ state, workspacePane, detailCursor, gitCursor }: { statconst focusArea = ws.focusArea;const rightPanel = ws.rightPanel;- // Layout math: rows budget- // statusBar(2) + tabBar(1) + inputBox(3) = 6 fixed rows- const fixedOverhead = 6;- const idePanelHeight = Math.max(8, rows - fixedOverhead);+ const idePanelHeight = Math.max(4, height - 1); // tab bar occupies one row// Column widths — 3 columns: explorer | code | right panel (chat or git)let explorerWidth: number;@@ -1445,9 +1466,9 @@ function WorkspaceBody({ state, workspacePane, detailCursor, gitCursor }: { stat}return (- <Box flexDirection="column" flexGrow={1}>+ <Box flexDirection="column" height={height} overflow="hidden"><WorkspaceTabBar ws={ws} focusArea={focusArea} cols={cols} />- <Box flexDirection="row">+ <Box flexDirection="row" height={idePanelHeight} overflow="hidden"><Box width={explorerWidth}><ExplorerPanelws={ws}@@ -1470,6 +1491,7 @@ function WorkspaceBody({ state, workspacePane, detailCursor, gitCursor }: { statpanelHeight={idePanelHeight}isFocused={focusArea === 'chat'}scrollOffset={ws.chatScrollOffset}+ onScrollClamp={(distance) => onInput(`/ws chat-set ${distance}`)}/>) : (<GitPanel@@ -1555,81 +1577,100 @@ function SpotifyBody({ activeIdx, nowPlaying, status, volume, albumArtAnsi }: {);}-function ChatMessagesView({ messages, agentName }: { messages: ChatMessage[]; agentName: string }) {+function ChatMessagesView({ messages, agentName, maxLines }: { messages: ChatMessage[]; agentName: string; maxLines?: number }) {if (messages.length === 0) return null;- const visible = messages.slice(-50);- const cache = React.useRef<Map<string, string>>(new Map());- const wasStreaming = React.useRef<Set<string>>(new Set());+return (- <Box flexDirection="column" flexGrow={1} paddingX={1}>- {visible.map((msg) => {- const isCompletion = msg.role === 'system' && msg.content.startsWith('━━━');- const roleColor = isCompletion ? 'green' : msg.role === 'user' ? 'yellow' : msg.role === 'system' ? 'gray' : 'cyan';- const prefix = msg.role === 'user' ? 'You' : msg.role === 'system' ? '' : agentName;- if (isCompletion) {- const meta = msg.completionMeta;- const formatTokens = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;- return (- <Box key={msg.id} flexDirection="column" marginBottom={1}>- <Text color="green" bold>{msg.content}</Text>- {meta && (- <Box flexDirection="row" paddingLeft={2}>- <Text color="gray">☿ </Text>- <Text color="white" bold>{meta.model}</Text>- <Text color="gray"> via </Text>- <Text color="cyan">{meta.provider}</Text>- <Text color="gray"> · </Text>- <Text color="yellow">{formatTokens(meta.totalTokens)}</Text>- <Text color="gray"> tokens · Budget </Text>- {(() => {- const pct = Math.round(meta.budgetPercentage);- const barLen = 16;- const filled = Math.round((pct / 100) * barLen);- const barColor = pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green';- return (- <>- <Text color={barColor}>{'█'.repeat(filled)}</Text>- <Text color="gray">{'░'.repeat(barLen - filled)}</Text>- <Text color={barColor}> {pct}%</Text>- </>- );- })()}- </Box>- )}- </Box>- );- }- let rendered: string;- if (msg.streaming) {- rendered = renderMarkdown(msg.content);- cache.current.set(msg.id, rendered);- wasStreaming.current.add(msg.id);- } else if (wasStreaming.current.has(msg.id)) {- // Streaming just ended — re-render with final complete content- rendered = renderMarkdown(msg.content);- cache.current.set(msg.id, rendered);- wasStreaming.current.delete(msg.id);- } else {- rendered = cache.current.get(msg.id) ?? renderMarkdown(msg.content);- cache.current.set(msg.id, rendered);- }- return (- <Box key={msg.id} flexDirection="column" marginBottom={1}>- <Box>- <Text bold color={roleColor}>{prefix}:</Text>- </Box>- <Box marginLeft={2} flexDirection="column">- {rendered.split('\n').map((line, idx) => (- <Text key={`${msg.id}:${idx}`}>{line.length > 0 ? line : ' '}</Text>- ))}- </Box>- </Box>- );- })}+ <Box flexDirection="column" flexGrow={1} flexShrink={0} paddingX={1}>+ {messages.slice(-50).map((msg) => (+ <MessageRow key={msg.id} msg={msg} agentName={agentName} maxLines={maxLines} />+ ))}</Box>);}+/**+ * Renders a single chat message (user / agent / system completion banner).+ *+ * `live` marks the currently-streaming message; it gets `flexShrink={0}` so+ * Ink's Yoga layout never compresses its rows while deltas are arriving,+ * which is what previously caused the visible "font shrink" + flicker.+ */+const MessageRow = React.memo(function MessageRow({+ msg,+ agentName,+ maxLines,+}: { msg: ChatMessage; agentName: string; maxLines?: number }) {+ const isCompletion = msg.role === 'system' && msg.content.startsWith('━━━');+ const roleColor = isCompletion+ ? 'green'+ : msg.role === 'user'+ ? 'yellow'+ : msg.role === 'system'+ ? 'gray'+ : 'cyan';+ const prefix = msg.role === 'user' ? 'You' : msg.role === 'system' ? '' : agentName;++ if (isCompletion) {+ const meta = msg.completionMeta;+ const formatTokens = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);+ return (+ <Box key={msg.id} flexDirection="column" marginBottom={1} flexShrink={0}>+ <Text color="green" bold>+ {msg.content}+ </Text>+ {meta && (+ <Box flexDirection="row" paddingLeft={2} flexShrink={0}>+ <Text color="gray">☿ </Text>+ <Text color="white" bold>+ {meta.model}+ </Text>+ <Text color="gray"> via </Text>+ <Text color="cyan">{meta.provider}</Text>+ <Text color="gray"> · </Text>+ <Text color="yellow">{formatTokens(meta.totalTokens)}</Text>+ <Text color="gray"> tokens · Budget </Text>+ {(() => {+ const pct = Math.round(meta.budgetPercentage);+ const barLen = 16;+ const filled = Math.round((pct / 100) * barLen);+ const barColor = pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green';+ return (+ <>+ <Text color={barColor}>{'█'.repeat(filled)}</Text>+ <Text color="gray">{'░'.repeat(barLen - filled)}</Text>+ <Text color={barColor}> {pct}%</Text>+ </>+ );+ })()}+ </Box>+ )}+ </Box>+ );+ }++ const renderedLines = renderMarkdown(msg.content).split('\n');+ const visibleLines = maxLines && renderedLines.length > maxLines+ ? ['…', ...renderedLines.slice(-(maxLines - 1))]+ : renderedLines;+ return (+ <Box key={msg.id} flexDirection="column" marginBottom={1} flexShrink={0}>+ <Box flexShrink={0}>+ <Text bold color={roleColor}>+ {prefix}:+ </Text>+ </Box>+ <Box marginLeft={2} flexDirection="column" flexShrink={0}>+ {visibleLines.map((line, idx) => (+ <Box key={`${msg.id}:${idx}`} flexShrink={0}>+ <Text>{line.length > 0 ? line : ' '}</Text>+ </Box>+ ))}+ </Box>+ </Box>+ );+});+const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];/**diff --git a/src/ui/terminal-viewport.test.ts b/src/ui/terminal-viewport.test.tsnew file mode 100644index 00000000..eda0b06a--- /dev/null+++ b/src/ui/terminal-viewport.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';+import { getViewportWindow, moveViewport, normalizeTerminalText } from './terminal-viewport.js';++describe('terminal viewport', () => {+ it('follows the bottom at zero distance and reaches both boundaries', () => {+ expect(getViewportWindow(100, 20, 0)).toMatchObject({ start: 80, end: 100, distanceFromBottom: 0 });+ expect(getViewportWindow(100, 20, Number.MAX_SAFE_INTEGER)).toMatchObject({+ start: 0,+ end: 20,+ distanceFromBottom: 80,+ });+ expect(moveViewport(80, -100, 100, 20)).toBe(0);+ expect(moveViewport(0, 100, 100, 20)).toBe(80);+ });++ it('does not create blank space when content is shorter than the viewport', () => {+ expect(getViewportWindow(3, 20, 10)).toEqual({+ start: 0,+ end: 3,+ distanceFromBottom: 0,+ maxDistanceFromBottom: 0,+ });+ });++ it('normalizes Windows and legacy Mac line endings', () => {+ expect(normalizeTerminalText('one\r\ntwo\rthree')).toBe('one\ntwo\nthree');+ });+});diff --git a/src/ui/terminal-viewport.ts b/src/ui/terminal-viewport.tsnew file mode 100644index 00000000..f74e8c6e--- /dev/null+++ b/src/ui/terminal-viewport.ts@@ -0,0 +1,34 @@+export interface ViewportWindow {+ start: number;+ end: number;+ distanceFromBottom: number;+ maxDistanceFromBottom: number;+}++export function normalizeTerminalText(text: string): string {+ return text.replace(/\r\n?/g, '\n');+}++export function getViewportWindow(totalLines: number, viewportLines: number, distanceFromBottom: number): ViewportWindow {+ const safeTotal = Math.max(0, totalLines);+ const safeViewport = Math.max(1, viewportLines);+ const maxDistanceFromBottom = Math.max(0, safeTotal - safeViewport);+ const distance = Math.max(0, Math.min(maxDistanceFromBottom, distanceFromBottom));+ const start = Math.max(0, safeTotal - safeViewport - distance);+ return {+ start,+ end: Math.min(safeTotal, start + safeViewport),+ distanceFromBottom: distance,+ maxDistanceFromBottom,+ };+}++export function moveViewport(+ distanceFromBottom: number,+ deltaTowardTop: number,+ totalLines: number,+ viewportLines: number,+): number {+ const { maxDistanceFromBottom } = getViewportWindow(totalLines, viewportLines, distanceFromBottom);+ return Math.max(0, Math.min(maxDistanceFromBottom, distanceFromBottom + deltaTowardTop));+}diff --git a/src/ui/types.ts b/src/ui/types.tsindex ca23e303..dbe8a7c5 100644--- a/src/ui/types.ts+++ b/src/ui/types.ts@@ -116,6 +116,12 @@ export interface SaverInfo {savedLifetime: number;}+export interface CurrentSessionInfo {+ alias: string;+ shortId: string;+ title: string;+}+export interface MercuryAppState {mode: AppMode;programmingMode: ProgrammingModeState;@@ -133,6 +139,7 @@ export interface MercuryAppState {isThinking: boolean;permissionPrompt: PermissionPromptState | null;workspace: WorkspaceState | null;+ currentSession: CurrentSessionInfo | null;}export type BgTaskType = 'shell' | 'agent';@@ -152,7 +159,7 @@ export interface BackgroundTaskInfo {}export interface PermissionPromptState {- type: 'mode' | 'ask' | 'continue';+ type: 'mode' | 'ask' | 'continue' | 'choice';message: string;options?: Array<{ value: string; label: string }>;resolve: (value: string | boolean) => void;diff --git a/src/utils/config-cloud.test.ts b/src/utils/config-cloud.test.tsnew file mode 100644index 00000000..c59b6875--- /dev/null+++ b/src/utils/config-cloud.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import {+ LEGACY_SEED_API_URL,+ LEGACY_SEED_WS_URL,+ MERCURY_CLOUD_API_URL,+ MERCURY_CLOUD_WS_URL,+} from '../cloud/endpoints.js';+import { getDefaultConfig, normalizeCloudConfig } from './config.js';++describe('Mercury Cloud endpoint defaults', () => {+ it('seeds the production backend API and WebSocket endpoints', () => {+ const previousApiUrl = process.env.MERCURY_CLOUD_API_URL;+ const previousWsUrl = process.env.MERCURY_CLOUD_WS_URL;+ delete process.env.MERCURY_CLOUD_API_URL;+ delete process.env.MERCURY_CLOUD_WS_URL;+ const config = getDefaultConfig();+ if (previousApiUrl === undefined) delete process.env.MERCURY_CLOUD_API_URL;+ else process.env.MERCURY_CLOUD_API_URL = previousApiUrl;+ if (previousWsUrl === undefined) delete process.env.MERCURY_CLOUD_WS_URL;+ else process.env.MERCURY_CLOUD_WS_URL = previousWsUrl;++ expect(config.cloud.apiUrl).toBe(MERCURY_CLOUD_API_URL);+ expect(config.cloud.wsUrl).toBe(MERCURY_CLOUD_WS_URL);+ });++ it('migrates only the obsolete seeded endpoints', () => {+ const config = getDefaultConfig();+ config.cloud.apiUrl = LEGACY_SEED_API_URL;+ config.cloud.wsUrl = LEGACY_SEED_WS_URL;++ normalizeCloudConfig(config);++ expect(config.cloud.apiUrl).toBe(MERCURY_CLOUD_API_URL);+ expect(config.cloud.wsUrl).toBe(MERCURY_CLOUD_WS_URL);+ expect(config.providers.mercuryCloud.baseUrl).toBe(MERCURY_CLOUD_API_URL);+ });++ it('preserves custom self-hosted endpoints', () => {+ const config = getDefaultConfig();+ config.cloud.apiUrl = 'https://mercury.example.com';+ config.cloud.wsUrl = 'wss://mercury.example.com/custom-ws';++ normalizeCloudConfig(config);++ expect(config.cloud.apiUrl).toBe('https://mercury.example.com');+ expect(config.cloud.wsUrl).toBe('wss://mercury.example.com/custom-ws');+ });+});diff --git a/src/utils/config.ts b/src/utils/config.tsindex f7ce2b49..cb0ac92e 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -1,9 +1,15 @@-import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';+import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync, closeSync, openSync, renameSync, unlinkSync } from 'node:fs';import { join, resolve } from 'node:path';import { homedir } from 'node:os';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import { config as loadDotenv } from 'dotenv';import type { SignalAccessUser, SignalPendingRequest, DiscordAccessUser, DiscordPendingRequest, SlackAccessUser, SlackPendingRequest } from '../types/channel.js';+import {+ LEGACY_SEED_API_URL,+ LEGACY_SEED_WS_URL,+ MERCURY_CLOUD_API_URL,+ MERCURY_CLOUD_WS_URL,+} from '../cloud/endpoints.js';const MERCURY_HOME = join(homedir(), '.mercury');@@ -48,6 +54,7 @@ export interface TelegramPendingRequest {}export type ProviderName =+ | 'mercuryCloud'| 'openai'| 'anthropic'| 'deepseek'@@ -60,14 +67,27 @@ export type ProviderName =| 'chatgptWeb'| 'githubCopilot';+export interface CloudConfig {+ enabled: boolean;+ apiUrl: string;+ wsUrl: string;+ jwt: string;+ refreshToken: string;+ agentId: string;+ tier: string;+ agentApiKey: string;+}+export interface MercuryConfig {identity: {name: string;owner: string;creator?: string;};+ cloud: CloudConfig;providers: {default: ProviderName;+ mercuryCloud: ProviderConfig;openai: ProviderConfig;anthropic: ProviderConfig;deepseek: ProviderConfig;@@ -138,6 +158,14 @@ export interface MercuryConfig {secondBrain: {enabled: boolean;};+ collaborativeKnowledge?: {+ /** When true, new memories extracted via remember() are marked shareable. */+ shareLearning?: boolean;+ /** When true, the agent queries the cloud shared pool for additional+ * context after retrieving from its local second brain. Defaults to+ * true when the agent is paired with Mercury Cloud. */+ poolSearch?: boolean;+ };};heartbeat: {intervalMinutes: number;@@ -196,14 +224,33 @@ function getEnvBool(key: string, fallback: boolean): boolean {export function getDefaultConfig(): MercuryConfig {const home = getMercuryHome();+ const cloudApiUrl = getEnv('MERCURY_CLOUD_API_URL', MERCURY_CLOUD_API_URL);+ const cloudWsUrl = getEnv('MERCURY_CLOUD_WS_URL', MERCURY_CLOUD_WS_URL);return {identity: {name: getEnv('MERCURY_NAME', 'Mercury'),owner: getEnv('MERCURY_OWNER', ''),creator: getEnv('MERCURY_CREATOR', ''),},+ cloud: {+ enabled: getEnvBool('MERCURY_CLOUD_ENABLED', false),+ apiUrl: cloudApiUrl,+ wsUrl: cloudWsUrl,+ jwt: getEnv('MERCURY_CLOUD_JWT', ''),+ refreshToken: getEnv('MERCURY_CLOUD_REFRESH_TOKEN', ''),+ agentId: getEnv('MERCURY_CLOUD_AGENT_ID', ''),+ tier: getEnv('MERCURY_CLOUD_TIER', 'free'),+ agentApiKey: getEnv('MERCURY_CLOUD_AGENT_API_KEY', ''),+ },providers: {default: getEnv('DEFAULT_PROVIDER', 'deepseek') as ProviderName,+ mercuryCloud: {+ name: 'mercuryCloud',+ apiKey: '',+ baseUrl: cloudApiUrl,+ model: getEnv('MERCURY_CLOUD_MODEL', 'mercury-mini'),+ enabled: getEnvBool('MERCURY_CLOUD_ENABLED', false),+ },openai: {name: 'openai',apiKey: getEnv('OPENAI_API_KEY', ''),@@ -340,6 +387,10 @@ export function getDefaultConfig(): MercuryConfig {secondBrain: {enabled: getEnvBool('SECOND_BRAIN_ENABLED', true),},+ collaborativeKnowledge: {+ shareLearning: getEnvBool('SHARE_LEARNING', false),+ poolSearch: getEnvBool('POOL_SEARCH', true),+ },},heartbeat: {intervalMinutes: getEnvNum('HEARTBEAT_INTERVAL_MINUTES', 60),@@ -374,13 +425,17 @@ export function getDefaultConfig(): MercuryConfig {}const CONFIG_PATH = join(getMercuryHome(), 'mercury.yaml');+const CONFIG_LOCK_PATH = `${CONFIG_PATH}.lock`;export function loadConfig(): MercuryConfig {if (existsSync(CONFIG_PATH)) {+ // Tighten permissions on an existing config file that contains live+ // tokens but was written before the 0600 default.+ try { chmodSync(CONFIG_PATH, 0o600); } catch {}const raw = readFileSync(CONFIG_PATH, 'utf-8');const fileConfig = parseYaml(raw) as Partial<MercuryConfig>;const defaults = getDefaultConfig();- return migrateLegacyDiscordAccess(+ return normalizeCloudConfig(migrateLegacyDiscordAccess(migrateLegacyOllamaLocalBaseUrl(migrateLegacyOllamaCloudBaseUrl(migrateLegacySignalAccess(@@ -388,19 +443,116 @@ export function loadConfig(): MercuryConfig {),),),- );+ ));}- return migrateLegacyDiscordAccess(+ return normalizeCloudConfig(migrateLegacyDiscordAccess(migrateLegacyTelegramAccess(getDefaultConfig()),- );+ ));+}++export function normalizeCloudConfig(config: MercuryConfig): MercuryConfig {+ // Single source of truth: cloud.apiUrl/wsUrl define the Mercury Cloud backend.+ // providers.mercuryCloud.baseUrl is derived for the OpenAI-compatible client.+ if (!config.cloud.apiUrl || config.cloud.apiUrl === LEGACY_SEED_API_URL) {+ config.cloud.apiUrl = MERCURY_CLOUD_API_URL;+ }+ if (config.cloud.wsUrl === LEGACY_SEED_WS_URL) {+ config.cloud.wsUrl = MERCURY_CLOUD_WS_URL;+ }+ if (!config.cloud.wsUrl) config.cloud.wsUrl = deriveCloudWsUrl(config.cloud.apiUrl);+ config.providers.mercuryCloud.baseUrl = config.cloud.apiUrl;+ if (config.cloud.jwt && !config.providers.mercuryCloud.apiKey) {+ config.providers.mercuryCloud.apiKey = config.cloud.jwt;+ }+ return config;+}++function deriveCloudWsUrl(apiUrl: string): string {+ try {+ const url = new URL(apiUrl);+ url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';+ url.pathname = `${url.pathname.replace(/\/$/, '')}/ws`;+ url.search = '';+ url.hash = '';+ return url.toString();+ } catch {+ return MERCURY_CLOUD_WS_URL;+ }}export function saveConfig(config: MercuryConfig): void {+ const lockFd = acquireConfigLock();+ try {+ saveConfigUnlocked(config);+ } finally {+ releaseConfigLock(lockFd);+ }+}++export function updateConfig(mutator: (config: MercuryConfig) => void): MercuryConfig {+ const lockFd = acquireConfigLock();+ try {+ const config = loadConfig();+ mutator(config);+ saveConfigUnlocked(config);+ return config;+ } finally {+ releaseConfigLock(lockFd);+ }+}++function saveConfigUnlocked(config: MercuryConfig): void {+ config = normalizeCloudConfig(config);const dir = getMercuryHome();if (!existsSync(dir)) {mkdirSync(dir, { recursive: true });}- writeFileSync(CONFIG_PATH, stringifyYaml(config), 'utf-8');+ const tempPath = `${CONFIG_PATH}.${process.pid}.${Date.now()}.tmp`;+ try {+ writeFileSync(tempPath, stringifyYaml(config), { encoding: 'utf-8', mode: 0o600 });+ renameSync(tempPath, CONFIG_PATH);+ } finally {+ try { unlinkSync(tempPath); } catch {}+ }+ // The config file contains live JWTs and refresh tokens. Restrict to the+ // owner so other users on shared servers cannot read or rotate them.+ try { chmodSync(CONFIG_PATH, 0o600); } catch {}+}++function acquireConfigLock(): number {+ const dir = getMercuryHome();+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });+ const deadline = Date.now() + 2_000;+ const waitBuffer = new Int32Array(new SharedArrayBuffer(4));++ while (true) {+ try {+ const fd = openSync(CONFIG_LOCK_PATH, 'wx', 0o600);+ writeFileSync(fd, String(process.pid), 'utf-8');+ return fd;+ } catch (error: any) {+ if (error?.code !== 'EEXIST') throw error;+ let ownerPid = 0;+ try { ownerPid = parseInt(readFileSync(CONFIG_LOCK_PATH, 'utf-8'), 10); } catch {}+ let ownerAlive = false;+ if (ownerPid > 0) {+ try { process.kill(ownerPid, 0); ownerAlive = true; } catch {}+ }+ if (ownerAlive) {+ if (Date.now() >= deadline) {+ throw new Error(`Mercury configuration is still being updated by process ${ownerPid}; retry the command`);+ }+ Atomics.wait(waitBuffer, 0, 0, 25);+ continue;+ }+ try { unlinkSync(CONFIG_LOCK_PATH); } catch {}+ }+ }+}++function releaseConfigLock(fd: number): void {+ try { closeSync(fd); } catch {}+ try { unlinkSync(CONFIG_LOCK_PATH); } catch {}}export function isSetupComplete(): boolean {@@ -446,6 +598,9 @@ export function getActiveProviders(config: MercuryConfig): ProviderConfig[] {export function isProviderConfigured(provider: ProviderConfig): boolean {if (!provider.enabled) return false;+ if (provider.name === 'mercuryCloud') {+ return provider.model.length > 0;+ }if (provider.name === 'ollamaLocal') {return provider.baseUrl.length > 0 && provider.model.length > 0;}diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex 8d855d85..8cedcb13 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -112,6 +112,12 @@ export function getManual(): string {['/menu', 'Open the CLI command picker with arrow-key navigation'],['/help', 'Show this manual'],['/status', 'Show config and budget info'],+ ['/sessions', 'List active canonical sessions'],+ ['/session new', 'Create and switch to a new session'],+ ['/session <ref>', 'Switch by UUID/prefix/alias'],+ ['/session current', 'Show the current session'],+ ['/session archive <ref>', 'Archive a session'],+ ['/session delete <ref>', 'Permanently delete a session after confirmation'],['/progress', 'Show live status for the current long task'],['/telegram', 'CLI chat only: open the Telegram management menu'],['/telegram pending', 'CLI chat only: list pending Telegram requests'],@@ -158,6 +164,11 @@ export function getManual(): string {['/code agent <task>', 'Delegate a coding task to a sub-agent in background'],['/code off', 'Exit programming mode'],['/code toggle', 'Cycle through: off → plan → execute → off'],+ ['/research', 'Show research mode status'],+ ['/research on', 'Enable deep research mode (web research + rich markdown article)'],+ ['/research off', 'Exit research mode'],+ ['/research toggle', 'Toggle research mode on/off'],+ ['/research <topic>', 'Enable research mode for a specific topic'],['/ws exit', 'Exit workspace IDE mode back to general chat'],['/ws open <path>', 'Open a workspace directory in IDE mode'],['/ws refresh', 'Refresh file tree + git status panel'],@@ -270,6 +281,7 @@ export function getTelegramHelp(): string {lines.push('/progress — Live status for the current task');lines.push('/permissions — Switch Ask Me / Allow All mode');lines.push('/models — List providers or switch AI model');+ lines.push('/cloud models — List Mercury Cloud models and switch');lines.push('/stream — Toggle text streaming on/off');lines.push('');@@ -299,6 +311,14 @@ export function getTelegramHelp(): string {lines.push('/code agent <task> — Delegate coding to a sub-agent');lines.push('');+ lines.push('**Research Mode**');+ lines.push('/research — Show current research mode status');+ lines.push('/research on — Enable deep web research + rich markdown article');+ lines.push('/research off — Exit research mode');+ lines.push('/research toggle — Toggle research mode');+ lines.push('/research <topic> — Enable research mode for a specific topic');+ lines.push('');+lines.push('**Sub-Agents**');lines.push('/agents — List all sub-agents');lines.push('/agents stop <id|all> — Stop a sub-agent');@@ -357,6 +377,7 @@ export function getDiscordHelp(): string {lines.push('/progress \u2014 Live status for the current task');lines.push('/permissions \u2014 Switch Ask Me / Allow All mode');lines.push('/models \u2014 List providers or switch AI model');+ lines.push('/cloud models \u2014 List Mercury Cloud models and switch');lines.push('');lines.push('**Budget**');diff --git a/src/utils/open-url.test.ts b/src/utils/open-url.test.tsnew file mode 100644index 00000000..144e89de--- /dev/null+++ b/src/utils/open-url.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it, vi } from 'vitest';+import { getUrlOpeners, openUrl } from './open-url.js';++describe('URL opening', () => {+ it('prefers termux-open-url and falls back to xdg-open on Termux', () => {+ expect(getUrlOpeners('https://example.com', { TERMUX_VERSION: '0.119' }, 'linux')).toEqual([+ { command: 'termux-open-url', args: ['https://example.com'] },+ { command: 'xdg-open', args: ['https://example.com'] },+ ]);+ });++ it('falls back safely and never throws when openers fail', async () => {+ const succeedsSecond = vi.fn()+ .mockRejectedValueOnce(new Error('missing'))+ .mockResolvedValueOnce(undefined);+ const openers = getUrlOpeners('https://example.com', { TERMUX_VERSION: '0.119' }, 'linux');+ expect(await openUrl('https://example.com', succeedsSecond, openers)).toBe(true);++ const alwaysFails = vi.fn().mockRejectedValue(new Error('headless'));+ expect(await openUrl('https://example.com', alwaysFails, openers)).toBe(false);+ });+});diff --git a/src/utils/open-url.ts b/src/utils/open-url.tsnew file mode 100644index 00000000..e1906623--- /dev/null+++ b/src/utils/open-url.ts@@ -0,0 +1,43 @@+import { execFile } from 'node:child_process';+import { promisify } from 'node:util';+import { isTermux } from './platform.js';++const execFileAsync = promisify(execFile);++export interface UrlOpener {+ command: string;+ args: string[];+}++export function getUrlOpeners(+ url: string,+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform,+): UrlOpener[] {+ if (isTermux(env, platform)) {+ return [+ { command: 'termux-open-url', args: [url] },+ { command: 'xdg-open', args: [url] },+ ];+ }+ if (platform === 'darwin') return [{ command: 'open', args: [url] }];+ if (platform === 'win32') return [{ command: 'cmd.exe', args: ['/d', '/s', '/c', 'start', '', url] }];+ return [{ command: 'xdg-open', args: [url] }];+}++export async function openUrl(+ url: string,+ run: (command: string, args: string[]) => Promise<unknown> = (command, args) =>+ execFileAsync(command, args, { windowsHide: true, timeout: 10_000 }),+ openers: UrlOpener[] = getUrlOpeners(url),+): Promise<boolean> {+ for (const opener of openers) {+ try {+ await run(opener.command, opener.args);+ return true;+ } catch {+ // Try the next platform-safe opener, or let the caller show the URL.+ }+ }+ return false;+}diff --git a/src/utils/platform.test.ts b/src/utils/platform.test.tsnew file mode 100644index 00000000..bbf595fb--- /dev/null+++ b/src/utils/platform.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';+import { isTermux, resolveShell } from './platform.js';++describe('isTermux', () => {+ it('detects Termux environment markers on Linux', () => {+ expect(isTermux({ TERMUX_VERSION: '0.119' }, 'linux')).toBe(true);+ expect(isTermux({ PREFIX: '/data/data/com.termux/files/usr' }, 'linux')).toBe(true);+ });++ it('does not classify desktop Linux or non-Linux platforms as Termux', () => {+ expect(isTermux({}, 'linux')).toBe(false);+ expect(isTermux({ TERMUX_VERSION: '0.119' }, 'darwin')).toBe(false);+ });+});++describe('resolveShell', () => {+ const existing = new Set([+ '/custom/sh',+ '/shell/sh',+ '/data/data/com.termux/files/usr/bin/sh',+ '/bin/sh',+ ]);+ const fileExists = (path: string) => existing.has(path);++ it('uses explicit shell configuration in priority order', () => {+ expect(resolveShell({ MERCURY_SHELL: '/custom/sh', SHELL: '/shell/sh' }, fileExists)).toBe('/custom/sh');+ expect(resolveShell({ MERCURY_SHELL: '/missing', SHELL: '/shell/sh' }, fileExists)).toBe('/shell/sh');+ });++ it('uses the Termux prefix shell before /bin/sh', () => {+ expect(resolveShell({ TERMUX_VERSION: '0.119', PREFIX: '/data/data/com.termux/files/usr' }, fileExists, 'linux'))+ .toBe('/data/data/com.termux/files/usr/bin/sh');+ });+});diff --git a/src/utils/platform.ts b/src/utils/platform.tsnew file mode 100644index 00000000..f435ef10--- /dev/null+++ b/src/utils/platform.ts@@ -0,0 +1,28 @@+import { existsSync } from 'node:fs';+import { posix as posixPath } from 'node:path';++export function isTermux(+ env: NodeJS.ProcessEnv = process.env,+ platform: NodeJS.Platform = process.platform,+): boolean {+ if (platform !== 'linux') return false;+ return Boolean(+ env.TERMUX_VERSION ||+ env.TERMUX_APP_PID ||+ env.PREFIX?.includes('com.termux'),+ );+}++export function resolveShell(+ env: NodeJS.ProcessEnv = process.env,+ fileExists: (path: string) => boolean = existsSync,+ platform: NodeJS.Platform = process.platform,+): string {+ const candidates = [env.MERCURY_SHELL, env.SHELL];+ if (isTermux(env, platform)) {+ candidates.push(env.PREFIX ? posixPath.join(env.PREFIX, 'bin', 'sh') : undefined);+ }+ candidates.push('/bin/sh');++ return candidates.find((candidate) => candidate && fileExists(candidate)) || '/bin/sh';+}diff --git a/src/utils/provider-models.test.ts b/src/utils/provider-models.test.tsindex 74a464b5..adf8def4 100644--- a/src/utils/provider-models.test.ts+++ b/src/utils/provider-models.test.ts@@ -29,17 +29,10 @@ describe('buildModelCatalog', () => {it('limits the list of displayed models', () => {const catalog = buildModelCatalog('anthropic', ['claude-sonnet-4-20250514',- 'claude-opus-4-20250514',- 'claude-3-7-sonnet-latest',- 'claude-3-5-sonnet-latest',- 'claude-3-5-haiku-latest',- 'claude-test-a',- 'claude-test-b',- 'claude-test-c',- 'claude-test-d',+ ...Array.from({ length: 55 }, (_, index) => `claude-test-${String(index).padStart(2, '0')}`),]);- expect(catalog.models).toHaveLength(7);+ expect(catalog.models).toHaveLength(50);expect(catalog.models).not.toContain('claude-sonnet-4-20250514');});diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.tsindex 3a50d38f..4c0c2453 100644--- a/src/utils/provider-models.ts+++ b/src/utils/provider-models.ts@@ -1,13 +1,14 @@import type { ProviderConfig, ProviderName } from './config.js';import { fetchChatGPTModels } from '../auth/chatgpt-models.js';import { fetchGitHubModels } from '../auth/github-models.js';+import { MERCURY_CLOUD_API_URL } from '../cloud/endpoints.js';export interface ProviderModelCatalog {models: string[];recommendedModel: string;}-const MAX_MODEL_OPTIONS = 7;+const MAX_MODEL_OPTIONS = 50;const OPENAI_PREFERRED_MODELS = ['gpt-5.2',@@ -92,6 +93,15 @@ const GITHUB_COPILOT_PREFERRED_MODELS = ['gemini-3.1-pro-preview',] as const;+const MERCURY_CLOUD_PREFERRED_MODELS = [+ 'mercury-mini',+ 'mercury-flash',+ 'mercury-pro',+ 'mercury-reason',+ 'mercury-opus',+ 'mercury-gpt5',+] as const;+export class ProviderModelFetchError extends Error {constructor(message: string) {super(message);@@ -99,6 +109,25 @@ export class ProviderModelFetchError extends Error {}}+export function getPreferredModelsForProvider(provider: ProviderName): string[] {+ const preferredByProvider: Record<ProviderName, readonly string[]> = {+ mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,+ deepseek: DEEPSEEK_PREFERRED_MODELS,+ openai: OPENAI_PREFERRED_MODELS,+ anthropic: ANTHROPIC_PREFERRED_MODELS,+ grok: GROK_PREFERRED_MODELS,+ ollamaCloud: OLLAMA_CLOUD_PREFERRED_MODELS,+ ollamaLocal: OLLAMA_LOCAL_PREFERRED_MODELS,+ openaiCompat: OPENAI_COMPAT_PREFERRED_MODELS,+ mimo: MIMO_PREFERRED_MODELS,+ mimoTokenPlan: MIMO_TOKEN_PLAN_PREFERRED_MODELS,+ chatgptWeb: CHATGPT_WEB_PREFERRED_MODELS,+ githubCopilot: GITHUB_COPILOT_PREFERRED_MODELS,+ };++ return [...preferredByProvider[provider]];+}+interface OpenAIModelResponse {data?: Array<{ id?: string }>;}@@ -189,6 +218,7 @@ function chooseRecommendedModel(currentModel?: string,): string {const preferredByProvider: Record<ProviderName, readonly string[]> = {+ mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,deepseek: DEEPSEEK_PREFERRED_MODELS,openai: OPENAI_PREFERRED_MODELS,anthropic: ANTHROPIC_PREFERRED_MODELS,@@ -227,6 +257,7 @@ export function buildModelCatalog(const recommendedModel = chooseRecommendedModel(provider, filtered, currentModel);const preferredByProvider: Record<ProviderName, readonly string[]> = {+ mercuryCloud: MERCURY_CLOUD_PREFERRED_MODELS,deepseek: DEEPSEEK_PREFERRED_MODELS,openai: OPENAI_PREFERRED_MODELS,anthropic: ANTHROPIC_PREFERRED_MODELS,@@ -399,10 +430,56 @@ async function fetchMiMoTokenPlanModels(config: ProviderConfig): Promise<Providereturn buildModelCatalog('mimoTokenPlan', ids, config.model);}+async function fetchMercuryCloudModels(config: ProviderConfig): Promise<ProviderModelCatalog> {+ const baseUrl = trimTrailingSlash(config.baseUrl || MERCURY_CLOUD_API_URL);+ const jwt = config.apiKey;++ if (!jwt) {+ return buildModelCatalog(+ 'mercuryCloud',+ [...MERCURY_CLOUD_PREFERRED_MODELS],+ config.model || 'mercury-mini',+ );+ }++ interface MercuryCloudModel {+ id: string;+ label: string;+ available?: boolean;+ }++ const data = await fetchJson<{ object: string; data: MercuryCloudModel[] }>(+ `${baseUrl}/v1/models`,+ {+ headers: {+ Authorization: `Bearer ${jwt}`,+ },+ },+ 'Could not fetch Mercury Cloud models. Check your cloud connection.',+ );++ // The Cloud /v1/models endpoint returns an OpenAI-shaped { object: 'list', data: [...] }+ // payload with a per-model `available` flag computed from the user's subscription tier.+ // Only surface models the user is approved for; fall back to the full list if the flag+ // is missing (older API deployments) so the dropdown is never empty.+ const allModels = Array.isArray(data.data) ? data.data : [];+ const allowed = allModels.filter((m) => m.available === true).map((m) => m.id);+ const ids = allowed.length > 0 ? allowed : allModels.map((m) => m.id);+ const models = uniq(ids);+ return {+ recommendedModel: config.model && models.includes(config.model) ? config.model : models[0] || config.model || 'mercury-mini',+ models: limitModels(models.filter((model) => model !== config.model)),+ };+}+export async function fetchProviderModelCatalog(provider: ProviderName,config: ProviderConfig,): Promise<ProviderModelCatalog> {+ if (provider === 'mercuryCloud') {+ return fetchMercuryCloudModels(config);+ }+if (provider === 'anthropic') {return fetchAnthropicModels(config);}diff --git a/src/utils/tokens.ts b/src/utils/tokens.tsindex 34ac7c75..5bde5a62 100644--- a/src/utils/tokens.ts+++ b/src/utils/tokens.ts@@ -112,6 +112,34 @@ export class TokenBudget {}this.persist();+ this.syncToCloud(logEntry).catch((err) => {+ logger.warn({ err }, 'Failed to sync token usage to Mercury Cloud');+ });+ }++ private async syncToCloud(entry: TokenLogEntry): Promise<void> {+ if (!this.config.cloud.enabled || !this.config.cloud.jwt || !this.config.cloud.agentId || !this.config.cloud.apiUrl) return;+ if (entry.provider === 'mercuryCloud' || entry.provider === 'Mercury Cloud') return;+ if (entry.totalTokens <= 0) return;++ const res = await fetch(`${this.config.cloud.apiUrl}/v1/agents/${this.config.cloud.agentId}/usage/sync`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${this.config.cloud.jwt}`,+ },+ body: JSON.stringify({+ model: `${entry.provider}:${entry.model}`,+ tokensIn: entry.inputTokens,+ tokensOut: entry.outputTokens,+ costCredits: 0,+ timestamp: new Date(entry.timestamp).toISOString(),+ }),+ });++ if (!res.ok) {+ throw new Error(`usage sync failed: ${res.status}`);+ }}getUsageByAgent(agentId: string): { used: number; percentage: number } {@@ -262,4 +290,4 @@ export class TokenBudget {channelType: typeof entry.channelType === 'string' && entry.channelType ? entry.channelType : 'unknown',};}-}\ No newline at end of file+}diff --git a/src/web/api/brain.ts b/src/web/api/brain.tsindex deb51180..5e8ea834 100644--- a/src/web/api/brain.ts+++ b/src/web/api/brain.ts@@ -1,5 +1,5 @@import { Hono } from 'hono';-import { loadConfig, getMemoryDir } from '../../utils/config.js';+import { loadConfig, getMemoryDir, saveConfig } from '../../utils/config.js';import { isBetterSqlite3Available } from '../../memory/second-brain-db.js';import { UserMemoryStore } from '../../memory/user-memory.js';import { join } from 'node:path';@@ -73,11 +73,37 @@ const brain = new Hono();brain.get('/api/brain/status', async (c) => {const mem = ensureMemory();if (mem) {- return c.json({ ...mem.getSummary(), available: true });+ return c.json({ ...mem.getSummary(), available: true, shareLearning: mem.isShareLearning(), shareableCount: mem.countShareable() });}return c.json({ total: 0, byType: {}, learningPaused: false, available: false, error: SQLITE_DEPENDENCY_ERROR }, 503);});+// Toggle shared learning — when on, new memories extracted via remember() are+// marked shareable so the cloud fetch can pull them into the collaborative pool.+brain.post('/api/brain/shared-learning', async (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);+ const body = await c.req.json().catch(() => ({}));+ const enabled = Boolean(body.enabled);+ mem.setShareLearning(enabled);++ // Persist to config so it survives restarts.+ try {+ const config = loadConfig();+ if (!config.memory.collaborativeKnowledge) config.memory.collaborativeKnowledge = {};+ config.memory.collaborativeKnowledge.shareLearning = enabled;+ saveConfig(config);+ } catch { /* best-effort — in-memory toggle still works */ }++ return c.json({ shareLearning: enabled, shareableCount: mem.countShareable() });+});++brain.get('/api/brain/shared-learning', async (c) => {+ const mem = ensureMemory();+ if (!mem) return c.json({ error: SQLITE_DEPENDENCY_ERROR, available: false }, 503);+ return c.json({ shareLearning: mem.isShareLearning(), shareableCount: mem.countShareable() });+});+brain.get('/api/brain/memory', async (c) => {const mem = ensureMemory();if (mem) {diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex a467151b..4fc05a28 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -4,12 +4,42 @@ import type { ProgrammingMode, ProgrammingModeState } from '../../core/programmiimport { existsSync, readFileSync, writeFileSync, readdirSync, statSync } from 'node:fs';import { join, extname, basename, relative, resolve } from 'node:path';import { getMercuryHome, loadConfig, getActiveProviders } from '../../utils/config.js';-import { listThreads, loadThread, deleteThread as removeThread, appendMessage } from './chat-history.js';+import type { SessionRepository } from '../../sessions/index.js';let webChannel: WebChannel | null = null;let programmingMode: ProgrammingMode | null = null;let modelSwitchFn: ((provider: string) => Promise<{ ok: boolean; message: string }>) | null = null;let currentProviderFn: (() => { name: string; model: string }) | null = null;+let sessions: SessionRepository | null = null;+let sessionSyncEnabledFn: (() => boolean) | null = null;++export function setSessionRepository(repository: SessionRepository): void {+ sessions = repository;+}++export function setSessionSyncEnabledCallback(fn: () => boolean): void {+ sessionSyncEnabledFn = fn;+}++function toThread(session: ReturnType<SessionRepository['get']>, includeMessages = true) {+ return {+ id: session.id,+ shortId: session.shortId,+ alias: session.alias,+ title: session.title,+ createdAt: new Date(session.createdAt).toISOString(),+ updatedAt: new Date(session.updatedAt).toISOString(),+ messages: includeMessages ? session.messages.map((message) => ({+ id: message.id,+ threadId: session.id,+ role: message.role,+ content: message.content,+ timestamp: new Date(message.timestamp).toISOString(),+ kind: message.kind,+ sequence: message.sequence,+ })) : [],+ };+}export function setProgrammingMode(pm: ProgrammingMode): void {programmingMode = pm;@@ -70,7 +100,7 @@ chat.get('/api/chat/events', (c) => {const stream = new ReadableStream({start(controller) {- const clientId = ch.addSSEClient(controller);+ const clientId = ch.addSSEClient(controller, c.req.query('sessionId'));const encoder = new TextEncoder();const send = (data: string) => {@@ -112,15 +142,27 @@ chat.post('/api/chat/send', async (c) => {return c.json({ error: 'Web channel not initialized' }, 503);}- const body = await c.req.json<{ content: string; threadId?: string }>();+ const body = await c.req.json<{ content: string; sessionId?: string; threadId?: string }>();if (!body.content?.trim()) {return c.json({ error: 'Message content required' }, 400);}try {- const threadId = (body.threadId && body.threadId.trim()) ? body.threadId.trim() : 'web:default';- webChannel.emitMessageInThread(body.content.trim(), threadId);- return c.json({ sent: true });+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ const requestedId = body.sessionId?.trim() || body.threadId?.trim();+ let session = requestedId ? sessions.getByBinding('web', requestedId) : null;+ if (requestedId && !session) {+ try {+ session = sessions.get(requestedId);+ } catch {+ session = /^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(requestedId)+ ? sessions.getOrCreateBound('web', requestedId, requestedId)+ : sessions.getOrCreateBound('web', requestedId);+ }+ }+ session ??= sessions.getOrCreateBound('web', 'web:default');+ webChannel.emitMessageInThread(body.content.trim(), session.id, session.id);+ return c.json({ sent: true, sessionId: session.id });} catch (err: any) {return c.json({ error: err.message }, 500);}@@ -374,37 +416,55 @@ chat.put('/api/workspace/root', async (c) => {// ─── Chat History ─────────────────────────────────────────────chat.get('/api/chat/threads', (c) => {- return c.json({ threads: listThreads() });+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ return c.json({ threads: sessions.list().map((session) => toThread(session, false)) });+});++chat.post('/api/chat/threads', async (c) => {+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ const body: { title?: string } = await c.req.json<{ title?: string }>().catch(() => ({}));+ return c.json(toThread(sessions.create({ title: body.title }), true), 201);});chat.get('/api/chat/threads/:id', (c) => {const id = c.req.param('id');- const thread = loadThread(id);- if (!thread) return c.json({ error: 'Thread not found' }, 404);- return c.json(thread);+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ try {+ return c.json(toThread(sessions.get(id), true));+ } catch {+ return c.json({ error: 'Thread not found' }, 404);+ }});chat.delete('/api/chat/threads/:id', (c) => {const id = c.req.param('id');- const deleted = removeThread(id);- return c.json({ deleted });+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ try {+ sessions.archive(id);+ return c.json({ deleted: true });+ } catch {+ return c.json({ deleted: false }, 404);+ }});-chat.post('/api/chat/threads/:id/messages', async (c) => {+chat.post('/api/chat/threads/:id/delete', async (c) => {const id = c.req.param('id');- const body = await c.req.json<{ role: 'user' | 'assistant'; content: string }>();- if (!body.content || !body.role) {- return c.json({ error: 'role and content required' }, 400);+ if (!sessions) return c.json({ error: 'Session repository not initialized' }, 503);+ const body: { confirmSessionId?: string } = await c.req.json<{ confirmSessionId?: string }>().catch(() => ({}));+ if (body.confirmSessionId !== id) return c.json({ error: 'Explicit session deletion confirmation is required' }, 400);+ try {+ const target = sessions.get(id);+ if (target.id !== id) return c.json({ error: 'Confirmation must use the exact session ID' }, 400);+ const syncPending = sessionSyncEnabledFn?.() === true;+ const deleted = syncPending ? sessions.markDeleted(target.id) : sessions.deletePermanently(target.id);+ return c.json({ deleted: true, sessionId: deleted.id, syncPending });+ } catch {+ return c.json({ deleted: false, error: 'Thread not found' }, 404);}- const msg = {- id: crypto.randomUUID(),- threadId: id,- role: body.role,- content: body.content,- timestamp: Date.now(),- };- appendMessage(id, msg);- return c.json({ saved: true, message: msg });+});++chat.post('/api/chat/threads/:id/messages', async (c) => {+ return c.json({ error: 'Messages are written by /api/chat/send and the agent runtime' }, 410);});export default chat;diff --git a/src/web/api/providers.ts b/src/web/api/providers.tsindex 8a9d3006..e2ab277d 100644--- a/src/web/api/providers.ts+++ b/src/web/api/providers.ts@@ -26,7 +26,7 @@ providers.post('/api/providers/:name', async (c) => {const body = await c.req.json();const config = loadConfig();- const validNames: ProviderName[] = ['openai', 'anthropic', 'deepseek', 'grok', 'ollamaCloud', 'ollamaLocal'];+ const validNames: ProviderName[] = ['mercuryCloud', 'openai', 'anthropic', 'deepseek', 'grok', 'ollamaCloud', 'ollamaLocal', 'openaiCompat', 'mimo', 'mimoTokenPlan'];if (!validNames.includes(providerName)) {return c.json({ error: 'Unknown provider' }, 400);}diff --git a/src/web/api/workspace-ide.ts b/src/web/api/workspace-ide.tsindex 6d999d09..78492428 100644--- a/src/web/api/workspace-ide.ts+++ b/src/web/api/workspace-ide.ts@@ -5,6 +5,7 @@ import { join, resolve, relative, extname, basename } from 'node:path';import { getMercuryHome, loadConfig } from '../../utils/config.js';import { generateText } from 'ai';import type { ProviderRegistry } from '../../providers/registry.js';+import { resolveShell } from '../../utils/platform.js';let providerRegistry: ProviderRegistry | undefined;@@ -280,7 +281,7 @@ ide.post('/api/terminal/exec', async (c) => {encoding: 'utf8',timeout: 30000,maxBuffer: 2 * 1024 * 1024,- shell: '/bin/zsh',+ shell: resolveShell(),env: { ...process.env, TERM: 'xterm-256color' },});diff --git a/src/web/server.ts b/src/web/server.tsindex 53bee61e..cf0a39e7 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -12,7 +12,7 @@ import providerRoutes from './api/providers.js';import configRoutes from './api/config.js';import systemRoutes, { setScheduler } from './api/system.js';import brainRoutes, { setUserMemory } from './api/brain.js';-import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback } from './api/chat.js';+import chatRoutes, { setWebChannel, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setSessionRepository, setSessionSyncEnabledCallback } from './api/chat.js';import agentRoutes, { setAgentSupervisor, setBackgroundTaskManager } from './api/agents.js';import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';@@ -20,6 +20,9 @@ import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';import { BoardManager } from '../core/board-manager.js';import { isBetterSqlite3Available } from '../memory/second-brain-db.js';+export { setSessionRepository };+export { setSessionSyncEnabledCallback };+const app = new Hono();const __dirname = dirname(fileURLToPath(import.meta.url));diff --git a/ui/src/hooks/useSSE.ts b/ui/src/hooks/useSSE.tsindex 407850b0..fc8f7b34 100644--- a/ui/src/hooks/useSSE.ts+++ b/ui/src/hooks/useSSE.ts@@ -1,6 +1,5 @@import { useEffect, useRef, useCallback, useState } from "react";import { useChatStore } from "@/stores/chat";-import api from "@/lib/api";interface SSEResult {connected: boolean;@@ -14,13 +13,15 @@ export function useSSE(): SSEResult {const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const store = useChatStore;+ const activeSessionId = useChatStore((state) => state.activeThreadId);const connect = useCallback(() => {if (esRef.current) {esRef.current.close();}- const es = new EventSource("/api/chat/events");+ const query = activeSessionId ? `?sessionId=${encodeURIComponent(activeSessionId)}` : "";+ const es = new EventSource(`/api/chat/events${query}`);esRef.current = es;es.onopen = () => {@@ -104,13 +105,7 @@ export function useSSE(): SSEResult {timestamp: new Date().toISOString(),});- // Persist assistant message to thread- const threadId = store.getState().activeThreadId;- if (threadId) {- api.chat.threads.addMessage(threadId, "assistant", fullText)- .then(() => store.getState().bumpThreadVersion())- .catch(() => {});- }+ store.getState().bumpThreadVersion();} catch {// Always reset busy state even if parsing failsstore.getState().clearStreaming();@@ -155,7 +150,7 @@ export function useSSE(): SSEResult {timestamp: new Date().toISOString(),});});- }, [store]);+ }, [store, activeSessionId]);useEffect(() => {connect();diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.tsindex 0f54746f..12301212 100644--- a/ui/src/lib/api.ts+++ b/ui/src/lib/api.ts@@ -105,7 +105,7 @@ export const providers = {// ── Chat ──export const chat = {send: (content: string, threadId?: string) =>- post<{ sent: boolean }>("/api/chat/send", { content, threadId }),+ post<{ sent: boolean; sessionId: string }>("/api/chat/send", { content, sessionId: threadId }),settings: {get: () => get<ChatSettings>("/api/chat/settings"),update: (data: Partial<ChatSettings>) =>@@ -122,8 +122,9 @@ export const chat = {},threads: {list: () => get<{ threads: ChatThread[] }>("/api/chat/threads"),+ create: (title?: string) => post<ChatThread>("/api/chat/threads", { title }),get: (id: string) => get<ChatThread>(`/api/chat/threads/${id}`),- delete: (id: string) => del<{ deleted: boolean }>(`/api/chat/threads/${id}`),+ delete: (id: string) => post<{ deleted: boolean; syncPending: boolean }>(`/api/chat/threads/${id}/delete`, { confirmSessionId: id }),addMessage: (id: string, role: string, content: string) =>post<{ saved: boolean }>(`/api/chat/threads/${id}/messages`, {role,diff --git a/ui/src/pages/Chat.tsx b/ui/src/pages/Chat.tsxindex dd6f8785..91ae6710 100644--- a/ui/src/pages/Chat.tsx+++ b/ui/src/pages/Chat.tsx@@ -476,7 +476,8 @@ export function ChatPage() {// Ensure we have a thread ID — create one if neededlet threadId = activeThreadId;if (!threadId) {- threadId = `web:${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ const thread = await api.chat.threads.create();+ threadId = thread.id;setActiveThread(threadId);}@@ -491,13 +492,9 @@ export function ChatPage() {// Immediately show waiting statesetWaiting(true);- // Persist user message to backend thread- api.chat.threads.addMessage(threadId, "user", content)- .then(() => bumpThreadVersion())- .catch(() => {});-try {await api.chat.send(content, threadId);+ bumpThreadVersion();// Reload threads in background to pick up new threadreloadThreads();} catch {diff --git a/ui/src/pages/Workspace.tsx b/ui/src/pages/Workspace.tsxindex 46528007..618aeecf 100644--- a/ui/src/pages/Workspace.tsx+++ b/ui/src/pages/Workspace.tsx@@ -989,7 +989,8 @@ function BottomPanel({let threadId = activeThreadId;if (!threadId) {- threadId = `web:${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;+ const thread = await api.chat.threads.create();+ threadId = thread.id;setActiveThread(threadId);}@@ -1001,12 +1002,9 @@ function BottomPanel({});setWaiting(true);- api.chat.threads.addMessage(threadId, "user", content)- .then(() => bumpThreadVersion())- .catch(() => {});-try {await api.chat.send(content, threadId);+ bumpThreadVersion();} catch {setWaiting(false);clearStreaming();diff --git a/ui/vite.config.ts b/ui/vite.config.tsindex 0081f70c..d172575e 100644--- a/ui/vite.config.ts+++ b/ui/vite.config.ts@@ -70,7 +70,7 @@ export default defineConfig({},build: {outDir: "dist",- sourcemap: true,+ sourcemap: false,chunkSizeWarningLimit: 650,rollupOptions: {output: {diff --git a/website/docs/getting-started/platforms/termux.mdx b/website/docs/getting-started/platforms/termux.mdxindex 39143d88..64c2eaa7 100644--- a/website/docs/getting-started/platforms/termux.mdx+++ b/website/docs/getting-started/platforms/termux.mdx@@ -12,7 +12,7 @@ Mercury runs on **Android via [Termux](https://termux.dev/)**, giving you a real- Android 7.0+- Termux installed from **[F-Droid](https://f-droid.org/en/packages/com.termux/)** or **[GitHub Releases](https://github.com/termux/termux-app/releases)** (the Play Store build is unmaintained — do not use it)-- ~150 MB free storage+- ~500 MB free storage for Node.js, Mercury, and native module compilation- Network access### Install Node.js + Mercury@@ -21,12 +21,12 @@ Termux is the recommended path on Android because the prebuilt Linux binaries ta```bashpkg update && pkg upgrade -y-pkg install nodejs-lts git -y+pkg install nodejs-lts git python make clang pkg-config -ynpm i -g @cosmicstack/mercury-agentmercury```-That's it. `nodejs-lts` ships Node 20+, which is what Mercury requires.+`nodejs-lts` provides Node 20+ and npm. Python, Make, Clang, and pkg-config are required when npm needs to build native dependencies such as `better-sqlite3` for Android's bionic libc. Do not use Mercury's standalone Linux binary on Termux.### Storage access (optional but recommended)@@ -41,24 +41,37 @@ Now you can point Mercury at projects in `~/storage/shared/Projects/...`.### Keep Mercury running in the background-Termux kills processes when the app is swiped away unless you:+Android may stop Termux processes when the app is swiped away or the device sleeps. For the best available background behavior:-1. Enable **Termux:Boot** (from F-Droid) for auto-start on boot.-2. Acquire a wakelock so Android doesn't suspend the process:+1. Install **Termux:API** and **Termux:Boot** from the same source as Termux (F-Droid or GitHub), then install the API commands:```bash+ pkg install termux-apitermux-wake-lock```-3. Disable battery optimization for Termux in **Settings → Apps → Termux → Battery**.+2. Disable battery optimization for Termux in **Settings → Apps → Termux → Battery**.+3. Start Mercury with its supported daemon command:-For full 24/7 operation, run Mercury in daemon mode:+ ```bash+ mercury start+ ```++Termux does not run systemd, so `mercury service install` is intentionally unsupported. To request startup after reboot, create `~/.termux/boot/start-mercury`:```bash-mercury daemon start+mkdir -p ~/.termux/boot+cat > ~/.termux/boot/start-mercury <<'EOF'+#!/data/data/com.termux/files/usr/bin/sh+termux-wake-lock+mercury start+EOF+chmod +x ~/.termux/boot/start-mercury```-See [Daemon Mode](../../daemon-mode/daemon-mode) for details.+Termux:Boot only runs after the user has opened its app once, and Android/OEM background restrictions can still stop Mercury. A wakelock reduces suspension but increases battery use; release it with `termux-wake-unlock` when Mercury is stopped. This setup cannot guarantee server-like 24/7 availability.++See [Daemon Mode](../../daemon-mode/daemon-mode) for `mercury start`, `mercury status`, and `mercury stop` details.### Telegram bot on the go@@ -66,12 +79,14 @@ A common Termux setup: run Mercury's [Telegram integration](../../integrations/t```bashmercury doctor # enable Telegram, paste bot token-mercury daemon start+mercury start```### Known limitations- **No prebuilt binary** — must use npm. The standalone installer (`install.sh`) won't work on Termux because of glibc/bionic differences.+- **No system service manager** — systemd service install/status/uninstall is unavailable. Use Mercury's daemon commands and optionally Termux:Boot.+- **No guaranteed background uptime** — wakelocks and Termux:Boot cannot override every Android or OEM process-killing policy.- **TUI rendering** — Mercury's interface assumes a wide terminal. Rotate landscape or pair Termux with an external keyboard for the best experience.- **Background limits** — Aggressive OEMs (Xiaomi, Oppo, Huawei) need extra battery-optimization tweaks beyond the standard Android settings.- **Storage permission** — Required for accessing project files outside `$HOME`.