hermes-pilot 0.0.0-stage → 0.2.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +390 -0
  3. package/README.md +398 -2
  4. package/__init__.py +15 -0
  5. package/apps/bridge/src/api-errors.js +165 -0
  6. package/apps/bridge/src/architect.js +1298 -0
  7. package/apps/bridge/src/auth.js +202 -0
  8. package/apps/bridge/src/capabilities.js +256 -0
  9. package/apps/bridge/src/capture.js +145 -0
  10. package/apps/bridge/src/chat-profile.js +95 -0
  11. package/apps/bridge/src/config.js +73 -0
  12. package/apps/bridge/src/discord.js +89 -0
  13. package/apps/bridge/src/gitinfo.js +211 -0
  14. package/apps/bridge/src/hermes.js +97 -0
  15. package/apps/bridge/src/inbox.js +347 -0
  16. package/apps/bridge/src/kanban.js +361 -0
  17. package/apps/bridge/src/lang.js +60 -0
  18. package/apps/bridge/src/live.js +285 -0
  19. package/apps/bridge/src/memos.js +150 -0
  20. package/apps/bridge/src/ops.js +201 -0
  21. package/apps/bridge/src/pair-codes.js +125 -0
  22. package/apps/bridge/src/pipeline-optimizer.js +358 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1018 -0
  24. package/apps/bridge/src/qr.js +808 -0
  25. package/apps/bridge/src/repos.js +544 -0
  26. package/apps/bridge/src/review-watcher.js +271 -0
  27. package/apps/bridge/src/review.js +1749 -0
  28. package/apps/bridge/src/search.js +162 -0
  29. package/apps/bridge/src/server.js +1738 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +734 -0
  32. package/apps/bridge/src/tail.js +28 -0
  33. package/apps/bridge/src/telemetry.js +667 -0
  34. package/apps/bridge/src/term-snippets.js +228 -0
  35. package/apps/bridge/src/transcript.js +231 -0
  36. package/apps/bridge/src/usage.js +294 -0
  37. package/apps/bridge/src/workerFeed.js +72 -0
  38. package/apps/dashboard/index.js +2014 -0
  39. package/apps/dashboard/manifest.json +14 -0
  40. package/apps/dashboard/pilot_dashboard.py +1466 -0
  41. package/apps/dashboard/plugin_api.py +237 -0
  42. package/apps/dashboard/plugin_init.py +15 -0
  43. package/apps/dashboard/style.css +928 -0
  44. package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
  45. package/apps/web/dist/assets/TermPane-U500JD2P.js +12 -0
  46. package/apps/web/dist/assets/index-6iFDsB0G.css +1 -0
  47. package/apps/web/dist/assets/index-X4Bi2FWB.js +94 -0
  48. package/apps/web/dist/favicon.ico +0 -0
  49. package/apps/web/dist/icon-180-v6.png +0 -0
  50. package/apps/web/dist/icon-192-v6.png +0 -0
  51. package/apps/web/dist/icon-512-v6.png +0 -0
  52. package/apps/web/dist/icon-maskable-192-v6.png +0 -0
  53. package/apps/web/dist/icon-maskable-512-v6.png +0 -0
  54. package/apps/web/dist/icon-v6.svg +15 -0
  55. package/apps/web/dist/index.html +21 -0
  56. package/apps/web/dist/manifest.webmanifest +49 -0
  57. package/apps/web/dist/sw.js +69 -0
  58. package/bin/hermes-pilot.mjs +964 -0
  59. package/dashboard/dist/index.js +2014 -0
  60. package/dashboard/dist/style.css +928 -0
  61. package/dashboard/manifest.json +14 -0
  62. package/dashboard/pilot_dashboard.py +1466 -0
  63. package/dashboard/plugin_api.py +237 -0
  64. package/package.json +75 -4
  65. package/plugin.json +70 -0
  66. package/plugin.yaml +4 -0
  67. package/scripts/deploy.mjs +58 -0
  68. package/scripts/migrate-to-hermes-pilot.mjs +472 -0
  69. package/scripts/postinstall.mjs +32 -0
  70. package/scripts/sync-dashboard.mjs +98 -0
  71. package/skills/annotation/SKILL.md +103 -0
  72. package/skills/quick-review/SKILL.md +170 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +175 -0
@@ -0,0 +1,964 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `hermes-pilot` CLI(SPEC §8.1 / D9)。
4
+ *
5
+ * ```text
6
+ * hermes-pilot init 初回セットアップ+ペアリング QR
7
+ * hermes-pilot start [--port 4097] [--host 127.0.0.1] ブリッジを起動
8
+ * hermes-pilot qr [--port 4097] ペアリング URL と QR を表示
9
+ * hermes-pilot service install|uninstall|restart|status 常駐化(launchd / systemd --user)
10
+ * hermes-pilot migrate 旧 akapen / mobile-pwa からの移行
11
+ * ```
12
+ *
13
+ * 設計メモ:
14
+ * - **依存ゼロ**。QR は `apps/bridge/src/qr.js`(自作エンコーダ)、サービス定義は文字列生成。
15
+ * - データ先は `~/.hermes/plugin-data/hermes-pilot/`(`HP_DATA_DIR` / `HM_DATA` で上書き可)。
16
+ * - 旧 `ai.hermes.hermes-mobile` は**止めない**。新ラベル `ai.hermes.pilot` を併設し、
17
+ * README の移行手順で切り替える(HEADS-UP)。
18
+ */
19
+
20
+ import fs from 'node:fs'
21
+ import path from 'node:path'
22
+ import os from 'node:os'
23
+ import crypto from 'node:crypto'
24
+ import readline from 'node:readline'
25
+ import { execFileSync } from 'node:child_process'
26
+ import { spawnSync } from 'node:child_process'
27
+ import { fileURLToPath } from 'node:url'
28
+ import { collectPairing, qrPng, qrSvg, qrTerminal, tailscaleCommandCandidates } from '../apps/bridge/src/qr.js'
29
+ import { createPairCodes } from '../apps/bridge/src/pair-codes.js'
30
+
31
+ /** リポジトリのルート(このファイルは `bin/` の下)。 */
32
+ export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
33
+
34
+ /** macOS の launchd ラベル(旧 `ai.hermes.hermes-mobile` とは別物)。 */
35
+ export const SERVICE_LABEL = 'ai.hermes.pilot'
36
+
37
+ /** Linux の systemd --user ユニット名。 */
38
+ export const SYSTEMD_UNIT = 'hermes-pilot.service'
39
+
40
+ /** 既定の待受。 */
41
+ export const DEFAULT_PORT = 4097
42
+ export const DEFAULT_HOST = '127.0.0.1'
43
+
44
+ /** 同梱スキル(`hermes-pilot init` で `~/.hermes/skills/` へ配置する)。 */
45
+ export const BUNDLED_SKILLS = ['quick-review', 'annotation', 'spec-architect']
46
+
47
+ /** 標準ダッシュボード(:9119)に出すタブのプラグイン名。 */
48
+ export const DASHBOARD_PLUGIN = 'hermes-pilot'
49
+
50
+ /**
51
+ * ダッシュボード・プラグインの配置表(リポジトリ内 → `~/.hermes/plugins/hermes-pilot/`)。
52
+ *
53
+ * 標準ダッシュボードは `<plugins>/<name>/dashboard/manifest.json` を走査し、
54
+ * `manifest.json` の `entry` / `css` を `dashboard/` からの相対パスとして配信する
55
+ * (`hermes_cli/web_server_dashboard.py`)。リポジトリでは編集しやすいよう
56
+ * `apps/dashboard/` 直下に置き、`init` が `dashboard/` と `dist/` の形へ写す。
57
+ */
58
+ export const DASHBOARD_FILES = [
59
+ { from: 'plugin.yaml', to: 'plugin.yaml' },
60
+ // ユーザープラグインの dashboard バックエンドは「本物の・有効なプラグイン」でないと
61
+ // マウントされない(`hermes_cli/web_server_dashboard.py` → `_plugin_api_mount_skip_reason`)。
62
+ // `hermes plugins enable hermes-pilot` が名前を解決できるよう、no-op の `register` を置く。
63
+ { from: 'apps/dashboard/plugin_init.py', to: '__init__.py' },
64
+ { from: 'apps/dashboard/manifest.json', to: 'dashboard/manifest.json' },
65
+ { from: 'apps/dashboard/plugin_api.py', to: 'dashboard/plugin_api.py' },
66
+ { from: 'apps/dashboard/pilot_dashboard.py', to: 'dashboard/pilot_dashboard.py' },
67
+ { from: 'apps/dashboard/index.js', to: 'dashboard/dist/index.js' },
68
+ { from: 'apps/dashboard/style.css', to: 'dashboard/dist/style.css' },
69
+ ]
70
+
71
+ /**
72
+ * `HERMES_HOME` の補正(`scripts/migrate-to-hermes-pilot.mjs` の同名関数と同じ規則)。
73
+ *
74
+ * worker / cron からは `HERMES_HOME` がプロファイルディレクトリ
75
+ * (`~/.hermes/profiles/<name>`)を指すことがある。その時は 2 つ上を Hermes ホームとして扱う。
76
+ * ここで重複定義しているのは、`node:sqlite` を使う migrate モジュールを
77
+ * `--help` / `qr` / `service status` のたびに読み込まない(ExperimentalWarning を出さない)ため。
78
+ * @param {string} raw 生のパス
79
+ * @param {string} home ホーム
80
+ * @returns {string} 正規化した Hermes ホーム
81
+ */
82
+ export function resolveHermesHome(raw, home = os.homedir()) {
83
+ const abs = path.resolve(String(raw).replace(/^~/, home))
84
+ if (path.basename(path.dirname(abs)) === 'profiles') return path.dirname(path.dirname(abs))
85
+ return abs
86
+ }
87
+
88
+ /**
89
+ * データ先の解決(`apps/bridge/src/config.js` と同じ規則 + プロファイル補正)。
90
+ * @param {object} [env] 環境変数
91
+ * @returns {{home: string, hermesHome: string, pluginDataDir: string, dataDir: string, tokenPath: string, reviewDir: string, configPath: string, skillsDir: string, logDir: string}} パス
92
+ */
93
+ export function resolvePaths(env = process.env) {
94
+ const home = env.HOME ?? os.homedir()
95
+ const hermesHome = resolveHermesHome(env.HERMES_HOME ?? path.join(home, '.hermes'), home)
96
+ const pluginDataDir = env.HP_DATA_DIR ?? path.join(hermesHome, 'plugin-data', 'hermes-pilot')
97
+ const dataDir = env.HM_DATA ?? pluginDataDir
98
+ return {
99
+ home,
100
+ hermesHome,
101
+ pluginDataDir,
102
+ dataDir,
103
+ tokenPath: path.join(dataDir, 'token'),
104
+ configPath: path.join(dataDir, 'config.json'),
105
+ reviewDir: path.join(pluginDataDir, 'review'),
106
+ skillsDir: path.join(hermesHome, 'skills'),
107
+ logDir: path.join(hermesHome, 'logs'),
108
+ }
109
+ }
110
+
111
+ /**
112
+ * 引数を `{ command, flags, rest }` に分解する(`--key value` と `--key=value` の両方)。
113
+ * @param {string[]} argv `process.argv.slice(2)`
114
+ * @returns {{command: string, sub: string|null, flags: Record<string, string|boolean>, rest: string[]}} 解析結果
115
+ */
116
+ export function parseArgv(argv = []) {
117
+ const args = argv.filter((a) => typeof a === 'string')
118
+ const flags = {}
119
+ const rest = []
120
+ let command = ''
121
+ let sub = null
122
+ for (let i = 0; i < args.length; i++) {
123
+ const a = args[i]
124
+ if (a.startsWith('--')) {
125
+ const body = a.slice(2)
126
+ const eq = body.indexOf('=')
127
+ if (eq >= 0) {
128
+ flags[body.slice(0, eq)] = body.slice(eq + 1)
129
+ } else {
130
+ const next = args[i + 1]
131
+ if (next !== undefined && !next.startsWith('-') && ['port', 'host', 'tls-port', 'home', 'target-dir'].includes(body)) {
132
+ flags[body] = next
133
+ i++
134
+ } else {
135
+ flags[body] = true
136
+ }
137
+ }
138
+ continue
139
+ }
140
+ if (!command) {
141
+ command = a
142
+ continue
143
+ }
144
+ if (!sub) {
145
+ sub = a
146
+ continue
147
+ }
148
+ rest.push(a)
149
+ }
150
+ return { command, sub, flags, rest }
151
+ }
152
+
153
+ /** ヘルプ。 */
154
+ export function helpText() {
155
+ return [
156
+ 'hermes-pilot — control your Hermes Agent from your phone or tablet',
157
+ '',
158
+ 'Usage:',
159
+ ' hermes-pilot init [--force] [--target-dir <plugin dir>] [--yes]',
160
+ ' First-run setup: data dirs, token, skills, dashboard tab, pairing QR',
161
+ ' --target-dir: where `hermes plugins install` unpacked this repo',
162
+ ' --yes: migrate legacy akapen/mobile-pwa data without asking',
163
+ ' hermes-pilot start [--port 4097] [--host 127.0.0.1] [--tls-port 8444]',
164
+ ' Build the UI if needed and run the bridge',
165
+ ' hermes-pilot qr [--port 4097] [--tls-port 8444] [--png <path>]',
166
+ ' Print the pairing URL and a terminal QR',
167
+ ' hermes-pilot service install|uninstall|restart|status [--dry-run]',
168
+ ' Keep the bridge running (launchd / systemd --user)',
169
+ ' hermes-pilot migrate Copy data from the old akapen / mobile-pwa layout',
170
+ ' hermes-pilot --help Show this help',
171
+ '',
172
+ '環境 / Environment:',
173
+ ' HERMES_HOME Hermes home (default ~/.hermes)',
174
+ ' HP_DATA_DIR Plugin data dir (default ~/.hermes/plugin-data/hermes-pilot)',
175
+ '',
176
+ 'データ先 / Data: ~/.hermes/plugin-data/hermes-pilot/',
177
+ '既存の ai.hermes.hermes-mobile は止めません(新ラベル ai.hermes.pilot を併設)。',
178
+ ].join('\n')
179
+ }
180
+
181
+ /**
182
+ * トークンを用意する(無ければ 256-bit hex を 0600 で作る)。
183
+ * @param {string} tokenPath トークンファイル
184
+ * @param {object} [opts] オプション
185
+ * @param {boolean} [opts.create] 無いときに作るか
186
+ * @returns {{token: string|null, created: boolean}} 結果
187
+ */
188
+ export function ensureToken(tokenPath, { create = true } = {}) {
189
+ try {
190
+ const existing = fs.readFileSync(tokenPath, 'utf8').trim()
191
+ if (existing) return { token: existing, created: false }
192
+ } catch {
193
+ /* 初回 */
194
+ }
195
+ if (!create) return { token: null, created: false }
196
+ const token = crypto.randomBytes(32).toString('hex') // 256-bit
197
+ fs.mkdirSync(path.dirname(tokenPath), { recursive: true, mode: 0o700 })
198
+ fs.writeFileSync(tokenPath, token, { mode: 0o600 })
199
+ try {
200
+ fs.chmodSync(tokenPath, 0o600)
201
+ } catch {
202
+ /* 既に 0600 でない FS でも続ける */
203
+ }
204
+ return { token, created: true }
205
+ }
206
+
207
+ /**
208
+ * `tailscale status --json` を読む(無い環境では null)。CLI では同期で十分。
209
+ * @returns {string|null} 生 JSON
210
+ */
211
+ export function readTailscaleStatus() {
212
+ for (const bin of tailscaleCommandCandidates()) {
213
+ try {
214
+ const text = String(
215
+ execFileSync(bin, ['status', '--json'], {
216
+ timeout: 1500,
217
+ maxBuffer: 4 * 1024 * 1024,
218
+ encoding: 'utf8',
219
+ stdio: ['ignore', 'pipe', 'ignore'],
220
+ }),
221
+ )
222
+ if (text.trim()) return text
223
+ } catch {
224
+ /* 次の候補(PATH に無い macOS アプリ版など)へ */
225
+ }
226
+ }
227
+ return null
228
+ }
229
+
230
+ /**
231
+ * 設定ファイル(`config.json`)を読む。無ければ既定。
232
+ * @param {string} configPath パス
233
+ * @returns {{lang: string, scanDirs: string[], servicePort: number, tlsPort: number|null, tailscaleDns: string|null}} 設定
234
+ */
235
+ export function readConfig(configPath) {
236
+ try {
237
+ const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
238
+ return {
239
+ lang: typeof raw?.lang === 'string' ? raw.lang : 'en',
240
+ scanDirs: Array.isArray(raw?.scanDirs) ? raw.scanDirs : ['~/Projects', '~/projects'],
241
+ servicePort: Number(raw?.servicePort) || DEFAULT_PORT,
242
+ // Tailscale serve が 443 以外に出す構成(`tailscale serve --https=8444` 等)向け
243
+ tlsPort: Number(raw?.tlsPort) || null,
244
+ // 常駐(launchd)からアプリ版 Tailscale を叩けない環境の控え
245
+ tailscaleDns: typeof raw?.tailscaleDns === 'string' && raw.tailscaleDns.trim() ? raw.tailscaleDns.trim() : null,
246
+ }
247
+ } catch {
248
+ return { lang: 'en', scanDirs: ['~/Projects', '~/projects'], servicePort: DEFAULT_PORT, tlsPort: null, tailscaleDns: null }
249
+ }
250
+ }
251
+
252
+ /**
253
+ * launchd の plist を組み立てる(macOS)。
254
+ * @param {object} opts 入力
255
+ * @param {string} opts.label ラベル
256
+ * @param {string} opts.node node の実行パス
257
+ * @param {string} opts.cli CLI の絶対パス
258
+ * @param {number} opts.port 待受ポート
259
+ * @param {string} opts.host 待受ホスト
260
+ * @param {string} opts.hermesHome HERMES_HOME
261
+ * @param {string} opts.logDir ログ出力先
262
+ * @param {string} opts.workdir 作業ディレクトリ
263
+ * @returns {string} plist XML
264
+ */
265
+ export function buildLaunchdPlist({ label, node, cli, port, host, hermesHome, logDir, workdir }) {
266
+ const esc = (s) => String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c])
267
+ return `<?xml version="1.0" encoding="UTF-8"?>
268
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
269
+ <plist version="1.0">
270
+ <dict>
271
+ <key>Label</key>
272
+ <string>${esc(label)}</string>
273
+ <key>ProgramArguments</key>
274
+ <array>
275
+ <string>${esc(node)}</string>
276
+ <string>${esc(cli)}</string>
277
+ <string>start</string>
278
+ <string>--port</string>
279
+ <string>${esc(port)}</string>
280
+ <string>--host</string>
281
+ <string>${esc(host)}</string>
282
+ </array>
283
+ <key>RunAtLoad</key>
284
+ <true/>
285
+ <key>KeepAlive</key>
286
+ <true/>
287
+ <key>WorkingDirectory</key>
288
+ <string>${esc(workdir)}</string>
289
+ <key>EnvironmentVariables</key>
290
+ <dict>
291
+ <key>HERMES_HOME</key>
292
+ <string>${esc(hermesHome)}</string>
293
+ <key>PATH</key>
294
+ <string>${esc(path.join(hermesHome, 'hermes-agent', '.hermes', 'bin'))}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
295
+ </dict>
296
+ <key>StandardOutPath</key>
297
+ <string>${esc(path.join(logDir, 'pilot.out.log'))}</string>
298
+ <key>StandardErrorPath</key>
299
+ <string>${esc(path.join(logDir, 'pilot.err.log'))}</string>
300
+ </dict>
301
+ </plist>
302
+ `
303
+ }
304
+
305
+ /**
306
+ * systemd --user のユニットを組み立てる(Linux)。
307
+ * @param {object} opts 入力(`buildLaunchdPlist` と同じ項目)
308
+ * @returns {string} unit ファイル
309
+ */
310
+ export function buildSystemdUnit({ node, cli, port, host, hermesHome, workdir }) {
311
+ return `[Unit]
312
+ Description=Hermes Pilot bridge
313
+ After=network.target
314
+
315
+ [Service]
316
+ Type=simple
317
+ WorkingDirectory=${workdir}
318
+ Environment=HERMES_HOME=${hermesHome}
319
+ ExecStart=${node} ${cli} start --port ${port} --host ${host}
320
+ Restart=always
321
+ RestartSec=3
322
+
323
+ [Install]
324
+ WantedBy=default.target
325
+ `
326
+ }
327
+
328
+ /** 配列を改行付きで出力する。 */
329
+ function out(...lines) {
330
+ console.log(lines.join('\n'))
331
+ }
332
+
333
+ /**
334
+ * ペアリング情報をまとめて表示用にする。
335
+ * @param {object} opts 入力
336
+ * @param {string} opts.token トークン
337
+ * @param {number} opts.port ポート
338
+ * @returns {{targets: Array<object>, best: object|null, dnsName: string|null, lanIp: string|null}} 情報
339
+ */
340
+ export function pairingInfo({ token, port, tlsPort = null, dnsName = null }) {
341
+ return collectPairing({ token, port, tlsPort, dnsName, tailscaleJson: readTailscaleStatus() })
342
+ }
343
+
344
+ /**
345
+ * ワンタイム・ペアリングコードを発行して注意書きを出す。
346
+ *
347
+ * 本トークン(64 文字)を URL に載せると QR が高密度になり、端末 80x24 では
348
+ * 行が溢れてカメラが読めない。短いコード(8 文字)で QR を粗くする。
349
+ * @param {string} dataDir データ先(`pair-codes.json` を置く)
350
+ * @returns {string} 発行したコード
351
+ */
352
+ export function mintPairCode(dataDir) {
353
+ const { code, expiresAt } = createPairCodes({ dataDir }).mint()
354
+ const minutes = Math.max(1, Math.round((expiresAt - Date.now()) / 60000))
355
+ out('', `ワンタイムコード / one-time code: ${code}(${minutes} 分有効・1 回限り)`)
356
+ return code
357
+ }
358
+
359
+ /**
360
+ * ペアリング URL と QR を表示する。
361
+ * @param {object} opts 入力
362
+ * @param {string} opts.token トークン
363
+ * @param {number} opts.port ポート
364
+ * @param {boolean} [opts.svg] SVG も 1 行で出す
365
+ */
366
+ function printPairing({ token, port, tlsPort = null, dnsName = null, svg = false, pngPath = null }) {
367
+ const info = pairingInfo({ token, port, tlsPort, dnsName })
368
+ out('', '接続先候補 / Pairing targets:')
369
+ for (const t of info.targets) out(` - ${t.label}: ${t.url}`)
370
+ if (!info.best) {
371
+ out('', '到達可能なアドレスがありません(Tailscale か LAN を確認してください)。')
372
+ return
373
+ }
374
+ // 端末の半角ブロックは行間が塗られず、カメラから見ると暗い横縞が QR を横切るため
375
+ // 読み取れない(実測: 別端末のスキャナも無反応)。PNG を書いて**画像として**出す。
376
+ if (pngPath) {
377
+ try {
378
+ const png = qrPng(info.best.url)
379
+ fs.mkdirSync(path.dirname(pngPath), { recursive: true })
380
+ fs.writeFileSync(pngPath, png, { mode: 0o600 })
381
+ out('', `QR 画像 / PNG: ${pngPath}`, ` → これを大きく開いてカメラで読み取ってください(${png.length} bytes)。`)
382
+ } catch (err) {
383
+ out('', `QR 画像を書けませんでした: ${err?.message ?? err}`)
384
+ }
385
+ }
386
+ const cols = process.stdout.columns || 80
387
+ const rows = process.stdout.rows || 24
388
+ // 端末に収まらない QR を出すと、行が折り返すか上にスクロールして欠けたコードになる(実測:
389
+ // 64 文字トークンの URL は 27 行になり 80x24 で読めなかった)。収まる候補を選び、
390
+ // どれも収まらないときは PNG の案内だけにする。
391
+ const dims = (s) => {
392
+ const lines = s.split('\n')
393
+ return { width: lines[0].replace(/\x1b\[[0-9;]*m/g, '').length, height: lines.length }
394
+ }
395
+ const fits = (s) => {
396
+ const d = dims(s)
397
+ return d.width <= cols - 2 && d.height <= rows - 6
398
+ }
399
+ let pick = info.targets[0]
400
+ let qr = qrTerminal(pick.url)
401
+ if (!fits(qr)) {
402
+ // 短い候補(LAN など)なら端末に収まる
403
+ for (const t of info.targets) {
404
+ const candidate = qrTerminal(t.url)
405
+ if (fits(candidate)) {
406
+ pick = t
407
+ qr = candidate
408
+ break
409
+ }
410
+ }
411
+ }
412
+ if (!fits(qr)) {
413
+ const d = dims(qrTerminal(info.best.url))
414
+ out(
415
+ '',
416
+ `端末 QR はこの端末(${cols}x${rows})に収まらないため省略しました(${d.width} 桁 x ${d.height} 行)。`,
417
+ ' → 上の PNG を開いて読み取るか、PC のブラウザで「設定 → ペアリング QR」を大きく表示してください。',
418
+ )
419
+ if (svg) out('', qrSvg(info.best.url))
420
+ return
421
+ }
422
+ out('', `端末表示の QR(${pick.label}・参考)— 読み取れないときは上の PNG を使ってください:`, '')
423
+ out(qr)
424
+ if (svg) out('', qrSvg(info.best.url))
425
+ }
426
+
427
+ /**
428
+ * 旧環境があるときに `init` がどう振る舞うかを決める(D55: 無言の自動移行をやめる)。
429
+ *
430
+ * - 旧環境が無い → `skip`
431
+ * - `--yes` → `migrate`(明示同意とみなす)
432
+ * - TTY → `ask`(`y/N`。既定は N)
433
+ * - 非 TTY かつ `--yes` 無し(cron / CI / パイプ) → `manual`(移行せずコマンドを案内)
434
+ *
435
+ * @param {{hasLegacy?: boolean, yes?: boolean, isTTY?: boolean}} [opts]
436
+ * @returns {'skip'|'migrate'|'ask'|'manual'}
437
+ */
438
+ export function migrationDecision({ hasLegacy = false, yes = false, isTTY = false } = {}) {
439
+ if (!hasLegacy) return 'skip'
440
+ if (yes) return 'migrate'
441
+ return isTTY ? 'ask' : 'manual'
442
+ }
443
+
444
+ /**
445
+ * TTY で `y/N` を聞く(既定 N。Enter だけなら移行しない)。
446
+ * @param {object} [opts]
447
+ * @param {NodeJS.ReadableStream} [opts.input]
448
+ * @param {NodeJS.WritableStream} [opts.output]
449
+ * @param {string} [opts.question]
450
+ * @returns {Promise<boolean>} 移行するなら true
451
+ */
452
+ export function askMigrate({ input = process.stdin, output = process.stdout, question } = {}) {
453
+ const q =
454
+ question ??
455
+ '旧環境(akapen / mobile-pwa)が見つかりました。今すぐ移行しますか? / Migrate legacy data now? [y/N]: '
456
+ const rl = readline.createInterface({ input, output })
457
+ return new Promise((resolve) => {
458
+ let answered = false
459
+ rl.question(q, (answer) => {
460
+ answered = true
461
+ rl.close()
462
+ resolve(/^y(es)?$/i.test(String(answer).trim()))
463
+ })
464
+ // Ctrl-D / EOF は「いいえ」として扱う(無言で移行しない)
465
+ rl.on('close', () => {
466
+ if (!answered) resolve(false)
467
+ })
468
+ })
469
+ }
470
+
471
+ /**
472
+ * 旧環境が残っているか(`init` の移行判定)。
473
+ * @param {object} p `resolvePaths()` の結果
474
+ * @returns {boolean} 残っていれば true
475
+ */
476
+ function hasLegacyEnv(p) {
477
+ return [
478
+ path.join(p.home, 'Projects', 'akapen'),
479
+ path.join(p.home, 'projects', 'akapen'),
480
+ path.join(p.hermesHome, 'mobile-pwa'),
481
+ path.join(p.hermesHome, 'plugin-data', 'akapen'),
482
+ ].some((dir) => fs.existsSync(dir))
483
+ }
484
+
485
+ /**
486
+ * 標準ダッシュボード用タブの配置先を返す(`installDashboardPlugin` の `root`)。
487
+ *
488
+ * 通常は `~/.hermes/plugins/hermes-pilot/`。`hermes plugins install` が**リポジトリ
489
+ * ルート自体**をプラグインディレクトリとして展開した場合はプラグインのベースが
490
+ * 別の場所になるので、`HERMES_PLUGINS_DIR`(ベース)か `targetDir`(完全パス)で
491
+ * 上書きできる。D56 の「`targetDir === ROOT` のときは自己上書きしない」判定はここで得た
492
+ * パスを :func:`sameDir` で `ROOT` と比べて行う。
493
+ * @param {object} p `resolvePaths()` の結果
494
+ * @param {object} [opts] オプション
495
+ * @param {string|null} [opts.targetDir] 完全パスで指定する場合
496
+ * @param {object} [opts.env] 環境変数
497
+ * @returns {string} プラグインのディレクトリ
498
+ */
499
+ export function resolveDashboardTarget(p, { targetDir = null, env = process.env } = {}) {
500
+ const expand = (value) => path.resolve(String(value).replace(/^~(?=$|\/)/, p.home ?? os.homedir()))
501
+ if (targetDir) return expand(targetDir)
502
+ const base = env.HERMES_PLUGINS_DIR ? expand(env.HERMES_PLUGINS_DIR) : path.join(p.hermesHome, 'plugins')
503
+ return path.join(base, DASHBOARD_PLUGIN)
504
+ }
505
+
506
+ /**
507
+ * 2 つのパスが同じディレクトリを指すか(symlink を解決する)。
508
+ *
509
+ * `hermes plugins install` はクローン先を symlink にすることがあり、文字列比較だけだと
510
+ * 「リポジトリルートに直接インストールされた」ケースを取り逃がして自己上書きする。
511
+ * @param {string} a パス
512
+ * @param {string} b パス
513
+ * @returns {boolean} 同じ実体なら true
514
+ */
515
+ export function sameDir(a, b) {
516
+ const real = (dir) => {
517
+ try {
518
+ return fs.realpathSync(dir)
519
+ } catch {
520
+ return null
521
+ }
522
+ }
523
+ const ra = real(a)
524
+ const rb = real(b)
525
+ if (ra && rb) return ra === rb
526
+ return path.resolve(a) === path.resolve(b)
527
+ }
528
+
529
+ /**
530
+ * 標準ダッシュボード用タブを `~/.hermes/plugins/hermes-pilot/` へ**冪等に**配置する。
531
+ *
532
+ * - 既にあるファイルは `force` が真のときだけ上書きする(`skills` 配置と同じ流儀)。
533
+ * - あわせて `dashboard.json`(CLI の絶対パス・node・リポジトリ根)をデータ先へ書き、
534
+ * ダッシュボードの「サービス」操作がこれを spawn できるようにする。
535
+ * - **自己上書きの回避(D56)**: 配置先がリポジトリルート自身(`targetDir === ROOT`)の
536
+ * ときはコピーを行わない。ルートには `__init__.py` / `dashboard/` が既にコミット済みで、
537
+ * 写し元(`apps/dashboard/`)と写し先が同一ツリーになるため、コピーは無意味か
538
+ * 破壊的(`apps/dashboard/` → `dashboard/` の逆向き同期事故)になりうる。
539
+ * この場合はスキル・データ初期化だけを完了させ、`selfHosted: true` で返す。
540
+ * @param {object} p `resolvePaths()` の結果
541
+ * @param {object} [opts] オプション
542
+ * @param {boolean} [opts.force] 既存ファイルも上書きする
543
+ * @param {string|null} [opts.targetDir] 配置先を明示する(省略時は `~/.hermes/plugins/hermes-pilot`)
544
+ * @returns {{root: string, installed: string[], skipped: string[], selfHosted: boolean}} 結果
545
+ */
546
+ export function installDashboardPlugin(p, { force = false, targetDir = null } = {}) {
547
+ const root = resolveDashboardTarget(p, { targetDir })
548
+ const selfHosted = sameDir(root, ROOT)
549
+ const installed = []
550
+ const skipped = []
551
+ if (!selfHosted) {
552
+ for (const file of DASHBOARD_FILES) {
553
+ const src = path.join(ROOT, file.from)
554
+ const dest = path.join(root, file.to)
555
+ if (!fs.existsSync(src)) continue
556
+ if (fs.existsSync(dest) && !force) {
557
+ skipped.push(dest)
558
+ continue
559
+ }
560
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
561
+ fs.copyFileSync(src, dest)
562
+ installed.push(dest)
563
+ }
564
+ }
565
+ // サービス操作は CLI を spawn する。常駐・worker からも辿れるよう絶対パスで残す。
566
+ fs.mkdirSync(p.dataDir, { recursive: true, mode: 0o700 })
567
+ fs.writeFileSync(
568
+ path.join(p.dataDir, 'dashboard.json'),
569
+ `${JSON.stringify(
570
+ {
571
+ version: 1,
572
+ plugin: DASHBOARD_PLUGIN,
573
+ root: ROOT,
574
+ cli: path.join(ROOT, 'bin', 'hermes-pilot.mjs'),
575
+ node: process.execPath,
576
+ updatedAt: new Date().toISOString(),
577
+ },
578
+ null,
579
+ 2,
580
+ )}\n`,
581
+ { mode: 0o600 },
582
+ )
583
+ return { root, installed, skipped, selfHosted }
584
+ }
585
+
586
+ /**
587
+ * `init` の本体(冪等)。
588
+ * @param {object} p `resolvePaths()` の結果
589
+ * @param {number} port ポート
590
+ * @param {object} [opts] オプション
591
+ * @param {number|null} [opts.tlsPort] TLS ポート
592
+ * @param {boolean} [opts.force] ダッシュボード・プラグインを上書きする
593
+ * @param {string|null} [opts.targetDir] ダッシュボード・プラグインの配置先(`hermes plugins install` の展開先)
594
+ * @param {boolean} [opts.yes] 旧環境の移行を確認なしで実行する(`--yes` / D55)
595
+ * @param {() => Promise<boolean>} [opts.confirm] 移行確認関数(テスト用 DI。既定は `askMigrate`)
596
+ * @param {boolean|null} [opts.isTTY] TTY 判定の上書き(テスト用。既定は stdin+stdout の TTY)
597
+ * @returns {{created: boolean, migrated: boolean, migration: string, skills: string[], dashboard: object}} 結果
598
+ */
599
+ export async function runInit(
600
+ p,
601
+ port,
602
+ { tlsPort = null, force = false, targetDir = null, yes = false, confirm = null, isTTY = null } = {},
603
+ ) {
604
+ fs.mkdirSync(p.dataDir, { recursive: true, mode: 0o700 })
605
+ for (const sub of ['sheets', 'shots', 'library']) {
606
+ fs.mkdirSync(path.join(p.reviewDir, sub), { recursive: true })
607
+ }
608
+ fs.mkdirSync(p.logDir, { recursive: true })
609
+ if (!fs.existsSync(p.configPath)) {
610
+ fs.writeFileSync(p.configPath, `${JSON.stringify({ lang: 'en', scanDirs: ['~/Projects', '~/projects'], servicePort: port }, null, 2)}\n`)
611
+ }
612
+ const { created } = ensureToken(p.tokenPath)
613
+
614
+ // D55: 旧環境の移行は **明示同意**(`--yes` / TTY での y / `migrate` サブコマンド)でのみ実行する。
615
+ // 無言の自動移行は Hermes state を勝手に書き換えるので廃止した。
616
+ const tty = isTTY === null ? Boolean(process.stdin.isTTY && process.stdout.isTTY) : Boolean(isTTY)
617
+ const decision = migrationDecision({ hasLegacy: hasLegacyEnv(p), yes, isTTY: tty })
618
+ let migrated = false
619
+ let migration = decision
620
+ if (decision === 'migrate' || decision === 'ask') {
621
+ const proceed = decision === 'migrate' ? true : await (confirm ?? askMigrate)()
622
+ if (proceed) {
623
+ const { migrate, formatReport } = await loadMigrate()
624
+ const report = migrate({ home: p.home, hermesHome: p.hermesHome, pluginDataDir: p.pluginDataDir })
625
+ out('旧環境が見つかったので移行しました / Migrated legacy data:', '', formatReport(report))
626
+ migrated = true
627
+ migration = 'migrate'
628
+ } else {
629
+ migration = 'manual'
630
+ }
631
+ }
632
+ if (migration === 'manual') {
633
+ out(
634
+ '旧環境(akapen / mobile-pwa)はまだ残っていますが、移行していません / legacy data found; not migrated',
635
+ ' → 移行するには: node bin/hermes-pilot.mjs migrate',
636
+ ' (確認を省略する場合は init --yes)',
637
+ )
638
+ }
639
+
640
+ const installed = []
641
+ for (const name of BUNDLED_SKILLS) {
642
+ const src = path.join(ROOT, 'skills', name)
643
+ const dest = path.join(p.skillsDir, name)
644
+ if (!fs.existsSync(src)) continue
645
+ try {
646
+ fs.cpSync(src, dest, { recursive: true, force: false, preserveTimestamps: true })
647
+ installed.push(dest)
648
+ } catch (err) {
649
+ out(` ! skill ${name}: ${err?.message ?? err}`)
650
+ }
651
+ }
652
+ // 標準ダッシュボードのタブ(冪等)。`--force` で既存ファイルも上書きする。
653
+ const dashboard = installDashboardPlugin(p, { force, targetDir })
654
+ out(
655
+ '',
656
+ 'hermes-pilot init 完了 / done',
657
+ ` データ / data : ${p.dataDir}`,
658
+ ` トークン / token: ${p.tokenPath}${created ? '(新規作成 0600)' : '(既存)'}`,
659
+ ` スキル / skills: ${installed.length ? installed.join(', ') : '(既に配置済み)'}`,
660
+ ` 移行 / migrate: ${migrated ? '実行' : migration === 'manual' ? '未実行(migrate サブコマンドで実行)' : '不要'}`,
661
+ )
662
+ if (dashboard.selfHosted) {
663
+ // リポジトリルート自体がプラグインディレクトリ(`hermes plugins install` 直後の形)。
664
+ // ルートに `__init__.py` / `dashboard/` がコミット済みなのでコピーはしない。
665
+ out(
666
+ ` ダッシュボード / dashboard tab: ${dashboard.root}`,
667
+ ' リポジトリルートがプラグインディレクトリなのでコピーは省略(自己上書きの回避)。',
668
+ ' / plugin dir == repo root: nothing to copy, the layout is already committed.',
669
+ ' → 初回は `hermes plugins enable hermes-pilot` とダッシュボードの再起動が必要です。',
670
+ )
671
+ } else {
672
+ out(
673
+ ` ダッシュボード / dashboard tab: ${dashboard.root}`,
674
+ ` ${dashboard.installed.length} ファイル配置${dashboard.installed.length ? '' : '(既に配置済み。--force で上書き)'}`,
675
+ ' → Hermes ダッシュボード(:9119)の「Hermes Pilot」タブに出ます。初回は `hermes plugins enable hermes-pilot` とダッシュボードの再起動が必要です。',
676
+ )
677
+ }
678
+ printPairing({ token: mintPairCode(p.dataDir), port, tlsPort, pngPath: path.join(p.dataDir, 'pair-qr.png') })
679
+ return { created, migrated, migration, skills: installed, dashboard }
680
+ }
681
+
682
+ // migrate モジュールは CLI 実行時にだけ遅延ロードする(テストの import を軽くする)
683
+ let migrateModule = {}
684
+ const loadMigrate = async () => {
685
+ if (!migrateModule.migrate) migrateModule = await import('../scripts/migrate-to-hermes-pilot.mjs')
686
+ return migrateModule
687
+ }
688
+
689
+ /** launchd の状態(`launchctl print` の終了コード)。 */
690
+ function launchdLoaded(label) {
691
+ const r = spawnSync('launchctl', ['print', `gui/${process.getuid?.() ?? 501}/${label}`], { encoding: 'utf8' })
692
+ return { loaded: r.status === 0, code: r.status, out: `${r.stdout ?? ''}${r.stderr ?? ''}`.trim() }
693
+ }
694
+
695
+ /**
696
+ * `service` サブコマンド。
697
+ * @param {string|null} sub install|uninstall|restart|status
698
+ * @param {object} opts 入力
699
+ * @param {object} opts.paths `resolvePaths()`
700
+ * @param {number} opts.port ポート
701
+ * @param {string} opts.host ホスト
702
+ * @param {boolean} opts.dryRun 書き込まない
703
+ * @returns {number} 終了コード
704
+ */
705
+ export function runService(sub, { paths, port, host, dryRun = false }) {
706
+ const platform = process.platform
707
+ if (platform === 'darwin') {
708
+ const plistPath = path.join(paths.home, 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`)
709
+ const uid = process.getuid?.() ?? 501
710
+ const domain = `gui/${uid}`
711
+ if (sub === 'install') {
712
+ const body = buildLaunchdPlist({
713
+ label: SERVICE_LABEL,
714
+ node: process.execPath,
715
+ cli: path.join(ROOT, 'bin', 'hermes-pilot.mjs'),
716
+ port,
717
+ host,
718
+ hermesHome: paths.hermesHome,
719
+ logDir: paths.logDir,
720
+ workdir: ROOT,
721
+ })
722
+ out(`plist: ${plistPath}`)
723
+ if (dryRun) {
724
+ out(body)
725
+ return 0
726
+ }
727
+ fs.mkdirSync(path.dirname(plistPath), { recursive: true })
728
+ fs.mkdirSync(paths.logDir, { recursive: true })
729
+ fs.writeFileSync(plistPath, body, { mode: 0o644 })
730
+ const boot = spawnSync('launchctl', ['bootstrap', domain, plistPath], { encoding: 'utf8' })
731
+ if (boot.status !== 0) {
732
+ // 既に読み込まれている場合は kickstart で反映する
733
+ const kick = spawnSync('launchctl', ['kickstart', '-k', `${domain}/${SERVICE_LABEL}`], { encoding: 'utf8' })
734
+ out(`launchctl bootstrap: ${(boot.stderr || boot.stdout || '').trim() || 'already loaded'}`)
735
+ out(`launchctl kickstart: exit ${kick.status}`)
736
+ } else {
737
+ out(`launchctl bootstrap: ok(${domain})`)
738
+ }
739
+ out(`常駐を開始しました / service installed: ${SERVICE_LABEL}`)
740
+ return 0
741
+ }
742
+ if (sub === 'uninstall') {
743
+ out(`plist: ${plistPath}`)
744
+ if (dryRun) return 0
745
+ const r = spawnSync('launchctl', ['bootout', `${domain}/${SERVICE_LABEL}`], { encoding: 'utf8' })
746
+ out(`launchctl bootout: exit ${r.status}`)
747
+ try {
748
+ fs.rmSync(plistPath, { force: true })
749
+ out('plist を削除しました')
750
+ } catch (err) {
751
+ out(`plist の削除に失敗: ${err?.message ?? err}`)
752
+ }
753
+ out('旧 ai.hermes.hermes-mobile はそのままです(必要なら手動で bootout)。')
754
+ return 0
755
+ }
756
+ if (sub === 'restart') {
757
+ if (dryRun) {
758
+ out(`launchctl bootout + bootstrap ${domain}/${SERVICE_LABEL}`)
759
+ return 0
760
+ }
761
+ // kickstart -k は読み込み済みのジョブ定義を使い回すので、plist の
762
+ // EnvironmentVariables(PATH など)を直しても反映されない(実測: PATH に
763
+ // hermes が無いままブリッジが起動し、レビュー回答の comment/unblock が全滅した)。
764
+ // bootout → bootstrap で plist を読み直し、失敗したときだけ kickstart に落とす。
765
+ const off = spawnSync('launchctl', ['bootout', `${domain}/${SERVICE_LABEL}`], { encoding: 'utf8' })
766
+ out(`launchctl bootout: exit ${off.status}`)
767
+ if (!fs.existsSync(plistPath)) {
768
+ out(`plist がありません(先に service install を実行してください): ${plistPath}`)
769
+ return 1
770
+ }
771
+ // bootout 直後の bootstrap は "Input/output error (5)" で失敗することがある
772
+ // (実測: アンロードが終わる前)。数百 ms 待って数回だけ試す。
773
+ let on = { status: 1, stderr: '' }
774
+ for (let i = 0; i < 4; i++) {
775
+ spawnSync('sleep', ['0.4'], { encoding: 'utf8' })
776
+ on = spawnSync('launchctl', ['bootstrap', domain, plistPath], { encoding: 'utf8' })
777
+ if (on.status === 0) break
778
+ }
779
+ if (on.status === 0) {
780
+ out('launchctl bootstrap: ok(plist を読み直した)')
781
+ return 0
782
+ }
783
+ out(`launchctl bootstrap: exit ${on.status}${on.stderr ? ` (${on.stderr.trim()})` : ''}`)
784
+ const r = spawnSync('launchctl', ['kickstart', '-k', `${domain}/${SERVICE_LABEL}`], { encoding: 'utf8' })
785
+ out(`launchctl kickstart: exit ${r.status}${r.stderr ? ` (${r.stderr.trim()})` : ''}`)
786
+ return r.status === 0 ? 0 : 1
787
+ }
788
+ if (sub === 'status' || !sub) {
789
+ const st = launchdLoaded(SERVICE_LABEL)
790
+ out(`service: ${SERVICE_LABEL}`)
791
+ out(`plist: ${plistPath}${fs.existsSync(plistPath) ? '(あり)' : '(なし)'}`)
792
+ out(st.loaded ? '状態 / state: running' : '状態 / state: not installed(hermes-pilot service install)')
793
+ return 0
794
+ }
795
+ out(`unknown service subcommand: ${sub}`)
796
+ return 2
797
+ }
798
+
799
+ // Linux / その他は systemd --user
800
+ const unitDir = path.join(paths.home, '.config', 'systemd', 'user')
801
+ const unitPath = path.join(unitDir, SYSTEMD_UNIT)
802
+ const sys = (args) => spawnSync('systemctl', ['--user', ...args], { encoding: 'utf8' })
803
+ if (sub === 'install') {
804
+ const body = buildSystemdUnit({
805
+ node: process.execPath,
806
+ cli: path.join(ROOT, 'bin', 'hermes-pilot.mjs'),
807
+ port,
808
+ host,
809
+ hermesHome: paths.hermesHome,
810
+ workdir: ROOT,
811
+ })
812
+ out(`unit: ${unitPath}`)
813
+ if (dryRun) {
814
+ out(body)
815
+ return 0
816
+ }
817
+ fs.mkdirSync(unitDir, { recursive: true })
818
+ fs.mkdirSync(paths.logDir, { recursive: true })
819
+ fs.writeFileSync(unitPath, body)
820
+ const daemon = sys(['daemon-reload'])
821
+ const enable = sys(['enable', '--now', SYSTEMD_UNIT])
822
+ out(`systemctl --user daemon-reload: exit ${daemon.status}`)
823
+ out(`systemctl --user enable --now: exit ${enable.status}`)
824
+ return enable.status === 0 ? 0 : 1
825
+ }
826
+ if (sub === 'uninstall') {
827
+ if (dryRun) {
828
+ out(`systemctl --user disable --now ${SYSTEMD_UNIT} && rm ${unitPath}`)
829
+ return 0
830
+ }
831
+ const r = sys(['disable', '--now', SYSTEMD_UNIT])
832
+ out(`systemctl --user disable --now: exit ${r.status}`)
833
+ try {
834
+ fs.rmSync(unitPath, { force: true })
835
+ } catch {
836
+ /* 既に無い */
837
+ }
838
+ return 0
839
+ }
840
+ if (sub === 'restart') {
841
+ if (dryRun) {
842
+ out(`systemctl --user restart ${SYSTEMD_UNIT}`)
843
+ return 0
844
+ }
845
+ const r = sys(['restart', SYSTEMD_UNIT])
846
+ out(`systemctl --user restart: exit ${r.status}`)
847
+ return r.status === 0 ? 0 : 1
848
+ }
849
+ if (sub === 'status' || !sub) {
850
+ const r = sys(['is-active', SYSTEMD_UNIT])
851
+ out(`service: ${SYSTEMD_UNIT}`)
852
+ out(`unit: ${unitPath}${fs.existsSync(unitPath) ? '(あり)' : '(なし)'}`)
853
+ out(`状態 / state: ${String(r.stdout ?? '').trim() || 'unknown'}(exit ${r.status})`)
854
+ return 0
855
+ }
856
+ out(`unknown service subcommand: ${sub}`)
857
+ return 2
858
+ }
859
+
860
+ /**
861
+ * `start` の本体。UI が無ければビルドし、ブリッジを起動する。
862
+ * @param {object} opts 入力
863
+ * @param {object} opts.paths `resolvePaths()`
864
+ * @param {number} opts.port ポート
865
+ * @param {string} opts.host ホスト
866
+ * @param {boolean} [opts.noQr] QR を出さない
867
+ * @returns {Promise<void>}
868
+ */
869
+ export async function runStart({ paths, port, host, tlsPort = null, dnsName = null, noQr = false }) {
870
+ const index = path.join(ROOT, 'apps', 'web', 'dist', 'index.html')
871
+ if (!fs.existsSync(index)) {
872
+ out('UI が未ビルドなのでビルドします / building the UI…')
873
+ const build = spawnSync('npm', ['run', 'build'], { cwd: ROOT, stdio: 'inherit' })
874
+ if (build.status !== 0) {
875
+ out('ビルドに失敗しました / build failed')
876
+ process.exit(1)
877
+ }
878
+ }
879
+ ensureToken(paths.tokenPath)
880
+ if (!noQr) printPairing({ token: mintPairCode(paths.dataDir), port, tlsPort, dnsName, pngPath: path.join(paths.dataDir, 'pair-qr.png') })
881
+ process.env.HM_PORT = String(port)
882
+ process.env.HM_HOST = host
883
+ if (!process.env.HERMES_HOME) process.env.HERMES_HOME = paths.hermesHome
884
+ await import(path.join(ROOT, 'apps', 'bridge', 'src', 'server.js'))
885
+ }
886
+
887
+ /**
888
+ * CLI のエントリ。
889
+ * @param {string[]} [argv] 引数(テスト用)
890
+ * @returns {Promise<number>} 終了コード
891
+ */
892
+ export async function main(argv = process.argv.slice(2)) {
893
+ const { command, sub, flags } = parseArgv(argv)
894
+ const paths = resolvePaths(process.env)
895
+ const cfg = readConfig(paths.configPath)
896
+ const port = Number(flags.port) || cfg.servicePort || DEFAULT_PORT
897
+ const tlsPort = Number(flags['tls-port']) || cfg.tlsPort || null
898
+ const dnsName = cfg.tailscaleDns || null
899
+ const host = typeof flags.host === 'string' ? flags.host : DEFAULT_HOST
900
+ const dryRun = Boolean(flags['dry-run'])
901
+
902
+ if (!command || command === 'help' || flags.help || flags.h) {
903
+ out(helpText())
904
+ return 0
905
+ }
906
+
907
+ if (command === 'init') {
908
+ await runInit(paths, port, {
909
+ tlsPort,
910
+ force: Boolean(flags.force),
911
+ targetDir: typeof flags['target-dir'] === 'string' ? flags['target-dir'] : null,
912
+ yes: Boolean(flags.yes || flags.y),
913
+ })
914
+ return 0
915
+ }
916
+
917
+ if (command === 'qr') {
918
+ const { created } = ensureToken(paths.tokenPath)
919
+ if (created) out(`トークンを新規作成しました / token created: ${paths.tokenPath}`)
920
+ printPairing({
921
+ token: mintPairCode(paths.dataDir),
922
+ port,
923
+ tlsPort,
924
+ dnsName,
925
+ svg: Boolean(flags.svg),
926
+ pngPath: typeof flags.png === 'string' ? flags.png : path.join(paths.dataDir, 'pair-qr.png'),
927
+ })
928
+ return 0
929
+ }
930
+
931
+ if (command === 'start') {
932
+ await runStart({ paths, port, host, tlsPort, dnsName, noQr: Boolean(flags['no-qr']) })
933
+ return 0
934
+ }
935
+
936
+ if (command === 'service') {
937
+ return runService(sub, { paths, port, host, dryRun })
938
+ }
939
+
940
+ if (command === 'migrate') {
941
+ const mod = await loadMigrate()
942
+ const report = mod.migrate({ home: paths.home, hermesHome: paths.hermesHome, pluginDataDir: paths.pluginDataDir })
943
+ out(mod.formatReport(report))
944
+ return 0
945
+ }
946
+
947
+ out(`unknown command: ${command}`, '', helpText())
948
+ return 2
949
+ }
950
+
951
+ const invokedDirectly =
952
+ process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url))
953
+
954
+ if (invokedDirectly) {
955
+ main()
956
+ .then((code) => {
957
+ if (code) process.exit(code)
958
+ })
959
+ .catch((err) => {
960
+ console.error(`[hermes-pilot] ${err?.stack ?? err}`)
961
+ process.exit(1)
962
+ })
963
+ }
964
+