@moxt-ai/cli 0.10.0-beta.1 → 0.10.0-beta.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.
package/README.md CHANGED
@@ -25,15 +25,18 @@ When a same-channel update is cached, the next eligible command offers **Update
25
25
  command stdout remains safe to pipe. Daemon, help, version, telemetry, CI, and
26
26
  non-interactive invocations never prompt or install.
27
27
 
28
- After a CLI update, Moxt refreshes a running Local Machine Connector installed
29
- under launchd, a systemd user service, or Supervisor. The refresh preserves the
30
- configured service manager and updates its absolute Node and CLI paths. Active
31
- Jobs are reported before the restart and recover as interrupted with
32
- `daemon_restarted`. A foreground `moxt machine daemon` process is never
33
- restarted automatically. Updates performed by Homebrew, a package manager, or
34
- the standalone installer are reconciled on the new CLI's next normal command
35
- when it uses the managed service's recorded stable launcher path. A different
36
- CLI installation cannot take over the service automatically.
28
+ After a CLI update, Moxt refreshes a running Local Machine Connector or recovers
29
+ a temporarily offline managed Connector installed under launchd, a systemd user
30
+ service, or Supervisor. The refresh preserves the configured service manager
31
+ and updates its absolute Node and CLI paths. Active Jobs are reported before the
32
+ restart and recover as interrupted with `daemon_restarted`. A foreground `moxt
33
+ machine daemon` process is never restarted automatically. Updates performed by
34
+ Homebrew, a package manager, or the standalone installer are reconciled on the
35
+ new CLI's next normal command when it uses the managed service's recorded stable
36
+ launcher path. A different CLI installation cannot take over the service
37
+ automatically. A managed Connector explicitly stopped with `moxt machine
38
+ service stop` remains stopped across later CLI invocations until the user runs
39
+ `moxt machine service restart` or installs the service again.
37
40
 
38
41
  If the CLI installation succeeds but the Connector refresh fails, the CLI
39
42
  update remains successful. Moxt validates the new CLI entrypoint before changing
package/dist/index.cjs CHANGED
@@ -5175,7 +5175,7 @@ var init_codex_executor = __esm({
5175
5175
  });
5176
5176
 
5177
5177
  // ../machine-connector/dist/runtime/runtime-types.js
5178
- var PersistedMachineJobPhase;
5178
+ var PersistedMachineJobPhase, ManagedServiceDesiredState;
5179
5179
  var init_runtime_types = __esm({
5180
5180
  "../machine-connector/dist/runtime/runtime-types.js"() {
5181
5181
  "use strict";
@@ -5186,6 +5186,10 @@ var init_runtime_types = __esm({
5186
5186
  PersistedMachineJobPhase2["TerminalPendingUpload"] = "terminal_pending_upload";
5187
5187
  PersistedMachineJobPhase2["Uploaded"] = "uploaded";
5188
5188
  })(PersistedMachineJobPhase || (PersistedMachineJobPhase = {}));
5189
+ (function(ManagedServiceDesiredState2) {
5190
+ ManagedServiceDesiredState2["Running"] = "running";
5191
+ ManagedServiceDesiredState2["Stopped"] = "stopped";
5192
+ })(ManagedServiceDesiredState || (ManagedServiceDesiredState = {}));
5189
5193
  }
5190
5194
  });
5191
5195
 
@@ -6682,6 +6686,12 @@ var init_version = __esm({
6682
6686
  });
6683
6687
 
6684
6688
  // ../machine-connector/dist/runtime/relay-client.js
6689
+ function localCodexRuntimeEventsRequestBody(fence, firstSequence, events) {
6690
+ return { ...fence, events, firstSequence };
6691
+ }
6692
+ function localCodexRuntimeEventsRequestBytes(fence, firstSequence, events) {
6693
+ return Buffer.byteLength(JSON.stringify(localCodexRuntimeEventsRequestBody(fence, firstSequence, events)), "utf8");
6694
+ }
6685
6695
  async function postJson(url, body, accessToken, externalSignal) {
6686
6696
  const headers = {
6687
6697
  "Content-Type": "application/json",
@@ -6845,7 +6855,7 @@ var init_relay_client = __esm({
6845
6855
  return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/lease`, fence, signal);
6846
6856
  }
6847
6857
  async appendCodexRuntimeEvents(attemptId, fence, firstSequence, events) {
6848
- return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/events`, { ...fence, events, firstSequence });
6858
+ return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/events`, localCodexRuntimeEventsRequestBody(fence, firstSequence, events));
6849
6859
  }
6850
6860
  async updateCodexRuntimeState(attemptId, fence, state) {
6851
6861
  await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/state`, { ...fence, ...state });
@@ -6943,9 +6953,9 @@ var init_runtime_logger = __esm({
6943
6953
  async info(message, metadata = {}) {
6944
6954
  await this.write("info", message, metadata, this.store.runtimeLogPath());
6945
6955
  }
6946
- async error(message, error) {
6947
- const metadata = error instanceof Error ? { message: error.message, stack: error.stack } : { error };
6948
- await this.write("error", message, metadata, this.store.runtimeErrorLogPath());
6956
+ async error(message, error, context = {}) {
6957
+ const errorMetadata = error instanceof Error ? { message: error.message, stack: error.stack } : { error };
6958
+ await this.write("error", message, { ...context, ...errorMetadata }, this.store.runtimeErrorLogPath());
6949
6959
  }
6950
6960
  async write(level, message, metadata, path4) {
6951
6961
  await (0, import_promises10.appendFile)(path4, `${JSON.stringify({
@@ -8104,6 +8114,9 @@ function normalizeItem(item, completed, baseCorrelation, canonicalRoot) {
8104
8114
  if (itemType === "fileChange") {
8105
8115
  return event(completed ? "file_change_completed" : "file_change_started", { changes: item.changes, status: item.status }, correlation, canonicalRoot);
8106
8116
  }
8117
+ if (itemType === "contextCompaction") {
8118
+ return event(completed ? "context_compaction_completed" : "context_compaction_started", {}, correlation, canonicalRoot);
8119
+ }
8107
8120
  if (itemType === "mcpToolCall" || itemType === "dynamicToolCall" || itemType === "collabAgentToolCall" || itemType === "webSearch" || itemType === "imageGeneration" || itemType === "imageView") {
8108
8121
  return event(completed ? "tool_completed" : "tool_started", sanitizeThreadItem(item), correlation, canonicalRoot);
8109
8122
  }
@@ -8274,6 +8287,9 @@ var init_event_normalizer = __esm({
8274
8287
  function isMissingThreadResponse(message, threadId) {
8275
8288
  return message === `thread not found: ${threadId}` || message === `no rollout found for thread id ${threadId}` || message === `no rollout found for conversation id ${threadId}`;
8276
8289
  }
8290
+ function isThreadNameMetadataPendingResponse(message) {
8291
+ return message.startsWith("failed to set thread name:") && message.includes("failed to read session metadata ") && message.includes(": rollout at ") && message.endsWith(" is empty");
8292
+ }
8277
8293
  function createActiveAttempt(claim, durable, workingDirectory) {
8278
8294
  let resolveTerminal = (_value) => void 0;
8279
8295
  const terminal = new Promise((resolve9) => {
@@ -8303,6 +8319,16 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8303
8319
  workingDirectory
8304
8320
  };
8305
8321
  }
8322
+ function createInitialThreadNameState() {
8323
+ let resolveCompletion = () => void 0;
8324
+ const completion = new Promise((resolve9) => {
8325
+ resolveCompletion = resolve9;
8326
+ });
8327
+ return {
8328
+ completion,
8329
+ resolve: resolveCompletion
8330
+ };
8331
+ }
8306
8332
  function fenceFor(claim, connectorInstanceId) {
8307
8333
  return {
8308
8334
  attemptGeneration: claim.attemptGeneration,
@@ -8323,6 +8349,36 @@ function persistedFence(persisted) {
8323
8349
  runToken: persisted.claim.runToken
8324
8350
  };
8325
8351
  }
8352
+ function preferredEventUploadBatch(fence, pendingEvents) {
8353
+ if (pendingEvents.length === 0) {
8354
+ throw new Error("Local Codex event upload requires a pending event");
8355
+ }
8356
+ const firstSequence = pendingEvents[0].sequence;
8357
+ const events = [];
8358
+ let requestBytes = localCodexRuntimeEventsRequestBytes(fence, firstSequence, events);
8359
+ for (const event2 of pendingEvents.slice(0, maximumEventUploadCount)) {
8360
+ const serializedEvent = JSON.stringify(event2);
8361
+ if (serializedEvent === void 0) {
8362
+ throw new Error(`Local Codex event ${event2.sequence} cannot be serialized`);
8363
+ }
8364
+ const candidateBytes = requestBytes + Buffer.byteLength(serializedEvent, "utf8") + (events.length === 0 ? 0 : 1);
8365
+ if (events.length > 0 && candidateBytes > preferredEventUploadRequestBytes) {
8366
+ break;
8367
+ }
8368
+ events.push(event2);
8369
+ requestBytes = candidateBytes;
8370
+ }
8371
+ return { events, requestBytes };
8372
+ }
8373
+ function eventUploadBatch(fence, events) {
8374
+ if (events.length === 0) {
8375
+ throw new Error("Local Codex event upload batch cannot be empty");
8376
+ }
8377
+ return {
8378
+ events,
8379
+ requestBytes: localCodexRuntimeEventsRequestBytes(fence, events[0].sequence, events)
8380
+ };
8381
+ }
8326
8382
  function requireThreadId(response) {
8327
8383
  const id = response.thread?.id;
8328
8384
  if (id === void 0 || id === "") {
@@ -8536,7 +8592,7 @@ function parseLeaseDeadline(value) {
8536
8592
  }
8537
8593
  return parsed;
8538
8594
  }
8539
- var import_node_child_process4, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
8595
+ var import_node_child_process4, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
8540
8596
  var init_runtime_worker = __esm({
8541
8597
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
8542
8598
  "use strict";
@@ -8553,11 +8609,16 @@ var init_runtime_worker = __esm({
8553
8609
  claimWaitSeconds = 25;
8554
8610
  eventUploadCoalesceMilliseconds = 500;
8555
8611
  eventUploadRetryMilliseconds = 1e3;
8612
+ maximumEventUploadCount = 500;
8613
+ preferredEventUploadRequestBytes = 96e3;
8556
8614
  leaseRenewIntervalMilliseconds = 1e4;
8557
8615
  leaseRenewRetryMilliseconds = 1e3;
8558
8616
  interactionTimeoutMilliseconds = 10 * 60 * 1e3;
8559
8617
  executableProbeTimeoutMilliseconds = 5e3;
8560
8618
  recoveryRetryMilliseconds = 1e3;
8619
+ initialThreadNameRetryMilliseconds = 250;
8620
+ maximumThreadNameRetryMilliseconds = 2e3;
8621
+ maximumInitialThreadNameAttempts = 8;
8561
8622
  ThreadUnavailableError = class extends Error {
8562
8623
  constructor(message) {
8563
8624
  super(message);
@@ -8634,9 +8695,13 @@ var init_runtime_worker = __esm({
8634
8695
  if (normalized === void 0) {
8635
8696
  return;
8636
8697
  }
8698
+ const initialThreadName = active.initialThreadName;
8637
8699
  if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId !== void 0 && normalized.correlation.nativeThreadId !== active.nativeThreadId) {
8638
8700
  return;
8639
8701
  }
8702
+ if (normalized.kind === "thread_title_updated" && normalized.payload.title === initialThreadName?.projectedTitle) {
8703
+ return;
8704
+ }
8640
8705
  const notificationTurnId = normalized.correlation.nativeTurnId;
8641
8706
  if (notificationTurnId !== void 0) {
8642
8707
  if (this.processPool.isRetiredTurn(notificationTurnId)) {
@@ -8651,6 +8716,12 @@ var init_runtime_worker = __esm({
8651
8716
  return;
8652
8717
  }
8653
8718
  }
8719
+ if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0) {
8720
+ await initialThreadName.completion;
8721
+ if (active.finished.signal.aborted) {
8722
+ return;
8723
+ }
8724
+ }
8654
8725
  void this.enqueueSpool(active, async () => {
8655
8726
  const persisted = await active.durable.appendEvent(normalized.kind, normalized.payload, normalized.correlation);
8656
8727
  if (normalized.correlation.nativeThreadId !== void 0 && active.nativeThreadId === void 0) {
@@ -8814,6 +8885,9 @@ var init_runtime_worker = __esm({
8814
8885
  active.nativeThreadId = nativeThreadId;
8815
8886
  await durable.markThreadPrepared(nativeThreadId);
8816
8887
  await active.spoolQueue;
8888
+ if (isNewThread) {
8889
+ active.initialThreadName = createInitialThreadNameState();
8890
+ }
8817
8891
  if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
8818
8892
  await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
8819
8893
  }
@@ -8848,7 +8922,11 @@ var init_runtime_worker = __esm({
8848
8922
  });
8849
8923
  await this.interruptActiveTurnIfRequested(active, client);
8850
8924
  if (isNewThread) {
8851
- await this.setInitialThreadName(client, claim, nativeThreadId);
8925
+ try {
8926
+ await this.setInitialThreadName(client, active, nativeThreadId);
8927
+ } finally {
8928
+ active.initialThreadName?.resolve();
8929
+ }
8852
8930
  }
8853
8931
  const terminal = await Promise.race([
8854
8932
  active.terminal,
@@ -8880,6 +8958,7 @@ var init_runtime_worker = __esm({
8880
8958
  await this.failAttempt(active, error);
8881
8959
  }
8882
8960
  } finally {
8961
+ active.initialThreadName?.resolve();
8883
8962
  if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
8884
8963
  this.processPool.retireTurn(active.nativeTurnId);
8885
8964
  }
@@ -9024,9 +9103,11 @@ var init_runtime_worker = __esm({
9024
9103
  let snapshot = durable.snapshot();
9025
9104
  const fence = persistedFence(snapshot);
9026
9105
  while (durable.pendingEvents().length > 0) {
9027
- const events = durable.pendingEvents().slice(0, 500);
9028
- const response = await this.relay.appendCodexRuntimeEvents(snapshot.claim.attemptId, fence, events[0].sequence, events);
9029
- await durable.acknowledgeEvents(response.acknowledgedSequence);
9106
+ await this.uploadNextEventBatch({
9107
+ attemptId: snapshot.claim.attemptId,
9108
+ durable,
9109
+ fence
9110
+ });
9030
9111
  snapshot = durable.snapshot();
9031
9112
  }
9032
9113
  if (snapshot.phase !== LocalCodexAttemptPhase.TerminalPendingUpload || snapshot.finalSequence === void 0 || snapshot.finalStatus === void 0) {
@@ -9200,12 +9281,44 @@ var init_runtime_worker = __esm({
9200
9281
  }
9201
9282
  async flushEvents(active) {
9202
9283
  await active.spoolQueue;
9203
- const events = active.durable.pendingEvents().slice(0, 500);
9204
- if (events.length === 0) {
9284
+ await this.uploadNextEventBatch({
9285
+ attemptId: active.claim.attemptId,
9286
+ durable: active.durable,
9287
+ fence: fenceFor(active.claim, this.connectorInstanceId)
9288
+ });
9289
+ }
9290
+ async uploadNextEventBatch(request2) {
9291
+ const pendingEvents = request2.durable.pendingEvents();
9292
+ if (pendingEvents.length === 0) {
9205
9293
  return;
9206
9294
  }
9207
- const response = await this.relay.appendCodexRuntimeEvents(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), events[0].sequence, events);
9208
- await active.durable.acknowledgeEvents(response.acknowledgedSequence);
9295
+ let batch = preferredEventUploadBatch(request2.fence, pendingEvents);
9296
+ while (true) {
9297
+ try {
9298
+ const response = await this.relay.appendCodexRuntimeEvents(request2.attemptId, request2.fence, batch.events[0].sequence, batch.events);
9299
+ await request2.durable.acknowledgeEvents(response.acknowledgedSequence);
9300
+ return;
9301
+ } catch (error) {
9302
+ const firstSequence = batch.events[0].sequence;
9303
+ const metadata = {
9304
+ attemptId: request2.attemptId,
9305
+ eventCount: batch.events.length,
9306
+ firstSequence,
9307
+ requestBytes: batch.requestBytes
9308
+ };
9309
+ if (error instanceof RelayHttpError) {
9310
+ metadata.status = error.status;
9311
+ }
9312
+ if (error instanceof RelayHttpError && error.status === 413 && batch.events.length > 1) {
9313
+ await this.logger.info(`Local Codex event upload exceeded the relay request limit; retrying a smaller batch`, metadata);
9314
+ const eventCount = Math.ceil(batch.events.length / 2);
9315
+ batch = eventUploadBatch(request2.fence, batch.events.slice(0, eventCount));
9316
+ continue;
9317
+ }
9318
+ await this.logger.error(`Failed to upload Local Codex events for ${request2.attemptId}`, error, metadata);
9319
+ throw error;
9320
+ }
9321
+ }
9209
9322
  }
9210
9323
  enqueueEventFlush(active) {
9211
9324
  if (active.eventUploadScheduled) {
@@ -9319,7 +9432,8 @@ var init_runtime_worker = __esm({
9319
9432
  const status = this.processPool.status();
9320
9433
  return status.appServerStatus === LocalCodexComponentStatusWire.Ready && status.codexAuthStatus === LocalCodexComponentStatusWire.Ready && status.codexBinaryStatus === LocalCodexComponentStatusWire.Ready;
9321
9434
  }
9322
- async setInitialThreadName(client, claim, threadId) {
9435
+ async setInitialThreadName(client, active, threadId) {
9436
+ const claim = active.claim;
9323
9437
  if (claim.executionContext.workflowTaskId !== void 0 || claim.executionContext.workflowWatcherId !== void 0) {
9324
9438
  return;
9325
9439
  }
@@ -9331,13 +9445,42 @@ var init_runtime_worker = __esm({
9331
9445
  if (name === "") {
9332
9446
  return;
9333
9447
  }
9334
- try {
9335
- await client.request("thread/name/set", {
9336
- name,
9337
- threadId
9448
+ const signal = active.finished.signal;
9449
+ let retryMilliseconds = initialThreadNameRetryMilliseconds;
9450
+ for (let attempt = 1; attempt <= maximumInitialThreadNameAttempts; attempt += 1) {
9451
+ if (signal.aborted) {
9452
+ return;
9453
+ }
9454
+ try {
9455
+ await client.request("thread/name/set", {
9456
+ name,
9457
+ threadId
9458
+ });
9459
+ } catch (error) {
9460
+ const metadataPending = error instanceof AppServerResponseError && isThreadNameMetadataPendingResponse(error.responseMessage);
9461
+ if (!metadataPending || attempt === maximumInitialThreadNameAttempts) {
9462
+ await this.logger.error(`Failed to name Local Codex thread ${threadId}`, error);
9463
+ return;
9464
+ }
9465
+ await waitForAbort(signal, retryMilliseconds);
9466
+ retryMilliseconds = Math.min(retryMilliseconds * 2, maximumThreadNameRetryMilliseconds);
9467
+ continue;
9468
+ }
9469
+ const initialThreadName = active.initialThreadName;
9470
+ if (initialThreadName === void 0) {
9471
+ throw new AppServerProtocolError("Initial thread name state is unavailable");
9472
+ }
9473
+ initialThreadName.projectedTitle = name;
9474
+ await this.enqueueSpool(active, async () => {
9475
+ const titleAlreadyProjected = active.durable.snapshot().events.some((event2) => {
9476
+ return event2.kind === "thread_title_updated" && event2.payload.title === name;
9477
+ });
9478
+ if (titleAlreadyProjected) {
9479
+ return;
9480
+ }
9481
+ await active.durable.appendEvent("thread_title_updated", { title: name }, { nativeThreadId: threadId });
9338
9482
  });
9339
- } catch (error) {
9340
- await this.logger.error(`Failed to name Local Codex thread ${threadId}`, error);
9483
+ return;
9341
9484
  }
9342
9485
  }
9343
9486
  unregisterRoute() {
@@ -10597,6 +10740,9 @@ function createServiceEnvironment(options) {
10597
10740
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
10598
10741
  const manager = await configuredServiceManager(store, runtime);
10599
10742
  await restartManager(manager, store, runtime);
10743
+ if (manager !== UserServiceManager.None) {
10744
+ await persistServiceDesiredState(store, manager, ManagedServiceDesiredState.Running);
10745
+ }
10600
10746
  return manager;
10601
10747
  }
10602
10748
  async function refreshManagedUserService(store, options, runtime = defaultServiceManagerRuntime) {
@@ -10668,9 +10814,24 @@ async function managedServiceOwnsProcess(manager, processId, store, runtime = de
10668
10814
  async function recordedServiceManager(store) {
10669
10815
  return await readStoredServiceManager(store);
10670
10816
  }
10817
+ async function recordedServiceDesiredState(store) {
10818
+ const desiredState = (await store.readServiceManager()).value?.desiredState;
10819
+ if (desiredState === void 0)
10820
+ return ManagedServiceDesiredState.Running;
10821
+ if (desiredState === ManagedServiceDesiredState.Running) {
10822
+ return ManagedServiceDesiredState.Running;
10823
+ }
10824
+ if (desiredState === ManagedServiceDesiredState.Stopped) {
10825
+ return ManagedServiceDesiredState.Stopped;
10826
+ }
10827
+ throw new Error(`Unsupported managed service desired state: ${desiredState}`);
10828
+ }
10671
10829
  async function stopUserService(store, runtime = defaultServiceManagerRuntime) {
10672
10830
  const manager = await configuredServiceManager(store, runtime);
10673
10831
  await stopManager(manager, store, runtime);
10832
+ if (manager !== UserServiceManager.None) {
10833
+ await persistServiceDesiredState(store, manager, ManagedServiceDesiredState.Stopped);
10834
+ }
10674
10835
  return manager;
10675
10836
  }
10676
10837
  async function uninstallUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -10881,13 +11042,18 @@ function parseProcessId(value) {
10881
11042
  const processId = Number.parseInt(value.trim(), 10);
10882
11043
  return Number.isSafeInteger(processId) && processId > 0 ? processId : void 0;
10883
11044
  }
10884
- async function persistServiceManager(store, manager, managedEntrypointPath) {
11045
+ async function persistServiceManager(store, manager, managedEntrypointPath, desiredState = ManagedServiceDesiredState.Running) {
10885
11046
  await store.writeServiceManager({
11047
+ desiredState,
10886
11048
  ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path10.resolve)(managedEntrypointPath) } : {},
10887
11049
  manager,
10888
11050
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10889
11051
  });
10890
11052
  }
11053
+ async function persistServiceDesiredState(store, manager, desiredState) {
11054
+ const stored = (await store.readServiceManager()).value;
11055
+ await persistServiceManager(store, manager, stored?.managedEntrypointPath, desiredState);
11056
+ }
10891
11057
  async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
10892
11058
  const stored = (await store.readServiceManager()).value;
10893
11059
  if (!stored || stored.manager === UserServiceManager.None)
@@ -11113,33 +11279,23 @@ async function startSupervisorUserService(store, runtime, previousSupervisorProc
11113
11279
  }
11114
11280
  async function reloadSupervisorConfiguration(store, runtime) {
11115
11281
  const configPath = supervisorConfigPath(store);
11116
- const processIdBeforeStop = await runServiceProbe(runtime, "supervisorctl", [
11117
- "-c",
11118
- configPath,
11119
- "pid",
11120
- supervisorProgramName
11121
- ]);
11122
- if ((parseProcessId(processIdBeforeStop.stdout) ?? 0) > 0) {
11282
+ const processIdBeforeStop = await currentSupervisorProgramProcessId(store, runtime);
11283
+ if (processIdBeforeStop !== void 0) {
11123
11284
  await runtime.run("supervisorctl", [
11124
11285
  "-c",
11125
11286
  configPath,
11126
11287
  "stop",
11127
11288
  supervisorProgramName
11128
11289
  ]);
11129
- const processIdAfterStop = await runServiceProbe(runtime, "supervisorctl", ["-c", configPath, "pid", supervisorProgramName]);
11130
- if ((parseProcessId(processIdAfterStop.stdout) ?? 0) > 0) {
11290
+ const processIdAfterStop = await currentSupervisorProgramProcessId(store, runtime);
11291
+ if (processIdAfterStop !== void 0) {
11131
11292
  throw new Error("Supervisor did not stop the existing Moxt Machine Connector process");
11132
11293
  }
11133
11294
  }
11134
11295
  await runtime.run("supervisorctl", ["-c", configPath, "reread"]);
11135
11296
  await runtime.run("supervisorctl", ["-c", configPath, "update"]);
11136
- const processId = await runServiceProbe(runtime, "supervisorctl", [
11137
- "-c",
11138
- configPath,
11139
- "pid",
11140
- supervisorProgramName
11141
- ]);
11142
- if ((parseProcessId(processId.stdout) ?? 0) > 0)
11297
+ const processId = await currentSupervisorProgramProcessId(store, runtime);
11298
+ if (processId !== void 0)
11143
11299
  return;
11144
11300
  await runtime.run("supervisorctl", [
11145
11301
  "-c",
@@ -11328,6 +11484,7 @@ var init_service_manager = __esm({
11328
11484
  import_node_os7 = require("os");
11329
11485
  import_node_path10 = require("path");
11330
11486
  import_node_util2 = require("util");
11487
+ init_runtime_types();
11331
11488
  init_shell_environment();
11332
11489
  execFileAsync = (0, import_node_util2.promisify)(import_node_child_process5.execFile);
11333
11490
  launchAgentLabel = "ai.moxt.machine-connector";
@@ -11383,24 +11540,27 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11383
11540
  if (!lock)
11384
11541
  return { outcome: DaemonReconcileOutcome.Skipped };
11385
11542
  try {
11386
- const initial = await reachableRuntimeStatus(store);
11387
- if (!initial)
11388
- return { outcome: DaemonReconcileOutcome.Skipped };
11389
11543
  const manager = await recordedServiceManager(store);
11390
11544
  if (manager === UserServiceManager.None) {
11391
11545
  return { outcome: DaemonReconcileOutcome.Skipped };
11392
11546
  }
11393
- if (initial.cliVersion === options.cliVersion) {
11547
+ if (await recordedServiceDesiredState(store) === ManagedServiceDesiredState.Stopped) {
11394
11548
  return { manager, outcome: DaemonReconcileOutcome.Skipped };
11395
11549
  }
11396
- let managerOwnsProcess;
11397
- try {
11398
- managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
11399
- } catch (error) {
11400
- throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage4(error)}`, { cause: error });
11550
+ const initial = await reachableRuntimeStatus(store);
11551
+ if (initial?.cliVersion === options.cliVersion) {
11552
+ return { manager, outcome: DaemonReconcileOutcome.Skipped };
11401
11553
  }
11402
- if (!managerOwnsProcess) {
11403
- return { outcome: DaemonReconcileOutcome.Skipped };
11554
+ if (initial) {
11555
+ let managerOwnsProcess;
11556
+ try {
11557
+ managerOwnsProcess = await managedServiceOwnsProcess(manager, initial.pid, store);
11558
+ } catch (error) {
11559
+ throw new DaemonRefreshError("ownership", `could not verify that the reachable Connector belongs to ${manager}: ${errorMessage4(error)}`, { cause: error });
11560
+ }
11561
+ if (!managerOwnsProcess) {
11562
+ return { outcome: DaemonReconcileOutcome.Skipped };
11563
+ }
11404
11564
  }
11405
11565
  try {
11406
11566
  await validateCliEntrypoint(options, store);
@@ -11409,7 +11569,7 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11409
11569
  cause: error
11410
11570
  });
11411
11571
  }
11412
- if (initial.activeJobs.length > 0) {
11572
+ if (initial && initial.activeJobs.length > 0) {
11413
11573
  options.onActiveJobs?.(initial.activeJobs.length);
11414
11574
  }
11415
11575
  let refresh;
@@ -11429,12 +11589,12 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
11429
11589
  const deadline = Date.now() + reconcileTimeoutMilliseconds;
11430
11590
  while (Date.now() < deadline) {
11431
11591
  const current2 = await reachableRuntimeStatus(store);
11432
- if (current2?.cliVersion === options.cliVersion && current2.connectorInstanceId !== initial.connectorInstanceId) {
11592
+ if (current2?.cliVersion === options.cliVersion && current2.connectorInstanceId !== initial?.connectorInstanceId) {
11433
11593
  return { manager, outcome: DaemonReconcileOutcome.Restarted };
11434
11594
  }
11435
11595
  await delay6(100);
11436
11596
  }
11437
- const verificationMessage = `managed daemon did not report CLI ${options.cliVersion} with a new instance ID`;
11597
+ const verificationMessage = initial ? `managed daemon did not report CLI ${options.cliVersion} with a new instance ID` : `managed daemon did not become reachable with CLI ${options.cliVersion}`;
11438
11598
  try {
11439
11599
  await refresh.rollback();
11440
11600
  } catch (error) {
@@ -11498,6 +11658,7 @@ var init_daemon_reconcile = __esm({
11498
11658
  init_local_ipc();
11499
11659
  init_process_lock();
11500
11660
  init_service_manager();
11661
+ init_runtime_types();
11501
11662
  init_store();
11502
11663
  reconcileTimeoutMilliseconds = 12e3;
11503
11664
  execFileAsync2 = (0, import_node_util3.promisify)(import_node_child_process6.execFile);
@@ -12401,6 +12562,7 @@ var init_device_identity = __esm({
12401
12562
  async function pairMachine(store, options) {
12402
12563
  await store.initialize();
12403
12564
  const canonicalRoot = await store.getCanonicalRoot(options.rootPath);
12565
+ const rootDisplayName = displayNameForRoot(canonicalRoot);
12404
12566
  const identity = await ensureMachineIdentity(store);
12405
12567
  const machineName = options.machineName ?? (0, import_node_os8.hostname)();
12406
12568
  const operatingSystem = getOperatingSystem();
@@ -12413,7 +12575,7 @@ async function pairMachine(store, options) {
12413
12575
  machineName,
12414
12576
  operatingSystem,
12415
12577
  protocolVersion: machineProtocolVersion,
12416
- rootDisplayName: (0, import_node_path12.basename)(canonicalRoot),
12578
+ rootDisplayName,
12417
12579
  rootHandle
12418
12580
  });
12419
12581
  options.onConfirmation?.(proposal.confirmationUrl);
@@ -12442,7 +12604,7 @@ async function pairMachine(store, options) {
12442
12604
  purpose: credentials.purpose,
12443
12605
  refreshToken: credentials.refreshToken,
12444
12606
  relayOrigin: options.relayOrigin.replace(/\/+$/, ""),
12445
- rootDisplayName: (0, import_node_path12.basename)(canonicalRoot),
12607
+ rootDisplayName,
12446
12608
  rootHandle,
12447
12609
  rootPath: canonicalRoot,
12448
12610
  targetId: credentials.targetId,
@@ -12462,6 +12624,10 @@ async function pairMachine(store, options) {
12462
12624
  }
12463
12625
  throw new Error("Local Machine pairing expired");
12464
12626
  }
12627
+ function displayNameForRoot(canonicalRoot) {
12628
+ const name = (0, import_node_path12.basename)(canonicalRoot);
12629
+ return name.length > 0 ? name : canonicalRoot;
12630
+ }
12465
12631
  function getOperatingSystem() {
12466
12632
  if ((0, import_node_os8.platform)() === "darwin") {
12467
12633
  return MachineOperatingSystem.MacOS;
@@ -12943,6 +13109,7 @@ __export(dist_exports, {
12943
13109
  MachineProtocolInvariantError: () => MachineProtocolInvariantError,
12944
13110
  MachineRelayClient: () => MachineRelayClient,
12945
13111
  MachineRuntimeStore: () => MachineRuntimeStore,
13112
+ ManagedServiceDesiredState: () => ManagedServiceDesiredState,
12946
13113
  PairingRelayClient: () => PairingRelayClient,
12947
13114
  PersistedMachineJobPhase: () => PersistedMachineJobPhase,
12948
13115
  RelayHttpError: () => RelayHttpError,
@@ -12967,6 +13134,7 @@ __export(dist_exports, {
12967
13134
  executeClaudeStart: () => executeClaudeStart,
12968
13135
  installUserService: () => installUserService,
12969
13136
  isTerminalJobStatus: () => isTerminalJobStatus,
13137
+ localCodexRuntimeEventsRequestBytes: () => localCodexRuntimeEventsRequestBytes,
12970
13138
  localMachineJobTargetRelationship: () => localMachineJobTargetRelationship,
12971
13139
  machineExecutionContextEnvironmentName: () => machineExecutionContextEnvironmentName,
12972
13140
  machineManagerActions: () => machineManagerActions,
@@ -12976,6 +13144,7 @@ __export(dist_exports, {
12976
13144
  parseLocalMachineJobExecutionContext: () => parseLocalMachineJobExecutionContext,
12977
13145
  parseServiceManagerPreference: () => parseServiceManagerPreference,
12978
13146
  reconcileManagedDaemon: () => reconcileManagedDaemon,
13147
+ recordedServiceDesiredState: () => recordedServiceDesiredState,
12979
13148
  recordedServiceManager: () => recordedServiceManager,
12980
13149
  refreshManagedUserService: () => refreshManagedUserService,
12981
13150
  renderMachineManager: () => renderMachineManager,
@@ -13189,7 +13358,7 @@ function getApiKeyOrUndefined() {
13189
13358
 
13190
13359
  // src/utils/http.ts
13191
13360
  function getUserAgent() {
13192
- return `moxt-cli/${"0.10.0-beta.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
13361
+ return `moxt-cli/${"0.10.0-beta.3"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
13193
13362
  }
13194
13363
  async function sendRequest(method, path4, init) {
13195
13364
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -26772,7 +26941,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
26772
26941
  var MAX_BATCH_SIZE = 100;
26773
26942
  function commonLabels() {
26774
26943
  return {
26775
- cli_version: "0.10.0-beta.1",
26944
+ cli_version: "0.10.0-beta.3",
26776
26945
  node_version: process.versions.node,
26777
26946
  os: (0, import_node_os9.platform)(),
26778
26947
  arch: (0, import_node_os9.arch)(),
@@ -26818,7 +26987,7 @@ async function flush() {
26818
26987
  }
26819
26988
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
26820
26989
  const payload = {
26821
- release_id: "0.10.0-beta.1",
26990
+ release_id: "0.10.0-beta.3",
26822
26991
  client_type: "cli",
26823
26992
  metric_data_list: batch.map((m) => ({
26824
26993
  profile: "cli",
@@ -27201,9 +27370,9 @@ function commandPath3(command) {
27201
27370
  }
27202
27371
 
27203
27372
  // src/index.ts
27204
- var program2 = createProgram("0.10.0-beta.1");
27205
- installDaemonReconcileHook(program2, "0.10.0-beta.1");
27206
- installUpdateHook(program2, "0.10.0-beta.1");
27373
+ var program2 = createProgram("0.10.0-beta.3");
27374
+ installDaemonReconcileHook(program2, "0.10.0-beta.3");
27375
+ installUpdateHook(program2, "0.10.0-beta.3");
27207
27376
  instrumentProgram(program2);
27208
27377
  installExitHandler();
27209
27378
  program2.parseAsync(process.argv).then(async () => {