@vibefield/puppeteer-adapter-claude 0.0.0-stage → 0.2.1

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 (215) hide show
  1. package/LICENSE +21 -0
  2. package/dist/detection.d.ts +78 -0
  3. package/dist/detection.d.ts.map +1 -0
  4. package/dist/detection.js +167 -0
  5. package/dist/detection.js.map +1 -0
  6. package/dist/driver.d.ts +145 -0
  7. package/dist/driver.d.ts.map +1 -0
  8. package/dist/driver.js +840 -0
  9. package/dist/driver.js.map +1 -0
  10. package/dist/generated/detection-surface.d.ts +30 -0
  11. package/dist/generated/detection-surface.d.ts.map +1 -0
  12. package/dist/generated/detection-surface.js +34 -0
  13. package/dist/generated/detection-surface.js.map +1 -0
  14. package/dist/generated/registry.d.ts +45 -0
  15. package/dist/generated/registry.d.ts.map +1 -0
  16. package/dist/generated/registry.js +287 -0
  17. package/dist/generated/registry.js.map +1 -0
  18. package/dist/index.d.ts +27 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +27 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/launch/hook-switches.d.ts +32 -0
  23. package/dist/launch/hook-switches.d.ts.map +1 -0
  24. package/dist/launch/hook-switches.js +56 -0
  25. package/dist/launch/hook-switches.js.map +1 -0
  26. package/dist/launch/invocation-grammar.d.ts +196 -0
  27. package/dist/launch/invocation-grammar.d.ts.map +1 -0
  28. package/dist/launch/invocation-grammar.js +857 -0
  29. package/dist/launch/invocation-grammar.js.map +1 -0
  30. package/dist/launch/native-invocation.d.ts +42 -0
  31. package/dist/launch/native-invocation.d.ts.map +1 -0
  32. package/dist/launch/native-invocation.js +130 -0
  33. package/dist/launch/native-invocation.js.map +1 -0
  34. package/dist/launch/prepare.d.ts +137 -0
  35. package/dist/launch/prepare.d.ts.map +1 -0
  36. package/dist/launch/prepare.js +317 -0
  37. package/dist/launch/prepare.js.map +1 -0
  38. package/dist/launch/settings.d.ts +63 -0
  39. package/dist/launch/settings.d.ts.map +1 -0
  40. package/dist/launch/settings.js +94 -0
  41. package/dist/launch/settings.js.map +1 -0
  42. package/dist/normalization/adapter.d.ts +3 -0
  43. package/dist/normalization/adapter.d.ts.map +1 -0
  44. package/dist/normalization/adapter.js +4 -0
  45. package/dist/normalization/adapter.js.map +1 -0
  46. package/dist/normalization/compaction.d.ts +4 -0
  47. package/dist/normalization/compaction.d.ts.map +1 -0
  48. package/dist/normalization/compaction.js +7 -0
  49. package/dist/normalization/compaction.js.map +1 -0
  50. package/dist/normalization/context-window.d.ts +3 -0
  51. package/dist/normalization/context-window.d.ts.map +1 -0
  52. package/dist/normalization/context-window.js +4 -0
  53. package/dist/normalization/context-window.js.map +1 -0
  54. package/dist/normalization/conversation.d.ts +3 -0
  55. package/dist/normalization/conversation.d.ts.map +1 -0
  56. package/dist/normalization/conversation.js +4 -0
  57. package/dist/normalization/conversation.js.map +1 -0
  58. package/dist/normalization/delegation.d.ts +4 -0
  59. package/dist/normalization/delegation.d.ts.map +1 -0
  60. package/dist/normalization/delegation.js +7 -0
  61. package/dist/normalization/delegation.js.map +1 -0
  62. package/dist/normalization/effort.d.ts +8 -0
  63. package/dist/normalization/effort.d.ts.map +1 -0
  64. package/dist/normalization/effort.js +16 -0
  65. package/dist/normalization/effort.js.map +1 -0
  66. package/dist/normalization/environment.d.ts +5 -0
  67. package/dist/normalization/environment.d.ts.map +1 -0
  68. package/dist/normalization/environment.js +10 -0
  69. package/dist/normalization/environment.js.map +1 -0
  70. package/dist/normalization/index.d.ts +20 -0
  71. package/dist/normalization/index.d.ts.map +1 -0
  72. package/dist/normalization/index.js +20 -0
  73. package/dist/normalization/index.js.map +1 -0
  74. package/dist/normalization/interaction.d.ts +38 -0
  75. package/dist/normalization/interaction.d.ts.map +1 -0
  76. package/dist/normalization/interaction.js +60 -0
  77. package/dist/normalization/interaction.js.map +1 -0
  78. package/dist/normalization/mode.d.ts +11 -0
  79. package/dist/normalization/mode.d.ts.map +1 -0
  80. package/dist/normalization/mode.js +37 -0
  81. package/dist/normalization/mode.js.map +1 -0
  82. package/dist/normalization/model.d.ts +5 -0
  83. package/dist/normalization/model.d.ts.map +1 -0
  84. package/dist/normalization/model.js +7 -0
  85. package/dist/normalization/model.js.map +1 -0
  86. package/dist/normalization/monitor-capabilities.d.ts +4 -0
  87. package/dist/normalization/monitor-capabilities.d.ts.map +1 -0
  88. package/dist/normalization/monitor-capabilities.js +121 -0
  89. package/dist/normalization/monitor-capabilities.js.map +1 -0
  90. package/dist/normalization/monitor.d.ts +46 -0
  91. package/dist/normalization/monitor.d.ts.map +1 -0
  92. package/dist/normalization/monitor.js +332 -0
  93. package/dist/normalization/monitor.js.map +1 -0
  94. package/dist/normalization/notification.d.ts +4 -0
  95. package/dist/normalization/notification.d.ts.map +1 -0
  96. package/dist/normalization/notification.js +9 -0
  97. package/dist/normalization/notification.js.map +1 -0
  98. package/dist/normalization/pipeline.d.ts +56 -0
  99. package/dist/normalization/pipeline.d.ts.map +1 -0
  100. package/dist/normalization/pipeline.js +472 -0
  101. package/dist/normalization/pipeline.js.map +1 -0
  102. package/dist/normalization/session.d.ts +6 -0
  103. package/dist/normalization/session.d.ts.map +1 -0
  104. package/dist/normalization/session.js +17 -0
  105. package/dist/normalization/session.js.map +1 -0
  106. package/dist/normalization/tool.d.ts +8 -0
  107. package/dist/normalization/tool.d.ts.map +1 -0
  108. package/dist/normalization/tool.js +64 -0
  109. package/dist/normalization/tool.js.map +1 -0
  110. package/dist/normalization/turn.d.ts +6 -0
  111. package/dist/normalization/turn.d.ts.map +1 -0
  112. package/dist/normalization/turn.js +15 -0
  113. package/dist/normalization/turn.js.map +1 -0
  114. package/dist/normalization/types.d.ts +47 -0
  115. package/dist/normalization/types.d.ts.map +1 -0
  116. package/dist/normalization/types.js +2 -0
  117. package/dist/normalization/types.js.map +1 -0
  118. package/dist/normalization/wire.d.ts +10 -0
  119. package/dist/normalization/wire.d.ts.map +1 -0
  120. package/dist/normalization/wire.js +75 -0
  121. package/dist/normalization/wire.js.map +1 -0
  122. package/dist/normalization/workspace.d.ts +5 -0
  123. package/dist/normalization/workspace.d.ts.map +1 -0
  124. package/dist/normalization/workspace.js +68 -0
  125. package/dist/normalization/workspace.js.map +1 -0
  126. package/dist/observation/hook-bridge.d.ts +72 -0
  127. package/dist/observation/hook-bridge.d.ts.map +1 -0
  128. package/dist/observation/hook-bridge.js +250 -0
  129. package/dist/observation/hook-bridge.js.map +1 -0
  130. package/dist/observation/otel/actor.d.ts +14 -0
  131. package/dist/observation/otel/actor.d.ts.map +1 -0
  132. package/dist/observation/otel/actor.js +44 -0
  133. package/dist/observation/otel/actor.js.map +1 -0
  134. package/dist/observation/otel/capability.d.ts +4 -0
  135. package/dist/observation/otel/capability.d.ts.map +1 -0
  136. package/dist/observation/otel/capability.js +24 -0
  137. package/dist/observation/otel/capability.js.map +1 -0
  138. package/dist/observation/otel/index.d.ts +6 -0
  139. package/dist/observation/otel/index.d.ts.map +1 -0
  140. package/dist/observation/otel/index.js +6 -0
  141. package/dist/observation/otel/index.js.map +1 -0
  142. package/dist/observation/otel/model.d.ts +9 -0
  143. package/dist/observation/otel/model.d.ts.map +1 -0
  144. package/dist/observation/otel/model.js +16 -0
  145. package/dist/observation/otel/model.js.map +1 -0
  146. package/dist/observation/otel/usage.d.ts +16 -0
  147. package/dist/observation/otel/usage.d.ts.map +1 -0
  148. package/dist/observation/otel/usage.js +75 -0
  149. package/dist/observation/otel/usage.js.map +1 -0
  150. package/dist/observation/otel/wire.d.ts +15 -0
  151. package/dist/observation/otel/wire.d.ts.map +1 -0
  152. package/dist/observation/otel/wire.js +147 -0
  153. package/dist/observation/otel/wire.js.map +1 -0
  154. package/dist/observation/semantic-provider.d.ts +45 -0
  155. package/dist/observation/semantic-provider.d.ts.map +1 -0
  156. package/dist/observation/semantic-provider.js +8 -0
  157. package/dist/observation/semantic-provider.js.map +1 -0
  158. package/dist/observation/status-channel.d.ts +70 -0
  159. package/dist/observation/status-channel.d.ts.map +1 -0
  160. package/dist/observation/status-channel.js +268 -0
  161. package/dist/observation/status-channel.js.map +1 -0
  162. package/dist/observation/transcript/conversation.d.ts +6 -0
  163. package/dist/observation/transcript/conversation.d.ts.map +1 -0
  164. package/dist/observation/transcript/conversation.js +170 -0
  165. package/dist/observation/transcript/conversation.js.map +1 -0
  166. package/dist/observation/transcript/index.d.ts +5 -0
  167. package/dist/observation/transcript/index.d.ts.map +1 -0
  168. package/dist/observation/transcript/index.js +5 -0
  169. package/dist/observation/transcript/index.js.map +1 -0
  170. package/dist/observation/transcript/provider.d.ts +7 -0
  171. package/dist/observation/transcript/provider.d.ts.map +1 -0
  172. package/dist/observation/transcript/provider.js +132 -0
  173. package/dist/observation/transcript/provider.js.map +1 -0
  174. package/dist/observation/transcript/services/jsonl-reader.d.ts +12 -0
  175. package/dist/observation/transcript/services/jsonl-reader.d.ts.map +1 -0
  176. package/dist/observation/transcript/services/jsonl-reader.js +140 -0
  177. package/dist/observation/transcript/services/jsonl-reader.js.map +1 -0
  178. package/dist/observation/transcript/services/yield.d.ts +3 -0
  179. package/dist/observation/transcript/services/yield.d.ts.map +1 -0
  180. package/dist/observation/transcript/services/yield.js +15 -0
  181. package/dist/observation/transcript/services/yield.js.map +1 -0
  182. package/dist/observation/transcript/wire.d.ts +26 -0
  183. package/dist/observation/transcript/wire.d.ts.map +1 -0
  184. package/dist/observation/transcript/wire.js +89 -0
  185. package/dist/observation/transcript/wire.js.map +1 -0
  186. package/dist/services/account-usage.d.ts +86 -0
  187. package/dist/services/account-usage.d.ts.map +1 -0
  188. package/dist/services/account-usage.js +813 -0
  189. package/dist/services/account-usage.js.map +1 -0
  190. package/dist/services/distribution.d.ts +64 -0
  191. package/dist/services/distribution.d.ts.map +1 -0
  192. package/dist/services/distribution.js +255 -0
  193. package/dist/services/distribution.js.map +1 -0
  194. package/dist/services/event-source.d.ts +29 -0
  195. package/dist/services/event-source.d.ts.map +1 -0
  196. package/dist/services/event-source.js +38 -0
  197. package/dist/services/event-source.js.map +1 -0
  198. package/dist/services/extensions.d.ts +46 -0
  199. package/dist/services/extensions.d.ts.map +1 -0
  200. package/dist/services/extensions.js +1263 -0
  201. package/dist/services/extensions.js.map +1 -0
  202. package/dist/services/models.d.ts +6 -0
  203. package/dist/services/models.d.ts.map +1 -0
  204. package/dist/services/models.js +90 -0
  205. package/dist/services/models.js.map +1 -0
  206. package/dist/services/profiles.d.ts +48 -0
  207. package/dist/services/profiles.d.ts.map +1 -0
  208. package/dist/services/profiles.js +176 -0
  209. package/dist/services/profiles.js.map +1 -0
  210. package/dist/services/prompt.d.ts +39 -0
  211. package/dist/services/prompt.d.ts.map +1 -0
  212. package/dist/services/prompt.js +107 -0
  213. package/dist/services/prompt.js.map +1 -0
  214. package/package.json +46 -3
  215. package/README.md +0 -3
package/dist/driver.js ADDED
@@ -0,0 +1,840 @@
1
+ /**
2
+ * Claude session driver — the composition layer (DESIGN §11, §16).
3
+ *
4
+ * Runs HUB-SIDE (Electron main / future daemon), never in the pty-host: the
5
+ * host stays Claude-agnostic. The driver owns observation and control only;
6
+ * PROCESS lifecycle (spawn/terminate) belongs to the host behind the injected
7
+ * ports:
8
+ *
9
+ * prepare (settings + UUID join contract)
10
+ * → ports.spawn (the host carries the hook token in its explicit env grant)
11
+ * → hook bridge (loopback HTTP; the ONLY session it accepts is ours)
12
+ * → category normalizers → candidate event source → runtime ingress
13
+ * → live transcript provider (lazy: attached at the
14
+ * first hook payload that hands us transcript_path)
15
+ * → authenticated OTLP logs (settled request usage, when available)
16
+ * → prompt injector (uses ports.automate; confirmation and
17
+ * permission gating wired from the normalized event stream)
18
+ *
19
+ * Observation level (DESIGN §19.2) is reported honestly: 'terminal-only'
20
+ * until the first hook arrives, 'native-hooks' after.
21
+ */
22
+ import { randomUUID } from 'node:crypto';
23
+ import { homedir } from 'node:os';
24
+ import { join, resolve } from 'node:path';
25
+ import {} from '@vibefield/puppeteer-core';
26
+ import { createHookBridge } from './observation/hook-bridge.js';
27
+ import { ClaudeHookNormalizer } from './normalization/index.js';
28
+ import { prepareClaudeSession, cleanupClaudeSession, hasClaudeOtelExporterConflict, locateClaudeTranscript, } from './launch/prepare.js';
29
+ import { createPromptInjector } from './services/prompt.js';
30
+ import { observeClaudeStatusLineAccountUsage } from './services/account-usage.js';
31
+ import { claudeContextWindowEvent, claudeEnvironmentEvents } from './observation/status-channel.js';
32
+ import { ClaudeMonitorEvidence } from './normalization/monitor.js';
33
+ import { decodeClaudeOtelLogs, isClaudeOtelLogsVerified, normalizeClaudeOtelModel, normalizeClaudeOtelUsage, otelString, supportsClaudeOtelLogs, } from './observation/otel/index.js';
34
+ import { ClaudeTranscriptObservationProvider } from './observation/transcript/provider.js';
35
+ import { claudePermissionMode } from './normalization/mode.js';
36
+ import { ClaudeEventSource } from './services/event-source.js';
37
+ const TOKEN_ENV_VAR = 'PUPPETEER_HOOK_TOKEN';
38
+ const MAX_OTEL_USAGE_FINGERPRINTS = 20_000;
39
+ const MAX_OTEL_ACTOR_FINGERPRINTS = 4_096;
40
+ function rememberFingerprint(fingerprints, key, fingerprint, capacity) {
41
+ fingerprints.delete(key);
42
+ fingerprints.set(key, fingerprint);
43
+ while (fingerprints.size > capacity) {
44
+ const oldest = fingerprints.keys().next().value;
45
+ if (oldest === undefined)
46
+ break;
47
+ fingerprints.delete(oldest);
48
+ }
49
+ }
50
+ function hookEventConfidence(hookEventName, event, payload) {
51
+ if (event.type === 'interaction:question-requested' ||
52
+ (hookEventName === 'PreCompact' && event.type === 'compaction:started') ||
53
+ (['Stop', 'StopFailure', 'SessionEnd', 'PreCompact', 'UserPromptSubmit'].includes(hookEventName) &&
54
+ event.type === 'compaction:completed') ||
55
+ (['tool:requested', 'tool:started', 'tool:completed', 'tool:failed', 'workspace:file-operation'].includes(event.type) &&
56
+ typeof payload.tool_use_id !== 'string')) {
57
+ return 'inferred';
58
+ }
59
+ return 'authoritative';
60
+ }
61
+ function payloadVersion(payload) {
62
+ if (!payload || typeof payload !== 'object')
63
+ return undefined;
64
+ const body = payload;
65
+ return typeof body.version === 'string'
66
+ ? body.version
67
+ : typeof body.claude_version === 'string'
68
+ ? body.claude_version
69
+ : undefined;
70
+ }
71
+ export async function prepareClaudeTuiSession(options) {
72
+ if (options.resume && options.resumeInvocation) {
73
+ throw new Error('Claude preparation accepts resume or resumeInvocation, not both');
74
+ }
75
+ // Session id first: the bridge must be able to enforce its allow-list from
76
+ // the instant it starts listening, with no window where the closure could
77
+ // dereference a not-yet-prepared session. On resume the id is the session
78
+ // being resumed (it keeps its own id); otherwise mint a fresh one.
79
+ const sessionId = options.resume ?? randomUUID();
80
+ let selectedSessionId = options.resume ?? (options.resumeInvocation ? undefined : sessionId);
81
+ let selectionLocked = options.resume !== undefined;
82
+ // Sessions a native resume launch runs that are never the one resumed.
83
+ const bootSessionIds = new Set();
84
+ const { otelUsageEnabled, otelUsageUnavailableReason, otelUsageVerified } = otelUsagePolicy(options);
85
+ const bridge = (options.hookBridgeFactory ?? createHookBridge)({
86
+ ...ingressPins(options.ingress),
87
+ allowSession: (id, kind, body) => {
88
+ // `/clear` is a native in-process identity rotation regardless of how
89
+ // the original conversation was selected. Once authenticated, its
90
+ // SessionStart becomes the new allow-list claim and stale ids are denied.
91
+ if (kind === 'hook' && body.hook_event_name === 'SessionStart' && body.source === 'clear') {
92
+ selectedSessionId = id;
93
+ selectionLocked = true;
94
+ return true;
95
+ }
96
+ if (!options.resumeInvocation) {
97
+ return id === selectedSessionId;
98
+ }
99
+ // Claude chooses the session after launch (`--resume` picker, `--continue`).
100
+ // Until it announces the choice with the resumed session's SessionStart,
101
+ // the process runs a throwaway boot session: 2.1.269 fires that session's
102
+ // InstructionsLoaded (load_reason session_start) before the picker is
103
+ // even shown, and a release may announce it with a `startup`
104
+ // SessionStart (packages/surface/vendors/claude/findings.md §6). Neither
105
+ // is ever the session observed here, so its hooks are acknowledged and
106
+ // dropped rather than allowed to bind. Status lines rendered for the
107
+ // highlighted conversation stay visible but claim nothing. The choice
108
+ // may still move while only SessionStarts have arrived; the first hook
109
+ // the announced session runs makes it final.
110
+ const isHook = kind === 'hook';
111
+ const isSessionStart = isHook && body.hook_event_name === 'SessionStart';
112
+ if (!selectionLocked && isSessionStart && body.source !== 'startup') {
113
+ bootSessionIds.delete(id);
114
+ selectedSessionId = id;
115
+ return true;
116
+ }
117
+ if (id === selectedSessionId) {
118
+ if (isHook)
119
+ selectionLocked = true;
120
+ return true;
121
+ }
122
+ if (bootSessionIds.has(id) ||
123
+ (!selectionLocked && (isSessionStart || (selectedSessionId === undefined && isHook)))) {
124
+ bootSessionIds.add(id);
125
+ return 'ignore';
126
+ }
127
+ return selectedSessionId === undefined && !isHook;
128
+ },
129
+ });
130
+ await bridge.start();
131
+ try {
132
+ reportBound(bridge, options.ingress);
133
+ const prepared = await prepareClaudeSession({
134
+ cwd: options.cwd,
135
+ sessionId,
136
+ resume: options.resume,
137
+ resumeInvocation: options.resumeInvocation,
138
+ title: options.title,
139
+ executable: options.executable,
140
+ env: options.env,
141
+ permissionMode: options.permissionMode,
142
+ model: options.model,
143
+ effort: options.effort,
144
+ settingSources: options.settingSources,
145
+ configDir: options.configDir,
146
+ fileChangeMatcher: options.fileChangeMatcher,
147
+ carriedArgs: options.carriedArgs,
148
+ prompt: options.prompt,
149
+ home: options.home,
150
+ readsNoSettingsFiles: options.readsNoSettingsFiles,
151
+ refuseHooksOff: options.refuseHooksOff,
152
+ endpoint: bridge.endpoint(),
153
+ ...(otelUsageEnabled ? { otelLogsEndpoint: bridge.otelLogsEndpoint() } : {}),
154
+ statusLineEndpoint: bridge.statusLineEndpoint(),
155
+ ...(options.observeSubagentStatus === false
156
+ ? {}
157
+ : { subagentStatusLineEndpoint: bridge.subagentStatusLineEndpoint() }),
158
+ tokenEnvVar: TOKEN_ENV_VAR,
159
+ token: bridge.token,
160
+ });
161
+ try {
162
+ const observation = createClaudeObservation(options, bridge, { sessionId: prepared.sessionId, cleanup: () => cleanupClaudeSession(prepared) }, () => selectedSessionId ?? prepared.sessionId, otelUsageEnabled, otelUsageUnavailableReason, otelUsageVerified);
163
+ return {
164
+ sessionId: prepared.sessionId,
165
+ launch: prepared,
166
+ adopt: observation.adopt,
167
+ dispose: observation.dispose,
168
+ };
169
+ }
170
+ catch (error) {
171
+ await cleanupClaudeSession(prepared);
172
+ throw error;
173
+ }
174
+ }
175
+ catch (err) {
176
+ await bridge.dispose();
177
+ throw err;
178
+ }
179
+ }
180
+ /** What the OTLP usage rail may do for this session, from the caller's option and the launch environment. */
181
+ function otelUsagePolicy(options) {
182
+ const otelUsageUnavailableReason = options.observeOtlpUsage === false
183
+ ? 'Authenticated OTLP request logs were disabled by the session option.'
184
+ : !supportsClaudeOtelLogs(options.providerVersion)
185
+ ? `Claude ${options.providerVersion} predates the locally verified OTLP log contract.`
186
+ : hasClaudeOtelExporterConflict()
187
+ ? 'Authenticated OTLP setup was disabled because the launching environment already owns exporter settings.'
188
+ : undefined;
189
+ return {
190
+ otelUsageEnabled: otelUsageUnavailableReason === undefined,
191
+ otelUsageUnavailableReason,
192
+ otelUsageVerified: isClaudeOtelLogsVerified(options.providerVersion),
193
+ };
194
+ }
195
+ /** The bridge options a host's ingress pins: only the keys it set (a fake bridge sees no `undefined`). */
196
+ function ingressPins(ingress) {
197
+ return {
198
+ ...(ingress?.port !== undefined && ingress.port !== 0 ? { port: ingress.port } : {}),
199
+ ...(ingress?.token !== undefined ? { token: ingress.token } : {}),
200
+ };
201
+ }
202
+ /** Tell the host what the bridge bound — port from the endpoint URL, the bearer as minted or pinned. */
203
+ function reportBound(bridge, ingress) {
204
+ if (!ingress?.onBound)
205
+ return;
206
+ let port;
207
+ try {
208
+ port = Number(new URL(bridge.endpoint()).port);
209
+ }
210
+ catch {
211
+ return;
212
+ }
213
+ if (!Number.isInteger(port) || port <= 0)
214
+ return;
215
+ ingress.onBound({ port, token: bridge.token });
216
+ }
217
+ function createClaudeObservation(options, bridge, bound, nativeSessionId = () => bound.sessionId, otelUsageEnabled = false, otelUsageUnavailableReason, otelUsageVerified = false) {
218
+ const normalizer = new ClaudeHookNormalizer();
219
+ const events = new ClaudeEventSource({ sessionId: nativeSessionId, providerVersion: options.providerVersion });
220
+ let observation = 'terminal-only';
221
+ let transcriptPath;
222
+ const semanticProvider = options.semanticProviderFactory?.() ?? new ClaudeTranscriptObservationProvider();
223
+ const semanticCapabilities = Promise.resolve().then(() => semanticProvider.capabilities());
224
+ const monitorEvidence = new ClaudeMonitorEvidence({
225
+ nativeSessionId,
226
+ otelUsageEnabled,
227
+ otelUsageUnavailableReason,
228
+ otelUsageVerified,
229
+ });
230
+ let semanticHandle;
231
+ let semanticAttachment;
232
+ let semanticGeneration = 0;
233
+ let adoptedRuntimeSessionId;
234
+ let adoptedSession;
235
+ let disposed = false;
236
+ // A transcript known before anyone listens (a re-attach) is armed at the
237
+ // first subscription, like configured intent and capabilities: the event
238
+ // source buffers early candidates, so nothing is lost by waiting — the wait
239
+ // ORDERS the baseline read after the intent and capability batches.
240
+ let pendingTranscript;
241
+ let subscribed = false;
242
+ let capabilitiesBatch = monitorEvidence.capabilitiesBatch(new Date().toISOString());
243
+ let semanticCapabilitiesPublished = false;
244
+ let hookRailAvailable = true;
245
+ let hookRailUnavailableReason = 'Claude hook bridge unavailable';
246
+ let matchingFaultHooks = 0;
247
+ let hookRailFaultInjected = false;
248
+ const pendingPermissionIds = new Set();
249
+ const pendingQuestionIds = new Set();
250
+ let configuredIntentPublished = false;
251
+ let observedStatusEnvironmentKey;
252
+ let observedStatusContextKey;
253
+ const observedOtelUsage = new Map();
254
+ const observedOtelModels = new Map();
255
+ const injector = createPromptInjector({
256
+ automate: (operation) => {
257
+ if (!adoptedRuntimeSessionId) {
258
+ return Promise.resolve({ accepted: false, reason: 'prepared Claude session is not adopted' });
259
+ }
260
+ return options.automate(adoptedRuntimeSessionId, operation);
261
+ },
262
+ });
263
+ function emitMonitorBatch(batch) {
264
+ apply({ type: 'monitor:batch', batch }, {
265
+ source: 'native-protocol',
266
+ timestamp: batch.observedAt,
267
+ confidence: 'authoritative',
268
+ });
269
+ }
270
+ emitMonitorBatch(capabilitiesBatch);
271
+ async function publishCapabilities() {
272
+ if (semanticCapabilitiesPublished || disposed)
273
+ return;
274
+ semanticCapabilitiesPublished = true;
275
+ const semantic = await semanticCapabilities.catch(() => []);
276
+ if (disposed)
277
+ return;
278
+ const batch = monitorEvidence.capabilitiesBatch(new Date().toISOString());
279
+ const byFamily = new Map(batch.capabilities?.map((capability) => [capability.family, capability]) ?? []);
280
+ for (const capability of semantic) {
281
+ const current = byFamily.get(capability.family);
282
+ if (!current || (current.support === 'unsupported' && capability.support !== 'unsupported')) {
283
+ byFamily.set(capability.family, capability);
284
+ }
285
+ }
286
+ const merged = { ...batch, capabilities: [...byFamily.values()] };
287
+ capabilitiesBatch = hookRailAvailable
288
+ ? merged
289
+ : monitorEvidence.hookRailUnavailableBatch(new Date().toISOString(), hookRailUnavailableReason, merged.capabilities);
290
+ emitMonitorBatch(capabilitiesBatch);
291
+ }
292
+ function apply(event, meta) {
293
+ // Settled request usage belongs exclusively to authenticated API telemetry.
294
+ if (event.type === 'usage:tokens-used' && meta.source !== 'native-telemetry')
295
+ return;
296
+ // Injector wiring rides the normalized stream, not raw payloads.
297
+ switch (event.type) {
298
+ case 'turn:started':
299
+ injector.handleTurnStarted(event.turnId, event.prompt);
300
+ break;
301
+ case 'interaction:permission-requested':
302
+ pendingPermissionIds.add(event.requestId);
303
+ injector.setPermissionPending(pendingPermissionIds.size > 0);
304
+ break;
305
+ case 'interaction:permission-resolved':
306
+ pendingPermissionIds.delete(event.requestId);
307
+ injector.setPermissionPending(pendingPermissionIds.size > 0);
308
+ break;
309
+ case 'interaction:question-requested':
310
+ pendingQuestionIds.add(event.requestId);
311
+ injector.setQuestionPending(pendingQuestionIds.size > 0);
312
+ break;
313
+ case 'interaction:question-resolved':
314
+ pendingQuestionIds.delete(event.requestId);
315
+ injector.setQuestionPending(pendingQuestionIds.size > 0);
316
+ break;
317
+ case 'session:started':
318
+ if (!event.rebind)
319
+ break;
320
+ pendingPermissionIds.clear();
321
+ pendingQuestionIds.clear();
322
+ injector.setPermissionPending(false);
323
+ injector.setQuestionPending(false);
324
+ break;
325
+ // A native boundary is authoritative even if an older Claude release
326
+ // omitted a resolution signal for one request.
327
+ case 'turn:completed':
328
+ case 'turn:failed':
329
+ case 'session:exited':
330
+ pendingPermissionIds.clear();
331
+ pendingQuestionIds.clear();
332
+ injector.setPermissionPending(false);
333
+ injector.setQuestionPending(false);
334
+ break;
335
+ }
336
+ events.publish(event, meta);
337
+ }
338
+ function publishConfiguredIntent() {
339
+ if (configuredIntentPublished)
340
+ return;
341
+ configuredIntentPublished = true;
342
+ const publication = {
343
+ source: 'runtime',
344
+ timestamp: new Date().toISOString(),
345
+ providerVersion: options.providerVersion,
346
+ };
347
+ if (options.model) {
348
+ apply({ type: 'model:updated', intent: 'configured', model: { id: options.model, provider: 'anthropic' } }, publication);
349
+ }
350
+ if (options.effort) {
351
+ apply({ type: 'effort:updated', intent: 'configured', effort: options.effort }, publication);
352
+ }
353
+ // A launch that named no mode configured none: the first hook says which one Claude chose.
354
+ if (options.permissionMode !== null) {
355
+ apply({
356
+ type: 'mode:updated',
357
+ intent: 'configured',
358
+ modeKind: 'provider-permission',
359
+ mode: claudePermissionMode(options.permissionMode ?? 'default'),
360
+ }, publication);
361
+ }
362
+ }
363
+ const reportHookRailUnavailable = (reason) => {
364
+ if (disposed || !hookRailAvailable)
365
+ return;
366
+ const observedAt = new Date().toISOString();
367
+ hookRailAvailable = false;
368
+ hookRailUnavailableReason = reason;
369
+ observation = semanticHandle ? 'native-log' : 'terminal-only';
370
+ capabilitiesBatch = monitorEvidence.hookRailUnavailableBatch(observedAt, reason, capabilitiesBatch.capabilities);
371
+ emitMonitorBatch(capabilitiesBatch);
372
+ apply({ type: 'adapter:native-event', adapter: 'claude-code', nativeType: 'hook-bridge.unavailable' }, {
373
+ source: 'runtime',
374
+ timestamp: observedAt,
375
+ providerVersion: options.providerVersion,
376
+ native: { reason },
377
+ });
378
+ };
379
+ bridge.onUnavailable(reportHookRailUnavailable);
380
+ bridge.onOtelLogs((otelEnvelope) => {
381
+ if (!otelUsageEnabled || disposed)
382
+ return;
383
+ for (const record of decodeClaudeOtelLogs(otelEnvelope.body, otelEnvelope.receivedAt)) {
384
+ if (otelString(record, 'session.id') !== nativeSessionId())
385
+ continue;
386
+ const usage = normalizeClaudeOtelUsage(record);
387
+ const model = normalizeClaudeOtelModel(record);
388
+ if (!usage && !model) {
389
+ apply({
390
+ type: 'adapter:native-event',
391
+ adapter: 'claude-code',
392
+ nativeType: `otel:${otelString(record, 'event.name') ?? record.body ?? 'log'}`,
393
+ }, {
394
+ source: 'native-telemetry',
395
+ timestamp: record.timestamp,
396
+ promptId: otelString(record, 'prompt.id'),
397
+ providerVersion: record.providerVersion ?? options.providerVersion,
398
+ confidence: 'authoritative',
399
+ native: record,
400
+ });
401
+ if (observation === 'terminal-only')
402
+ observation = 'native-log';
403
+ continue;
404
+ }
405
+ if (observation === 'terminal-only')
406
+ observation = 'native-log';
407
+ if (usage) {
408
+ const key = usage.event.usageId;
409
+ const fingerprint = JSON.stringify([
410
+ usage.event,
411
+ usage.agentId ?? null,
412
+ usage.agentType ?? null,
413
+ usage.actorKey ?? null,
414
+ usage.actorRole ?? null,
415
+ ]);
416
+ const previous = observedOtelUsage.get(key);
417
+ rememberFingerprint(observedOtelUsage, key, fingerprint, MAX_OTEL_USAGE_FINGERPRINTS);
418
+ if (previous !== fingerprint) {
419
+ apply(usage.event, {
420
+ source: 'native-telemetry',
421
+ timestamp: usage.timestamp,
422
+ promptId: usage.promptId,
423
+ agentId: usage.agentId,
424
+ agentType: usage.agentType,
425
+ actorKey: usage.actorKey,
426
+ actorRole: usage.actorRole,
427
+ providerVersion: usage.providerVersion ?? options.providerVersion,
428
+ confidence: 'authoritative',
429
+ native: usage.nativeEvent,
430
+ });
431
+ }
432
+ }
433
+ if (model) {
434
+ const key = model.agentId ?? model.actorKey ?? 'root';
435
+ const fingerprint = JSON.stringify(model.event);
436
+ if (observedOtelModels.get(key) !== fingerprint) {
437
+ rememberFingerprint(observedOtelModels, key, fingerprint, MAX_OTEL_ACTOR_FINGERPRINTS);
438
+ apply(model.event, {
439
+ source: 'native-telemetry',
440
+ timestamp: model.timestamp,
441
+ promptId: otelString(record, 'prompt.id'),
442
+ agentId: model.agentId,
443
+ agentType: model.agentType,
444
+ actorKey: model.actorKey,
445
+ actorRole: model.actorRole,
446
+ providerVersion: record.providerVersion ?? options.providerVersion,
447
+ confidence: 'authoritative',
448
+ native: record,
449
+ });
450
+ }
451
+ }
452
+ }
453
+ });
454
+ function ensureSemanticProvider(path) {
455
+ if (semanticAttachment && transcriptPath === path)
456
+ return;
457
+ semanticGeneration += 1;
458
+ const generation = semanticGeneration;
459
+ const priorAttachment = semanticAttachment;
460
+ transcriptPath = path;
461
+ const nextAttachment = (async () => {
462
+ const prior = await priorAttachment?.catch(() => undefined);
463
+ await prior?.dispose();
464
+ await semanticCapabilities;
465
+ if (disposed || generation !== semanticGeneration)
466
+ return undefined;
467
+ const handle = await semanticProvider.attach({
468
+ nativeSessionId: nativeSessionId(),
469
+ transcriptPath: path,
470
+ pollIntervalMs: options.transcriptPollIntervalMs,
471
+ });
472
+ if (disposed || generation !== semanticGeneration) {
473
+ await handle.dispose();
474
+ return undefined;
475
+ }
476
+ semanticHandle = handle;
477
+ // A tailed transcript is native-log observation. Hooks upgrade it; they
478
+ // never come first for a re-attached session, which announces nothing.
479
+ if (observation === 'terminal-only')
480
+ observation = 'native-log';
481
+ handle.onEvent((semantic) => {
482
+ if (disposed || generation !== semanticGeneration)
483
+ return;
484
+ apply(semantic.event, {
485
+ source: 'native-transcript',
486
+ timestamp: semantic.timestamp,
487
+ promptId: semantic.promptId,
488
+ turnId: semantic.turnId,
489
+ agentId: semantic.agentId,
490
+ agentType: semantic.agentType,
491
+ native: semantic.nativeEvent,
492
+ replay: semantic.replay,
493
+ });
494
+ });
495
+ handle.onBatch((batch) => {
496
+ if (disposed || generation !== semanticGeneration)
497
+ return;
498
+ emitMonitorBatch(batch);
499
+ });
500
+ handle.onError((error) => {
501
+ if (disposed || generation !== semanticGeneration)
502
+ return;
503
+ apply({ type: 'adapter:native-event', adapter: 'claude-code', nativeType: 'semantic-observer.error' }, {
504
+ source: 'runtime',
505
+ timestamp: new Date().toISOString(),
506
+ native: {
507
+ name: error.name,
508
+ code: typeof error.code === 'string'
509
+ ? error.code
510
+ : 'unknown',
511
+ },
512
+ });
513
+ // The semantic rail publishes its own degraded batch; hooks and the TUI continue.
514
+ });
515
+ try {
516
+ await handle.poll();
517
+ }
518
+ catch (error) {
519
+ if (semanticHandle === handle)
520
+ semanticHandle = undefined;
521
+ await handle.dispose();
522
+ throw error;
523
+ }
524
+ return handle;
525
+ })().catch((error) => {
526
+ if (!disposed && generation === semanticGeneration) {
527
+ if (semanticAttachment === nextAttachment)
528
+ semanticAttachment = undefined;
529
+ apply({ type: 'adapter:native-event', adapter: 'claude-code', nativeType: 'semantic-observer.unavailable' }, {
530
+ source: 'runtime',
531
+ timestamp: new Date().toISOString(),
532
+ native: { error: error instanceof Error ? error.message : String(error) },
533
+ });
534
+ }
535
+ return undefined;
536
+ });
537
+ semanticAttachment = nextAttachment;
538
+ }
539
+ function pollSemantic(hint) {
540
+ void semanticAttachment
541
+ ?.then((handle) => handle?.poll(hint))
542
+ .catch(() => {
543
+ // The provider reports its own degraded readiness; hooks continue.
544
+ });
545
+ }
546
+ bridge.onEvent((hookEnvelope) => {
547
+ observation = 'native-hooks';
548
+ const body = hookEnvelope.body;
549
+ const normalized = normalizer.normalize(body);
550
+ for (const diagnostic of normalized.diagnostics) {
551
+ try {
552
+ options.onDiagnostic?.(diagnostic);
553
+ }
554
+ catch {
555
+ // Diagnostic consumers must not affect Claude or the normalized stream.
556
+ }
557
+ }
558
+ // The bridge admits only the selected session's hooks, so the first
559
+ // transcript path to arrive is that session's durable history — on a
560
+ // native resume, the path its SessionStart announces.
561
+ if (normalized.transcriptPath)
562
+ ensureSemanticProvider(normalized.transcriptPath);
563
+ const hookEventName = typeof body.hook_event_name === 'string' ? body.hook_event_name : 'unknown';
564
+ if (normalized.sessionId)
565
+ monitorEvidence.observeNativeSession(normalized.sessionId);
566
+ if (normalized.agentId) {
567
+ if (hookEventName === 'SubagentStart') {
568
+ monitorEvidence.observeNativeAgentStarted(normalized.agentId, normalized.agentType);
569
+ }
570
+ else if (hookEventName === 'SubagentStop') {
571
+ monitorEvidence.observeNativeAgentStopped(normalized.agentId, normalized.agentType);
572
+ }
573
+ else {
574
+ monitorEvidence.observeNativeAgent(normalized.agentId, normalized.agentType);
575
+ }
576
+ }
577
+ for (const event of normalized.events) {
578
+ if (event.type === 'context-window:invalidated') {
579
+ emitMonitorBatch(monitorEvidence.rootContextInvalidationBatch(hookEnvelope.receivedAt, hookEnvelope.requestId));
580
+ }
581
+ apply(event, {
582
+ source: 'native-hook',
583
+ timestamp: hookEnvelope.receivedAt,
584
+ promptId: normalized.promptId,
585
+ turnId: normalized.turnId,
586
+ agentId: normalized.agentId,
587
+ agentType: normalized.agentType,
588
+ providerVersion: normalized.providerVersion,
589
+ confidence: hookEventConfidence(hookEventName, event, body),
590
+ native: body,
591
+ });
592
+ }
593
+ // Hooks fire near transcript appends — poke the semantic source instead
594
+ // of waiting out its fallback interval.
595
+ pollSemantic({
596
+ hookEventName,
597
+ nativeSessionId: normalized.sessionId,
598
+ promptId: normalized.promptId,
599
+ agentId: normalized.agentId,
600
+ agentType: normalized.agentType,
601
+ });
602
+ const fault = options.hookRailFaultInjection;
603
+ if (!fault || hookRailFaultInjected || hookEventName !== fault.afterHookEvent)
604
+ return;
605
+ matchingFaultHooks += 1;
606
+ if (matchingFaultHooks < (fault.occurrence ?? 1))
607
+ return;
608
+ hookRailFaultInjected = true;
609
+ const reason = fault.reason ?? `Claude hook bridge canary fault after ${hookEventName}`;
610
+ // The current hook has already been acknowledged by HookBridge. Close
611
+ // the real listener on the next microtask, then publish rail degradation
612
+ // directly because intentional disposal correctly suppresses the
613
+ // bridge's unexpected-close callback.
614
+ queueMicrotask(() => {
615
+ void bridge.dispose().then(() => reportHookRailUnavailable(reason), () => reportHookRailUnavailable(reason));
616
+ });
617
+ });
618
+ bridge.onStatusLine((statusEnvelope) => {
619
+ // Account usage is process-global (subscription quota), not session state.
620
+ observeClaudeStatusLineAccountUsage(statusEnvelope.body, statusEnvelope.receivedAt);
621
+ const monitorBatch = monitorEvidence.rootStatusBatch(statusEnvelope.body, statusEnvelope.receivedAt, statusEnvelope.requestId);
622
+ if (monitorBatch)
623
+ emitMonitorBatch(monitorBatch);
624
+ const environmentEvents = claudeEnvironmentEvents(statusEnvelope.body);
625
+ if (environmentEvents.length > 0) {
626
+ const environmentKey = JSON.stringify(environmentEvents);
627
+ if (environmentKey !== observedStatusEnvironmentKey) {
628
+ observedStatusEnvironmentKey = environmentKey;
629
+ for (const event of environmentEvents) {
630
+ apply(event, {
631
+ source: 'native-statusline',
632
+ timestamp: statusEnvelope.receivedAt,
633
+ providerVersion: payloadVersion(statusEnvelope.body),
634
+ native: statusEnvelope.body,
635
+ });
636
+ }
637
+ }
638
+ }
639
+ const contextEvent = claudeContextWindowEvent(statusEnvelope.body);
640
+ if (!contextEvent)
641
+ return;
642
+ if (contextEvent.type === 'context-window:invalidated') {
643
+ if (!observedStatusContextKey)
644
+ return;
645
+ observedStatusContextKey = undefined;
646
+ }
647
+ else {
648
+ const contextKey = JSON.stringify(contextEvent);
649
+ if (contextKey === observedStatusContextKey)
650
+ return;
651
+ observedStatusContextKey = contextKey;
652
+ }
653
+ apply(contextEvent, {
654
+ source: 'native-statusline',
655
+ timestamp: statusEnvelope.receivedAt,
656
+ providerVersion: payloadVersion(statusEnvelope.body),
657
+ native: statusEnvelope.body,
658
+ });
659
+ });
660
+ if (options.observeSubagentStatus !== false) {
661
+ bridge.onSubagentStatusLine((statusEnvelope) => {
662
+ const batch = monitorEvidence.childStatusBatch(statusEnvelope.body, statusEnvelope.receivedAt, statusEnvelope.requestId);
663
+ if (batch)
664
+ emitMonitorBatch(batch);
665
+ });
666
+ }
667
+ async function dispose(disposeOptions) {
668
+ if (disposed)
669
+ return;
670
+ disposed = true;
671
+ events.close();
672
+ const attached = await semanticAttachment?.catch(() => undefined);
673
+ await attached?.dispose();
674
+ if (disposeOptions?.release) {
675
+ // The host leaves, the process stays: the bridge drains rather than
676
+ // resets, and the staged settings and forwarders the process execs on
677
+ // every hook are NOT removed — a host that comes back rebinds the same
678
+ // port and the hooks keep landing.
679
+ await bridge.dispose({ drain: true });
680
+ return;
681
+ }
682
+ await bridge.dispose();
683
+ await bound.cleanup();
684
+ }
685
+ return {
686
+ async adopt(runtimeSessionId) {
687
+ if (disposed)
688
+ throw new Error('prepared Claude session is disposed');
689
+ if (adoptedRuntimeSessionId && adoptedRuntimeSessionId !== runtimeSessionId) {
690
+ throw new Error(`prepared Claude session is already adopted by ${adoptedRuntimeSessionId}`);
691
+ }
692
+ if (adoptedSession)
693
+ return adoptedSession;
694
+ adoptedRuntimeSessionId = runtimeSessionId;
695
+ adoptedSession = {
696
+ get sessionId() {
697
+ return nativeSessionId();
698
+ },
699
+ runtimeSessionId,
700
+ observationLevel: () => observation,
701
+ transcriptPath: () => transcriptPath,
702
+ events: {
703
+ onCandidate(listener) {
704
+ const unsubscribe = events.onCandidate(listener);
705
+ subscribed = true;
706
+ // configured intent is a LAUNCH fact (the model, effort and mode
707
+ // this host asked for); an attached process was asked by someone
708
+ // else, and its next hook or status line says what it is
709
+ if (!options.attached)
710
+ publishConfiguredIntent();
711
+ void publishCapabilities();
712
+ if (pendingTranscript !== undefined) {
713
+ const path = pendingTranscript;
714
+ pendingTranscript = undefined;
715
+ ensureSemanticProvider(path);
716
+ }
717
+ return unsubscribe;
718
+ },
719
+ },
720
+ services: {
721
+ prompt: { submit: (submission) => injector.submit(submission) },
722
+ },
723
+ pollTranscript: async () => {
724
+ const handle = await semanticAttachment;
725
+ await handle?.poll();
726
+ },
727
+ dispose,
728
+ };
729
+ return adoptedSession;
730
+ },
731
+ dispose,
732
+ observeTranscript: (path) => {
733
+ if (disposed)
734
+ return;
735
+ if (subscribed)
736
+ ensureSemanticProvider(path);
737
+ else
738
+ pendingTranscript = path;
739
+ },
740
+ };
741
+ }
742
+ /**
743
+ * Bind to a running Claude Code process (see {@link AttachClaudeTuiSessionOptions}).
744
+ * Fails — before anything is adopted — when the pinned port cannot be bound:
745
+ * the host then knows the ingress is lost and resumes the continuation instead.
746
+ */
747
+ export async function attachClaudeTuiSession(options) {
748
+ if (!Number.isInteger(options.ingress.port) || options.ingress.port <= 0 || options.ingress.token.length === 0) {
749
+ throw new Error('Claude attach needs the ingress the process was launched against (a positive port and a token)');
750
+ }
751
+ const { otelUsageEnabled, otelUsageUnavailableReason, otelUsageVerified } = otelUsagePolicy(options);
752
+ const configDir = (options.configDir ?? options.env?.CLAUDE_CONFIG_DIR ?? process.env.CLAUDE_CONFIG_DIR)?.trim();
753
+ const root = options.env?.PUPPETEER_IMPOSTER_HOME ?? (configDir ? resolve(options.cwd, configDir) : join(homedir(), '.claude'));
754
+ let selectedSessionId = options.sessionId;
755
+ let heardPinned = false;
756
+ let observation;
757
+ const bridge = (options.hookBridgeFactory ?? createHookBridge)({
758
+ port: options.ingress.port,
759
+ token: options.ingress.token,
760
+ allowSession: (id, kind, body) => {
761
+ if (id === selectedSessionId) {
762
+ if (kind === 'hook')
763
+ heardPinned = true;
764
+ return true;
765
+ }
766
+ // `/clear` rotates the native identity in-process; the attached session
767
+ // follows it exactly as a spawned one does.
768
+ if (kind === 'hook' && body.hook_event_name === 'SessionStart' && body.source === 'clear') {
769
+ selectedSessionId = id;
770
+ heardPinned = true;
771
+ return true;
772
+ }
773
+ // A `/clear` typed while no host was listening rotated the id unheard.
774
+ // The first authenticated hook under a new id — before the selected id
775
+ // has spoken since the attach — is that rotation, when the new id
776
+ // already has a transcript under the same root (a subagent's or a
777
+ // stranger's id has none there). Once heard, the selection is final
778
+ // until the next in-process `/clear`.
779
+ if (kind === 'hook' && !heardPinned) {
780
+ const rotated = locateClaudeTranscript(id, root);
781
+ if (rotated !== undefined) {
782
+ selectedSessionId = id;
783
+ heardPinned = true;
784
+ observation?.observeTranscript(rotated);
785
+ return true;
786
+ }
787
+ }
788
+ return false;
789
+ },
790
+ });
791
+ await bridge.start();
792
+ try {
793
+ observation = createClaudeObservation({ ...options, ingress: undefined, attached: true }, bridge, { sessionId: options.sessionId, cleanup: async () => undefined }, () => selectedSessionId, otelUsageEnabled, otelUsageUnavailableReason, otelUsageVerified);
794
+ // The durable rail first: a quiet session announces nothing until its next
795
+ // hook, and its transcript already says where it stands.
796
+ const transcript = locateClaudeTranscript(options.sessionId, root);
797
+ if (transcript !== undefined)
798
+ observation.observeTranscript(transcript);
799
+ return await observation.adopt(options.runtimeSessionId);
800
+ }
801
+ catch (err) {
802
+ await bridge.dispose();
803
+ throw err;
804
+ }
805
+ }
806
+ export async function createClaudeSession(options) {
807
+ const prepared = await prepareClaudeTuiSession({
808
+ cwd: options.cwd,
809
+ title: options.title,
810
+ executable: options.executable,
811
+ env: options.env,
812
+ permissionMode: options.permissionMode,
813
+ model: options.model,
814
+ effort: options.effort,
815
+ settingSources: options.settingSources,
816
+ configDir: options.configDir,
817
+ providerVersion: options.providerVersion,
818
+ fileChangeMatcher: options.fileChangeMatcher,
819
+ resume: options.resume,
820
+ resumeInvocation: options.resumeInvocation,
821
+ transcriptPollIntervalMs: options.transcriptPollIntervalMs,
822
+ onDiagnostic: options.onDiagnostic,
823
+ ingress: options.ingress,
824
+ hookBridgeFactory: options.hookBridgeFactory,
825
+ hookRailFaultInjection: options.hookRailFaultInjection,
826
+ semanticProviderFactory: options.semanticProviderFactory,
827
+ observeOtlpUsage: options.observeOtlpUsage,
828
+ observeSubagentStatus: options.observeSubagentStatus,
829
+ automate: options.ports.automate,
830
+ });
831
+ try {
832
+ const { runtimeSessionId } = await options.ports.spawn(prepared.launch);
833
+ return await prepared.adopt(runtimeSessionId);
834
+ }
835
+ catch (err) {
836
+ await prepared.dispose();
837
+ throw err;
838
+ }
839
+ }
840
+ //# sourceMappingURL=driver.js.map