@dev-anywhere/proxy 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/{autostart-C3RNQ65S.js → autostart-ZQ5YVCZY.js} +2 -2
  2. package/dist/{chunk-V4HDLUAQ.js → chunk-25JBQRJI.js} +20 -4
  3. package/dist/chunk-25JBQRJI.js.map +1 -0
  4. package/dist/chunk-44SDJYGT.js +344 -0
  5. package/dist/chunk-44SDJYGT.js.map +1 -0
  6. package/dist/{chunk-KINQESTO.js → chunk-CMADETTC.js} +7 -5
  7. package/dist/chunk-CMADETTC.js.map +1 -0
  8. package/dist/{chunk-MLE2OKCM.js → chunk-H623APEF.js} +3 -3
  9. package/dist/{chunk-MLE2OKCM.js.map → chunk-H623APEF.js.map} +1 -1
  10. package/dist/{chunk-74HWO753.js → chunk-M72SC32A.js} +3 -3
  11. package/dist/{chunk-VHMAUU72.js → chunk-QZ3OZJBG.js} +2 -2
  12. package/dist/{chunk-GFDOVLGL.js → chunk-WLXTXXNY.js} +246 -6
  13. package/dist/chunk-WLXTXXNY.js.map +1 -0
  14. package/dist/index.js +8 -8
  15. package/dist/index.js.map +1 -1
  16. package/dist/serve.js +3735 -4061
  17. package/dist/serve.js.map +1 -1
  18. package/dist/session-worker.js +3 -3
  19. package/dist/{terminal-7JY6J3XN.js → terminal-PIFFUL2A.js} +16 -42
  20. package/dist/terminal-PIFFUL2A.js.map +1 -0
  21. package/dist/terminal-worker.js +222 -284
  22. package/dist/terminal-worker.js.map +1 -1
  23. package/dist/update-runner.js +1 -1
  24. package/package.json +3 -3
  25. package/dist/chunk-77NR262K.js +0 -219
  26. package/dist/chunk-77NR262K.js.map +0 -1
  27. package/dist/chunk-GFDOVLGL.js.map +0 -1
  28. package/dist/chunk-KINQESTO.js.map +0 -1
  29. package/dist/chunk-V4HDLUAQ.js.map +0 -1
  30. package/dist/terminal-7JY6J3XN.js.map +0 -1
  31. /package/dist/{autostart-C3RNQ65S.js.map → autostart-ZQ5YVCZY.js.map} +0 -0
  32. /package/dist/{chunk-74HWO753.js.map → chunk-M72SC32A.js.map} +0 -0
  33. /package/dist/{chunk-VHMAUU72.js.map → chunk-QZ3OZJBG.js.map} +0 -0
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ PtyRuntime,
4
+ parseTerminalWorkerBootstrap,
5
+ parseTerminalWorkerCliArgs
6
+ } from "./chunk-44SDJYGT.js";
2
7
  import {
3
8
  IpcProtocolError,
4
9
  ReconnectSupervisor,
@@ -8,35 +13,24 @@ import {
8
13
  swapServeSocket,
9
14
  tryConnect,
10
15
  waitForMessage
11
- } from "./chunk-74HWO753.js";
16
+ } from "./chunk-M72SC32A.js";
12
17
  import "./chunk-2YUDGRJ6.js";
13
- import {
14
- PtyRenderSequencer,
15
- PtySynchronizedOutputCoalescer,
16
- extractOscSignals,
17
- extractOscWorkingDirectory
18
- } from "./chunk-GFDOVLGL.js";
18
+ import "./chunk-WLXTXXNY.js";
19
19
  import "./chunk-DAFUSBKJ.js";
20
20
  import "./chunk-PCF2R2TG.js";
21
+ import "./chunk-QZ3OZJBG.js";
21
22
  import {
22
- PTY_INITIAL_MAX_COLS,
23
- PTY_INITIAL_MAX_ROWS,
24
- PTY_INITIAL_MIN_COLS,
25
- PTY_INITIAL_MIN_ROWS,
23
+ ControlErrorCode,
26
24
  TERMINAL_IPC_PROTOCOL_VERSION,
27
25
  createIpcReader,
28
26
  encodeBinaryIpcFrame,
29
27
  serializeIpc
30
- } from "./chunk-V4HDLUAQ.js";
28
+ } from "./chunk-25JBQRJI.js";
31
29
  import "./chunk-77QVUYU7.js";
32
30
  import {
33
31
  sanitizeProviderErrorTail
34
32
  } from "./chunk-J5V2TKSV.js";
35
- import {
36
- defaultShell,
37
- normalizeProcessEnvironment,
38
- prepareCommandLaunch
39
- } from "./chunk-KINQESTO.js";
33
+ import "./chunk-CMADETTC.js";
40
34
  import {
41
35
  terminalLogger
42
36
  } from "./chunk-KWODOJBK.js";
@@ -44,199 +38,139 @@ import {
44
38
  SOCK_PATH,
45
39
  STOPPED_PATH
46
40
  } from "./chunk-YK2XKOP4.js";
47
- import "./chunk-ICSO3ZIS.js";
41
+ import {
42
+ flushLogger
43
+ } from "./chunk-ICSO3ZIS.js";
48
44
 
49
45
  // src/terminal-worker.ts
50
- import * as pty from "node-pty";
51
46
  import { existsSync } from "fs";
52
-
53
- // src/terminal-worker-args.ts
54
- function parseDimension(value, max) {
55
- const parsed = Number(value);
56
- if (!Number.isInteger(parsed) || parsed <= 0) return null;
57
- return Math.min(max, parsed);
58
- }
59
- function parseTerminalWorkerCliArgs(argv) {
60
- let index = 0;
61
- while (index < argv.length) {
62
- const arg = argv[index];
63
- if (arg === "--profile") {
64
- index += 2;
65
- continue;
66
- }
67
- if (arg?.startsWith("--profile=")) {
68
- index += 1;
69
- continue;
70
- }
71
- if (arg === "--") {
72
- index += 1;
73
- break;
74
- }
75
- break;
76
- }
77
- const [sessionId2, cwd2, name2, colsValue, rowsValue] = argv.slice(index);
78
- if (!sessionId2 || !cwd2 || !name2) return null;
79
- const cols2 = parseDimension(colsValue, PTY_INITIAL_MAX_COLS);
80
- const rows2 = parseDimension(rowsValue, PTY_INITIAL_MAX_ROWS);
81
- if (cols2 === null || rows2 === null) return null;
82
- return {
83
- sessionId: sessionId2,
84
- cwd: cwd2,
85
- name: name2,
86
- cols: Math.max(PTY_INITIAL_MIN_COLS, cols2),
87
- rows: Math.max(PTY_INITIAL_MIN_ROWS, rows2)
88
- };
89
- }
90
-
91
- // src/terminal-worker.ts
92
- var RECONNECT_INITIAL_DELAY_MS = 1e3;
93
- var RECONNECT_MAX_DELAY_MS = 5e3;
94
- var SPAWN_FAILURE_THRESHOLD = 3;
95
47
  var TerminalRegistrationRejectedError = class extends Error {
96
- constructor(message) {
97
- super(message);
98
- this.name = "TerminalRegistrationRejectedError";
99
- }
100
48
  };
101
- function normalizeTerminalWorkerEnv(env) {
102
- const normalized = {};
103
- for (const [key, value] of Object.entries(normalizeProcessEnvironment(env))) {
104
- if (value !== void 0) normalized[key] = value;
105
- }
106
- delete normalized.NO_COLOR;
107
- if (normalized.CLICOLOR === "0") delete normalized.CLICOLOR;
108
- normalized.TERM = "xterm-256color";
109
- normalized.COLORTERM = "truecolor";
110
- normalized.CLICOLOR = "1";
111
- return normalized;
112
- }
113
- var ShellTerminalWorker = class {
114
- constructor(sessionId2, cwd2, name2, cols2, rows2) {
115
- this.sessionId = sessionId2;
116
- this.cwd = cwd2;
117
- this.name = name2;
118
- this.currentCwd = cwd2;
119
- this.renderSequencer = new PtyRenderSequencer({ cols: cols2, rows: rows2 });
120
- this.synchronizedOutput = new PtySynchronizedOutputCoalescer({
121
- emit: (data) => this.emitRenderData(data),
122
- onOverflow: (event) => {
123
- terminalLogger.warn(
124
- { sessionId: this.sessionId, ...event },
125
- "PTY synchronized-output transaction exceeded buffer limit; streaming remainder"
126
- );
127
- }
128
- });
49
+ var TerminalWorker = class {
50
+ constructor(identity, bootstrap) {
51
+ this.identity = identity;
52
+ this.bootstrap = bootstrap;
53
+ this.currentCwd = bootstrap.cwd;
129
54
  }
130
- sessionId;
131
- cwd;
132
- name;
55
+ identity;
56
+ bootstrap;
133
57
  socket = null;
134
- child = null;
135
- renderSequencer;
58
+ runtime = null;
136
59
  exiting = false;
60
+ approvalWaiting = false;
61
+ currentCwd;
137
62
  reconnectSupervisor = new ReconnectSupervisor({
138
- initialDelayMs: RECONNECT_INITIAL_DELAY_MS,
139
- maxDelayMs: RECONNECT_MAX_DELAY_MS
63
+ initialDelayMs: 1e3,
64
+ maxDelayMs: 5e3
140
65
  });
141
- currentCwd;
142
- outputTail = "";
143
- synchronizedOutput;
144
66
  async run() {
67
+ process.on("SIGTERM", () => this.shutdown(143));
68
+ process.on("SIGINT", () => this.shutdown(130));
145
69
  this.socket = await ensureService("connect-only");
146
- await requestTerminalAdmission(this.socket, {
70
+ await this.admit(this.socket);
71
+ this.setupSocketHandlers(this.socket);
72
+ await this.registerWithServe();
73
+ try {
74
+ this.startPty();
75
+ } catch (error) {
76
+ const message = error instanceof Error ? error.message : String(error);
77
+ terminalLogger.error(
78
+ { sessionId: this.identity.sessionId, error: message },
79
+ "Terminal worker PTY failed to start"
80
+ );
81
+ this.exit({
82
+ exitCode: 1,
83
+ errorTail: sanitizeProviderErrorTail(message),
84
+ runtimeError: { errorCode: ControlErrorCode.PROCESS_START_FAILED, error: message }
85
+ });
86
+ }
87
+ }
88
+ async admit(socket) {
89
+ await requestTerminalAdmission(socket, {
147
90
  clientKind: "terminal-worker",
148
91
  terminalProtocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
149
- sessionId: this.sessionId
92
+ sessionId: this.identity.sessionId
150
93
  });
151
- this.setupSocketHandlers(this.socket);
152
- await this.registerWithServe();
153
- this.startPty();
154
- process.on("SIGTERM", () => this.shutdown(143));
155
- process.on("SIGINT", () => this.shutdown(130));
156
94
  }
157
95
  async registerWithServe() {
158
96
  if (!this.socket?.writable) throw new Error("Serve socket is not writable");
159
97
  const responsePromise = waitForMessage(this.socket, "session_create_response");
98
+ const registration = {
99
+ type: "session_create_request",
100
+ protocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
101
+ mode: "pty",
102
+ cwd: this.currentCwd,
103
+ pid: process.pid,
104
+ sessionId: this.identity.sessionId,
105
+ name: this.bootstrap.name
106
+ };
160
107
  this.socket.write(
161
- serializeIpc({
162
- type: "session_create_request",
163
- protocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
164
- mode: "pty",
165
- provider: "claude",
166
- cwd: this.currentCwd,
167
- pid: process.pid,
168
- sessionId: this.sessionId,
169
- name: this.name,
170
- kind: "terminal"
171
- })
108
+ serializeIpc(
109
+ this.identity.kind === "terminal" ? { ...registration, kind: "terminal", provider: "claude" } : { ...registration, kind: "agent", provider: this.identity.provider }
110
+ )
172
111
  );
173
112
  let response;
174
113
  try {
175
114
  response = await responsePromise;
176
115
  } catch (error) {
177
- if (error instanceof IpcProtocolError) {
116
+ if (error instanceof IpcProtocolError)
178
117
  throw new TerminalRegistrationRejectedError(error.message);
179
- }
180
118
  throw error;
181
119
  }
182
- if (!response.success) {
183
- this.socket.destroy();
120
+ if (!response.success)
184
121
  throw new TerminalRegistrationRejectedError(
185
122
  `Failed to register terminal worker: ${response.error}`
186
123
  );
187
- }
188
124
  this.socket.write(
189
- serializeIpc({ type: "pty_register", sessionId: this.sessionId, pid: process.pid })
125
+ serializeIpc({ type: "pty_register", sessionId: this.identity.sessionId, pid: process.pid })
190
126
  );
191
- terminalLogger.info({ sessionId: this.sessionId }, "Terminal worker registered with serve");
127
+ this.runtime?.replaySemanticState();
128
+ terminalLogger.info({ sessionId: this.identity.sessionId }, "Terminal worker registered with serve");
192
129
  }
193
130
  startPty() {
194
- if (this.child) return;
195
- const shell = defaultShell();
196
- const launch = prepareCommandLaunch(shell, [], process.env, process.platform, this.cwd);
197
- const child = pty.spawn(launch.command, launch.ptyArgs ?? launch.args, {
198
- name: "xterm-256color",
199
- cols: this.renderSequencer.cols,
200
- rows: this.renderSequencer.rows,
201
- cwd: this.cwd,
202
- env: normalizeTerminalWorkerEnv(launch.env)
203
- });
204
- this.child = child;
205
- child.onData((data) => this.handlePtyData(data));
206
- child.onExit(({ exitCode, signal }) => {
207
- const code = signal ? 128 + signal : exitCode;
208
- terminalLogger.info({ sessionId: this.sessionId, code }, "Terminal worker PTY exited");
209
- const errorTail = code === 0 ? "" : sanitizeProviderErrorTail(this.outputTail);
210
- this.exit(code, errorTail || void 0);
211
- });
212
- terminalLogger.info(
213
- { sessionId: this.sessionId, pid: child.pid, shell, cwd: this.cwd },
214
- "Terminal worker PTY started"
215
- );
216
- }
217
- handlePtyData(data) {
218
- this.outputTail = `${this.outputTail}${data}`.slice(-8192);
219
- this.synchronizedOutput.push(data);
220
- const signal = extractOscSignals(data);
221
- const cwd2 = extractOscWorkingDirectory(data);
222
- if (cwd2 && cwd2 !== this.currentCwd) {
223
- this.currentCwd = cwd2;
224
- if (this.socket?.writable) {
225
- this.socket.write(serializeIpc({ type: "pty_cwd_change", sessionId: this.sessionId, cwd: cwd2 }));
131
+ if (this.runtime) return;
132
+ const { sessionId } = this.identity;
133
+ const bootstrap = this.bootstrap;
134
+ const base = {
135
+ sessionId,
136
+ cwd: bootstrap.cwd,
137
+ cols: bootstrap.cols,
138
+ rows: bootstrap.rows,
139
+ env: process.env
140
+ };
141
+ this.runtime = new PtyRuntime(
142
+ bootstrap.kind === "terminal" ? { ...base, kind: "terminal", shell: bootstrap.shell } : {
143
+ ...base,
144
+ kind: "agent",
145
+ provider: bootstrap.provider,
146
+ args: bootstrap.args,
147
+ permissionMode: bootstrap.permissionMode,
148
+ nativeSessionId: bootstrap.nativeSessionId,
149
+ hook: bootstrap.hook
150
+ },
151
+ {
152
+ output: (data, outputSeq) => {
153
+ if (this.socket?.writable)
154
+ this.socket.write(
155
+ encodeBinaryIpcFrame(sessionId, Buffer.from(data, "utf8"), outputSeq)
156
+ );
157
+ },
158
+ resize: (cols, rows, outputSeq) => this.send({ type: "pty_resize", sessionId, cols, rows, outputSeq }),
159
+ title: (title) => this.send({ type: "pty_title_change", sessionId, title }),
160
+ cwd: (cwd) => {
161
+ if (cwd === this.currentCwd) return;
162
+ this.currentCwd = cwd;
163
+ this.send({ type: "pty_cwd_change", sessionId, cwd });
164
+ },
165
+ semantic: (state, seq, meta) => this.send({ type: "pty_semantic_event", sessionId, state, seq, ...meta }),
166
+ exit: (event) => this.exit(event)
226
167
  }
227
- }
228
- if (signal?.title && this.socket?.writable) {
229
- this.socket.write(
230
- serializeIpc({ type: "pty_title_change", sessionId: this.sessionId, title: signal.title })
231
- );
232
- }
168
+ );
169
+ this.runtime.setApprovalWaiting(this.approvalWaiting);
170
+ this.runtime.start();
233
171
  }
234
- emitRenderData(data) {
235
- if (!data) return;
236
- const outputSeq = this.renderSequencer.write(data);
237
- if (outputSeq === null) return;
238
- if (!this.socket?.writable) return;
239
- this.socket.write(encodeBinaryIpcFrame(this.sessionId, Buffer.from(data, "utf-8"), outputSeq));
172
+ send(message) {
173
+ if (this.socket?.writable) this.socket.write(serializeIpc(message));
240
174
  }
241
175
  setupSocketHandlers(socket) {
242
176
  createIpcReader(
@@ -248,42 +182,56 @@ var ShellTerminalWorker = class {
248
182
  }
249
183
  );
250
184
  socket.on("close", () => {
251
- if (this.exiting) return;
185
+ if (this.exiting || this.socket !== socket) return;
252
186
  terminalLogger.info(
253
- { sessionId: this.sessionId },
187
+ { sessionId: this.identity.sessionId },
254
188
  "Serve socket closed; terminal worker will reconnect"
255
189
  );
256
- void this.reconnectToServe();
257
- });
258
- socket.on("error", (err) => {
259
- terminalLogger.warn({ sessionId: this.sessionId, err: err.message }, "Terminal worker socket error");
190
+ this.reconnectToServe();
260
191
  });
192
+ socket.on(
193
+ "error",
194
+ (err) => terminalLogger.warn(
195
+ { sessionId: this.identity.sessionId, err: err.message },
196
+ "Terminal worker socket error"
197
+ )
198
+ );
261
199
  }
262
200
  handleServeMessage(msg) {
263
- if ("sessionId" in msg && msg.sessionId !== this.sessionId) return;
201
+ if ("sessionId" in msg && msg.sessionId !== this.identity.sessionId) return;
264
202
  switch (msg.type) {
265
203
  case "pty_input":
266
- this.child?.write(msg.data);
204
+ this.runtime?.write(msg.data);
205
+ terminalLogger.debug(
206
+ { sessionId: this.identity.sessionId, traceId: msg.traceId, bytes: msg.data.length },
207
+ "Raw PTY input written to worker PTY"
208
+ );
267
209
  break;
268
- case "pty_subscribe":
269
- {
270
- const responseSocket = this.socket;
271
- if (!responseSocket?.writable) break;
272
- this.renderSequencer.captureSnapshot((snapshot) => {
273
- if (this.socket !== responseSocket || !responseSocket.writable) return;
274
- responseSocket.write(
275
- serializeIpc({
276
- type: "pty_snapshot",
277
- sessionId: this.sessionId,
278
- ...snapshot,
279
- requestId: msg.requestId
280
- })
281
- );
282
- });
283
- }
210
+ case "pty_subscribe": {
211
+ const responseSocket = this.socket;
212
+ if (!responseSocket?.writable) break;
213
+ this.runtime?.snapshot((snapshot) => {
214
+ if (this.socket !== responseSocket || !responseSocket.writable) return;
215
+ responseSocket.write(
216
+ serializeIpc({
217
+ type: "pty_snapshot",
218
+ sessionId: this.identity.sessionId,
219
+ ...snapshot,
220
+ requestId: msg.requestId
221
+ })
222
+ );
223
+ });
284
224
  break;
225
+ }
285
226
  case "pty_resize_request":
286
- this.resize(msg.cols, msg.rows);
227
+ this.runtime?.resize(msg.cols, msg.rows);
228
+ break;
229
+ case "pty_approval_context":
230
+ this.approvalWaiting = msg.waiting;
231
+ this.runtime?.setApprovalWaiting(msg.waiting);
232
+ break;
233
+ case "bridge_status":
234
+ if (msg.connected) this.runtime?.replaySemanticState();
287
235
  break;
288
236
  case "pty_terminate":
289
237
  this.shutdown(0);
@@ -293,131 +241,121 @@ var ShellTerminalWorker = class {
293
241
  break;
294
242
  }
295
243
  }
296
- resize(cols2, rows2) {
297
- this.synchronizedOutput.flush();
298
- const outputSeq = this.renderSequencer.resize(cols2, rows2);
299
- if (outputSeq === null) return;
300
- if (this.socket?.writable) {
301
- this.socket.write(
302
- serializeIpc({
303
- type: "pty_resize",
304
- sessionId: this.sessionId,
305
- cols: cols2,
306
- rows: rows2,
307
- outputSeq
308
- })
309
- );
310
- }
311
- this.child?.resize(cols2, rows2);
312
- terminalLogger.info({ sessionId: this.sessionId, cols: cols2, rows: rows2 }, "Terminal worker PTY resized");
313
- }
314
244
  reconnectToServe() {
315
245
  let consecutiveSpawnFailures = 0;
316
246
  const run = this.reconnectSupervisor.request({
317
247
  shouldStop: () => this.exiting,
318
248
  attempt: async (attempt) => {
319
- const stopped = existsSync(STOPPED_PATH);
320
- const degraded = consecutiveSpawnFailures >= SPAWN_FAILURE_THRESHOLD;
321
- const passive = stopped || degraded;
249
+ const passive = existsSync(STOPPED_PATH) || consecutiveSpawnFailures >= 3;
250
+ let candidate = null;
322
251
  try {
323
- const newSocket = passive ? await tryConnect(SOCK_PATH) : await ensureService("reconnect");
324
- if (!newSocket) return "retry";
325
- await requestTerminalAdmission(newSocket, {
326
- clientKind: "terminal-worker",
327
- terminalProtocolVersion: TERMINAL_IPC_PROTOCOL_VERSION,
328
- sessionId: this.sessionId
329
- });
252
+ candidate = passive ? await tryConnect(SOCK_PATH) : await ensureService("reconnect");
253
+ if (!candidate) return "retry";
254
+ await this.admit(candidate);
330
255
  consecutiveSpawnFailures = 0;
331
- this.socket = this.socket ? swapServeSocket(this.socket, newSocket) : newSocket;
256
+ this.socket = this.socket ? swapServeSocket(this.socket, candidate) : candidate;
332
257
  this.setupSocketHandlers(this.socket);
333
258
  await this.registerWithServe();
334
- terminalLogger.info({ sessionId: this.sessionId, attempt }, "Terminal worker reconnected to serve");
259
+ terminalLogger.info(
260
+ { sessionId: this.identity.sessionId, attempt },
261
+ "Terminal worker reconnected to serve"
262
+ );
335
263
  return "connected";
336
264
  } catch (err) {
337
- const failedSocket = this.socket;
338
- this.socket = null;
339
- failedSocket?.destroy();
265
+ candidate?.destroy();
266
+ if (this.socket === candidate) this.socket = null;
340
267
  terminalLogger.warn(
341
268
  {
342
- sessionId: this.sessionId,
269
+ sessionId: this.identity.sessionId,
343
270
  attempt,
344
271
  err: err instanceof Error ? err.message : String(err)
345
272
  },
346
273
  "Terminal worker reconnect failed"
347
274
  );
348
- if (err instanceof TerminalRegistrationRejectedError) {
349
- this.shutdown(1);
350
- return "stop";
351
- }
352
- if (err instanceof TerminalAdmissionRetiredError) {
275
+ if (err instanceof TerminalRegistrationRejectedError || err instanceof TerminalAdmissionRetiredError) {
353
276
  this.shutdown(1);
354
277
  return "stop";
355
278
  }
356
- if (!passive) {
357
- consecutiveSpawnFailures += 1;
358
- if (consecutiveSpawnFailures === SPAWN_FAILURE_THRESHOLD) {
359
- terminalLogger.warn(
360
- { sessionId: this.sessionId, failures: consecutiveSpawnFailures },
361
- "Terminal worker daemon auto-start disabled after repeated failures"
362
- );
363
- }
279
+ if (!passive && ++consecutiveSpawnFailures === 3) {
280
+ terminalLogger.warn(
281
+ { sessionId: this.identity.sessionId, failures: consecutiveSpawnFailures },
282
+ "Terminal worker daemon auto-start disabled after repeated failures"
283
+ );
364
284
  }
365
285
  return "retry";
366
286
  }
367
287
  }
368
288
  });
369
- if (!run.started) return;
370
- void run.completion.catch((err) => {
371
- terminalLogger.error(
372
- { sessionId: this.sessionId, err: err instanceof Error ? err.message : String(err) },
373
- "Terminal worker reconnect loop failed"
374
- );
375
- this.shutdown(1);
376
- });
289
+ if (run.started)
290
+ void run.completion.catch((err) => {
291
+ terminalLogger.error(
292
+ {
293
+ sessionId: this.identity.sessionId,
294
+ err: err instanceof Error ? err.message : String(err)
295
+ },
296
+ "Terminal worker reconnect loop failed"
297
+ );
298
+ this.shutdown(1);
299
+ });
377
300
  }
378
- shutdown(code) {
301
+ shutdown(exitCode) {
379
302
  if (this.exiting) return;
380
- this.exiting = true;
381
- try {
382
- this.child?.kill();
383
- } catch {
384
- }
385
- this.exit(code);
303
+ this.runtime?.terminate();
304
+ this.exit({ exitCode });
386
305
  }
387
- exit(code, errorTail) {
388
- if (this.exiting && !this.child) return;
306
+ exit(event) {
307
+ if (this.exiting) return;
389
308
  this.exiting = true;
390
- this.child = null;
391
- this.synchronizedOutput.dispose();
392
- this.renderSequencer.dispose();
309
+ this.runtime?.terminate();
310
+ this.runtime = null;
311
+ terminalLogger.info({ sessionId: this.identity.sessionId, ...event }, "Terminal worker PTY exited");
393
312
  if (this.socket?.writable) {
394
- const socket = this.socket;
395
- const timer = setTimeout(() => process.exit(code), 500);
396
- socket.end(
397
- serializeIpc({
398
- type: "pty_deregister",
399
- sessionId: this.sessionId,
400
- exitCode: code,
401
- ...errorTail ? { errorTail } : {}
402
- }),
313
+ const timer = setTimeout(() => process.exit(event.exitCode), 500);
314
+ this.socket.end(
315
+ serializeIpc({ type: "pty_deregister", sessionId: this.identity.sessionId, ...event }),
403
316
  () => {
404
317
  clearTimeout(timer);
405
- process.exit(code);
318
+ process.exit(event.exitCode);
406
319
  }
407
320
  );
408
- return;
409
- }
410
- process.exit(code);
321
+ } else process.exit(event.exitCode);
411
322
  }
412
323
  };
413
- var parsedArgs = parseTerminalWorkerCliArgs(process.argv.slice(2));
414
- if (!parsedArgs) {
415
- console.error("Usage: terminal-worker [--profile <name>] <sessionId> <cwd> <name> <cols> <rows>");
416
- process.exit(1);
324
+ function readBootstrap() {
325
+ return new Promise((resolve, reject) => {
326
+ let raw = "";
327
+ const timer = setTimeout(() => reject(new Error("Terminal worker bootstrap timed out")), 5e3);
328
+ process.stdin.setEncoding("utf8");
329
+ process.stdin.on("data", (chunk) => {
330
+ raw += chunk;
331
+ if (raw.length > 65536) {
332
+ clearTimeout(timer);
333
+ reject(new Error("Terminal worker bootstrap exceeds size limit"));
334
+ process.stdin.destroy();
335
+ }
336
+ });
337
+ process.stdin.once("end", () => {
338
+ clearTimeout(timer);
339
+ resolve(raw);
340
+ });
341
+ process.stdin.once("error", (error) => {
342
+ clearTimeout(timer);
343
+ reject(error);
344
+ });
345
+ });
346
+ }
347
+ async function main() {
348
+ const identity = parseTerminalWorkerCliArgs(process.argv.slice(2));
349
+ if (!identity)
350
+ throw new Error(
351
+ "Usage: terminal-worker --profile <name> --session <id> --kind <agent|terminal> --provider <provider>"
352
+ );
353
+ const bootstrap = parseTerminalWorkerBootstrap(await readBootstrap(), identity);
354
+ await new TerminalWorker(identity, bootstrap).run();
417
355
  }
418
- var { sessionId, cwd, name, cols, rows } = parsedArgs;
419
- new ShellTerminalWorker(sessionId, cwd, name, cols, rows).run().catch((err) => {
356
+ void main().catch(async (err) => {
420
357
  terminalLogger.error({ err: err instanceof Error ? err.message : String(err) }, "Terminal worker failed");
358
+ await flushLogger(terminalLogger);
421
359
  process.exit(1);
422
360
  });
423
361
  //# sourceMappingURL=terminal-worker.js.map