tailii-host 0.5.0 → 0.6.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.
Files changed (78) hide show
  1. package/dist/approval/hook.js +1 -1
  2. package/dist/approval/hook.js.map +1 -1
  3. package/dist/backend/herdr.d.ts +19 -0
  4. package/dist/backend/herdr.js +70 -13
  5. package/dist/backend/herdr.js.map +1 -1
  6. package/dist/backend/sessionBackend.d.ts +12 -0
  7. package/dist/backend/sessionBackend.js +6 -0
  8. package/dist/backend/sessionBackend.js.map +1 -1
  9. package/dist/backend/tmux.d.ts +152 -2
  10. package/dist/backend/tmux.js +477 -12
  11. package/dist/backend/tmux.js.map +1 -1
  12. package/dist/chat/chatTailController.d.ts +3 -1
  13. package/dist/chat/chatTailController.js +3 -0
  14. package/dist/chat/chatTailController.js.map +1 -1
  15. package/dist/chat/subagentTailer.d.ts +10 -0
  16. package/dist/chat/subagentTailer.js +215 -51
  17. package/dist/chat/subagentTailer.js.map +1 -1
  18. package/dist/chat/subagentTranscript.js +51 -5
  19. package/dist/chat/subagentTranscript.js.map +1 -1
  20. package/dist/chat/transcriptTailer.d.ts +28 -1
  21. package/dist/chat/transcriptTailer.js +115 -2
  22. package/dist/chat/transcriptTailer.js.map +1 -1
  23. package/dist/codex/codexNativeTurnController.js +20 -4
  24. package/dist/codex/codexNativeTurnController.js.map +1 -1
  25. package/dist/codex/codexRolloutTailer.d.ts +1 -0
  26. package/dist/codex/codexRolloutTailer.js +7 -0
  27. package/dist/codex/codexRolloutTailer.js.map +1 -1
  28. package/dist/codex/codexSystemNotice.d.ts +16 -0
  29. package/dist/codex/codexSystemNotice.js +195 -0
  30. package/dist/codex/codexSystemNotice.js.map +1 -0
  31. package/dist/engine/handlers/accountUsage.d.ts +17 -0
  32. package/dist/engine/handlers/accountUsage.js +40 -6
  33. package/dist/engine/handlers/accountUsage.js.map +1 -1
  34. package/dist/engine/handlers/mode.js +42 -1
  35. package/dist/engine/handlers/mode.js.map +1 -1
  36. package/dist/engine/handlers/usage.js +4 -1
  37. package/dist/engine/handlers/usage.js.map +1 -1
  38. package/dist/hub/engineRelaySocket.d.ts +3 -0
  39. package/dist/hub/engineRelaySocket.js +2 -1
  40. package/dist/hub/engineRelaySocket.js.map +1 -1
  41. package/dist/hub/hubDaemon.js +8 -2
  42. package/dist/hub/hubDaemon.js.map +1 -1
  43. package/dist/hub/hubProtocol.js +8 -2
  44. package/dist/hub/hubProtocol.js.map +1 -1
  45. package/dist/hub/panePreviewPump.d.ts +27 -0
  46. package/dist/hub/panePreviewPump.js +62 -1
  47. package/dist/hub/panePreviewPump.js.map +1 -1
  48. package/dist/hub/sessionHub.d.ts +48 -1
  49. package/dist/hub/sessionHub.js +165 -14
  50. package/dist/hub/sessionHub.js.map +1 -1
  51. package/dist/protocol/decode.js +14 -0
  52. package/dist/protocol/decode.js.map +1 -1
  53. package/dist/protocol/messages.d.ts +28 -0
  54. package/dist/services/accountIdentity.js +3 -1
  55. package/dist/services/accountIdentity.js.map +1 -1
  56. package/dist/services/officialApps.d.ts +9 -0
  57. package/dist/services/officialApps.js +56 -23
  58. package/dist/services/officialApps.js.map +1 -1
  59. package/dist/services/planUsageFetcher.d.ts +35 -3
  60. package/dist/services/planUsageFetcher.js +34 -6
  61. package/dist/services/planUsageFetcher.js.map +1 -1
  62. package/dist/sessions/claudeSessionStore.js +30 -0
  63. package/dist/sessions/claudeSessionStore.js.map +1 -1
  64. package/dist/sessions/heartbeat.d.ts +7 -1
  65. package/dist/sessions/heartbeat.js +3 -1
  66. package/dist/sessions/heartbeat.js.map +1 -1
  67. package/dist/sessions/sessionSearch.js +23 -5
  68. package/dist/sessions/sessionSearch.js.map +1 -1
  69. package/dist/shared/crossSession.d.ts +15 -0
  70. package/dist/shared/crossSession.js +75 -0
  71. package/dist/shared/crossSession.js.map +1 -0
  72. package/dist/shared/harnessReminder.d.ts +32 -0
  73. package/dist/shared/harnessReminder.js +124 -0
  74. package/dist/shared/harnessReminder.js.map +1 -0
  75. package/dist/shared/systemNotice.d.ts +30 -0
  76. package/dist/shared/systemNotice.js +209 -0
  77. package/dist/shared/systemNotice.js.map +1 -0
  78. package/package.json +3 -3
@@ -2,12 +2,14 @@
2
2
  // tailii (TS host) — connection 非依存 Session Hub コア。
3
3
  import { reaperTick } from "./reaper.js";
4
4
  import * as fs from "node:fs";
5
+ import * as os from "node:os";
5
6
  import * as path from "node:path";
6
7
  import { bumpHeartbeat, listHeartbeatSessions, readHeartbeat, writeHeartbeat } from "../sessions/heartbeat.js";
7
- import { ensureDirectory0700 } from "../shared/paths.js";
8
+ import { claudeProjectSlug, ensureDirectory0700 } from "../shared/paths.js";
8
9
  import { decodeHubClientLine, encodeHubMessage, } from "./hubProtocol.js";
9
- import { HISTORY_DONE_STREAM_ID } from "../chat/transcriptTailer.js";
10
+ import { HISTORY_DONE_STREAM_ID, findTrailingInterruptMarkerMs, } from "../chat/transcriptTailer.js";
10
11
  import { PROTOCOL_V1, PROTOCOL_V2 } from "../protocol.js";
12
+ import { LoginCodeError } from "../backend/tmux.js";
11
13
  import { CodexAppServerManager } from "../codex/codexAppServer.js";
12
14
  import { CodexNativeTurnController, chatContentKey, } from "../codex/codexNativeTurnController.js";
13
15
  import { CONTEXT_STREAM_ID as CODEX_CONTEXT_STREAM_ID, CONTEXT_WINDOW_STREAM_ID as CODEX_CONTEXT_WINDOW_STREAM_ID, MODEL_STREAM_ID as CODEX_MODEL_STREAM_ID, } from "../codex/codexRolloutTailer.js";
@@ -20,6 +22,20 @@ import { CONTEXT_STREAM_ID as CODEX_CONTEXT_STREAM_ID, CONTEXT_WINDOW_STREAM_ID
20
22
  const BACKFILL_STALL_TIMEOUT_MS = 15_000;
21
23
  const DELIVERED_RECEIPT_TTL_MS = 30 * 24 * 60 * 60 * 1_000;
22
24
  const MAX_DELIVERED_RECEIPTS_PER_SESSION = 10_000;
25
+ /** 中断マーカーで done にした後、継続 hook(Pre/PostToolUse)の遅着 active を残響として無視する窓(ms)。 */
26
+ const LATE_HOOK_AFTER_INTERRUPT_MS = 3_000;
27
+ /** ターンを始めない継続 hook か(新ターンの権威は UserPromptSubmit のみ)。 */
28
+ function isContinuationHookEvent(event) {
29
+ return event === "PreToolUse" || event === "PostToolUse";
30
+ }
31
+ /** 既定の claude transcript 解決(`~/.claude/projects/<slug>/<sessionId>.jsonl`)。ID 未記録は null。 */
32
+ function defaultTranscriptPathFor(meta) {
33
+ // 他の tail open と同じ優先順(providerSessionId → claudeSessionId)。別会話を照合しない。
34
+ const sessionId = meta.providerSessionId ?? meta.claudeSessionId;
35
+ if (sessionId === undefined || sessionId.length === 0)
36
+ return null;
37
+ return path.join(os.homedir(), ".claude", "projects", claudeProjectSlug(meta.cwd), `${sessionId}.jsonl`);
38
+ }
23
39
  export class SessionHub {
24
40
  options;
25
41
  clients = new Map();
@@ -27,6 +43,7 @@ export class SessionHub {
27
43
  previewWatchers = new Set();
28
44
  actors = new Map();
29
45
  now;
46
+ nowMs;
30
47
  replayLimit;
31
48
  injectionsInFlight = 0;
32
49
  codexStartsInFlight = 0;
@@ -37,6 +54,7 @@ export class SessionHub {
37
54
  constructor(options) {
38
55
  this.options = options;
39
56
  this.now = options.now ?? (() => Math.floor(Date.now() / 1000));
57
+ this.nowMs = options.nowMs ?? (() => Date.now());
40
58
  this.replayLimit = options.replayLimit ?? 500;
41
59
  }
42
60
  get clientCount() { return this.clients.size; }
@@ -68,9 +86,51 @@ export class SessionHub {
68
86
  // (稼働中の hub は毎 tick bump しているので、直前まで生きていた heartbeat は必ず新しい)。
69
87
  if (this.now() - heartbeat.ts >= this.options.timeoutSeconds)
70
88
  continue;
71
- this.actor(session).processingSince = heartbeat.ts;
89
+ // 再起動前に利用者が中断して放置した会話は Stop hook が無く active のまま残る。engine の
90
+ // 再接続購読は newerThanMs 付きで履歴のマーカーを流さないため、tail 経由では二度と
91
+ // 観測できない。transcript 末尾を直接照合し、最後の発話が開始以降の中断マーカーなら
92
+ // 処理中に戻さず idle へ確定する。
93
+ const trailingInterruptMs = this.trailingInterruptMarkerMs(session);
94
+ if (trailingInterruptMs !== null && (heartbeat.sinceMs === undefined || trailingInterruptMs >= heartbeat.sinceMs)) {
95
+ // 再起動中に hook が新ターンの active を書いた直後なら上書きしない(読んだ内容と同じときだけ倒す)。
96
+ const latest = readHeartbeat(this.options.heartbeatDir, session);
97
+ const unchanged = latest !== null && latest.ts === heartbeat.ts && latest.state === heartbeat.state &&
98
+ latest.event === heartbeat.event && latest.sinceMs === heartbeat.sinceMs;
99
+ if (!unchanged) {
100
+ // 消えていた(kill 後の掃除)場合も再生成しない。
101
+ this.options.log?.(`restore: heartbeat が更新されたため中断判定を見送る session=${session}`);
102
+ }
103
+ else {
104
+ try {
105
+ writeHeartbeat(this.options.heartbeatDir, session, { ts: this.now(), state: "idle", event: "restore-interrupted" });
106
+ }
107
+ catch (error) {
108
+ this.options.log?.(`heartbeat 書込失敗: ${String(error)}`);
109
+ }
110
+ this.options.log?.(`restore: 中断済みのため処理中を復元しない session=${session}`);
111
+ continue;
112
+ }
113
+ }
114
+ const actor = this.actor(session);
115
+ actor.processingSince = heartbeat.ts;
116
+ // 真の開始時刻は heartbeat の sinceMs(applyProcessing が書き、bump が保持する)。ts は
117
+ // 毎 tick bump されるので使えない。無ければ(hook 直書きの heartbeat・旧形式)復元時刻を
118
+ // 境界にする: 再起動前の中断は上の transcript 照合が担い、再起動後の中断は必ずこれより
119
+ // 新しい。null(全採用)にすると、開き直しの全履歴再生で流れる過去ターンのマーカーが
120
+ // 進行中ターンを落とす。
121
+ actor.processingSinceMs = heartbeat.sinceMs ?? this.nowMs();
72
122
  }
73
123
  }
124
+ /** 復元時の照合用: transcript 末尾の中断マーカー timestamp(claude 会話のみ。不明は null)。 */
125
+ trailingInterruptMarkerMs(session) {
126
+ const meta = this.options.metadataStore.get(session);
127
+ if (meta === null || meta.agent === "codex")
128
+ return null;
129
+ const transcriptPath = (this.options.transcriptPathFor ?? defaultTranscriptPathFor)(meta);
130
+ if (transcriptPath === null)
131
+ return null;
132
+ return findTrailingInterruptMarkerMs(transcriptPath);
133
+ }
74
134
  /** 永続化済み設問を復元する。App Server の request handle は再起動を越せないため TUI のみ対象。 */
75
135
  restorePendingQuestions() {
76
136
  const restored = this.readPendingQuestions();
@@ -207,8 +267,10 @@ export class SessionHub {
207
267
  if (message.event === "dismiss")
208
268
  void this.drainChatQueue(message.session, actor);
209
269
  }
210
- else if (message.type === "session_processing")
211
- this.applyProcessing(message.session, message.state);
270
+ else if (message.type === "session_processing") {
271
+ if (!this.applyProcessing(message.session, message.state, message.event))
272
+ return;
273
+ }
212
274
  this.broadcast(message);
213
275
  }
214
276
  handleClientMessage(client, line) {
@@ -553,7 +615,8 @@ export class SessionHub {
553
615
  actor.runtimeClaim = null;
554
616
  return;
555
617
  }
556
- this.applyProcessing(message.session, message.state);
618
+ if (!this.applyProcessing(message.session, message.state, message.event))
619
+ return;
557
620
  this.broadcast(message);
558
621
  }
559
622
  async tick() {
@@ -699,6 +762,10 @@ export class SessionHub {
699
762
  else {
700
763
  this.syncPreview(session, actor);
701
764
  }
765
+ // 会話を開き直したとき(pump は一覧 watch で稼働中)、静止した入力待ちダイアログの
766
+ // フレームは変化しないので再送しないと転写カードが出ない。
767
+ if (preview && !wasPreview)
768
+ actor.previewPump?.resendLastIfInteractive?.();
702
769
  // preview=false 中に engine が route できなかった image/subagent event を、同じ
703
770
  // subscriber の前面昇格時にも afterSeq から回収する。既存購読だからと no-op にしない。
704
771
  if (!existing.backfilling && afterSeq !== undefined) {
@@ -723,6 +790,8 @@ export class SessionHub {
723
790
  }
724
791
  // 初回 backfill が同期的に多数の行を生成する前に pane capture を開始する。
725
792
  this.syncPreview(session, actor);
793
+ if (preview)
794
+ actor.previewPump?.resendLastIfInteractive?.();
726
795
  if (first) {
727
796
  this.startSharedTail(session, actor, newerThanMs ?? null);
728
797
  // processing 完了で一度 unsubscribe された後も、actor の replay buffer が残る間は
@@ -798,7 +867,7 @@ export class SessionHub {
798
867
  return;
799
868
  const tail = this.options.tailFactory((payload) => {
800
869
  this.publishConversationEvent(session, actor, payload);
801
- });
870
+ }, undefined, (event) => this.handleClaudeTurnLifecycle(session, actor, event));
802
871
  actor.tail = tail;
803
872
  tail.open(meta.cwd, meta.providerSessionId ?? meta.claudeSessionId ?? null, newerThanMs, meta.agent ?? "claude");
804
873
  }
@@ -1220,7 +1289,8 @@ export class SessionHub {
1220
1289
  actor(session) {
1221
1290
  let actor = this.actors.get(session);
1222
1291
  if (actor === undefined) {
1223
- actor = { pendingQuestion: null, processingSince: null, focusedBy: new Set(), subscribers: new Map(),
1292
+ actor = { pendingQuestion: null, processingSince: null, processingSinceMs: null, lastInterruptDoneMs: null,
1293
+ focusedBy: new Set(), subscribers: new Map(),
1224
1294
  nextServerSeq: 1, replayBuffer: [], tail: null, tailRetryTimer: null,
1225
1295
  previewPump: null, backfillTails: new Map(),
1226
1296
  seenClientMessageIds: new Set(), deliveredChatMessageIds: new Map(),
@@ -1428,14 +1498,25 @@ export class SessionHub {
1428
1498
  continue;
1429
1499
  actor.injectingChatMessageIds.delete(message.clientMessageId);
1430
1500
  actor.pendingChatMessages.delete(message.clientMessageId);
1431
- actor.uncertainChatMessages.set(message.clientMessageId, message);
1501
+ // `/login` 中の門番(LoginCodeError)は 1 キーも送る前の確定拒否 = 非配達が確定している。
1502
+ // uncertain(配送不明)に積むと削除不能・後続ブロックのゾンビになるので、失敗として
1503
+ // そのまま片付ける。それ以外の注入失敗は従来どおり配送不明として明示再送に倒す。
1504
+ const rejectedBeforeSend = error instanceof LoginCodeError;
1505
+ if (rejectedBeforeSend) {
1506
+ removeOrderedID(actor.chatOrder, message.clientMessageId);
1507
+ }
1508
+ else {
1509
+ actor.uncertainChatMessages.set(message.clientMessageId, message);
1510
+ }
1432
1511
  this.persistChatReceipts();
1512
+ // 利用者向け文言だけを出す(`String(error)` は `LoginCodeError: …` と型名が前置される)。
1513
+ const userText = rejectedBeforeSend && error instanceof Error ? error.message : String(error);
1433
1514
  for (const waiter of entry.waiters) {
1434
1515
  this.sendTo(waiter.client, {
1435
- type: "chat_send_result", id: waiter.id, status: "failed", error: String(error),
1516
+ type: "chat_send_result", id: waiter.id, status: "failed", error: userText,
1436
1517
  });
1437
1518
  }
1438
- this.publishCodexMarker(session, `chat-send-error-${message.id}`, `⚠️ メッセージ送信失敗: ${String(error)}`);
1519
+ this.publishCodexMarker(session, `chat-send-error-${message.id}`, `⚠️ メッセージ送信失敗: ${userText}`);
1439
1520
  this.options.log?.(`chat 注入失敗 session=${session}: ${String(error)}`);
1440
1521
  }
1441
1522
  finally {
@@ -1600,14 +1681,83 @@ export class SessionHub {
1600
1681
  type: "chat_output", v: PROTOCOL_V1, streamId, role: "system", text, eof: true,
1601
1682
  });
1602
1683
  }
1603
- applyProcessing(session, state) {
1684
+ /**
1685
+ * transcript の中断確定マーカーで処理完了を補完する。Claude Code の Stop hook は利用者の中断
1686
+ * (Esc / Ctrl-C)では発火しないため、hook だけでは処理中状態がターン終了後も残り、iOS は
1687
+ * 会話を開き直す・再接続するたびに停止ボタン/処理中表示を張り直してしまう(実機 09-02)。
1688
+ * 共有 tail は購読の張り直しで履歴から再生されるため、マーカーの timestamp が現ターンの
1689
+ * 処理開始時刻以降のものだけを採用する(過去ターンのマーカーで進行中ターンを落とさない)。
1690
+ *
1691
+ * 時刻の比較根拠: `processingSinceMs` は UserPromptSubmit hook を hub が受信した時刻(ターン
1692
+ * 開始。継続 hook では進めない)。中断→即再送信(実測 10〜200ms 後)でも、新ターンの hook
1693
+ * 受信は必ずマーカー書込より後(同一マシンの時計・因果順)なので、マーカーは新ターンの開始
1694
+ * より古く見えて棄却される。tail がマーカーを hook より先に届けた場合は前ターンを done に
1695
+ * し、直後の UserPromptSubmit で active に戻る。中断直後に遅着する Pre/PostToolUse の active
1696
+ * は `applyProcessing` が残響として無視する。
1697
+ *
1698
+ * 副作用は hook の Stop と同じ `applyProcessing("done")` 一式(heartbeat idle。設問提示中なら
1699
+ * その dismiss と chat queue の drain)。中断はターン終了なので Stop 後と同じ振る舞い。
1700
+ */
1701
+ handleClaudeTurnLifecycle(session, actor, event) {
1702
+ if (event.kind !== "interrupted")
1703
+ return;
1704
+ if (this.actors.get(session) !== actor)
1705
+ return;
1706
+ if (actor.processingSince === null)
1707
+ return;
1708
+ if (this.options.metadataStore.get(session)?.agent === "codex")
1709
+ return;
1710
+ if (actor.processingSinceMs !== null && event.atMs < actor.processingSinceMs)
1711
+ return;
1712
+ this.options.log?.(`interrupt marker で処理完了を補完 session=${session}`);
1713
+ actor.lastInterruptDoneMs = this.nowMs();
1714
+ this.applyProcessing(session, "done");
1715
+ this.broadcast({ type: "session_processing", session, state: "done" });
1716
+ }
1717
+ /**
1718
+ * 処理中状態を反映する。戻り値 false は「中断済みターンの残響として無視した」(呼び手は
1719
+ * broadcast しない)。`event` は hook 名(relay 由来。codex controller / 旧 hook は undefined)。
1720
+ */
1721
+ applyProcessing(session, state, event) {
1604
1722
  const actor = this.actor(session);
1605
- actor.processingSince = state === "active" ? this.now() : null;
1723
+ if (state === "active") {
1724
+ // 中断直後に遅着する継続 hook(Pre/PostToolUse)は中断済みターンの残響。hook は別プロセス
1725
+ // 起動+relay で 100〜300ms 遅れるため、マーカー書込より後に届き得る。採用すると Stop hook の
1726
+ // 無いターンが永久に処理中へ戻る(停止ボタン再点灯)。新ターンの開始は UserPromptSubmit
1727
+ // だけが権威(中断→即再送信は通常どおり active)。
1728
+ if (isContinuationHookEvent(event) && actor.processingSince === null && actor.lastInterruptDoneMs !== null &&
1729
+ this.nowMs() - actor.lastInterruptDoneMs < LATE_HOOK_AFTER_INTERRUPT_MS) {
1730
+ this.options.log?.(`audit late-hook-after-interrupt ignored session=${session} event=${event}`);
1731
+ // hook が直書きした active の heartbeat も戻す(reaper の bump 代行で不死化させない)。
1732
+ // ただし heartbeat がその hook の書込のままのときだけ。別の書込(新ターンの
1733
+ // UserPromptSubmit 等)に置き換わっていれば触らない(生きたターンの reaper 保護を剥がさない)。
1734
+ try {
1735
+ const latest = readHeartbeat(this.options.heartbeatDir, session);
1736
+ if (latest !== null && latest.state === "active" && latest.event === event) {
1737
+ writeHeartbeat(this.options.heartbeatDir, session, { ts: this.now(), state: "idle", event: "late-hook-after-interrupt" });
1738
+ }
1739
+ }
1740
+ catch (error) {
1741
+ this.options.log?.(`heartbeat 書込失敗: ${String(error)}`);
1742
+ }
1743
+ return false;
1744
+ }
1745
+ actor.processingSince = this.now();
1746
+ // ターン開始は UserPromptSubmit で確定し、継続 hook では進めない(未確定なら今)。
1747
+ actor.processingSinceMs =
1748
+ event === "UserPromptSubmit" || actor.processingSinceMs === null ? this.nowMs() : actor.processingSinceMs;
1749
+ }
1750
+ else {
1751
+ actor.processingSince = null;
1752
+ actor.processingSinceMs = null;
1753
+ }
1606
1754
  // 一覧 watch 中は処理開始/完了で pump を起動/停止する(前面購読とは独立)。
1607
1755
  this.syncPreview(session, actor);
1608
1756
  try {
1609
1757
  writeHeartbeat(this.options.heartbeatDir, session, { ts: this.now(), state: state === "active" ? "active" : "idle",
1610
- event: state === "active" ? "hub-processing" : "hub-processing-done" });
1758
+ event: state === "active" ? "hub-processing" : "hub-processing-done",
1759
+ // 再起動後の中断マーカー照合用に開始時刻を残す(bump は保持する)。
1760
+ ...(actor.processingSinceMs !== null ? { sinceMs: actor.processingSinceMs } : {}) });
1611
1761
  }
1612
1762
  catch (error) {
1613
1763
  this.options.log?.(`heartbeat 書込失敗: ${String(error)}`);
@@ -1618,6 +1768,7 @@ export class SessionHub {
1618
1768
  this.broadcast({ type: "question_event", session, event: "dismiss", id });
1619
1769
  void this.drainChatQueue(session, actor);
1620
1770
  }
1771
+ return true;
1621
1772
  }
1622
1773
  bumpSafe(session, event, fallbackState = "idle") {
1623
1774
  try {