hermes-pilot 0.0.0-stage → 0.2.2

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 +419 -0
  3. package/README.md +428 -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 +513 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1022 -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 +1745 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +806 -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-q4f5Zu0I.js +12 -0
  46. package/apps/web/dist/assets/index-BzUof8lw.js +94 -0
  47. package/apps/web/dist/assets/index-DwZdbPU7.css +1 -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 +138 -0
  72. package/skills/quick-review/SKILL.md +200 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +226 -0
@@ -0,0 +1,73 @@
1
+ import path from 'node:path'
2
+ import os from 'node:os'
3
+ import fs from 'node:fs'
4
+
5
+ export const VERSION = '0.1.0'
6
+
7
+ /**
8
+ * `config.json`(CLI が書く設定)からペアリング用の値だけ拾う。
9
+ *
10
+ * `tailscaleDns` / `tlsPort` は、常駐プロセスから Tailscale CLI を叩けない環境
11
+ * (macOS アプリ版は launchd から実行すると GUI 起動に失敗する)で
12
+ * ペアリング URL を正しく出すための控え。壊れていても起動は止めない。
13
+ * @param {string} configPath config.json のパス
14
+ * @returns {{tailscaleDns: string|null, tlsPort: number|null}} 値
15
+ */
16
+ export function readPairingConfig(configPath) {
17
+ try {
18
+ const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
19
+ const dns = typeof raw?.tailscaleDns === 'string' ? raw.tailscaleDns.trim().replace(/\.$/, '') : ''
20
+ const tlsPort = Number(raw?.tlsPort)
21
+ return { tailscaleDns: dns || null, tlsPort: Number.isFinite(tlsPort) && tlsPort > 0 ? tlsPort : null }
22
+ } catch {
23
+ return { tailscaleDns: null, tlsPort: null }
24
+ }
25
+ }
26
+
27
+ /**
28
+ * ブリッジの設定。既存の Hermes ダッシュボード(9119)は変更しない前提。
29
+ * @returns {object} 設定
30
+ */
31
+ export function loadConfig() {
32
+ const home = process.env.HOME ?? os.homedir()
33
+ const hermesHome = process.env.HERMES_HOME ?? path.join(home, '.hermes')
34
+ // 公開プラグインのデータ先(D1 / §3.2)。token・audit・snippets・repos.json はここへ一本化する。
35
+ const pluginDataDir =
36
+ process.env.HP_DATA_DIR ?? path.join(hermesHome, 'plugin-data', 'hermes-pilot')
37
+ // 旧 `mobile-pwa` を指したい検証用に HM_DATA も受けるが、既定は hermes-pilot。
38
+ const dataDir = process.env.HM_DATA ?? pluginDataDir
39
+ const configPath = path.join(pluginDataDir, 'config.json')
40
+ const pairing = readPairingConfig(configPath)
41
+ return {
42
+ version: VERSION,
43
+ home,
44
+ host: process.env.HM_HOST ?? '127.0.0.1',
45
+ port: Number(process.env.HM_PORT ?? 4097),
46
+ /** 変更しない既存サーバ */
47
+ hermesBase: process.env.HERMES_BASE ?? 'http://127.0.0.1:9119',
48
+ hermesHome,
49
+ kanbanRoot: path.join(hermesHome, 'kanban'),
50
+ kanbanDb: path.join(hermesHome, 'kanban.db'),
51
+ /** 会話ログ(セッション横断検索の対象。読取専用で開く) */
52
+ stateDb: process.env.HM_STATE_DB ?? path.join(hermesHome, 'state.db'),
53
+ logDir: path.join(hermesHome, 'logs'),
54
+ dataDir,
55
+ pluginDataDir,
56
+ /** レビューワークスペース(sheets / shots / library / feed.jsonl 等) */
57
+ reviewDir: path.join(pluginDataDir, 'review'),
58
+ /** リポジトリ設定(scanDirs / pinned / hidden / custom) */
59
+ reposPath: process.env.HP_REPOS_JSON ?? path.join(pluginDataDir, 'repos.json'),
60
+ tokenPath: path.join(dataDir, 'token'),
61
+ auditPath: path.join(dataDir, 'audit.jsonl'),
62
+ /** CLI が書く設定(lang / scanDirs / servicePort / tlsPort / tailscaleDns) */
63
+ configPath,
64
+ /** ペアリング URL の控え(Tailscale CLI を叩けない常駐環境向け, SPEC §8.2) */
65
+ pairing,
66
+ cookieName: 'hm_session',
67
+ /** 端末セッションの有効期間(30日) */
68
+ sessionTtlMs: 30 * 24 * 60 * 60 * 1000,
69
+ distDir: path.resolve(import.meta.dirname, '../../web/dist'),
70
+ /** ポーリング前提の軽量 API なので素直に制限する */
71
+ rate: { windowMs: 60_000, maxWrites: 60 },
72
+ }
73
+ }
@@ -0,0 +1,89 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+
4
+ /**
5
+ * Discord のディープリンク。
6
+ *
7
+ * `~/.hermes/sessions/sessions.json` の各エントリは `session_id` と
8
+ * `origin`(platform / guild_id / thread_id / parent_chat_id / message_id)を持つので、
9
+ * 外部 API を叩かずにリンクを組み立てられる(実測で guild_id まで入っている)。
10
+ *
11
+ * kanban-sop の履歴 `metadata.session_anchor.chat_id` はスレッドIDなので、
12
+ * タスク → セッション → リンクの順で解決する。
13
+ */
14
+ export function createDiscord(cfg) {
15
+ const sessionsPath = cfg.sessionsFile ?? path.join(cfg.home, '.hermes', 'sessions', 'sessions.json')
16
+
17
+ /** @type {{mtimeMs: number, bySession: Map<string, {url: string, threadId: string, guildId: string, chatName: string, messageId: string|null}>}} */
18
+ let cache = { mtimeMs: -1, bySession: new Map() }
19
+
20
+ /** sessions.json を読み直す(mtime が変わったときだけ)。 */
21
+ function load() {
22
+ let st
23
+ try {
24
+ st = fs.statSync(sessionsPath)
25
+ } catch {
26
+ return cache.bySession
27
+ }
28
+ if (st.mtimeMs === cache.mtimeMs) return cache.bySession
29
+ let data
30
+ try {
31
+ data = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'))
32
+ } catch {
33
+ return cache.bySession
34
+ }
35
+ const bySession = new Map()
36
+ for (const [key, v] of Object.entries(data)) {
37
+ if (!v || typeof v !== 'object') continue
38
+ if (v.platform !== 'discord') continue
39
+ let origin = v.origin
40
+ if (typeof origin === 'string') {
41
+ try {
42
+ origin = JSON.parse(origin.replace(/'/g, '"'))
43
+ } catch {
44
+ origin = null
45
+ }
46
+ }
47
+ const guildId = origin?.guild_id ?? null
48
+ const threadId = origin?.thread_id ?? origin?.chat_id ?? null
49
+ const sessionId = v.session_id
50
+ if (!guildId || !threadId || !sessionId) continue
51
+ const messageId = origin?.message_id ?? null
52
+ const url = `https://discord.com/channels/${guildId}/${threadId}`
53
+ bySession.set(sessionId, {
54
+ url,
55
+ threadId,
56
+ guildId,
57
+ messageId,
58
+ chatName: origin?.chat_name ?? key,
59
+ chatType: v.chat_type ?? '',
60
+ })
61
+ }
62
+ cache = { mtimeMs: st.mtimeMs, bySession }
63
+ return bySession
64
+ }
65
+
66
+ /**
67
+ * セッションIDからリンクを引く。
68
+ * @param {string|null} sessionId セッションID
69
+ * @returns {object|null} リンク情報
70
+ */
71
+ function forSession(sessionId) {
72
+ if (!sessionId) return null
73
+ return load().get(String(sessionId)) ?? null
74
+ }
75
+
76
+ /**
77
+ * タスク(session_anchor)からリンクを引く。アンカーが無ければ null。
78
+ * @param {{session_id?: string}|null} anchor アンカー
79
+ * @returns {object|null} リンク情報
80
+ */
81
+ function forAnchor(anchor) {
82
+ if (!anchor?.session_id) return null
83
+ const hit = load().get(String(anchor.session_id))
84
+ if (!hit) return null
85
+ return { ...hit, messageId: anchor.message_id ?? hit.messageId ?? null }
86
+ }
87
+
88
+ return { forSession, forAnchor }
89
+ }
@@ -0,0 +1,211 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { execFile } from 'node:child_process'
4
+
5
+ /**
6
+ * タスクと Git の紐付け。
7
+ *
8
+ * データ源は `~/.hermes/state/kanban-sop/history.jsonl`(kanban-sop の done が
9
+ * `metadata.git` = {repo, branch, head, dirty, changed_count} と
10
+ * `metadata.session_anchor` = {chat_id, message_id, session_id, user} を残している)。
11
+ * ここに無いタスクは**推測で埋めない**(バッジを出さない)。
12
+ *
13
+ * git は `execFile` でシェルを介さず実行し、リポジトリも head も履歴の値しか使わない。
14
+ */
15
+
16
+ const MAX_PATCH_LINES = 200
17
+ const MAX_PATCH_BYTES = 60_000
18
+
19
+ export function createGitInfo(cfg) {
20
+ const historyPath = cfg.sopHistory ?? path.join(cfg.home, '.hermes', 'state', 'kanban-sop', 'history.jsonl')
21
+
22
+ /** @type {{mtimeMs: number, map: Map<string, {git: object, anchor: object|null}>}} */
23
+ let cache = { mtimeMs: -1, map: new Map() }
24
+ /** @type {Map<string, string>} */
25
+ const subjectCache = new Map()
26
+ /** @type {Map<string, {at: number, files: Array<{path: string, add: number, del: number}>, subject: string}>} */
27
+ const numstatCache = new Map()
28
+
29
+ /** 履歴を読み直す(mtime が変わったときだけ)。 */
30
+ function loadHistory() {
31
+ let st
32
+ try {
33
+ st = fs.statSync(historyPath)
34
+ } catch {
35
+ return new Map()
36
+ }
37
+ if (st.mtimeMs === cache.mtimeMs) return cache.map
38
+ const map = new Map()
39
+ let text = ''
40
+ try {
41
+ text = fs.readFileSync(historyPath, 'utf8')
42
+ } catch {
43
+ return cache.map
44
+ }
45
+ for (const line of text.split('\n')) {
46
+ if (!line.trim()) continue
47
+ let row
48
+ try {
49
+ row = JSON.parse(line)
50
+ } catch {
51
+ continue
52
+ }
53
+ if (row?.event !== 'done' || !row.task_id) continue
54
+ const md = row.metadata ?? {}
55
+ const git = md.git
56
+ if (!git?.repo) continue
57
+ map.set(String(row.task_id), { git, anchor: md.session_anchor ?? null, changedFiles: md.changed_files ?? [] })
58
+ }
59
+ cache = { mtimeMs: st.mtimeMs, map }
60
+ return map
61
+ }
62
+
63
+ /** タスクIDから履歴のエントリを引く。 */
64
+ function entryFor(taskId) {
65
+ const map = loadHistory()
66
+ return map.get(String(taskId)) ?? null
67
+ }
68
+
69
+ /** `git -C repo args...` を実行して stdout を返す(失敗は null)。 */
70
+ function git(repo, args, maxBuffer = 1_000_000) {
71
+ return new Promise((resolve) => {
72
+ execFile(
73
+ 'git',
74
+ ['-C', repo, ...args],
75
+ { timeout: 10_000, maxBuffer, env: { ...process.env, GIT_PAGER: 'cat', GIT_TERMINAL_PROMPT: '0' } },
76
+ (err, stdout) => resolve(err ? null : String(stdout ?? '')),
77
+ )
78
+ })
79
+ }
80
+
81
+ /** コミットの1行目サマリ(キャッシュ付き)。 */
82
+ async function subject(repo, head) {
83
+ if (!repo || !head) return ''
84
+ const key = `${repo}@${head}`
85
+ if (subjectCache.has(key)) return subjectCache.get(key)
86
+ const out = await git(repo, ['log', '-1', '--format=%s', head])
87
+ const s = (out ?? '').trim().split('\n')[0] ?? ''
88
+ subjectCache.set(key, s)
89
+ return s
90
+ }
91
+
92
+ /**
93
+ * タスクの git 情報(バッジ用)。履歴に無ければ null。
94
+ * @param {string} taskId タスクID
95
+ * @returns {Promise<{repo: string, branch: string, head: string, dirty: boolean, changedCount: number, subject: string} | null>} 情報
96
+ */
97
+ async function forTask(taskId) {
98
+ const e = entryFor(taskId)
99
+ if (!e) return null
100
+ const { repo, branch, head, dirty, changed_count: changedCount } = e.git
101
+ return {
102
+ repo,
103
+ branch: branch ?? '',
104
+ head: head ?? '',
105
+ dirty: Boolean(dirty),
106
+ changedCount: Number(changedCount ?? 0),
107
+ subject: await subject(repo, head),
108
+ }
109
+ }
110
+
111
+ /**
112
+ * コミットの差分サマリ(+add −del のファイル一覧)。
113
+ * @param {string} taskId タスクID
114
+ * @returns {Promise<object>} サマリ
115
+ */
116
+ async function diffSummary(taskId) {
117
+ const e = entryFor(taskId)
118
+ if (!e) {
119
+ return { ok: false, reason: 'このタスクの git 記録がありません(kanban-sop 経由でない可能性)' }
120
+ }
121
+ const { repo, head, dirty } = e.git
122
+ if (!head) return { ok: false, reason: 'コミットがまだありません' }
123
+ if (!fs.existsSync(repo)) return { ok: false, reason: `リポジトリが見つかりません: ${repo}` }
124
+
125
+ const key = `${repo}@${head}`
126
+ const cached = numstatCache.get(key)
127
+ let files = cached?.files
128
+ let subj = cached?.subject
129
+ if (!files) {
130
+ const out = await git(repo, ['show', '--numstat', '--format=%h%x09%s', head])
131
+ if (out == null) return { ok: false, reason: 'git show に失敗しました' }
132
+ const lines = out.split('\n')
133
+ const headLine = lines.shift() ?? ''
134
+ subj = headLine.split('\t')[1] ?? ''
135
+ files = []
136
+ for (const l of lines) {
137
+ if (!l.trim()) continue
138
+ const [add, del, file] = l.split('\t')
139
+ if (!file) continue
140
+ files.push({
141
+ path: file,
142
+ add: add === '-' ? 0 : Number(add) || 0,
143
+ del: del === '-' ? 0 : Number(del) || 0,
144
+ binary: add === '-' && del === '-',
145
+ })
146
+ }
147
+ numstatCache.set(key, { at: Date.now(), files, subject: subj })
148
+ if (subj) subjectCache.set(key, subj)
149
+ }
150
+ const total = files.reduce((a, f) => ({ add: a.add + f.add, del: a.del + f.del }), { add: 0, del: 0 })
151
+ return {
152
+ ok: true,
153
+ repo,
154
+ head,
155
+ subject: subj ?? '',
156
+ dirty: Boolean(dirty),
157
+ files: files.slice(0, 100),
158
+ total,
159
+ truncated: files.length > 100,
160
+ changedFilesFallback: e.changedFiles ?? [],
161
+ }
162
+ }
163
+
164
+ /**
165
+ * 1ファイルのパッチ(そのコミットに含まれるファイルだけ許可)。
166
+ * @param {string} taskId タスクID
167
+ * @param {string} file パス
168
+ * @returns {Promise<object>} パッチ
169
+ */
170
+ async function filePatch(taskId, file) {
171
+ const e = entryFor(taskId)
172
+ if (!e?.git?.head) return { ok: false, reason: 'コミットがありません' }
173
+ const { repo, head } = e.git
174
+ const key = `${repo}@${head}`
175
+ if (!numstatCache.has(key)) await diffSummary(taskId)
176
+ const files = numstatCache.get(key)?.files ?? []
177
+ const allowed = files.some((f) => f.path === file)
178
+ if (!allowed) return { ok: false, reason: 'そのコミットに含まれないファイルです' }
179
+
180
+ const patch = await git(repo, ['show', '--format=', '--no-color', head, '--', file], MAX_PATCH_BYTES * 4)
181
+ if (patch == null) return { ok: false, reason: 'git show に失敗しました' }
182
+ const lines = patch.split('\n')
183
+ const clipped = lines.slice(0, MAX_PATCH_LINES).join('\n')
184
+ const text = clipped.length > MAX_PATCH_BYTES ? clipped.slice(0, MAX_PATCH_BYTES) : clipped
185
+ return {
186
+ ok: true,
187
+ path: file,
188
+ text,
189
+ lines: lines.length,
190
+ truncated: lines.length > MAX_PATCH_LINES || text.length < patch.length,
191
+ }
192
+ }
193
+
194
+ /** 起動時にサマリを温める(初回リクエストの待ちを無くす)。 */
195
+ async function warm() {
196
+ const map = loadHistory()
197
+ const seen = new Set()
198
+ for (const [, e] of map) {
199
+ const head = e?.git?.head
200
+ const repo = e?.git?.repo
201
+ if (!head || !repo) continue
202
+ const key = `${repo}@${head}`
203
+ if (seen.has(key)) continue
204
+ seen.add(key)
205
+ if (seen.size > 200) break
206
+ await subject(repo, head)
207
+ }
208
+ }
209
+
210
+ return { forTask, diffSummary, filePatch, entryFor, warm }
211
+ }
@@ -0,0 +1,97 @@
1
+ import { ApiError } from './api-errors.js'
2
+
3
+ /**
4
+ * 既存 Hermes サーバ(127.0.0.1:9119)への薄いクライアント。
5
+ *
6
+ * セッショントークンは起動時に env か SPA の HTML から解決し、**端末には返さない**。
7
+ * ダッシュボードが再起動してトークンが変わった場合は 401 を見て 1 回だけ再解決する。
8
+ *
9
+ * 失敗は `ApiError('HERMES_TOKEN_MISSING')` で返す(日本語の `new Error('…')` を投げると
10
+ * `sendFailure` の `detail` として画面にそのまま出る=i18n の穴。`test/i18nLeak.test.js` が検出)。
11
+ *
12
+ * @param {object} cfg 設定
13
+ * @returns {object} クライアント
14
+ */
15
+ export function createHermesClient(cfg) {
16
+ let token = process.env.HERMES_DASHBOARD_SESSION_TOKEN || ''
17
+ let resolving = null
18
+
19
+ /** SPA の HTML からトークンを拾う(env 未設定時の唯一の経路)。 */
20
+ async function scrape() {
21
+ const res = await fetch(`${cfg.hermesBase}/`, { signal: AbortSignal.timeout(5000) })
22
+ const html = await res.text()
23
+ const m = /window\.__HERMES_SESSION_TOKEN__\s*=\s*"([^"]+)"/.exec(html)
24
+ if (!m) throw new ApiError('HERMES_TOKEN_MISSING', {}, 503)
25
+ return m[1]
26
+ }
27
+
28
+ /**
29
+ * トークンを保証する。
30
+ * @param {boolean} force 強制再解決
31
+ * @returns {Promise<string>} トークン
32
+ */
33
+ async function ensureToken(force = false) {
34
+ if (process.env.HERMES_DASHBOARD_SESSION_TOKEN) return process.env.HERMES_DASHBOARD_SESSION_TOKEN
35
+ if (token && !force) return token
36
+ if (!resolving) {
37
+ resolving = scrape()
38
+ .then((t) => {
39
+ token = t
40
+ return t
41
+ })
42
+ .finally(() => {
43
+ resolving = null
44
+ })
45
+ }
46
+ return resolving
47
+ }
48
+
49
+ /**
50
+ * REST を叩く。
51
+ * @param {string} pathname `/api/...`
52
+ * @param {{method?: string, body?: any, timeoutMs?: number}} [opts] オプション
53
+ * @returns {Promise<{status: number, data: any}>} 応答
54
+ */
55
+ async function call(pathname, opts = {}) {
56
+ const { method = 'GET', body, timeoutMs = 15000 } = opts
57
+ const run = async (tok) => {
58
+ const res = await fetch(`${cfg.hermesBase}${pathname}`, {
59
+ method,
60
+ headers: {
61
+ 'x-hermes-session-token': tok,
62
+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),
63
+ },
64
+ body: body !== undefined ? JSON.stringify(body) : undefined,
65
+ signal: AbortSignal.timeout(timeoutMs),
66
+ })
67
+ const text = await res.text()
68
+ let data = text
69
+ try {
70
+ data = text ? JSON.parse(text) : null
71
+ } catch {
72
+ /* テキストのまま */
73
+ }
74
+ return { status: res.status, data }
75
+ }
76
+ let out = await run(await ensureToken())
77
+ // gateway を再起動するとセッショントークンが回る。401/403 のどちらでも1回だけ取り直す
78
+ if (out.status === 401 || out.status === 403) out = await run(await ensureToken(true))
79
+ return out
80
+ }
81
+
82
+ /** WS の上流 URL(トークンはサーバ側で付ける)。 */
83
+ async function wsUrl(pathname = '/api/ws', { fresh = false } = {}) {
84
+ // fresh: gateway 再起動でトークンが回っても、次に繋ぐときに拾い直す
85
+ const tok = await ensureToken(fresh)
86
+ return `${cfg.hermesBase.replace(/^http/, 'ws')}${pathname}?token=${encodeURIComponent(tok)}`
87
+ }
88
+
89
+ return {
90
+ ensureToken,
91
+ call,
92
+ wsUrl,
93
+ get cached() {
94
+ return Boolean(token)
95
+ },
96
+ }
97
+ }