@cocorograph/hub-agent 0.6.44 → 0.6.45

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cocorograph/hub-agent",
3
- "version": "0.6.44",
3
+ "version": "0.6.45",
4
4
  "description": "Hub Hosted Cockpit のローカル常駐 agent。Hub と outbound WSS で接続し、ローカルの tmux/pty を中継する。",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -0,0 +1,185 @@
1
+ /**
2
+ * jsonl ライブ追従 watcher の束ね役 (T04784 逐次表示)。
3
+ *
4
+ * Cockpit の TUI チャットは「対話 TUI (tmux/PTY) の claude が書く jsonl」を表示源にする。
5
+ * 従来は session.event (ターン境界) を合図に jsonl 全体を再 hydrate して「どさっと」更新
6
+ * していたが、ターン中の途中経過は 2.5s ポーリングで拾うしかなく、逐次性が弱かった。
7
+ *
8
+ * 本 manager は、ブラウザが送る `claude.tui.viewing {session_id, cwd}` ハートビート
9
+ * (= まさにその session を TUI チャットで閲覧している瞬間) を起点に、対象 session の
10
+ * jsonl を byte offset で tail し (claude-history-watch.mjs)、追記行を 1 行ずつ
11
+ * `claude.jsonl.event` として WS push する。これでターン中の本文・ツール結果が逐次
12
+ * ブラウザに届き、再 hydrate / ポーリングが不要になる。
13
+ *
14
+ * ライフサイクルは watcher ゲートの TuiViewerRegistry と相似形:
15
+ * - note(): 閲覧ハートビートで watcher を起動 or TTL 延長。
16
+ * - unwatch(): claude.tui.unviewing で即停止。
17
+ * - _sweep(): TTL 失効した watcher を掃除 (unviewing 取りこぼし対策)。
18
+ *
19
+ * 課金枠への影響なし: jsonl の読み取りはローカル FS の追従であり、モデル呼び出しを
20
+ * 伴わない (SDK query を起こさない)。TUI モード = サブスク枠のまま。
21
+ *
22
+ * fromEnd=true で監視開始時点の既存内容はスキップする。初回履歴は claude.history.request
23
+ * で別途 hydrate 済みのため、tail は新規分だけでよい (二重 push は frontend が uuid で排除)。
24
+ */
25
+
26
+ import { watchSessionFile } from "./claude-history-watch.mjs"
27
+ import { jsonlPath } from "./claude-history.mjs"
28
+
29
+ /** watcher 鮮度 (ms)。ブラウザのハートビート間隔 (5s) の 3 倍を既定とする。 */
30
+ const WATCHER_TTL_MS = Number(process.env.COCKPIT_JSONL_WATCH_TTL_MS) || 15_000
31
+ /** TTL 失効 watcher を掃除する周期 (ms)。 */
32
+ const SWEEP_INTERVAL_MS = 30 * 1000
33
+
34
+ /**
35
+ * session_id ごとに 1 つの jsonl tail watcher を保持し、閲覧ハートビートで延命する。
36
+ */
37
+ export class JsonlLiveWatchers {
38
+ /**
39
+ * @param {object} args
40
+ * @param {(obj: object) => unknown} args.send - WS 送信 (client.send バインド済み)
41
+ * @param {() => Promise<string|undefined>|string|undefined} args.getProjectsRoot
42
+ * - ~/.claude/projects の実効ルート解決 (アカウント切替を反映)
43
+ * @param {number} [args.ttlMs]
44
+ * @param {import('pino').Logger} [args.logger]
45
+ */
46
+ constructor({ send, getProjectsRoot, ttlMs = WATCHER_TTL_MS, logger } = {}) {
47
+ this.send = send
48
+ this.getProjectsRoot = getProjectsRoot
49
+ this.ttlMs = ttlMs
50
+ this.logger = logger
51
+ /** @type {Map<string, {watcher: {stop: () => void}, cwd: string, expiresAt: number}>} */
52
+ this._entries = new Map()
53
+ this._sweepTimer = null
54
+ /** 同一 session に対する note() の競合を直列化する (二重 watcher 防止)。 */
55
+ this._starting = new Set()
56
+ }
57
+
58
+ /** 周期 sweep を張る。 */
59
+ start() {
60
+ this._sweepTimer = setInterval(() => this._sweep(), SWEEP_INTERVAL_MS)
61
+ // 他 timer 同様 unref して agent のアイドル終了を妨げない。
62
+ this._sweepTimer?.unref?.()
63
+ }
64
+
65
+ /**
66
+ * 閲覧ハートビートを受けて watcher を起動 or 延命する。
67
+ *
68
+ * @param {{session_id?: string|null, cwd?: string|null}} info
69
+ * @returns {Promise<void>}
70
+ */
71
+ async note({ session_id, cwd } = {}) {
72
+ if (!session_id || !cwd) return
73
+ const existing = this._entries.get(session_id)
74
+ if (existing) {
75
+ // 既に追従中: TTL を延長するだけ (cwd が変わるのは想定外なので無視)。
76
+ existing.expiresAt = Date.now() + this.ttlMs
77
+ return
78
+ }
79
+ // 起動中の重複呼び出しを弾く (ハートビートが連続して来ても watcher は 1 本)。
80
+ if (this._starting.has(session_id)) return
81
+ this._starting.add(session_id)
82
+ try {
83
+ const projectsRoot = await this._resolveProjectsRoot()
84
+ // 起動処理中に別経路で登録済みになっていないか再チェック。
85
+ if (this._entries.has(session_id)) return
86
+ const filePath = jsonlPath({ cwd, session_id, projectsRoot })
87
+ const watcher = watchSessionFile({
88
+ filePath,
89
+ fromEnd: true,
90
+ logger: this.logger,
91
+ onEvent: (event) => {
92
+ try {
93
+ this.send?.({
94
+ type: "claude.jsonl.event",
95
+ session_id,
96
+ cwd,
97
+ event,
98
+ })
99
+ } catch (err) {
100
+ this.logger?.warn(
101
+ { err: err?.message },
102
+ "jsonl live watch send failed",
103
+ )
104
+ }
105
+ },
106
+ })
107
+ this._entries.set(session_id, {
108
+ watcher,
109
+ cwd,
110
+ expiresAt: Date.now() + this.ttlMs,
111
+ })
112
+ } catch (err) {
113
+ this.logger?.warn(
114
+ { err: err?.message, session_id },
115
+ "jsonl live watch start failed",
116
+ )
117
+ } finally {
118
+ this._starting.delete(session_id)
119
+ }
120
+ }
121
+
122
+ /**
123
+ * 閲覧終了を受けて watcher を即停止する。
124
+ *
125
+ * @param {{session_id?: string|null}} info
126
+ */
127
+ unwatch({ session_id } = {}) {
128
+ if (!session_id) return
129
+ const entry = this._entries.get(session_id)
130
+ if (!entry) return
131
+ this._entries.delete(session_id)
132
+ try {
133
+ entry.watcher.stop()
134
+ } catch {
135
+ /* ignore */
136
+ }
137
+ }
138
+
139
+ async _resolveProjectsRoot() {
140
+ try {
141
+ const r = this.getProjectsRoot?.()
142
+ return r && typeof r.then === "function" ? await r : r
143
+ } catch {
144
+ return undefined
145
+ }
146
+ }
147
+
148
+ /** TTL を過ぎた watcher を停止・削除する (unviewing 取りこぼし対策)。 */
149
+ _sweep() {
150
+ const now = Date.now()
151
+ for (const [session_id, entry] of this._entries) {
152
+ if (entry.expiresAt <= now) {
153
+ this._entries.delete(session_id)
154
+ try {
155
+ entry.watcher.stop()
156
+ } catch {
157
+ /* ignore */
158
+ }
159
+ }
160
+ }
161
+ }
162
+
163
+ /** 全 watcher と sweep timer を停止する。 */
164
+ stop() {
165
+ if (this._sweepTimer) {
166
+ clearInterval(this._sweepTimer)
167
+ this._sweepTimer = null
168
+ }
169
+ for (const entry of this._entries.values()) {
170
+ try {
171
+ entry.watcher.stop()
172
+ } catch {
173
+ /* ignore */
174
+ }
175
+ }
176
+ this._entries.clear()
177
+ }
178
+
179
+ /** テスト用: 現在追従中の session_id 数。 */
180
+ get size() {
181
+ return this._entries.size
182
+ }
183
+ }
184
+
185
+ export default JsonlLiveWatchers
package/src/main.mjs CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  } from "./tmux.mjs"
52
52
  import { TuiPermissionBridge } from "./tui-permission-bridge.mjs"
53
53
  import { TuiViewerRegistry } from "./tui-viewer-registry.mjs"
54
+ import { JsonlLiveWatchers } from "./jsonl-live-watchers.mjs"
54
55
  import {
55
56
  contextWindowSize,
56
57
  getSessionUsages,
@@ -439,6 +440,17 @@ export async function startDaemon({ version, ptyModule, claudeSdk } = {}) {
439
440
  await tuiViewerRegistry.start()
440
441
  ctx.tuiViewerRegistry = tuiViewerRegistry
441
442
 
443
+ // jsonl ライブ追従 (T04784 逐次表示): TUI チャットの閲覧ハートビートを起点に対象
444
+ // session の jsonl を tail し、追記行を claude.jsonl.event として逐次 push する。
445
+ // これで session.event 合図 → 全体再 hydrate + 2.5s ポーリングの「どさっと」を廃せる。
446
+ const jsonlLiveWatchers = new JsonlLiveWatchers({
447
+ send: (obj) => client.send(obj),
448
+ getProjectsRoot: getActiveProjectsRoot,
449
+ logger,
450
+ })
451
+ jsonlLiveWatchers.start()
452
+ ctx.jsonlLiveWatchers = jsonlLiveWatchers
453
+
442
454
  const shutdown = async (signal) => {
443
455
  logger.info({ signal }, "shutting down")
444
456
  await runHookBroadcast(plugins, "onAgentStop", ctx)
@@ -446,6 +458,7 @@ export async function startDaemon({ version, ptyModule, claudeSdk } = {}) {
446
458
  sessionEventLoop?.stop?.()
447
459
  tuiPermissionBridge.stop()
448
460
  tuiViewerRegistry.stop()
461
+ jsonlLiveWatchers.stop()
449
462
  ptyBridge.shutdown()
450
463
  claudeBridge?.shutdown?.()
451
464
  client.stop()
@@ -1032,12 +1045,18 @@ async function dispatch(msg, ctx) {
1032
1045
  ctx.tuiViewerRegistry
1033
1046
  ?.note({ session_id: msg.session_id, cwd: msg.cwd })
1034
1047
  .catch(() => {})
1048
+ // T04784 逐次表示: 閲覧中だけ jsonl を tail して claude.jsonl.event を push。
1049
+ ctx.jsonlLiveWatchers
1050
+ ?.note({ session_id: msg.session_id, cwd: msg.cwd })
1051
+ .catch(() => {})
1035
1052
  return
1036
1053
  case "claude.tui.unviewing":
1037
1054
  // 閲覧終了。session_id マーカーを即失効させ、以降の Bash を即 ask に倒す。
1038
1055
  ctx.tuiViewerRegistry
1039
1056
  ?.unview({ session_id: msg.session_id })
1040
1057
  .catch(() => {})
1058
+ // jsonl tail も即停止 (閲覧していない session を追従し続けない)。
1059
+ ctx.jsonlLiveWatchers?.unwatch({ session_id: msg.session_id })
1041
1060
  return
1042
1061
  case "claude.mcp.status":
1043
1062
  case "claude.mcp.reconnect":