pi-better-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +615 -2
  2. package/codex-plugin/.agents/plugins/marketplace.json +17 -0
  3. package/codex-plugin/plugins/pi-remote/.codex-plugin/plugin.json +20 -0
  4. package/codex-plugin/plugins/pi-remote/.mcp.json +13 -0
  5. package/codex-plugin/plugins/pi-remote/server.mjs +118 -0
  6. package/codex-plugin/plugins/pi-remote/skills/pi-remote/SKILL.md +19 -0
  7. package/package.json +60 -4
  8. package/scripts/bootstrap-host.sh +107 -0
  9. package/scripts/private-runtime/format.ts +65 -0
  10. package/scripts/private-runtime/installer.ts +166 -0
  11. package/scripts/private-runtime/package-lock.json +1491 -0
  12. package/scripts/private-runtime/package.json +17 -0
  13. package/scripts/test-on-pi.sh +34 -0
  14. package/src/cli-args.ts +38 -0
  15. package/src/cli.ts +90 -0
  16. package/src/client.ts +152 -0
  17. package/src/codex/adapter.ts +299 -0
  18. package/src/codex/app-server.ts +112 -0
  19. package/src/codex/daemon.ts +232 -0
  20. package/src/codex/deliver.ts +103 -0
  21. package/src/codex/preflight.ts +15 -0
  22. package/src/codex/provider.ts +55 -0
  23. package/src/codex/return.ts +110 -0
  24. package/src/codex/rollout.ts +160 -0
  25. package/src/codex/runtime.ts +126 -0
  26. package/src/codex/ws-unix.ts +112 -0
  27. package/src/companion.ts +96 -0
  28. package/src/control.ts +85 -0
  29. package/src/core/adapter.ts +109 -0
  30. package/src/core/bundle.ts +764 -0
  31. package/src/core/exclusions.ts +53 -0
  32. package/src/core/move-host.ts +268 -0
  33. package/src/core/ownership.ts +135 -0
  34. package/src/core/transfer.ts +73 -0
  35. package/src/daemon-owner.ts +130 -0
  36. package/src/detach/detach.ts +150 -0
  37. package/src/detach/extension.ts +244 -0
  38. package/src/detach/local-sink.ts +203 -0
  39. package/src/detach/local-source.ts +133 -0
  40. package/src/detach/local-state.ts +87 -0
  41. package/src/detach/recover.ts +53 -0
  42. package/src/event-log.ts +163 -0
  43. package/src/git.ts +35 -0
  44. package/src/handshake.ts +57 -0
  45. package/src/hosted-session.ts +576 -0
  46. package/src/index.ts +31 -0
  47. package/src/lifecycle-config.ts +29 -0
  48. package/src/maintenance.ts +317 -0
  49. package/src/move/auth.ts +16 -0
  50. package/src/move/orchestrate.ts +163 -0
  51. package/src/move/pi-adapter.ts +181 -0
  52. package/src/move/preflight.ts +197 -0
  53. package/src/move/service.ts +16 -0
  54. package/src/paths.ts +52 -0
  55. package/src/protocol.ts +212 -0
  56. package/src/registry.ts +559 -0
  57. package/src/remote/answer.ts +95 -0
  58. package/src/remote/attach-codex.ts +41 -0
  59. package/src/remote/attach.ts +41 -0
  60. package/src/remote/console.ts +126 -0
  61. package/src/remote/context.ts +75 -0
  62. package/src/remote/cursors.ts +36 -0
  63. package/src/remote/ls.ts +44 -0
  64. package/src/remote/move.ts +85 -0
  65. package/src/remote/new.ts +37 -0
  66. package/src/remote/process-runner.ts +51 -0
  67. package/src/remote/recover.ts +35 -0
  68. package/src/remote/return.ts +49 -0
  69. package/src/remote/sessions.ts +33 -0
  70. package/src/remote/steer.ts +40 -0
  71. package/src/remote/tail.ts +91 -0
  72. package/src/remote/target.ts +313 -0
  73. package/src/remote-cli.ts +73 -0
  74. package/src/remote-client/connection-progress.ts +62 -0
  75. package/src/remote-client/extension.ts +368 -0
  76. package/src/remote-client/folder-browser.ts +165 -0
  77. package/src/remote-client/host.ts +127 -0
  78. package/src/remote-client/local-work.ts +62 -0
  79. package/src/remote-client/menu.ts +68 -0
  80. package/src/remote-client/packages.ts +331 -0
  81. package/src/remote-client/pi-1.2-bridge.ts +482 -0
  82. package/src/remote-client/profiles.ts +38 -0
  83. package/src/remote-client/remote-progress.ts +39 -0
  84. package/src/remote-client/session-browser.ts +267 -0
  85. package/src/remote-client/session.ts +1205 -0
  86. package/src/remote-client/ssh-hosts.ts +185 -0
  87. package/src/remote-client/transfer-command.ts +189 -0
  88. package/src/remote-client/upgrade-transport.ts +105 -0
  89. package/src/server.ts +398 -0
  90. package/src/session-activity.ts +173 -0
  91. package/src/shared-ssh-core/index.ts +950 -0
  92. package/src/startup/activation.ts +621 -0
  93. package/src/startup/admission.ts +98 -0
  94. package/src/startup/artifact.ts +65 -0
  95. package/src/startup/commands.ts +37 -0
  96. package/src/startup/ensure.ts +137 -0
  97. package/src/startup/install.ts +115 -0
  98. package/src/startup/managed-types.ts +61 -0
  99. package/src/startup/runtime.ts +138 -0
  100. package/src/ui-bridge.ts +124 -0
@@ -0,0 +1,1205 @@
1
+ import { posix, win32 } from "node:path";
2
+ import { buildContextEntries, buildSessionContext, SettingsManager, type RpcSessionState } from "@earendil-works/pi-coding-agent";
3
+ import type { DaemonClient } from "../client.ts";
4
+ import { remoteArgumentCompletions } from "./menu.ts";
5
+
6
+ // Wire metadata and native UI objects differ between Pi 0.82 (repo types) and 1.2.
7
+ // These values are presentation data only; none are an executable Agent or provider.
8
+ type Presentation = Record<string, any>;
9
+ type SessionEvent = Presentation & { type: string };
10
+ type Envelope = { sessionId?: string; seq?: unknown; generation?: unknown; event?: any };
11
+ type Listener = (event: any) => void | Promise<void>;
12
+
13
+ export interface ClientSnapshot {
14
+ generation: string;
15
+ lastSeq: number;
16
+ sessionId: string;
17
+ cwd: string;
18
+ name?: string;
19
+ sessionFile: string;
20
+ state: RpcSessionState;
21
+ messages: any[];
22
+ entries: any[];
23
+ leafId: string | null;
24
+ tools: any[];
25
+ commands: any[];
26
+ models: any[];
27
+ contextUsage: any;
28
+ stats: any;
29
+ activeMessage?: any;
30
+ activeTools?: any[];
31
+ }
32
+
33
+ export interface RemoteClientSessionOptions {
34
+ onDisconnect?: () => void;
35
+ onLocalCommand?: (text: string) => Promise<boolean>;
36
+ localCommandCompletions?: (prefix: string) => ReturnType<typeof remoteArgumentCompletions> | Promise<ReturnType<typeof remoteArgumentCompletions>>;
37
+ reconnectAfterUpgrade?: (notice: RuntimeUpgradeNotice, signal: AbortSignal) => Promise<ReplacementRemoteTransport>;
38
+ onReconnected?: (client: DaemonClient) => void;
39
+ onUpgradeStatus?: (phase: "restarting" | "reconnecting" | "ready", notice: RuntimeUpgradeNotice) => void;
40
+ }
41
+
42
+ export interface RuntimeUpgradeNotice { operationId: string; buildId: string }
43
+ export interface ReplacementRemoteTransport {
44
+ client: DaemonClient;
45
+ dispose?: () => void | Promise<void>;
46
+ }
47
+
48
+ class SupersededTransportError extends Error {
49
+ constructor() { super("The remote transport changed during this request. Its outcome is not replayed; check the refreshed remote history."); }
50
+ }
51
+
52
+ function upgradeNotice(event: Presentation): RuntimeUpgradeNotice | undefined {
53
+ if (event.type !== "runtime_upgrade" || event.phase !== "restarting") return undefined;
54
+ if (![event.operationId, event.buildId].every(value => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{5,255}$/.test(value))) return undefined;
55
+ return { operationId: event.operationId, buildId: event.buildId };
56
+ }
57
+
58
+ function validateReplacement(client: DaemonClient, previous: DaemonClient, notice: RuntimeUpgradeNotice): void {
59
+ const hello = client.server as Presentation | undefined;
60
+ if ((hello?.build?.contentId ?? hello?.buildId) !== notice.buildId) throw new Error("Upgrade reconnect reached a different server build");
61
+ if (typeof hello?.instanceId !== "string" || !hello.instanceId) throw new Error("Upgrade reconnect has no daemon instance identity");
62
+ if (previous.server?.piVersion && hello.piVersion !== previous.server.piVersion) throw new Error("Upgrade reconnect changed the Pi SDK version");
63
+ if (previous.server?.instanceId && hello.instanceId === previous.server.instanceId) throw new Error("Upgrade reconnect reached the previous daemon instance");
64
+ }
65
+
66
+ function loggedUpgrade(envelope: Envelope, sessionId: string, generation?: string, lastSeq = 0): RuntimeUpgradeNotice | undefined {
67
+ if (envelope.sessionId !== sessionId || typeof envelope.generation !== "string" || !envelope.generation ||
68
+ (generation !== undefined && envelope.generation !== generation) ||
69
+ typeof envelope.seq !== "number" || !Number.isSafeInteger(envelope.seq) || envelope.seq <= lastSeq) return undefined;
70
+ return upgradeNotice(envelope.event ?? {});
71
+ }
72
+
73
+ function unsupported(operation: string): never {
74
+ throw new Error(`${operation} is not supported by the remote session; no local execution or persistence is allowed`);
75
+ }
76
+
77
+ function copy<T>(value: T): T {
78
+ return structuredClone(value);
79
+ }
80
+
81
+ // Only display metadata crosses into the presentation cache. Transport options
82
+ // (including headers and credential-bearing URLs) are never needed by the UI.
83
+ function modelMetadata(model: any): any {
84
+ if (model == null) return model;
85
+ const safe: Presentation = {};
86
+ for (const key of ["id", "provider", "name", "api", "reasoning", "input", "cost", "contextWindow", "maxTokens",
87
+ "thinkingLevels", "subscription", "authType"]) {
88
+ if (Object.hasOwn(model, key)) safe[key] = copy(model[key]);
89
+ }
90
+ return safe;
91
+ }
92
+
93
+ function sanitizeModels(value: Presentation): void {
94
+ if (value.model && typeof value.model === "object") value.model = modelMetadata(value.model);
95
+ if (Array.isArray(value.models)) value.models = value.models.map(modelMetadata);
96
+ if (Array.isArray(value.scopedModels)) {
97
+ value.scopedModels = value.scopedModels.map(({ model, thinkingLevel }: Presentation) => ({ model: modelMetadata(model), thinkingLevel }));
98
+ }
99
+ if (value.routedModel) {
100
+ value.routedModel = { model: modelMetadata(value.routedModel.model), thinkingLevel: value.routedModel.thinkingLevel };
101
+ }
102
+ }
103
+
104
+ export class SnapshotRequiredError extends Error {
105
+ constructor(message: string) {
106
+ super(message);
107
+ this.name = "SnapshotRequiredError";
108
+ }
109
+ }
110
+
111
+ function validateSnapshot(snapshot: ClientSnapshot): void {
112
+ if (!snapshot || typeof snapshot.generation !== "string" || !snapshot.generation ||
113
+ !Number.isSafeInteger(snapshot.lastSeq) || snapshot.lastSeq < 0 ||
114
+ typeof snapshot.sessionId !== "string" || typeof snapshot.cwd !== "string" ||
115
+ typeof snapshot.sessionFile !== "string" || !snapshot.state ||
116
+ ![snapshot.messages, snapshot.entries, snapshot.tools, snapshot.commands, snapshot.models].every(Array.isArray) ||
117
+ !(snapshot.leafId === null || typeof snapshot.leafId === "string")) {
118
+ throw new Error("Invalid client_snapshot response");
119
+ }
120
+ }
121
+
122
+ /** The authoritative remote projection. Exported so replay semantics can be tested without faking a daemon. */
123
+ export class RemoteSessionCache {
124
+ snapshot!: ClientSnapshot;
125
+ streamingMessage: any;
126
+ readonly pendingToolCalls = new Set<string>();
127
+ readonly toolExecutions = new Map<string, any>();
128
+ steering: string[] = [];
129
+ followUp: string[] = [];
130
+ retryAttempt = 0;
131
+ private messageIndex: number | undefined;
132
+ private readonly argumentBuffers = new Map<number, string>();
133
+
134
+ constructor(snapshot: ClientSnapshot) {
135
+ this.replace(snapshot);
136
+ }
137
+
138
+ replace(snapshot: ClientSnapshot): void {
139
+ validateSnapshot(snapshot);
140
+ this.snapshot = copy(snapshot);
141
+ sanitizeModels(this.snapshot);
142
+ sanitizeModels(this.snapshot.state);
143
+ const state = this.snapshot.state as Presentation;
144
+ this.steering = copy(state.steering ?? []);
145
+ this.followUp = copy(state.followUp ?? []);
146
+ this.retryAttempt = state.retryAttempt ?? 0;
147
+ this.pendingToolCalls.clear();
148
+ this.toolExecutions.clear();
149
+ this.streamingMessage = copy(snapshot.activeMessage ?? state.streamMessage);
150
+ for (const tool of snapshot.activeTools ?? []) {
151
+ this.pendingToolCalls.add(tool.toolCallId);
152
+ this.toolExecutions.set(tool.toolCallId, copy(tool));
153
+ }
154
+ const last = this.snapshot.messages.length - 1;
155
+ this.messageIndex = this.streamingMessage && last >= 0 &&
156
+ JSON.stringify(this.snapshot.messages[last]) === JSON.stringify(this.streamingMessage) ? last : undefined;
157
+ this.argumentBuffers.clear();
158
+ }
159
+
160
+ get state(): Presentation {
161
+ return { ...this.snapshot.state, messages: this.snapshot.messages, tools: this.snapshot.tools,
162
+ streamMessage: this.streamingMessage, pendingToolCalls: new Set(this.pendingToolCalls) };
163
+ }
164
+
165
+ /** Reject gaps before touching state. Duplicate/replayed events have no observable effect. */
166
+ apply(envelope: Envelope): SessionEvent | undefined {
167
+ if (envelope.sessionId !== this.snapshot.sessionId) return undefined;
168
+ if (envelope.generation !== undefined && envelope.generation !== this.snapshot.generation) {
169
+ throw new SnapshotRequiredError("Remote session generation changed");
170
+ }
171
+ const seq = envelope.seq;
172
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 1) {
173
+ throw new SnapshotRequiredError("Invalid remote event sequence");
174
+ }
175
+ if (seq <= this.snapshot.lastSeq) return undefined;
176
+ if (seq !== this.snapshot.lastSeq + 1) throw new SnapshotRequiredError("Remote event sequence has a gap");
177
+ const event = copy(envelope.event) as SessionEvent;
178
+ if (!event || typeof event.type !== "string") throw new SnapshotRequiredError("Invalid remote event");
179
+ sanitizeModels(event);
180
+ const state = this.snapshot.state as Presentation;
181
+ switch (event.type) {
182
+ case "agent_start":
183
+ state.isStreaming = true;
184
+ this.pendingToolCalls.clear();
185
+ this.toolExecutions.clear();
186
+ break;
187
+ // Pi 1.2 can retry/compact after agent_end. Only agent_settled is idle.
188
+ case "agent_settled":
189
+ state.isStreaming = false;
190
+ state.isCompacting = false;
191
+ this.retryAttempt = 0;
192
+ this.streamingMessage = undefined;
193
+ this.pendingToolCalls.clear();
194
+ break;
195
+ case "message_start":
196
+ this.messageIndex = this.snapshot.messages.length;
197
+ this.snapshot.messages.push(event.message);
198
+ this.argumentBuffers.clear();
199
+ if (event.message.role === "assistant") this.streamingMessage = event.message;
200
+ break;
201
+ case "message_update": {
202
+ const message = event.message ?? this.updateDelta(event);
203
+ if (!message) throw new SnapshotRequiredError("Streaming update has no starting message");
204
+ event.message = message;
205
+ this.streamingMessage = message;
206
+ if (this.messageIndex === undefined) this.messageIndex = this.snapshot.messages.length;
207
+ this.snapshot.messages[this.messageIndex] = message;
208
+ break;
209
+ }
210
+ case "message_end":
211
+ if (this.messageIndex === undefined) this.snapshot.messages.push(event.message);
212
+ else this.snapshot.messages[this.messageIndex] = event.message;
213
+ this.messageIndex = undefined;
214
+ this.streamingMessage = undefined;
215
+ this.argumentBuffers.clear();
216
+ break;
217
+ case "tool_execution_start":
218
+ this.pendingToolCalls.add(event.toolCallId);
219
+ this.toolExecutions.set(event.toolCallId, event);
220
+ break;
221
+ case "tool_execution_update":
222
+ this.toolExecutions.set(event.toolCallId, event);
223
+ break;
224
+ case "tool_execution_end":
225
+ this.pendingToolCalls.delete(event.toolCallId);
226
+ this.toolExecutions.delete(event.toolCallId);
227
+ break;
228
+ case "queue_update":
229
+ this.steering = event.steering;
230
+ this.followUp = event.followUp;
231
+ state.pendingMessageCount = this.steering.length + this.followUp.length;
232
+ break;
233
+ case "session_info_changed":
234
+ this.snapshot.name = event.name;
235
+ state.sessionName = event.name;
236
+ break;
237
+ case "thinking_level_changed": state.thinkingLevel = event.level; break;
238
+ case "compaction_start":
239
+ case "auto_compaction_start": state.isCompacting = true; break;
240
+ case "compaction_end":
241
+ case "auto_compaction_end": state.isCompacting = false; break;
242
+ case "auto_retry_start": this.retryAttempt = event.attempt; break;
243
+ case "auto_retry_end": this.retryAttempt = 0; break;
244
+ case "entry_appended":
245
+ if (!this.snapshot.entries.some((entry) => entry.id === event.entry.id)) {
246
+ this.snapshot.entries.push(event.entry);
247
+ this.snapshot.leafId = event.entry.id;
248
+ }
249
+ break;
250
+ }
251
+ this.snapshot.lastSeq = seq;
252
+ return event;
253
+ }
254
+
255
+ private updateDelta(event: SessionEvent): any {
256
+ if (!this.streamingMessage) return undefined;
257
+ const message = copy(this.streamingMessage);
258
+ const update = event.assistantMessageEvent;
259
+ if (!update) return undefined;
260
+ const index = update.contentIndex;
261
+ const content = message.content;
262
+ switch (update.type) {
263
+ case "text_start": content[index] = { type: "text", text: "" }; break;
264
+ case "thinking_start": content[index] = { type: "thinking", thinking: "" }; break;
265
+ case "text_delta":
266
+ case "thinking_delta": {
267
+ const key = update.type === "text_delta" ? "text" : "thinking";
268
+ content[index] ??= { type: key, [key]: "" };
269
+ content[index][key] += update.delta;
270
+ break;
271
+ }
272
+ case "text_end": content[index] = { type: "text", text: update.content }; break;
273
+ case "thinking_end": content[index] = { type: "thinking", thinking: update.content }; break;
274
+ case "toolcall_start":
275
+ content[index] = { type: "toolCall", id: update.id, name: update.toolName, arguments: {} };
276
+ this.argumentBuffers.set(index, "");
277
+ break;
278
+ case "toolcall_delta": {
279
+ const json = (this.argumentBuffers.get(index) ?? "") + update.delta;
280
+ this.argumentBuffers.set(index, json);
281
+ try { content[index].arguments = JSON.parse(json); } catch { /* The final toolcall_end carries complete arguments. */ }
282
+ break;
283
+ }
284
+ case "toolcall_end": content[index] = update.toolCall; break;
285
+ case "done": return update.message;
286
+ case "error": return update.error;
287
+ }
288
+ if (event.usage) message.usage = event.usage;
289
+ return message;
290
+ }
291
+ }
292
+
293
+ /** Presentation-only tree. Never instantiates a SessionManager or opens a session file. */
294
+ export class RemoteSessionManager {
295
+ private readonly cache: RemoteSessionCache;
296
+ constructor(cache: RemoteSessionCache) { this.cache = cache; }
297
+ getCwd(): string { return this.cache.snapshot.cwd; }
298
+ getSessionId(): string { return this.cache.snapshot.sessionId; }
299
+ getSessionFile(): string { return this.cache.snapshot.sessionFile; }
300
+ getSessionName(): string | undefined { return this.cache.snapshot.name; }
301
+ getSessionDir(): string {
302
+ const file = this.getSessionFile();
303
+ return (file.includes("\\") ? win32 : posix).dirname(file);
304
+ }
305
+ isPersisted(): boolean { return Boolean(this.getSessionFile()); }
306
+ usesDefaultSessionDir(): boolean { return false; }
307
+ getLeafId(): string | null { return this.cache.snapshot.leafId; }
308
+ getLeafEntry(): any { return this.getEntry(this.getLeafId() ?? ""); }
309
+ getEntries(): any[] { return copy(this.cache.snapshot.entries); }
310
+ getEntryCount(): number { return this.cache.snapshot.entries.length; }
311
+ getChildren(parentId: string): any[] { return this.getEntries().filter((entry) => entry.parentId === parentId); }
312
+ getEntry(id: string): any { return copy(this.cache.snapshot.entries.find((entry) => entry.id === id)); }
313
+ getHeader(): never { return unsupported("Session header (not included in client_snapshot)"); }
314
+ getBranch(fromId?: string): any[] {
315
+ const entries = new Map(this.cache.snapshot.entries.map((entry) => [entry.id, entry]));
316
+ const branch: any[] = [];
317
+ const seen = new Set<string>();
318
+ let entry = entries.get(fromId ?? this.getLeafId());
319
+ while (entry && !seen.has(entry.id)) {
320
+ seen.add(entry.id);
321
+ branch.push(entry);
322
+ entry = entries.get(entry.parentId);
323
+ }
324
+ return copy(branch.reverse());
325
+ }
326
+ buildContextEntries(): any[] {
327
+ return copy(buildContextEntries(this.cache.snapshot.entries, this.getLeafId()));
328
+ }
329
+ buildSessionContext(): any {
330
+ return copy(buildSessionContext(this.cache.snapshot.entries, this.getLeafId()));
331
+ }
332
+ getLabel(id: string): string | undefined {
333
+ return this.cache.snapshot.entries.filter((entry) => entry.type === "label" && entry.targetId === id).at(-1)?.label;
334
+ }
335
+ getTree(): any[] {
336
+ const entries = this.getEntries();
337
+ const nodes = new Map<string, any>(entries.map((entry) => [entry.id, { entry, children: [], label: this.getLabel(entry.id) }]));
338
+ const roots: any[] = [];
339
+ for (const entry of entries) {
340
+ const node = nodes.get(entry.id);
341
+ const parent = nodes.get(entry.parentId);
342
+ if (!parent || entry.parentId === entry.id) roots.push(node);
343
+ else parent.children.push(node);
344
+ }
345
+ return roots;
346
+ }
347
+ appendMessage(): never { return unsupported("sessionManager.appendMessage"); }
348
+ appendCustomEntry(): never { return unsupported("sessionManager.appendCustomEntry"); }
349
+ appendCustomMessageEntry(): never { return unsupported("sessionManager.appendCustomMessageEntry"); }
350
+ appendLabelChange(): never { return unsupported("sessionManager.appendLabelChange"); }
351
+ appendSessionInfo(): never { return unsupported("sessionManager.appendSessionInfo"); }
352
+ appendModelChange(): never { return unsupported("sessionManager.appendModelChange"); }
353
+ appendThinkingLevelChange(): never { return unsupported("sessionManager.appendThinkingLevelChange"); }
354
+ appendCompaction(): never { return unsupported("sessionManager.appendCompaction"); }
355
+ appendUsage(): never { return unsupported("sessionManager.appendUsage"); }
356
+ appendContextEdit(): never { return unsupported("sessionManager.appendContextEdit"); }
357
+ branchWithSummary(): never { return unsupported("sessionManager.branchWithSummary"); }
358
+ createBranchedSession(): never { return unsupported("sessionManager.createBranchedSession"); }
359
+ branch(): never { return unsupported("sessionManager.branch"); }
360
+ resetLeaf(): never { return unsupported("sessionManager.resetLeaf"); }
361
+ newSession(): never { return unsupported("sessionManager.newSession"); }
362
+ setSessionFile(): never { return unsupported("sessionManager.setSessionFile"); }
363
+ flush(): never { return unsupported("sessionManager.flush"); }
364
+ }
365
+
366
+ /** Model metadata, never provider implementations, credentials, or a local catalog. */
367
+ export class RemoteModelRuntime {
368
+ private readonly cache: RemoteSessionCache;
369
+ private readonly refreshRemote?: () => Promise<void>;
370
+ constructor(cache: RemoteSessionCache, refreshRemote?: () => Promise<void>) {
371
+ this.cache = cache;
372
+ this.refreshRemote = refreshRemote;
373
+ }
374
+ getAvailableSnapshot(): any[] { return copy(this.cache.snapshot.models); }
375
+ async getAvailable(provider?: string): Promise<any[]> { return this.getModels(provider); }
376
+ getModels(provider?: string): any[] { return this.getAvailableSnapshot().filter((model) => !provider || model.provider === provider); }
377
+ getAllModels(provider?: string): any[] { return this.getModels(provider); }
378
+ getModel(provider: string, id: string): any { return this.getModels(provider).find((model) => model.id === id); }
379
+ getPhysicalModel(provider: string, id: string): any { return this.getModel(provider, id); }
380
+ getProviders(): any[] {
381
+ return [...new Set(this.cache.snapshot.models.map((model) => model.provider))].map((id) => ({ id, name: id, auth: {} }));
382
+ }
383
+ getProvider(id: string): any { return this.getProviders().find((provider) => provider.id === id); }
384
+ getError(): undefined { return undefined; }
385
+ // Subscription indication is metadata only, not an inference from local credentials.
386
+ isUsingSubscription(provider: string): boolean { return this.getModels(provider).some((model) => model.subscription === true); }
387
+ isUsingOAuth(provider: string): boolean { return this.getModels(provider).some((model) => model.authType === "oauth"); }
388
+ getProviderAuthStatus(provider: string): any {
389
+ return { configured: this.getModels(provider).length > 0, label: "Remote daemon" };
390
+ }
391
+ getAuth(): never { return unsupported("modelRuntime.getAuth (remote credentials)"); }
392
+ checkAuth(): never { return unsupported("modelRuntime.checkAuth (remote credentials)"); }
393
+ listCredentials(): never { return unsupported("modelRuntime.listCredentials"); }
394
+ login(): never { return unsupported("modelRuntime.login"); }
395
+ logout(): never { return unsupported("modelRuntime.logout"); }
396
+ async refresh(): Promise<any> {
397
+ if (!this.refreshRemote) return unsupported("modelRuntime.refresh (no remote connection)");
398
+ await this.refreshRemote();
399
+ return { aborted: false, errors: new Map() };
400
+ }
401
+ setRuntimeApiKey(): never { return unsupported("modelRuntime.setRuntimeApiKey"); }
402
+ registerProvider(): never { return unsupported("modelRuntime.registerProvider"); }
403
+ stream(): never { return unsupported("modelRuntime.stream"); }
404
+ streamSimple(): never { return unsupported("modelRuntime.streamSimple"); }
405
+ complete(): never { return unsupported("modelRuntime.complete"); }
406
+ completeSimple(): never { return unsupported("modelRuntime.completeSimple"); }
407
+ removeRuntimeApiKey(): never { return unsupported("modelRuntime.removeRuntimeApiKey"); }
408
+ unregisterProvider(): never { return unsupported("modelRuntime.unregisterProvider"); }
409
+ }
410
+
411
+ export class RemoteClientSession {
412
+ readonly sessionManager: RemoteSessionManager;
413
+ readonly modelRuntime: RemoteModelRuntime;
414
+ readonly extensionRunner: Presentation;
415
+ readonly resourceLoader: Presentation;
416
+ readonly agent: Presentation;
417
+ // In-memory presentation preferences only. The bridge may replace these with
418
+ // the existing local UI preferences; neither option persists remote state.
419
+ settingsManager: any;
420
+ private client: DaemonClient;
421
+ private readonly cache: RemoteSessionCache;
422
+ private readonly options: RemoteClientSessionOptions;
423
+ private readonly listeners = new Set<Listener>();
424
+ private readonly dialogs = new Map<string, Presentation>();
425
+ private readonly dialogControllers = new Map<string, AbortController>();
426
+ private readonly uiRequests: SessionEvent[] = [];
427
+ private readonly idleWaiters = new Set<{ resolve: () => void; reject: (error: Error) => void }>();
428
+ private readonly eventWaiters = new Set<{ generation: string; seq: number; resolve: () => void; reject: (error: Error) => void }>();
429
+ private subscribedSeq = 0;
430
+ private uiContext: any;
431
+ private bindings: Presentation = {};
432
+ private detachEvents?: () => void;
433
+ private deactivateClose?: () => void;
434
+ private detached = false;
435
+ private failed?: Error;
436
+ private controller = false;
437
+ private reconciling?: Promise<void>;
438
+ private buffered: Envelope[] = [];
439
+ private receiving = false;
440
+ private bashOutput?: (chunk: string) => void;
441
+ private bashRunning = false;
442
+ private pendingBashSnapshot = false;
443
+ private transportEpoch = 0;
444
+ private transportReady = true;
445
+ private pendingUpgrade?: RuntimeUpgradeNotice;
446
+ private reconnecting?: Promise<void>;
447
+ private reconnectAbort?: AbortController;
448
+ private disposeReplacement?: () => void | Promise<void>;
449
+ private disconnectNotified = false;
450
+
451
+ private constructor(client: DaemonClient, snapshot: ClientSnapshot, options: RemoteClientSessionOptions) {
452
+ this.client = client;
453
+ this.options = options;
454
+ this.cache = new RemoteSessionCache(snapshot);
455
+ this.sessionManager = new RemoteSessionManager(this.cache);
456
+ this.modelRuntime = new RemoteModelRuntime(this.cache, async () => {
457
+ const data = await this.request("get_available_models");
458
+ this.cache.snapshot.models = data.models.map(modelMetadata);
459
+ });
460
+ this.settingsManager = SettingsManager.inMemory();
461
+ const session = this;
462
+ this.agent = Object.freeze({
463
+ get state() { return session.state; },
464
+ get signal() { return session.presentationSignal.signal; },
465
+ get transport() { return undefined; },
466
+ hasQueuedMessages: () => this.pendingMessageCount > 0,
467
+ abort: () => unsupported("agent.abort; use session.abort to abort remotely"),
468
+ prompt: () => unsupported("agent.prompt; use session.prompt"),
469
+ setModel: () => unsupported("agent.setModel; use session.setModel"),
470
+ setTools: () => unsupported("agent.setTools"),
471
+ });
472
+ this.extensionRunner = Object.freeze({
473
+ getRegisteredCommands: () => this.commands().filter((command) => command.source !== "prompt"),
474
+ getCommand: (name: string) => this.commands().find((command) => command.invocationName === name),
475
+ getCommandDiagnostics: () => [],
476
+ getShortcutDiagnostics: () => [],
477
+ getShortcuts: () => new Map(),
478
+ getMarkdownTransformers: () => [],
479
+ getEntryRenderer: () => undefined,
480
+ getMessageRenderer: () => undefined,
481
+ resolveToolRenderers: (_name: string, fallback: () => unknown) => fallback(),
482
+ getModelRegistry: () => this.modelRuntime,
483
+ hasHandlers: () => false,
484
+ emit: async (event: SessionEvent) => {
485
+ if (event.type !== "session_shutdown") return unsupported(`Local extension event '${event.type}'`);
486
+ // Only the local presentation binding is shutting down, not the remote extensions.
487
+ },
488
+ // No local extension interceptors. executeBash forwards the actual execution to the daemon.
489
+ emitUserBash: async () => undefined,
490
+ });
491
+ this.resourceLoader = Object.freeze({
492
+ getExtensions: () => ({ extensions: [], errors: [], warnings: [] }),
493
+ getThemes: () => ({ themes: [], diagnostics: [] }),
494
+ getSkills: () => ({ skills: [], diagnostics: [] }),
495
+ getPrompts: () => ({ prompts: this.promptTemplates, diagnostics: [] }),
496
+ getAgentsFiles: () => ({ agentsFiles: [] }),
497
+ getSystemPromptSource: () => undefined,
498
+ getAppendSystemPromptSources: () => [],
499
+ getPathMetadata: () => new Map(),
500
+ reload: () => unsupported("resourceLoader.reload"),
501
+ });
502
+ }
503
+
504
+ private readonly presentationSignal = new AbortController();
505
+
506
+ static async connect(client: DaemonClient, sessionId: string, options: RemoteClientSessionOptions = {}): Promise<RemoteClientSession> {
507
+ return this.attach(client, sessionId, options);
508
+ }
509
+
510
+ private static async attach(client: DaemonClient, sessionId: string, options: RemoteClientSessionOptions,
511
+ owned?: ReplacementRemoteTransport, completedNotice?: RuntimeUpgradeNotice): Promise<RemoteClientSession> {
512
+ // Listen before reading the snapshot: the supplied client may already be subscribed.
513
+ let session: RemoteClientSession | undefined;
514
+ const early: Envelope[] = [];
515
+ let closed = false;
516
+ const detach = client.onEvent((event) => {
517
+ if (event.sessionId !== sessionId) return;
518
+ if (session) session.receive(event, client, 0);
519
+ else early.push(event);
520
+ });
521
+ const detachClose = client.onClose(() => { closed = true; session?.disconnect(client, 0); });
522
+ try {
523
+ const response = await client.call({ type: "client_snapshot", sessionId });
524
+ validateSnapshot(response.data);
525
+ if (response.data.sessionId !== sessionId) throw new Error("client_snapshot returned a different session");
526
+ session = new RemoteClientSession(client, response.data, options);
527
+ if (owned) session.disposeReplacement = owned.dispose ?? (() => {});
528
+ session.detachEvents = detach;
529
+ session.deactivateClose = detachClose;
530
+ for (const event of early) session.receive(event, client, 0);
531
+ if (closed && session.pendingUpgrade) {
532
+ session.disconnect(client, 0);
533
+ throw new SupersededTransportError();
534
+ }
535
+ if (closed) throw new Error("Remote connection closed during snapshot");
536
+ await session.resubscribe();
537
+ const lease = await session.request("acquire_control");
538
+ session.controller = true;
539
+ for (const dialog of lease?.needsInput ?? []) session.dialogs.set(dialog.id, dialog);
540
+ await session.loadThinkingLevels();
541
+ session.receiving = true;
542
+ session.drain();
543
+ await session.flushReceivedEvents();
544
+ if (completedNotice) {
545
+ options.onReconnected?.(client);
546
+ session.upgradeStatus("ready", completedNotice);
547
+ }
548
+ return session;
549
+ } catch (error) {
550
+ if (session && (error instanceof SupersededTransportError || session.pendingUpgrade) && options.reconnectAfterUpgrade && !session.failed && !session.detached) {
551
+ if (!session.reconnecting && session.pendingUpgrade) session.disconnect(client, 0);
552
+ await session.reconnecting;
553
+ session.assertConnected();
554
+ session.receiving = true;
555
+ session.drain();
556
+ await session.flushReceivedEvents();
557
+ return session;
558
+ }
559
+ if (session) session.dispose();
560
+ else {
561
+ detach(); detachClose();
562
+ if (owned) { client.close(); await owned.dispose?.(); }
563
+ // No projection exists yet. A logged notice must carry its own valid
564
+ // generation and cursor; the replacement still has to prove its identity.
565
+ let generation: string | undefined;
566
+ let lastSeq = 0;
567
+ let notice: RuntimeUpgradeNotice | undefined;
568
+ for (const envelope of early) {
569
+ if (envelope.sessionId !== sessionId || typeof envelope.generation !== "string" || !envelope.generation ||
570
+ typeof envelope.seq !== "number" || !Number.isSafeInteger(envelope.seq) || envelope.seq <= lastSeq) continue;
571
+ generation ??= envelope.generation;
572
+ notice ??= loggedUpgrade(envelope, sessionId, generation, lastSeq);
573
+ if (envelope.generation === generation) lastSeq = envelope.seq;
574
+ }
575
+ if (closed && notice && options.reconnectAfterUpgrade) {
576
+ const abort = new AbortController();
577
+ options.onUpgradeStatus?.("restarting", notice);
578
+ options.onUpgradeStatus?.("reconnecting", notice);
579
+ const replacement = await options.reconnectAfterUpgrade(notice, abort.signal);
580
+ try { validateReplacement(replacement.client, client, notice); }
581
+ catch (error) { replacement.client.close(); await replacement.dispose?.(); throw error; }
582
+ return this.attach(replacement.client, sessionId, options, replacement, notice);
583
+ }
584
+ }
585
+ throw error;
586
+ }
587
+ }
588
+
589
+ get sessionId(): string { return this.cache.snapshot.sessionId; }
590
+ get sessionFile(): string { return this.cache.snapshot.sessionFile; }
591
+ get sessionName(): string | undefined { return this.cache.snapshot.name; }
592
+ get cwd(): string { return this.cache.snapshot.cwd; }
593
+ get generation(): string { return this.cache.snapshot.generation; }
594
+ get lastSeq(): number { return this.cache.snapshot.lastSeq; }
595
+ get state(): Presentation { return copy(this.cache.state); }
596
+ get messages(): any[] { return copy(this.cache.snapshot.messages); }
597
+ get model(): any { return copy(this.cache.snapshot.state.model); }
598
+ get thinkingLevel(): any { return this.cache.snapshot.state.thinkingLevel; }
599
+ get isStreaming(): boolean { return this.cache.snapshot.state.isStreaming; }
600
+ get isCompacting(): boolean { return this.cache.snapshot.state.isCompacting; }
601
+ get isIdle(): boolean { return !this.detached && !this.failed && !this.isStreaming && !this.isCompacting && !this.bashRunning && !this.reconciling && !this.reconnecting && this.lastSeq >= this.subscribedSeq; }
602
+ get isBashRunning(): boolean { return this.bashRunning; }
603
+ get retryAttempt(): number { return this.cache.retryAttempt; }
604
+ get pendingMessageCount(): number { return this.cache.snapshot.state.pendingMessageCount; }
605
+ get autoCompactionEnabled(): boolean { return this.cache.snapshot.state.autoCompactionEnabled; }
606
+ get steeringMode(): any { return this.cache.snapshot.state.steeringMode; }
607
+ get followUpMode(): any { return this.cache.snapshot.state.followUpMode; }
608
+ get scopedModels(): any[] { return copy((this.cache.snapshot.state as Presentation).scopedModels ?? []); }
609
+ get systemPrompt(): string {
610
+ const prompt = (this.cache.snapshot.state as Presentation).systemPrompt;
611
+ return typeof prompt === "string" ? prompt : unsupported("systemPrompt (not included in client_snapshot)");
612
+ }
613
+ get routedModel(): any { return copy((this.cache.snapshot.state as Presentation).routedModel); }
614
+ get cacheWarmingStatus(): any { return copy((this.cache.snapshot.state as Presentation).cacheWarmingStatus); }
615
+ get promptTemplates(): any[] { return this.commands().filter((command) => command.source === "prompt"); }
616
+ get skills(): any[] { return []; }
617
+ getContextUsage(): any { return copy(this.cache.snapshot.contextUsage); }
618
+ getSessionStats(): any { return copy(this.cache.snapshot.stats); }
619
+ getSteeringMessages(): string[] { return [...this.cache.steering]; }
620
+ getFollowUpMessages(): string[] { return [...this.cache.followUp]; }
621
+ getAllTools(): any[] { return copy(this.cache.snapshot.tools); }
622
+ getActiveToolNames(): string[] { return this.cache.snapshot.tools.map((tool) => tool.name); }
623
+ getToolDefinition(name: string): any { return copy(this.cache.snapshot.tools.find((tool) => tool.name === name)); }
624
+ getLastAssistantText(): string | undefined {
625
+ const message = [...this.cache.snapshot.messages].reverse().find((message) => message.role === "assistant");
626
+ return message?.content.filter((block: any) => block.type === "text").map((block: any) => block.text).join("") || undefined;
627
+ }
628
+ supportsThinking(): boolean { return Boolean(this.model?.reasoning); }
629
+ getAvailableThinkingLevels(): string[] {
630
+ const levels = (this.cache.snapshot.state as Presentation).availableThinkingLevels ?? this.model?.thinkingLevels;
631
+ if (levels) return [...levels];
632
+ if (!this.supportsThinking()) return ["off"];
633
+ return unsupported("Available thinking levels (missing remote metadata)");
634
+ }
635
+
636
+ subscribe(listener: Listener): () => void {
637
+ this.assertConnected();
638
+ this.listeners.add(listener);
639
+ for (const event of this.activeEvents()) this.deliver(listener, event);
640
+ return () => { this.listeners.delete(listener); };
641
+ }
642
+
643
+ private activeEvents(): SessionEvent[] {
644
+ const initial: SessionEvent[] = [];
645
+ if (this.isStreaming) initial.push({ type: "agent_start" }, { type: "turn_start" });
646
+ if (this.cache.streamingMessage) initial.push({ type: "message_start", message: copy(this.cache.streamingMessage) });
647
+ for (const tool of this.cache.toolExecutions.values()) {
648
+ if (!this.cache.pendingToolCalls.has(tool.toolCallId)) continue;
649
+ initial.push({ ...copy(tool), type: "tool_execution_start" });
650
+ if (tool.partialResult) initial.push({ ...copy(tool), type: "tool_execution_update" });
651
+ }
652
+ return initial;
653
+ }
654
+
655
+ async bindExtensions(bindings: Presentation): Promise<void> {
656
+ this.assertConnected();
657
+ this.bindings = bindings;
658
+ this.uiContext = bindings.uiContext;
659
+ for (const request of this.uiRequests.splice(0)) this.present(request);
660
+ this.presentDialogs();
661
+ }
662
+
663
+ async prompt(text: string, options: Presentation = {}): Promise<any> {
664
+ if (this.reconnecting && !this.failed && !this.detached && !/^\/remote(?:\s+(?:disconnect|sessions))?\s*$/i.test(text)) throw new Error("Remote server upgrade is reconnecting; commands are paused and will not be replayed");
665
+ if (await this.options.onLocalCommand?.(text)) return "handled";
666
+ this.assertConnected();
667
+ if (options.tools || options.systemPrompt) return unsupported("Per-prompt local tools/system prompt");
668
+ const data = await this.request("prompt", { message: text, images: options.images, streamingBehavior: options.streamingBehavior });
669
+ options.preflightResult?.(data?.disposition ?? "started");
670
+ return data?.disposition;
671
+ }
672
+ async steer(text: string, images?: any[]): Promise<any> { return (await this.request("steer", { message: text, images }))?.disposition; }
673
+ async followUp(text: string, images?: any[]): Promise<any> { return (await this.request("follow_up", { message: text, images }))?.disposition; }
674
+ async abort(): Promise<void> { await this.request("abort"); }
675
+ async abortBash(): Promise<void> { await this.request("abort_bash"); }
676
+ async abortRetry(): Promise<void> { await this.request("abort_retry"); }
677
+ async compact(customInstructions?: string): Promise<any> {
678
+ const result = await this.request("compact", { customInstructions });
679
+ await this.flushReceivedEvents();
680
+ return result;
681
+ }
682
+ async exportToHtml(outputPath?: string): Promise<string> { return (await this.request("export_html", { outputPath })).path; }
683
+ async setModel(model: Presentation, _options?: Presentation): Promise<void> {
684
+ const result = await this.request("set_model", { provider: model.provider, modelId: model.id });
685
+ this.cache.snapshot.state.model = modelMetadata(result);
686
+ await this.refreshPresentation();
687
+ await this.loadThinkingLevels();
688
+ }
689
+ async cycleModel(direction: "forward" | "backward" = "forward"): Promise<any> {
690
+ if (direction !== "forward") return unsupported("Backward model cycling (RPC has no direction)");
691
+ const result = await this.request("cycle_model");
692
+ if (result) {
693
+ sanitizeModels(result);
694
+ this.cache.snapshot.state.model = result.model;
695
+ this.cache.snapshot.state.thinkingLevel = result.thinkingLevel;
696
+ await this.loadThinkingLevels();
697
+ }
698
+ return copy(result ?? undefined);
699
+ }
700
+ setThinkingLevel(level: string, _options?: Presentation): Promise<void> { return this.setting("set_thinking_level", { level }, "thinkingLevel", level); }
701
+ setAutoCompactionEnabled(enabled: boolean): Promise<void> { return this.setting("set_auto_compaction", { enabled }, "autoCompactionEnabled", enabled); }
702
+ setAutoRetryEnabled(enabled: boolean): Promise<void> { return this.setting("set_auto_retry", { enabled }, "autoRetryEnabled", enabled); }
703
+ setSteeringMode(mode: string): Promise<void> { return this.setting("set_steering_mode", { mode }, "steeringMode", mode); }
704
+ setFollowUpMode(mode: string): Promise<void> { return this.setting("set_follow_up_mode", { mode }, "followUpMode", mode); }
705
+ setSessionName(name: string): Promise<void> {
706
+ return this.setting("set_session_name", { name }, "sessionName", name.trim()).then(() => { this.cache.snapshot.name = name.trim(); });
707
+ }
708
+ private setting(type: string, payload: Presentation, key: string, value: unknown): Promise<void> {
709
+ const operation = this.request(type, payload).then(async () => {
710
+ if (type === "set_thinking_level") {
711
+ const state = await this.request("get_state");
712
+ value = state.thinkingLevel;
713
+ }
714
+ (this.cache.snapshot.state as Presentation)[key] = value;
715
+ });
716
+ // Native UI uses synchronous setters. Observe failures even when it ignores the returned promise.
717
+ void operation.catch((error) => this.report(error));
718
+ return operation;
719
+ }
720
+ async executeBash(command: string, onChunk?: (chunk: string) => void, options: Presentation = {}): Promise<any> {
721
+ this.assertConnected();
722
+ if (options.operations) return unsupported("Local bash operations");
723
+ if (this.bashRunning) throw new Error("A remote bash command is already running on this client");
724
+ this.bashRunning = true;
725
+ this.bashOutput = onChunk;
726
+ try {
727
+ const result = await this.request("bash", { command, excludeFromContext: options.excludeFromContext });
728
+ this.pendingBashSnapshot = true;
729
+ await this.flushReceivedEvents();
730
+ // recordBashResult persists without normal message/entry events, including
731
+ // intercepted user_bash results. Rebase at a snapshot cursor before redraw.
732
+ await this.reconcile();
733
+ if (!this.isStreaming) this.pendingBashSnapshot = false;
734
+ await this.flushReceivedEvents();
735
+ return result;
736
+ } finally {
737
+ this.bashOutput = undefined;
738
+ this.bashRunning = false;
739
+ this.resolveIdle();
740
+ }
741
+ }
742
+ waitForIdle(): Promise<void> {
743
+ this.assertConnected();
744
+ if (this.isIdle) return Promise.resolve();
745
+ return new Promise((resolve, reject) => this.idleWaiters.add({ resolve, reject }));
746
+ }
747
+
748
+ async clearQueue(): Promise<{ steering: string[]; followUp: string[] }> {
749
+ const result = await this.request("clear_queue");
750
+ this.cache.steering = [];
751
+ this.cache.followUp = [];
752
+ (this.cache.snapshot.state as Presentation).pendingMessageCount = 0;
753
+ return copy(result);
754
+ }
755
+ async cycleThinkingLevel(): Promise<string | undefined> {
756
+ const result = await this.request("cycle_thinking_level");
757
+ if (result?.level) this.cache.snapshot.state.thinkingLevel = result.level;
758
+ return result?.level;
759
+ }
760
+ private async loadThinkingLevels(): Promise<void> {
761
+ const result = await this.request("get_available_thinking_levels");
762
+ (this.cache.snapshot.state as Presentation).availableThinkingLevels = copy(result.levels);
763
+ }
764
+ abortCompaction(): never { return unsupported("abortCompaction (no daemon RPC)"); }
765
+ abortBranchSummary(): never { return unsupported("abortBranchSummary (no daemon RPC)"); }
766
+ navigateTree(): never { return unsupported("navigateTree (no daemon RPC)"); }
767
+ setScopedModels(): never { return unsupported("setScopedModels (no daemon RPC)"); }
768
+ setCacheWarmingMode(): never { return unsupported("setCacheWarmingMode (no daemon RPC)"); }
769
+ recordBashResult(): never { return unsupported("recordBashResult (daemon owns persistence)"); }
770
+ exportToJsonl(): never { return unsupported("exportToJsonl (no daemon RPC)"); }
771
+ async reload(): Promise<void> {
772
+ if (!this.client.server?.capabilities?.includes("remote-reload-v1")) throw new Error("Update pi-better-server on the remote host to enable /reload");
773
+ await this.request("client_reload");
774
+ await this.refreshPresentation(true);
775
+ }
776
+ getUserMessagesForForking(): never { return unsupported("Forking a pinned remote session"); }
777
+
778
+ /** A transfer can resume this source in a new hosted generation without closing the socket. */
779
+ async reconcileAfterTransfer(): Promise<void> {
780
+ this.assertConnected();
781
+ await this.reconcile();
782
+ await this.flushReceivedEvents();
783
+ }
784
+
785
+ /** Detach only. The caller owns the connection; a lost UI never aborts the remote agent. */
786
+ dispose(): void {
787
+ if (this.detached) return;
788
+ this.detached = true;
789
+ this.transportEpoch++;
790
+ this.reconnectAbort?.abort();
791
+ this.detachEvents?.();
792
+ this.deactivateClose?.();
793
+ this.deactivateClose = undefined;
794
+ this.listeners.clear();
795
+ this.buffered = [];
796
+ this.uiRequests.length = 0;
797
+ this.cancelLocalDialogs();
798
+ this.uiContext = undefined;
799
+ this.bindings = {};
800
+ this.rejectIdle(new Error("Remote session detached"));
801
+ if (this.controller) {
802
+ this.controller = false;
803
+ void this.client.call({ type: "release_control", sessionId: this.sessionId }).catch(() => undefined);
804
+ }
805
+ this.cleanupReplacement();
806
+ }
807
+
808
+ private commands(): any[] {
809
+ const commands: any[] = this.cache.snapshot.commands.filter((command) => !this.options.onLocalCommand || (command.invocationName ?? command.name) !== "remote").map((command) => ({ ...copy(command), invocationName: command.invocationName ?? command.name,
810
+ filePath: command.sourceInfo?.path ?? `remote:/commands/${command.name}`,
811
+ sourceInfo: command.sourceInfo ?? { path: "remote", source: "remote", scope: "project", origin: "top-level" },
812
+ handler: (args: string) => this.prompt(`/${command.invocationName ?? command.name}${args ? ` ${args}` : ""}`) }));
813
+ if (this.options.onLocalCommand) commands.unshift({
814
+ name: "remote", invocationName: "remote", description: "Open remote connection options",
815
+ filePath: "client:/remote", sourceInfo: { path: "client", source: "client", scope: "user", origin: "top-level" },
816
+ getArgumentCompletions: (prefix: string) => this.options.localCommandCompletions?.(prefix) ?? remoteArgumentCompletions(prefix, true),
817
+ handler: (args: string) => this.prompt(`/remote${args ? ` ${args}` : ""}`),
818
+ });
819
+ return commands;
820
+ }
821
+ private assertConnected(): void {
822
+ if (this.failed) throw this.failed;
823
+ if (this.detached) throw new Error("Remote session is detached");
824
+ }
825
+ private async request(type: string, payload: Presentation = {}): Promise<any> {
826
+ this.assertConnected();
827
+ const reads = ["client_snapshot", "subscribe", "acquire_control", "get_available_thinking_levels", "get_available_models"];
828
+ if (this.reconnecting && !reads.includes(type)) throw new Error("Remote server upgrade is reconnecting; commands are disabled until it completes");
829
+ if (this.reconciling && !reads.includes(type)) throw new Error("Remote snapshot reconciliation is in progress; commands are disabled until it completes");
830
+ if (!this.transportReady) throw new Error("Remote server upgrade is reconnecting; requests are paused");
831
+ const client = this.client;
832
+ const epoch = this.transportEpoch;
833
+ try {
834
+ const response = await client.call({ ...payload, type, sessionId: this.sessionId });
835
+ if (epoch !== this.transportEpoch || client !== this.client) throw new SupersededTransportError();
836
+ this.assertConnected();
837
+ return response.data;
838
+ } catch (error) {
839
+ if (epoch !== this.transportEpoch) throw new SupersededTransportError();
840
+ throw error;
841
+ }
842
+ }
843
+ private async resubscribe(): Promise<void> {
844
+ const response = await this.request("subscribe", { sinceSeq: this.lastSeq });
845
+ if (response?.truncated || (response?.generation !== undefined && response.generation !== this.generation)) {
846
+ await this.reconcile();
847
+ } else {
848
+ this.trackSubscription(response);
849
+ }
850
+ }
851
+ private trackSubscription(response: Presentation | undefined): void {
852
+ const seq = response?.lastSeq ?? this.lastSeq;
853
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new Error("Invalid remote subscription cursor");
854
+ this.subscribedSeq = Math.max(seq, this.lastSeq);
855
+ }
856
+ private receive(envelope: Envelope, client = this.client, epoch = this.transportEpoch): void {
857
+ if (this.detached || this.failed || client !== this.client || epoch !== this.transportEpoch || envelope.sessionId !== this.sessionId) return;
858
+ // Arm before close even if an earlier metadata read is pending. The new peer
859
+ // must still prove the expected build and an authoritative session snapshot.
860
+ if (this.options.reconnectAfterUpgrade) {
861
+ const notice = loggedUpgrade(envelope, this.sessionId, this.generation, this.lastSeq);
862
+ if (notice && !this.pendingUpgrade) {
863
+ this.pendingUpgrade = notice;
864
+ this.upgradeStatus("restarting", notice);
865
+ }
866
+ }
867
+ this.buffered.push(envelope);
868
+ if (this.receiving) this.drain();
869
+ }
870
+ private draining?: Promise<void>;
871
+ private drain(): void {
872
+ if (this.draining || this.reconciling || !this.receiving || this.detached || this.failed) return;
873
+ this.draining = this.drainEvents().catch((error) => this.fail(error)).finally(() => {
874
+ this.draining = undefined;
875
+ if (this.buffered.length) this.drain();
876
+ });
877
+ }
878
+ private async drainEvents(): Promise<void> {
879
+ const epoch = this.transportEpoch;
880
+ while (this.buffered.length && !this.reconciling && this.receiving && !this.detached && !this.failed && epoch === this.transportEpoch) {
881
+ const envelope = this.buffered.shift()!;
882
+ try {
883
+ const event = this.cache.apply(envelope);
884
+ if (!event) continue;
885
+ // Entries must be ready before native compaction handling rebuilds the chat.
886
+ if (["compaction_end", "auto_compaction_end"].includes(event.type)) await this.reconcile();
887
+ if (event.type === "agent_end" && this.client.server?.piVersion.startsWith("0.") && !event.willRetry) {
888
+ this.cache.snapshot.state.isStreaming = false;
889
+ }
890
+ if (event.type === "extension_ui_request") this.present(event);
891
+ else if (event.type === "extension_ui_resolved") {
892
+ this.dialogs.delete(event.id);
893
+ this.dialogControllers.get(event.id)?.abort();
894
+ this.dialogControllers.delete(event.id);
895
+ } else {
896
+ if (event.type === "bash_execution_update") this.bashOutput?.(event.delta);
897
+ this.emit(event);
898
+ }
899
+ // Persisted message IDs and usage are not in message_end events. Refresh on
900
+ // lifecycle boundaries, never on an interval and never by polling tools.
901
+ // Bash results executed during a run are persisted only when Pi settles.
902
+ if (event.type === "remote_resources_reloaded") await this.refreshPresentation(true);
903
+ if (event.type === "agent_settled" && this.pendingBashSnapshot) {
904
+ await this.reconcile();
905
+ this.pendingBashSnapshot = this.isStreaming;
906
+ } else if (["agent_settled", "turn_end"].includes(event.type)) await this.refreshPresentation();
907
+ this.resolveEventWaiters();
908
+ this.resolveIdle();
909
+ } catch (error) {
910
+ if (error instanceof SnapshotRequiredError) await this.reconcile();
911
+ else throw error;
912
+ }
913
+ }
914
+ }
915
+ private reconcile(): Promise<void> {
916
+ if (this.reconciling) return this.reconciling;
917
+ this.reconciling = (async () => {
918
+ this.cancelLocalDialogs();
919
+ for (let attempt = 0; attempt < 3; attempt++) {
920
+ const snapshot = await this.request("client_snapshot") as ClientSnapshot;
921
+ if (snapshot.sessionId !== this.sessionId) throw new Error("client_snapshot returned a different session");
922
+ this.assertConnected();
923
+ this.cache.replace(snapshot);
924
+ this.subscribedSeq = this.lastSeq;
925
+ this.buffered = this.buffered.filter((envelope) =>
926
+ (envelope.generation === undefined || envelope.generation === this.generation) &&
927
+ typeof envelope.seq === "number" && envelope.seq > this.lastSeq);
928
+ const replay = await this.request("subscribe", { sinceSeq: this.lastSeq });
929
+ if (replay?.truncated || (replay?.generation !== undefined && replay.generation !== this.generation)) continue;
930
+ this.trackSubscription(replay);
931
+ if (this.controller) {
932
+ const lease = await this.request("acquire_control");
933
+ for (const dialog of lease?.needsInput ?? []) this.dialogs.set(dialog.id, dialog);
934
+ }
935
+ await this.loadThinkingLevels();
936
+ this.assertConnected();
937
+ this.emit({ type: "remote_snapshot", snapshot: copy(this.cache.snapshot) });
938
+ return;
939
+ }
940
+ throw new Error("Remote snapshot could not establish a contiguous subscription");
941
+ })().catch((error) => {
942
+ this.fail(error);
943
+ throw error;
944
+ }).finally(() => {
945
+ this.reconciling = undefined;
946
+ this.drain();
947
+ this.presentDialogs();
948
+ this.resolveEventWaiters();
949
+ this.resolveIdle();
950
+ });
951
+ return this.reconciling;
952
+ }
953
+ private presentationRefresh?: Promise<void>;
954
+ private refreshPresentation(requireFresh = false): Promise<void> {
955
+ if (this.presentationRefresh) {
956
+ const pending = this.presentationRefresh;
957
+ return requireFresh ? pending.then(() => this.refreshPresentation()) : pending;
958
+ }
959
+ this.presentationRefresh = (async () => {
960
+ const previous = this.cache.snapshot;
961
+ const snapshot = await this.request("client_snapshot") as ClientSnapshot;
962
+ validateSnapshot(snapshot);
963
+ if (snapshot.sessionId !== this.sessionId) throw new Error("client_snapshot returned a different session");
964
+ if (this.detached || this.failed || this.reconciling || this.cache.snapshot !== previous) return;
965
+ if (snapshot.generation !== this.generation) { await this.reconcile(); return; }
966
+ // Keep the live message/lifecycle cursor: this request may cover later events
967
+ // still in transit. Only replace presentation data omitted by native events.
968
+ for (const key of ["entries", "leafId", "tools", "models", "commands", "contextUsage", "stats"] as const) {
969
+ (this.cache.snapshot as Presentation)[key] = copy(snapshot[key]);
970
+ }
971
+ sanitizeModels(this.cache.snapshot);
972
+ this.emit({ type: "remote_metadata_updated" });
973
+ this.emit({ type: "session_info_changed", name: this.sessionName });
974
+ })().finally(() => { this.presentationRefresh = undefined; });
975
+ return this.presentationRefresh;
976
+ }
977
+ private disconnect(client = this.client, epoch = this.transportEpoch): void {
978
+ if (this.detached || this.failed || client !== this.client || epoch !== this.transportEpoch) return;
979
+ if (this.pendingUpgrade && this.options.reconnectAfterUpgrade) {
980
+ if (this.reconnecting) this.invalidateTransport();
981
+ else this.reconnectUpgrade(this.pendingUpgrade);
982
+ return;
983
+ }
984
+ this.controller = false;
985
+ this.fail(new Error("Remote connection closed; reconnect and obtain a fresh snapshot before sending commands"));
986
+ this.notifyDisconnect();
987
+ }
988
+ private fail(error: unknown): void {
989
+ if (error instanceof SupersededTransportError) return;
990
+ if (this.detached || this.failed) return;
991
+ this.failed = error instanceof Error ? error : new Error(String(error));
992
+ this.detachEvents?.();
993
+ this.deactivateClose?.();
994
+ this.deactivateClose = undefined;
995
+ this.cancelLocalDialogs();
996
+ this.rejectIdle(this.failed);
997
+ this.report(this.failed);
998
+ }
999
+ private notifyDisconnect(): void {
1000
+ if (this.disconnectNotified || this.detached) return;
1001
+ this.disconnectNotified = true;
1002
+ this.options.onDisconnect?.();
1003
+ }
1004
+
1005
+ private upgradeStatus(phase: "restarting" | "reconnecting" | "ready", notice: RuntimeUpgradeNotice): void {
1006
+ try { this.options.onUpgradeStatus?.(phase, notice); }
1007
+ catch (error) { this.report(error); }
1008
+ }
1009
+
1010
+ private cleanupReplacement(): void {
1011
+ const dispose = this.disposeReplacement;
1012
+ this.disposeReplacement = undefined;
1013
+ if (!dispose) return;
1014
+ this.client.close();
1015
+ void Promise.resolve().then(dispose).catch(error => this.report(error));
1016
+ }
1017
+
1018
+ private invalidateTransport(): void {
1019
+ this.transportEpoch++;
1020
+ this.transportReady = false;
1021
+ this.receiving = false;
1022
+ this.controller = false;
1023
+ this.detachEvents?.();
1024
+ this.deactivateClose?.();
1025
+ this.buffered = [];
1026
+ this.uiRequests.length = 0;
1027
+ this.cancelLocalDialogs();
1028
+ for (const waiter of this.eventWaiters) waiter.reject(new SupersededTransportError());
1029
+ this.eventWaiters.clear();
1030
+ }
1031
+
1032
+ private reconnectUpgrade(notice: RuntimeUpgradeNotice): void {
1033
+ const reconnect = this.options.reconnectAfterUpgrade!;
1034
+ const abort = new AbortController();
1035
+ this.reconnectAbort = abort;
1036
+ this.invalidateTransport();
1037
+ this.reconnecting = (async () => {
1038
+ // One worker owns all successive replacements, including a restart that
1039
+ // closes the next peer before its snapshot/control/replay finishes.
1040
+ for (;;) {
1041
+ const previous = this.client;
1042
+ this.pendingUpgrade = undefined;
1043
+ this.upgradeStatus("reconnecting", notice);
1044
+ await Promise.allSettled([this.reconciling, this.presentationRefresh, this.draining]);
1045
+ abort.signal.throwIfAborted();
1046
+ this.assertConnected();
1047
+ let replacement: ReplacementRemoteTransport | undefined;
1048
+ let adopted = false;
1049
+ try {
1050
+ replacement = await reconnect(notice, abort.signal);
1051
+ abort.signal.throwIfAborted();
1052
+ this.assertConnected();
1053
+ validateReplacement(replacement.client, previous, notice);
1054
+ this.cleanupReplacement();
1055
+ const client = replacement.client;
1056
+ const epoch = this.transportEpoch;
1057
+ this.client = client;
1058
+ this.transportReady = true;
1059
+ this.presentationRefresh = undefined;
1060
+ this.disposeReplacement = replacement.dispose ?? (() => {});
1061
+ adopted = true;
1062
+ this.detachEvents = client.onEvent(event => this.receive(event, client, epoch));
1063
+ this.deactivateClose = client.onClose(() => this.disconnect(client, epoch));
1064
+ this.controller = true;
1065
+ await this.reconcile();
1066
+ this.assertConnected();
1067
+ if (epoch !== this.transportEpoch) throw new SupersededTransportError();
1068
+ for (const event of this.activeEvents()) this.emit(event);
1069
+ this.receiving = true;
1070
+ this.drain();
1071
+ await this.flushReceivedEvents();
1072
+ this.assertConnected();
1073
+ if (epoch !== this.transportEpoch) throw new SupersededTransportError();
1074
+ this.options.onReconnected?.(client);
1075
+ this.disconnectNotified = false;
1076
+ this.upgradeStatus("ready", notice);
1077
+ // Status callbacks may close a peer whose next notice is already armed.
1078
+ if (epoch !== this.transportEpoch) throw new SupersededTransportError();
1079
+ return;
1080
+ } catch (error) {
1081
+ if (!(error instanceof SupersededTransportError) || !this.pendingUpgrade || this.detached || this.failed) throw error;
1082
+ notice = this.pendingUpgrade;
1083
+ } finally {
1084
+ if (!adopted && replacement) {
1085
+ replacement.client.close();
1086
+ await replacement.dispose?.();
1087
+ }
1088
+ }
1089
+ }
1090
+ })().catch(error => {
1091
+ if (this.detached) return;
1092
+ this.controller = false;
1093
+ this.fail(error);
1094
+ this.cleanupReplacement();
1095
+ this.notifyDisconnect();
1096
+ }).finally(() => {
1097
+ this.reconnecting = undefined;
1098
+ if (this.reconnectAbort === abort) this.reconnectAbort = undefined;
1099
+ this.drain();
1100
+ this.presentDialogs();
1101
+ this.resolveEventWaiters();
1102
+ this.resolveIdle();
1103
+ });
1104
+ }
1105
+
1106
+ private report(error: unknown): void {
1107
+ if (this.detached) return;
1108
+ const message = error instanceof Error ? error.message : String(error);
1109
+ this.uiContext?.notify?.(message, "error");
1110
+ this.bindings.onError?.({ extensionPath: "remote", error: message });
1111
+ }
1112
+ private deliver(listener: Listener, event: SessionEvent): void {
1113
+ try { void Promise.resolve(listener(copy(event))).catch((error) => this.report(error)); }
1114
+ catch (error) { this.report(error); }
1115
+ }
1116
+ private emit(event: SessionEvent): void {
1117
+ for (const listener of this.listeners) this.deliver(listener, event);
1118
+ }
1119
+ private async flushReceivedEvents(): Promise<void> {
1120
+ for (;;) {
1121
+ this.assertConnected();
1122
+ if (this.reconciling) await this.reconciling;
1123
+ const seq = this.buffered.reduce((last, event) => typeof event.seq === "number" ? Math.max(last, event.seq) : last,
1124
+ Math.max(this.lastSeq, this.subscribedSeq));
1125
+ if (seq <= this.lastSeq) return;
1126
+ await new Promise<void>((resolve, reject) => this.eventWaiters.add({ generation: this.generation, seq, resolve, reject }));
1127
+ }
1128
+ }
1129
+ private resolveEventWaiters(): void {
1130
+ for (const waiter of this.eventWaiters) {
1131
+ if (waiter.generation === this.generation && waiter.seq > this.lastSeq) continue;
1132
+ this.eventWaiters.delete(waiter);
1133
+ waiter.resolve();
1134
+ }
1135
+ }
1136
+ private resolveIdle(): void {
1137
+ if (!this.isIdle) return;
1138
+ for (const waiter of this.idleWaiters) waiter.resolve();
1139
+ this.idleWaiters.clear();
1140
+ }
1141
+ private rejectIdle(error: Error): void {
1142
+ for (const waiter of this.idleWaiters) waiter.reject(error);
1143
+ this.idleWaiters.clear();
1144
+ for (const waiter of this.eventWaiters) waiter.reject(error);
1145
+ this.eventWaiters.clear();
1146
+ }
1147
+ private cancelLocalDialogs(): void {
1148
+ for (const controller of this.dialogControllers.values()) controller.abort();
1149
+ this.dialogControllers.clear();
1150
+ this.dialogs.clear();
1151
+ }
1152
+ private presentDialogs(): void {
1153
+ if (!this.controller || !this.uiContext || this.reconciling || this.reconnecting || this.detached || this.failed) return;
1154
+ for (const dialog of this.dialogs.values()) {
1155
+ if (!this.dialogControllers.has(dialog.id)) void this.showDialog(dialog).catch((error) => this.report(error));
1156
+ }
1157
+ }
1158
+ private present(request: SessionEvent): void {
1159
+ if (["select", "confirm", "input", "editor"].includes(request.method)) {
1160
+ this.dialogs.set(request.id, request);
1161
+ this.presentDialogs();
1162
+ return;
1163
+ }
1164
+ if (!this.uiContext) { this.uiRequests.push(request); return; }
1165
+ const ui = this.uiContext;
1166
+ switch (request.method) {
1167
+ case "notify": ui.notify(request.message, request.notifyType); break;
1168
+ case "setStatus": ui.setStatus(request.statusKey, request.statusText); break;
1169
+ case "setWidget":
1170
+ if (request.widgetLines !== undefined && (!Array.isArray(request.widgetLines) || !request.widgetLines.every((line: unknown) => typeof line === "string"))) {
1171
+ throw new Error("Remote custom widget components are not supported; only text lines are supported");
1172
+ }
1173
+ ui.setWidget(request.widgetKey, request.widgetLines, { placement: request.widgetPlacement });
1174
+ break;
1175
+ case "setTitle": ui.setTitle(request.title); break;
1176
+ case "set_editor_text": ui.setEditorText(request.text); break;
1177
+ default: throw new Error(`Remote extension UI method '${request.method}' is not supported`);
1178
+ }
1179
+ }
1180
+ private async showDialog(dialog: Presentation): Promise<void> {
1181
+ const controller = new AbortController();
1182
+ this.dialogControllers.set(dialog.id, controller);
1183
+ const ui = this.uiContext;
1184
+ const options = { signal: controller.signal, timeout: dialog.timeout };
1185
+ let answer: Presentation;
1186
+ try {
1187
+ let result: unknown;
1188
+ switch (dialog.method) {
1189
+ case "select": result = await ui.select(dialog.title, dialog.options, options); break;
1190
+ case "confirm": result = await ui.confirm(dialog.title, dialog.message, options); break;
1191
+ case "input": result = await ui.input(dialog.title, dialog.placeholder, options); break;
1192
+ case "editor": result = await ui.editor(dialog.title, dialog.prefill); break;
1193
+ default: return unsupported(`Remote dialog '${dialog.method}'`);
1194
+ }
1195
+ answer = dialog.method === "confirm" && typeof result === "boolean" ? { confirmed: result }
1196
+ : typeof result === "string" ? { value: result } : { cancelled: true };
1197
+ } catch (error) {
1198
+ if (!controller.signal.aborted) this.report(error);
1199
+ answer = { cancelled: true };
1200
+ }
1201
+ if (controller.signal.aborted || !this.controller || this.detached || this.failed || !this.dialogs.has(dialog.id)) return;
1202
+ try { await this.request("extension_ui_response", { requestId: dialog.id, ...answer }); }
1203
+ finally { this.dialogs.delete(dialog.id); this.dialogControllers.delete(dialog.id); }
1204
+ }
1205
+ }