@agentuity/coder-tui 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.
- package/README.md +57 -0
- package/dist/chain-preview.d.ts +55 -0
- package/dist/chain-preview.d.ts.map +1 -0
- package/dist/chain-preview.js +472 -0
- package/dist/chain-preview.js.map +1 -0
- package/dist/client.d.ts +44 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +411 -0
- package/dist/client.js.map +1 -0
- package/dist/commands.d.ts +22 -0
- package/dist/commands.d.ts.map +1 -0
- package/dist/commands.js +99 -0
- package/dist/commands.js.map +1 -0
- package/dist/footer.d.ts +34 -0
- package/dist/footer.d.ts.map +1 -0
- package/dist/footer.js +249 -0
- package/dist/footer.js.map +1 -0
- package/dist/handlers.d.ts +24 -0
- package/dist/handlers.d.ts.map +1 -0
- package/dist/handlers.js +83 -0
- package/dist/handlers.js.map +1 -0
- package/dist/hub-overlay-state.d.ts +31 -0
- package/dist/hub-overlay-state.d.ts.map +1 -0
- package/dist/hub-overlay-state.js +78 -0
- package/dist/hub-overlay-state.js.map +1 -0
- package/dist/hub-overlay.d.ts +146 -0
- package/dist/hub-overlay.d.ts.map +1 -0
- package/dist/hub-overlay.js +2354 -0
- package/dist/hub-overlay.js.map +1 -0
- package/dist/inbound-rpc.d.ts +3 -0
- package/dist/inbound-rpc.d.ts.map +1 -0
- package/dist/inbound-rpc.js +29 -0
- package/dist/inbound-rpc.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1641 -0
- package/dist/index.js.map +1 -0
- package/dist/native-remote-ui-context.d.ts +5 -0
- package/dist/native-remote-ui-context.d.ts.map +1 -0
- package/dist/native-remote-ui-context.js +30 -0
- package/dist/native-remote-ui-context.js.map +1 -0
- package/dist/output-viewer.d.ts +49 -0
- package/dist/output-viewer.d.ts.map +1 -0
- package/dist/output-viewer.js +389 -0
- package/dist/output-viewer.js.map +1 -0
- package/dist/overlay.d.ts +40 -0
- package/dist/overlay.d.ts.map +1 -0
- package/dist/overlay.js +225 -0
- package/dist/overlay.js.map +1 -0
- package/dist/protocol.d.ts +605 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +4 -0
- package/dist/protocol.js.map +1 -0
- package/dist/remote-lifecycle.d.ts +61 -0
- package/dist/remote-lifecycle.d.ts.map +1 -0
- package/dist/remote-lifecycle.js +190 -0
- package/dist/remote-lifecycle.js.map +1 -0
- package/dist/remote-session.d.ts +130 -0
- package/dist/remote-session.d.ts.map +1 -0
- package/dist/remote-session.js +896 -0
- package/dist/remote-session.js.map +1 -0
- package/dist/remote-tui.d.ts +42 -0
- package/dist/remote-tui.d.ts.map +1 -0
- package/dist/remote-tui.js +868 -0
- package/dist/remote-tui.js.map +1 -0
- package/dist/remote-ui-handler.d.ts +5 -0
- package/dist/remote-ui-handler.d.ts.map +1 -0
- package/dist/remote-ui-handler.js +53 -0
- package/dist/remote-ui-handler.js.map +1 -0
- package/dist/renderers.d.ts +34 -0
- package/dist/renderers.d.ts.map +1 -0
- package/dist/renderers.js +669 -0
- package/dist/renderers.js.map +1 -0
- package/dist/review.d.ts +15 -0
- package/dist/review.d.ts.map +1 -0
- package/dist/review.js +154 -0
- package/dist/review.js.map +1 -0
- package/dist/titlebar.d.ts +3 -0
- package/dist/titlebar.d.ts.map +1 -0
- package/dist/titlebar.js +59 -0
- package/dist/titlebar.js.map +1 -0
- package/dist/todo/index.d.ts +3 -0
- package/dist/todo/index.d.ts.map +1 -0
- package/dist/todo/index.js +3 -0
- package/dist/todo/index.js.map +1 -0
- package/dist/todo/store.d.ts +6 -0
- package/dist/todo/store.d.ts.map +1 -0
- package/dist/todo/store.js +43 -0
- package/dist/todo/store.js.map +1 -0
- package/dist/todo/types.d.ts +13 -0
- package/dist/todo/types.d.ts.map +1 -0
- package/dist/todo/types.js +2 -0
- package/dist/todo/types.js.map +1 -0
- package/package.json +42 -0
- package/src/chain-preview.ts +621 -0
- package/src/client.ts +527 -0
- package/src/commands.ts +132 -0
- package/src/footer.ts +305 -0
- package/src/handlers.ts +113 -0
- package/src/hub-overlay-state.ts +127 -0
- package/src/hub-overlay.ts +3037 -0
- package/src/inbound-rpc.ts +35 -0
- package/src/index.ts +1963 -0
- package/src/native-remote-ui-context.ts +41 -0
- package/src/output-viewer.ts +480 -0
- package/src/overlay.ts +294 -0
- package/src/protocol.ts +758 -0
- package/src/remote-lifecycle.ts +270 -0
- package/src/remote-session.ts +1100 -0
- package/src/remote-tui.ts +1023 -0
- package/src/remote-ui-handler.ts +86 -0
- package/src/renderers.ts +740 -0
- package/src/review.ts +201 -0
- package/src/titlebar.ts +63 -0
- package/src/todo/index.ts +2 -0
- package/src/todo/store.ts +49 -0
- package/src/todo/types.ts +14 -0
|
@@ -0,0 +1,896 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote Session Bridge — TUI ↔ Hub ↔ Sandbox
|
|
3
|
+
*
|
|
4
|
+
* Handles the WebSocket connection and RPC protocol bridge for remote mode.
|
|
5
|
+
* In remote mode, the local Pi TUI connects to an existing sandbox session
|
|
6
|
+
* through the Hub, acting as a thin client:
|
|
7
|
+
* - User input → rpc_command → Hub → sandbox
|
|
8
|
+
* - Sandbox events → rpc_event → Hub → TUI rendering
|
|
9
|
+
* - Extension UI dialogs → rpc_ui_request/response → Hub ↔ TUI
|
|
10
|
+
*
|
|
11
|
+
* This module manages the connection lifecycle and provides an API
|
|
12
|
+
* for the extension to send commands and receive events.
|
|
13
|
+
*/
|
|
14
|
+
import { applyRemoteLifecycleEvent, clearRemoteLifecycleWorkingMessage, createRemoteLifecycleState, getRemoteLifecycleActivityLabel, getRemoteLifecycleLabel, syncRemoteLifecycleWorkingMessage, } from "./remote-lifecycle.js";
|
|
15
|
+
const DEBUG = !!process.env['AGENTUITY_DEBUG'];
|
|
16
|
+
function log(msg) {
|
|
17
|
+
if (DEBUG)
|
|
18
|
+
console.error(`[remote-session] ${msg}`);
|
|
19
|
+
}
|
|
20
|
+
// ── Remote Session Client ──
|
|
21
|
+
const RECONNECT_BASE_MS = 1_000;
|
|
22
|
+
const RECONNECT_MAX_MS = 30_000;
|
|
23
|
+
const MAX_RECONNECT_ATTEMPTS = 20;
|
|
24
|
+
export class RemoteSession {
|
|
25
|
+
ws = null;
|
|
26
|
+
connected = false;
|
|
27
|
+
intentionallyClosed = false;
|
|
28
|
+
hubWsUrl = '';
|
|
29
|
+
reconnectAttempts = 0;
|
|
30
|
+
reconnectTimer = null;
|
|
31
|
+
eventHandlers = [];
|
|
32
|
+
uiHandler = null;
|
|
33
|
+
responseHandlers = [];
|
|
34
|
+
connectionHandlers = [];
|
|
35
|
+
lifecycleHandlers = [];
|
|
36
|
+
lifecycleState;
|
|
37
|
+
replaySettledTimer = null;
|
|
38
|
+
/** Session ID this client is connected to */
|
|
39
|
+
sessionId;
|
|
40
|
+
/** Session label (populated after connection) */
|
|
41
|
+
label = '';
|
|
42
|
+
/** API key for Hub authentication (Hub API key or CLI/platform key) */
|
|
43
|
+
apiKey = null;
|
|
44
|
+
/** Organization ID for CLI/platform key auth (sent as x-agentuity-orgid header) */
|
|
45
|
+
orgId = null;
|
|
46
|
+
constructor(sessionId) {
|
|
47
|
+
this.sessionId = sessionId;
|
|
48
|
+
this.lifecycleState = createRemoteLifecycleState(sessionId);
|
|
49
|
+
}
|
|
50
|
+
dispatchEvent(event) {
|
|
51
|
+
for (const handler of this.eventHandlers) {
|
|
52
|
+
try {
|
|
53
|
+
handler(event);
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
log(`Event handler error: ${err instanceof Error ? err.message : String(err)}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
dispatchResponse(response) {
|
|
61
|
+
for (const handler of this.responseHandlers) {
|
|
62
|
+
try {
|
|
63
|
+
handler(response);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
log(`Response handler error: ${err instanceof Error ? err.message : String(err)}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
applyLifecycle(event) {
|
|
71
|
+
const next = applyRemoteLifecycleEvent(this.lifecycleState, event);
|
|
72
|
+
if (next === this.lifecycleState)
|
|
73
|
+
return;
|
|
74
|
+
this.lifecycleState = next;
|
|
75
|
+
for (const handler of this.lifecycleHandlers) {
|
|
76
|
+
try {
|
|
77
|
+
handler(this.lifecycleState);
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
log(`Lifecycle handler error: ${err instanceof Error ? err.message : String(err)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
clearReplaySettledTimer() {
|
|
85
|
+
if (!this.replaySettledTimer)
|
|
86
|
+
return;
|
|
87
|
+
clearTimeout(this.replaySettledTimer);
|
|
88
|
+
this.replaySettledTimer = null;
|
|
89
|
+
}
|
|
90
|
+
scheduleReplaySettled() {
|
|
91
|
+
this.clearReplaySettledTimer();
|
|
92
|
+
this.replaySettledTimer = setTimeout(() => {
|
|
93
|
+
this.replaySettledTimer = null;
|
|
94
|
+
this.applyLifecycle({ type: 'replay_idle' });
|
|
95
|
+
}, 400);
|
|
96
|
+
}
|
|
97
|
+
observeLiveSignal(eventType, isStreaming) {
|
|
98
|
+
const liveEvents = new Set([
|
|
99
|
+
'agent_start',
|
|
100
|
+
'agent_end',
|
|
101
|
+
'message_start',
|
|
102
|
+
'message_update',
|
|
103
|
+
'message_end',
|
|
104
|
+
'thinking_start',
|
|
105
|
+
'thinking_update',
|
|
106
|
+
'thinking_end',
|
|
107
|
+
'tool_call',
|
|
108
|
+
'tool_result',
|
|
109
|
+
'tool_execution_start',
|
|
110
|
+
'tool_execution_end',
|
|
111
|
+
'task_start',
|
|
112
|
+
'task_complete',
|
|
113
|
+
'task_error',
|
|
114
|
+
'turn_start',
|
|
115
|
+
'turn_end',
|
|
116
|
+
'rpc_response',
|
|
117
|
+
'rpc_ui_request',
|
|
118
|
+
]);
|
|
119
|
+
if (!liveEvents.has(eventType))
|
|
120
|
+
return;
|
|
121
|
+
this.clearReplaySettledTimer();
|
|
122
|
+
this.applyLifecycle({ type: 'live_signal', isStreaming });
|
|
123
|
+
}
|
|
124
|
+
getLiveSignalStreamingState(eventType) {
|
|
125
|
+
if (eventType === 'agent_start' ||
|
|
126
|
+
eventType === 'message_start' ||
|
|
127
|
+
eventType === 'message_update' ||
|
|
128
|
+
eventType === 'thinking_start' ||
|
|
129
|
+
eventType === 'thinking_update' ||
|
|
130
|
+
eventType === 'tool_execution_start' ||
|
|
131
|
+
eventType === 'turn_start' ||
|
|
132
|
+
eventType === 'task_start') {
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
if (eventType === 'agent_end' || eventType === 'turn_end') {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
shouldMarkResuming(commandType) {
|
|
141
|
+
return commandType === 'prompt' || commandType === 'follow_up' || commandType === 'steer';
|
|
142
|
+
}
|
|
143
|
+
shouldObserveRpcResponseAsLive() {
|
|
144
|
+
return this.lifecycleState.phase !== 'paused' && this.lifecycleState.phase !== 'replaying';
|
|
145
|
+
}
|
|
146
|
+
/** Register a handler for RPC events from the sandbox */
|
|
147
|
+
onEvent(handler) {
|
|
148
|
+
this.eventHandlers.push(handler);
|
|
149
|
+
}
|
|
150
|
+
/** Register a handler for RPC responses from the sandbox */
|
|
151
|
+
onResponse(handler) {
|
|
152
|
+
this.responseHandlers.push(handler);
|
|
153
|
+
}
|
|
154
|
+
/** Register the UI dialog handler (select, confirm, input, editor) */
|
|
155
|
+
setUiHandler(handler) {
|
|
156
|
+
this.uiHandler = handler;
|
|
157
|
+
}
|
|
158
|
+
/** Register a connection state change handler */
|
|
159
|
+
onConnectionChange(handler) {
|
|
160
|
+
this.connectionHandlers.push(handler);
|
|
161
|
+
}
|
|
162
|
+
/** Register a lifecycle state handler for remote attach/replay/live transitions. */
|
|
163
|
+
onLifecycleChange(handler) {
|
|
164
|
+
this.lifecycleHandlers.push(handler);
|
|
165
|
+
handler(this.lifecycleState);
|
|
166
|
+
}
|
|
167
|
+
getLifecycleState() {
|
|
168
|
+
return this.lifecycleState;
|
|
169
|
+
}
|
|
170
|
+
/** Connect to the Hub WebSocket as a controller for the remote session */
|
|
171
|
+
async connect(hubWsUrl) {
|
|
172
|
+
this.hubWsUrl = hubWsUrl;
|
|
173
|
+
this.intentionallyClosed = false;
|
|
174
|
+
this.reconnectAttempts = 0;
|
|
175
|
+
return this.doConnect();
|
|
176
|
+
}
|
|
177
|
+
doConnect() {
|
|
178
|
+
return new Promise((resolve, reject) => {
|
|
179
|
+
const isReconnect = this.reconnectAttempts > 0;
|
|
180
|
+
this.applyLifecycle({ type: 'connect_start', reconnect: isReconnect });
|
|
181
|
+
// Build URL with controller params + auth query params
|
|
182
|
+
// Auth is sent as both headers AND query params because WebSocket
|
|
183
|
+
// upgrade requests may not reliably forward custom headers across
|
|
184
|
+
// all runtimes and proxies.
|
|
185
|
+
const url = new URL(this.hubWsUrl);
|
|
186
|
+
url.searchParams.set('sessionId', this.sessionId);
|
|
187
|
+
url.searchParams.set('role', 'controller');
|
|
188
|
+
const wsHeaders = {};
|
|
189
|
+
if (this.apiKey) {
|
|
190
|
+
// Send auth as query param (reliable across all runtimes)
|
|
191
|
+
url.searchParams.set('token', this.apiKey);
|
|
192
|
+
if (this.apiKey.startsWith('agc_')) {
|
|
193
|
+
// Hub API key — also send as header for backward compat
|
|
194
|
+
wsHeaders['x-agentuity-auth-api-key'] = this.apiKey;
|
|
195
|
+
url.searchParams.set('apiKey', this.apiKey);
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
// CLI/platform key — also send as header for backward compat
|
|
199
|
+
wsHeaders['Authorization'] = `Bearer ${this.apiKey}`;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (this.orgId) {
|
|
203
|
+
url.searchParams.set('orgId', this.orgId);
|
|
204
|
+
wsHeaders['x-agentuity-orgid'] = this.orgId;
|
|
205
|
+
}
|
|
206
|
+
log(`${isReconnect ? 'Reconnecting' : 'Connecting'} to ${url.toString()}`);
|
|
207
|
+
this.ws =
|
|
208
|
+
Object.keys(wsHeaders).length > 0
|
|
209
|
+
? new WebSocket(url.toString(), { headers: wsHeaders })
|
|
210
|
+
: new WebSocket(url.toString());
|
|
211
|
+
const connectTimeout = setTimeout(() => {
|
|
212
|
+
reject(new Error('Remote session connection timed out'));
|
|
213
|
+
this.ws?.close();
|
|
214
|
+
}, 30_000);
|
|
215
|
+
this.ws.onopen = () => {
|
|
216
|
+
log('WebSocket connected');
|
|
217
|
+
};
|
|
218
|
+
this.ws.onmessage = (event) => {
|
|
219
|
+
let data;
|
|
220
|
+
try {
|
|
221
|
+
const raw = typeof event.data === 'string'
|
|
222
|
+
? event.data
|
|
223
|
+
: new TextDecoder().decode(event.data);
|
|
224
|
+
data = JSON.parse(raw);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const type = data.type;
|
|
230
|
+
// Init message — connection established
|
|
231
|
+
if (type === 'init') {
|
|
232
|
+
clearTimeout(connectTimeout);
|
|
233
|
+
this.connected = true;
|
|
234
|
+
this.reconnectAttempts = 0;
|
|
235
|
+
if (data.sessionId)
|
|
236
|
+
this.sessionId = data.sessionId;
|
|
237
|
+
if (typeof data.label === 'string')
|
|
238
|
+
this.label = data.label;
|
|
239
|
+
this.applyLifecycle({
|
|
240
|
+
type: 'init',
|
|
241
|
+
sessionId: typeof data.sessionId === 'string' ? data.sessionId : undefined,
|
|
242
|
+
label: typeof data.label === 'string' ? data.label : undefined,
|
|
243
|
+
});
|
|
244
|
+
try {
|
|
245
|
+
this.ws?.send(JSON.stringify({ type: 'bootstrap_ready' }));
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
// Let the close/error path surface bootstrap failure.
|
|
249
|
+
}
|
|
250
|
+
log(`Connected to session ${this.sessionId}`);
|
|
251
|
+
this.notifyConnectionChange('connected');
|
|
252
|
+
resolve();
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
// Connection rejected
|
|
256
|
+
if (type === 'connection_rejected') {
|
|
257
|
+
clearTimeout(connectTimeout);
|
|
258
|
+
const msg = data.message || 'Connection rejected';
|
|
259
|
+
this.applyLifecycle({
|
|
260
|
+
type: 'rpc_command_error',
|
|
261
|
+
error: msg,
|
|
262
|
+
paused: false,
|
|
263
|
+
});
|
|
264
|
+
reject(new Error(msg));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (type === 'protocol_error') {
|
|
268
|
+
clearTimeout(connectTimeout);
|
|
269
|
+
const msg = data.message || 'Hub protocol error';
|
|
270
|
+
this.applyLifecycle({
|
|
271
|
+
type: 'rpc_command_error',
|
|
272
|
+
error: msg,
|
|
273
|
+
paused: false,
|
|
274
|
+
});
|
|
275
|
+
this.dispatchEvent({
|
|
276
|
+
type: 'protocol_error',
|
|
277
|
+
...data,
|
|
278
|
+
_source: 'hub',
|
|
279
|
+
});
|
|
280
|
+
if (!this.connected) {
|
|
281
|
+
reject(new Error(msg));
|
|
282
|
+
}
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (type === 'session_resume') {
|
|
286
|
+
this.applyLifecycle({
|
|
287
|
+
type: 'session_resume',
|
|
288
|
+
streamId: typeof data.streamId === 'string' ? data.streamId : null,
|
|
289
|
+
streamUrl: typeof data.streamUrl === 'string' ? data.streamUrl : null,
|
|
290
|
+
});
|
|
291
|
+
this.dispatchEvent({
|
|
292
|
+
type: 'session_resume',
|
|
293
|
+
...data,
|
|
294
|
+
_source: 'hub',
|
|
295
|
+
});
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (type === 'session_stream_ready') {
|
|
299
|
+
this.applyLifecycle({
|
|
300
|
+
type: 'stream_ready',
|
|
301
|
+
streamId: typeof data.streamId === 'string' ? data.streamId : null,
|
|
302
|
+
streamUrl: typeof data.streamUrl === 'string' ? data.streamUrl : null,
|
|
303
|
+
});
|
|
304
|
+
this.dispatchEvent({
|
|
305
|
+
type: 'session_stream_ready',
|
|
306
|
+
...data,
|
|
307
|
+
_source: 'hub',
|
|
308
|
+
});
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (type === 'rpc_command_error') {
|
|
312
|
+
const error = typeof data.error === 'string' ? data.error : 'Remote command failed';
|
|
313
|
+
this.applyLifecycle({
|
|
314
|
+
type: 'rpc_command_error',
|
|
315
|
+
error,
|
|
316
|
+
paused: /sandbox .*not connected|resume/i.test(error),
|
|
317
|
+
});
|
|
318
|
+
this.dispatchEvent({
|
|
319
|
+
type: 'rpc_command_error',
|
|
320
|
+
...data,
|
|
321
|
+
_source: 'hub',
|
|
322
|
+
});
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
// Broadcast-wrapped messages from Hub (LIVE events)
|
|
326
|
+
// Format: { type: 'broadcast', event: '<name>', data: { ...payload } }
|
|
327
|
+
if (type === 'broadcast') {
|
|
328
|
+
const broadcastEvent = data.event;
|
|
329
|
+
const broadcastData = data.data ?? {};
|
|
330
|
+
if (broadcastEvent === 'rpc_event') {
|
|
331
|
+
const rpcEvent = broadcastData.event;
|
|
332
|
+
if (rpcEvent) {
|
|
333
|
+
this.observeLiveSignal(rpcEvent.type, this.getLiveSignalStreamingState(rpcEvent.type));
|
|
334
|
+
this.dispatchEvent({ ...rpcEvent, _source: 'live' });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
else if (broadcastEvent === 'rpc_response') {
|
|
338
|
+
const response = broadcastData.response;
|
|
339
|
+
if (response) {
|
|
340
|
+
if (this.shouldObserveRpcResponseAsLive()) {
|
|
341
|
+
this.observeLiveSignal('rpc_response');
|
|
342
|
+
}
|
|
343
|
+
this.dispatchResponse(response);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
else if (broadcastEvent === 'rpc_ui_request') {
|
|
347
|
+
this.observeLiveSignal('rpc_ui_request');
|
|
348
|
+
this.handleUiRequest({
|
|
349
|
+
id: broadcastData.id,
|
|
350
|
+
method: broadcastData.method,
|
|
351
|
+
params: broadcastData.params ?? {},
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
else {
|
|
355
|
+
// Lifecycle event broadcasts (agent_start, message_end, turn_start, etc.)
|
|
356
|
+
// The broadcastData IS the event payload with a `type` field matching broadcastEvent.
|
|
357
|
+
// Dispatch as a regular event so the TUI can render agent activity.
|
|
358
|
+
this.observeLiveSignal(broadcastEvent, this.getLiveSignalStreamingState(broadcastEvent));
|
|
359
|
+
this.dispatchEvent({
|
|
360
|
+
type: broadcastEvent,
|
|
361
|
+
...broadcastData,
|
|
362
|
+
_source: 'live',
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
// Legacy/raw RPC messages — tolerated but not expected on the controller path.
|
|
368
|
+
if (type === 'rpc_event') {
|
|
369
|
+
const rpcEvent = data.event;
|
|
370
|
+
if (rpcEvent) {
|
|
371
|
+
this.applyLifecycle({ type: 'replay_event' });
|
|
372
|
+
this.scheduleReplaySettled();
|
|
373
|
+
this.dispatchEvent({ ...rpcEvent, _source: 'replay' });
|
|
374
|
+
}
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (type === 'rpc_response') {
|
|
378
|
+
const response = data.response;
|
|
379
|
+
if (response) {
|
|
380
|
+
if (this.shouldObserveRpcResponseAsLive()) {
|
|
381
|
+
this.observeLiveSignal('rpc_response');
|
|
382
|
+
}
|
|
383
|
+
this.dispatchResponse(response);
|
|
384
|
+
}
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (type === 'rpc_ui_request') {
|
|
388
|
+
this.observeLiveSignal('rpc_ui_request');
|
|
389
|
+
this.handleUiRequest({
|
|
390
|
+
id: data.id,
|
|
391
|
+
method: data.method,
|
|
392
|
+
params: data.params ?? {},
|
|
393
|
+
});
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
// Session hydration (conversation entries + task states from observer hydration)
|
|
397
|
+
if (type === 'session_hydration') {
|
|
398
|
+
this.applyLifecycle({
|
|
399
|
+
type: 'hydration',
|
|
400
|
+
leadConnected: typeof data.leadConnected === 'boolean' ? data.leadConnected : undefined,
|
|
401
|
+
isStreaming: typeof data.streamingState
|
|
402
|
+
?.isStreaming === 'boolean'
|
|
403
|
+
? Boolean(data.streamingState.isStreaming)
|
|
404
|
+
: undefined,
|
|
405
|
+
});
|
|
406
|
+
// Pass through as an event so the extension can render it
|
|
407
|
+
for (const handler of this.eventHandlers) {
|
|
408
|
+
try {
|
|
409
|
+
handler({ type: 'session_hydration', ...data });
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
log(`Hydration handler error: ${err instanceof Error ? err.message : String(err)}`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
log(`Unhandled message type: ${type}`);
|
|
418
|
+
};
|
|
419
|
+
this.ws.onerror = (err) => {
|
|
420
|
+
clearTimeout(connectTimeout);
|
|
421
|
+
if (!this.connected) {
|
|
422
|
+
const message = 'message' in err ? err.message : 'WebSocket error';
|
|
423
|
+
reject(new Error(message));
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
this.ws.onclose = () => {
|
|
427
|
+
clearTimeout(connectTimeout);
|
|
428
|
+
const wasConnected = this.connected;
|
|
429
|
+
this.connected = false;
|
|
430
|
+
this.clearReplaySettledTimer();
|
|
431
|
+
if (!this.intentionallyClosed) {
|
|
432
|
+
if (wasConnected) {
|
|
433
|
+
log('WebSocket closed unexpectedly — scheduling reconnect');
|
|
434
|
+
this.notifyConnectionChange('reconnecting');
|
|
435
|
+
this.applyLifecycle({ type: 'connection_change', state: 'reconnecting' });
|
|
436
|
+
this.scheduleReconnect();
|
|
437
|
+
}
|
|
438
|
+
else if (!isReconnect) {
|
|
439
|
+
// Failed initial connect and not already in reconnect loop
|
|
440
|
+
log('WebSocket closed during initial connect');
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
scheduleReconnect() {
|
|
447
|
+
if (this.intentionallyClosed)
|
|
448
|
+
return;
|
|
449
|
+
if (this.reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
|
450
|
+
log(`Max reconnect attempts (${MAX_RECONNECT_ATTEMPTS}) reached — giving up`);
|
|
451
|
+
this.notifyConnectionChange('disconnected');
|
|
452
|
+
this.applyLifecycle({ type: 'connection_change', state: 'disconnected' });
|
|
453
|
+
return;
|
|
454
|
+
}
|
|
455
|
+
const delay = Math.min(RECONNECT_BASE_MS * Math.pow(2, this.reconnectAttempts), RECONNECT_MAX_MS);
|
|
456
|
+
this.reconnectAttempts++;
|
|
457
|
+
log(`Reconnect attempt ${this.reconnectAttempts} in ${delay}ms`);
|
|
458
|
+
this.reconnectTimer = setTimeout(async () => {
|
|
459
|
+
this.reconnectTimer = null;
|
|
460
|
+
try {
|
|
461
|
+
await this.doConnect();
|
|
462
|
+
// On successful reconnect, request fresh state
|
|
463
|
+
this.getState();
|
|
464
|
+
}
|
|
465
|
+
catch (err) {
|
|
466
|
+
log(`Reconnect failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
467
|
+
this.scheduleReconnect();
|
|
468
|
+
}
|
|
469
|
+
}, delay);
|
|
470
|
+
}
|
|
471
|
+
notifyConnectionChange(state) {
|
|
472
|
+
for (const handler of this.connectionHandlers) {
|
|
473
|
+
try {
|
|
474
|
+
handler(state);
|
|
475
|
+
}
|
|
476
|
+
catch {
|
|
477
|
+
/* ignore */
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
/** Send an RPC command to the sandbox (prompt, steer, abort, etc.) */
|
|
482
|
+
sendCommand(command) {
|
|
483
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
484
|
+
log('Cannot send command — not connected');
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (this.shouldMarkResuming(command.type) && this.lifecycleState.phase === 'paused') {
|
|
488
|
+
this.applyLifecycle({ type: 'local_resume_requested' });
|
|
489
|
+
}
|
|
490
|
+
this.ws.send(JSON.stringify({
|
|
491
|
+
type: 'rpc_command',
|
|
492
|
+
command,
|
|
493
|
+
}));
|
|
494
|
+
}
|
|
495
|
+
/** Send a user prompt to the remote sandbox */
|
|
496
|
+
prompt(message, images) {
|
|
497
|
+
this.sendCommand({
|
|
498
|
+
type: 'prompt',
|
|
499
|
+
message,
|
|
500
|
+
...(images?.length ? { images } : {}),
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
/** Steer the agent mid-turn */
|
|
504
|
+
steer(message) {
|
|
505
|
+
this.sendCommand({ type: 'steer', message });
|
|
506
|
+
}
|
|
507
|
+
/** Abort current operation */
|
|
508
|
+
abort() {
|
|
509
|
+
this.sendCommand({ type: 'abort' });
|
|
510
|
+
}
|
|
511
|
+
/** Get current session state */
|
|
512
|
+
getState() {
|
|
513
|
+
this.sendCommand({ type: 'get_state', id: crypto.randomUUID() });
|
|
514
|
+
}
|
|
515
|
+
/** Get all messages in current session */
|
|
516
|
+
getMessages() {
|
|
517
|
+
this.sendCommand({ type: 'get_messages', id: crypto.randomUUID() });
|
|
518
|
+
}
|
|
519
|
+
/** Compact the session context */
|
|
520
|
+
compact() {
|
|
521
|
+
this.sendCommand({ type: 'compact' });
|
|
522
|
+
}
|
|
523
|
+
/** Close the connection */
|
|
524
|
+
close() {
|
|
525
|
+
this.intentionallyClosed = true;
|
|
526
|
+
this.clearReplaySettledTimer();
|
|
527
|
+
if (this.reconnectTimer) {
|
|
528
|
+
clearTimeout(this.reconnectTimer);
|
|
529
|
+
this.reconnectTimer = null;
|
|
530
|
+
}
|
|
531
|
+
this.ws?.close();
|
|
532
|
+
this.ws = null;
|
|
533
|
+
this.applyLifecycle({ type: 'connection_change', state: 'disconnected' });
|
|
534
|
+
}
|
|
535
|
+
get isConnected() {
|
|
536
|
+
return this.connected;
|
|
537
|
+
}
|
|
538
|
+
/** Handle UI request from sandbox — delegate to registered handler */
|
|
539
|
+
async handleUiRequest(request) {
|
|
540
|
+
if (!this.uiHandler) {
|
|
541
|
+
log(`No UI handler for ${request.method} — sending null response`);
|
|
542
|
+
this.sendUiResponse(request.id, null);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
try {
|
|
546
|
+
const result = await this.uiHandler(request);
|
|
547
|
+
this.sendUiResponse(request.id, result);
|
|
548
|
+
}
|
|
549
|
+
catch (err) {
|
|
550
|
+
log(`UI handler error for ${request.method}: ${err instanceof Error ? err.message : String(err)}`);
|
|
551
|
+
this.sendUiResponse(request.id, null);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
/** Send UI response back to sandbox */
|
|
555
|
+
sendUiResponse(id, result) {
|
|
556
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN)
|
|
557
|
+
return;
|
|
558
|
+
this.ws.send(JSON.stringify({
|
|
559
|
+
type: 'rpc_ui_response',
|
|
560
|
+
id,
|
|
561
|
+
result,
|
|
562
|
+
}));
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Set up remote mode for the Pi extension.
|
|
567
|
+
*
|
|
568
|
+
* Connects to an existing sandbox session through the Hub and bridges
|
|
569
|
+
* user input → RPC commands and sandbox events → TUI rendering.
|
|
570
|
+
*
|
|
571
|
+
* Uses Pi's extension APIs for rich rendering:
|
|
572
|
+
* - pi.sendMessage() for completed assistant messages
|
|
573
|
+
* - ctx.ui.setWidget() for streaming output
|
|
574
|
+
* - ctx.ui.setWorkingMessage() for tool execution status
|
|
575
|
+
* - ctx.ui.setStatus() for connection and agent state
|
|
576
|
+
*/
|
|
577
|
+
export async function setupRemoteMode(pi, hubWsUrl, sessionId) {
|
|
578
|
+
const remote = new RemoteSession(sessionId);
|
|
579
|
+
// ── Track streaming state for widget rendering ──
|
|
580
|
+
let messageBuffer = '';
|
|
581
|
+
let thinkingBuffer = '';
|
|
582
|
+
let isStreaming = false;
|
|
583
|
+
let currentTool = null;
|
|
584
|
+
let extensionCtxRef = null;
|
|
585
|
+
let lifecycleOwnsWorkingMessage = false;
|
|
586
|
+
// Called by the extension setup to provide the rendering context
|
|
587
|
+
remote._setExtensionCtx = (ctx) => {
|
|
588
|
+
extensionCtxRef = ctx;
|
|
589
|
+
applyLifecycleUi(remote.getLifecycleState());
|
|
590
|
+
};
|
|
591
|
+
// ── Render streaming output as a widget ──
|
|
592
|
+
function updateStreamWidget() {
|
|
593
|
+
if (!extensionCtxRef?.hasUI)
|
|
594
|
+
return;
|
|
595
|
+
if (!isStreaming && !messageBuffer)
|
|
596
|
+
return;
|
|
597
|
+
// Show the most recent streaming text in a widget
|
|
598
|
+
const display = messageBuffer.length > 2000 ? `...${messageBuffer.slice(-2000)}` : messageBuffer;
|
|
599
|
+
if (display) {
|
|
600
|
+
extensionCtxRef.ui.setWidget('remote_stream', display.split('\n'));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
function clearStreamWidget() {
|
|
604
|
+
if (!extensionCtxRef?.hasUI)
|
|
605
|
+
return;
|
|
606
|
+
extensionCtxRef.ui.setWidget('remote_stream', undefined);
|
|
607
|
+
}
|
|
608
|
+
function applyLifecycleUi(state) {
|
|
609
|
+
if (!extensionCtxRef?.hasUI)
|
|
610
|
+
return;
|
|
611
|
+
const shortSession = state.sessionId.slice(0, 16);
|
|
612
|
+
extensionCtxRef.ui.setStatus('remote_connection', `Remote: ${shortSession}${shortSession.length < state.sessionId.length ? '...' : ''} ${getRemoteLifecycleLabel(state)}`);
|
|
613
|
+
const activity = getRemoteLifecycleActivityLabel(state);
|
|
614
|
+
if (activity) {
|
|
615
|
+
extensionCtxRef.ui.setStatus('remote_activity', activity);
|
|
616
|
+
}
|
|
617
|
+
else {
|
|
618
|
+
extensionCtxRef.ui.setStatus('remote_activity', state.isStreaming ? 'agent working...' : 'idle');
|
|
619
|
+
}
|
|
620
|
+
lifecycleOwnsWorkingMessage = syncRemoteLifecycleWorkingMessage(state, extensionCtxRef.ui, lifecycleOwnsWorkingMessage);
|
|
621
|
+
}
|
|
622
|
+
function setNonLifecycleWorkingMessage(message) {
|
|
623
|
+
if (!extensionCtxRef?.hasUI)
|
|
624
|
+
return;
|
|
625
|
+
extensionCtxRef.ui.setWorkingMessage(message);
|
|
626
|
+
lifecycleOwnsWorkingMessage = false;
|
|
627
|
+
}
|
|
628
|
+
function clearWorkingMessage() {
|
|
629
|
+
if (!extensionCtxRef?.hasUI)
|
|
630
|
+
return;
|
|
631
|
+
if (lifecycleOwnsWorkingMessage) {
|
|
632
|
+
lifecycleOwnsWorkingMessage = clearRemoteLifecycleWorkingMessage(extensionCtxRef.ui, lifecycleOwnsWorkingMessage);
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
extensionCtxRef.ui.setWorkingMessage();
|
|
636
|
+
lifecycleOwnsWorkingMessage = false;
|
|
637
|
+
}
|
|
638
|
+
// ── Set up UI handler (wired to Pi's UI later in setupRemoteModeExtension) ──
|
|
639
|
+
// Default handler — overridden by setupRemoteModeExtension once ctx is available
|
|
640
|
+
remote.setUiHandler(async (request) => {
|
|
641
|
+
log(`UI request: ${request.method} (${request.id}) — no ctx yet`);
|
|
642
|
+
const fireAndForget = ['notify', 'setStatus', 'setWidget', 'setTitle', 'set_editor_text'];
|
|
643
|
+
if (fireAndForget.includes(request.method))
|
|
644
|
+
return undefined;
|
|
645
|
+
return null;
|
|
646
|
+
});
|
|
647
|
+
// ── Handle RPC responses (get_state, get_messages results) ──
|
|
648
|
+
remote.onResponse((response) => {
|
|
649
|
+
if (!response.success) {
|
|
650
|
+
log(`RPC response error for ${response.command}: ${response.error ?? 'unknown'}`);
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
switch (response.command) {
|
|
654
|
+
case 'get_state': {
|
|
655
|
+
const state = response.data;
|
|
656
|
+
if (state) {
|
|
657
|
+
isStreaming = !!state.isStreaming;
|
|
658
|
+
if (extensionCtxRef?.hasUI) {
|
|
659
|
+
if (state.isStreaming) {
|
|
660
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'agent working...');
|
|
661
|
+
}
|
|
662
|
+
else if (state.isWaitingForInput) {
|
|
663
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'waiting for input');
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'idle');
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
log(`State hydrated: streaming=${state.isStreaming}, waiting=${state.isWaitingForInput}`);
|
|
670
|
+
}
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
case 'get_messages': {
|
|
674
|
+
const messages = response.data;
|
|
675
|
+
if (messages?.length) {
|
|
676
|
+
hydrateMessages(messages);
|
|
677
|
+
}
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
// ── Hydrate message history into the TUI ──
|
|
683
|
+
function hydrateMessages(messages) {
|
|
684
|
+
// Show the last few messages as custom messages in the TUI
|
|
685
|
+
const recent = messages.slice(-20);
|
|
686
|
+
let hydrated = 0;
|
|
687
|
+
for (const msg of recent) {
|
|
688
|
+
const text = typeof msg.content === 'string'
|
|
689
|
+
? msg.content
|
|
690
|
+
: Array.isArray(msg.content)
|
|
691
|
+
? msg.content
|
|
692
|
+
.filter((c) => c.type === 'text' && typeof c.text === 'string')
|
|
693
|
+
.map((c) => c.text)
|
|
694
|
+
.join('\n')
|
|
695
|
+
: '';
|
|
696
|
+
if (!text)
|
|
697
|
+
continue;
|
|
698
|
+
const role = msg.role === 'assistant' ? 'assistant' : 'user';
|
|
699
|
+
pi.sendMessage({
|
|
700
|
+
customType: 'remote_history',
|
|
701
|
+
content: text,
|
|
702
|
+
display: true,
|
|
703
|
+
details: { role, timestamp: msg.timestamp, hydrated: true },
|
|
704
|
+
});
|
|
705
|
+
hydrated++;
|
|
706
|
+
}
|
|
707
|
+
log(`Hydrated ${hydrated} messages from history`);
|
|
708
|
+
}
|
|
709
|
+
// ── Handle RPC events for rendering ──
|
|
710
|
+
remote.onEvent((event) => {
|
|
711
|
+
const eventType = event.type;
|
|
712
|
+
switch (eventType) {
|
|
713
|
+
case 'session_resume':
|
|
714
|
+
log(`Session resume signaled (${typeof event.streamId === 'string' ? event.streamId : 'no stream id'})`);
|
|
715
|
+
break;
|
|
716
|
+
case 'session_stream_ready':
|
|
717
|
+
log(`Durable stream ready (${typeof event.streamId === 'string' ? event.streamId : 'no stream id'})`);
|
|
718
|
+
break;
|
|
719
|
+
case 'rpc_command_error': {
|
|
720
|
+
const error = typeof event.error === 'string'
|
|
721
|
+
? event.error
|
|
722
|
+
: 'Remote command failed';
|
|
723
|
+
if (extensionCtxRef?.hasUI) {
|
|
724
|
+
extensionCtxRef.ui.notify(error, 'warning');
|
|
725
|
+
clearWorkingMessage();
|
|
726
|
+
}
|
|
727
|
+
isStreaming = false;
|
|
728
|
+
clearStreamWidget();
|
|
729
|
+
log(`Remote command error: ${error}`);
|
|
730
|
+
break;
|
|
731
|
+
}
|
|
732
|
+
case 'message_start':
|
|
733
|
+
messageBuffer = '';
|
|
734
|
+
thinkingBuffer = '';
|
|
735
|
+
isStreaming = true;
|
|
736
|
+
if (extensionCtxRef?.hasUI) {
|
|
737
|
+
setNonLifecycleWorkingMessage('Responding...');
|
|
738
|
+
}
|
|
739
|
+
break;
|
|
740
|
+
case 'message_update': {
|
|
741
|
+
const delta = event.text ?? '';
|
|
742
|
+
messageBuffer += delta;
|
|
743
|
+
updateStreamWidget();
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
case 'message_end': {
|
|
747
|
+
isStreaming = false;
|
|
748
|
+
clearStreamWidget();
|
|
749
|
+
clearWorkingMessage();
|
|
750
|
+
// Extract content — prefer streamed buffer, fall back to message_end payload
|
|
751
|
+
let finalContent = messageBuffer.trim();
|
|
752
|
+
if (!finalContent) {
|
|
753
|
+
// Lifecycle broadcasts include full message in the event payload
|
|
754
|
+
const msg = event.message;
|
|
755
|
+
if (msg) {
|
|
756
|
+
const content = msg.content;
|
|
757
|
+
if (typeof content === 'string') {
|
|
758
|
+
finalContent = content.trim();
|
|
759
|
+
}
|
|
760
|
+
else if (Array.isArray(content)) {
|
|
761
|
+
finalContent = content
|
|
762
|
+
.filter((c) => !!c &&
|
|
763
|
+
typeof c === 'object' &&
|
|
764
|
+
c.type === 'text' &&
|
|
765
|
+
typeof c.text === 'string')
|
|
766
|
+
.map((c) => c.text)
|
|
767
|
+
.join('\n')
|
|
768
|
+
.trim();
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
// Only display assistant messages (skip user message echoes)
|
|
773
|
+
const msgRole = event.message?.role;
|
|
774
|
+
if (finalContent && msgRole !== 'user') {
|
|
775
|
+
pi.sendMessage({
|
|
776
|
+
customType: 'remote_message',
|
|
777
|
+
content: finalContent,
|
|
778
|
+
display: true,
|
|
779
|
+
details: { role: 'assistant' },
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
messageBuffer = '';
|
|
783
|
+
log(`Message complete`);
|
|
784
|
+
break;
|
|
785
|
+
}
|
|
786
|
+
case 'thinking_start':
|
|
787
|
+
thinkingBuffer = '';
|
|
788
|
+
break;
|
|
789
|
+
case 'thinking_update': {
|
|
790
|
+
const delta = event.text ?? '';
|
|
791
|
+
thinkingBuffer += delta;
|
|
792
|
+
break;
|
|
793
|
+
}
|
|
794
|
+
case 'thinking_end':
|
|
795
|
+
// Thinking is internal — just log it
|
|
796
|
+
if (thinkingBuffer) {
|
|
797
|
+
log(`Thinking complete (${thinkingBuffer.length} chars)`);
|
|
798
|
+
}
|
|
799
|
+
thinkingBuffer = '';
|
|
800
|
+
break;
|
|
801
|
+
case 'agent_start': {
|
|
802
|
+
const agent = event.agentName ?? 'agent';
|
|
803
|
+
if (extensionCtxRef?.hasUI) {
|
|
804
|
+
extensionCtxRef.ui.setStatus('remote_activity', `${agent} working...`);
|
|
805
|
+
}
|
|
806
|
+
log(`Agent started: ${agent}`);
|
|
807
|
+
break;
|
|
808
|
+
}
|
|
809
|
+
case 'agent_end':
|
|
810
|
+
if (extensionCtxRef?.hasUI) {
|
|
811
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'idle');
|
|
812
|
+
}
|
|
813
|
+
clearStreamWidget();
|
|
814
|
+
log(`Agent ended`);
|
|
815
|
+
break;
|
|
816
|
+
case 'tool_execution_start': {
|
|
817
|
+
const tool = event.toolName ?? 'tool';
|
|
818
|
+
currentTool = tool;
|
|
819
|
+
if (extensionCtxRef?.hasUI) {
|
|
820
|
+
setNonLifecycleWorkingMessage(`Running ${tool}...`);
|
|
821
|
+
extensionCtxRef.ui.setStatus('remote_activity', `Running ${tool}...`);
|
|
822
|
+
}
|
|
823
|
+
log(`Tool: ${tool}`);
|
|
824
|
+
break;
|
|
825
|
+
}
|
|
826
|
+
case 'tool_execution_end': {
|
|
827
|
+
const tool = event.toolName ?? currentTool ?? 'tool';
|
|
828
|
+
currentTool = null;
|
|
829
|
+
if (extensionCtxRef?.hasUI) {
|
|
830
|
+
clearWorkingMessage();
|
|
831
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'agent working...');
|
|
832
|
+
}
|
|
833
|
+
log(`Tool done: ${tool}`);
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
case 'turn_start':
|
|
837
|
+
if (extensionCtxRef?.hasUI) {
|
|
838
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'agent working...');
|
|
839
|
+
}
|
|
840
|
+
log('Turn started');
|
|
841
|
+
break;
|
|
842
|
+
case 'turn_end':
|
|
843
|
+
if (extensionCtxRef?.hasUI) {
|
|
844
|
+
extensionCtxRef.ui.setStatus('remote_activity', 'idle');
|
|
845
|
+
}
|
|
846
|
+
clearWorkingMessage();
|
|
847
|
+
clearStreamWidget();
|
|
848
|
+
log('Turn ended');
|
|
849
|
+
break;
|
|
850
|
+
case 'session_hydration': {
|
|
851
|
+
// Hydrate conversation history from Hub
|
|
852
|
+
const entries = event.entries;
|
|
853
|
+
if (entries?.length) {
|
|
854
|
+
let hydrated = 0;
|
|
855
|
+
for (const entry of entries.slice(-30)) {
|
|
856
|
+
if (!entry.content)
|
|
857
|
+
continue;
|
|
858
|
+
const role = entry.type === 'message' ? 'assistant' : 'user';
|
|
859
|
+
pi.sendMessage({
|
|
860
|
+
customType: 'remote_history',
|
|
861
|
+
content: entry.content,
|
|
862
|
+
display: true,
|
|
863
|
+
details: { role, timestamp: entry.timestamp, hydrated: true },
|
|
864
|
+
});
|
|
865
|
+
hydrated++;
|
|
866
|
+
}
|
|
867
|
+
log(`Hydrated ${hydrated} entries from session_hydration`);
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
log('Received session_hydration with no entries');
|
|
871
|
+
}
|
|
872
|
+
break;
|
|
873
|
+
}
|
|
874
|
+
case 'auto_compaction_start':
|
|
875
|
+
if (extensionCtxRef?.hasUI) {
|
|
876
|
+
setNonLifecycleWorkingMessage('Compacting context...');
|
|
877
|
+
}
|
|
878
|
+
break;
|
|
879
|
+
case 'auto_compaction_end':
|
|
880
|
+
clearWorkingMessage();
|
|
881
|
+
break;
|
|
882
|
+
}
|
|
883
|
+
});
|
|
884
|
+
// ── Connection/lifecycle state handling ──
|
|
885
|
+
remote.onLifecycleChange((state) => {
|
|
886
|
+
applyLifecycleUi(state);
|
|
887
|
+
});
|
|
888
|
+
// Connect to Hub after all listeners are attached so hydration/replay frames are not dropped.
|
|
889
|
+
await remote.connect(hubWsUrl);
|
|
890
|
+
log(`Remote mode active — session ${sessionId}`);
|
|
891
|
+
// Request initial state from the sandbox
|
|
892
|
+
remote.getState();
|
|
893
|
+
remote.getMessages();
|
|
894
|
+
return remote;
|
|
895
|
+
}
|
|
896
|
+
//# sourceMappingURL=remote-session.js.map
|