hermes-pilot 0.2.0 → 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/README.ja.md CHANGED
@@ -97,6 +97,33 @@ curl -s -H "x-client: mobile" \
97
97
  "http://127.0.0.1:4097/api/telemetry/receipt?board=<board>&hours=24&t=$(cat ~/.hermes/plugin-data/hermes-pilot/token)"
98
98
  ```
99
99
 
100
+ ## 抽象ロールとネイティブ委譲
101
+
102
+ バッチを振り分けるのは**モデル名ではなくロール**です。パイプライン全体を 4 つの抽象ロールで覆い、
103
+ リポジトリと同梱 3 スキルが使う語彙はこの 4 つだけです。
104
+
105
+ - `role:planner` — 設計・仕様策定・影響分析・難所の原因究明。
106
+ - `role:builder` — 実装・テスト修復・ビルド・定型のカンバン作業(既定)。
107
+ - `role:visual-reviewer` — スクショ/赤入れ画像の読解と `390×844` / `820×1180` の視覚検収。
108
+ - `role:decision-framer` — クイックレビューの設問設計とトレードオフ整理。
109
+
110
+ バッチに `- **Recommended Role**: \`role:planner\`` と書けば、ブリッジがそれを抽出して起票タスク本文の
111
+ `[Hermes Pilot Execution Contract]` にロール指針を注入します。書かない SPEC は従来どおりに動きます。
112
+
113
+ 委譲は**ネイティブ**(Hermes 自身の `delegate_task`)だけで、外部 AI CLI の子プロセス(`gemini -p` /
114
+ `agy -p` など)は起動しません(`npm run check:oauth` がランタイム側の起動を検出すると失敗します)。
115
+ しかも**止まりません**: 委譲先がエラー・レート制限・タイムアウト・未設定のいずれでも、親はプロファイルが
116
+ 宣言したフォールバック順で自分のモデルのまま続行し、バッチは最後まで完走します。委譲の失敗でタスクが
117
+ 止まったままになることはありません。
118
+
119
+ **モデル名を書かない場所。** リポジトリと同梱 3 スキルは抽象ロールしか語りません。「どのロールをどの
120
+ モデルに割り当て、失敗時にどこへ落とすか」の対応表は運用者のもので、Hermes プロファイル側(毎ターン読む
121
+ 短い契約は `~/.hermes/SOUL.md`、具体的な割当表はプロファイル自身の `SOUL.md` とメモリ)に置きます。この
122
+ 分離が、誰の環境にも入るプラグインでいるための条件です。`POST /api/pipeline/optimize` はマーカーブロックを
123
+ `~/.hermes/SOUL.md` と、見つかった各 `~/.hermes/profiles/<name>/SOUL.md` へ冪等に書き込み(実行前に
124
+ `.bak-<stamp>` を退避)、`GET /api/pipeline/status` はファイルの中身を返さずにプロファイルごとの適用状況
125
+ だけを返します。
126
+
100
127
  ## 意思決定コックピット(v2)
101
128
 
102
129
  「エージェントが判断を待っている」から「また走り出した」までを最短にする 5 つ。スマホからも標準
@@ -145,8 +172,10 @@ curl -s -H "x-client: mobile" \
145
172
  - **スニペット帯トグル** — チャット入力欄の上、注釈ツールバー、端末キーのチップ帯はそれぞれ折りたためます。
146
173
  選択は帯ごとに記憶され、390px の画面で入力欄とキーボードが場所を取り合いません。
147
174
  - **1 タップ環境最適化** — *設定 → この Hermes を最適化*(`POST /api/pipeline/optimize`)が
148
- `~/.hermes/SOUL.md` へ A2B の規律節を**冪等に**追記し、同梱 3 スキルを `~/.hermes/skills/` へ配置します。
149
- `GET /api/pipeline/status` は適用済みかだけを返し、`SOUL.md` の中身は返しません。
175
+ `~/.hermes/SOUL.md` と各プロファイルの `~/.hermes/profiles/<name>/SOUL.md` へ A2B の規律節を**冪等に**
176
+ 追記し(既存節は重複させず、実行前に `.bak-<stamp>` を退避)、同梱 3 スキルを `~/.hermes/skills/` へ
177
+ 配置します。`GET /api/pipeline/status` はプロファイルごとの適用済み状況だけを返し、`SOUL.md` の中身は
178
+ 返しません。
150
179
  - **旧 cron の自動片付け** — `migrate`(と `init`)は旧 `mobile-akapen-watch` / `mobile-review-watch` の
151
180
  cron を削除します。完了フィードはブリッジ内蔵の監視が書くようになり、2 者が書くと報告が二重になるためです。
152
181
  他の cron とストアのトップレベル構造は変更しません。
package/README.md CHANGED
@@ -98,6 +98,34 @@ curl -s -H "x-client: mobile" \
98
98
  "http://127.0.0.1:4097/api/telemetry/receipt?board=<board>&hours=24&t=$(cat ~/.hermes/plugin-data/hermes-pilot/token)"
99
99
  ```
100
100
 
101
+ ## Abstract roles and native delegation
102
+
103
+ A batch is routed by **role**, not by model name. Four abstract roles cover the whole pipeline, and they are
104
+ the only vocabulary the repo and the bundled skills use:
105
+
106
+ - `role:planner` — design, spec authoring, impact analysis, hard root-cause work.
107
+ - `role:builder` — implementation, test repair, builds, routine kanban work (the default).
108
+ - `role:visual-reviewer` — screenshot / annotation reading and `390×844` / `820×1180` visual acceptance.
109
+ - `role:decision-framer` — quick-review question design and trade-off framing.
110
+
111
+ A batch may declare `- **Recommended Role**: \`role:planner\``; the bridge extracts it and adds the role
112
+ guidance to the `[Hermes Pilot Execution Contract]` appended to the filed task. Specs without the line behave
113
+ exactly as before.
114
+
115
+ Delegation is **native** — Hermes's own `delegate_task` — and never an external AI CLI subprocess
116
+ (`gemini -p`, `agy -p`, …); `npm run check:oauth` fails if a runtime file tries to spawn one. It is also
117
+ **non-blocking**: if the delegated model errors, is rate-limited, times out or is not configured, the parent
118
+ continues on its own model in the fallback order its profile declares, and the batch still finishes. A failed
119
+ delegation never leaves a task stopped.
120
+
121
+ **Where the models are named: not here.** The repository and the three bundled skills speak only abstract
122
+ roles. The mapping (which role uses which model, in what fallback order) belongs to the operator and lives in
123
+ the Hermes profile — `~/.hermes/SOUL.md` for the short always-read contract, the profile's own `SOUL.md` and
124
+ memory for the concrete assignment table. That split is what keeps the plugin installable for anyone.
125
+ `POST /api/pipeline/optimize` writes the marker block into `~/.hermes/SOUL.md` **and** every
126
+ `~/.hermes/profiles/<name>/SOUL.md` it finds, idempotently and after a `.bak-<stamp>` backup;
127
+ `GET /api/pipeline/status` reports which profiles are applied without returning any file content.
128
+
101
129
  ## Decision cockpit (v2)
102
130
 
103
131
  Five additions that shorten the loop from "the agent needs a decision" to "it is running again".
@@ -150,9 +178,11 @@ Every one of them is reachable from the phone and from the standard dashboard.
150
178
  keys can each be collapsed. The choice is per band and remembered, so a small phone keeps the composer and
151
179
  the keyboard from fighting for the same 390 px.
152
180
  - **1-tap environment optimisation** — *Settings → Optimise this Hermes* (`POST /api/pipeline/optimize`)
153
- appends the A2B discipline section to `~/.hermes/SOUL.md` (idempotent — an existing section is never
154
- duplicated) and places the three bundled skills into `~/.hermes/skills/`. `GET /api/pipeline/status` reports
155
- what is already applied without returning any `SOUL.md` content.
181
+ appends the A2B discipline section to `~/.hermes/SOUL.md` and to each profile's
182
+ `~/.hermes/profiles/<name>/SOUL.md` (idempotent — an existing section is never duplicated, and a
183
+ `.bak-<stamp>` backup is taken first), then places the three bundled skills into `~/.hermes/skills/`.
184
+ `GET /api/pipeline/status` reports what is already applied, per profile, without returning any `SOUL.md`
185
+ content.
156
186
  - **Legacy cron cleanup** — `migrate` (and `init`) removes the old `mobile-akapen-watch` /
157
187
  `mobile-review-watch` cron entries, because the bridge's own watcher writes the completion feed now and two
158
188
  writers produced duplicate reports. Other cron entries and the store's top-level shape are untouched.
@@ -40,6 +40,10 @@ export const A2B_RULES = [
40
40
  '- 判断が必要になったら**長文の質問をチャットへ並べない**。`quick-review` シートを作り、',
41
41
  ' `[review] label=... round=...` 行付きのタスクを起票して `needs_input` で止める。',
42
42
  '- 見た目の検収は `annotation`(スクリーンショット+赤)で受ける。文章で聞き返さない。',
43
+ // D60 / D61 / D63: 抽象ロール・ネイティブ委譲・外部 CLI 禁止(SOUL を太らせないため 3 行に抑える)
44
+ '- 抽象ロール(`role:planner` / `role:builder` / `role:visual-reviewer` / `role:decision-framer`)で捉え、',
45
+ ' ロールごとの実モデル割当とフォールバック順はプロファイルメモリの表に従い `delegate_task` で委譲する。',
46
+ ' 委譲の失敗・レート制限・タイムアウト・未対応では止めずフォールバックへ回し、外部 AI CLI のサブプロセス起動はしない。',
43
47
  '- タスク本文に `Mode: zero-stop` / `fast-track-review` / `visual-gate` があればその契約に従う。',
44
48
  ' `zero-stop` は `npm run verify` が通るまで自律修復し、通過後に `done` にする。',
45
49
  '- 完了報告は「何をしたか / 検証コマンドと exit code / 未検証 / 次の一手」の 4 点に絞る。',
@@ -115,29 +119,42 @@ export function nextBackupPath(soulPath, stamp, exists = (p) => fs.existsSync(p)
115
119
  }
116
120
 
117
121
  /**
118
- * `<hermesHome>/SOUL.md` へ A2B 行動規範を冪等に適用する。
122
+ * `SOUL.md` 1 枚へ A2B 行動規範を冪等に適用する(本体。`optimizeHermesSoul` とプロファイル同期の共通処理)。
119
123
  *
120
124
  * 2 回目以降はブロックが同一なので**書き込みもバックアップもしない**(1 タップボタンの連打で
121
125
  * `SOUL.md.bak-*` が増えない)。内容が変わるときだけバックアップを 1 枚作ってから書く。
122
126
  *
123
- * @param {{hermesHome?: string, now?: number, block?: string}} [opts] 入力
124
- * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, error?: string}} 結果
127
+ * @param {string} soulPath 対象ファイルの絶対パス
128
+ * @param {{now?: number, block?: string, create?: boolean}} [opts] 入力(`create:false` はファイルが無ければ作らない)
129
+ * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, exists: boolean, applied: boolean, error?: string}} 結果
125
130
  */
126
- export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK } = {}) {
127
- const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
128
- const soulPath = path.join(home, 'SOUL.md')
131
+ function applySoulFile(soulPath, { now = Date.now(), block = A2B_RULE_BLOCK, create = true } = {}) {
129
132
  let current = ''
133
+ let exists = false
130
134
  try {
131
135
  current = fs.readFileSync(soulPath, 'utf8')
136
+ exists = true
132
137
  } catch (err) {
133
138
  if (err?.code !== 'ENOENT') {
134
- return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath: null, error: String(err?.message ?? err) }
139
+ return {
140
+ ok: false,
141
+ path: soulPath,
142
+ mode: 'error',
143
+ changed: false,
144
+ backupPath: null,
145
+ exists: false,
146
+ applied: false,
147
+ error: String(err?.message ?? err),
148
+ }
135
149
  }
150
+ // `create:false` は既存 SOUL.md だけを対象にする(人の環境に勝手に作らない)。
151
+ if (!create) return { ok: true, path: soulPath, mode: 'skipped', changed: false, backupPath: null, exists: false, applied: false }
136
152
  }
137
153
 
138
154
  const merged = mergeSoul(current, block)
155
+ const applied = merged.text.includes(A2B_START) && merged.text.includes(A2B_END)
139
156
  if (!merged.changed) {
140
- return { ok: true, path: soulPath, mode: 'unchanged', changed: false, backupPath: null }
157
+ return { ok: true, path: soulPath, mode: 'unchanged', changed: false, backupPath: null, exists, applied }
141
158
  }
142
159
 
143
160
  let backupPath = null
@@ -152,9 +169,145 @@ export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_R
152
169
  fs.writeFileSync(tmp, merged.text, { encoding: 'utf8', mode: 0o600 })
153
170
  fs.renameSync(tmp, soulPath)
154
171
  } catch (err) {
155
- return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath, error: String(err?.message ?? err) }
172
+ return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath, exists, applied, error: String(err?.message ?? err) }
173
+ }
174
+ return { ok: true, path: soulPath, mode: merged.mode, changed: true, backupPath, exists: true, applied: true }
175
+ }
176
+
177
+ /**
178
+ * `<hermesHome>/SOUL.md` へ A2B 行動規範を冪等に適用する。
179
+ *
180
+ * 引数・戻り値は従来どおり(`{ ok, path, mode, changed, backupPath }`)。プロファイル配下の同期は
181
+ * `optimizeProfileSouls` が担う(D64)。
182
+ *
183
+ * @param {{hermesHome?: string, now?: number, block?: string}} [opts] 入力
184
+ * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, error?: string}} 結果
185
+ */
186
+ export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK } = {}) {
187
+ const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
188
+ const soulPath = path.join(home, 'SOUL.md')
189
+ const applied = applySoulFile(soulPath, { now, block, create: true })
190
+ // `exists` / `applied` は内部用の追加情報。従来の戻り値の形は変えない。
191
+ const { exists: _exists, applied: _applied, ...result } = applied
192
+ return result
193
+ }
194
+
195
+ /**
196
+ * プロファイル配下で `SOUL.md` を**新規作成してよい**名前(D64)。
197
+ *
198
+ * ディレクトリが既にある場合だけ、そして `mobile` だけ(実運用で毎ターン読ませたいプロファイル)。
199
+ * それ以外のプロファイルは既存 `SOUL.md` があるときだけ更新する=人の環境を勝手に増やさない。
200
+ */
201
+ export const PROFILE_SOUL_CREATE_IF_MISSING = ['mobile']
202
+
203
+ /**
204
+ * `<hermesHome>/profiles` 配下のプロファイル名(ディレクトリのみ・隠しディレクトリ除外)。
205
+ *
206
+ * @param {string} hermesHome Hermes のホーム
207
+ * @returns {string[]} 昇順のプロファイル名
208
+ */
209
+ export function listProfileNames(hermesHome) {
210
+ let entries = []
211
+ try {
212
+ entries = fs.readdirSync(path.join(String(hermesHome), 'profiles'), { withFileTypes: true })
213
+ } catch {
214
+ return []
215
+ }
216
+ return entries
217
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
218
+ .map((e) => e.name)
219
+ .sort()
220
+ }
221
+
222
+ /**
223
+ * プロファイル 1 つ分の `SOUL.md` 適用状況(**中身は返さない**)。
224
+ *
225
+ * @param {string} hermesHome Hermes のホーム
226
+ * @param {string} name プロファイル名
227
+ * @returns {{name: string, path: string, exists: boolean, applied: boolean, backups: number}} 状態
228
+ */
229
+ function profileSoulState(hermesHome, name) {
230
+ const soulPath = path.join(String(hermesHome), 'profiles', name, 'SOUL.md')
231
+ let exists = false
232
+ let applied = false
233
+ try {
234
+ const text = fs.readFileSync(soulPath, 'utf8')
235
+ exists = true
236
+ applied = text.includes(A2B_START) && text.includes(A2B_END)
237
+ } catch {
238
+ exists = false
239
+ }
240
+ let backups = 0
241
+ try {
242
+ backups = fs.readdirSync(path.dirname(soulPath)).filter((n) => n.startsWith('SOUL.md.bak-')).length
243
+ } catch {
244
+ backups = 0
245
+ }
246
+ return { name, path: soulPath, exists, applied, backups }
247
+ }
248
+
249
+ /**
250
+ * `~/.hermes/profiles/<name>/SOUL.md` へ A2B 行動規範を**非破壊・冪等**に同期する(D64)。
251
+ *
252
+ * - 対象は `profiles` を渡せばその名前だけ、省略時は `<hermesHome>/profiles/*` を自動検出。
253
+ * - `SOUL.md` が既にある → マーカー間だけ置換し、内容が変わるときだけ `.bak-<stamp>` を 1 枚作る。
254
+ * - `SOUL.md` が無い → `PROFILE_SOUL_CREATE_IF_MISSING`(`mobile`)だけ最小構成で新規作成、
255
+ * それ以外は `mode: 'skipped'`(ディレクトリを勝手に作らない)。
256
+ * - 内容(テキスト)は戻り値に載せない。`changed` / `mode` / `backupPath` / 件数だけ。
257
+ *
258
+ * @param {{hermesHome?: string, now?: number, block?: string, profiles?: string[]}} [opts] 入力
259
+ * @returns {{ok: boolean, profiles: Array<{name: string, path: string, exists: boolean, applied: boolean, changed: boolean, mode: string, backupPath: string|null, backups: number, error?: string}>}} 結果
260
+ */
261
+ export function optimizeProfileSouls({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK, profiles } = {}) {
262
+ const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
263
+ const names = Array.isArray(profiles) && profiles.length
264
+ ? profiles.map((n) => String(n ?? '').trim()).filter(Boolean)
265
+ : listProfileNames(home)
266
+
267
+ const out = []
268
+ for (const name of names) {
269
+ // パス連結に使う名前だけを受け付ける(`../` 等の脱出を許さない)。
270
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || name === '.' || name === '..') continue
271
+ const dir = path.join(home, 'profiles', name)
272
+ let dirExists = false
273
+ try {
274
+ dirExists = fs.statSync(dir).isDirectory()
275
+ } catch {
276
+ dirExists = false
277
+ }
278
+ if (!dirExists) {
279
+ out.push({
280
+ name,
281
+ path: path.join(dir, 'SOUL.md'),
282
+ exists: false,
283
+ applied: false,
284
+ changed: false,
285
+ mode: 'skipped',
286
+ backupPath: null,
287
+ backups: 0,
288
+ })
289
+ continue
290
+ }
291
+
292
+ const r = applySoulFile(path.join(dir, 'SOUL.md'), {
293
+ now,
294
+ block,
295
+ create: PROFILE_SOUL_CREATE_IF_MISSING.includes(name),
296
+ })
297
+ const state = profileSoulState(home, name)
298
+ out.push({
299
+ name,
300
+ path: r.path,
301
+ exists: r.exists,
302
+ applied: Boolean(r.applied),
303
+ changed: Boolean(r.changed),
304
+ mode: r.mode,
305
+ backupPath: r.backupPath ?? null,
306
+ backups: state.backups,
307
+ ...(r.error ? { error: r.error } : {}),
308
+ })
156
309
  }
157
- return { ok: true, path: soulPath, mode: merged.mode, changed: true, backupPath }
310
+ return { ok: out.every((p) => p.mode !== 'error'), profiles: out }
158
311
  }
159
312
 
160
313
  /**
@@ -351,6 +504,8 @@ export function getOptimizeStatus({
351
504
  backups: backups.length,
352
505
  latestBackup: backups.length ? backups[backups.length - 1] : null,
353
506
  },
507
+ // プロファイル配下(`profiles/<name>/SOUL.md`)も「適用済みか」だけを返す(中身は返さない)。
508
+ profiles: listProfileNames(hh).map((name) => profileSoulState(hh, name)),
354
509
  hermes: skillState(path.join(hh, 'skills')),
355
510
  bundled: { source: skillsSrcDir, names: BUNDLED_SKILLS },
356
511
  antigravity,
@@ -638,7 +638,7 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
638
638
  return out
639
639
  }
640
640
 
641
- /** `state.db` から cwd 一致の最新通常セッションを 1 件返す。 */
641
+ /** `state.db` から cwd 一致の最新通常セッション `{ id, at }` を 1 件返す。 */
642
642
  function latestSessionForCwd(dbPath, workdir) {
643
643
  let db
644
644
  try {
@@ -649,7 +649,7 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
649
649
  const want = normalizePath(workdir)
650
650
  try {
651
651
  const sql = (order) =>
652
- `SELECT id, cwd FROM sessions
652
+ `SELECT id, cwd, ${order} AS ts FROM sessions
653
653
  WHERE cwd IS NOT NULL AND id NOT LIKE 'local-%'
654
654
  ORDER BY ${order} DESC LIMIT 300`
655
655
  let rows = []
@@ -659,7 +659,9 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
659
659
  rows = db.prepare(sql('started_at')).all()
660
660
  }
661
661
  for (const r of rows) {
662
- if (normalizePath(r.cwd) === want) return String(r.id)
662
+ if (normalizePath(r.cwd) === want) {
663
+ return { id: String(r.id), at: Number(r.ts) || 0 }
664
+ }
663
665
  }
664
666
  return null
665
667
  } catch {
@@ -734,10 +736,12 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
734
736
  if (CHAT_ID_RE.test(origin)) return origin
735
737
  const workdir = boardWorkdir(group.board)
736
738
  if (workdir) {
739
+ let best = null
737
740
  for (const dbPath of stateDbs()) {
738
- const id = latestSessionForCwd(dbPath, workdir)
739
- if (id) return id
741
+ const hit = latestSessionForCwd(dbPath, workdir)
742
+ if (hit && (!best || hit.at > best.at)) best = hit
740
743
  }
744
+ if (best) return best.id
741
745
  }
742
746
  return '__latest__'
743
747
  }
@@ -38,6 +38,7 @@ import {
38
38
  getOptimizeStatus,
39
39
  optimizeAgentSkills,
40
40
  optimizeHermesSoul,
41
+ optimizeProfileSouls,
41
42
  } from './pipeline-optimizer.js'
42
43
  import { createPairCodes } from './pair-codes.js'
43
44
  import { createMemosStore } from './memos.js'
@@ -695,19 +696,25 @@ async function handleApi(req, res, url) {
695
696
  // 既定は SOUL とスキル配置の両方。片方だけ試したいときは明示的に false を渡す。
696
697
  const doSoul = body?.soul !== false
697
698
  const doSkills = body?.skills !== false
699
+ // プロファイル別 `SOUL.md`(`profiles/<name>/SOUL.md`)も同じ 1 タップで冪等同期する(D64)。
700
+ const doProfiles = doSoul && body?.profiles !== false
698
701
  const soul = doSoul ? optimizeHermesSoul({ hermesHome: cfg.hermesHome }) : null
702
+ const profiles = doProfiles ? optimizeProfileSouls({ hermesHome: cfg.hermesHome }) : null
699
703
  const skills = doSkills ? optimizeAgentSkills({ home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }) : null
700
- const ok = (soul?.ok ?? true) && (skills?.ok ?? true)
704
+ const ok = (soul?.ok ?? true) && (profiles?.ok ?? true) && (skills?.ok ?? true)
701
705
  auth.audit({
702
706
  kind: 'pipeline.optimize',
703
707
  soul: soul?.mode ?? null,
704
708
  soulChanged: Boolean(soul?.changed),
709
+ profileTargets: profiles?.profiles?.length ?? 0,
710
+ profileChanged: profiles?.profiles?.filter((p) => p.changed).length ?? 0,
705
711
  skillTargets: skills?.targets?.length ?? 0,
706
712
  ok,
707
713
  })
708
714
  return sendJson(res, ok ? 200 : 500, {
709
715
  ok,
710
716
  soul,
717
+ profiles,
711
718
  skills,
712
719
  status: getOptimizeStatus({ hermesHome: cfg.hermesHome, home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }),
713
720
  })
@@ -94,6 +94,51 @@ export function extractExecutionMode(section) {
94
94
  /** 行動契約ブロックの見出し(本文中で一意)。 */
95
95
  export const CONTRACT_HEADER = '[Hermes Pilot Execution Contract]'
96
96
 
97
+ /**
98
+ * 抽象ロールの語彙(D60)。公開コードは**この 4 つだけ**を知り、実モデル名は知らない
99
+ * (プロファイルメモリの割当表が実モデルを決める)。
100
+ */
101
+ export const ABSTRACT_ROLES = ['role:planner', 'role:builder', 'role:visual-reviewer', 'role:decision-framer']
102
+
103
+ /**
104
+ * バッチ本文の推奨ロール宣言行(`- **Recommended Role**: \`role:builder\`` / `- **推奨ロール**: role:planner`)。
105
+ * バックティック・大小文字・全角コロンを許容する。
106
+ */
107
+ export const RECOMMENDED_ROLE_RE = /^[-*]?\s*\*\*\s*(?:Recommended Role|推奨ロール)\s*\*\*\s*[::]\s*(.+)$/im
108
+
109
+ /**
110
+ * 推奨ロール表記を正規化する(未知・未宣言は `null`)。
111
+ *
112
+ * `role:` 接頭辞の有無、バックティック、前後の空白・句読点を吸収する。
113
+ * 抽象ロール 4 つ以外は**推測せず** `null`(後方互換)。
114
+ *
115
+ * @param {unknown} raw `role:builder` / `builder` / `` `role:planner` `` など
116
+ * @returns {'role:planner'|'role:builder'|'role:visual-reviewer'|'role:decision-framer'|null} 正規化したロール
117
+ */
118
+ export function normalizeRecommendedRole(raw) {
119
+ const text = String(raw ?? '')
120
+ .replace(/[`'"「」]/g, '')
121
+ .trim()
122
+ .toLowerCase()
123
+ if (!text) return null
124
+ // 行末に説明が続く場合(`role:builder — 通常実装`)は最初の語だけを見る。
125
+ const token = text.split(/[\s,;/|、。]+/)[0].replace(/^role\s*[::]\s*/, '')
126
+ const role = `role:${token}`
127
+ return ABSTRACT_ROLES.includes(role) ? role : null
128
+ }
129
+
130
+ /**
131
+ * バッチ本文から推奨ロールを読む(未宣言は `null`=後方互換)。
132
+ *
133
+ * @param {string[]|string} section バッチ本文の行(または本文)
134
+ * @returns {'role:planner'|'role:builder'|'role:visual-reviewer'|'role:decision-framer'|null} ロール
135
+ */
136
+ export function extractRecommendedRole(section) {
137
+ const text = Array.isArray(section) ? section.join('\n') : String(section ?? '')
138
+ const m = RECOMMENDED_ROLE_RE.exec(text)
139
+ return m ? normalizeRecommendedRole(m[1]) : null
140
+ }
141
+
97
142
  /** モード別の行動契約(`buildTaskBody` が本文末尾へ注入する)。 */
98
143
  export const MODE_CONTRACTS = {
99
144
  'zero-stop': [
@@ -115,21 +160,46 @@ export const MODE_CONTRACTS = {
115
160
  /**
116
161
  * モード別の行動契約ブロック(`[Hermes Pilot Execution Contract]`)を組み立てる。
117
162
  *
163
+ * モード未宣言でも `recommendedRole` があれば契約を出す(ロール指針だけは届ける)。
164
+ * `recommendedRole` 指定時・`visual-gate` のときは、ネイティブ `delegate_task` +
165
+ * フォールバックと外部 AI CLI 禁止を 2 行だけ添える(D61 / D63)。
166
+ *
118
167
  * @param {string} mode 正規化済みモード
119
- * @returns {string} 本文末尾に足すブロック(未知モードは空文字)
168
+ * @param {{recommendedRole?: string|null}} [opts] 推奨ロール(未宣言は `null`)
169
+ * @returns {string} 本文末尾に足すブロック(モードもロールも無ければ空文字=後方互換)
120
170
  */
121
- export function buildExecutionContract(mode) {
171
+ export function buildExecutionContract(mode, { recommendedRole = null } = {}) {
122
172
  const key = normalizeExecutionMode(mode)
123
- if (!key) return ''
124
- const rules = MODE_CONTRACTS[key] ?? []
173
+ const role = normalizeRecommendedRole(recommendedRole)
174
+ const gate = key === 'visual-gate'
175
+ if (!key && !role) return ''
176
+ const rules = key ? (MODE_CONTRACTS[key] ?? []) : []
177
+
178
+ const delegation = []
179
+ if (role) {
180
+ delegation.push(
181
+ `- Recommended role: \`${role}\` — resolve it against the profile's abstract-role table before starting.`,
182
+ )
183
+ } else if (gate) {
184
+ delegation.push(
185
+ '- Recommended role: `role:visual-reviewer` — delegate screenshot / annotated-image review through native delegation.',
186
+ )
187
+ }
188
+ if (role || gate) {
189
+ delegation.push(
190
+ '- Delegate only through Hermes native delegation; on error, rate limit, timeout or an unsupported model, continue down the fallback chain instead of blocking.',
191
+ '- Never launch an external AI CLI as a subprocess (no wrapped CLI runs); native providers only.',
192
+ )
193
+ }
194
+
125
195
  return [
126
196
  '',
127
197
  CONTRACT_HEADER,
128
198
  '',
129
- `Mode: ${key}`,
130
- '',
199
+ ...(key ? [`Mode: ${key}`, ''] : []),
131
200
  'This task was filed by the Hermes Pilot Spec Launchpad. The contract below overrides any habit of asking first.',
132
201
  ...rules,
202
+ ...delegation,
133
203
  '- Finish with a short report: what changed, the verification command and its exit code, and what is still unverified.',
134
204
  ].join('\n')
135
205
  }
@@ -175,6 +245,8 @@ export function parseSpec(text) {
175
245
  objective: extractObjective(body),
176
246
  // 実行モード(未宣言の過去 SPEC は null=後方互換)
177
247
  mode: extractExecutionMode(body),
248
+ // 推奨ロール(未宣言は null。抽象ロール 4 つ以外も null に正規化する)
249
+ recommendedRole: extractRecommendedRole(body),
178
250
  // 末尾の区切り線(`---`)は本文に含めない
179
251
  section: trimTrailingRule(body.join('\n')),
180
252
  })
@@ -307,7 +379,7 @@ export function buildTaskBody({ specRelPath, repoPath, board, batch, chat }) {
307
379
  ].join('\n')
308
380
  // 契約ブロックは**末尾に必ず残す**(抜粋だけを切り詰める)。6000 字上限で契約が消えると
309
381
  // 自走の保証が壊れるため、順序は「見出し → 抜粋 → 契約」で固定する。
310
- const contract = buildExecutionContract(mode)
382
+ const contract = buildExecutionContract(mode, { recommendedRole: batch?.recommendedRole })
311
383
  const room = Math.max(0, BODY_MAX - head.length - contract.length)
312
384
  const section = String(batch?.section ?? '').slice(0, room)
313
385
  return `${head}${section}${contract}`.slice(0, BODY_MAX)
@@ -3,7 +3,7 @@
3
3
  "label": "Hermes Pilot",
4
4
  "description": "Pair a phone with the Hermes Pilot PWA and drive the A2B pipeline from it — Spec Seed to filed batches, live architect progress, one-tap review sheets and visual annotation — plus the one-time pairing QR, bridge status, scan directories and the keep-alive service, all from the standard dashboard.",
5
5
  "icon": "QrCode",
6
- "version": "0.2.0",
6
+ "version": "0.2.2",
7
7
  "tab": {
8
8
  "path": "/hermes-pilot",
9
9
  "position": "after:git-ops"
@@ -1,4 +1,4 @@
1
- import{u as be,r as Y,a as we,s as ye,o as Ee,h as ke,j as J,S as Le,I as De,b as Re}from"./index-X4Bi2FWB.js";var ge={exports:{}};(function(se,le){(function(Q,K){se.exports=K()})(globalThis,()=>(()=>{var Q={4567:function(T,r,a){var l=this&&this.__decorate||function(e,t,o,f){var d,p=arguments.length,h=p<3?t:f===null?f=Object.getOwnPropertyDescriptor(t,o):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")h=Reflect.decorate(e,t,o,f);else for(var m=e.length-1;m>=0;m--)(d=e[m])&&(h=(p<3?d(h):p>3?d(t,o,h):d(t,o))||h);return p>3&&h&&Object.defineProperty(t,o,h),h},_=this&&this.__param||function(e,t){return function(o,f){t(o,f,e)}};Object.defineProperty(r,"__esModule",{value:!0}),r.AccessibilityManager=void 0;const n=a(9042),u=a(9924),v=a(844),g=a(4725),c=a(2585),i=a(3656);let s=r.AccessibilityManager=class extends v.Disposable{constructor(e,t,o,f){super(),this._terminal=e,this._coreBrowserService=o,this._renderService=f,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let d=0;d<this._terminal.rows;d++)this._rowElements[d]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[d]);if(this._topBoundaryFocusListener=d=>this._handleBoundaryFocus(d,0),this._bottomBoundaryFocusListener=d=>this._handleBoundaryFocus(d,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new u.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(d=>this._handleResize(d.rows))),this.register(this._terminal.onRender(d=>this._refreshRows(d.start,d.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(d=>this._handleChar(d))),this.register(this._terminal.onLineFeed(()=>this._handleChar(`
1
+ import{u as be,r as Y,a as we,s as ye,o as Ee,h as ke,j as J,S as Le,I as De,b as Re}from"./index-BzUof8lw.js";var ge={exports:{}};(function(se,le){(function(Q,K){se.exports=K()})(globalThis,()=>(()=>{var Q={4567:function(T,r,a){var l=this&&this.__decorate||function(e,t,o,f){var d,p=arguments.length,h=p<3?t:f===null?f=Object.getOwnPropertyDescriptor(t,o):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")h=Reflect.decorate(e,t,o,f);else for(var m=e.length-1;m>=0;m--)(d=e[m])&&(h=(p<3?d(h):p>3?d(t,o,h):d(t,o))||h);return p>3&&h&&Object.defineProperty(t,o,h),h},_=this&&this.__param||function(e,t){return function(o,f){t(o,f,e)}};Object.defineProperty(r,"__esModule",{value:!0}),r.AccessibilityManager=void 0;const n=a(9042),u=a(9924),v=a(844),g=a(4725),c=a(2585),i=a(3656);let s=r.AccessibilityManager=class extends v.Disposable{constructor(e,t,o,f){super(),this._terminal=e,this._coreBrowserService=o,this._renderService=f,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let d=0;d<this._terminal.rows;d++)this._rowElements[d]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[d]);if(this._topBoundaryFocusListener=d=>this._handleBoundaryFocus(d,0),this._bottomBoundaryFocusListener=d=>this._handleBoundaryFocus(d,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new u.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize(d=>this._handleResize(d.rows))),this.register(this._terminal.onRender(d=>this._refreshRows(d.start,d.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(d=>this._handleChar(d))),this.register(this._terminal.onLineFeed(()=>this._handleChar(`
2
2
  `))),this.register(this._terminal.onA11yTab(d=>this._handleTab(d))),this.register(this._terminal.onKey(d=>this._handleKey(d.key))),this.register(this._terminal.onBlur(()=>this._clearLiveRegion())),this.register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this.register((0,i.addDisposableDomListener)(document,"selectionchange",()=>this._handleSelectionChange())),this.register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRows(),this.register((0,v.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
3
3
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=n.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const o=this._terminal.buffer,f=o.lines.length.toString();for(let d=e;d<=t;d++){const p=o.lines.get(o.ydisp+d),h=[],m=(p==null?void 0:p.translateToString(!0,void 0,void 0,h))||"",y=(o.ydisp+d+1).toString(),k=this._rowElements[d];k&&(m.length===0?(k.innerText=" ",this._rowColumns.set(k,[0,1])):(k.textContent=m,this._rowColumns.set(k,h)),k.setAttribute("aria-posinset",y),k.setAttribute("aria-setsize",f))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const o=e.target,f=this._rowElements[t===0?1:this._rowElements.length-2];if(o.getAttribute("aria-posinset")===(t===0?"1":`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==f)return;let d,p;if(t===0?(d=o,p=this._rowElements.pop(),this._rowContainer.removeChild(p)):(d=this._rowElements.shift(),p=o,this._rowContainer.removeChild(d)),d.removeEventListener("focus",this._topBoundaryFocusListener),p.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){const h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{const h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){var m;if(this._rowElements.length===0)return;const e=document.getSelection();if(!e)return;if(e.isCollapsed)return void(this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection());if(!e.anchorNode||!e.focusNode)return void console.error("anchorNode and/or focusNode are null");let t={node:e.anchorNode,offset:e.anchorOffset},o={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(o.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===o.node&&t.offset>o.offset)&&([t,o]=[o,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;const f=this._rowElements.slice(-1)[0];if(o.node.compareDocumentPosition(f)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(o={node:f,offset:((m=f.textContent)==null?void 0:m.length)??0}),!this._rowContainer.contains(o.node))return;const d=({node:y,offset:k})=>{const L=y instanceof Text?y.parentNode:y;let b=parseInt(L==null?void 0:L.getAttribute("aria-posinset"),10)-1;if(isNaN(b))return console.warn("row is invalid. Race condition?"),null;const x=this._rowColumns.get(L);if(!x)return console.warn("columns is null. Race condition?"),null;let A=k<x.length?x[k]:x.slice(-1)[0]+1;return A>=this._terminal.cols&&(++b,A=0),{row:b,column:A}},p=d(t),h=d(o);if(p&&h){if(p.row>h.row||p.row===h.row&&p.column>=h.column)throw new Error("invalid range");this._terminal.select(p.column,p.row,(h.row-p.row)*this._terminal.cols-p.column+h.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}};r.AccessibilityManager=s=l([_(1,c.IInstantiationService),_(2,g.ICoreBrowserService),_(3,g.IRenderService)],s)},3614:(T,r)=>{function a(u){return u.replace(/\r?\n/g,"\r")}function l(u,v){return v?"\x1B[200~"+u+"\x1B[201~":u}function _(u,v,g,c){u=l(u=a(u),g.decPrivateModes.bracketedPasteMode&&c.rawOptions.ignoreBracketedPasteMode!==!0),g.triggerDataEvent(u,!0),v.value=""}function n(u,v,g){const c=g.getBoundingClientRect(),i=u.clientX-c.left-10,s=u.clientY-c.top-10;v.style.width="20px",v.style.height="20px",v.style.left=`${i}px`,v.style.top=`${s}px`,v.style.zIndex="1000",v.focus()}Object.defineProperty(r,"__esModule",{value:!0}),r.rightClickHandler=r.moveTextAreaUnderMouseCursor=r.paste=r.handlePasteEvent=r.copyHandler=r.bracketTextForPaste=r.prepareTextForTerminal=void 0,r.prepareTextForTerminal=a,r.bracketTextForPaste=l,r.copyHandler=function(u,v){u.clipboardData&&u.clipboardData.setData("text/plain",v.selectionText),u.preventDefault()},r.handlePasteEvent=function(u,v,g,c){u.stopPropagation(),u.clipboardData&&_(u.clipboardData.getData("text/plain"),v,g,c)},r.paste=_,r.moveTextAreaUnderMouseCursor=n,r.rightClickHandler=function(u,v,g,c,i){n(u,v,g),i&&c.rightClickSelect(u),v.value=c.selectionText,v.select()}},7239:(T,r,a)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.ColorContrastCache=void 0;const l=a(1505);r.ColorContrastCache=class{constructor(){this._color=new l.TwoKeyMap,this._css=new l.TwoKeyMap}setCss(_,n,u){this._css.set(_,n,u)}getCss(_,n){return this._css.get(_,n)}setColor(_,n,u){this._color.set(_,n,u)}getColor(_,n){return this._color.get(_,n)}clear(){this._color.clear(),this._css.clear()}}},3656:(T,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.addDisposableDomListener=void 0,r.addDisposableDomListener=function(a,l,_,n){a.addEventListener(l,_,n);let u=!1;return{dispose:()=>{u||(u=!0,a.removeEventListener(l,_,n))}}}},3551:function(T,r,a){var l=this&&this.__decorate||function(s,e,t,o){var f,d=arguments.length,p=d<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,t):o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")p=Reflect.decorate(s,e,t,o);else for(var h=s.length-1;h>=0;h--)(f=s[h])&&(p=(d<3?f(p):d>3?f(e,t,p):f(e,t))||p);return d>3&&p&&Object.defineProperty(e,t,p),p},_=this&&this.__param||function(s,e){return function(t,o){e(t,o,s)}};Object.defineProperty(r,"__esModule",{value:!0}),r.Linkifier=void 0;const n=a(3656),u=a(8460),v=a(844),g=a(2585),c=a(4725);let i=r.Linkifier=class extends v.Disposable{get currentLink(){return this._currentLink}constructor(s,e,t,o,f){super(),this._element=s,this._mouseService=e,this._renderService=t,this._bufferService=o,this._linkProviderService=f,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new u.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new u.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,v.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,v.toDisposable)(()=>{var d;this._lastMouseEvent=void 0,(d=this._activeProviderReplies)==null||d.clear()})),this.register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this.register((0,n.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,n.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(s){this._lastMouseEvent=s;const e=this._positionFromMouseEvent(s,this._element,this._mouseService);if(!e)return;this._isMouseOut=!1;const t=s.composedPath();for(let o=0;o<t.length;o++){const f=t[o];if(f.classList.contains("xterm"))break;if(f.classList.contains("xterm-hover"))return}this._lastBufferCell&&e.x===this._lastBufferCell.x&&e.y===this._lastBufferCell.y||(this._handleHover(e),this._lastBufferCell=e)}_handleHover(s){if(this._activeLine!==s.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(s,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,s)||(this._clearCurrentLink(),this._askForLink(s,!0))}_askForLink(s,e){var o,f;this._activeProviderReplies&&e||((o=this._activeProviderReplies)==null||o.forEach(d=>{d==null||d.forEach(p=>{p.link.dispose&&p.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=s.y);let t=!1;for(const[d,p]of this._linkProviderService.linkProviders.entries())e?(f=this._activeProviderReplies)!=null&&f.get(d)&&(t=this._checkLinkProviderResult(d,s,t)):p.provideLinks(s.y,h=>{var y,k;if(this._isMouseOut)return;const m=h==null?void 0:h.map(L=>({link:L}));(y=this._activeProviderReplies)==null||y.set(d,m),t=this._checkLinkProviderResult(d,s,t),((k=this._activeProviderReplies)==null?void 0:k.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(s.y,this._activeProviderReplies)})}_removeIntersectingLinks(s,e){const t=new Set;for(let o=0;o<e.size;o++){const f=e.get(o);if(f)for(let d=0;d<f.length;d++){const p=f[d],h=p.link.range.start.y<s?0:p.link.range.start.x,m=p.link.range.end.y>s?this._bufferService.cols:p.link.range.end.x;for(let y=h;y<=m;y++){if(t.has(y)){f.splice(d--,1);break}t.add(y)}}}}_checkLinkProviderResult(s,e,t){var d;if(!this._activeProviderReplies)return t;const o=this._activeProviderReplies.get(s);let f=!1;for(let p=0;p<s;p++)this._activeProviderReplies.has(p)&&!this._activeProviderReplies.get(p)||(f=!0);if(!f&&o){const p=o.find(h=>this._linkAtPosition(h.link,e));p&&(t=!0,this._handleNewLink(p))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!t)for(let p=0;p<this._activeProviderReplies.size;p++){const h=(d=this._activeProviderReplies.get(p))==null?void 0:d.find(m=>this._linkAtPosition(m.link,e));if(h){t=!0,this._handleNewLink(h);break}}return t}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(s){if(!this._currentLink)return;const e=this._positionFromMouseEvent(s,this._element,this._mouseService);e&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,e)&&this._currentLink.link.activate(s,this._currentLink.link.text)}_clearCurrentLink(s,e){this._currentLink&&this._lastMouseEvent&&(!s||!e||this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=e)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,v.disposeArray)(this._linkCacheDisposables))}_handleNewLink(s){if(!this._lastMouseEvent)return;const e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._linkAtPosition(s.link,e)&&(this._currentLink=s,this._currentLink.state={decorations:{underline:s.link.decorations===void 0||s.link.decorations.underline,pointerCursor:s.link.decorations===void 0||s.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,s.link,this._lastMouseEvent),s.link.decorations={},Object.defineProperties(s.link.decorations,{pointerCursor:{get:()=>{var t,o;return(o=(t=this._currentLink)==null?void 0:t.state)==null?void 0:o.decorations.pointerCursor},set:t=>{var o;(o=this._currentLink)!=null&&o.state&&this._currentLink.state.decorations.pointerCursor!==t&&(this._currentLink.state.decorations.pointerCursor=t,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",t))}},underline:{get:()=>{var t,o;return(o=(t=this._currentLink)==null?void 0:t.state)==null?void 0:o.decorations.underline},set:t=>{var o,f,d;(o=this._currentLink)!=null&&o.state&&((d=(f=this._currentLink)==null?void 0:f.state)==null?void 0:d.decorations.underline)!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(s.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(t=>{if(!this._currentLink)return;const o=t.start===0?0:t.start+1+this._bufferService.buffer.ydisp,f=this._bufferService.buffer.ydisp+1+t.end;if(this._currentLink.link.range.start.y>=o&&this._currentLink.link.range.end.y<=f&&(this._clearCurrentLink(o,f),this._lastMouseEvent)){const d=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);d&&this._askForLink(d,!1)}})))}_linkHover(s,e,t){var o;(o=this._currentLink)!=null&&o.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(e,!0),this._currentLink.state.decorations.pointerCursor&&s.classList.add("xterm-cursor-pointer")),e.hover&&e.hover(t,e.text)}_fireUnderlineEvent(s,e){const t=s.range,o=this._bufferService.buffer.ydisp,f=this._createLinkUnderlineEvent(t.start.x-1,t.start.y-o-1,t.end.x,t.end.y-o-1,void 0);(e?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(f)}_linkLeave(s,e,t){var o;(o=this._currentLink)!=null&&o.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(e,!1),this._currentLink.state.decorations.pointerCursor&&s.classList.remove("xterm-cursor-pointer")),e.leave&&e.leave(t,e.text)}_linkAtPosition(s,e){const t=s.range.start.y*this._bufferService.cols+s.range.start.x,o=s.range.end.y*this._bufferService.cols+s.range.end.x,f=e.y*this._bufferService.cols+e.x;return t<=f&&f<=o}_positionFromMouseEvent(s,e,t){const o=t.getCoords(s,e,this._bufferService.cols,this._bufferService.rows);if(o)return{x:o[0],y:o[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(s,e,t,o,f){return{x1:s,y1:e,x2:t,y2:o,cols:this._bufferService.cols,fg:f}}};r.Linkifier=i=l([_(1,c.IMouseService),_(2,c.IRenderService),_(3,g.IBufferService),_(4,c.ILinkProviderService)],i)},9042:(T,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),r.tooMuchOutput=r.promptLabel=void 0,r.promptLabel="Terminal input",r.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(T,r,a){var l=this&&this.__decorate||function(c,i,s,e){var t,o=arguments.length,f=o<3?i:e===null?e=Object.getOwnPropertyDescriptor(i,s):e;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(c,i,s,e);else for(var d=c.length-1;d>=0;d--)(t=c[d])&&(f=(o<3?t(f):o>3?t(i,s,f):t(i,s))||f);return o>3&&f&&Object.defineProperty(i,s,f),f},_=this&&this.__param||function(c,i){return function(s,e){i(s,e,c)}};Object.defineProperty(r,"__esModule",{value:!0}),r.OscLinkProvider=void 0;const n=a(511),u=a(2585);let v=r.OscLinkProvider=class{constructor(c,i,s){this._bufferService=c,this._optionsService=i,this._oscLinkService=s}provideLinks(c,i){var m;const s=this._bufferService.buffer.lines.get(c-1);if(!s)return void i(void 0);const e=[],t=this._optionsService.rawOptions.linkHandler,o=new n.CellData,f=s.getTrimmedLength();let d=-1,p=-1,h=!1;for(let y=0;y<f;y++)if(p!==-1||s.hasContent(y)){if(s.loadCell(y,o),o.hasExtendedAttrs()&&o.extended.urlId){if(p===-1){p=y,d=o.extended.urlId;continue}h=o.extended.urlId!==d}else p!==-1&&(h=!0);if(h||p!==-1&&y===f-1){const k=(m=this._oscLinkService.getLinkData(d))==null?void 0:m.uri;if(k){const L={start:{x:p+1,y:c},end:{x:y+(h||y!==f-1?0:1),y:c}};let b=!1;if(!(t!=null&&t.allowNonHttpProtocols))try{const x=new URL(k);["http:","https:"].includes(x.protocol)||(b=!0)}catch{b=!0}b||e.push({text:k,range:L,activate:(x,A)=>t?t.activate(x,A,L):g(0,A),hover:(x,A)=>{var P;return(P=t==null?void 0:t.hover)==null?void 0:P.call(t,x,A,L)},leave:(x,A)=>{var P;return(P=t==null?void 0:t.leave)==null?void 0:P.call(t,x,A,L)}})}h=!1,o.hasExtendedAttrs()&&o.extended.urlId?(p=y,d=o.extended.urlId):(p=-1,d=-1)}}i(e)}};function g(c,i){if(confirm(`Do you want to navigate to ${i}?
4
4