@ai-vibeway/cli 0.0.200 → 0.0.201
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/ccswitch.js +1 -1
- package/package.json +1 -1
package/dist/lib/ccswitch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as t,mkdirSync as e,readFileSync as r,readdirSync as n,rmSync as
|
|
1
|
+
import{existsSync as t,mkdirSync as e,readFileSync as r,readdirSync as n,rmSync as i}from"fs";import{join as o}from"path";import{spawn as s,spawnSync as c}from"child_process";import{BRAND_NAME as p,CLI_NAME as a,PROVIDER_KEY as u,brandEnv as d}from"./brand.js";import{toolHome as l}from"./tools/types.js";import{atomicWriteFile as f,backupBeforeWrite as h}from"./tools/backup.js";import{columnsOf as m,openSqlite as g,rollback as w}from"./sqlite.js";import{KEY_INFO_PATH as _}from"./gateway-protocol.js";import{configManager as E}from"./config.js";import{logger as S}from"../utils/logger.js";import{getAdapter as y}from"./tools/registry.js";import{resolveModelCatalog as b}from"./model-catalog.js";import{gatewayAddresses as v}from"./gateway-addresses.js";export const CCSWITCH_SETTING="ccswitch";export const CCSWITCH_SCHEMAS=[29,30];const A=["id","app_type","name","settings_config","website_url","category","created_at","sort_index","notes","icon","meta","is_current","in_failover_queue"],C=["provider_id","app_type","url","added_at"],D={claude:"currentProviderClaude",codex:"currentProviderCodex","claude-desktop":"currentProviderClaudeDesktop",grokbuild:"currentProviderGrokbuild",agy:"currentProviderAgy"},x=new Set(["workbuddy","codebuddy","dsh"]);export function isAdditiveCcSwitchApp(t){return x.has(t)}export function ccSwitchCardId(){return`${u}-${a}`}function T(){return Boolean(d("TEST_HOME")?.trim())}export function ccSwitchDeviceDir(){return o(l(),".cc-switch")}export function ccSwitchDataDir(){try{const e=JSON.parse(r(function(){const t=l(),e="com.ccswitch.desktop";if("darwin"===process.platform)return o(t,"Library","Application Support",e,"app_paths.json");if("win32"===process.platform){const r=!T()&&process.env.APPDATA?process.env.APPDATA:o(t,"AppData","Roaming");return o(r,e,"app_paths.json")}const r=!T()&&process.env.XDG_DATA_HOME?process.env.XDG_DATA_HOME:o(t,".local","share");return o(r,e,"app_paths.json")}(),"utf-8")).app_config_dir_override;if("string"==typeof e&&e.trim()){const r=e.trim(),n="~"===r?l():r.startsWith("~/")||r.startsWith("~\\")?o(l(),r.slice(2)):r;if(t(n))return n}}catch{}return ccSwitchDeviceDir()}export function ccSwitchDbPath(){return o(ccSwitchDataDir(),"cc-switch.db")}function N(t){try{const e=JSON.parse(r(o(ccSwitchDeviceDir(),"live-state.json"),"utf-8")),n=e.apps?.[t]?.mode;return"string"==typeof n?n:"direct"}catch{return"direct"}}const P=(t,e)=>{const r=c(t,e,{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:`${r.stdout??""}`}};let R=P,M=null;export function setCcSwitchRunningForTests(t){M=t}export function setCcSwitchRunnerForTests(t){R=t??P}export function isCcSwitchRunning(){return null!==M?M:!T()&&("win32"===process.platform?/cc-switch\.exe/i.test(R("tasklist",["/FI","IMAGENAME eq cc-switch.exe","/NH"]).stdout):0===R("pgrep",["-x","cc-switch"]).status)}function O(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}export function quitCcSwitch(){const e=function(){if("darwin"===process.platform)return null;if("win32"===process.platform)return R("powershell.exe",["-NoProfile","-NonInteractive","-Command","(Get-Process -Name cc-switch -ErrorAction SilentlyContinue | Select-Object -First 1).Path"]).stdout.trim()||null;const e=R("pgrep",["-x","cc-switch"]).stdout.trim().split(/\s+/)[0];if(!e)return null;try{const n=r(`/proc/${e}/environ`,"utf-8").split("\0"),i=t=>n.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1),s=i("APPIMAGE");if(s&&t(s))return s;const c=i("APPDIR");if(c&&t(o(c,"AppRun"))&&!c.startsWith("/tmp/.mount_"))return o(c,"AppRun")}catch{}return R("readlink",[`/proc/${e}/exe`]).stdout.trim()||null}();"darwin"===process.platform?R("osascript",["-e",'tell application id "com.ccswitch.desktop" to quit']):"win32"===process.platform?R("taskkill",["/IM","cc-switch.exe","/F"]):R("pkill",["-TERM","-x","cc-switch"]);for(let t=0;t<20&&isCcSwitchRunning();t++)O(500);return isCcSwitchRunning()?null:{reopen(){try{"darwin"===process.platform?c("open",["-b","com.ccswitch.desktop"],{stdio:"ignore",timeout:1e4}):e&&s(e,[],{detached:!0,stdio:"ignore",windowsHide:!1}).unref()}catch(t){S.logError("ccswitch.reopen",t)}}}}export async function inspectCcSwitch(){const e=ccSwitchDbPath();if(!t(e))return{ok:!1,problem:"not_installed",dbPath:e};const r=await g(e);if("string"==typeof r)return{ok:!1,problem:"no_sqlite",dbPath:e,detail:r};try{const t=Number(r.prepare("PRAGMA user_version").all()[0]?.user_version);if(!CCSWITCH_SCHEMAS.includes(t))return{ok:!1,problem:"unsupported_schema",schema:t,dbPath:e};const n=m(r,"providers"),i=m(r,"provider_endpoints"),o=[...A.filter(t=>!n.has(t)),...C.filter(t=>!i.has(t)).map(t=>`provider_endpoints.${t}`)];return o.length>0?{ok:!1,problem:"unexpected_tables",schema:t,dbPath:e,detail:o.join(",")}:isCcSwitchRunning()?{ok:!1,problem:"running",schema:t,dbPath:e}:{ok:!0,schema:t,dbPath:e}}catch(t){return{ok:!1,problem:"unreadable",dbPath:e,detail:t instanceof Error?t.message:String(t)}}finally{r.close()}}function k(){return`({\n request: {\n url: "{{baseUrl}}".replace(/\\/+$/, "").replace(/\\/v1(beta)?$/, "") + "${_}",\n method: "GET",\n headers: { "Authorization": "Bearer {{apiKey}}" }\n },\n extractor: function (response) {\n if (!response || response.success !== true || !response.data) {\n var msg = response && (response.message || (response.error && response.error.message));\n return { isValid: false, invalidMessage: msg || "Query failed" };\n }\n var b = response.data.balance;\n var result = { isValid: true, planName: response.data.group };\n if (b && typeof b.remaining === "number") {\n result.remaining = b.remaining;\n result.unit = b.unit === "TOKENS" ? "tokens" : (b.unit === "CUSTOM" ? b.symbol : b.unit);\n }\n return result;\n }\n})`}function I(e,n){const i=o(ccSwitchDeviceDir(),"settings.json");let s={};try{s=JSON.parse(r(i,"utf-8"))}catch{}const c=D[e];c&&s[c]!==n&&(t(i)&&h(i),f(i,JSON.stringify({...s,[c]:n},null,2)+"\n",384))}function H(t){try{const e="string"==typeof t?JSON.parse(t):null;return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}export async function writeCcSwitchCards(t){const r=await g(ccSwitchDbPath());if("string"==typeof r)throw new Error(r);const s=r,c=Date.now(),a=[],u=[];try{s.exec("PRAGMA busy_timeout = 5000"),function(t){const r=o(E.getConfigDir(),"backups"),s=o(r,`cc-switch-${Date.now()}.db`);try{e(r,{recursive:!0,mode:448}),t.exec(`VACUUM INTO '${s.replace(/'/g,"''")}'`);const c=n(r).filter(t=>/^cc-switch-\d+\.db$/.test(t)).sort().reverse().slice(5);for(const t of c)i(o(r,t),{force:!0})}catch(t){S.logError("ccswitch.snapshotDb",t)}}(s),s.exec("BEGIN IMMEDIATE");for(const e of t){const t=x.has(e.app),r=!t&&"proxy"===N(e.app),n=Boolean(e.current)&&!r,i=e.endpoints[0]?.replace(/\/v1$/,"")??E.getBaseUrl(),o=[],d=[];for(const r of e.cards){const a=r.id??ccSwitchCardId(),u=s.prepare("SELECT meta, settings_config FROM providers WHERE id = ? AND app_type = ?").all(a,e.app);if(u.length>0&&e.owns&&!e.owns(a,H(u[0].settings_config))){d.push(a);continue}const l={...H(u[0]?.meta),usage_script:{enabled:!0,language:"javascript",code:k(),timeout:10},...r.meta};t&&void 0!==e.current&&(l.liveConfigManaged=n);const f=JSON.stringify(r.settingsConfig),h=r.name??p;if(u.length>0)s.prepare("UPDATE providers SET name = ?, settings_config = ?, website_url = ?, meta = ? WHERE id = ? AND app_type = ?").run(h,f,i,JSON.stringify(l),a,e.app);else{const t=s.prepare("SELECT COALESCE(MAX(sort_index), -1) + 1 AS next FROM providers WHERE app_type = ?").all(e.app)[0];s.prepare("INSERT INTO providers (id, app_type, name, settings_config, website_url, category, created_at, sort_index, notes, icon, meta, is_current, in_failover_queue)\n VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, NULL, ?, 0, 0)").run(a,e.app,h,f,i,c,Number(t.next),JSON.stringify(l))}s.prepare("DELETE FROM provider_endpoints WHERE provider_id = ? AND app_type = ?").run(a,e.app);for(const t of e.endpoints.slice(1))s.prepare("INSERT INTO provider_endpoints (provider_id, app_type, url, added_at) VALUES (?, ?, ?, ?)").run(a,e.app,t,c);o.push(a)}if(e.owns){const t=s.prepare("SELECT id, settings_config FROM providers WHERE app_type = ?").all(e.app);for(const r of t)!o.includes(r.id)&&e.owns(r.id,H(r.settings_config))&&(s.prepare("DELETE FROM provider_endpoints WHERE provider_id = ? AND app_type = ?").run(r.id,e.app),s.prepare("DELETE FROM providers WHERE id = ? AND app_type = ?").run(r.id,e.app))}if(n&&!t&&o.length>0){const t=o[0];s.prepare("UPDATE providers SET is_current = 0 WHERE app_type = ? AND id <> ?").run(e.app,t),s.prepare("UPDATE providers SET is_current = 1 WHERE app_type = ? AND id = ?").run(e.app,t),D[e.app]&&u.push({app:e.app,id:t})}a.push({app:e.app,written:o.length,skipped:d,current:n&&o.length>0,proxyMode:r})}s.exec("COMMIT")}catch(t){throw w(s),t}finally{s.close()}for(const{app:t,id:e}of u)I(t,e);return a}export async function ccSwitchContext(t,e,r){const n=y(t),i=n?.wantsModelCatalog?await b(e):null;return{apiKey:e,baseUrl:E.getBaseUrl(),models:r,settings:E.getToolSettings(t),...i?{catalog:i}:{}}}export function buildCcSwitchCards(t,e){const r=y(t)?.ccSwitch;if(!r)return null;const n=e.baseUrl.replace(/\/+$/,"").replace(/\/v1$/,""),i=[n,...v().map(t=>t.url.replace(/\/+$/,"")).filter(t=>t!==n)];return{app:r.app,cards:r.cards(e),endpoints:i.map(t=>t+r.endpointPath),...r.owns?{owns:r.owns.bind(r)}:{}}}export async function hasCcSwitchCards(e){if(!t(ccSwitchDbPath()))return!1;const r=await g(ccSwitchDbPath());if("string"==typeof r)return!1;try{const t=r.prepare("SELECT id, settings_config FROM providers WHERE app_type = ?").all(e.app),n=new Set(e.cards.map(t=>t.id??ccSwitchCardId()));return t.some(t=>n.has(t.id)||Boolean(e.owns?.(t.id,H(t.settings_config))))}catch{return!1}finally{r.close()}}
|