@cocorograph/hub-agent 0.6.6 → 0.6.7

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/usage.mjs +97 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cocorograph/hub-agent",
3
- "version": "0.6.6",
3
+ "version": "0.6.7",
4
4
  "description": "Hub Hosted Cockpit のローカル常駐 agent。Hub と outbound WSS で接続し、ローカルの tmux/pty を中継する。",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/usage.mjs CHANGED
@@ -55,6 +55,12 @@ function statuslineSessionsDir() {
55
55
 
56
56
  const SESSION_STALE_MS = 15 * 60 * 1000
57
57
 
58
+ // コンテキスト窓サイズ (トークン)。Opus/Sonnet 4.x は 200k が標準。
59
+ // 1M ベータ等を使う場合は HUB_CONTEXT_WINDOW で上書き。
60
+ const CONTEXT_WINDOW = Number(process.env.HUB_CONTEXT_WINDOW) || 200000
61
+ // チャットモード(SDK)の context% 推定で参照する jsonl の鮮度窓 (直近 N 分)。
62
+ const CONTEXT_JSONL_RECENT_MS = 30 * 60 * 1000
63
+
58
64
  const PLAN_LIMITS = {
59
65
  pro: { msg5h: 45, msg7d: 315 },
60
66
  max_5x: { msg5h: 280, msg7d: 1960 },
@@ -230,15 +236,104 @@ async function readEstimate(now) {
230
236
  }
231
237
  }
232
238
 
239
+ /** statusLine cache ファイルの mtime (ms)。存在しなければ 0。 */
240
+ async function statuslineCacheMtime() {
241
+ try {
242
+ return (await fs.stat(statuslineCache())).mtimeMs
243
+ } catch {
244
+ return null
245
+ }
246
+ }
247
+
248
+ /**
249
+ * 直近にアクティブな session jsonl の最後の assistant.usage から context% を
250
+ * 推定する。チャットモード(SDK headless)は statusLine を書き出さないため、
251
+ * ドーナツ(usage.context)が固まるのを防ぐフォールバック。
252
+ *
253
+ * context トークン = input + cache_read + cache_creation (+ 直近応答の output)。
254
+ * プロンプトキャッシュ有効時は cache_creation / cache_read に大半が乗るため、
255
+ * input_tokens だけだと大幅に過小評価になる点に注意 (3 種を必ず合算する)。
256
+ *
257
+ * @returns {Promise<{ percent: number, mtimeMs: number } | null>}
258
+ */
259
+ async function latestJsonlContext(now) {
260
+ const projects = await fs.readdir(projectsDir()).catch(() => null)
261
+ if (!projects) return null
262
+ const recent = now - CONTEXT_JSONL_RECENT_MS
263
+ let best = null // { mtimeMs, fp }
264
+ await Promise.all(
265
+ projects.map(async (p) => {
266
+ const dir = path.join(projectsDir(), p)
267
+ const files = await fs.readdir(dir).catch(() => [])
268
+ for (const f of files) {
269
+ if (!f.endsWith(".jsonl")) continue
270
+ const fp = path.join(dir, f)
271
+ try {
272
+ const st = await fs.stat(fp)
273
+ if (st.mtimeMs < recent) continue
274
+ if (!best || st.mtimeMs > best.mtimeMs) best = { mtimeMs: st.mtimeMs, fp }
275
+ } catch {
276
+ /* ignore */
277
+ }
278
+ }
279
+ }),
280
+ )
281
+ if (!best) return null
282
+ const text = await readOrNull(best.fp)
283
+ if (!text) return null
284
+ const lines = text.split("\n")
285
+ // 末尾から最初に見つかった assistant.usage を採用 (= 現在の文脈サイズ)
286
+ for (let i = lines.length - 1; i >= 0; i--) {
287
+ const line = lines[i]
288
+ if (!line || !line.includes('"usage"')) continue
289
+ let d
290
+ try {
291
+ d = JSON.parse(line)
292
+ } catch {
293
+ continue
294
+ }
295
+ if (d.type !== "assistant") continue
296
+ const u = d.message?.usage
297
+ if (!u) continue
298
+ const tokens =
299
+ (u.input_tokens || 0) +
300
+ (u.cache_read_input_tokens || 0) +
301
+ (u.cache_creation_input_tokens || 0) +
302
+ (u.output_tokens || 0)
303
+ if (tokens <= 0) continue
304
+ const percent = Math.min(100, Math.round((tokens / CONTEXT_WINDOW) * 1000) / 10)
305
+ return { percent, mtimeMs: best.mtimeMs }
306
+ }
307
+ return null
308
+ }
309
+
233
310
  /**
234
311
  * 5h / 7d 集計の UsageStats を返す。statusLine が無い環境では transcript
235
312
  * から推定する。
313
+ *
314
+ * context%: statusLine 値が最新 jsonl より新しければ official を優先。
315
+ * 古い / 無い (= チャットモードで statusLine 未更新) 場合は jsonl 推定で上書き。
236
316
  */
237
317
  export async function getUsage() {
238
318
  const now = Date.now()
239
319
  const official = await readOfficial(now)
240
- if (official) return official
241
- return readEstimate(now)
320
+ const result = official || (await readEstimate(now))
321
+
322
+ const est = await latestJsonlContext(now)
323
+ if (est) {
324
+ const cacheMtime = await statuslineCacheMtime()
325
+ // statusLine が jsonl と同程度以上に新しければ official.context が信頼できる
326
+ // (ターミナルモード)。jsonl の方が新しい (チャットモード) なら推定で上書き。
327
+ const officialFresh =
328
+ official &&
329
+ typeof official.context === "number" &&
330
+ cacheMtime !== null &&
331
+ cacheMtime >= est.mtimeMs - 5000
332
+ if (!officialFresh) {
333
+ result.context = est.percent
334
+ }
335
+ }
336
+ return result
242
337
  }
243
338
 
244
339
  /**