@dobbylab/liftlens-agent 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs ADDED
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env node
2
+ // LiftLens local agent — one-line setup:
3
+ //
4
+ // npx @dobbylab/liftlens-agent start + open the web app, auto-paired
5
+ // npx @dobbylab/liftlens-agent install run in the background, start at login (macOS launchd / Linux systemd --user)
6
+ // npx @dobbylab/liftlens-agent status health + runtime check
7
+ // npx @dobbylab/liftlens-agent pair re-open the pairing link (e.g. new browser)
8
+ // npx @dobbylab/liftlens-agent uninstall remove the background service
9
+ //
10
+ // Everything stays on this machine: the bridge binds to 127.0.0.1, the web app keeps
11
+ // videos + logs in the browser, and coaching runs on the user's own Claude Code.
12
+
13
+ import { execFileSync, spawn } from 'node:child_process'
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { AGENT_URL, BUILD, HOME, PORT, RUN_CMD, VERSION, WEB_URL, detectRuntimes, pairUrl, readToken, rotateToken } from './config.mjs'
19
+ import { coachesDir, syncCoaches, syncState } from './sync.mjs'
20
+ import { listRuntimes, readConfig, runtimeById, writeConfig } from './runtimes.mjs'
21
+ import { parseArgs } from 'node:util'
22
+
23
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
24
+ const PKG_DIR = path.resolve(__dirname, '..')
25
+ const APP_DIR = path.join(HOME, 'app') // stable copy used by the background service
26
+ const LOG = path.join(HOME, 'agent.log')
27
+ const LABEL = 'com.liftlens.agent'
28
+ const PLIST = path.join(os.homedir(), 'Library/LaunchAgents', `${LABEL}.plist`)
29
+ const UNIT = path.join(os.homedir(), '.config/systemd/user/liftlens-agent.service')
30
+
31
+ const c = {
32
+ acid: (s) => `\x1b[38;5;155m${s}\x1b[0m`,
33
+ dim: (s) => `\x1b[2m${s}\x1b[0m`,
34
+ red: (s) => `\x1b[31m${s}\x1b[0m`,
35
+ bold: (s) => `\x1b[1m${s}\x1b[0m`,
36
+ }
37
+ const ok = (s) => console.log(` ${c.acid('✓')} ${s}`)
38
+ const bad = (s) => console.log(` ${c.red('✗')} ${s}`)
39
+ const info = (s) => console.log(` ${c.dim('·')} ${s}`)
40
+
41
+ function openBrowser(url) {
42
+ const cmd = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['rundll32.exe', ['url.dll,FileProtocolHandler', url]] : ['xdg-open', [url]]
43
+ try {
44
+ spawn(cmd[0], cmd[1], { detached: true, stdio: 'ignore' }).unref()
45
+ return true
46
+ } catch {
47
+ return false
48
+ }
49
+ }
50
+
51
+ async function health() {
52
+ try {
53
+ const r = await fetch(`${AGENT_URL}/health`, { signal: AbortSignal.timeout(1500) })
54
+ return r.ok ? await r.json() : null
55
+ } catch {
56
+ return null
57
+ }
58
+ }
59
+
60
+ function banner() {
61
+ console.log(`\n ${c.bold('LiftLens agent')} ${c.dim('v' + VERSION)} ${c.dim('— 本地教练桥接,视频与记录不出本机')}\n`)
62
+ }
63
+
64
+ function checkRuntime() {
65
+ const rt = detectRuntimes()
66
+ if (rt.claude) ok(`Claude Code ${c.dim(rt.claude.version ?? '')}`)
67
+ else {
68
+ bad('没有找到 Claude Code(教练点评需要它)')
69
+ info(`安装:${c.acid('npm i -g @anthropic-ai/claude-code')},然后运行一次 ${c.acid('claude')} 完成登录`)
70
+ }
71
+ return rt
72
+ }
73
+
74
+ // ---------------------------------------------------------------- commands
75
+
76
+ async function start({ open = true } = {}) {
77
+ banner()
78
+ let running = await health()
79
+ // The port is held by another version / a build for another site (e.g. a dev build): ask it to yield and replace it with this one
80
+ if (running && (running.build !== BUILD || running.web !== WEB_URL)) {
81
+ const what = `v${running.version ?? '?'}${running.build ? ` · ${running.build}` : ''}${running.web ? ` · ${running.web}` : ''}`
82
+ if (fs.existsSync(PLIST) || fs.existsSync(UNIT)) {
83
+ bad(`后台服务里是另一个版本(${what})。运行本命令加上 ${c.acid('install')} 即可替换成当前版本`)
84
+ process.exit(1)
85
+ }
86
+ info(`本机已有另一个 LiftLens agent(${what}),替换为当前版本…`)
87
+ try {
88
+ await fetch(`${AGENT_URL}/shutdown`, { method: 'POST', headers: { 'x-liftlens-token': readToken() }, signal: AbortSignal.timeout(1500) })
89
+ } catch {
90
+ /* older versions have no /shutdown */
91
+ }
92
+ for (let i = 0; i < 20 && running; i++) {
93
+ await new Promise((r) => setTimeout(r, 150))
94
+ running = await health()
95
+ }
96
+ if (running) {
97
+ bad(`旧的 agent 没有退出。请在它所在的终端按 Ctrl+C(或结束占用 ${PORT} 端口的 node 进程),再运行本命令`)
98
+ process.exit(1)
99
+ }
100
+ }
101
+ if (running) {
102
+ ok(`已经在后台运行 ${c.dim(AGENT_URL)}`)
103
+ if (open) {
104
+ openBrowser(pairUrl())
105
+ ok('已在浏览器打开 LiftLens(自动配对)')
106
+ }
107
+ return
108
+ }
109
+ checkRuntime()
110
+ const { startServer, loadCoaches } = await import('./server.mjs')
111
+ try {
112
+ await startServer()
113
+ } catch (e) {
114
+ bad(e.code === 'EADDRINUSE' ? `端口 ${PORT} 被占用,可用 LIFTLENS_PORT=xxxx 换一个` : e.message)
115
+ process.exit(1)
116
+ }
117
+ ok(`监听 ${AGENT_URL} ${c.dim('(仅本机)')}`)
118
+ ok(`教练 skills:${loadCoaches().map((x) => x.displayName ?? x.name).join(' / ')}`)
119
+ const url = pairUrl()
120
+ if (open && openBrowser(url)) ok('已在浏览器打开 LiftLens,自动完成配对')
121
+ else info(`在浏览器打开以完成配对:\n ${c.acid(url)}`)
122
+ console.log(`\n ${c.dim('想开机自动运行?在刚才的命令后面加上')} ${c.acid('install')} ${c.dim('再运行一次 · Ctrl+C 退出')}\n`)
123
+ }
124
+
125
+ function copyApp() {
126
+ // npx runs from a temporary cache dir — install a stable copy for the background service
127
+ fs.rmSync(APP_DIR, { recursive: true, force: true })
128
+ fs.mkdirSync(APP_DIR, { recursive: true })
129
+ fs.cpSync(path.join(PKG_DIR, 'package.json'), path.join(APP_DIR, 'package.json'))
130
+ fs.cpSync(path.join(PKG_DIR, 'src'), path.join(APP_DIR, 'src'), { recursive: true })
131
+ fs.cpSync(coachesDir(), path.join(APP_DIR, 'coaches'), { recursive: true, dereference: true })
132
+ const npm = path.join(path.dirname(process.execPath), process.platform === 'win32' ? 'npm.cmd' : 'npm')
133
+ execFileSync(fs.existsSync(npm) ? npm : 'npm', ['install', '--omit=dev', '--no-audit', '--no-fund', '--loglevel=error'], {
134
+ cwd: APP_DIR,
135
+ stdio: 'inherit',
136
+ })
137
+ }
138
+
139
+ function serviceEnv() {
140
+ // launchd/systemd start with a minimal PATH — pin the runtime we found now
141
+ const rt = detectRuntimes()
142
+ const env = {
143
+ PATH: [path.dirname(process.execPath), rt.claude ? path.dirname(rt.claude.path) : null, '/usr/local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin'].filter(Boolean).join(':'),
144
+ LIFTLENS_WEB_URL: WEB_URL,
145
+ LIFTLENS_PORT: String(PORT),
146
+ HOME: os.homedir(),
147
+ }
148
+ if (rt.claude) env.LIFTLENS_CLAUDE = rt.claude.path
149
+ for (const k of ['LIFTLENS_MODEL', 'LIFTLENS_ORIGINS']) if (process.env[k]) env[k] = process.env[k]
150
+ return env
151
+ }
152
+
153
+ async function install({ open = true } = {}) {
154
+ banner()
155
+ checkRuntime()
156
+ if (await health()) info('检测到正在运行的 agent,安装后台服务后它会被替换')
157
+ copyApp()
158
+ ok(`已复制到 ${c.dim(APP_DIR)}`)
159
+ const entry = path.join(APP_DIR, 'src/cli.mjs')
160
+ const env = serviceEnv()
161
+
162
+ if (process.platform === 'darwin') {
163
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;')
164
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
165
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
166
+ <plist version="1.0"><dict>
167
+ <key>Label</key><string>${LABEL}</string>
168
+ <key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(entry)}</string><string>serve</string></array>
169
+ <key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k, v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>
170
+ <key>RunAtLoad</key><true/>
171
+ <key>KeepAlive</key><true/>
172
+ <key>StandardOutPath</key><string>${xml(LOG)}</string>
173
+ <key>StandardErrorPath</key><string>${xml(LOG)}</string>
174
+ </dict></plist>`
175
+ fs.mkdirSync(path.dirname(PLIST), { recursive: true })
176
+ try {
177
+ execFileSync('launchctl', ['bootout', `gui/${process.getuid()}`, PLIST], { stdio: 'ignore' })
178
+ } catch {
179
+ /* not loaded yet */
180
+ }
181
+ fs.writeFileSync(PLIST, plist)
182
+ execFileSync('launchctl', ['bootstrap', `gui/${process.getuid()}`, PLIST])
183
+ ok(`已注册为登录项(launchd:${c.dim(LABEL)})`)
184
+ } else if (process.platform === 'linux') {
185
+ const unit = `[Unit]
186
+ Description=LiftLens local agent
187
+ [Service]
188
+ ExecStart=${process.execPath} ${entry} serve
189
+ Restart=always
190
+ ${Object.entries(env).map(([k, v]) => `Environment=${k}=${v}`).join('\n')}
191
+ StandardOutput=append:${LOG}
192
+ StandardError=append:${LOG}
193
+ [Install]
194
+ WantedBy=default.target
195
+ `
196
+ fs.mkdirSync(path.dirname(UNIT), { recursive: true })
197
+ fs.writeFileSync(UNIT, unit)
198
+ execFileSync('systemctl', ['--user', 'daemon-reload'])
199
+ execFileSync('systemctl', ['--user', 'enable', '--now', 'liftlens-agent.service'])
200
+ ok('已注册为 systemd 用户服务(liftlens-agent.service)')
201
+ } else {
202
+ bad(`暂不支持在 Windows 上自动注册后台服务,请用 ${RUN_CMD} 前台运行`)
203
+ return
204
+ }
205
+
206
+ for (let i = 0; i < 20 && !(await health()); i++) await new Promise((r) => setTimeout(r, 300))
207
+ if (await health()) {
208
+ ok(`后台服务已启动 ${c.dim(AGENT_URL)},日志:${c.dim(LOG)}`)
209
+ if (open) {
210
+ openBrowser(pairUrl())
211
+ ok('已在浏览器打开 LiftLens,自动完成配对。以后开机即可直接使用。')
212
+ } else info(`配对链接:${c.acid(pairUrl())}`)
213
+ } else bad(`服务没有起来,请查看日志:${LOG}`)
214
+ console.log()
215
+ }
216
+
217
+ function uninstall() {
218
+ banner()
219
+ if (process.platform === 'darwin' && fs.existsSync(PLIST)) {
220
+ try {
221
+ execFileSync('launchctl', ['bootout', `gui/${process.getuid()}`, PLIST], { stdio: 'ignore' })
222
+ } catch {
223
+ /* already stopped */
224
+ }
225
+ fs.rmSync(PLIST)
226
+ ok('已移除登录项')
227
+ }
228
+ if (process.platform === 'linux' && fs.existsSync(UNIT)) {
229
+ try {
230
+ execFileSync('systemctl', ['--user', 'disable', '--now', 'liftlens-agent.service'], { stdio: 'ignore' })
231
+ } catch {
232
+ /* ignore */
233
+ }
234
+ fs.rmSync(UNIT)
235
+ ok('已移除 systemd 用户服务')
236
+ }
237
+ fs.rmSync(APP_DIR, { recursive: true, force: true })
238
+ ok(`已删除 ${APP_DIR}(配对码保留在 ${path.join(HOME, 'token')})`)
239
+ console.log()
240
+ }
241
+
242
+ async function status() {
243
+ banner()
244
+ const h = await health()
245
+ if (h) ok(`运行中 ${c.dim(AGENT_URL)} · v${h.version}`)
246
+ else bad('没有在运行。请到 LiftLens 网页「本地 Agent」页复制启动命令')
247
+ const installed = (process.platform === 'darwin' && fs.existsSync(PLIST)) || (process.platform === 'linux' && fs.existsSync(UNIT))
248
+ installed ? ok('已设置开机自启') : info('未设置开机自启(在启动命令后面加上 install 运行即可)')
249
+ checkRuntime()
250
+ info(`网页:${WEB_URL}`)
251
+ const r = await syncCoaches({ force: true })
252
+ const dir = coachesDir()
253
+ if (r.error) info(`教练 skills:${syncState.source === 'synced' ? '已同步版本 ' + syncState.version : '安装包自带'}(检查更新失败:${r.error})`)
254
+ else ok(`教练 skills:版本 ${syncState.version}${r.updated ? '(刚刚更新)' : '(已是最新)'}`)
255
+ info(c.dim(dir))
256
+ console.log()
257
+ }
258
+
259
+ async function pair({ rotate = false } = {}) {
260
+ banner()
261
+ const token = rotate ? rotateToken() : readToken()
262
+ if (rotate) info('已生成新的配对码;旧的浏览器配对立即失效(后台服务需要重启:install 一次即可)')
263
+ const url = pairUrl(token)
264
+ if (openBrowser(url)) ok('已在浏览器打开配对链接')
265
+ info(c.acid(url))
266
+ console.log()
267
+ }
268
+
269
+ async function runtimesCmd() {
270
+ banner()
271
+ const list = await listRuntimes()
272
+ for (const group of ['local', 'cloud']) {
273
+ console.log(` ${c.bold(group === 'local' ? '本地 agent / 模型' : '云端模型 API')}`)
274
+ for (const r of list.filter((x) => x.group === group)) {
275
+ const mark = r.current ? c.acid('●') : r.available ? c.acid('○') : c.dim('·')
276
+ const state = r.available ? `${r.model ?? ''}` : c.dim(r.reason ?? '')
277
+ console.log(` ${mark} ${r.id.padEnd(18)} ${r.label.padEnd(26)} ${state}`)
278
+ }
279
+ console.log()
280
+ }
281
+ info(`切换:${c.acid('<启动命令> use <id> [--model ...] [--key ...]')},例如 use anthropic --key sk-ant-...`)
282
+ console.log()
283
+ }
284
+
285
+ async function useCmd(args) {
286
+ banner()
287
+ const { positionals, values } = parseArgs({
288
+ args,
289
+ allowPositionals: true,
290
+ options: {
291
+ model: { type: 'string' },
292
+ key: { type: 'string' },
293
+ 'base-url': { type: 'string' },
294
+ region: { type: 'string' },
295
+ project: { type: 'string' },
296
+ location: { type: 'string' },
297
+ path: { type: 'string' },
298
+ name: { type: 'string' },
299
+ },
300
+ })
301
+ const id = positionals[0]
302
+ if (!id || !runtimeById(id)) {
303
+ bad(`请指定运行时 id,可选:${(await listRuntimes()).map((r) => r.id).join(' / ')}`)
304
+ return
305
+ }
306
+ const cfg = readConfig()
307
+ const rc = { ...(cfg.runtimes?.[id] ?? {}) }
308
+ const map = { model: 'model', key: 'apiKey', 'base-url': 'baseURL', region: 'region', project: 'project', location: 'location', path: 'path', name: 'name' }
309
+ for (const [flag, field] of Object.entries(map)) if (values[flag] !== undefined) rc[field] = values[flag]
310
+ writeConfig({ ...cfg, runtime: id, runtimes: { ...(cfg.runtimes ?? {}), [id]: rc } })
311
+ const r = (await listRuntimes()).find((x) => x.id === id)
312
+ ok(`默认运行时:${r.label}${values.key ? '(API key 已保存到本机 ~/.liftlens/config.json)' : ''}`)
313
+ r.available ? ok(`可用 · 模型 ${r.model}`) : bad(`暂不可用:${r.reason}`)
314
+ if (await health()) info('正在运行的 agent 下次点评时会自动使用新设置,无需重启')
315
+ console.log()
316
+ }
317
+
318
+ function help() {
319
+ banner()
320
+ console.log(` ${c.acid(`${RUN_CMD}`)} 启动并在浏览器自动配对
321
+ ${c.acid(`${RUN_CMD} install`)} 后台运行 + 开机自启(macOS / Linux)
322
+ ${c.acid(`${RUN_CMD} status`)} 查看运行状态
323
+ ${c.acid(`${RUN_CMD} pair`)} 重新打开配对链接(--rotate 重新生成配对码)
324
+ ${c.acid(`${RUN_CMD} uninstall`)} 移除后台服务
325
+ ${c.acid(`${RUN_CMD} runtimes`)} 列出可用的 agent / 模型(本地 + 云端)
326
+ ${c.acid(`${RUN_CMD} use <id>`)} 切换默认 agent,可带 --model --key --base-url --region --project
327
+
328
+ 环境变量:LIFTLENS_WEB_URL(网页地址,默认 ${WEB_URL}) · LIFTLENS_PORT(默认 4517) · LIFTLENS_MODEL(如 sonnet)
329
+ `)
330
+ }
331
+
332
+ const [cmd = 'start', ...rest] = process.argv.slice(2)
333
+ const flags = new Set(rest)
334
+ switch (cmd) {
335
+ case 'start':
336
+ await start({ open: !flags.has('--no-open') })
337
+ break
338
+ case 'serve': // used by the background service: no banner/browser
339
+ await (await import('./server.mjs')).startServer()
340
+ console.log(`[${new Date().toISOString()}] liftlens-agent v${VERSION} listening on ${AGENT_URL}`)
341
+ break
342
+ case 'install':
343
+ await install({ open: !flags.has('--no-open') })
344
+ break
345
+ case 'uninstall':
346
+ uninstall()
347
+ break
348
+ case 'status':
349
+ await status()
350
+ break
351
+ case 'runtimes':
352
+ await runtimesCmd()
353
+ break
354
+ case 'use':
355
+ await useCmd(rest)
356
+ break
357
+ case 'pair':
358
+ await pair({ rotate: flags.has('--rotate') })
359
+ break
360
+ case '-v':
361
+ case '--version':
362
+ console.log(VERSION)
363
+ break
364
+ default:
365
+ help()
366
+ }
package/src/config.mjs ADDED
@@ -0,0 +1,90 @@
1
+ // Shared configuration for the LiftLens local agent.
2
+ import { execFileSync } from 'node:child_process'
3
+ import { randomBytes } from 'node:crypto'
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { agentBuildId } from './build-id.mjs'
9
+
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
11
+
12
+ const PKG = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'))
13
+ // running from the repo checkout: pick up the git-ignored root .env (see .env.example)
14
+ try {
15
+ const envFile = path.join(__dirname, '../../.env')
16
+ if (fs.existsSync(envFile)) process.loadEnvFile(envFile)
17
+ } catch {
18
+ /* Node < 20.12: rely on the real environment */
19
+ }
20
+ export const VERSION = PKG.version
21
+ /** what users type to run this agent, e.g. `npx @dobbylab/liftlens-agent` */
22
+ export const RUN_CMD = `npx ${PKG.name}`
23
+ export const BUILD = agentBuildId(__dirname)
24
+ export const PORT = Number(process.env.LIFTLENS_PORT ?? 4517)
25
+ export const AGENT_URL = `http://127.0.0.1:${PORT}`
26
+ /** Where the LiftLens web app lives. Used for the one-click pairing link + CORS allow-list. */
27
+ // env > baked-in default (set by scripts/deploy.sh for the hosted tarball) > local dev server
28
+ export const WEB_URL = (process.env.LIFTLENS_WEB_URL ?? PKG.liftlens?.webUrl ?? 'http://localhost:5180').replace(/\/$/, '')
29
+ /** local dev: use the repo's coaches/ as-is, never a synced copy */
30
+ export const IS_DEV_WEB = /^https?:\/\/(localhost|127\.0\.0\.1)(:|\/|$)/.test(WEB_URL)
31
+ export const MODEL = process.env.LIFTLENS_MODEL // optional, e.g. "sonnet"
32
+
33
+ export const HOME = path.join(os.homedir(), '.liftlens')
34
+ fs.mkdirSync(HOME, { recursive: true })
35
+
36
+ /** Coach skills shipped with the package (agent/coaches) or the repo checkout (../coaches). Synced copies win — see sync.mjs. */
37
+ export const BUNDLED_COACHES_DIR = [process.env.LIFTLENS_COACHES, path.join(__dirname, '../coaches'), path.join(__dirname, '../../coaches')]
38
+ .filter(Boolean)
39
+ .map((p) => path.resolve(p))
40
+ .find((p) => fs.existsSync(path.join(p, '_shared'))) ?? path.join(__dirname, '../coaches')
41
+
42
+ /**
43
+ * Production site: written into the package by scripts/deploy.sh at release time (package.json liftlens.webUrl); local dev uses
44
+ * LIFTLENS_SITE (see .env.example in the repo root). No deployment URL is hardcoded.
45
+ */
46
+ export const OFFICIAL_WEB_URL = (process.env.LIFTLENS_SITE ?? PKG.liftlens?.webUrl ?? '').replace(/\/$/, '')
47
+ export const ORIGINS = [
48
+ ...new Set([
49
+ ...(OFFICIAL_WEB_URL ? [OFFICIAL_WEB_URL] : []),
50
+ ...(process.env.LIFTLENS_ORIGINS ?? 'http://localhost:5180,http://127.0.0.1:5180,http://localhost:4173').split(','),
51
+ new URL(WEB_URL).origin,
52
+ ]),
53
+ ]
54
+ .map((s) => s.trim())
55
+ .filter(Boolean)
56
+
57
+ // ---------- pairing token ----------
58
+ const tokenFile = path.join(HOME, 'token')
59
+ export function readToken() {
60
+ if (!fs.existsSync(tokenFile)) rotateToken()
61
+ return fs.readFileSync(tokenFile, 'utf8').trim()
62
+ }
63
+ export function rotateToken() {
64
+ fs.writeFileSync(tokenFile, randomBytes(12).toString('base64url'), { mode: 0o600 })
65
+ return fs.readFileSync(tokenFile, 'utf8').trim()
66
+ }
67
+ /** One-click pairing: the web app reads the token from the URL fragment (never sent to a server). */
68
+ export function pairUrl(token = readToken()) {
69
+ return `${WEB_URL}/agent#pair=${encodeURIComponent(token)}&agent=${encodeURIComponent(AGENT_URL)}`
70
+ }
71
+
72
+ // ---------- runtime discovery ----------
73
+ export function which(bin) {
74
+ try {
75
+ return execFileSync(process.platform === 'win32' ? 'where' : '/usr/bin/which', [bin], { encoding: 'utf8' }).trim().split('\n')[0] || null
76
+ } catch {
77
+ return null
78
+ }
79
+ }
80
+ export function versionOf(bin) {
81
+ try {
82
+ return execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 8000 }).trim().split('\n')[0]
83
+ } catch {
84
+ return null
85
+ }
86
+ }
87
+ export function detectRuntimes() {
88
+ const claude = process.env.LIFTLENS_CLAUDE ?? which('claude')
89
+ return { claude: claude ? { path: claude, version: versionOf(claude) } : null }
90
+ }