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,228 @@
1
+ import { getCapabilities, serviceCommands } from './capabilities.js'
2
+ import { normalizeCustom, normalizeOverrides, langOf, BUILTIN_IDS as CHAT_IDS } from './snippets.js'
3
+
4
+ /**
5
+ * 端末タブの定型コマンド(SPEC §3.3 / D12)。
6
+ *
7
+ * `run: true` のものだけ**長押しで実行**できる(タップは常に挿入のみ)。
8
+ * 破壊的・不可逆なもの(削除系・kill 系)は載せない。
9
+ *
10
+ * 個人環境のサービス名は**載せない**。再起動・状態確認は
11
+ * `capabilities.serviceManager`(launchd / systemd)で分岐する(SPEC §5.3)。
12
+ *
13
+ * ラベルと説明(note)は en / ja の両文面を持つが、**コマンド文字列(text)は英語 ASCII のみ**
14
+ * (シェルの echo も英語。G2①)。
15
+ */
16
+
17
+ /** @typedef {{id: string, label: string, text: string, hot?: boolean, run?: boolean, note?: string}} TermSnippet */
18
+
19
+ const DRAIN = '~/.hermes/.drain_request.json'
20
+ const L = '~/.hermes/logs'
21
+
22
+ /**
23
+ * 既定の並び(SPEC §3.3 の表と同じ順)。`<svc.*>` は Capability 依存。
24
+ * @type {Array<{id: string, hot?: boolean, run?: boolean, en: [string, string], ja: [string, string], text: string | ((svc: ReturnType<typeof serviceCommands>, manager: string) => string)}>}
25
+ */
26
+ const TABLE = [
27
+ // --- Hot 6(バーに出す)----------------------------------------------------
28
+ {
29
+ id: 't-pilot-restart',
30
+ hot: true,
31
+ run: true,
32
+ en: ['Restart Pilot', 'Restart Hermes Pilot bridge (4097)'],
33
+ ja: ['Pilot再起動', 'Hermes Pilot ブリッジ(4097)を再起動'],
34
+ text: (svc) => svc.restart,
35
+ },
36
+ {
37
+ id: 't-gw-status',
38
+ hot: true,
39
+ run: true,
40
+ en: ['GW Status', 'Hermes gateway status & PID'],
41
+ ja: ['GW状態', 'gateway の稼働状況・PID'],
42
+ text: 'hermes gateway status',
43
+ },
44
+ {
45
+ id: 't-gw-restart',
46
+ hot: true,
47
+ run: true,
48
+ en: ['Restart GW', 'Restart Hermes gateway'],
49
+ ja: ['GW再起動', 'gateway を再起動'],
50
+ text: 'hermes gateway restart',
51
+ },
52
+ {
53
+ id: 't-drain-restart',
54
+ hot: true,
55
+ run: true,
56
+ en: ['Clear Drain + GW', 'Remove drain marker & restart GW'],
57
+ ja: ['解除+GW再起動', 'ドレイン解除+gateway再起動'],
58
+ text: `rm -f ${DRAIN} && hermes gateway restart`,
59
+ },
60
+ {
61
+ id: 't-kanban',
62
+ hot: true,
63
+ run: true,
64
+ en: ['Kanban Active', 'List kanban tasks'],
65
+ ja: ['カンバン一覧', 'カンバンのタスク一覧'],
66
+ text: 'hermes kanban list',
67
+ },
68
+ {
69
+ id: 't-gw-log',
70
+ hot: true,
71
+ run: true,
72
+ en: ['GW Log', `Last 80 lines of gateway.log`],
73
+ ja: ['GWログ', 'gateway.log の末尾80行'],
74
+ text: `tail -n 80 ${L}/gateway.log`,
75
+ },
76
+
77
+ // --- シート(10個)----------------------------------------------------------
78
+ {
79
+ id: 't-pilot-status',
80
+ run: true,
81
+ en: ['Pilot Status', 'Service status of Hermes Pilot'],
82
+ ja: ['Pilot状態', 'Hermes Pilot のサービス状態'],
83
+ text: (svc) => svc.status,
84
+ },
85
+ {
86
+ id: 't-pair-qr',
87
+ run: true,
88
+ en: ['Pairing QR', 'Show pairing URL & QR in terminal'],
89
+ ja: ['ペアリングQR', 'ペアリングURLとQRを表示'],
90
+ // 未公開 npm パッケージを前提にしない(SPEC-CATALOG-ADMISSION D59)。リポジトリ/プラグイン
91
+ // ディレクトリを cwd にして実行する。`npm link` 済みなら `hermes-pilot qr` でもよい。
92
+ text: 'node bin/hermes-pilot.mjs qr',
93
+ },
94
+ {
95
+ id: 't-verify',
96
+ run: true,
97
+ en: ['Run Verify', 'Run tests, PWA check, and build'],
98
+ ja: ['Verify実行', 'テスト・PWA検査・ビルドを一括実行'],
99
+ text: 'npm run verify',
100
+ },
101
+ {
102
+ id: 't-deploy',
103
+ run: true,
104
+ en: ['Deploy Web', 'Zero-downtime build & swap dist'],
105
+ ja: ['Webデプロイ', '無停止ビルド&dist入れ替え'],
106
+ text: 'npm run deploy',
107
+ },
108
+ {
109
+ id: 't-drain-clear',
110
+ run: true,
111
+ en: ['Clear Drain', 'Remove drain marker only'],
112
+ ja: ['ドレイン解除', 'ドレインマーカーのみ削除'],
113
+ text: `rm -f ${DRAIN} && echo "drain marker removed"`,
114
+ },
115
+ {
116
+ id: 't-list',
117
+ run: true,
118
+ en: ['Services', 'List Hermes background services'],
119
+ ja: ['サービス一覧', 'hermes 系サービス一覧'],
120
+ text: (svc) => svc.list,
121
+ },
122
+ {
123
+ id: 't-errors',
124
+ run: true,
125
+ en: ['Error Log', 'Last 80 lines of errors.log'],
126
+ ja: ['エラーログ', 'errors.log の末尾80行'],
127
+ text: `tail -n 80 ${L}/errors.log`,
128
+ },
129
+ {
130
+ id: 't-health',
131
+ run: true,
132
+ en: ['Reachability', 'Check HTTP 200 on 9119 & 4097'],
133
+ ja: ['疎通確認', '9119 と 4097 の HTTP 応答確認'],
134
+ text:
135
+ 'curl -s -o /dev/null -w "dashboard %{http_code}\\n" http://127.0.0.1:9119/; ' +
136
+ 'curl -s -o /dev/null -w "pilot %{http_code}\\n" http://127.0.0.1:4097/healthz',
137
+ },
138
+ {
139
+ id: 't-port',
140
+ run: true,
141
+ en: ['Ports', 'Check listening processes on 9119 & 4097'],
142
+ ja: ['ポート確認', '9119 と 4097 の LISTEN 確認'],
143
+ text: 'lsof -nP -iTCP:9119 -sTCP:LISTEN; lsof -nP -iTCP:4097 -sTCP:LISTEN',
144
+ },
145
+ {
146
+ id: 't-git',
147
+ run: true,
148
+ en: ['Git State', 'Short status & last 3 commits'],
149
+ ja: ['git状態', '差分と直近3コミット'],
150
+ text: 'git status --short && git log --oneline -3',
151
+ },
152
+ ]
153
+
154
+ /** 端末スニペットの組み込み ID(overrides の検証に使う)。 */
155
+ export const TERM_BUILTIN_IDS = TABLE.map((s) => s.id)
156
+
157
+ /**
158
+ * 端末スニペットを組み立てる(上書きなしの素の一覧)。
159
+ * @param {{serviceManager?: string, pilotServiceUnit?: string}} [caps] Capability(既定は起動時検出)
160
+ * @param {'en'|'ja'} [lang] 表示言語(既定 en・SPEC D5)
161
+ * @returns {TermSnippet[]} スニペット
162
+ */
163
+ export function buildTermSnippets(caps = getCapabilities(), lang = 'en') {
164
+ const svc = serviceCommands(caps)
165
+ const manager = caps?.serviceManager === 'launchd' ? 'launchd' : 'systemd'
166
+ const l = langOf(lang)
167
+ return TABLE.map((s) => {
168
+ const [label, note] = l === 'ja' ? s.ja : s.en
169
+ return {
170
+ id: s.id,
171
+ label,
172
+ text: typeof s.text === 'function' ? s.text(svc, manager) : s.text,
173
+ hot: Boolean(s.hot),
174
+ run: s.run !== false,
175
+ note,
176
+ }
177
+ })
178
+ }
179
+
180
+ /**
181
+ * UI 向け一覧(`hidden` も含む・設定画面用)。
182
+ * @param {object} [caps] Capability(既定は起動時検出)
183
+ * @param {'en'|'ja'} [lang] 表示言語(既定 en)
184
+ * @param {Record<string, object>} [overrides] 組み込みの上書き
185
+ * @param {Array<object>} [custom] ユーザー定義
186
+ * @returns {Array<object>} スニペット
187
+ */
188
+ export function allTermSnippets(caps, lang = 'en', overrides = {}, custom = []) {
189
+ const ov = normalizeOverrides(overrides, TERM_BUILTIN_IDS)
190
+ const builtin = buildTermSnippets(caps, lang).map((s) => {
191
+ const o = ov[s.id] ?? {}
192
+ return {
193
+ ...s,
194
+ hot: typeof o.hot === 'boolean' ? o.hot : s.hot,
195
+ hidden: o.hidden === true,
196
+ custom: false,
197
+ }
198
+ })
199
+ const user = normalizeCustom(custom, { withRun: true }).map((s) => ({
200
+ id: s.id,
201
+ label: s.label,
202
+ text: s.text,
203
+ hot: Boolean(s.hot),
204
+ run: s.run !== false,
205
+ note: s.note ?? '',
206
+ hidden: s.hidden === true,
207
+ custom: true,
208
+ }))
209
+ return [...builtin, ...user]
210
+ }
211
+
212
+ /**
213
+ * 端末画面向け一覧(`hidden` を除く)。
214
+ * @param {object} [caps] Capability
215
+ * @param {'en'|'ja'} [lang] 表示言語
216
+ * @param {Record<string, object>} [overrides] 組み込みの上書き
217
+ * @param {Array<object>} [custom] ユーザー定義
218
+ * @returns {Array<object>} スニペット
219
+ */
220
+ export function listTermSnippets(caps, lang = 'en', overrides = {}, custom = []) {
221
+ return allTermSnippets(caps, lang, overrides, custom).filter((s) => !s.hidden)
222
+ }
223
+
224
+ /** 既定 Capability・既定言語(en)で組み立てた一覧(後方互換・テスト用)。 */
225
+ export const TERM_SNIPPETS = buildTermSnippets()
226
+
227
+ /** 端末側でも「チャットの ID を上書きしない」ことを明示(テスト用)。 */
228
+ export const CHAT_BUILTIN_IDS = CHAT_IDS
@@ -0,0 +1,231 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { DatabaseSync } from 'node:sqlite'
4
+
5
+ /** 既定の取得件数(1ターンでツールを多用するとすぐ上限に達するため大きめ)。 */
6
+ const DEFAULT_LIMIT = 200
7
+ /** 1回の取得で返す最大件数。 */
8
+ const MAX_LIMIT = 1000
9
+ /** `tool_calls` から引数を復元するとき、1引数あたり保持する最大文字数。 */
10
+ const MAX_ARG_CHARS = 500
11
+ /** 引数マップ構築でさかのぼる assistant 行の上限(暴走防止)。 */
12
+ const MAX_CALL_ROWS = 800
13
+ /** 表示に使う引数キー(機密を丸ごと載せないための許可リスト)。 */
14
+ const ARG_KEYS = ['command', 'path', 'file_path', 'query', 'goal', 'code', 'url', 'pattern', 'title', 'text', 'task_id']
15
+
16
+ /** 引数の文字列を最大長へ切り詰める(空白潰しは表示側で行う)。 */
17
+ function clip(v) {
18
+ const s = String(v ?? '')
19
+ return s.length > MAX_ARG_CHARS ? s.slice(0, MAX_ARG_CHARS) : s
20
+ }
21
+
22
+ /** 表示用の軽量引数オブジェクトを作る(許可キーのみ・文字列のみ)。 */
23
+ function summarizeToolArgs(args) {
24
+ if (!args || typeof args !== 'object' || Array.isArray(args)) return null
25
+ const out = {}
26
+ for (const k of ARG_KEYS) {
27
+ const v = args[k]
28
+ if (typeof v === 'string' && v.trim()) out[k] = clip(v)
29
+ }
30
+ return Object.keys(out).length ? out : null
31
+ }
32
+
33
+ /** `arguments` は JSON 文字列のこともオブジェクトのこともある。 */
34
+ function normalizeArgs(raw) {
35
+ if (raw && typeof raw === 'object') return raw
36
+ if (typeof raw !== 'string' || !raw.trim()) return null
37
+ try {
38
+ const parsed = JSON.parse(raw)
39
+ return parsed && typeof parsed === 'object' ? parsed : null
40
+ } catch {
41
+ return null
42
+ }
43
+ }
44
+
45
+ /**
46
+ * `tool_calls` 列の JSON を `[{ id, name, args }]` へ正規化する。
47
+ * 配列形式(OpenAI 互換 `[{id, function:{name, arguments}}]`)、
48
+ * 単一オブジェクト形式、`{ <callId>: { name, args } }` 形式のいずれも受ける。
49
+ */
50
+ export function parseToolCalls(raw) {
51
+ const out = []
52
+ if (!raw) return out
53
+ let data = raw
54
+ if (typeof raw === 'string') {
55
+ try {
56
+ data = JSON.parse(raw)
57
+ } catch {
58
+ return out
59
+ }
60
+ }
61
+ if (!data || typeof data !== 'object') return out
62
+ const push = (id, name, args) => {
63
+ const callId = String(id ?? '')
64
+ const toolName = typeof name === 'string' ? name : ''
65
+ const parsedArgs = normalizeArgs(args)
66
+ if (callId && (toolName || parsedArgs)) out.push({ id: callId, name: toolName, args: parsedArgs })
67
+ }
68
+ const fromEntry = (item, fallbackId) => {
69
+ if (!item || typeof item !== 'object') return
70
+ const fn = item.function && typeof item.function === 'object' ? item.function : null
71
+ push(
72
+ item.id ?? item.tool_call_id ?? item.call_id ?? fallbackId,
73
+ fn?.name ?? item.name ?? item.tool_name,
74
+ fn?.arguments ?? item.arguments ?? item.args ?? item.input,
75
+ )
76
+ }
77
+ if (Array.isArray(data)) {
78
+ for (const item of data) fromEntry(item, null)
79
+ return out
80
+ }
81
+ if (data.function || data.name || data.tool_name) {
82
+ fromEntry(data, data.id ?? data.tool_call_id ?? data.call_id)
83
+ return out
84
+ }
85
+ for (const [k, v] of Object.entries(data)) fromEntry(v, k)
86
+ return out
87
+ }
88
+
89
+ /**
90
+ * セッションの読み取り専用トランスクリプト。
91
+ *
92
+ * カンバンの作業ログ(`local-…`)は `session.resume` を Hermes が拒否する
93
+ * (code 4132: 盤面が観測できない書き手を作らないため)。そこで state.db から
94
+ * 直接、表示用の抜粋だけを読む。**書き込みはしない**。
95
+ */
96
+ export function createTranscript(cfg) {
97
+ const dbPath = cfg.stateDb ?? path.join(cfg.home ?? '', '.hermes', 'state.db')
98
+
99
+ /** messages テーブルにある列名の集合(旧スキーマ後方互換のため probe する)。 */
100
+ function columnsOf(db) {
101
+ const names = new Set()
102
+ try {
103
+ for (const r of db.prepare("SELECT name FROM pragma_table_info('messages')").all()) names.add(String(r.name))
104
+ } catch {
105
+ /* pragma が引けない DB は列なし扱い */
106
+ }
107
+ return names
108
+ }
109
+
110
+ /**
111
+ * `tool_call_id -> { name, args }` を `tool_calls` から組み立てる。
112
+ * 取得範囲の末尾(page[0].id)以前の assistant 行だけを見る。
113
+ */
114
+ function buildCallMap(db, sessionId, maxId) {
115
+ const map = new Map()
116
+ if (!Number.isFinite(maxId) || maxId <= 0) return map
117
+ let rows = []
118
+ try {
119
+ rows = db
120
+ .prepare(
121
+ `SELECT id, tool_calls
122
+ FROM messages
123
+ WHERE session_id = ?
124
+ AND role = 'assistant'
125
+ AND tool_calls IS NOT NULL
126
+ AND length(COALESCE(tool_calls, '')) > 2
127
+ AND id <= ?
128
+ ORDER BY id DESC
129
+ LIMIT ?`,
130
+ )
131
+ .all(sessionId, maxId, MAX_CALL_ROWS)
132
+ } catch {
133
+ return map
134
+ }
135
+ for (const r of rows) {
136
+ for (const call of parseToolCalls(r.tool_calls)) {
137
+ if (!map.has(call.id)) map.set(call.id, call)
138
+ }
139
+ }
140
+ return map
141
+ }
142
+
143
+ /**
144
+ * 1セッションのメッセージを古い順に返す。
145
+ * @param {string} sessionId セッションID
146
+ * @param {{limit?: number, before?: number, includeTools?: boolean, dbPath?: string}} [opts] 条件(before はメッセージID)
147
+ * @returns {{ok: boolean, sessionId: string, messages: Array<object>, oldestId: number|null, hasMore: boolean, reason?: string}} 結果
148
+ */
149
+ function read(sessionId, opts = {}) {
150
+ const id = String(sessionId ?? '').slice(0, 128)
151
+ if (!id) return { ok: false, sessionId: id, messages: [], oldestId: null, hasMore: false, reason: 'session_id が必要です' }
152
+ // プロファイル横断表示のため、呼び出し側が対象 DB を指定できる
153
+ const effectivePath = opts.dbPath || dbPath
154
+ if (!fs.existsSync(effectivePath))
155
+ return { ok: false, sessionId: id, messages: [], oldestId: null, hasMore: false, reason: 'state.db が見つかりません' }
156
+ const asked = Number(opts.limit)
157
+ const limit = Number.isFinite(asked) ? Math.min(Math.max(Math.trunc(asked), 1), MAX_LIMIT) : DEFAULT_LIMIT
158
+ const before = Number(opts.before ?? 0) || 0
159
+
160
+ let db
161
+ try {
162
+ db = new DatabaseSync(effectivePath, { readOnly: true })
163
+ let title = ''
164
+ try {
165
+ const t = db.prepare('SELECT title, display_name FROM sessions WHERE id = ?').get(id)
166
+ title = String(t?.title || t?.display_name || '')
167
+ } catch {
168
+ title = ''
169
+ }
170
+ const cols = columnsOf(db)
171
+ const hasToolName = cols.has('tool_name')
172
+ const hasToolCallId = cols.has('tool_call_id')
173
+ const hasToolCalls = cols.has('tool_calls')
174
+ const roles = opts.includeTools ? "('user', 'assistant', 'tool')" : "('user', 'assistant')"
175
+ const selectCols = [
176
+ 'id',
177
+ 'role',
178
+ 'content',
179
+ 'timestamp',
180
+ hasToolName ? 'tool_name' : 'NULL AS tool_name',
181
+ hasToolCallId ? 'tool_call_id' : 'NULL AS tool_call_id',
182
+ ].join(', ')
183
+ // hasMore を厳密にするため 1 件多く取り、余りがあるかで判定する
184
+ const rows = db
185
+ .prepare(
186
+ `SELECT ${selectCols}
187
+ FROM messages
188
+ WHERE session_id = ?
189
+ AND role IN ${roles}
190
+ ${opts.includeTools ? '' : 'AND COALESCE(active, 1) = 1'}
191
+ AND length(COALESCE(content, '')) > 0
192
+ ${before ? 'AND id < ?' : ''}
193
+ ORDER BY id DESC
194
+ LIMIT ?`,
195
+ )
196
+ .all(...(before ? [id, before, limit + 1] : [id, limit + 1]))
197
+ const hasMore = rows.length > limit
198
+ const page = hasMore ? rows.slice(0, limit) : rows
199
+ const callMap = hasToolCalls && opts.includeTools ? buildCallMap(db, id, Number(page[0]?.id)) : new Map()
200
+ const messages = page
201
+ .map((r) => {
202
+ const isTool = r.role === 'tool'
203
+ const callId = String(r.tool_call_id ?? '')
204
+ const call = isTool && callId ? callMap.get(callId) : null
205
+ const msg = {
206
+ id: Number(r.id),
207
+ role: r.role,
208
+ toolName: isTool ? r.tool_name || call?.name || null : null,
209
+ toolArgs: isTool ? summarizeToolArgs(call?.args) : null,
210
+ text: String(r.content ?? '').slice(0, isTool ? 400 : 8000),
211
+ at: Math.round(Number(r.timestamp ?? 0) * 1000),
212
+ }
213
+ if (callId) msg.toolCallId = callId
214
+ return msg
215
+ })
216
+ .reverse()
217
+ // messages[0] は最古(reverse 後)— ページングの `before` にそのまま渡せる
218
+ return { ok: true, sessionId: id, title, messages, oldestId: messages[0]?.id ?? null, hasMore }
219
+ } catch (e) {
220
+ return { ok: false, sessionId: id, messages: [], oldestId: null, hasMore: false, reason: `読み取りに失敗しました: ${e.message}` }
221
+ } finally {
222
+ try {
223
+ db?.close()
224
+ } catch {
225
+ /* noop */
226
+ }
227
+ }
228
+ }
229
+
230
+ return { read }
231
+ }