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.
- package/LICENSE +21 -0
- package/README.ja.md +419 -0
- package/README.md +428 -2
- package/__init__.py +15 -0
- package/apps/bridge/src/api-errors.js +165 -0
- package/apps/bridge/src/architect.js +1298 -0
- package/apps/bridge/src/auth.js +202 -0
- package/apps/bridge/src/capabilities.js +256 -0
- package/apps/bridge/src/capture.js +145 -0
- package/apps/bridge/src/chat-profile.js +95 -0
- package/apps/bridge/src/config.js +73 -0
- package/apps/bridge/src/discord.js +89 -0
- package/apps/bridge/src/gitinfo.js +211 -0
- package/apps/bridge/src/hermes.js +97 -0
- package/apps/bridge/src/inbox.js +347 -0
- package/apps/bridge/src/kanban.js +361 -0
- package/apps/bridge/src/lang.js +60 -0
- package/apps/bridge/src/live.js +285 -0
- package/apps/bridge/src/memos.js +150 -0
- package/apps/bridge/src/ops.js +201 -0
- package/apps/bridge/src/pair-codes.js +125 -0
- package/apps/bridge/src/pipeline-optimizer.js +513 -0
- package/apps/bridge/src/pipeline-watcher.js +1022 -0
- package/apps/bridge/src/qr.js +808 -0
- package/apps/bridge/src/repos.js +544 -0
- package/apps/bridge/src/review-watcher.js +271 -0
- package/apps/bridge/src/review.js +1749 -0
- package/apps/bridge/src/search.js +162 -0
- package/apps/bridge/src/server.js +1745 -0
- package/apps/bridge/src/snippets.js +373 -0
- package/apps/bridge/src/specs.js +806 -0
- package/apps/bridge/src/tail.js +28 -0
- package/apps/bridge/src/telemetry.js +667 -0
- package/apps/bridge/src/term-snippets.js +228 -0
- package/apps/bridge/src/transcript.js +231 -0
- package/apps/bridge/src/usage.js +294 -0
- package/apps/bridge/src/workerFeed.js +72 -0
- package/apps/dashboard/index.js +2014 -0
- package/apps/dashboard/manifest.json +14 -0
- package/apps/dashboard/pilot_dashboard.py +1466 -0
- package/apps/dashboard/plugin_api.py +237 -0
- package/apps/dashboard/plugin_init.py +15 -0
- package/apps/dashboard/style.css +928 -0
- package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
- package/apps/web/dist/assets/TermPane-q4f5Zu0I.js +12 -0
- package/apps/web/dist/assets/index-BzUof8lw.js +94 -0
- package/apps/web/dist/assets/index-DwZdbPU7.css +1 -0
- package/apps/web/dist/favicon.ico +0 -0
- package/apps/web/dist/icon-180-v6.png +0 -0
- package/apps/web/dist/icon-192-v6.png +0 -0
- package/apps/web/dist/icon-512-v6.png +0 -0
- package/apps/web/dist/icon-maskable-192-v6.png +0 -0
- package/apps/web/dist/icon-maskable-512-v6.png +0 -0
- package/apps/web/dist/icon-v6.svg +15 -0
- package/apps/web/dist/index.html +21 -0
- package/apps/web/dist/manifest.webmanifest +49 -0
- package/apps/web/dist/sw.js +69 -0
- package/bin/hermes-pilot.mjs +964 -0
- package/dashboard/dist/index.js +2014 -0
- package/dashboard/dist/style.css +928 -0
- package/dashboard/manifest.json +14 -0
- package/dashboard/pilot_dashboard.py +1466 -0
- package/dashboard/plugin_api.py +237 -0
- package/package.json +75 -4
- package/plugin.json +70 -0
- package/plugin.yaml +4 -0
- package/scripts/deploy.mjs +58 -0
- package/scripts/migrate-to-hermes-pilot.mjs +472 -0
- package/scripts/postinstall.mjs +32 -0
- package/scripts/sync-dashboard.mjs +98 -0
- package/skills/annotation/SKILL.md +138 -0
- package/skills/quick-review/SKILL.md +200 -0
- package/skills/quick-review/assets/sheet-template.html +175 -0
- package/skills/spec-architect/SKILL.md +226 -0
|
@@ -0,0 +1,1745 @@
|
|
|
1
|
+
import http from 'node:http'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { WebSocketServer, WebSocket } from 'ws'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
import { loadConfig, VERSION } from './config.js'
|
|
7
|
+
import { createAuth, isAllowedWsOrigin } from './auth.js'
|
|
8
|
+
import { createHermesClient } from './hermes.js'
|
|
9
|
+
import { createKanban } from './kanban.js'
|
|
10
|
+
import { createReview, injectReviewBridge, reviewSheetHeaders, reviewViewHeaders, reviewViewHtml } from './review.js'
|
|
11
|
+
import { createReviewWatcher } from './review-watcher.js'
|
|
12
|
+
import { createPipelineWatcher, readPipelineReports } from './pipeline-watcher.js'
|
|
13
|
+
import { createOps } from './ops.js'
|
|
14
|
+
import {
|
|
15
|
+
CUSTOM_MAX,
|
|
16
|
+
HOT_LIMIT,
|
|
17
|
+
allSnippets,
|
|
18
|
+
readSnippetStore,
|
|
19
|
+
writeSnippetStore,
|
|
20
|
+
BUILTIN_IDS,
|
|
21
|
+
} from './snippets.js'
|
|
22
|
+
import { allTermSnippets, TERM_BUILTIN_IDS } from './term-snippets.js'
|
|
23
|
+
import { createGitInfo } from './gitinfo.js'
|
|
24
|
+
import { createDiscord } from './discord.js'
|
|
25
|
+
import { createSearch } from './search.js'
|
|
26
|
+
import { createTranscript } from './transcript.js'
|
|
27
|
+
import { createWorkerFeed } from './workerFeed.js'
|
|
28
|
+
import { createCapture } from './capture.js'
|
|
29
|
+
import { createUsage } from './usage.js'
|
|
30
|
+
import { createTelemetry } from './telemetry.js'
|
|
31
|
+
import { createLive } from './live.js'
|
|
32
|
+
import { createInbox } from './inbox.js'
|
|
33
|
+
import { createRepos, normalizePath } from './repos.js'
|
|
34
|
+
import { createSpecs, listSpecs, readSpecContent } from './specs.js'
|
|
35
|
+
import { createArchitect } from './architect.js'
|
|
36
|
+
import {
|
|
37
|
+
DEFAULT_SKILLS_SRC,
|
|
38
|
+
getOptimizeStatus,
|
|
39
|
+
optimizeAgentSkills,
|
|
40
|
+
optimizeHermesSoul,
|
|
41
|
+
optimizeProfileSouls,
|
|
42
|
+
} from './pipeline-optimizer.js'
|
|
43
|
+
import { createPairCodes } from './pair-codes.js'
|
|
44
|
+
import { createMemosStore } from './memos.js'
|
|
45
|
+
import { getCapabilities } from './capabilities.js'
|
|
46
|
+
import { errorBody } from './api-errors.js'
|
|
47
|
+
import { resolveLang } from './lang.js'
|
|
48
|
+
import { checkFrame, rejectionFrame } from './chat-profile.js'
|
|
49
|
+
import { readTailText } from './tail.js'
|
|
50
|
+
import { collectPairing, qrPng, qrRows, qrSvg, tailscaleCommandCandidates } from './qr.js'
|
|
51
|
+
|
|
52
|
+
const require = createRequire(import.meta.url)
|
|
53
|
+
const pty = safeRequire('node-pty')
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* `tailscale status --json` を 1 回だけ叩いて 60 秒キャッシュする。
|
|
57
|
+
*
|
|
58
|
+
* Tailscale が無い・ログインしていない環境では素直に null(LAN 候補だけ出す)。
|
|
59
|
+
* ここで失敗してもペアリングは成立させる(QR が出ない理由にしない)。
|
|
60
|
+
* @returns {Promise<string|null>} 生の JSON 文字列
|
|
61
|
+
*/
|
|
62
|
+
let tailscaleCache = { at: 0, json: null }
|
|
63
|
+
async function tailscaleStatusJson() {
|
|
64
|
+
const now = Date.now()
|
|
65
|
+
if (now - tailscaleCache.at < 60_000) return tailscaleCache.json
|
|
66
|
+
const { execFile } = await import('node:child_process')
|
|
67
|
+
let json = null
|
|
68
|
+
for (const bin of tailscaleCommandCandidates()) {
|
|
69
|
+
json = await new Promise((resolve) => {
|
|
70
|
+
try {
|
|
71
|
+
execFile(bin, ['status', '--json'], { timeout: 1500, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) =>
|
|
72
|
+
resolve(err ? null : String(stdout)),
|
|
73
|
+
)
|
|
74
|
+
} catch {
|
|
75
|
+
resolve(null)
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
if (json) break
|
|
79
|
+
}
|
|
80
|
+
tailscaleCache = { at: now, json }
|
|
81
|
+
return json
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* node-pty はネイティブモジュール。無くても他は動かす。
|
|
86
|
+
* @param {string} name モジュール名
|
|
87
|
+
* @returns {any|null} モジュール
|
|
88
|
+
*/
|
|
89
|
+
function safeRequire(name) {
|
|
90
|
+
try {
|
|
91
|
+
return require(name)
|
|
92
|
+
} catch {
|
|
93
|
+
return null
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const cfg = loadConfig()
|
|
98
|
+
const capabilities = getCapabilities()
|
|
99
|
+
// ワンタイム・ペアリングコード(QR を短くするため。SPEC §8.2 の one-time token)
|
|
100
|
+
const pairCodes = createPairCodes(cfg)
|
|
101
|
+
const memos = createMemosStore(cfg.dataDir)
|
|
102
|
+
const auth = createAuth(cfg, { pairCodes })
|
|
103
|
+
const hermes = createHermesClient(cfg)
|
|
104
|
+
const kanban = createKanban(cfg)
|
|
105
|
+
// リポジトリ(作業ディレクトリ)↔ ボード。一覧は repos.json + 1 階層スキャン
|
|
106
|
+
// + ボードの default_workdir + 直近セッション cwd の統合(SPEC §5.1)
|
|
107
|
+
const repos = createRepos(cfg, { boards: () => kanban.boards() })
|
|
108
|
+
// Spec Launchpad(`docs/SPEC-*.md` → バッチ → カンバン一括起票)。SPEC §5.4 / D15④
|
|
109
|
+
const specs = createSpecs(cfg, { tasks: (board) => kanban.tasks(board, { limit: 200 }), listSpecs })
|
|
110
|
+
// Architect(仕様の種 → SPEC / A2B)。ランナーは Hermes Native(`hermes kanban create`)だけ。
|
|
111
|
+
const architect = createArchitect(cfg, {
|
|
112
|
+
listSpecs,
|
|
113
|
+
readTasks: (board) => kanban.tasks(board, { limit: 200 }),
|
|
114
|
+
})
|
|
115
|
+
const review = createReview(cfg, { targets: () => repos.targets() })
|
|
116
|
+
// 完了・ブロックの記録はブリッジ内蔵(D7)。外部 cron は要らない。
|
|
117
|
+
const reviewWatcher = createReviewWatcher(cfg, { review })
|
|
118
|
+
const ops = createOps(cfg, hermes, auth, { kanban })
|
|
119
|
+
const gitinfo = createGitInfo(cfg)
|
|
120
|
+
// 使用量(コスト・トークン・API コール)はテレメトリとパイプライン報告の双方が使う(V7-2)。
|
|
121
|
+
const usage = createUsage(cfg)
|
|
122
|
+
// パイプライン完走レポート(D20 / D21)。Spec ラン/ボードウェーブの収束を監視する。
|
|
123
|
+
// `usage` を渡すと報告に Spec スコープの API コール数・トークン数が入る。
|
|
124
|
+
const pipelineWatcher = createPipelineWatcher(cfg, { gitinfo, usage })
|
|
125
|
+
const discord = createDiscord(cfg)
|
|
126
|
+
const search = createSearch(cfg)
|
|
127
|
+
const transcript = createTranscript(cfg)
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* プロファイル一覧(name と state.db の在処)。30秒キャッシュ。
|
|
131
|
+
* チャット一覧をプロジェクト横断にするために使う。
|
|
132
|
+
*/
|
|
133
|
+
let profilesCache = { at: 0, list: [] }
|
|
134
|
+
async function listProfiles() {
|
|
135
|
+
if (Date.now() - profilesCache.at < 30_000 && profilesCache.list.length) return profilesCache.list
|
|
136
|
+
const r = await hermes.call('/api/profiles', { timeoutMs: 8000 })
|
|
137
|
+
const list = r.status === 200 ? (r.data?.profiles ?? []) : []
|
|
138
|
+
if (list.length) profilesCache = { at: Date.now(), list }
|
|
139
|
+
return list
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** プロファイル名 → state.db のパス(不明なら既定)。 */
|
|
143
|
+
function stateDbFor(profiles, name) {
|
|
144
|
+
const hit = profiles.find((p) => p.name === name)
|
|
145
|
+
if (!hit?.path) return cfg.stateDb
|
|
146
|
+
return path.join(hit.path, 'state.db')
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 全プロファイルの state.db 一覧(重複除去・default フォールバック付き)。 */
|
|
150
|
+
async function listStateDbs() {
|
|
151
|
+
const profiles = await listProfiles()
|
|
152
|
+
const out = []
|
|
153
|
+
const seen = new Set()
|
|
154
|
+
for (const p of profiles) {
|
|
155
|
+
if (!p?.name) continue
|
|
156
|
+
const dbPath = p.path ? path.join(p.path, 'state.db') : cfg.stateDb
|
|
157
|
+
if (seen.has(dbPath)) continue
|
|
158
|
+
seen.add(dbPath)
|
|
159
|
+
out.push({ profile: p.name, path: dbPath })
|
|
160
|
+
}
|
|
161
|
+
if (!seen.has(cfg.stateDb)) {
|
|
162
|
+
out.unshift({ profile: 'default', path: cfg.stateDb })
|
|
163
|
+
}
|
|
164
|
+
return out
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 実行ワーカーのトランスクリプトを読む(レビュー詳細とタスク詳細で共通)。
|
|
169
|
+
*
|
|
170
|
+
* セッションの DB はイベントが記録した実パス(`info.db`)を最優先。記録が無い/空でも
|
|
171
|
+
* `/api/boards/:slug/tasks/:id` は任意のボードを扱うので、全プロファイルの state.db を
|
|
172
|
+
* 横断して messages が 1 件以上あった DB を採用する(選択ロジックは `workerFeed.js`)。
|
|
173
|
+
*/
|
|
174
|
+
const readWorkerFeed = createWorkerFeed({
|
|
175
|
+
listStateDbs,
|
|
176
|
+
read: (sessionId, opts) => transcript.read(sessionId, opts),
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
const capture = createCapture(cfg)
|
|
180
|
+
// Zero-Typing 実行サマリ(完了レシート・SPEC-PILOT-V5 §3.3 ③ / D26③)。
|
|
181
|
+
// usage / 完走レポート / カンバン / audit.jsonl を読むだけで、書き込みはしない。
|
|
182
|
+
const telemetry = createTelemetry(cfg, {
|
|
183
|
+
usage,
|
|
184
|
+
reports: (opts) => readPipelineReports(cfg.reviewDir, opts),
|
|
185
|
+
tasks: (board) => kanban.tasks(board, { limit: 200 }),
|
|
186
|
+
})
|
|
187
|
+
const live = createLive(cfg, kanban)
|
|
188
|
+
const inbox = createInbox(cfg, kanban)
|
|
189
|
+
// 起動時にコミットサマリを温める(初回のタスク一覧を待たせない)
|
|
190
|
+
gitinfo.warm().catch(() => {})
|
|
191
|
+
|
|
192
|
+
// スニペット(組み込みの Hot/Hidden 上書き + ユーザー定義を小さな JSON に保存する・SPEC §3.4)
|
|
193
|
+
const SNIPPET_STORE = {
|
|
194
|
+
chat: { file: path.join(cfg.dataDir, 'snippets.json'), ids: BUILTIN_IDS, withRun: false },
|
|
195
|
+
term: { file: path.join(cfg.dataDir, 'term-snippets.json'), ids: TERM_BUILTIN_IDS, withRun: true },
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* スニペット設定を読む(version 1 は読取時に version 2 へ補完)。
|
|
200
|
+
* @param {'chat'|'term'} kind 種類
|
|
201
|
+
* @returns {{version: 2, overrides: Record<string, object>, custom: Array<object>}} 設定
|
|
202
|
+
*/
|
|
203
|
+
function loadSnippetStore(kind) {
|
|
204
|
+
const s = SNIPPET_STORE[kind]
|
|
205
|
+
return readSnippetStore(s.file, { ids: s.ids, withRun: s.withRun, max: CUSTOM_MAX })
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* スニペット設定を保存する(`reset: true` で既定に戻す)。
|
|
210
|
+
* @param {'chat'|'term'} kind 種類
|
|
211
|
+
* @param {{custom?: unknown, overrides?: unknown, reset?: boolean}} [body] 変更内容
|
|
212
|
+
* @returns {{version: 2, overrides: Record<string, object>, custom: Array<object>}} 保存した設定
|
|
213
|
+
*/
|
|
214
|
+
function saveSnippetStore(kind, body = {}) {
|
|
215
|
+
const s = SNIPPET_STORE[kind]
|
|
216
|
+
const prev = loadSnippetStore(kind)
|
|
217
|
+
const reset = body?.reset === true
|
|
218
|
+
const hasCustom = body != null && Object.prototype.hasOwnProperty.call(body, 'custom')
|
|
219
|
+
const hasOverrides = body != null && Object.prototype.hasOwnProperty.call(body, 'overrides')
|
|
220
|
+
return writeSnippetStore(
|
|
221
|
+
s.file,
|
|
222
|
+
{
|
|
223
|
+
custom: reset ? [] : hasCustom ? body.custom : prev.custom,
|
|
224
|
+
overrides: reset ? {} : hasOverrides ? body.overrides : prev.overrides,
|
|
225
|
+
},
|
|
226
|
+
{ ids: s.ids, withRun: s.withRun, max: CUSTOM_MAX },
|
|
227
|
+
)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* API 応答(`{snippets, allSnippets, overrides, custom, customMax, hotLimit, lang}`)。
|
|
232
|
+
* @param {'chat'|'term'} kind 種類
|
|
233
|
+
* @param {'en'|'ja'} lang 表示言語
|
|
234
|
+
* @returns {Record<string, unknown>} 応答
|
|
235
|
+
*/
|
|
236
|
+
function snippetPayload(kind, lang) {
|
|
237
|
+
const store = loadSnippetStore(kind)
|
|
238
|
+
const all =
|
|
239
|
+
kind === 'term'
|
|
240
|
+
? allTermSnippets(capabilities, lang, store.overrides, store.custom)
|
|
241
|
+
: allSnippets(store.custom, lang, store.overrides)
|
|
242
|
+
return {
|
|
243
|
+
snippets: all.filter((s) => !s.hidden),
|
|
244
|
+
allSnippets: all,
|
|
245
|
+
overrides: store.overrides,
|
|
246
|
+
custom: store.custom,
|
|
247
|
+
customMax: CUSTOM_MAX,
|
|
248
|
+
hotLimit: HOT_LIMIT,
|
|
249
|
+
lang,
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const MIME = {
|
|
254
|
+
'.html': 'text/html; charset=utf-8',
|
|
255
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
256
|
+
'.css': 'text/css; charset=utf-8',
|
|
257
|
+
'.json': 'application/json; charset=utf-8',
|
|
258
|
+
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
|
259
|
+
'.svg': 'image/svg+xml',
|
|
260
|
+
'.png': 'image/png',
|
|
261
|
+
'.jpg': 'image/jpeg',
|
|
262
|
+
'.webp': 'image/webp',
|
|
263
|
+
'.ico': 'image/x-icon',
|
|
264
|
+
'.map': 'application/json; charset=utf-8',
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** @param {import('node:http').ServerResponse} res 応答 */
|
|
268
|
+
function sendJson(res, status, data) {
|
|
269
|
+
const body = JSON.stringify(data, null, 2)
|
|
270
|
+
res.writeHead(status, {
|
|
271
|
+
'content-type': 'application/json; charset=utf-8',
|
|
272
|
+
'content-length': Buffer.byteLength(body),
|
|
273
|
+
'cache-control': 'no-store',
|
|
274
|
+
})
|
|
275
|
+
res.end(body)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* エラー応答(SPEC §6.3)。`{ok:false, code, error, params}` の形に統一する。
|
|
280
|
+
* @param {import('node:http').ServerResponse} res 応答
|
|
281
|
+
* @param {number} status HTTP ステータス
|
|
282
|
+
* @param {string} code エラーコード
|
|
283
|
+
* @param {Record<string, unknown>} [params] プレースホルダ値
|
|
284
|
+
* @returns {void}
|
|
285
|
+
*/
|
|
286
|
+
function sendError(res, status, code, params) {
|
|
287
|
+
sendJson(res, status, errorBody(code, params))
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 内部モジュールの `{ok:false, code?, error|message}` を §6.3 の形へ正規化して返す。
|
|
292
|
+
* 元の説明文は `detail` に残す(英語既定だけでは原因が分からない時用)。
|
|
293
|
+
* @param {import('node:http').ServerResponse} res 応答
|
|
294
|
+
* @param {number} status HTTP ステータス
|
|
295
|
+
* @param {{code?: string, error?: unknown, message?: unknown, params?: object, status?: unknown, reason?: unknown}} r 失敗結果
|
|
296
|
+
* @returns {void}
|
|
297
|
+
*/
|
|
298
|
+
function sendFailure(res, status, r) {
|
|
299
|
+
const fallback = status === 404 ? 'NOT_FOUND' : status === 409 ? 'CONFLICT' : 'BAD_REQUEST'
|
|
300
|
+
const code = r?.code ?? fallback
|
|
301
|
+
const params = r?.params ?? (r?.status ? { status: r.status } : {})
|
|
302
|
+
const body = errorBody(code, params)
|
|
303
|
+
const detail = [r?.message, r?.error, r?.reason].find((v) => typeof v === 'string' && v.trim())
|
|
304
|
+
if (detail && detail !== body.error) body.detail = String(detail)
|
|
305
|
+
sendJson(res, status, body)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* リクエストの表示言語(`?lang=` → `Accept-Language` → en・SPEC §6.1)。
|
|
310
|
+
* @param {import('node:http').IncomingMessage} req リクエスト
|
|
311
|
+
* @param {URL} url URL
|
|
312
|
+
* @returns {'en'|'ja'} 言語
|
|
313
|
+
*/
|
|
314
|
+
function langOf(req, url) {
|
|
315
|
+
return resolveLang({ queryLang: url.searchParams.get('lang'), acceptLanguage: req.headers['accept-language'] })
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 本文を JSON として読む(上限 1MB)。 */
|
|
319
|
+
function readJson(req, limit = 1_000_000) {
|
|
320
|
+
return new Promise((resolve, reject) => {
|
|
321
|
+
const chunks = []
|
|
322
|
+
let size = 0
|
|
323
|
+
req.on('data', (c) => {
|
|
324
|
+
size += c.length
|
|
325
|
+
if (size > limit) {
|
|
326
|
+
reject(Object.assign(new Error('payload too large'), { statusCode: 413 }))
|
|
327
|
+
req.destroy()
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
chunks.push(c)
|
|
331
|
+
})
|
|
332
|
+
req.on('end', () => {
|
|
333
|
+
if (!chunks.length) return resolve({})
|
|
334
|
+
try {
|
|
335
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
|
336
|
+
} catch {
|
|
337
|
+
reject(Object.assign(new Error('invalid JSON'), { statusCode: 400 }))
|
|
338
|
+
}
|
|
339
|
+
})
|
|
340
|
+
req.on('error', reject)
|
|
341
|
+
})
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** 書き込み系の簡易レート制限。 */
|
|
345
|
+
const writes = []
|
|
346
|
+
function writeAllowed(max = 60, windowMs = 60_000) {
|
|
347
|
+
const now = Date.now()
|
|
348
|
+
while (writes.length && now - writes[0] > windowMs) writes.shift()
|
|
349
|
+
if (writes.length >= max) return false
|
|
350
|
+
writes.push(now)
|
|
351
|
+
return true
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* ペアリング(`POST /api/auth/login`)専用の簡易レート制限。
|
|
356
|
+
* アプリの書き込み枠と混ぜない(混ぜると通常操作が 10 回で詰まる)。
|
|
357
|
+
*/
|
|
358
|
+
const loginAttempts = []
|
|
359
|
+
function loginAllowed(max = 12, windowMs = 60_000) {
|
|
360
|
+
const now = Date.now()
|
|
361
|
+
while (loginAttempts.length && now - loginAttempts[0] > windowMs) loginAttempts.shift()
|
|
362
|
+
if (loginAttempts.length >= max) return false
|
|
363
|
+
loginAttempts.push(now)
|
|
364
|
+
return true
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** 読み取り系の簡易レート制限(機能別バケットで分離)。書き込みとは枠を分ける。 */
|
|
368
|
+
const readBuckets = new Map()
|
|
369
|
+
function readAllowed(bucket = 'default', max = 240, windowMs = 60_000) {
|
|
370
|
+
const now = Date.now()
|
|
371
|
+
let arr = readBuckets.get(bucket)
|
|
372
|
+
if (!arr) {
|
|
373
|
+
arr = []
|
|
374
|
+
readBuckets.set(bucket, arr)
|
|
375
|
+
}
|
|
376
|
+
while (arr.length && now - arr[0] > windowMs) arr.shift()
|
|
377
|
+
if (arr.length >= max) return false
|
|
378
|
+
arr.push(now)
|
|
379
|
+
return true
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const LOGIN_HTML = `<!doctype html><meta charset="utf-8">
|
|
383
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
384
|
+
<title>Hermes Pilot — ログイン</title>
|
|
385
|
+
<style>body{background:#07171b;color:#e6f4f1;font:15px/1.6 system-ui;margin:0;display:grid;place-items:center;height:100vh}
|
|
386
|
+
form{background:#0d242a;padding:24px;border-radius:16px;border:1px solid #1d3a41;width:min(88vw,360px)}
|
|
387
|
+
h1{font-size:16px;margin:0 0 12px}input{width:100%;padding:12px;border-radius:10px;border:1px solid #24515a;background:#081e23;color:#e6f4f1;font-size:15px;box-sizing:border-box}
|
|
388
|
+
button{margin-top:12px;width:100%;padding:12px;border-radius:10px;border:0;background:#13807f;color:#fff;font-size:15px}
|
|
389
|
+
p{color:#7fa6a3;font-size:12px;margin:10px 0 0}</style>
|
|
390
|
+
<form method="get" action="/auth"><h1>Hermes Pilot</h1>
|
|
391
|
+
<input name="t" placeholder="アプリトークン" autocomplete="off" autocapitalize="off" spellcheck="false">
|
|
392
|
+
<button>入る</button>
|
|
393
|
+
<p>トークンは <code>~/.hermes/plugin-data/hermes-pilot/token</code>(トークンファイル)を確認してください。</p></form>`
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 静的配信。`dist` が無い/ビルド途中なら直前の正常ビルド(`dist.prev`)で配る。
|
|
397
|
+
*
|
|
398
|
+
* 実測: 改修中にビルドが走っている間 `dist` が欠け、PWA が
|
|
399
|
+
* 「ブリッジに接続できません」で使えなくなった。落とさないための保険。
|
|
400
|
+
*/
|
|
401
|
+
function distCandidates() {
|
|
402
|
+
return [cfg.distDir, `${cfg.distDir}.prev`]
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** キャッシュ方針(html/manifest/json は no-cache、/assets/ のハッシュ付きは長期)。 */
|
|
406
|
+
function cacheControlFor(file) {
|
|
407
|
+
const ext = path.extname(file)
|
|
408
|
+
if (ext === '.html' || ext === '.webmanifest' || ext === '.json') return 'no-cache'
|
|
409
|
+
if (file.includes(`${path.sep}assets${path.sep}`)) return 'public, max-age=31536000, immutable'
|
|
410
|
+
return 'public, max-age=3600, must-revalidate'
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const readOrNull = (file) =>
|
|
414
|
+
new Promise((resolve) => fs.readFile(file, (err, buf) => resolve(err ? null : { buf, file })))
|
|
415
|
+
|
|
416
|
+
/** 候補ディレクトリを順に試し、最初に見つかった {buf,file} を返す。 */
|
|
417
|
+
async function readFirst(files) {
|
|
418
|
+
for (const file of files) {
|
|
419
|
+
const hit = await readOrNull(file)
|
|
420
|
+
if (hit) return hit
|
|
421
|
+
}
|
|
422
|
+
return null
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async function serveStatic(req, res, pathname) {
|
|
426
|
+
const rel = pathname === '/' ? '/index.html' : pathname
|
|
427
|
+
const file = path.join(cfg.distDir, rel)
|
|
428
|
+
if (!file.startsWith(cfg.distDir)) {
|
|
429
|
+
res.writeHead(403).end('forbidden')
|
|
430
|
+
return
|
|
431
|
+
}
|
|
432
|
+
const dirs = distCandidates()
|
|
433
|
+
const hit = await readFirst(dirs.map((d) => path.join(d, rel)))
|
|
434
|
+
if (hit) {
|
|
435
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(hit.file)] ?? 'application/octet-stream',
|
|
436
|
+
'cache-control': cacheControlFor(hit.file) })
|
|
437
|
+
res.end(hit.buf)
|
|
438
|
+
return
|
|
439
|
+
}
|
|
440
|
+
if (path.extname(rel)) {
|
|
441
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('not found')
|
|
442
|
+
return
|
|
443
|
+
}
|
|
444
|
+
// SPA フォールバック
|
|
445
|
+
const index = await readFirst(dirs.map((d) => path.join(d, 'index.html')))
|
|
446
|
+
if (!index) {
|
|
447
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('UI not built (run npm run build)')
|
|
448
|
+
return
|
|
449
|
+
}
|
|
450
|
+
res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-cache' }).end(index.buf)
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** ログの末尾を返す。 */
|
|
454
|
+
function tailLog(name, lines = 200) {
|
|
455
|
+
const safe = String(name ?? 'gateway').replace(/[^a-z0-9._-]/gi, '')
|
|
456
|
+
const file = path.join(cfg.logDir, safe.endsWith('.log') ? safe : `${safe}.log`)
|
|
457
|
+
if (!file.startsWith(cfg.logDir)) throw Object.assign(new Error('invalid log'), { statusCode: 400 })
|
|
458
|
+
const text = readTailText(file, 256 * 1024)
|
|
459
|
+
return text.split('\n').slice(-Math.min(lines, 1000)).join('\n')
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Spec Launchpad の対象リポジトリを決める(SPEC §5.4)。
|
|
464
|
+
*
|
|
465
|
+
* `?repo=<repoId>` は repos の 1 件。`?board=<slug>`(未指定なら現在のボード)は
|
|
466
|
+
* そのボードの `default_workdir` をリポジトリとして扱う。
|
|
467
|
+
*
|
|
468
|
+
* @param {{repoId?: string|null, boardSlug?: string|null}} q クエリ
|
|
469
|
+
* @returns {{repo: string, label: string, path: string, board: string|null}|null} 対象
|
|
470
|
+
*/
|
|
471
|
+
function resolveSpecRepo({ repoId = null, boardSlug = null } = {}) {
|
|
472
|
+
const list = repos.list()
|
|
473
|
+
const want = String(repoId ?? '').trim()
|
|
474
|
+
if (want) {
|
|
475
|
+
const hit = list.find((r) => r.id === want)
|
|
476
|
+
return hit
|
|
477
|
+
? { repo: hit.id, label: hit.label, path: hit.path, board: hit.boards?.[0]?.slug ?? null }
|
|
478
|
+
: null
|
|
479
|
+
}
|
|
480
|
+
const boards = kanban.boards()
|
|
481
|
+
const slug = String(boardSlug ?? '').trim() || boards.find((b) => b.current)?.slug || ''
|
|
482
|
+
const board = boards.find((b) => b.slug === slug)
|
|
483
|
+
if (!board?.workdir) return null
|
|
484
|
+
const key = normalizePath(board.workdir)
|
|
485
|
+
const hit = list.find((r) => normalizePath(r.path) === key)
|
|
486
|
+
return {
|
|
487
|
+
repo: hit?.id ?? board.slug,
|
|
488
|
+
label: hit?.label ?? board.name ?? board.slug,
|
|
489
|
+
path: board.workdir,
|
|
490
|
+
board: board.slug,
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** API のルーティング。 */
|
|
495
|
+
|
|
496
|
+
async function handleApi(req, res, url) {
|
|
497
|
+
const seg = url.pathname.split('/').filter(Boolean) // ['api', ...]
|
|
498
|
+
const [, a, b, c, d, e] = seg
|
|
499
|
+
|
|
500
|
+
if (a === 'me') return sendJson(res, 200, { ok: true, version: VERSION })
|
|
501
|
+
|
|
502
|
+
if (a === 'overview') {
|
|
503
|
+
const data = await ops.overview()
|
|
504
|
+
// 実行中タスク数(アプリバッジ用)
|
|
505
|
+
data.runningTasks = Number(data.kanban?.running ?? 0)
|
|
506
|
+
// 緊急停止(ESTOP)の状態
|
|
507
|
+
data.paused = ops.paused()
|
|
508
|
+
return sendJson(res, 200, data)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// 実行環境の Capability(OS・サービス管理・CLI の有無)。SPEC §5.3
|
|
512
|
+
if (a === 'capabilities') {
|
|
513
|
+
return sendJson(res, 200, capabilities)
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ワンタップ QR ペアリング(SPEC §8.2)。認証済みセッションから 2 台目を迎える。
|
|
517
|
+
// 接続先候補(Tailscale HTTPS / LAN / localhost)と QR(SVG) を返す。
|
|
518
|
+
if (a === 'auth' && b === 'pairing' && req.method === 'GET') {
|
|
519
|
+
const ts = await tailscaleStatusJson()
|
|
520
|
+
// QR を短くするため、本トークンではなくワンタイムコードを URL に載せる(10 分・1 回限り)
|
|
521
|
+
const minted = pairCodes.mint()
|
|
522
|
+
const info = collectPairing({
|
|
523
|
+
token: minted.code,
|
|
524
|
+
port: cfg.port,
|
|
525
|
+
tailscaleJson: ts,
|
|
526
|
+
// 常駐から Tailscale CLI を叩けない環境の控え(config.json)
|
|
527
|
+
dnsName: cfg.pairing?.tailscaleDns ?? null,
|
|
528
|
+
tlsPort: cfg.pairing?.tlsPort ?? null,
|
|
529
|
+
})
|
|
530
|
+
auth.audit({ kind: 'auth.pairing', target: info.best?.kind ?? null })
|
|
531
|
+
return sendJson(res, 200, {
|
|
532
|
+
ok: true,
|
|
533
|
+
port: cfg.port,
|
|
534
|
+
tlsPort: cfg.pairing?.tlsPort ?? null,
|
|
535
|
+
tailscale: Boolean(info.dnsName),
|
|
536
|
+
dnsName: info.dnsName,
|
|
537
|
+
lanIp: info.lanIp,
|
|
538
|
+
targets: info.targets,
|
|
539
|
+
// 有効期限(ミリ秒エポック)。画面に「あと何分」を出せるようにする
|
|
540
|
+
expiresAt: minted.expiresAt,
|
|
541
|
+
// フロントはこの行列を canvas に整数ピクセルで描く(SVG の CSS 縮小は半端な
|
|
542
|
+
// ピクセルになり、スキャナが反応しないため)。`qrSvg` は後方互換で残す。
|
|
543
|
+
qrRows: info.best ? qrRows(info.best.url) : null,
|
|
544
|
+
qrMargin: 4,
|
|
545
|
+
// 実画像(base64 PNG, 41 モジュール x 7px = 287px = 7px/モジュールの整数倍)。
|
|
546
|
+
// <img> ならどのブラウザでも canvas と違って確実に合成される。
|
|
547
|
+
qrPng: info.best ? `data:image/png;base64,${qrPng(info.best.url, { scale: 7 }).toString('base64')}` : null,
|
|
548
|
+
qrSvg: info.best ? qrSvg(info.best.url) : null,
|
|
549
|
+
})
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
// --- リポジトリ(作業ディレクトリ)とボード -------------------------------
|
|
553
|
+
// GET /api/repos … 統合一覧 + scanDirs
|
|
554
|
+
// POST /api/repos … { path, label? } で追加 / { scanDirs } で走査先を更新
|
|
555
|
+
// POST /api/repos/scan … 即時再スキャン(キャッシュ TTL 30 秒を飛ばす)
|
|
556
|
+
// POST /api/repos/:id/board … 板が無いリポジトリにボードを 1 つ作る
|
|
557
|
+
// DELETE /api/repos/:id … custom から削除 / 自動検出は hidden へ
|
|
558
|
+
if (a === 'repos') {
|
|
559
|
+
if (!b && req.method === 'GET') {
|
|
560
|
+
return sendJson(res, 200, { repos: repos.list(), scanDirs: repos.scanDirs() })
|
|
561
|
+
}
|
|
562
|
+
if (!b && req.method === 'POST') {
|
|
563
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
564
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
565
|
+
}
|
|
566
|
+
const body = await readJson(req)
|
|
567
|
+
const r = Array.isArray(body?.scanDirs) ? repos.setScanDirs(body.scanDirs) : repos.add(body)
|
|
568
|
+
auth.audit({ kind: 'repos.save', ok: Boolean(r.ok), path: body?.path ?? null })
|
|
569
|
+
if (!r.ok) return sendFailure(res, 400, r)
|
|
570
|
+
return sendJson(res, 201, { ...r, repos: repos.list({ force: true }), scanDirs: repos.scanDirs() })
|
|
571
|
+
}
|
|
572
|
+
if (b === 'scan' && req.method === 'POST') {
|
|
573
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
574
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
575
|
+
}
|
|
576
|
+
const r = repos.scan()
|
|
577
|
+
auth.audit({ kind: 'repos.scan', count: r.repos.length })
|
|
578
|
+
return sendJson(res, 200, r)
|
|
579
|
+
}
|
|
580
|
+
if (b && c === 'board' && req.method === 'POST') {
|
|
581
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
582
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
583
|
+
}
|
|
584
|
+
const r = await repos.createBoard(b)
|
|
585
|
+
auth.audit({ kind: 'repos.board.create', repo: b, board: r.board?.slug ?? null, ok: Boolean(r.ok) })
|
|
586
|
+
return r.ok ? sendJson(res, 201, r) : sendFailure(res, 400, r)
|
|
587
|
+
}
|
|
588
|
+
if (b && req.method === 'DELETE') {
|
|
589
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
590
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
591
|
+
}
|
|
592
|
+
const r = repos.remove(b)
|
|
593
|
+
auth.audit({ kind: 'repos.remove', repo: b, hidden: r.hidden ?? null, ok: Boolean(r.ok) })
|
|
594
|
+
if (!r.ok) return sendFailure(res, 400, r)
|
|
595
|
+
return sendJson(res, 200, { ...r, repos: repos.list({ force: true }) })
|
|
596
|
+
}
|
|
597
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// --- Spec Launchpad -------------------------------------------------------
|
|
601
|
+
// GET /api/specs?repo=<repoId> | ?board=<slug> … SPEC とバッチ一覧(SPEC §5.4)
|
|
602
|
+
// POST /api/specs/launch { repo?, board?, specRelPath, batchIds?, assignee? }
|
|
603
|
+
// … バッチを一括起票(同一ボードの未完了はスキップ)
|
|
604
|
+
if (a === 'specs') {
|
|
605
|
+
if (!b && req.method === 'GET') {
|
|
606
|
+
const target = resolveSpecRepo({
|
|
607
|
+
repoId: url.searchParams.get('repo'),
|
|
608
|
+
boardSlug: url.searchParams.get('board'),
|
|
609
|
+
})
|
|
610
|
+
if (!target) return sendError(res, 404, 'NOT_FOUND', { resource: 'repo' })
|
|
611
|
+
return sendJson(res, 200, {
|
|
612
|
+
ok: true,
|
|
613
|
+
repo: target.repo,
|
|
614
|
+
label: target.label,
|
|
615
|
+
path: target.path,
|
|
616
|
+
board: target.board,
|
|
617
|
+
specs: specs.listSpecs(target.path),
|
|
618
|
+
})
|
|
619
|
+
}
|
|
620
|
+
// GET /api/specs/content?board=<slug>&repo=<id>&path=<rel>
|
|
621
|
+
// … 1 枚の SPEC の全文(リポジトリ境界内・`.md` のみ・256KB 上限)
|
|
622
|
+
// 不正パス(`../` 等)は 400、未検出は 404(`readSpecContent` の ApiError を外側が拾う)
|
|
623
|
+
if (b === 'content' && req.method === 'GET') {
|
|
624
|
+
const target = resolveSpecRepo({
|
|
625
|
+
repoId: url.searchParams.get('repo'),
|
|
626
|
+
boardSlug: url.searchParams.get('board'),
|
|
627
|
+
})
|
|
628
|
+
if (!target) return sendError(res, 404, 'NOT_FOUND', { resource: 'repo' })
|
|
629
|
+
const content = readSpecContent(target.path, url.searchParams.get('path'))
|
|
630
|
+
auth.audit({ kind: 'specs.content', repo: target.repo, path: content.path, bytes: content.bytes })
|
|
631
|
+
return sendJson(res, 200, { ...content, repo: target.repo, label: target.label, board: target.board })
|
|
632
|
+
}
|
|
633
|
+
// GET /api/specs/reports?board=<slug>&limit=<n> … 直近のパイプライン完走レポート(D20 / D21)
|
|
634
|
+
if (b === 'reports' && req.method === 'GET') {
|
|
635
|
+
const board = String(url.searchParams.get('board') ?? '').trim()
|
|
636
|
+
const limit = Number(url.searchParams.get('limit')) || 20
|
|
637
|
+
return sendJson(res, 200, {
|
|
638
|
+
ok: true,
|
|
639
|
+
board: board || null,
|
|
640
|
+
reports: readPipelineReports(cfg.reviewDir, { board, limit }),
|
|
641
|
+
})
|
|
642
|
+
}
|
|
643
|
+
if (b === 'launch' && req.method === 'POST') {
|
|
644
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
645
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
646
|
+
}
|
|
647
|
+
const body = await readJson(req)
|
|
648
|
+
const target = resolveSpecRepo({ repoId: body?.repo, boardSlug: body?.board })
|
|
649
|
+
if (!target) return sendError(res, 404, 'NOT_FOUND', { resource: 'repo' })
|
|
650
|
+
const board = String(body?.board ?? target.board ?? '').trim()
|
|
651
|
+
const r = await specs.launchSpec({
|
|
652
|
+
repoPath: target.path,
|
|
653
|
+
board,
|
|
654
|
+
specRelPath: body?.specRelPath,
|
|
655
|
+
batchIds: body?.batchIds,
|
|
656
|
+
assignee: String(body?.assignee ?? 'mobile').trim() || 'mobile',
|
|
657
|
+
// 起票元チャット(`Chat:` 行 + ラン記録の originSessionId)。書式外は specs 側で捨てる。
|
|
658
|
+
chat: body?.chat,
|
|
659
|
+
dryRun: Boolean(body?.dryRun),
|
|
660
|
+
})
|
|
661
|
+
auth.audit({
|
|
662
|
+
kind: 'specs.launch',
|
|
663
|
+
board,
|
|
664
|
+
spec: String(body?.specRelPath ?? ''),
|
|
665
|
+
created: r.created?.length ?? 0,
|
|
666
|
+
skipped: r.skipped?.length ?? 0,
|
|
667
|
+
failed: r.failed?.length ?? 0,
|
|
668
|
+
ok: Boolean(r.ok),
|
|
669
|
+
})
|
|
670
|
+
return r.ok ? sendJson(res, 201, r) : sendFailure(res, 400, r)
|
|
671
|
+
}
|
|
672
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// --- A2B パイプライン最適化(第3段 / SPEC §3.2・D25③) ----------------------
|
|
676
|
+
// GET /api/pipeline/status … 適用済みか(中身は返さない)
|
|
677
|
+
// POST /api/pipeline/optimize { soul?, skills? }
|
|
678
|
+
// … SOUL.md へ冪等追記+スキル配置
|
|
679
|
+
if (a === 'pipeline') {
|
|
680
|
+
if (b === 'status' && req.method === 'GET') {
|
|
681
|
+
return sendJson(
|
|
682
|
+
res,
|
|
683
|
+
200,
|
|
684
|
+
getOptimizeStatus({
|
|
685
|
+
hermesHome: cfg.hermesHome,
|
|
686
|
+
home: cfg.home,
|
|
687
|
+
skillsSrcDir: DEFAULT_SKILLS_SRC,
|
|
688
|
+
}),
|
|
689
|
+
)
|
|
690
|
+
}
|
|
691
|
+
if (b === 'optimize' && req.method === 'POST') {
|
|
692
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
693
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
694
|
+
}
|
|
695
|
+
const body = await readJson(req)
|
|
696
|
+
// 既定は SOUL とスキル配置の両方。片方だけ試したいときは明示的に false を渡す。
|
|
697
|
+
const doSoul = body?.soul !== false
|
|
698
|
+
const doSkills = body?.skills !== false
|
|
699
|
+
// プロファイル別 `SOUL.md`(`profiles/<name>/SOUL.md`)も同じ 1 タップで冪等同期する(D64)。
|
|
700
|
+
const doProfiles = doSoul && body?.profiles !== false
|
|
701
|
+
const soul = doSoul ? optimizeHermesSoul({ hermesHome: cfg.hermesHome }) : null
|
|
702
|
+
const profiles = doProfiles ? optimizeProfileSouls({ hermesHome: cfg.hermesHome }) : null
|
|
703
|
+
const skills = doSkills ? optimizeAgentSkills({ home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }) : null
|
|
704
|
+
const ok = (soul?.ok ?? true) && (profiles?.ok ?? true) && (skills?.ok ?? true)
|
|
705
|
+
auth.audit({
|
|
706
|
+
kind: 'pipeline.optimize',
|
|
707
|
+
soul: soul?.mode ?? null,
|
|
708
|
+
soulChanged: Boolean(soul?.changed),
|
|
709
|
+
profileTargets: profiles?.profiles?.length ?? 0,
|
|
710
|
+
profileChanged: profiles?.profiles?.filter((p) => p.changed).length ?? 0,
|
|
711
|
+
skillTargets: skills?.targets?.length ?? 0,
|
|
712
|
+
ok,
|
|
713
|
+
})
|
|
714
|
+
return sendJson(res, ok ? 200 : 500, {
|
|
715
|
+
ok,
|
|
716
|
+
soul,
|
|
717
|
+
profiles,
|
|
718
|
+
skills,
|
|
719
|
+
status: getOptimizeStatus({ hermesHome: cfg.hermesHome, home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }),
|
|
720
|
+
})
|
|
721
|
+
}
|
|
722
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// --- Architect(仕様の種 → SPEC)/ハイブリッド A2B(SPEC V5 §3.2・§3.3① / D23・D25・D26①)--
|
|
726
|
+
// POST /api/architect/seed { repo?, board?, seedText, runner?, autoStart?, executionPolicy?, chat?, lang? }
|
|
727
|
+
// … 202 で `{ok, jobId, status}` を即返し、Architect は背後で走る(画面を待たせない)
|
|
728
|
+
// GET /api/architect/jobs?board=<slug>&repo=<id>
|
|
729
|
+
// … ジョブ / 完成 SPEC(`spec_ready`)/ 未起票 SPEC(一括起票カードの材料)
|
|
730
|
+
// POST /api/architect/jobs/:id/dismiss
|
|
731
|
+
// … ジョブ破棄をサーバー側に永続化する(再取得しても進行バーに出ない。SPEC V7 §3.1)
|
|
732
|
+
// GET /api/architect/config ・ PUT /api/architect/config { runner }
|
|
733
|
+
// … 実行ランナー(`hermes` 固定。他の値は INVALID_RUNNER = HTTP 400)
|
|
734
|
+
if (a === 'architect') {
|
|
735
|
+
if (b === 'config') {
|
|
736
|
+
if (req.method === 'GET') {
|
|
737
|
+
return sendJson(res, 200, { ok: true, ...architect.getConfig() })
|
|
738
|
+
}
|
|
739
|
+
if (req.method === 'PUT' || req.method === 'POST') {
|
|
740
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
741
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
742
|
+
}
|
|
743
|
+
const body = await readJson(req)
|
|
744
|
+
// 正規化せずに渡す(未知のランナー名は INVALID_RUNNER で 400 にする)
|
|
745
|
+
const r = architect.setConfig({ runner: body?.runner })
|
|
746
|
+
auth.audit({ kind: 'architect.config', runner: r.runner ?? null, ok: Boolean(r.ok) })
|
|
747
|
+
if (!r.ok) return sendFailure(res, r.code === 'INVALID_RUNNER' ? 400 : 409, r)
|
|
748
|
+
return sendJson(res, 200, { ok: true, ...architect.getConfig() })
|
|
749
|
+
}
|
|
750
|
+
return sendError(res, 405, 'METHOD_NOT_ALLOWED')
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
if (b === 'seed' && req.method === 'POST') {
|
|
754
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
755
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
756
|
+
}
|
|
757
|
+
const body = await readJson(req)
|
|
758
|
+
const target = resolveSpecRepo({ repoId: body?.repo, boardSlug: body?.board })
|
|
759
|
+
if (!target) return sendError(res, 404, 'NOT_FOUND', { resource: 'repo' })
|
|
760
|
+
const board = String(body?.board ?? target.board ?? '').trim()
|
|
761
|
+
const r = await architect.seed({
|
|
762
|
+
repoPath: target.path,
|
|
763
|
+
board,
|
|
764
|
+
seedText: body?.seedText,
|
|
765
|
+
runner: body?.runner,
|
|
766
|
+
autoStart: Boolean(body?.autoStart),
|
|
767
|
+
executionPolicy: body?.executionPolicy,
|
|
768
|
+
chat: body?.chat,
|
|
769
|
+
lang: body?.lang,
|
|
770
|
+
})
|
|
771
|
+
auth.audit({
|
|
772
|
+
kind: 'architect.seed',
|
|
773
|
+
board,
|
|
774
|
+
repo: target.repo,
|
|
775
|
+
runner: r.runner ?? null,
|
|
776
|
+
executionPolicy: r.executionPolicy ?? null,
|
|
777
|
+
autoStart: Boolean(body?.autoStart),
|
|
778
|
+
chars: String(body?.seedText ?? '').length,
|
|
779
|
+
ok: Boolean(r.ok),
|
|
780
|
+
})
|
|
781
|
+
// 202: ジョブは動き出したが、SPEC はまだ無い(PWA は jobs をポーリングする)
|
|
782
|
+
return r.ok ? sendJson(res, 202, r) : sendFailure(res, 400, r)
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
if (b === 'jobs' && c && d === 'dismiss' && req.method === 'POST') {
|
|
786
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
787
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
788
|
+
}
|
|
789
|
+
const r = architect.dismiss(c)
|
|
790
|
+
auth.audit({ kind: 'architect.dismiss', jobId: String(c), ok: Boolean(r.ok), persisted: Boolean(r.persisted) })
|
|
791
|
+
if (!r.ok) return sendFailure(res, r.code === 'JOB_NOT_FOUND' ? 404 : 400, r)
|
|
792
|
+
return sendJson(res, 200, { ok: true, jobId: r.jobId, persisted: Boolean(r.persisted) })
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
if (b === 'jobs' && !c && req.method === 'GET') {
|
|
796
|
+
const board = String(url.searchParams.get('board') ?? '').trim()
|
|
797
|
+
// D42: 既定はアクティブジョブをボード横断で返す。`?strictBoard=1` で V7 互換の厳密一致。
|
|
798
|
+
const strictBoard = ['1', 'true', 'yes'].includes(String(url.searchParams.get('strictBoard') ?? '').trim().toLowerCase())
|
|
799
|
+
const target = resolveSpecRepo({ repoId: url.searchParams.get('repo'), boardSlug: board || null })
|
|
800
|
+
const snapshot = await architect.jobs({
|
|
801
|
+
board,
|
|
802
|
+
strictBoard,
|
|
803
|
+
...(target?.path ? { include: { repoPath: target.path, board: target.board ?? board } } : {}),
|
|
804
|
+
})
|
|
805
|
+
return sendJson(res, 200, snapshot)
|
|
806
|
+
}
|
|
807
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
if (a === 'boards') {
|
|
811
|
+
// /api/boards … ボード一覧
|
|
812
|
+
// /api/boards/:slug/tasks … タスク一覧(git / Discord 付き)
|
|
813
|
+
// /api/boards/:slug/tasks/:id … タスク詳細
|
|
814
|
+
// /api/boards/:slug/tasks/:id/diff … そのタスクのコミット差分
|
|
815
|
+
// POST /api/boards/:slug/tasks/:id/abort … 実行中タスクの中断
|
|
816
|
+
if (!b) return sendJson(res, 200, { boards: kanban.boards() })
|
|
817
|
+
// クイック起票(POST /api/boards/:slug/tasks)
|
|
818
|
+
if (b && c === 'tasks' && !d && req.method === 'POST') {
|
|
819
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
820
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
821
|
+
}
|
|
822
|
+
const body = await readJson(req)
|
|
823
|
+
const r = await capture.create({ ...body, board: b })
|
|
824
|
+
auth.audit({
|
|
825
|
+
kind: 'kanban.create',
|
|
826
|
+
board: b,
|
|
827
|
+
task: r.task?.id ?? null,
|
|
828
|
+
created: Boolean(r.created),
|
|
829
|
+
ok: Boolean(r.ok),
|
|
830
|
+
})
|
|
831
|
+
return r.ok ? sendJson(res, 201, r) : sendFailure(res, 400, r)
|
|
832
|
+
}
|
|
833
|
+
if (b && c === 'tasks' && !d) {
|
|
834
|
+
// 一覧は本文を載せない(1 件 1.5KB 平均 × 60 件で 90KB になり、モバイル回線で重い)。
|
|
835
|
+
// 本文は詳細(/api/boards/:slug/tasks/:id)から取る。
|
|
836
|
+
const list = kanban.tasks(b, { limit: Number(url.searchParams.get('limit') ?? 60), withBody: false })
|
|
837
|
+
// 履歴(kanban-sop)に記録があるタスクだけ git / Discord を添える
|
|
838
|
+
const enriched = await Promise.all(
|
|
839
|
+
list.map(async (t) => {
|
|
840
|
+
const entry = gitinfo.entryFor(t.id)
|
|
841
|
+
if (!entry) return t
|
|
842
|
+
const [g, dc] = await Promise.all([gitinfo.forTask(t.id), Promise.resolve(discord.forAnchor(entry.anchor))])
|
|
843
|
+
return { ...t, git: g, discord: dc }
|
|
844
|
+
}),
|
|
845
|
+
)
|
|
846
|
+
return sendJson(res, 200, { tasks: enriched })
|
|
847
|
+
}
|
|
848
|
+
if (b && c === 'tasks' && d && e === 'diff' && req.method === 'GET') {
|
|
849
|
+
const file = url.searchParams.get('file')
|
|
850
|
+
if (file) {
|
|
851
|
+
const patch = await gitinfo.filePatch(d, String(file).slice(0, 400))
|
|
852
|
+
return sendJson(res, patch.ok ? 200 : 404, patch)
|
|
853
|
+
}
|
|
854
|
+
const summary = await gitinfo.diffSummary(d)
|
|
855
|
+
return sendJson(res, summary.ok ? 200 : 404, summary)
|
|
856
|
+
}
|
|
857
|
+
if (b && c === 'tasks' && d && e === 'comment' && req.method === 'POST') {
|
|
858
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
859
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
860
|
+
}
|
|
861
|
+
const body = await readJson(req)
|
|
862
|
+
const out = await inbox.comment(b, d, body?.body ?? body?.text, String(body?.by ?? 'mobile'))
|
|
863
|
+
auth.audit({ kind: 'kanban.comment', board: b, task: d, chars: String(body?.body ?? body?.text ?? '').length })
|
|
864
|
+
return sendJson(res, 200, out)
|
|
865
|
+
}
|
|
866
|
+
if (b && c === 'tasks' && d && e === 'close' && req.method === 'POST') {
|
|
867
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
868
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
869
|
+
}
|
|
870
|
+
const body = await readJson(req)
|
|
871
|
+
const out = await inbox.close(b, d, body?.action, body?.note ?? body?.reason ?? '', String(body?.by ?? 'mobile'))
|
|
872
|
+
auth.audit({
|
|
873
|
+
kind: 'kanban.close',
|
|
874
|
+
board: b,
|
|
875
|
+
task: d,
|
|
876
|
+
action: body?.action ?? null,
|
|
877
|
+
status: out.status,
|
|
878
|
+
noop: Boolean(out.noop),
|
|
879
|
+
})
|
|
880
|
+
return sendJson(res, 200, out)
|
|
881
|
+
}
|
|
882
|
+
if (b && c === 'tasks' && d && e === 'unblock' && req.method === 'POST') {
|
|
883
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
884
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
885
|
+
}
|
|
886
|
+
const body = await readJson(req)
|
|
887
|
+
const out = await inbox.unblock(b, d, body?.note ?? body?.reason ?? '', String(body?.by ?? 'mobile'))
|
|
888
|
+
auth.audit({
|
|
889
|
+
kind: 'kanban.unblock',
|
|
890
|
+
board: b,
|
|
891
|
+
task: d,
|
|
892
|
+
status: out.status,
|
|
893
|
+
noop: Boolean(out.noop),
|
|
894
|
+
})
|
|
895
|
+
return sendJson(res, 200, out)
|
|
896
|
+
}
|
|
897
|
+
if (b && c === 'tasks' && d && e === 'worker' && req.method === 'GET') {
|
|
898
|
+
// 任意のボードの実行中タスクでもワーカーのライブ進捗を読めるようにする(SPEC V8-B3)
|
|
899
|
+
const info = kanban.taskSession(b, d)
|
|
900
|
+
if (!info) return sendError(res, 404, 'NO_SESSION')
|
|
901
|
+
const { feed, db, profile } = await readWorkerFeed(info.sessionId, info, Number(url.searchParams.get('limit') ?? 40))
|
|
902
|
+
return sendJson(res, 200, {
|
|
903
|
+
taskId: d,
|
|
904
|
+
status: kanban.task(b, d).status,
|
|
905
|
+
sessionId: info.sessionId,
|
|
906
|
+
db,
|
|
907
|
+
profile,
|
|
908
|
+
feed,
|
|
909
|
+
})
|
|
910
|
+
}
|
|
911
|
+
if (b && c === 'tasks' && d && e === 'abort' && req.method === 'POST') {
|
|
912
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
913
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
914
|
+
}
|
|
915
|
+
const body = await readJson(req)
|
|
916
|
+
const reason = String(body?.reason ?? 'mobile kill switch').slice(0, 200)
|
|
917
|
+
const out = await kanban.abort(b, d, reason)
|
|
918
|
+
auth.audit({ kind: 'kanban.abort', board: b, task: d, reason, result: out })
|
|
919
|
+
return sendJson(res, 200, out)
|
|
920
|
+
}
|
|
921
|
+
if (b && c === 'tasks' && d) {
|
|
922
|
+
const detail = kanban.task(b, d)
|
|
923
|
+
const entry = gitinfo.entryFor(d)
|
|
924
|
+
if (entry) {
|
|
925
|
+
detail.git = await gitinfo.forTask(d)
|
|
926
|
+
detail.discord = discord.forAnchor(entry.anchor)
|
|
927
|
+
}
|
|
928
|
+
return sendJson(res, 200, detail)
|
|
929
|
+
}
|
|
930
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
|
|
934
|
+
// --- レビュー(review)------------------------------------------------------
|
|
935
|
+
// 全ルートは SPEC §4.2。旧 `/api/akapen/*` は廃止し、ここに一本化する。
|
|
936
|
+
// /api/review … 一覧(review / ready / done)
|
|
937
|
+
// /api/review/:id/sheet … シート HTML(常に sandbox・生成物)
|
|
938
|
+
// /api/review/:id/view … 単体タブ用ラッパー(sandbox iframe + postMessage 中継)
|
|
939
|
+
// /api/review/:id/data … sheet.json(PWA のネイティブフォーム用)
|
|
940
|
+
// POST /api/review/:id/answer … 回答を保存 → comment → unblock(冪等)
|
|
941
|
+
// POST /api/review/:id/reopen … 反映が違うとき review に戻す
|
|
942
|
+
if (a === 'review') {
|
|
943
|
+
if (!b) {
|
|
944
|
+
return sendJson(res, 200, {
|
|
945
|
+
board: review.board,
|
|
946
|
+
workdir: review.workdir(),
|
|
947
|
+
items: review.list(Number(url.searchParams.get('limit') ?? 80)),
|
|
948
|
+
})
|
|
949
|
+
}
|
|
950
|
+
// /api/review/feed?limit=&since= … 作業フィード(監視 cron が書く 1 行ログ)
|
|
951
|
+
if (b === 'feed' && req.method === 'GET') {
|
|
952
|
+
return sendJson(res, 200, {
|
|
953
|
+
items: review.feed(
|
|
954
|
+
Number(url.searchParams.get('limit') ?? 20),
|
|
955
|
+
Number(url.searchParams.get('since') ?? 0),
|
|
956
|
+
),
|
|
957
|
+
})
|
|
958
|
+
}
|
|
959
|
+
// /api/review/chat-reports?limit=&since= … 全会話ぶんの完了報告(未読の点を出すため)
|
|
960
|
+
// 会話一覧の行と下部ナビのチャットタブは「どの会話に新着があるか」を 1 回で要る。
|
|
961
|
+
if (b === 'chat-reports' && req.method === 'GET') {
|
|
962
|
+
return sendJson(res, 200, {
|
|
963
|
+
items: review.chatReports({
|
|
964
|
+
limit: Number(url.searchParams.get('limit') ?? 200),
|
|
965
|
+
since: Number(url.searchParams.get('since') ?? 0),
|
|
966
|
+
}),
|
|
967
|
+
})
|
|
968
|
+
}
|
|
969
|
+
// /api/review/chat-report?session_id=&limit=&since= … その会話に流す完了報告
|
|
970
|
+
// (監視 cron が起票元の会話へ返す 1 行。端末はチャットタブが 15 秒ごとに読む)
|
|
971
|
+
if (b === 'chat-report' && req.method === 'GET') {
|
|
972
|
+
const sessionId = String(url.searchParams.get('session_id') || '')
|
|
973
|
+
if (!sessionId) return sendError(res, 400, 'SESSION_REQUIRED')
|
|
974
|
+
return sendJson(res, 200, {
|
|
975
|
+
sessionId,
|
|
976
|
+
items: review.chatReport(sessionId, {
|
|
977
|
+
limit: Number(url.searchParams.get('limit') ?? 3),
|
|
978
|
+
since: Number(url.searchParams.get('since') ?? 0),
|
|
979
|
+
}),
|
|
980
|
+
})
|
|
981
|
+
}
|
|
982
|
+
// /api/review/:id/session … 実行ワーカーの session_id を解決する
|
|
983
|
+
if (c === 'session' && req.method === 'GET') {
|
|
984
|
+
const info = review.sessionId(b)
|
|
985
|
+
if (!info) return sendError(res, 404, 'NO_SESSION')
|
|
986
|
+
return sendJson(res, 200, { taskId: b, status: info.status, sessionId: info.sessionId })
|
|
987
|
+
}
|
|
988
|
+
if (c === 'worker' && req.method === 'GET') {
|
|
989
|
+
// worker(profile mobile)の進行を読む。session.resume は通らないので state.db を直接読む
|
|
990
|
+
const info = review.sessionId(b)
|
|
991
|
+
if (!info) return sendError(res, 404, 'NO_SESSION')
|
|
992
|
+
const { feed, db, profile } = await readWorkerFeed(info.sessionId, info, Number(url.searchParams.get('limit') ?? 40))
|
|
993
|
+
return sendJson(res, 200, { taskId: b, status: info.status, sessionId: info.sessionId, db, profile, feed })
|
|
994
|
+
}
|
|
995
|
+
// /api/review/library … 注釈の下地にできる画像(library + shots)
|
|
996
|
+
// /api/review/library/file?path= … その画像
|
|
997
|
+
// /api/review/from-image … 画像から注釈タスクを1件作る
|
|
998
|
+
if (b === 'targets') {
|
|
999
|
+
return sendJson(res, 200, { targets: review.targets() })
|
|
1000
|
+
}
|
|
1001
|
+
if (b === 'library' && !c) {
|
|
1002
|
+
return sendJson(res, 200, { items: review.library(Number(url.searchParams.get('limit') ?? 60)) })
|
|
1003
|
+
}
|
|
1004
|
+
if (b === 'library' && c === 'file' && req.method === 'GET') {
|
|
1005
|
+
const r = review.libraryFile(String(url.searchParams.get('path') || ''))
|
|
1006
|
+
if (!r.ok) return sendFailure(res, 404, r)
|
|
1007
|
+
res.writeHead(200, { 'content-type': r.type, 'cache-control': 'private, max-age=600' })
|
|
1008
|
+
return res.end(r.data)
|
|
1009
|
+
}
|
|
1010
|
+
// POST /api/review/annotation/new … 画像から注釈タスクを1件作る(SPEC §4.2)
|
|
1011
|
+
// 旧 `/api/review/from-image` は、配信済み dist を掴んだ端末のために受け続ける。
|
|
1012
|
+
if (((b === 'annotation' && c === 'new') || b === 'from-image') && req.method === 'POST') {
|
|
1013
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1014
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1015
|
+
}
|
|
1016
|
+
const body = await readJson(req, 12_000_000)
|
|
1017
|
+
const r = await review.createFromImage(body || {})
|
|
1018
|
+
auth.audit({ kind: 'review.from_image', task: r.taskId ?? null, source: body?.source ?? 'upload', ok: Boolean(r.ok) })
|
|
1019
|
+
return r.ok ? sendJson(res, 201, r) : sendFailure(res, 400, r)
|
|
1020
|
+
}
|
|
1021
|
+
if (c === 'image' && req.method === 'GET') {
|
|
1022
|
+
const r = review.image(b, {
|
|
1023
|
+
annotated: url.searchParams.get('annotated') === '1',
|
|
1024
|
+
// compare=1 … Before(前回の赤入れ/前ラウンド)画像。SPEC §5.2
|
|
1025
|
+
compare: url.searchParams.get('compare') === '1',
|
|
1026
|
+
})
|
|
1027
|
+
if (!r.ok) return sendFailure(res, 404, r)
|
|
1028
|
+
res.writeHead(200, { 'content-type': r.type, 'cache-control': 'private, max-age=120' })
|
|
1029
|
+
return res.end(r.data)
|
|
1030
|
+
}
|
|
1031
|
+
if (c === 'annotation' && req.method === 'GET') {
|
|
1032
|
+
const r = review.annotation(b)
|
|
1033
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 404, r)
|
|
1034
|
+
}
|
|
1035
|
+
if (c === 'annotation' && req.method === 'POST') {
|
|
1036
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1037
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1038
|
+
}
|
|
1039
|
+
// 画像は base64 で来るので、この経路だけ上限を上げる(既定は 1MB)
|
|
1040
|
+
const body = await readJson(req, 12_000_000)
|
|
1041
|
+
const r = await review.saveAnnotation(b, body || {})
|
|
1042
|
+
auth.audit({
|
|
1043
|
+
kind: 'review.annotation',
|
|
1044
|
+
task: b,
|
|
1045
|
+
duplicate: Boolean(r.duplicate),
|
|
1046
|
+
marks: r.marks ?? 0,
|
|
1047
|
+
ok: Boolean(r.ok),
|
|
1048
|
+
})
|
|
1049
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 400, r)
|
|
1050
|
+
}
|
|
1051
|
+
if (c === 'sheet' && req.method === 'GET') {
|
|
1052
|
+
const r = review.sheetHtml(b)
|
|
1053
|
+
if (!r.ok) return sendFailure(res, r.code === 'NOT_FOUND' ? 404 : 409, r)
|
|
1054
|
+
// D57: 埋め込みでも単体タブでも**同じ**厳格な CSP(sandbox = 不透明オリジン)で返す。
|
|
1055
|
+
// シート内のスクリプトは same-origin Cookie にも /ws/term にも /api/* にも届かない。
|
|
1056
|
+
// 回答は postMessage で親(PWA の iframe / :id/view ラッパー)へ渡し、親が POST する。
|
|
1057
|
+
res.writeHead(200, reviewSheetHeaders())
|
|
1058
|
+
return res.end(injectReviewBridge(r.html, b))
|
|
1059
|
+
}
|
|
1060
|
+
// /api/review/:id/view … 単体タブ用のラッパー(D57)。
|
|
1061
|
+
// シートを sandbox iframe で囲み、postMessage を受けて same-origin で回答を POST する。
|
|
1062
|
+
// 存在判定は sheetHtml(.html が無くても .json から生成できる)に合わせる。
|
|
1063
|
+
if (c === 'view' && req.method === 'GET') {
|
|
1064
|
+
const r = review.sheetHtml(b)
|
|
1065
|
+
if (!r.ok) return sendFailure(res, r.code === 'NOT_FOUND' ? 404 : 409, r)
|
|
1066
|
+
res.writeHead(200, reviewViewHeaders())
|
|
1067
|
+
return res.end(reviewViewHtml(b))
|
|
1068
|
+
}
|
|
1069
|
+
if (c === 'thumb' && req.method === 'GET') {
|
|
1070
|
+
const rel = url.pathname.split('/').slice(5).join('/')
|
|
1071
|
+
const r = review.thumb(decodeURIComponent(rel))
|
|
1072
|
+
if (!r.ok) return sendFailure(res, 404, r)
|
|
1073
|
+
res.writeHead(200, { 'content-type': r.type, 'cache-control': 'private, max-age=600' })
|
|
1074
|
+
return res.end(r.data)
|
|
1075
|
+
}
|
|
1076
|
+
if (c === 'data' && req.method === 'GET') {
|
|
1077
|
+
const r = review.sheetData(b)
|
|
1078
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 409, r)
|
|
1079
|
+
}
|
|
1080
|
+
if (c === 'answer' && req.method === 'POST') {
|
|
1081
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1082
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1083
|
+
}
|
|
1084
|
+
const body = await readJson(req)
|
|
1085
|
+
const r = await review.answer(b, body || {})
|
|
1086
|
+
auth.audit({
|
|
1087
|
+
kind: 'review.answer',
|
|
1088
|
+
task: b,
|
|
1089
|
+
duplicate: Boolean(r.duplicate),
|
|
1090
|
+
choiceCount: Array.isArray(body?.answers) ? body.answers.length : 0,
|
|
1091
|
+
ok: Boolean(r.ok),
|
|
1092
|
+
})
|
|
1093
|
+
// レビュー待ち以外への送信は 409(状態の衝突)として返す。他の失敗は 400。
|
|
1094
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, r.code === 'NOT_WAITING' ? 409 : 400, r)
|
|
1095
|
+
}
|
|
1096
|
+
if (c === 'reopen' && req.method === 'POST') {
|
|
1097
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1098
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1099
|
+
}
|
|
1100
|
+
const body = await readJson(req)
|
|
1101
|
+
const r = await review.reopen(b, body?.reason)
|
|
1102
|
+
auth.audit({ kind: 'review.reopen', task: b, ok: Boolean(r.ok) })
|
|
1103
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 400, r)
|
|
1104
|
+
}
|
|
1105
|
+
// POST /api/review/:id/approve … 赤入れせずに 1 タップ検収(SPEC §5.2.3)
|
|
1106
|
+
// コメント `Visual check passed` を残して done(作業済み)または unblock(未作業)へ進める。
|
|
1107
|
+
if (c === 'approve' && req.method === 'POST') {
|
|
1108
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1109
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1110
|
+
}
|
|
1111
|
+
const body = await readJson(req)
|
|
1112
|
+
const r = await review.approve(b, body || {})
|
|
1113
|
+
auth.audit({
|
|
1114
|
+
kind: 'review.approve',
|
|
1115
|
+
task: b,
|
|
1116
|
+
duplicate: Boolean(r.duplicate),
|
|
1117
|
+
moved: r.moved ?? null,
|
|
1118
|
+
ok: Boolean(r.ok),
|
|
1119
|
+
})
|
|
1120
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, r.code === 'NOT_WAITING' ? 409 : 400, r)
|
|
1121
|
+
}
|
|
1122
|
+
return sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// --- 読み取り専用トランスクリプト ------------------------------------------
|
|
1126
|
+
// /api/sessions/:id/transcript … カンバン作業ログなど resume できない会話
|
|
1127
|
+
if (a === 'sessions' && b && c === 'transcript' && req.method === 'GET') {
|
|
1128
|
+
if (!readAllowed('transcript', cfg.rate.maxReads ?? 240, cfg.rate.windowMs)) {
|
|
1129
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1130
|
+
}
|
|
1131
|
+
const profileName = url.searchParams.get('profile')
|
|
1132
|
+
const profiles = profileName ? await listProfiles() : []
|
|
1133
|
+
const r = transcript.read(decodeURIComponent(b), {
|
|
1134
|
+
limit: Number(url.searchParams.get('limit') ?? 200),
|
|
1135
|
+
before: Number(url.searchParams.get('before') ?? 0),
|
|
1136
|
+
includeTools: url.searchParams.get('tools') === '1',
|
|
1137
|
+
dbPath: profileName ? stateDbFor(profiles, profileName) : undefined,
|
|
1138
|
+
})
|
|
1139
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 404, r)
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
// --- ライブ進捗(実行中ターンと実行中タスク)--------------------------------
|
|
1143
|
+
// /api/live … 5秒ポーリング前提。全プロファイルの state.db のリースとカンバンを合成する
|
|
1144
|
+
if (a === 'live' && req.method === 'GET') {
|
|
1145
|
+
if (!readAllowed('live', cfg.rate.maxReads ?? 240, cfg.rate.windowMs)) {
|
|
1146
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1147
|
+
}
|
|
1148
|
+
// Architect(仕様策定)は カンバンタスクを持たない Agy Opt-in ジョブも含めて
|
|
1149
|
+
// ボード横断で拾う(SPEC-PILOT-V9 §3.2)。取れなくても /api/live は返す。
|
|
1150
|
+
let archJobs = []
|
|
1151
|
+
try {
|
|
1152
|
+
const archSnap = await architect.jobs({ strictBoard: false })
|
|
1153
|
+
archJobs = Array.isArray(archSnap?.jobs) ? archSnap.jobs : []
|
|
1154
|
+
} catch {
|
|
1155
|
+
archJobs = []
|
|
1156
|
+
}
|
|
1157
|
+
const r = live.snapshot({ dbs: await listStateDbs(), architect: archJobs })
|
|
1158
|
+
// Discord 由来のターンにはスレッドリンクを添える
|
|
1159
|
+
for (const t of r.turns) {
|
|
1160
|
+
const link = discord.forSession(t.sessionId)
|
|
1161
|
+
if (link) t.discordUrl = link.url
|
|
1162
|
+
}
|
|
1163
|
+
return sendJson(res, 200, r)
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// --- アイコン取得ログ(インストール時の実態確認)----------------------------
|
|
1167
|
+
if (a === 'asset-log' && req.method === 'GET') {
|
|
1168
|
+
const n = Math.min(Math.max(Number(url.searchParams.get('lines') ?? 40), 1), 200)
|
|
1169
|
+
let lines = []
|
|
1170
|
+
try {
|
|
1171
|
+
const txt = readTailText(path.join(cfg.dataDir, 'asset-access.log'), 128 * 1024)
|
|
1172
|
+
lines = txt.trim().split('\n').slice(-n)
|
|
1173
|
+
} catch {
|
|
1174
|
+
lines = []
|
|
1175
|
+
}
|
|
1176
|
+
return sendJson(res, 200, { lines })
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// --- 承認待ちインボックス --------------------------------------------------
|
|
1180
|
+
// /api/inbox … ボード横断の blocked タスク(読む+コメントで答える)
|
|
1181
|
+
if (a === 'inbox' && req.method === 'GET') {
|
|
1182
|
+
if (!readAllowed('inbox', cfg.rate.maxReads ?? 240, cfg.rate.windowMs)) {
|
|
1183
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1184
|
+
}
|
|
1185
|
+
return sendJson(res, 200, inbox.list())
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// --- 使用量(コスト・トークン)----------------------------------------------
|
|
1189
|
+
// /api/usage?hours=24 … 合計とモデル別・上位セッション(全プロファイル合算)
|
|
1190
|
+
if (a === 'usage' && req.method === 'GET') {
|
|
1191
|
+
const r = usage.summary({ hours: Number(url.searchParams.get('hours') ?? 24), dbs: await listStateDbs() })
|
|
1192
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 500, r)
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// --- Zero-Typing 実行サマリ(完了レシート)-----------------------------------
|
|
1196
|
+
// /api/telemetry/receipt?board=<slug>&spec=<rel>&hours=24
|
|
1197
|
+
// コスト / キャッシュ率 / 推定節約額 / 操作メトリクス(タップ・赤入れ・入力文字)を
|
|
1198
|
+
// 読み取り専用で集計する。欠損は 500 にせず、その項目を null + missing で返す。
|
|
1199
|
+
if (a === 'telemetry' && b === 'receipt' && req.method === 'GET') {
|
|
1200
|
+
if (!readAllowed('telemetry', cfg.rate.maxReads ?? 240, cfg.rate.windowMs)) {
|
|
1201
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1202
|
+
}
|
|
1203
|
+
const r = telemetry.receipt({
|
|
1204
|
+
board: String(url.searchParams.get('board') ?? '').trim(),
|
|
1205
|
+
spec: String(url.searchParams.get('spec') ?? '').trim(),
|
|
1206
|
+
hours: Number(url.searchParams.get('hours') ?? 24),
|
|
1207
|
+
dbs: await listStateDbs(),
|
|
1208
|
+
})
|
|
1209
|
+
return sendJson(res, 200, r)
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// --- 横断検索 --------------------------------------------------------------
|
|
1213
|
+
// /api/search?q=&limit=&hours= … 全プロファイル・全セッションの発言から抜粋を返す(読み取り専用)
|
|
1214
|
+
if (a === 'search' && req.method === 'GET') {
|
|
1215
|
+
const q = String(url.searchParams.get('q') ?? '')
|
|
1216
|
+
if (!q.trim()) return sendError(res, 400, 'QUERY_REQUIRED')
|
|
1217
|
+
if (!readAllowed('search', cfg.rate.maxReads ?? 240, cfg.rate.windowMs)) {
|
|
1218
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1219
|
+
}
|
|
1220
|
+
const r = search.search({
|
|
1221
|
+
q,
|
|
1222
|
+
limit: Number(url.searchParams.get('limit') ?? 30),
|
|
1223
|
+
hours: Number(url.searchParams.get('hours') ?? 0),
|
|
1224
|
+
dbs: await listStateDbs(),
|
|
1225
|
+
})
|
|
1226
|
+
// 該当セッションが Discord 由来ならスレッドリンクも添える
|
|
1227
|
+
if (r.ok) {
|
|
1228
|
+
for (const h of r.hits) {
|
|
1229
|
+
const link = discord.forSession(h.sessionId)
|
|
1230
|
+
if (link) h.discordUrl = link.url
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
return r.ok ? sendJson(res, 200, r) : sendFailure(res, 400, r)
|
|
1234
|
+
}
|
|
1235
|
+
|
|
1236
|
+
// --- Discord ディープリンク ------------------------------------------------
|
|
1237
|
+
// /api/discord/session?session_id=... … そのセッションの Discord スレッド
|
|
1238
|
+
if (a === 'discord' && b === 'session' && req.method === 'GET') {
|
|
1239
|
+
const sid = url.searchParams.get('session_id')
|
|
1240
|
+
const link = discord.forSession(sid)
|
|
1241
|
+
return sendJson(res, link ? 200 : 404, link ? { link } : { link: null })
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
if (a === 'gateway' && b && req.method === 'POST') {
|
|
1245
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) return sendError(res, 429, 'RATE_LIMITED')
|
|
1246
|
+
const body = await readJson(req)
|
|
1247
|
+
const by = String(body?.by ?? 'mobile')
|
|
1248
|
+
if (b === 'pause' || b === 'resume') {
|
|
1249
|
+
const expected = b.toUpperCase()
|
|
1250
|
+
if (String(body?.confirm ?? '').toUpperCase() !== expected) {
|
|
1251
|
+
return sendError(res, 400, 'CONFIRM_MISMATCH', { expected })
|
|
1252
|
+
}
|
|
1253
|
+
const out = b === 'pause' ? await ops.pause(String(body?.reason ?? 'mobile'), by) : await ops.resume(by)
|
|
1254
|
+
return sendJson(res, 200, out)
|
|
1255
|
+
}
|
|
1256
|
+
const out = await ops.gateway(b, body?.confirm, by)
|
|
1257
|
+
return sendJson(res, 200, out)
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
if (a === 'sessions') {
|
|
1261
|
+
const limit = Number(url.searchParams.get('limit') ?? 20)
|
|
1262
|
+
// タスクタブは全ボード横断なので、チャットも全プロファイル横断にする。
|
|
1263
|
+
// ダッシュボード API は ?profile= を受けるので、列挙して合成する。
|
|
1264
|
+
const profiles = await listProfiles()
|
|
1265
|
+
const names = profiles.length ? profiles.map((p) => p.name) : [null]
|
|
1266
|
+
const perProfile = await Promise.all(
|
|
1267
|
+
names.map(async (name) => {
|
|
1268
|
+
const qs = new URLSearchParams({ limit: String(limit) })
|
|
1269
|
+
if (name) qs.set('profile', name)
|
|
1270
|
+
const r = await hermes.call(`/api/sessions?${qs}`, { timeoutMs: 10000 })
|
|
1271
|
+
if (r.status !== 200) return []
|
|
1272
|
+
return (r.data?.sessions ?? []).map((s) => ({
|
|
1273
|
+
id: s.id,
|
|
1274
|
+
title: s.title ?? s.display_name ?? s.session_key ?? s.id,
|
|
1275
|
+
source: s.source,
|
|
1276
|
+
model: s.model,
|
|
1277
|
+
profile: name ?? 'default',
|
|
1278
|
+
active: Boolean(s.is_active),
|
|
1279
|
+
lastActivity: s.last_activity_description ?? null,
|
|
1280
|
+
lastActive: s.last_active ? Number(s.last_active) * 1000 : null,
|
|
1281
|
+
messages: s.message_count ?? 0,
|
|
1282
|
+
tools: s.tool_call_count ?? 0,
|
|
1283
|
+
cost: s.estimated_cost_usd ?? null,
|
|
1284
|
+
preview: s.preview ?? null,
|
|
1285
|
+
}))
|
|
1286
|
+
}),
|
|
1287
|
+
)
|
|
1288
|
+
const sessions = perProfile
|
|
1289
|
+
.flat()
|
|
1290
|
+
.sort((x, y) => (y.lastActive ?? 0) - (x.lastActive ?? 0))
|
|
1291
|
+
.slice(0, limit)
|
|
1292
|
+
return sendJson(res, 200, { sessions, profiles: names.filter(Boolean) })
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// --- 端末の定型コマンド ---------------------------------------------------
|
|
1296
|
+
if (a === 'snippets' && b === 'term') {
|
|
1297
|
+
if (req.method === 'GET') return sendJson(res, 200, snippetPayload('term', langOf(req, url)))
|
|
1298
|
+
if (req.method === 'PUT') {
|
|
1299
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1300
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1301
|
+
}
|
|
1302
|
+
const body = await readJson(req)
|
|
1303
|
+
const saved = saveSnippetStore('term', body ?? {})
|
|
1304
|
+
auth.audit({ kind: 'term_snippets.save', count: saved.custom.length, overrides: Object.keys(saved.overrides).length })
|
|
1305
|
+
return sendJson(res, 200, snippetPayload('term', langOf(req, url)))
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// --- メモ・ひらめき・受信箱 ----------------------------------------------
|
|
1310
|
+
if (a === 'memos' && !b) {
|
|
1311
|
+
if (req.method === 'GET') {
|
|
1312
|
+
return sendJson(res, 200, { ok: true, memos: memos.list() })
|
|
1313
|
+
}
|
|
1314
|
+
if (req.method === 'POST') {
|
|
1315
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1316
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1317
|
+
}
|
|
1318
|
+
const body = await readJson(req)
|
|
1319
|
+
const memo = memos.create(body ?? {})
|
|
1320
|
+
auth.audit({ kind: 'memos.create', id: memo.id, memoKind: memo.kind })
|
|
1321
|
+
return sendJson(res, 201, { ok: true, memo })
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
if (a === 'memos' && b && !c) {
|
|
1325
|
+
if (req.method === 'PATCH') {
|
|
1326
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1327
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1328
|
+
}
|
|
1329
|
+
const body = await readJson(req)
|
|
1330
|
+
const memo = memos.update(b, body ?? {})
|
|
1331
|
+
return sendJson(res, 200, { ok: true, memo })
|
|
1332
|
+
}
|
|
1333
|
+
if (req.method === 'DELETE') {
|
|
1334
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1335
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1336
|
+
}
|
|
1337
|
+
const out = memos.remove(b)
|
|
1338
|
+
return sendJson(res, 200, out)
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
// --- 定型スニペット ------------------------------------------------------
|
|
1343
|
+
if (a === 'snippets') {
|
|
1344
|
+
if (req.method === 'GET') {
|
|
1345
|
+
return sendJson(res, 200, snippetPayload('chat', langOf(req, url)))
|
|
1346
|
+
}
|
|
1347
|
+
if (req.method === 'PUT') {
|
|
1348
|
+
if (!writeAllowed(cfg.rate.maxWrites, cfg.rate.windowMs)) {
|
|
1349
|
+
return sendError(res, 429, 'RATE_LIMITED')
|
|
1350
|
+
}
|
|
1351
|
+
const body = await readJson(req)
|
|
1352
|
+
const saved = saveSnippetStore('chat', body ?? {})
|
|
1353
|
+
auth.audit({ kind: 'snippets.save', count: saved.custom.length, overrides: Object.keys(saved.overrides).length })
|
|
1354
|
+
return sendJson(res, 200, snippetPayload('chat', langOf(req, url)))
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
// --- 端末側の例外を受け取る(下部ナビ消失などの原因調査用)-------------
|
|
1359
|
+
if (a === 'client-error' && req.method === 'POST') {
|
|
1360
|
+
if (!writeAllowed(30, 60_000)) return sendError(res, 429, 'RATE_LIMITED')
|
|
1361
|
+
const body = await readJson(req, 200_000)
|
|
1362
|
+
try {
|
|
1363
|
+
fs.mkdirSync(cfg.dataDir, { recursive: true })
|
|
1364
|
+
fs.appendFileSync(
|
|
1365
|
+
path.join(cfg.dataDir, 'client-errors.log'),
|
|
1366
|
+
`${JSON.stringify({ at: new Date().toISOString(), ...body })}\n`,
|
|
1367
|
+
)
|
|
1368
|
+
} catch {
|
|
1369
|
+
/* 記録に失敗しても返すだけ */
|
|
1370
|
+
}
|
|
1371
|
+
return sendJson(res, 200, { ok: true })
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
if (a === 'logs') {
|
|
1375
|
+
const name = url.searchParams.get('file') ?? 'gateway'
|
|
1376
|
+
const lines = Number(url.searchParams.get('lines') ?? 200)
|
|
1377
|
+
return sendJson(res, 200, { file: name, text: tailLog(name, lines) })
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
if (a === 'audit') {
|
|
1381
|
+
let text = ''
|
|
1382
|
+
try {
|
|
1383
|
+
text = readTailText(cfg.auditPath, 128 * 1024)
|
|
1384
|
+
} catch {
|
|
1385
|
+
text = ''
|
|
1386
|
+
}
|
|
1387
|
+
const rawLines = text.split('\n').filter(Boolean).slice(-Number(url.searchParams.get('lines') ?? 100))
|
|
1388
|
+
const parsed = []
|
|
1389
|
+
for (const l of rawLines) {
|
|
1390
|
+
try {
|
|
1391
|
+
parsed.push(JSON.parse(l))
|
|
1392
|
+
} catch {
|
|
1393
|
+
/* 壊れた行は捨てる */
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
return sendJson(res, 200, { lines: parsed })
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
sendError(res, 404, 'UNKNOWN_ENDPOINT', { path: url.pathname })
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* 認証不要で配るパス(アプリの殻)。
|
|
1404
|
+
*
|
|
1405
|
+
* WebAPK の生成は **Google のサーバーが認証なしで** manifest / アイコン / start_url を
|
|
1406
|
+
* 取得するため、ここを Cookie の内側に置くと Android で
|
|
1407
|
+
* 「This app cannot be installed」になる(実測)。データ(/api, /ws)は必ず認証の内側。
|
|
1408
|
+
* @param {string} pathname パス
|
|
1409
|
+
* @returns {boolean} 公開してよいか
|
|
1410
|
+
*/
|
|
1411
|
+
function isPublicPath(pathname) {
|
|
1412
|
+
if (pathname === '/' || pathname === '/index.html') return true
|
|
1413
|
+
if (pathname === '/healthz' || pathname === '/auth') return true
|
|
1414
|
+
if (pathname === '/manifest.webmanifest' || pathname === '/sw.js' || pathname === '/favicon.ico') return true
|
|
1415
|
+
if (pathname.startsWith('/assets/')) return true
|
|
1416
|
+
if (/^\/icon(-[a-z0-9-]+)?\.(png|svg)$/i.test(pathname)) return true
|
|
1417
|
+
return false
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
/** アイコン/manifest の取得を記録する(インストール時に端末が何を取りに来たか確認するため)。 */
|
|
1421
|
+
function logAssetAccess(cfg, req, url) {
|
|
1422
|
+
const p = url.pathname
|
|
1423
|
+
if (!/^\/(icon|manifest\.webmanifest|sw\.js|favicon)/.test(p)) return
|
|
1424
|
+
try {
|
|
1425
|
+
const line = JSON.stringify({
|
|
1426
|
+
at: new Date().toISOString(),
|
|
1427
|
+
p,
|
|
1428
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 200),
|
|
1429
|
+
ref: String(req.headers.referer ?? '').slice(0, 120),
|
|
1430
|
+
})
|
|
1431
|
+
fs.appendFile(path.join(cfg.dataDir, 'asset-access.log'), `${line}\n`, () => {})
|
|
1432
|
+
} catch {
|
|
1433
|
+
/* noop */
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
const server = http.createServer(async (req, res) => {
|
|
1438
|
+
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`)
|
|
1439
|
+
logAssetAccess(cfg, req, url)
|
|
1440
|
+
|
|
1441
|
+
if (url.pathname === '/healthz') return sendJson(res, 200, { ok: true, version: VERSION })
|
|
1442
|
+
|
|
1443
|
+
// 認証(/auth はトークン交換のみ)
|
|
1444
|
+
if (url.pathname === '/auth') {
|
|
1445
|
+
const value = auth.exchange(url.searchParams.get('t'))
|
|
1446
|
+
if (!value) {
|
|
1447
|
+
res.writeHead(401, { 'content-type': 'text/html; charset=utf-8' }).end(LOGIN_HTML)
|
|
1448
|
+
return
|
|
1449
|
+
}
|
|
1450
|
+
res.writeHead(302, { 'set-cookie': auth.cookieHeader(value), location: '/' }).end()
|
|
1451
|
+
return
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// ワンタップ QR ペアリング: `?token=` を HttpOnly Cookie に交換する(SPEC §8.2)。
|
|
1455
|
+
// 殻(/ と /assets)は公開なので、未ログインでもこの 1 本だけは叩ける。
|
|
1456
|
+
// 照合は auth.exchange(定数時間比較)に任せ、成功時だけ Cookie を返す。
|
|
1457
|
+
if (url.pathname === '/api/auth/login') {
|
|
1458
|
+
if (req.method !== 'POST') return sendError(res, 405, 'METHOD_NOT_ALLOWED')
|
|
1459
|
+
if (!loginAllowed()) return sendError(res, 429, 'RATE_LIMITED')
|
|
1460
|
+
let body = {}
|
|
1461
|
+
try {
|
|
1462
|
+
body = await readJson(req, 4096)
|
|
1463
|
+
} catch {
|
|
1464
|
+
body = {}
|
|
1465
|
+
}
|
|
1466
|
+
const given = typeof body?.token === 'string' ? body.token : (url.searchParams.get('token') ?? '')
|
|
1467
|
+
const value = auth.exchange(given)
|
|
1468
|
+
if (!value) {
|
|
1469
|
+
auth.audit({ kind: 'auth.login', ok: false })
|
|
1470
|
+
return sendError(res, 401, 'AUTH_REQUIRED')
|
|
1471
|
+
}
|
|
1472
|
+
auth.audit({ kind: 'auth.login', ok: true })
|
|
1473
|
+
const payload = JSON.stringify({ ok: true })
|
|
1474
|
+
res.writeHead(200, {
|
|
1475
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1476
|
+
'content-length': Buffer.byteLength(payload),
|
|
1477
|
+
'cache-control': 'no-store',
|
|
1478
|
+
'set-cookie': auth.cookieHeader(value),
|
|
1479
|
+
})
|
|
1480
|
+
return res.end(payload)
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
if (!isPublicPath(url.pathname) && !auth.authorized(req)) {
|
|
1484
|
+
if (url.pathname.startsWith('/api/')) return sendError(res, 401, 'AUTH_REQUIRED')
|
|
1485
|
+
res.writeHead(401, { 'content-type': 'text/html; charset=utf-8' }).end(LOGIN_HTML)
|
|
1486
|
+
return
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
// 殻は公開、API は認証必須(殻の中の /api/* 呼び出しで 401 を受けたら UI がログインを出す)
|
|
1490
|
+
if (url.pathname.startsWith('/api/') && !auth.authorized(req)) {
|
|
1491
|
+
return sendError(res, 401, 'AUTH_REQUIRED')
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
try {
|
|
1495
|
+
if (url.pathname.startsWith('/api/')) return await handleApi(req, res, url)
|
|
1496
|
+
return serveStatic(req, res, url.pathname)
|
|
1497
|
+
} catch (err) {
|
|
1498
|
+
const status = err?.statusCode ?? 500
|
|
1499
|
+
if (status >= 500) console.error('[api] 失敗:', err)
|
|
1500
|
+
// `ApiError` など `code` / `params` を持つ throw はそのコードで返す(SPEC-i18n-resp B1)。
|
|
1501
|
+
const code = typeof err?.code === 'string' && err.code ? err.code : status >= 500 ? 'INTERNAL' : 'BAD_REQUEST'
|
|
1502
|
+
sendFailure(res, status, { code, params: err?.params, message: String(err?.message ?? '') })
|
|
1503
|
+
}
|
|
1504
|
+
})
|
|
1505
|
+
|
|
1506
|
+
// --- WebSocket -------------------------------------------------------------
|
|
1507
|
+
|
|
1508
|
+
const wssChat = new WebSocketServer({ noServer: true })
|
|
1509
|
+
const wssTerm = new WebSocketServer({ noServer: true })
|
|
1510
|
+
|
|
1511
|
+
server.on('upgrade', (req, socket, head) => {
|
|
1512
|
+
if (!isAllowedWsOrigin(req)) {
|
|
1513
|
+
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
|
|
1514
|
+
socket.destroy()
|
|
1515
|
+
return
|
|
1516
|
+
}
|
|
1517
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
1518
|
+
if (!auth.authorized(req)) {
|
|
1519
|
+
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n')
|
|
1520
|
+
socket.destroy()
|
|
1521
|
+
return
|
|
1522
|
+
}
|
|
1523
|
+
if (url.pathname === '/ws/chat') {
|
|
1524
|
+
wssChat.handleUpgrade(req, socket, head, (ws) => proxyChat(ws))
|
|
1525
|
+
return
|
|
1526
|
+
}
|
|
1527
|
+
if (url.pathname === '/ws/term') {
|
|
1528
|
+
wssTerm.handleUpgrade(req, socket, head, (ws) => openTerm(ws))
|
|
1529
|
+
return
|
|
1530
|
+
}
|
|
1531
|
+
socket.write('HTTP/1.1 404 Not Found\r\n\r\n')
|
|
1532
|
+
socket.destroy()
|
|
1533
|
+
})
|
|
1534
|
+
|
|
1535
|
+
/**
|
|
1536
|
+
* チャット WS を Hermes の /api/ws へ中継する(プロトコルは素通し)。
|
|
1537
|
+
* 端末からは JSON-RPC がそのまま見えるので、探針テストと同じ経路になる。
|
|
1538
|
+
* @param {WebSocket} client 端末側
|
|
1539
|
+
*/
|
|
1540
|
+
async function proxyChat(client) {
|
|
1541
|
+
let upstream
|
|
1542
|
+
const started = Date.now()
|
|
1543
|
+
// この接続で送ってよいプロファイル名(serve 済み)。取れなければ default のみ。
|
|
1544
|
+
// **listener より先に await しない**: 待つ間に届いた端末フレームは listener が無いと捨てられる
|
|
1545
|
+
// (実測: 最初の session.list が消えて 20 秒タイムアウトした)。解決までは hold に溜める。
|
|
1546
|
+
let allowed = []
|
|
1547
|
+
let allowedReady = false
|
|
1548
|
+
const hold = []
|
|
1549
|
+
/** @type {string[]} */
|
|
1550
|
+
const queue = []
|
|
1551
|
+
listProfiles()
|
|
1552
|
+
.then((list) => {
|
|
1553
|
+
allowed = (list ?? []).map((p) => p.name).filter(Boolean)
|
|
1554
|
+
})
|
|
1555
|
+
.catch(() => {})
|
|
1556
|
+
.finally(() => {
|
|
1557
|
+
allowedReady = true
|
|
1558
|
+
for (const t of hold.splice(0)) forward(t)
|
|
1559
|
+
})
|
|
1560
|
+
|
|
1561
|
+
/** 1 フレームを検証して上流へ流す(プロファイル検証はここだけ)。 */
|
|
1562
|
+
function forward(text) {
|
|
1563
|
+
const checked = checkFrame(text, allowed)
|
|
1564
|
+
if (!checked.ok) {
|
|
1565
|
+
// 上流には流さない。端末には JSON-RPC エラーとして返す(SPEC-PROFILE-CHAT 決定 D1)
|
|
1566
|
+
if (client.readyState === WebSocket.OPEN) client.send(rejectionFrame(checked.id, checked.message))
|
|
1567
|
+
auth.audit({ kind: 'chat.profile', method: checked.method, profile: checked.profile, blocked: true })
|
|
1568
|
+
return
|
|
1569
|
+
}
|
|
1570
|
+
if (checked.profile) auth.audit({ kind: 'chat.profile', method: checked.method, profile: checked.profile })
|
|
1571
|
+
const out = checked.text
|
|
1572
|
+
if (upstream?.readyState === WebSocket.OPEN) upstream.send(out)
|
|
1573
|
+
else queue.push(out)
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
try {
|
|
1577
|
+
// 端末が繋ぐたびにトークンを取り直す(gateway 再起動後の 403 を自己回復)
|
|
1578
|
+
upstream = new WebSocket(await hermes.wsUrl('/api/ws', { fresh: true }), { headers: { Origin: cfg.hermesBase } })
|
|
1579
|
+
} catch (err) {
|
|
1580
|
+
client.send(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'bridge.error', payload: { message: String(err?.message ?? err) } } }))
|
|
1581
|
+
client.close(1011)
|
|
1582
|
+
return
|
|
1583
|
+
}
|
|
1584
|
+
client.on('message', (raw) => {
|
|
1585
|
+
const text = raw.toString()
|
|
1586
|
+
if (!allowedReady) {
|
|
1587
|
+
hold.push(text)
|
|
1588
|
+
return
|
|
1589
|
+
}
|
|
1590
|
+
forward(text)
|
|
1591
|
+
})
|
|
1592
|
+
// 上流は無音で切ることがある(実測: code=1005 が散発)。25秒ごとに ping して
|
|
1593
|
+
// 「応答が来ないまま画面が止まる」を防ぐ。pong が90秒来なければ張り直す。
|
|
1594
|
+
let ka = null
|
|
1595
|
+
let lastPong = Date.now()
|
|
1596
|
+
|
|
1597
|
+
upstream.on('open', () => {
|
|
1598
|
+
for (const q of queue.splice(0)) upstream.send(q)
|
|
1599
|
+
client.send(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'bridge.ready', payload: {} } }))
|
|
1600
|
+
console.log(`[chat] upstream open (${Date.now() - started}ms)`)
|
|
1601
|
+
lastPong = Date.now()
|
|
1602
|
+
ka = setInterval(() => {
|
|
1603
|
+
if (upstream?.readyState !== WebSocket.OPEN) return
|
|
1604
|
+
if (Date.now() - lastPong > 90_000) {
|
|
1605
|
+
console.log('[chat] upstream silent 90s → close')
|
|
1606
|
+
try {
|
|
1607
|
+
upstream.terminate()
|
|
1608
|
+
} catch {}
|
|
1609
|
+
return
|
|
1610
|
+
}
|
|
1611
|
+
try {
|
|
1612
|
+
upstream.ping()
|
|
1613
|
+
} catch {}
|
|
1614
|
+
}, 25_000)
|
|
1615
|
+
})
|
|
1616
|
+
upstream.on('pong', () => {
|
|
1617
|
+
lastPong = Date.now()
|
|
1618
|
+
})
|
|
1619
|
+
upstream.on('message', (raw) => {
|
|
1620
|
+
if (client.readyState === WebSocket.OPEN) client.send(raw.toString())
|
|
1621
|
+
})
|
|
1622
|
+
const closeBoth = (code = 1000, reason = '') => {
|
|
1623
|
+
try {
|
|
1624
|
+
if (client.readyState === WebSocket.OPEN) client.close(code, reason)
|
|
1625
|
+
} catch {
|
|
1626
|
+
/* noop */
|
|
1627
|
+
}
|
|
1628
|
+
try {
|
|
1629
|
+
upstream.close()
|
|
1630
|
+
} catch {
|
|
1631
|
+
/* noop */
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
upstream.on('close', (code) => {
|
|
1635
|
+
if (ka) clearInterval(ka)
|
|
1636
|
+
console.log(`[chat] upstream closed code=${code} after ${Date.now() - started}ms`)
|
|
1637
|
+
closeBoth(code === 1000 ? 1000 : 1011, `upstream ${code}`)
|
|
1638
|
+
})
|
|
1639
|
+
upstream.on('error', () => closeBoth(1011, 'upstream error'))
|
|
1640
|
+
client.on('close', () => {
|
|
1641
|
+
try {
|
|
1642
|
+
upstream.close()
|
|
1643
|
+
} catch {
|
|
1644
|
+
/* noop */
|
|
1645
|
+
}
|
|
1646
|
+
})
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
/**
|
|
1650
|
+
* 端末(実 PTY)。Hermes 側に汎用シェルの口が無いためブリッジが PTY を持つ。
|
|
1651
|
+
* @param {WebSocket} ws 端末
|
|
1652
|
+
*/
|
|
1653
|
+
function openTerm(ws) {
|
|
1654
|
+
if (!pty) {
|
|
1655
|
+
ws.send(JSON.stringify({ t: 'out', d: '\r\n[bridge] node-pty が読み込めません\r\n' }))
|
|
1656
|
+
ws.close(1011)
|
|
1657
|
+
return
|
|
1658
|
+
}
|
|
1659
|
+
const shell = process.env.SHELL || '/bin/zsh'
|
|
1660
|
+
/** @type {any} */
|
|
1661
|
+
let proc
|
|
1662
|
+
try {
|
|
1663
|
+
proc = pty.spawn(shell, ['-l'], {
|
|
1664
|
+
name: 'xterm-256color',
|
|
1665
|
+
cols: 80,
|
|
1666
|
+
rows: 24,
|
|
1667
|
+
cwd: process.env.HOME,
|
|
1668
|
+
env: { ...process.env, TERM: 'xterm-256color' },
|
|
1669
|
+
})
|
|
1670
|
+
} catch (err) {
|
|
1671
|
+
// ここで例外を投げるとプロセスごと落ちる(実測: spawn-helper の実行権限欠落)
|
|
1672
|
+
auth.audit({ kind: 'term.error', message: String(err?.message ?? err) })
|
|
1673
|
+
ws.send(JSON.stringify({ t: 'out', d: `\r\n[bridge] PTY を起動できません: ${err?.message ?? err}\r\n` }))
|
|
1674
|
+
ws.close(1011)
|
|
1675
|
+
return
|
|
1676
|
+
}
|
|
1677
|
+
auth.audit({ kind: 'term.open', pid: proc.pid, shell })
|
|
1678
|
+
proc.onData((d) => {
|
|
1679
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ t: 'out', d }))
|
|
1680
|
+
})
|
|
1681
|
+
proc.onExit(({ exitCode }) => {
|
|
1682
|
+
auth.audit({ kind: 'term.exit', pid: proc.pid, exitCode })
|
|
1683
|
+
try {
|
|
1684
|
+
ws.close(1000, 'exit')
|
|
1685
|
+
} catch {
|
|
1686
|
+
/* noop */
|
|
1687
|
+
}
|
|
1688
|
+
})
|
|
1689
|
+
ws.on('message', (raw) => {
|
|
1690
|
+
let msg
|
|
1691
|
+
try {
|
|
1692
|
+
msg = JSON.parse(raw.toString())
|
|
1693
|
+
} catch {
|
|
1694
|
+
proc.write(raw.toString())
|
|
1695
|
+
return
|
|
1696
|
+
}
|
|
1697
|
+
if (msg?.t === 'in') proc.write(String(msg.d ?? ''))
|
|
1698
|
+
else if (msg?.t === 'resize') proc.resize(Math.max(20, Number(msg.c) || 80), Math.max(5, Number(msg.r) || 24))
|
|
1699
|
+
})
|
|
1700
|
+
ws.on('close', () => {
|
|
1701
|
+
auth.audit({ kind: 'term.close', pid: proc.pid })
|
|
1702
|
+
try {
|
|
1703
|
+
proc.kill()
|
|
1704
|
+
} catch {
|
|
1705
|
+
/* noop */
|
|
1706
|
+
}
|
|
1707
|
+
})
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
server.on('error', (err) => {
|
|
1711
|
+
if (err?.code === 'EADDRINUSE') {
|
|
1712
|
+
console.error(
|
|
1713
|
+
`[bridge] ポート ${cfg.port} は使用中です。手動起動したプロセスが残っていませんか: ` +
|
|
1714
|
+
`lsof -nP -iTCP:${cfg.port} -sTCP:LISTEN → hermes-pilot service restart(または launchctl kickstart -k gui/$(id -u)/ai.hermes.pilot)`,
|
|
1715
|
+
)
|
|
1716
|
+
process.exit(75)
|
|
1717
|
+
}
|
|
1718
|
+
console.error('[bridge] サーバエラー:', err)
|
|
1719
|
+
process.exit(1)
|
|
1720
|
+
})
|
|
1721
|
+
|
|
1722
|
+
server.listen(cfg.port, cfg.host, async () => {
|
|
1723
|
+
console.log(`[bridge] Hermes Pilot: http://${cfg.host}:${cfg.port}`)
|
|
1724
|
+
console.log(`[bridge] 上流: ${cfg.hermesBase}`)
|
|
1725
|
+
console.log(`[bridge] トークンファイル: ${cfg.tokenPath}`)
|
|
1726
|
+
console.log(`[bridge] 管理画面: http://${cfg.host}:${cfg.port}/auth`)
|
|
1727
|
+
// 内蔵ウォッチャー(D7)。初回はベースライン確立のみで過去分は通知しない。
|
|
1728
|
+
try {
|
|
1729
|
+
reviewWatcher.start()
|
|
1730
|
+
} catch (err) {
|
|
1731
|
+
console.warn(`[bridge] reviewWatcher を起動できません: ${err?.message}`)
|
|
1732
|
+
}
|
|
1733
|
+
// パイプライン完走レポート(D20 / D21)。初回はベースライン確立のみ。
|
|
1734
|
+
try {
|
|
1735
|
+
pipelineWatcher.start()
|
|
1736
|
+
} catch (err) {
|
|
1737
|
+
console.warn(`[bridge] pipelineWatcher を起動できません: ${err?.message}`)
|
|
1738
|
+
}
|
|
1739
|
+
try {
|
|
1740
|
+
await hermes.ensureToken()
|
|
1741
|
+
console.log('[bridge] Hermes セッショントークン: 解決済み')
|
|
1742
|
+
} catch (err) {
|
|
1743
|
+
console.warn(`[bridge] トークン解決に失敗(ダッシュボード停止?): ${err?.message}`)
|
|
1744
|
+
}
|
|
1745
|
+
})
|