@camerontaylor/paseo-client 0.8.0-fork.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -0
- package/dist/compat/normalize-provider-models.d.ts +11 -0
- package/dist/compat/normalize-provider-models.js +51 -0
- package/dist/connection/index.d.ts +42 -0
- package/dist/connection/index.js +111 -0
- package/dist/creation/index.d.ts +47 -0
- package/dist/creation/index.js +216 -0
- package/dist/daemon-client-relay-e2ee-transport.d.ts +8 -0
- package/dist/daemon-client-relay-e2ee-transport.js +161 -0
- package/dist/daemon-client-runtime-metrics.d.ts +39 -0
- package/dist/daemon-client-runtime-metrics.js +173 -0
- package/dist/daemon-client-transport-types.d.ts +36 -0
- package/dist/daemon-client-transport-types.js +2 -0
- package/dist/daemon-client-transport-utils.d.ts +13 -0
- package/dist/daemon-client-transport-utils.js +123 -0
- package/dist/daemon-client-transport.d.ts +5 -0
- package/dist/daemon-client-transport.js +4 -0
- package/dist/daemon-client-websocket-transport.d.ts +12 -0
- package/dist/daemon-client-websocket-transport.js +140 -0
- package/dist/daemon-client.d.ts +1245 -0
- package/dist/daemon-client.js +4783 -0
- package/dist/index.d.ts +383 -0
- package/dist/index.js +407 -0
- package/dist/provider-snapshots/index.d.ts +23 -0
- package/dist/provider-snapshots/index.js +60 -0
- package/dist/terminal-stream-router.d.ts +28 -0
- package/dist/terminal-stream-router.js +109 -0
- package/dist/terminals/index.d.ts +69 -0
- package/dist/terminals/index.js +103 -0
- package/package.json +51 -0
|
@@ -0,0 +1,4783 @@
|
|
|
1
|
+
import { ProviderSnapshotUpdates } from "./provider-snapshots/index.js";
|
|
2
|
+
import { ConnectionSubscriptions, DEFAULT_CLIENT_CAPABILITIES, } from "./connection/index.js";
|
|
3
|
+
import { CreationClient } from "./creation/index.js";
|
|
4
|
+
import { CLIENT_CAPS } from "@camerontaylor/paseo-protocol/client-capabilities";
|
|
5
|
+
import { parsePluginSourceReference } from "@camerontaylor/paseo-protocol/plugin-source-reference";
|
|
6
|
+
import { AgentCreateFailedStatusPayloadSchema, AgentCreatedStatusPayloadSchema, AgentRefreshedStatusPayloadSchema, AgentResumedStatusPayloadSchema, parseServerInfoStatusPayload, RestartRequestedStatusPayloadSchema, ShutdownRequestedStatusPayloadSchema, DaemonUpdateResponseSchema, SessionInboundMessageSchema, } from "@camerontaylor/paseo-protocol/messages";
|
|
7
|
+
import { validateWSOutboundMessage } from "@camerontaylor/paseo-protocol/validation/ws-outbound";
|
|
8
|
+
import { isRelayClientWebSocketUrl } from "@camerontaylor/paseo-protocol/daemon-endpoints";
|
|
9
|
+
import { terminalSubscriptionKey } from "@camerontaylor/paseo-protocol/terminal-subscription-key";
|
|
10
|
+
import { asUint8Array, decodeFileTransferFrame, encodeFileTransferFrame, decodeTerminalStreamFrame, FileTransferOpcode, TerminalStreamOpcode, } from "@camerontaylor/paseo-protocol/binary-frames/index";
|
|
11
|
+
import { createRelayE2eeTransportFactory, createWebSocketTransportFactory, decodeMessageData, defaultWebSocketFactory, describeTransportClose, describeTransportError, } from "./daemon-client-transport.js";
|
|
12
|
+
import { DaemonClientRuntimeMetrics } from "./daemon-client-runtime-metrics.js";
|
|
13
|
+
import { normalizeListProviderModelsPayload, normalizeProviderSnapshotUpdateMessage, normalizeProvidersSnapshotPayload, } from "./compat/normalize-provider-models.js";
|
|
14
|
+
import { TerminalStreamRouter } from "./terminal-stream-router.js";
|
|
15
|
+
const consoleLogger = {
|
|
16
|
+
debug: () => { },
|
|
17
|
+
info: (obj, msg) => console.log(msg, obj),
|
|
18
|
+
warn: (obj, msg) => console.warn(msg, obj),
|
|
19
|
+
error: (obj, msg) => console.error(msg, obj),
|
|
20
|
+
};
|
|
21
|
+
const perfNow = typeof performance !== "undefined" && typeof performance.now === "function"
|
|
22
|
+
? () => performance.now()
|
|
23
|
+
: () => Date.now();
|
|
24
|
+
const PROJECT_GITHUB_CLONE_TIMEOUT_MS = 5 * 60 * 1000;
|
|
25
|
+
function normalizePassword(value) {
|
|
26
|
+
if (typeof value !== "string") {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
return value.length > 0 ? value : null;
|
|
30
|
+
}
|
|
31
|
+
function extractCorrelatedResponseIdentity(input) {
|
|
32
|
+
if (!input || typeof input !== "object") {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
const envelope = input;
|
|
36
|
+
if (envelope.type !== "session" || !envelope.message || typeof envelope.message !== "object") {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const message = envelope.message;
|
|
40
|
+
if (typeof message.type !== "string" ||
|
|
41
|
+
!(message.type === "rpc_error" ||
|
|
42
|
+
message.type.endsWith("_response") ||
|
|
43
|
+
message.type.endsWith(".response") ||
|
|
44
|
+
message.type.endsWith("/response"))) {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
if (!message.payload || typeof message.payload !== "object") {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const payload = message.payload;
|
|
51
|
+
if (typeof payload.requestId !== "string") {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
requestId: payload.requestId,
|
|
56
|
+
responseType: message.type,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// COMPAT(daemon-client-object-options): added in v0.1.102; remove after
|
|
60
|
+
// 2026-12-29 once SDK callers have migrated to object parameters.
|
|
61
|
+
function normalizeFetchAgentOptions(input, legacyOptions) {
|
|
62
|
+
if (typeof input !== "string") {
|
|
63
|
+
return input;
|
|
64
|
+
}
|
|
65
|
+
if (typeof legacyOptions === "string") {
|
|
66
|
+
return { agentId: input, requestId: legacyOptions };
|
|
67
|
+
}
|
|
68
|
+
return { agentId: input, ...legacyOptions };
|
|
69
|
+
}
|
|
70
|
+
function normalizeListCommandsOptions(input, legacyOptions) {
|
|
71
|
+
if (typeof input !== "string") {
|
|
72
|
+
return input;
|
|
73
|
+
}
|
|
74
|
+
if (typeof legacyOptions === "string") {
|
|
75
|
+
return { agentId: input, requestId: legacyOptions };
|
|
76
|
+
}
|
|
77
|
+
return { agentId: input, ...legacyOptions };
|
|
78
|
+
}
|
|
79
|
+
class DaemonRpcError extends Error {
|
|
80
|
+
constructor(params) {
|
|
81
|
+
const parts = [params.error];
|
|
82
|
+
if (params.requestType)
|
|
83
|
+
parts.push(`requestType=${params.requestType}`);
|
|
84
|
+
if (params.code)
|
|
85
|
+
parts.push(`code=${params.code}`);
|
|
86
|
+
super(parts.join(" "));
|
|
87
|
+
this.name = "DaemonRpcError";
|
|
88
|
+
this.requestId = params.requestId;
|
|
89
|
+
this.requestType = params.requestType;
|
|
90
|
+
this.code = params.code;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
class DaemonProtocolError extends Error {
|
|
94
|
+
constructor(identity) {
|
|
95
|
+
const responseLabel = identity.responseType ?? "unknown response";
|
|
96
|
+
super(`Response validation failed for ${responseLabel}`);
|
|
97
|
+
this.code = "invalid_response";
|
|
98
|
+
this.name = "DaemonProtocolError";
|
|
99
|
+
this.requestId = identity.requestId;
|
|
100
|
+
this.responseType = identity.responseType;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
class PingTimeoutError extends Error {
|
|
104
|
+
constructor(timeoutMs) {
|
|
105
|
+
super(`Ping timed out (${timeoutMs}ms)`);
|
|
106
|
+
this.timeoutMs = timeoutMs;
|
|
107
|
+
this.name = "PingTimeoutError";
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function toTimeoutError(error, label, timeoutMs) {
|
|
111
|
+
if (error instanceof PingTimeoutError) {
|
|
112
|
+
return new Error(`${label} timed out (${timeoutMs}ms)`);
|
|
113
|
+
}
|
|
114
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
115
|
+
}
|
|
116
|
+
const DEFAULT_RECONNECT_BASE_DELAY_MS = 1500;
|
|
117
|
+
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30000;
|
|
118
|
+
const DEFAULT_SESSION_RPC_TIMEOUT_MS = 60000;
|
|
119
|
+
const PUSH_TOKEN_REVOCATION_TIMEOUT_MS = 2000;
|
|
120
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 15000;
|
|
121
|
+
const DEFAULT_LIVENESS_TIMEOUT_MS = 5000;
|
|
122
|
+
const LIVENESS_HEARTBEAT_INTERVAL_MS = 10000;
|
|
123
|
+
const LIVENESS_HEARTBEAT_TIMEOUT_MS = 15000;
|
|
124
|
+
const LIVENESS_FAILURE_RECONNECT_THRESHOLD = 2;
|
|
125
|
+
/** Default timeout for waiting for connection before sending queued messages */
|
|
126
|
+
const DEFAULT_SEND_QUEUE_TIMEOUT_MS = DEFAULT_SESSION_RPC_TIMEOUT_MS;
|
|
127
|
+
const DEFAULT_DICTATION_FINISH_ACCEPT_TIMEOUT_MS = DEFAULT_SESSION_RPC_TIMEOUT_MS;
|
|
128
|
+
const DEFAULT_DICTATION_FINISH_FALLBACK_TIMEOUT_MS = 5 * 60 * 1000;
|
|
129
|
+
const DEFAULT_DICTATION_FINISH_TIMEOUT_GRACE_MS = 5000;
|
|
130
|
+
function isWaiterTimeoutError(error) {
|
|
131
|
+
return error instanceof Error && error.message.startsWith("Timeout waiting for message");
|
|
132
|
+
}
|
|
133
|
+
function normalizeClientId(value) {
|
|
134
|
+
if (typeof value !== "string") {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
const trimmed = value.trim();
|
|
138
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
139
|
+
}
|
|
140
|
+
function decodeBase64ToBytes(base64) {
|
|
141
|
+
const binary = globalThis.atob(base64);
|
|
142
|
+
const bytes = new Uint8Array(binary.length);
|
|
143
|
+
for (let index = 0; index < binary.length; index += 1) {
|
|
144
|
+
bytes[index] = binary.charCodeAt(index);
|
|
145
|
+
}
|
|
146
|
+
return bytes;
|
|
147
|
+
}
|
|
148
|
+
function legacyExplorerFileToBytes(file) {
|
|
149
|
+
let bytes;
|
|
150
|
+
if (file.encoding === "base64" && file.content) {
|
|
151
|
+
bytes = decodeBase64ToBytes(file.content);
|
|
152
|
+
}
|
|
153
|
+
else if (file.encoding === "utf-8" && file.content) {
|
|
154
|
+
bytes = new TextEncoder().encode(file.content);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
bytes = new Uint8Array();
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
bytes,
|
|
161
|
+
mime: file.mimeType ?? "application/octet-stream",
|
|
162
|
+
size: file.size,
|
|
163
|
+
path: file.path,
|
|
164
|
+
kind: file.kind,
|
|
165
|
+
modifiedAt: file.modifiedAt,
|
|
166
|
+
revision: file.revision,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function binaryFileKind(mime, encoding) {
|
|
170
|
+
if (mime.startsWith("image/")) {
|
|
171
|
+
return "image";
|
|
172
|
+
}
|
|
173
|
+
if (encoding === "utf-8" || mime.startsWith("text/") || mime === "application/json") {
|
|
174
|
+
return "text";
|
|
175
|
+
}
|
|
176
|
+
return "binary";
|
|
177
|
+
}
|
|
178
|
+
function concatByteChunks(chunks, size) {
|
|
179
|
+
const bytes = new Uint8Array(size);
|
|
180
|
+
let offset = 0;
|
|
181
|
+
for (const chunk of chunks) {
|
|
182
|
+
bytes.set(chunk, offset);
|
|
183
|
+
offset += chunk.byteLength;
|
|
184
|
+
}
|
|
185
|
+
return bytes;
|
|
186
|
+
}
|
|
187
|
+
function getTransportFrameSize(frame) {
|
|
188
|
+
if (typeof frame === "string") {
|
|
189
|
+
return frame.length;
|
|
190
|
+
}
|
|
191
|
+
return frame.byteLength;
|
|
192
|
+
}
|
|
193
|
+
function describeInboundTransportFrame(frame, rawBytes) {
|
|
194
|
+
if (typeof frame === "string") {
|
|
195
|
+
return { kind: "text", size: String(frame.length) };
|
|
196
|
+
}
|
|
197
|
+
if (rawBytes) {
|
|
198
|
+
return { kind: "binary", size: String(rawBytes.byteLength) };
|
|
199
|
+
}
|
|
200
|
+
return { kind: "unknown", size: "0" };
|
|
201
|
+
}
|
|
202
|
+
function hashForLog(value) {
|
|
203
|
+
let hash = 0;
|
|
204
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
205
|
+
hash = (hash * 31 + value.charCodeAt(index)) | 0;
|
|
206
|
+
}
|
|
207
|
+
return `h_${Math.abs(hash).toString(16)}`;
|
|
208
|
+
}
|
|
209
|
+
function toReasonCode(reason) {
|
|
210
|
+
if (!reason) {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
const normalized = reason.toLowerCase();
|
|
214
|
+
if (normalized.includes("timed out")) {
|
|
215
|
+
return "connect_timeout";
|
|
216
|
+
}
|
|
217
|
+
if (normalized.includes("disposed")) {
|
|
218
|
+
return "disposed";
|
|
219
|
+
}
|
|
220
|
+
if (normalized.includes("client closed")) {
|
|
221
|
+
return "client_closed";
|
|
222
|
+
}
|
|
223
|
+
if (normalized.includes("transport")) {
|
|
224
|
+
return "transport_error";
|
|
225
|
+
}
|
|
226
|
+
if (normalized.includes("failed to connect")) {
|
|
227
|
+
return "connect_failed";
|
|
228
|
+
}
|
|
229
|
+
return "unknown";
|
|
230
|
+
}
|
|
231
|
+
export class DaemonClient {
|
|
232
|
+
constructor(config) {
|
|
233
|
+
this.config = config;
|
|
234
|
+
this.providerSnapshotUpdates = new ProviderSnapshotUpdates({
|
|
235
|
+
fetch: (cwd) => this.requestProvidersSnapshot({ cwd }),
|
|
236
|
+
emit: (message) => this.deliverSessionMessage(message),
|
|
237
|
+
failed: (error) => this.logger.error({ err: error }, "Failed to resolve provider snapshot"),
|
|
238
|
+
});
|
|
239
|
+
this.subscriptions = new ConnectionSubscriptions({
|
|
240
|
+
timelines: (agentIds) => (this.isConnected ? this.sendTimelineSubscription(agentIds) : null),
|
|
241
|
+
events: (events) => this.sendEventSubscription(events),
|
|
242
|
+
failed: (error) => this.logger.error({ err: error }, "Failed to update connection subscriptions"),
|
|
243
|
+
});
|
|
244
|
+
this.transport = null;
|
|
245
|
+
this.transportCleanup = [];
|
|
246
|
+
this.rawMessageListeners = new Set();
|
|
247
|
+
this.messageHandlers = new Map();
|
|
248
|
+
this.eventListeners = new Set();
|
|
249
|
+
this.waiters = new Set();
|
|
250
|
+
this.checkoutStatusInFlight = new Map();
|
|
251
|
+
this.connectionListeners = new Set();
|
|
252
|
+
this.reconnectTimeout = null;
|
|
253
|
+
this.connectTimeout = null;
|
|
254
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
255
|
+
this.reconnectAttempt = 0;
|
|
256
|
+
this.shouldReconnect = true;
|
|
257
|
+
this.connectPromise = null;
|
|
258
|
+
this.connectResolve = null;
|
|
259
|
+
this.connectReject = null;
|
|
260
|
+
this.lastErrorValue = null;
|
|
261
|
+
this.connectionState = { status: "idle" };
|
|
262
|
+
this.checkoutDiffSubscriptions = new Map();
|
|
263
|
+
this.terminalDirectorySubscriptions = new Map();
|
|
264
|
+
this.fileSubscriptions = new Map();
|
|
265
|
+
this.terminalStreams = new TerminalStreamRouter();
|
|
266
|
+
this.pendingBinaryFileReads = new Map();
|
|
267
|
+
this.activeBinaryFileTransfers = new Map();
|
|
268
|
+
this.completedBinaryFileReads = new Map();
|
|
269
|
+
this.pendingSendQueue = [];
|
|
270
|
+
this.lastServerInfoMessage = null;
|
|
271
|
+
this.runtimeMetricsInterval = null;
|
|
272
|
+
this.runtimeMetrics = null;
|
|
273
|
+
this.pingProbe = null;
|
|
274
|
+
this.livenessHeartbeatTimer = null;
|
|
275
|
+
this.lastLivenessRttMs = null;
|
|
276
|
+
this.consecutiveLivenessFailures = 0;
|
|
277
|
+
// ============================================================================
|
|
278
|
+
// Agent Lifecycle
|
|
279
|
+
// ============================================================================
|
|
280
|
+
this.creations = new CreationClient({
|
|
281
|
+
supports: () => this.lastServerInfoMessage?.features?.creationLifecycle === true,
|
|
282
|
+
connected: () => this.connectionState.status === "connected",
|
|
283
|
+
requestId: () => this.createRequestId(),
|
|
284
|
+
request: (kind, input) => kind === "workspace"
|
|
285
|
+
? this.sendCorrelatedSessionRequest({
|
|
286
|
+
requestId: input.requestId,
|
|
287
|
+
message: { ...input, type: "workspace.create.request" },
|
|
288
|
+
responseType: "workspace.create.response",
|
|
289
|
+
timeout: 0,
|
|
290
|
+
})
|
|
291
|
+
: this.sendCorrelatedSessionRequest({
|
|
292
|
+
requestId: input.requestId,
|
|
293
|
+
message: { ...input, type: "agent.create.request" },
|
|
294
|
+
responseType: "agent.create.response",
|
|
295
|
+
timeout: 0,
|
|
296
|
+
}),
|
|
297
|
+
subscribe: async (kind, idempotencyKey, subscribe = true) => {
|
|
298
|
+
const result = await this.sendCorrelatedSessionRequest({
|
|
299
|
+
message: { type: "creation.subscribe.request", kind, idempotencyKey, subscribe },
|
|
300
|
+
responseType: "creation.subscribe.response",
|
|
301
|
+
});
|
|
302
|
+
if (result.error)
|
|
303
|
+
throw new Error(result.error);
|
|
304
|
+
return result.snapshot;
|
|
305
|
+
},
|
|
306
|
+
legacyAgent: (input) => this.createLegacyAgent(input),
|
|
307
|
+
legacyWorkspace: (input) => this.createLegacyWorkspace(input, input.requestId),
|
|
308
|
+
sendMessage: (id, text, options) => this.sendMessage(id, text, options),
|
|
309
|
+
});
|
|
310
|
+
this.logger = config.logger ?? consoleLogger;
|
|
311
|
+
this.logConnectionPath = isRelayClientWebSocketUrl(this.config.url) ? "relay" : "direct";
|
|
312
|
+
let parsedUrlForLog = null;
|
|
313
|
+
try {
|
|
314
|
+
parsedUrlForLog = new URL(this.config.url);
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
parsedUrlForLog = null;
|
|
318
|
+
}
|
|
319
|
+
const parsedServerIdForLog = normalizeClientId(parsedUrlForLog?.searchParams.get("serverId"));
|
|
320
|
+
this.logServerId = parsedServerIdForLog ?? parsedUrlForLog?.host ?? null;
|
|
321
|
+
const resolvedClientId = normalizeClientId(this.config.clientId);
|
|
322
|
+
if (!resolvedClientId) {
|
|
323
|
+
throw new Error("Daemon client requires a non-empty clientId");
|
|
324
|
+
}
|
|
325
|
+
this.config.clientId = resolvedClientId;
|
|
326
|
+
this.logClientIdHash = hashForLog(resolvedClientId);
|
|
327
|
+
this.logGeneration =
|
|
328
|
+
typeof this.config.runtimeGeneration === "number" &&
|
|
329
|
+
Number.isFinite(this.config.runtimeGeneration)
|
|
330
|
+
? this.config.runtimeGeneration
|
|
331
|
+
: null;
|
|
332
|
+
const runtimeMetricsIntervalMs = typeof config.runtimeMetricsIntervalMs === "number" && config.runtimeMetricsIntervalMs > 0
|
|
333
|
+
? config.runtimeMetricsIntervalMs
|
|
334
|
+
: 0;
|
|
335
|
+
if (runtimeMetricsIntervalMs > 0) {
|
|
336
|
+
const runtimeMetricsWindowMs = typeof config.runtimeMetricsWindowMs === "number" && config.runtimeMetricsWindowMs > 0
|
|
337
|
+
? Math.max(config.runtimeMetricsWindowMs, runtimeMetricsIntervalMs)
|
|
338
|
+
: undefined;
|
|
339
|
+
this.runtimeMetrics = new DaemonClientRuntimeMetrics(this.logger, {
|
|
340
|
+
connectionPath: this.logConnectionPath,
|
|
341
|
+
serverId: this.logServerId,
|
|
342
|
+
getConnectionStatus: () => this.connectionState.status,
|
|
343
|
+
}, runtimeMetricsWindowMs ? { windowMs: runtimeMetricsWindowMs } : undefined);
|
|
344
|
+
this.runtimeMetricsInterval = setInterval(() => {
|
|
345
|
+
this.runtimeMetrics?.flush();
|
|
346
|
+
}, runtimeMetricsIntervalMs);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
// ============================================================================
|
|
350
|
+
// Connection
|
|
351
|
+
// ============================================================================
|
|
352
|
+
async connect() {
|
|
353
|
+
if (this.connectionState.status === "disposed") {
|
|
354
|
+
throw new Error("Daemon client is disposed");
|
|
355
|
+
}
|
|
356
|
+
if (this.connectionState.status === "connected") {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (this.connectPromise) {
|
|
360
|
+
return this.connectPromise;
|
|
361
|
+
}
|
|
362
|
+
this.shouldReconnect = true;
|
|
363
|
+
this.connectPromise = new Promise((resolve, reject) => {
|
|
364
|
+
this.connectResolve = resolve;
|
|
365
|
+
this.connectReject = reject;
|
|
366
|
+
this.attemptConnect();
|
|
367
|
+
});
|
|
368
|
+
return this.connectPromise;
|
|
369
|
+
}
|
|
370
|
+
attemptConnect() {
|
|
371
|
+
if (this.connectionState.status === "disposed") {
|
|
372
|
+
this.rejectConnect(new Error("Daemon client is disposed"));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
if (!this.shouldReconnect) {
|
|
376
|
+
this.rejectConnect(new Error("Daemon client is closed"));
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
if (this.connectionState.status === "connecting") {
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const headers = {};
|
|
383
|
+
const password = normalizePassword(this.config.password);
|
|
384
|
+
if (password) {
|
|
385
|
+
headers.Authorization = `Bearer ${password}`;
|
|
386
|
+
}
|
|
387
|
+
else if (this.config.authHeader) {
|
|
388
|
+
headers.Authorization = this.config.authHeader;
|
|
389
|
+
}
|
|
390
|
+
const protocols = password ? [`paseo.bearer.${password}`] : undefined;
|
|
391
|
+
try {
|
|
392
|
+
// Reconnect can overlap with browser close/error delivery ordering.
|
|
393
|
+
// Always dispose previous transport before constructing the next one.
|
|
394
|
+
this.disposeTransport();
|
|
395
|
+
const baseTransportFactory = this.config.transportFactory ??
|
|
396
|
+
createWebSocketTransportFactory(this.config.webSocketFactory ?? defaultWebSocketFactory);
|
|
397
|
+
const shouldUseRelayE2ee = this.config.e2ee?.enabled === true && isRelayClientWebSocketUrl(this.config.url);
|
|
398
|
+
let transportFactory = baseTransportFactory;
|
|
399
|
+
if (shouldUseRelayE2ee) {
|
|
400
|
+
const daemonPublicKeyB64 = this.config.e2ee?.daemonPublicKeyB64;
|
|
401
|
+
if (!daemonPublicKeyB64) {
|
|
402
|
+
throw new Error("daemonPublicKeyB64 is required for relay E2EE");
|
|
403
|
+
}
|
|
404
|
+
transportFactory = createRelayE2eeTransportFactory({
|
|
405
|
+
baseFactory: baseTransportFactory,
|
|
406
|
+
daemonPublicKeyB64,
|
|
407
|
+
logger: this.logger,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
const transportUrl = this.resolveTransportUrlForAttempt();
|
|
411
|
+
const transport = transportFactory({
|
|
412
|
+
url: transportUrl,
|
|
413
|
+
headers,
|
|
414
|
+
...(protocols ? { protocols } : {}),
|
|
415
|
+
});
|
|
416
|
+
this.transport = transport;
|
|
417
|
+
this.lastServerInfoMessage = null;
|
|
418
|
+
this.updateConnectionState({
|
|
419
|
+
status: "connecting",
|
|
420
|
+
attempt: this.reconnectAttempt,
|
|
421
|
+
}, { event: "CONNECT_REQUEST" });
|
|
422
|
+
this.resetConnectTimeout();
|
|
423
|
+
const timeoutMs = Math.max(1, this.config.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS);
|
|
424
|
+
this.connectTimeout = setTimeout(() => {
|
|
425
|
+
if (this.connectionState.status !== "connecting") {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
this.lastErrorValue = "Connection timed out";
|
|
429
|
+
this.disposeTransport(1001, "Connection timed out");
|
|
430
|
+
this.scheduleReconnect({
|
|
431
|
+
reason: "Connection timed out",
|
|
432
|
+
event: "CONNECT_TIMEOUT",
|
|
433
|
+
reasonCode: "connect_timeout",
|
|
434
|
+
});
|
|
435
|
+
}, timeoutMs);
|
|
436
|
+
this.transportCleanup = [
|
|
437
|
+
transport.onOpen(() => {
|
|
438
|
+
if (this.pendingGenericTransportErrorTimeout) {
|
|
439
|
+
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
|
440
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
441
|
+
}
|
|
442
|
+
this.lastErrorValue = null;
|
|
443
|
+
this.sendHelloMessage();
|
|
444
|
+
}),
|
|
445
|
+
transport.onClose((event) => {
|
|
446
|
+
this.resetConnectTimeout();
|
|
447
|
+
if (this.pendingGenericTransportErrorTimeout) {
|
|
448
|
+
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
|
449
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
450
|
+
}
|
|
451
|
+
const reason = describeTransportClose(event);
|
|
452
|
+
if (reason) {
|
|
453
|
+
this.lastErrorValue = reason;
|
|
454
|
+
}
|
|
455
|
+
this.scheduleReconnect({
|
|
456
|
+
reason,
|
|
457
|
+
event: "TRANSPORT_CLOSE",
|
|
458
|
+
reasonCode: "transport_closed",
|
|
459
|
+
});
|
|
460
|
+
}),
|
|
461
|
+
transport.onError((event) => {
|
|
462
|
+
this.resetConnectTimeout();
|
|
463
|
+
const reason = describeTransportError(event);
|
|
464
|
+
const isGeneric = reason === "Transport error";
|
|
465
|
+
// Browser WebSocket.onerror often provides no useful details and is followed
|
|
466
|
+
// by a close event (often with code 1006). Prefer surfacing the close details
|
|
467
|
+
// instead of immediately disconnecting with a generic "Transport error".
|
|
468
|
+
if (isGeneric) {
|
|
469
|
+
this.lastErrorValue ?? (this.lastErrorValue = reason);
|
|
470
|
+
if (!this.pendingGenericTransportErrorTimeout) {
|
|
471
|
+
this.pendingGenericTransportErrorTimeout = setTimeout(() => {
|
|
472
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
473
|
+
if (this.connectionState.status === "connected" ||
|
|
474
|
+
this.connectionState.status === "connecting") {
|
|
475
|
+
this.lastErrorValue = reason;
|
|
476
|
+
this.scheduleReconnect({
|
|
477
|
+
reason,
|
|
478
|
+
event: "TRANSPORT_ERROR",
|
|
479
|
+
reasonCode: "transport_error",
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
}, 250);
|
|
483
|
+
}
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (this.pendingGenericTransportErrorTimeout) {
|
|
487
|
+
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
|
488
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
489
|
+
}
|
|
490
|
+
this.lastErrorValue = reason;
|
|
491
|
+
this.scheduleReconnect({
|
|
492
|
+
reason,
|
|
493
|
+
event: "TRANSPORT_ERROR",
|
|
494
|
+
reasonCode: "transport_error",
|
|
495
|
+
});
|
|
496
|
+
}),
|
|
497
|
+
transport.onMessage((data) => this.handleTransportMessage(data)),
|
|
498
|
+
];
|
|
499
|
+
}
|
|
500
|
+
catch (error) {
|
|
501
|
+
this.resetConnectTimeout();
|
|
502
|
+
const message = error instanceof Error ? error.message : "Failed to connect";
|
|
503
|
+
this.lastErrorValue = message;
|
|
504
|
+
this.scheduleReconnect({
|
|
505
|
+
reason: message,
|
|
506
|
+
event: "CONNECT_FAILED",
|
|
507
|
+
reasonCode: "connect_failed",
|
|
508
|
+
});
|
|
509
|
+
this.rejectConnect(error instanceof Error ? error : new Error(message));
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
resolveConnect() {
|
|
513
|
+
if (this.connectResolve) {
|
|
514
|
+
this.connectResolve();
|
|
515
|
+
}
|
|
516
|
+
this.connectPromise = null;
|
|
517
|
+
this.connectResolve = null;
|
|
518
|
+
this.connectReject = null;
|
|
519
|
+
}
|
|
520
|
+
rejectConnect(error) {
|
|
521
|
+
if (this.connectReject) {
|
|
522
|
+
this.connectReject(error);
|
|
523
|
+
}
|
|
524
|
+
this.connectPromise = null;
|
|
525
|
+
this.connectResolve = null;
|
|
526
|
+
this.connectReject = null;
|
|
527
|
+
}
|
|
528
|
+
async close() {
|
|
529
|
+
if (this.connectionState.status === "disposed") {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
this.shouldReconnect = false;
|
|
533
|
+
this.subscriptions.close();
|
|
534
|
+
this.connectPromise = null;
|
|
535
|
+
this.connectResolve = null;
|
|
536
|
+
this.connectReject = null;
|
|
537
|
+
if (this.reconnectTimeout) {
|
|
538
|
+
clearTimeout(this.reconnectTimeout);
|
|
539
|
+
this.reconnectTimeout = null;
|
|
540
|
+
}
|
|
541
|
+
this.resetConnectTimeout();
|
|
542
|
+
this.disposeTransport(1000, "Client closed");
|
|
543
|
+
this.providerSnapshotUpdates.clear();
|
|
544
|
+
this.clearWaiters(new Error("Daemon client closed"));
|
|
545
|
+
this.creations.close();
|
|
546
|
+
this.rejectPendingSendQueue(new Error("Daemon client closed"));
|
|
547
|
+
this.rejectPingProbe(new Error("Daemon client closed"));
|
|
548
|
+
this.terminalStreams.clearSlots();
|
|
549
|
+
this.fileSubscriptions.clear();
|
|
550
|
+
this.lastServerInfoMessage = null;
|
|
551
|
+
if (this.runtimeMetricsInterval) {
|
|
552
|
+
clearInterval(this.runtimeMetricsInterval);
|
|
553
|
+
this.runtimeMetricsInterval = null;
|
|
554
|
+
this.runtimeMetrics?.flush({ final: true });
|
|
555
|
+
this.runtimeMetrics = null;
|
|
556
|
+
}
|
|
557
|
+
this.updateConnectionState({ status: "disposed" }, { event: "DISPOSE", reason: "Client closed", reasonCode: "disposed" });
|
|
558
|
+
}
|
|
559
|
+
ensureConnected() {
|
|
560
|
+
if (this.connectionState.status === "disposed") {
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
if (!this.shouldReconnect) {
|
|
564
|
+
this.shouldReconnect = true;
|
|
565
|
+
}
|
|
566
|
+
if (this.connectionState.status === "connected" ||
|
|
567
|
+
this.connectionState.status === "connecting") {
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
if (this.reconnectTimeout) {
|
|
571
|
+
clearTimeout(this.reconnectTimeout);
|
|
572
|
+
this.reconnectTimeout = null;
|
|
573
|
+
}
|
|
574
|
+
if (this.connectPromise) {
|
|
575
|
+
this.attemptConnect();
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
void this.connect();
|
|
579
|
+
}
|
|
580
|
+
getConnectionState() {
|
|
581
|
+
return this.connectionState;
|
|
582
|
+
}
|
|
583
|
+
subscribeConnectionStatus(listener) {
|
|
584
|
+
this.connectionListeners.add(listener);
|
|
585
|
+
listener(this.connectionState);
|
|
586
|
+
return () => {
|
|
587
|
+
this.connectionListeners.delete(listener);
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
get isConnected() {
|
|
591
|
+
return this.connectionState.status === "connected";
|
|
592
|
+
}
|
|
593
|
+
get isConnecting() {
|
|
594
|
+
return this.connectionState.status === "connecting";
|
|
595
|
+
}
|
|
596
|
+
get lastError() {
|
|
597
|
+
return this.lastErrorValue;
|
|
598
|
+
}
|
|
599
|
+
getLastLivenessRttMs() {
|
|
600
|
+
return this.lastLivenessRttMs;
|
|
601
|
+
}
|
|
602
|
+
// ============================================================================
|
|
603
|
+
// Message Subscription
|
|
604
|
+
// ============================================================================
|
|
605
|
+
subscribe(handler) {
|
|
606
|
+
this.eventListeners.add(handler);
|
|
607
|
+
this.updateEventSubscriptions();
|
|
608
|
+
return () => {
|
|
609
|
+
this.eventListeners.delete(handler);
|
|
610
|
+
this.updateEventSubscriptions();
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
subscribeRawMessages(handler) {
|
|
614
|
+
this.rawMessageListeners.add(handler);
|
|
615
|
+
return () => {
|
|
616
|
+
this.rawMessageListeners.delete(handler);
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
on(arg1, arg2) {
|
|
620
|
+
if (typeof arg1 === "function") {
|
|
621
|
+
return this.subscribe(arg1);
|
|
622
|
+
}
|
|
623
|
+
const type = arg1;
|
|
624
|
+
const handler = arg2;
|
|
625
|
+
if (!this.messageHandlers.has(type)) {
|
|
626
|
+
this.messageHandlers.set(type, new Set());
|
|
627
|
+
}
|
|
628
|
+
this.messageHandlers.get(type).add(handler);
|
|
629
|
+
this.updateEventSubscriptions();
|
|
630
|
+
return () => {
|
|
631
|
+
const handlers = this.messageHandlers.get(type);
|
|
632
|
+
if (!handlers) {
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
handlers.delete(handler);
|
|
636
|
+
if (handlers.size === 0) {
|
|
637
|
+
this.messageHandlers.delete(type);
|
|
638
|
+
}
|
|
639
|
+
this.updateEventSubscriptions();
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
onAgentAttentionRequired(handler) {
|
|
643
|
+
const unsubscribeLegacy = this.on("agent_stream", (message) => {
|
|
644
|
+
if (message.payload.event.type !== "attention_required") {
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
const event = message.payload.event;
|
|
648
|
+
handler({
|
|
649
|
+
agentId: message.payload.agentId,
|
|
650
|
+
reason: event.reason,
|
|
651
|
+
timestamp: event.timestamp,
|
|
652
|
+
shouldNotify: event.shouldNotify,
|
|
653
|
+
...(event.notification ? { notification: event.notification } : {}),
|
|
654
|
+
});
|
|
655
|
+
});
|
|
656
|
+
const unsubscribeDedicated = this.on("agent_attention_required", (message) => {
|
|
657
|
+
handler(message.payload);
|
|
658
|
+
});
|
|
659
|
+
return () => {
|
|
660
|
+
unsubscribeLegacy();
|
|
661
|
+
unsubscribeDedicated();
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
// ============================================================================
|
|
665
|
+
// Core Send Helpers
|
|
666
|
+
// ============================================================================
|
|
667
|
+
beginTraceSection(name, args) {
|
|
668
|
+
const trace = this.config.trace;
|
|
669
|
+
if (!trace?.isEnabled()) {
|
|
670
|
+
return false;
|
|
671
|
+
}
|
|
672
|
+
trace.beginSection(name, args);
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
endTraceSection(isOpen) {
|
|
676
|
+
if (isOpen) {
|
|
677
|
+
this.config.trace?.endSection();
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
traceInstant(name, args) {
|
|
681
|
+
const isOpen = this.beginTraceSection(name, args);
|
|
682
|
+
this.endTraceSection(isOpen);
|
|
683
|
+
}
|
|
684
|
+
sendJsonMessage(envelopeType, messageType, message) {
|
|
685
|
+
this.traceInstant("paseo.ws.message.outbound", {
|
|
686
|
+
envelopeType,
|
|
687
|
+
messageType,
|
|
688
|
+
});
|
|
689
|
+
this.sendTransportFrame(JSON.stringify(message));
|
|
690
|
+
}
|
|
691
|
+
sendTransportFrame(frame) {
|
|
692
|
+
if (!this.transport) {
|
|
693
|
+
throw new Error("Transport not connected");
|
|
694
|
+
}
|
|
695
|
+
const isOpen = this.beginTraceSection("paseo.ws.frame.outbound", {
|
|
696
|
+
kind: typeof frame === "string" ? "text" : "binary",
|
|
697
|
+
size: String(getTransportFrameSize(frame)),
|
|
698
|
+
});
|
|
699
|
+
try {
|
|
700
|
+
this.transport.send(frame);
|
|
701
|
+
}
|
|
702
|
+
finally {
|
|
703
|
+
this.endTraceSection(isOpen);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Send a session message. For fire-and-forget messages (heartbeats, etc.),
|
|
708
|
+
* failures are suppressed if `suppressSendErrors` is configured.
|
|
709
|
+
* For RPC methods that wait for responses, use `sendSessionMessageOrThrow` instead.
|
|
710
|
+
*/
|
|
711
|
+
sendSessionMessage(message) {
|
|
712
|
+
if (!this.transport || this.connectionState.status !== "connected") {
|
|
713
|
+
if (this.config.suppressSendErrors) {
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
throw new Error(`Transport not connected (status: ${this.connectionState.status})`);
|
|
717
|
+
}
|
|
718
|
+
const payload = SessionInboundMessageSchema.parse(message);
|
|
719
|
+
try {
|
|
720
|
+
this.sendJsonMessage("session", payload.type, { type: "session", message: payload });
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
if (this.config.suppressSendErrors) {
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
sendBinaryFrame(frame) {
|
|
730
|
+
if (!this.transport || this.connectionState.status !== "connected") {
|
|
731
|
+
if (this.config.suppressSendErrors) {
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
throw new Error(`Transport not connected (status: ${this.connectionState.status})`);
|
|
735
|
+
}
|
|
736
|
+
try {
|
|
737
|
+
this.traceInstant("paseo.ws.message.outbound", {
|
|
738
|
+
envelopeType: "binary",
|
|
739
|
+
messageType: "binary",
|
|
740
|
+
});
|
|
741
|
+
this.sendTransportFrame(frame);
|
|
742
|
+
}
|
|
743
|
+
catch (error) {
|
|
744
|
+
if (this.config.suppressSendErrors) {
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Send a session message for RPC methods that create waiters.
|
|
752
|
+
* If the connection is still being established ("connecting"), the message
|
|
753
|
+
* is queued and will be sent once connected (or rejected after timeout).
|
|
754
|
+
* This prevents waiters from hanging forever when called during connection.
|
|
755
|
+
*/
|
|
756
|
+
sendSessionMessageOrThrow(message) {
|
|
757
|
+
const status = this.connectionState.status;
|
|
758
|
+
// If connected, send immediately
|
|
759
|
+
if (this.transport && status === "connected") {
|
|
760
|
+
const payload = SessionInboundMessageSchema.parse(message);
|
|
761
|
+
this.sendJsonMessage("session", payload.type, { type: "session", message: payload });
|
|
762
|
+
return Promise.resolve();
|
|
763
|
+
}
|
|
764
|
+
// If connecting, queue the message to be sent once connected
|
|
765
|
+
if (status === "connecting") {
|
|
766
|
+
return new Promise((resolve, reject) => {
|
|
767
|
+
const timeoutHandle = setTimeout(() => {
|
|
768
|
+
// Remove from queue
|
|
769
|
+
const idx = this.pendingSendQueue.findIndex((p) => p.resolve === resolve);
|
|
770
|
+
if (idx !== -1) {
|
|
771
|
+
this.pendingSendQueue.splice(idx, 1);
|
|
772
|
+
}
|
|
773
|
+
reject(new Error(`Timed out waiting for connection to send message`));
|
|
774
|
+
}, DEFAULT_SEND_QUEUE_TIMEOUT_MS);
|
|
775
|
+
this.pendingSendQueue.push({ message, resolve, reject, timeoutHandle });
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
// Not connected and not connecting - fail immediately
|
|
779
|
+
return Promise.reject(new Error(`Transport not connected (status: ${status})`));
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Flush pending send queue - called when connection is established.
|
|
783
|
+
*/
|
|
784
|
+
flushPendingSendQueue() {
|
|
785
|
+
const queue = this.pendingSendQueue;
|
|
786
|
+
this.pendingSendQueue = [];
|
|
787
|
+
for (const pending of queue) {
|
|
788
|
+
clearTimeout(pending.timeoutHandle);
|
|
789
|
+
try {
|
|
790
|
+
if (this.transport && this.connectionState.status === "connected") {
|
|
791
|
+
const payload = SessionInboundMessageSchema.parse(pending.message);
|
|
792
|
+
this.sendJsonMessage("session", payload.type, { type: "session", message: payload });
|
|
793
|
+
pending.resolve();
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
pending.reject(new Error("Connection lost before message could be sent"));
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
catch (error) {
|
|
800
|
+
pending.reject(error instanceof Error ? error : new Error(String(error)));
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Reject all pending sends - called when connection fails or is closed.
|
|
806
|
+
*/
|
|
807
|
+
rejectPendingSendQueue(error) {
|
|
808
|
+
const queue = this.pendingSendQueue;
|
|
809
|
+
this.pendingSendQueue = [];
|
|
810
|
+
for (const pending of queue) {
|
|
811
|
+
clearTimeout(pending.timeoutHandle);
|
|
812
|
+
pending.reject(error);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
async sendRequest(params) {
|
|
816
|
+
const timeout = params.timeout ?? DEFAULT_SESSION_RPC_TIMEOUT_MS;
|
|
817
|
+
const { promise, cancel } = this.waitForWithCancel((msg) => {
|
|
818
|
+
if (msg.type === "rpc_error" && msg.payload.requestId === params.requestId) {
|
|
819
|
+
return {
|
|
820
|
+
kind: "error",
|
|
821
|
+
error: new DaemonRpcError({
|
|
822
|
+
requestId: msg.payload.requestId,
|
|
823
|
+
error: msg.payload.error,
|
|
824
|
+
requestType: msg.payload.requestType,
|
|
825
|
+
code: msg.payload.code,
|
|
826
|
+
}),
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
const value = params.select(msg);
|
|
830
|
+
if (value === null) {
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
return { kind: "ok", value };
|
|
834
|
+
}, timeout, { ...params.options, requestId: params.requestId });
|
|
835
|
+
try {
|
|
836
|
+
await this.sendSessionMessageOrThrow(params.message);
|
|
837
|
+
}
|
|
838
|
+
catch (error) {
|
|
839
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
840
|
+
cancel(err);
|
|
841
|
+
void promise.catch(() => undefined);
|
|
842
|
+
throw err;
|
|
843
|
+
}
|
|
844
|
+
const result = await promise;
|
|
845
|
+
if (result.kind === "error") {
|
|
846
|
+
throw result.error;
|
|
847
|
+
}
|
|
848
|
+
return result.value;
|
|
849
|
+
}
|
|
850
|
+
async sendCorrelatedRequest(params) {
|
|
851
|
+
return this.sendRequest({
|
|
852
|
+
requestId: params.requestId,
|
|
853
|
+
message: params.message,
|
|
854
|
+
timeout: params.timeout,
|
|
855
|
+
options: params.options,
|
|
856
|
+
select: (msg) => {
|
|
857
|
+
const correlated = msg;
|
|
858
|
+
if (correlated.type !== params.responseType) {
|
|
859
|
+
return null;
|
|
860
|
+
}
|
|
861
|
+
const payload = correlated.payload;
|
|
862
|
+
if (payload.requestId !== params.requestId) {
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
if (!params.selectPayload) {
|
|
866
|
+
return payload;
|
|
867
|
+
}
|
|
868
|
+
return params.selectPayload(payload);
|
|
869
|
+
},
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
sendCorrelatedSessionRequest(params) {
|
|
873
|
+
const resolvedRequestId = this.createRequestId(params.requestId);
|
|
874
|
+
const message = SessionInboundMessageSchema.parse({
|
|
875
|
+
...params.message,
|
|
876
|
+
requestId: resolvedRequestId,
|
|
877
|
+
});
|
|
878
|
+
return this.sendCorrelatedRequest({
|
|
879
|
+
requestId: resolvedRequestId,
|
|
880
|
+
message,
|
|
881
|
+
responseType: params.responseType,
|
|
882
|
+
timeout: params.timeout,
|
|
883
|
+
options: { skipQueue: true },
|
|
884
|
+
...(params.selectPayload ? { selectPayload: params.selectPayload } : {}),
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
sendNamespacedCorrelatedSessionRequest(params) {
|
|
888
|
+
const responseType = params.message.type.replace(/\.request$/, ".response");
|
|
889
|
+
return this.sendCorrelatedSessionRequest({
|
|
890
|
+
...params,
|
|
891
|
+
responseType,
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
sendSessionMessageStrict(message) {
|
|
895
|
+
if (!this.transport || this.connectionState.status !== "connected") {
|
|
896
|
+
throw new Error("Transport not connected");
|
|
897
|
+
}
|
|
898
|
+
const payload = SessionInboundMessageSchema.parse(message);
|
|
899
|
+
try {
|
|
900
|
+
this.sendJsonMessage("session", payload.type, { type: "session", message: payload });
|
|
901
|
+
}
|
|
902
|
+
catch (error) {
|
|
903
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
async clearAgentAttention(agentId) {
|
|
907
|
+
const requestId = this.createRequestId();
|
|
908
|
+
const message = SessionInboundMessageSchema.parse({
|
|
909
|
+
type: "clear_agent_attention",
|
|
910
|
+
agentId,
|
|
911
|
+
requestId,
|
|
912
|
+
});
|
|
913
|
+
await this.sendRequest({
|
|
914
|
+
requestId,
|
|
915
|
+
message,
|
|
916
|
+
options: { skipQueue: true },
|
|
917
|
+
select: (msg) => {
|
|
918
|
+
if (msg.type !== "clear_agent_attention_response") {
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
if (msg.payload.requestId !== requestId) {
|
|
922
|
+
return null;
|
|
923
|
+
}
|
|
924
|
+
return msg.payload;
|
|
925
|
+
},
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
async clearWorkspaceAttention(workspaceId) {
|
|
929
|
+
const requestId = this.createRequestId();
|
|
930
|
+
const message = SessionInboundMessageSchema.parse({
|
|
931
|
+
type: "workspace.clear_attention.request",
|
|
932
|
+
workspaceId,
|
|
933
|
+
requestId,
|
|
934
|
+
});
|
|
935
|
+
const response = await this.sendRequest({
|
|
936
|
+
requestId,
|
|
937
|
+
message,
|
|
938
|
+
options: { skipQueue: true },
|
|
939
|
+
select: (msg) => {
|
|
940
|
+
if (msg.type !== "workspace.clear_attention.response") {
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
943
|
+
if (msg.payload.requestId !== requestId) {
|
|
944
|
+
return null;
|
|
945
|
+
}
|
|
946
|
+
return msg.payload;
|
|
947
|
+
},
|
|
948
|
+
});
|
|
949
|
+
if (!response.success) {
|
|
950
|
+
throw new Error(response.error ?? "Failed to clear workspace attention");
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
async markWorkspaceUnread(workspaceId, requestId) {
|
|
954
|
+
const response = await this.sendNamespacedCorrelatedSessionRequest({
|
|
955
|
+
requestId,
|
|
956
|
+
message: {
|
|
957
|
+
type: "workspace.mark_unread.request",
|
|
958
|
+
workspaceId,
|
|
959
|
+
},
|
|
960
|
+
});
|
|
961
|
+
if (!response.success) {
|
|
962
|
+
throw new Error(response.error ?? "Failed to mark workspace unread");
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
sendHeartbeat(params) {
|
|
966
|
+
this.sendSessionMessage({
|
|
967
|
+
type: "client_heartbeat",
|
|
968
|
+
deviceType: params.deviceType,
|
|
969
|
+
focusedAgentId: params.focusedAgentId,
|
|
970
|
+
focusedTerminalId: params.focusedTerminalId ?? null,
|
|
971
|
+
lastActivityAt: params.lastActivityAt,
|
|
972
|
+
appVisible: params.appVisible,
|
|
973
|
+
appVisibilityChangedAt: params.appVisibilityChangedAt,
|
|
974
|
+
});
|
|
975
|
+
}
|
|
976
|
+
registerPushToken(token) {
|
|
977
|
+
this.sendSessionMessage({
|
|
978
|
+
type: "register_push_token",
|
|
979
|
+
token,
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
async unregisterPushToken(token) {
|
|
983
|
+
const requestId = this.createRequestId();
|
|
984
|
+
await this.sendCorrelatedSessionRequest({
|
|
985
|
+
requestId,
|
|
986
|
+
message: { type: "push.unregister.request", token, requestId },
|
|
987
|
+
responseType: "push.unregister.response",
|
|
988
|
+
timeout: PUSH_TOKEN_REVOCATION_TIMEOUT_MS,
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
async ping(params) {
|
|
992
|
+
const requestId = params?.requestId ?? `ping-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
993
|
+
const clientSentAt = Date.now();
|
|
994
|
+
const payload = await this.sendRequest({
|
|
995
|
+
requestId,
|
|
996
|
+
message: { type: "ping", requestId, clientSentAt },
|
|
997
|
+
timeout: params?.timeoutMs ?? 5000,
|
|
998
|
+
select: (msg) => {
|
|
999
|
+
if (msg.type !== "pong")
|
|
1000
|
+
return null;
|
|
1001
|
+
if (msg.payload.requestId !== requestId)
|
|
1002
|
+
return null;
|
|
1003
|
+
if (typeof msg.payload.serverReceivedAt !== "number")
|
|
1004
|
+
return null;
|
|
1005
|
+
if (typeof msg.payload.serverSentAt !== "number")
|
|
1006
|
+
return null;
|
|
1007
|
+
return msg.payload;
|
|
1008
|
+
},
|
|
1009
|
+
});
|
|
1010
|
+
return {
|
|
1011
|
+
requestId,
|
|
1012
|
+
clientSentAt,
|
|
1013
|
+
serverReceivedAt: payload.serverReceivedAt,
|
|
1014
|
+
serverSentAt: payload.serverSentAt,
|
|
1015
|
+
rttMs: Date.now() - clientSentAt,
|
|
1016
|
+
};
|
|
1017
|
+
}
|
|
1018
|
+
measureLatency(params) {
|
|
1019
|
+
const timeoutMs = Math.max(1, params?.timeoutMs ?? DEFAULT_LIVENESS_TIMEOUT_MS);
|
|
1020
|
+
return this.sendPingAwaitRtt({ timeoutMs, drivesLivenessFailure: false }).catch((error) => {
|
|
1021
|
+
throw toTimeoutError(error, "Latency measurement", timeoutMs);
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
async livenessPing(params) {
|
|
1025
|
+
const timeoutMs = Math.max(1, params?.timeoutMs ?? DEFAULT_LIVENESS_TIMEOUT_MS);
|
|
1026
|
+
try {
|
|
1027
|
+
const rttMs = await this.sendPingAwaitRtt({ timeoutMs, drivesLivenessFailure: true });
|
|
1028
|
+
this.lastLivenessRttMs = rttMs;
|
|
1029
|
+
return rttMs;
|
|
1030
|
+
}
|
|
1031
|
+
catch (error) {
|
|
1032
|
+
throw toTimeoutError(error, "Liveness check", timeoutMs);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
sendPingAwaitRtt(params) {
|
|
1036
|
+
if (this.connectionState.status !== "connected" || !this.transport) {
|
|
1037
|
+
return Promise.reject(new Error(`Transport not connected (status: ${this.connectionState.status})`));
|
|
1038
|
+
}
|
|
1039
|
+
if (this.pingProbe) {
|
|
1040
|
+
return this.pingProbe.promise;
|
|
1041
|
+
}
|
|
1042
|
+
const startedAt = perfNow();
|
|
1043
|
+
const timeoutMs = params.timeoutMs;
|
|
1044
|
+
let resolveProbe = null;
|
|
1045
|
+
let rejectProbe = null;
|
|
1046
|
+
const promise = new Promise((resolve, reject) => {
|
|
1047
|
+
resolveProbe = resolve;
|
|
1048
|
+
rejectProbe = reject;
|
|
1049
|
+
});
|
|
1050
|
+
const probe = {
|
|
1051
|
+
promise,
|
|
1052
|
+
resolve: (value) => resolveProbe?.(value),
|
|
1053
|
+
reject: (error) => rejectProbe?.(error),
|
|
1054
|
+
timeoutHandle: setTimeout(() => {
|
|
1055
|
+
if (this.pingProbe !== probe) {
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
this.pingProbe = null;
|
|
1059
|
+
const error = new PingTimeoutError(timeoutMs);
|
|
1060
|
+
probe.reject(error);
|
|
1061
|
+
if (probe.drivesLivenessFailure) {
|
|
1062
|
+
this.recordLivenessFailure(toTimeoutError(error, "Liveness check", timeoutMs));
|
|
1063
|
+
}
|
|
1064
|
+
}, timeoutMs),
|
|
1065
|
+
startedAt,
|
|
1066
|
+
drivesLivenessFailure: params.drivesLivenessFailure,
|
|
1067
|
+
};
|
|
1068
|
+
this.pingProbe = probe;
|
|
1069
|
+
try {
|
|
1070
|
+
this.sendJsonMessage("ping", "ping", { type: "ping" });
|
|
1071
|
+
}
|
|
1072
|
+
catch (error) {
|
|
1073
|
+
this.clearPingProbe();
|
|
1074
|
+
const sendError = error instanceof Error ? error : new Error(String(error));
|
|
1075
|
+
if (probe.drivesLivenessFailure) {
|
|
1076
|
+
this.recordLivenessFailure(sendError);
|
|
1077
|
+
}
|
|
1078
|
+
return Promise.reject(sendError);
|
|
1079
|
+
}
|
|
1080
|
+
return promise;
|
|
1081
|
+
}
|
|
1082
|
+
startLivenessHeartbeat() {
|
|
1083
|
+
this.stopLivenessHeartbeat();
|
|
1084
|
+
this.lastLivenessRttMs = null;
|
|
1085
|
+
this.scheduleNextLivenessHeartbeat();
|
|
1086
|
+
}
|
|
1087
|
+
stopLivenessHeartbeat() {
|
|
1088
|
+
if (!this.livenessHeartbeatTimer) {
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
clearTimeout(this.livenessHeartbeatTimer);
|
|
1092
|
+
this.livenessHeartbeatTimer = null;
|
|
1093
|
+
}
|
|
1094
|
+
scheduleNextLivenessHeartbeat() {
|
|
1095
|
+
if (this.connectionState.status !== "connected" || this.livenessHeartbeatTimer) {
|
|
1096
|
+
return;
|
|
1097
|
+
}
|
|
1098
|
+
this.livenessHeartbeatTimer = setTimeout(() => {
|
|
1099
|
+
this.livenessHeartbeatTimer = null;
|
|
1100
|
+
this.livenessPing({ timeoutMs: LIVENESS_HEARTBEAT_TIMEOUT_MS })
|
|
1101
|
+
.catch(() => { })
|
|
1102
|
+
.finally(() => {
|
|
1103
|
+
this.scheduleNextLivenessHeartbeat();
|
|
1104
|
+
});
|
|
1105
|
+
}, LIVENESS_HEARTBEAT_INTERVAL_MS);
|
|
1106
|
+
}
|
|
1107
|
+
// ============================================================================
|
|
1108
|
+
// Agent RPCs (requestId-correlated)
|
|
1109
|
+
// ============================================================================
|
|
1110
|
+
async fetchAgents(options) {
|
|
1111
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
1112
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1113
|
+
type: "fetch_agents_request",
|
|
1114
|
+
requestId: resolvedRequestId,
|
|
1115
|
+
...(options?.scope ? { scope: options.scope } : {}),
|
|
1116
|
+
...(options?.filter ? { filter: options.filter } : {}),
|
|
1117
|
+
...(options?.sort ? { sort: options.sort } : {}),
|
|
1118
|
+
...(options?.page ? { page: options.page } : {}),
|
|
1119
|
+
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
|
|
1120
|
+
...(options?.sync ? { sync: options.sync } : {}),
|
|
1121
|
+
});
|
|
1122
|
+
return this.sendRequest({
|
|
1123
|
+
requestId: resolvedRequestId,
|
|
1124
|
+
message,
|
|
1125
|
+
timeout: options?.timeout,
|
|
1126
|
+
options: { skipQueue: true },
|
|
1127
|
+
select: (msg) => {
|
|
1128
|
+
if (msg.type !== "fetch_agents_response") {
|
|
1129
|
+
return null;
|
|
1130
|
+
}
|
|
1131
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1132
|
+
return null;
|
|
1133
|
+
}
|
|
1134
|
+
return msg.payload;
|
|
1135
|
+
},
|
|
1136
|
+
});
|
|
1137
|
+
}
|
|
1138
|
+
async fetchAgentHistory(options) {
|
|
1139
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
1140
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1141
|
+
type: "fetch_agent_history_request",
|
|
1142
|
+
requestId: resolvedRequestId,
|
|
1143
|
+
...(options?.filter ? { filter: options.filter } : {}),
|
|
1144
|
+
...(options?.search ? { search: options.search } : {}),
|
|
1145
|
+
...(options?.sort ? { sort: options.sort } : {}),
|
|
1146
|
+
...(options?.page ? { page: options.page } : {}),
|
|
1147
|
+
});
|
|
1148
|
+
return this.sendRequest({
|
|
1149
|
+
requestId: resolvedRequestId,
|
|
1150
|
+
message,
|
|
1151
|
+
options: { skipQueue: true },
|
|
1152
|
+
select: (msg) => {
|
|
1153
|
+
if (msg.type !== "fetch_agent_history_response") {
|
|
1154
|
+
return null;
|
|
1155
|
+
}
|
|
1156
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1157
|
+
return null;
|
|
1158
|
+
}
|
|
1159
|
+
return msg.payload;
|
|
1160
|
+
},
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
async fetchRecentProviderSessions(options) {
|
|
1164
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
1165
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1166
|
+
type: "fetch_recent_provider_sessions_request",
|
|
1167
|
+
requestId: resolvedRequestId,
|
|
1168
|
+
...(options?.cwd ? { cwd: options.cwd } : {}),
|
|
1169
|
+
...(options?.providers ? { providers: options.providers } : {}),
|
|
1170
|
+
...(options?.since ? { since: options.since } : {}),
|
|
1171
|
+
...(options?.limit ? { limit: options.limit } : {}),
|
|
1172
|
+
...(options?.query !== undefined ? { query: options.query } : {}),
|
|
1173
|
+
});
|
|
1174
|
+
return this.sendRequest({
|
|
1175
|
+
requestId: resolvedRequestId,
|
|
1176
|
+
message,
|
|
1177
|
+
options: { skipQueue: true },
|
|
1178
|
+
select: (msg) => {
|
|
1179
|
+
if (msg.type !== "fetch_recent_provider_sessions_response") {
|
|
1180
|
+
return null;
|
|
1181
|
+
}
|
|
1182
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1183
|
+
return null;
|
|
1184
|
+
}
|
|
1185
|
+
return msg.payload;
|
|
1186
|
+
},
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1189
|
+
async fetchWorkspaces(options) {
|
|
1190
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
1191
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1192
|
+
type: "fetch_workspaces_request",
|
|
1193
|
+
requestId: resolvedRequestId,
|
|
1194
|
+
...(options?.filter ? { filter: options.filter } : {}),
|
|
1195
|
+
...(options?.sort ? { sort: options.sort } : {}),
|
|
1196
|
+
...(options?.page ? { page: options.page } : {}),
|
|
1197
|
+
...(options?.subscribe ? { subscribe: options.subscribe } : {}),
|
|
1198
|
+
...(options?.sync ? { sync: options.sync } : {}),
|
|
1199
|
+
});
|
|
1200
|
+
return this.sendRequest({
|
|
1201
|
+
requestId: resolvedRequestId,
|
|
1202
|
+
message,
|
|
1203
|
+
options: { skipQueue: true },
|
|
1204
|
+
select: (msg) => {
|
|
1205
|
+
if (msg.type !== "fetch_workspaces_response") {
|
|
1206
|
+
return null;
|
|
1207
|
+
}
|
|
1208
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1209
|
+
return null;
|
|
1210
|
+
}
|
|
1211
|
+
return msg.payload;
|
|
1212
|
+
},
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
listWorkspaceLabels(options) {
|
|
1216
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1217
|
+
requestId: options.requestId,
|
|
1218
|
+
message: {
|
|
1219
|
+
type: "workspace.label.list.request",
|
|
1220
|
+
subscribe: { subscriptionId: options.subscriptionId },
|
|
1221
|
+
...(options.sync ? { sync: options.sync } : {}),
|
|
1222
|
+
},
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
setWorkspaceLabel(options) {
|
|
1226
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1227
|
+
requestId: options.requestId,
|
|
1228
|
+
message: {
|
|
1229
|
+
type: "workspace.label.assignment.set.request",
|
|
1230
|
+
workspaceId: options.workspaceId,
|
|
1231
|
+
label: options.label,
|
|
1232
|
+
assigned: options.assigned,
|
|
1233
|
+
},
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
updateWorkspaceLabel(options) {
|
|
1237
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1238
|
+
requestId: options.requestId,
|
|
1239
|
+
message: {
|
|
1240
|
+
type: "workspace.label.update.request",
|
|
1241
|
+
name: options.name,
|
|
1242
|
+
...(options.newName === undefined ? {} : { newName: options.newName }),
|
|
1243
|
+
...(options.color === undefined ? {} : { color: options.color }),
|
|
1244
|
+
},
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
deleteWorkspaceLabel(options) {
|
|
1248
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1249
|
+
requestId: options.requestId,
|
|
1250
|
+
message: { type: "workspace.label.delete.request", name: options.name },
|
|
1251
|
+
});
|
|
1252
|
+
}
|
|
1253
|
+
inspectWorkspaceLabelDelete(options) {
|
|
1254
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1255
|
+
requestId: options.requestId,
|
|
1256
|
+
message: {
|
|
1257
|
+
type: "workspace.label.delete.inspect.request",
|
|
1258
|
+
name: options.name,
|
|
1259
|
+
},
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
async listProjects(options) {
|
|
1263
|
+
const requestId = typeof options === "string" ? options : options?.requestId;
|
|
1264
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
1265
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1266
|
+
type: "project.list.request",
|
|
1267
|
+
requestId: resolvedRequestId,
|
|
1268
|
+
...(typeof options === "object" && options.sync ? { sync: options.sync } : {}),
|
|
1269
|
+
});
|
|
1270
|
+
return this.sendRequest({
|
|
1271
|
+
requestId: resolvedRequestId,
|
|
1272
|
+
message,
|
|
1273
|
+
options: { skipQueue: true },
|
|
1274
|
+
select: (msg) => {
|
|
1275
|
+
if (msg.type !== "project.list.response")
|
|
1276
|
+
return null;
|
|
1277
|
+
if (msg.payload.requestId !== resolvedRequestId)
|
|
1278
|
+
return null;
|
|
1279
|
+
return msg.payload;
|
|
1280
|
+
},
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
async openProject(cwd, requestId) {
|
|
1284
|
+
return this.sendCorrelatedSessionRequest({
|
|
1285
|
+
requestId,
|
|
1286
|
+
message: {
|
|
1287
|
+
type: "open_project_request",
|
|
1288
|
+
cwd,
|
|
1289
|
+
},
|
|
1290
|
+
responseType: "open_project_response",
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
async addProject(cwd, requestId) {
|
|
1294
|
+
return this.sendCorrelatedSessionRequest({
|
|
1295
|
+
requestId,
|
|
1296
|
+
message: {
|
|
1297
|
+
type: "project.add.request",
|
|
1298
|
+
cwd,
|
|
1299
|
+
},
|
|
1300
|
+
responseType: "project.add.response",
|
|
1301
|
+
});
|
|
1302
|
+
}
|
|
1303
|
+
async createProjectDirectory(input, requestId) {
|
|
1304
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1305
|
+
requestId,
|
|
1306
|
+
message: {
|
|
1307
|
+
type: "project.create_directory.request",
|
|
1308
|
+
parentPath: input.parentPath,
|
|
1309
|
+
name: input.name,
|
|
1310
|
+
},
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
async searchGithubRepositories(input, requestId) {
|
|
1314
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1315
|
+
requestId,
|
|
1316
|
+
message: {
|
|
1317
|
+
type: "workspace.github.search_repositories.request",
|
|
1318
|
+
query: input.query,
|
|
1319
|
+
limit: input.limit,
|
|
1320
|
+
},
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
async cloneGithubProject(input, requestId) {
|
|
1324
|
+
const message = {
|
|
1325
|
+
type: "project.github.clone.request",
|
|
1326
|
+
repo: input.repo,
|
|
1327
|
+
targetDirectory: input.targetDirectory,
|
|
1328
|
+
...(input.cloneProtocol ? { cloneProtocol: input.cloneProtocol } : {}),
|
|
1329
|
+
};
|
|
1330
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1331
|
+
requestId,
|
|
1332
|
+
message,
|
|
1333
|
+
timeout: PROJECT_GITHUB_CLONE_TIMEOUT_MS,
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
async startWorkspaceScript(workspaceId, scriptName, requestId) {
|
|
1337
|
+
return this.sendCorrelatedSessionRequest({
|
|
1338
|
+
requestId,
|
|
1339
|
+
message: {
|
|
1340
|
+
type: "start_workspace_script_request",
|
|
1341
|
+
workspaceId,
|
|
1342
|
+
scriptName,
|
|
1343
|
+
},
|
|
1344
|
+
responseType: "start_workspace_script_response",
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
async listWorkspaceScripts(workspaceId, requestId) {
|
|
1348
|
+
return this.sendCorrelatedSessionRequest({
|
|
1349
|
+
requestId,
|
|
1350
|
+
message: { type: "workspace.script.list.request", workspaceId },
|
|
1351
|
+
responseType: "workspace.script.list.response",
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
async startWorkspaceScriptWithStatus(workspaceId, scriptName, requestId) {
|
|
1355
|
+
return this.sendCorrelatedSessionRequest({
|
|
1356
|
+
requestId,
|
|
1357
|
+
message: { type: "workspace.script.start.request", workspaceId, scriptName },
|
|
1358
|
+
responseType: "workspace.script.start.response",
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
async stopWorkspaceScript(workspaceId, scriptName, requestId) {
|
|
1362
|
+
return this.sendCorrelatedSessionRequest({
|
|
1363
|
+
requestId,
|
|
1364
|
+
message: { type: "workspace.script.stop.request", workspaceId, scriptName },
|
|
1365
|
+
responseType: "workspace.script.stop.response",
|
|
1366
|
+
});
|
|
1367
|
+
}
|
|
1368
|
+
async archiveWorkspace(workspaceId, requestId) {
|
|
1369
|
+
return this.sendCorrelatedSessionRequest({
|
|
1370
|
+
requestId,
|
|
1371
|
+
message: {
|
|
1372
|
+
type: "archive_workspace_request",
|
|
1373
|
+
workspaceId,
|
|
1374
|
+
},
|
|
1375
|
+
responseType: "archive_workspace_response",
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
1378
|
+
async fetchWorkspaceSetupStatus(workspaceId, requestId) {
|
|
1379
|
+
return this.sendCorrelatedSessionRequest({
|
|
1380
|
+
requestId,
|
|
1381
|
+
message: {
|
|
1382
|
+
type: "workspace_setup_status_request",
|
|
1383
|
+
workspaceId,
|
|
1384
|
+
},
|
|
1385
|
+
responseType: "workspace_setup_status_response",
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
async runWorkspaceSetup(workspaceId, requestId) {
|
|
1389
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
1390
|
+
requestId,
|
|
1391
|
+
message: { type: "workspace.setup.run.request", workspaceId },
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
async fetchAgent(input, legacyOptions) {
|
|
1395
|
+
const options = normalizeFetchAgentOptions(input, legacyOptions);
|
|
1396
|
+
const resolvedRequestId = this.createRequestId(options.requestId);
|
|
1397
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1398
|
+
type: "fetch_agent_request",
|
|
1399
|
+
requestId: resolvedRequestId,
|
|
1400
|
+
agentId: options.agentId,
|
|
1401
|
+
});
|
|
1402
|
+
const payload = await this.sendRequest({
|
|
1403
|
+
requestId: resolvedRequestId,
|
|
1404
|
+
message,
|
|
1405
|
+
timeout: options.timeout,
|
|
1406
|
+
options: { skipQueue: true },
|
|
1407
|
+
select: (msg) => {
|
|
1408
|
+
if (msg.type !== "fetch_agent_response") {
|
|
1409
|
+
return null;
|
|
1410
|
+
}
|
|
1411
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1412
|
+
return null;
|
|
1413
|
+
}
|
|
1414
|
+
return msg.payload;
|
|
1415
|
+
},
|
|
1416
|
+
});
|
|
1417
|
+
if (payload.error) {
|
|
1418
|
+
throw new Error(payload.error);
|
|
1419
|
+
}
|
|
1420
|
+
if (!payload.agent) {
|
|
1421
|
+
return null;
|
|
1422
|
+
}
|
|
1423
|
+
return { agent: payload.agent, project: payload.project ?? null };
|
|
1424
|
+
}
|
|
1425
|
+
resubscribeCheckoutDiffSubscriptions() {
|
|
1426
|
+
if (this.checkoutDiffSubscriptions.size === 0) {
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
for (const [subscriptionId, subscription] of this.checkoutDiffSubscriptions) {
|
|
1430
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1431
|
+
type: "subscribe_checkout_diff_request",
|
|
1432
|
+
subscriptionId,
|
|
1433
|
+
cwd: subscription.cwd,
|
|
1434
|
+
compare: subscription.compare,
|
|
1435
|
+
requestId: this.createRequestId(),
|
|
1436
|
+
});
|
|
1437
|
+
this.sendSessionMessage(message);
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
resubscribeTerminalDirectorySubscriptions() {
|
|
1441
|
+
if (this.terminalDirectorySubscriptions.size === 0) {
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
for (const subscription of this.terminalDirectorySubscriptions.values()) {
|
|
1445
|
+
this.sendSessionMessage({
|
|
1446
|
+
type: "subscribe_terminals_request",
|
|
1447
|
+
cwd: subscription.cwd,
|
|
1448
|
+
...(subscription.workspaceId !== undefined
|
|
1449
|
+
? { workspaceId: subscription.workspaceId }
|
|
1450
|
+
: {}),
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
resubscribeFileSubscriptions() {
|
|
1455
|
+
for (const [subscriptionId, subscription] of this.fileSubscriptions) {
|
|
1456
|
+
void this.sendCorrelatedSessionRequest({
|
|
1457
|
+
message: {
|
|
1458
|
+
type: "fs.file.subscribe.request",
|
|
1459
|
+
cwd: subscription.cwd,
|
|
1460
|
+
path: subscription.path,
|
|
1461
|
+
subscriptionId,
|
|
1462
|
+
},
|
|
1463
|
+
responseType: "fs.file.subscribe.response",
|
|
1464
|
+
})
|
|
1465
|
+
.then((payload) => subscription.onUpdate(payload.initial))
|
|
1466
|
+
.catch(() => undefined);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
async createAgent(options) {
|
|
1470
|
+
const result = await this.creations.createAgent({
|
|
1471
|
+
...options,
|
|
1472
|
+
config: resolveAgentConfig(options),
|
|
1473
|
+
});
|
|
1474
|
+
if (result.error || !result.agent)
|
|
1475
|
+
throw new Error(result.error ?? "Agent creation failed");
|
|
1476
|
+
return result.agent;
|
|
1477
|
+
}
|
|
1478
|
+
async createLegacyAgent(options) {
|
|
1479
|
+
if (options.idempotencyKey !== undefined)
|
|
1480
|
+
this.requireAgentRequestReceipts();
|
|
1481
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1482
|
+
const config = resolveAgentConfig(options);
|
|
1483
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1484
|
+
type: "create_agent_request",
|
|
1485
|
+
requestId,
|
|
1486
|
+
config,
|
|
1487
|
+
...(options.env ? { env: options.env } : {}),
|
|
1488
|
+
...(options.workspaceId !== undefined ? { workspaceId: options.workspaceId } : {}),
|
|
1489
|
+
...(options.callerAgentId !== undefined ? { callerAgentId: options.callerAgentId } : {}),
|
|
1490
|
+
...(options.initialPrompt ? { initialPrompt: options.initialPrompt } : {}),
|
|
1491
|
+
idempotencyKey: options.idempotencyKey,
|
|
1492
|
+
...(options.clientMessageId ? { clientMessageId: options.clientMessageId } : {}),
|
|
1493
|
+
...(options.outputSchema ? { outputSchema: options.outputSchema } : {}),
|
|
1494
|
+
...(options.images && options.images.length > 0 ? { images: options.images } : {}),
|
|
1495
|
+
...(options.attachments && options.attachments.length > 0
|
|
1496
|
+
? { attachments: options.attachments }
|
|
1497
|
+
: {}),
|
|
1498
|
+
...(options.git ? { git: options.git } : {}),
|
|
1499
|
+
...(options.worktree ? { worktree: options.worktree } : {}),
|
|
1500
|
+
...(options.autoArchive !== undefined ? { autoArchive: options.autoArchive } : {}),
|
|
1501
|
+
...(options.worktreeName ? { worktreeName: options.worktreeName } : {}),
|
|
1502
|
+
...(options.labels && Object.keys(options.labels).length > 0
|
|
1503
|
+
? { labels: options.labels }
|
|
1504
|
+
: {}),
|
|
1505
|
+
});
|
|
1506
|
+
const status = await this.sendRequest({
|
|
1507
|
+
requestId,
|
|
1508
|
+
message,
|
|
1509
|
+
options: { skipQueue: true },
|
|
1510
|
+
select: (msg) => {
|
|
1511
|
+
if (msg.type !== "status") {
|
|
1512
|
+
return null;
|
|
1513
|
+
}
|
|
1514
|
+
const created = AgentCreatedStatusPayloadSchema.safeParse(msg.payload);
|
|
1515
|
+
if (created.success && created.data.requestId === requestId) {
|
|
1516
|
+
return created.data;
|
|
1517
|
+
}
|
|
1518
|
+
const failed = AgentCreateFailedStatusPayloadSchema.safeParse(msg.payload);
|
|
1519
|
+
if (failed.success && failed.data.requestId === requestId) {
|
|
1520
|
+
return failed.data;
|
|
1521
|
+
}
|
|
1522
|
+
return null;
|
|
1523
|
+
},
|
|
1524
|
+
});
|
|
1525
|
+
if (status.status === "agent_create_failed") {
|
|
1526
|
+
throw new Error(status.error);
|
|
1527
|
+
}
|
|
1528
|
+
return status.agent;
|
|
1529
|
+
}
|
|
1530
|
+
requireAgentRequestReceipts() {
|
|
1531
|
+
// COMPAT(agentRequestReceipts): added in v0.7.3; remove gate after 2027-03-05.
|
|
1532
|
+
if (this.lastServerInfoMessage?.features?.agentRequestReceipts !== true) {
|
|
1533
|
+
throw new Error("Update the host to use retry-safe agent creation.");
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
async deleteAgent(agentId) {
|
|
1537
|
+
const requestId = this.createRequestId();
|
|
1538
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1539
|
+
type: "delete_agent_request",
|
|
1540
|
+
agentId,
|
|
1541
|
+
requestId,
|
|
1542
|
+
});
|
|
1543
|
+
await this.sendRequest({
|
|
1544
|
+
requestId,
|
|
1545
|
+
message,
|
|
1546
|
+
options: { skipQueue: true },
|
|
1547
|
+
select: (msg) => {
|
|
1548
|
+
if (msg.type !== "agent_deleted") {
|
|
1549
|
+
return null;
|
|
1550
|
+
}
|
|
1551
|
+
if (msg.payload.requestId !== requestId) {
|
|
1552
|
+
return null;
|
|
1553
|
+
}
|
|
1554
|
+
return msg.payload;
|
|
1555
|
+
},
|
|
1556
|
+
});
|
|
1557
|
+
}
|
|
1558
|
+
async archiveAgent(agentId) {
|
|
1559
|
+
const requestId = this.createRequestId();
|
|
1560
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1561
|
+
type: "archive_agent_request",
|
|
1562
|
+
agentId,
|
|
1563
|
+
requestId,
|
|
1564
|
+
});
|
|
1565
|
+
const result = await this.sendRequest({
|
|
1566
|
+
requestId,
|
|
1567
|
+
message,
|
|
1568
|
+
options: { skipQueue: true },
|
|
1569
|
+
select: (msg) => {
|
|
1570
|
+
if (msg.type !== "agent_archived") {
|
|
1571
|
+
return null;
|
|
1572
|
+
}
|
|
1573
|
+
if (msg.payload.requestId !== requestId) {
|
|
1574
|
+
return null;
|
|
1575
|
+
}
|
|
1576
|
+
return msg.payload;
|
|
1577
|
+
},
|
|
1578
|
+
});
|
|
1579
|
+
return { archivedAt: result.archivedAt };
|
|
1580
|
+
}
|
|
1581
|
+
async detachAgent(agentId) {
|
|
1582
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
1583
|
+
message: {
|
|
1584
|
+
type: "agent.detach.request",
|
|
1585
|
+
agentId,
|
|
1586
|
+
},
|
|
1587
|
+
});
|
|
1588
|
+
if (!payload.accepted) {
|
|
1589
|
+
throw new Error(payload.error ?? "detachAgent rejected");
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
async updateAgent(agentId, updates) {
|
|
1593
|
+
const requestId = this.createRequestId();
|
|
1594
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1595
|
+
type: "update_agent_request",
|
|
1596
|
+
agentId,
|
|
1597
|
+
...(updates.name !== undefined ? { name: updates.name } : {}),
|
|
1598
|
+
...(updates.labels && Object.keys(updates.labels).length > 0
|
|
1599
|
+
? { labels: updates.labels }
|
|
1600
|
+
: {}),
|
|
1601
|
+
requestId,
|
|
1602
|
+
});
|
|
1603
|
+
const payload = await this.sendRequest({
|
|
1604
|
+
requestId,
|
|
1605
|
+
message,
|
|
1606
|
+
options: { skipQueue: true },
|
|
1607
|
+
select: (msg) => {
|
|
1608
|
+
if (msg.type !== "update_agent_response") {
|
|
1609
|
+
return null;
|
|
1610
|
+
}
|
|
1611
|
+
if (msg.payload.requestId !== requestId) {
|
|
1612
|
+
return null;
|
|
1613
|
+
}
|
|
1614
|
+
return msg.payload;
|
|
1615
|
+
},
|
|
1616
|
+
});
|
|
1617
|
+
if (!payload.accepted) {
|
|
1618
|
+
throw new Error(payload.error ?? "updateAgent rejected");
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
async renameProject(projectId, customName, requestId) {
|
|
1622
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
1623
|
+
requestId,
|
|
1624
|
+
message: {
|
|
1625
|
+
type: "project.rename.request",
|
|
1626
|
+
projectId,
|
|
1627
|
+
customName,
|
|
1628
|
+
},
|
|
1629
|
+
responseType: "project.rename.response",
|
|
1630
|
+
});
|
|
1631
|
+
if (!payload.accepted) {
|
|
1632
|
+
throw new Error(payload.error ?? "renameProject rejected");
|
|
1633
|
+
}
|
|
1634
|
+
return { customName: payload.customName };
|
|
1635
|
+
}
|
|
1636
|
+
async setProjectIcon(projectId, source, requestId) {
|
|
1637
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
1638
|
+
requestId,
|
|
1639
|
+
message: { type: "project.icon.set.request", projectId, source },
|
|
1640
|
+
});
|
|
1641
|
+
if (!payload.accepted)
|
|
1642
|
+
throw new Error(payload.error ?? "setProjectIcon rejected");
|
|
1643
|
+
}
|
|
1644
|
+
async removeProject(projectId, requestId) {
|
|
1645
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
1646
|
+
requestId,
|
|
1647
|
+
message: {
|
|
1648
|
+
type: "project.remove.request",
|
|
1649
|
+
projectId,
|
|
1650
|
+
},
|
|
1651
|
+
});
|
|
1652
|
+
if (!payload.accepted) {
|
|
1653
|
+
throw new Error(payload.error ?? "removeProject rejected");
|
|
1654
|
+
}
|
|
1655
|
+
return { removedWorkspaceIds: payload.removedWorkspaceIds };
|
|
1656
|
+
}
|
|
1657
|
+
async setWorkspaceTitle(workspaceId, title, requestId) {
|
|
1658
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
1659
|
+
requestId,
|
|
1660
|
+
message: {
|
|
1661
|
+
type: "workspace.title.set.request",
|
|
1662
|
+
workspaceId,
|
|
1663
|
+
title,
|
|
1664
|
+
},
|
|
1665
|
+
responseType: "workspace.title.set.response",
|
|
1666
|
+
});
|
|
1667
|
+
if (!payload.accepted) {
|
|
1668
|
+
throw new Error(payload.error ?? "setWorkspaceTitle rejected");
|
|
1669
|
+
}
|
|
1670
|
+
return { title: payload.title };
|
|
1671
|
+
}
|
|
1672
|
+
async setWorkspacePinned(workspaceId, pinned, requestId) {
|
|
1673
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
1674
|
+
requestId,
|
|
1675
|
+
message: {
|
|
1676
|
+
type: "workspace.pin.set.request",
|
|
1677
|
+
workspaceId,
|
|
1678
|
+
pinned,
|
|
1679
|
+
},
|
|
1680
|
+
responseType: "workspace.pin.set.response",
|
|
1681
|
+
});
|
|
1682
|
+
if (!payload.accepted) {
|
|
1683
|
+
throw new Error(payload.error ?? "setWorkspacePinned rejected");
|
|
1684
|
+
}
|
|
1685
|
+
return { pinnedAt: payload.pinnedAt };
|
|
1686
|
+
}
|
|
1687
|
+
async inspectWorkspaceRecovery(workspaceId, requestId) {
|
|
1688
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
1689
|
+
requestId,
|
|
1690
|
+
message: {
|
|
1691
|
+
type: "workspace.recovery.inspect.request",
|
|
1692
|
+
workspaceId,
|
|
1693
|
+
},
|
|
1694
|
+
});
|
|
1695
|
+
return payload.state;
|
|
1696
|
+
}
|
|
1697
|
+
async restoreWorkspace(workspaceId, requestId) {
|
|
1698
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
1699
|
+
requestId,
|
|
1700
|
+
message: {
|
|
1701
|
+
type: "workspace.recovery.restore.request",
|
|
1702
|
+
workspaceId,
|
|
1703
|
+
},
|
|
1704
|
+
timeout: 150000,
|
|
1705
|
+
});
|
|
1706
|
+
if (!payload.accepted) {
|
|
1707
|
+
throw new Error(payload.error ?? "Workspace recovery was rejected by the host");
|
|
1708
|
+
}
|
|
1709
|
+
}
|
|
1710
|
+
async resumeAgent(handle, overrides) {
|
|
1711
|
+
const requestId = this.createRequestId();
|
|
1712
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1713
|
+
type: "resume_agent_request",
|
|
1714
|
+
requestId,
|
|
1715
|
+
handle,
|
|
1716
|
+
...(overrides ? { overrides } : {}),
|
|
1717
|
+
});
|
|
1718
|
+
const status = await this.sendRequest({
|
|
1719
|
+
requestId,
|
|
1720
|
+
message,
|
|
1721
|
+
options: { skipQueue: true },
|
|
1722
|
+
select: (msg) => {
|
|
1723
|
+
if (msg.type !== "status") {
|
|
1724
|
+
return null;
|
|
1725
|
+
}
|
|
1726
|
+
const resumed = AgentResumedStatusPayloadSchema.safeParse(msg.payload);
|
|
1727
|
+
if (resumed.success && resumed.data.requestId === requestId) {
|
|
1728
|
+
return resumed.data;
|
|
1729
|
+
}
|
|
1730
|
+
return null;
|
|
1731
|
+
},
|
|
1732
|
+
});
|
|
1733
|
+
return status.agent;
|
|
1734
|
+
}
|
|
1735
|
+
async importAgent(input) {
|
|
1736
|
+
const requestId = this.createRequestId();
|
|
1737
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1738
|
+
type: "import_agent_request",
|
|
1739
|
+
requestId,
|
|
1740
|
+
...("providerId" in input
|
|
1741
|
+
? { providerId: input.providerId, providerHandleId: input.providerHandleId }
|
|
1742
|
+
: { provider: input.provider, sessionId: input.sessionId }),
|
|
1743
|
+
...(input.cwd ? { cwd: input.cwd } : {}),
|
|
1744
|
+
...(input.workspaceId ? { workspaceId: input.workspaceId } : {}),
|
|
1745
|
+
...(input.labels && Object.keys(input.labels).length > 0 ? { labels: input.labels } : {}),
|
|
1746
|
+
});
|
|
1747
|
+
const status = await this.sendRequest({
|
|
1748
|
+
requestId,
|
|
1749
|
+
message,
|
|
1750
|
+
options: { skipQueue: true },
|
|
1751
|
+
select: (msg) => {
|
|
1752
|
+
if (msg.type !== "status") {
|
|
1753
|
+
return null;
|
|
1754
|
+
}
|
|
1755
|
+
const resumed = AgentResumedStatusPayloadSchema.safeParse(msg.payload);
|
|
1756
|
+
if (resumed.success && resumed.data.requestId === requestId) {
|
|
1757
|
+
return resumed.data;
|
|
1758
|
+
}
|
|
1759
|
+
const failed = AgentCreateFailedStatusPayloadSchema.safeParse(msg.payload);
|
|
1760
|
+
if (failed.success && failed.data.requestId === requestId) {
|
|
1761
|
+
return failed.data;
|
|
1762
|
+
}
|
|
1763
|
+
return null;
|
|
1764
|
+
},
|
|
1765
|
+
});
|
|
1766
|
+
if (status.status === "agent_create_failed") {
|
|
1767
|
+
throw new Error(status.error);
|
|
1768
|
+
}
|
|
1769
|
+
return status.agent;
|
|
1770
|
+
}
|
|
1771
|
+
async refreshAgent(agentId, requestId) {
|
|
1772
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
1773
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1774
|
+
type: "refresh_agent_request",
|
|
1775
|
+
agentId,
|
|
1776
|
+
requestId: resolvedRequestId,
|
|
1777
|
+
});
|
|
1778
|
+
return this.sendRequest({
|
|
1779
|
+
requestId: resolvedRequestId,
|
|
1780
|
+
message,
|
|
1781
|
+
options: { skipQueue: true },
|
|
1782
|
+
select: (msg) => {
|
|
1783
|
+
if (msg.type !== "status") {
|
|
1784
|
+
return null;
|
|
1785
|
+
}
|
|
1786
|
+
const refreshed = AgentRefreshedStatusPayloadSchema.safeParse(msg.payload);
|
|
1787
|
+
if (refreshed.success && refreshed.data.requestId === resolvedRequestId) {
|
|
1788
|
+
return refreshed.data;
|
|
1789
|
+
}
|
|
1790
|
+
return null;
|
|
1791
|
+
},
|
|
1792
|
+
});
|
|
1793
|
+
}
|
|
1794
|
+
async fetchAgentTimeline(agentId, options = {}) {
|
|
1795
|
+
const resolvedRequestId = this.createRequestId(options.requestId);
|
|
1796
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1797
|
+
type: "fetch_agent_timeline_request",
|
|
1798
|
+
agentId,
|
|
1799
|
+
requestId: resolvedRequestId,
|
|
1800
|
+
...(options.direction ? { direction: options.direction } : {}),
|
|
1801
|
+
...(options.cursor ? { cursor: options.cursor } : {}),
|
|
1802
|
+
...(typeof options.limit === "number" ? { limit: options.limit } : {}),
|
|
1803
|
+
...(options.projection ? { projection: options.projection } : {}),
|
|
1804
|
+
...(options.mergeWindow === true ? { mergeWindow: true } : {}),
|
|
1805
|
+
});
|
|
1806
|
+
const payload = await this.sendRequest({
|
|
1807
|
+
requestId: resolvedRequestId,
|
|
1808
|
+
message,
|
|
1809
|
+
timeout: options.timeout,
|
|
1810
|
+
options: { skipQueue: true },
|
|
1811
|
+
select: (msg) => {
|
|
1812
|
+
if (msg.type !== "fetch_agent_timeline_response") {
|
|
1813
|
+
return null;
|
|
1814
|
+
}
|
|
1815
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
1816
|
+
return null;
|
|
1817
|
+
}
|
|
1818
|
+
return msg.payload;
|
|
1819
|
+
},
|
|
1820
|
+
});
|
|
1821
|
+
if (payload.error) {
|
|
1822
|
+
throw new Error(payload.error);
|
|
1823
|
+
}
|
|
1824
|
+
return payload;
|
|
1825
|
+
}
|
|
1826
|
+
async appendAgentTimelineItem(agentId, item) {
|
|
1827
|
+
const requestId = this.createRequestId();
|
|
1828
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
1829
|
+
requestId,
|
|
1830
|
+
message: { type: "agent.timeline.append.request", requestId, agentId, item },
|
|
1831
|
+
responseType: "agent.timeline.append.response",
|
|
1832
|
+
});
|
|
1833
|
+
return { seq: payload.seq, epoch: payload.epoch };
|
|
1834
|
+
}
|
|
1835
|
+
async listAgentTimelinePrompts(agentId, options = {}) {
|
|
1836
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1837
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1838
|
+
type: "agent.timeline.list_prompts.request",
|
|
1839
|
+
agentId,
|
|
1840
|
+
requestId,
|
|
1841
|
+
});
|
|
1842
|
+
const payload = await this.sendRequest({
|
|
1843
|
+
requestId,
|
|
1844
|
+
message,
|
|
1845
|
+
timeout: options.timeout,
|
|
1846
|
+
options: { skipQueue: true },
|
|
1847
|
+
select: (response) => response.type === "agent.timeline.list_prompts.response" &&
|
|
1848
|
+
response.payload.requestId === requestId
|
|
1849
|
+
? response.payload
|
|
1850
|
+
: null,
|
|
1851
|
+
});
|
|
1852
|
+
if (payload.error) {
|
|
1853
|
+
throw new Error(payload.error);
|
|
1854
|
+
}
|
|
1855
|
+
return payload;
|
|
1856
|
+
}
|
|
1857
|
+
async listProviderSubagents(parentAgentId, options = {}) {
|
|
1858
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1859
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1860
|
+
type: "agent.provider_subagents.list.request",
|
|
1861
|
+
parentAgentId,
|
|
1862
|
+
requestId,
|
|
1863
|
+
});
|
|
1864
|
+
const payload = await this.sendRequest({
|
|
1865
|
+
requestId,
|
|
1866
|
+
message,
|
|
1867
|
+
timeout: options.timeout,
|
|
1868
|
+
options: { skipQueue: true },
|
|
1869
|
+
select: (response) => response.type === "agent.provider_subagents.list.response" &&
|
|
1870
|
+
response.payload.requestId === requestId
|
|
1871
|
+
? response.payload
|
|
1872
|
+
: null,
|
|
1873
|
+
});
|
|
1874
|
+
if (payload.error) {
|
|
1875
|
+
throw new Error(payload.error);
|
|
1876
|
+
}
|
|
1877
|
+
return payload;
|
|
1878
|
+
}
|
|
1879
|
+
async fetchProviderSubagentTimeline(parentAgentId, subagentId, options = {}) {
|
|
1880
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1881
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1882
|
+
type: "agent.provider_subagents.timeline.get.request",
|
|
1883
|
+
parentAgentId,
|
|
1884
|
+
subagentId,
|
|
1885
|
+
requestId,
|
|
1886
|
+
...(options.direction ? { direction: options.direction } : {}),
|
|
1887
|
+
...(options.cursor ? { cursor: options.cursor } : {}),
|
|
1888
|
+
...(typeof options.limit === "number" ? { limit: options.limit } : {}),
|
|
1889
|
+
});
|
|
1890
|
+
const payload = await this.sendRequest({
|
|
1891
|
+
requestId,
|
|
1892
|
+
message,
|
|
1893
|
+
timeout: options.timeout,
|
|
1894
|
+
options: { skipQueue: true },
|
|
1895
|
+
select: (response) => response.type === "agent.provider_subagents.timeline.get.response" &&
|
|
1896
|
+
response.payload.requestId === requestId
|
|
1897
|
+
? response.payload
|
|
1898
|
+
: null,
|
|
1899
|
+
});
|
|
1900
|
+
if (payload.error) {
|
|
1901
|
+
throw new Error(payload.error);
|
|
1902
|
+
}
|
|
1903
|
+
return payload;
|
|
1904
|
+
}
|
|
1905
|
+
async askSideConversation(parentAgentId, threadId, question, options = {}) {
|
|
1906
|
+
this.requireSideConversationSupport();
|
|
1907
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1908
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1909
|
+
type: "agent.side_conversation.ask.request",
|
|
1910
|
+
parentAgentId,
|
|
1911
|
+
threadId,
|
|
1912
|
+
question,
|
|
1913
|
+
requestId,
|
|
1914
|
+
});
|
|
1915
|
+
const payload = await this.sendRequest({
|
|
1916
|
+
requestId,
|
|
1917
|
+
message,
|
|
1918
|
+
timeout: options.timeout,
|
|
1919
|
+
options: { skipQueue: true },
|
|
1920
|
+
select: (response) => response.type === "agent.side_conversation.ask.response" &&
|
|
1921
|
+
response.payload.requestId === requestId
|
|
1922
|
+
? response.payload
|
|
1923
|
+
: null,
|
|
1924
|
+
});
|
|
1925
|
+
if (payload.error)
|
|
1926
|
+
throw new Error(payload.error);
|
|
1927
|
+
return payload;
|
|
1928
|
+
}
|
|
1929
|
+
async fetchSideConversationTimeline(parentAgentId, threadId, options = {}) {
|
|
1930
|
+
this.requireSideConversationSupport();
|
|
1931
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1932
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1933
|
+
type: "agent.side_conversation.timeline.get.request",
|
|
1934
|
+
parentAgentId,
|
|
1935
|
+
threadId,
|
|
1936
|
+
requestId,
|
|
1937
|
+
});
|
|
1938
|
+
const payload = await this.sendRequest({
|
|
1939
|
+
requestId,
|
|
1940
|
+
message,
|
|
1941
|
+
timeout: options.timeout,
|
|
1942
|
+
options: { skipQueue: true },
|
|
1943
|
+
select: (response) => response.type === "agent.side_conversation.timeline.get.response" &&
|
|
1944
|
+
response.payload.requestId === requestId
|
|
1945
|
+
? response.payload
|
|
1946
|
+
: null,
|
|
1947
|
+
});
|
|
1948
|
+
if (payload.error)
|
|
1949
|
+
throw new Error(payload.error);
|
|
1950
|
+
return payload;
|
|
1951
|
+
}
|
|
1952
|
+
async listSideConversations(parentAgentId, options = {}) {
|
|
1953
|
+
this.requireSideConversationSupport();
|
|
1954
|
+
const requestId = this.createRequestId(options.requestId);
|
|
1955
|
+
const message = SessionInboundMessageSchema.parse({
|
|
1956
|
+
type: "agent.side_conversation.list.request",
|
|
1957
|
+
parentAgentId,
|
|
1958
|
+
requestId,
|
|
1959
|
+
});
|
|
1960
|
+
const payload = await this.sendRequest({
|
|
1961
|
+
requestId,
|
|
1962
|
+
message,
|
|
1963
|
+
timeout: options.timeout,
|
|
1964
|
+
options: { skipQueue: true },
|
|
1965
|
+
select: (response) => response.type === "agent.side_conversation.list.response" &&
|
|
1966
|
+
response.payload.requestId === requestId
|
|
1967
|
+
? response.payload
|
|
1968
|
+
: null,
|
|
1969
|
+
});
|
|
1970
|
+
if (payload.error)
|
|
1971
|
+
throw new Error(payload.error);
|
|
1972
|
+
return payload;
|
|
1973
|
+
}
|
|
1974
|
+
setAgentTimelineSubscription(agentIds) {
|
|
1975
|
+
return this.subscriptions.setViewed(agentIds);
|
|
1976
|
+
}
|
|
1977
|
+
subscribeAgentTimeline(agentId, handler) {
|
|
1978
|
+
const stream = this.on("agent_stream", (message) => {
|
|
1979
|
+
if (message.payload.agentId === agentId)
|
|
1980
|
+
handler(message);
|
|
1981
|
+
});
|
|
1982
|
+
const replacement = this.on("agent.timeline.replacement", (message) => {
|
|
1983
|
+
if (message.payload.agentId === agentId)
|
|
1984
|
+
handler(message);
|
|
1985
|
+
});
|
|
1986
|
+
const release = this.subscriptions.observeTimeline(agentId);
|
|
1987
|
+
return Object.assign(() => {
|
|
1988
|
+
stream();
|
|
1989
|
+
replacement();
|
|
1990
|
+
release();
|
|
1991
|
+
}, { ready: release.ready });
|
|
1992
|
+
}
|
|
1993
|
+
updateEventSubscriptions() {
|
|
1994
|
+
const events = [
|
|
1995
|
+
"project.update",
|
|
1996
|
+
"providers_snapshot_update",
|
|
1997
|
+
"agent_attention_required",
|
|
1998
|
+
"agent_permission_request",
|
|
1999
|
+
"agent_permission_resolved",
|
|
2000
|
+
];
|
|
2001
|
+
if (this.eventListeners.size === 0 && !this.messageHandlers.has("providers_snapshot_update")) {
|
|
2002
|
+
this.providerSnapshotUpdates.clear();
|
|
2003
|
+
}
|
|
2004
|
+
this.subscriptions.setEvents(events.filter((type) => this.eventListeners.size > 0 || (this.messageHandlers.get(type)?.size ?? 0) > 0));
|
|
2005
|
+
}
|
|
2006
|
+
async sendEventSubscription(events) {
|
|
2007
|
+
if (this.connectionState.status !== "connected")
|
|
2008
|
+
return;
|
|
2009
|
+
// COMPAT(explicitEventSubscriptions): added in v0.8.0, remove legacy broadcast handling after 2027-03-08.
|
|
2010
|
+
if (!this.lastServerInfoMessage?.features?.explicitEventSubscriptions ||
|
|
2011
|
+
this.config.capabilities?.[CLIENT_CAPS.explicitEventSubscriptions] === false)
|
|
2012
|
+
return;
|
|
2013
|
+
await this.sendCorrelatedSessionRequest({
|
|
2014
|
+
message: { type: "session.events.set_subscription.request", events },
|
|
2015
|
+
responseType: "session.events.set_subscription.response",
|
|
2016
|
+
});
|
|
2017
|
+
}
|
|
2018
|
+
async sendTimelineSubscription(agentIds) {
|
|
2019
|
+
if (this.connectionState.status !== "connected")
|
|
2020
|
+
return;
|
|
2021
|
+
// COMPAT(selectiveAgentTimeline): added in v0.1.106. Old daemons keep their
|
|
2022
|
+
// legacy global stream and do not understand this RPC. Remove after
|
|
2023
|
+
// 2027-01-12 once the supported daemon floor is >= v0.1.106.
|
|
2024
|
+
if (!this.lastServerInfoMessage?.features?.selectiveAgentTimeline) {
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
const requestId = this.createRequestId();
|
|
2028
|
+
const normalizedAgentIds = [...new Set(agentIds)].sort();
|
|
2029
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2030
|
+
type: "agent.timeline.set_subscription.request",
|
|
2031
|
+
agentIds: normalizedAgentIds,
|
|
2032
|
+
requestId,
|
|
2033
|
+
});
|
|
2034
|
+
await this.sendRequest({
|
|
2035
|
+
requestId,
|
|
2036
|
+
message,
|
|
2037
|
+
options: { skipQueue: true },
|
|
2038
|
+
select: (response) => {
|
|
2039
|
+
if (response.type !== "agent.timeline.set_subscription.response") {
|
|
2040
|
+
return null;
|
|
2041
|
+
}
|
|
2042
|
+
return response.payload.requestId === requestId ? response.payload : null;
|
|
2043
|
+
},
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
async buildAgentForkContext(agentId, options = {}) {
|
|
2047
|
+
const resolvedRequestId = this.createRequestId(options.requestId);
|
|
2048
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2049
|
+
type: "agent.fork_context.request",
|
|
2050
|
+
agentId,
|
|
2051
|
+
requestId: resolvedRequestId,
|
|
2052
|
+
...(options.boundaryCursor ? { boundaryCursor: options.boundaryCursor } : {}),
|
|
2053
|
+
...(options.boundaryMessageId ? { boundaryMessageId: options.boundaryMessageId } : {}),
|
|
2054
|
+
});
|
|
2055
|
+
const payload = await this.sendRequest({
|
|
2056
|
+
requestId: resolvedRequestId,
|
|
2057
|
+
message,
|
|
2058
|
+
timeout: 15000,
|
|
2059
|
+
options: { skipQueue: true },
|
|
2060
|
+
select: (msg) => {
|
|
2061
|
+
if (msg.type !== "agent.fork_context.response") {
|
|
2062
|
+
return null;
|
|
2063
|
+
}
|
|
2064
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
2065
|
+
return null;
|
|
2066
|
+
}
|
|
2067
|
+
return msg.payload;
|
|
2068
|
+
},
|
|
2069
|
+
});
|
|
2070
|
+
if (payload.error) {
|
|
2071
|
+
throw new Error(payload.error);
|
|
2072
|
+
}
|
|
2073
|
+
return payload;
|
|
2074
|
+
}
|
|
2075
|
+
// ============================================================================
|
|
2076
|
+
// Agent Interaction
|
|
2077
|
+
// ============================================================================
|
|
2078
|
+
async sendAgentMessage(agentId, text, options) {
|
|
2079
|
+
const requestId = this.createRequestId();
|
|
2080
|
+
const messageId = options?.messageId ?? crypto.randomUUID();
|
|
2081
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2082
|
+
type: "send_agent_message_request",
|
|
2083
|
+
requestId,
|
|
2084
|
+
agentId,
|
|
2085
|
+
text,
|
|
2086
|
+
...(messageId ? { messageId } : {}),
|
|
2087
|
+
...(options?.activeTurnBehavior ? { activeTurnBehavior: options.activeTurnBehavior } : {}),
|
|
2088
|
+
...(options?.images ? { images: options.images } : {}),
|
|
2089
|
+
...(options?.attachments ? { attachments: options.attachments } : {}),
|
|
2090
|
+
});
|
|
2091
|
+
const payload = await this.sendRequest({
|
|
2092
|
+
requestId,
|
|
2093
|
+
message,
|
|
2094
|
+
options: { skipQueue: true },
|
|
2095
|
+
select: (msg) => {
|
|
2096
|
+
if (msg.type !== "send_agent_message_response") {
|
|
2097
|
+
return null;
|
|
2098
|
+
}
|
|
2099
|
+
if (msg.payload.requestId !== requestId) {
|
|
2100
|
+
return null;
|
|
2101
|
+
}
|
|
2102
|
+
return msg.payload;
|
|
2103
|
+
},
|
|
2104
|
+
});
|
|
2105
|
+
if (!payload.accepted) {
|
|
2106
|
+
throw new Error(payload.error ?? "sendAgentMessage rejected");
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
async sendMessage(agentId, text, options) {
|
|
2110
|
+
await this.sendAgentMessage(agentId, text, options);
|
|
2111
|
+
}
|
|
2112
|
+
async rewindAgent(agentId, messageId, mode) {
|
|
2113
|
+
const requestId = this.createRequestId();
|
|
2114
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2115
|
+
type: "agent.rewind.request",
|
|
2116
|
+
requestId,
|
|
2117
|
+
agentId,
|
|
2118
|
+
messageId,
|
|
2119
|
+
mode,
|
|
2120
|
+
});
|
|
2121
|
+
const payload = await this.sendRequest({
|
|
2122
|
+
requestId,
|
|
2123
|
+
message,
|
|
2124
|
+
options: { skipQueue: true },
|
|
2125
|
+
select: (msg) => {
|
|
2126
|
+
if (msg.type !== "agent.rewind.response") {
|
|
2127
|
+
return null;
|
|
2128
|
+
}
|
|
2129
|
+
if (msg.payload.requestId !== requestId) {
|
|
2130
|
+
return null;
|
|
2131
|
+
}
|
|
2132
|
+
return msg.payload;
|
|
2133
|
+
},
|
|
2134
|
+
});
|
|
2135
|
+
if (!payload.ok) {
|
|
2136
|
+
throw new Error(payload.error ?? "Agent rewind failed");
|
|
2137
|
+
}
|
|
2138
|
+
return payload;
|
|
2139
|
+
}
|
|
2140
|
+
async cancelAgent(agentId) {
|
|
2141
|
+
const requestId = this.createRequestId();
|
|
2142
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2143
|
+
type: "cancel_agent_request",
|
|
2144
|
+
agentId,
|
|
2145
|
+
requestId,
|
|
2146
|
+
});
|
|
2147
|
+
const payload = await this.sendRequest({
|
|
2148
|
+
requestId,
|
|
2149
|
+
message,
|
|
2150
|
+
options: { skipQueue: true },
|
|
2151
|
+
select: (msg) => {
|
|
2152
|
+
if (msg.type !== "cancel_agent_response") {
|
|
2153
|
+
return null;
|
|
2154
|
+
}
|
|
2155
|
+
if (msg.payload.requestId !== requestId) {
|
|
2156
|
+
return null;
|
|
2157
|
+
}
|
|
2158
|
+
return msg.payload;
|
|
2159
|
+
},
|
|
2160
|
+
});
|
|
2161
|
+
if (payload.error) {
|
|
2162
|
+
throw new Error(payload.error);
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
async setAgentMode(agentId, modeId) {
|
|
2166
|
+
const requestId = this.createRequestId();
|
|
2167
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2168
|
+
type: "set_agent_mode_request",
|
|
2169
|
+
agentId,
|
|
2170
|
+
modeId,
|
|
2171
|
+
requestId,
|
|
2172
|
+
});
|
|
2173
|
+
const payload = await this.sendRequest({
|
|
2174
|
+
requestId,
|
|
2175
|
+
message,
|
|
2176
|
+
options: { skipQueue: true },
|
|
2177
|
+
select: (msg) => {
|
|
2178
|
+
if (msg.type !== "set_agent_mode_response") {
|
|
2179
|
+
return null;
|
|
2180
|
+
}
|
|
2181
|
+
if (msg.payload.requestId !== requestId) {
|
|
2182
|
+
return null;
|
|
2183
|
+
}
|
|
2184
|
+
return msg.payload;
|
|
2185
|
+
},
|
|
2186
|
+
});
|
|
2187
|
+
if (!payload.accepted) {
|
|
2188
|
+
throw new Error(payload.error ?? "setAgentMode rejected");
|
|
2189
|
+
}
|
|
2190
|
+
return payload.notice ?? null;
|
|
2191
|
+
}
|
|
2192
|
+
async setAgentModel(agentId, modelId) {
|
|
2193
|
+
const requestId = this.createRequestId();
|
|
2194
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2195
|
+
type: "set_agent_model_request",
|
|
2196
|
+
agentId,
|
|
2197
|
+
modelId,
|
|
2198
|
+
requestId,
|
|
2199
|
+
});
|
|
2200
|
+
const payload = await this.sendRequest({
|
|
2201
|
+
requestId,
|
|
2202
|
+
message,
|
|
2203
|
+
options: { skipQueue: true },
|
|
2204
|
+
select: (msg) => {
|
|
2205
|
+
if (msg.type !== "set_agent_model_response") {
|
|
2206
|
+
return null;
|
|
2207
|
+
}
|
|
2208
|
+
if (msg.payload.requestId !== requestId) {
|
|
2209
|
+
return null;
|
|
2210
|
+
}
|
|
2211
|
+
return msg.payload;
|
|
2212
|
+
},
|
|
2213
|
+
});
|
|
2214
|
+
if (!payload.accepted) {
|
|
2215
|
+
throw new Error(payload.error ?? "setAgentModel rejected");
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
async setAgentFeature(agentId, featureId, value) {
|
|
2219
|
+
const requestId = this.createRequestId();
|
|
2220
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2221
|
+
type: "set_agent_feature_request",
|
|
2222
|
+
agentId,
|
|
2223
|
+
featureId,
|
|
2224
|
+
value,
|
|
2225
|
+
requestId,
|
|
2226
|
+
});
|
|
2227
|
+
const payload = await this.sendRequest({
|
|
2228
|
+
requestId,
|
|
2229
|
+
message,
|
|
2230
|
+
options: { skipQueue: true },
|
|
2231
|
+
select: (msg) => {
|
|
2232
|
+
if (msg.type !== "set_agent_feature_response") {
|
|
2233
|
+
return null;
|
|
2234
|
+
}
|
|
2235
|
+
if (msg.payload.requestId !== requestId) {
|
|
2236
|
+
return null;
|
|
2237
|
+
}
|
|
2238
|
+
return msg.payload;
|
|
2239
|
+
},
|
|
2240
|
+
});
|
|
2241
|
+
if (!payload.accepted) {
|
|
2242
|
+
throw new Error(payload.error ?? "setAgentFeature rejected");
|
|
2243
|
+
}
|
|
2244
|
+
}
|
|
2245
|
+
async setAgentThinkingOption(agentId, thinkingOptionId) {
|
|
2246
|
+
const requestId = this.createRequestId();
|
|
2247
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2248
|
+
type: "set_agent_thinking_request",
|
|
2249
|
+
agentId,
|
|
2250
|
+
thinkingOptionId,
|
|
2251
|
+
requestId,
|
|
2252
|
+
});
|
|
2253
|
+
const payload = await this.sendRequest({
|
|
2254
|
+
requestId,
|
|
2255
|
+
message,
|
|
2256
|
+
options: { skipQueue: true },
|
|
2257
|
+
select: (msg) => {
|
|
2258
|
+
if (msg.type !== "set_agent_thinking_response") {
|
|
2259
|
+
return null;
|
|
2260
|
+
}
|
|
2261
|
+
if (msg.payload.requestId !== requestId) {
|
|
2262
|
+
return null;
|
|
2263
|
+
}
|
|
2264
|
+
return msg.payload;
|
|
2265
|
+
},
|
|
2266
|
+
});
|
|
2267
|
+
if (!payload.accepted) {
|
|
2268
|
+
throw new Error(payload.error ?? "setAgentThinkingOption rejected");
|
|
2269
|
+
}
|
|
2270
|
+
return payload.notice ?? null;
|
|
2271
|
+
}
|
|
2272
|
+
/**
|
|
2273
|
+
* Applies a whole agent-config bundle in one request. Use this instead of
|
|
2274
|
+
* chaining the single-field setters when the values belong together so client
|
|
2275
|
+
* interruption and other mutations cannot interleave between steps. A
|
|
2276
|
+
* provider rejection can still leave earlier steps applied.
|
|
2277
|
+
* Gated on `server_info.features.agentConfigApply`.
|
|
2278
|
+
*/
|
|
2279
|
+
async applyAgentConfig(agentId, config) {
|
|
2280
|
+
const requestId = this.createRequestId();
|
|
2281
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2282
|
+
type: "agent.config.apply.request",
|
|
2283
|
+
agentId,
|
|
2284
|
+
config,
|
|
2285
|
+
requestId,
|
|
2286
|
+
});
|
|
2287
|
+
const payload = await this.sendRequest({
|
|
2288
|
+
requestId,
|
|
2289
|
+
message,
|
|
2290
|
+
options: { skipQueue: true },
|
|
2291
|
+
select: (msg) => {
|
|
2292
|
+
if (msg.type !== "agent.config.apply.response") {
|
|
2293
|
+
return null;
|
|
2294
|
+
}
|
|
2295
|
+
if (msg.payload.requestId !== requestId) {
|
|
2296
|
+
return null;
|
|
2297
|
+
}
|
|
2298
|
+
return msg.payload;
|
|
2299
|
+
},
|
|
2300
|
+
});
|
|
2301
|
+
if (!payload.accepted) {
|
|
2302
|
+
throw new Error(payload.error ?? "applyAgentConfig rejected");
|
|
2303
|
+
}
|
|
2304
|
+
return payload.notice ?? null;
|
|
2305
|
+
}
|
|
2306
|
+
async restartServer(reason, requestId) {
|
|
2307
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
2308
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2309
|
+
type: "restart_server_request",
|
|
2310
|
+
...(reason && reason.trim().length > 0 ? { reason } : {}),
|
|
2311
|
+
requestId: resolvedRequestId,
|
|
2312
|
+
});
|
|
2313
|
+
return this.sendRequest({
|
|
2314
|
+
requestId: resolvedRequestId,
|
|
2315
|
+
message,
|
|
2316
|
+
options: { skipQueue: true },
|
|
2317
|
+
select: (msg) => {
|
|
2318
|
+
if (msg.type !== "status") {
|
|
2319
|
+
return null;
|
|
2320
|
+
}
|
|
2321
|
+
const restarted = RestartRequestedStatusPayloadSchema.safeParse(msg.payload);
|
|
2322
|
+
if (!restarted.success) {
|
|
2323
|
+
return null;
|
|
2324
|
+
}
|
|
2325
|
+
if (restarted.data.requestId !== resolvedRequestId) {
|
|
2326
|
+
return null;
|
|
2327
|
+
}
|
|
2328
|
+
return restarted.data;
|
|
2329
|
+
},
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
async shutdownServer(options) {
|
|
2333
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
2334
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2335
|
+
type: "shutdown_server_request",
|
|
2336
|
+
requestId: resolvedRequestId,
|
|
2337
|
+
});
|
|
2338
|
+
return this.sendRequest({
|
|
2339
|
+
requestId: resolvedRequestId,
|
|
2340
|
+
message,
|
|
2341
|
+
timeout: options?.timeout,
|
|
2342
|
+
options: { skipQueue: true },
|
|
2343
|
+
select: (msg) => {
|
|
2344
|
+
if (msg.type !== "status") {
|
|
2345
|
+
return null;
|
|
2346
|
+
}
|
|
2347
|
+
const shutdown = ShutdownRequestedStatusPayloadSchema.safeParse(msg.payload);
|
|
2348
|
+
if (!shutdown.success) {
|
|
2349
|
+
return null;
|
|
2350
|
+
}
|
|
2351
|
+
if (shutdown.data.requestId !== resolvedRequestId) {
|
|
2352
|
+
return null;
|
|
2353
|
+
}
|
|
2354
|
+
return shutdown.data;
|
|
2355
|
+
},
|
|
2356
|
+
});
|
|
2357
|
+
}
|
|
2358
|
+
async updateDaemon(requestId) {
|
|
2359
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
2360
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2361
|
+
type: "daemon.update.request",
|
|
2362
|
+
requestId: resolvedRequestId,
|
|
2363
|
+
});
|
|
2364
|
+
return this.sendRequest({
|
|
2365
|
+
requestId: resolvedRequestId,
|
|
2366
|
+
message,
|
|
2367
|
+
timeout: 300000, // 5 minutes — npm update can be slow on remote machines
|
|
2368
|
+
options: { skipQueue: true },
|
|
2369
|
+
select: (msg) => {
|
|
2370
|
+
const parsed = DaemonUpdateResponseSchema.safeParse(msg);
|
|
2371
|
+
if (!parsed.success) {
|
|
2372
|
+
return null;
|
|
2373
|
+
}
|
|
2374
|
+
if (parsed.data.payload.requestId !== resolvedRequestId) {
|
|
2375
|
+
return null;
|
|
2376
|
+
}
|
|
2377
|
+
return parsed.data.payload;
|
|
2378
|
+
},
|
|
2379
|
+
});
|
|
2380
|
+
}
|
|
2381
|
+
// ============================================================================
|
|
2382
|
+
// Audio / Voice
|
|
2383
|
+
// ============================================================================
|
|
2384
|
+
async setVoiceMode(enabled, agentId) {
|
|
2385
|
+
const requestId = this.createRequestId();
|
|
2386
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2387
|
+
type: "set_voice_mode",
|
|
2388
|
+
enabled,
|
|
2389
|
+
...(agentId ? { agentId } : {}),
|
|
2390
|
+
requestId,
|
|
2391
|
+
});
|
|
2392
|
+
const response = await this.sendRequest({
|
|
2393
|
+
requestId,
|
|
2394
|
+
message,
|
|
2395
|
+
select: (msg) => {
|
|
2396
|
+
if (msg.type !== "set_voice_mode_response") {
|
|
2397
|
+
return null;
|
|
2398
|
+
}
|
|
2399
|
+
if (msg.payload.requestId !== requestId) {
|
|
2400
|
+
return null;
|
|
2401
|
+
}
|
|
2402
|
+
return msg.payload;
|
|
2403
|
+
},
|
|
2404
|
+
});
|
|
2405
|
+
if (!response.accepted) {
|
|
2406
|
+
const codeSuffix = typeof response.reasonCode === "string" && response.reasonCode.trim().length > 0
|
|
2407
|
+
? ` (${response.reasonCode})`
|
|
2408
|
+
: "";
|
|
2409
|
+
throw new Error((response.error ?? "Failed to set voice mode") + codeSuffix);
|
|
2410
|
+
}
|
|
2411
|
+
return response;
|
|
2412
|
+
}
|
|
2413
|
+
async sendVoiceAudioChunk(audio, format, isLast = false) {
|
|
2414
|
+
this.sendSessionMessage({ type: "voice_audio_chunk", audio, format, isLast });
|
|
2415
|
+
}
|
|
2416
|
+
async startDictationStream(dictationId, format) {
|
|
2417
|
+
const ack = this.waitForWithCancel((msg) => {
|
|
2418
|
+
if (msg.type !== "dictation_stream_ack") {
|
|
2419
|
+
return null;
|
|
2420
|
+
}
|
|
2421
|
+
if (msg.payload.dictationId !== dictationId) {
|
|
2422
|
+
return null;
|
|
2423
|
+
}
|
|
2424
|
+
if (msg.payload.ackSeq !== -1) {
|
|
2425
|
+
return null;
|
|
2426
|
+
}
|
|
2427
|
+
return msg.payload;
|
|
2428
|
+
}, 30000, { skipQueue: true });
|
|
2429
|
+
const ackPromise = ack.promise.then(() => undefined);
|
|
2430
|
+
const streamError = this.waitForWithCancel((msg) => {
|
|
2431
|
+
if (msg.type !== "dictation_stream_error") {
|
|
2432
|
+
return null;
|
|
2433
|
+
}
|
|
2434
|
+
if (msg.payload.dictationId !== dictationId) {
|
|
2435
|
+
return null;
|
|
2436
|
+
}
|
|
2437
|
+
return msg.payload;
|
|
2438
|
+
}, 30000, { skipQueue: true });
|
|
2439
|
+
const errorPromise = streamError.promise.then((payload) => {
|
|
2440
|
+
throw new Error(payload.error);
|
|
2441
|
+
});
|
|
2442
|
+
const cleanupError = new Error("Cancelled dictation start waiter");
|
|
2443
|
+
try {
|
|
2444
|
+
this.sendSessionMessageStrict({ type: "dictation_stream_start", dictationId, format });
|
|
2445
|
+
await Promise.race([ackPromise, errorPromise]);
|
|
2446
|
+
}
|
|
2447
|
+
finally {
|
|
2448
|
+
ack.cancel(cleanupError);
|
|
2449
|
+
streamError.cancel(cleanupError);
|
|
2450
|
+
void ackPromise.catch(() => undefined);
|
|
2451
|
+
void errorPromise.catch(() => undefined);
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
sendDictationStreamChunk(dictationId, seq, audio, format) {
|
|
2455
|
+
this.sendSessionMessageStrict({
|
|
2456
|
+
type: "dictation_stream_chunk",
|
|
2457
|
+
dictationId,
|
|
2458
|
+
seq,
|
|
2459
|
+
audio,
|
|
2460
|
+
format,
|
|
2461
|
+
});
|
|
2462
|
+
}
|
|
2463
|
+
async finishDictationStream(dictationId, finalSeq) {
|
|
2464
|
+
const final = this.waitForWithCancel((msg) => {
|
|
2465
|
+
if (msg.type !== "dictation_stream_final") {
|
|
2466
|
+
return null;
|
|
2467
|
+
}
|
|
2468
|
+
if (msg.payload.dictationId !== dictationId) {
|
|
2469
|
+
return null;
|
|
2470
|
+
}
|
|
2471
|
+
return msg.payload;
|
|
2472
|
+
}, 0, { skipQueue: true });
|
|
2473
|
+
const streamError = this.waitForWithCancel((msg) => {
|
|
2474
|
+
if (msg.type !== "dictation_stream_error") {
|
|
2475
|
+
return null;
|
|
2476
|
+
}
|
|
2477
|
+
if (msg.payload.dictationId !== dictationId) {
|
|
2478
|
+
return null;
|
|
2479
|
+
}
|
|
2480
|
+
return msg.payload;
|
|
2481
|
+
}, 0, { skipQueue: true });
|
|
2482
|
+
const finishAccepted = this.waitForWithCancel((msg) => {
|
|
2483
|
+
if (msg.type !== "dictation_stream_finish_accepted") {
|
|
2484
|
+
return null;
|
|
2485
|
+
}
|
|
2486
|
+
if (msg.payload.dictationId !== dictationId) {
|
|
2487
|
+
return null;
|
|
2488
|
+
}
|
|
2489
|
+
return msg.payload;
|
|
2490
|
+
}, DEFAULT_DICTATION_FINISH_ACCEPT_TIMEOUT_MS, { skipQueue: true });
|
|
2491
|
+
const finalPromise = final.promise;
|
|
2492
|
+
const errorPromise = streamError.promise.then((payload) => {
|
|
2493
|
+
throw new Error(payload.error);
|
|
2494
|
+
});
|
|
2495
|
+
const finishAcceptedPromise = finishAccepted.promise;
|
|
2496
|
+
const finalOutcomePromise = finalPromise.then((payload) => ({
|
|
2497
|
+
kind: "final",
|
|
2498
|
+
payload,
|
|
2499
|
+
}));
|
|
2500
|
+
const errorOutcomePromise = errorPromise.then(() => ({
|
|
2501
|
+
kind: "error",
|
|
2502
|
+
error: new Error("Unexpected dictation stream error state"),
|
|
2503
|
+
}), (error) => ({
|
|
2504
|
+
kind: "error",
|
|
2505
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
2506
|
+
}));
|
|
2507
|
+
const finishAcceptedOutcomePromise = finishAcceptedPromise.then((payload) => ({ kind: "accepted", payload }), (error) => {
|
|
2508
|
+
if (isWaiterTimeoutError(error)) {
|
|
2509
|
+
return { kind: "accepted_timeout" };
|
|
2510
|
+
}
|
|
2511
|
+
return {
|
|
2512
|
+
kind: "accepted_error",
|
|
2513
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
2514
|
+
};
|
|
2515
|
+
});
|
|
2516
|
+
const waitForFinalResult = async (timeoutMs) => {
|
|
2517
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
2518
|
+
const outcome = await Promise.race([finalOutcomePromise, errorOutcomePromise]);
|
|
2519
|
+
if (outcome.kind === "error") {
|
|
2520
|
+
throw outcome.error;
|
|
2521
|
+
}
|
|
2522
|
+
return outcome.payload;
|
|
2523
|
+
}
|
|
2524
|
+
let timeoutHandle = null;
|
|
2525
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
2526
|
+
timeoutHandle = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs);
|
|
2527
|
+
});
|
|
2528
|
+
const outcome = await Promise.race([
|
|
2529
|
+
finalOutcomePromise,
|
|
2530
|
+
errorOutcomePromise,
|
|
2531
|
+
timeoutPromise,
|
|
2532
|
+
]);
|
|
2533
|
+
if (timeoutHandle) {
|
|
2534
|
+
clearTimeout(timeoutHandle);
|
|
2535
|
+
}
|
|
2536
|
+
if (outcome.kind === "timeout") {
|
|
2537
|
+
throw new Error(`Timeout waiting for dictation finalization (${timeoutMs}ms)`);
|
|
2538
|
+
}
|
|
2539
|
+
if (outcome.kind === "error") {
|
|
2540
|
+
throw outcome.error;
|
|
2541
|
+
}
|
|
2542
|
+
return outcome.payload;
|
|
2543
|
+
};
|
|
2544
|
+
const cleanupError = new Error("Cancelled dictation finish waiter");
|
|
2545
|
+
try {
|
|
2546
|
+
this.sendSessionMessageStrict({ type: "dictation_stream_finish", dictationId, finalSeq });
|
|
2547
|
+
const firstOutcome = await Promise.race([
|
|
2548
|
+
finalOutcomePromise,
|
|
2549
|
+
errorOutcomePromise,
|
|
2550
|
+
finishAcceptedOutcomePromise,
|
|
2551
|
+
]);
|
|
2552
|
+
if (firstOutcome.kind === "final") {
|
|
2553
|
+
return firstOutcome.payload;
|
|
2554
|
+
}
|
|
2555
|
+
if (firstOutcome.kind === "error") {
|
|
2556
|
+
throw firstOutcome.error;
|
|
2557
|
+
}
|
|
2558
|
+
if (firstOutcome.kind === "accepted") {
|
|
2559
|
+
return await waitForFinalResult(firstOutcome.payload.timeoutMs + DEFAULT_DICTATION_FINISH_TIMEOUT_GRACE_MS);
|
|
2560
|
+
}
|
|
2561
|
+
return await waitForFinalResult(DEFAULT_DICTATION_FINISH_FALLBACK_TIMEOUT_MS);
|
|
2562
|
+
}
|
|
2563
|
+
finally {
|
|
2564
|
+
final.cancel(cleanupError);
|
|
2565
|
+
streamError.cancel(cleanupError);
|
|
2566
|
+
finishAccepted.cancel(cleanupError);
|
|
2567
|
+
void finalPromise.catch(() => undefined);
|
|
2568
|
+
void errorPromise.catch(() => undefined);
|
|
2569
|
+
void finishAcceptedPromise.catch(() => undefined);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
cancelDictationStream(dictationId) {
|
|
2573
|
+
this.sendSessionMessageStrict({ type: "dictation_stream_cancel", dictationId });
|
|
2574
|
+
}
|
|
2575
|
+
async abortRequest() {
|
|
2576
|
+
this.sendSessionMessage({ type: "abort_request" });
|
|
2577
|
+
}
|
|
2578
|
+
async audioPlayed(id) {
|
|
2579
|
+
this.sendSessionMessage({ type: "audio_played", id });
|
|
2580
|
+
}
|
|
2581
|
+
// ============================================================================
|
|
2582
|
+
// Git Operations
|
|
2583
|
+
// ============================================================================
|
|
2584
|
+
async getCheckoutStatus(cwd, options) {
|
|
2585
|
+
const requestId = options?.requestId;
|
|
2586
|
+
if (!requestId) {
|
|
2587
|
+
const existing = this.checkoutStatusInFlight.get(cwd);
|
|
2588
|
+
if (existing) {
|
|
2589
|
+
return existing;
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
2593
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2594
|
+
type: "checkout_status_request",
|
|
2595
|
+
cwd,
|
|
2596
|
+
requestId: resolvedRequestId,
|
|
2597
|
+
});
|
|
2598
|
+
const responsePromise = this.sendRequest({
|
|
2599
|
+
requestId: resolvedRequestId,
|
|
2600
|
+
message,
|
|
2601
|
+
options: { skipQueue: true },
|
|
2602
|
+
select: (msg) => {
|
|
2603
|
+
if (msg.type !== "checkout_status_response") {
|
|
2604
|
+
return null;
|
|
2605
|
+
}
|
|
2606
|
+
if (msg.payload.requestId !== resolvedRequestId) {
|
|
2607
|
+
return null;
|
|
2608
|
+
}
|
|
2609
|
+
return msg.payload;
|
|
2610
|
+
},
|
|
2611
|
+
});
|
|
2612
|
+
if (!requestId) {
|
|
2613
|
+
this.checkoutStatusInFlight.set(cwd, responsePromise);
|
|
2614
|
+
void responsePromise
|
|
2615
|
+
.finally(() => {
|
|
2616
|
+
if (this.checkoutStatusInFlight.get(cwd) === responsePromise) {
|
|
2617
|
+
this.checkoutStatusInFlight.delete(cwd);
|
|
2618
|
+
}
|
|
2619
|
+
})
|
|
2620
|
+
.catch(() => undefined);
|
|
2621
|
+
}
|
|
2622
|
+
return responsePromise;
|
|
2623
|
+
}
|
|
2624
|
+
normalizeCheckoutDiffCompare(compare) {
|
|
2625
|
+
if (compare.mode === "uncommitted") {
|
|
2626
|
+
return compare.ignoreWhitespace === true
|
|
2627
|
+
? { mode: "uncommitted", ignoreWhitespace: true }
|
|
2628
|
+
: { mode: "uncommitted" };
|
|
2629
|
+
}
|
|
2630
|
+
const trimmedBaseRef = compare.baseRef?.trim();
|
|
2631
|
+
if (!trimmedBaseRef) {
|
|
2632
|
+
return compare.ignoreWhitespace === true
|
|
2633
|
+
? { mode: "base", ignoreWhitespace: true }
|
|
2634
|
+
: { mode: "base" };
|
|
2635
|
+
}
|
|
2636
|
+
return compare.ignoreWhitespace === true
|
|
2637
|
+
? { mode: "base", baseRef: trimmedBaseRef, ignoreWhitespace: true }
|
|
2638
|
+
: { mode: "base", baseRef: trimmedBaseRef };
|
|
2639
|
+
}
|
|
2640
|
+
async getCheckoutDiff(cwd, compare, requestId) {
|
|
2641
|
+
const oneShotSubscriptionId = `oneshot-checkout-diff:${crypto.randomUUID()}`;
|
|
2642
|
+
try {
|
|
2643
|
+
const payload = await this.subscribeCheckoutDiff(cwd, compare, {
|
|
2644
|
+
subscriptionId: oneShotSubscriptionId,
|
|
2645
|
+
requestId,
|
|
2646
|
+
});
|
|
2647
|
+
return {
|
|
2648
|
+
cwd: payload.cwd,
|
|
2649
|
+
files: payload.files,
|
|
2650
|
+
error: payload.error,
|
|
2651
|
+
diffTooLarge: payload.diffTooLarge,
|
|
2652
|
+
requestId: payload.requestId,
|
|
2653
|
+
};
|
|
2654
|
+
}
|
|
2655
|
+
finally {
|
|
2656
|
+
try {
|
|
2657
|
+
this.unsubscribeCheckoutDiff(oneShotSubscriptionId);
|
|
2658
|
+
}
|
|
2659
|
+
catch {
|
|
2660
|
+
// Ignore disconnect races during one-shot cleanup.
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
async subscribeCheckoutDiff(cwd, compare, options) {
|
|
2665
|
+
const subscriptionId = options?.subscriptionId ?? crypto.randomUUID();
|
|
2666
|
+
const normalizedCompare = this.normalizeCheckoutDiffCompare(compare);
|
|
2667
|
+
const previousSubscription = this.checkoutDiffSubscriptions.get(subscriptionId) ?? null;
|
|
2668
|
+
this.checkoutDiffSubscriptions.set(subscriptionId, {
|
|
2669
|
+
cwd,
|
|
2670
|
+
compare: normalizedCompare,
|
|
2671
|
+
});
|
|
2672
|
+
const resolvedRequestId = this.createRequestId(options?.requestId);
|
|
2673
|
+
const message = SessionInboundMessageSchema.parse({
|
|
2674
|
+
type: "subscribe_checkout_diff_request",
|
|
2675
|
+
subscriptionId,
|
|
2676
|
+
cwd,
|
|
2677
|
+
compare: normalizedCompare,
|
|
2678
|
+
requestId: resolvedRequestId,
|
|
2679
|
+
});
|
|
2680
|
+
try {
|
|
2681
|
+
return await this.sendCorrelatedRequest({
|
|
2682
|
+
requestId: resolvedRequestId,
|
|
2683
|
+
message,
|
|
2684
|
+
responseType: "subscribe_checkout_diff_response",
|
|
2685
|
+
options: { skipQueue: true },
|
|
2686
|
+
selectPayload: (payload) => {
|
|
2687
|
+
if (payload.subscriptionId !== subscriptionId) {
|
|
2688
|
+
return null;
|
|
2689
|
+
}
|
|
2690
|
+
return payload;
|
|
2691
|
+
},
|
|
2692
|
+
});
|
|
2693
|
+
}
|
|
2694
|
+
catch (error) {
|
|
2695
|
+
if (previousSubscription) {
|
|
2696
|
+
this.checkoutDiffSubscriptions.set(subscriptionId, previousSubscription);
|
|
2697
|
+
}
|
|
2698
|
+
else {
|
|
2699
|
+
this.checkoutDiffSubscriptions.delete(subscriptionId);
|
|
2700
|
+
}
|
|
2701
|
+
throw error;
|
|
2702
|
+
}
|
|
2703
|
+
}
|
|
2704
|
+
unsubscribeCheckoutDiff(subscriptionId) {
|
|
2705
|
+
this.checkoutDiffSubscriptions.delete(subscriptionId);
|
|
2706
|
+
this.sendSessionMessage({
|
|
2707
|
+
type: "unsubscribe_checkout_diff_request",
|
|
2708
|
+
subscriptionId,
|
|
2709
|
+
});
|
|
2710
|
+
}
|
|
2711
|
+
async checkoutCommit(cwd, input, requestId) {
|
|
2712
|
+
return this.sendCorrelatedSessionRequest({
|
|
2713
|
+
requestId,
|
|
2714
|
+
message: {
|
|
2715
|
+
type: "checkout_commit_request",
|
|
2716
|
+
cwd,
|
|
2717
|
+
message: input.message,
|
|
2718
|
+
addAll: input.addAll,
|
|
2719
|
+
},
|
|
2720
|
+
responseType: "checkout_commit_response",
|
|
2721
|
+
});
|
|
2722
|
+
}
|
|
2723
|
+
async checkoutMerge(cwd, input, requestId) {
|
|
2724
|
+
return this.sendCorrelatedSessionRequest({
|
|
2725
|
+
requestId,
|
|
2726
|
+
message: {
|
|
2727
|
+
type: "checkout_merge_request",
|
|
2728
|
+
cwd,
|
|
2729
|
+
baseRef: input.baseRef,
|
|
2730
|
+
strategy: input.strategy,
|
|
2731
|
+
requireCleanTarget: input.requireCleanTarget,
|
|
2732
|
+
},
|
|
2733
|
+
responseType: "checkout_merge_response",
|
|
2734
|
+
});
|
|
2735
|
+
}
|
|
2736
|
+
async checkoutMergeFromBase(cwd, input, requestId) {
|
|
2737
|
+
return this.sendCorrelatedSessionRequest({
|
|
2738
|
+
requestId,
|
|
2739
|
+
message: {
|
|
2740
|
+
type: "checkout_merge_from_base_request",
|
|
2741
|
+
cwd,
|
|
2742
|
+
baseRef: input.baseRef,
|
|
2743
|
+
requireCleanTarget: input.requireCleanTarget,
|
|
2744
|
+
},
|
|
2745
|
+
responseType: "checkout_merge_from_base_response",
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
async checkoutPull(cwd, requestId) {
|
|
2749
|
+
return this.sendCorrelatedSessionRequest({
|
|
2750
|
+
requestId,
|
|
2751
|
+
message: {
|
|
2752
|
+
type: "checkout_pull_request",
|
|
2753
|
+
cwd,
|
|
2754
|
+
},
|
|
2755
|
+
responseType: "checkout_pull_response",
|
|
2756
|
+
});
|
|
2757
|
+
}
|
|
2758
|
+
async checkoutPush(cwd, requestId) {
|
|
2759
|
+
return this.sendCorrelatedSessionRequest({
|
|
2760
|
+
requestId,
|
|
2761
|
+
message: {
|
|
2762
|
+
type: "checkout_push_request",
|
|
2763
|
+
cwd,
|
|
2764
|
+
},
|
|
2765
|
+
responseType: "checkout_push_response",
|
|
2766
|
+
});
|
|
2767
|
+
}
|
|
2768
|
+
async checkoutRefresh(cwd, requestId) {
|
|
2769
|
+
return this.sendCorrelatedSessionRequest({
|
|
2770
|
+
requestId,
|
|
2771
|
+
message: {
|
|
2772
|
+
type: "checkout.refresh.request",
|
|
2773
|
+
cwd,
|
|
2774
|
+
},
|
|
2775
|
+
responseType: "checkout.refresh.response",
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
async listCheckoutCommits(cwd, requestId) {
|
|
2779
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
2780
|
+
requestId,
|
|
2781
|
+
message: {
|
|
2782
|
+
type: "checkout.commits.list.request",
|
|
2783
|
+
cwd,
|
|
2784
|
+
},
|
|
2785
|
+
timeout: 60000,
|
|
2786
|
+
});
|
|
2787
|
+
if (payload.error) {
|
|
2788
|
+
throw new Error(payload.error.message);
|
|
2789
|
+
}
|
|
2790
|
+
return { baseRef: payload.baseRef, commits: payload.commits };
|
|
2791
|
+
}
|
|
2792
|
+
async getCommitFileDiff(cwd, sha, path, requestId) {
|
|
2793
|
+
const payload = await this.sendNamespacedCorrelatedSessionRequest({
|
|
2794
|
+
requestId,
|
|
2795
|
+
message: {
|
|
2796
|
+
type: "checkout.commits.file_diff.request",
|
|
2797
|
+
cwd,
|
|
2798
|
+
sha,
|
|
2799
|
+
path,
|
|
2800
|
+
},
|
|
2801
|
+
timeout: 60000,
|
|
2802
|
+
});
|
|
2803
|
+
if (payload.error) {
|
|
2804
|
+
throw new Error(payload.error.message);
|
|
2805
|
+
}
|
|
2806
|
+
return { file: payload.file };
|
|
2807
|
+
}
|
|
2808
|
+
async checkoutPrCreate(cwd, input, requestId) {
|
|
2809
|
+
return this.sendCorrelatedSessionRequest({
|
|
2810
|
+
requestId,
|
|
2811
|
+
message: {
|
|
2812
|
+
type: "checkout_pr_create_request",
|
|
2813
|
+
cwd,
|
|
2814
|
+
title: input.title,
|
|
2815
|
+
body: input.body,
|
|
2816
|
+
baseRef: input.baseRef,
|
|
2817
|
+
},
|
|
2818
|
+
responseType: "checkout_pr_create_response",
|
|
2819
|
+
});
|
|
2820
|
+
}
|
|
2821
|
+
async checkoutPrMerge(cwd, input, requestId) {
|
|
2822
|
+
return this.sendCorrelatedSessionRequest({
|
|
2823
|
+
requestId,
|
|
2824
|
+
message: {
|
|
2825
|
+
type: "checkout_pr_merge_request",
|
|
2826
|
+
cwd,
|
|
2827
|
+
mergeMethod: input.method,
|
|
2828
|
+
},
|
|
2829
|
+
responseType: "checkout_pr_merge_response",
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
async checkoutForgeSetAutoMerge(cwd, input, requestId) {
|
|
2833
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
2834
|
+
requestId,
|
|
2835
|
+
message: {
|
|
2836
|
+
type: "checkout.forge.set_auto_merge.request",
|
|
2837
|
+
cwd,
|
|
2838
|
+
enabled: input.enabled,
|
|
2839
|
+
...(input.enabled ? { mergeMethod: input.method } : {}),
|
|
2840
|
+
},
|
|
2841
|
+
timeout: 60000,
|
|
2842
|
+
});
|
|
2843
|
+
}
|
|
2844
|
+
async checkoutGithubSetAutoMerge(cwd, input, requestId) {
|
|
2845
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
2846
|
+
requestId,
|
|
2847
|
+
message: {
|
|
2848
|
+
type: "checkout.github.set_auto_merge.request",
|
|
2849
|
+
cwd,
|
|
2850
|
+
enabled: input.enabled,
|
|
2851
|
+
...(input.enabled ? { mergeMethod: input.method } : {}),
|
|
2852
|
+
},
|
|
2853
|
+
});
|
|
2854
|
+
}
|
|
2855
|
+
async checkoutForgeGetCheckDetails(input, requestId) {
|
|
2856
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
2857
|
+
requestId,
|
|
2858
|
+
message: {
|
|
2859
|
+
type: "checkout.forge.get_check_details.request",
|
|
2860
|
+
cwd: input.cwd,
|
|
2861
|
+
repoOwner: input.repoOwner,
|
|
2862
|
+
repoName: input.repoName,
|
|
2863
|
+
checkRunId: input.checkRunId,
|
|
2864
|
+
workflowRunId: input.workflowRunId,
|
|
2865
|
+
changeRequestNumber: input.changeRequestNumber,
|
|
2866
|
+
},
|
|
2867
|
+
timeout: 60000,
|
|
2868
|
+
});
|
|
2869
|
+
}
|
|
2870
|
+
async checkoutGithubGetCheckDetails(input, requestId) {
|
|
2871
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
2872
|
+
requestId,
|
|
2873
|
+
message: {
|
|
2874
|
+
type: "checkout.github.get_check_details.request",
|
|
2875
|
+
cwd: input.cwd,
|
|
2876
|
+
repoOwner: input.repoOwner,
|
|
2877
|
+
repoName: input.repoName,
|
|
2878
|
+
checkRunId: input.checkRunId,
|
|
2879
|
+
workflowRunId: input.workflowRunId,
|
|
2880
|
+
},
|
|
2881
|
+
});
|
|
2882
|
+
}
|
|
2883
|
+
async checkoutPrStatus(cwd, requestId) {
|
|
2884
|
+
return this.sendCorrelatedSessionRequest({
|
|
2885
|
+
requestId,
|
|
2886
|
+
message: {
|
|
2887
|
+
type: "checkout_pr_status_request",
|
|
2888
|
+
cwd,
|
|
2889
|
+
},
|
|
2890
|
+
responseType: "checkout_pr_status_response",
|
|
2891
|
+
});
|
|
2892
|
+
}
|
|
2893
|
+
async pullRequestTimeline(input, requestId) {
|
|
2894
|
+
return this.sendCorrelatedSessionRequest({
|
|
2895
|
+
requestId,
|
|
2896
|
+
message: {
|
|
2897
|
+
type: "pull_request_timeline_request",
|
|
2898
|
+
cwd: input.cwd,
|
|
2899
|
+
prNumber: input.prNumber,
|
|
2900
|
+
repoOwner: input.repoOwner,
|
|
2901
|
+
repoName: input.repoName,
|
|
2902
|
+
},
|
|
2903
|
+
responseType: "pull_request_timeline_response",
|
|
2904
|
+
});
|
|
2905
|
+
}
|
|
2906
|
+
async checkoutSwitchBranch(cwd, branch, requestId) {
|
|
2907
|
+
return this.sendCorrelatedSessionRequest({
|
|
2908
|
+
requestId,
|
|
2909
|
+
message: {
|
|
2910
|
+
type: "checkout_switch_branch_request",
|
|
2911
|
+
cwd,
|
|
2912
|
+
branch,
|
|
2913
|
+
},
|
|
2914
|
+
responseType: "checkout_switch_branch_response",
|
|
2915
|
+
});
|
|
2916
|
+
}
|
|
2917
|
+
async renameBranch(input) {
|
|
2918
|
+
return this.sendCorrelatedSessionRequest({
|
|
2919
|
+
requestId: input.requestId,
|
|
2920
|
+
message: {
|
|
2921
|
+
type: "checkout.rename_branch.request",
|
|
2922
|
+
cwd: input.cwd,
|
|
2923
|
+
branch: input.branch,
|
|
2924
|
+
},
|
|
2925
|
+
responseType: "checkout.rename_branch.response",
|
|
2926
|
+
});
|
|
2927
|
+
}
|
|
2928
|
+
async stashSave(cwd, options, requestId) {
|
|
2929
|
+
return this.sendCorrelatedSessionRequest({
|
|
2930
|
+
requestId,
|
|
2931
|
+
message: {
|
|
2932
|
+
type: "stash_save_request",
|
|
2933
|
+
cwd,
|
|
2934
|
+
branch: options?.branch,
|
|
2935
|
+
},
|
|
2936
|
+
responseType: "stash_save_response",
|
|
2937
|
+
});
|
|
2938
|
+
}
|
|
2939
|
+
async stashPop(cwd, stashIndex, requestId) {
|
|
2940
|
+
return this.sendCorrelatedSessionRequest({
|
|
2941
|
+
requestId,
|
|
2942
|
+
message: {
|
|
2943
|
+
type: "stash_pop_request",
|
|
2944
|
+
cwd,
|
|
2945
|
+
stashIndex,
|
|
2946
|
+
},
|
|
2947
|
+
responseType: "stash_pop_response",
|
|
2948
|
+
});
|
|
2949
|
+
}
|
|
2950
|
+
async stashList(cwd, options, requestId) {
|
|
2951
|
+
return this.sendCorrelatedSessionRequest({
|
|
2952
|
+
requestId,
|
|
2953
|
+
message: {
|
|
2954
|
+
type: "stash_list_request",
|
|
2955
|
+
cwd,
|
|
2956
|
+
paseoOnly: options?.paseoOnly,
|
|
2957
|
+
},
|
|
2958
|
+
responseType: "stash_list_response",
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
2961
|
+
async getPaseoWorktreeList(input, requestId) {
|
|
2962
|
+
return this.sendCorrelatedSessionRequest({
|
|
2963
|
+
requestId,
|
|
2964
|
+
message: {
|
|
2965
|
+
type: "paseo_worktree_list_request",
|
|
2966
|
+
cwd: input.cwd,
|
|
2967
|
+
repoRoot: input.repoRoot,
|
|
2968
|
+
},
|
|
2969
|
+
responseType: "paseo_worktree_list_response",
|
|
2970
|
+
});
|
|
2971
|
+
}
|
|
2972
|
+
async archivePaseoWorktree(input, requestId) {
|
|
2973
|
+
return this.sendCorrelatedSessionRequest({
|
|
2974
|
+
requestId,
|
|
2975
|
+
message: {
|
|
2976
|
+
type: "paseo_worktree_archive_request",
|
|
2977
|
+
worktreePath: input.worktreePath,
|
|
2978
|
+
repoRoot: input.repoRoot,
|
|
2979
|
+
branchName: input.branchName,
|
|
2980
|
+
...(input.workspaceId !== undefined ? { workspaceId: input.workspaceId } : {}),
|
|
2981
|
+
...(input.scope !== undefined ? { scope: input.scope } : {}),
|
|
2982
|
+
},
|
|
2983
|
+
responseType: "paseo_worktree_archive_response",
|
|
2984
|
+
});
|
|
2985
|
+
}
|
|
2986
|
+
async createPaseoWorktree(input, requestId) {
|
|
2987
|
+
return this.sendCorrelatedSessionRequest({
|
|
2988
|
+
requestId,
|
|
2989
|
+
message: {
|
|
2990
|
+
type: "create_paseo_worktree_request",
|
|
2991
|
+
cwd: input.cwd,
|
|
2992
|
+
...(input.projectId !== undefined ? { projectId: input.projectId } : {}),
|
|
2993
|
+
worktreeSlug: input.worktreeSlug,
|
|
2994
|
+
...(input.firstAgentContext !== undefined
|
|
2995
|
+
? { firstAgentContext: input.firstAgentContext }
|
|
2996
|
+
: {}),
|
|
2997
|
+
...(input.refName !== undefined ? { refName: input.refName } : {}),
|
|
2998
|
+
...(input.action !== undefined ? { action: input.action } : {}),
|
|
2999
|
+
...(input.checkoutSource !== undefined ? { checkoutSource: input.checkoutSource } : {}),
|
|
3000
|
+
...(input.githubPrNumber !== undefined ? { githubPrNumber: input.githubPrNumber } : {}),
|
|
3001
|
+
},
|
|
3002
|
+
responseType: "create_paseo_worktree_response",
|
|
3003
|
+
});
|
|
3004
|
+
}
|
|
3005
|
+
async createWorkspace(input, requestId) {
|
|
3006
|
+
const resolvedRequestId = this.createRequestId(requestId ?? input.requestId);
|
|
3007
|
+
const result = await this.creations.createWorkspace({
|
|
3008
|
+
...input,
|
|
3009
|
+
requestId: resolvedRequestId,
|
|
3010
|
+
...(input.agent
|
|
3011
|
+
? { agent: { ...input.agent, config: resolveAgentConfig(input.agent) } }
|
|
3012
|
+
: {}),
|
|
3013
|
+
});
|
|
3014
|
+
return {
|
|
3015
|
+
...result,
|
|
3016
|
+
workspace: result.workspace ?? null,
|
|
3017
|
+
agent: result.agent ?? undefined,
|
|
3018
|
+
setupTerminalId: result.setupTerminalId ?? null,
|
|
3019
|
+
requestId: result.requestId ?? resolvedRequestId,
|
|
3020
|
+
};
|
|
3021
|
+
}
|
|
3022
|
+
async createLegacyWorkspace(input, requestId) {
|
|
3023
|
+
// COMPAT(workspaceRequestReceipts): added in v0.8.0; remove gate after 2027-03-07.
|
|
3024
|
+
if (input.idempotencyKey !== undefined &&
|
|
3025
|
+
!this.lastServerInfoMessage?.features?.workspaceRequestReceipts) {
|
|
3026
|
+
throw new Error("Update the host to use retry-safe workspace creation.");
|
|
3027
|
+
}
|
|
3028
|
+
return this.sendCorrelatedSessionRequest({
|
|
3029
|
+
requestId,
|
|
3030
|
+
message: {
|
|
3031
|
+
type: "workspace.create.request",
|
|
3032
|
+
source: input.source,
|
|
3033
|
+
...(input.idempotencyKey !== undefined ? { idempotencyKey: input.idempotencyKey } : {}),
|
|
3034
|
+
...(input.title !== undefined ? { title: input.title } : {}),
|
|
3035
|
+
...(input.firstAgentContext !== undefined
|
|
3036
|
+
? { firstAgentContext: input.firstAgentContext }
|
|
3037
|
+
: {}),
|
|
3038
|
+
},
|
|
3039
|
+
responseType: "workspace.create.response",
|
|
3040
|
+
});
|
|
3041
|
+
}
|
|
3042
|
+
async validateBranch(options, requestId) {
|
|
3043
|
+
return this.sendCorrelatedSessionRequest({
|
|
3044
|
+
requestId,
|
|
3045
|
+
message: {
|
|
3046
|
+
type: "validate_branch_request",
|
|
3047
|
+
cwd: options.cwd,
|
|
3048
|
+
branchName: options.branchName,
|
|
3049
|
+
},
|
|
3050
|
+
responseType: "validate_branch_response",
|
|
3051
|
+
});
|
|
3052
|
+
}
|
|
3053
|
+
async getBranchSuggestions(options, requestId) {
|
|
3054
|
+
return this.sendCorrelatedSessionRequest({
|
|
3055
|
+
requestId,
|
|
3056
|
+
message: {
|
|
3057
|
+
type: "branch_suggestions_request",
|
|
3058
|
+
cwd: options.cwd,
|
|
3059
|
+
query: options.query,
|
|
3060
|
+
limit: options.limit,
|
|
3061
|
+
},
|
|
3062
|
+
responseType: "branch_suggestions_response",
|
|
3063
|
+
});
|
|
3064
|
+
}
|
|
3065
|
+
async searchForge(options, requestId) {
|
|
3066
|
+
return this.sendCorrelatedSessionRequest({
|
|
3067
|
+
requestId,
|
|
3068
|
+
message: {
|
|
3069
|
+
type: "forge.search.request",
|
|
3070
|
+
cwd: options.cwd,
|
|
3071
|
+
query: options.query,
|
|
3072
|
+
limit: options.limit,
|
|
3073
|
+
kinds: options.kinds,
|
|
3074
|
+
},
|
|
3075
|
+
responseType: "forge.search.response",
|
|
3076
|
+
timeout: 15000,
|
|
3077
|
+
});
|
|
3078
|
+
}
|
|
3079
|
+
async searchGitHub(options, requestId) {
|
|
3080
|
+
return this.sendCorrelatedSessionRequest({
|
|
3081
|
+
requestId,
|
|
3082
|
+
message: {
|
|
3083
|
+
type: "github_search_request",
|
|
3084
|
+
cwd: options.cwd,
|
|
3085
|
+
query: options.query,
|
|
3086
|
+
limit: options.limit,
|
|
3087
|
+
kinds: options.kinds,
|
|
3088
|
+
},
|
|
3089
|
+
responseType: "github_search_response",
|
|
3090
|
+
});
|
|
3091
|
+
}
|
|
3092
|
+
async getDirectorySuggestions(options, requestId) {
|
|
3093
|
+
return this.sendCorrelatedSessionRequest({
|
|
3094
|
+
requestId,
|
|
3095
|
+
message: {
|
|
3096
|
+
type: "directory_suggestions_request",
|
|
3097
|
+
query: options.query,
|
|
3098
|
+
cwd: options.cwd,
|
|
3099
|
+
includeFiles: options.includeFiles,
|
|
3100
|
+
includeDirectories: options.includeDirectories,
|
|
3101
|
+
matchMode: options.matchMode,
|
|
3102
|
+
limit: options.limit,
|
|
3103
|
+
},
|
|
3104
|
+
responseType: "directory_suggestions_response",
|
|
3105
|
+
// Home-tree scans on large home dirs can take several seconds; don't cut
|
|
3106
|
+
// the suggestion request off early (it would surface as an empty list).
|
|
3107
|
+
});
|
|
3108
|
+
}
|
|
3109
|
+
// ============================================================================
|
|
3110
|
+
// File Explorer
|
|
3111
|
+
// ============================================================================
|
|
3112
|
+
async requestFileExplorer(cwd, path, mode, requestId, acceptBinary = false, maxBytes) {
|
|
3113
|
+
return this.sendCorrelatedSessionRequest({
|
|
3114
|
+
requestId,
|
|
3115
|
+
message: {
|
|
3116
|
+
type: "file_explorer_request",
|
|
3117
|
+
cwd,
|
|
3118
|
+
path,
|
|
3119
|
+
mode,
|
|
3120
|
+
...(acceptBinary ? { acceptBinary: true } : {}),
|
|
3121
|
+
...(maxBytes ? { maxBytes } : {}),
|
|
3122
|
+
},
|
|
3123
|
+
responseType: "file_explorer_response",
|
|
3124
|
+
});
|
|
3125
|
+
}
|
|
3126
|
+
async listDirectory(cwd, path, requestId) {
|
|
3127
|
+
const payload = await this.requestFileExplorer(cwd, path, "list", requestId);
|
|
3128
|
+
if (payload.error) {
|
|
3129
|
+
throw new Error(payload.error);
|
|
3130
|
+
}
|
|
3131
|
+
if (!payload.directory) {
|
|
3132
|
+
throw new Error("Directory listing unavailable.");
|
|
3133
|
+
}
|
|
3134
|
+
return payload.directory;
|
|
3135
|
+
}
|
|
3136
|
+
async readFile(cwd, path, requestId, maxBytes) {
|
|
3137
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3138
|
+
this.pendingBinaryFileReads.set(resolvedRequestId, { cwd, path, maxBytes });
|
|
3139
|
+
try {
|
|
3140
|
+
const payload = await this.requestFileExplorer(cwd, path, "file", resolvedRequestId, true, maxBytes);
|
|
3141
|
+
if (payload.error) {
|
|
3142
|
+
throw new Error(payload.error);
|
|
3143
|
+
}
|
|
3144
|
+
const binaryResult = this.completedBinaryFileReads.get(resolvedRequestId);
|
|
3145
|
+
if (binaryResult) {
|
|
3146
|
+
this.completedBinaryFileReads.delete(resolvedRequestId);
|
|
3147
|
+
return binaryResult;
|
|
3148
|
+
}
|
|
3149
|
+
if (!payload.file) {
|
|
3150
|
+
throw new Error("File unavailable.");
|
|
3151
|
+
}
|
|
3152
|
+
return legacyExplorerFileToBytes(payload.file);
|
|
3153
|
+
}
|
|
3154
|
+
finally {
|
|
3155
|
+
this.pendingBinaryFileReads.delete(resolvedRequestId);
|
|
3156
|
+
this.activeBinaryFileTransfers.delete(resolvedRequestId);
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
async subscribeFile(input, onUpdate) {
|
|
3160
|
+
const subscriptionId = this.createRequestId();
|
|
3161
|
+
this.fileSubscriptions.set(subscriptionId, { ...input, onUpdate });
|
|
3162
|
+
try {
|
|
3163
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3164
|
+
message: {
|
|
3165
|
+
type: "fs.file.subscribe.request",
|
|
3166
|
+
cwd: input.cwd,
|
|
3167
|
+
path: input.path,
|
|
3168
|
+
subscriptionId,
|
|
3169
|
+
},
|
|
3170
|
+
responseType: "fs.file.subscribe.response",
|
|
3171
|
+
});
|
|
3172
|
+
return {
|
|
3173
|
+
initial: payload.initial,
|
|
3174
|
+
unsubscribe: () => {
|
|
3175
|
+
if (!this.fileSubscriptions.delete(subscriptionId))
|
|
3176
|
+
return;
|
|
3177
|
+
void this.sendCorrelatedSessionRequest({
|
|
3178
|
+
message: { type: "fs.file.unsubscribe.request", subscriptionId },
|
|
3179
|
+
responseType: "fs.file.unsubscribe.response",
|
|
3180
|
+
}).catch(() => undefined);
|
|
3181
|
+
},
|
|
3182
|
+
};
|
|
3183
|
+
}
|
|
3184
|
+
catch (error) {
|
|
3185
|
+
this.fileSubscriptions.delete(subscriptionId);
|
|
3186
|
+
throw error;
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
async writeFile(input) {
|
|
3190
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3191
|
+
message: { type: "fs.file.write.request", ...input },
|
|
3192
|
+
responseType: "fs.file.write.response",
|
|
3193
|
+
});
|
|
3194
|
+
return payload.result;
|
|
3195
|
+
}
|
|
3196
|
+
async createFileEntry(input) {
|
|
3197
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3198
|
+
message: { type: "fs.entry.create.request", ...input },
|
|
3199
|
+
});
|
|
3200
|
+
}
|
|
3201
|
+
async renameFileEntry(input) {
|
|
3202
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3203
|
+
message: { type: "fs.entry.rename.request", ...input },
|
|
3204
|
+
});
|
|
3205
|
+
}
|
|
3206
|
+
async duplicateFileEntry(input) {
|
|
3207
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3208
|
+
message: { type: "fs.entry.duplicate.request", ...input },
|
|
3209
|
+
});
|
|
3210
|
+
}
|
|
3211
|
+
async deleteFileEntry(input) {
|
|
3212
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3213
|
+
message: { type: "fs.entry.delete.request", ...input },
|
|
3214
|
+
});
|
|
3215
|
+
}
|
|
3216
|
+
async checkoutDiscardChanges(cwd, input) {
|
|
3217
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3218
|
+
message: { type: "checkout.discard_changes.request", cwd, paths: input.paths },
|
|
3219
|
+
});
|
|
3220
|
+
}
|
|
3221
|
+
async uploadFile(input) {
|
|
3222
|
+
const bytes = asUint8Array(input.bytes);
|
|
3223
|
+
if (!bytes) {
|
|
3224
|
+
throw new Error("File bytes are required.");
|
|
3225
|
+
}
|
|
3226
|
+
const resolvedRequestId = this.createRequestId(input.requestId);
|
|
3227
|
+
const modifiedAt = input.modifiedAt ?? new Date().toISOString();
|
|
3228
|
+
const responsePromise = this.sendCorrelatedRequest({
|
|
3229
|
+
requestId: resolvedRequestId,
|
|
3230
|
+
message: {
|
|
3231
|
+
type: "file.upload.request",
|
|
3232
|
+
fileName: input.fileName,
|
|
3233
|
+
mimeType: input.mimeType,
|
|
3234
|
+
size: bytes.byteLength,
|
|
3235
|
+
modifiedAt,
|
|
3236
|
+
requestId: resolvedRequestId,
|
|
3237
|
+
},
|
|
3238
|
+
responseType: "file.upload.response",
|
|
3239
|
+
options: { skipQueue: true },
|
|
3240
|
+
});
|
|
3241
|
+
this.sendBinaryFrame(encodeFileTransferFrame({
|
|
3242
|
+
opcode: FileTransferOpcode.FileBegin,
|
|
3243
|
+
requestId: resolvedRequestId,
|
|
3244
|
+
metadata: {
|
|
3245
|
+
mime: input.mimeType,
|
|
3246
|
+
size: bytes.byteLength,
|
|
3247
|
+
encoding: "binary",
|
|
3248
|
+
modifiedAt,
|
|
3249
|
+
fileName: input.fileName,
|
|
3250
|
+
},
|
|
3251
|
+
}));
|
|
3252
|
+
const chunkSize = input.chunkSize ?? 1024 * 1024;
|
|
3253
|
+
for (let offset = 0; offset < bytes.byteLength; offset += chunkSize) {
|
|
3254
|
+
this.sendBinaryFrame(encodeFileTransferFrame({
|
|
3255
|
+
opcode: FileTransferOpcode.FileChunk,
|
|
3256
|
+
requestId: resolvedRequestId,
|
|
3257
|
+
payload: bytes.subarray(offset, Math.min(offset + chunkSize, bytes.byteLength)),
|
|
3258
|
+
}));
|
|
3259
|
+
}
|
|
3260
|
+
this.sendBinaryFrame(encodeFileTransferFrame({
|
|
3261
|
+
opcode: FileTransferOpcode.FileEnd,
|
|
3262
|
+
requestId: resolvedRequestId,
|
|
3263
|
+
}));
|
|
3264
|
+
return responsePromise;
|
|
3265
|
+
}
|
|
3266
|
+
async requestDownloadToken(cwd, path, requestId) {
|
|
3267
|
+
return this.sendCorrelatedSessionRequest({
|
|
3268
|
+
requestId,
|
|
3269
|
+
message: {
|
|
3270
|
+
type: "file_download_token_request",
|
|
3271
|
+
cwd,
|
|
3272
|
+
path,
|
|
3273
|
+
},
|
|
3274
|
+
responseType: "file_download_token_response",
|
|
3275
|
+
});
|
|
3276
|
+
}
|
|
3277
|
+
async requestProjectIcon(cwd, requestId) {
|
|
3278
|
+
return this.sendCorrelatedSessionRequest({
|
|
3279
|
+
requestId,
|
|
3280
|
+
message: {
|
|
3281
|
+
type: "project_icon_request",
|
|
3282
|
+
cwd,
|
|
3283
|
+
},
|
|
3284
|
+
responseType: "project_icon_response",
|
|
3285
|
+
});
|
|
3286
|
+
}
|
|
3287
|
+
async getProjectIcon(projectId, requestId) {
|
|
3288
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3289
|
+
requestId,
|
|
3290
|
+
message: { type: "project.icon.get.request", projectId },
|
|
3291
|
+
});
|
|
3292
|
+
}
|
|
3293
|
+
// ============================================================================
|
|
3294
|
+
// Provider Models / Commands
|
|
3295
|
+
// ============================================================================
|
|
3296
|
+
async listProviderModels(provider, options) {
|
|
3297
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3298
|
+
requestId: options?.requestId,
|
|
3299
|
+
message: {
|
|
3300
|
+
type: "list_provider_models_request",
|
|
3301
|
+
provider,
|
|
3302
|
+
cwd: options?.cwd,
|
|
3303
|
+
},
|
|
3304
|
+
responseType: "list_provider_models_response",
|
|
3305
|
+
// Provider SDK cold starts (especially model discovery) can exceed 60s.
|
|
3306
|
+
timeout: 90000,
|
|
3307
|
+
});
|
|
3308
|
+
return normalizeListProviderModelsPayload(payload);
|
|
3309
|
+
}
|
|
3310
|
+
async listProviderModes(provider, options) {
|
|
3311
|
+
return this.sendCorrelatedSessionRequest({
|
|
3312
|
+
requestId: options?.requestId,
|
|
3313
|
+
message: {
|
|
3314
|
+
type: "list_provider_modes_request",
|
|
3315
|
+
provider,
|
|
3316
|
+
cwd: options?.cwd,
|
|
3317
|
+
},
|
|
3318
|
+
responseType: "list_provider_modes_response",
|
|
3319
|
+
timeout: 90000,
|
|
3320
|
+
});
|
|
3321
|
+
}
|
|
3322
|
+
async listProviderFeatures(draftConfig, options) {
|
|
3323
|
+
return this.sendCorrelatedSessionRequest({
|
|
3324
|
+
requestId: options?.requestId,
|
|
3325
|
+
message: {
|
|
3326
|
+
type: "list_provider_features_request",
|
|
3327
|
+
draftConfig,
|
|
3328
|
+
},
|
|
3329
|
+
responseType: "list_provider_features_response",
|
|
3330
|
+
timeout: 90000,
|
|
3331
|
+
});
|
|
3332
|
+
}
|
|
3333
|
+
async listAvailableProviders(options) {
|
|
3334
|
+
return this.sendCorrelatedSessionRequest({
|
|
3335
|
+
requestId: options?.requestId,
|
|
3336
|
+
message: {
|
|
3337
|
+
type: "list_available_providers_request",
|
|
3338
|
+
},
|
|
3339
|
+
responseType: "list_available_providers_response",
|
|
3340
|
+
});
|
|
3341
|
+
}
|
|
3342
|
+
async getProvidersSnapshot(options) {
|
|
3343
|
+
const payload = await this.requestProvidersSnapshot(options);
|
|
3344
|
+
return normalizeProvidersSnapshotPayload(payload, this.config.providerSnapshots !== "wire");
|
|
3345
|
+
}
|
|
3346
|
+
requestProvidersSnapshot(options) {
|
|
3347
|
+
return this.sendCorrelatedSessionRequest({
|
|
3348
|
+
requestId: options?.requestId,
|
|
3349
|
+
message: {
|
|
3350
|
+
type: "get_providers_snapshot_request",
|
|
3351
|
+
cwd: options?.cwd,
|
|
3352
|
+
ifNoneMatch: options?.ifNoneMatch,
|
|
3353
|
+
},
|
|
3354
|
+
responseType: "get_providers_snapshot_response",
|
|
3355
|
+
});
|
|
3356
|
+
}
|
|
3357
|
+
async getDaemonConfig(requestId) {
|
|
3358
|
+
return this.sendCorrelatedSessionRequest({
|
|
3359
|
+
requestId,
|
|
3360
|
+
message: {
|
|
3361
|
+
type: "get_daemon_config_request",
|
|
3362
|
+
},
|
|
3363
|
+
responseType: "get_daemon_config_response",
|
|
3364
|
+
});
|
|
3365
|
+
}
|
|
3366
|
+
async getDaemonStatus(options) {
|
|
3367
|
+
return this.sendCorrelatedSessionRequest({
|
|
3368
|
+
requestId: options?.requestId,
|
|
3369
|
+
message: {
|
|
3370
|
+
type: "daemon.get_status.request",
|
|
3371
|
+
},
|
|
3372
|
+
responseType: "daemon.get_status.response",
|
|
3373
|
+
timeout: options?.timeout,
|
|
3374
|
+
});
|
|
3375
|
+
}
|
|
3376
|
+
async reloadDaemonConfig(requestId) {
|
|
3377
|
+
this.requireDaemonConfigReloadSupport();
|
|
3378
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3379
|
+
requestId,
|
|
3380
|
+
message: { type: "daemon.config.reload.request" },
|
|
3381
|
+
});
|
|
3382
|
+
}
|
|
3383
|
+
async connectHub(hubUrl, token, permissions = [], requestId) {
|
|
3384
|
+
this.requireHubRelationshipSupport();
|
|
3385
|
+
return this.sendCorrelatedSessionRequest({
|
|
3386
|
+
requestId,
|
|
3387
|
+
message: { type: "hub.management.daemon.connect.request", hubUrl, token, permissions },
|
|
3388
|
+
responseType: "hub.management.daemon.connect.response",
|
|
3389
|
+
});
|
|
3390
|
+
}
|
|
3391
|
+
async updateHubPermissions(input, requestId) {
|
|
3392
|
+
this.requireHubRelationshipSupport();
|
|
3393
|
+
return this.sendCorrelatedSessionRequest({
|
|
3394
|
+
requestId,
|
|
3395
|
+
message: {
|
|
3396
|
+
type: "hub.management.daemon.permissions.update.request",
|
|
3397
|
+
grant: input.grant ?? [],
|
|
3398
|
+
revoke: input.revoke ?? [],
|
|
3399
|
+
},
|
|
3400
|
+
responseType: "hub.management.daemon.permissions.update.response",
|
|
3401
|
+
});
|
|
3402
|
+
}
|
|
3403
|
+
async getHubStatus(requestId) {
|
|
3404
|
+
this.requireHubRelationshipSupport();
|
|
3405
|
+
return this.sendCorrelatedSessionRequest({
|
|
3406
|
+
requestId,
|
|
3407
|
+
message: { type: "hub.management.daemon.get_status.request" },
|
|
3408
|
+
responseType: "hub.management.daemon.get_status.response",
|
|
3409
|
+
});
|
|
3410
|
+
}
|
|
3411
|
+
async disconnectHub(force = false, requestId) {
|
|
3412
|
+
this.requireHubRelationshipSupport();
|
|
3413
|
+
return this.sendCorrelatedSessionRequest({
|
|
3414
|
+
requestId,
|
|
3415
|
+
message: { type: "hub.management.daemon.disconnect.request", force },
|
|
3416
|
+
responseType: "hub.management.daemon.disconnect.response",
|
|
3417
|
+
});
|
|
3418
|
+
}
|
|
3419
|
+
async getDaemonPairingOffer(options) {
|
|
3420
|
+
return this.sendCorrelatedSessionRequest({
|
|
3421
|
+
requestId: options?.requestId,
|
|
3422
|
+
message: {
|
|
3423
|
+
type: "daemon.get_pairing_offer.request",
|
|
3424
|
+
},
|
|
3425
|
+
responseType: "daemon.get_pairing_offer.response",
|
|
3426
|
+
timeout: options?.timeout,
|
|
3427
|
+
});
|
|
3428
|
+
}
|
|
3429
|
+
async collectDiagnostics(requestId) {
|
|
3430
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3431
|
+
requestId,
|
|
3432
|
+
message: {
|
|
3433
|
+
type: "diagnostics.request",
|
|
3434
|
+
},
|
|
3435
|
+
});
|
|
3436
|
+
}
|
|
3437
|
+
async patchDaemonConfig(config, requestId) {
|
|
3438
|
+
return this.sendCorrelatedSessionRequest({
|
|
3439
|
+
requestId,
|
|
3440
|
+
message: {
|
|
3441
|
+
type: "set_daemon_config_request",
|
|
3442
|
+
config,
|
|
3443
|
+
},
|
|
3444
|
+
responseType: "set_daemon_config_response",
|
|
3445
|
+
});
|
|
3446
|
+
}
|
|
3447
|
+
sendBrowserAutomationExecuteResponse(response) {
|
|
3448
|
+
this.sendSessionMessageStrict(response);
|
|
3449
|
+
}
|
|
3450
|
+
async readProjectConfig(repoRoot, requestId) {
|
|
3451
|
+
return this.sendCorrelatedSessionRequest({
|
|
3452
|
+
requestId,
|
|
3453
|
+
message: {
|
|
3454
|
+
type: "read_project_config_request",
|
|
3455
|
+
repoRoot,
|
|
3456
|
+
},
|
|
3457
|
+
responseType: "read_project_config_response",
|
|
3458
|
+
});
|
|
3459
|
+
}
|
|
3460
|
+
async writeProjectConfig(input) {
|
|
3461
|
+
return this.sendCorrelatedSessionRequest({
|
|
3462
|
+
requestId: input.requestId,
|
|
3463
|
+
message: {
|
|
3464
|
+
type: "write_project_config_request",
|
|
3465
|
+
repoRoot: input.repoRoot,
|
|
3466
|
+
config: input.config,
|
|
3467
|
+
expectedRevision: input.expectedRevision,
|
|
3468
|
+
},
|
|
3469
|
+
responseType: "write_project_config_response",
|
|
3470
|
+
});
|
|
3471
|
+
}
|
|
3472
|
+
async refreshProvidersSnapshot(options) {
|
|
3473
|
+
return this.sendCorrelatedSessionRequest({
|
|
3474
|
+
requestId: options?.requestId,
|
|
3475
|
+
message: {
|
|
3476
|
+
type: "refresh_providers_snapshot_request",
|
|
3477
|
+
cwd: options?.cwd,
|
|
3478
|
+
providers: options?.providers,
|
|
3479
|
+
},
|
|
3480
|
+
responseType: "refresh_providers_snapshot_response",
|
|
3481
|
+
timeout: 120000,
|
|
3482
|
+
});
|
|
3483
|
+
}
|
|
3484
|
+
async getProviderDiagnostic(provider, options) {
|
|
3485
|
+
return this.sendCorrelatedSessionRequest({
|
|
3486
|
+
requestId: options?.requestId,
|
|
3487
|
+
message: {
|
|
3488
|
+
type: "provider_diagnostic_request",
|
|
3489
|
+
provider,
|
|
3490
|
+
},
|
|
3491
|
+
responseType: "provider_diagnostic_response",
|
|
3492
|
+
timeout: 180000,
|
|
3493
|
+
});
|
|
3494
|
+
}
|
|
3495
|
+
async listProviderUsage(options) {
|
|
3496
|
+
return this.sendNamespacedCorrelatedSessionRequest({
|
|
3497
|
+
requestId: options?.requestId,
|
|
3498
|
+
message: {
|
|
3499
|
+
type: "provider.usage.list.request",
|
|
3500
|
+
},
|
|
3501
|
+
});
|
|
3502
|
+
}
|
|
3503
|
+
async listCommands(input, legacyOptions) {
|
|
3504
|
+
const options = normalizeListCommandsOptions(input, legacyOptions);
|
|
3505
|
+
return this.sendCorrelatedSessionRequest({
|
|
3506
|
+
requestId: options.requestId,
|
|
3507
|
+
message: {
|
|
3508
|
+
type: "list_commands_request",
|
|
3509
|
+
agentId: options.agentId,
|
|
3510
|
+
...(options.draftConfig ? { draftConfig: options.draftConfig } : {}),
|
|
3511
|
+
},
|
|
3512
|
+
responseType: "list_commands_response",
|
|
3513
|
+
});
|
|
3514
|
+
}
|
|
3515
|
+
// ============================================================================
|
|
3516
|
+
// Permissions
|
|
3517
|
+
// ============================================================================
|
|
3518
|
+
async respondToPermission(agentId, requestId, response) {
|
|
3519
|
+
this.sendSessionMessage({
|
|
3520
|
+
type: "agent_permission_response",
|
|
3521
|
+
agentId,
|
|
3522
|
+
requestId,
|
|
3523
|
+
response,
|
|
3524
|
+
});
|
|
3525
|
+
}
|
|
3526
|
+
async getPluginCatalog() {
|
|
3527
|
+
const requestId = this.createRequestId();
|
|
3528
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3529
|
+
requestId,
|
|
3530
|
+
message: { type: "plugin.catalog.get.request", requestId },
|
|
3531
|
+
responseType: "plugin.catalog.get.response",
|
|
3532
|
+
});
|
|
3533
|
+
return payload.plugins;
|
|
3534
|
+
}
|
|
3535
|
+
async listPlugins() {
|
|
3536
|
+
const requestId = this.createRequestId();
|
|
3537
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3538
|
+
requestId,
|
|
3539
|
+
message: { type: "plugin.list.request", requestId },
|
|
3540
|
+
responseType: "plugin.list.response",
|
|
3541
|
+
});
|
|
3542
|
+
return payload.plugins;
|
|
3543
|
+
}
|
|
3544
|
+
async getPluginLogs(pluginId) {
|
|
3545
|
+
const requestId = this.createRequestId();
|
|
3546
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3547
|
+
requestId,
|
|
3548
|
+
message: { type: "plugin.logs.get.request", requestId, pluginId },
|
|
3549
|
+
responseType: "plugin.logs.get.response",
|
|
3550
|
+
});
|
|
3551
|
+
return payload.entries;
|
|
3552
|
+
}
|
|
3553
|
+
async getAgentSkillsStatus() {
|
|
3554
|
+
const requestId = this.createRequestId();
|
|
3555
|
+
return this.sendCorrelatedSessionRequest({
|
|
3556
|
+
message: { type: "agent.skills.get_status.request", requestId },
|
|
3557
|
+
responseType: "agent.skills.get_status.response",
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
async reconcileAgentSkills() {
|
|
3561
|
+
const requestId = this.createRequestId();
|
|
3562
|
+
return this.sendCorrelatedSessionRequest({
|
|
3563
|
+
message: { type: "agent.skills.reconcile.request", requestId },
|
|
3564
|
+
responseType: "agent.skills.reconcile.response",
|
|
3565
|
+
});
|
|
3566
|
+
}
|
|
3567
|
+
async uninstallAgentSkills() {
|
|
3568
|
+
const requestId = this.createRequestId();
|
|
3569
|
+
return this.sendCorrelatedSessionRequest({
|
|
3570
|
+
message: { type: "agent.skills.uninstall.request", requestId },
|
|
3571
|
+
responseType: "agent.skills.uninstall.response",
|
|
3572
|
+
});
|
|
3573
|
+
}
|
|
3574
|
+
async saveAgentSkillsSelection(selection, confirmedRemovals) {
|
|
3575
|
+
const requestId = this.createRequestId();
|
|
3576
|
+
return this.sendCorrelatedSessionRequest({
|
|
3577
|
+
message: {
|
|
3578
|
+
type: "agent.skills.save_selection.request",
|
|
3579
|
+
requestId,
|
|
3580
|
+
selection,
|
|
3581
|
+
...(confirmedRemovals ? { confirmedRemovals: [...confirmedRemovals] } : {}),
|
|
3582
|
+
},
|
|
3583
|
+
responseType: "agent.skills.save_selection.response",
|
|
3584
|
+
});
|
|
3585
|
+
}
|
|
3586
|
+
async importLegacyAgentSkillsSelection(selection) {
|
|
3587
|
+
const requestId = this.createRequestId();
|
|
3588
|
+
return this.sendCorrelatedSessionRequest({
|
|
3589
|
+
message: {
|
|
3590
|
+
type: "agent.skills.import_legacy_selection.request",
|
|
3591
|
+
requestId,
|
|
3592
|
+
selection,
|
|
3593
|
+
},
|
|
3594
|
+
responseType: "agent.skills.import_legacy_selection.response",
|
|
3595
|
+
});
|
|
3596
|
+
}
|
|
3597
|
+
async installDirectoryPlugin(path, id) {
|
|
3598
|
+
const requestId = this.createRequestId();
|
|
3599
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3600
|
+
requestId,
|
|
3601
|
+
message: { type: "plugin.directory.install.request", requestId, path, ...(id ? { id } : {}) },
|
|
3602
|
+
responseType: "plugin.directory.install.response",
|
|
3603
|
+
});
|
|
3604
|
+
return payload.plugin;
|
|
3605
|
+
}
|
|
3606
|
+
async installPluginSource(input) {
|
|
3607
|
+
const requestId = this.createRequestId();
|
|
3608
|
+
const reference = parsePluginSourceReference(input.source);
|
|
3609
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3610
|
+
requestId,
|
|
3611
|
+
message: {
|
|
3612
|
+
type: "plugin.source.install.request",
|
|
3613
|
+
requestId,
|
|
3614
|
+
source: reference.source,
|
|
3615
|
+
...(reference.pluginPath ? { pluginPath: reference.pluginPath } : {}),
|
|
3616
|
+
...(input.id ? { id: input.id } : {}),
|
|
3617
|
+
...(input.ref ? { ref: input.ref } : {}),
|
|
3618
|
+
},
|
|
3619
|
+
responseType: "plugin.source.install.response",
|
|
3620
|
+
});
|
|
3621
|
+
return payload.plugin;
|
|
3622
|
+
}
|
|
3623
|
+
async getPluginSourceStatus(pluginId) {
|
|
3624
|
+
const requestId = this.createRequestId();
|
|
3625
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3626
|
+
requestId,
|
|
3627
|
+
message: {
|
|
3628
|
+
type: "plugin.source.status.request",
|
|
3629
|
+
requestId,
|
|
3630
|
+
...(pluginId ? { pluginId } : {}),
|
|
3631
|
+
},
|
|
3632
|
+
responseType: "plugin.source.status.response",
|
|
3633
|
+
});
|
|
3634
|
+
return payload.plugins;
|
|
3635
|
+
}
|
|
3636
|
+
async updatePluginSources(pluginId) {
|
|
3637
|
+
const requestId = this.createRequestId();
|
|
3638
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3639
|
+
requestId,
|
|
3640
|
+
message: {
|
|
3641
|
+
type: "plugin.source.update.request",
|
|
3642
|
+
requestId,
|
|
3643
|
+
...(pluginId ? { pluginId } : {}),
|
|
3644
|
+
},
|
|
3645
|
+
responseType: "plugin.source.update.response",
|
|
3646
|
+
});
|
|
3647
|
+
return payload.plugins;
|
|
3648
|
+
}
|
|
3649
|
+
async inspectDirectoryPlugin(path) {
|
|
3650
|
+
const requestId = this.createRequestId();
|
|
3651
|
+
return this.sendCorrelatedSessionRequest({
|
|
3652
|
+
requestId,
|
|
3653
|
+
message: { type: "plugin.directory.inspect.request", requestId, path },
|
|
3654
|
+
responseType: "plugin.directory.inspect.response",
|
|
3655
|
+
});
|
|
3656
|
+
}
|
|
3657
|
+
async reloadPlugin(pluginId) {
|
|
3658
|
+
return this.managePlugin("reload", pluginId);
|
|
3659
|
+
}
|
|
3660
|
+
async enablePlugin(pluginId) {
|
|
3661
|
+
return this.managePlugin("enable", pluginId);
|
|
3662
|
+
}
|
|
3663
|
+
async disablePlugin(pluginId) {
|
|
3664
|
+
return this.managePlugin("disable", pluginId);
|
|
3665
|
+
}
|
|
3666
|
+
async removePlugin(pluginId) {
|
|
3667
|
+
const requestId = this.createRequestId();
|
|
3668
|
+
await this.sendCorrelatedSessionRequest({
|
|
3669
|
+
requestId,
|
|
3670
|
+
message: { type: "plugin.remove.request", requestId, pluginId },
|
|
3671
|
+
responseType: "plugin.remove.response",
|
|
3672
|
+
});
|
|
3673
|
+
}
|
|
3674
|
+
async managePlugin(action, pluginId) {
|
|
3675
|
+
const requestId = this.createRequestId();
|
|
3676
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3677
|
+
requestId,
|
|
3678
|
+
message: { type: `plugin.${action}.request`, requestId, pluginId },
|
|
3679
|
+
responseType: `plugin.${action}.response`,
|
|
3680
|
+
});
|
|
3681
|
+
return payload.plugin;
|
|
3682
|
+
}
|
|
3683
|
+
async invokePluginRpc(pluginId, method, input) {
|
|
3684
|
+
const requestId = this.createRequestId();
|
|
3685
|
+
const payload = await this.sendCorrelatedSessionRequest({
|
|
3686
|
+
requestId,
|
|
3687
|
+
message: {
|
|
3688
|
+
type: "plugin.rpc.invoke.request",
|
|
3689
|
+
requestId,
|
|
3690
|
+
pluginId,
|
|
3691
|
+
method,
|
|
3692
|
+
input,
|
|
3693
|
+
},
|
|
3694
|
+
responseType: "plugin.rpc.invoke.response",
|
|
3695
|
+
});
|
|
3696
|
+
return payload.output;
|
|
3697
|
+
}
|
|
3698
|
+
async respondToPermissionAndWait(agentId, requestId, response, timeout = 15000) {
|
|
3699
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3700
|
+
type: "agent_permission_response",
|
|
3701
|
+
agentId,
|
|
3702
|
+
requestId,
|
|
3703
|
+
response,
|
|
3704
|
+
});
|
|
3705
|
+
return this.sendRequest({
|
|
3706
|
+
requestId,
|
|
3707
|
+
message,
|
|
3708
|
+
timeout,
|
|
3709
|
+
options: { skipQueue: true },
|
|
3710
|
+
select: (msg) => {
|
|
3711
|
+
if (msg.type !== "agent_permission_resolved") {
|
|
3712
|
+
return null;
|
|
3713
|
+
}
|
|
3714
|
+
if (msg.payload.requestId !== requestId) {
|
|
3715
|
+
return null;
|
|
3716
|
+
}
|
|
3717
|
+
if (msg.payload.agentId !== agentId) {
|
|
3718
|
+
return null;
|
|
3719
|
+
}
|
|
3720
|
+
return msg.payload;
|
|
3721
|
+
},
|
|
3722
|
+
});
|
|
3723
|
+
}
|
|
3724
|
+
// ============================================================================
|
|
3725
|
+
// Waiting / Streaming Helpers
|
|
3726
|
+
// ============================================================================
|
|
3727
|
+
async waitForAgentUpsert(agentId, predicate, timeout = 60000) {
|
|
3728
|
+
const deadline = Date.now() + timeout;
|
|
3729
|
+
const remainingTimeoutMs = () => Math.max(1, deadline - Date.now());
|
|
3730
|
+
const timeoutError = () => new Error(`Timed out waiting for agent ${agentId}`);
|
|
3731
|
+
const fetchAgentWithinDeadline = () => this.fetchAgent({ agentId, timeout: remainingTimeoutMs() }).catch(() => null);
|
|
3732
|
+
const initialResult = await fetchAgentWithinDeadline();
|
|
3733
|
+
if (initialResult && predicate(initialResult.agent)) {
|
|
3734
|
+
return initialResult.agent;
|
|
3735
|
+
}
|
|
3736
|
+
if (Date.now() >= deadline) {
|
|
3737
|
+
throw timeoutError();
|
|
3738
|
+
}
|
|
3739
|
+
return await new Promise((resolve, reject) => {
|
|
3740
|
+
let settled = false;
|
|
3741
|
+
let pollInFlight = false;
|
|
3742
|
+
let pollTimer = null;
|
|
3743
|
+
let timeoutTimer = null;
|
|
3744
|
+
let unsubscribe = null;
|
|
3745
|
+
const finish = (result) => {
|
|
3746
|
+
if (settled) {
|
|
3747
|
+
return;
|
|
3748
|
+
}
|
|
3749
|
+
settled = true;
|
|
3750
|
+
if (timeoutTimer) {
|
|
3751
|
+
clearTimeout(timeoutTimer);
|
|
3752
|
+
timeoutTimer = null;
|
|
3753
|
+
}
|
|
3754
|
+
if (pollTimer) {
|
|
3755
|
+
clearInterval(pollTimer);
|
|
3756
|
+
pollTimer = null;
|
|
3757
|
+
}
|
|
3758
|
+
if (unsubscribe) {
|
|
3759
|
+
unsubscribe();
|
|
3760
|
+
unsubscribe = null;
|
|
3761
|
+
}
|
|
3762
|
+
if (result.kind === "ok") {
|
|
3763
|
+
resolve(result.snapshot);
|
|
3764
|
+
return;
|
|
3765
|
+
}
|
|
3766
|
+
reject(result.error);
|
|
3767
|
+
};
|
|
3768
|
+
const maybeResolve = (snapshot) => {
|
|
3769
|
+
if (!snapshot) {
|
|
3770
|
+
return false;
|
|
3771
|
+
}
|
|
3772
|
+
if (!predicate(snapshot)) {
|
|
3773
|
+
return false;
|
|
3774
|
+
}
|
|
3775
|
+
finish({ kind: "ok", snapshot });
|
|
3776
|
+
return true;
|
|
3777
|
+
};
|
|
3778
|
+
const poll = async () => {
|
|
3779
|
+
if (settled || pollInFlight) {
|
|
3780
|
+
return;
|
|
3781
|
+
}
|
|
3782
|
+
pollInFlight = true;
|
|
3783
|
+
try {
|
|
3784
|
+
const result = await fetchAgentWithinDeadline();
|
|
3785
|
+
maybeResolve(result?.agent ?? null);
|
|
3786
|
+
}
|
|
3787
|
+
finally {
|
|
3788
|
+
pollInFlight = false;
|
|
3789
|
+
}
|
|
3790
|
+
};
|
|
3791
|
+
unsubscribe = this.on("agent_update", (message) => {
|
|
3792
|
+
if (settled) {
|
|
3793
|
+
return;
|
|
3794
|
+
}
|
|
3795
|
+
if (message.payload.kind !== "upsert") {
|
|
3796
|
+
return;
|
|
3797
|
+
}
|
|
3798
|
+
const snapshot = message.payload.agent;
|
|
3799
|
+
if (snapshot.id !== agentId) {
|
|
3800
|
+
return;
|
|
3801
|
+
}
|
|
3802
|
+
maybeResolve(snapshot);
|
|
3803
|
+
});
|
|
3804
|
+
const remaining = Math.max(1, deadline - Date.now());
|
|
3805
|
+
timeoutTimer = setTimeout(() => {
|
|
3806
|
+
finish({
|
|
3807
|
+
kind: "error",
|
|
3808
|
+
error: timeoutError(),
|
|
3809
|
+
});
|
|
3810
|
+
}, remaining);
|
|
3811
|
+
pollTimer = setInterval(() => {
|
|
3812
|
+
void poll();
|
|
3813
|
+
}, 250);
|
|
3814
|
+
void poll();
|
|
3815
|
+
});
|
|
3816
|
+
}
|
|
3817
|
+
async waitForFinish(agentId, timeout = 60000) {
|
|
3818
|
+
const requestId = this.createRequestId();
|
|
3819
|
+
const hasTimeout = Number.isFinite(timeout) && timeout > 0;
|
|
3820
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3821
|
+
type: "wait_for_finish_request",
|
|
3822
|
+
requestId,
|
|
3823
|
+
agentId,
|
|
3824
|
+
...(hasTimeout ? { timeoutMs: timeout } : {}),
|
|
3825
|
+
});
|
|
3826
|
+
const payload = await this.sendCorrelatedRequest({
|
|
3827
|
+
requestId,
|
|
3828
|
+
message,
|
|
3829
|
+
responseType: "wait_for_finish_response",
|
|
3830
|
+
timeout: hasTimeout ? timeout + 5000 : 0,
|
|
3831
|
+
options: { skipQueue: true },
|
|
3832
|
+
});
|
|
3833
|
+
return {
|
|
3834
|
+
status: payload.status,
|
|
3835
|
+
final: payload.final,
|
|
3836
|
+
error: payload.error,
|
|
3837
|
+
lastMessage: payload.lastMessage,
|
|
3838
|
+
};
|
|
3839
|
+
}
|
|
3840
|
+
// ============================================================================
|
|
3841
|
+
// Terminals
|
|
3842
|
+
// ============================================================================
|
|
3843
|
+
subscribeTerminals(input) {
|
|
3844
|
+
this.terminalDirectorySubscriptions.set(terminalSubscriptionKey(input.cwd, input.workspaceId), {
|
|
3845
|
+
cwd: input.cwd,
|
|
3846
|
+
workspaceId: input.workspaceId,
|
|
3847
|
+
});
|
|
3848
|
+
if (!this.transport || this.connectionState.status !== "connected") {
|
|
3849
|
+
return;
|
|
3850
|
+
}
|
|
3851
|
+
this.sendSessionMessage({
|
|
3852
|
+
type: "subscribe_terminals_request",
|
|
3853
|
+
cwd: input.cwd,
|
|
3854
|
+
...(input.workspaceId !== undefined ? { workspaceId: input.workspaceId } : {}),
|
|
3855
|
+
});
|
|
3856
|
+
}
|
|
3857
|
+
unsubscribeTerminals(input) {
|
|
3858
|
+
this.terminalDirectorySubscriptions.delete(terminalSubscriptionKey(input.cwd, input.workspaceId));
|
|
3859
|
+
if (!this.transport || this.connectionState.status !== "connected") {
|
|
3860
|
+
return;
|
|
3861
|
+
}
|
|
3862
|
+
this.sendSessionMessage({
|
|
3863
|
+
type: "unsubscribe_terminals_request",
|
|
3864
|
+
cwd: input.cwd,
|
|
3865
|
+
...(input.workspaceId !== undefined ? { workspaceId: input.workspaceId } : {}),
|
|
3866
|
+
});
|
|
3867
|
+
}
|
|
3868
|
+
async listTerminals(cwd, requestId, options) {
|
|
3869
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3870
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3871
|
+
type: "list_terminals_request",
|
|
3872
|
+
...(cwd === undefined ? {} : { cwd }),
|
|
3873
|
+
...(options?.workspaceId !== undefined ? { workspaceId: options.workspaceId } : {}),
|
|
3874
|
+
requestId: resolvedRequestId,
|
|
3875
|
+
});
|
|
3876
|
+
return this.sendCorrelatedRequest({
|
|
3877
|
+
requestId: resolvedRequestId,
|
|
3878
|
+
message,
|
|
3879
|
+
responseType: "list_terminals_response",
|
|
3880
|
+
options: { skipQueue: true },
|
|
3881
|
+
});
|
|
3882
|
+
}
|
|
3883
|
+
async createTerminal(cwd, name, requestId, options) {
|
|
3884
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3885
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3886
|
+
type: "create_terminal_request",
|
|
3887
|
+
cwd,
|
|
3888
|
+
name,
|
|
3889
|
+
agentId: options?.agentId,
|
|
3890
|
+
command: options?.command,
|
|
3891
|
+
args: options?.args,
|
|
3892
|
+
...(options?.workspaceId !== undefined ? { workspaceId: options.workspaceId } : {}),
|
|
3893
|
+
...(options?.size !== undefined ? { size: options.size } : {}),
|
|
3894
|
+
requestId: resolvedRequestId,
|
|
3895
|
+
});
|
|
3896
|
+
return this.sendCorrelatedRequest({
|
|
3897
|
+
requestId: resolvedRequestId,
|
|
3898
|
+
message,
|
|
3899
|
+
responseType: "create_terminal_response",
|
|
3900
|
+
options: { skipQueue: true },
|
|
3901
|
+
});
|
|
3902
|
+
}
|
|
3903
|
+
async renameTerminal(input) {
|
|
3904
|
+
return this.sendCorrelatedSessionRequest({
|
|
3905
|
+
requestId: input.requestId,
|
|
3906
|
+
message: {
|
|
3907
|
+
type: "terminal.rename.request",
|
|
3908
|
+
terminalId: input.terminalId,
|
|
3909
|
+
title: input.title,
|
|
3910
|
+
},
|
|
3911
|
+
responseType: "terminal.rename.response",
|
|
3912
|
+
});
|
|
3913
|
+
}
|
|
3914
|
+
async subscribeTerminal(terminalId, optionsOrRequestId) {
|
|
3915
|
+
const restore = typeof optionsOrRequestId === "object" ? optionsOrRequestId.restore : undefined;
|
|
3916
|
+
const requestId = typeof optionsOrRequestId === "object" ? optionsOrRequestId.requestId : optionsOrRequestId;
|
|
3917
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3918
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3919
|
+
type: "subscribe_terminal_request",
|
|
3920
|
+
terminalId,
|
|
3921
|
+
requestId: resolvedRequestId,
|
|
3922
|
+
...(restore ? { restore } : {}),
|
|
3923
|
+
});
|
|
3924
|
+
const payload = await this.sendCorrelatedRequest({
|
|
3925
|
+
requestId: resolvedRequestId,
|
|
3926
|
+
message,
|
|
3927
|
+
responseType: "subscribe_terminal_response",
|
|
3928
|
+
options: { skipQueue: true },
|
|
3929
|
+
});
|
|
3930
|
+
if (payload.error === null) {
|
|
3931
|
+
this.terminalStreams.setSlot(terminalId, payload.slot);
|
|
3932
|
+
}
|
|
3933
|
+
return payload;
|
|
3934
|
+
}
|
|
3935
|
+
unsubscribeTerminal(terminalId) {
|
|
3936
|
+
this.terminalStreams.removeTerminal(terminalId);
|
|
3937
|
+
this.sendSessionMessage({
|
|
3938
|
+
type: "unsubscribe_terminal_request",
|
|
3939
|
+
terminalId,
|
|
3940
|
+
});
|
|
3941
|
+
}
|
|
3942
|
+
sendTerminalInput(terminalId, message) {
|
|
3943
|
+
const frame = this.terminalStreams.encodeInput(terminalId, message);
|
|
3944
|
+
if (frame) {
|
|
3945
|
+
this.sendBinaryFrame(frame);
|
|
3946
|
+
return;
|
|
3947
|
+
}
|
|
3948
|
+
this.sendSessionMessage({
|
|
3949
|
+
type: "terminal_input",
|
|
3950
|
+
terminalId,
|
|
3951
|
+
message,
|
|
3952
|
+
});
|
|
3953
|
+
}
|
|
3954
|
+
async killTerminal(terminalId, requestId) {
|
|
3955
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3956
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3957
|
+
type: "kill_terminal_request",
|
|
3958
|
+
terminalId,
|
|
3959
|
+
requestId: resolvedRequestId,
|
|
3960
|
+
});
|
|
3961
|
+
return this.sendCorrelatedRequest({
|
|
3962
|
+
requestId: resolvedRequestId,
|
|
3963
|
+
message,
|
|
3964
|
+
responseType: "kill_terminal_response",
|
|
3965
|
+
options: { skipQueue: true },
|
|
3966
|
+
});
|
|
3967
|
+
}
|
|
3968
|
+
async closeItems(input, requestId) {
|
|
3969
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3970
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3971
|
+
type: "close_items_request",
|
|
3972
|
+
agentIds: input.agentIds ?? [],
|
|
3973
|
+
terminalIds: input.terminalIds ?? [],
|
|
3974
|
+
requestId: resolvedRequestId,
|
|
3975
|
+
});
|
|
3976
|
+
return this.sendCorrelatedRequest({
|
|
3977
|
+
requestId: resolvedRequestId,
|
|
3978
|
+
message,
|
|
3979
|
+
responseType: "close_items_response",
|
|
3980
|
+
options: { skipQueue: true },
|
|
3981
|
+
});
|
|
3982
|
+
}
|
|
3983
|
+
async captureTerminal(terminalId, options, requestId) {
|
|
3984
|
+
const resolvedRequestId = this.createRequestId(requestId);
|
|
3985
|
+
const message = SessionInboundMessageSchema.parse({
|
|
3986
|
+
type: "capture_terminal_request",
|
|
3987
|
+
terminalId,
|
|
3988
|
+
...(options?.start === undefined ? {} : { start: options.start }),
|
|
3989
|
+
...(options?.end === undefined ? {} : { end: options.end }),
|
|
3990
|
+
...(options?.stripAnsi === undefined ? {} : { stripAnsi: options.stripAnsi }),
|
|
3991
|
+
requestId: resolvedRequestId,
|
|
3992
|
+
});
|
|
3993
|
+
return this.sendCorrelatedRequest({
|
|
3994
|
+
requestId: resolvedRequestId,
|
|
3995
|
+
message,
|
|
3996
|
+
responseType: "capture_terminal_response",
|
|
3997
|
+
options: { skipQueue: true },
|
|
3998
|
+
});
|
|
3999
|
+
}
|
|
4000
|
+
async scheduleCreate(options) {
|
|
4001
|
+
return this.sendCorrelatedSessionRequest({
|
|
4002
|
+
requestId: options.requestId,
|
|
4003
|
+
message: {
|
|
4004
|
+
type: "schedule/create",
|
|
4005
|
+
prompt: options.prompt,
|
|
4006
|
+
cadence: options.cadence,
|
|
4007
|
+
target: options.target,
|
|
4008
|
+
...(options.name ? { name: options.name } : {}),
|
|
4009
|
+
...(typeof options.maxRuns === "number" ? { maxRuns: options.maxRuns } : {}),
|
|
4010
|
+
...(options.expiresAt ? { expiresAt: options.expiresAt } : {}),
|
|
4011
|
+
...(typeof options.runOnCreate === "boolean" ? { runOnCreate: options.runOnCreate } : {}),
|
|
4012
|
+
},
|
|
4013
|
+
responseType: "schedule/create/response",
|
|
4014
|
+
});
|
|
4015
|
+
}
|
|
4016
|
+
async scheduleList(requestId) {
|
|
4017
|
+
return this.sendCorrelatedSessionRequest({
|
|
4018
|
+
requestId,
|
|
4019
|
+
message: {
|
|
4020
|
+
type: "schedule/list",
|
|
4021
|
+
},
|
|
4022
|
+
responseType: "schedule/list/response",
|
|
4023
|
+
});
|
|
4024
|
+
}
|
|
4025
|
+
async scheduleInspect(options) {
|
|
4026
|
+
return this.sendCorrelatedSessionRequest({
|
|
4027
|
+
requestId: options.requestId,
|
|
4028
|
+
message: {
|
|
4029
|
+
type: "schedule/inspect",
|
|
4030
|
+
scheduleId: options.id,
|
|
4031
|
+
},
|
|
4032
|
+
responseType: "schedule/inspect/response",
|
|
4033
|
+
});
|
|
4034
|
+
}
|
|
4035
|
+
async scheduleLogs(options) {
|
|
4036
|
+
return this.sendCorrelatedSessionRequest({
|
|
4037
|
+
requestId: options.requestId,
|
|
4038
|
+
message: {
|
|
4039
|
+
type: "schedule/logs",
|
|
4040
|
+
scheduleId: options.id,
|
|
4041
|
+
},
|
|
4042
|
+
responseType: "schedule/logs/response",
|
|
4043
|
+
});
|
|
4044
|
+
}
|
|
4045
|
+
async schedulePause(options) {
|
|
4046
|
+
return this.sendCorrelatedSessionRequest({
|
|
4047
|
+
requestId: options.requestId,
|
|
4048
|
+
message: {
|
|
4049
|
+
type: "schedule/pause",
|
|
4050
|
+
scheduleId: options.id,
|
|
4051
|
+
},
|
|
4052
|
+
responseType: "schedule/pause/response",
|
|
4053
|
+
});
|
|
4054
|
+
}
|
|
4055
|
+
async scheduleResume(options) {
|
|
4056
|
+
return this.sendCorrelatedSessionRequest({
|
|
4057
|
+
requestId: options.requestId,
|
|
4058
|
+
message: {
|
|
4059
|
+
type: "schedule/resume",
|
|
4060
|
+
scheduleId: options.id,
|
|
4061
|
+
},
|
|
4062
|
+
responseType: "schedule/resume/response",
|
|
4063
|
+
});
|
|
4064
|
+
}
|
|
4065
|
+
async scheduleDelete(options) {
|
|
4066
|
+
return this.sendCorrelatedSessionRequest({
|
|
4067
|
+
requestId: options.requestId,
|
|
4068
|
+
message: {
|
|
4069
|
+
type: "schedule/delete",
|
|
4070
|
+
scheduleId: options.id,
|
|
4071
|
+
},
|
|
4072
|
+
responseType: "schedule/delete/response",
|
|
4073
|
+
});
|
|
4074
|
+
}
|
|
4075
|
+
async scheduleRunOnce(options) {
|
|
4076
|
+
return this.sendCorrelatedSessionRequest({
|
|
4077
|
+
requestId: options.requestId,
|
|
4078
|
+
message: {
|
|
4079
|
+
type: "schedule/run-once",
|
|
4080
|
+
scheduleId: options.id,
|
|
4081
|
+
},
|
|
4082
|
+
responseType: "schedule/run-once/response",
|
|
4083
|
+
});
|
|
4084
|
+
}
|
|
4085
|
+
async scheduleUpdate(options) {
|
|
4086
|
+
return this.sendCorrelatedSessionRequest({
|
|
4087
|
+
requestId: options.requestId,
|
|
4088
|
+
message: {
|
|
4089
|
+
type: "schedule/update",
|
|
4090
|
+
scheduleId: options.id,
|
|
4091
|
+
...(options.name !== undefined ? { name: options.name } : {}),
|
|
4092
|
+
...(options.prompt !== undefined ? { prompt: options.prompt } : {}),
|
|
4093
|
+
...(options.cadence !== undefined ? { cadence: options.cadence } : {}),
|
|
4094
|
+
...(options.newAgentConfig !== undefined ? { newAgentConfig: options.newAgentConfig } : {}),
|
|
4095
|
+
...(options.maxRuns !== undefined ? { maxRuns: options.maxRuns } : {}),
|
|
4096
|
+
...(options.expiresAt !== undefined ? { expiresAt: options.expiresAt } : {}),
|
|
4097
|
+
},
|
|
4098
|
+
responseType: "schedule/update/response",
|
|
4099
|
+
});
|
|
4100
|
+
}
|
|
4101
|
+
onTerminalStreamEvent(handler) {
|
|
4102
|
+
return this.terminalStreams.onEvent(handler);
|
|
4103
|
+
}
|
|
4104
|
+
async waitForTerminalStreamEvent(predicate, timeout = 5000) {
|
|
4105
|
+
return new Promise((resolve, reject) => {
|
|
4106
|
+
const timeoutHandle = setTimeout(() => {
|
|
4107
|
+
unsubscribe();
|
|
4108
|
+
reject(new Error(`Timeout waiting for terminal stream event (${timeout}ms)`));
|
|
4109
|
+
}, timeout);
|
|
4110
|
+
const unsubscribe = this.onTerminalStreamEvent((event) => {
|
|
4111
|
+
if (!predicate(event)) {
|
|
4112
|
+
return;
|
|
4113
|
+
}
|
|
4114
|
+
clearTimeout(timeoutHandle);
|
|
4115
|
+
unsubscribe();
|
|
4116
|
+
resolve(event);
|
|
4117
|
+
});
|
|
4118
|
+
});
|
|
4119
|
+
}
|
|
4120
|
+
// ============================================================================
|
|
4121
|
+
// Internals
|
|
4122
|
+
// ============================================================================
|
|
4123
|
+
createRequestId(requestId) {
|
|
4124
|
+
return requestId ?? crypto.randomUUID();
|
|
4125
|
+
}
|
|
4126
|
+
getLastServerInfoMessage() {
|
|
4127
|
+
return this.lastServerInfoMessage;
|
|
4128
|
+
}
|
|
4129
|
+
requireHubRelationshipSupport() {
|
|
4130
|
+
// COMPAT(hubRelationship): added in v0.1.X, drop the gate when floor >= v0.1.X.
|
|
4131
|
+
if (this.lastServerInfoMessage?.features?.hubRelationship !== true) {
|
|
4132
|
+
throw new Error("Update the host to use Hub relationship management.");
|
|
4133
|
+
}
|
|
4134
|
+
}
|
|
4135
|
+
requireDaemonConfigReloadSupport() {
|
|
4136
|
+
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
|
4137
|
+
if (this.lastServerInfoMessage?.features?.daemonConfigReload !== true) {
|
|
4138
|
+
throw new Error("Update the host to reload daemon configuration.");
|
|
4139
|
+
}
|
|
4140
|
+
}
|
|
4141
|
+
requireSideConversationSupport() {
|
|
4142
|
+
// COMPAT(sideConversations): added in 0.7.0-beta.2.fork.1, fork-only — stock peers never gain it, so the gate lasts as long as stock peers are supported.
|
|
4143
|
+
if (this.lastServerInfoMessage?.features?.sideConversations !== true) {
|
|
4144
|
+
throw new Error("Update the host to use side conversations.");
|
|
4145
|
+
}
|
|
4146
|
+
}
|
|
4147
|
+
resolveTransportUrlForAttempt() {
|
|
4148
|
+
return this.config.url;
|
|
4149
|
+
}
|
|
4150
|
+
sendHelloMessage() {
|
|
4151
|
+
if (!this.transport) {
|
|
4152
|
+
this.scheduleReconnect({
|
|
4153
|
+
reason: "Transport unavailable before hello",
|
|
4154
|
+
event: "HELLO_TRANSPORT_MISSING",
|
|
4155
|
+
reasonCode: "transport_error",
|
|
4156
|
+
});
|
|
4157
|
+
return;
|
|
4158
|
+
}
|
|
4159
|
+
try {
|
|
4160
|
+
this.sendJsonMessage("hello", "hello", {
|
|
4161
|
+
type: "hello",
|
|
4162
|
+
clientId: this.config.clientId,
|
|
4163
|
+
clientType: this.config.clientType ?? "cli",
|
|
4164
|
+
protocolVersion: 1,
|
|
4165
|
+
capabilities: {
|
|
4166
|
+
...DEFAULT_CLIENT_CAPABILITIES,
|
|
4167
|
+
// COMPAT(sideConversations): added in 0.7.0-beta.2.fork.1, fork-only.
|
|
4168
|
+
[CLIENT_CAPS.sideConversations]: true,
|
|
4169
|
+
...this.config.capabilities,
|
|
4170
|
+
},
|
|
4171
|
+
...(this.config.appVersion ? { appVersion: this.config.appVersion } : {}),
|
|
4172
|
+
});
|
|
4173
|
+
}
|
|
4174
|
+
catch (error) {
|
|
4175
|
+
const message = error instanceof Error ? error.message : "Failed to send hello message";
|
|
4176
|
+
this.lastErrorValue = message;
|
|
4177
|
+
this.scheduleReconnect({
|
|
4178
|
+
reason: message,
|
|
4179
|
+
event: "HELLO_SEND_FAILED",
|
|
4180
|
+
reasonCode: "transport_error",
|
|
4181
|
+
});
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
disposeTransport(code = 1001, reason = "Reconnecting") {
|
|
4185
|
+
this.providerSnapshotUpdates.pause();
|
|
4186
|
+
this.stopLivenessHeartbeat();
|
|
4187
|
+
this.cleanupTransport();
|
|
4188
|
+
if (this.transport) {
|
|
4189
|
+
try {
|
|
4190
|
+
this.transport.close(code, reason);
|
|
4191
|
+
}
|
|
4192
|
+
catch {
|
|
4193
|
+
// no-op
|
|
4194
|
+
}
|
|
4195
|
+
this.transport = null;
|
|
4196
|
+
}
|
|
4197
|
+
}
|
|
4198
|
+
cleanupTransport() {
|
|
4199
|
+
this.resetConnectTimeout();
|
|
4200
|
+
if (this.pendingGenericTransportErrorTimeout) {
|
|
4201
|
+
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
|
4202
|
+
this.pendingGenericTransportErrorTimeout = null;
|
|
4203
|
+
}
|
|
4204
|
+
for (const cleanup of this.transportCleanup) {
|
|
4205
|
+
try {
|
|
4206
|
+
cleanup();
|
|
4207
|
+
}
|
|
4208
|
+
catch {
|
|
4209
|
+
// no-op
|
|
4210
|
+
}
|
|
4211
|
+
}
|
|
4212
|
+
this.transportCleanup = [];
|
|
4213
|
+
}
|
|
4214
|
+
resetConnectTimeout() {
|
|
4215
|
+
if (!this.connectTimeout) {
|
|
4216
|
+
return;
|
|
4217
|
+
}
|
|
4218
|
+
clearTimeout(this.connectTimeout);
|
|
4219
|
+
this.connectTimeout = null;
|
|
4220
|
+
}
|
|
4221
|
+
handleTransportMessage(data) {
|
|
4222
|
+
const rawData = data && typeof data === "object" && "data" in data ? data.data : data;
|
|
4223
|
+
if (typeof Blob !== "undefined" &&
|
|
4224
|
+
rawData instanceof Blob &&
|
|
4225
|
+
typeof rawData.arrayBuffer === "function") {
|
|
4226
|
+
void rawData
|
|
4227
|
+
.arrayBuffer()
|
|
4228
|
+
.then((buffer) => {
|
|
4229
|
+
this.handleTransportMessage(buffer);
|
|
4230
|
+
return;
|
|
4231
|
+
})
|
|
4232
|
+
.catch(() => {
|
|
4233
|
+
// Ignore failed blob decoding and allow reconnect logic to recover.
|
|
4234
|
+
});
|
|
4235
|
+
return;
|
|
4236
|
+
}
|
|
4237
|
+
const rawBytes = asUint8Array(rawData);
|
|
4238
|
+
const isOpen = this.beginTraceSection("paseo.ws.frame.inbound", describeInboundTransportFrame(rawData, rawBytes));
|
|
4239
|
+
try {
|
|
4240
|
+
if (rawBytes && this.tryHandleBinaryFrame(rawBytes)) {
|
|
4241
|
+
return;
|
|
4242
|
+
}
|
|
4243
|
+
const payload = decodeMessageData(rawData);
|
|
4244
|
+
if (!payload) {
|
|
4245
|
+
return;
|
|
4246
|
+
}
|
|
4247
|
+
this.handleJsonPayload(payload, rawBytes?.byteLength);
|
|
4248
|
+
}
|
|
4249
|
+
finally {
|
|
4250
|
+
this.endTraceSection(isOpen);
|
|
4251
|
+
}
|
|
4252
|
+
}
|
|
4253
|
+
handleJsonPayload(payload, rawBytesLength) {
|
|
4254
|
+
const bytes = rawBytesLength ?? payload.length;
|
|
4255
|
+
const startMs = perfNow();
|
|
4256
|
+
let parsedJson;
|
|
4257
|
+
const parseTraceOpen = this.beginTraceSection("paseo.ws.json.parse", {
|
|
4258
|
+
size: String(bytes),
|
|
4259
|
+
});
|
|
4260
|
+
try {
|
|
4261
|
+
parsedJson = JSON.parse(payload);
|
|
4262
|
+
}
|
|
4263
|
+
catch {
|
|
4264
|
+
return;
|
|
4265
|
+
}
|
|
4266
|
+
finally {
|
|
4267
|
+
this.endTraceSection(parseTraceOpen);
|
|
4268
|
+
}
|
|
4269
|
+
const parsed = validateWSOutboundMessage(parsedJson);
|
|
4270
|
+
if (!parsed.success) {
|
|
4271
|
+
const responseIdentity = extractCorrelatedResponseIdentity(parsedJson);
|
|
4272
|
+
const envelopeType = parsedJson != null &&
|
|
4273
|
+
typeof parsedJson === "object" &&
|
|
4274
|
+
"type" in parsedJson &&
|
|
4275
|
+
typeof parsedJson.type === "string"
|
|
4276
|
+
? parsedJson.type
|
|
4277
|
+
: "unknown";
|
|
4278
|
+
const msgType = responseIdentity?.responseType ?? envelopeType;
|
|
4279
|
+
this.logger.warn({ msgType, error: parsed.error.message }, "Message validation failed");
|
|
4280
|
+
if (responseIdentity) {
|
|
4281
|
+
this.rejectWaitersForRequestId(responseIdentity.requestId, new DaemonProtocolError(responseIdentity));
|
|
4282
|
+
}
|
|
4283
|
+
return;
|
|
4284
|
+
}
|
|
4285
|
+
this.consecutiveLivenessFailures = 0;
|
|
4286
|
+
if (parsed.data.type === "pong") {
|
|
4287
|
+
this.traceInstant("paseo.ws.message.inbound", {
|
|
4288
|
+
envelopeType: "pong",
|
|
4289
|
+
messageType: "pong",
|
|
4290
|
+
});
|
|
4291
|
+
this.resolvePingProbe();
|
|
4292
|
+
this.runtimeMetrics?.recordMessage("pong", bytes, perfNow() - startMs);
|
|
4293
|
+
return;
|
|
4294
|
+
}
|
|
4295
|
+
this.traceInstant("paseo.ws.message.inbound", {
|
|
4296
|
+
envelopeType: "session",
|
|
4297
|
+
messageType: parsed.data.message.type,
|
|
4298
|
+
});
|
|
4299
|
+
this.handleSessionMessage(parsed.data.message);
|
|
4300
|
+
const msgType = parsed.data.message.type;
|
|
4301
|
+
this.runtimeMetrics?.recordMessage(msgType, bytes, perfNow() - startMs);
|
|
4302
|
+
if (parsed.data.message.type === "agent_stream") {
|
|
4303
|
+
this.runtimeMetrics?.recordAgentStream(parsed.data.message.payload);
|
|
4304
|
+
}
|
|
4305
|
+
}
|
|
4306
|
+
tryHandleBinaryFrame(rawBytes) {
|
|
4307
|
+
const fileFrame = decodeFileTransferFrame(rawBytes);
|
|
4308
|
+
if (fileFrame) {
|
|
4309
|
+
this.traceInstant("paseo.ws.message.inbound", {
|
|
4310
|
+
envelopeType: "binary",
|
|
4311
|
+
messageType: "file",
|
|
4312
|
+
opcode: String(fileFrame.opcode),
|
|
4313
|
+
});
|
|
4314
|
+
this.consecutiveLivenessFailures = 0;
|
|
4315
|
+
this.handleFileTransferFrame(fileFrame);
|
|
4316
|
+
this.runtimeMetrics?.recordBinaryFrame("other", rawBytes.byteLength, 0);
|
|
4317
|
+
return true;
|
|
4318
|
+
}
|
|
4319
|
+
const frame = decodeTerminalStreamFrame(rawBytes);
|
|
4320
|
+
if (!frame) {
|
|
4321
|
+
return false;
|
|
4322
|
+
}
|
|
4323
|
+
this.traceInstant("paseo.ws.message.inbound", {
|
|
4324
|
+
envelopeType: "binary",
|
|
4325
|
+
messageType: "terminal",
|
|
4326
|
+
opcode: String(frame.opcode),
|
|
4327
|
+
});
|
|
4328
|
+
this.consecutiveLivenessFailures = 0;
|
|
4329
|
+
const binaryStartMs = perfNow();
|
|
4330
|
+
this.terminalStreams.handleFrame(frame);
|
|
4331
|
+
let frameKind = "other";
|
|
4332
|
+
if (frame.opcode === TerminalStreamOpcode.Output) {
|
|
4333
|
+
frameKind = "output";
|
|
4334
|
+
}
|
|
4335
|
+
else if (frame.opcode === TerminalStreamOpcode.Snapshot) {
|
|
4336
|
+
frameKind = "snapshot";
|
|
4337
|
+
}
|
|
4338
|
+
else if (frame.opcode === TerminalStreamOpcode.Restore) {
|
|
4339
|
+
frameKind = "output";
|
|
4340
|
+
}
|
|
4341
|
+
this.runtimeMetrics?.recordBinaryFrame(frameKind, rawBytes.byteLength, perfNow() - binaryStartMs);
|
|
4342
|
+
return true;
|
|
4343
|
+
}
|
|
4344
|
+
handleFileTransferFrame(frame) {
|
|
4345
|
+
if (frame.opcode === FileTransferOpcode.FileBegin) {
|
|
4346
|
+
const pending = this.pendingBinaryFileReads.get(frame.requestId);
|
|
4347
|
+
if (!pending) {
|
|
4348
|
+
return;
|
|
4349
|
+
}
|
|
4350
|
+
this.activeBinaryFileTransfers.set(frame.requestId, {
|
|
4351
|
+
...pending,
|
|
4352
|
+
mime: frame.metadata.mime,
|
|
4353
|
+
size: frame.metadata.size,
|
|
4354
|
+
encoding: frame.metadata.encoding,
|
|
4355
|
+
modifiedAt: frame.metadata.modifiedAt,
|
|
4356
|
+
revision: frame.metadata.revision,
|
|
4357
|
+
chunks: [],
|
|
4358
|
+
});
|
|
4359
|
+
return;
|
|
4360
|
+
}
|
|
4361
|
+
const transfer = this.activeBinaryFileTransfers.get(frame.requestId);
|
|
4362
|
+
if (!transfer) {
|
|
4363
|
+
return;
|
|
4364
|
+
}
|
|
4365
|
+
if (frame.opcode === FileTransferOpcode.FileChunk) {
|
|
4366
|
+
// COMPAT(fileReadByteBudget): added in v0.5.0, remove after 2027-02-21 once daemon floor >= v0.5.0.
|
|
4367
|
+
// Old daemons stream despite maxBytes; discard before client-side accumulation.
|
|
4368
|
+
if (transfer.maxBytes && transfer.size > transfer.maxBytes) {
|
|
4369
|
+
return;
|
|
4370
|
+
}
|
|
4371
|
+
transfer.chunks.push(frame.payload);
|
|
4372
|
+
return;
|
|
4373
|
+
}
|
|
4374
|
+
// COMPAT(fileReadByteBudget): added in v0.5.0, remove after 2027-02-21 once daemon floor >= v0.5.0.
|
|
4375
|
+
if (transfer.maxBytes && transfer.size > transfer.maxBytes) {
|
|
4376
|
+
this.activeBinaryFileTransfers.delete(frame.requestId);
|
|
4377
|
+
this.handleSessionMessage({
|
|
4378
|
+
type: "file_explorer_response",
|
|
4379
|
+
payload: {
|
|
4380
|
+
cwd: transfer.cwd,
|
|
4381
|
+
path: transfer.path,
|
|
4382
|
+
mode: "file",
|
|
4383
|
+
directory: null,
|
|
4384
|
+
file: null,
|
|
4385
|
+
error: "File is too large to display",
|
|
4386
|
+
requestId: frame.requestId,
|
|
4387
|
+
},
|
|
4388
|
+
});
|
|
4389
|
+
return;
|
|
4390
|
+
}
|
|
4391
|
+
const bytes = concatByteChunks(transfer.chunks, transfer.size);
|
|
4392
|
+
this.activeBinaryFileTransfers.delete(frame.requestId);
|
|
4393
|
+
this.completedBinaryFileReads.set(frame.requestId, {
|
|
4394
|
+
bytes,
|
|
4395
|
+
mime: transfer.mime,
|
|
4396
|
+
size: transfer.size,
|
|
4397
|
+
path: transfer.path,
|
|
4398
|
+
kind: binaryFileKind(transfer.mime, transfer.encoding),
|
|
4399
|
+
modifiedAt: transfer.modifiedAt,
|
|
4400
|
+
revision: transfer.revision,
|
|
4401
|
+
});
|
|
4402
|
+
this.handleSessionMessage({
|
|
4403
|
+
type: "file_explorer_response",
|
|
4404
|
+
payload: {
|
|
4405
|
+
cwd: transfer.cwd,
|
|
4406
|
+
path: transfer.path,
|
|
4407
|
+
mode: "file",
|
|
4408
|
+
directory: null,
|
|
4409
|
+
file: null,
|
|
4410
|
+
error: null,
|
|
4411
|
+
requestId: frame.requestId,
|
|
4412
|
+
},
|
|
4413
|
+
});
|
|
4414
|
+
}
|
|
4415
|
+
updateConnectionState(next, metadata) {
|
|
4416
|
+
const previous = this.connectionState;
|
|
4417
|
+
this.connectionState = next;
|
|
4418
|
+
const reasonFromNext = next.status === "disconnected" && typeof next.reason === "string" ? next.reason : null;
|
|
4419
|
+
const reason = metadata?.reason ?? reasonFromNext;
|
|
4420
|
+
const reasonCode = metadata?.reasonCode ?? toReasonCode(reason);
|
|
4421
|
+
this.logger.debug({
|
|
4422
|
+
serverId: this.logServerId,
|
|
4423
|
+
clientIdHash: this.logClientIdHash,
|
|
4424
|
+
from: previous.status,
|
|
4425
|
+
to: next.status,
|
|
4426
|
+
event: metadata?.event ?? "STATE_UPDATE",
|
|
4427
|
+
connectionPath: this.logConnectionPath,
|
|
4428
|
+
generation: this.logGeneration,
|
|
4429
|
+
reasonCode,
|
|
4430
|
+
reason,
|
|
4431
|
+
}, "DaemonClientTransition");
|
|
4432
|
+
for (const listener of this.connectionListeners) {
|
|
4433
|
+
try {
|
|
4434
|
+
listener(next);
|
|
4435
|
+
}
|
|
4436
|
+
catch {
|
|
4437
|
+
// no-op
|
|
4438
|
+
}
|
|
4439
|
+
}
|
|
4440
|
+
}
|
|
4441
|
+
setReconnectEnabled(enabled) {
|
|
4442
|
+
this.config = { ...this.config, reconnect: { ...this.config.reconnect, enabled } };
|
|
4443
|
+
if (!enabled && this.reconnectTimeout) {
|
|
4444
|
+
clearTimeout(this.reconnectTimeout);
|
|
4445
|
+
this.reconnectTimeout = null;
|
|
4446
|
+
}
|
|
4447
|
+
}
|
|
4448
|
+
scheduleReconnect(input) {
|
|
4449
|
+
if (this.reconnectTimeout) {
|
|
4450
|
+
clearTimeout(this.reconnectTimeout);
|
|
4451
|
+
this.reconnectTimeout = null;
|
|
4452
|
+
}
|
|
4453
|
+
const wasDisposed = this.connectionState.status === "disposed";
|
|
4454
|
+
const reason = input?.reason;
|
|
4455
|
+
if (typeof reason === "string" && reason.trim().length > 0) {
|
|
4456
|
+
this.lastErrorValue = reason.trim();
|
|
4457
|
+
}
|
|
4458
|
+
this.providerSnapshotUpdates.pause();
|
|
4459
|
+
// Clear all pending waiters and queued sends since the connection was lost
|
|
4460
|
+
// and responses from the previous connection will never arrive.
|
|
4461
|
+
this.clearWaiters(new Error(reason ?? "Connection lost"));
|
|
4462
|
+
this.rejectPendingSendQueue(new Error(reason ?? "Connection lost"));
|
|
4463
|
+
this.rejectPingProbe(new Error(reason ?? "Connection lost"));
|
|
4464
|
+
this.terminalStreams.clearSlots();
|
|
4465
|
+
this.lastServerInfoMessage = null;
|
|
4466
|
+
if (wasDisposed) {
|
|
4467
|
+
this.rejectConnect(new Error(reason ?? "Daemon client is disposed"));
|
|
4468
|
+
return;
|
|
4469
|
+
}
|
|
4470
|
+
this.emitDisconnectedStateForReconnect(reason, input);
|
|
4471
|
+
if (!this.shouldReconnect || this.config.reconnect?.enabled === false) {
|
|
4472
|
+
this.rejectConnect(new Error(reason ?? "Transport disconnected before connect"));
|
|
4473
|
+
return;
|
|
4474
|
+
}
|
|
4475
|
+
this.armReconnectTimer();
|
|
4476
|
+
}
|
|
4477
|
+
emitDisconnectedStateForReconnect(reason, input) {
|
|
4478
|
+
this.updateConnectionState({
|
|
4479
|
+
status: "disconnected",
|
|
4480
|
+
...(reason ? { reason } : {}),
|
|
4481
|
+
}, {
|
|
4482
|
+
event: input?.event ?? "TRANSPORT_CLOSE",
|
|
4483
|
+
...(reason ? { reason } : {}),
|
|
4484
|
+
...(input?.reasonCode ? { reasonCode: input.reasonCode } : {}),
|
|
4485
|
+
});
|
|
4486
|
+
}
|
|
4487
|
+
armReconnectTimer() {
|
|
4488
|
+
const attempt = this.reconnectAttempt;
|
|
4489
|
+
const baseDelay = this.config.reconnect?.baseDelayMs ?? DEFAULT_RECONNECT_BASE_DELAY_MS;
|
|
4490
|
+
const maxDelay = this.config.reconnect?.maxDelayMs ?? DEFAULT_RECONNECT_MAX_DELAY_MS;
|
|
4491
|
+
const delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
|
|
4492
|
+
this.reconnectAttempt = attempt + 1;
|
|
4493
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
4494
|
+
this.reconnectTimeout = null;
|
|
4495
|
+
if (!this.shouldReconnect) {
|
|
4496
|
+
return;
|
|
4497
|
+
}
|
|
4498
|
+
this.attemptConnect();
|
|
4499
|
+
}, delay);
|
|
4500
|
+
}
|
|
4501
|
+
resolvePingProbe() {
|
|
4502
|
+
const probe = this.pingProbe;
|
|
4503
|
+
if (!probe) {
|
|
4504
|
+
return;
|
|
4505
|
+
}
|
|
4506
|
+
this.pingProbe = null;
|
|
4507
|
+
clearTimeout(probe.timeoutHandle);
|
|
4508
|
+
probe.resolve(perfNow() - probe.startedAt);
|
|
4509
|
+
}
|
|
4510
|
+
clearPingProbe() {
|
|
4511
|
+
const probe = this.pingProbe;
|
|
4512
|
+
if (!probe) {
|
|
4513
|
+
return;
|
|
4514
|
+
}
|
|
4515
|
+
this.pingProbe = null;
|
|
4516
|
+
clearTimeout(probe.timeoutHandle);
|
|
4517
|
+
}
|
|
4518
|
+
rejectPingProbe(error) {
|
|
4519
|
+
const probe = this.pingProbe;
|
|
4520
|
+
if (!probe) {
|
|
4521
|
+
return;
|
|
4522
|
+
}
|
|
4523
|
+
this.pingProbe = null;
|
|
4524
|
+
clearTimeout(probe.timeoutHandle);
|
|
4525
|
+
probe.reject(error);
|
|
4526
|
+
}
|
|
4527
|
+
recordLivenessFailure(error) {
|
|
4528
|
+
this.consecutiveLivenessFailures += 1;
|
|
4529
|
+
if (this.consecutiveLivenessFailures < LIVENESS_FAILURE_RECONNECT_THRESHOLD) {
|
|
4530
|
+
return;
|
|
4531
|
+
}
|
|
4532
|
+
this.consecutiveLivenessFailures = 0;
|
|
4533
|
+
this.lastErrorValue = error.message;
|
|
4534
|
+
this.disposeTransport(1001, "Liveness check timed out");
|
|
4535
|
+
this.scheduleReconnect({
|
|
4536
|
+
reason: error.message,
|
|
4537
|
+
event: "LIVENESS_TIMEOUT",
|
|
4538
|
+
reasonCode: "liveness_timeout",
|
|
4539
|
+
});
|
|
4540
|
+
}
|
|
4541
|
+
handleSessionMessage(msg) {
|
|
4542
|
+
if (msg.type === "providers_snapshot_update" &&
|
|
4543
|
+
this.config.providerSnapshots !== "wire" &&
|
|
4544
|
+
msg.payload.snapshotHash &&
|
|
4545
|
+
!msg.payload.compactSnapshot) {
|
|
4546
|
+
if (this.messageHandlers.has(msg.type) || this.eventListeners.size > 0) {
|
|
4547
|
+
this.providerSnapshotUpdates.receive(msg);
|
|
4548
|
+
}
|
|
4549
|
+
return;
|
|
4550
|
+
}
|
|
4551
|
+
this.deliverSessionMessage(msg);
|
|
4552
|
+
}
|
|
4553
|
+
deliverSessionMessage(msg) {
|
|
4554
|
+
const consumerMessage = normalizeProviderSnapshotUpdateMessage(msg, this.config.providerSnapshots !== "wire");
|
|
4555
|
+
if (consumerMessage.type === "status") {
|
|
4556
|
+
const serverInfo = parseServerInfoStatusPayload(consumerMessage.payload);
|
|
4557
|
+
if (serverInfo) {
|
|
4558
|
+
this.lastServerInfoMessage = serverInfo;
|
|
4559
|
+
if (this.connectionState.status === "connecting") {
|
|
4560
|
+
this.resetConnectTimeout();
|
|
4561
|
+
this.reconnectAttempt = 0;
|
|
4562
|
+
this.updateConnectionState({ status: "connected" }, { event: "HELLO_SERVER_INFO" });
|
|
4563
|
+
this.startLivenessHeartbeat();
|
|
4564
|
+
this.subscriptions.restore();
|
|
4565
|
+
this.providerSnapshotUpdates.resume();
|
|
4566
|
+
this.resubscribeCheckoutDiffSubscriptions();
|
|
4567
|
+
this.resubscribeTerminalDirectorySubscriptions();
|
|
4568
|
+
this.resubscribeFileSubscriptions();
|
|
4569
|
+
this.creations.reconnect();
|
|
4570
|
+
this.flushPendingSendQueue();
|
|
4571
|
+
this.resolveConnect();
|
|
4572
|
+
}
|
|
4573
|
+
}
|
|
4574
|
+
}
|
|
4575
|
+
if (consumerMessage.type === "terminal_stream_exit") {
|
|
4576
|
+
this.terminalStreams.removeTerminal(consumerMessage.payload.terminalId);
|
|
4577
|
+
}
|
|
4578
|
+
if (consumerMessage.type === "fs.file.update") {
|
|
4579
|
+
this.fileSubscriptions
|
|
4580
|
+
.get(consumerMessage.payload.subscriptionId)
|
|
4581
|
+
?.onUpdate(consumerMessage.payload.version);
|
|
4582
|
+
}
|
|
4583
|
+
if (this.rawMessageListeners.size > 0) {
|
|
4584
|
+
for (const handler of this.rawMessageListeners) {
|
|
4585
|
+
try {
|
|
4586
|
+
handler(consumerMessage);
|
|
4587
|
+
}
|
|
4588
|
+
catch {
|
|
4589
|
+
// no-op
|
|
4590
|
+
}
|
|
4591
|
+
}
|
|
4592
|
+
}
|
|
4593
|
+
const handlers = this.messageHandlers.get(consumerMessage.type);
|
|
4594
|
+
if (handlers) {
|
|
4595
|
+
for (const handler of handlers) {
|
|
4596
|
+
try {
|
|
4597
|
+
handler(consumerMessage);
|
|
4598
|
+
}
|
|
4599
|
+
catch {
|
|
4600
|
+
// no-op
|
|
4601
|
+
}
|
|
4602
|
+
}
|
|
4603
|
+
}
|
|
4604
|
+
const event = this.toEvent(consumerMessage);
|
|
4605
|
+
if (event) {
|
|
4606
|
+
for (const handler of this.eventListeners) {
|
|
4607
|
+
handler(event);
|
|
4608
|
+
}
|
|
4609
|
+
}
|
|
4610
|
+
if (consumerMessage.type === "workspace.create.update" ||
|
|
4611
|
+
consumerMessage.type === "agent.create.update")
|
|
4612
|
+
this.creations.receive(consumerMessage.payload);
|
|
4613
|
+
this.resolveWaiters(consumerMessage);
|
|
4614
|
+
}
|
|
4615
|
+
resolveWaiters(msg) {
|
|
4616
|
+
for (const waiter of Array.from(this.waiters)) {
|
|
4617
|
+
const result = waiter.predicate(msg);
|
|
4618
|
+
if (result !== null) {
|
|
4619
|
+
this.waiters.delete(waiter);
|
|
4620
|
+
if (waiter.timeoutHandle) {
|
|
4621
|
+
clearTimeout(waiter.timeoutHandle);
|
|
4622
|
+
}
|
|
4623
|
+
waiter.resolve(result);
|
|
4624
|
+
}
|
|
4625
|
+
}
|
|
4626
|
+
}
|
|
4627
|
+
rejectWaitersForRequestId(requestId, error) {
|
|
4628
|
+
for (const waiter of Array.from(this.waiters)) {
|
|
4629
|
+
if (waiter.requestId !== requestId) {
|
|
4630
|
+
continue;
|
|
4631
|
+
}
|
|
4632
|
+
this.waiters.delete(waiter);
|
|
4633
|
+
if (waiter.timeoutHandle) {
|
|
4634
|
+
clearTimeout(waiter.timeoutHandle);
|
|
4635
|
+
}
|
|
4636
|
+
waiter.reject(error);
|
|
4637
|
+
}
|
|
4638
|
+
}
|
|
4639
|
+
clearWaiters(error) {
|
|
4640
|
+
for (const waiter of Array.from(this.waiters)) {
|
|
4641
|
+
if (waiter.timeoutHandle) {
|
|
4642
|
+
clearTimeout(waiter.timeoutHandle);
|
|
4643
|
+
}
|
|
4644
|
+
waiter.reject(error);
|
|
4645
|
+
}
|
|
4646
|
+
this.waiters.clear();
|
|
4647
|
+
}
|
|
4648
|
+
toEvent(msg) {
|
|
4649
|
+
switch (msg.type) {
|
|
4650
|
+
case "agent_update":
|
|
4651
|
+
return {
|
|
4652
|
+
type: "agent_update",
|
|
4653
|
+
agentId: msg.payload.kind === "upsert" ? msg.payload.agent.id : msg.payload.agentId,
|
|
4654
|
+
payload: msg.payload,
|
|
4655
|
+
};
|
|
4656
|
+
case "workspace_update":
|
|
4657
|
+
return {
|
|
4658
|
+
type: "workspace_update",
|
|
4659
|
+
workspaceId: msg.payload.kind === "upsert" ? msg.payload.workspace.id : msg.payload.id,
|
|
4660
|
+
payload: msg.payload,
|
|
4661
|
+
};
|
|
4662
|
+
case "project.update":
|
|
4663
|
+
return { type: "project.update", payload: msg.payload };
|
|
4664
|
+
case "workspace_setup_progress":
|
|
4665
|
+
return {
|
|
4666
|
+
type: "workspace_setup_progress",
|
|
4667
|
+
workspaceId: msg.payload.workspaceId,
|
|
4668
|
+
payload: msg.payload,
|
|
4669
|
+
};
|
|
4670
|
+
case "agent_stream":
|
|
4671
|
+
return {
|
|
4672
|
+
type: "agent_stream",
|
|
4673
|
+
agentId: msg.payload.agentId,
|
|
4674
|
+
event: msg.payload.event,
|
|
4675
|
+
timestamp: msg.payload.timestamp,
|
|
4676
|
+
...(typeof msg.payload.seq === "number" ? { seq: msg.payload.seq } : {}),
|
|
4677
|
+
...(typeof msg.payload.epoch === "string" ? { epoch: msg.payload.epoch } : {}),
|
|
4678
|
+
};
|
|
4679
|
+
case "status":
|
|
4680
|
+
return { type: "status", payload: msg.payload };
|
|
4681
|
+
case "agent_deleted":
|
|
4682
|
+
return { type: "agent_deleted", agentId: msg.payload.agentId };
|
|
4683
|
+
case "agent_permission_request":
|
|
4684
|
+
return {
|
|
4685
|
+
type: "agent_permission_request",
|
|
4686
|
+
agentId: msg.payload.agentId,
|
|
4687
|
+
request: msg.payload.request,
|
|
4688
|
+
};
|
|
4689
|
+
case "agent_permission_resolved":
|
|
4690
|
+
return {
|
|
4691
|
+
type: "agent_permission_resolved",
|
|
4692
|
+
agentId: msg.payload.agentId,
|
|
4693
|
+
requestId: msg.payload.requestId,
|
|
4694
|
+
resolution: msg.payload.resolution,
|
|
4695
|
+
};
|
|
4696
|
+
case "providers_snapshot_update":
|
|
4697
|
+
return {
|
|
4698
|
+
type: "providers_snapshot_update",
|
|
4699
|
+
payload: msg.payload,
|
|
4700
|
+
};
|
|
4701
|
+
default:
|
|
4702
|
+
return null;
|
|
4703
|
+
}
|
|
4704
|
+
}
|
|
4705
|
+
waitForWithCancel(predicate, timeout = 30000, options) {
|
|
4706
|
+
// Capture stack trace at call site, not inside setTimeout
|
|
4707
|
+
const timeoutError = new Error(`Timeout waiting for message (${timeout}ms)`);
|
|
4708
|
+
let waiter = null;
|
|
4709
|
+
let settled = false;
|
|
4710
|
+
let rejectFn = null;
|
|
4711
|
+
const promise = new Promise((resolve, reject) => {
|
|
4712
|
+
const wrappedResolve = (value) => {
|
|
4713
|
+
if (settled)
|
|
4714
|
+
return;
|
|
4715
|
+
settled = true;
|
|
4716
|
+
resolve(value);
|
|
4717
|
+
};
|
|
4718
|
+
const wrappedReject = (error) => {
|
|
4719
|
+
if (settled)
|
|
4720
|
+
return;
|
|
4721
|
+
settled = true;
|
|
4722
|
+
reject(error);
|
|
4723
|
+
};
|
|
4724
|
+
rejectFn = wrappedReject;
|
|
4725
|
+
const timeoutHandle = timeout > 0
|
|
4726
|
+
? setTimeout(() => {
|
|
4727
|
+
if (waiter) {
|
|
4728
|
+
this.waiters.delete(waiter);
|
|
4729
|
+
}
|
|
4730
|
+
wrappedReject(timeoutError);
|
|
4731
|
+
}, timeout)
|
|
4732
|
+
: null;
|
|
4733
|
+
waiter = {
|
|
4734
|
+
predicate,
|
|
4735
|
+
resolve: wrappedResolve,
|
|
4736
|
+
reject: wrappedReject,
|
|
4737
|
+
timeoutHandle,
|
|
4738
|
+
requestId: options?.requestId,
|
|
4739
|
+
};
|
|
4740
|
+
this.waiters.add(waiter);
|
|
4741
|
+
});
|
|
4742
|
+
const cancel = (error) => {
|
|
4743
|
+
if (settled) {
|
|
4744
|
+
return;
|
|
4745
|
+
}
|
|
4746
|
+
if (waiter) {
|
|
4747
|
+
this.waiters.delete(waiter);
|
|
4748
|
+
if (waiter.timeoutHandle) {
|
|
4749
|
+
clearTimeout(waiter.timeoutHandle);
|
|
4750
|
+
}
|
|
4751
|
+
}
|
|
4752
|
+
if (rejectFn) {
|
|
4753
|
+
rejectFn(error);
|
|
4754
|
+
return;
|
|
4755
|
+
}
|
|
4756
|
+
// Extremely unlikely: cancel called before the Promise executor ran.
|
|
4757
|
+
queueMicrotask(() => {
|
|
4758
|
+
if (!settled && rejectFn) {
|
|
4759
|
+
rejectFn(error);
|
|
4760
|
+
}
|
|
4761
|
+
});
|
|
4762
|
+
};
|
|
4763
|
+
return { promise, cancel };
|
|
4764
|
+
}
|
|
4765
|
+
}
|
|
4766
|
+
function resolveAgentConfig(options) {
|
|
4767
|
+
const { config, provider, cwd, agentId: _agentId, onEvent: _onEvent, idempotencyKey: _idempotencyKey, clientMessageId: _clientMessageId, callerAgentId: _callerAgentId, outputSchema: _outputSchema, attachments: _attachments, worktree: _worktree, autoArchive: _autoArchive, env: _env, workspaceId: _workspaceId, initialPrompt: _initialPrompt, images: _images, git: _git, worktreeName: _worktreeName, requestId: _requestId, labels: _labels, ...overrides } = options;
|
|
4768
|
+
const baseConfig = {
|
|
4769
|
+
...(provider ? { provider } : {}),
|
|
4770
|
+
...(cwd ? { cwd } : {}),
|
|
4771
|
+
...overrides,
|
|
4772
|
+
};
|
|
4773
|
+
const merged = config ? { ...baseConfig, ...config } : baseConfig;
|
|
4774
|
+
if (!merged.provider || !merged.cwd) {
|
|
4775
|
+
throw new Error("createAgent requires provider and cwd");
|
|
4776
|
+
}
|
|
4777
|
+
return {
|
|
4778
|
+
...merged,
|
|
4779
|
+
provider: merged.provider,
|
|
4780
|
+
cwd: merged.cwd,
|
|
4781
|
+
};
|
|
4782
|
+
}
|
|
4783
|
+
//# sourceMappingURL=daemon-client.js.map
|