@cocorograph/hub-agent 0.7.37 → 0.7.42

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.
@@ -0,0 +1,150 @@
1
+ /**
2
+ * sibling-inject (同一 cwd の claude⇄codex 相互依頼) の受信ブリッジ (2026-07-04)。
3
+ *
4
+ * ask-sibling スキル経由の `cockpit_orch.py` (Cockpit ブラウザの WS 接続を持たない、
5
+ * Bash tool 経由で動く別プロセス) が、同一マシン上で稼働中の hub-agent デーモンへ
6
+ * 「この cwd の生きているチャットセッション (claude/codex) へ新規ターンを注入して
7
+ * ほしい」と頼むための受信口。
8
+ *
9
+ * 設計 (WHY): hub-agent はローカル HTTP/Unix ソケットサーバを持たないため、既存の
10
+ * ファイル IPC 前例 (tui-permission-bridge.mjs 等、`/tmp/cockpit_*` + fs.watch +
11
+ * atomic write) と同じパターンに揃える。
12
+ *
13
+ * ⚠️ セキュリティ設計 (2026-07-04 セッションでユーザー承認済み): この機構は
14
+ * 「生きている自律エージェント (シェル/API/MCP ツールへのフルアクセス権を持つ)
15
+ * へ外部プロセスから新規指示を注入する」という強い書き込み権限を持つため、
16
+ * `src/sibling-token.mjs` の cwd スコープ capability トークンによる検証を必須とする。
17
+ * トークンが一致しない要求は無視し (実行せず削除)、warn ログのみ残す。
18
+ *
19
+ * 契約: request file `<request_id>.json` = `{cwd, target_cli_kind, text, token}`。
20
+ * 処理後は必ず削除し (成否問わず)、呼び出し側が待ち受けられるよう
21
+ * `<request_id>.result.json` = `{ok, error?}` を書く。
22
+ */
23
+
24
+ import { watch } from "node:fs"
25
+ import { mkdir, readFile, writeFile, rename, unlink, readdir } from "node:fs/promises"
26
+ import path from "node:path"
27
+
28
+ import { verifySiblingToken } from "./sibling-token.mjs"
29
+
30
+ export const SIBLING_REQUESTS_DIR =
31
+ process.env.COCKPIT_SIBLING_REQUESTS_DIR || "/tmp/cockpit_sibling_requests"
32
+
33
+ export class SiblingInjectBridge {
34
+ /**
35
+ * @param {{dir?: string, claudeBridge?: object, codexBridge?: object, logger?: object}} [opts]
36
+ */
37
+ constructor({ dir = SIBLING_REQUESTS_DIR, claudeBridge, codexBridge, logger } = {}) {
38
+ this.dir = dir
39
+ this.claudeBridge = claudeBridge
40
+ this.codexBridge = codexBridge
41
+ this.logger = logger
42
+ /** @type {Set<string>} 二重処理防止 (request_id) */
43
+ this._seen = new Set()
44
+ this._watcher = null
45
+ }
46
+
47
+ /** 監視ディレクトリを作成し、既存要求を sweep してから fs.watch を張る。 */
48
+ async start() {
49
+ await mkdir(this.dir, { recursive: true })
50
+ await this._sweep()
51
+ try {
52
+ this._watcher = watch(this.dir, (_event, filename) => {
53
+ if (filename && filename.endsWith(".json") && !filename.endsWith(".result.json")) {
54
+ this._ingest(filename).catch((err) => {
55
+ this.logger?.warn({ err: err?.message, filename }, "sibling-inject ingest failed")
56
+ })
57
+ }
58
+ })
59
+ } catch (err) {
60
+ this.logger?.warn(
61
+ { err: err?.message },
62
+ "sibling-inject watcher: fs.watch failed, watcher disabled",
63
+ )
64
+ }
65
+ }
66
+
67
+ /** 起動時 / 取りこぼし保険: dir 内の全要求ファイルを読む。 */
68
+ async _sweep() {
69
+ let names = []
70
+ try {
71
+ names = await readdir(this.dir)
72
+ } catch {
73
+ return
74
+ }
75
+ for (const n of names) {
76
+ if (n.endsWith(".json") && !n.endsWith(".result.json")) {
77
+ await this._ingest(n).catch((err) => {
78
+ this.logger?.warn({ err: err?.message, filename: n }, "sibling-inject sweep failed")
79
+ })
80
+ }
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 要求ファイル 1 件を読み、トークン検証後に対象 cwd のセッションへ注入する。
86
+ * 成否によらず要求ファイルは削除し、結果ファイルを書く。
87
+ * @param {string} filename `<request_id>.json`
88
+ */
89
+ async _ingest(filename) {
90
+ const request_id = filename.slice(0, -".json".length)
91
+ if (this._seen.has(request_id)) return
92
+ this._seen.add(request_id)
93
+ const fp = path.join(this.dir, filename)
94
+ let body
95
+ try {
96
+ body = JSON.parse(await readFile(fp, "utf-8"))
97
+ } catch {
98
+ // partial write / 既に消えた → 次の watch イベントで拾い直す (seen から外す)。
99
+ this._seen.delete(request_id)
100
+ return
101
+ }
102
+
103
+ const { cwd, target_cli_kind, text, token } = body || {}
104
+ let result
105
+ if (!cwd || !text || (target_cli_kind !== "claude" && target_cli_kind !== "codex")) {
106
+ result = { ok: false, error: "invalid_request" }
107
+ } else if (!verifySiblingToken(cwd, token)) {
108
+ this.logger?.warn({ cwd, request_id }, "sibling-inject: token mismatch, request denied")
109
+ result = { ok: false, error: "invalid_token" }
110
+ } else {
111
+ const bridge = target_cli_kind === "codex" ? this.codexBridge : this.claudeBridge
112
+ const sent = bridge?.sendToCwd?.(cwd, text) ?? false
113
+ result = sent
114
+ ? { ok: true }
115
+ : { ok: false, error: "no_live_session_for_cwd" }
116
+ }
117
+
118
+ await this._writeResult(request_id, result)
119
+ // 要求ファイルは処理後に必ず削除する (成否問わず、再処理させないため)。
120
+ try {
121
+ await unlink(fp)
122
+ } catch {
123
+ /* 既に無ければ no-op */
124
+ }
125
+ }
126
+
127
+ /** 結果ファイルを atomic write する (呼び出し側 CLI がポーリングする)。 */
128
+ async _writeResult(request_id, result) {
129
+ const fp = path.join(this.dir, `${request_id}.result.json`)
130
+ const tmp = `${fp}.tmp`
131
+ try {
132
+ await writeFile(tmp, JSON.stringify(result))
133
+ await rename(tmp, fp)
134
+ } catch (err) {
135
+ this.logger?.warn({ err: err?.message, request_id }, "sibling-inject result write failed")
136
+ }
137
+ }
138
+
139
+ /** watcher を閉じる。 */
140
+ stop() {
141
+ try {
142
+ this._watcher?.close()
143
+ } catch {
144
+ /* ignore */
145
+ }
146
+ this._watcher = null
147
+ }
148
+ }
149
+
150
+ export default SiblingInjectBridge
@@ -0,0 +1,62 @@
1
+ /**
2
+ * sibling-inject (同一 cwd の claude⇄codex 相互依頼) 用の cwd スコープ capability
3
+ * トークンストア (2026-07-04)。
4
+ *
5
+ * 設計の背景 (WHY):
6
+ * hub-agent はローカル HTTP/Unix ソケットサーバを持たず、既存のローカル IPC は
7
+ * すべて `/tmp/cockpit_*` 配下のファイルベース (tui-permission-bridge.mjs 等) で、
8
+ * 認証機構を持たない (同一 UID なら誰でも読み書きできる想定)。
9
+ *
10
+ * sibling-inject はこの上に「生きているチャットセッションへ新規ターンを注入する」
11
+ * という強い書き込み権限を追加するため、無認証のままだと「同一マシン上の無関係な
12
+ * 別プロセス (npm postinstall スクリプト等) が自律エージェント (シェル/API/MCP
13
+ * ツールへのフルアクセス権を持つ) へ任意の指示を注入できる」という新しい攻撃面に
14
+ * なる (2026-07-04 セッションで実装時に確認済みの懸念、ユーザー承認済み)。
15
+ *
16
+ * 対策: cwd ごとにランダムな capability トークンを発行し、hub-agent がそのセッション
17
+ * (claude/codex いずれも) を spawn する際に **そのプロセス自身の環境変数にのみ**
18
+ * 渡す (`COCKPIT_SIBLING_TOKEN`、ディスクには書かない)。sibling-inject の受信側は
19
+ * このトークンが一致した場合のみ注入を実行する。これにより「/tmp を書き換えられる
20
+ * 全プロセス」ではなく「そのセッション自身の環境変数を読めるプロセス (= 既に
21
+ * hub-agent が spawn した agent 自身、またはその子プロセス)」だけが注入できる設計に
22
+ * 絞り込める。Hub ユーザートークン (agent 全体を認証する、より広い権限を持つ鍵) を
23
+ * 転用しない理由: ディスク保存されるため同じ攻撃者から結局読める上、漏洩時の被害
24
+ * 範囲がこの cwd 限定トークンより大きくなるため。
25
+ */
26
+
27
+ import { randomBytes } from "node:crypto"
28
+
29
+ /** @type {Map<string, string>} cwd -> token */
30
+ const tokensByCwd = new Map()
31
+
32
+ /**
33
+ * 指定 cwd の capability トークンを返す (無ければ新規発行)。
34
+ * @param {string} cwd
35
+ * @returns {string}
36
+ */
37
+ export function getOrCreateSiblingToken(cwd) {
38
+ if (!cwd) throw new Error("getOrCreateSiblingToken: cwd is required")
39
+ let token = tokensByCwd.get(cwd)
40
+ if (!token) {
41
+ token = randomBytes(32).toString("hex")
42
+ tokensByCwd.set(cwd, token)
43
+ }
44
+ return token
45
+ }
46
+
47
+ /**
48
+ * 指定 cwd に対して提示されたトークンが正しいか検証する。
49
+ * @param {string} cwd
50
+ * @param {string} token
51
+ * @returns {boolean}
52
+ */
53
+ export function verifySiblingToken(cwd, token) {
54
+ if (!cwd || !token) return false
55
+ const expected = tokensByCwd.get(cwd)
56
+ return typeof expected === "string" && expected === token
57
+ }
58
+
59
+ /** テスト用: トークンストアを全クリアする。 */
60
+ export function _resetSiblingTokens() {
61
+ tokensByCwd.clear()
62
+ }