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