@moxt-ai/cli 0.10.0 → 0.11.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -6675,6 +6675,40 @@ var init_shell_environment = __esm({
6675
6675
  }
6676
6676
  });
6677
6677
 
6678
+ // ../machine-connector/dist/runtime/retry-backoff.js
6679
+ var RetryBackoff;
6680
+ var init_retry_backoff = __esm({
6681
+ "../machine-connector/dist/runtime/retry-backoff.js"() {
6682
+ "use strict";
6683
+ init_cjs_shims();
6684
+ RetryBackoff = class {
6685
+ currentMilliseconds;
6686
+ maximumMilliseconds;
6687
+ minimumMilliseconds;
6688
+ random;
6689
+ constructor(options) {
6690
+ if (!Number.isFinite(options.minimumMilliseconds) || options.minimumMilliseconds <= 0 || !Number.isFinite(options.maximumMilliseconds) || options.maximumMilliseconds < options.minimumMilliseconds) {
6691
+ throw new Error("Retry backoff interval range is invalid");
6692
+ }
6693
+ this.maximumMilliseconds = options.maximumMilliseconds;
6694
+ this.minimumMilliseconds = options.minimumMilliseconds;
6695
+ this.random = options.random ?? Math.random;
6696
+ this.currentMilliseconds = this.minimumMilliseconds;
6697
+ }
6698
+ nextDelayMilliseconds() {
6699
+ const sampledValue = this.random();
6700
+ const randomValue = Number.isFinite(sampledValue) ? Math.max(0, Math.min(1, sampledValue)) : 0.5;
6701
+ const delayMilliseconds = Math.min(this.maximumMilliseconds, this.currentMilliseconds * (0.75 + randomValue * 0.5));
6702
+ this.currentMilliseconds = Math.min(this.currentMilliseconds * 2, this.maximumMilliseconds);
6703
+ return delayMilliseconds;
6704
+ }
6705
+ reset() {
6706
+ this.currentMilliseconds = this.minimumMilliseconds;
6707
+ }
6708
+ };
6709
+ }
6710
+ });
6711
+
6678
6712
  // ../machine-connector/dist/runtime/version.js
6679
6713
  var connectorVersion;
6680
6714
  var init_version = __esm({
@@ -6752,7 +6786,13 @@ function localCodexRuntimeEventsRequestBody(fence, firstSequence, events) {
6752
6786
  function localCodexRuntimeEventsRequestBytes(fence, firstSequence, events) {
6753
6787
  return Buffer.byteLength(JSON.stringify(localCodexRuntimeEventsRequestBody(fence, firstSequence, events)), "utf8");
6754
6788
  }
6755
- async function postJson(url, body, accessToken, externalSignal) {
6789
+ function bindAccessTokenRejection(error, accessToken) {
6790
+ if (error instanceof RelayHttpError && error.status === 401) {
6791
+ return new AccessTokenRejectedError(error, accessToken.revision);
6792
+ }
6793
+ return error instanceof Error ? error : new Error(String(error));
6794
+ }
6795
+ async function postJson(url, body, accessToken, externalSignal, timeoutMilliseconds = requestTimeoutMilliseconds) {
6756
6796
  const headers = {
6757
6797
  "Content-Type": "application/json",
6758
6798
  "User-Agent": `moxt-machine-connector/${connectorVersion}`
@@ -6764,18 +6804,18 @@ async function postJson(url, body, accessToken, externalSignal) {
6764
6804
  body: JSON.stringify(body),
6765
6805
  headers,
6766
6806
  method: "POST",
6767
- signal: requestSignal(externalSignal)
6807
+ signal: requestSignal(timeoutMilliseconds, externalSignal)
6768
6808
  });
6769
6809
  const responseText = await response.text();
6770
6810
  if (!response.ok) {
6771
- throw new RelayHttpError(response.status, responseText);
6811
+ throw relayHttpError(response, responseText);
6772
6812
  }
6773
6813
  if (responseText.length === 0) {
6774
6814
  return void 0;
6775
6815
  }
6776
6816
  return JSON.parse(responseText);
6777
6817
  }
6778
- async function getJson(url, accessToken, extraHeaders, externalSignal) {
6818
+ async function getJson(url, accessToken, extraHeaders, externalSignal, timeoutMilliseconds = requestTimeoutMilliseconds) {
6779
6819
  const response = await fetch(url, {
6780
6820
  headers: {
6781
6821
  ...extraHeaders,
@@ -6783,23 +6823,129 @@ async function getJson(url, accessToken, extraHeaders, externalSignal) {
6783
6823
  "User-Agent": `moxt-machine-connector/${connectorVersion}`
6784
6824
  },
6785
6825
  method: "GET",
6786
- signal: requestSignal(externalSignal)
6826
+ signal: requestSignal(timeoutMilliseconds, externalSignal)
6787
6827
  });
6788
6828
  const responseText = await response.text();
6789
6829
  if (!response.ok) {
6790
- throw new RelayHttpError(response.status, responseText);
6830
+ throw relayHttpError(response, responseText);
6791
6831
  }
6792
6832
  return JSON.parse(responseText);
6793
6833
  }
6794
- function requestSignal(externalSignal) {
6834
+ function requestSignal(timeoutMilliseconds, externalSignal) {
6795
6835
  if (externalSignal === void 0) {
6796
- return AbortSignal.timeout(requestTimeoutMilliseconds);
6836
+ return AbortSignal.timeout(timeoutMilliseconds);
6797
6837
  }
6798
6838
  return AbortSignal.any([
6799
6839
  externalSignal,
6800
- AbortSignal.timeout(requestTimeoutMilliseconds)
6840
+ AbortSignal.timeout(timeoutMilliseconds)
6801
6841
  ]);
6802
6842
  }
6843
+ function relayHttpError(response, responseBody) {
6844
+ return new RelayHttpError(response.status, responseBody, retryAfterMilliseconds(response).value);
6845
+ }
6846
+ function retryAfterMilliseconds(response) {
6847
+ const retryAfter = response.headers.get("retry-after");
6848
+ if (retryAfter === null) {
6849
+ return {};
6850
+ }
6851
+ const seconds = Number(retryAfter);
6852
+ if (Number.isFinite(seconds) && seconds >= 0) {
6853
+ return { value: seconds * 1e3 };
6854
+ }
6855
+ const retryAt = Date.parse(retryAfter);
6856
+ if (!Number.isFinite(retryAt)) {
6857
+ return {};
6858
+ }
6859
+ return { value: Math.max(0, retryAt - Date.now()) };
6860
+ }
6861
+ function requestWithoutLongPolling(request2, timeoutField) {
6862
+ if (typeof request2 !== "object" || request2 === null || Array.isArray(request2)) {
6863
+ return request2;
6864
+ }
6865
+ return { ...request2, [timeoutField]: 0 };
6866
+ }
6867
+ function isRetryableRelayFailure(error) {
6868
+ if (error instanceof MachineConnectionRevokedError) {
6869
+ return false;
6870
+ }
6871
+ if (!(error instanceof RelayHttpError)) {
6872
+ return true;
6873
+ }
6874
+ return error.status === 408 || error.status === 425 || error.status === 429 || error.status >= 500;
6875
+ }
6876
+ function isPermanentRelayFailure(error) {
6877
+ return error instanceof MachineConnectionRevokedError || error instanceof RelayHttpError && !isRetryableRelayFailure(error);
6878
+ }
6879
+ function completionSignal() {
6880
+ let resolveCompletion;
6881
+ const completion = new Promise((resolvePromise) => {
6882
+ resolveCompletion = resolvePromise;
6883
+ });
6884
+ return { completion, resolve: resolveCompletion };
6885
+ }
6886
+ async function waitForSignal(milliseconds, signal) {
6887
+ if (milliseconds <= 0) {
6888
+ throwIfAborted(signal);
6889
+ return;
6890
+ }
6891
+ if (signal === void 0) {
6892
+ await new Promise((resolvePromise) => {
6893
+ const timeout = setTimeout(resolvePromise, milliseconds);
6894
+ timeout.unref();
6895
+ });
6896
+ return;
6897
+ }
6898
+ await new Promise((resolvePromise, rejectPromise) => {
6899
+ const timeout = setTimeout(() => {
6900
+ signal.removeEventListener("abort", onAbort);
6901
+ resolvePromise();
6902
+ }, milliseconds);
6903
+ const onAbort = () => {
6904
+ clearTimeout(timeout);
6905
+ signal.removeEventListener("abort", onAbort);
6906
+ rejectPromise(abortError(signal));
6907
+ };
6908
+ timeout.unref();
6909
+ signal.addEventListener("abort", onAbort, { once: true });
6910
+ if (signal.aborted) {
6911
+ onAbort();
6912
+ }
6913
+ });
6914
+ }
6915
+ async function waitForCompletion(completion, signal) {
6916
+ throwIfAborted(signal);
6917
+ if (signal === void 0) {
6918
+ await completion;
6919
+ return;
6920
+ }
6921
+ await new Promise((resolvePromise, rejectPromise) => {
6922
+ const onAbort = () => {
6923
+ signal.removeEventListener("abort", onAbort);
6924
+ rejectPromise(abortError(signal));
6925
+ };
6926
+ signal.addEventListener("abort", onAbort, { once: true });
6927
+ if (signal.aborted) {
6928
+ onAbort();
6929
+ }
6930
+ void completion.then(() => {
6931
+ signal.removeEventListener("abort", onAbort);
6932
+ resolvePromise();
6933
+ });
6934
+ });
6935
+ }
6936
+ function throwIfAborted(signal) {
6937
+ if (signal?.aborted === true) {
6938
+ throw abortError(signal);
6939
+ }
6940
+ }
6941
+ function abortError(signal) {
6942
+ if (signal.reason instanceof Error) {
6943
+ return signal.reason;
6944
+ }
6945
+ const error = new Error("Relay request aborted");
6946
+ error.name = "AbortError";
6947
+ return error;
6948
+ }
6803
6949
  function toRelayEvent(event2) {
6804
6950
  let payload = {};
6805
6951
  if (event2.payloadJson) {
@@ -6823,22 +6969,42 @@ function toRelayEvent(event2) {
6823
6969
  function normalizeOrigin(relayOrigin) {
6824
6970
  return relayOrigin.replace(/\/+$/, "");
6825
6971
  }
6826
- var requestTimeoutMilliseconds, RelayHttpError, MachineConnectionRevokedError, PairingRelayClient, MachineRelayClient;
6972
+ var requestTimeoutMilliseconds, probeRequestTimeoutMilliseconds, defaultRelayRetryMilliseconds, maximumRelayRetryMilliseconds, minimumBulkRelayRequestIntervalMilliseconds, minimumLongPollRelayRequestIntervalMilliseconds, minimumShortRelayRequestIntervalMilliseconds, maximumConcurrentBulkRelayRequests, maximumConcurrentShortRelayRequests, maximumAuthenticatedRequestAttempts, RelayHttpError, AccessTokenRejectedError, MachineConnectionRevokedError, RelayRequestMode, RelayCircuitKind, RelayRequestCoordinator, PairingRelayClient, MachineRelayClient;
6827
6973
  var init_relay_client = __esm({
6828
6974
  "../machine-connector/dist/runtime/relay-client.js"() {
6829
6975
  "use strict";
6830
6976
  init_cjs_shims();
6977
+ init_retry_backoff();
6831
6978
  init_version();
6832
6979
  init_contracts2();
6833
6980
  requestTimeoutMilliseconds = 65e3;
6981
+ probeRequestTimeoutMilliseconds = 1e4;
6982
+ defaultRelayRetryMilliseconds = 1e3;
6983
+ maximumRelayRetryMilliseconds = 6e4;
6984
+ minimumBulkRelayRequestIntervalMilliseconds = 10;
6985
+ minimumLongPollRelayRequestIntervalMilliseconds = 10;
6986
+ minimumShortRelayRequestIntervalMilliseconds = 5;
6987
+ maximumConcurrentBulkRelayRequests = 16;
6988
+ maximumConcurrentShortRelayRequests = 32;
6989
+ maximumAuthenticatedRequestAttempts = 4;
6834
6990
  RelayHttpError = class extends Error {
6835
6991
  responseBody;
6992
+ retryAfterMilliseconds;
6836
6993
  status;
6837
- constructor(status, responseBody) {
6994
+ constructor(status, responseBody, retryAfterMilliseconds2) {
6838
6995
  super(`Machine Relay returned HTTP ${status}: ${responseBody}`);
6839
6996
  this.name = "RelayHttpError";
6840
6997
  this.status = status;
6841
6998
  this.responseBody = responseBody;
6999
+ this.retryAfterMilliseconds = retryAfterMilliseconds2;
7000
+ }
7001
+ };
7002
+ AccessTokenRejectedError = class extends RelayHttpError {
7003
+ accessTokenRevision;
7004
+ constructor(error, accessTokenRevision) {
7005
+ super(error.status, error.responseBody, error.retryAfterMilliseconds);
7006
+ this.name = "AccessTokenRejectedError";
7007
+ this.accessTokenRevision = accessTokenRevision;
6842
7008
  }
6843
7009
  };
6844
7010
  MachineConnectionRevokedError = class extends Error {
@@ -6849,6 +7015,298 @@ var init_relay_client = __esm({
6849
7015
  this.connectionId = connectionId;
6850
7016
  }
6851
7017
  };
7018
+ (function(RelayRequestMode2) {
7019
+ RelayRequestMode2["Bulk"] = "bulk";
7020
+ RelayRequestMode2["LongPoll"] = "long_poll";
7021
+ RelayRequestMode2["Short"] = "short";
7022
+ })(RelayRequestMode || (RelayRequestMode = {}));
7023
+ (function(RelayCircuitKind2) {
7024
+ RelayCircuitKind2["Acknowledgement"] = "acknowledgement";
7025
+ RelayCircuitKind2["Claim"] = "claim";
7026
+ RelayCircuitKind2["ControlPoll"] = "control_poll";
7027
+ RelayCircuitKind2["Discovery"] = "discovery";
7028
+ RelayCircuitKind2["Events"] = "events";
7029
+ RelayCircuitKind2["Heartbeat"] = "heartbeat";
7030
+ RelayCircuitKind2["Lease"] = "lease";
7031
+ RelayCircuitKind2["Other"] = "other";
7032
+ RelayCircuitKind2["Refresh"] = "refresh";
7033
+ RelayCircuitKind2["State"] = "state";
7034
+ })(RelayCircuitKind || (RelayCircuitKind = {}));
7035
+ RelayRequestCoordinator = class {
7036
+ activeBulkRequests = 0;
7037
+ activeShortRequests = 0;
7038
+ circuits = /* @__PURE__ */ new Map();
7039
+ maximumConcurrentBulkRequests;
7040
+ maximumConcurrentShortRequests;
7041
+ maximumRetryMilliseconds;
7042
+ minimumBulkRequestIntervalMilliseconds;
7043
+ minimumLongPollRequestIntervalMilliseconds;
7044
+ minimumShortRequestIntervalMilliseconds;
7045
+ nextBulkRequestStartMilliseconds = 0;
7046
+ nextLongPollRequestStartMilliseconds = 0;
7047
+ nextShortRequestStartMilliseconds = 0;
7048
+ permitWaiters = [];
7049
+ constructor(options) {
7050
+ this.maximumConcurrentShortRequests = options.maximumConcurrentShortRequests ?? maximumConcurrentShortRelayRequests;
7051
+ this.maximumConcurrentBulkRequests = options.maximumConcurrentBulkRequests ?? Math.min(maximumConcurrentBulkRelayRequests, Math.max(1, Math.floor(this.maximumConcurrentShortRequests / 2)));
7052
+ this.maximumRetryMilliseconds = options.maximumRetryMilliseconds ?? maximumRelayRetryMilliseconds;
7053
+ this.minimumBulkRequestIntervalMilliseconds = options.minimumBulkRequestIntervalMilliseconds ?? minimumBulkRelayRequestIntervalMilliseconds;
7054
+ this.minimumLongPollRequestIntervalMilliseconds = options.minimumLongPollRequestIntervalMilliseconds ?? minimumLongPollRelayRequestIntervalMilliseconds;
7055
+ this.minimumShortRequestIntervalMilliseconds = options.minimumShortRequestIntervalMilliseconds ?? minimumShortRelayRequestIntervalMilliseconds;
7056
+ for (const circuitKind of Object.values(RelayCircuitKind)) {
7057
+ this.circuits.set(circuitKind, {
7058
+ blockedUntilMilliseconds: 0,
7059
+ generation: 0,
7060
+ open: false,
7061
+ retryBackoff: new RetryBackoff({
7062
+ maximumMilliseconds: this.maximumRetryMilliseconds,
7063
+ minimumMilliseconds: options.minimumRetryMilliseconds ?? defaultRelayRetryMilliseconds,
7064
+ random: options.random
7065
+ })
7066
+ });
7067
+ }
7068
+ if (!Number.isInteger(this.maximumConcurrentShortRequests) || this.maximumConcurrentShortRequests <= 0 || !Number.isInteger(this.maximumConcurrentBulkRequests) || this.maximumConcurrentBulkRequests <= 0 || this.maximumConcurrentBulkRequests > this.maximumConcurrentShortRequests) {
7069
+ throw new Error("Relay concurrent request limits are invalid");
7070
+ }
7071
+ if (!Number.isFinite(this.minimumBulkRequestIntervalMilliseconds) || this.minimumBulkRequestIntervalMilliseconds < 0 || !Number.isFinite(this.minimumLongPollRequestIntervalMilliseconds) || this.minimumLongPollRequestIntervalMilliseconds < 0 || !Number.isFinite(this.minimumShortRequestIntervalMilliseconds) || this.minimumShortRequestIntervalMilliseconds < 0) {
7072
+ throw new Error("Relay minimum request interval must be a non-negative number");
7073
+ }
7074
+ }
7075
+ async run(circuitKind, mode, operation, signal) {
7076
+ const admission = await this.admit(circuitKind, mode, signal);
7077
+ try {
7078
+ const result = await operation(admission.probe);
7079
+ this.recordSuccess(admission);
7080
+ return result;
7081
+ } catch (error) {
7082
+ this.recordFailure(admission, error, signal);
7083
+ throw error;
7084
+ } finally {
7085
+ if (admission.shortRequestPermit) {
7086
+ this.releaseShortRequestPermit(admission.bulkRequestPermit);
7087
+ }
7088
+ }
7089
+ }
7090
+ async admit(circuitKind, mode, signal) {
7091
+ while (true) {
7092
+ const circuitAdmission = await this.reserveCircuitAdmission(circuitKind, mode, signal);
7093
+ const bulkRequest = mode === RelayRequestMode.Bulk;
7094
+ let shortRequestPermit = false;
7095
+ try {
7096
+ await this.waitForRequestStart(mode, signal);
7097
+ if (mode !== RelayRequestMode.LongPoll) {
7098
+ await this.acquireShortRequestPermit(bulkRequest, circuitAdmission.probe, signal);
7099
+ shortRequestPermit = true;
7100
+ }
7101
+ if (this.isCurrentAdmission(circuitAdmission)) {
7102
+ return {
7103
+ ...circuitAdmission,
7104
+ bulkRequestPermit: bulkRequest,
7105
+ shortRequestPermit
7106
+ };
7107
+ }
7108
+ } catch (error) {
7109
+ if (circuitAdmission.probe) {
7110
+ this.cancelProbe(circuitAdmission);
7111
+ }
7112
+ throw error;
7113
+ }
7114
+ if (shortRequestPermit) {
7115
+ this.releaseShortRequestPermit(bulkRequest);
7116
+ }
7117
+ }
7118
+ }
7119
+ async reserveCircuitAdmission(circuitKind, mode, signal) {
7120
+ const circuit = this.requireCircuit(circuitKind);
7121
+ while (true) {
7122
+ throwIfAborted(signal);
7123
+ if (!circuit.open) {
7124
+ return {
7125
+ circuitKind,
7126
+ generation: circuit.generation,
7127
+ mode,
7128
+ probe: false
7129
+ };
7130
+ }
7131
+ const blockedForMilliseconds = circuit.blockedUntilMilliseconds - Date.now();
7132
+ if (blockedForMilliseconds > 0) {
7133
+ await waitForSignal(blockedForMilliseconds, signal);
7134
+ continue;
7135
+ }
7136
+ if (circuit.probe !== void 0) {
7137
+ await waitForCompletion(circuit.probe.completion, signal);
7138
+ continue;
7139
+ }
7140
+ const probeSignal = completionSignal();
7141
+ circuit.probe = {
7142
+ completion: probeSignal.completion,
7143
+ generation: circuit.generation,
7144
+ resolve: () => probeSignal.resolve()
7145
+ };
7146
+ return {
7147
+ circuitKind,
7148
+ generation: circuit.generation,
7149
+ mode,
7150
+ probe: true
7151
+ };
7152
+ }
7153
+ }
7154
+ async waitForRequestStart(mode, signal) {
7155
+ const now = Date.now();
7156
+ const longPoll = mode === RelayRequestMode.LongPoll;
7157
+ const bulk = mode === RelayRequestMode.Bulk;
7158
+ const scheduledAt = Math.max(now, longPoll ? this.nextLongPollRequestStartMilliseconds : bulk ? this.nextBulkRequestStartMilliseconds : this.nextShortRequestStartMilliseconds);
7159
+ if (longPoll) {
7160
+ this.nextLongPollRequestStartMilliseconds = scheduledAt + this.minimumLongPollRequestIntervalMilliseconds;
7161
+ } else if (bulk) {
7162
+ this.nextBulkRequestStartMilliseconds = scheduledAt + this.minimumBulkRequestIntervalMilliseconds;
7163
+ } else {
7164
+ this.nextShortRequestStartMilliseconds = scheduledAt + this.minimumShortRequestIntervalMilliseconds;
7165
+ }
7166
+ await waitForSignal(scheduledAt - now, signal);
7167
+ }
7168
+ async acquireShortRequestPermit(bulkRequest, probe, signal) {
7169
+ throwIfAborted(signal);
7170
+ const completion = completionSignal();
7171
+ const waiter = {
7172
+ bulkRequest,
7173
+ completion: completion.completion,
7174
+ granted: false,
7175
+ probe,
7176
+ resolve: () => completion.resolve()
7177
+ };
7178
+ this.permitWaiters.push(waiter);
7179
+ this.grantRequestPermits();
7180
+ try {
7181
+ await waitForCompletion(waiter.completion, signal);
7182
+ } catch (error) {
7183
+ if (waiter.granted) {
7184
+ this.releaseShortRequestPermit(waiter.bulkRequest);
7185
+ } else {
7186
+ const index2 = this.permitWaiters.indexOf(waiter);
7187
+ if (index2 >= 0) {
7188
+ this.permitWaiters.splice(index2, 1);
7189
+ }
7190
+ this.grantRequestPermits();
7191
+ }
7192
+ throw error;
7193
+ }
7194
+ }
7195
+ releaseShortRequestPermit(bulkRequest) {
7196
+ this.activeShortRequests -= 1;
7197
+ if (bulkRequest) {
7198
+ this.activeBulkRequests -= 1;
7199
+ }
7200
+ this.grantRequestPermits();
7201
+ }
7202
+ grantRequestPermits() {
7203
+ while (this.activeShortRequests < this.maximumConcurrentShortRequests) {
7204
+ const criticalIndex = this.permitWaiters.findIndex((waiter2) => !waiter2.bulkRequest || waiter2.probe);
7205
+ let waiterIndex = criticalIndex;
7206
+ if (waiterIndex < 0 && this.activeBulkRequests < this.maximumConcurrentBulkRequests && this.permitWaiters.length > 0) {
7207
+ waiterIndex = 0;
7208
+ }
7209
+ if (waiterIndex < 0) {
7210
+ return;
7211
+ }
7212
+ const waiter = this.permitWaiters.splice(waiterIndex, 1)[0];
7213
+ if (waiter === void 0) {
7214
+ throw new Error("Relay request permit waiter is unavailable");
7215
+ }
7216
+ waiter.granted = true;
7217
+ this.activeShortRequests += 1;
7218
+ if (waiter.bulkRequest) {
7219
+ this.activeBulkRequests += 1;
7220
+ }
7221
+ waiter.resolve();
7222
+ }
7223
+ }
7224
+ recordSuccess(admission) {
7225
+ if (!admission.probe || !this.isCurrentAdmission(admission)) {
7226
+ return;
7227
+ }
7228
+ const circuit = this.requireCircuit(admission.circuitKind);
7229
+ const probe = circuit.probe;
7230
+ circuit.open = false;
7231
+ circuit.blockedUntilMilliseconds = 0;
7232
+ circuit.generation += 1;
7233
+ this.resetRequestSchedule(admission.mode);
7234
+ circuit.retryBackoff.reset();
7235
+ delete circuit.probe;
7236
+ probe?.resolve();
7237
+ }
7238
+ recordFailure(admission, error, signal) {
7239
+ if (signal?.aborted === true && !(error instanceof RelayHttpError) && !(error instanceof MachineConnectionRevokedError)) {
7240
+ if (admission.probe) {
7241
+ this.cancelProbe(admission);
7242
+ }
7243
+ return;
7244
+ }
7245
+ if (!isRetryableRelayFailure(error)) {
7246
+ this.recordSuccess(admission);
7247
+ return;
7248
+ }
7249
+ if (admission.circuitKind === RelayCircuitKind.State) {
7250
+ return;
7251
+ }
7252
+ if (!this.isCurrentAdmission(admission)) {
7253
+ return;
7254
+ }
7255
+ this.openCircuit(admission.circuitKind, admission.mode, error instanceof RelayHttpError ? error.retryAfterMilliseconds : void 0);
7256
+ }
7257
+ openCircuit(circuitKind, mode, retryAfterMilliseconds2) {
7258
+ const circuit = this.requireCircuit(circuitKind);
7259
+ const jitteredMilliseconds = circuit.retryBackoff.nextDelayMilliseconds();
7260
+ const serverDelayMilliseconds = Math.min(this.maximumRetryMilliseconds, Math.max(0, retryAfterMilliseconds2 ?? 0));
7261
+ const delayMilliseconds = Math.max(jitteredMilliseconds, serverDelayMilliseconds);
7262
+ const previousProbe = circuit.probe;
7263
+ circuit.open = true;
7264
+ circuit.generation += 1;
7265
+ circuit.blockedUntilMilliseconds = Date.now() + delayMilliseconds;
7266
+ this.resetRequestSchedule(mode);
7267
+ delete circuit.probe;
7268
+ previousProbe?.resolve();
7269
+ }
7270
+ cancelProbe(admission) {
7271
+ if (!admission.probe || !this.isCurrentAdmission(admission)) {
7272
+ return;
7273
+ }
7274
+ const circuit = this.requireCircuit(admission.circuitKind);
7275
+ const probe = circuit.probe;
7276
+ delete circuit.probe;
7277
+ circuit.blockedUntilMilliseconds = Date.now();
7278
+ probe?.resolve();
7279
+ }
7280
+ isCurrentAdmission(admission) {
7281
+ const circuit = this.requireCircuit(admission.circuitKind);
7282
+ if (admission.generation !== circuit.generation) {
7283
+ return false;
7284
+ }
7285
+ if (!admission.probe) {
7286
+ return !circuit.open;
7287
+ }
7288
+ return circuit.open && circuit.probe?.generation === admission.generation;
7289
+ }
7290
+ resetRequestSchedule(mode) {
7291
+ const now = Date.now();
7292
+ if (mode === RelayRequestMode.Bulk) {
7293
+ this.nextBulkRequestStartMilliseconds = now;
7294
+ return;
7295
+ }
7296
+ if (mode === RelayRequestMode.LongPoll) {
7297
+ this.nextLongPollRequestStartMilliseconds = now;
7298
+ return;
7299
+ }
7300
+ this.nextShortRequestStartMilliseconds = now;
7301
+ }
7302
+ requireCircuit(circuitKind) {
7303
+ const circuit = this.circuits.get(circuitKind);
7304
+ if (circuit === void 0) {
7305
+ throw new Error(`Relay circuit ${circuitKind} is unavailable`);
7306
+ }
7307
+ return circuit;
7308
+ }
7309
+ };
6852
7310
  PairingRelayClient = class {
6853
7311
  relayOrigin;
6854
7312
  constructor(relayOrigin) {
@@ -6864,28 +7322,39 @@ var init_relay_client = __esm({
6864
7322
  MachineRelayClient = class {
6865
7323
  connection;
6866
7324
  store;
6867
- hooks;
7325
+ options;
7326
+ accessTokenRevision = 0;
6868
7327
  refreshState = {};
7328
+ requestCoordinator;
6869
7329
  revoked = false;
6870
- constructor(connection, store, hooks = {}) {
7330
+ constructor(connection, store, options = {}) {
6871
7331
  this.connection = connection;
6872
7332
  this.store = store;
6873
- this.hooks = hooks;
7333
+ this.options = options;
7334
+ this.requestCoordinator = new RelayRequestCoordinator(options);
6874
7335
  }
6875
7336
  isRevoked() {
6876
7337
  return this.revoked;
6877
7338
  }
6878
- async heartbeat(request2) {
6879
- await this.authenticatedPost("heartbeat", request2);
7339
+ async heartbeat(request2, signal) {
7340
+ await this.authenticatedPost("heartbeat", request2, {
7341
+ circuitKind: RelayCircuitKind.Heartbeat,
7342
+ signal
7343
+ });
6880
7344
  }
6881
7345
  async disconnect() {
6882
7346
  await this.authenticatedPost("disconnect", {});
6883
7347
  }
6884
- async claim(request2) {
6885
- return await this.authenticatedPost("jobs/claim", request2);
7348
+ async claim(request2, signal) {
7349
+ return await this.authenticatedPost("jobs/claim", request2, {
7350
+ circuitKind: RelayCircuitKind.Claim,
7351
+ mode: RelayRequestMode.LongPoll,
7352
+ probeBody: requestWithoutLongPolling(request2, "timeoutSeconds"),
7353
+ signal
7354
+ });
6886
7355
  }
6887
7356
  async renewLease(request2) {
6888
- return await this.authenticatedPost("jobs/lease", request2);
7357
+ return await this.authenticatedPost("jobs/lease", request2, { circuitKind: RelayCircuitKind.Lease });
6889
7358
  }
6890
7359
  async appendEvents(jobId, generation, leaseToken, runToken, protocolVersion, events) {
6891
7360
  return await this.authenticatedPost("jobs/events", {
@@ -6895,41 +7364,75 @@ var init_relay_client = __esm({
6895
7364
  leaseToken,
6896
7365
  protocolVersion,
6897
7366
  runToken
7367
+ }, {
7368
+ circuitKind: RelayCircuitKind.Events,
7369
+ mode: RelayRequestMode.Bulk
6898
7370
  });
6899
7371
  }
6900
7372
  async updateJob(request2) {
6901
- await this.authenticatedPost("jobs/state", request2);
7373
+ await this.authenticatedPost("jobs/state", request2, {
7374
+ circuitKind: RelayCircuitKind.State
7375
+ });
6902
7376
  }
6903
- async pollControls(request2) {
6904
- return await this.authenticatedPost("controls/poll", request2);
7377
+ async pollControls(request2, signal) {
7378
+ return await this.authenticatedPost("controls/poll", request2, {
7379
+ circuitKind: RelayCircuitKind.ControlPoll,
7380
+ mode: RelayRequestMode.LongPoll,
7381
+ probeBody: requestWithoutLongPolling(request2, "timeoutSeconds"),
7382
+ signal
7383
+ });
6905
7384
  }
6906
7385
  async acknowledgeControl(request2) {
6907
- await this.authenticatedPost("controls/acknowledge", request2);
7386
+ await this.authenticatedPost("controls/acknowledge", request2, {
7387
+ circuitKind: RelayCircuitKind.Acknowledgement
7388
+ });
6908
7389
  }
6909
- async heartbeatCodexRuntime(request2) {
6910
- return await this.authenticatedPost("codex-runtime/heartbeat", request2);
7390
+ async heartbeatCodexRuntime(request2, signal) {
7391
+ return await this.authenticatedPost("codex-runtime/heartbeat", request2, {
7392
+ circuitKind: RelayCircuitKind.Heartbeat,
7393
+ signal
7394
+ });
6911
7395
  }
6912
7396
  async claimCodexRuntime(request2, signal) {
6913
- return await this.authenticatedPost("codex-runtime/turns/claim", request2, signal);
7397
+ return await this.authenticatedPost("codex-runtime/turns/claim", request2, {
7398
+ circuitKind: RelayCircuitKind.Claim,
7399
+ mode: RelayRequestMode.LongPoll,
7400
+ probeBody: { ...request2, waitSeconds: 0 },
7401
+ signal
7402
+ });
6914
7403
  }
6915
7404
  async claimCodexRuntimeDiscovery(request2, signal) {
6916
- return await this.authenticatedPost("codex-runtime/discovery/claim", request2, signal);
7405
+ return await this.authenticatedPost("codex-runtime/discovery/claim", request2, {
7406
+ circuitKind: RelayCircuitKind.Discovery,
7407
+ mode: RelayRequestMode.LongPoll,
7408
+ probeBody: { ...request2, waitSeconds: 0 },
7409
+ signal
7410
+ });
6917
7411
  }
6918
- async completeCodexRuntimeDiscovery(requestId, connectorInstanceId, result) {
7412
+ async completeCodexRuntimeDiscovery(requestId, connectorInstanceId, result, signal) {
6919
7413
  return await this.authenticatedPost(`codex-runtime/discovery/requests/${encodeURIComponent(requestId)}/result`, {
6920
7414
  ...result,
6921
7415
  connectorInstanceId,
6922
7416
  protocolVersion: localCodexRuntimeProtocolVersion
7417
+ }, {
7418
+ circuitKind: RelayCircuitKind.Discovery,
7419
+ signal
6923
7420
  });
6924
7421
  }
6925
7422
  async renewCodexRuntimeLease(attemptId, fence, signal) {
6926
- return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/lease`, fence, signal);
7423
+ return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/lease`, fence, {
7424
+ circuitKind: RelayCircuitKind.Lease,
7425
+ signal
7426
+ });
6927
7427
  }
6928
7428
  async appendCodexRuntimeEvents(attemptId, fence, firstSequence, events) {
6929
- return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/events`, localCodexRuntimeEventsRequestBody(fence, firstSequence, events));
7429
+ return await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/events`, localCodexRuntimeEventsRequestBody(fence, firstSequence, events), {
7430
+ circuitKind: RelayCircuitKind.Events,
7431
+ mode: RelayRequestMode.Bulk
7432
+ });
6930
7433
  }
6931
7434
  async updateCodexRuntimeState(attemptId, fence, state) {
6932
- await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/state`, { ...fence, ...state });
7435
+ await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/state`, { ...fence, ...state }, { circuitKind: RelayCircuitKind.State });
6933
7436
  }
6934
7437
  async pollCodexRuntimeControls(attemptId, fence, after, waitSeconds, signal) {
6935
7438
  return await this.authenticatedGet(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/controls`, { after: String(after), waitSeconds: String(waitSeconds) }, {
@@ -6939,63 +7442,107 @@ var init_relay_client = __esm({
6939
7442
  "x-moxt-local-codex-process-generation": String(fence.processGeneration),
6940
7443
  "x-moxt-local-codex-protocol-version": fence.protocolVersion,
6941
7444
  "x-moxt-local-codex-run-token": fence.runToken
6942
- }, signal);
7445
+ }, {
7446
+ circuitKind: RelayCircuitKind.ControlPoll,
7447
+ mode: RelayRequestMode.LongPoll,
7448
+ probeQuery: {
7449
+ after: String(after),
7450
+ waitSeconds: "0"
7451
+ },
7452
+ signal
7453
+ });
6943
7454
  }
6944
- async acknowledgeCodexRuntimeControl(attemptId, fence, controlId, outcome) {
6945
- await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/controls/acknowledge`, { ...fence, controlId, outcome });
7455
+ async acknowledgeCodexRuntimeControl(attemptId, fence, controlId, outcome, signal) {
7456
+ await this.authenticatedPost(`codex-runtime/attempts/${encodeURIComponent(attemptId)}/controls/acknowledge`, { ...fence, controlId, outcome }, {
7457
+ circuitKind: RelayCircuitKind.Acknowledgement,
7458
+ signal
7459
+ });
6946
7460
  }
6947
- async authenticatedPost(path4, body, signal) {
6948
- if (this.revoked) {
6949
- throw new MachineConnectionRevokedError(this.connection.connectionId);
6950
- }
6951
- const url = `${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`;
6952
- try {
6953
- return await postJson(url, body, this.connection.accessToken, signal);
6954
- } catch (error) {
6955
- if (!(error instanceof RelayHttpError) || error.status !== 401) {
6956
- throw error;
6957
- }
6958
- }
6959
- await this.refreshAccessTokenOnce();
6960
- return await postJson(url, body, this.connection.accessToken, signal);
7461
+ async authenticatedPost(path4, body, options = {}) {
7462
+ const request2 = async () => {
7463
+ return await this.requestCoordinator.run(options.circuitKind ?? RelayCircuitKind.Other, options.mode ?? RelayRequestMode.Short, async (probe) => {
7464
+ if (this.revoked) {
7465
+ throw new MachineConnectionRevokedError(this.connection.connectionId);
7466
+ }
7467
+ const accessToken = this.accessTokenSnapshot();
7468
+ const url = `${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`;
7469
+ const requestBody = probe && options.probeBody !== void 0 ? options.probeBody : body;
7470
+ try {
7471
+ return await postJson(url, requestBody, accessToken.token, options.signal, probe ? probeRequestTimeoutMilliseconds : requestTimeoutMilliseconds);
7472
+ } catch (error) {
7473
+ throw bindAccessTokenRejection(error, accessToken);
7474
+ }
7475
+ }, options.signal);
7476
+ };
7477
+ return await this.retryAuthenticatedRequest(request2);
6961
7478
  }
6962
- async authenticatedGet(path4, query, headers, signal) {
6963
- if (this.revoked) {
6964
- throw new MachineConnectionRevokedError(this.connection.connectionId);
6965
- }
6966
- const url = new URL(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`);
6967
- for (const [name, value] of Object.entries(query)) {
6968
- url.searchParams.set(name, value);
6969
- }
6970
- try {
6971
- return await getJson(url.toString(), this.connection.accessToken, headers, signal);
6972
- } catch (error) {
6973
- if (!(error instanceof RelayHttpError) || error.status !== 401) {
6974
- throw error;
7479
+ async authenticatedGet(path4, query, headers, options = {}) {
7480
+ const request2 = async () => {
7481
+ return await this.requestCoordinator.run(options.circuitKind ?? RelayCircuitKind.Other, options.mode ?? RelayRequestMode.Short, async (probe) => {
7482
+ if (this.revoked) {
7483
+ throw new MachineConnectionRevokedError(this.connection.connectionId);
7484
+ }
7485
+ const accessToken = this.accessTokenSnapshot();
7486
+ const url = new URL(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/${path4}`);
7487
+ const requestQuery = probe && options.probeQuery !== void 0 ? options.probeQuery : query;
7488
+ for (const [name, value] of Object.entries(requestQuery)) {
7489
+ url.searchParams.set(name, value);
7490
+ }
7491
+ try {
7492
+ return await getJson(url.toString(), accessToken.token, headers, options.signal, probe ? probeRequestTimeoutMilliseconds : requestTimeoutMilliseconds);
7493
+ } catch (error) {
7494
+ throw bindAccessTokenRejection(error, accessToken);
7495
+ }
7496
+ }, options.signal);
7497
+ };
7498
+ return await this.retryAuthenticatedRequest(request2);
7499
+ }
7500
+ async retryAuthenticatedRequest(request2) {
7501
+ for (let attempt = 1; attempt <= maximumAuthenticatedRequestAttempts; attempt += 1) {
7502
+ try {
7503
+ return await request2();
7504
+ } catch (error) {
7505
+ if (!(error instanceof AccessTokenRejectedError)) {
7506
+ throw error;
7507
+ }
7508
+ if (attempt === maximumAuthenticatedRequestAttempts) {
7509
+ throw error;
7510
+ }
7511
+ await this.refreshAccessTokenOnce(error.accessTokenRevision);
6975
7512
  }
6976
7513
  }
6977
- await this.refreshAccessTokenOnce();
6978
- return await getJson(url.toString(), this.connection.accessToken, headers, signal);
7514
+ throw new Error("Authenticated Relay request exhausted its attempts");
6979
7515
  }
6980
- async refreshAccessTokenOnce() {
7516
+ accessTokenSnapshot() {
7517
+ return {
7518
+ revision: this.accessTokenRevision,
7519
+ token: this.connection.accessToken
7520
+ };
7521
+ }
7522
+ async refreshAccessTokenOnce(rejectedAccessTokenRevision) {
7523
+ if (rejectedAccessTokenRevision !== this.accessTokenRevision) {
7524
+ return;
7525
+ }
6981
7526
  if (!this.refreshState.promise) {
6982
- this.refreshState.promise = this.refreshAccessToken().finally(() => {
7527
+ this.refreshState.promise = this.requestCoordinator.run(RelayCircuitKind.Refresh, RelayRequestMode.Short, async (probe) => {
7528
+ await this.refreshAccessToken(probe ? probeRequestTimeoutMilliseconds : requestTimeoutMilliseconds);
7529
+ }).finally(() => {
6983
7530
  delete this.refreshState.promise;
6984
7531
  });
6985
7532
  }
6986
7533
  await this.refreshState.promise;
6987
7534
  }
6988
- async refreshAccessToken() {
7535
+ async refreshAccessToken(timeoutMilliseconds) {
6989
7536
  let response;
6990
7537
  try {
6991
- response = await postJson(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/pairing/refresh`, { refreshToken: this.connection.refreshToken });
7538
+ response = await postJson(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/pairing/refresh`, { refreshToken: this.connection.refreshToken }, void 0, void 0, timeoutMilliseconds);
6992
7539
  } catch (error) {
6993
7540
  if (!(error instanceof RelayHttpError) || error.status !== 401) {
6994
7541
  throw error;
6995
7542
  }
6996
7543
  const revokedError = new MachineConnectionRevokedError(this.connection.connectionId);
6997
7544
  this.revoked = true;
6998
- await this.hooks.onConnectionRevoked?.(revokedError);
7545
+ await this.options.onConnectionRevoked?.(revokedError);
6999
7546
  throw revokedError;
7000
7547
  }
7001
7548
  this.connection = {
@@ -7003,6 +7550,7 @@ var init_relay_client = __esm({
7003
7550
  accessToken: response.accessToken,
7004
7551
  accessTokenExpiresAt: response.accessTokenExpiresAt
7005
7552
  };
7553
+ this.accessTokenRevision += 1;
7006
7554
  await this.store.saveConnection(this.connection);
7007
7555
  }
7008
7556
  };
@@ -8185,11 +8733,11 @@ var init_app_server_client = __esm({
8185
8733
  });
8186
8734
 
8187
8735
  // ../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js
8188
- function assertCompatibleClaim(persisted, connectionId, claim) {
8736
+ function assertCompatibleClaim(persisted, connectionId, claim, allowRestartFenceRotation) {
8189
8737
  if (persisted.connectionId !== connectionId || persisted.claim.attemptId !== claim.attemptId || persisted.claim.attemptGeneration !== claim.attemptGeneration || persisted.claim.conversationId !== claim.conversationId || persisted.claim.turnId !== claim.turnId || persisted.claim.expectedNativeStoreIdentity !== claim.expectedNativeStoreIdentity) {
8190
8738
  throw new Error(`Local Codex Runtime attempt ${claim.attemptId} conflicts with its durable spool`);
8191
8739
  }
8192
- if (persisted.phase !== LocalCodexAttemptPhase.Claimed && (persisted.claim.leaseToken !== claim.leaseToken || persisted.claim.runToken !== claim.runToken)) {
8740
+ if (persisted.phase !== LocalCodexAttemptPhase.Claimed && !allowRestartFenceRotation && (persisted.claim.leaseToken !== claim.leaseToken || persisted.claim.runToken !== claim.runToken)) {
8193
8741
  throw new Error(`Running Local Codex Runtime attempt ${claim.attemptId} changed its fence`);
8194
8742
  }
8195
8743
  }
@@ -8217,16 +8765,19 @@ var init_durable_attempt = __esm({
8217
8765
  DurableLocalCodexAttempt = class _DurableLocalCodexAttempt {
8218
8766
  store;
8219
8767
  state;
8768
+ recoveryRequired;
8220
8769
  mutationQueue = Promise.resolve();
8221
- constructor(store, state) {
8770
+ constructor(store, state, recoveryRequired = false) {
8222
8771
  this.store = store;
8223
8772
  this.state = state;
8773
+ this.recoveryRequired = recoveryRequired;
8224
8774
  }
8225
8775
  static async create(store, connectionId, connectorInstanceId, claim) {
8226
8776
  const persisted = (await store.readLocalCodexAttempt(claim.attemptId)).value;
8227
8777
  if (persisted !== void 0) {
8228
- assertCompatibleClaim(persisted, connectionId, claim);
8229
- if (persisted.phase === LocalCodexAttemptPhase.Claimed) {
8778
+ const recoveryRequired = persisted.phase === LocalCodexAttemptPhase.TerminalPendingUpload || persisted.phase === LocalCodexAttemptPhase.Running && persisted.connectorInstanceId !== connectorInstanceId;
8779
+ assertCompatibleClaim(persisted, connectionId, claim, recoveryRequired);
8780
+ if (persisted.phase === LocalCodexAttemptPhase.Claimed || recoveryRequired) {
8230
8781
  persisted.claim = claim;
8231
8782
  persisted.connectorInstanceId = connectorInstanceId;
8232
8783
  persisted.acknowledgedSequence = claim.lastAcknowledgedEventSequence;
@@ -8235,7 +8786,7 @@ var init_durable_attempt = __esm({
8235
8786
  persisted.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
8236
8787
  await store.writeLocalCodexAttempt(persisted);
8237
8788
  }
8238
- return new _DurableLocalCodexAttempt(store, persisted);
8789
+ return new _DurableLocalCodexAttempt(store, persisted, recoveryRequired);
8239
8790
  }
8240
8791
  const state = {
8241
8792
  acknowledgedSequence: claim.lastAcknowledgedEventSequence,
@@ -8258,6 +8809,9 @@ var init_durable_attempt = __esm({
8258
8809
  snapshot() {
8259
8810
  return structuredClone(this.state);
8260
8811
  }
8812
+ requiresRecovery() {
8813
+ return this.recoveryRequired;
8814
+ }
8261
8815
  async markRunning(nativeThreadId, nativeTurnId) {
8262
8816
  await this.mutate(async () => {
8263
8817
  this.state.nativeThreadId = nativeThreadId;
@@ -8728,12 +9282,15 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8728
9282
  eventUploadQueue: Promise.resolve(),
8729
9283
  fatal,
8730
9284
  finished: new AbortController(),
9285
+ ignoreProcessLoss: false,
8731
9286
  interruptedCleanupStarted: false,
8732
9287
  leaseDeadlineMilliseconds: parseLeaseDeadline(claim.leaseExpiresAt),
8733
9288
  nativeThreadId: durable.snapshot().nativeThreadId ?? claim.nativeThreadId,
9289
+ processQuarantined: false,
8734
9290
  spoolQueue: Promise.resolve(),
8735
9291
  subagentThreadIds: /* @__PURE__ */ new Set(),
8736
9292
  terminal,
9293
+ turnStartPending: false,
8737
9294
  resolveFatal,
8738
9295
  resolveTerminal,
8739
9296
  workingDirectory
@@ -8820,6 +9377,24 @@ function appServerMessageThreadId(message) {
8820
9377
  }
8821
9378
  return optionalString2(safeRecord(params.thread).id);
8822
9379
  }
9380
+ function appServerMessageTurnId(message) {
9381
+ const params = safeRecord(message.params);
9382
+ const direct = optionalString2(params.turnId).value;
9383
+ if (direct !== void 0) {
9384
+ return { value: direct };
9385
+ }
9386
+ return optionalString2(safeRecord(params.turn).id);
9387
+ }
9388
+ function activeOwnsThread(active, threadId) {
9389
+ return active.nativeThreadId === threadId || active.subagentThreadIds.has(threadId) || active.initialThreadName?.generation?.threadId === threadId;
9390
+ }
9391
+ function singleActiveAttempt(attempts) {
9392
+ if (attempts.length !== 1) {
9393
+ return {};
9394
+ }
9395
+ const value = attempts[0];
9396
+ return value === void 0 ? {} : { value };
9397
+ }
8823
9398
  function normalizeThreadTitle(value) {
8824
9399
  const title = Array.from(value.trim().replace(/\s+/g, " ")).slice(0, maximumThreadTitleCharacters).join("");
8825
9400
  return title === "" ? {} : { value: title };
@@ -9120,6 +9695,32 @@ async function waitForAbort(signal, milliseconds) {
9120
9695
  signal.addEventListener("abort", complete, { once: true });
9121
9696
  });
9122
9697
  }
9698
+ function createReclaimableClaimWindow() {
9699
+ let accepted = false;
9700
+ let close = () => void 0;
9701
+ const completion = new Promise((resolvePromise) => {
9702
+ close = resolvePromise;
9703
+ });
9704
+ return {
9705
+ accept: () => {
9706
+ accepted = true;
9707
+ close();
9708
+ },
9709
+ close,
9710
+ completion,
9711
+ isAccepted: () => accepted
9712
+ };
9713
+ }
9714
+ function rejectWhenAborted(signal) {
9715
+ return new Promise((_resolve, reject) => {
9716
+ const rejectStopped = () => reject(new WorkerStoppedError());
9717
+ if (signal.aborted) {
9718
+ rejectStopped();
9719
+ return;
9720
+ }
9721
+ signal.addEventListener("abort", rejectStopped, { once: true });
9722
+ });
9723
+ }
9123
9724
  function parseLeaseDeadline(value) {
9124
9725
  const parsed = Date.parse(value);
9125
9726
  if (!Number.isFinite(parsed)) {
@@ -9127,7 +9728,7 @@ function parseLeaseDeadline(value) {
9127
9728
  }
9128
9729
  return parsed;
9129
9730
  }
9130
- 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;
9731
+ var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, defaultNetworkRetryMilliseconds, maximumNetworkRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryScanIntervalMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
9131
9732
  var init_runtime_worker = __esm({
9132
9733
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
9133
9734
  "use strict";
@@ -9138,6 +9739,7 @@ var init_runtime_worker = __esm({
9138
9739
  import_node_path11 = require("path");
9139
9740
  init_process_executor();
9140
9741
  init_relay_client();
9742
+ init_retry_backoff();
9141
9743
  init_app_server_client();
9142
9744
  init_contracts2();
9143
9745
  init_durable_attempt();
@@ -9146,19 +9748,18 @@ var init_runtime_worker = __esm({
9146
9748
  claimRetryMilliseconds = 250;
9147
9749
  claimWaitSeconds = 25;
9148
9750
  discoveryWaitSeconds = 25;
9149
- discoveryRetryMilliseconds = 1e3;
9150
9751
  maximumDiscoveryDirectories = 1e3;
9151
9752
  maximumDiscoveryModels = 100;
9152
9753
  maximumModelListPages = 10;
9153
9754
  eventUploadCoalesceMilliseconds = 500;
9154
- eventUploadRetryMilliseconds = 1e3;
9155
9755
  maximumEventUploadCount = 500;
9156
9756
  preferredEventUploadRequestBytes = 96e3;
9157
9757
  leaseRenewIntervalMilliseconds = 1e4;
9158
- leaseRenewRetryMilliseconds = 1e3;
9758
+ defaultNetworkRetryMilliseconds = 1e3;
9759
+ maximumNetworkRetryMilliseconds = 6e4;
9159
9760
  interactionTimeoutMilliseconds = 10 * 60 * 1e3;
9160
9761
  executableProbeTimeoutMilliseconds = 5e3;
9161
- recoveryRetryMilliseconds = 1e3;
9762
+ recoveryScanIntervalMilliseconds = 1e3;
9162
9763
  initialThreadNameRetryMilliseconds = 250;
9163
9764
  maximumThreadNameRetryMilliseconds = 2e3;
9164
9765
  maximumInitialThreadNameAttempts = 8;
@@ -9203,6 +9804,12 @@ var init_runtime_worker = __esm({
9203
9804
  this.name = "UnknownTurnStartResultError";
9204
9805
  }
9205
9806
  };
9807
+ WorkerStoppedError = class extends Error {
9808
+ constructor() {
9809
+ super("Local Codex Runtime worker stopped");
9810
+ this.name = "WorkerStoppedError";
9811
+ }
9812
+ };
9206
9813
  LocalCodexRuntimeConnectionWorker = class {
9207
9814
  connection;
9208
9815
  relay;
@@ -9211,15 +9818,18 @@ var init_runtime_worker = __esm({
9211
9818
  environment;
9212
9819
  connectorInstanceId;
9213
9820
  logger;
9214
- active = {};
9821
+ activeAttempts = /* @__PURE__ */ new Map();
9215
9822
  configured = false;
9216
9823
  enabled = false;
9824
+ executionTasks = /* @__PURE__ */ new Map();
9217
9825
  lastCapabilityStartError;
9218
9826
  lifetimeAbort = new AbortController();
9827
+ networkRetryMilliseconds;
9828
+ random;
9219
9829
  registered = true;
9220
9830
  unrecoverableAttemptIds = /* @__PURE__ */ new Set();
9221
9831
  running;
9222
- constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger) {
9832
+ constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger, options = {}) {
9223
9833
  this.connection = connection;
9224
9834
  this.relay = relay;
9225
9835
  this.store = store;
@@ -9227,6 +9837,8 @@ var init_runtime_worker = __esm({
9227
9837
  this.environment = environment;
9228
9838
  this.connectorInstanceId = connectorInstanceId;
9229
9839
  this.logger = logger;
9840
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
9841
+ this.random = options.random ?? Math.random;
9230
9842
  this.processPool.register(connection.connectionId, this);
9231
9843
  }
9232
9844
  async run() {
@@ -9242,13 +9854,55 @@ var init_runtime_worker = __esm({
9242
9854
  }
9243
9855
  revoke() {
9244
9856
  this.lifetimeAbort.abort();
9245
- this.active.value?.finished.abort();
9857
+ for (const active of this.activeAttempts.values()) {
9858
+ active.finished.abort();
9859
+ }
9246
9860
  }
9247
9861
  status() {
9248
9862
  return this.processPool.status();
9249
9863
  }
9864
+ ownsMessage(message) {
9865
+ return this.activeAttemptForMessage(message).value !== void 0;
9866
+ }
9867
+ activeAttemptForMessage(message) {
9868
+ const threadId = appServerMessageThreadId(message).value;
9869
+ const turnId = appServerMessageTurnId(message).value;
9870
+ if (threadId === void 0 && turnId === void 0) {
9871
+ return {};
9872
+ }
9873
+ if (turnId !== void 0) {
9874
+ const exactTurnMatches = [...this.activeAttempts.values()].filter((active) => {
9875
+ if (active.finished.signal.aborted) {
9876
+ return false;
9877
+ }
9878
+ const generation = active.initialThreadName?.generation;
9879
+ const ownsTurn = active.nativeTurnId === turnId || generation?.turnId === turnId;
9880
+ return ownsTurn && (threadId === void 0 || activeOwnsThread(active, threadId));
9881
+ });
9882
+ if (exactTurnMatches.length > 0) {
9883
+ return singleActiveAttempt(exactTurnMatches);
9884
+ }
9885
+ }
9886
+ if (threadId === void 0) {
9887
+ return {};
9888
+ }
9889
+ const threadMatches = [...this.activeAttempts.values()].filter((active) => {
9890
+ if (active.finished.signal.aborted) {
9891
+ return false;
9892
+ }
9893
+ const generation = active.initialThreadName?.generation;
9894
+ const ownsVisibleThread = active.nativeThreadId === threadId;
9895
+ const ownsSubagentThread = active.subagentThreadIds.has(threadId);
9896
+ const ownsTitleThread = generation?.threadId === threadId;
9897
+ if (turnId === void 0) {
9898
+ return ownsVisibleThread || ownsSubagentThread || ownsTitleThread;
9899
+ }
9900
+ return ownsSubagentThread || ownsVisibleThread && active.nativeTurnId === void 0 || ownsTitleThread && generation?.turnId === void 0;
9901
+ });
9902
+ return singleActiveAttempt(threadMatches);
9903
+ }
9250
9904
  async onNotification(message) {
9251
- const active = this.active.value;
9905
+ const active = this.activeAttemptForMessage(message).value;
9252
9906
  if (active === void 0 || active.finished.signal.aborted) {
9253
9907
  return;
9254
9908
  }
@@ -9290,7 +9944,13 @@ var init_runtime_worker = __esm({
9290
9944
  initialThreadName.terminalObserved = true;
9291
9945
  }
9292
9946
  if (normalized.terminalStatus === LocalCodexTurnStatusWire.Interrupted) {
9293
- await this.stopInterruptedExecution(active, normalized);
9947
+ if (active.interruptedCleanupTask === void 0) {
9948
+ const task = this.stopInterruptedExecution(active, normalized).catch((error) => {
9949
+ this.signalFatal(active, error instanceof Error ? error : new Error(String(error)));
9950
+ });
9951
+ active.interruptedCleanupTask = task;
9952
+ void task;
9953
+ }
9294
9954
  return;
9295
9955
  }
9296
9956
  if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0 && !initialThreadName.completed) {
@@ -9317,46 +9977,113 @@ var init_runtime_worker = __esm({
9317
9977
  void this.enqueueEventFlush(active).catch(() => void 0);
9318
9978
  }
9319
9979
  async stopInterruptedExecution(active, normalized) {
9980
+ if (active.interruptedCleanupStarted) {
9981
+ return;
9982
+ }
9320
9983
  active.interruptedCleanupStarted = true;
9984
+ active.ignoreProcessLoss = true;
9321
9985
  active.initialThreadName?.generation?.resolve();
9322
- const client = this.processPool.currentClient().value;
9986
+ const client = active.appServerClient ?? this.processPool.currentClient().value;
9987
+ let cleanupFailed = false;
9323
9988
  if (client !== void 0 && active.nativeThreadId !== void 0) {
9324
- await Promise.all([active.nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
9325
- try {
9326
- await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
9327
- } catch (error) {
9328
- await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; stopping its App Server process tree`, error);
9329
- }
9330
- }));
9989
+ cleanupFailed = !await this.cleanBackgroundTerminals(active, client, "interrupted");
9331
9990
  }
9332
- try {
9333
- await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9334
- } catch (error) {
9335
- const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
9336
- await this.enqueueSpool(active, async () => {
9337
- const terminal = await active.durable.appendEvent("turn_failed", {
9338
- message: failure.message,
9339
- status: "runtime_lost"
9340
- }, {
9341
- nativeThreadId: active.nativeThreadId,
9342
- nativeTurnId: active.nativeTurnId
9991
+ const quarantineProcess = cleanupFailed || !this.processPool.hasOtherActiveExecution();
9992
+ if (quarantineProcess) {
9993
+ active.processQuarantined = true;
9994
+ try {
9995
+ if (client === void 0) {
9996
+ await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9997
+ } else {
9998
+ await this.processPool.quarantineProcess(client, active.processTreeCapture);
9999
+ }
10000
+ } catch (error) {
10001
+ const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
10002
+ await this.enqueueSpool(active, async () => {
10003
+ const terminal = await active.durable.appendEvent("turn_failed", {
10004
+ message: failure.message,
10005
+ status: "runtime_lost"
10006
+ }, {
10007
+ nativeThreadId: active.nativeThreadId,
10008
+ nativeTurnId: active.nativeTurnId
10009
+ });
10010
+ const result = {
10011
+ errorCode: "runtime_lost",
10012
+ errorMessage: failure.message,
10013
+ finalSequence: terminal.sequence,
10014
+ status: LocalCodexTurnStatusWire.RuntimeLost
10015
+ };
10016
+ await active.durable.markTerminal(result);
10017
+ this.settleTerminal(active, result);
9343
10018
  });
9344
- const result = {
9345
- errorCode: "runtime_lost",
9346
- errorMessage: failure.message,
9347
- finalSequence: terminal.sequence,
9348
- status: LocalCodexTurnStatusWire.RuntimeLost
9349
- };
9350
- await active.durable.markTerminal(result);
9351
- this.settleTerminal(active, result);
9352
- });
9353
- return;
10019
+ return;
10020
+ }
9354
10021
  }
9355
10022
  this.completeInitialThreadName(active);
9356
10023
  this.persistNormalizedNotification(active, normalized);
9357
10024
  }
10025
+ async cleanBackgroundTerminals(active, client, cleanupReason) {
10026
+ const nativeThreadId = active.nativeThreadId;
10027
+ if (nativeThreadId === void 0) {
10028
+ return false;
10029
+ }
10030
+ let cleanupSucceeded = true;
10031
+ await Promise.all([nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
10032
+ try {
10033
+ await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
10034
+ } catch (error) {
10035
+ cleanupSucceeded = false;
10036
+ await this.logger.error(`Failed to clean background terminals for ${cleanupReason} Local Codex thread ${threadId}; the shared App Server is no longer trusted`, error);
10037
+ }
10038
+ }));
10039
+ return cleanupSucceeded;
10040
+ }
10041
+ async stopExecutionAfterLeaseLoss(active) {
10042
+ active.interruptedCleanupStarted = true;
10043
+ this.completeInitialThreadName(active);
10044
+ if (!active.acceptedByAppServer && !active.turnStartPending) {
10045
+ return;
10046
+ }
10047
+ const client = active.appServerClient;
10048
+ const nativeThreadId = active.nativeThreadId;
10049
+ const nativeTurnId = active.nativeTurnId;
10050
+ const targetedCleanupPossible = active.acceptedByAppServer && client !== void 0 && !client.isClosed() && nativeThreadId !== void 0 && nativeTurnId !== void 0;
10051
+ let targetedCleanupSucceeded = targetedCleanupPossible;
10052
+ if (!targetedCleanupPossible) {
10053
+ const stateReason = active.turnStartPending ? "turn/start has no trusted result yet" : "the accepted native Turn or App Server client is unavailable";
10054
+ await this.logger.error(`Cannot target Local Codex attempt ${active.claim.attemptId} after its lease was lost; quarantining the untrusted App Server generation`, new AppServerProtocolError(stateReason));
10055
+ }
10056
+ if (targetedCleanupSucceeded && client !== void 0 && nativeThreadId !== void 0 && nativeTurnId !== void 0) {
10057
+ try {
10058
+ await client.requestWithin("turn/interrupt", {
10059
+ threadId: nativeThreadId,
10060
+ turnId: nativeTurnId
10061
+ }, interruptedExecutionCleanupTimeoutMilliseconds);
10062
+ this.processPool.retireTurn(nativeTurnId);
10063
+ } catch (error) {
10064
+ targetedCleanupSucceeded = false;
10065
+ await this.logger.error(`Failed to interrupt Local Codex turn ${nativeTurnId} after its lease was lost; the shared App Server is no longer trusted`, error);
10066
+ }
10067
+ const terminalsCleaned = await this.cleanBackgroundTerminals(active, client, "lease-lost");
10068
+ targetedCleanupSucceeded = targetedCleanupSucceeded && terminalsCleaned;
10069
+ }
10070
+ if (targetedCleanupSucceeded) {
10071
+ return;
10072
+ }
10073
+ active.ignoreProcessLoss = true;
10074
+ active.processQuarantined = true;
10075
+ try {
10076
+ if (client === void 0) {
10077
+ await this.processPool.quarantineCurrentProcess();
10078
+ } else {
10079
+ await this.processPool.quarantineProcess(client);
10080
+ }
10081
+ } catch (error) {
10082
+ await this.logger.error(`Failed to quarantine the Codex App Server after Local Codex attempt ${active.claim.attemptId} lost its lease and targeted cleanup failed`, error);
10083
+ }
10084
+ }
9358
10085
  async onServerRequest(message) {
9359
- const active = this.active.value;
10086
+ const active = this.activeAttemptForMessage(message).value;
9360
10087
  const client = this.processPool.currentClient().value;
9361
10088
  const requestId = rpcIdentifier2(message.id).value;
9362
10089
  if (active === void 0 || client === void 0 || requestId === void 0 || message.method === void 0) {
@@ -9398,46 +10125,50 @@ var init_runtime_worker = __esm({
9398
10125
  await this.enqueueEventFlush(active);
9399
10126
  }
9400
10127
  async onProcessExit(error) {
9401
- const active = this.active.value;
9402
- if (active === void 0 || !active.acceptedByAppServer) {
9403
- return;
9404
- }
9405
- active.initialThreadName?.generation?.resolve();
9406
- await this.enqueueSpool(active, async () => {
9407
- await active.durable.appendEvent("runtime_error", { message: error.message }, {
9408
- nativeThreadId: active.nativeThreadId,
9409
- nativeTurnId: active.nativeTurnId
9410
- });
9411
- const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
9412
- nativeThreadId: active.nativeThreadId,
9413
- nativeTurnId: active.nativeTurnId
10128
+ await Promise.all([...this.activeAttempts.values()].filter((active) => active.acceptedByAppServer && !active.finished.signal.aborted && !active.ignoreProcessLoss && active.terminalValue === void 0).map(async (active) => {
10129
+ active.initialThreadName?.generation?.resolve();
10130
+ await this.enqueueSpool(active, async () => {
10131
+ await active.durable.appendEvent("runtime_error", { message: error.message }, {
10132
+ nativeThreadId: active.nativeThreadId,
10133
+ nativeTurnId: active.nativeTurnId
10134
+ });
10135
+ const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
10136
+ nativeThreadId: active.nativeThreadId,
10137
+ nativeTurnId: active.nativeTurnId
10138
+ });
10139
+ const result = {
10140
+ errorCode: "runtime_lost",
10141
+ errorMessage: error.message,
10142
+ finalSequence: terminal.sequence,
10143
+ status: LocalCodexTurnStatusWire.RuntimeLost
10144
+ };
10145
+ await active.durable.markTerminal(result);
10146
+ this.settleTerminal(active, result);
9414
10147
  });
9415
- const result = {
9416
- errorCode: "runtime_lost",
9417
- errorMessage: error.message,
9418
- finalSequence: terminal.sequence,
9419
- status: LocalCodexTurnStatusWire.RuntimeLost
9420
- };
9421
- await active.durable.markTerminal(result);
9422
- this.settleTerminal(active, result);
9423
- });
10148
+ }));
9424
10149
  }
9425
10150
  async runLoops() {
9426
10151
  try {
9427
10152
  await Promise.all([
9428
10153
  this.runHeartbeatLoop(),
9429
- this.runClaimLoop(),
9430
10154
  this.runDiscoveryLoop(),
9431
- this.runRecoveryLoop()
10155
+ this.runAttemptLoops()
9432
10156
  ]);
9433
10157
  } finally {
9434
- this.active.value?.finished.abort();
10158
+ for (const active of this.activeAttempts.values()) {
10159
+ active.finished.abort();
10160
+ }
10161
+ await Promise.all(this.executionTasks.values());
9435
10162
  this.unregisterRoute();
9436
10163
  }
9437
10164
  }
10165
+ async runAttemptLoops() {
10166
+ await this.scanPersistedAttempts();
10167
+ await Promise.all([this.runClaimLoop(), this.runRecoveryLoop()]);
10168
+ }
9438
10169
  async runHeartbeatLoop() {
9439
10170
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9440
- if (this.active.value?.interruptedCleanupStarted) {
10171
+ if ([...this.activeAttempts.values()].some((active) => active.interruptedCleanupStarted)) {
9441
10172
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9442
10173
  continue;
9443
10174
  }
@@ -9446,23 +10177,27 @@ var init_runtime_worker = __esm({
9446
10177
  const response = await this.sendHeartbeat();
9447
10178
  this.applyHeartbeatResponse(response);
9448
10179
  } catch (error) {
9449
- if (!this.lifetimeAbort.signal.aborted) {
9450
- await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
10180
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10181
+ return;
9451
10182
  }
10183
+ await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
9452
10184
  }
9453
10185
  await waitForAbort(this.lifetimeAbort.signal, heartbeatIntervalMilliseconds);
9454
10186
  }
9455
10187
  }
9456
10188
  async runClaimLoop() {
10189
+ const retryBackoff = this.createNetworkRetryBackoff();
9457
10190
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9458
10191
  if (!this.configured || !this.enabled || !this.runtimeReady()) {
9459
10192
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9460
10193
  continue;
9461
10194
  }
9462
- if (!this.processPool.tryAcquire(this.connection.connectionId)) {
10195
+ const slot = this.processPool.tryAcquireExecutionSlot(this.connection.connectionId).value;
10196
+ if (slot === void 0) {
9463
10197
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9464
10198
  continue;
9465
10199
  }
10200
+ let executionScheduled = false;
9466
10201
  try {
9467
10202
  const capability = this.processPool.status();
9468
10203
  const response = await this.relay.claimCodexRuntime({
@@ -9473,22 +10208,46 @@ var init_runtime_worker = __esm({
9473
10208
  waitSeconds: claimWaitSeconds
9474
10209
  }, this.lifetimeAbort.signal);
9475
10210
  if (response.attempt === void 0) {
9476
- this.processPool.release(this.connection.connectionId);
10211
+ retryBackoff.reset();
9477
10212
  continue;
9478
10213
  }
9479
- await this.executeAttempt(response.attempt);
10214
+ const reclaimableClaimWindow = this.scheduleExecution(slot, response.attempt);
10215
+ executionScheduled = true;
10216
+ await reclaimableClaimWindow.completion;
10217
+ if (reclaimableClaimWindow.isAccepted()) {
10218
+ retryBackoff.reset();
10219
+ } else {
10220
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10221
+ }
9480
10222
  } catch (error) {
9481
- if (!this.lifetimeAbort.signal.aborted) {
9482
- await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
9483
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10223
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10224
+ return;
9484
10225
  }
10226
+ await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
10227
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
9485
10228
  } finally {
9486
- this.active = {};
9487
- this.processPool.release(this.connection.connectionId);
10229
+ if (!executionScheduled) {
10230
+ this.processPool.releaseExecutionSlot(slot);
10231
+ }
9488
10232
  }
9489
10233
  }
9490
10234
  }
10235
+ scheduleExecution(slot, claim) {
10236
+ if (this.executionTasks.has(claim.attemptId)) {
10237
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already executing`);
10238
+ }
10239
+ this.processPool.markExecutionStarted(slot);
10240
+ const reclaimableClaimWindow = createReclaimableClaimWindow();
10241
+ const task = this.executeAttempt(claim, reclaimableClaimWindow).catch(async (error) => await this.logger.error(`Local Codex attempt ${claim.attemptId} execution crashed`, error).catch(() => void 0)).finally(() => {
10242
+ reclaimableClaimWindow.close();
10243
+ this.executionTasks.delete(claim.attemptId);
10244
+ this.processPool.releaseExecutionSlot(slot);
10245
+ });
10246
+ this.executionTasks.set(claim.attemptId, task);
10247
+ return reclaimableClaimWindow;
10248
+ }
9491
10249
  async runDiscoveryLoop() {
10250
+ const retryBackoff = this.createNetworkRetryBackoff();
9492
10251
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9493
10252
  try {
9494
10253
  const response = await this.relay.claimCodexRuntimeDiscovery({
@@ -9497,14 +10256,17 @@ var init_runtime_worker = __esm({
9497
10256
  waitSeconds: discoveryWaitSeconds
9498
10257
  }, this.lifetimeAbort.signal);
9499
10258
  if (response.request === void 0) {
10259
+ retryBackoff.reset();
9500
10260
  continue;
9501
10261
  }
9502
10262
  await this.completeDiscovery(response.request);
10263
+ retryBackoff.reset();
9503
10264
  } catch (error) {
9504
- if (!this.lifetimeAbort.signal.aborted) {
9505
- await this.logger.error(`Local Codex discovery loop failed for connection ${this.connection.connectionId}`, error);
9506
- await waitForAbort(this.lifetimeAbort.signal, discoveryRetryMilliseconds);
10265
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10266
+ return;
9507
10267
  }
10268
+ await this.logger.error(`Local Codex discovery loop failed for connection ${this.connection.connectionId}`, error);
10269
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
9508
10270
  }
9509
10271
  }
9510
10272
  }
@@ -9520,7 +10282,7 @@ var init_runtime_worker = __esm({
9520
10282
  status: LocalCodexDiscoveryStatusWire.Failed
9521
10283
  };
9522
10284
  }
9523
- const completion = await this.relay.completeCodexRuntimeDiscovery(request2.requestId, this.connectorInstanceId, result);
10285
+ const completion = await this.relay.completeCodexRuntimeDiscovery(request2.requestId, this.connectorInstanceId, result, this.lifetimeAbort.signal);
9524
10286
  if (!completion.accepted) {
9525
10287
  await this.logger.info(`Local Codex discovery request ${request2.requestId} expired before completion`);
9526
10288
  }
@@ -9587,15 +10349,29 @@ var init_runtime_worker = __esm({
9587
10349
  truncated: eligibleDirectories.length > maximumDiscoveryDirectories
9588
10350
  };
9589
10351
  }
9590
- async executeAttempt(claim) {
10352
+ async executeAttempt(claim, reclaimableClaimWindow) {
9591
10353
  const durable = await DurableLocalCodexAttempt.create(this.store, this.connection.connectionId, this.connectorInstanceId, claim);
10354
+ if (durable.requiresRecovery()) {
10355
+ await this.recoverPersistedAttempt(durable.snapshot());
10356
+ reclaimableClaimWindow.accept();
10357
+ return;
10358
+ }
9592
10359
  const active = createActiveAttempt(claim, durable, this.connection.rootPath);
9593
- this.active = { value: active };
10360
+ if (this.activeAttempts.has(claim.attemptId)) {
10361
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already active`);
10362
+ }
10363
+ this.activeAttempts.set(claim.attemptId, active);
9594
10364
  const leaseLoop = this.runLeaseLoop(active);
9595
10365
  const controlLoop = this.runControlLoop(active);
9596
10366
  try {
9597
10367
  active.workingDirectory = await resolveCanonicalWorkingDirectory(this.connection.rootPath, claim.relativeWorkingDirectory);
10368
+ if (active.fatalError !== void 0) {
10369
+ throw active.fatalError;
10370
+ }
9598
10371
  let client = await this.processPool.ensureStarted();
10372
+ if (active.fatalError !== void 0) {
10373
+ throw active.fatalError;
10374
+ }
9599
10375
  const isNewThread = active.nativeThreadId === void 0;
9600
10376
  let nativeThreadId;
9601
10377
  try {
@@ -9609,6 +10385,10 @@ var init_runtime_worker = __esm({
9609
10385
  nativeThreadId = await this.prepareThread(client, active);
9610
10386
  }
9611
10387
  active.nativeThreadId = nativeThreadId;
10388
+ active.appServerClient = client;
10389
+ if (active.fatalError !== void 0) {
10390
+ throw active.fatalError;
10391
+ }
9612
10392
  await durable.markThreadPrepared(nativeThreadId);
9613
10393
  await active.spoolQueue;
9614
10394
  if (isNewThread) {
@@ -9620,7 +10400,11 @@ var init_runtime_worker = __esm({
9620
10400
  if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
9621
10401
  await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
9622
10402
  }
10403
+ if (active.fatalError !== void 0) {
10404
+ throw active.fatalError;
10405
+ }
9623
10406
  let response;
10407
+ active.turnStartPending = true;
9624
10408
  try {
9625
10409
  response = await client.request("turn/start", {
9626
10410
  approvalPolicy: claim.approvalPolicy,
@@ -9637,6 +10421,8 @@ var init_runtime_worker = __esm({
9637
10421
  throw new UnknownTurnStartResultError("Codex App Server turn/start result is unknown; the process generation was quarantined", { cause: error });
9638
10422
  }
9639
10423
  throw error;
10424
+ } finally {
10425
+ active.turnStartPending = false;
9640
10426
  }
9641
10427
  const nativeTurnId = requireTurnId(response);
9642
10428
  if (active.nativeTurnId !== void 0 && active.nativeTurnId !== nativeTurnId) {
@@ -9662,12 +10448,14 @@ var init_runtime_worker = __esm({
9662
10448
  nativeTurnId,
9663
10449
  status: LocalCodexTurnStatusWire.Running
9664
10450
  });
10451
+ reclaimableClaimWindow.accept();
9665
10452
  await this.interruptActiveTurnIfRequested(active, client);
9666
10453
  const terminal = await Promise.race([
9667
10454
  active.terminal,
9668
10455
  active.fatal.then((error) => {
9669
10456
  throw error;
9670
- })
10457
+ }),
10458
+ rejectWhenAborted(active.finished.signal)
9671
10459
  ]);
9672
10460
  await active.spoolQueue;
9673
10461
  await this.flushAllEvents(active);
@@ -9681,12 +10469,13 @@ var init_runtime_worker = __esm({
9681
10469
  });
9682
10470
  await durable.markUploaded();
9683
10471
  await this.store.deleteLocalCodexAttempt(claim.attemptId);
9684
- if (active.interruptedCleanupStarted) {
10472
+ if (active.processQuarantined) {
9685
10473
  active.finished.abort();
9686
10474
  await this.restoreAppServerAfterInterruption(active);
9687
10475
  }
9688
10476
  } catch (error) {
9689
- if (error instanceof LeaseLostError) {
10477
+ if (error instanceof WorkerStoppedError) {
10478
+ } else if (error instanceof LeaseLostError) {
9690
10479
  await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after losing its execution lease`, error);
9691
10480
  } else if (error instanceof SpoolPersistenceError) {
9692
10481
  try {
@@ -9701,17 +10490,23 @@ var init_runtime_worker = __esm({
9701
10490
  await this.failAttempt(active, error);
9702
10491
  }
9703
10492
  } finally {
9704
- this.completeInitialThreadName(active);
9705
- active.finished.abort();
9706
- await active.initialThreadName?.task;
9707
- const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9708
- if (titleGenerationTurnId !== void 0) {
9709
- this.processPool.retireTurn(titleGenerationTurnId);
9710
- }
9711
- if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
9712
- this.processPool.retireTurn(active.nativeTurnId);
10493
+ try {
10494
+ this.completeInitialThreadName(active);
10495
+ active.finished.abort();
10496
+ await active.interruptedCleanupTask;
10497
+ await active.leaseLossCleanupTask;
10498
+ await active.initialThreadName?.task;
10499
+ const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
10500
+ if (titleGenerationTurnId !== void 0) {
10501
+ this.processPool.retireTurn(titleGenerationTurnId);
10502
+ }
10503
+ if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
10504
+ this.processPool.retireTurn(active.nativeTurnId);
10505
+ }
10506
+ await Promise.all([leaseLoop, controlLoop]);
10507
+ } finally {
10508
+ this.activeAttempts.delete(claim.attemptId);
9713
10509
  }
9714
- await Promise.all([leaseLoop, controlLoop]);
9715
10510
  }
9716
10511
  }
9717
10512
  async prepareThread(client, active) {
@@ -9796,15 +10591,24 @@ var init_runtime_worker = __esm({
9796
10591
  }
9797
10592
  }
9798
10593
  async runRecoveryLoop() {
10594
+ const retryBackoff = this.createNetworkRetryBackoff();
9799
10595
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9800
- try {
9801
- await this.recoverPersistedAttempts();
9802
- } catch (error) {
9803
- if (!this.lifetimeAbort.signal.aborted) {
9804
- await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
9805
- }
10596
+ const scanSucceeded = await this.scanPersistedAttempts();
10597
+ if (scanSucceeded) {
10598
+ retryBackoff.reset();
9806
10599
  }
9807
- await waitForAbort(this.lifetimeAbort.signal, recoveryRetryMilliseconds);
10600
+ await waitForAbort(this.lifetimeAbort.signal, scanSucceeded ? recoveryScanIntervalMilliseconds : retryBackoff.nextDelayMilliseconds());
10601
+ }
10602
+ }
10603
+ async scanPersistedAttempts() {
10604
+ try {
10605
+ await this.recoverPersistedAttempts();
10606
+ return true;
10607
+ } catch (error) {
10608
+ if (!this.lifetimeAbort.signal.aborted) {
10609
+ await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
10610
+ }
10611
+ return false;
9808
10612
  }
9809
10613
  }
9810
10614
  async recoverPersistedAttempts() {
@@ -9816,10 +10620,12 @@ var init_runtime_worker = __esm({
9816
10620
  try {
9817
10621
  await this.recoverPersistedAttempt(persisted);
9818
10622
  } catch (error) {
9819
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10623
+ if (isPermanentRelayFailure(error)) {
9820
10624
  this.unrecoverableAttemptIds.add(persisted.claim.attemptId);
10625
+ await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10626
+ continue;
9821
10627
  }
9822
- await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10628
+ throw error;
9823
10629
  }
9824
10630
  }
9825
10631
  }
@@ -9875,13 +10681,15 @@ var init_runtime_worker = __esm({
9875
10681
  await this.store.deleteLocalCodexAttempt(snapshot.claim.attemptId);
9876
10682
  }
9877
10683
  async runLeaseLoop(active) {
10684
+ const retryBackoff = this.createNetworkRetryBackoff();
10685
+ let nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
9878
10686
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
9879
10687
  const remaining = active.leaseDeadlineMilliseconds - Date.now();
9880
10688
  if (remaining <= 0) {
9881
10689
  await this.loseLease(active, "Local Codex execution lease expired");
9882
10690
  return;
9883
10691
  }
9884
- await waitForAbort(active.finished.signal, Math.min(leaseRenewIntervalMilliseconds, remaining));
10692
+ await waitForAbort(active.finished.signal, Math.min(nextRenewalDelayMilliseconds, remaining));
9885
10693
  if (active.finished.signal.aborted) {
9886
10694
  return;
9887
10695
  }
@@ -9892,12 +10700,14 @@ var init_runtime_worker = __esm({
9892
10700
  try {
9893
10701
  const response = await this.renewLeaseBeforeDeadline(active);
9894
10702
  active.leaseDeadlineMilliseconds = parseLeaseDeadline(response.leaseExpiresAt);
10703
+ retryBackoff.reset();
10704
+ nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
9895
10705
  } catch (error) {
9896
10706
  if (active.finished.signal.aborted) {
9897
10707
  return;
9898
10708
  }
9899
10709
  await this.logger.error(`Failed to renew Local Codex attempt ${active.claim.attemptId}`, error);
9900
- if (error instanceof LeaseLostError || error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10710
+ if (error instanceof LeaseLostError || isPermanentRelayFailure(error)) {
9901
10711
  await this.loseLease(active, errorMessage3(error));
9902
10712
  return;
9903
10713
  }
@@ -9906,7 +10716,7 @@ var init_runtime_worker = __esm({
9906
10716
  await this.loseLease(active, "Local Codex execution lease expired");
9907
10717
  return;
9908
10718
  }
9909
- await waitForAbort(active.finished.signal, Math.min(leaseRenewRetryMilliseconds, retryRemaining));
10719
+ nextRenewalDelayMilliseconds = Math.min(retryBackoff.nextDelayMilliseconds(), retryRemaining);
9910
10720
  }
9911
10721
  }
9912
10722
  }
@@ -9936,11 +10746,19 @@ var init_runtime_worker = __esm({
9936
10746
  }
9937
10747
  }
9938
10748
  async loseLease(active, message) {
9939
- const error = new LeaseLostError(message);
9940
- this.signalFatal(active, error);
9941
- await this.processPool.quarantineCurrentProcess();
10749
+ if (active.leaseLossCleanupTask !== void 0) {
10750
+ await active.leaseLossCleanupTask;
10751
+ return;
10752
+ }
10753
+ const cleanupTask = Promise.resolve().then(async () => {
10754
+ await this.stopExecutionAfterLeaseLoss(active);
10755
+ });
10756
+ active.leaseLossCleanupTask = cleanupTask;
10757
+ this.signalFatal(active, new LeaseLostError(message));
10758
+ await cleanupTask;
9942
10759
  }
9943
10760
  async runControlLoop(active) {
10761
+ const retryBackoff = this.createNetworkRetryBackoff();
9944
10762
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
9945
10763
  try {
9946
10764
  const page = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
@@ -9948,14 +10766,15 @@ var init_runtime_worker = __esm({
9948
10766
  await this.applyControl(active, control);
9949
10767
  active.controlCursor = Math.max(active.controlCursor, control.cursor);
9950
10768
  }
10769
+ retryBackoff.reset();
9951
10770
  } catch (error) {
9952
10771
  if (!active.finished.signal.aborted) {
9953
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10772
+ if (isPermanentRelayFailure(error)) {
9954
10773
  await this.loseLease(active, errorMessage3(error));
9955
10774
  return;
9956
10775
  }
9957
10776
  await this.logger.error(`Failed to poll Local Codex controls for ${active.claim.attemptId}`, error);
9958
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10777
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
9959
10778
  }
9960
10779
  }
9961
10780
  }
@@ -9964,7 +10783,7 @@ var init_runtime_worker = __esm({
9964
10783
  await active.durable.recordControl(control.controlId);
9965
10784
  const previouslyApplied = active.durable.appliedControlOutcome(control.controlId).value;
9966
10785
  if (previouslyApplied !== void 0) {
9967
- await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, previouslyApplied);
10786
+ await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, previouslyApplied, active.finished.signal);
9968
10787
  return;
9969
10788
  }
9970
10789
  const client = this.processPool.currentClient().value;
@@ -9988,7 +10807,7 @@ var init_runtime_worker = __esm({
9988
10807
  outcome = await this.applySteerControl(active, control);
9989
10808
  }
9990
10809
  await active.durable.markControlApplied(control.controlId, outcome);
9991
- await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, outcome);
10810
+ await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, outcome, active.finished.signal);
9992
10811
  }
9993
10812
  async applySteerControl(active, control) {
9994
10813
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
@@ -10024,7 +10843,9 @@ var init_runtime_worker = __esm({
10024
10843
  if (!active.abortRequested || active.abortSent || active.nativeThreadId === void 0 || active.nativeTurnId === void 0) {
10025
10844
  return;
10026
10845
  }
10027
- active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10846
+ if (!this.processPool.hasOtherActiveExecution()) {
10847
+ active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10848
+ }
10028
10849
  await client.request("turn/interrupt", {
10029
10850
  threadId: active.nativeThreadId,
10030
10851
  turnId: active.nativeTurnId
@@ -10094,41 +10915,52 @@ var init_runtime_worker = __esm({
10094
10915
  }
10095
10916
  async flushAllEvents(active) {
10096
10917
  await active.eventUploadQueue.catch(() => void 0);
10918
+ const retryBackoff = this.createNetworkRetryBackoff();
10097
10919
  while (active.durable.pendingEvents().length > 0) {
10098
10920
  if (active.fatalError !== void 0) {
10099
10921
  throw active.fatalError;
10100
10922
  }
10101
10923
  try {
10102
10924
  await this.flushEvents(active);
10925
+ retryBackoff.reset();
10103
10926
  } catch (error) {
10104
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10927
+ if (isPermanentRelayFailure(error)) {
10105
10928
  throw error;
10106
10929
  }
10107
10930
  if (active.finished.signal.aborted || this.lifetimeAbort.signal.aborted) {
10108
10931
  throw error;
10109
10932
  }
10110
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10933
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
10111
10934
  }
10112
10935
  }
10113
10936
  }
10114
10937
  async retryStateUpdate(active, state) {
10938
+ const retryBackoff = this.createNetworkRetryBackoff();
10115
10939
  while (!this.lifetimeAbort.signal.aborted) {
10116
10940
  if (active.fatalError !== void 0) {
10117
10941
  throw active.fatalError;
10118
10942
  }
10119
10943
  try {
10120
10944
  await this.relay.updateCodexRuntimeState(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), state);
10945
+ retryBackoff.reset();
10121
10946
  return;
10122
10947
  } catch (error) {
10123
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10948
+ if (isPermanentRelayFailure(error)) {
10124
10949
  throw error;
10125
10950
  }
10126
10951
  await this.logger.error(`Failed to update Local Codex state for ${active.claim.attemptId}`, error);
10127
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10952
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10128
10953
  }
10129
10954
  }
10130
10955
  throw new Error("Local Codex Runtime stopped before state ACK");
10131
10956
  }
10957
+ createNetworkRetryBackoff() {
10958
+ return new RetryBackoff({
10959
+ maximumMilliseconds: maximumNetworkRetryMilliseconds,
10960
+ minimumMilliseconds: this.networkRetryMilliseconds,
10961
+ random: this.random
10962
+ });
10963
+ }
10132
10964
  settleTerminal(active, terminal) {
10133
10965
  if (active.terminalValue !== void 0) {
10134
10966
  return;
@@ -10196,7 +11028,7 @@ var init_runtime_worker = __esm({
10196
11028
  moxtCliVersion: moxt.version,
10197
11029
  protocolVersion: localCodexRuntimeProtocolVersion,
10198
11030
  ...unavailableReason === void 0 ? {} : { unavailableReason }
10199
- });
11031
+ }, this.lifetimeAbort.signal);
10200
11032
  }
10201
11033
  applyHeartbeatResponse(response) {
10202
11034
  this.configured = response.configured;
@@ -10388,7 +11220,6 @@ ${titleInput}`,
10388
11220
  if (!this.registered) {
10389
11221
  return;
10390
11222
  }
10391
- this.processPool.release(this.connection.connectionId);
10392
11223
  this.processPool.unregister(this.connection.connectionId);
10393
11224
  this.registered = false;
10394
11225
  }
@@ -10407,18 +11238,20 @@ function localCodexProcessPoolKey(environment, nativeStoreIdentitySeed) {
10407
11238
  "connector-owned-app-server-stdio-v1"
10408
11239
  ].join("\0")).digest("hex");
10409
11240
  }
10410
- var import_node_crypto8, LocalCodexProcessPool;
11241
+ var import_node_crypto8, maximumConcurrentTurns, LocalCodexProcessPool;
10411
11242
  var init_process_pool = __esm({
10412
11243
  "../machine-connector/dist/runtime/local-codex-runtime/process-pool.js"() {
10413
11244
  "use strict";
10414
11245
  init_cjs_shims();
10415
11246
  import_node_crypto8 = require("crypto");
10416
11247
  init_app_server_client();
11248
+ maximumConcurrentTurns = 1e3;
10417
11249
  LocalCodexProcessPool = class {
10418
11250
  poolKey;
10419
11251
  logger;
10420
- activeOwner = {};
11252
+ activeSlots = /* @__PURE__ */ new Map();
10421
11253
  loadedThreadIds = /* @__PURE__ */ new Set();
11254
+ nextSlotId = 1;
10422
11255
  routes = /* @__PURE__ */ new Map();
10423
11256
  retiredTurnIds = /* @__PURE__ */ new Set();
10424
11257
  supervisor;
@@ -10428,7 +11261,7 @@ var init_process_pool = __esm({
10428
11261
  this.logger = logger;
10429
11262
  this.supervisor = new LocalCodexAppServerSupervisor(environment.HOME ?? process.cwd(), environment, nativeStoreIdentitySeed, {
10430
11263
  onNotification: async (message) => {
10431
- await this.activeRoute().value?.onNotification(message);
11264
+ await this.routeNotification(message);
10432
11265
  },
10433
11266
  onProcessExit: async (error, processGeneration) => {
10434
11267
  if (!this.supervisor.markProcessLost(processGeneration)) {
@@ -10436,18 +11269,10 @@ var init_process_pool = __esm({
10436
11269
  }
10437
11270
  this.loadedThreadIds.clear();
10438
11271
  await this.logger.error(`Shared Codex App Server generation ${processGeneration} exited`, error);
10439
- await this.activeRoute().value?.onProcessExit(error);
11272
+ await this.broadcastProcessExit(error);
10440
11273
  },
10441
11274
  onServerRequest: async (message) => {
10442
- const route = this.activeRoute().value;
10443
- if (route !== void 0) {
10444
- await route.onServerRequest(message);
10445
- return;
10446
- }
10447
- const client = this.supervisor.currentClient().value;
10448
- if (client !== void 0 && message.id !== void 0) {
10449
- await client.respondWithError(message.id, -32e3, "No owning Local Codex Runtime turn");
10450
- }
11275
+ await this.routeServerRequest(message);
10451
11276
  },
10452
11277
  onStderr: async (text3) => {
10453
11278
  await this.logger.info("Codex App Server stderr", {
@@ -10465,7 +11290,7 @@ var init_process_pool = __esm({
10465
11290
  this.routes.set(ownerId, route);
10466
11291
  }
10467
11292
  unregister(ownerId) {
10468
- if (this.activeOwner.value === ownerId) {
11293
+ if ([...this.activeSlots.values()].some((slot) => slot.ownerId === ownerId)) {
10469
11294
  throw new Error(`Local Codex route ${ownerId} still owns capacity`);
10470
11295
  }
10471
11296
  this.routes.delete(ownerId);
@@ -10474,27 +11299,35 @@ var init_process_pool = __esm({
10474
11299
  this.waitingOwners.splice(index2, 1);
10475
11300
  }
10476
11301
  }
10477
- tryAcquire(ownerId) {
11302
+ tryAcquireExecutionSlot(ownerId) {
10478
11303
  if (!this.routes.has(ownerId)) {
10479
11304
  throw new Error(`Local Codex route ${ownerId} is not registered`);
10480
11305
  }
10481
- if (this.activeOwner.value === ownerId) {
10482
- return true;
10483
- }
10484
11306
  if (!this.waitingOwners.includes(ownerId)) {
10485
11307
  this.waitingOwners.push(ownerId);
10486
11308
  }
10487
- if (this.activeOwner.value !== void 0 || this.waitingOwners[0] !== ownerId) {
10488
- return false;
11309
+ if (this.activeSlots.size >= maximumConcurrentTurns || this.waitingOwners[0] !== ownerId) {
11310
+ return {};
10489
11311
  }
10490
11312
  this.waitingOwners.shift();
10491
- this.activeOwner = { value: ownerId };
10492
- return true;
11313
+ const value = { ownerId, slotId: this.nextSlotId };
11314
+ this.nextSlotId += 1;
11315
+ this.activeSlots.set(value.slotId, { executing: false, ownerId });
11316
+ return { value };
10493
11317
  }
10494
- release(ownerId) {
10495
- if (this.activeOwner.value === ownerId) {
10496
- this.activeOwner = {};
11318
+ markExecutionStarted(slot) {
11319
+ const active = this.requireActiveSlot(slot);
11320
+ if (active.executing) {
11321
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is already executing`);
10497
11322
  }
11323
+ active.executing = true;
11324
+ }
11325
+ releaseExecutionSlot(slot) {
11326
+ this.requireActiveSlot(slot);
11327
+ this.activeSlots.delete(slot.slotId);
11328
+ }
11329
+ hasOtherActiveExecution() {
11330
+ return [...this.activeSlots.values()].filter((slot) => slot.executing).length > 1;
10498
11331
  }
10499
11332
  retireTurn(nativeTurnId) {
10500
11333
  this.retiredTurnIds.add(nativeTurnId);
@@ -10539,29 +11372,87 @@ var init_process_pool = __esm({
10539
11372
  return client === void 0 ? {} : { value: await client.captureProcessTree() };
10540
11373
  }
10541
11374
  async quarantineCurrentProcess(capture) {
11375
+ const processGeneration = this.supervisor.currentClient().value?.processGeneration;
10542
11376
  this.loadedThreadIds.clear();
10543
- await this.supervisor.quarantineCurrentProcess(capture);
11377
+ try {
11378
+ await this.supervisor.quarantineCurrentProcess(capture);
11379
+ } finally {
11380
+ if (processGeneration !== void 0) {
11381
+ await this.broadcastProcessExit(new AppServerProcessLostError(`Shared Codex App Server generation ${processGeneration} was quarantined`));
11382
+ }
11383
+ }
11384
+ }
11385
+ async quarantineProcess(client, capture) {
11386
+ if (this.supervisor.currentClient().value === client) {
11387
+ await this.quarantineCurrentProcess(capture);
11388
+ return;
11389
+ }
11390
+ await client.stop(capture);
10544
11391
  }
10545
11392
  async stop() {
10546
11393
  this.loadedThreadIds.clear();
10547
11394
  await this.supervisor.stop();
10548
11395
  }
10549
- activeRoute() {
10550
- const owner = this.activeOwner.value;
10551
- if (owner === void 0) {
10552
- return {};
11396
+ matchingRoutes(message) {
11397
+ return [...this.routes.values()].filter((route) => route.ownsMessage(message));
11398
+ }
11399
+ async routeNotification(message) {
11400
+ const routes = this.matchingRoutes(message);
11401
+ if (routes.length === 0) {
11402
+ return;
11403
+ }
11404
+ if (routes.length > 1) {
11405
+ await this.logger.error("Local Codex App Server notification matched multiple runtime routes", new Error(message.method ?? "Unknown App Server notification"));
11406
+ return;
11407
+ }
11408
+ const route = routes[0];
11409
+ if (route === void 0) {
11410
+ throw new Error("Expected one Local Codex notification route");
11411
+ }
11412
+ await route.onNotification(message);
11413
+ }
11414
+ async routeServerRequest(message) {
11415
+ const routes = this.matchingRoutes(message);
11416
+ if (routes.length === 1) {
11417
+ const route = routes[0];
11418
+ if (route === void 0) {
11419
+ throw new Error("Expected one Local Codex request route");
11420
+ }
11421
+ await route.onServerRequest(message);
11422
+ return;
11423
+ }
11424
+ if (routes.length > 1) {
11425
+ await this.logger.error("Local Codex App Server request matched multiple runtime routes", new Error(message.method ?? "Unknown App Server request"));
11426
+ }
11427
+ const client = this.supervisor.currentClient().value;
11428
+ if (client !== void 0 && message.id !== void 0) {
11429
+ await client.respondWithError(message.id, -32e3, routes.length === 0 ? "No owning Local Codex Runtime turn" : "Ambiguous Local Codex Runtime turn ownership");
11430
+ }
11431
+ }
11432
+ async broadcastProcessExit(error) {
11433
+ await Promise.all([...this.routes.values()].map(async (route) => {
11434
+ try {
11435
+ await route.onProcessExit(error);
11436
+ } catch (routeError) {
11437
+ await this.logger.error("Failed to settle a Local Codex route after the shared App Server exited", routeError).catch(() => void 0);
11438
+ }
11439
+ }));
11440
+ }
11441
+ requireActiveSlot(slot) {
11442
+ const active = this.activeSlots.get(slot.slotId);
11443
+ if (active === void 0) {
11444
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is not active`);
10553
11445
  }
10554
- const value = this.routes.get(owner);
10555
- return value === void 0 ? {} : { value };
11446
+ if (active.ownerId !== slot.ownerId) {
11447
+ throw new Error(`Local Codex capacity slot ${slot.slotId} belongs to another route`);
11448
+ }
11449
+ return active;
10556
11450
  }
10557
11451
  };
10558
11452
  }
10559
11453
  });
10560
11454
 
10561
11455
  // ../machine-connector/dist/runtime/daemon.js
10562
- function isPermanentRelayFailure(error) {
10563
- return error instanceof MachineConnectionRevokedError || error instanceof RelayHttpError && (error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404 || error.status === 409 || error.status === 410);
10564
- }
10565
11456
  async function withDeadline(operation, deadline) {
10566
11457
  if (deadline === void 0) {
10567
11458
  return await operation;
@@ -10582,7 +11473,7 @@ function delay4(milliseconds) {
10582
11473
  setTimeout(resolvePromise, milliseconds);
10583
11474
  });
10584
11475
  }
10585
- var import_node_os8, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
11476
+ var import_node_os8, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds2, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
10586
11477
  var init_daemon = __esm({
10587
11478
  "../machine-connector/dist/runtime/daemon.js"() {
10588
11479
  "use strict";
@@ -10603,6 +11494,7 @@ var init_daemon = __esm({
10603
11494
  init_process_executor();
10604
11495
  init_shell_environment();
10605
11496
  init_relay_client();
11497
+ init_retry_backoff();
10606
11498
  init_runtime_logger();
10607
11499
  init_runtime_types();
10608
11500
  init_store();
@@ -10616,7 +11508,7 @@ var init_daemon = __esm({
10616
11508
  commandOutputFlushIntervalMilliseconds = 250;
10617
11509
  agentOutputLimitBytes = 2e6;
10618
11510
  defaultLeaseSeconds = 90;
10619
- defaultNetworkRetryMilliseconds = 2e3;
11511
+ defaultNetworkRetryMilliseconds2 = 2e3;
10620
11512
  defaultLeaseSafetyMarginMilliseconds = 1e4;
10621
11513
  defaultTerminalForegroundBudgetMilliseconds = 5e3;
10622
11514
  maximumEventUploadRetryMilliseconds = 6e4;
@@ -10668,7 +11560,7 @@ var init_daemon = __esm({
10668
11560
  this.shellEnvironmentManager = options.shellEnvironmentManager ?? new ShellEnvironmentManager();
10669
11561
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
10670
11562
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
10671
- this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
11563
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds2;
10672
11564
  this.random = options.random ?? Math.random;
10673
11565
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
10674
11566
  }
@@ -10811,7 +11703,10 @@ var init_daemon = __esm({
10811
11703
  ]);
10812
11704
  }
10813
11705
  async runLocalCodexRuntime(connection, relay) {
10814
- const worker = new LocalCodexRuntimeConnectionWorker(connection, relay, this.store, this.localCodexProcessPool(connection.machineId), this.shellEnvironmentManager.snapshot(), this.connectorInstanceId, this.logger);
11706
+ const worker = new LocalCodexRuntimeConnectionWorker(connection, relay, this.store, this.localCodexProcessPool(connection.machineId), this.shellEnvironmentManager.snapshot(), this.connectorInstanceId, this.logger, {
11707
+ networkRetryMilliseconds: this.networkRetryMilliseconds,
11708
+ random: this.random
11709
+ });
10815
11710
  this.localCodexWorkers.set(connection.connectionId, worker);
10816
11711
  if (this.stopping) {
10817
11712
  await worker.stop();
@@ -10841,9 +11736,11 @@ var init_daemon = __esm({
10841
11736
  return existing;
10842
11737
  }
10843
11738
  const relay = new MachineRelayClient(connection, this.store, {
11739
+ minimumRetryMilliseconds: this.networkRetryMilliseconds,
10844
11740
  onConnectionRevoked: async (error) => {
10845
11741
  await this.handleConnectionRevoked(connection, error);
10846
- }
11742
+ },
11743
+ random: this.random
10847
11744
  });
10848
11745
  this.relayClients.set(connection.connectionId, relay);
10849
11746
  return relay;
@@ -10873,7 +11770,7 @@ var init_daemon = __esm({
10873
11770
  protocolVersion: machineProtocolVersion
10874
11771
  });
10875
11772
  } catch (error) {
10876
- if (relay.isRevoked()) {
11773
+ if (this.stopping || relay.isRevoked()) {
10877
11774
  return;
10878
11775
  }
10879
11776
  await this.logger.error(`Heartbeat failed for connection ${connection.connectionId}`, error);
@@ -10882,6 +11779,7 @@ var init_daemon = __esm({
10882
11779
  }
10883
11780
  }
10884
11781
  async runClaimLoop(connection, relay) {
11782
+ const retryBackoff = this.createNetworkRetryBackoff();
10885
11783
  while (!this.stopping && !relay.isRevoked()) {
10886
11784
  try {
10887
11785
  const response = await relay.claim({
@@ -10897,17 +11795,19 @@ var init_daemon = __esm({
10897
11795
  }
10898
11796
  this.startClaimExecution(activeJob);
10899
11797
  }
11798
+ retryBackoff.reset();
10900
11799
  } catch (error) {
10901
- if (relay.isRevoked()) {
11800
+ if (this.stopping || relay.isRevoked()) {
10902
11801
  return;
10903
11802
  }
10904
11803
  await this.logger.error(`Job claim failed for connection ${connection.connectionId}`, error);
10905
- await this.waitUntilStop(this.networkRetryMilliseconds);
11804
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
10906
11805
  }
10907
11806
  }
10908
11807
  }
10909
11808
  async runControlLoop(connection, relay) {
10910
11809
  let cursor = 0;
11810
+ const retryBackoff = this.createNetworkRetryBackoff();
10911
11811
  while (!this.stopping && !relay.isRevoked()) {
10912
11812
  try {
10913
11813
  const response = await relay.pollControls({
@@ -10922,12 +11822,13 @@ var init_daemon = __esm({
10922
11822
  if (response.commands.length === 0) {
10923
11823
  cursor = response.nextCursor;
10924
11824
  }
11825
+ retryBackoff.reset();
10925
11826
  } catch (error) {
10926
- if (relay.isRevoked()) {
11827
+ if (this.stopping || relay.isRevoked()) {
10927
11828
  return;
10928
11829
  }
10929
11830
  await this.logger.error(`Control poll failed for connection ${connection.connectionId}`, error);
10930
- await this.waitUntilStop(this.networkRetryMilliseconds);
11831
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
10931
11832
  }
10932
11833
  }
10933
11834
  }
@@ -11415,6 +12316,13 @@ var init_daemon = __esm({
11415
12316
  await delay4(Math.min(250, deadline - Date.now()));
11416
12317
  }
11417
12318
  }
12319
+ createNetworkRetryBackoff() {
12320
+ return new RetryBackoff({
12321
+ maximumMilliseconds: maximumTerminalRetryMilliseconds,
12322
+ minimumMilliseconds: this.networkRetryMilliseconds,
12323
+ random: this.random
12324
+ });
12325
+ }
11418
12326
  cancellationResult(activeJob) {
11419
12327
  const reason = activeJob.cancellation.currentReason();
11420
12328
  if (reason === ExecutionCancellationReason.LeaseLost) {
@@ -14149,6 +15057,8 @@ __export(dist_exports, {
14149
15057
  executeClaudeReply: () => executeClaudeReply,
14150
15058
  executeClaudeStart: () => executeClaudeStart,
14151
15059
  installUserService: () => installUserService,
15060
+ isPermanentRelayFailure: () => isPermanentRelayFailure,
15061
+ isRetryableRelayFailure: () => isRetryableRelayFailure,
14152
15062
  isTerminalJobStatus: () => isTerminalJobStatus,
14153
15063
  localCodexRuntimeEventsRequestBytes: () => localCodexRuntimeEventsRequestBytes,
14154
15064
  localMachineJobTargetRelationship: () => localMachineJobTargetRelationship,
@@ -14374,7 +15284,7 @@ function getApiKeyOrUndefined() {
14374
15284
 
14375
15285
  // src/utils/http.ts
14376
15286
  function getUserAgent() {
14377
- return `moxt-cli/${"0.10.0"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
15287
+ return `moxt-cli/${"0.11.0-beta.1"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
14378
15288
  }
14379
15289
  async function sendRequest(method, path4, init) {
14380
15290
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -27704,6 +28614,14 @@ var import_node_util6 = require("util");
27704
28614
  var MAX_DESC_LENGTH = 5e3;
27705
28615
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
27706
28616
  var MAX_COMMENT_CONTENT_BYTES = MAX_COMMENT_CONTENT_LENGTH * 4;
28617
+ function addTeammateAttributionOption(command) {
28618
+ return command.option("--as-teammate <teammateId>", "Attribute this Workflow write to a managed AI teammate");
28619
+ }
28620
+ function addTeammateAttribution(body, options) {
28621
+ const asTeammateId = parseOptionalPositiveInteger(options.asTeammate, "--as-teammate");
28622
+ if (asTeammateId !== void 0) body.asTeammateId = asTeammateId;
28623
+ return body;
28624
+ }
27707
28625
  var WorkflowOptionsError = class extends Error {
27708
28626
  constructor(message) {
27709
28627
  super(message);
@@ -27735,6 +28653,9 @@ function addPreferredAssigneeOptions(command) {
27735
28653
  }
27736
28654
  function parsePositiveInteger(raw, label) {
27737
28655
  const parsed = Number.parseInt(raw, 10);
28656
+ if (Number.isInteger(parsed) && !Number.isSafeInteger(parsed)) {
28657
+ throw new WorkflowOptionsError(`Error: ${label} must be a safe positive integer, got "${raw}".`);
28658
+ }
27738
28659
  if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
27739
28660
  throw new WorkflowOptionsError(`Error: ${label} must be a positive integer, got "${raw}".`);
27740
28661
  }
@@ -27775,13 +28696,32 @@ function parseWorkflowScope(raw) {
27775
28696
  }
27776
28697
  function parseTaskScope(raw) {
27777
28698
  if (raw == null || raw === "") return "all";
27778
- if (raw === "all" || raw === "assigned_to_me" || raw === "subscribed_by_me" || raw === "owner_is_me") {
27779
- return raw;
28699
+ if (raw === "all" || raw === "assigned_to_me" || raw === "reported_by_me") return raw;
28700
+ throw new WorkflowOptionsError(
28701
+ 'Error: --scope must be "all", "assigned_to_me", or "reported_by_me".'
28702
+ );
28703
+ }
28704
+ function parseStatusTypeFilter(raw) {
28705
+ if (raw == null || raw === "") return void 0;
28706
+ if (raw === "todo") return 1;
28707
+ if (raw === "in-progress") return 2;
28708
+ if (raw === "done") return 3;
28709
+ throw new WorkflowOptionsError('Error: --status-type must be "todo", "in-progress", or "done".');
28710
+ }
28711
+ function parseTaskSortField(raw) {
28712
+ const value = raw ?? "default";
28713
+ if (value === "default" || value === "title" || value === "status" || value === "assignee" || value === "owner" || value === "priority" || value === "updated") {
28714
+ return value;
27780
28715
  }
27781
28716
  throw new WorkflowOptionsError(
27782
- 'Error: --scope must be "all", "assigned_to_me", "subscribed_by_me", or "owner_is_me".'
28717
+ 'Error: --sort-by must be "default", "title", "status", "assignee", "owner", "priority", or "updated".'
27783
28718
  );
27784
28719
  }
28720
+ function parseTaskSortDirection(raw) {
28721
+ const value = raw ?? "desc";
28722
+ if (value === "asc" || value === "desc") return value;
28723
+ throw new WorkflowOptionsError('Error: --sort-direction must be "asc" or "desc".');
28724
+ }
27785
28725
  function parseHttpUrl(raw, label = "--url") {
27786
28726
  const url = raw.trim();
27787
28727
  try {
@@ -27867,9 +28807,11 @@ function parseAssigneeBody(options, allowClear) {
27867
28807
  if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
27868
28808
  return {};
27869
28809
  }
27870
- function parseTaskListFilterQuery(options) {
28810
+ function parseTaskListFilter(options, scope, currentHumanId) {
27871
28811
  const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28812
+ const filterReporterHumanId = parseOptionalPositiveInteger(options.reporterHumanId, "--reporter-human-id");
27872
28813
  const filterPriority = parsePriority(options.priority);
28814
+ const filterStatusType = parseStatusTypeFilter(options.statusType);
27873
28815
  const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
27874
28816
  const filterAssigneeAssistantId = parseOptionalPositiveInteger(
27875
28817
  options.assigneeAssistantId,
@@ -27883,14 +28825,57 @@ function parseTaskListFilterQuery(options) {
27883
28825
  if (assigneeFilterCount > 1) {
27884
28826
  throw new WorkflowOptionsError("Error: assignee filter options are mutually exclusive.");
27885
28827
  }
28828
+ if (scope === "assigned_to_me" && assigneeFilterCount > 0) {
28829
+ throw new WorkflowOptionsError("Error: --scope assigned_to_me cannot be combined with assignee filters.");
28830
+ }
28831
+ if (scope === "reported_by_me" && filterReporterHumanId !== void 0) {
28832
+ throw new WorkflowOptionsError(
28833
+ "Error: --scope reported_by_me cannot be combined with --reporter-human-id."
28834
+ );
28835
+ }
28836
+ if (scope !== "all" && currentHumanId === void 0) {
28837
+ throw new Error(`Current human ID is required for task scope: ${scope}`);
28838
+ }
27886
28839
  return {
27887
- filterOwnerHumanId,
27888
- filterPriority,
27889
- filterAssigneeHumanId,
27890
- filterAssigneeAssistantId,
27891
- filterAssigneeTeammateId
28840
+ ownerHumanIds: filterOwnerHumanId === void 0 ? null : [{ type: "human", humanId: filterOwnerHumanId }],
28841
+ reporterHumanIds: scope === "reported_by_me" ? [{ type: "human", humanId: currentHumanId }] : filterReporterHumanId === void 0 ? null : [{ type: "human", humanId: filterReporterHumanId }],
28842
+ assignee: scope === "assigned_to_me" ? [{ type: "human", humanId: currentHumanId }] : filterAssigneeHumanId !== void 0 ? [{ type: "human", humanId: filterAssigneeHumanId }] : filterAssigneeAssistantId !== void 0 ? [{ type: "assistant", aiAssistantId: filterAssigneeAssistantId }] : filterAssigneeTeammateId !== void 0 ? [{ type: "teammate", aiTeammateId: filterAssigneeTeammateId }] : null,
28843
+ priorities: filterPriority === void 0 ? null : [filterPriority],
28844
+ statusTypes: filterStatusType === void 0 ? null : [filterStatusType],
28845
+ latestActAtAfter: null,
28846
+ latestActAtBefore: null
27892
28847
  };
27893
28848
  }
28849
+ function matchesMaskedEmail(email, maskedEmail) {
28850
+ const normalizedEmail = email.toLowerCase();
28851
+ const normalizedMask = maskedEmail.toLowerCase();
28852
+ return normalizedEmail.length === normalizedMask.length && [...normalizedMask].every((character, index2) => character === "*" || character === normalizedEmail[index2]);
28853
+ }
28854
+ async function resolveCurrentHumanId(workspaceId) {
28855
+ const [currentUserResponse, membersResponse] = await Promise.all([
28856
+ httpGet("/users/whoami"),
28857
+ httpGet(`/workspaces/${workspaceId}/members`)
28858
+ ]);
28859
+ if (!currentUserResponse.ok) failResponse(currentUserResponse);
28860
+ if (!membersResponse.ok) failResponse(membersResponse);
28861
+ const matchingMembers = membersResponse.data.members.filter(
28862
+ (member) => matchesMaskedEmail(member.email, currentUserResponse.data.email)
28863
+ );
28864
+ if (matchingMembers.length !== 1) {
28865
+ printError("Error: unable to uniquely resolve the current human ID in this workspace.");
28866
+ process.exit(1);
28867
+ }
28868
+ return matchingMembers[0].userId;
28869
+ }
28870
+ function parseReporterBody(options) {
28871
+ const reporterHumanId = parseOptionalPositiveInteger(options.reporterHumanId, "--reporter-human-id");
28872
+ if (options.clearReporter && reporterHumanId !== void 0) {
28873
+ throw new WorkflowOptionsError("Error: --clear-reporter cannot be used with --reporter-human-id.");
28874
+ }
28875
+ if (options.clearReporter) return { reporterHumanId: null };
28876
+ if (reporterHumanId !== void 0) return { reporterHumanId };
28877
+ return {};
28878
+ }
27894
28879
  function parsePreferredAssigneeBody(options) {
27895
28880
  const hasClear = options.clearPreferredAssignee === true;
27896
28881
  const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
@@ -28069,7 +29054,7 @@ function printWorkflowDetail(item) {
28069
29054
  function printTaskSummary(item) {
28070
29055
  const runIds = item.runningAgentRuns.map((run) => run.pipelineId).join(",") || "-";
28071
29056
  print(
28072
- `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
29057
+ `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} reporter=${item.reporterHumanId ?? "-"} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
28073
29058
  );
28074
29059
  }
28075
29060
  function printTaskDetail(item, linkedLinkTitles) {
@@ -28077,6 +29062,7 @@ function printTaskDetail(item, linkedLinkTitles) {
28077
29062
  printDetailField2("scopedId", item.scopedId);
28078
29063
  printDetailField2("workflowFileId", item.workflowFileId);
28079
29064
  printDetailField2("ownerHumanId", item.ownerHumanId);
29065
+ printDetailField2("reporterHumanId", item.reporterHumanId);
28080
29066
  printDetailField2("title", item.title);
28081
29067
  printDetailTextField2("desc", item.desc);
28082
29068
  printDetailField2("statusScopedId", item.statusScopedId);
@@ -28397,33 +29383,41 @@ function registerTransitionCommands(workflow) {
28397
29383
  function registerTaskCommands(workflow) {
28398
29384
  const task = workflow.command("task").description("Workflow task operations");
28399
29385
  addWorkspaceOption(
28400
- task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--priority <priority>", "Filter by priority: urgent, high, medium, or low").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID")
28401
- ).action(
28402
- async (options) => {
28403
- const query = runOrExit4(
28404
- () => buildQuery({
28405
- scope: parseTaskScope(options.scope),
28406
- limit: parseSearchLimit(options.limit, 50, 100),
28407
- cursor: options.cursor,
28408
- workflowFileId: options.workflowFileId,
28409
- ...parseTaskListFilterQuery(options)
28410
- })
28411
- );
28412
- startSpinner("Fetching workflow tasks...");
28413
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v4${query}`);
28414
- if (!response.ok) {
28415
- stopSpinner(false, "Failed");
28416
- failResponse(response);
28417
- }
28418
- if (response.data.tasks.length === 0) {
28419
- stopSpinner(true, "No workflow tasks found.");
28420
- return;
29386
+ task.command("list").description("List workflow tasks").option("--scope <scope>", "Task scope: all, assigned_to_me, or reported_by_me", "all").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--priority <priority>", "Filter by priority: urgent, high, medium, or low").option("--status-type <type>", "Filter by status type: todo, in-progress, or done").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--reporter-human-id <humanId>", "Filter by task reporter human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID").option(
29387
+ "--sort-by <field>",
29388
+ "Sort by default, title, status, assignee, owner, priority, or updated",
29389
+ "default"
29390
+ ).option("--sort-direction <direction>", "Sort direction: asc or desc", "desc")
29391
+ ).action(async (options) => {
29392
+ const scope = runOrExit4(() => parseTaskScope(options.scope));
29393
+ const currentHumanId = scope === "all" ? void 0 : await resolveCurrentHumanId(options.workspace);
29394
+ const body = runOrExit4(() => ({
29395
+ limit: parseSearchLimit(options.limit, 50, 100),
29396
+ cursor: options.cursor,
29397
+ workflowFileId: options.workflowFileId,
29398
+ filter: parseTaskListFilter(options, scope, currentHumanId),
29399
+ sort: {
29400
+ field: parseTaskSortField(options.sortBy),
29401
+ direction: parseTaskSortDirection(options.sortDirection)
28421
29402
  }
28422
- stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
28423
- for (const item of response.data.tasks) printTaskSummary(item);
28424
- if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
29403
+ }));
29404
+ startSpinner("Fetching workflow tasks...");
29405
+ const response = await httpPost(
29406
+ `/workspaces/${options.workspace}/workflow-tasks-v5`,
29407
+ body
29408
+ );
29409
+ if (!response.ok) {
29410
+ stopSpinner(false, "Failed");
29411
+ failResponse(response);
28425
29412
  }
28426
- );
29413
+ if (response.data.tasks.length === 0) {
29414
+ stopSpinner(true, "No workflow tasks found.");
29415
+ return;
29416
+ }
29417
+ stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
29418
+ for (const item of response.data.tasks) printTaskSummary(item);
29419
+ if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
29420
+ });
28427
29421
  addWorkspaceOption(
28428
29422
  task.command("get").description("Get a workflow task").argument("<workflowFileId>").argument("<taskScopedId>")
28429
29423
  ).action(async (workflowFileId, taskScopedId, options) => {
@@ -28439,7 +29433,7 @@ function registerTaskCommands(workflow) {
28439
29433
  });
28440
29434
  addAssigneeOptions(
28441
29435
  addWorkspaceOption(
28442
- task.command("create").description("Create a workflow task").argument("<workflowFileId>").requiredOption("--title <title>", "Task title").requiredOption("--status <statusScopedId>", "Status scoped ID").option("--priority <priority>", "Priority: urgent, high, medium, or low", "medium").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--owner-human-id <humanId>", "Task owner human ID")
29436
+ task.command("create").description("Create a workflow task").argument("<workflowFileId>").requiredOption("--title <title>", "Task title").requiredOption("--status <statusScopedId>", "Status scoped ID").option("--priority <priority>", "Priority: urgent, high, medium, or low", "medium").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--owner-human-id <humanId>", "Task owner human ID").option("--reporter-human-id <humanId>", "Task reporter human ID").option("--clear-reporter", "Create the task without a reporter")
28443
29437
  )
28444
29438
  ).action(
28445
29439
  async (workflowFileId, options) => {
@@ -28454,11 +29448,12 @@ function registerTaskCommands(workflow) {
28454
29448
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28455
29449
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
28456
29450
  Object.assign(next, parseAssigneeBody(options, false));
29451
+ Object.assign(next, parseReporterBody(options));
28457
29452
  return next;
28458
29453
  });
28459
29454
  startSpinner("Creating task...");
28460
29455
  const createResponse = await httpPost(
28461
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2`,
29456
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3`,
28462
29457
  body
28463
29458
  );
28464
29459
  if (!createResponse.ok) {
@@ -28479,7 +29474,7 @@ function registerTaskCommands(workflow) {
28479
29474
  }
28480
29475
  );
28481
29476
  addWorkspaceOption(
28482
- task.command("update").description("Update workflow task metadata").argument("<workflowFileId>").argument("<taskScopedId>").option("--title <title>", "Task title").option("--priority <priority>", "Priority: urgent, high, medium, or low").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--clear-desc", "Clear task description").option("--owner-human-id <humanId>", "Task owner human ID")
29477
+ addTeammateAttributionOption(task.command("update")).description("Update workflow task metadata").argument("<workflowFileId>").argument("<taskScopedId>").option("--title <title>", "Task title").option("--priority <priority>", "Priority: urgent, high, medium, or low").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--clear-desc", "Clear task description").option("--owner-human-id <humanId>", "Task owner human ID").option("--reporter-human-id <humanId>", "Task reporter human ID").option("--clear-reporter", "Clear the task reporter")
28483
29478
  ).action(
28484
29479
  async (workflowFileId, taskScopedId, options) => {
28485
29480
  const body = runOrExit4(() => {
@@ -28495,13 +29490,14 @@ function registerTaskCommands(workflow) {
28495
29490
  if (options.clearDesc) next.desc = null;
28496
29491
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28497
29492
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
29493
+ Object.assign(next, parseReporterBody(options));
28498
29494
  assertNonEmptyBody(next);
28499
- return next;
29495
+ return addTeammateAttribution(next, options);
28500
29496
  });
28501
29497
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28502
29498
  startSpinner("Updating task...");
28503
29499
  const updateResponse = await httpPatch(
28504
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/metadata`,
29500
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3/${id}/metadata`,
28505
29501
  body
28506
29502
  );
28507
29503
  if (!updateResponse.ok) {
@@ -28522,7 +29518,7 @@ function registerTaskCommands(workflow) {
28522
29518
  if (action === "add-linked-links") {
28523
29519
  command.option("--title <title>", "Optional link title");
28524
29520
  }
28525
- addWorkspaceOption(command).action(
29521
+ addWorkspaceOption(addTeammateAttributionOption(command)).action(
28526
29522
  async (workflowFileId, taskScopedId, options) => {
28527
29523
  const { id, link } = runOrExit4(() => ({
28528
29524
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
@@ -28531,9 +29527,10 @@ function registerTaskCommands(workflow) {
28531
29527
  url: parseHttpUrl(options.url)
28532
29528
  }
28533
29529
  }));
29530
+ const body = runOrExit4(() => addTeammateAttribution({ links: [link] }, options));
28534
29531
  startSpinner(action === "add-linked-links" ? "Adding linked URL..." : "Removing linked URL...");
28535
29532
  const path4 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-links`;
28536
- const updateResponse = action === "add-linked-links" ? await httpPost(path4, { links: [link] }) : await httpDelete(path4, { links: [link] });
29533
+ const updateResponse = action === "add-linked-links" ? await httpPost(path4, body) : await httpDelete(path4, body);
28537
29534
  if (!updateResponse.ok) {
28538
29535
  stopSpinner(false, "Failed");
28539
29536
  failResponse(updateResponse);
@@ -28549,17 +29546,18 @@ function registerTaskCommands(workflow) {
28549
29546
  );
28550
29547
  }
28551
29548
  addWorkspaceOption(
28552
- task.command("move").description("Move a workflow task to another status").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID")
29549
+ addTeammateAttributionOption(task.command("move")).description("Move a workflow task to another status").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID")
28553
29550
  ).action(
28554
29551
  async (workflowFileId, taskScopedId, options) => {
28555
29552
  const { id, statusScopedId } = runOrExit4(() => ({
28556
29553
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28557
29554
  statusScopedId: parsePositiveInteger(options.status, "--status")
28558
29555
  }));
29556
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId }, options));
28559
29557
  startSpinner("Moving task...");
28560
29558
  const updateResponse = await httpPatch(
28561
29559
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/status`,
28562
- { statusScopedId }
29560
+ body
28563
29561
  );
28564
29562
  if (!updateResponse.ok) {
28565
29563
  stopSpinner(false, "Failed");
@@ -28575,7 +29573,7 @@ function registerTaskCommands(workflow) {
28575
29573
  }
28576
29574
  );
28577
29575
  addWorkspaceOption(
28578
- task.command("move-after").description("Move a workflow task after an anchor task within a Board column").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID").option("--after <taskScopedId>", "Anchor task scoped ID").option("--first", "Move to the top of the column")
29576
+ addTeammateAttributionOption(task.command("move-after")).description("Move a workflow task after an anchor task within a Board column").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID").option("--after <taskScopedId>", "Anchor task scoped ID").option("--first", "Move to the top of the column")
28579
29577
  ).action(
28580
29578
  async (workflowFileId, taskScopedId, options) => {
28581
29579
  const { id, statusScopedId, anchorTaskScopedId } = runOrExit4(() => {
@@ -28591,10 +29589,11 @@ function registerTaskCommands(workflow) {
28591
29589
  anchorTaskScopedId: options.first ? null : parsePositiveInteger(options.after, "--after")
28592
29590
  };
28593
29591
  });
29592
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId, anchorTaskScopedId }, options));
28594
29593
  startSpinner("Moving task...");
28595
29594
  const updateResponse = await httpPost(
28596
29595
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/move-after`,
28597
- { statusScopedId, anchorTaskScopedId }
29596
+ body
28598
29597
  );
28599
29598
  if (!updateResponse.ok) {
28600
29599
  stopSpinner(false, "Failed");
@@ -28611,14 +29610,14 @@ function registerTaskCommands(workflow) {
28611
29610
  );
28612
29611
  addAssigneeOptions(
28613
29612
  addWorkspaceOption(
28614
- task.command("assign").description("Update workflow task assignee").argument("<workflowFileId>").argument("<taskScopedId>").option("--clear", "Clear assignee")
29613
+ addTeammateAttributionOption(task.command("assign")).description("Update workflow task assignee").argument("<workflowFileId>").argument("<taskScopedId>").option("--clear", "Clear assignee")
28615
29614
  )
28616
29615
  ).action(
28617
29616
  async (workflowFileId, taskScopedId, options) => {
28618
29617
  const body = runOrExit4(() => {
28619
29618
  const next = parseAssigneeBody(options, true);
28620
29619
  if (Object.keys(next).length === 0 && options.clear !== true) assertNonEmptyBody(next);
28621
- return next;
29620
+ return addTeammateAttribution(next, options);
28622
29621
  });
28623
29622
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28624
29623
  startSpinner("Updating task assignee...");
@@ -28656,23 +29655,23 @@ function registerTaskCommands(workflow) {
28656
29655
  }
28657
29656
  function getWorkflowTask(workspaceId, workflowFileId, taskScopedId) {
28658
29657
  return httpGet(
28659
- `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v3/${taskScopedId}`
29658
+ `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v4/${taskScopedId}`
28660
29659
  );
28661
29660
  }
28662
29661
  function registerCommentCommands(workflow) {
28663
29662
  const comment = workflow.command("comment").description("Workflow task comment operations");
28664
29663
  addWorkspaceOption(
28665
- comment.command("create").description("Create a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
29664
+ addTeammateAttributionOption(comment.command("create")).description("Create a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
28666
29665
  ).action(
28667
29666
  async (workflowFileId, taskScopedId, options) => {
28668
- const { id, content: content3 } = runOrExit4(() => ({
29667
+ const { id, body } = runOrExit4(() => ({
28669
29668
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28670
- content: readCommentContentFile2(options.contentPath)
29669
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28671
29670
  }));
28672
29671
  startSpinner("Creating comment...");
28673
29672
  const response = await httpPost(
28674
29673
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}/comments`,
28675
- { content: content3 }
29674
+ body
28676
29675
  );
28677
29676
  if (!response.ok) {
28678
29677
  stopSpinner(false, "Failed");
@@ -28712,18 +29711,18 @@ function registerCommentCommands(workflow) {
28712
29711
  if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
28713
29712
  });
28714
29713
  addWorkspaceOption(
28715
- comment.command("update").description("Edit a workflow task comment authored by the current user").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
29714
+ addTeammateAttributionOption(comment.command("update")).description("Edit a workflow task comment authored by the current actor").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
28716
29715
  ).action(
28717
29716
  async (workflowFileId, taskScopedId, commentId, options) => {
28718
- const { task, comment: commentIdValue, content: content3 } = runOrExit4(() => ({
29717
+ const { task, comment: commentIdValue, body } = runOrExit4(() => ({
28719
29718
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28720
29719
  comment: parsePositiveInteger(commentId, "commentId"),
28721
- content: readCommentContentFile2(options.contentPath)
29720
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28722
29721
  }));
28723
29722
  startSpinner("Updating comment...");
28724
29723
  const response = await httpPatch(
28725
29724
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${task}/comments/${commentIdValue}`,
28726
- { content: content3 }
29725
+ body
28727
29726
  );
28728
29727
  if (!response.ok) {
28729
29728
  stopSpinner(false, "Failed");
@@ -28733,16 +29732,17 @@ function registerCommentCommands(workflow) {
28733
29732
  }
28734
29733
  );
28735
29734
  addWorkspaceOption(
28736
- comment.command("delete").description("Delete a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>")
29735
+ addTeammateAttributionOption(comment.command("delete")).description("Delete a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>")
28737
29736
  ).action(
28738
29737
  async (workflowFileId, taskScopedId, commentId, options) => {
28739
29738
  const ids = runOrExit4(() => ({
28740
29739
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28741
- comment: parsePositiveInteger(commentId, "commentId")
29740
+ comment: parsePositiveInteger(commentId, "commentId"),
29741
+ asTeammateId: parseOptionalPositiveInteger(options.asTeammate, "--as-teammate")
28742
29742
  }));
28743
29743
  startSpinner("Deleting comment...");
28744
29744
  const response = await httpDelete(
28745
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${ids.task}/comments/${ids.comment}`
29745
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${ids.task}/comments/${ids.comment}${buildQuery({ asTeammateId: ids.asTeammateId })}`
28746
29746
  );
28747
29747
  if (!response.ok) {
28748
29748
  stopSpinner(false, "Failed");
@@ -28796,7 +29796,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
28796
29796
  var MAX_BATCH_SIZE = 100;
28797
29797
  function commonLabels() {
28798
29798
  return {
28799
- cli_version: "0.10.0",
29799
+ cli_version: "0.11.0-beta.1",
28800
29800
  node_version: process.versions.node,
28801
29801
  os: (0, import_node_os11.platform)(),
28802
29802
  arch: (0, import_node_os11.arch)(),
@@ -28842,7 +29842,7 @@ async function flush() {
28842
29842
  }
28843
29843
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
28844
29844
  const payload = {
28845
- release_id: "0.10.0",
29845
+ release_id: "0.11.0-beta.1",
28846
29846
  client_type: "cli",
28847
29847
  metric_data_list: batch.map((m) => ({
28848
29848
  profile: "cli",
@@ -29225,9 +30225,9 @@ function commandPath3(command) {
29225
30225
  }
29226
30226
 
29227
30227
  // src/index.ts
29228
- var program2 = createProgram("0.10.0");
29229
- installDaemonReconcileHook(program2, "0.10.0");
29230
- installUpdateHook(program2, "0.10.0");
30228
+ var program2 = createProgram("0.11.0-beta.1");
30229
+ installDaemonReconcileHook(program2, "0.11.0-beta.1");
30230
+ installUpdateHook(program2, "0.11.0-beta.1");
29231
30231
  instrumentProgram(program2);
29232
30232
  installExitHandler();
29233
30233
  program2.parseAsync(process.argv).then(async () => {