@rallycry/conveyor-agent 10.13.71 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2564 @@
1
+ import {
2
+ CLONE_TIMEOUT_MS,
3
+ DEFAULT_RETRY_DELAY_MS,
4
+ FETCH_TIMEOUT_MS,
5
+ GIT_PREP_MAX_RETRIES
6
+ } from "./chunk-GL2DIQEQ.js";
7
+ import {
8
+ buildConveyorSocketOptions,
9
+ callWithAck,
10
+ heartbeatStatusFor,
11
+ loopStatusForRunnerStatus,
12
+ waitForConnected
13
+ } from "./chunk-IA45XHOA.js";
14
+ import {
15
+ WorkbenchError,
16
+ getWorkbenchClient
17
+ } from "./chunk-EXQ6AHOY.js";
18
+ import {
19
+ workbenchEnabled
20
+ } from "./chunk-KMB3BU4S.js";
21
+ import {
22
+ gitCredentialHelper,
23
+ sleep,
24
+ syncGithubTokenFiles,
25
+ writeGitCredential
26
+ } from "./chunk-W4LZ7R6Z.js";
27
+
28
+ // src/setup/bootstrap.ts
29
+ var BOOTSTRAP_TIMEOUT_MS = 3e4;
30
+ var RETRY_DELAYS_MS = [5e3, 1e4, 2e4];
31
+ function emitFailureEvent(payload) {
32
+ process.stderr.write(JSON.stringify(payload) + "\n");
33
+ }
34
+ async function singleBootstrapAttempt(apiUrl, instanceName, bootstrapToken, timeoutMs) {
35
+ const controller = new AbortController();
36
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
37
+ try {
38
+ const headers = {};
39
+ if (bootstrapToken) headers["x-codespace-token"] = bootstrapToken;
40
+ const response = await fetch(`${apiUrl}/api/codespace/bootstrap/${instanceName}`, {
41
+ headers,
42
+ signal: controller.signal
43
+ });
44
+ if (!response.ok) {
45
+ const errorText = await response.text().catch(() => "");
46
+ return {
47
+ ok: false,
48
+ status: response.status,
49
+ errorText: errorText.slice(0, 500),
50
+ reason: response.status === 401 || response.status === 403 ? "auth_rejected" : "http_error"
51
+ };
52
+ }
53
+ const body = await response.json();
54
+ return { ok: true, body };
55
+ } catch (err) {
56
+ const message = err instanceof Error ? err.message : String(err);
57
+ const reason = controller.signal.aborted ? "timeout" : "network_error";
58
+ return { ok: false, errorText: message.slice(0, 500), reason };
59
+ } finally {
60
+ clearTimeout(timer);
61
+ }
62
+ }
63
+ function buildFailure(reason, attempts, status, detail) {
64
+ const out = { ok: false, reason, attempts };
65
+ if (status === void 0) {
66
+ } else {
67
+ out.status = status;
68
+ }
69
+ if (detail) out.detail = detail;
70
+ return out;
71
+ }
72
+ function isRetryable(reason, retryOnHttpError) {
73
+ if (reason === "timeout" || reason === "network_error") return true;
74
+ return retryOnHttpError === true && reason === "http_error";
75
+ }
76
+ async function fetchBootstrap(opts) {
77
+ const timeoutMs = opts.timeoutMs ?? BOOTSTRAP_TIMEOUT_MS;
78
+ const delays = opts.retryDelaysMs ?? RETRY_DELAYS_MS;
79
+ const maxAttempts = delays.length + 1;
80
+ const hasBootstrapToken = Boolean(opts.bootstrapToken);
81
+ const hasTaskToken = Boolean(process.env.CONVEYOR_TASK_TOKEN);
82
+ let lastReason = "unknown";
83
+ let lastStatus;
84
+ let lastDetail;
85
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
86
+ const result = await singleBootstrapAttempt(
87
+ opts.apiUrl,
88
+ opts.instanceName,
89
+ opts.bootstrapToken,
90
+ timeoutMs
91
+ );
92
+ if (result.ok && result.body) {
93
+ return { ok: true, config: result.body, attempts: attempt };
94
+ }
95
+ lastReason = result.reason ?? "unknown";
96
+ lastStatus = result.status;
97
+ lastDetail = result.errorText;
98
+ const failurePayload = {
99
+ event: "bootstrap_failed",
100
+ reason: lastReason,
101
+ apiUrl: opts.apiUrl,
102
+ instanceName: opts.instanceName,
103
+ hasBootstrapToken,
104
+ hasTaskToken,
105
+ attempt
106
+ };
107
+ if (lastStatus === void 0) {
108
+ } else {
109
+ failurePayload.status = lastStatus;
110
+ }
111
+ if (lastDetail) failurePayload.detail = lastDetail;
112
+ emitFailureEvent(failurePayload);
113
+ if (!isRetryable(lastReason, opts.retryOnHttpError) || attempt >= maxAttempts) {
114
+ return buildFailure(lastReason, attempt, lastStatus, lastDetail);
115
+ }
116
+ await sleep(delays[attempt - 1]);
117
+ }
118
+ return buildFailure(lastReason, maxAttempts, lastStatus, lastDetail);
119
+ }
120
+ function applyBootstrapToEnv(config) {
121
+ for (const [key, value] of Object.entries(config.envVars ?? {})) {
122
+ process.env[key] = value;
123
+ }
124
+ if (config.mode === "project") {
125
+ if (config.projectToken) process.env.CONVEYOR_PROJECT_TOKEN = config.projectToken;
126
+ if (config.projectId) process.env.CONVEYOR_PROJECT_ID = config.projectId;
127
+ if (config.workspaceBranch) process.env.CONVEYOR_WORKSPACE_BRANCH = config.workspaceBranch;
128
+ return;
129
+ }
130
+ if (config.taskId) process.env.CONVEYOR_TASK_ID = config.taskId;
131
+ if (config.sessionId) process.env.CONVEYOR_SESSION_ID = config.sessionId;
132
+ if (config.taskToken) process.env.CONVEYOR_TASK_TOKEN = config.taskToken;
133
+ if (config.agentMode !== void 0) process.env.CONVEYOR_AGENT_MODE = config.agentMode;
134
+ if (config.isAuto !== void 0) process.env.CONVEYOR_IS_AUTO = config.isAuto;
135
+ if (config.runnerMode) process.env.CONVEYOR_MODE = config.runnerMode;
136
+ if (config.taskBranch) process.env.CONVEYOR_TASK_BRANCH = config.taskBranch;
137
+ }
138
+
139
+ // src/utils/logger.ts
140
+ function createServiceLogger(service) {
141
+ const prefix = `[conveyor-agent:${service}]`;
142
+ return {
143
+ info(message, data) {
144
+ const extra = data ? ` ${JSON.stringify(data)}` : "";
145
+ process.stderr.write(`${prefix} ${message}${extra}
146
+ `);
147
+ },
148
+ warn(message, data) {
149
+ const extra = data ? ` ${JSON.stringify(data)}` : "";
150
+ process.stderr.write(`${prefix} WARN ${message}${extra}
151
+ `);
152
+ },
153
+ error(message, data) {
154
+ const extra = data ? ` ${JSON.stringify(data)}` : "";
155
+ process.stderr.write(`${prefix} ERROR ${message}${extra}
156
+ `);
157
+ }
158
+ };
159
+ }
160
+
161
+ // src/connection/agent-connection.ts
162
+ import { existsSync } from "fs";
163
+ import { fileURLToPath } from "url";
164
+ import { Worker } from "worker_threads";
165
+ import { io } from "socket.io-client";
166
+
167
+ // src/setup/bootstrap-poll.ts
168
+ var PollUntilBoundHttpError = class extends Error {
169
+ constructor(status) {
170
+ super(`pollUntilBound got unexpected status ${status}`);
171
+ this.status = status;
172
+ this.name = "PollUntilBoundHttpError";
173
+ }
174
+ status;
175
+ };
176
+ async function pollUntilBound(opts) {
177
+ const pollIntervalMs = opts.pollIntervalMs ?? 2e3;
178
+ const maxWaitMs = opts.maxWaitMs ?? 30 * 60 * 1e3;
179
+ const deadline = Date.now() + maxWaitMs;
180
+ while (true) {
181
+ const response = await fetch(`${opts.apiUrl}/api/v3/pods/bootstrap`, {
182
+ headers: { Authorization: `Bearer ${opts.bootstrapToken}` }
183
+ });
184
+ if (response.status === 200) {
185
+ return await response.json();
186
+ }
187
+ if (response.status === 204) {
188
+ if (Date.now() >= deadline) {
189
+ throw new Error(`pollUntilBound timed out after ${maxWaitMs}ms waiting for pod bind`);
190
+ }
191
+ await sleep(pollIntervalMs);
192
+ continue;
193
+ }
194
+ throw new PollUntilBoundHttpError(response.status);
195
+ }
196
+ }
197
+
198
+ // src/connection/bundle-credentials.ts
199
+ function readBundleIdentity(sessionJwt) {
200
+ if (!sessionJwt) return {};
201
+ const segments = sessionJwt.split(".");
202
+ if (segments.length !== 3) return {};
203
+ try {
204
+ const json = Buffer.from(segments[1], "base64url").toString("utf8");
205
+ const claims = JSON.parse(json);
206
+ return {
207
+ ...typeof claims.sessionId === "string" ? { sessionId: claims.sessionId } : {},
208
+ ...typeof claims.role === "string" ? { role: claims.role } : {}
209
+ };
210
+ } catch {
211
+ return {};
212
+ }
213
+ }
214
+ function bundleMayWriteGithubFiles(bundle, self) {
215
+ const identity = readBundleIdentity(bundle.sessionJwt);
216
+ if (identity.sessionId && self.sessionId && identity.sessionId !== self.sessionId) {
217
+ return {
218
+ allowed: false,
219
+ reason: `bundle resolved to session ${identity.sessionId}, not ours (${self.sessionId})`
220
+ };
221
+ }
222
+ if (identity.role === "reader" && self.role && self.role !== "reader") {
223
+ return {
224
+ allowed: false,
225
+ reason: `bundle carries a reader-scoped token but this session is a ${self.role}`
226
+ };
227
+ }
228
+ return { allowed: true };
229
+ }
230
+ function applyBundleGithubToken(bundle, self) {
231
+ if (!bundle.githubToken) return { written: false, reason: "bundle carried no GitHub token" };
232
+ const permitted = bundleMayWriteGithubFiles(bundle, self);
233
+ if (!permitted.allowed) {
234
+ return { written: false, ...permitted.reason ? { reason: permitted.reason } : {} };
235
+ }
236
+ syncGithubTokenFiles(bundle.githubToken);
237
+ return { written: true };
238
+ }
239
+ function syncBundleGithubToken(token) {
240
+ syncGithubTokenFiles(token);
241
+ }
242
+
243
+ // src/connection/agent-connection.ts
244
+ var logger = createServiceLogger("agent-connection");
245
+ var EVENT_BATCH_MS = 500;
246
+ var MAX_EVENT_BUFFER = 5e3;
247
+ var TOKEN_REFRESH_INTERVAL_MS = 45 * 60 * 1e3;
248
+ var AgentConnection = class _AgentConnection {
249
+ socket = null;
250
+ config;
251
+ eventBuffer = [];
252
+ flushTimer = null;
253
+ tokenRefreshTimer = null;
254
+ lastEmittedStatus = null;
255
+ lastReportedStatus = null;
256
+ droppedEventCount = 0;
257
+ // Pending answer resolvers for askUserQuestion room-event fallback
258
+ pendingAnswerResolvers = /* @__PURE__ */ new Map();
259
+ // Dedup: suppress near-identical messages within a short window
260
+ recentMessages = [];
261
+ static DEDUP_WINDOW_MS = 3e4;
262
+ static DEDUP_SIMILARITY_THRESHOLD = 0.7;
263
+ static DEDUP_PREVIEW_LIMIT = 120;
264
+ // Early-buffering: events that arrive before callbacks are registered
265
+ earlyMessages = [];
266
+ earlyStop = false;
267
+ earlySoftStop = false;
268
+ earlyModeChanges = [];
269
+ // Registered callbacks
270
+ messageCallback = null;
271
+ stopCallback = null;
272
+ softStopCallback = null;
273
+ modeChangeCallback = null;
274
+ apiKeyUpdateCallback = null;
275
+ pullBranchCallback = null;
276
+ runStartCommandCallback = null;
277
+ earlyRunStartCommand = false;
278
+ earlyPullBranches = [];
279
+ spawnReviewCallback = null;
280
+ earlySpawnReviews = [];
281
+ spawnBuilderCallback = null;
282
+ earlySpawnBuilders = [];
283
+ spawnTuiCallback = null;
284
+ earlySpawnTuis = [];
285
+ probeUsageCallback = null;
286
+ earlyProbeUsage = false;
287
+ // PTY relay (S5 terminal). Single-slot callbacks, set per PtySession run.
288
+ ptyInputCallback = null;
289
+ ptyResizeCallback = null;
290
+ constructor(config) {
291
+ this.config = config;
292
+ }
293
+ get sessionId() {
294
+ return this.config.sessionId;
295
+ }
296
+ get connected() {
297
+ return this.socket?.connected ?? false;
298
+ }
299
+ // ── Typed service method call ──────────────────────────────────────────
300
+ // Socket.IO keeps the SAME Socket instance across transport-level
301
+ // reconnects (it only goes null on an explicit disconnect() teardown), so a
302
+ // brief flap leaves `this.socket` non-null but `.connected === false`. Rather
303
+ // than failing a tool call instantly (which the spawned `claude` surfaces as
304
+ // "Conveyor MCP disconnected" and an excuse to go idle), we wait out a short
305
+ // reconnect window, then emit with an ack timeout so a buffered packet whose
306
+ // ack never returns can't hang the call forever. We do NOT auto-retry the
307
+ // emit — re-sending a write could double-apply it; the agent prompt instructs
308
+ // the model to retry the tool, which is the safe place to decide idempotency.
309
+ static CALL_CONNECT_WAIT_MS = 2e4;
310
+ static CALL_ACK_TIMEOUT_MS = 3e4;
311
+ // ── Proactive socket recycle ───────────────────────────────────────────
312
+ // Cloud Run severs every WebSocket at its request timeout (3600s is the
313
+ // platform ceiling), so a socket that lives past ~60 minutes is killed at a
314
+ // random moment — historically mid-tool-call, which let the spawned CLI
315
+ // abandon its MCP session. Recycle the transport at a QUIET moment (no
316
+ // in-flight RPC) before the platform deadline instead: an engine-level close
317
+ // looks like a transport drop, so Socket.IO's auto-reconnect and the
318
+ // io "reconnect" → reconnectToSession() recovery path run unchanged. Jitter
319
+ // keeps a fleet of pods from recycling in one thundering herd.
320
+ static SOCKET_RECYCLE_BASE_MS = 52 * 60 * 1e3;
321
+ static SOCKET_RECYCLE_JITTER_MS = 4 * 60 * 1e3;
322
+ static SOCKET_RECYCLE_BUSY_POLL_MS = 15e3;
323
+ recycleTimer = null;
324
+ pendingCalls = 0;
325
+ async call(method, payload) {
326
+ const socket = this.socket;
327
+ if (!socket) {
328
+ throw new Error(
329
+ `Not connected (method: ${String(method)}, session: ${this.config.sessionId})`
330
+ );
331
+ }
332
+ this.pendingCalls++;
333
+ try {
334
+ if (!socket.connected) {
335
+ await this.waitForConnected(socket, _AgentConnection.CALL_CONNECT_WAIT_MS, String(method));
336
+ }
337
+ return await this.emitWithAck(socket, method, payload);
338
+ } finally {
339
+ this.pendingCalls--;
340
+ }
341
+ }
342
+ /** (Re)arm the recycle timer — called on every successful (re)connect. */
343
+ scheduleSocketRecycle() {
344
+ this.clearSocketRecycle();
345
+ const delay2 = _AgentConnection.SOCKET_RECYCLE_BASE_MS + Math.random() * _AgentConnection.SOCKET_RECYCLE_JITTER_MS;
346
+ this.armRecycleTimer(delay2);
347
+ }
348
+ clearSocketRecycle() {
349
+ if (this.recycleTimer) {
350
+ clearTimeout(this.recycleTimer);
351
+ this.recycleTimer = null;
352
+ }
353
+ }
354
+ armRecycleTimer(delay2) {
355
+ this.recycleTimer = setTimeout(() => {
356
+ this.recycleTimer = null;
357
+ this.attemptSocketRecycle();
358
+ }, delay2);
359
+ this.recycleTimer.unref?.();
360
+ }
361
+ attemptSocketRecycle() {
362
+ const socket = this.socket;
363
+ if (!socket?.connected) return;
364
+ if (this.pendingCalls > 0) {
365
+ this.armRecycleTimer(_AgentConnection.SOCKET_RECYCLE_BUSY_POLL_MS);
366
+ return;
367
+ }
368
+ process.stderr.write(
369
+ "[conveyor-agent] Recycling socket ahead of the platform request timeout\n"
370
+ );
371
+ socket.io.engine?.close?.();
372
+ }
373
+ /** Resolve once `socket` reports connected, or reject after `timeoutMs`. */
374
+ waitForConnected(socket, timeoutMs, method) {
375
+ return waitForConnected(socket, timeoutMs, () => {
376
+ return new Error(
377
+ `Not connected \u2014 socket did not reconnect within ${timeoutMs / 1e3}s (method: ${method}, session: ${this.config.sessionId}). Transient; retry.`
378
+ );
379
+ });
380
+ }
381
+ /** Emit an RPC and resolve on ack, rejecting if no ack arrives in time. */
382
+ emitWithAck(socket, method, payload) {
383
+ return callWithAck(
384
+ socket,
385
+ `agentSessionService:${String(method)}`,
386
+ payload,
387
+ {
388
+ timeoutMs: _AgentConnection.CALL_ACK_TIMEOUT_MS,
389
+ requireData: true,
390
+ makeTimeoutError: () => new Error(
391
+ `Service call timed out after ${_AgentConnection.CALL_ACK_TIMEOUT_MS / 1e3}s (method: ${String(method)}, session: ${this.config.sessionId}). Usually a transient reconnect; retry.`
392
+ ),
393
+ makeFailureError: (error) => new Error(error ?? `Service call failed: ${String(method)}`)
394
+ }
395
+ );
396
+ }
397
+ // ── Connection lifecycle ───────────────────────────────────────────────
398
+ // oxlint-disable-next-line max-lines-per-function -- socket setup requires registering many co-located event handlers
399
+ connect() {
400
+ if (!this.config.apiUrl) {
401
+ return Promise.reject(new Error("Cannot connect: apiUrl is empty"));
402
+ }
403
+ this.startProactiveTokenRefresh();
404
+ return new Promise((resolve, reject) => {
405
+ let settled = false;
406
+ let attempts = 0;
407
+ const maxInitialAttempts = 30;
408
+ process.stderr.write(
409
+ `[conveyor-agent] Connecting to ${this.config.apiUrl} (mode: ${this.config.runnerMode ?? "task"}, session: ${this.config.sessionId})
410
+ `
411
+ );
412
+ this.socket = io(
413
+ this.config.apiUrl,
414
+ buildConveyorSocketOptions({
415
+ taskToken: this.config.taskToken,
416
+ runnerMode: this.config.runnerMode ?? "task"
417
+ })
418
+ );
419
+ this.socket.on("session:message", (msg) => {
420
+ const incoming = {
421
+ content: msg.content,
422
+ userId: msg.userId,
423
+ ...msg.source && { source: msg.source },
424
+ ...msg.files && { files: msg.files },
425
+ ...msg.delivery === "prefill" && { delivery: msg.delivery }
426
+ };
427
+ if (this.messageCallback) this.messageCallback(incoming);
428
+ else this.earlyMessages.push(incoming);
429
+ });
430
+ this.socket.on("session:stop", () => {
431
+ if (this.stopCallback) this.stopCallback();
432
+ else this.earlyStop = true;
433
+ });
434
+ this.socket.on("session:softStop", () => {
435
+ if (this.softStopCallback) this.softStopCallback();
436
+ else this.earlySoftStop = true;
437
+ });
438
+ this.socket.on("session:modeChange", (data) => {
439
+ if (this.modeChangeCallback) this.modeChangeCallback(data);
440
+ else this.earlyModeChanges.push(data);
441
+ });
442
+ this.socket.on(
443
+ "session:answerQuestion",
444
+ (data) => {
445
+ const resolver = this.pendingAnswerResolvers.get(data.requestId);
446
+ if (resolver) resolver(data.answers);
447
+ }
448
+ );
449
+ this.socket.on("agentRunner:updateApiKey", (data) => {
450
+ if (this.apiKeyUpdateCallback) this.apiKeyUpdateCallback(data);
451
+ });
452
+ this.socket.on("session:pullBranch", (data) => {
453
+ if (this.pullBranchCallback) this.pullBranchCallback(data);
454
+ else this.earlyPullBranches.push(data);
455
+ });
456
+ this.socket.on("session:spawnReview", (data) => {
457
+ if (this.spawnReviewCallback) this.spawnReviewCallback(data);
458
+ else this.earlySpawnReviews.push(data);
459
+ });
460
+ this.socket.on("session:spawnBuilder", (data) => {
461
+ if (this.spawnBuilderCallback) this.spawnBuilderCallback(data);
462
+ else this.earlySpawnBuilders.push(data);
463
+ });
464
+ this.socket.on("session:spawnTui", (data) => {
465
+ if (this.spawnTuiCallback) this.spawnTuiCallback(data);
466
+ else this.earlySpawnTuis.push(data);
467
+ });
468
+ this.socket.on("session:probeUsage", () => {
469
+ if (this.probeUsageCallback) this.probeUsageCallback();
470
+ else this.earlyProbeUsage = true;
471
+ });
472
+ this.socket.on("session:runStartCommand", () => {
473
+ if (this.runStartCommandCallback) this.runStartCommandCallback();
474
+ else this.earlyRunStartCommand = true;
475
+ });
476
+ this.socket.on("pty:input", (data) => {
477
+ if (data.sessionId && data.sessionId !== this.config.sessionId) return;
478
+ this.ptyInputCallback?.(data.data);
479
+ });
480
+ this.socket.on("pty:resize", (data) => {
481
+ if (data.sessionId && data.sessionId !== this.config.sessionId) return;
482
+ this.ptyResizeCallback?.(data.cols, data.rows);
483
+ });
484
+ this.socket.on("connect", () => {
485
+ process.stderr.write("[conveyor-agent] Socket connected\n");
486
+ this.scheduleSocketRecycle();
487
+ if (!settled) {
488
+ settled = true;
489
+ resolve();
490
+ }
491
+ });
492
+ this.socket.on("connect_error", (err) => {
493
+ attempts++;
494
+ process.stderr.write(
495
+ `[conveyor-agent] Connection error (attempt ${attempts}/${maxInitialAttempts}): ${err.message}
496
+ `
497
+ );
498
+ if (!settled && attempts >= maxInitialAttempts) {
499
+ settled = true;
500
+ reject(
501
+ new Error(
502
+ `Failed to connect to ${this.config.apiUrl} after ${maxInitialAttempts} attempts: ${err.message}`
503
+ )
504
+ );
505
+ }
506
+ });
507
+ this.socket.on("disconnect", (reason) => {
508
+ process.stderr.write(`[conveyor-agent] Disconnected: ${reason}
509
+ `);
510
+ if (reason === "io server disconnect" || reason === "server namespace disconnect") {
511
+ this.scheduleReconnectAfterServerDisconnect();
512
+ }
513
+ });
514
+ this.socket.on("auth:rejected", () => {
515
+ process.stderr.write("[conveyor-agent] Auth rejected by server, refreshing taskToken\n");
516
+ void this.refreshTaskTokenFromBootstrap().catch(() => {
517
+ });
518
+ });
519
+ this.socket.io.on("reconnect", (reconnectAttempts) => {
520
+ process.stderr.write(
521
+ `[conveyor-agent] Reconnected (attempts: ${reconnectAttempts}, ${(/* @__PURE__ */ new Date()).toISOString()})
522
+ `
523
+ );
524
+ this.sendHeartbeat();
525
+ void this.reconnectToSession();
526
+ });
527
+ this.socket.io.on("reconnect_attempt", () => {
528
+ });
529
+ });
530
+ }
531
+ disconnect() {
532
+ this.stopProactiveTokenRefresh();
533
+ this.clearSocketRecycle();
534
+ this.stopHeartbeatWorker();
535
+ void this.flushEvents();
536
+ if (this.socket) {
537
+ this.socket.io.reconnection(false);
538
+ this.socket.removeAllListeners();
539
+ this.socket.disconnect();
540
+ this.socket = null;
541
+ }
542
+ }
543
+ // ── Reconnect with retry ────────────────────────────────────────────
544
+ //
545
+ // Socket.IO already retries the transport forever. This higher-level helper
546
+ // re-issues the `connectAgent` RPC after a successful reconnect to re-join
547
+ // the session room and drain pending messages. We retry indefinitely with a
548
+ // capped exponential backoff — a stranded codespace with a missing agent is
549
+ // worse than a long-running reconnect loop, and a transient API outage
550
+ // shouldn't kill the agent process.
551
+ static RECONNECT_BASE_DELAY_MS = 2e3;
552
+ static RECONNECT_MAX_DELAY_MS = 6e4;
553
+ static RECONNECT_STATUS_EVERY_N = 3;
554
+ isReconnecting = false;
555
+ reconnectingAfterServerDisconnect = false;
556
+ /** Capped exponential backoff (2s, 4s, 8s, 16s, 32s, then 60s steady) shared
557
+ * by both reconnect loops (connectAgent-RPC and server-disconnect). */
558
+ static backoffDelayMs(attempt) {
559
+ return Math.min(
560
+ _AgentConnection.RECONNECT_BASE_DELAY_MS * 2 ** Math.min(attempt - 1, 5),
561
+ _AgentConnection.RECONNECT_MAX_DELAY_MS
562
+ );
563
+ }
564
+ /** Sleep `ms`, unref'd so it never holds the process open on its own. */
565
+ static delay(ms) {
566
+ return new Promise((resolve) => {
567
+ const timer = setTimeout(resolve, ms);
568
+ timer.unref?.();
569
+ });
570
+ }
571
+ /**
572
+ * Invoked after every successful session reconnect (the `connectAgent` RPC
573
+ * re-established the session room). The runner uses this to force a TUI
574
+ * repaint: the reconnect may have landed on a different/restarted API
575
+ * process whose PTY scrollback ring is empty, and a quiet terminal would
576
+ * otherwise never re-seed it.
577
+ */
578
+ onReconnected;
579
+ async reconnectToSession() {
580
+ if (this.isReconnecting) return;
581
+ this.isReconnecting = true;
582
+ try {
583
+ let attempt = 0;
584
+ while (this.socket) {
585
+ attempt++;
586
+ try {
587
+ const { pendingMessages } = await this.call("connectAgent", {
588
+ sessionId: this.config.sessionId
589
+ });
590
+ this.drainPendingMessages(pendingMessages);
591
+ process.stderr.write(
592
+ `[conveyor-agent] Reconnected to session successfully (attempts: ${attempt})
593
+ `
594
+ );
595
+ if (this.lastEmittedStatus && this.lastEmittedStatus !== this.lastReportedStatus) {
596
+ const status = this.lastEmittedStatus;
597
+ void this.call("reportAgentStatus", {
598
+ sessionId: this.config.sessionId,
599
+ status
600
+ }).then(() => {
601
+ this.lastReportedStatus = status;
602
+ }).catch(() => {
603
+ });
604
+ }
605
+ this.sendEvent({
606
+ type: "agent_runner_status",
607
+ reason: "reconnected",
608
+ attempts: attempt
609
+ });
610
+ try {
611
+ this.onReconnected?.();
612
+ } catch {
613
+ }
614
+ return;
615
+ } catch (err) {
616
+ const errMsg = err instanceof Error ? err.message : String(err);
617
+ const delayMs = _AgentConnection.backoffDelayMs(attempt);
618
+ process.stderr.write(
619
+ `[conveyor-agent] connectAgent failed (attempt ${attempt}): ${errMsg} \u2014 retrying in ${delayMs / 1e3}s
620
+ `
621
+ );
622
+ if (this.looksLikeAuthError(errMsg)) {
623
+ void this.refreshTaskTokenFromBootstrap().catch(() => {
624
+ });
625
+ }
626
+ if (attempt % _AgentConnection.RECONNECT_STATUS_EVERY_N === 0) {
627
+ this.sendEvent({
628
+ type: "agent_runner_status",
629
+ reason: "reconnecting",
630
+ attempt
631
+ });
632
+ }
633
+ await _AgentConnection.delay(delayMs);
634
+ }
635
+ }
636
+ } finally {
637
+ this.isReconnecting = false;
638
+ }
639
+ }
640
+ /**
641
+ * Drive a bounded reconnect after a server-initiated disconnect. Loops until
642
+ * the socket reconnects or is torn down, nudging socket.connect() on each
643
+ * pass with a capped exponential backoff. A token refresh is attempted every
644
+ * pass (rate-limited to once/60s inside refreshTaskTokenFromBootstrap) but
645
+ * its result NEVER gates the reconnect — the socket must recover even when
646
+ * there is no fresh token to apply.
647
+ */
648
+ scheduleReconnectAfterServerDisconnect() {
649
+ if (this.reconnectingAfterServerDisconnect) return;
650
+ this.reconnectingAfterServerDisconnect = true;
651
+ void this.reconnectAfterServerDisconnect().finally(() => {
652
+ this.reconnectingAfterServerDisconnect = false;
653
+ });
654
+ }
655
+ async reconnectAfterServerDisconnect() {
656
+ let attempt = 0;
657
+ while (this.socket && !this.socket.connected) {
658
+ attempt++;
659
+ try {
660
+ await this.refreshTaskTokenFromBootstrap();
661
+ } catch {
662
+ }
663
+ const socket = this.socket;
664
+ if (!socket || socket.connected) return;
665
+ socket.connect();
666
+ try {
667
+ await this.waitForConnected(
668
+ socket,
669
+ _AgentConnection.CALL_CONNECT_WAIT_MS,
670
+ "server-disconnect-reconnect"
671
+ );
672
+ this.sendHeartbeat();
673
+ void this.reconnectToSession();
674
+ return;
675
+ } catch {
676
+ const delayMs = _AgentConnection.backoffDelayMs(attempt);
677
+ process.stderr.write(
678
+ `[conveyor-agent] server-disconnect reconnect attempt ${attempt} did not connect within ${_AgentConnection.CALL_CONNECT_WAIT_MS / 1e3}s \u2014 retrying in ${delayMs / 1e3}s
679
+ `
680
+ );
681
+ await _AgentConnection.delay(delayMs);
682
+ }
683
+ }
684
+ }
685
+ looksLikeAuthError(message) {
686
+ return /unauthor|forbid|auth|token|session (?:not found|expired|invalid)|invalid session/i.test(
687
+ message
688
+ );
689
+ }
690
+ // ── Proactive task-token refresh ────────────────────────────────────────
691
+ //
692
+ // Socket.IO only re-presents the taskToken on a (re)connect handshake, and
693
+ // the server only re-validates the JWT then. So a token that expires while
694
+ // the socket stays connected goes unnoticed until the next RPC fails. Re-mint
695
+ // periodically from the bootstrap endpoint — refreshFromBootstrap() updates
696
+ // both this.config.taskToken and socket.auth.taskToken, so any later
697
+ // reconnect carries a fresh token. No-ops for project mode / missing
698
+ // codespace env, and is rate-limited to once/60s inside refreshFromBootstrap.
699
+ startProactiveTokenRefresh() {
700
+ if (this.tokenRefreshTimer) return;
701
+ this.tokenRefreshTimer = setInterval(() => {
702
+ void this.refreshTaskTokenFromBootstrap().catch(() => {
703
+ });
704
+ }, TOKEN_REFRESH_INTERVAL_MS);
705
+ this.tokenRefreshTimer.unref?.();
706
+ }
707
+ stopProactiveTokenRefresh() {
708
+ if (this.tokenRefreshTimer) {
709
+ clearInterval(this.tokenRefreshTimer);
710
+ this.tokenRefreshTimer = null;
711
+ }
712
+ }
713
+ drainPendingMessages(messages) {
714
+ for (const msg of messages) {
715
+ if (!msg.content) continue;
716
+ if (this.messageCallback) {
717
+ this.messageCallback({ content: msg.content, userId: msg.userId });
718
+ } else {
719
+ this.earlyMessages.push({ content: msg.content, userId: msg.userId });
720
+ }
721
+ }
722
+ }
723
+ // ── Callback registration with early-buffer draining ───────────────
724
+ onMessage(callback) {
725
+ this.messageCallback = callback;
726
+ for (const msg of this.earlyMessages) callback(msg);
727
+ this.earlyMessages = [];
728
+ }
729
+ onStop(callback) {
730
+ this.stopCallback = callback;
731
+ if (this.earlyStop) {
732
+ callback();
733
+ this.earlyStop = false;
734
+ }
735
+ }
736
+ onSoftStop(callback) {
737
+ this.softStopCallback = callback;
738
+ if (this.earlySoftStop) {
739
+ callback();
740
+ this.earlySoftStop = false;
741
+ }
742
+ }
743
+ onModeChange(callback) {
744
+ this.modeChangeCallback = callback;
745
+ for (const data of this.earlyModeChanges) callback(data);
746
+ this.earlyModeChanges = [];
747
+ }
748
+ onApiKeyUpdate(callback) {
749
+ this.apiKeyUpdateCallback = callback;
750
+ }
751
+ onPullBranch(callback) {
752
+ this.pullBranchCallback = callback;
753
+ for (const data of this.earlyPullBranches) callback(data);
754
+ this.earlyPullBranches = [];
755
+ }
756
+ onSpawnReview(callback) {
757
+ this.spawnReviewCallback = callback;
758
+ for (const data of this.earlySpawnReviews) callback(data);
759
+ this.earlySpawnReviews = [];
760
+ }
761
+ /** Mirror of onSpawnReview for the Builder handoff. Drains the early buffer
762
+ * so a Build pressed during boot is not lost. */
763
+ onSpawnBuilder(callback) {
764
+ this.spawnBuilderCallback = callback;
765
+ for (const data of this.earlySpawnBuilders) callback(data);
766
+ this.earlySpawnBuilders = [];
767
+ }
768
+ /**
769
+ * Report that a same-pod review child failed to spawn (fire-and-forget).
770
+ * The server Ends the orphaned review session and falls back to a dedicated
771
+ * review pod. sessionId is OUR (builder) session — the task-identity guard runs on
772
+ * it; the review session is identified separately.
773
+ */
774
+ reportReviewSpawnFailure(reviewSessionId, error) {
775
+ if (!this.socket) return;
776
+ void this.call("reportReviewSpawnFailure", {
777
+ sessionId: this.config.sessionId,
778
+ reviewSessionId,
779
+ ...error ? { error: error.slice(0, 2e3) } : {}
780
+ }).catch(() => {
781
+ });
782
+ }
783
+ /**
784
+ * Report that this (planner) pod could not spawn the Builder child, so the
785
+ * server can End the orphaned build session and reopen the card instead of
786
+ * leaving it InProgress with a Builder tab that never appears.
787
+ *
788
+ * sessionId is OUR (planner) session — the task-identity guard runs on it;
789
+ * the build session is identified separately.
790
+ */
791
+ reportBuilderSpawnFailure(buildSessionId, error) {
792
+ if (!this.socket) return;
793
+ void this.call("reportBuilderSpawnFailure", {
794
+ sessionId: this.config.sessionId,
795
+ buildSessionId,
796
+ ...error ? { error: error.slice(0, 2e3) } : {}
797
+ }).catch(() => {
798
+ });
799
+ }
800
+ /**
801
+ * Report that this pod's git credential is dead and refreshing did not fix
802
+ * it (fire-and-forget).
803
+ *
804
+ * Purely diagnostic. Until this existed a pod could lose git entirely and
805
+ * leave no server-side trace at all — the refresh RPC succeeded every time,
806
+ * so the failure was visible only in pod stderr, which is why it took two
807
+ * investigations to attribute. `tokenShape` describes the served credential
808
+ * (length, prefix class, mtime) and NEVER carries its value.
809
+ */
810
+ reportCredentialFailure(details) {
811
+ if (!this.socket) return;
812
+ void this.call("reportCredentialFailure", {
813
+ sessionId: this.config.sessionId,
814
+ ...details.error ? { error: details.error.slice(0, 2e3) } : {},
815
+ ...details.tokenShape ? { tokenShape: details.tokenShape.slice(0, 500) } : {},
816
+ ...details.healed === void 0 ? {} : { healed: details.healed }
817
+ }).catch(() => {
818
+ });
819
+ }
820
+ /**
821
+ * Ask the server to destroy and recreate this pod (fire-and-forget). The
822
+ * agent calls this only when it has proven it cannot recover in place — the
823
+ * shared `~/.claude` GCS FUSE mount is dead and no in-container action can
824
+ * remount it. The server rate-limits the recycle and posts `reason` to the
825
+ * card; old servers that don't know the method reject harmlessly, leaving
826
+ * today's behavior (a failed turn with a chat warning).
827
+ */
828
+ requestWorkspaceRecycle(reason) {
829
+ if (!this.socket) return;
830
+ void this.call("requestWorkspaceRecycle", {
831
+ sessionId: this.config.sessionId,
832
+ reason: reason.slice(0, 2e3)
833
+ }).catch(() => {
834
+ });
835
+ }
836
+ onSpawnTui(callback) {
837
+ this.spawnTuiCallback = callback;
838
+ for (const data of this.earlySpawnTuis) callback(data);
839
+ this.earlySpawnTuis = [];
840
+ }
841
+ /** Register the on-demand usage-refresh handler; drains an early-buffered
842
+ * `session:probeUsage` that arrived before the runner was ready. */
843
+ onProbeUsage(callback) {
844
+ this.probeUsageCallback = callback;
845
+ if (this.earlyProbeUsage) {
846
+ this.earlyProbeUsage = false;
847
+ callback();
848
+ }
849
+ }
850
+ /**
851
+ * Report that a same-pod TUI/shell child failed to spawn (fire-and-forget).
852
+ * The server Ends the orphaned session — no fallback pod (unlike review).
853
+ * sessionId is OUR (builder) session — the task-identity guard runs on it.
854
+ */
855
+ reportSessionSpawnFailure(spawnedSessionId, error) {
856
+ if (!this.socket) return;
857
+ void this.call("reportSessionSpawnFailure", {
858
+ sessionId: this.config.sessionId,
859
+ spawnedSessionId,
860
+ ...error ? { error: error.slice(0, 2e3) } : {}
861
+ }).catch(() => {
862
+ });
863
+ }
864
+ /** Register the restart handler, draining a `session:runStartCommand` that
865
+ * arrived before the supervisor was ready. Collapsed to one drain: two
866
+ * clicks during boot should produce one restart, not two competing ones. */
867
+ onRunStartCommand(callback) {
868
+ this.runStartCommandCallback = callback;
869
+ if (this.earlyRunStartCommand) {
870
+ this.earlyRunStartCommand = false;
871
+ callback();
872
+ }
873
+ }
874
+ // ── PTY relay (S5 Connected-TUI terminal) ──────────────────────────
875
+ /**
876
+ * Forward a raw chunk of terminal output to the S2 relay (fire-and-forget).
877
+ * The first chunk creates the server-side scrollback ring, which is what
878
+ * surfaces the terminal in the UI. `dims` seed/refresh the ring geometry.
879
+ */
880
+ sendPtyOutput(data, dims) {
881
+ if (!this.socket) return;
882
+ void this.call("ptyOutput", {
883
+ sessionId: this.config.sessionId,
884
+ data,
885
+ ...dims ? { cols: dims.cols, rows: dims.rows } : {}
886
+ }).catch(() => {
887
+ });
888
+ }
889
+ /**
890
+ * Forward one compact chat-proxy event derived from the transcript JSONL to
891
+ * the relay (fire-and-forget). Feeds the experimental chat PTY proxy ring.
892
+ * Old servers that don't know the method reject harmlessly.
893
+ */
894
+ sendPtyChatEvent(event) {
895
+ if (!this.socket) return;
896
+ void this.call("ptyChatEvent", {
897
+ sessionId: this.config.sessionId,
898
+ event
899
+ }).catch(() => {
900
+ });
901
+ }
902
+ /**
903
+ * Report that the interactive CLI process for this session has died and no
904
+ * respawn is imminent (fire-and-forget). The server clears the scrollback
905
+ * ring and broadcasts pty:ended so clients hide the Connected-TUI tab. Old
906
+ * servers that don't know the method reject harmlessly.
907
+ */
908
+ sendPtyEnded() {
909
+ if (!this.socket) return;
910
+ void this.call("ptyEnded", { sessionId: this.config.sessionId }).catch(() => {
911
+ });
912
+ }
913
+ /**
914
+ * Report the port this pod's in-pod PTY stream server bound to, or null when
915
+ * it stopped (fire-and-forget). The server persists it so a viewer can be
916
+ * handed a port-scoped tunnel URL and stream the TUI straight from the pod.
917
+ * Old servers that don't know the method reject harmlessly — the session then
918
+ * just stays on the relay transport.
919
+ */
920
+ reportPtyStream(port) {
921
+ if (!this.socket) return;
922
+ void this.call("reportPtyStream", {
923
+ sessionId: this.config.sessionId,
924
+ port
925
+ }).catch(() => {
926
+ });
927
+ }
928
+ /** Subscribe to relayed keystrokes. Returns an unsubscribe fn. */
929
+ onPtyInput(handler) {
930
+ this.ptyInputCallback = handler;
931
+ return () => {
932
+ if (this.ptyInputCallback === handler) this.ptyInputCallback = null;
933
+ };
934
+ }
935
+ /** Subscribe to relayed (reconciled) terminal resizes. Returns an unsubscribe fn. */
936
+ onPtyResize(handler) {
937
+ this.ptyResizeCallback = handler;
938
+ return () => {
939
+ if (this.ptyResizeCallback === handler) this.ptyResizeCallback = null;
940
+ };
941
+ }
942
+ // ── Convenience methods (thin wrappers around call / emit) ─────────
943
+ async emitStatus(status, reason, questionText) {
944
+ this.lastEmittedStatus = status;
945
+ await this.flushEvents();
946
+ const payload = {
947
+ sessionId: this.config.sessionId,
948
+ status,
949
+ ...reason ? { reason } : {},
950
+ // Only sent with a pending TUI questionnaire (reason "user_question") so
951
+ // the server can surface the real question text in the notification.
952
+ ...questionText ? { questionText } : {}
953
+ };
954
+ const AWAIT_STATUSES = ["idle", "waiting_for_input", "connected"];
955
+ if (AWAIT_STATUSES.includes(status)) {
956
+ try {
957
+ await this.call("reportAgentStatus", payload);
958
+ this.lastReportedStatus = status;
959
+ } catch {
960
+ }
961
+ } else {
962
+ void this.call("reportAgentStatus", payload).then(() => {
963
+ this.lastReportedStatus = status;
964
+ }).catch(() => {
965
+ });
966
+ }
967
+ }
968
+ postChatMessage(content, milestone) {
969
+ if (!this.socket) return;
970
+ if (this.suppressIfDuplicate(content)) return;
971
+ void this.call("postAgentMessage", {
972
+ sessionId: this.config.sessionId,
973
+ content,
974
+ milestone
975
+ }).catch(() => {
976
+ });
977
+ }
978
+ // Awaitable variant of postChatMessage for callers that need to guarantee
979
+ // the message is acknowledged by the server before proceeding (e.g. before
980
+ // aborting the session). Dedup still applies; a suppressed message resolves
981
+ // immediately without hitting the wire.
982
+ async postChatMessageAwait(content, milestone) {
983
+ if (!this.socket) return;
984
+ if (this.suppressIfDuplicate(content)) return;
985
+ try {
986
+ await this.call("postAgentMessage", {
987
+ sessionId: this.config.sessionId,
988
+ content,
989
+ milestone
990
+ });
991
+ } catch (err) {
992
+ process.stderr.write(
993
+ `[conveyor-agent] postChatMessageAwait failed: ${err instanceof Error ? err.message : String(err)}
994
+ `
995
+ );
996
+ }
997
+ }
998
+ suppressIfDuplicate(content) {
999
+ const d = this.checkAndTrackDuplicate(content);
1000
+ if (!d.duplicate) return false;
1001
+ process.stderr.write(
1002
+ `[dedup] Suppressed near-duplicate (matched: "${d.matchedMessagePreview}")
1003
+ `
1004
+ );
1005
+ return true;
1006
+ }
1007
+ // Exposed so `post_to_chat` can surface suppression back to the agent.
1008
+ checkAndTrackDuplicate(content) {
1009
+ const now = Date.now();
1010
+ this.recentMessages = this.recentMessages.filter(
1011
+ (m) => now - m.timestamp < _AgentConnection.DEDUP_WINDOW_MS
1012
+ );
1013
+ const words = new Set(
1014
+ content.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/).filter((w) => w.length >= 3)
1015
+ );
1016
+ if (words.size === 0) return { duplicate: false };
1017
+ for (const recent of this.recentMessages) {
1018
+ let intersection = 0;
1019
+ for (const w of words) if (recent.words.has(w)) intersection++;
1020
+ const union = (/* @__PURE__ */ new Set([...words, ...recent.words])).size;
1021
+ if (union > 0 && intersection / union > _AgentConnection.DEDUP_SIMILARITY_THRESHOLD) {
1022
+ return { duplicate: true, matchedMessagePreview: recent.preview };
1023
+ }
1024
+ }
1025
+ const max = _AgentConnection.DEDUP_PREVIEW_LIMIT;
1026
+ const preview = content.length > max ? content.slice(0, max) + "\u2026" : content;
1027
+ this.recentMessages.push({ words, timestamp: now, preview });
1028
+ if (this.recentMessages.length > 3) this.recentMessages.shift();
1029
+ return { duplicate: false };
1030
+ }
1031
+ /**
1032
+ * @param loopStatus overrides the status derived from the last emitted
1033
+ * runner status. SessionRunner passes it so an idle runner that still has
1034
+ * background work outstanding in the pod beats as `waiting` (→ `active` on
1035
+ * the wire) rather than `idle`, which would let the workspace activity
1036
+ * clock expire mid-gate. See connection/loop-lag.ts `heartbeatStatusFor`.
1037
+ *
1038
+ * Without an override the status comes from `loopStatusForRunnerStatus`, the
1039
+ * same total classifier SessionRunner uses, so both paths agree. This used to
1040
+ * be a partial map covering 5 of the 11 `AgentRunnerStatus` values with a
1041
+ * `?? "active"` fallback, which meant a parked runner (`waiting_for_input`,
1042
+ * `finished`, `error`, `stopping`, `disconnected`) beat as ACTIVE on every
1043
+ * no-arg call site — the reconnect paths below, and the shell/project/adhoc
1044
+ * runners, which never pass a loop status at all. That renewed the workspace
1045
+ * activity clock for an agent doing nothing, so the card stayed "active" and
1046
+ * its pod stayed up long past the project's inactivity window.
1047
+ */
1048
+ sendHeartbeat(loopLagMs, loopStatus) {
1049
+ if (!this.socket) return;
1050
+ const heartbeatStatus = heartbeatStatusFor(
1051
+ loopStatus ?? loopStatusForRunnerStatus(this.lastEmittedStatus)
1052
+ );
1053
+ void this.call("heartbeat", {
1054
+ sessionId: this.config.sessionId,
1055
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1056
+ status: heartbeatStatus,
1057
+ ...loopLagMs !== void 0 && loopLagMs > 0 ? { loopLagMs: Math.round(loopLagMs) } : {}
1058
+ }).catch(() => {
1059
+ });
1060
+ }
1061
+ // ── Starvation-proof heartbeat worker ────────────────────────────────
1062
+ //
1063
+ // A worker thread with its own event loop + Socket.IO connection keeps the
1064
+ // v3 session lease renewed even when the MAIN loop is stalled (the failure
1065
+ // mode where a heavy gate got the session declared stranded and restarted
1066
+ // mid-run). Best-effort by design: any spawn/runtime failure just degrades
1067
+ // heartbeats to main-loop-only. See heartbeat-worker.ts for the policy.
1068
+ heartbeatWorker = null;
1069
+ startHeartbeatWorker(sharedBuffer, intervalMs = 3e4) {
1070
+ if (this.heartbeatWorker) return;
1071
+ try {
1072
+ const workerUrl = new URL("./heartbeat-worker.js", import.meta.url);
1073
+ if (!existsSync(fileURLToPath(workerUrl))) {
1074
+ process.stderr.write(
1075
+ "[conveyor-agent] heartbeat worker bundle not found \u2014 main-loop heartbeat only\n"
1076
+ );
1077
+ return;
1078
+ }
1079
+ const worker = new Worker(workerUrl, {
1080
+ workerData: {
1081
+ apiUrl: this.config.apiUrl,
1082
+ taskToken: this.config.taskToken,
1083
+ sessionId: this.config.sessionId,
1084
+ runnerMode: this.config.runnerMode ?? "task",
1085
+ sharedBuffer,
1086
+ intervalMs
1087
+ }
1088
+ });
1089
+ worker.unref();
1090
+ worker.on("error", (err) => {
1091
+ const message = err instanceof Error ? err.message : String(err);
1092
+ process.stderr.write(`[conveyor-agent] heartbeat worker error: ${message}
1093
+ `);
1094
+ this.heartbeatWorker = null;
1095
+ });
1096
+ worker.on("exit", (code) => {
1097
+ if (code !== 0) {
1098
+ process.stderr.write(`[conveyor-agent] heartbeat worker exited (code ${code})
1099
+ `);
1100
+ }
1101
+ this.heartbeatWorker = null;
1102
+ });
1103
+ this.heartbeatWorker = worker;
1104
+ process.stderr.write("[conveyor-agent] heartbeat worker started\n");
1105
+ } catch (err) {
1106
+ process.stderr.write(
1107
+ `[conveyor-agent] heartbeat worker failed to start: ${err instanceof Error ? err.message : String(err)}
1108
+ `
1109
+ );
1110
+ this.heartbeatWorker = null;
1111
+ }
1112
+ }
1113
+ stopHeartbeatWorker() {
1114
+ const worker = this.heartbeatWorker;
1115
+ this.heartbeatWorker = null;
1116
+ if (worker) void worker.terminate();
1117
+ }
1118
+ emitModeChanged(agentMode) {
1119
+ this.sendEvent({ type: "mode_changed", agentMode });
1120
+ }
1121
+ async updateTaskFields(fields) {
1122
+ if (!this.socket) return { ok: false, error: "socket not connected" };
1123
+ try {
1124
+ await this.call("updateTaskFields", { sessionId: this.config.sessionId, ...fields });
1125
+ return { ok: true };
1126
+ } catch (err) {
1127
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1128
+ }
1129
+ }
1130
+ storeSessionId(sdkSessionId) {
1131
+ void this.call("storeSessionId", { sessionId: this.config.sessionId, sdkSessionId }).catch(
1132
+ () => {
1133
+ }
1134
+ );
1135
+ }
1136
+ /** Report the full current set of runtime-discovered listening ports.
1137
+ * Throws on failure so the PortDiscovery poller can retry on its next
1138
+ * tick (a swallowed error here would silently drop the delta). */
1139
+ async reportDiscoveredPorts(ports) {
1140
+ await this.call("reportDiscoveredPorts", { sessionId: this.config.sessionId, ports });
1141
+ }
1142
+ /** Boot-milestone report over the socket — the codespace-parity fallback
1143
+ * for the GKE pod bootstrap-token route. Fire-and-forget: a failed report
1144
+ * must never delay or fail the boot path. */
1145
+ reportBootMilestone(key) {
1146
+ void this.call("reportBootMilestone", { sessionId: this.config.sessionId, key }).catch(
1147
+ () => {
1148
+ }
1149
+ );
1150
+ }
1151
+ // ── Typing indicators ───────────────────────────────────────────────
1152
+ sendTypingStart() {
1153
+ this.sendEvent({ type: "agent_typing_start" });
1154
+ }
1155
+ sendTypingStop() {
1156
+ this.sendEvent({ type: "agent_typing_stop" });
1157
+ }
1158
+ // ── RPC convenience wrappers (v6 compat, will migrate to call()) ───
1159
+ emitRateLimitPause(resetsAt) {
1160
+ this.sendEvent({ type: "rate_limit_update", resetsAt });
1161
+ }
1162
+ updateStatus(status) {
1163
+ this.emitStatus(status);
1164
+ }
1165
+ /**
1166
+ * The session's key hit a hard usage cap — ask the server to stamp it
1167
+ * limited and hand back the best remaining key's credential env (or a
1168
+ * requeue confirmation when none is left). Awaited: the caller swaps
1169
+ * credentials and resumes on success, so it needs the real response.
1170
+ */
1171
+ async cycleCodingAgentKey(rateLimitType, resetsAt) {
1172
+ return await this.call("cycleCodingAgentKey", {
1173
+ sessionId: this.config.sessionId,
1174
+ rateLimitType,
1175
+ ...resetsAt ? { resetsAt } : {}
1176
+ });
1177
+ }
1178
+ // ── Question handling ──────────────────────────────────────────────
1179
+ async askUserQuestion(questions) {
1180
+ const questionText = questions.map(
1181
+ (q) => `**${q.header}**
1182
+ ${q.question}${q.options.length ? "\n" + q.options.map((o) => `- ${o.label}: ${o.description}`).join("\n") : ""}`
1183
+ ).join("\n\n");
1184
+ const requestId = crypto.randomUUID();
1185
+ const roomEventPromise = new Promise((resolve) => {
1186
+ this.pendingAnswerResolvers.set(requestId, resolve);
1187
+ });
1188
+ const rpcPromise = this.call("askUserQuestion", {
1189
+ sessionId: this.config.sessionId,
1190
+ question: questionText,
1191
+ requestId,
1192
+ questions
1193
+ }).then((res) => res.answers);
1194
+ try {
1195
+ return await Promise.race([rpcPromise, roomEventPromise]);
1196
+ } finally {
1197
+ this.pendingAnswerResolvers.delete(requestId);
1198
+ }
1199
+ }
1200
+ // ── Typed service method wrappers ───────────────────────────────────
1201
+ getTaskProperties() {
1202
+ return this.call("getTaskProperties", { sessionId: this.config.sessionId });
1203
+ }
1204
+ triggerIdentification() {
1205
+ return this.call("triggerIdentification", { sessionId: this.config.sessionId });
1206
+ }
1207
+ handoffToImplementer(payload) {
1208
+ return this.call("handoffToImplementer", {
1209
+ sessionId: this.config.sessionId,
1210
+ ...payload
1211
+ });
1212
+ }
1213
+ async refreshAuthToken() {
1214
+ const result = await this.refreshFromBootstrap();
1215
+ return result.refreshedClaude;
1216
+ }
1217
+ /**
1218
+ * Refresh the in-process `CONVEYOR_TASK_TOKEN` from the bootstrap endpoint.
1219
+ * Returns true if a new token was applied. Rate-limited locally to once per
1220
+ * 60s so a tight auth-rejected loop can't hammer the bootstrap endpoint —
1221
+ * the server enforces the same window via `lastBootstrapAt`.
1222
+ */
1223
+ lastTaskTokenRefreshAt = 0;
1224
+ async refreshTaskTokenFromBootstrap() {
1225
+ const result = await this.refreshFromBootstrap();
1226
+ return result.refreshedTaskToken;
1227
+ }
1228
+ refreshFromBootstrap() {
1229
+ const none = Promise.resolve({ refreshedClaude: false, refreshedTaskToken: false });
1230
+ const podBootstrapToken = process.env.POD_BOOTSTRAP_TOKEN;
1231
+ const codespaceName = process.env.CODESPACE_NAME;
1232
+ const apiUrl = this.config.apiUrl;
1233
+ if (!apiUrl || !podBootstrapToken && !codespaceName) {
1234
+ return none;
1235
+ }
1236
+ const now = Date.now();
1237
+ if (now - this.lastTaskTokenRefreshAt < 6e4) {
1238
+ return none;
1239
+ }
1240
+ this.lastTaskTokenRefreshAt = now;
1241
+ if (podBootstrapToken) {
1242
+ return this.refreshFromV3Bootstrap(apiUrl, podBootstrapToken);
1243
+ }
1244
+ if (!codespaceName) return none;
1245
+ return this.refreshFromCodespaceBootstrap(apiUrl, codespaceName);
1246
+ }
1247
+ /** Legacy GitHub Codespaces refresh path — keys on instance name. */
1248
+ async refreshFromCodespaceBootstrap(apiUrl, codespaceName) {
1249
+ const bootstrapToken = process.env.CONVEYOR_BOOTSTRAP_TOKEN;
1250
+ const result = await fetchBootstrap({
1251
+ apiUrl,
1252
+ instanceName: codespaceName,
1253
+ bootstrapToken
1254
+ // Do not retry on http errors during a runtime refresh — a 401/403
1255
+ // means the token is consumed / session terminal and retrying won't
1256
+ // help. Network/timeout still retry inside fetchBootstrap.
1257
+ });
1258
+ if (!result.ok) {
1259
+ logger.warn("bootstrap refresh abandoned \u2014 pod credentials will go stale", {
1260
+ path: "codespace",
1261
+ reason: result.reason,
1262
+ status: result.status,
1263
+ attempts: result.attempts,
1264
+ detail: result.detail
1265
+ });
1266
+ return { refreshedClaude: false, refreshedTaskToken: false };
1267
+ }
1268
+ const previousTaskToken = process.env.CONVEYOR_TASK_TOKEN;
1269
+ applyBootstrapToEnv(result.config);
1270
+ const env = result.config.envVars ?? {};
1271
+ syncBundleGithubToken(env.CONVEYOR_GITHUB_TOKEN ?? env.GH_TOKEN ?? env.GITHUB_TOKEN);
1272
+ const refreshedTaskToken = result.config.mode !== "project" && Boolean(result.config.taskToken) && result.config.taskToken !== previousTaskToken;
1273
+ if (refreshedTaskToken && result.config.taskToken) {
1274
+ this.config.taskToken = result.config.taskToken;
1275
+ if (this.socket) {
1276
+ const auth = this.socket.auth;
1277
+ if (auth && typeof auth === "object") {
1278
+ auth.taskToken = result.config.taskToken;
1279
+ }
1280
+ }
1281
+ this.heartbeatWorker?.postMessage({ taskToken: result.config.taskToken });
1282
+ }
1283
+ const refreshedClaude = Boolean(result.config.envVars?.CLAUDE_CODE_OAUTH_TOKEN);
1284
+ return { refreshedClaude, refreshedTaskToken };
1285
+ }
1286
+ /**
1287
+ * v3 refresh: re-fetch the full bootstrap bundle from the pod's bound v3
1288
+ * route and swap the credentials in place. The GitHub installation token
1289
+ * dies at ~1h and the sessionJwt at 24h; re-polling the bootstrap GET with
1290
+ * the same pod token is the designed refresh mechanism.
1291
+ */
1292
+ async refreshFromV3Bootstrap(apiUrl, bootstrapToken) {
1293
+ const bundle = await this.pollBundleWithRateLimitRetry(apiUrl, bootstrapToken);
1294
+ if (!bundle) {
1295
+ return { refreshedClaude: false, refreshedTaskToken: false };
1296
+ }
1297
+ const previousTaskToken = process.env.CONVEYOR_TASK_TOKEN;
1298
+ for (const [key, value] of Object.entries(bundle.envVars ?? {})) {
1299
+ process.env[key] = value;
1300
+ }
1301
+ if (bundle.githubToken) {
1302
+ process.env.CONVEYOR_GITHUB_TOKEN = bundle.githubToken;
1303
+ this.applyBundleCredentialFiles(bundle, previousTaskToken);
1304
+ }
1305
+ if (bundle.anthropicKey) process.env.ANTHROPIC_API_KEY = bundle.anthropicKey;
1306
+ if (bundle.gcpToken) process.env.CLOUDSDK_AUTH_ACCESS_TOKEN = bundle.gcpToken;
1307
+ const refreshedTaskToken = Boolean(bundle.sessionJwt) && bundle.sessionJwt !== previousTaskToken;
1308
+ if (refreshedTaskToken) {
1309
+ process.env.CONVEYOR_TASK_TOKEN = bundle.sessionJwt;
1310
+ this.config.taskToken = bundle.sessionJwt;
1311
+ if (this.socket) {
1312
+ const auth = this.socket.auth;
1313
+ if (auth && typeof auth === "object") {
1314
+ auth.taskToken = bundle.sessionJwt;
1315
+ }
1316
+ }
1317
+ this.heartbeatWorker?.postMessage({ taskToken: bundle.sessionJwt });
1318
+ }
1319
+ const refreshedClaude = Boolean(bundle.envVars?.CLAUDE_CODE_OAUTH_TOKEN);
1320
+ return { refreshedClaude, refreshedTaskToken };
1321
+ }
1322
+ /**
1323
+ * Write the bundle's GitHub token to the shared credential files — unless the
1324
+ * bundle belongs to another session.
1325
+ *
1326
+ * The bootstrap GET is keyed by the POD, so on a pod also hosting a same-pod
1327
+ * review it can resolve to the reader session, whose token is read-only.
1328
+ * Writing that over the shared files silently downgrades the builder's push
1329
+ * credential. Our own taskToken carries the same claims, so it is what we
1330
+ * compare against.
1331
+ *
1332
+ * The legitimate case this path exists for — our own session's bundle
1333
+ * refreshing the token when the RPC is failing — is unaffected.
1334
+ */
1335
+ applyBundleCredentialFiles(bundle, previousTaskToken) {
1336
+ const self = readBundleIdentity(previousTaskToken);
1337
+ const result = applyBundleGithubToken(bundle, {
1338
+ sessionId: this.config.sessionId || self.sessionId,
1339
+ ...self.role ? { role: self.role } : {}
1340
+ });
1341
+ if (!result.written && result.reason) {
1342
+ process.stderr.write(
1343
+ `[conveyor-agent] Skipped writing GitHub credential files from the bootstrap bundle: ${result.reason}
1344
+ `
1345
+ );
1346
+ }
1347
+ }
1348
+ /**
1349
+ * Poll the bootstrap bundle once (maxWaitMs 0), retrying only on a transient
1350
+ * 429 (standby-pool pods share one Cloud NAT IP against podBootstrapLimiter)
1351
+ * with a short backoff. Returns null when the refresh should be abandoned —
1352
+ * a non-429 error, or 429s past the retry budget — so the caller no-ops
1353
+ * instead of parking a RUNNING pod in a poll loop.
1354
+ */
1355
+ async pollBundleWithRateLimitRetry(apiUrl, bootstrapToken) {
1356
+ const retryDelaysMs = [1e3, 3e3];
1357
+ for (let attempt = 0; ; attempt++) {
1358
+ try {
1359
+ return await pollUntilBound({ apiUrl, bootstrapToken, maxWaitMs: 0 });
1360
+ } catch (err) {
1361
+ const isRateLimited = err instanceof PollUntilBoundHttpError && err.status === 429;
1362
+ if (!isRateLimited || attempt >= retryDelaysMs.length) {
1363
+ logger.warn("bootstrap refresh abandoned \u2014 pod credentials will go stale", {
1364
+ path: "v3",
1365
+ attempt,
1366
+ rateLimited: isRateLimited,
1367
+ error: err instanceof Error ? err.message : String(err)
1368
+ });
1369
+ return null;
1370
+ }
1371
+ await new Promise((resolve) => {
1372
+ setTimeout(resolve, retryDelaysMs[attempt]);
1373
+ });
1374
+ }
1375
+ }
1376
+ }
1377
+ // ── Event buffering ────────────────────────────────────────────────
1378
+ sendEvent(event) {
1379
+ if (!this.socket) return;
1380
+ this.enqueueEvents([{ event }], false);
1381
+ }
1382
+ /** Append (or, on `toFront`, prepend for a failed-flush re-queue) events to
1383
+ * the buffer, then cap + arm the flush timer. Single owner of the overflow
1384
+ * policy so append and re-queue can't diverge on the drop accounting. */
1385
+ enqueueEvents(entries, toFront) {
1386
+ if (toFront) this.eventBuffer.unshift(...entries);
1387
+ else this.eventBuffer.push(...entries);
1388
+ while (this.eventBuffer.length > MAX_EVENT_BUFFER) {
1389
+ this.eventBuffer.shift();
1390
+ this.droppedEventCount++;
1391
+ if (this.droppedEventCount === 1 || this.droppedEventCount % 500 === 0) {
1392
+ process.stderr.write(
1393
+ `[conveyor-agent] eventBuffer overflow \u2014 dropped ${this.droppedEventCount} event(s) (cap: ${MAX_EVENT_BUFFER})
1394
+ `
1395
+ );
1396
+ }
1397
+ }
1398
+ if (this.socket && !this.flushTimer) {
1399
+ this.flushTimer = setTimeout(() => void this.flushEvents(), EVENT_BATCH_MS);
1400
+ }
1401
+ }
1402
+ async flushEvents() {
1403
+ if (this.flushTimer) {
1404
+ clearTimeout(this.flushTimer);
1405
+ this.flushTimer = null;
1406
+ }
1407
+ if (!this.socket || this.eventBuffer.length === 0) return;
1408
+ const entries = this.eventBuffer;
1409
+ this.eventBuffer = [];
1410
+ const events = entries.map((entry) => entry.event);
1411
+ try {
1412
+ await this.call("emitAgentEvent", { sessionId: this.config.sessionId, events });
1413
+ } catch {
1414
+ this.requeueFailedEvents(entries);
1415
+ }
1416
+ }
1417
+ /** Put a failed flush's events back at the FRONT of the buffer, preserving
1418
+ * order, via the shared cap-and-arm path. */
1419
+ requeueFailedEvents(entries) {
1420
+ this.enqueueEvents(entries, true);
1421
+ }
1422
+ };
1423
+
1424
+ // src/runner/git-run.ts
1425
+ import { execFile } from "child_process";
1426
+ import { promisify } from "util";
1427
+ var execFileAsync = promisify(execFile);
1428
+ var GIT_TIMEOUT_MS = 6e4;
1429
+ var GIT_SLOW_TIMEOUT_MS = 12e4;
1430
+ var GIT_MAX_BUFFER = 16 * 1024 * 1024;
1431
+ async function git(cwd, args, timeoutMs = GIT_TIMEOUT_MS) {
1432
+ if (workbenchEnabled()) {
1433
+ try {
1434
+ const { stdout: stdout2 } = await getWorkbenchClient().execFile("git", args, {
1435
+ cwd,
1436
+ timeout: timeoutMs,
1437
+ maxBuffer: GIT_MAX_BUFFER
1438
+ });
1439
+ return stdout2.trim();
1440
+ } catch (err) {
1441
+ if (err instanceof Error && err.message.startsWith("Command timed out:")) {
1442
+ err.killed = true;
1443
+ }
1444
+ throw err;
1445
+ }
1446
+ }
1447
+ const { stdout } = await execFileAsync("git", args, {
1448
+ cwd,
1449
+ timeout: timeoutMs,
1450
+ maxBuffer: GIT_MAX_BUFFER
1451
+ });
1452
+ return stdout.toString().trim();
1453
+ }
1454
+
1455
+ // src/runner/git-credential-ops.ts
1456
+ function credentialErrorText(err) {
1457
+ const raw = err instanceof Error ? err.message : String(err);
1458
+ return raw.replace(/\/\/[^@\s]+@/g, "//***@");
1459
+ }
1460
+ async function updateRemoteCredential(cwd, credential) {
1461
+ const result = { ok: false, storeWritten: false, helperConfigured: false };
1462
+ try {
1463
+ const currentUrl = await git(cwd, ["remote", "get-url", "origin"]);
1464
+ const cloneUrl = credential.cloneUrl ?? currentUrl;
1465
+ const normalizedUrl = writeGitCredential(cwd, cloneUrl, credential);
1466
+ result.storeWritten = true;
1467
+ if (currentUrl !== normalizedUrl) {
1468
+ await git(cwd, ["remote", "set-url", "origin", normalizedUrl]);
1469
+ }
1470
+ await git(cwd, ["config", "--local", "credential.helper", gitCredentialHelper(cwd)]);
1471
+ result.helperConfigured = true;
1472
+ result.ok = true;
1473
+ } catch (err) {
1474
+ result.error = credentialErrorText(err);
1475
+ }
1476
+ return result;
1477
+ }
1478
+ async function updateRemoteToken(cwd, token) {
1479
+ const username = process.env.CONVEYOR_GIT_USERNAME || "x-access-token";
1480
+ const cloneUrl = process.env.CONVEYOR_GIT_CLONE_URL || void 0;
1481
+ const credential = await updateRemoteCredential(cwd, { username, secret: token, cloneUrl });
1482
+ process.env.CONVEYOR_GIT_SECRET = token;
1483
+ const files = syncGithubTokenFiles(token);
1484
+ return { credential, files };
1485
+ }
1486
+ async function verifyGitCredential(cwd) {
1487
+ try {
1488
+ await git(cwd, ["ls-remote", "--heads", "origin"], 3e4);
1489
+ return { ok: true, outcome: "ok" };
1490
+ } catch (err) {
1491
+ const killed = err.killed === true;
1492
+ return {
1493
+ ok: false,
1494
+ outcome: killed ? "timeout" : "denied",
1495
+ error: credentialErrorText(err)
1496
+ };
1497
+ }
1498
+ }
1499
+
1500
+ // src/runner/git-utils.ts
1501
+ import { realpathSync } from "fs";
1502
+
1503
+ // src/runner/force-fresh-cooldown.ts
1504
+ var FORCE_FRESH_COOLDOWN_MS = 30 * 60 * 1e3;
1505
+ var blockedUntil = 0;
1506
+ function forceFreshCooldownRemainingMs() {
1507
+ return Math.max(0, blockedUntil - Date.now());
1508
+ }
1509
+ function forceFreshMintBlocked() {
1510
+ return forceFreshCooldownRemainingMs() > 0;
1511
+ }
1512
+ function recordForceFreshFailure() {
1513
+ blockedUntil = Date.now() + FORCE_FRESH_COOLDOWN_MS;
1514
+ }
1515
+ function clearForceFreshCooldown() {
1516
+ blockedUntil = 0;
1517
+ }
1518
+ function forceFreshCooldownNotice() {
1519
+ const minutes = Math.ceil(forceFreshCooldownRemainingMs() / 6e4);
1520
+ return `- the force-fresh retry was SKIPPED: one already failed against this pod, so it is on a ${Math.round(FORCE_FRESH_COOLDOWN_MS / 6e4)}-minute cooldown (${minutes} min left). Re-minting cannot fix a credential the pod cannot serve.`;
1521
+ }
1522
+
1523
+ // src/runner/git-utils.ts
1524
+ async function ensureOnTaskBranch(cwd, taskBranch, baseBranch) {
1525
+ if (!taskBranch) return true;
1526
+ try {
1527
+ if (await getCurrentBranch(cwd) === taskBranch) return true;
1528
+ let existsOnOrigin = true;
1529
+ try {
1530
+ await git(cwd, [
1531
+ "fetch",
1532
+ "origin",
1533
+ `+refs/heads/${taskBranch}:refs/remotes/origin/${taskBranch}`
1534
+ ]);
1535
+ } catch (err) {
1536
+ if (String(err).includes("couldn't find remote ref")) existsOnOrigin = false;
1537
+ else throw err;
1538
+ }
1539
+ if (existsOnOrigin) {
1540
+ await git(cwd, ["checkout", "-B", taskBranch, `origin/${taskBranch}`], 3e4);
1541
+ process.stderr.write(`[conveyor-agent] Checked out task branch ${taskBranch}
1542
+ `);
1543
+ return true;
1544
+ }
1545
+ if (!baseBranch) {
1546
+ process.stderr.write(
1547
+ `[conveyor-agent] Warning: task branch ${taskBranch} missing on origin and no base branch given
1548
+ `
1549
+ );
1550
+ return false;
1551
+ }
1552
+ await git(cwd, [
1553
+ "fetch",
1554
+ "origin",
1555
+ `+refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}`
1556
+ ]);
1557
+ await git(cwd, ["checkout", "-B", taskBranch, `origin/${baseBranch}`], 3e4);
1558
+ await git(cwd, ["push", "-u", "origin", taskBranch], 3e4);
1559
+ process.stderr.write(
1560
+ `[conveyor-agent] Created task branch ${taskBranch} from origin/${baseBranch} and pushed
1561
+ `
1562
+ );
1563
+ return true;
1564
+ } catch {
1565
+ process.stderr.write(`[conveyor-agent] Warning: ensureOnTaskBranch(${taskBranch}) failed
1566
+ `);
1567
+ return false;
1568
+ }
1569
+ }
1570
+ async function hasUncommittedChanges(cwd) {
1571
+ const status = await git(cwd, ["status", "--porcelain"], GIT_SLOW_TIMEOUT_MS);
1572
+ return status.length > 0;
1573
+ }
1574
+ async function getCurrentBranch(cwd) {
1575
+ try {
1576
+ const branch = await git(cwd, ["branch", "--show-current"]);
1577
+ return branch || null;
1578
+ } catch {
1579
+ return null;
1580
+ }
1581
+ }
1582
+ async function hasUnpushedCommits(cwd) {
1583
+ try {
1584
+ const currentBranch = await getCurrentBranch(cwd);
1585
+ if (!currentBranch) return false;
1586
+ try {
1587
+ await git(cwd, ["rev-parse", `origin/${currentBranch}`]);
1588
+ } catch {
1589
+ try {
1590
+ await git(cwd, ["rev-parse", "HEAD"]);
1591
+ return true;
1592
+ } catch {
1593
+ return false;
1594
+ }
1595
+ }
1596
+ const ahead = await git(cwd, [
1597
+ "rev-list",
1598
+ "--count",
1599
+ "HEAD",
1600
+ "--not",
1601
+ `origin/${currentBranch}`
1602
+ ]);
1603
+ return parseInt(ahead, 10) > 0;
1604
+ } catch {
1605
+ return false;
1606
+ }
1607
+ }
1608
+ async function remoteMatchesLocalHead(cwd, branch) {
1609
+ try {
1610
+ const [remote, local] = await Promise.all([
1611
+ git(cwd, ["ls-remote", "origin", `refs/heads/${branch}`], GIT_SLOW_TIMEOUT_MS),
1612
+ git(cwd, ["rev-parse", "HEAD"])
1613
+ ]);
1614
+ const remoteSha = remote.split(/\s+/)[0] ?? "";
1615
+ return /^[0-9a-f]{40}$/i.test(remoteSha) && remoteSha === local.trim();
1616
+ } catch {
1617
+ return false;
1618
+ }
1619
+ }
1620
+ async function stageAndCommit(cwd, message) {
1621
+ try {
1622
+ await git(cwd, ["add", "-A"], GIT_SLOW_TIMEOUT_MS);
1623
+ if (!await hasUncommittedChanges(cwd)) return null;
1624
+ await git(cwd, ["commit", "-m", message], GIT_SLOW_TIMEOUT_MS);
1625
+ return await git(cwd, ["rev-parse", "HEAD"]);
1626
+ } catch {
1627
+ return null;
1628
+ }
1629
+ }
1630
+ function errLooksLikeAuth(err) {
1631
+ if (err.killed) return true;
1632
+ const stderr = err.stderr?.toString() ?? "";
1633
+ const stdout = err.stdout?.toString() ?? "";
1634
+ const msg = stderr || stdout || (err instanceof Error ? err.message : "");
1635
+ return /authentication|authorization|403|401|token/i.test(msg);
1636
+ }
1637
+ async function tryPush(cwd, branch, skipVerify = false) {
1638
+ const noVerify = skipVerify ? ["--no-verify"] : [];
1639
+ try {
1640
+ await git(cwd, ["push", ...noVerify, "origin", branch], 3e4);
1641
+ return true;
1642
+ } catch (err) {
1643
+ if (errLooksLikeAuth(err)) return false;
1644
+ process.stderr.write(
1645
+ `[conveyor-agent] Plain push of ${branch} failed \u2014 retrying with --force-with-lease
1646
+ `
1647
+ );
1648
+ try {
1649
+ await git(cwd, ["push", ...noVerify, "--force-with-lease", "origin", branch], 3e4);
1650
+ return true;
1651
+ } catch {
1652
+ return false;
1653
+ }
1654
+ }
1655
+ }
1656
+ async function isAuthError(cwd) {
1657
+ try {
1658
+ await git(cwd, ["push", "--dry-run"], 3e4);
1659
+ return false;
1660
+ } catch (err) {
1661
+ return errLooksLikeAuth(err);
1662
+ }
1663
+ }
1664
+ function wipRefForBranch(branch) {
1665
+ return `conveyor-wip/${branch}`;
1666
+ }
1667
+ var wipRefPushed = /* @__PURE__ */ new Set();
1668
+ var wipRefPreserved = /* @__PURE__ */ new Set();
1669
+ async function createWipSnapshot(cwd, message) {
1670
+ let savedIndexTree;
1671
+ try {
1672
+ savedIndexTree = await git(cwd, ["write-tree"], GIT_SLOW_TIMEOUT_MS);
1673
+ } catch {
1674
+ return null;
1675
+ }
1676
+ try {
1677
+ await git(cwd, ["add", "-A"], GIT_SLOW_TIMEOUT_MS);
1678
+ const sha = await git(cwd, ["stash", "create", message], GIT_SLOW_TIMEOUT_MS);
1679
+ return sha || null;
1680
+ } catch {
1681
+ return null;
1682
+ } finally {
1683
+ try {
1684
+ await git(cwd, ["read-tree", savedIndexTree], GIT_SLOW_TIMEOUT_MS);
1685
+ } catch {
1686
+ }
1687
+ }
1688
+ }
1689
+ async function tryPushRefspec(cwd, refspec, force = false) {
1690
+ try {
1691
+ const forceArgs = force ? ["--force"] : [];
1692
+ await git(cwd, ["push", "--no-verify", ...forceArgs, "origin", refspec], 3e4);
1693
+ return true;
1694
+ } catch {
1695
+ return false;
1696
+ }
1697
+ }
1698
+ async function refreshRemoteToken(cwd, refreshToken) {
1699
+ if (!refreshToken) return;
1700
+ try {
1701
+ const token = await refreshToken();
1702
+ if (token) {
1703
+ await updateRemoteToken(cwd, token);
1704
+ process.env.GITHUB_TOKEN = token;
1705
+ process.env.GH_TOKEN = token;
1706
+ }
1707
+ } catch {
1708
+ }
1709
+ }
1710
+ async function restoreWipSnapshot(cwd, branch) {
1711
+ if (!branch) return "none";
1712
+ const ref = wipRefForBranch(branch);
1713
+ try {
1714
+ await git(cwd, ["fetch", "origin", `+refs/heads/${ref}:refs/remotes/origin/${ref}`]);
1715
+ } catch (err) {
1716
+ if (isMissingRefError(err)) return "none";
1717
+ wipRefPreserved.add(cwd);
1718
+ return "failed";
1719
+ }
1720
+ try {
1721
+ const sha = await git(cwd, ["rev-parse", `refs/remotes/origin/${ref}`]);
1722
+ const parent = await git(cwd, ["rev-parse", `${sha}^`]);
1723
+ const head = await git(cwd, ["rev-parse", "HEAD"]);
1724
+ if (parent !== head) {
1725
+ try {
1726
+ await git(cwd, ["stash", "apply", sha], GIT_SLOW_TIMEOUT_MS);
1727
+ wipRefPushed.add(cwd);
1728
+ wipRefPreserved.delete(cwd);
1729
+ return "applied";
1730
+ } catch {
1731
+ try {
1732
+ await git(cwd, ["reset", "--merge"], GIT_SLOW_TIMEOUT_MS);
1733
+ } catch {
1734
+ }
1735
+ wipRefPreserved.add(cwd);
1736
+ return "stale";
1737
+ }
1738
+ }
1739
+ await git(cwd, ["stash", "apply", sha], GIT_SLOW_TIMEOUT_MS);
1740
+ wipRefPushed.add(cwd);
1741
+ wipRefPreserved.delete(cwd);
1742
+ return "applied";
1743
+ } catch {
1744
+ wipRefPreserved.add(cwd);
1745
+ return "failed";
1746
+ }
1747
+ }
1748
+ function isMissingRefError(err) {
1749
+ const stderr = err.stderr?.toString() ?? "";
1750
+ const msg = stderr || (err instanceof Error ? err.message : String(err));
1751
+ return /couldn't find remote ref|couldn't find remote|no such ref|not our ref/i.test(msg);
1752
+ }
1753
+ async function flushPendingChanges(cwd, opts) {
1754
+ let committed = false;
1755
+ let pushed = false;
1756
+ let hadWork = false;
1757
+ try {
1758
+ const branch = await getCurrentBranch(cwd);
1759
+ if (!branch) return { committed, pushed, hadWork };
1760
+ const dirty = await hasUncommittedChanges(cwd);
1761
+ const unpushed = await hasUnpushedCommits(cwd);
1762
+ if (!dirty && !unpushed) {
1763
+ await dropStaleWipRef(cwd, branch, opts?.refreshToken);
1764
+ return { committed, pushed, hadWork };
1765
+ }
1766
+ hadWork = true;
1767
+ await refreshRemoteToken(cwd, opts?.refreshToken);
1768
+ if (unpushed) {
1769
+ pushed = await pushToOrigin(cwd, opts?.refreshToken);
1770
+ }
1771
+ if (dirty && !wipRefPreserved.has(cwd)) {
1772
+ const message = opts?.wipMessage ?? "WIP: conveyor-agent snapshot";
1773
+ const sha = await createWipSnapshot(cwd, message);
1774
+ if (sha) {
1775
+ committed = await tryPushRefspec(cwd, `${sha}:refs/heads/${wipRefForBranch(branch)}`, true);
1776
+ if (committed) wipRefPushed.add(cwd);
1777
+ }
1778
+ }
1779
+ } catch {
1780
+ }
1781
+ return { committed, pushed, hadWork };
1782
+ }
1783
+ async function dropStaleWipRef(cwd, branch, refreshToken) {
1784
+ if (wipRefPreserved.has(cwd) || !wipRefPushed.has(cwd)) return;
1785
+ await refreshRemoteToken(cwd, refreshToken);
1786
+ if (await tryPushRefspec(cwd, `:refs/heads/${wipRefForBranch(branch)}`)) {
1787
+ wipRefPushed.delete(cwd);
1788
+ }
1789
+ }
1790
+ async function pushToOrigin(cwd, refreshToken, skipVerify = false) {
1791
+ try {
1792
+ const currentBranch = await getCurrentBranch(cwd);
1793
+ if (!currentBranch) return false;
1794
+ if (refreshToken) {
1795
+ try {
1796
+ const token = await refreshToken();
1797
+ if (token) {
1798
+ await updateRemoteToken(cwd, token);
1799
+ process.env.GITHUB_TOKEN = token;
1800
+ process.env.GH_TOKEN = token;
1801
+ }
1802
+ } catch {
1803
+ }
1804
+ }
1805
+ if (await tryPush(cwd, currentBranch, skipVerify)) {
1806
+ clearForceFreshCooldown();
1807
+ return true;
1808
+ }
1809
+ if (refreshToken && !forceFreshMintBlocked() && await isAuthError(cwd)) {
1810
+ const token = await refreshToken({ forceFresh: true });
1811
+ if (token) {
1812
+ await updateRemoteToken(cwd, token);
1813
+ process.env.GITHUB_TOKEN = token;
1814
+ process.env.GH_TOKEN = token;
1815
+ const pushed = await tryPush(cwd, currentBranch, skipVerify);
1816
+ if (pushed) clearForceFreshCooldown();
1817
+ else recordForceFreshFailure();
1818
+ return pushed;
1819
+ }
1820
+ }
1821
+ return false;
1822
+ } catch {
1823
+ return false;
1824
+ }
1825
+ }
1826
+ function branchBackupRef(branch) {
1827
+ return `conveyor-wip/branches/${branch}`;
1828
+ }
1829
+ async function listWorktrees(cwd) {
1830
+ try {
1831
+ const out = await git(cwd, ["worktree", "list", "--porcelain"]);
1832
+ const result = [];
1833
+ for (const entry of out.split("\n\n")) {
1834
+ const lines = entry.trim().split("\n");
1835
+ const wl = lines.find((l) => l.startsWith("worktree "));
1836
+ if (!wl) continue;
1837
+ const bl = lines.find((l) => l.startsWith("branch "));
1838
+ result.push({
1839
+ path: wl.slice("worktree ".length),
1840
+ branch: bl ? bl.slice("branch refs/heads/".length) : null
1841
+ });
1842
+ }
1843
+ return result;
1844
+ } catch {
1845
+ return [];
1846
+ }
1847
+ }
1848
+ async function listLocalBranches(cwd) {
1849
+ try {
1850
+ const out = await git(cwd, ["for-each-ref", "--format=%(refname:short)", "refs/heads/"]);
1851
+ return out.split("\n").map((s) => s.trim()).filter(Boolean);
1852
+ } catch {
1853
+ return [];
1854
+ }
1855
+ }
1856
+ async function branchUnpushedCount(cwd, branch) {
1857
+ try {
1858
+ const n = await git(cwd, ["rev-list", "--count", branch, "--not", "--remotes=origin"]);
1859
+ return Number.parseInt(n, 10) || 0;
1860
+ } catch {
1861
+ return 0;
1862
+ }
1863
+ }
1864
+ function samePath(a, b) {
1865
+ try {
1866
+ return realpathSync(a) === realpathSync(b);
1867
+ } catch {
1868
+ return a === b;
1869
+ }
1870
+ }
1871
+ async function flushAllPendingWork(cwd, opts) {
1872
+ try {
1873
+ const primary = await flushPendingChanges(cwd, opts);
1874
+ await refreshRemoteToken(cwd, opts?.refreshToken);
1875
+ const currentBranch = await getCurrentBranch(cwd);
1876
+ const worktreesSnapshotted = await snapshotOtherWorktrees(cwd, opts?.wipMessage);
1877
+ const branchesBackedUp = await backupOtherBranches(cwd, currentBranch);
1878
+ return {
1879
+ hadWork: primary.hadWork || worktreesSnapshotted > 0 || branchesBackedUp > 0,
1880
+ branchesBackedUp,
1881
+ worktreesSnapshotted
1882
+ };
1883
+ } catch {
1884
+ return { hadWork: false, branchesBackedUp: 0, worktreesSnapshotted: 0 };
1885
+ }
1886
+ }
1887
+ async function snapshotOtherWorktrees(cwd, wipMessage) {
1888
+ let count = 0;
1889
+ for (const wt of await listWorktrees(cwd)) {
1890
+ if (samePath(wt.path, cwd) || !wt.branch) continue;
1891
+ try {
1892
+ if (!await hasUncommittedChanges(wt.path)) continue;
1893
+ const sha = await createWipSnapshot(wt.path, wipMessage ?? "WIP: conveyor-agent snapshot");
1894
+ if (sha && await tryPushRefspec(wt.path, `${sha}:refs/heads/${wipRefForBranch(wt.branch)}`, true)) {
1895
+ wipRefPushed.add(wt.path);
1896
+ count++;
1897
+ }
1898
+ } catch {
1899
+ }
1900
+ }
1901
+ return count;
1902
+ }
1903
+ async function backupOtherBranches(cwd, currentBranch) {
1904
+ let count = 0;
1905
+ for (const branch of await listLocalBranches(cwd)) {
1906
+ if (branch === currentBranch || branch.startsWith("conveyor-wip/")) continue;
1907
+ try {
1908
+ if (await branchUnpushedCount(cwd, branch) === 0) continue;
1909
+ if (await tryPushRefspec(
1910
+ cwd,
1911
+ `refs/heads/${branch}:refs/heads/${branchBackupRef(branch)}`,
1912
+ true
1913
+ )) {
1914
+ count++;
1915
+ }
1916
+ } catch {
1917
+ }
1918
+ }
1919
+ return count;
1920
+ }
1921
+
1922
+ // src/setup/config.ts
1923
+ import { join } from "path";
1924
+
1925
+ // src/workbench/fs.ts
1926
+ import {
1927
+ readFile as localReadFile,
1928
+ readdir as localReaddir,
1929
+ stat as localStat
1930
+ } from "fs/promises";
1931
+ async function readWorkspaceFile(path) {
1932
+ if (workbenchEnabled()) {
1933
+ return (await getWorkbenchClient().readFile(path)).toString("utf8");
1934
+ }
1935
+ return localReadFile(path, "utf-8");
1936
+ }
1937
+ function readWorkspaceBytes(path) {
1938
+ if (workbenchEnabled()) return getWorkbenchClient().readFile(path);
1939
+ return localReadFile(path);
1940
+ }
1941
+ function readWorkspaceDir(path) {
1942
+ if (workbenchEnabled()) return getWorkbenchClient().readdir(path);
1943
+ return localReaddir(path);
1944
+ }
1945
+ async function statWorkspacePath(path) {
1946
+ if (workbenchEnabled()) return getWorkbenchClient().stat(path);
1947
+ try {
1948
+ const s = await localStat(path);
1949
+ return {
1950
+ exists: true,
1951
+ isFile: s.isFile(),
1952
+ isDirectory: s.isDirectory(),
1953
+ size: s.size,
1954
+ mtimeMs: s.mtimeMs
1955
+ };
1956
+ } catch {
1957
+ return { exists: false, isFile: false, isDirectory: false, size: 0, mtimeMs: 0 };
1958
+ }
1959
+ }
1960
+ async function workspacePathExists(path) {
1961
+ return (await statWorkspacePath(path)).exists;
1962
+ }
1963
+
1964
+ // src/setup/config.ts
1965
+ var DEVCONTAINER_PATH = ".devcontainer/conveyor/devcontainer.json";
1966
+ var DEVCONTAINER_PORT_DENY_LIST = /* @__PURE__ */ new Set([5432, 6379, 9200]);
1967
+ async function loadForwardPorts(workspaceDir) {
1968
+ try {
1969
+ const raw = await readWorkspaceFile(join(workspaceDir, DEVCONTAINER_PATH));
1970
+ const parsed = JSON.parse(raw);
1971
+ const ports = (parsed.forwardPorts ?? []).filter(
1972
+ (p) => typeof p === "number" && !DEVCONTAINER_PORT_DENY_LIST.has(p)
1973
+ );
1974
+ const attributes = {};
1975
+ for (const [key, value] of Object.entries(parsed.portsAttributes ?? {})) {
1976
+ if (!value || typeof value !== "object") continue;
1977
+ const entry = {};
1978
+ if (typeof value.label === "string") entry.label = value.label;
1979
+ if (value.visibility === "public" || value.visibility === "private") {
1980
+ entry.visibility = value.visibility;
1981
+ }
1982
+ attributes[key] = entry;
1983
+ }
1984
+ return { ports, attributes };
1985
+ } catch {
1986
+ return { ports: [], attributes: {} };
1987
+ }
1988
+ }
1989
+ function buildSessionPreviewPorts(result) {
1990
+ return result.ports.filter((port) => !DEVCONTAINER_PORT_DENY_LIST.has(port)).map((port) => {
1991
+ const attr = result.attributes[String(port)];
1992
+ const entry = { port };
1993
+ if (attr?.label) entry.label = attr.label;
1994
+ if (attr?.visibility) entry.visibility = attr.visibility;
1995
+ return entry;
1996
+ });
1997
+ }
1998
+ function loadConveyorConfig() {
1999
+ const envStart = process.env.CONVEYOR_START_COMMAND;
2000
+ if (envStart) {
2001
+ return { startCommand: envStart };
2002
+ }
2003
+ return null;
2004
+ }
2005
+
2006
+ // src/runner/lifecycle.ts
2007
+ var DEFAULT_LIFECYCLE_CONFIG = {
2008
+ idleTimeoutMs: 30 * 60 * 1e3,
2009
+ dormantTimeoutMs: 60 * 60 * 1e3,
2010
+ heartbeatIntervalMs: 3e4,
2011
+ tokenRefreshIntervalMs: 45 * 60 * 1e3,
2012
+ gitFlushIntervalMs: 2 * 60 * 1e3,
2013
+ usageSampleIntervalMs: 5 * 60 * 1e3,
2014
+ usageSampleInitialDelayMs: 3e4
2015
+ };
2016
+ var Lifecycle = class {
2017
+ config;
2018
+ callbacks;
2019
+ heartbeatTimer = null;
2020
+ tokenRefreshTimer = null;
2021
+ idleTimer = null;
2022
+ idleCheckInterval = null;
2023
+ dormantTimer = null;
2024
+ gitFlushTimer = null;
2025
+ usageSampleTimer = null;
2026
+ constructor(config, callbacks) {
2027
+ this.config = config;
2028
+ this.callbacks = callbacks;
2029
+ }
2030
+ // ── Heartbeat ──────────────────────────────────────────────────────
2031
+ startHeartbeat() {
2032
+ this.stopHeartbeat();
2033
+ this.heartbeatTimer = setInterval(() => {
2034
+ this.callbacks.onHeartbeat();
2035
+ }, this.config.heartbeatIntervalMs);
2036
+ }
2037
+ stopHeartbeat() {
2038
+ if (this.heartbeatTimer) {
2039
+ clearInterval(this.heartbeatTimer);
2040
+ this.heartbeatTimer = null;
2041
+ }
2042
+ }
2043
+ // ── Token refresh ─────────────────────────────────────────────────
2044
+ startTokenRefresh() {
2045
+ this.stopTokenRefresh();
2046
+ this.callbacks.onTokenRefresh();
2047
+ this.tokenRefreshTimer = setInterval(() => {
2048
+ this.callbacks.onTokenRefresh();
2049
+ }, this.config.tokenRefreshIntervalMs);
2050
+ }
2051
+ stopTokenRefresh() {
2052
+ if (this.tokenRefreshTimer) {
2053
+ clearInterval(this.tokenRefreshTimer);
2054
+ this.tokenRefreshTimer = null;
2055
+ }
2056
+ }
2057
+ // ── Periodic git flush ────────────────────────────────────────────
2058
+ startGitFlush() {
2059
+ this.stopGitFlush();
2060
+ if (this.config.gitFlushIntervalMs <= 0) return;
2061
+ this.gitFlushTimer = setInterval(() => {
2062
+ this.callbacks.onGitFlush();
2063
+ }, this.config.gitFlushIntervalMs);
2064
+ }
2065
+ stopGitFlush() {
2066
+ if (this.gitFlushTimer) {
2067
+ clearInterval(this.gitFlushTimer);
2068
+ this.gitFlushTimer = null;
2069
+ }
2070
+ }
2071
+ // ── Claude key usage sampling ─────────────────────────────────────
2072
+ startUsageSample() {
2073
+ this.stopUsageSample();
2074
+ if (this.config.usageSampleIntervalMs <= 0) return;
2075
+ this.usageSampleTimer = setTimeout(() => {
2076
+ this.callbacks.onUsageSample();
2077
+ this.usageSampleTimer = setInterval(() => {
2078
+ this.callbacks.onUsageSample();
2079
+ }, this.config.usageSampleIntervalMs);
2080
+ }, this.config.usageSampleInitialDelayMs);
2081
+ }
2082
+ stopUsageSample() {
2083
+ if (this.usageSampleTimer) {
2084
+ clearInterval(this.usageSampleTimer);
2085
+ this.usageSampleTimer = null;
2086
+ }
2087
+ }
2088
+ // ── Idle timer ─────────────────────────────────────────────────────
2089
+ /** Start (or restart) the idle timer.
2090
+ * @param overrideMs Optional custom delay in ms, mirroring
2091
+ * `startDormantTimer`. SessionRunner passes a short delay when it DEFERS a
2092
+ * shutdown because a spawned child is still working: the pod must re-check
2093
+ * soon after that child exits, rather than granting itself a fresh full idle
2094
+ * window every time it defers. */
2095
+ startIdleTimer(overrideMs) {
2096
+ this.clearIdleTimers();
2097
+ const delay2 = Math.max(0, overrideMs ?? this.config.idleTimeoutMs);
2098
+ this.idleTimer = setTimeout(() => {
2099
+ this.callbacks.onIdleTimeout();
2100
+ }, delay2);
2101
+ }
2102
+ cancelIdleTimer() {
2103
+ this.clearIdleTimers();
2104
+ }
2105
+ // ── Dormant timer ──────────────────────────────────────────────────
2106
+ /** Start (or restart) the dormant timer.
2107
+ * @param overrideMs Optional custom delay in ms. When provided, the timer
2108
+ * fires after exactly that delay instead of `dormantTimeoutMs`. SessionRunner
2109
+ * uses this to enforce an *absolute* deadline across cycles: even if the
2110
+ * dormant wait is interrupted by an inbound message, the next iteration
2111
+ * passes the remaining time, so the agent shuts down at the original
2112
+ * deadline regardless of message volume. */
2113
+ startDormantTimer(overrideMs) {
2114
+ this.cancelDormantTimer();
2115
+ const delay2 = Math.max(0, overrideMs ?? this.config.dormantTimeoutMs);
2116
+ this.dormantTimer = setTimeout(() => {
2117
+ this.callbacks.onDormantTimeout();
2118
+ }, delay2);
2119
+ }
2120
+ cancelDormantTimer() {
2121
+ if (this.dormantTimer) {
2122
+ clearTimeout(this.dormantTimer);
2123
+ this.dormantTimer = null;
2124
+ }
2125
+ }
2126
+ // ── Cleanup ────────────────────────────────────────────────────────
2127
+ destroy() {
2128
+ this.stopHeartbeat();
2129
+ this.stopTokenRefresh();
2130
+ this.stopGitFlush();
2131
+ this.stopUsageSample();
2132
+ this.clearIdleTimers();
2133
+ this.cancelDormantTimer();
2134
+ }
2135
+ // ── Private ────────────────────────────────────────────────────────
2136
+ clearIdleTimers() {
2137
+ if (this.idleTimer) {
2138
+ clearTimeout(this.idleTimer);
2139
+ this.idleTimer = null;
2140
+ }
2141
+ if (this.idleCheckInterval) {
2142
+ clearInterval(this.idleCheckInterval);
2143
+ this.idleCheckInterval = null;
2144
+ }
2145
+ }
2146
+ };
2147
+
2148
+ // src/setup/git-ready.ts
2149
+ var GATE_MARGIN_MS = 5 * 6e4;
2150
+ var DEFAULT_TIMEOUT_MS = GIT_PREP_MAX_RETRIES * (CLONE_TIMEOUT_MS + FETCH_TIMEOUT_MS) + (GIT_PREP_MAX_RETRIES - 1) * DEFAULT_RETRY_DELAY_MS + GATE_MARGIN_MS;
2151
+ var DEFAULT_POLL_MS = 200;
2152
+ function awaitGitReady(opts = {}) {
2153
+ if (!workbenchEnabled()) {
2154
+ return Promise.resolve("not-gated");
2155
+ }
2156
+ const clientFn = opts.clientFn ?? getWorkbenchClient;
2157
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2158
+ const pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
2159
+ opts.onLog?.("waiting for workspace git (workbench daemon)");
2160
+ return pollDaemon(clientFn, timeoutMs, pollMs, opts.onLog, opts.signal);
2161
+ }
2162
+ function delay(ms, signal) {
2163
+ if (!signal) {
2164
+ return new Promise((resolve) => {
2165
+ setTimeout(resolve, ms);
2166
+ });
2167
+ }
2168
+ if (signal.aborted) return Promise.resolve();
2169
+ return new Promise((resolve) => {
2170
+ const timer = setTimeout(() => {
2171
+ signal.removeEventListener("abort", onAbort);
2172
+ resolve();
2173
+ }, ms);
2174
+ const onAbort = () => {
2175
+ clearTimeout(timer);
2176
+ resolve();
2177
+ };
2178
+ signal.addEventListener("abort", onAbort, { once: true });
2179
+ });
2180
+ }
2181
+ async function pollOnce(clientFn, reportError) {
2182
+ try {
2183
+ const frame = await clientFn().gitStatus();
2184
+ if (frame.state === "ready") return { state: "ready", log: "workspace git ready" };
2185
+ if (frame.state === "failed") {
2186
+ return {
2187
+ state: "failed",
2188
+ log: `workspace git preparation failed: ${frame.reason ?? "unknown reason"}`
2189
+ };
2190
+ }
2191
+ return { state: null };
2192
+ } catch (err) {
2193
+ if (err instanceof WorkbenchError && err.code === "unauthorized") {
2194
+ return {
2195
+ state: "failed",
2196
+ log: "workspace git gate unauthorized \u2014 workbench token missing or invalid, giving up"
2197
+ };
2198
+ }
2199
+ const message = err instanceof Error ? err.message : String(err);
2200
+ return reportError ? { state: null, log: `workspace git poll error (retrying): ${message}` } : { state: null };
2201
+ }
2202
+ }
2203
+ async function pollDaemon(clientFn, timeoutMs, pollMs, onLog, signal) {
2204
+ const deadline = Date.now() + timeoutMs;
2205
+ let loggedError = false;
2206
+ for (; ; ) {
2207
+ if (signal?.aborted) {
2208
+ onLog?.("workspace git wait aborted \u2014 giving up");
2209
+ return "timeout";
2210
+ }
2211
+ const outcome = await pollOnce(clientFn, !loggedError);
2212
+ if (outcome.log !== void 0) {
2213
+ loggedError = true;
2214
+ onLog?.(outcome.log);
2215
+ }
2216
+ if (outcome.state !== null) return outcome.state;
2217
+ if (Date.now() >= deadline) {
2218
+ onLog?.(`workspace git not ready after ${timeoutMs}ms \u2014 giving up`);
2219
+ return "timeout";
2220
+ }
2221
+ await delay(pollMs, signal);
2222
+ }
2223
+ }
2224
+
2225
+ // src/runner/port-discovery.ts
2226
+ import { readFile } from "fs/promises";
2227
+ import { execFile as execFile2 } from "child_process";
2228
+ var PROC_TCP_LISTEN_STATE = "0A";
2229
+ function isLoopbackHexAddress(hex) {
2230
+ const addr = hex.toUpperCase();
2231
+ if (addr.length === 8) {
2232
+ return addr.slice(6, 8) === "7F";
2233
+ }
2234
+ if (addr.length === 32) {
2235
+ if (addr === "00000000000000000000000001000000") return true;
2236
+ if (addr.slice(0, 16) === "0000000000000000" && addr.slice(16, 24) === "FFFF0000") {
2237
+ return addr.slice(30, 32) === "7F";
2238
+ }
2239
+ return false;
2240
+ }
2241
+ return false;
2242
+ }
2243
+ function parseProcNetTcpListeners(content) {
2244
+ const sockets = [];
2245
+ const lines = content.split("\n");
2246
+ for (let i = 1; i < lines.length; i++) {
2247
+ const line = lines[i];
2248
+ if (!line) continue;
2249
+ const cols = line.trim().split(/\s+/);
2250
+ if (cols.length < 4 || cols[3] !== PROC_TCP_LISTEN_STATE) continue;
2251
+ const local = cols[1];
2252
+ if (!local) continue;
2253
+ const [addrHex, portHex] = local.split(":");
2254
+ if (!addrHex || !portHex) continue;
2255
+ const port = Number.parseInt(portHex, 16);
2256
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
2257
+ sockets.push({ port, loopback: isLoopbackHexAddress(addrHex) });
2258
+ }
2259
+ return sockets;
2260
+ }
2261
+ function collectScan(sockets) {
2262
+ const ports = /* @__PURE__ */ new Set();
2263
+ const hasExternal = /* @__PURE__ */ new Set();
2264
+ for (const { port, loopback } of sockets) {
2265
+ ports.add(port);
2266
+ if (!loopback) hasExternal.add(port);
2267
+ }
2268
+ const loopbackOnly = /* @__PURE__ */ new Set();
2269
+ for (const port of ports) {
2270
+ if (!hasExternal.has(port)) loopbackOnly.add(port);
2271
+ }
2272
+ return { ports, loopbackOnly };
2273
+ }
2274
+ var DEFAULT_PROC_PATHS = ["/proc/net/tcp", "/proc/net/tcp6"];
2275
+ async function readProcListeningPorts(procPaths = DEFAULT_PROC_PATHS) {
2276
+ const sockets = [];
2277
+ let readable = false;
2278
+ for (const path of procPaths) {
2279
+ try {
2280
+ const content = await readFile(path, "utf8");
2281
+ readable = true;
2282
+ sockets.push(...parseProcNetTcpListeners(content));
2283
+ } catch {
2284
+ }
2285
+ }
2286
+ return readable ? collectScan(sockets) : null;
2287
+ }
2288
+ async function readNetstatListeningPorts() {
2289
+ const output = await new Promise((resolve) => {
2290
+ execFile2("netstat", ["-an", "-p", "tcp"], { timeout: 5e3 }, (err, stdout) => {
2291
+ resolve(err ? null : stdout);
2292
+ });
2293
+ });
2294
+ if (output === null) return null;
2295
+ const sockets = [];
2296
+ for (const line of output.split("\n")) {
2297
+ if (!line.includes("LISTEN")) continue;
2298
+ const cols = line.trim().split(/\s+/);
2299
+ const local = cols[3];
2300
+ if (!local) continue;
2301
+ const lastDot = local.lastIndexOf(".");
2302
+ if (lastDot < 0) continue;
2303
+ const host = local.slice(0, lastDot);
2304
+ const port = Number(local.slice(lastDot + 1));
2305
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
2306
+ const loopback = host.startsWith("127.") || host === "::1" || host === "localhost";
2307
+ sockets.push({ port, loopback });
2308
+ }
2309
+ return collectScan(sockets);
2310
+ }
2311
+ async function readListeningPorts() {
2312
+ const proc = await readProcListeningPorts();
2313
+ if (proc !== null) return proc;
2314
+ if (process.platform !== "linux") return readNetstatListeningPorts();
2315
+ return null;
2316
+ }
2317
+ var DEFAULT_EXCLUDED_PORTS = [2222, 5432, 6379, 9200];
2318
+ var DEFAULT_EPHEMERAL_PORT_MIN = 32768;
2319
+ var DEFAULT_DISCOVERY_INTERVAL_MS = 15e3;
2320
+ var DEFAULT_MAX_PORTS = 16;
2321
+ var CONFIRM_SCANS = 2;
2322
+ var PortDiscovery = class {
2323
+ opts;
2324
+ intervalMs;
2325
+ maxPorts;
2326
+ excluded;
2327
+ ephemeralPortMin;
2328
+ scan;
2329
+ now;
2330
+ log;
2331
+ baseline = null;
2332
+ tracked = /* @__PURE__ */ new Map();
2333
+ /** Loopback-only candidates already warned about (once per port). */
2334
+ warnedLoopback = /* @__PURE__ */ new Set();
2335
+ timer = null;
2336
+ ticking = false;
2337
+ disabled = false;
2338
+ stopped = false;
2339
+ /** Set when the confirmed set changed (or a report failed) — cleared only
2340
+ * after a successful report, so transient RPC failures retry next tick. */
2341
+ reportPending = false;
2342
+ lastReportedKey = "";
2343
+ constructor(options) {
2344
+ this.opts = options;
2345
+ this.intervalMs = options.intervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;
2346
+ this.maxPorts = options.maxPorts ?? DEFAULT_MAX_PORTS;
2347
+ this.excluded = new Set(options.excludedPorts ?? DEFAULT_EXCLUDED_PORTS);
2348
+ this.ephemeralPortMin = options.ephemeralPortMin ?? DEFAULT_EPHEMERAL_PORT_MIN;
2349
+ this.scan = options.scan ?? readListeningPorts;
2350
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
2351
+ this.log = options.log ?? ((m) => process.stderr.write(`[conveyor-agent] ${m}
2352
+ `));
2353
+ }
2354
+ /** Take the baseline scan and start polling. Safe to call once. */
2355
+ async start() {
2356
+ if (this.timer || this.disabled || this.stopped) return;
2357
+ const baseline = await this.scanSafe();
2358
+ if (this.stopped) return;
2359
+ if (baseline === null) {
2360
+ this.disabled = true;
2361
+ this.log("Port discovery disabled: no listening-socket source available");
2362
+ return;
2363
+ }
2364
+ this.baseline = baseline.ports;
2365
+ this.timer = setInterval(() => void this.tick(), this.intervalMs);
2366
+ this.timer.unref?.();
2367
+ }
2368
+ stop() {
2369
+ this.stopped = true;
2370
+ if (this.timer) {
2371
+ clearInterval(this.timer);
2372
+ this.timer = null;
2373
+ }
2374
+ }
2375
+ /** One poll cycle. Exposed for tests (deterministic, no timers needed). */
2376
+ async tick() {
2377
+ if (this.ticking || this.disabled || !this.baseline) return;
2378
+ this.ticking = true;
2379
+ try {
2380
+ const current = await this.scanSafe();
2381
+ if (current === null) return;
2382
+ this.updateTracking(current);
2383
+ if (this.reportPending) await this.flushReport();
2384
+ } finally {
2385
+ this.ticking = false;
2386
+ }
2387
+ }
2388
+ async scanSafe() {
2389
+ try {
2390
+ return await this.scan();
2391
+ } catch {
2392
+ return null;
2393
+ }
2394
+ }
2395
+ isCandidate(port) {
2396
+ if (this.baseline?.has(port)) return false;
2397
+ if (this.excluded.has(port)) return false;
2398
+ if (port >= this.ephemeralPortMin) return false;
2399
+ return true;
2400
+ }
2401
+ updateTracking(current) {
2402
+ const reachable = /* @__PURE__ */ new Set();
2403
+ for (const port of current.ports) {
2404
+ if (!this.isCandidate(port)) continue;
2405
+ if (current.loopbackOnly.has(port)) {
2406
+ if (!this.warnedLoopback.has(port)) {
2407
+ this.warnedLoopback.add(port);
2408
+ this.log(
2409
+ `Port ${port} is listening on loopback only and cannot be previewed \u2014 bind 0.0.0.0 (or the pod IP) to make it reachable through the preview proxy`
2410
+ );
2411
+ }
2412
+ continue;
2413
+ }
2414
+ reachable.add(port);
2415
+ }
2416
+ for (const port of reachable) {
2417
+ const entry = this.tracked.get(port);
2418
+ if (!entry) {
2419
+ this.tracked.set(port, { seen: 1, missed: 0, confirmed: false, detectedAt: "" });
2420
+ continue;
2421
+ }
2422
+ entry.seen += 1;
2423
+ entry.missed = 0;
2424
+ if (!entry.confirmed && entry.seen >= CONFIRM_SCANS) {
2425
+ entry.confirmed = true;
2426
+ entry.detectedAt = this.now().toISOString();
2427
+ }
2428
+ }
2429
+ for (const [port, entry] of this.tracked) {
2430
+ if (reachable.has(port)) continue;
2431
+ entry.missed += 1;
2432
+ entry.seen = 0;
2433
+ if (entry.missed >= CONFIRM_SCANS || !entry.confirmed) this.tracked.delete(port);
2434
+ }
2435
+ const key = this.confirmedKey();
2436
+ if (key !== this.lastReportedKey) this.reportPending = true;
2437
+ }
2438
+ confirmedPorts() {
2439
+ const confirmed = [...this.tracked.entries()].filter(([, entry]) => entry.confirmed).sort(([a], [b]) => a - b).slice(0, this.maxPorts);
2440
+ return confirmed.map(([port, entry]) => ({
2441
+ port,
2442
+ protocol: "tcp",
2443
+ detectedAt: entry.detectedAt
2444
+ }));
2445
+ }
2446
+ confirmedKey() {
2447
+ return this.confirmedPorts().map(({ port }) => port).join(",");
2448
+ }
2449
+ async flushReport() {
2450
+ const ports = this.confirmedPorts();
2451
+ const key = ports.map(({ port }) => port).join(",");
2452
+ try {
2453
+ await this.opts.report(ports);
2454
+ this.lastReportedKey = key;
2455
+ this.reportPending = false;
2456
+ this.log(`Discovered preview ports: [${key || "none"}]`);
2457
+ } catch {
2458
+ return;
2459
+ }
2460
+ try {
2461
+ await this.opts.onReported?.(ports);
2462
+ } catch {
2463
+ }
2464
+ }
2465
+ };
2466
+
2467
+ // src/runner/codespace-port-visibility.ts
2468
+ import { execFile as execFile3 } from "child_process";
2469
+ var GH_TIMEOUT_MS = 15e3;
2470
+ var VISIBILITIES = ["org", "public"];
2471
+ function runGh(args) {
2472
+ return new Promise((resolve) => {
2473
+ execFile3("gh", [...args], { timeout: GH_TIMEOUT_MS }, (error, _stdout, stderr) => {
2474
+ resolve({ ok: !error, stderr: (stderr || (error ? String(error.message) : "")).trim() });
2475
+ });
2476
+ });
2477
+ }
2478
+ function isCodespaceEnvironment(env = process.env) {
2479
+ return env.CODESPACES === "true" && !!env.CODESPACE_NAME;
2480
+ }
2481
+ var CodespacePortVisibility = class {
2482
+ env;
2483
+ run;
2484
+ log;
2485
+ /** Ports already attempted (success or failure) — one try per process. */
2486
+ attempted = /* @__PURE__ */ new Set();
2487
+ constructor(options = {}) {
2488
+ this.env = options.env ?? process.env;
2489
+ this.run = options.run ?? runGh;
2490
+ this.log = options.log ?? ((m) => process.stderr.write(`[conveyor-agent] ${m}
2491
+ `));
2492
+ }
2493
+ /** Flip every not-yet-attempted port. Resolves even when everything fails. */
2494
+ async ensureVisible(ports) {
2495
+ if (!isCodespaceEnvironment(this.env)) return;
2496
+ const codespaceName = this.env.CODESPACE_NAME;
2497
+ for (const port of ports) {
2498
+ if (this.attempted.has(port)) continue;
2499
+ this.attempted.add(port);
2500
+ await this.flip(port, codespaceName);
2501
+ }
2502
+ }
2503
+ async flip(port, codespaceName) {
2504
+ let lastError = "";
2505
+ for (const visibility of VISIBILITIES) {
2506
+ const result = await this.run([
2507
+ "codespace",
2508
+ "ports",
2509
+ "visibility",
2510
+ `${port}:${visibility}`,
2511
+ "-c",
2512
+ codespaceName
2513
+ ]).catch((error) => ({
2514
+ ok: false,
2515
+ stderr: error instanceof Error ? error.message : String(error)
2516
+ }));
2517
+ if (result.ok) {
2518
+ this.log(`Forwarded port ${port} set to ${visibility} visibility`);
2519
+ return;
2520
+ }
2521
+ lastError = result.stderr;
2522
+ }
2523
+ this.log(
2524
+ `Could not change visibility of forwarded port ${port} \u2014 the preview URL may 404 for other users${lastError ? `: ${lastError}` : ""}`
2525
+ );
2526
+ }
2527
+ };
2528
+
2529
+ export {
2530
+ fetchBootstrap,
2531
+ applyBootstrapToEnv,
2532
+ createServiceLogger,
2533
+ AgentConnection,
2534
+ DEFAULT_LIFECYCLE_CONFIG,
2535
+ Lifecycle,
2536
+ readWorkspaceFile,
2537
+ readWorkspaceBytes,
2538
+ readWorkspaceDir,
2539
+ statWorkspacePath,
2540
+ workspacePathExists,
2541
+ GIT_TIMEOUT_MS,
2542
+ updateRemoteToken,
2543
+ verifyGitCredential,
2544
+ forceFreshMintBlocked,
2545
+ recordForceFreshFailure,
2546
+ clearForceFreshCooldown,
2547
+ forceFreshCooldownNotice,
2548
+ ensureOnTaskBranch,
2549
+ hasUncommittedChanges,
2550
+ getCurrentBranch,
2551
+ hasUnpushedCommits,
2552
+ remoteMatchesLocalHead,
2553
+ stageAndCommit,
2554
+ restoreWipSnapshot,
2555
+ flushPendingChanges,
2556
+ pushToOrigin,
2557
+ flushAllPendingWork,
2558
+ awaitGitReady,
2559
+ PortDiscovery,
2560
+ CodespacePortVisibility,
2561
+ loadForwardPorts,
2562
+ buildSessionPreviewPorts,
2563
+ loadConveyorConfig
2564
+ };