@moxt-ai/cli 0.10.0-beta.9 → 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
  };
@@ -8742,6 +9290,7 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8742
9290
  spoolQueue: Promise.resolve(),
8743
9291
  subagentThreadIds: /* @__PURE__ */ new Set(),
8744
9292
  terminal,
9293
+ turnStartPending: false,
8745
9294
  resolveFatal,
8746
9295
  resolveTerminal,
8747
9296
  workingDirectory
@@ -9147,11 +9696,20 @@ async function waitForAbort(signal, milliseconds) {
9147
9696
  });
9148
9697
  }
9149
9698
  function createReclaimableClaimWindow() {
9699
+ let accepted = false;
9150
9700
  let close = () => void 0;
9151
9701
  const completion = new Promise((resolvePromise) => {
9152
9702
  close = resolvePromise;
9153
9703
  });
9154
- return { close, completion };
9704
+ return {
9705
+ accept: () => {
9706
+ accepted = true;
9707
+ close();
9708
+ },
9709
+ close,
9710
+ completion,
9711
+ isAccepted: () => accepted
9712
+ };
9155
9713
  }
9156
9714
  function rejectWhenAborted(signal) {
9157
9715
  return new Promise((_resolve, reject) => {
@@ -9170,7 +9728,7 @@ function parseLeaseDeadline(value) {
9170
9728
  }
9171
9729
  return parsed;
9172
9730
  }
9173
- var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
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;
9174
9732
  var init_runtime_worker = __esm({
9175
9733
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
9176
9734
  "use strict";
@@ -9181,6 +9739,7 @@ var init_runtime_worker = __esm({
9181
9739
  import_node_path11 = require("path");
9182
9740
  init_process_executor();
9183
9741
  init_relay_client();
9742
+ init_retry_backoff();
9184
9743
  init_app_server_client();
9185
9744
  init_contracts2();
9186
9745
  init_durable_attempt();
@@ -9189,19 +9748,18 @@ var init_runtime_worker = __esm({
9189
9748
  claimRetryMilliseconds = 250;
9190
9749
  claimWaitSeconds = 25;
9191
9750
  discoveryWaitSeconds = 25;
9192
- discoveryRetryMilliseconds = 1e3;
9193
9751
  maximumDiscoveryDirectories = 1e3;
9194
9752
  maximumDiscoveryModels = 100;
9195
9753
  maximumModelListPages = 10;
9196
9754
  eventUploadCoalesceMilliseconds = 500;
9197
- eventUploadRetryMilliseconds = 1e3;
9198
9755
  maximumEventUploadCount = 500;
9199
9756
  preferredEventUploadRequestBytes = 96e3;
9200
9757
  leaseRenewIntervalMilliseconds = 1e4;
9201
- leaseRenewRetryMilliseconds = 1e3;
9758
+ defaultNetworkRetryMilliseconds = 1e3;
9759
+ maximumNetworkRetryMilliseconds = 6e4;
9202
9760
  interactionTimeoutMilliseconds = 10 * 60 * 1e3;
9203
9761
  executableProbeTimeoutMilliseconds = 5e3;
9204
- recoveryRetryMilliseconds = 1e3;
9762
+ recoveryScanIntervalMilliseconds = 1e3;
9205
9763
  initialThreadNameRetryMilliseconds = 250;
9206
9764
  maximumThreadNameRetryMilliseconds = 2e3;
9207
9765
  maximumInitialThreadNameAttempts = 8;
@@ -9266,10 +9824,12 @@ var init_runtime_worker = __esm({
9266
9824
  executionTasks = /* @__PURE__ */ new Map();
9267
9825
  lastCapabilityStartError;
9268
9826
  lifetimeAbort = new AbortController();
9827
+ networkRetryMilliseconds;
9828
+ random;
9269
9829
  registered = true;
9270
9830
  unrecoverableAttemptIds = /* @__PURE__ */ new Set();
9271
9831
  running;
9272
- constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger) {
9832
+ constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger, options = {}) {
9273
9833
  this.connection = connection;
9274
9834
  this.relay = relay;
9275
9835
  this.store = store;
@@ -9277,6 +9837,8 @@ var init_runtime_worker = __esm({
9277
9837
  this.environment = environment;
9278
9838
  this.connectorInstanceId = connectorInstanceId;
9279
9839
  this.logger = logger;
9840
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
9841
+ this.random = options.random ?? Math.random;
9280
9842
  this.processPool.register(connection.connectionId, this);
9281
9843
  }
9282
9844
  async run() {
@@ -9421,17 +9983,10 @@ var init_runtime_worker = __esm({
9421
9983
  active.interruptedCleanupStarted = true;
9422
9984
  active.ignoreProcessLoss = true;
9423
9985
  active.initialThreadName?.generation?.resolve();
9424
- const client = this.processPool.currentClient().value;
9986
+ const client = active.appServerClient ?? this.processPool.currentClient().value;
9425
9987
  let cleanupFailed = false;
9426
9988
  if (client !== void 0 && active.nativeThreadId !== void 0) {
9427
- await Promise.all([active.nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
9428
- try {
9429
- await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
9430
- } catch (error) {
9431
- cleanupFailed = true;
9432
- await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; quarantining the shared App Server`, error);
9433
- }
9434
- }));
9989
+ cleanupFailed = !await this.cleanBackgroundTerminals(active, client, "interrupted");
9435
9990
  }
9436
9991
  const quarantineProcess = cleanupFailed || !this.processPool.hasOtherActiveExecution();
9437
9992
  if (quarantineProcess) {
@@ -9467,6 +10022,66 @@ var init_runtime_worker = __esm({
9467
10022
  this.completeInitialThreadName(active);
9468
10023
  this.persistNormalizedNotification(active, normalized);
9469
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
+ }
9470
10085
  async onServerRequest(message) {
9471
10086
  const active = this.activeAttemptForMessage(message).value;
9472
10087
  const client = this.processPool.currentClient().value;
@@ -9562,14 +10177,16 @@ var init_runtime_worker = __esm({
9562
10177
  const response = await this.sendHeartbeat();
9563
10178
  this.applyHeartbeatResponse(response);
9564
10179
  } catch (error) {
9565
- if (!this.lifetimeAbort.signal.aborted) {
9566
- 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;
9567
10182
  }
10183
+ await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
9568
10184
  }
9569
10185
  await waitForAbort(this.lifetimeAbort.signal, heartbeatIntervalMilliseconds);
9570
10186
  }
9571
10187
  }
9572
10188
  async runClaimLoop() {
10189
+ const retryBackoff = this.createNetworkRetryBackoff();
9573
10190
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9574
10191
  if (!this.configured || !this.enabled || !this.runtimeReady()) {
9575
10192
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
@@ -9591,16 +10208,23 @@ var init_runtime_worker = __esm({
9591
10208
  waitSeconds: claimWaitSeconds
9592
10209
  }, this.lifetimeAbort.signal);
9593
10210
  if (response.attempt === void 0) {
10211
+ retryBackoff.reset();
9594
10212
  continue;
9595
10213
  }
9596
10214
  const reclaimableClaimWindow = this.scheduleExecution(slot, response.attempt);
9597
10215
  executionScheduled = true;
9598
- await reclaimableClaimWindow;
10216
+ await reclaimableClaimWindow.completion;
10217
+ if (reclaimableClaimWindow.isAccepted()) {
10218
+ retryBackoff.reset();
10219
+ } else {
10220
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10221
+ }
9599
10222
  } catch (error) {
9600
- if (!this.lifetimeAbort.signal.aborted) {
9601
- await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
9602
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10223
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10224
+ return;
9603
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());
9604
10228
  } finally {
9605
10229
  if (!executionScheduled) {
9606
10230
  this.processPool.releaseExecutionSlot(slot);
@@ -9620,9 +10244,10 @@ var init_runtime_worker = __esm({
9620
10244
  this.processPool.releaseExecutionSlot(slot);
9621
10245
  });
9622
10246
  this.executionTasks.set(claim.attemptId, task);
9623
- return reclaimableClaimWindow.completion;
10247
+ return reclaimableClaimWindow;
9624
10248
  }
9625
10249
  async runDiscoveryLoop() {
10250
+ const retryBackoff = this.createNetworkRetryBackoff();
9626
10251
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9627
10252
  try {
9628
10253
  const response = await this.relay.claimCodexRuntimeDiscovery({
@@ -9631,14 +10256,17 @@ var init_runtime_worker = __esm({
9631
10256
  waitSeconds: discoveryWaitSeconds
9632
10257
  }, this.lifetimeAbort.signal);
9633
10258
  if (response.request === void 0) {
10259
+ retryBackoff.reset();
9634
10260
  continue;
9635
10261
  }
9636
10262
  await this.completeDiscovery(response.request);
10263
+ retryBackoff.reset();
9637
10264
  } catch (error) {
9638
- if (!this.lifetimeAbort.signal.aborted) {
9639
- await this.logger.error(`Local Codex discovery loop failed for connection ${this.connection.connectionId}`, error);
9640
- await waitForAbort(this.lifetimeAbort.signal, discoveryRetryMilliseconds);
10265
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10266
+ return;
9641
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());
9642
10270
  }
9643
10271
  }
9644
10272
  }
@@ -9654,7 +10282,7 @@ var init_runtime_worker = __esm({
9654
10282
  status: LocalCodexDiscoveryStatusWire.Failed
9655
10283
  };
9656
10284
  }
9657
- 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);
9658
10286
  if (!completion.accepted) {
9659
10287
  await this.logger.info(`Local Codex discovery request ${request2.requestId} expired before completion`);
9660
10288
  }
@@ -9725,6 +10353,7 @@ var init_runtime_worker = __esm({
9725
10353
  const durable = await DurableLocalCodexAttempt.create(this.store, this.connection.connectionId, this.connectorInstanceId, claim);
9726
10354
  if (durable.requiresRecovery()) {
9727
10355
  await this.recoverPersistedAttempt(durable.snapshot());
10356
+ reclaimableClaimWindow.accept();
9728
10357
  return;
9729
10358
  }
9730
10359
  const active = createActiveAttempt(claim, durable, this.connection.rootPath);
@@ -9736,7 +10365,13 @@ var init_runtime_worker = __esm({
9736
10365
  const controlLoop = this.runControlLoop(active);
9737
10366
  try {
9738
10367
  active.workingDirectory = await resolveCanonicalWorkingDirectory(this.connection.rootPath, claim.relativeWorkingDirectory);
10368
+ if (active.fatalError !== void 0) {
10369
+ throw active.fatalError;
10370
+ }
9739
10371
  let client = await this.processPool.ensureStarted();
10372
+ if (active.fatalError !== void 0) {
10373
+ throw active.fatalError;
10374
+ }
9740
10375
  const isNewThread = active.nativeThreadId === void 0;
9741
10376
  let nativeThreadId;
9742
10377
  try {
@@ -9750,6 +10385,10 @@ var init_runtime_worker = __esm({
9750
10385
  nativeThreadId = await this.prepareThread(client, active);
9751
10386
  }
9752
10387
  active.nativeThreadId = nativeThreadId;
10388
+ active.appServerClient = client;
10389
+ if (active.fatalError !== void 0) {
10390
+ throw active.fatalError;
10391
+ }
9753
10392
  await durable.markThreadPrepared(nativeThreadId);
9754
10393
  await active.spoolQueue;
9755
10394
  if (isNewThread) {
@@ -9761,7 +10400,11 @@ var init_runtime_worker = __esm({
9761
10400
  if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
9762
10401
  await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
9763
10402
  }
10403
+ if (active.fatalError !== void 0) {
10404
+ throw active.fatalError;
10405
+ }
9764
10406
  let response;
10407
+ active.turnStartPending = true;
9765
10408
  try {
9766
10409
  response = await client.request("turn/start", {
9767
10410
  approvalPolicy: claim.approvalPolicy,
@@ -9778,6 +10421,8 @@ var init_runtime_worker = __esm({
9778
10421
  throw new UnknownTurnStartResultError("Codex App Server turn/start result is unknown; the process generation was quarantined", { cause: error });
9779
10422
  }
9780
10423
  throw error;
10424
+ } finally {
10425
+ active.turnStartPending = false;
9781
10426
  }
9782
10427
  const nativeTurnId = requireTurnId(response);
9783
10428
  if (active.nativeTurnId !== void 0 && active.nativeTurnId !== nativeTurnId) {
@@ -9803,7 +10448,7 @@ var init_runtime_worker = __esm({
9803
10448
  nativeTurnId,
9804
10449
  status: LocalCodexTurnStatusWire.Running
9805
10450
  });
9806
- reclaimableClaimWindow.close();
10451
+ reclaimableClaimWindow.accept();
9807
10452
  await this.interruptActiveTurnIfRequested(active, client);
9808
10453
  const terminal = await Promise.race([
9809
10454
  active.terminal,
@@ -9849,6 +10494,7 @@ var init_runtime_worker = __esm({
9849
10494
  this.completeInitialThreadName(active);
9850
10495
  active.finished.abort();
9851
10496
  await active.interruptedCleanupTask;
10497
+ await active.leaseLossCleanupTask;
9852
10498
  await active.initialThreadName?.task;
9853
10499
  const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9854
10500
  if (titleGenerationTurnId !== void 0) {
@@ -9945,18 +10591,24 @@ var init_runtime_worker = __esm({
9945
10591
  }
9946
10592
  }
9947
10593
  async runRecoveryLoop() {
10594
+ const retryBackoff = this.createNetworkRetryBackoff();
9948
10595
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9949
- await this.scanPersistedAttempts();
9950
- await waitForAbort(this.lifetimeAbort.signal, recoveryRetryMilliseconds);
10596
+ const scanSucceeded = await this.scanPersistedAttempts();
10597
+ if (scanSucceeded) {
10598
+ retryBackoff.reset();
10599
+ }
10600
+ await waitForAbort(this.lifetimeAbort.signal, scanSucceeded ? recoveryScanIntervalMilliseconds : retryBackoff.nextDelayMilliseconds());
9951
10601
  }
9952
10602
  }
9953
10603
  async scanPersistedAttempts() {
9954
10604
  try {
9955
10605
  await this.recoverPersistedAttempts();
10606
+ return true;
9956
10607
  } catch (error) {
9957
10608
  if (!this.lifetimeAbort.signal.aborted) {
9958
10609
  await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
9959
10610
  }
10611
+ return false;
9960
10612
  }
9961
10613
  }
9962
10614
  async recoverPersistedAttempts() {
@@ -9968,10 +10620,12 @@ var init_runtime_worker = __esm({
9968
10620
  try {
9969
10621
  await this.recoverPersistedAttempt(persisted);
9970
10622
  } catch (error) {
9971
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10623
+ if (isPermanentRelayFailure(error)) {
9972
10624
  this.unrecoverableAttemptIds.add(persisted.claim.attemptId);
10625
+ await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10626
+ continue;
9973
10627
  }
9974
- await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10628
+ throw error;
9975
10629
  }
9976
10630
  }
9977
10631
  }
@@ -10027,13 +10681,15 @@ var init_runtime_worker = __esm({
10027
10681
  await this.store.deleteLocalCodexAttempt(snapshot.claim.attemptId);
10028
10682
  }
10029
10683
  async runLeaseLoop(active) {
10684
+ const retryBackoff = this.createNetworkRetryBackoff();
10685
+ let nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
10030
10686
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
10031
10687
  const remaining = active.leaseDeadlineMilliseconds - Date.now();
10032
10688
  if (remaining <= 0) {
10033
10689
  await this.loseLease(active, "Local Codex execution lease expired");
10034
10690
  return;
10035
10691
  }
10036
- await waitForAbort(active.finished.signal, Math.min(leaseRenewIntervalMilliseconds, remaining));
10692
+ await waitForAbort(active.finished.signal, Math.min(nextRenewalDelayMilliseconds, remaining));
10037
10693
  if (active.finished.signal.aborted) {
10038
10694
  return;
10039
10695
  }
@@ -10044,12 +10700,14 @@ var init_runtime_worker = __esm({
10044
10700
  try {
10045
10701
  const response = await this.renewLeaseBeforeDeadline(active);
10046
10702
  active.leaseDeadlineMilliseconds = parseLeaseDeadline(response.leaseExpiresAt);
10703
+ retryBackoff.reset();
10704
+ nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
10047
10705
  } catch (error) {
10048
10706
  if (active.finished.signal.aborted) {
10049
10707
  return;
10050
10708
  }
10051
10709
  await this.logger.error(`Failed to renew Local Codex attempt ${active.claim.attemptId}`, error);
10052
- if (error instanceof LeaseLostError || error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10710
+ if (error instanceof LeaseLostError || isPermanentRelayFailure(error)) {
10053
10711
  await this.loseLease(active, errorMessage3(error));
10054
10712
  return;
10055
10713
  }
@@ -10058,7 +10716,7 @@ var init_runtime_worker = __esm({
10058
10716
  await this.loseLease(active, "Local Codex execution lease expired");
10059
10717
  return;
10060
10718
  }
10061
- await waitForAbort(active.finished.signal, Math.min(leaseRenewRetryMilliseconds, retryRemaining));
10719
+ nextRenewalDelayMilliseconds = Math.min(retryBackoff.nextDelayMilliseconds(), retryRemaining);
10062
10720
  }
10063
10721
  }
10064
10722
  }
@@ -10088,12 +10746,19 @@ var init_runtime_worker = __esm({
10088
10746
  }
10089
10747
  }
10090
10748
  async loseLease(active, message) {
10091
- const error = new LeaseLostError(message);
10092
- this.signalFatal(active, error);
10093
- active.ignoreProcessLoss = true;
10094
- 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;
10095
10759
  }
10096
10760
  async runControlLoop(active) {
10761
+ const retryBackoff = this.createNetworkRetryBackoff();
10097
10762
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
10098
10763
  try {
10099
10764
  const page = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
@@ -10101,14 +10766,15 @@ var init_runtime_worker = __esm({
10101
10766
  await this.applyControl(active, control);
10102
10767
  active.controlCursor = Math.max(active.controlCursor, control.cursor);
10103
10768
  }
10769
+ retryBackoff.reset();
10104
10770
  } catch (error) {
10105
10771
  if (!active.finished.signal.aborted) {
10106
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10772
+ if (isPermanentRelayFailure(error)) {
10107
10773
  await this.loseLease(active, errorMessage3(error));
10108
10774
  return;
10109
10775
  }
10110
10776
  await this.logger.error(`Failed to poll Local Codex controls for ${active.claim.attemptId}`, error);
10111
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10777
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
10112
10778
  }
10113
10779
  }
10114
10780
  }
@@ -10117,7 +10783,7 @@ var init_runtime_worker = __esm({
10117
10783
  await active.durable.recordControl(control.controlId);
10118
10784
  const previouslyApplied = active.durable.appliedControlOutcome(control.controlId).value;
10119
10785
  if (previouslyApplied !== void 0) {
10120
- 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);
10121
10787
  return;
10122
10788
  }
10123
10789
  const client = this.processPool.currentClient().value;
@@ -10141,7 +10807,7 @@ var init_runtime_worker = __esm({
10141
10807
  outcome = await this.applySteerControl(active, control);
10142
10808
  }
10143
10809
  await active.durable.markControlApplied(control.controlId, outcome);
10144
- 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);
10145
10811
  }
10146
10812
  async applySteerControl(active, control) {
10147
10813
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
@@ -10249,41 +10915,52 @@ var init_runtime_worker = __esm({
10249
10915
  }
10250
10916
  async flushAllEvents(active) {
10251
10917
  await active.eventUploadQueue.catch(() => void 0);
10918
+ const retryBackoff = this.createNetworkRetryBackoff();
10252
10919
  while (active.durable.pendingEvents().length > 0) {
10253
10920
  if (active.fatalError !== void 0) {
10254
10921
  throw active.fatalError;
10255
10922
  }
10256
10923
  try {
10257
10924
  await this.flushEvents(active);
10925
+ retryBackoff.reset();
10258
10926
  } catch (error) {
10259
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10927
+ if (isPermanentRelayFailure(error)) {
10260
10928
  throw error;
10261
10929
  }
10262
10930
  if (active.finished.signal.aborted || this.lifetimeAbort.signal.aborted) {
10263
10931
  throw error;
10264
10932
  }
10265
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10933
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
10266
10934
  }
10267
10935
  }
10268
10936
  }
10269
10937
  async retryStateUpdate(active, state) {
10938
+ const retryBackoff = this.createNetworkRetryBackoff();
10270
10939
  while (!this.lifetimeAbort.signal.aborted) {
10271
10940
  if (active.fatalError !== void 0) {
10272
10941
  throw active.fatalError;
10273
10942
  }
10274
10943
  try {
10275
10944
  await this.relay.updateCodexRuntimeState(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), state);
10945
+ retryBackoff.reset();
10276
10946
  return;
10277
10947
  } catch (error) {
10278
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10948
+ if (isPermanentRelayFailure(error)) {
10279
10949
  throw error;
10280
10950
  }
10281
10951
  await this.logger.error(`Failed to update Local Codex state for ${active.claim.attemptId}`, error);
10282
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10952
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10283
10953
  }
10284
10954
  }
10285
10955
  throw new Error("Local Codex Runtime stopped before state ACK");
10286
10956
  }
10957
+ createNetworkRetryBackoff() {
10958
+ return new RetryBackoff({
10959
+ maximumMilliseconds: maximumNetworkRetryMilliseconds,
10960
+ minimumMilliseconds: this.networkRetryMilliseconds,
10961
+ random: this.random
10962
+ });
10963
+ }
10287
10964
  settleTerminal(active, terminal) {
10288
10965
  if (active.terminalValue !== void 0) {
10289
10966
  return;
@@ -10351,7 +11028,7 @@ var init_runtime_worker = __esm({
10351
11028
  moxtCliVersion: moxt.version,
10352
11029
  protocolVersion: localCodexRuntimeProtocolVersion,
10353
11030
  ...unavailableReason === void 0 ? {} : { unavailableReason }
10354
- });
11031
+ }, this.lifetimeAbort.signal);
10355
11032
  }
10356
11033
  applyHeartbeatResponse(response) {
10357
11034
  this.configured = response.configured;
@@ -10710,7 +11387,6 @@ var init_process_pool = __esm({
10710
11387
  await this.quarantineCurrentProcess(capture);
10711
11388
  return;
10712
11389
  }
10713
- this.loadedThreadIds.clear();
10714
11390
  await client.stop(capture);
10715
11391
  }
10716
11392
  async stop() {
@@ -10777,9 +11453,6 @@ var init_process_pool = __esm({
10777
11453
  });
10778
11454
 
10779
11455
  // ../machine-connector/dist/runtime/daemon.js
10780
- function isPermanentRelayFailure(error) {
10781
- 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);
10782
- }
10783
11456
  async function withDeadline(operation, deadline) {
10784
11457
  if (deadline === void 0) {
10785
11458
  return await operation;
@@ -10800,7 +11473,7 @@ function delay4(milliseconds) {
10800
11473
  setTimeout(resolvePromise, milliseconds);
10801
11474
  });
10802
11475
  }
10803
- 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;
10804
11477
  var init_daemon = __esm({
10805
11478
  "../machine-connector/dist/runtime/daemon.js"() {
10806
11479
  "use strict";
@@ -10821,6 +11494,7 @@ var init_daemon = __esm({
10821
11494
  init_process_executor();
10822
11495
  init_shell_environment();
10823
11496
  init_relay_client();
11497
+ init_retry_backoff();
10824
11498
  init_runtime_logger();
10825
11499
  init_runtime_types();
10826
11500
  init_store();
@@ -10834,7 +11508,7 @@ var init_daemon = __esm({
10834
11508
  commandOutputFlushIntervalMilliseconds = 250;
10835
11509
  agentOutputLimitBytes = 2e6;
10836
11510
  defaultLeaseSeconds = 90;
10837
- defaultNetworkRetryMilliseconds = 2e3;
11511
+ defaultNetworkRetryMilliseconds2 = 2e3;
10838
11512
  defaultLeaseSafetyMarginMilliseconds = 1e4;
10839
11513
  defaultTerminalForegroundBudgetMilliseconds = 5e3;
10840
11514
  maximumEventUploadRetryMilliseconds = 6e4;
@@ -10886,7 +11560,7 @@ var init_daemon = __esm({
10886
11560
  this.shellEnvironmentManager = options.shellEnvironmentManager ?? new ShellEnvironmentManager();
10887
11561
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
10888
11562
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
10889
- this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
11563
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds2;
10890
11564
  this.random = options.random ?? Math.random;
10891
11565
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
10892
11566
  }
@@ -11029,7 +11703,10 @@ var init_daemon = __esm({
11029
11703
  ]);
11030
11704
  }
11031
11705
  async runLocalCodexRuntime(connection, relay) {
11032
- 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
+ });
11033
11710
  this.localCodexWorkers.set(connection.connectionId, worker);
11034
11711
  if (this.stopping) {
11035
11712
  await worker.stop();
@@ -11059,9 +11736,11 @@ var init_daemon = __esm({
11059
11736
  return existing;
11060
11737
  }
11061
11738
  const relay = new MachineRelayClient(connection, this.store, {
11739
+ minimumRetryMilliseconds: this.networkRetryMilliseconds,
11062
11740
  onConnectionRevoked: async (error) => {
11063
11741
  await this.handleConnectionRevoked(connection, error);
11064
- }
11742
+ },
11743
+ random: this.random
11065
11744
  });
11066
11745
  this.relayClients.set(connection.connectionId, relay);
11067
11746
  return relay;
@@ -11091,7 +11770,7 @@ var init_daemon = __esm({
11091
11770
  protocolVersion: machineProtocolVersion
11092
11771
  });
11093
11772
  } catch (error) {
11094
- if (relay.isRevoked()) {
11773
+ if (this.stopping || relay.isRevoked()) {
11095
11774
  return;
11096
11775
  }
11097
11776
  await this.logger.error(`Heartbeat failed for connection ${connection.connectionId}`, error);
@@ -11100,6 +11779,7 @@ var init_daemon = __esm({
11100
11779
  }
11101
11780
  }
11102
11781
  async runClaimLoop(connection, relay) {
11782
+ const retryBackoff = this.createNetworkRetryBackoff();
11103
11783
  while (!this.stopping && !relay.isRevoked()) {
11104
11784
  try {
11105
11785
  const response = await relay.claim({
@@ -11115,17 +11795,19 @@ var init_daemon = __esm({
11115
11795
  }
11116
11796
  this.startClaimExecution(activeJob);
11117
11797
  }
11798
+ retryBackoff.reset();
11118
11799
  } catch (error) {
11119
- if (relay.isRevoked()) {
11800
+ if (this.stopping || relay.isRevoked()) {
11120
11801
  return;
11121
11802
  }
11122
11803
  await this.logger.error(`Job claim failed for connection ${connection.connectionId}`, error);
11123
- await this.waitUntilStop(this.networkRetryMilliseconds);
11804
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
11124
11805
  }
11125
11806
  }
11126
11807
  }
11127
11808
  async runControlLoop(connection, relay) {
11128
11809
  let cursor = 0;
11810
+ const retryBackoff = this.createNetworkRetryBackoff();
11129
11811
  while (!this.stopping && !relay.isRevoked()) {
11130
11812
  try {
11131
11813
  const response = await relay.pollControls({
@@ -11140,12 +11822,13 @@ var init_daemon = __esm({
11140
11822
  if (response.commands.length === 0) {
11141
11823
  cursor = response.nextCursor;
11142
11824
  }
11825
+ retryBackoff.reset();
11143
11826
  } catch (error) {
11144
- if (relay.isRevoked()) {
11827
+ if (this.stopping || relay.isRevoked()) {
11145
11828
  return;
11146
11829
  }
11147
11830
  await this.logger.error(`Control poll failed for connection ${connection.connectionId}`, error);
11148
- await this.waitUntilStop(this.networkRetryMilliseconds);
11831
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
11149
11832
  }
11150
11833
  }
11151
11834
  }
@@ -11633,6 +12316,13 @@ var init_daemon = __esm({
11633
12316
  await delay4(Math.min(250, deadline - Date.now()));
11634
12317
  }
11635
12318
  }
12319
+ createNetworkRetryBackoff() {
12320
+ return new RetryBackoff({
12321
+ maximumMilliseconds: maximumTerminalRetryMilliseconds,
12322
+ minimumMilliseconds: this.networkRetryMilliseconds,
12323
+ random: this.random
12324
+ });
12325
+ }
11636
12326
  cancellationResult(activeJob) {
11637
12327
  const reason = activeJob.cancellation.currentReason();
11638
12328
  if (reason === ExecutionCancellationReason.LeaseLost) {
@@ -14367,6 +15057,8 @@ __export(dist_exports, {
14367
15057
  executeClaudeReply: () => executeClaudeReply,
14368
15058
  executeClaudeStart: () => executeClaudeStart,
14369
15059
  installUserService: () => installUserService,
15060
+ isPermanentRelayFailure: () => isPermanentRelayFailure,
15061
+ isRetryableRelayFailure: () => isRetryableRelayFailure,
14370
15062
  isTerminalJobStatus: () => isTerminalJobStatus,
14371
15063
  localCodexRuntimeEventsRequestBytes: () => localCodexRuntimeEventsRequestBytes,
14372
15064
  localMachineJobTargetRelationship: () => localMachineJobTargetRelationship,
@@ -14592,7 +15284,7 @@ function getApiKeyOrUndefined() {
14592
15284
 
14593
15285
  // src/utils/http.ts
14594
15286
  function getUserAgent() {
14595
- return `moxt-cli/${"0.10.0-beta.9"} (${(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}`;
14596
15288
  }
14597
15289
  async function sendRequest(method, path4, init) {
14598
15290
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -27922,6 +28614,14 @@ var import_node_util6 = require("util");
27922
28614
  var MAX_DESC_LENGTH = 5e3;
27923
28615
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
27924
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
+ }
27925
28625
  var WorkflowOptionsError = class extends Error {
27926
28626
  constructor(message) {
27927
28627
  super(message);
@@ -27953,6 +28653,9 @@ function addPreferredAssigneeOptions(command) {
27953
28653
  }
27954
28654
  function parsePositiveInteger(raw, label) {
27955
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
+ }
27956
28659
  if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
27957
28660
  throw new WorkflowOptionsError(`Error: ${label} must be a positive integer, got "${raw}".`);
27958
28661
  }
@@ -27993,13 +28696,32 @@ function parseWorkflowScope(raw) {
27993
28696
  }
27994
28697
  function parseTaskScope(raw) {
27995
28698
  if (raw == null || raw === "") return "all";
27996
- if (raw === "all" || raw === "assigned_to_me" || raw === "subscribed_by_me" || raw === "owner_is_me") {
27997
- 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;
27998
28715
  }
27999
28716
  throw new WorkflowOptionsError(
28000
- '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".'
28001
28718
  );
28002
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
+ }
28003
28725
  function parseHttpUrl(raw, label = "--url") {
28004
28726
  const url = raw.trim();
28005
28727
  try {
@@ -28085,9 +28807,11 @@ function parseAssigneeBody(options, allowClear) {
28085
28807
  if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
28086
28808
  return {};
28087
28809
  }
28088
- function parseTaskListFilterQuery(options) {
28810
+ function parseTaskListFilter(options, scope, currentHumanId) {
28089
28811
  const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28812
+ const filterReporterHumanId = parseOptionalPositiveInteger(options.reporterHumanId, "--reporter-human-id");
28090
28813
  const filterPriority = parsePriority(options.priority);
28814
+ const filterStatusType = parseStatusTypeFilter(options.statusType);
28091
28815
  const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
28092
28816
  const filterAssigneeAssistantId = parseOptionalPositiveInteger(
28093
28817
  options.assigneeAssistantId,
@@ -28101,14 +28825,57 @@ function parseTaskListFilterQuery(options) {
28101
28825
  if (assigneeFilterCount > 1) {
28102
28826
  throw new WorkflowOptionsError("Error: assignee filter options are mutually exclusive.");
28103
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
+ }
28104
28839
  return {
28105
- filterOwnerHumanId,
28106
- filterPriority,
28107
- filterAssigneeHumanId,
28108
- filterAssigneeAssistantId,
28109
- 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
28110
28847
  };
28111
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
+ }
28112
28879
  function parsePreferredAssigneeBody(options) {
28113
28880
  const hasClear = options.clearPreferredAssignee === true;
28114
28881
  const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
@@ -28287,7 +29054,7 @@ function printWorkflowDetail(item) {
28287
29054
  function printTaskSummary(item) {
28288
29055
  const runIds = item.runningAgentRuns.map((run) => run.pipelineId).join(",") || "-";
28289
29056
  print(
28290
- `${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}`
28291
29058
  );
28292
29059
  }
28293
29060
  function printTaskDetail(item, linkedLinkTitles) {
@@ -28295,6 +29062,7 @@ function printTaskDetail(item, linkedLinkTitles) {
28295
29062
  printDetailField2("scopedId", item.scopedId);
28296
29063
  printDetailField2("workflowFileId", item.workflowFileId);
28297
29064
  printDetailField2("ownerHumanId", item.ownerHumanId);
29065
+ printDetailField2("reporterHumanId", item.reporterHumanId);
28298
29066
  printDetailField2("title", item.title);
28299
29067
  printDetailTextField2("desc", item.desc);
28300
29068
  printDetailField2("statusScopedId", item.statusScopedId);
@@ -28615,33 +29383,41 @@ function registerTransitionCommands(workflow) {
28615
29383
  function registerTaskCommands(workflow) {
28616
29384
  const task = workflow.command("task").description("Workflow task operations");
28617
29385
  addWorkspaceOption(
28618
- 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")
28619
- ).action(
28620
- async (options) => {
28621
- const query = runOrExit4(
28622
- () => buildQuery({
28623
- scope: parseTaskScope(options.scope),
28624
- limit: parseSearchLimit(options.limit, 50, 100),
28625
- cursor: options.cursor,
28626
- workflowFileId: options.workflowFileId,
28627
- ...parseTaskListFilterQuery(options)
28628
- })
28629
- );
28630
- startSpinner("Fetching workflow tasks...");
28631
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v4${query}`);
28632
- if (!response.ok) {
28633
- stopSpinner(false, "Failed");
28634
- failResponse(response);
28635
- }
28636
- if (response.data.tasks.length === 0) {
28637
- stopSpinner(true, "No workflow tasks found.");
28638
- 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)
28639
29402
  }
28640
- stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
28641
- for (const item of response.data.tasks) printTaskSummary(item);
28642
- 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);
28643
29412
  }
28644
- );
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
+ });
28645
29421
  addWorkspaceOption(
28646
29422
  task.command("get").description("Get a workflow task").argument("<workflowFileId>").argument("<taskScopedId>")
28647
29423
  ).action(async (workflowFileId, taskScopedId, options) => {
@@ -28657,7 +29433,7 @@ function registerTaskCommands(workflow) {
28657
29433
  });
28658
29434
  addAssigneeOptions(
28659
29435
  addWorkspaceOption(
28660
- 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")
28661
29437
  )
28662
29438
  ).action(
28663
29439
  async (workflowFileId, options) => {
@@ -28672,11 +29448,12 @@ function registerTaskCommands(workflow) {
28672
29448
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28673
29449
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
28674
29450
  Object.assign(next, parseAssigneeBody(options, false));
29451
+ Object.assign(next, parseReporterBody(options));
28675
29452
  return next;
28676
29453
  });
28677
29454
  startSpinner("Creating task...");
28678
29455
  const createResponse = await httpPost(
28679
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2`,
29456
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3`,
28680
29457
  body
28681
29458
  );
28682
29459
  if (!createResponse.ok) {
@@ -28697,7 +29474,7 @@ function registerTaskCommands(workflow) {
28697
29474
  }
28698
29475
  );
28699
29476
  addWorkspaceOption(
28700
- 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")
28701
29478
  ).action(
28702
29479
  async (workflowFileId, taskScopedId, options) => {
28703
29480
  const body = runOrExit4(() => {
@@ -28713,13 +29490,14 @@ function registerTaskCommands(workflow) {
28713
29490
  if (options.clearDesc) next.desc = null;
28714
29491
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28715
29492
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
29493
+ Object.assign(next, parseReporterBody(options));
28716
29494
  assertNonEmptyBody(next);
28717
- return next;
29495
+ return addTeammateAttribution(next, options);
28718
29496
  });
28719
29497
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28720
29498
  startSpinner("Updating task...");
28721
29499
  const updateResponse = await httpPatch(
28722
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/metadata`,
29500
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3/${id}/metadata`,
28723
29501
  body
28724
29502
  );
28725
29503
  if (!updateResponse.ok) {
@@ -28740,7 +29518,7 @@ function registerTaskCommands(workflow) {
28740
29518
  if (action === "add-linked-links") {
28741
29519
  command.option("--title <title>", "Optional link title");
28742
29520
  }
28743
- addWorkspaceOption(command).action(
29521
+ addWorkspaceOption(addTeammateAttributionOption(command)).action(
28744
29522
  async (workflowFileId, taskScopedId, options) => {
28745
29523
  const { id, link } = runOrExit4(() => ({
28746
29524
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
@@ -28749,9 +29527,10 @@ function registerTaskCommands(workflow) {
28749
29527
  url: parseHttpUrl(options.url)
28750
29528
  }
28751
29529
  }));
29530
+ const body = runOrExit4(() => addTeammateAttribution({ links: [link] }, options));
28752
29531
  startSpinner(action === "add-linked-links" ? "Adding linked URL..." : "Removing linked URL...");
28753
29532
  const path4 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-links`;
28754
- 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);
28755
29534
  if (!updateResponse.ok) {
28756
29535
  stopSpinner(false, "Failed");
28757
29536
  failResponse(updateResponse);
@@ -28767,17 +29546,18 @@ function registerTaskCommands(workflow) {
28767
29546
  );
28768
29547
  }
28769
29548
  addWorkspaceOption(
28770
- 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")
28771
29550
  ).action(
28772
29551
  async (workflowFileId, taskScopedId, options) => {
28773
29552
  const { id, statusScopedId } = runOrExit4(() => ({
28774
29553
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28775
29554
  statusScopedId: parsePositiveInteger(options.status, "--status")
28776
29555
  }));
29556
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId }, options));
28777
29557
  startSpinner("Moving task...");
28778
29558
  const updateResponse = await httpPatch(
28779
29559
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/status`,
28780
- { statusScopedId }
29560
+ body
28781
29561
  );
28782
29562
  if (!updateResponse.ok) {
28783
29563
  stopSpinner(false, "Failed");
@@ -28793,7 +29573,7 @@ function registerTaskCommands(workflow) {
28793
29573
  }
28794
29574
  );
28795
29575
  addWorkspaceOption(
28796
- 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")
28797
29577
  ).action(
28798
29578
  async (workflowFileId, taskScopedId, options) => {
28799
29579
  const { id, statusScopedId, anchorTaskScopedId } = runOrExit4(() => {
@@ -28809,10 +29589,11 @@ function registerTaskCommands(workflow) {
28809
29589
  anchorTaskScopedId: options.first ? null : parsePositiveInteger(options.after, "--after")
28810
29590
  };
28811
29591
  });
29592
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId, anchorTaskScopedId }, options));
28812
29593
  startSpinner("Moving task...");
28813
29594
  const updateResponse = await httpPost(
28814
29595
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/move-after`,
28815
- { statusScopedId, anchorTaskScopedId }
29596
+ body
28816
29597
  );
28817
29598
  if (!updateResponse.ok) {
28818
29599
  stopSpinner(false, "Failed");
@@ -28829,14 +29610,14 @@ function registerTaskCommands(workflow) {
28829
29610
  );
28830
29611
  addAssigneeOptions(
28831
29612
  addWorkspaceOption(
28832
- 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")
28833
29614
  )
28834
29615
  ).action(
28835
29616
  async (workflowFileId, taskScopedId, options) => {
28836
29617
  const body = runOrExit4(() => {
28837
29618
  const next = parseAssigneeBody(options, true);
28838
29619
  if (Object.keys(next).length === 0 && options.clear !== true) assertNonEmptyBody(next);
28839
- return next;
29620
+ return addTeammateAttribution(next, options);
28840
29621
  });
28841
29622
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28842
29623
  startSpinner("Updating task assignee...");
@@ -28874,23 +29655,23 @@ function registerTaskCommands(workflow) {
28874
29655
  }
28875
29656
  function getWorkflowTask(workspaceId, workflowFileId, taskScopedId) {
28876
29657
  return httpGet(
28877
- `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v3/${taskScopedId}`
29658
+ `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v4/${taskScopedId}`
28878
29659
  );
28879
29660
  }
28880
29661
  function registerCommentCommands(workflow) {
28881
29662
  const comment = workflow.command("comment").description("Workflow task comment operations");
28882
29663
  addWorkspaceOption(
28883
- 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")
28884
29665
  ).action(
28885
29666
  async (workflowFileId, taskScopedId, options) => {
28886
- const { id, content: content3 } = runOrExit4(() => ({
29667
+ const { id, body } = runOrExit4(() => ({
28887
29668
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28888
- content: readCommentContentFile2(options.contentPath)
29669
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28889
29670
  }));
28890
29671
  startSpinner("Creating comment...");
28891
29672
  const response = await httpPost(
28892
29673
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}/comments`,
28893
- { content: content3 }
29674
+ body
28894
29675
  );
28895
29676
  if (!response.ok) {
28896
29677
  stopSpinner(false, "Failed");
@@ -28930,18 +29711,18 @@ function registerCommentCommands(workflow) {
28930
29711
  if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
28931
29712
  });
28932
29713
  addWorkspaceOption(
28933
- 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")
28934
29715
  ).action(
28935
29716
  async (workflowFileId, taskScopedId, commentId, options) => {
28936
- const { task, comment: commentIdValue, content: content3 } = runOrExit4(() => ({
29717
+ const { task, comment: commentIdValue, body } = runOrExit4(() => ({
28937
29718
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28938
29719
  comment: parsePositiveInteger(commentId, "commentId"),
28939
- content: readCommentContentFile2(options.contentPath)
29720
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28940
29721
  }));
28941
29722
  startSpinner("Updating comment...");
28942
29723
  const response = await httpPatch(
28943
29724
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${task}/comments/${commentIdValue}`,
28944
- { content: content3 }
29725
+ body
28945
29726
  );
28946
29727
  if (!response.ok) {
28947
29728
  stopSpinner(false, "Failed");
@@ -28951,16 +29732,17 @@ function registerCommentCommands(workflow) {
28951
29732
  }
28952
29733
  );
28953
29734
  addWorkspaceOption(
28954
- 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>")
28955
29736
  ).action(
28956
29737
  async (workflowFileId, taskScopedId, commentId, options) => {
28957
29738
  const ids = runOrExit4(() => ({
28958
29739
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28959
- comment: parsePositiveInteger(commentId, "commentId")
29740
+ comment: parsePositiveInteger(commentId, "commentId"),
29741
+ asTeammateId: parseOptionalPositiveInteger(options.asTeammate, "--as-teammate")
28960
29742
  }));
28961
29743
  startSpinner("Deleting comment...");
28962
29744
  const response = await httpDelete(
28963
- `/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 })}`
28964
29746
  );
28965
29747
  if (!response.ok) {
28966
29748
  stopSpinner(false, "Failed");
@@ -29014,7 +29796,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
29014
29796
  var MAX_BATCH_SIZE = 100;
29015
29797
  function commonLabels() {
29016
29798
  return {
29017
- cli_version: "0.10.0-beta.9",
29799
+ cli_version: "0.11.0-beta.1",
29018
29800
  node_version: process.versions.node,
29019
29801
  os: (0, import_node_os11.platform)(),
29020
29802
  arch: (0, import_node_os11.arch)(),
@@ -29060,7 +29842,7 @@ async function flush() {
29060
29842
  }
29061
29843
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
29062
29844
  const payload = {
29063
- release_id: "0.10.0-beta.9",
29845
+ release_id: "0.11.0-beta.1",
29064
29846
  client_type: "cli",
29065
29847
  metric_data_list: batch.map((m) => ({
29066
29848
  profile: "cli",
@@ -29443,9 +30225,9 @@ function commandPath3(command) {
29443
30225
  }
29444
30226
 
29445
30227
  // src/index.ts
29446
- var program2 = createProgram("0.10.0-beta.9");
29447
- installDaemonReconcileHook(program2, "0.10.0-beta.9");
29448
- installUpdateHook(program2, "0.10.0-beta.9");
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");
29449
30231
  instrumentProgram(program2);
29450
30232
  installExitHandler();
29451
30233
  program2.parseAsync(process.argv).then(async () => {