@agentuity/coder 2.0.6 → 2.0.8

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 (113) hide show
  1. package/AGENTS.md +43 -0
  2. package/README.md +75 -37
  3. package/dist/index.d.ts +1 -3
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1577
  6. package/dist/index.js.map +1 -1
  7. package/package.json +9 -12
  8. package/src/index.ts +51 -1885
  9. package/dist/chain-preview.d.ts +0 -55
  10. package/dist/chain-preview.d.ts.map +0 -1
  11. package/dist/chain-preview.js +0 -472
  12. package/dist/chain-preview.js.map +0 -1
  13. package/dist/client.d.ts +0 -43
  14. package/dist/client.d.ts.map +0 -1
  15. package/dist/client.js +0 -405
  16. package/dist/client.js.map +0 -1
  17. package/dist/commands.d.ts +0 -22
  18. package/dist/commands.d.ts.map +0 -1
  19. package/dist/commands.js +0 -99
  20. package/dist/commands.js.map +0 -1
  21. package/dist/footer.d.ts +0 -34
  22. package/dist/footer.d.ts.map +0 -1
  23. package/dist/footer.js +0 -249
  24. package/dist/footer.js.map +0 -1
  25. package/dist/handlers.d.ts +0 -24
  26. package/dist/handlers.d.ts.map +0 -1
  27. package/dist/handlers.js +0 -83
  28. package/dist/handlers.js.map +0 -1
  29. package/dist/hub-overlay-state.d.ts +0 -31
  30. package/dist/hub-overlay-state.d.ts.map +0 -1
  31. package/dist/hub-overlay-state.js +0 -78
  32. package/dist/hub-overlay-state.js.map +0 -1
  33. package/dist/hub-overlay.d.ts +0 -146
  34. package/dist/hub-overlay.d.ts.map +0 -1
  35. package/dist/hub-overlay.js +0 -2354
  36. package/dist/hub-overlay.js.map +0 -1
  37. package/dist/native-remote-ui-context.d.ts +0 -5
  38. package/dist/native-remote-ui-context.d.ts.map +0 -1
  39. package/dist/native-remote-ui-context.js +0 -30
  40. package/dist/native-remote-ui-context.js.map +0 -1
  41. package/dist/output-viewer.d.ts +0 -49
  42. package/dist/output-viewer.d.ts.map +0 -1
  43. package/dist/output-viewer.js +0 -389
  44. package/dist/output-viewer.js.map +0 -1
  45. package/dist/overlay.d.ts +0 -40
  46. package/dist/overlay.d.ts.map +0 -1
  47. package/dist/overlay.js +0 -225
  48. package/dist/overlay.js.map +0 -1
  49. package/dist/protocol.d.ts +0 -605
  50. package/dist/protocol.d.ts.map +0 -1
  51. package/dist/protocol.js +0 -4
  52. package/dist/protocol.js.map +0 -1
  53. package/dist/remote-lifecycle.d.ts +0 -61
  54. package/dist/remote-lifecycle.d.ts.map +0 -1
  55. package/dist/remote-lifecycle.js +0 -190
  56. package/dist/remote-lifecycle.js.map +0 -1
  57. package/dist/remote-session.d.ts +0 -128
  58. package/dist/remote-session.d.ts.map +0 -1
  59. package/dist/remote-session.js +0 -876
  60. package/dist/remote-session.js.map +0 -1
  61. package/dist/remote-tui.d.ts +0 -40
  62. package/dist/remote-tui.d.ts.map +0 -1
  63. package/dist/remote-tui.js +0 -867
  64. package/dist/remote-tui.js.map +0 -1
  65. package/dist/remote-ui-handler.d.ts +0 -5
  66. package/dist/remote-ui-handler.d.ts.map +0 -1
  67. package/dist/remote-ui-handler.js +0 -53
  68. package/dist/remote-ui-handler.js.map +0 -1
  69. package/dist/renderers.d.ts +0 -34
  70. package/dist/renderers.d.ts.map +0 -1
  71. package/dist/renderers.js +0 -669
  72. package/dist/renderers.js.map +0 -1
  73. package/dist/review.d.ts +0 -15
  74. package/dist/review.d.ts.map +0 -1
  75. package/dist/review.js +0 -154
  76. package/dist/review.js.map +0 -1
  77. package/dist/titlebar.d.ts +0 -3
  78. package/dist/titlebar.d.ts.map +0 -1
  79. package/dist/titlebar.js +0 -59
  80. package/dist/titlebar.js.map +0 -1
  81. package/dist/todo/index.d.ts +0 -3
  82. package/dist/todo/index.d.ts.map +0 -1
  83. package/dist/todo/index.js +0 -3
  84. package/dist/todo/index.js.map +0 -1
  85. package/dist/todo/store.d.ts +0 -6
  86. package/dist/todo/store.d.ts.map +0 -1
  87. package/dist/todo/store.js +0 -43
  88. package/dist/todo/store.js.map +0 -1
  89. package/dist/todo/types.d.ts +0 -13
  90. package/dist/todo/types.d.ts.map +0 -1
  91. package/dist/todo/types.js +0 -2
  92. package/dist/todo/types.js.map +0 -1
  93. package/src/chain-preview.ts +0 -621
  94. package/src/client.ts +0 -518
  95. package/src/commands.ts +0 -132
  96. package/src/footer.ts +0 -305
  97. package/src/handlers.ts +0 -113
  98. package/src/hub-overlay-state.ts +0 -127
  99. package/src/hub-overlay.ts +0 -3037
  100. package/src/native-remote-ui-context.ts +0 -41
  101. package/src/output-viewer.ts +0 -480
  102. package/src/overlay.ts +0 -294
  103. package/src/protocol.ts +0 -758
  104. package/src/remote-lifecycle.ts +0 -270
  105. package/src/remote-session.ts +0 -1080
  106. package/src/remote-tui.ts +0 -1020
  107. package/src/remote-ui-handler.ts +0 -86
  108. package/src/renderers.ts +0 -740
  109. package/src/review.ts +0 -201
  110. package/src/titlebar.ts +0 -63
  111. package/src/todo/index.ts +0 -2
  112. package/src/todo/store.ts +0 -49
  113. package/src/todo/types.ts +0 -14
package/src/remote-tui.ts DELETED
@@ -1,1020 +0,0 @@
1
- /**
2
- * Remote TUI — Native Pi Coding Agent Renderer for Remote Sessions
3
- *
4
- * Creates a real AgentSession + InteractiveMode backed by a remote sandbox
5
- * via Hub WebSocket, with the coder extension loaded for Hub UI (footer,
6
- * /hub overlay, commands, titlebar).
7
- *
8
- * Architecture:
9
- * Remote TUI → Hub WebSocket (controller) → Sandbox (Pi RPC mode)
10
- * - User input → agent.prompt() (monkey-patched) → RPC `prompt` → Hub → sandbox
11
- * - Sandbox Pi → AgentEvent stream → Hub broadcast → Agent.emit() → InteractiveMode renders natively
12
- * - Hub UI → coder extension (loaded via DefaultResourceLoader) provides footer, /hub, commands
13
- *
14
- * The local Agent never calls an LLM. Its prompt/steer/abort are monkey-patched
15
- * to send RPC commands. Its internal state is kept in sync with the remote agent
16
- * by mirroring state updates from each received event.
17
- *
18
- * The coder extension sees AGENTUITY_CODER_REMOTE_SESSION (Hub UI mode) +
19
- * AGENTUITY_CODER_NATIVE_REMOTE (skip legacy event rendering). It provides
20
- * Hub connection, footer, /hub overlay, commands, titlebar — but does NOT
21
- * intercept input or render events (this module handles both).
22
- *
23
- * IMPORTANT: Initialization order matters!
24
- * 1. Create RemoteSession (no connection yet)
25
- * 2. Create AgentSession, patch Agent/Session methods
26
- * 3. Register ALL event handlers on RemoteSession
27
- * 4. THEN connect — so hydration + replay events are captured
28
- */
29
-
30
- import {
31
- createAgentSession,
32
- DefaultResourceLoader,
33
- InteractiveMode,
34
- SessionManager,
35
- } from '@mariozechner/pi-coding-agent';
36
- import {
37
- getNativeRemoteExtensionContext,
38
- setNativeRemoteExtensionContext,
39
- waitForNativeRemoteExtensionContext,
40
- } from './native-remote-ui-context.ts';
41
- import {
42
- clearRemoteLifecycleWorkingMessage,
43
- getRemoteLifecycleActivityLabel,
44
- getRemoteLifecycleLabel,
45
- syncRemoteLifecycleWorkingMessage,
46
- type RemoteLifecycleState,
47
- } from './remote-lifecycle.ts';
48
- import { RemoteSession } from './remote-session.ts';
49
- import type { RpcEvent } from './remote-session.ts';
50
- import { agentuityCoderHub } from './index.ts';
51
- import { handleRemoteUiRequest, REMOTE_FIRE_AND_FORGET_UI_METHODS } from './remote-ui-handler.ts';
52
-
53
- const DEBUG = !!process.env['AGENTUITY_DEBUG'];
54
-
55
- function log(msg: string): void {
56
- if (DEBUG) console.error(`[remote-tui] ${msg}`);
57
- }
58
-
59
- /**
60
- * Run the native Pi TUI connected to a remote sandbox session.
61
- *
62
- * This is the entry point for `agentuity coder start --remote <sessionId>`.
63
- * Creates an AgentSession with the coder extension loaded (Hub UI), then
64
- * monkey-patches the Agent for remote-backed execution.
65
- */
66
- export async function runRemoteTui(options: {
67
- hubWsUrl: string;
68
- sessionId: string;
69
- }): Promise<void> {
70
- const { hubWsUrl, sessionId } = options;
71
-
72
- log(`Starting remote TUI for session ${sessionId}`);
73
- log(`Hub URL: ${hubWsUrl}`);
74
-
75
- // Set env vars BEFORE loading the extension so it enters native remote mode
76
- process.env.AGENTUITY_CODER_HUB_URL = hubWsUrl;
77
- process.env.AGENTUITY_CODER_REMOTE_SESSION = sessionId;
78
- process.env.AGENTUITY_CODER_NATIVE_REMOTE = '1';
79
- setNativeRemoteExtensionContext(null);
80
-
81
- // ── 1. Create RemoteSession (NOT connected yet) ──
82
- // We register all handlers BEFORE connecting so that the hydration
83
- // message from the Hub (sent immediately after init) is captured.
84
- const remote = new RemoteSession(sessionId);
85
- // TODO: Remove/Change when we get Agentuity service level auth enabled, this is just temporary
86
- remote.apiKey = process.env.AGENTUITY_CODER_API_KEY || null;
87
- let hydrationStreamingDetected = false;
88
- let sessionResumeSeen = false;
89
-
90
- // ── 2. Create AgentSession with coder extension loaded ──
91
- // The extension provides Hub UI (footer, /hub overlay, commands, titlebar).
92
- // AGENTUITY_CODER_NATIVE_REMOTE=1 tells it to skip legacy event rendering.
93
- const cwd = process.cwd();
94
- const resourceLoader = new DefaultResourceLoader({
95
- cwd,
96
- noExtensions: true, // Skip file-system extension discovery
97
- extensionFactories: [agentuityCoderHub], // Load coder extension directly
98
- });
99
- await resourceLoader.reload();
100
-
101
- const { session } = await createAgentSession({
102
- sessionManager: SessionManager.inMemory(),
103
- tools: [], // No local tools — sandbox has all the tools
104
- resourceLoader,
105
- });
106
- log('AgentSession created');
107
-
108
- // NOTE: Do NOT call session.bindExtensions() here.
109
- // InteractiveMode.initExtensions() calls it with the proper uiContext.
110
- // Calling it early fires session_start twice, duplicating extension init.
111
-
112
- // Access the Agent instance (typed as `any` for monkey-patching)
113
- const agent: any = session.agent;
114
- let lifecycleState = remote.getLifecycleState();
115
- let lifecycleOwnsWorkingMessage = false;
116
-
117
- function applyLifecycleUi(state: RemoteLifecycleState): void {
118
- const ctx = getNativeRemoteExtensionContext();
119
- if (!ctx?.hasUI) return;
120
-
121
- const shortSession = state.sessionId.slice(0, 16);
122
- ctx.ui.setStatus(
123
- 'remote_connection',
124
- `Remote: ${shortSession}${shortSession.length < state.sessionId.length ? '...' : ''} ${getRemoteLifecycleLabel(state)}`
125
- );
126
-
127
- const activity = getRemoteLifecycleActivityLabel(state);
128
- if (activity) {
129
- ctx.ui.setStatus('remote_activity', activity);
130
- } else {
131
- ctx.ui.setStatus('remote_activity', state.isStreaming ? 'agent working...' : 'idle');
132
- }
133
-
134
- lifecycleOwnsWorkingMessage = syncRemoteLifecycleWorkingMessage(
135
- state,
136
- ctx.ui,
137
- lifecycleOwnsWorkingMessage
138
- );
139
- }
140
-
141
- remote.onLifecycleChange((state) => {
142
- lifecycleState = state;
143
- applyLifecycleUi(state);
144
- });
145
- void waitForNativeRemoteExtensionContext(10_000).then((ctx) => {
146
- if (!ctx) return;
147
- applyLifecycleUi(lifecycleState);
148
- });
149
-
150
- // ── 3. Patch Agent to be remote-backed ──
151
- // Track the running prompt promise so InteractiveMode waits correctly
152
- let runningPromptResolve: (() => void) | null = null;
153
- let syntheticAgentStartEmitted = false;
154
-
155
- // Override Agent.prompt — send RPC prompt command, block until agent_end
156
- agent.prompt = async (input: any): Promise<void> => {
157
- const text = extractPromptText(input);
158
- log(`agent.prompt called, extracted text: ${text ? text.slice(0, 80) : '(empty)'}`);
159
- if (!text) return;
160
-
161
- // Set streaming state — InteractiveMode checks this
162
- agent._state.isStreaming = true;
163
- agent._state.streamMessage = null;
164
- agent._state.error = undefined;
165
-
166
- // Create runningPrompt so waitForIdle() works
167
- const runPromise = new Promise<void>((resolve) => {
168
- runningPromptResolve = resolve;
169
- });
170
- agent.runningPrompt = runPromise;
171
-
172
- // Emit synthetic agent_start so InteractiveMode shows "working" immediately
173
- syntheticAgentStartEmitted = true;
174
- agent.emit({ type: 'agent_start', agentName: 'lead', timestamp: Date.now() });
175
-
176
- // Send RPC command to sandbox
177
- remote.prompt(text);
178
- log(`Sent prompt: ${text.slice(0, 100)}`);
179
-
180
- // Block until agent_end received from remote
181
- await runPromise;
182
- };
183
-
184
- // Override Agent.steer — send RPC steer command
185
- agent.steer = (m: any) => {
186
- const text = extractMessageText(m);
187
- if (text) {
188
- remote.steer(text);
189
- log(`Sent steer: ${text.slice(0, 100)}`);
190
- }
191
- };
192
-
193
- // Override Agent.abort — send RPC abort command
194
- agent.abort = () => {
195
- remote.abort();
196
- log('Sent abort');
197
- resolveRunningPrompt();
198
- };
199
-
200
- // Override Agent.waitForIdle
201
- agent.waitForIdle = () => {
202
- return agent.runningPrompt ?? Promise.resolve();
203
- };
204
-
205
- // ── 4. Patch AgentSession methods ──
206
- // session.prompt() does model/API key validation before calling agent.prompt().
207
- // In remote mode, skip validation — the sandbox has the model/key.
208
- // InteractiveMode calls session.prompt(text, { streamingBehavior: "steer" })
209
- // when user types during streaming, and session.prompt(text, { streamingBehavior: "followUp" })
210
- // for Alt+Enter follow-ups. Handle these by routing to steer/followUp commands.
211
- (session as any).prompt = async (text: string, options?: any) => {
212
- const behavior = options?.streamingBehavior;
213
- log(`session.prompt called (behavior=${behavior ?? 'normal'}): ${text.slice(0, 80)}`);
214
-
215
- // Extension commands (start with /) — let AgentSession handle them
216
- // so extension-registered slash commands still work in remote mode
217
- if (text.startsWith('/') && (session as any)._tryExecuteExtensionCommand) {
218
- try {
219
- const handled = await (session as any)._tryExecuteExtensionCommand(text);
220
- if (handled) {
221
- log(`Extension command handled: ${text}`);
222
- return;
223
- }
224
- } catch (err) {
225
- log(`Extension command error: ${err}`);
226
- }
227
- }
228
-
229
- if (behavior === 'steer') {
230
- remote.steer(text);
231
- log(`Sent steer: ${text.slice(0, 80)}`);
232
- return;
233
- }
234
- if (behavior === 'followUp') {
235
- remote.sendCommand({ type: 'follow_up', message: text });
236
- log(`Sent follow-up: ${text.slice(0, 80)}`);
237
- return;
238
- }
239
-
240
- // Normal prompt — send to sandbox
241
- await agent.prompt(text);
242
- };
243
-
244
- (session as any).steer = async (text: string) => {
245
- remote.steer(text);
246
- };
247
-
248
- (session as any).followUp = async (text: string) => {
249
- remote.sendCommand({ type: 'follow_up', message: text });
250
- };
251
-
252
- (session as any).abort = async () => {
253
- remote.abort();
254
- resolveRunningPrompt();
255
- };
256
-
257
- // Disable auto-compaction (sandbox handles it)
258
- session.setAutoCompactionEnabled(false);
259
- session.setAutoRetryEnabled(false);
260
-
261
- // ── 5. Wire up remote events → Agent event pipeline ──
262
- // Only emit LIVE events (from broadcast) to Agent → InteractiveMode.
263
- // Replay events (from Durable Stream) are historical — skip them.
264
- // Hydration is handled separately via session_hydration → agent.replaceMessages().
265
- //
266
- // Events that arrive before InteractiveMode is initialized are buffered
267
- // and flushed after init (InteractiveMode registers listeners during init,
268
- // so agent.emit() before that fires into the void).
269
- let interactiveModeReady = false;
270
- let eventBuffer: RpcEvent[] = [];
271
- let seenMessageStart = false;
272
- let seenAgentStart = false;
273
-
274
- // Dedup guard: some events may arrive twice via different broadcast paths
275
- // (rpc_event envelope + direct lifecycle broadcast). Track recent live events
276
- // by type+timestamp to skip duplicates.
277
- const recentEventKeys = new Set<string>();
278
- const DEDUP_WINDOW_MS = 100;
279
-
280
- // InteractiveMode adds a new assistant component on every assistant message_start.
281
- // Track active/completed remote messages so normal terminal events and late duplicates
282
- // do not spawn extra components.
283
- let assistantStreamActive = false;
284
- const recentCompletedAssistantMessageKeys: string[] = [];
285
- const completedAssistantMessageKeySet = new Set<string>();
286
-
287
- function rememberCompletedAssistantMessage(key: string): void {
288
- if (completedAssistantMessageKeySet.has(key)) return;
289
- recentCompletedAssistantMessageKeys.push(key);
290
- completedAssistantMessageKeySet.add(key);
291
- if (recentCompletedAssistantMessageKeys.length > 32) {
292
- const expired = recentCompletedAssistantMessageKeys.shift();
293
- if (expired) completedAssistantMessageKeySet.delete(expired);
294
- }
295
- }
296
-
297
- function emitRemoteUserPrompt(text: string, timestamp: number): void {
298
- const userMessage = {
299
- role: 'user' as const,
300
- content: [{ type: 'text' as const, text }],
301
- timestamp,
302
- };
303
- const syntheticEvents = [
304
- { type: 'message_start', message: userMessage },
305
- { type: 'message_end', message: userMessage },
306
- ] as RpcEvent[];
307
-
308
- if (!interactiveModeReady) {
309
- eventBuffer.push(...syntheticEvents);
310
- log('Buffered synthetic user_prompt events (InteractiveMode not ready)');
311
- return;
312
- }
313
-
314
- for (const event of syntheticEvents) {
315
- agent.emit(event);
316
- }
317
- }
318
-
319
- remote.onEvent((rpcEvent: RpcEvent) => {
320
- const source = (rpcEvent as any)._source ?? 'unknown';
321
- const isReplay =
322
- source === 'replay' ||
323
- (rpcEvent as any).replay === true ||
324
- (rpcEvent as any).isReplay === true;
325
- log(`Event received: ${rpcEvent.type} (source=${source})`);
326
-
327
- if (rpcEvent.type === 'session_resume') {
328
- sessionResumeSeen = true;
329
- log(
330
- `Session resume signaled (${typeof (rpcEvent as any).streamId === 'string' ? (rpcEvent as any).streamId : 'no stream id'})`
331
- );
332
- return;
333
- }
334
-
335
- if (rpcEvent.type === 'session_stream_ready') {
336
- log(
337
- `Durable stream ready (${typeof (rpcEvent as any).streamId === 'string' ? (rpcEvent as any).streamId : 'no stream id'})`
338
- );
339
- return;
340
- }
341
-
342
- if (rpcEvent.type === 'rpc_command_error') {
343
- const error =
344
- typeof (rpcEvent as any).error === 'string'
345
- ? (rpcEvent as any).error
346
- : 'Remote command failed';
347
- const ctx = getNativeRemoteExtensionContext();
348
- if (ctx?.hasUI) {
349
- ctx.ui.notify(error, 'warning');
350
- lifecycleOwnsWorkingMessage = clearRemoteLifecycleWorkingMessage(
351
- ctx.ui,
352
- lifecycleOwnsWorkingMessage
353
- );
354
- }
355
- agent._state.error = error;
356
- seenAgentStart = false;
357
- seenMessageStart = false;
358
- resolveRunningPrompt();
359
- assistantStreamActive = false;
360
- log(`Remote command error: ${error}`);
361
- return;
362
- }
363
-
364
- // session_hydration is handled separately below — skip it here
365
- if (rpcEvent.type === 'session_hydration') return;
366
-
367
- // Remote prompts from other controllers are broadcast as user_prompt.
368
- // Convert them to synthetic user message lifecycle events so InteractiveMode
369
- // renders them like locally-entered prompts. Replays are covered by hydration.
370
- if (rpcEvent.type === 'user_prompt') {
371
- if (isReplay) {
372
- log('Skipping replay user_prompt');
373
- return;
374
- }
375
-
376
- const promptText =
377
- typeof (rpcEvent as any).content === 'string'
378
- ? (rpcEvent as any).content
379
- : typeof (rpcEvent as any).text === 'string'
380
- ? (rpcEvent as any).text
381
- : '';
382
- if (!promptText.trim()) {
383
- log('Skipping empty user_prompt');
384
- return;
385
- }
386
-
387
- const promptTimestamp =
388
- typeof (rpcEvent as any).timestamp === 'number'
389
- ? (rpcEvent as any).timestamp
390
- : Date.now();
391
- log('Rendering live user_prompt as synthetic user message');
392
- emitRemoteUserPrompt(promptText, promptTimestamp);
393
- return;
394
- }
395
-
396
- // Skip user-role message events — the TUI already shows user messages
397
- // via InteractiveMode input or the synthetic user_prompt path above.
398
- // Pi emits message_start/end for both user and assistant messages; without
399
- // this guard the same prompt can appear twice.
400
- if (rpcEvent.type === 'message_start' || rpcEvent.type === 'message_end') {
401
- const msg = (rpcEvent as any).message;
402
- if (msg?.role === 'user') {
403
- log(`Skipping ${rpcEvent.type} (role=user) — handled locally`);
404
- return;
405
- }
406
- }
407
-
408
- // Dedup: skip if we already processed the same event type + timestamp recently
409
- // Replays still check the cache, but they never populate it.
410
- const ts = (rpcEvent as any).timestamp ?? 0;
411
- const dedupKey = `${rpcEvent.type}:${ts}`;
412
- if (recentEventKeys.has(dedupKey)) {
413
- log(`Dedup: skipping duplicate ${rpcEvent.type} (ts=${ts})`);
414
- return;
415
- }
416
- if (!isReplay && ts > 0) {
417
- recentEventKeys.add(dedupKey);
418
- setTimeout(() => recentEventKeys.delete(dedupKey), DEDUP_WINDOW_MS);
419
- }
420
-
421
- // Skip duplicate agent_start if we already emitted a synthetic one
422
- if (rpcEvent.type === 'agent_start' && syntheticAgentStartEmitted) {
423
- syntheticAgentStartEmitted = false;
424
- // Still update state from real event
425
- updateAgentState(agent, rpcEvent);
426
- return;
427
- }
428
-
429
- // Skip replay events — these are historical from Durable Stream
430
- if (isReplay) {
431
- log(`Skipping replay event: ${rpcEvent.type}`);
432
- return;
433
- }
434
-
435
- const hadSeenAgentStart = seenAgentStart;
436
- const hadSeenMessageStart = seenMessageStart;
437
- const assistantMessageKey = getRemoteAssistantMessageKey(rpcEvent);
438
- if (
439
- assistantMessageKey &&
440
- (rpcEvent.type === 'message_start' || rpcEvent.type === 'message_end') &&
441
- completedAssistantMessageKeySet.has(assistantMessageKey)
442
- ) {
443
- log(`Dedup: skipping repeated assistant ${rpcEvent.type}`);
444
- return;
445
- }
446
-
447
- // State-based dedup for assistant message streaming.
448
- // Prevents duplicate AssistantMessageComponent from being added to the DOM.
449
- if (rpcEvent.type === 'message_start') {
450
- const msg = (rpcEvent as any).message;
451
- if (msg?.role === 'assistant') {
452
- if (assistantStreamActive) {
453
- log(`Dedup: skipping duplicate assistant message_start (stream already active)`);
454
- return;
455
- }
456
- assistantStreamActive = true;
457
- }
458
- }
459
- if (rpcEvent.type === 'message_end') {
460
- const msg = (rpcEvent as any).message;
461
- if (msg?.role === 'assistant') {
462
- assistantStreamActive = false;
463
- if (assistantMessageKey) {
464
- rememberCompletedAssistantMessage(assistantMessageKey);
465
- }
466
- }
467
- }
468
- if (rpcEvent.type === 'agent_end') {
469
- assistantStreamActive = false;
470
- }
471
-
472
- // Track streaming lifecycle events so we can inject synthetics when
473
- // we attach mid-stream (controller connected after agent already started).
474
- if (rpcEvent.type === 'agent_start') seenAgentStart = true;
475
- if (rpcEvent.type === 'agent_end') {
476
- seenAgentStart = false;
477
- seenMessageStart = false;
478
- }
479
- if (rpcEvent.type === 'message_start') seenMessageStart = true;
480
- if (rpcEvent.type === 'message_end') seenMessageStart = false;
481
-
482
- // Update agent internal state (mirrors Agent._runLoop behavior)
483
- updateAgentState(agent, rpcEvent);
484
-
485
- // Buffer events until InteractiveMode is ready to receive them
486
- if (!interactiveModeReady) {
487
- eventBuffer.push(rpcEvent);
488
- log(`Buffered event: ${rpcEvent.type} (InteractiveMode not ready)`);
489
- return;
490
- }
491
-
492
- // Mid-stream attach guard: if we receive message_update or message_end
493
- // without having seen message_start, inject synthetic agent_start +
494
- // message_start so InteractiveMode sets up its streaming component.
495
- // Without this, the events are silently dropped because
496
- // InteractiveMode.streamingComponent is null.
497
- // This happens when the controller connects mid-stream or after the
498
- // agent finishes — the broadcast of agent_start/message_start occurred
499
- // before the controller WebSocket was registered.
500
- let injectedSyntheticMessageStart = false;
501
- if (
502
- (rpcEvent.type === 'message_update' || rpcEvent.type === 'message_end') &&
503
- !hadSeenMessageStart
504
- ) {
505
- log(`Live ${rpcEvent.type} without prior message_start — injecting synthetics`);
506
- if (!hadSeenAgentStart) {
507
- agent.emit({ type: 'agent_start', agentName: 'lead', timestamp: Date.now() } as any);
508
- seenAgentStart = true;
509
- }
510
- agent.emit({
511
- type: 'message_start',
512
- message: {
513
- role: 'assistant',
514
- content: [],
515
- api: 'anthropic-messages',
516
- provider: 'anthropic',
517
- model: 'remote',
518
- usage: {
519
- input: 0,
520
- output: 0,
521
- cacheRead: 0,
522
- cacheWrite: 0,
523
- totalTokens: 0,
524
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
525
- },
526
- timestamp: Date.now(),
527
- },
528
- } as any);
529
- seenMessageStart = true;
530
- assistantStreamActive = true;
531
- injectedSyntheticMessageStart = true;
532
- }
533
-
534
- // Emit to subscribers — InteractiveMode.handleEvent processes this
535
- agent.emit(rpcEvent);
536
- if (injectedSyntheticMessageStart && rpcEvent.type === 'message_end') {
537
- seenMessageStart = false;
538
- seenAgentStart = hadSeenAgentStart;
539
- assistantStreamActive = false;
540
- }
541
-
542
- // Resolve running prompt when agent finishes
543
- if (rpcEvent.type === 'agent_end') {
544
- resolveRunningPrompt();
545
- }
546
- });
547
-
548
- // ── 6. Wire up UI handlers for extension dialogs from sandbox ──
549
- remote.setUiHandler(async (request) => {
550
- const ctx =
551
- getNativeRemoteExtensionContext() ?? (await waitForNativeRemoteExtensionContext(10_000));
552
- if (!ctx) {
553
- log(
554
- `UI request: ${request.method} (${request.id}) timed out waiting for extension UI context`
555
- );
556
- return REMOTE_FIRE_AND_FORGET_UI_METHODS.has(request.method) ? undefined : null;
557
- }
558
-
559
- try {
560
- return await handleRemoteUiRequest(ctx, request);
561
- } catch (err) {
562
- log(
563
- `UI request handler error for ${request.method}: ${err instanceof Error ? err.message : String(err)}`
564
- );
565
- return REMOTE_FIRE_AND_FORGET_UI_METHODS.has(request.method) ? undefined : null;
566
- }
567
- });
568
-
569
- // ── 7. Handle hydration (initial state from Hub) ──
570
- // Hydration arrives as the message AFTER 'init' on the WebSocket.
571
- // remote.connect() resolves on 'init', so hydration arrives in the next
572
- // event loop tick. We use a promise to wait for it before creating
573
- // InteractiveMode (which calls renderInitialMessages from SessionManager).
574
- const sm = session.sessionManager;
575
- let resolveHydration: () => void;
576
- let hydrationComplete = false;
577
- const hydrationReady = new Promise<void>((resolve) => {
578
- resolveHydration = () => {
579
- if (hydrationComplete) return;
580
- hydrationComplete = true;
581
- resolve();
582
- };
583
- });
584
-
585
- let hydrationCount = 0;
586
- remote.onEvent((event: RpcEvent) => {
587
- if (event.type !== 'session_hydration') return;
588
- hydrationCount++;
589
-
590
- const entries = (event as any).entries as
591
- | Array<{
592
- type: string;
593
- content?: string | Array<{ type: string; text?: string }>;
594
- role?: string;
595
- timestamp?: number;
596
- }>
597
- | undefined;
598
-
599
- // Extract task text from hydration (Hub includes session.sandbox?.task)
600
- const hydrationTask = (event as any).task as string | undefined;
601
-
602
- // On reconnect (2nd+ hydration), clear SM to prevent duplicate accumulation.
603
- // agent.replaceMessages() already replaces state.messages, but SM only appends.
604
- if (hydrationCount > 1) {
605
- log(`Re-hydration #${hydrationCount} — clearing SessionManager to prevent duplicates`);
606
- try {
607
- if (typeof (sm as any).clear === 'function') {
608
- (sm as any).clear();
609
- }
610
- } catch (err) {
611
- log(`SM clear error (non-fatal): ${err}`);
612
- }
613
- }
614
-
615
- if (!entries?.length) {
616
- log('Received session_hydration with no entries');
617
- // Even with no entries, inject task as user message if available
618
- if (hydrationTask) {
619
- const taskMsg = {
620
- role: 'user' as const,
621
- content: [{ type: 'text' as const, text: hydrationTask }],
622
- timestamp: Date.now(),
623
- };
624
- agent.replaceMessages([taskMsg]);
625
- try {
626
- sm.appendMessage(taskMsg as any);
627
- } catch (err) {
628
- log(`SM append task error: ${err}`);
629
- }
630
- log('Injected task as user message (no entries)');
631
- }
632
- resolveHydration!();
633
- return;
634
- }
635
-
636
- log(`Hydrating ${entries.length} entries (hydration #${hydrationCount})`);
637
- const agentMessages: any[] = [];
638
-
639
- // If we have a task and no user_prompt entry, inject the task as the first user message
640
- const hasUserEntry = entries.some((e) => e.type === 'user_prompt' || e.role === 'user');
641
- if (hydrationTask && !hasUserEntry) {
642
- const taskMsg = {
643
- role: 'user' as const,
644
- content: [{ type: 'text' as const, text: hydrationTask }],
645
- timestamp: Date.now(),
646
- };
647
- agentMessages.push(taskMsg);
648
- try {
649
- sm.appendMessage(taskMsg as any);
650
- } catch (err) {
651
- log(`SM append task error: ${err}`);
652
- }
653
- log('Injected task as user message');
654
- }
655
-
656
- for (const entry of entries) {
657
- const text =
658
- typeof entry.content === 'string'
659
- ? entry.content
660
- : Array.isArray(entry.content)
661
- ? entry.content
662
- .filter(
663
- (c): c is { type: string; text: string } =>
664
- c.type === 'text' && typeof c.text === 'string'
665
- )
666
- .map((c) => c.text)
667
- .join('\n')
668
- : '';
669
-
670
- if (!text) continue;
671
-
672
- // Hub conversation entries use type: 'message' for assistant, 'thinking' for thinking,
673
- // 'task_result' for delegation results, 'turn' for turn markers, 'user_prompt' for user input.
674
- // Only 'user_prompt' entries are user messages; everything else is assistant-side.
675
- const isAssistant =
676
- entry.role === 'assistant' ||
677
- entry.type === 'message' ||
678
- entry.type === 'thinking' ||
679
- entry.type === 'task_result' ||
680
- entry.type === 'assistant';
681
- if (isAssistant) {
682
- const msg = {
683
- role: 'assistant' as const,
684
- content: [{ type: 'text' as const, text }],
685
- api: 'anthropic-messages',
686
- provider: 'anthropic',
687
- model: 'remote',
688
- usage: {
689
- input: 0,
690
- output: 0,
691
- cacheRead: 0,
692
- cacheWrite: 0,
693
- totalTokens: 0,
694
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
695
- },
696
- stopReason: 'stop',
697
- timestamp: entry.timestamp ?? Date.now(),
698
- };
699
- agentMessages.push(msg);
700
- try {
701
- sm.appendMessage(msg as any);
702
- } catch (err) {
703
- log(`SM append error: ${err}`);
704
- }
705
- } else {
706
- const msg = {
707
- role: 'user' as const,
708
- content: [{ type: 'text' as const, text }],
709
- timestamp: entry.timestamp ?? Date.now(),
710
- };
711
- agentMessages.push(msg);
712
- try {
713
- sm.appendMessage(msg as any);
714
- } catch (err) {
715
- log(`SM append error: ${err}`);
716
- }
717
- }
718
- }
719
-
720
- if (agentMessages.length > 0) {
721
- agent.replaceMessages(agentMessages);
722
- log(`Hydrated ${agentMessages.length} agent messages (+ session manager)`);
723
- } else {
724
- log('Hydration: 0 messages after filtering (all entries had empty text?)');
725
- }
726
-
727
- // Restore streaming state from hydration — fixes first-connect miss
728
- const streamingState = (event as any).streamingState as
729
- | {
730
- isStreaming?: boolean;
731
- activeTasks?: Array<{ taskId: string; agent: string }>;
732
- }
733
- | undefined;
734
-
735
- if (streamingState?.isStreaming) {
736
- agent._state.isStreaming = true;
737
- hydrationStreamingDetected = true;
738
- // Create runningPrompt so InteractiveMode knows we're busy
739
- if (!agent.runningPrompt) {
740
- const runPromise = new Promise<void>((resolve) => {
741
- runningPromptResolve = resolve;
742
- });
743
- agent.runningPrompt = runPromise;
744
- }
745
- log(
746
- `Hydration: session is streaming with ${streamingState.activeTasks?.length ?? 0} active tasks`
747
- );
748
- }
749
-
750
- resolveHydration!();
751
- });
752
-
753
- // ── 8. NOW connect to Hub ──
754
- // All handlers are registered, so hydration + replay events will be captured.
755
- log('Connecting to Hub (handlers registered)...');
756
- await remote.connect(hubWsUrl);
757
- log('Connected to Hub as controller');
758
-
759
- // Wait for hydration message (arrives right after init), with a timeout
760
- // in case this is the first connection and there's nothing to hydrate.
761
- await Promise.race([
762
- hydrationReady,
763
- new Promise<void>((resolve) => {
764
- const waitStartedAt = Date.now();
765
- const poll = (): void => {
766
- if (hydrationComplete) {
767
- resolve();
768
- return;
769
- }
770
- const timeoutMs = sessionResumeSeen ? 5000 : 2000;
771
- if (Date.now() - waitStartedAt >= timeoutMs) {
772
- log('Hydration timeout — no session_hydration received');
773
- resolve();
774
- return;
775
- }
776
- setTimeout(poll, 50);
777
- };
778
- poll();
779
- }),
780
- ]);
781
- const smEntries = sm.getEntries?.() ?? [];
782
- log(`SessionManager has ${smEntries.length} entries after hydration`);
783
- log(`Post-hydration: SM has ${smEntries.length} entries, leafId=${sm.getLeafId?.() ?? 'N/A'}`);
784
-
785
- // ── 9. Start InteractiveMode — full native Pi TUI ──
786
- log('Creating InteractiveMode');
787
- const interactive = new InteractiveMode(session);
788
- log('InteractiveMode created, calling init...');
789
- await interactive.init();
790
-
791
- // Flush buffered events now that InteractiveMode is listening.
792
- // If the session was already streaming when we connected (mid-stream attach),
793
- // InteractiveMode needs agent_start + message_start to set up its streaming
794
- // components. Without these, message_update events are silently dropped
795
- // because InteractiveMode.streamingComponent is null.
796
- interactiveModeReady = true;
797
-
798
- if (hydrationStreamingDetected) {
799
- // Immediately emit agent_start + message_start so InteractiveMode shows
800
- // the streaming indicator right away, before any buffered events flush.
801
- // This prevents the blank screen gap between connect and first event.
802
- log('Hydration detected streaming — emitting immediate synthetics');
803
- agent.emit({ type: 'agent_start', agentName: 'lead', timestamp: Date.now() } as any);
804
- agent.emit({
805
- type: 'message_start',
806
- message: {
807
- role: 'assistant',
808
- content: [],
809
- api: 'anthropic-messages',
810
- provider: 'anthropic',
811
- model: 'remote',
812
- usage: {
813
- input: 0,
814
- output: 0,
815
- cacheRead: 0,
816
- cacheWrite: 0,
817
- totalTokens: 0,
818
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
819
- },
820
- timestamp: Date.now(),
821
- },
822
- } as any);
823
- seenAgentStart = true;
824
- seenMessageStart = true;
825
- assistantStreamActive = true;
826
-
827
- // Remove any agent_start/message_start from buffer since we already emitted them
828
- eventBuffer = eventBuffer.filter(
829
- (e) => e.type !== 'agent_start' && e.type !== 'message_start'
830
- );
831
- }
832
-
833
- if (eventBuffer.length > 0) {
834
- log(`Flushing ${eventBuffer.length} events: ${eventBuffer.map((e) => e.type).join(', ')}`);
835
- for (const buffered of eventBuffer) {
836
- agent.emit(buffered);
837
- if (buffered.type === 'agent_end') {
838
- resolveRunningPrompt();
839
- }
840
- }
841
- }
842
- eventBuffer = [];
843
-
844
- log('InteractiveMode initialized, calling run...');
845
-
846
- // Handle clean shutdown
847
- const cleanup = () => {
848
- remote.close();
849
- setNativeRemoteExtensionContext(null);
850
- interactive.stop();
851
- };
852
- process.on('SIGINT', cleanup);
853
- process.on('SIGTERM', cleanup);
854
-
855
- try {
856
- await interactive.run();
857
- } catch (err) {
858
- log(`InteractiveMode.run() threw: ${err instanceof Error ? err.stack : String(err)}`);
859
- throw err;
860
- } finally {
861
- remote.close();
862
- setNativeRemoteExtensionContext(null);
863
- log('Remote TUI exited');
864
- }
865
-
866
- // ── Helper: resolve the running prompt promise ──
867
- function resolveRunningPrompt(): void {
868
- syntheticAgentStartEmitted = false;
869
- agent._state.isStreaming = false;
870
- agent._state.streamMessage = null;
871
- agent._state.pendingToolCalls = new Set();
872
- if (runningPromptResolve) {
873
- runningPromptResolve();
874
- runningPromptResolve = null;
875
- agent.runningPrompt = undefined;
876
- }
877
- }
878
- }
879
-
880
- // ══════════════════════════════════════════════
881
- // Agent state synchronization
882
- // Mirrors Agent._runLoop state updates (agent.js lines 317-352)
883
- // ══════════════════════════════════════════════
884
-
885
- function updateAgentState(agent: any, event: RpcEvent): void {
886
- const state = agent._state;
887
-
888
- switch (event.type) {
889
- case 'agent_start':
890
- state.isStreaming = true;
891
- break;
892
-
893
- case 'agent_end':
894
- state.isStreaming = false;
895
- state.streamMessage = null;
896
- state.pendingToolCalls = new Set();
897
- break;
898
-
899
- case 'message_start':
900
- state.streamMessage = (event as any).message;
901
- state.isStreaming = true;
902
- break;
903
-
904
- case 'message_update':
905
- state.streamMessage = (event as any).message;
906
- break;
907
-
908
- case 'message_end':
909
- state.streamMessage = null;
910
- // NOTE: Do NOT push to state.messages here.
911
- // AgentSession._handleAgentEvent already persists via sessionManager.appendMessage().
912
- // Pushing here causes state.messages to accumulate duplicates with SM,
913
- // leading to visual duplicates if rebuildChatFromMessages() is ever triggered.
914
- break;
915
-
916
- case 'tool_execution_start': {
917
- const s = new Set(state.pendingToolCalls);
918
- s.add((event as any).toolCallId);
919
- state.pendingToolCalls = s;
920
- break;
921
- }
922
-
923
- case 'tool_execution_end': {
924
- const s = new Set(state.pendingToolCalls);
925
- s.delete((event as any).toolCallId);
926
- state.pendingToolCalls = s;
927
- break;
928
- }
929
-
930
- case 'thinking_start':
931
- state.isStreaming = true;
932
- break;
933
-
934
- case 'thinking_end':
935
- break;
936
-
937
- case 'tool_call':
938
- state.isStreaming = true;
939
- break;
940
-
941
- case 'tool_result':
942
- break;
943
-
944
- case 'task_start':
945
- state.isStreaming = true;
946
- break;
947
-
948
- case 'task_complete':
949
- case 'task_error':
950
- break;
951
-
952
- case 'turn_end': {
953
- const msg = (event as any).message;
954
- if (msg?.role === 'assistant' && msg?.errorMessage) {
955
- state.error = msg.errorMessage;
956
- }
957
- break;
958
- }
959
- }
960
- }
961
-
962
- // ══════════════════════════════════════════════
963
- // Text extraction helpers
964
- // ══════════════════════════════════════════════
965
-
966
- function extractPromptText(input: any): string {
967
- if (typeof input === 'string') return input;
968
-
969
- if (Array.isArray(input)) {
970
- return input.map(extractMessageText).filter(Boolean).join('\n');
971
- }
972
-
973
- return extractMessageText(input);
974
- }
975
-
976
- function extractMessageText(msg: any): string {
977
- if (typeof msg === 'string') return msg;
978
- if (!msg || typeof msg !== 'object') return '';
979
-
980
- if (typeof msg.content === 'string') return msg.content;
981
-
982
- if (Array.isArray(msg.content)) {
983
- return msg.content
984
- .filter((c: any) => c?.type === 'text' && typeof c.text === 'string')
985
- .map((c: any) => c.text)
986
- .join('\n');
987
- }
988
-
989
- return '';
990
- }
991
-
992
- function getRemoteAssistantMessageKey(event: RpcEvent): string | undefined {
993
- if (event.type !== 'message_start' && event.type !== 'message_end') return undefined;
994
-
995
- const message = (event as any).message;
996
- if (!message || typeof message !== 'object' || message.role !== 'assistant') {
997
- return undefined;
998
- }
999
-
1000
- const messageId = typeof message.id === 'string' ? message.id : '';
1001
- if (messageId) return `id:${messageId}`;
1002
-
1003
- const timestamp =
1004
- typeof message.timestamp === 'number'
1005
- ? String(message.timestamp)
1006
- : typeof message.timestamp === 'string'
1007
- ? message.timestamp
1008
- : typeof (event as any).timestamp === 'number'
1009
- ? String((event as any).timestamp)
1010
- : typeof (event as any).timestamp === 'string'
1011
- ? (event as any).timestamp
1012
- : '';
1013
- if (timestamp) return `ts:${timestamp}`;
1014
-
1015
- const text = extractMessageText(message);
1016
- if (!text) return undefined;
1017
-
1018
- const stopReason = typeof message.stopReason === 'string' ? message.stopReason : '';
1019
- return `text:${stopReason}|${text}`;
1020
- }