@moxt-ai/cli 0.10.0-beta.6 → 0.10.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7383,9 +7383,40 @@ function createAppServerEnvironment(environment) {
7383
7383
  function digestOpaque(value) {
7384
7384
  return (0, import_node_crypto6.createHash)("sha256").update(value).digest("hex");
7385
7385
  }
7386
- function extractCodexVersion(userAgent) {
7386
+ async function resolveCodexVersion(options) {
7387
+ const userAgentVersion = extractKnownCodexVersion(options.userAgent).value;
7388
+ if (userAgentVersion !== void 0) {
7389
+ return userAgentVersion;
7390
+ }
7391
+ const executableVersion = (await probeCodexVersion(options.executable, options.processBaseDirectory, options.environment)).value;
7392
+ return executableVersion ?? options.userAgent.slice(0, 64);
7393
+ }
7394
+ function extractKnownCodexVersion(userAgent) {
7387
7395
  const matched = /(?:codex_cli_rs|codex-cli|codex(?: desktop)?)\/([0-9][^\s/]*)/i.exec(userAgent);
7388
- return matched?.[1] ?? userAgent.slice(0, 64);
7396
+ return matched === null ? {} : { value: matched[1] };
7397
+ }
7398
+ async function probeCodexVersion(executable, processBaseDirectory, environment) {
7399
+ const result = await new Promise((resolve10) => {
7400
+ (0, import_node_child_process3.execFile)(executable, ["--version"], {
7401
+ cwd: processBaseDirectory,
7402
+ encoding: "utf8",
7403
+ env: { ...environment },
7404
+ maxBuffer: maximumCodexVersionOutputBytes,
7405
+ timeout: codexVersionProbeTimeoutMilliseconds,
7406
+ windowsHide: true
7407
+ }, (error, stdout) => {
7408
+ if (error !== null || typeof stdout !== "string") {
7409
+ resolve10({});
7410
+ return;
7411
+ }
7412
+ resolve10({ output: stdout });
7413
+ });
7414
+ });
7415
+ if (result.output === void 0) {
7416
+ return {};
7417
+ }
7418
+ const matched = /(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?=\s|$)/.exec(result.output);
7419
+ return matched === null ? {} : { value: matched[1] };
7389
7420
  }
7390
7421
  function assertSupportedCodexVersion(codexVersion) {
7391
7422
  const parsed = /^(\d+)\.(\d+)\.(\d+)/.exec(codexVersion);
@@ -7667,7 +7698,7 @@ function stopWindowsProcessTree(child) {
7667
7698
  failureMessage: stopped.error?.message ?? `taskkill exited with status ${String(stopped.status)}`
7668
7699
  };
7669
7700
  }
7670
- var import_node_child_process3, import_node_crypto6, import_node_fs2, import_node_os6, maximumFrameBytes, requestTimeoutMilliseconds2, processExitGraceMilliseconds, processTreePollMilliseconds, processTableTimeoutMilliseconds, processTableRetryMilliseconds, maximumProcessTableAttempts, maximumProcessTableBytes, maximumStderrTailCharacters, minimumCodexVersion, defaultProcessTableExecutable, appServerArguments, AppServerProcessTreeCaptureStatus, AppServerProcessLostError, AppServerProtocolError, AppServerUnsupportedVersionError, AppServerRequestTimeoutError, AppServerResponseError, AppServerClient, LocalCodexAppServerSupervisor;
7701
+ var import_node_child_process3, import_node_crypto6, import_node_fs2, import_node_os6, maximumFrameBytes, requestTimeoutMilliseconds2, processExitGraceMilliseconds, processTreePollMilliseconds, processTableTimeoutMilliseconds, processTableRetryMilliseconds, maximumProcessTableAttempts, maximumProcessTableBytes, maximumStderrTailCharacters, codexVersionProbeTimeoutMilliseconds, maximumCodexVersionOutputBytes, minimumCodexVersion, defaultProcessTableExecutable, appServerArguments, AppServerProcessTreeCaptureStatus, AppServerProcessLostError, AppServerProtocolError, AppServerUnsupportedVersionError, AppServerRequestTimeoutError, AppServerResponseError, AppServerClient, LocalCodexAppServerSupervisor;
7671
7702
  var init_app_server_client = __esm({
7672
7703
  "../machine-connector/dist/runtime/local-codex-runtime/app-server-client.js"() {
7673
7704
  "use strict";
@@ -7687,6 +7718,8 @@ var init_app_server_client = __esm({
7687
7718
  maximumProcessTableAttempts = 3;
7688
7719
  maximumProcessTableBytes = 8e6;
7689
7720
  maximumStderrTailCharacters = 4e3;
7721
+ codexVersionProbeTimeoutMilliseconds = 5e3;
7722
+ maximumCodexVersionOutputBytes = 4096;
7690
7723
  minimumCodexVersion = "0.146.0";
7691
7724
  defaultProcessTableExecutable = resolveDefaultProcessTableExecutable();
7692
7725
  appServerArguments = [
@@ -7806,7 +7839,12 @@ var init_app_server_client = __esm({
7806
7839
  version: connectorVersion
7807
7840
  }
7808
7841
  });
7809
- const codexVersion = extractCodexVersion(initialized.userAgent);
7842
+ const codexVersion = await resolveCodexVersion({
7843
+ environment,
7844
+ executable,
7845
+ processBaseDirectory: options.processBaseDirectory,
7846
+ userAgent: initialized.userAgent
7847
+ });
7810
7848
  assertSupportedCodexVersion(codexVersion);
7811
7849
  client.initializationCompleted = true;
7812
7850
  await client.notify("initialized");
@@ -8690,9 +8728,11 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8690
8728
  eventUploadQueue: Promise.resolve(),
8691
8729
  fatal,
8692
8730
  finished: new AbortController(),
8731
+ ignoreProcessLoss: false,
8693
8732
  interruptedCleanupStarted: false,
8694
8733
  leaseDeadlineMilliseconds: parseLeaseDeadline(claim.leaseExpiresAt),
8695
8734
  nativeThreadId: durable.snapshot().nativeThreadId ?? claim.nativeThreadId,
8735
+ processQuarantined: false,
8696
8736
  spoolQueue: Promise.resolve(),
8697
8737
  subagentThreadIds: /* @__PURE__ */ new Set(),
8698
8738
  terminal,
@@ -8782,6 +8822,24 @@ function appServerMessageThreadId(message) {
8782
8822
  }
8783
8823
  return optionalString2(safeRecord(params.thread).id);
8784
8824
  }
8825
+ function appServerMessageTurnId(message) {
8826
+ const params = safeRecord(message.params);
8827
+ const direct = optionalString2(params.turnId).value;
8828
+ if (direct !== void 0) {
8829
+ return { value: direct };
8830
+ }
8831
+ return optionalString2(safeRecord(params.turn).id);
8832
+ }
8833
+ function activeOwnsThread(active, threadId) {
8834
+ return active.nativeThreadId === threadId || active.subagentThreadIds.has(threadId) || active.initialThreadName?.generation?.threadId === threadId;
8835
+ }
8836
+ function singleActiveAttempt(attempts) {
8837
+ if (attempts.length !== 1) {
8838
+ return {};
8839
+ }
8840
+ const value = attempts[0];
8841
+ return value === void 0 ? {} : { value };
8842
+ }
8785
8843
  function normalizeThreadTitle(value) {
8786
8844
  const title = Array.from(value.trim().replace(/\s+/g, " ")).slice(0, maximumThreadTitleCharacters).join("");
8787
8845
  return title === "" ? {} : { value: title };
@@ -9082,6 +9140,16 @@ async function waitForAbort(signal, milliseconds) {
9082
9140
  signal.addEventListener("abort", complete, { once: true });
9083
9141
  });
9084
9142
  }
9143
+ function rejectWhenAborted(signal) {
9144
+ return new Promise((_resolve, reject) => {
9145
+ const rejectStopped = () => reject(new WorkerStoppedError());
9146
+ if (signal.aborted) {
9147
+ rejectStopped();
9148
+ return;
9149
+ }
9150
+ signal.addEventListener("abort", rejectStopped, { once: true });
9151
+ });
9152
+ }
9085
9153
  function parseLeaseDeadline(value) {
9086
9154
  const parsed = Date.parse(value);
9087
9155
  if (!Number.isFinite(parsed)) {
@@ -9089,7 +9157,7 @@ function parseLeaseDeadline(value) {
9089
9157
  }
9090
9158
  return parsed;
9091
9159
  }
9092
- var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
9160
+ var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
9093
9161
  var init_runtime_worker = __esm({
9094
9162
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
9095
9163
  "use strict";
@@ -9165,6 +9233,12 @@ var init_runtime_worker = __esm({
9165
9233
  this.name = "UnknownTurnStartResultError";
9166
9234
  }
9167
9235
  };
9236
+ WorkerStoppedError = class extends Error {
9237
+ constructor() {
9238
+ super("Local Codex Runtime worker stopped");
9239
+ this.name = "WorkerStoppedError";
9240
+ }
9241
+ };
9168
9242
  LocalCodexRuntimeConnectionWorker = class {
9169
9243
  connection;
9170
9244
  relay;
@@ -9173,9 +9247,10 @@ var init_runtime_worker = __esm({
9173
9247
  environment;
9174
9248
  connectorInstanceId;
9175
9249
  logger;
9176
- active = {};
9250
+ activeAttempts = /* @__PURE__ */ new Map();
9177
9251
  configured = false;
9178
9252
  enabled = false;
9253
+ executionTasks = /* @__PURE__ */ new Map();
9179
9254
  lastCapabilityStartError;
9180
9255
  lifetimeAbort = new AbortController();
9181
9256
  registered = true;
@@ -9204,13 +9279,55 @@ var init_runtime_worker = __esm({
9204
9279
  }
9205
9280
  revoke() {
9206
9281
  this.lifetimeAbort.abort();
9207
- this.active.value?.finished.abort();
9282
+ for (const active of this.activeAttempts.values()) {
9283
+ active.finished.abort();
9284
+ }
9208
9285
  }
9209
9286
  status() {
9210
9287
  return this.processPool.status();
9211
9288
  }
9289
+ ownsMessage(message) {
9290
+ return this.activeAttemptForMessage(message).value !== void 0;
9291
+ }
9292
+ activeAttemptForMessage(message) {
9293
+ const threadId = appServerMessageThreadId(message).value;
9294
+ const turnId = appServerMessageTurnId(message).value;
9295
+ if (threadId === void 0 && turnId === void 0) {
9296
+ return {};
9297
+ }
9298
+ if (turnId !== void 0) {
9299
+ const exactTurnMatches = [...this.activeAttempts.values()].filter((active) => {
9300
+ if (active.finished.signal.aborted) {
9301
+ return false;
9302
+ }
9303
+ const generation = active.initialThreadName?.generation;
9304
+ const ownsTurn = active.nativeTurnId === turnId || generation?.turnId === turnId;
9305
+ return ownsTurn && (threadId === void 0 || activeOwnsThread(active, threadId));
9306
+ });
9307
+ if (exactTurnMatches.length > 0) {
9308
+ return singleActiveAttempt(exactTurnMatches);
9309
+ }
9310
+ }
9311
+ if (threadId === void 0) {
9312
+ return {};
9313
+ }
9314
+ const threadMatches = [...this.activeAttempts.values()].filter((active) => {
9315
+ if (active.finished.signal.aborted) {
9316
+ return false;
9317
+ }
9318
+ const generation = active.initialThreadName?.generation;
9319
+ const ownsVisibleThread = active.nativeThreadId === threadId;
9320
+ const ownsSubagentThread = active.subagentThreadIds.has(threadId);
9321
+ const ownsTitleThread = generation?.threadId === threadId;
9322
+ if (turnId === void 0) {
9323
+ return ownsVisibleThread || ownsSubagentThread || ownsTitleThread;
9324
+ }
9325
+ return ownsSubagentThread || ownsVisibleThread && active.nativeTurnId === void 0 || ownsTitleThread && generation?.turnId === void 0;
9326
+ });
9327
+ return singleActiveAttempt(threadMatches);
9328
+ }
9212
9329
  async onNotification(message) {
9213
- const active = this.active.value;
9330
+ const active = this.activeAttemptForMessage(message).value;
9214
9331
  if (active === void 0 || active.finished.signal.aborted) {
9215
9332
  return;
9216
9333
  }
@@ -9252,7 +9369,13 @@ var init_runtime_worker = __esm({
9252
9369
  initialThreadName.terminalObserved = true;
9253
9370
  }
9254
9371
  if (normalized.terminalStatus === LocalCodexTurnStatusWire.Interrupted) {
9255
- await this.stopInterruptedExecution(active, normalized);
9372
+ if (active.interruptedCleanupTask === void 0) {
9373
+ const task = this.stopInterruptedExecution(active, normalized).catch((error) => {
9374
+ this.signalFatal(active, error instanceof Error ? error : new Error(String(error)));
9375
+ });
9376
+ active.interruptedCleanupTask = task;
9377
+ void task;
9378
+ }
9256
9379
  return;
9257
9380
  }
9258
9381
  if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0 && !initialThreadName.completed) {
@@ -9279,46 +9402,60 @@ var init_runtime_worker = __esm({
9279
9402
  void this.enqueueEventFlush(active).catch(() => void 0);
9280
9403
  }
9281
9404
  async stopInterruptedExecution(active, normalized) {
9405
+ if (active.interruptedCleanupStarted) {
9406
+ return;
9407
+ }
9282
9408
  active.interruptedCleanupStarted = true;
9409
+ active.ignoreProcessLoss = true;
9283
9410
  active.initialThreadName?.generation?.resolve();
9284
9411
  const client = this.processPool.currentClient().value;
9412
+ let cleanupFailed = false;
9285
9413
  if (client !== void 0 && active.nativeThreadId !== void 0) {
9286
9414
  await Promise.all([active.nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
9287
9415
  try {
9288
9416
  await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
9289
9417
  } catch (error) {
9290
- await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; stopping its App Server process tree`, error);
9418
+ cleanupFailed = true;
9419
+ await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; quarantining the shared App Server`, error);
9291
9420
  }
9292
9421
  }));
9293
9422
  }
9294
- try {
9295
- await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9296
- } catch (error) {
9297
- const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
9298
- await this.enqueueSpool(active, async () => {
9299
- const terminal = await active.durable.appendEvent("turn_failed", {
9300
- message: failure.message,
9301
- status: "runtime_lost"
9302
- }, {
9303
- nativeThreadId: active.nativeThreadId,
9304
- nativeTurnId: active.nativeTurnId
9423
+ const quarantineProcess = cleanupFailed || !this.processPool.hasOtherActiveExecution();
9424
+ if (quarantineProcess) {
9425
+ active.processQuarantined = true;
9426
+ try {
9427
+ if (client === void 0) {
9428
+ await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9429
+ } else {
9430
+ await this.processPool.quarantineProcess(client, active.processTreeCapture);
9431
+ }
9432
+ } catch (error) {
9433
+ const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
9434
+ await this.enqueueSpool(active, async () => {
9435
+ const terminal = await active.durable.appendEvent("turn_failed", {
9436
+ message: failure.message,
9437
+ status: "runtime_lost"
9438
+ }, {
9439
+ nativeThreadId: active.nativeThreadId,
9440
+ nativeTurnId: active.nativeTurnId
9441
+ });
9442
+ const result = {
9443
+ errorCode: "runtime_lost",
9444
+ errorMessage: failure.message,
9445
+ finalSequence: terminal.sequence,
9446
+ status: LocalCodexTurnStatusWire.RuntimeLost
9447
+ };
9448
+ await active.durable.markTerminal(result);
9449
+ this.settleTerminal(active, result);
9305
9450
  });
9306
- const result = {
9307
- errorCode: "runtime_lost",
9308
- errorMessage: failure.message,
9309
- finalSequence: terminal.sequence,
9310
- status: LocalCodexTurnStatusWire.RuntimeLost
9311
- };
9312
- await active.durable.markTerminal(result);
9313
- this.settleTerminal(active, result);
9314
- });
9315
- return;
9451
+ return;
9452
+ }
9316
9453
  }
9317
9454
  this.completeInitialThreadName(active);
9318
9455
  this.persistNormalizedNotification(active, normalized);
9319
9456
  }
9320
9457
  async onServerRequest(message) {
9321
- const active = this.active.value;
9458
+ const active = this.activeAttemptForMessage(message).value;
9322
9459
  const client = this.processPool.currentClient().value;
9323
9460
  const requestId = rpcIdentifier2(message.id).value;
9324
9461
  if (active === void 0 || client === void 0 || requestId === void 0 || message.method === void 0) {
@@ -9360,29 +9497,27 @@ var init_runtime_worker = __esm({
9360
9497
  await this.enqueueEventFlush(active);
9361
9498
  }
9362
9499
  async onProcessExit(error) {
9363
- const active = this.active.value;
9364
- if (active === void 0 || !active.acceptedByAppServer) {
9365
- return;
9366
- }
9367
- active.initialThreadName?.generation?.resolve();
9368
- await this.enqueueSpool(active, async () => {
9369
- await active.durable.appendEvent("runtime_error", { message: error.message }, {
9370
- nativeThreadId: active.nativeThreadId,
9371
- nativeTurnId: active.nativeTurnId
9372
- });
9373
- const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
9374
- nativeThreadId: active.nativeThreadId,
9375
- nativeTurnId: active.nativeTurnId
9500
+ await Promise.all([...this.activeAttempts.values()].filter((active) => active.acceptedByAppServer && !active.finished.signal.aborted && !active.ignoreProcessLoss && active.terminalValue === void 0).map(async (active) => {
9501
+ active.initialThreadName?.generation?.resolve();
9502
+ await this.enqueueSpool(active, async () => {
9503
+ await active.durable.appendEvent("runtime_error", { message: error.message }, {
9504
+ nativeThreadId: active.nativeThreadId,
9505
+ nativeTurnId: active.nativeTurnId
9506
+ });
9507
+ const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
9508
+ nativeThreadId: active.nativeThreadId,
9509
+ nativeTurnId: active.nativeTurnId
9510
+ });
9511
+ const result = {
9512
+ errorCode: "runtime_lost",
9513
+ errorMessage: error.message,
9514
+ finalSequence: terminal.sequence,
9515
+ status: LocalCodexTurnStatusWire.RuntimeLost
9516
+ };
9517
+ await active.durable.markTerminal(result);
9518
+ this.settleTerminal(active, result);
9376
9519
  });
9377
- const result = {
9378
- errorCode: "runtime_lost",
9379
- errorMessage: error.message,
9380
- finalSequence: terminal.sequence,
9381
- status: LocalCodexTurnStatusWire.RuntimeLost
9382
- };
9383
- await active.durable.markTerminal(result);
9384
- this.settleTerminal(active, result);
9385
- });
9520
+ }));
9386
9521
  }
9387
9522
  async runLoops() {
9388
9523
  try {
@@ -9393,13 +9528,16 @@ var init_runtime_worker = __esm({
9393
9528
  this.runRecoveryLoop()
9394
9529
  ]);
9395
9530
  } finally {
9396
- this.active.value?.finished.abort();
9531
+ for (const active of this.activeAttempts.values()) {
9532
+ active.finished.abort();
9533
+ }
9534
+ await Promise.all(this.executionTasks.values());
9397
9535
  this.unregisterRoute();
9398
9536
  }
9399
9537
  }
9400
9538
  async runHeartbeatLoop() {
9401
9539
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9402
- if (this.active.value?.interruptedCleanupStarted) {
9540
+ if ([...this.activeAttempts.values()].some((active) => active.interruptedCleanupStarted)) {
9403
9541
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9404
9542
  continue;
9405
9543
  }
@@ -9421,10 +9559,12 @@ var init_runtime_worker = __esm({
9421
9559
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9422
9560
  continue;
9423
9561
  }
9424
- if (!this.processPool.tryAcquire(this.connection.connectionId)) {
9562
+ const slot = this.processPool.tryAcquireExecutionSlot(this.connection.connectionId).value;
9563
+ if (slot === void 0) {
9425
9564
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9426
9565
  continue;
9427
9566
  }
9567
+ let executionScheduled = false;
9428
9568
  try {
9429
9569
  const capability = this.processPool.status();
9430
9570
  const response = await this.relay.claimCodexRuntime({
@@ -9435,21 +9575,33 @@ var init_runtime_worker = __esm({
9435
9575
  waitSeconds: claimWaitSeconds
9436
9576
  }, this.lifetimeAbort.signal);
9437
9577
  if (response.attempt === void 0) {
9438
- this.processPool.release(this.connection.connectionId);
9439
9578
  continue;
9440
9579
  }
9441
- await this.executeAttempt(response.attempt);
9580
+ this.scheduleExecution(slot, response.attempt);
9581
+ executionScheduled = true;
9442
9582
  } catch (error) {
9443
9583
  if (!this.lifetimeAbort.signal.aborted) {
9444
9584
  await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
9445
9585
  await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
9446
9586
  }
9447
9587
  } finally {
9448
- this.active = {};
9449
- this.processPool.release(this.connection.connectionId);
9588
+ if (!executionScheduled) {
9589
+ this.processPool.releaseExecutionSlot(slot);
9590
+ }
9450
9591
  }
9451
9592
  }
9452
9593
  }
9594
+ scheduleExecution(slot, claim) {
9595
+ if (this.executionTasks.has(claim.attemptId)) {
9596
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already executing`);
9597
+ }
9598
+ this.processPool.markExecutionStarted(slot);
9599
+ const task = this.executeAttempt(claim).catch(async (error) => await this.logger.error(`Local Codex attempt ${claim.attemptId} execution crashed`, error).catch(() => void 0)).finally(() => {
9600
+ this.executionTasks.delete(claim.attemptId);
9601
+ this.processPool.releaseExecutionSlot(slot);
9602
+ });
9603
+ this.executionTasks.set(claim.attemptId, task);
9604
+ }
9453
9605
  async runDiscoveryLoop() {
9454
9606
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9455
9607
  try {
@@ -9552,7 +9704,10 @@ var init_runtime_worker = __esm({
9552
9704
  async executeAttempt(claim) {
9553
9705
  const durable = await DurableLocalCodexAttempt.create(this.store, this.connection.connectionId, this.connectorInstanceId, claim);
9554
9706
  const active = createActiveAttempt(claim, durable, this.connection.rootPath);
9555
- this.active = { value: active };
9707
+ if (this.activeAttempts.has(claim.attemptId)) {
9708
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already active`);
9709
+ }
9710
+ this.activeAttempts.set(claim.attemptId, active);
9556
9711
  const leaseLoop = this.runLeaseLoop(active);
9557
9712
  const controlLoop = this.runControlLoop(active);
9558
9713
  try {
@@ -9629,7 +9784,8 @@ var init_runtime_worker = __esm({
9629
9784
  active.terminal,
9630
9785
  active.fatal.then((error) => {
9631
9786
  throw error;
9632
- })
9787
+ }),
9788
+ rejectWhenAborted(active.finished.signal)
9633
9789
  ]);
9634
9790
  await active.spoolQueue;
9635
9791
  await this.flushAllEvents(active);
@@ -9643,12 +9799,13 @@ var init_runtime_worker = __esm({
9643
9799
  });
9644
9800
  await durable.markUploaded();
9645
9801
  await this.store.deleteLocalCodexAttempt(claim.attemptId);
9646
- if (active.interruptedCleanupStarted) {
9802
+ if (active.processQuarantined) {
9647
9803
  active.finished.abort();
9648
9804
  await this.restoreAppServerAfterInterruption(active);
9649
9805
  }
9650
9806
  } catch (error) {
9651
- if (error instanceof LeaseLostError) {
9807
+ if (error instanceof WorkerStoppedError) {
9808
+ } else if (error instanceof LeaseLostError) {
9652
9809
  await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after losing its execution lease`, error);
9653
9810
  } else if (error instanceof SpoolPersistenceError) {
9654
9811
  try {
@@ -9663,17 +9820,22 @@ var init_runtime_worker = __esm({
9663
9820
  await this.failAttempt(active, error);
9664
9821
  }
9665
9822
  } finally {
9666
- this.completeInitialThreadName(active);
9667
- active.finished.abort();
9668
- await active.initialThreadName?.task;
9669
- const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9670
- if (titleGenerationTurnId !== void 0) {
9671
- this.processPool.retireTurn(titleGenerationTurnId);
9672
- }
9673
- if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
9674
- this.processPool.retireTurn(active.nativeTurnId);
9823
+ try {
9824
+ this.completeInitialThreadName(active);
9825
+ active.finished.abort();
9826
+ await active.interruptedCleanupTask;
9827
+ await active.initialThreadName?.task;
9828
+ const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9829
+ if (titleGenerationTurnId !== void 0) {
9830
+ this.processPool.retireTurn(titleGenerationTurnId);
9831
+ }
9832
+ if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
9833
+ this.processPool.retireTurn(active.nativeTurnId);
9834
+ }
9835
+ await Promise.all([leaseLoop, controlLoop]);
9836
+ } finally {
9837
+ this.activeAttempts.delete(claim.attemptId);
9675
9838
  }
9676
- await Promise.all([leaseLoop, controlLoop]);
9677
9839
  }
9678
9840
  }
9679
9841
  async prepareThread(client, active) {
@@ -9900,6 +10062,7 @@ var init_runtime_worker = __esm({
9900
10062
  async loseLease(active, message) {
9901
10063
  const error = new LeaseLostError(message);
9902
10064
  this.signalFatal(active, error);
10065
+ active.ignoreProcessLoss = true;
9903
10066
  await this.processPool.quarantineCurrentProcess();
9904
10067
  }
9905
10068
  async runControlLoop(active) {
@@ -9986,7 +10149,9 @@ var init_runtime_worker = __esm({
9986
10149
  if (!active.abortRequested || active.abortSent || active.nativeThreadId === void 0 || active.nativeTurnId === void 0) {
9987
10150
  return;
9988
10151
  }
9989
- active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10152
+ if (!this.processPool.hasOtherActiveExecution()) {
10153
+ active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10154
+ }
9990
10155
  await client.request("turn/interrupt", {
9991
10156
  threadId: active.nativeThreadId,
9992
10157
  turnId: active.nativeTurnId
@@ -10350,7 +10515,6 @@ ${titleInput}`,
10350
10515
  if (!this.registered) {
10351
10516
  return;
10352
10517
  }
10353
- this.processPool.release(this.connection.connectionId);
10354
10518
  this.processPool.unregister(this.connection.connectionId);
10355
10519
  this.registered = false;
10356
10520
  }
@@ -10369,18 +10533,20 @@ function localCodexProcessPoolKey(environment, nativeStoreIdentitySeed) {
10369
10533
  "connector-owned-app-server-stdio-v1"
10370
10534
  ].join("\0")).digest("hex");
10371
10535
  }
10372
- var import_node_crypto8, LocalCodexProcessPool;
10536
+ var import_node_crypto8, maximumConcurrentTurns, LocalCodexProcessPool;
10373
10537
  var init_process_pool = __esm({
10374
10538
  "../machine-connector/dist/runtime/local-codex-runtime/process-pool.js"() {
10375
10539
  "use strict";
10376
10540
  init_cjs_shims();
10377
10541
  import_node_crypto8 = require("crypto");
10378
10542
  init_app_server_client();
10543
+ maximumConcurrentTurns = 1e3;
10379
10544
  LocalCodexProcessPool = class {
10380
10545
  poolKey;
10381
10546
  logger;
10382
- activeOwner = {};
10547
+ activeSlots = /* @__PURE__ */ new Map();
10383
10548
  loadedThreadIds = /* @__PURE__ */ new Set();
10549
+ nextSlotId = 1;
10384
10550
  routes = /* @__PURE__ */ new Map();
10385
10551
  retiredTurnIds = /* @__PURE__ */ new Set();
10386
10552
  supervisor;
@@ -10390,7 +10556,7 @@ var init_process_pool = __esm({
10390
10556
  this.logger = logger;
10391
10557
  this.supervisor = new LocalCodexAppServerSupervisor(environment.HOME ?? process.cwd(), environment, nativeStoreIdentitySeed, {
10392
10558
  onNotification: async (message) => {
10393
- await this.activeRoute().value?.onNotification(message);
10559
+ await this.routeNotification(message);
10394
10560
  },
10395
10561
  onProcessExit: async (error, processGeneration) => {
10396
10562
  if (!this.supervisor.markProcessLost(processGeneration)) {
@@ -10398,18 +10564,10 @@ var init_process_pool = __esm({
10398
10564
  }
10399
10565
  this.loadedThreadIds.clear();
10400
10566
  await this.logger.error(`Shared Codex App Server generation ${processGeneration} exited`, error);
10401
- await this.activeRoute().value?.onProcessExit(error);
10567
+ await this.broadcastProcessExit(error);
10402
10568
  },
10403
10569
  onServerRequest: async (message) => {
10404
- const route = this.activeRoute().value;
10405
- if (route !== void 0) {
10406
- await route.onServerRequest(message);
10407
- return;
10408
- }
10409
- const client = this.supervisor.currentClient().value;
10410
- if (client !== void 0 && message.id !== void 0) {
10411
- await client.respondWithError(message.id, -32e3, "No owning Local Codex Runtime turn");
10412
- }
10570
+ await this.routeServerRequest(message);
10413
10571
  },
10414
10572
  onStderr: async (text3) => {
10415
10573
  await this.logger.info("Codex App Server stderr", {
@@ -10427,7 +10585,7 @@ var init_process_pool = __esm({
10427
10585
  this.routes.set(ownerId, route);
10428
10586
  }
10429
10587
  unregister(ownerId) {
10430
- if (this.activeOwner.value === ownerId) {
10588
+ if ([...this.activeSlots.values()].some((slot) => slot.ownerId === ownerId)) {
10431
10589
  throw new Error(`Local Codex route ${ownerId} still owns capacity`);
10432
10590
  }
10433
10591
  this.routes.delete(ownerId);
@@ -10436,27 +10594,35 @@ var init_process_pool = __esm({
10436
10594
  this.waitingOwners.splice(index2, 1);
10437
10595
  }
10438
10596
  }
10439
- tryAcquire(ownerId) {
10597
+ tryAcquireExecutionSlot(ownerId) {
10440
10598
  if (!this.routes.has(ownerId)) {
10441
10599
  throw new Error(`Local Codex route ${ownerId} is not registered`);
10442
10600
  }
10443
- if (this.activeOwner.value === ownerId) {
10444
- return true;
10445
- }
10446
10601
  if (!this.waitingOwners.includes(ownerId)) {
10447
10602
  this.waitingOwners.push(ownerId);
10448
10603
  }
10449
- if (this.activeOwner.value !== void 0 || this.waitingOwners[0] !== ownerId) {
10450
- return false;
10604
+ if (this.activeSlots.size >= maximumConcurrentTurns || this.waitingOwners[0] !== ownerId) {
10605
+ return {};
10451
10606
  }
10452
10607
  this.waitingOwners.shift();
10453
- this.activeOwner = { value: ownerId };
10454
- return true;
10608
+ const value = { ownerId, slotId: this.nextSlotId };
10609
+ this.nextSlotId += 1;
10610
+ this.activeSlots.set(value.slotId, { executing: false, ownerId });
10611
+ return { value };
10455
10612
  }
10456
- release(ownerId) {
10457
- if (this.activeOwner.value === ownerId) {
10458
- this.activeOwner = {};
10613
+ markExecutionStarted(slot) {
10614
+ const active = this.requireActiveSlot(slot);
10615
+ if (active.executing) {
10616
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is already executing`);
10459
10617
  }
10618
+ active.executing = true;
10619
+ }
10620
+ releaseExecutionSlot(slot) {
10621
+ this.requireActiveSlot(slot);
10622
+ this.activeSlots.delete(slot.slotId);
10623
+ }
10624
+ hasOtherActiveExecution() {
10625
+ return [...this.activeSlots.values()].filter((slot) => slot.executing).length > 1;
10460
10626
  }
10461
10627
  retireTurn(nativeTurnId) {
10462
10628
  this.retiredTurnIds.add(nativeTurnId);
@@ -10501,20 +10667,82 @@ var init_process_pool = __esm({
10501
10667
  return client === void 0 ? {} : { value: await client.captureProcessTree() };
10502
10668
  }
10503
10669
  async quarantineCurrentProcess(capture) {
10670
+ const processGeneration = this.supervisor.currentClient().value?.processGeneration;
10671
+ this.loadedThreadIds.clear();
10672
+ try {
10673
+ await this.supervisor.quarantineCurrentProcess(capture);
10674
+ } finally {
10675
+ if (processGeneration !== void 0) {
10676
+ await this.broadcastProcessExit(new AppServerProcessLostError(`Shared Codex App Server generation ${processGeneration} was quarantined`));
10677
+ }
10678
+ }
10679
+ }
10680
+ async quarantineProcess(client, capture) {
10681
+ if (this.supervisor.currentClient().value === client) {
10682
+ await this.quarantineCurrentProcess(capture);
10683
+ return;
10684
+ }
10504
10685
  this.loadedThreadIds.clear();
10505
- await this.supervisor.quarantineCurrentProcess(capture);
10686
+ await client.stop(capture);
10506
10687
  }
10507
10688
  async stop() {
10508
10689
  this.loadedThreadIds.clear();
10509
10690
  await this.supervisor.stop();
10510
10691
  }
10511
- activeRoute() {
10512
- const owner = this.activeOwner.value;
10513
- if (owner === void 0) {
10514
- return {};
10692
+ matchingRoutes(message) {
10693
+ return [...this.routes.values()].filter((route) => route.ownsMessage(message));
10694
+ }
10695
+ async routeNotification(message) {
10696
+ const routes = this.matchingRoutes(message);
10697
+ if (routes.length === 0) {
10698
+ return;
10699
+ }
10700
+ if (routes.length > 1) {
10701
+ await this.logger.error("Local Codex App Server notification matched multiple runtime routes", new Error(message.method ?? "Unknown App Server notification"));
10702
+ return;
10703
+ }
10704
+ const route = routes[0];
10705
+ if (route === void 0) {
10706
+ throw new Error("Expected one Local Codex notification route");
10707
+ }
10708
+ await route.onNotification(message);
10709
+ }
10710
+ async routeServerRequest(message) {
10711
+ const routes = this.matchingRoutes(message);
10712
+ if (routes.length === 1) {
10713
+ const route = routes[0];
10714
+ if (route === void 0) {
10715
+ throw new Error("Expected one Local Codex request route");
10716
+ }
10717
+ await route.onServerRequest(message);
10718
+ return;
10719
+ }
10720
+ if (routes.length > 1) {
10721
+ await this.logger.error("Local Codex App Server request matched multiple runtime routes", new Error(message.method ?? "Unknown App Server request"));
10722
+ }
10723
+ const client = this.supervisor.currentClient().value;
10724
+ if (client !== void 0 && message.id !== void 0) {
10725
+ await client.respondWithError(message.id, -32e3, routes.length === 0 ? "No owning Local Codex Runtime turn" : "Ambiguous Local Codex Runtime turn ownership");
10726
+ }
10727
+ }
10728
+ async broadcastProcessExit(error) {
10729
+ await Promise.all([...this.routes.values()].map(async (route) => {
10730
+ try {
10731
+ await route.onProcessExit(error);
10732
+ } catch (routeError) {
10733
+ await this.logger.error("Failed to settle a Local Codex route after the shared App Server exited", routeError).catch(() => void 0);
10734
+ }
10735
+ }));
10736
+ }
10737
+ requireActiveSlot(slot) {
10738
+ const active = this.activeSlots.get(slot.slotId);
10739
+ if (active === void 0) {
10740
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is not active`);
10741
+ }
10742
+ if (active.ownerId !== slot.ownerId) {
10743
+ throw new Error(`Local Codex capacity slot ${slot.slotId} belongs to another route`);
10515
10744
  }
10516
- const value = this.routes.get(owner);
10517
- return value === void 0 ? {} : { value };
10745
+ return active;
10518
10746
  }
10519
10747
  };
10520
10748
  }
@@ -14336,7 +14564,7 @@ function getApiKeyOrUndefined() {
14336
14564
 
14337
14565
  // src/utils/http.ts
14338
14566
  function getUserAgent() {
14339
- return `moxt-cli/${"0.10.0-beta.6"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
14567
+ return `moxt-cli/${"0.10.0-beta.8"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
14340
14568
  }
14341
14569
  async function sendRequest(method, path4, init) {
14342
14570
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -28758,7 +28986,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
28758
28986
  var MAX_BATCH_SIZE = 100;
28759
28987
  function commonLabels() {
28760
28988
  return {
28761
- cli_version: "0.10.0-beta.6",
28989
+ cli_version: "0.10.0-beta.8",
28762
28990
  node_version: process.versions.node,
28763
28991
  os: (0, import_node_os11.platform)(),
28764
28992
  arch: (0, import_node_os11.arch)(),
@@ -28804,7 +29032,7 @@ async function flush() {
28804
29032
  }
28805
29033
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
28806
29034
  const payload = {
28807
- release_id: "0.10.0-beta.6",
29035
+ release_id: "0.10.0-beta.8",
28808
29036
  client_type: "cli",
28809
29037
  metric_data_list: batch.map((m) => ({
28810
29038
  profile: "cli",
@@ -29187,9 +29415,9 @@ function commandPath3(command) {
29187
29415
  }
29188
29416
 
29189
29417
  // src/index.ts
29190
- var program2 = createProgram("0.10.0-beta.6");
29191
- installDaemonReconcileHook(program2, "0.10.0-beta.6");
29192
- installUpdateHook(program2, "0.10.0-beta.6");
29418
+ var program2 = createProgram("0.10.0-beta.8");
29419
+ installDaemonReconcileHook(program2, "0.10.0-beta.8");
29420
+ installUpdateHook(program2, "0.10.0-beta.8");
29193
29421
  instrumentProgram(program2);
29194
29422
  installExitHandler();
29195
29423
  program2.parseAsync(process.argv).then(async () => {