hermes-pilot 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.ja.md +390 -0
- package/README.md +398 -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 +358 -0
- package/apps/bridge/src/pipeline-watcher.js +1018 -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 +1738 -0
- package/apps/bridge/src/snippets.js +373 -0
- package/apps/bridge/src/specs.js +734 -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-U500JD2P.js +12 -0
- package/apps/web/dist/assets/index-6iFDsB0G.css +1 -0
- package/apps/web/dist/assets/index-X4Bi2FWB.js +94 -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 +103 -0
- package/skills/quick-review/SKILL.md +170 -0
- package/skills/quick-review/assets/sheet-template.html +175 -0
- package/skills/spec-architect/SKILL.md +175 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import crypto from 'node:crypto'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* アプリの入り口認証。
|
|
7
|
+
*
|
|
8
|
+
* - 端末には**アプリトークンだけ**を渡す(Hermes のセッショントークンは渡さない)
|
|
9
|
+
* - 最初の 1 回だけ `/auth?t=<token>` を踏ませて HttpOnly Cookie にする
|
|
10
|
+
* - **発行済みセッションはディスクに永続化**する(ブリッジ再起動で端末がログアウトしない)
|
|
11
|
+
* - トークンをローテーションすると(ファイルを消して再生成)、過去のセッションは自動で全失効
|
|
12
|
+
* - 書き込み系は `X-Client: mobile` 必須(CSRF の多層防御)
|
|
13
|
+
* - 待受は 127.0.0.1。外部公開は Tailscale serve のみ
|
|
14
|
+
*
|
|
15
|
+
* @param {object} cfg 設定
|
|
16
|
+
* @returns {object} 認証ヘルパ
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* WebSocket アップグレード時の Origin 検証(CSWSH 対策)。
|
|
20
|
+
* ブラウザからの接続(Origin ヘッダあり)は Host と同一オリジンのみ許可する。
|
|
21
|
+
* @param {import('node:http').IncomingMessage} req リクエスト
|
|
22
|
+
* @returns {boolean} 許可してよいか
|
|
23
|
+
*/
|
|
24
|
+
export function isAllowedWsOrigin(req) {
|
|
25
|
+
const origin = req.headers?.origin
|
|
26
|
+
if (!origin) return true
|
|
27
|
+
if (typeof origin !== 'string') return false
|
|
28
|
+
let parsed
|
|
29
|
+
try {
|
|
30
|
+
parsed = new URL(origin)
|
|
31
|
+
} catch {
|
|
32
|
+
return false
|
|
33
|
+
}
|
|
34
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
|
|
35
|
+
const rawHost = req.headers['x-forwarded-host'] ?? req.headers.host
|
|
36
|
+
const expectedHost = (Array.isArray(rawHost) ? rawHost[0] : rawHost ?? '').split(',')[0].trim().toLowerCase()
|
|
37
|
+
if (!expectedHost) return false
|
|
38
|
+
return parsed.host.toLowerCase() === expectedHost
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function createAuth(cfg, { pairCodes = null } = {}) {
|
|
42
|
+
fs.mkdirSync(cfg.dataDir, { recursive: true })
|
|
43
|
+
let token = ''
|
|
44
|
+
try {
|
|
45
|
+
token = fs.readFileSync(cfg.tokenPath, 'utf8').trim()
|
|
46
|
+
} catch {
|
|
47
|
+
/* 初回 */
|
|
48
|
+
}
|
|
49
|
+
if (!token) {
|
|
50
|
+
token = crypto.randomBytes(24).toString('base64url')
|
|
51
|
+
fs.writeFileSync(cfg.tokenPath, token, { mode: 0o600 })
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const hash = (v) => crypto.createHash('sha256').update(v).digest('hex')
|
|
55
|
+
const fingerprint = hash(token).slice(0, 16)
|
|
56
|
+
const sessionsPath = path.join(cfg.dataDir, 'sessions.json')
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 永続セッション。`{version, tokenFingerprint, sessions: {hash: {created, lastSeen}}}`
|
|
60
|
+
* @type {{version: number, tokenFingerprint: string, sessions: Record<string, {created: number, lastSeen: number}>}}
|
|
61
|
+
*/
|
|
62
|
+
let store = { version: 1, tokenFingerprint: fingerprint, sessions: {} }
|
|
63
|
+
try {
|
|
64
|
+
const loaded = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'))
|
|
65
|
+
if (loaded?.sessions && typeof loaded.sessions === 'object' && loaded.tokenFingerprint === fingerprint) {
|
|
66
|
+
store = { version: 1, tokenFingerprint: fingerprint, sessions: loaded.sessions }
|
|
67
|
+
}
|
|
68
|
+
} catch {
|
|
69
|
+
/* 初回・破損時は空から */
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let dirty = false
|
|
73
|
+
let lastFlush = 0
|
|
74
|
+
const flush = (force = false) => {
|
|
75
|
+
if (!dirty && !force) return
|
|
76
|
+
const now = Date.now()
|
|
77
|
+
if (!force && now - lastFlush < 5000) return // ディスク書き込みは 5 秒に 1 回まで
|
|
78
|
+
lastFlush = now
|
|
79
|
+
dirty = false
|
|
80
|
+
try {
|
|
81
|
+
const tmp = `${sessionsPath}.tmp`
|
|
82
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, tokenFingerprint: fingerprint, sessions: store.sessions }, null, 2), {
|
|
83
|
+
mode: 0o600,
|
|
84
|
+
})
|
|
85
|
+
fs.renameSync(tmp, sessionsPath)
|
|
86
|
+
} catch {
|
|
87
|
+
/* 永続化に失敗しても認証は続ける */
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 期限切れを落とす。 */
|
|
92
|
+
const prune = () => {
|
|
93
|
+
const now = Date.now()
|
|
94
|
+
let removed = 0
|
|
95
|
+
for (const [k, rec] of Object.entries(store.sessions)) {
|
|
96
|
+
if (now - (rec.lastSeen ?? rec.created ?? 0) > cfg.sessionTtlMs) {
|
|
97
|
+
delete store.sessions[k]
|
|
98
|
+
removed += 1
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (removed) {
|
|
102
|
+
dirty = true
|
|
103
|
+
flush(true)
|
|
104
|
+
}
|
|
105
|
+
return removed
|
|
106
|
+
}
|
|
107
|
+
prune()
|
|
108
|
+
|
|
109
|
+
const parseCookies = (header) => {
|
|
110
|
+
const out = {}
|
|
111
|
+
for (const part of String(header ?? '').split(';')) {
|
|
112
|
+
const i = part.indexOf('=')
|
|
113
|
+
if (i < 0) continue
|
|
114
|
+
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim())
|
|
115
|
+
}
|
|
116
|
+
return out
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function tokenMatches(given) {
|
|
120
|
+
if (typeof given !== 'string') return false
|
|
121
|
+
const a = Buffer.from(given)
|
|
122
|
+
const b = Buffer.from(token)
|
|
123
|
+
if (a.length !== b.length) return false
|
|
124
|
+
return crypto.timingSafeEqual(a, b)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
token,
|
|
129
|
+
auditPath: cfg.auditPath,
|
|
130
|
+
|
|
131
|
+
/** ワンタイム URL のトークンをセッション Cookie に交換する。 */
|
|
132
|
+
exchange(given) {
|
|
133
|
+
// 本トークン(64 文字)か、ワンタイム・ペアリングコード(短い使い捨て)のどちらでも通す
|
|
134
|
+
const byToken = tokenMatches(given)
|
|
135
|
+
if (!byToken && !pairCodes?.consume?.(given)) return null
|
|
136
|
+
prune()
|
|
137
|
+
const value = crypto.randomBytes(24).toString('base64url')
|
|
138
|
+
const now = Date.now()
|
|
139
|
+
store.sessions[hash(value)] = { created: now, lastSeen: now }
|
|
140
|
+
dirty = true
|
|
141
|
+
flush(true)
|
|
142
|
+
return value
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
/** @param {import('node:http').IncomingMessage} req リクエスト @returns {boolean} */
|
|
146
|
+
authorized(req) {
|
|
147
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
148
|
+
const byToken = tokenMatches(url.searchParams.get('t'))
|
|
149
|
+
if (!byToken) {
|
|
150
|
+
const cookie = parseCookies(req.headers.cookie)[cfg.cookieName]
|
|
151
|
+
if (!cookie) return false
|
|
152
|
+
const key = hash(cookie)
|
|
153
|
+
const rec = store.sessions[key]
|
|
154
|
+
if (!rec) return false
|
|
155
|
+
const now = Date.now()
|
|
156
|
+
if (now - (rec.lastSeen ?? rec.created ?? 0) > cfg.sessionTtlMs) {
|
|
157
|
+
delete store.sessions[key]
|
|
158
|
+
dirty = true
|
|
159
|
+
flush(true)
|
|
160
|
+
return false
|
|
161
|
+
}
|
|
162
|
+
rec.lastSeen = now
|
|
163
|
+
dirty = true
|
|
164
|
+
flush()
|
|
165
|
+
}
|
|
166
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && req.headers['x-client'] !== 'mobile') return false
|
|
167
|
+
return true
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
cookieHeader(value) {
|
|
171
|
+
return `${cfg.cookieName}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${Math.floor(cfg.sessionTtlMs / 1000)}`
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
/** 端末セッション一覧(診断用。Cookie の値は返さない)。 */
|
|
175
|
+
sessions() {
|
|
176
|
+
return Object.entries(store.sessions).map(([k, v]) => ({
|
|
177
|
+
id: k.slice(0, 8),
|
|
178
|
+
created: new Date(v.created).toISOString(),
|
|
179
|
+
lastSeen: new Date(v.lastSeen ?? v.created).toISOString(),
|
|
180
|
+
}))
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
/** 全端末をログアウトさせる(トークンは変えない)。 */
|
|
184
|
+
revokeAll() {
|
|
185
|
+
const n = Object.keys(store.sessions).length
|
|
186
|
+
store.sessions = {}
|
|
187
|
+
dirty = true
|
|
188
|
+
flush(true)
|
|
189
|
+
return n
|
|
190
|
+
},
|
|
191
|
+
|
|
192
|
+
/** 監査ログ(追記のみ)。 */
|
|
193
|
+
audit(entry) {
|
|
194
|
+
try {
|
|
195
|
+
fs.mkdirSync(path.dirname(cfg.auditPath), { recursive: true })
|
|
196
|
+
fs.appendFileSync(cfg.auditPath, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`)
|
|
197
|
+
} catch {
|
|
198
|
+
/* 監査の失敗で本処理は止めない */
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `hermes` CLI が入りやすいディレクトリ(PATH に載っていなくても見る)。
|
|
7
|
+
*
|
|
8
|
+
* 常駐(launchd / systemd)の PATH はログインシェルより狭いため、`hermes` が
|
|
9
|
+
* `~/.hermes/hermes-agent/.hermes/bin` に入っている構成では `which` 相当の
|
|
10
|
+
* 探索が失敗する。個人パスを焼き込まずに、よくある置き場所だけ補う。
|
|
11
|
+
* @param {string} [home] ホーム
|
|
12
|
+
* @returns {string[]} 候補ディレクトリ
|
|
13
|
+
*/
|
|
14
|
+
export function hermesCliDirs(home = os.homedir()) {
|
|
15
|
+
return [
|
|
16
|
+
path.join(home, '.hermes', 'hermes-agent', '.hermes', 'bin'),
|
|
17
|
+
path.join(home, '.local', 'bin'),
|
|
18
|
+
'/opt/homebrew/bin',
|
|
19
|
+
'/usr/local/bin',
|
|
20
|
+
]
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 実行環境の Capability(能力)検出。
|
|
25
|
+
*
|
|
26
|
+
* 公開プラグインとして「どこでも単体で動く」ために、個人環境の前提
|
|
27
|
+
* (macOS の launchd 固定・Tailscale 常備・`hermes` CLI の存在)を
|
|
28
|
+
* **ハードコードせず、起動時に測って分岐する**ための土台。
|
|
29
|
+
*
|
|
30
|
+
* 返す形(`GET /api/capabilities`):
|
|
31
|
+
* ```json
|
|
32
|
+
* { "os": "darwin", "serviceManager": "launchd", "hasTailscale": true,
|
|
33
|
+
* "hasHermesCli": true, "pilotServiceUnit": "ai.hermes.pilot" }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/** OS ごとの常駐ユニット名(D9 のサービス登録名と一致させる)。 */
|
|
38
|
+
export const PILOT_UNITS = {
|
|
39
|
+
darwin: 'ai.hermes.pilot',
|
|
40
|
+
linux: 'hermes-pilot.service',
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** サービス管理系の既定ユニット名。 */
|
|
44
|
+
export const DEFAULT_PILOT_UNIT = 'hermes-pilot.service'
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* OS → サービス管理方式。
|
|
48
|
+
* @param {string} [platform] `process.platform`
|
|
49
|
+
* @returns {'launchd'|'systemd'|'none'} 方式
|
|
50
|
+
*/
|
|
51
|
+
export function serviceManagerFor(platform = process.platform) {
|
|
52
|
+
if (platform === 'darwin') return 'launchd'
|
|
53
|
+
if (platform === 'linux') return 'systemd'
|
|
54
|
+
return 'none'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* PATH 上の実行ファイルの存在確認(`which` を spawn しない)。
|
|
59
|
+
* @param {string} name コマンド名
|
|
60
|
+
* @param {string} [pathEnv] PATH 文字列
|
|
61
|
+
* @returns {boolean} 見つかれば true
|
|
62
|
+
*/
|
|
63
|
+
export function hasBinary(name, pathEnv = process.env.PATH ?? '') {
|
|
64
|
+
const cmd = String(name ?? '').trim()
|
|
65
|
+
if (!cmd || cmd.includes('/')) return false
|
|
66
|
+
for (const dir of String(pathEnv).split(path.delimiter)) {
|
|
67
|
+
if (!dir) continue
|
|
68
|
+
for (const candidate of [cmd, `${cmd}.exe`]) {
|
|
69
|
+
try {
|
|
70
|
+
fs.accessSync(path.join(dir, candidate), fs.constants.X_OK)
|
|
71
|
+
return true
|
|
72
|
+
} catch {
|
|
73
|
+
/* 次のディレクトリへ */
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* PATH 文字列(またはディレクトリ配列)をディレクトリ一覧にする。
|
|
82
|
+
* @param {string|string[]} dirsOrPathEnv PATH 文字列かディレクトリ配列
|
|
83
|
+
* @returns {string[]} ディレクトリ一覧(空要素は落とす)
|
|
84
|
+
*/
|
|
85
|
+
export function toDirList(dirsOrPathEnv) {
|
|
86
|
+
if (Array.isArray(dirsOrPathEnv)) return dirsOrPathEnv.map((d) => String(d ?? '')).filter(Boolean)
|
|
87
|
+
return String(dirsOrPathEnv ?? '')
|
|
88
|
+
.split(path.delimiter)
|
|
89
|
+
.filter(Boolean)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* PATH(またはディレクトリ配列)から実行ファイルの**絶対パス**を返す。
|
|
94
|
+
*
|
|
95
|
+
* `hasBinary` の「あるか」に対して、こちらは「どこにあるか」を返す。
|
|
96
|
+
* `launchd` のように PATH が狭い環境でも、見つけた実パスをそのまま
|
|
97
|
+
* `execFile` に渡せるようにするための土台(シェルは介さない)。
|
|
98
|
+
*
|
|
99
|
+
* @param {string} name コマンド名(パス区切りを含むものは対象外)
|
|
100
|
+
* @param {string|string[]} [dirsOrPathEnv] PATH 文字列かディレクトリ配列
|
|
101
|
+
* @param {Function} [accessSync] 実行ビット確認の差し替え(テスト用)
|
|
102
|
+
* @returns {string|null} 絶対パス(無ければ null)
|
|
103
|
+
*/
|
|
104
|
+
export function findBinaryPath(name, dirsOrPathEnv = process.env.PATH ?? '', accessSync = fs.accessSync) {
|
|
105
|
+
const cmd = String(name ?? '').trim()
|
|
106
|
+
if (!cmd || cmd.includes('/')) return null
|
|
107
|
+
for (const dir of toDirList(dirsOrPathEnv)) {
|
|
108
|
+
for (const candidate of [cmd, `${cmd}.exe`]) {
|
|
109
|
+
const full = path.resolve(dir, candidate)
|
|
110
|
+
try {
|
|
111
|
+
accessSync(full, fs.constants.X_OK)
|
|
112
|
+
return full
|
|
113
|
+
} catch {
|
|
114
|
+
/* 次のディレクトリへ */
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 候補ディレクトリ群から実行ファイルを探す(`findBinaryPath` の薄い包み)。
|
|
123
|
+
* @param {string} name コマンド名
|
|
124
|
+
* @param {string[]} dirs 候補ディレクトリ
|
|
125
|
+
* @param {object} [opts] 差し替え
|
|
126
|
+
* @returns {string|null} 絶対パス(無ければ null)
|
|
127
|
+
*/
|
|
128
|
+
function findInDirs(name, dirs, { accessSync } = {}) {
|
|
129
|
+
const find = accessSync ? (p) => findBinaryPath(name, [p], accessSync) : (p) => findBinaryPath(name, [p])
|
|
130
|
+
for (const dir of dirs) {
|
|
131
|
+
if (!dir) continue
|
|
132
|
+
const hit = find(dir)
|
|
133
|
+
if (hit) return hit
|
|
134
|
+
}
|
|
135
|
+
return null
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* `hermes` CLI の実パスを解決する(PATH → 既知の置き場所 → 裸の名前)。
|
|
140
|
+
*
|
|
141
|
+
* 見つからなくても `'hermes'` を返す(既存の挙動を壊さない)。呼び出し側は
|
|
142
|
+
* そのまま `execFile` に渡せる。
|
|
143
|
+
* @param {object} [opts] 差し替え
|
|
144
|
+
* @param {string} [opts.pathEnv] PATH
|
|
145
|
+
* @param {string} [opts.home] ホーム(既知の置き場所の基準)
|
|
146
|
+
* @param {Function} [opts.accessSync] 実行ビット確認の差し替え(テスト用)
|
|
147
|
+
* @returns {string} 絶対パス、または `'hermes'`
|
|
148
|
+
*/
|
|
149
|
+
export function resolveHermesBin({ pathEnv = process.env.PATH ?? '', home = os.homedir(), accessSync } = {}) {
|
|
150
|
+
const hit = findBinaryPath('hermes', pathEnv, accessSync ?? fs.accessSync) ?? findInDirs('hermes', hermesCliDirs(home), { accessSync })
|
|
151
|
+
return hit ?? 'hermes'
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 子プロセスへ渡す `PATH` を作る(既存 PATH の末尾に既知の置き場所を足す)。
|
|
156
|
+
*
|
|
157
|
+
* 重複は落とし、元の PATH の順序は保つ(先頭の優先度を変えない)。
|
|
158
|
+
* @param {object} [opts] 差し替え
|
|
159
|
+
* @param {string} [opts.pathEnv] 元の PATH
|
|
160
|
+
* @param {string} [opts.home] ホーム
|
|
161
|
+
* @returns {string} 拡張した PATH
|
|
162
|
+
*/
|
|
163
|
+
export function buildAugmentedPath({ pathEnv = process.env.PATH ?? '', home = os.homedir() } = {}) {
|
|
164
|
+
const out = []
|
|
165
|
+
for (const dir of [...toDirList(pathEnv), ...hermesCliDirs(home)]) {
|
|
166
|
+
if (dir && !out.includes(dir)) out.push(dir)
|
|
167
|
+
}
|
|
168
|
+
return out.join(path.delimiter)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Tailscale の有無(CLI か macOS アプリのどちらか)。
|
|
173
|
+
* @param {object} [opts] 差し替え(テスト用)
|
|
174
|
+
* @param {string} [opts.pathEnv] PATH
|
|
175
|
+
* @param {boolean} [opts.appExists] アプリの存在を上書き
|
|
176
|
+
* @returns {boolean} あれば true
|
|
177
|
+
*/
|
|
178
|
+
export function detectTailscale({ pathEnv = process.env.PATH ?? '', appExists } = {}) {
|
|
179
|
+
if (hasBinary('tailscale', pathEnv)) return true
|
|
180
|
+
const appPaths = [
|
|
181
|
+
'/Applications/Tailscale.app',
|
|
182
|
+
path.join(os.homedir(), 'Applications/Tailscale.app'),
|
|
183
|
+
]
|
|
184
|
+
const exists = typeof appExists === 'function' ? appExists : (p) => fs.existsSync(p)
|
|
185
|
+
return appPaths.some((p) => exists(p))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* サービス再起動・状態確認コマンド(`term-snippets.js` が使う)。
|
|
190
|
+
* 個人環境のサービスラベルは使わない。
|
|
191
|
+
* @param {{serviceManager?: string, pilotServiceUnit?: string}} caps Capability
|
|
192
|
+
* @returns {{restart: string, status: string, list: string}} コマンド
|
|
193
|
+
*/
|
|
194
|
+
export function serviceCommands(caps = {}) {
|
|
195
|
+
const unit = String(caps.pilotServiceUnit || DEFAULT_PILOT_UNIT)
|
|
196
|
+
if (caps.serviceManager === 'launchd') {
|
|
197
|
+
return {
|
|
198
|
+
restart: `launchctl kickstart -k gui/$(id -u)/${unit}`,
|
|
199
|
+
status: `launchctl print gui/$(id -u)/${unit} | head -20`,
|
|
200
|
+
list: 'launchctl list | grep -i hermes',
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
restart: `systemctl --user restart ${unit}`,
|
|
205
|
+
status: `systemctl --user status ${unit} --no-pager | head -20`,
|
|
206
|
+
list: "systemctl --user list-units 'hermes*' --no-pager",
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Capability を検出する(純粋に近い。テストでは引数で固定する)。
|
|
212
|
+
* @param {object} [opts] 差し替え
|
|
213
|
+
* @param {string} [opts.platform] `process.platform`
|
|
214
|
+
* @param {string} [opts.pathEnv] PATH
|
|
215
|
+
* @param {Function} [opts.appExists] アプリ存在確認
|
|
216
|
+
* @param {string} [opts.home] ホーム(`hermes` CLI の候補ディレクトリ用)
|
|
217
|
+
* @param {Function} [opts.hasBinaryFn] 実行ファイル存在確認の差し替え(テスト用)
|
|
218
|
+
* @returns {{os: string, serviceManager: string, hasTailscale: boolean, hasHermesCli: boolean, pilotServiceUnit: string}} 検出結果
|
|
219
|
+
*/
|
|
220
|
+
export function detectCapabilities({
|
|
221
|
+
platform = process.platform,
|
|
222
|
+
pathEnv = process.env.PATH ?? '',
|
|
223
|
+
appExists,
|
|
224
|
+
home,
|
|
225
|
+
hasBinaryFn,
|
|
226
|
+
} = {}) {
|
|
227
|
+
const serviceManager = serviceManagerFor(platform)
|
|
228
|
+
const homeDir = home ?? os.homedir()
|
|
229
|
+
const cliDirs = hermesCliDirs(homeDir)
|
|
230
|
+
const find = typeof hasBinaryFn === 'function' ? hasBinaryFn : hasBinary
|
|
231
|
+
return {
|
|
232
|
+
os: platform,
|
|
233
|
+
serviceManager,
|
|
234
|
+
hasTailscale: detectTailscale({ pathEnv, appExists }),
|
|
235
|
+
// PATH に無くても既知の置き場所(~/.hermes/hermes-agent/.hermes/bin 等)を見る
|
|
236
|
+
hasHermesCli: find('hermes', pathEnv) || cliDirs.some((dir) => find('hermes', dir)),
|
|
237
|
+
pilotServiceUnit: PILOT_UNITS[platform] ?? DEFAULT_PILOT_UNIT,
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let cached = null
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 起動時に 1 度だけ検出してキャッシュする(`GET /api/capabilities` 用)。
|
|
245
|
+
* @param {object} [opts] 差し替え(テスト用)
|
|
246
|
+
* @returns {object} Capability
|
|
247
|
+
*/
|
|
248
|
+
export function getCapabilities(opts) {
|
|
249
|
+
if (!cached || opts) cached = detectCapabilities(opts)
|
|
250
|
+
return cached
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** テスト用にキャッシュを捨てる。 */
|
|
254
|
+
export function resetCapabilitiesCache() {
|
|
255
|
+
cached = null
|
|
256
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import crypto from 'node:crypto'
|
|
3
|
+
import { ApiError } from './api-errors.js'
|
|
4
|
+
import { buildAugmentedPath, resolveHermesBin } from './capabilities.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* クイック起票。
|
|
8
|
+
*
|
|
9
|
+
* カンバン DB には直接書かず、**`hermes kanban create` を CLI で実行**する
|
|
10
|
+
* (盤面のロック・イベント・通知の整合性は本体に任せる)。
|
|
11
|
+
* 連打や二重送信は idempotency key で吸収する(既定10分の窓)。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const TITLE_MAX = 200
|
|
15
|
+
const BODY_MAX = 4000
|
|
16
|
+
const DEDUPE_MS = 10 * 60_000
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 入力を検証・正規化する。
|
|
20
|
+
* @param {object} input 入力
|
|
21
|
+
* @returns {{board: string, title: string, body: string, priority: number, assignee: string|null}} 正規化
|
|
22
|
+
*/
|
|
23
|
+
export function normalizeCapture(input = {}) {
|
|
24
|
+
const board = String(input.board ?? '').trim()
|
|
25
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(board)) {
|
|
26
|
+
throw new ApiError('BOARD_NAME_INVALID', {}, 400)
|
|
27
|
+
}
|
|
28
|
+
const title = String(input.title ?? '')
|
|
29
|
+
.replace(/\s+/g, ' ')
|
|
30
|
+
.trim()
|
|
31
|
+
if (!title) throw new ApiError('TASK_TITLE_REQUIRED', {}, 400)
|
|
32
|
+
if (title.length > TITLE_MAX) {
|
|
33
|
+
throw new ApiError('TASK_TITLE_TOO_LONG', { max: TITLE_MAX }, 400)
|
|
34
|
+
}
|
|
35
|
+
const body = String(input.body ?? '').trim().slice(0, BODY_MAX)
|
|
36
|
+
const p = Number(input.priority ?? 0)
|
|
37
|
+
const priority = Number.isFinite(p) ? Math.min(9, Math.max(0, Math.trunc(p))) : 0
|
|
38
|
+
const rawAssignee = String(input.assignee ?? '').trim()
|
|
39
|
+
const assignee = rawAssignee && /^[\w.@-]{1,64}$/.test(rawAssignee) ? rawAssignee : null
|
|
40
|
+
return { board, title, body, priority, assignee }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* CLI に渡す引数を組み立てる。
|
|
45
|
+
* @param {object} c 正規化済み入力
|
|
46
|
+
* @returns {string[]} 引数
|
|
47
|
+
*/
|
|
48
|
+
export function buildCreateArgs(c) {
|
|
49
|
+
const args = ['kanban', '--board', c.board, 'create', c.title, '--json']
|
|
50
|
+
if (c.body) args.push('--body', c.body)
|
|
51
|
+
if (c.priority) args.push('--priority', String(c.priority))
|
|
52
|
+
if (c.assignee) args.push('--assignee', c.assignee)
|
|
53
|
+
return args
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 冪等キー(未指定なら内容と10分窓から導く)。
|
|
58
|
+
* @param {object} c 正規化済み入力
|
|
59
|
+
* @param {string|null} explicit 明示キー
|
|
60
|
+
* @returns {string} キー
|
|
61
|
+
*/
|
|
62
|
+
export function dedupeKey(c, explicit) {
|
|
63
|
+
const given = String(explicit ?? '').trim().slice(0, 128)
|
|
64
|
+
if (given) return `k:${given}`
|
|
65
|
+
const bucket = Math.floor(Date.now() / DEDUPE_MS)
|
|
66
|
+
return crypto
|
|
67
|
+
.createHash('sha1')
|
|
68
|
+
.update(`${c.board}|${c.title}|${c.body}|${c.priority}|${c.assignee ?? ''}|${bucket}`)
|
|
69
|
+
.digest('hex')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createCapture(cfg = {}) {
|
|
73
|
+
/** @type {Map<string, {at: number, task: object}>} */
|
|
74
|
+
const seen = new Map()
|
|
75
|
+
|
|
76
|
+
/** 既定の実行(テストでは差し替え可能)。 */
|
|
77
|
+
const run =
|
|
78
|
+
cfg.runner ??
|
|
79
|
+
((args) =>
|
|
80
|
+
new Promise((resolve) => {
|
|
81
|
+
execFile(
|
|
82
|
+
cfg.hermesBin ?? resolveHermesBin(),
|
|
83
|
+
args,
|
|
84
|
+
{ timeout: 30_000, maxBuffer: 1_000_000, env: { ...process.env, PATH: buildAugmentedPath() } },
|
|
85
|
+
(err, stdout, stderr) => {
|
|
86
|
+
resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
|
|
87
|
+
},
|
|
88
|
+
)
|
|
89
|
+
}))
|
|
90
|
+
|
|
91
|
+
function sweep() {
|
|
92
|
+
const now = Date.now()
|
|
93
|
+
for (const [k, v] of seen) if (now - v.at > DEDUPE_MS) seen.delete(k)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 起票する。
|
|
98
|
+
* @param {object} input 入力(board/title/body/priority/assignee/idempotencyKey)
|
|
99
|
+
* @returns {Promise<{ok: boolean, created: boolean, task?: object, error?: string}>} 結果
|
|
100
|
+
*/
|
|
101
|
+
async function create(input = {}) {
|
|
102
|
+
let c
|
|
103
|
+
try {
|
|
104
|
+
c = normalizeCapture(input)
|
|
105
|
+
} catch (e) {
|
|
106
|
+
return { ok: false, created: false, code: e.code, params: e.params, error: e.message }
|
|
107
|
+
}
|
|
108
|
+
sweep()
|
|
109
|
+
const key = dedupeKey(c, input.idempotencyKey)
|
|
110
|
+
const hit = seen.get(key)
|
|
111
|
+
if (hit) return { ok: true, created: false, task: { ...hit.task, deduped: true } }
|
|
112
|
+
|
|
113
|
+
const res = await run(buildCreateArgs(c))
|
|
114
|
+
|
|
115
|
+
if (res.code !== 0) {
|
|
116
|
+
const msg = (res.stderr || res.stdout || '').trim().slice(0, 400)
|
|
117
|
+
return { ok: false, created: false, code: 'CREATE_FAILED', error: msg }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let task = null
|
|
121
|
+
try {
|
|
122
|
+
const at = res.stdout.indexOf('{')
|
|
123
|
+
task = JSON.parse(at >= 0 ? res.stdout.slice(at) : res.stdout)
|
|
124
|
+
} catch {
|
|
125
|
+
const m = /Created (t_[0-9a-f]+)/.exec(res.stdout)
|
|
126
|
+
task = m ? { id: m[1] } : null
|
|
127
|
+
}
|
|
128
|
+
if (!task?.id) {
|
|
129
|
+
return { ok: false, created: false, code: 'TASK_ID_MISSING' }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const out = {
|
|
133
|
+
id: task.id,
|
|
134
|
+
title: task.title ?? c.title,
|
|
135
|
+
status: task.status ?? 'ready',
|
|
136
|
+
priority: Number(task.priority ?? c.priority),
|
|
137
|
+
assignee: task.assignee ?? c.assignee,
|
|
138
|
+
board: c.board,
|
|
139
|
+
}
|
|
140
|
+
seen.set(key, { at: Date.now(), task: out })
|
|
141
|
+
return { ok: true, created: true, task: out }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return { create }
|
|
145
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* チャット WS 中継で `session.create` / `session.resume` の `profile` を検証する。
|
|
3
|
+
*
|
|
4
|
+
* SPEC: `docs/SPEC-PROFILE-CHAT.md`(決定 D1: 3 プロファイルすべて送信可)。
|
|
5
|
+
* 端末は 1 本の `/ws/chat` しか持たないので、上流(`/api/ws`)へ流す前に
|
|
6
|
+
* **serve 済みプロファイル名だけ**を許す。名前は DB パスに化けるので厳しめに弾く。
|
|
7
|
+
*
|
|
8
|
+
* 設計上の約束:
|
|
9
|
+
* - 検証は純関数(上流も DB も触らない)→ テストは CLI なしで書ける
|
|
10
|
+
* - `profile` 省略は従来どおり(default)= 後方互換
|
|
11
|
+
* - 未知名・注入・型違いは **`-32602` をクライアントに返し、上流には流さない**
|
|
12
|
+
* (流すと `_profile_home()` 側の解決に任せることになり、失敗の見え方が遠くなる)
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { errorBody } from './api-errors.js'
|
|
16
|
+
|
|
17
|
+
/** `profile` を受けてよい RPC。`prompt.submit` はセッションに束縛済みなので対象外。 */
|
|
18
|
+
export const PROFILE_METHODS = new Set(['session.create', 'session.resume'])
|
|
19
|
+
|
|
20
|
+
/** 常に許可する名前(プロファイル一覧が取れないときの退避)。 */
|
|
21
|
+
const ALWAYS = 'default'
|
|
22
|
+
|
|
23
|
+
/** プロファイル名として妥当か(パス区切り・空白・過長を弾く)。 */
|
|
24
|
+
export function isSafeProfileName(name) {
|
|
25
|
+
return typeof name === 'string' && /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(name)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 1 フレームを検証する。
|
|
30
|
+
*
|
|
31
|
+
* @param {string} text 端末から来た生フレーム
|
|
32
|
+
* @param {Iterable<string>} allowed serve 済みプロファイル名
|
|
33
|
+
* @returns {{ok: true, text: string, profile: string|null, method: string|null}
|
|
34
|
+
* | {ok: false, id: number|string|null, message: string, profile: string|null, method: string|null}}
|
|
35
|
+
* `ok:false` のときは応答を返して上流へ流さない
|
|
36
|
+
*/
|
|
37
|
+
export function checkFrame(text, allowed) {
|
|
38
|
+
let msg
|
|
39
|
+
try {
|
|
40
|
+
msg = JSON.parse(text)
|
|
41
|
+
} catch {
|
|
42
|
+
return { ok: true, text, profile: null, method: null } // 壊れたフレームは従来どおり素通し(上流が判断)
|
|
43
|
+
}
|
|
44
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
|
|
45
|
+
return { ok: true, text, profile: null, method: null }
|
|
46
|
+
}
|
|
47
|
+
const method = typeof msg.method === 'string' ? msg.method : null
|
|
48
|
+
if (!method || !PROFILE_METHODS.has(method)) {
|
|
49
|
+
return { ok: true, text, profile: null, method }
|
|
50
|
+
}
|
|
51
|
+
const params = msg.params
|
|
52
|
+
if (!params || typeof params !== 'object') return { ok: true, text, profile: null, method }
|
|
53
|
+
if (!('profile' in params)) return { ok: true, text, profile: null, method }
|
|
54
|
+
|
|
55
|
+
const raw = params.profile
|
|
56
|
+
if (raw === null || raw === undefined || raw === '') {
|
|
57
|
+
// 明示的な「既定」はパラメータごと落として上流に既定を選ばせる
|
|
58
|
+
const next = { ...msg, params: { ...params } }
|
|
59
|
+
delete next.params.profile
|
|
60
|
+
return { ok: true, text: JSON.stringify(next), profile: null, method }
|
|
61
|
+
}
|
|
62
|
+
const name = String(raw).trim()
|
|
63
|
+
const allow = new Set([ALWAYS, ...(allowed ?? [])])
|
|
64
|
+
if (!isSafeProfileName(name) || !allow.has(name)) {
|
|
65
|
+
// 日本語を返さない: 文言は英語既定(`err.PROFILE_UNKNOWN`)で組み、コードで自言語化させる。
|
|
66
|
+
// `message` は WS の JSON-RPC 拒否フレーム(`rejectionFrame`)が読む。
|
|
67
|
+
const failure = errorBody('PROFILE_UNKNOWN', { profile: String(raw).slice(0, 60) })
|
|
68
|
+
return {
|
|
69
|
+
ok: false,
|
|
70
|
+
id: msg.id ?? null,
|
|
71
|
+
message: failure.error,
|
|
72
|
+
code: failure.code,
|
|
73
|
+
params: failure.params,
|
|
74
|
+
profile: name,
|
|
75
|
+
method,
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const next = { ...msg, params: { ...params, profile: name } }
|
|
79
|
+
return { ok: true, text: JSON.stringify(next), profile: name, method }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `checkFrame` が拒否したときの JSON-RPC エラーフレーム。
|
|
84
|
+
*
|
|
85
|
+
* @param {number|string|null} id リクエスト ID
|
|
86
|
+
* @param {string} message 文言
|
|
87
|
+
* @returns {string} JSON
|
|
88
|
+
*/
|
|
89
|
+
export function rejectionFrame(id, message) {
|
|
90
|
+
return JSON.stringify({
|
|
91
|
+
jsonrpc: '2.0',
|
|
92
|
+
id: id ?? null,
|
|
93
|
+
error: { code: -32602, message: `profile: ${message}` },
|
|
94
|
+
})
|
|
95
|
+
}
|