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

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");
7515
+ }
7516
+ accessTokenSnapshot() {
7517
+ return {
7518
+ revision: this.accessTokenRevision,
7519
+ token: this.connection.accessToken
7520
+ };
6979
7521
  }
6980
- async refreshAccessTokenOnce() {
7522
+ async refreshAccessTokenOnce(rejectedAccessTokenRevision) {
7523
+ if (rejectedAccessTokenRevision !== this.accessTokenRevision) {
7524
+ return;
7525
+ }
6981
7526
  if (!this.refreshState.promise) {
6982
- this.refreshState.promise = this.refreshAccessToken().finally(() => {
7527
+ this.refreshState.promise = this.requestCoordinator.run(RelayCircuitKind.Refresh, RelayRequestMode.Short, async (probe) => {
7528
+ await this.refreshAccessToken(probe ? probeRequestTimeoutMilliseconds : requestTimeoutMilliseconds);
7529
+ }).finally(() => {
6983
7530
  delete this.refreshState.promise;
6984
7531
  });
6985
7532
  }
6986
7533
  await this.refreshState.promise;
6987
7534
  }
6988
- async refreshAccessToken() {
7535
+ async refreshAccessToken(timeoutMilliseconds) {
6989
7536
  let response;
6990
7537
  try {
6991
- response = await postJson(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/pairing/refresh`, { refreshToken: this.connection.refreshToken });
7538
+ response = await postJson(`${normalizeOrigin(this.connection.relayOrigin)}/machine-relay/v1/pairing/refresh`, { refreshToken: this.connection.refreshToken }, void 0, void 0, timeoutMilliseconds);
6992
7539
  } catch (error) {
6993
7540
  if (!(error instanceof RelayHttpError) || error.status !== 401) {
6994
7541
  throw error;
6995
7542
  }
6996
7543
  const revokedError = new MachineConnectionRevokedError(this.connection.connectionId);
6997
7544
  this.revoked = true;
6998
- await this.hooks.onConnectionRevoked?.(revokedError);
7545
+ await this.options.onConnectionRevoked?.(revokedError);
6999
7546
  throw revokedError;
7000
7547
  }
7001
7548
  this.connection = {
@@ -7003,6 +7550,7 @@ var init_relay_client = __esm({
7003
7550
  accessToken: response.accessToken,
7004
7551
  accessTokenExpiresAt: response.accessTokenExpiresAt
7005
7552
  };
7553
+ this.accessTokenRevision += 1;
7006
7554
  await this.store.saveConnection(this.connection);
7007
7555
  }
7008
7556
  };
@@ -8185,11 +8733,11 @@ var init_app_server_client = __esm({
8185
8733
  });
8186
8734
 
8187
8735
  // ../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js
8188
- function assertCompatibleClaim(persisted, connectionId, claim) {
8736
+ function assertCompatibleClaim(persisted, connectionId, claim, allowRestartFenceRotation) {
8189
8737
  if (persisted.connectionId !== connectionId || persisted.claim.attemptId !== claim.attemptId || persisted.claim.attemptGeneration !== claim.attemptGeneration || persisted.claim.conversationId !== claim.conversationId || persisted.claim.turnId !== claim.turnId || persisted.claim.expectedNativeStoreIdentity !== claim.expectedNativeStoreIdentity) {
8190
8738
  throw new Error(`Local Codex Runtime attempt ${claim.attemptId} conflicts with its durable spool`);
8191
8739
  }
8192
- if (persisted.phase !== LocalCodexAttemptPhase.Claimed && (persisted.claim.leaseToken !== claim.leaseToken || persisted.claim.runToken !== claim.runToken)) {
8740
+ if (persisted.phase !== LocalCodexAttemptPhase.Claimed && !allowRestartFenceRotation && (persisted.claim.leaseToken !== claim.leaseToken || persisted.claim.runToken !== claim.runToken)) {
8193
8741
  throw new Error(`Running Local Codex Runtime attempt ${claim.attemptId} changed its fence`);
8194
8742
  }
8195
8743
  }
@@ -8205,6 +8753,24 @@ function boundedPayload(kind, payload) {
8205
8753
  truncated: true
8206
8754
  };
8207
8755
  }
8756
+ function sanitizeJsonbValue(value) {
8757
+ if (typeof value === "string") {
8758
+ return value.replaceAll("\0", "");
8759
+ }
8760
+ if (Array.isArray(value)) {
8761
+ return value.map(sanitizeJsonbValue);
8762
+ }
8763
+ if (value !== null && typeof value === "object") {
8764
+ return sanitizeJsonbRecord(value);
8765
+ }
8766
+ return value;
8767
+ }
8768
+ function sanitizeJsonbRecord(value) {
8769
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [
8770
+ key,
8771
+ sanitizeJsonbValue(item)
8772
+ ]));
8773
+ }
8208
8774
  var import_node_crypto7, maximumEventBytes, maximumSpoolBytes, DurableLocalCodexAttempt;
8209
8775
  var init_durable_attempt = __esm({
8210
8776
  "../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js"() {
@@ -8217,16 +8783,19 @@ var init_durable_attempt = __esm({
8217
8783
  DurableLocalCodexAttempt = class _DurableLocalCodexAttempt {
8218
8784
  store;
8219
8785
  state;
8786
+ recoveryRequired;
8220
8787
  mutationQueue = Promise.resolve();
8221
- constructor(store, state) {
8788
+ constructor(store, state, recoveryRequired = false) {
8222
8789
  this.store = store;
8223
8790
  this.state = state;
8791
+ this.recoveryRequired = recoveryRequired;
8224
8792
  }
8225
8793
  static async create(store, connectionId, connectorInstanceId, claim) {
8226
8794
  const persisted = (await store.readLocalCodexAttempt(claim.attemptId)).value;
8227
8795
  if (persisted !== void 0) {
8228
- assertCompatibleClaim(persisted, connectionId, claim);
8229
- if (persisted.phase === LocalCodexAttemptPhase.Claimed) {
8796
+ const recoveryRequired = persisted.phase === LocalCodexAttemptPhase.TerminalPendingUpload || persisted.phase === LocalCodexAttemptPhase.Running && persisted.connectorInstanceId !== connectorInstanceId;
8797
+ assertCompatibleClaim(persisted, connectionId, claim, recoveryRequired);
8798
+ if (persisted.phase === LocalCodexAttemptPhase.Claimed || recoveryRequired) {
8230
8799
  persisted.claim = claim;
8231
8800
  persisted.connectorInstanceId = connectorInstanceId;
8232
8801
  persisted.acknowledgedSequence = claim.lastAcknowledgedEventSequence;
@@ -8235,7 +8804,7 @@ var init_durable_attempt = __esm({
8235
8804
  persisted.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
8236
8805
  await store.writeLocalCodexAttempt(persisted);
8237
8806
  }
8238
- return new _DurableLocalCodexAttempt(store, persisted);
8807
+ return new _DurableLocalCodexAttempt(store, persisted, recoveryRequired);
8239
8808
  }
8240
8809
  const state = {
8241
8810
  acknowledgedSequence: claim.lastAcknowledgedEventSequence,
@@ -8258,6 +8827,9 @@ var init_durable_attempt = __esm({
8258
8827
  snapshot() {
8259
8828
  return structuredClone(this.state);
8260
8829
  }
8830
+ requiresRecovery() {
8831
+ return this.recoveryRequired;
8832
+ }
8261
8833
  async markRunning(nativeThreadId, nativeTurnId) {
8262
8834
  await this.mutate(async () => {
8263
8835
  this.state.nativeThreadId = nativeThreadId;
@@ -8278,7 +8850,7 @@ var init_durable_attempt = __esm({
8278
8850
  async appendEvent(kind, payload, correlation = {}, occurredAt = (/* @__PURE__ */ new Date()).toISOString()) {
8279
8851
  const holder = {};
8280
8852
  await this.mutate(async () => {
8281
- const safePayload = boundedPayload(kind, payload);
8853
+ const safePayload = boundedPayload(kind, sanitizeJsonbRecord(payload));
8282
8854
  const event2 = {
8283
8855
  eventId: (0, import_node_crypto7.randomUUID)(),
8284
8856
  kind,
@@ -8307,7 +8879,10 @@ var init_durable_attempt = __esm({
8307
8879
  return structuredClone(holder.value);
8308
8880
  }
8309
8881
  pendingEvents() {
8310
- return structuredClone(this.state.events.filter((event2) => event2.sequence > this.state.acknowledgedSequence));
8882
+ return structuredClone(this.state.events.filter((event2) => event2.sequence > this.state.acknowledgedSequence).map((event2) => ({
8883
+ ...event2,
8884
+ payload: sanitizeJsonbRecord(event2.payload)
8885
+ })));
8311
8886
  }
8312
8887
  async acknowledgeEvents(sequence) {
8313
8888
  await this.mutate(async () => {
@@ -8728,12 +9303,15 @@ function createActiveAttempt(claim, durable, workingDirectory) {
8728
9303
  eventUploadQueue: Promise.resolve(),
8729
9304
  fatal,
8730
9305
  finished: new AbortController(),
9306
+ ignoreProcessLoss: false,
8731
9307
  interruptedCleanupStarted: false,
8732
9308
  leaseDeadlineMilliseconds: parseLeaseDeadline(claim.leaseExpiresAt),
8733
9309
  nativeThreadId: durable.snapshot().nativeThreadId ?? claim.nativeThreadId,
9310
+ processQuarantined: false,
8734
9311
  spoolQueue: Promise.resolve(),
8735
9312
  subagentThreadIds: /* @__PURE__ */ new Set(),
8736
9313
  terminal,
9314
+ turnStartPending: false,
8737
9315
  resolveFatal,
8738
9316
  resolveTerminal,
8739
9317
  workingDirectory
@@ -8820,6 +9398,24 @@ function appServerMessageThreadId(message) {
8820
9398
  }
8821
9399
  return optionalString2(safeRecord(params.thread).id);
8822
9400
  }
9401
+ function appServerMessageTurnId(message) {
9402
+ const params = safeRecord(message.params);
9403
+ const direct = optionalString2(params.turnId).value;
9404
+ if (direct !== void 0) {
9405
+ return { value: direct };
9406
+ }
9407
+ return optionalString2(safeRecord(params.turn).id);
9408
+ }
9409
+ function activeOwnsThread(active, threadId) {
9410
+ return active.nativeThreadId === threadId || active.subagentThreadIds.has(threadId) || active.initialThreadName?.generation?.threadId === threadId;
9411
+ }
9412
+ function singleActiveAttempt(attempts) {
9413
+ if (attempts.length !== 1) {
9414
+ return {};
9415
+ }
9416
+ const value = attempts[0];
9417
+ return value === void 0 ? {} : { value };
9418
+ }
8823
9419
  function normalizeThreadTitle(value) {
8824
9420
  const title = Array.from(value.trim().replace(/\s+/g, " ")).slice(0, maximumThreadTitleCharacters).join("");
8825
9421
  return title === "" ? {} : { value: title };
@@ -9120,6 +9716,32 @@ async function waitForAbort(signal, milliseconds) {
9120
9716
  signal.addEventListener("abort", complete, { once: true });
9121
9717
  });
9122
9718
  }
9719
+ function createReclaimableClaimWindow() {
9720
+ let accepted = false;
9721
+ let close = () => void 0;
9722
+ const completion = new Promise((resolvePromise) => {
9723
+ close = resolvePromise;
9724
+ });
9725
+ return {
9726
+ accept: () => {
9727
+ accepted = true;
9728
+ close();
9729
+ },
9730
+ close,
9731
+ completion,
9732
+ isAccepted: () => accepted
9733
+ };
9734
+ }
9735
+ function rejectWhenAborted(signal) {
9736
+ return new Promise((_resolve, reject) => {
9737
+ const rejectStopped = () => reject(new WorkerStoppedError());
9738
+ if (signal.aborted) {
9739
+ rejectStopped();
9740
+ return;
9741
+ }
9742
+ signal.addEventListener("abort", rejectStopped, { once: true });
9743
+ });
9744
+ }
9123
9745
  function parseLeaseDeadline(value) {
9124
9746
  const parsed = Date.parse(value);
9125
9747
  if (!Number.isFinite(parsed)) {
@@ -9127,7 +9749,7 @@ function parseLeaseDeadline(value) {
9127
9749
  }
9128
9750
  return parsed;
9129
9751
  }
9130
- var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, discoveryRetryMilliseconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, eventUploadRetryMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryRetryMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, LocalCodexRuntimeConnectionWorker;
9752
+ var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, defaultNetworkRetryMilliseconds, maximumNetworkRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryScanIntervalMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
9131
9753
  var init_runtime_worker = __esm({
9132
9754
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
9133
9755
  "use strict";
@@ -9138,6 +9760,7 @@ var init_runtime_worker = __esm({
9138
9760
  import_node_path11 = require("path");
9139
9761
  init_process_executor();
9140
9762
  init_relay_client();
9763
+ init_retry_backoff();
9141
9764
  init_app_server_client();
9142
9765
  init_contracts2();
9143
9766
  init_durable_attempt();
@@ -9146,19 +9769,18 @@ var init_runtime_worker = __esm({
9146
9769
  claimRetryMilliseconds = 250;
9147
9770
  claimWaitSeconds = 25;
9148
9771
  discoveryWaitSeconds = 25;
9149
- discoveryRetryMilliseconds = 1e3;
9150
9772
  maximumDiscoveryDirectories = 1e3;
9151
9773
  maximumDiscoveryModels = 100;
9152
9774
  maximumModelListPages = 10;
9153
9775
  eventUploadCoalesceMilliseconds = 500;
9154
- eventUploadRetryMilliseconds = 1e3;
9155
9776
  maximumEventUploadCount = 500;
9156
9777
  preferredEventUploadRequestBytes = 96e3;
9157
9778
  leaseRenewIntervalMilliseconds = 1e4;
9158
- leaseRenewRetryMilliseconds = 1e3;
9779
+ defaultNetworkRetryMilliseconds = 1e3;
9780
+ maximumNetworkRetryMilliseconds = 6e4;
9159
9781
  interactionTimeoutMilliseconds = 10 * 60 * 1e3;
9160
9782
  executableProbeTimeoutMilliseconds = 5e3;
9161
- recoveryRetryMilliseconds = 1e3;
9783
+ recoveryScanIntervalMilliseconds = 1e3;
9162
9784
  initialThreadNameRetryMilliseconds = 250;
9163
9785
  maximumThreadNameRetryMilliseconds = 2e3;
9164
9786
  maximumInitialThreadNameAttempts = 8;
@@ -9203,6 +9825,12 @@ var init_runtime_worker = __esm({
9203
9825
  this.name = "UnknownTurnStartResultError";
9204
9826
  }
9205
9827
  };
9828
+ WorkerStoppedError = class extends Error {
9829
+ constructor() {
9830
+ super("Local Codex Runtime worker stopped");
9831
+ this.name = "WorkerStoppedError";
9832
+ }
9833
+ };
9206
9834
  LocalCodexRuntimeConnectionWorker = class {
9207
9835
  connection;
9208
9836
  relay;
@@ -9211,15 +9839,18 @@ var init_runtime_worker = __esm({
9211
9839
  environment;
9212
9840
  connectorInstanceId;
9213
9841
  logger;
9214
- active = {};
9842
+ activeAttempts = /* @__PURE__ */ new Map();
9215
9843
  configured = false;
9216
9844
  enabled = false;
9845
+ executionTasks = /* @__PURE__ */ new Map();
9217
9846
  lastCapabilityStartError;
9218
9847
  lifetimeAbort = new AbortController();
9848
+ networkRetryMilliseconds;
9849
+ random;
9219
9850
  registered = true;
9220
9851
  unrecoverableAttemptIds = /* @__PURE__ */ new Set();
9221
9852
  running;
9222
- constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger) {
9853
+ constructor(connection, relay, store, processPool, environment, connectorInstanceId, logger, options = {}) {
9223
9854
  this.connection = connection;
9224
9855
  this.relay = relay;
9225
9856
  this.store = store;
@@ -9227,6 +9858,8 @@ var init_runtime_worker = __esm({
9227
9858
  this.environment = environment;
9228
9859
  this.connectorInstanceId = connectorInstanceId;
9229
9860
  this.logger = logger;
9861
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
9862
+ this.random = options.random ?? Math.random;
9230
9863
  this.processPool.register(connection.connectionId, this);
9231
9864
  }
9232
9865
  async run() {
@@ -9242,13 +9875,55 @@ var init_runtime_worker = __esm({
9242
9875
  }
9243
9876
  revoke() {
9244
9877
  this.lifetimeAbort.abort();
9245
- this.active.value?.finished.abort();
9878
+ for (const active of this.activeAttempts.values()) {
9879
+ active.finished.abort();
9880
+ }
9246
9881
  }
9247
9882
  status() {
9248
9883
  return this.processPool.status();
9249
9884
  }
9885
+ ownsMessage(message) {
9886
+ return this.activeAttemptForMessage(message).value !== void 0;
9887
+ }
9888
+ activeAttemptForMessage(message) {
9889
+ const threadId = appServerMessageThreadId(message).value;
9890
+ const turnId = appServerMessageTurnId(message).value;
9891
+ if (threadId === void 0 && turnId === void 0) {
9892
+ return {};
9893
+ }
9894
+ if (turnId !== void 0) {
9895
+ const exactTurnMatches = [...this.activeAttempts.values()].filter((active) => {
9896
+ if (active.finished.signal.aborted) {
9897
+ return false;
9898
+ }
9899
+ const generation = active.initialThreadName?.generation;
9900
+ const ownsTurn = active.nativeTurnId === turnId || generation?.turnId === turnId;
9901
+ return ownsTurn && (threadId === void 0 || activeOwnsThread(active, threadId));
9902
+ });
9903
+ if (exactTurnMatches.length > 0) {
9904
+ return singleActiveAttempt(exactTurnMatches);
9905
+ }
9906
+ }
9907
+ if (threadId === void 0) {
9908
+ return {};
9909
+ }
9910
+ const threadMatches = [...this.activeAttempts.values()].filter((active) => {
9911
+ if (active.finished.signal.aborted) {
9912
+ return false;
9913
+ }
9914
+ const generation = active.initialThreadName?.generation;
9915
+ const ownsVisibleThread = active.nativeThreadId === threadId;
9916
+ const ownsSubagentThread = active.subagentThreadIds.has(threadId);
9917
+ const ownsTitleThread = generation?.threadId === threadId;
9918
+ if (turnId === void 0) {
9919
+ return ownsVisibleThread || ownsSubagentThread || ownsTitleThread;
9920
+ }
9921
+ return ownsSubagentThread || ownsVisibleThread && active.nativeTurnId === void 0 || ownsTitleThread && generation?.turnId === void 0;
9922
+ });
9923
+ return singleActiveAttempt(threadMatches);
9924
+ }
9250
9925
  async onNotification(message) {
9251
- const active = this.active.value;
9926
+ const active = this.activeAttemptForMessage(message).value;
9252
9927
  if (active === void 0 || active.finished.signal.aborted) {
9253
9928
  return;
9254
9929
  }
@@ -9290,7 +9965,13 @@ var init_runtime_worker = __esm({
9290
9965
  initialThreadName.terminalObserved = true;
9291
9966
  }
9292
9967
  if (normalized.terminalStatus === LocalCodexTurnStatusWire.Interrupted) {
9293
- await this.stopInterruptedExecution(active, normalized);
9968
+ if (active.interruptedCleanupTask === void 0) {
9969
+ const task = this.stopInterruptedExecution(active, normalized).catch((error) => {
9970
+ this.signalFatal(active, error instanceof Error ? error : new Error(String(error)));
9971
+ });
9972
+ active.interruptedCleanupTask = task;
9973
+ void task;
9974
+ }
9294
9975
  return;
9295
9976
  }
9296
9977
  if (normalized.terminalStatus !== void 0 && initialThreadName !== void 0 && !initialThreadName.completed) {
@@ -9317,46 +9998,113 @@ var init_runtime_worker = __esm({
9317
9998
  void this.enqueueEventFlush(active).catch(() => void 0);
9318
9999
  }
9319
10000
  async stopInterruptedExecution(active, normalized) {
10001
+ if (active.interruptedCleanupStarted) {
10002
+ return;
10003
+ }
9320
10004
  active.interruptedCleanupStarted = true;
10005
+ active.ignoreProcessLoss = true;
9321
10006
  active.initialThreadName?.generation?.resolve();
9322
- const client = this.processPool.currentClient().value;
10007
+ const client = active.appServerClient ?? this.processPool.currentClient().value;
10008
+ let cleanupFailed = false;
9323
10009
  if (client !== void 0 && active.nativeThreadId !== void 0) {
9324
- await Promise.all([active.nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
9325
- try {
9326
- await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
9327
- } catch (error) {
9328
- await this.logger.error(`Failed to clean background terminals for interrupted Local Codex thread ${threadId}; stopping its App Server process tree`, error);
9329
- }
9330
- }));
10010
+ cleanupFailed = !await this.cleanBackgroundTerminals(active, client, "interrupted");
9331
10011
  }
9332
- try {
9333
- await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
9334
- } catch (error) {
9335
- const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
9336
- await this.enqueueSpool(active, async () => {
9337
- const terminal = await active.durable.appendEvent("turn_failed", {
9338
- message: failure.message,
9339
- status: "runtime_lost"
9340
- }, {
9341
- nativeThreadId: active.nativeThreadId,
9342
- nativeTurnId: active.nativeTurnId
10012
+ const quarantineProcess = cleanupFailed || !this.processPool.hasOtherActiveExecution();
10013
+ if (quarantineProcess) {
10014
+ active.processQuarantined = true;
10015
+ try {
10016
+ if (client === void 0) {
10017
+ await this.processPool.quarantineCurrentProcess(active.processTreeCapture);
10018
+ } else {
10019
+ await this.processPool.quarantineProcess(client, active.processTreeCapture);
10020
+ }
10021
+ } catch (error) {
10022
+ const failure = error instanceof Error ? error : new AppServerProcessLostError(String(error));
10023
+ await this.enqueueSpool(active, async () => {
10024
+ const terminal = await active.durable.appendEvent("turn_failed", {
10025
+ message: failure.message,
10026
+ status: "runtime_lost"
10027
+ }, {
10028
+ nativeThreadId: active.nativeThreadId,
10029
+ nativeTurnId: active.nativeTurnId
10030
+ });
10031
+ const result = {
10032
+ errorCode: "runtime_lost",
10033
+ errorMessage: failure.message,
10034
+ finalSequence: terminal.sequence,
10035
+ status: LocalCodexTurnStatusWire.RuntimeLost
10036
+ };
10037
+ await active.durable.markTerminal(result);
10038
+ this.settleTerminal(active, result);
9343
10039
  });
9344
- const result = {
9345
- errorCode: "runtime_lost",
9346
- errorMessage: failure.message,
9347
- finalSequence: terminal.sequence,
9348
- status: LocalCodexTurnStatusWire.RuntimeLost
9349
- };
9350
- await active.durable.markTerminal(result);
9351
- this.settleTerminal(active, result);
9352
- });
9353
- return;
10040
+ return;
10041
+ }
9354
10042
  }
9355
10043
  this.completeInitialThreadName(active);
9356
10044
  this.persistNormalizedNotification(active, normalized);
9357
10045
  }
10046
+ async cleanBackgroundTerminals(active, client, cleanupReason) {
10047
+ const nativeThreadId = active.nativeThreadId;
10048
+ if (nativeThreadId === void 0) {
10049
+ return false;
10050
+ }
10051
+ let cleanupSucceeded = true;
10052
+ await Promise.all([nativeThreadId, ...active.subagentThreadIds].map(async (threadId) => {
10053
+ try {
10054
+ await client.requestWithin("thread/backgroundTerminals/clean", { threadId }, interruptedExecutionCleanupTimeoutMilliseconds);
10055
+ } catch (error) {
10056
+ cleanupSucceeded = false;
10057
+ await this.logger.error(`Failed to clean background terminals for ${cleanupReason} Local Codex thread ${threadId}; the shared App Server is no longer trusted`, error);
10058
+ }
10059
+ }));
10060
+ return cleanupSucceeded;
10061
+ }
10062
+ async stopExecutionAfterLeaseLoss(active) {
10063
+ active.interruptedCleanupStarted = true;
10064
+ this.completeInitialThreadName(active);
10065
+ if (!active.acceptedByAppServer && !active.turnStartPending) {
10066
+ return;
10067
+ }
10068
+ const client = active.appServerClient;
10069
+ const nativeThreadId = active.nativeThreadId;
10070
+ const nativeTurnId = active.nativeTurnId;
10071
+ const targetedCleanupPossible = active.acceptedByAppServer && client !== void 0 && !client.isClosed() && nativeThreadId !== void 0 && nativeTurnId !== void 0;
10072
+ let targetedCleanupSucceeded = targetedCleanupPossible;
10073
+ if (!targetedCleanupPossible) {
10074
+ const stateReason = active.turnStartPending ? "turn/start has no trusted result yet" : "the accepted native Turn or App Server client is unavailable";
10075
+ 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));
10076
+ }
10077
+ if (targetedCleanupSucceeded && client !== void 0 && nativeThreadId !== void 0 && nativeTurnId !== void 0) {
10078
+ try {
10079
+ await client.requestWithin("turn/interrupt", {
10080
+ threadId: nativeThreadId,
10081
+ turnId: nativeTurnId
10082
+ }, interruptedExecutionCleanupTimeoutMilliseconds);
10083
+ this.processPool.retireTurn(nativeTurnId);
10084
+ } catch (error) {
10085
+ targetedCleanupSucceeded = false;
10086
+ 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);
10087
+ }
10088
+ const terminalsCleaned = await this.cleanBackgroundTerminals(active, client, "lease-lost");
10089
+ targetedCleanupSucceeded = targetedCleanupSucceeded && terminalsCleaned;
10090
+ }
10091
+ if (targetedCleanupSucceeded) {
10092
+ return;
10093
+ }
10094
+ active.ignoreProcessLoss = true;
10095
+ active.processQuarantined = true;
10096
+ try {
10097
+ if (client === void 0) {
10098
+ await this.processPool.quarantineCurrentProcess();
10099
+ } else {
10100
+ await this.processPool.quarantineProcess(client);
10101
+ }
10102
+ } catch (error) {
10103
+ 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);
10104
+ }
10105
+ }
9358
10106
  async onServerRequest(message) {
9359
- const active = this.active.value;
10107
+ const active = this.activeAttemptForMessage(message).value;
9360
10108
  const client = this.processPool.currentClient().value;
9361
10109
  const requestId = rpcIdentifier2(message.id).value;
9362
10110
  if (active === void 0 || client === void 0 || requestId === void 0 || message.method === void 0) {
@@ -9398,46 +10146,50 @@ var init_runtime_worker = __esm({
9398
10146
  await this.enqueueEventFlush(active);
9399
10147
  }
9400
10148
  async onProcessExit(error) {
9401
- const active = this.active.value;
9402
- if (active === void 0 || !active.acceptedByAppServer) {
9403
- return;
9404
- }
9405
- active.initialThreadName?.generation?.resolve();
9406
- await this.enqueueSpool(active, async () => {
9407
- await active.durable.appendEvent("runtime_error", { message: error.message }, {
9408
- nativeThreadId: active.nativeThreadId,
9409
- nativeTurnId: active.nativeTurnId
9410
- });
9411
- const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
9412
- nativeThreadId: active.nativeThreadId,
9413
- nativeTurnId: active.nativeTurnId
10149
+ await Promise.all([...this.activeAttempts.values()].filter((active) => active.acceptedByAppServer && !active.finished.signal.aborted && !active.ignoreProcessLoss && active.terminalValue === void 0).map(async (active) => {
10150
+ active.initialThreadName?.generation?.resolve();
10151
+ await this.enqueueSpool(active, async () => {
10152
+ await active.durable.appendEvent("runtime_error", { message: error.message }, {
10153
+ nativeThreadId: active.nativeThreadId,
10154
+ nativeTurnId: active.nativeTurnId
10155
+ });
10156
+ const terminal = await active.durable.appendEvent("turn_failed", { status: "runtime_lost" }, {
10157
+ nativeThreadId: active.nativeThreadId,
10158
+ nativeTurnId: active.nativeTurnId
10159
+ });
10160
+ const result = {
10161
+ errorCode: "runtime_lost",
10162
+ errorMessage: error.message,
10163
+ finalSequence: terminal.sequence,
10164
+ status: LocalCodexTurnStatusWire.RuntimeLost
10165
+ };
10166
+ await active.durable.markTerminal(result);
10167
+ this.settleTerminal(active, result);
9414
10168
  });
9415
- const result = {
9416
- errorCode: "runtime_lost",
9417
- errorMessage: error.message,
9418
- finalSequence: terminal.sequence,
9419
- status: LocalCodexTurnStatusWire.RuntimeLost
9420
- };
9421
- await active.durable.markTerminal(result);
9422
- this.settleTerminal(active, result);
9423
- });
10169
+ }));
9424
10170
  }
9425
10171
  async runLoops() {
9426
10172
  try {
9427
10173
  await Promise.all([
9428
10174
  this.runHeartbeatLoop(),
9429
- this.runClaimLoop(),
9430
10175
  this.runDiscoveryLoop(),
9431
- this.runRecoveryLoop()
10176
+ this.runAttemptLoops()
9432
10177
  ]);
9433
10178
  } finally {
9434
- this.active.value?.finished.abort();
10179
+ for (const active of this.activeAttempts.values()) {
10180
+ active.finished.abort();
10181
+ }
10182
+ await Promise.all(this.executionTasks.values());
9435
10183
  this.unregisterRoute();
9436
10184
  }
9437
10185
  }
10186
+ async runAttemptLoops() {
10187
+ await this.scanPersistedAttempts();
10188
+ await Promise.all([this.runClaimLoop(), this.runRecoveryLoop()]);
10189
+ }
9438
10190
  async runHeartbeatLoop() {
9439
10191
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9440
- if (this.active.value?.interruptedCleanupStarted) {
10192
+ if ([...this.activeAttempts.values()].some((active) => active.interruptedCleanupStarted)) {
9441
10193
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9442
10194
  continue;
9443
10195
  }
@@ -9446,23 +10198,27 @@ var init_runtime_worker = __esm({
9446
10198
  const response = await this.sendHeartbeat();
9447
10199
  this.applyHeartbeatResponse(response);
9448
10200
  } catch (error) {
9449
- if (!this.lifetimeAbort.signal.aborted) {
9450
- await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
10201
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10202
+ return;
9451
10203
  }
10204
+ await this.logger.error(`Local Codex Runtime heartbeat failed for connection ${this.connection.connectionId}`, error);
9452
10205
  }
9453
10206
  await waitForAbort(this.lifetimeAbort.signal, heartbeatIntervalMilliseconds);
9454
10207
  }
9455
10208
  }
9456
10209
  async runClaimLoop() {
10210
+ const retryBackoff = this.createNetworkRetryBackoff();
9457
10211
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9458
10212
  if (!this.configured || !this.enabled || !this.runtimeReady()) {
9459
10213
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9460
10214
  continue;
9461
10215
  }
9462
- if (!this.processPool.tryAcquire(this.connection.connectionId)) {
10216
+ const slot = this.processPool.tryAcquireExecutionSlot(this.connection.connectionId).value;
10217
+ if (slot === void 0) {
9463
10218
  await waitForAbort(this.lifetimeAbort.signal, claimRetryMilliseconds);
9464
10219
  continue;
9465
10220
  }
10221
+ let executionScheduled = false;
9466
10222
  try {
9467
10223
  const capability = this.processPool.status();
9468
10224
  const response = await this.relay.claimCodexRuntime({
@@ -9473,22 +10229,46 @@ var init_runtime_worker = __esm({
9473
10229
  waitSeconds: claimWaitSeconds
9474
10230
  }, this.lifetimeAbort.signal);
9475
10231
  if (response.attempt === void 0) {
9476
- this.processPool.release(this.connection.connectionId);
10232
+ retryBackoff.reset();
9477
10233
  continue;
9478
10234
  }
9479
- await this.executeAttempt(response.attempt);
10235
+ const reclaimableClaimWindow = this.scheduleExecution(slot, response.attempt);
10236
+ executionScheduled = true;
10237
+ await reclaimableClaimWindow.completion;
10238
+ if (reclaimableClaimWindow.isAccepted()) {
10239
+ retryBackoff.reset();
10240
+ } else {
10241
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10242
+ }
9480
10243
  } catch (error) {
9481
- if (!this.lifetimeAbort.signal.aborted) {
9482
- await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
9483
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10244
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10245
+ return;
9484
10246
  }
10247
+ await this.logger.error(`Local Codex Runtime claim loop failed for connection ${this.connection.connectionId}`, error);
10248
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
9485
10249
  } finally {
9486
- this.active = {};
9487
- this.processPool.release(this.connection.connectionId);
10250
+ if (!executionScheduled) {
10251
+ this.processPool.releaseExecutionSlot(slot);
10252
+ }
9488
10253
  }
9489
10254
  }
9490
10255
  }
10256
+ scheduleExecution(slot, claim) {
10257
+ if (this.executionTasks.has(claim.attemptId)) {
10258
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already executing`);
10259
+ }
10260
+ this.processPool.markExecutionStarted(slot);
10261
+ const reclaimableClaimWindow = createReclaimableClaimWindow();
10262
+ const task = this.executeAttempt(claim, reclaimableClaimWindow).catch(async (error) => await this.logger.error(`Local Codex attempt ${claim.attemptId} execution crashed`, error).catch(() => void 0)).finally(() => {
10263
+ reclaimableClaimWindow.close();
10264
+ this.executionTasks.delete(claim.attemptId);
10265
+ this.processPool.releaseExecutionSlot(slot);
10266
+ });
10267
+ this.executionTasks.set(claim.attemptId, task);
10268
+ return reclaimableClaimWindow;
10269
+ }
9491
10270
  async runDiscoveryLoop() {
10271
+ const retryBackoff = this.createNetworkRetryBackoff();
9492
10272
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9493
10273
  try {
9494
10274
  const response = await this.relay.claimCodexRuntimeDiscovery({
@@ -9497,14 +10277,17 @@ var init_runtime_worker = __esm({
9497
10277
  waitSeconds: discoveryWaitSeconds
9498
10278
  }, this.lifetimeAbort.signal);
9499
10279
  if (response.request === void 0) {
10280
+ retryBackoff.reset();
9500
10281
  continue;
9501
10282
  }
9502
10283
  await this.completeDiscovery(response.request);
10284
+ retryBackoff.reset();
9503
10285
  } catch (error) {
9504
- if (!this.lifetimeAbort.signal.aborted) {
9505
- await this.logger.error(`Local Codex discovery loop failed for connection ${this.connection.connectionId}`, error);
9506
- await waitForAbort(this.lifetimeAbort.signal, discoveryRetryMilliseconds);
10286
+ if (this.lifetimeAbort.signal.aborted || this.relay.isRevoked()) {
10287
+ return;
9507
10288
  }
10289
+ await this.logger.error(`Local Codex discovery loop failed for connection ${this.connection.connectionId}`, error);
10290
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
9508
10291
  }
9509
10292
  }
9510
10293
  }
@@ -9520,7 +10303,7 @@ var init_runtime_worker = __esm({
9520
10303
  status: LocalCodexDiscoveryStatusWire.Failed
9521
10304
  };
9522
10305
  }
9523
- const completion = await this.relay.completeCodexRuntimeDiscovery(request2.requestId, this.connectorInstanceId, result);
10306
+ const completion = await this.relay.completeCodexRuntimeDiscovery(request2.requestId, this.connectorInstanceId, result, this.lifetimeAbort.signal);
9524
10307
  if (!completion.accepted) {
9525
10308
  await this.logger.info(`Local Codex discovery request ${request2.requestId} expired before completion`);
9526
10309
  }
@@ -9587,15 +10370,29 @@ var init_runtime_worker = __esm({
9587
10370
  truncated: eligibleDirectories.length > maximumDiscoveryDirectories
9588
10371
  };
9589
10372
  }
9590
- async executeAttempt(claim) {
10373
+ async executeAttempt(claim, reclaimableClaimWindow) {
9591
10374
  const durable = await DurableLocalCodexAttempt.create(this.store, this.connection.connectionId, this.connectorInstanceId, claim);
10375
+ if (durable.requiresRecovery()) {
10376
+ await this.recoverPersistedAttempt(durable.snapshot());
10377
+ reclaimableClaimWindow.accept();
10378
+ return;
10379
+ }
9592
10380
  const active = createActiveAttempt(claim, durable, this.connection.rootPath);
9593
- this.active = { value: active };
10381
+ if (this.activeAttempts.has(claim.attemptId)) {
10382
+ throw new Error(`Local Codex attempt ${claim.attemptId} is already active`);
10383
+ }
10384
+ this.activeAttempts.set(claim.attemptId, active);
9594
10385
  const leaseLoop = this.runLeaseLoop(active);
9595
10386
  const controlLoop = this.runControlLoop(active);
9596
10387
  try {
9597
10388
  active.workingDirectory = await resolveCanonicalWorkingDirectory(this.connection.rootPath, claim.relativeWorkingDirectory);
10389
+ if (active.fatalError !== void 0) {
10390
+ throw active.fatalError;
10391
+ }
9598
10392
  let client = await this.processPool.ensureStarted();
10393
+ if (active.fatalError !== void 0) {
10394
+ throw active.fatalError;
10395
+ }
9599
10396
  const isNewThread = active.nativeThreadId === void 0;
9600
10397
  let nativeThreadId;
9601
10398
  try {
@@ -9609,6 +10406,10 @@ var init_runtime_worker = __esm({
9609
10406
  nativeThreadId = await this.prepareThread(client, active);
9610
10407
  }
9611
10408
  active.nativeThreadId = nativeThreadId;
10409
+ active.appServerClient = client;
10410
+ if (active.fatalError !== void 0) {
10411
+ throw active.fatalError;
10412
+ }
9612
10413
  await durable.markThreadPrepared(nativeThreadId);
9613
10414
  await active.spoolQueue;
9614
10415
  if (isNewThread) {
@@ -9620,7 +10421,11 @@ var init_runtime_worker = __esm({
9620
10421
  if (isNewThread && !active.durable.snapshot().events.some((event2) => event2.kind === "thread_started")) {
9621
10422
  await active.durable.appendEvent("thread_started", {}, { nativeThreadId });
9622
10423
  }
10424
+ if (active.fatalError !== void 0) {
10425
+ throw active.fatalError;
10426
+ }
9623
10427
  let response;
10428
+ active.turnStartPending = true;
9624
10429
  try {
9625
10430
  response = await client.request("turn/start", {
9626
10431
  approvalPolicy: claim.approvalPolicy,
@@ -9637,6 +10442,8 @@ var init_runtime_worker = __esm({
9637
10442
  throw new UnknownTurnStartResultError("Codex App Server turn/start result is unknown; the process generation was quarantined", { cause: error });
9638
10443
  }
9639
10444
  throw error;
10445
+ } finally {
10446
+ active.turnStartPending = false;
9640
10447
  }
9641
10448
  const nativeTurnId = requireTurnId(response);
9642
10449
  if (active.nativeTurnId !== void 0 && active.nativeTurnId !== nativeTurnId) {
@@ -9662,12 +10469,14 @@ var init_runtime_worker = __esm({
9662
10469
  nativeTurnId,
9663
10470
  status: LocalCodexTurnStatusWire.Running
9664
10471
  });
10472
+ reclaimableClaimWindow.accept();
9665
10473
  await this.interruptActiveTurnIfRequested(active, client);
9666
10474
  const terminal = await Promise.race([
9667
10475
  active.terminal,
9668
10476
  active.fatal.then((error) => {
9669
10477
  throw error;
9670
- })
10478
+ }),
10479
+ rejectWhenAborted(active.finished.signal)
9671
10480
  ]);
9672
10481
  await active.spoolQueue;
9673
10482
  await this.flushAllEvents(active);
@@ -9681,12 +10490,13 @@ var init_runtime_worker = __esm({
9681
10490
  });
9682
10491
  await durable.markUploaded();
9683
10492
  await this.store.deleteLocalCodexAttempt(claim.attemptId);
9684
- if (active.interruptedCleanupStarted) {
10493
+ if (active.processQuarantined) {
9685
10494
  active.finished.abort();
9686
10495
  await this.restoreAppServerAfterInterruption(active);
9687
10496
  }
9688
10497
  } catch (error) {
9689
- if (error instanceof LeaseLostError) {
10498
+ if (error instanceof WorkerStoppedError) {
10499
+ } else if (error instanceof LeaseLostError) {
9690
10500
  await this.logger.error(`Local Codex attempt ${claim.attemptId} stopped after losing its execution lease`, error);
9691
10501
  } else if (error instanceof SpoolPersistenceError) {
9692
10502
  try {
@@ -9701,17 +10511,23 @@ var init_runtime_worker = __esm({
9701
10511
  await this.failAttempt(active, error);
9702
10512
  }
9703
10513
  } finally {
9704
- this.completeInitialThreadName(active);
9705
- active.finished.abort();
9706
- await active.initialThreadName?.task;
9707
- const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
9708
- if (titleGenerationTurnId !== void 0) {
9709
- this.processPool.retireTurn(titleGenerationTurnId);
9710
- }
9711
- if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
9712
- this.processPool.retireTurn(active.nativeTurnId);
10514
+ try {
10515
+ this.completeInitialThreadName(active);
10516
+ active.finished.abort();
10517
+ await active.interruptedCleanupTask;
10518
+ await active.leaseLossCleanupTask;
10519
+ await active.initialThreadName?.task;
10520
+ const titleGenerationTurnId = active.initialThreadName?.generation?.turnId;
10521
+ if (titleGenerationTurnId !== void 0) {
10522
+ this.processPool.retireTurn(titleGenerationTurnId);
10523
+ }
10524
+ if (active.acceptedByAppServer && active.nativeTurnId !== void 0) {
10525
+ this.processPool.retireTurn(active.nativeTurnId);
10526
+ }
10527
+ await Promise.all([leaseLoop, controlLoop]);
10528
+ } finally {
10529
+ this.activeAttempts.delete(claim.attemptId);
9713
10530
  }
9714
- await Promise.all([leaseLoop, controlLoop]);
9715
10531
  }
9716
10532
  }
9717
10533
  async prepareThread(client, active) {
@@ -9796,15 +10612,24 @@ var init_runtime_worker = __esm({
9796
10612
  }
9797
10613
  }
9798
10614
  async runRecoveryLoop() {
10615
+ const retryBackoff = this.createNetworkRetryBackoff();
9799
10616
  while (!this.lifetimeAbort.signal.aborted && !this.relay.isRevoked()) {
9800
- try {
9801
- await this.recoverPersistedAttempts();
9802
- } catch (error) {
9803
- if (!this.lifetimeAbort.signal.aborted) {
9804
- await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
9805
- }
10617
+ const scanSucceeded = await this.scanPersistedAttempts();
10618
+ if (scanSucceeded) {
10619
+ retryBackoff.reset();
10620
+ }
10621
+ await waitForAbort(this.lifetimeAbort.signal, scanSucceeded ? recoveryScanIntervalMilliseconds : retryBackoff.nextDelayMilliseconds());
10622
+ }
10623
+ }
10624
+ async scanPersistedAttempts() {
10625
+ try {
10626
+ await this.recoverPersistedAttempts();
10627
+ return true;
10628
+ } catch (error) {
10629
+ if (!this.lifetimeAbort.signal.aborted) {
10630
+ await this.logger.error(`Failed to scan persisted Local Codex attempts for connection ${this.connection.connectionId}`, error);
9806
10631
  }
9807
- await waitForAbort(this.lifetimeAbort.signal, recoveryRetryMilliseconds);
10632
+ return false;
9808
10633
  }
9809
10634
  }
9810
10635
  async recoverPersistedAttempts() {
@@ -9816,10 +10641,12 @@ var init_runtime_worker = __esm({
9816
10641
  try {
9817
10642
  await this.recoverPersistedAttempt(persisted);
9818
10643
  } catch (error) {
9819
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10644
+ if (isPermanentRelayFailure(error)) {
9820
10645
  this.unrecoverableAttemptIds.add(persisted.claim.attemptId);
10646
+ await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10647
+ continue;
9821
10648
  }
9822
- await this.logger.error(`Failed to recover Local Codex attempt ${persisted.claim.attemptId}`, error);
10649
+ throw error;
9823
10650
  }
9824
10651
  }
9825
10652
  }
@@ -9875,13 +10702,15 @@ var init_runtime_worker = __esm({
9875
10702
  await this.store.deleteLocalCodexAttempt(snapshot.claim.attemptId);
9876
10703
  }
9877
10704
  async runLeaseLoop(active) {
10705
+ const retryBackoff = this.createNetworkRetryBackoff();
10706
+ let nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
9878
10707
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
9879
10708
  const remaining = active.leaseDeadlineMilliseconds - Date.now();
9880
10709
  if (remaining <= 0) {
9881
10710
  await this.loseLease(active, "Local Codex execution lease expired");
9882
10711
  return;
9883
10712
  }
9884
- await waitForAbort(active.finished.signal, Math.min(leaseRenewIntervalMilliseconds, remaining));
10713
+ await waitForAbort(active.finished.signal, Math.min(nextRenewalDelayMilliseconds, remaining));
9885
10714
  if (active.finished.signal.aborted) {
9886
10715
  return;
9887
10716
  }
@@ -9892,12 +10721,14 @@ var init_runtime_worker = __esm({
9892
10721
  try {
9893
10722
  const response = await this.renewLeaseBeforeDeadline(active);
9894
10723
  active.leaseDeadlineMilliseconds = parseLeaseDeadline(response.leaseExpiresAt);
10724
+ retryBackoff.reset();
10725
+ nextRenewalDelayMilliseconds = leaseRenewIntervalMilliseconds;
9895
10726
  } catch (error) {
9896
10727
  if (active.finished.signal.aborted) {
9897
10728
  return;
9898
10729
  }
9899
10730
  await this.logger.error(`Failed to renew Local Codex attempt ${active.claim.attemptId}`, error);
9900
- if (error instanceof LeaseLostError || error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10731
+ if (error instanceof LeaseLostError || isPermanentRelayFailure(error)) {
9901
10732
  await this.loseLease(active, errorMessage3(error));
9902
10733
  return;
9903
10734
  }
@@ -9906,7 +10737,7 @@ var init_runtime_worker = __esm({
9906
10737
  await this.loseLease(active, "Local Codex execution lease expired");
9907
10738
  return;
9908
10739
  }
9909
- await waitForAbort(active.finished.signal, Math.min(leaseRenewRetryMilliseconds, retryRemaining));
10740
+ nextRenewalDelayMilliseconds = Math.min(retryBackoff.nextDelayMilliseconds(), retryRemaining);
9910
10741
  }
9911
10742
  }
9912
10743
  }
@@ -9936,11 +10767,19 @@ var init_runtime_worker = __esm({
9936
10767
  }
9937
10768
  }
9938
10769
  async loseLease(active, message) {
9939
- const error = new LeaseLostError(message);
9940
- this.signalFatal(active, error);
9941
- await this.processPool.quarantineCurrentProcess();
10770
+ if (active.leaseLossCleanupTask !== void 0) {
10771
+ await active.leaseLossCleanupTask;
10772
+ return;
10773
+ }
10774
+ const cleanupTask = Promise.resolve().then(async () => {
10775
+ await this.stopExecutionAfterLeaseLoss(active);
10776
+ });
10777
+ active.leaseLossCleanupTask = cleanupTask;
10778
+ this.signalFatal(active, new LeaseLostError(message));
10779
+ await cleanupTask;
9942
10780
  }
9943
10781
  async runControlLoop(active) {
10782
+ const retryBackoff = this.createNetworkRetryBackoff();
9944
10783
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
9945
10784
  try {
9946
10785
  const page = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
@@ -9948,14 +10787,15 @@ var init_runtime_worker = __esm({
9948
10787
  await this.applyControl(active, control);
9949
10788
  active.controlCursor = Math.max(active.controlCursor, control.cursor);
9950
10789
  }
10790
+ retryBackoff.reset();
9951
10791
  } catch (error) {
9952
10792
  if (!active.finished.signal.aborted) {
9953
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10793
+ if (isPermanentRelayFailure(error)) {
9954
10794
  await this.loseLease(active, errorMessage3(error));
9955
10795
  return;
9956
10796
  }
9957
10797
  await this.logger.error(`Failed to poll Local Codex controls for ${active.claim.attemptId}`, error);
9958
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10798
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
9959
10799
  }
9960
10800
  }
9961
10801
  }
@@ -9964,7 +10804,7 @@ var init_runtime_worker = __esm({
9964
10804
  await active.durable.recordControl(control.controlId);
9965
10805
  const previouslyApplied = active.durable.appliedControlOutcome(control.controlId).value;
9966
10806
  if (previouslyApplied !== void 0) {
9967
- await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, previouslyApplied);
10807
+ await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, previouslyApplied, active.finished.signal);
9968
10808
  return;
9969
10809
  }
9970
10810
  const client = this.processPool.currentClient().value;
@@ -9988,7 +10828,7 @@ var init_runtime_worker = __esm({
9988
10828
  outcome = await this.applySteerControl(active, control);
9989
10829
  }
9990
10830
  await active.durable.markControlApplied(control.controlId, outcome);
9991
- await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, outcome);
10831
+ await this.relay.acknowledgeCodexRuntimeControl(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), control.controlId, outcome, active.finished.signal);
9992
10832
  }
9993
10833
  async applySteerControl(active, control) {
9994
10834
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
@@ -10024,7 +10864,9 @@ var init_runtime_worker = __esm({
10024
10864
  if (!active.abortRequested || active.abortSent || active.nativeThreadId === void 0 || active.nativeTurnId === void 0) {
10025
10865
  return;
10026
10866
  }
10027
- active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10867
+ if (!this.processPool.hasOtherActiveExecution()) {
10868
+ active.processTreeCapture = (await this.processPool.captureCurrentProcessTree()).value;
10869
+ }
10028
10870
  await client.request("turn/interrupt", {
10029
10871
  threadId: active.nativeThreadId,
10030
10872
  turnId: active.nativeTurnId
@@ -10094,41 +10936,52 @@ var init_runtime_worker = __esm({
10094
10936
  }
10095
10937
  async flushAllEvents(active) {
10096
10938
  await active.eventUploadQueue.catch(() => void 0);
10939
+ const retryBackoff = this.createNetworkRetryBackoff();
10097
10940
  while (active.durable.pendingEvents().length > 0) {
10098
10941
  if (active.fatalError !== void 0) {
10099
10942
  throw active.fatalError;
10100
10943
  }
10101
10944
  try {
10102
10945
  await this.flushEvents(active);
10946
+ retryBackoff.reset();
10103
10947
  } catch (error) {
10104
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10948
+ if (isPermanentRelayFailure(error)) {
10105
10949
  throw error;
10106
10950
  }
10107
10951
  if (active.finished.signal.aborted || this.lifetimeAbort.signal.aborted) {
10108
10952
  throw error;
10109
10953
  }
10110
- await waitForAbort(active.finished.signal, eventUploadRetryMilliseconds);
10954
+ await waitForAbort(active.finished.signal, retryBackoff.nextDelayMilliseconds());
10111
10955
  }
10112
10956
  }
10113
10957
  }
10114
10958
  async retryStateUpdate(active, state) {
10959
+ const retryBackoff = this.createNetworkRetryBackoff();
10115
10960
  while (!this.lifetimeAbort.signal.aborted) {
10116
10961
  if (active.fatalError !== void 0) {
10117
10962
  throw active.fatalError;
10118
10963
  }
10119
10964
  try {
10120
10965
  await this.relay.updateCodexRuntimeState(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), state);
10966
+ retryBackoff.reset();
10121
10967
  return;
10122
10968
  } catch (error) {
10123
- if (error instanceof RelayHttpError && error.status >= 400 && error.status < 500) {
10969
+ if (isPermanentRelayFailure(error)) {
10124
10970
  throw error;
10125
10971
  }
10126
10972
  await this.logger.error(`Failed to update Local Codex state for ${active.claim.attemptId}`, error);
10127
- await waitForAbort(this.lifetimeAbort.signal, eventUploadRetryMilliseconds);
10973
+ await waitForAbort(this.lifetimeAbort.signal, retryBackoff.nextDelayMilliseconds());
10128
10974
  }
10129
10975
  }
10130
10976
  throw new Error("Local Codex Runtime stopped before state ACK");
10131
10977
  }
10978
+ createNetworkRetryBackoff() {
10979
+ return new RetryBackoff({
10980
+ maximumMilliseconds: maximumNetworkRetryMilliseconds,
10981
+ minimumMilliseconds: this.networkRetryMilliseconds,
10982
+ random: this.random
10983
+ });
10984
+ }
10132
10985
  settleTerminal(active, terminal) {
10133
10986
  if (active.terminalValue !== void 0) {
10134
10987
  return;
@@ -10196,7 +11049,7 @@ var init_runtime_worker = __esm({
10196
11049
  moxtCliVersion: moxt.version,
10197
11050
  protocolVersion: localCodexRuntimeProtocolVersion,
10198
11051
  ...unavailableReason === void 0 ? {} : { unavailableReason }
10199
- });
11052
+ }, this.lifetimeAbort.signal);
10200
11053
  }
10201
11054
  applyHeartbeatResponse(response) {
10202
11055
  this.configured = response.configured;
@@ -10388,7 +11241,6 @@ ${titleInput}`,
10388
11241
  if (!this.registered) {
10389
11242
  return;
10390
11243
  }
10391
- this.processPool.release(this.connection.connectionId);
10392
11244
  this.processPool.unregister(this.connection.connectionId);
10393
11245
  this.registered = false;
10394
11246
  }
@@ -10407,18 +11259,20 @@ function localCodexProcessPoolKey(environment, nativeStoreIdentitySeed) {
10407
11259
  "connector-owned-app-server-stdio-v1"
10408
11260
  ].join("\0")).digest("hex");
10409
11261
  }
10410
- var import_node_crypto8, LocalCodexProcessPool;
11262
+ var import_node_crypto8, maximumConcurrentTurns, LocalCodexProcessPool;
10411
11263
  var init_process_pool = __esm({
10412
11264
  "../machine-connector/dist/runtime/local-codex-runtime/process-pool.js"() {
10413
11265
  "use strict";
10414
11266
  init_cjs_shims();
10415
11267
  import_node_crypto8 = require("crypto");
10416
11268
  init_app_server_client();
11269
+ maximumConcurrentTurns = 1e3;
10417
11270
  LocalCodexProcessPool = class {
10418
11271
  poolKey;
10419
11272
  logger;
10420
- activeOwner = {};
11273
+ activeSlots = /* @__PURE__ */ new Map();
10421
11274
  loadedThreadIds = /* @__PURE__ */ new Set();
11275
+ nextSlotId = 1;
10422
11276
  routes = /* @__PURE__ */ new Map();
10423
11277
  retiredTurnIds = /* @__PURE__ */ new Set();
10424
11278
  supervisor;
@@ -10428,7 +11282,7 @@ var init_process_pool = __esm({
10428
11282
  this.logger = logger;
10429
11283
  this.supervisor = new LocalCodexAppServerSupervisor(environment.HOME ?? process.cwd(), environment, nativeStoreIdentitySeed, {
10430
11284
  onNotification: async (message) => {
10431
- await this.activeRoute().value?.onNotification(message);
11285
+ await this.routeNotification(message);
10432
11286
  },
10433
11287
  onProcessExit: async (error, processGeneration) => {
10434
11288
  if (!this.supervisor.markProcessLost(processGeneration)) {
@@ -10436,18 +11290,10 @@ var init_process_pool = __esm({
10436
11290
  }
10437
11291
  this.loadedThreadIds.clear();
10438
11292
  await this.logger.error(`Shared Codex App Server generation ${processGeneration} exited`, error);
10439
- await this.activeRoute().value?.onProcessExit(error);
11293
+ await this.broadcastProcessExit(error);
10440
11294
  },
10441
11295
  onServerRequest: async (message) => {
10442
- const route = this.activeRoute().value;
10443
- if (route !== void 0) {
10444
- await route.onServerRequest(message);
10445
- return;
10446
- }
10447
- const client = this.supervisor.currentClient().value;
10448
- if (client !== void 0 && message.id !== void 0) {
10449
- await client.respondWithError(message.id, -32e3, "No owning Local Codex Runtime turn");
10450
- }
11296
+ await this.routeServerRequest(message);
10451
11297
  },
10452
11298
  onStderr: async (text3) => {
10453
11299
  await this.logger.info("Codex App Server stderr", {
@@ -10465,7 +11311,7 @@ var init_process_pool = __esm({
10465
11311
  this.routes.set(ownerId, route);
10466
11312
  }
10467
11313
  unregister(ownerId) {
10468
- if (this.activeOwner.value === ownerId) {
11314
+ if ([...this.activeSlots.values()].some((slot) => slot.ownerId === ownerId)) {
10469
11315
  throw new Error(`Local Codex route ${ownerId} still owns capacity`);
10470
11316
  }
10471
11317
  this.routes.delete(ownerId);
@@ -10474,27 +11320,35 @@ var init_process_pool = __esm({
10474
11320
  this.waitingOwners.splice(index2, 1);
10475
11321
  }
10476
11322
  }
10477
- tryAcquire(ownerId) {
11323
+ tryAcquireExecutionSlot(ownerId) {
10478
11324
  if (!this.routes.has(ownerId)) {
10479
11325
  throw new Error(`Local Codex route ${ownerId} is not registered`);
10480
11326
  }
10481
- if (this.activeOwner.value === ownerId) {
10482
- return true;
10483
- }
10484
11327
  if (!this.waitingOwners.includes(ownerId)) {
10485
11328
  this.waitingOwners.push(ownerId);
10486
11329
  }
10487
- if (this.activeOwner.value !== void 0 || this.waitingOwners[0] !== ownerId) {
10488
- return false;
11330
+ if (this.activeSlots.size >= maximumConcurrentTurns || this.waitingOwners[0] !== ownerId) {
11331
+ return {};
10489
11332
  }
10490
11333
  this.waitingOwners.shift();
10491
- this.activeOwner = { value: ownerId };
10492
- return true;
11334
+ const value = { ownerId, slotId: this.nextSlotId };
11335
+ this.nextSlotId += 1;
11336
+ this.activeSlots.set(value.slotId, { executing: false, ownerId });
11337
+ return { value };
10493
11338
  }
10494
- release(ownerId) {
10495
- if (this.activeOwner.value === ownerId) {
10496
- this.activeOwner = {};
11339
+ markExecutionStarted(slot) {
11340
+ const active = this.requireActiveSlot(slot);
11341
+ if (active.executing) {
11342
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is already executing`);
10497
11343
  }
11344
+ active.executing = true;
11345
+ }
11346
+ releaseExecutionSlot(slot) {
11347
+ this.requireActiveSlot(slot);
11348
+ this.activeSlots.delete(slot.slotId);
11349
+ }
11350
+ hasOtherActiveExecution() {
11351
+ return [...this.activeSlots.values()].filter((slot) => slot.executing).length > 1;
10498
11352
  }
10499
11353
  retireTurn(nativeTurnId) {
10500
11354
  this.retiredTurnIds.add(nativeTurnId);
@@ -10539,29 +11393,87 @@ var init_process_pool = __esm({
10539
11393
  return client === void 0 ? {} : { value: await client.captureProcessTree() };
10540
11394
  }
10541
11395
  async quarantineCurrentProcess(capture) {
11396
+ const processGeneration = this.supervisor.currentClient().value?.processGeneration;
10542
11397
  this.loadedThreadIds.clear();
10543
- await this.supervisor.quarantineCurrentProcess(capture);
11398
+ try {
11399
+ await this.supervisor.quarantineCurrentProcess(capture);
11400
+ } finally {
11401
+ if (processGeneration !== void 0) {
11402
+ await this.broadcastProcessExit(new AppServerProcessLostError(`Shared Codex App Server generation ${processGeneration} was quarantined`));
11403
+ }
11404
+ }
11405
+ }
11406
+ async quarantineProcess(client, capture) {
11407
+ if (this.supervisor.currentClient().value === client) {
11408
+ await this.quarantineCurrentProcess(capture);
11409
+ return;
11410
+ }
11411
+ await client.stop(capture);
10544
11412
  }
10545
11413
  async stop() {
10546
11414
  this.loadedThreadIds.clear();
10547
11415
  await this.supervisor.stop();
10548
11416
  }
10549
- activeRoute() {
10550
- const owner = this.activeOwner.value;
10551
- if (owner === void 0) {
10552
- return {};
11417
+ matchingRoutes(message) {
11418
+ return [...this.routes.values()].filter((route) => route.ownsMessage(message));
11419
+ }
11420
+ async routeNotification(message) {
11421
+ const routes = this.matchingRoutes(message);
11422
+ if (routes.length === 0) {
11423
+ return;
11424
+ }
11425
+ if (routes.length > 1) {
11426
+ await this.logger.error("Local Codex App Server notification matched multiple runtime routes", new Error(message.method ?? "Unknown App Server notification"));
11427
+ return;
11428
+ }
11429
+ const route = routes[0];
11430
+ if (route === void 0) {
11431
+ throw new Error("Expected one Local Codex notification route");
11432
+ }
11433
+ await route.onNotification(message);
11434
+ }
11435
+ async routeServerRequest(message) {
11436
+ const routes = this.matchingRoutes(message);
11437
+ if (routes.length === 1) {
11438
+ const route = routes[0];
11439
+ if (route === void 0) {
11440
+ throw new Error("Expected one Local Codex request route");
11441
+ }
11442
+ await route.onServerRequest(message);
11443
+ return;
11444
+ }
11445
+ if (routes.length > 1) {
11446
+ await this.logger.error("Local Codex App Server request matched multiple runtime routes", new Error(message.method ?? "Unknown App Server request"));
11447
+ }
11448
+ const client = this.supervisor.currentClient().value;
11449
+ if (client !== void 0 && message.id !== void 0) {
11450
+ await client.respondWithError(message.id, -32e3, routes.length === 0 ? "No owning Local Codex Runtime turn" : "Ambiguous Local Codex Runtime turn ownership");
11451
+ }
11452
+ }
11453
+ async broadcastProcessExit(error) {
11454
+ await Promise.all([...this.routes.values()].map(async (route) => {
11455
+ try {
11456
+ await route.onProcessExit(error);
11457
+ } catch (routeError) {
11458
+ await this.logger.error("Failed to settle a Local Codex route after the shared App Server exited", routeError).catch(() => void 0);
11459
+ }
11460
+ }));
11461
+ }
11462
+ requireActiveSlot(slot) {
11463
+ const active = this.activeSlots.get(slot.slotId);
11464
+ if (active === void 0) {
11465
+ throw new Error(`Local Codex capacity slot ${slot.slotId} is not active`);
10553
11466
  }
10554
- const value = this.routes.get(owner);
10555
- return value === void 0 ? {} : { value };
11467
+ if (active.ownerId !== slot.ownerId) {
11468
+ throw new Error(`Local Codex capacity slot ${slot.slotId} belongs to another route`);
11469
+ }
11470
+ return active;
10556
11471
  }
10557
11472
  };
10558
11473
  }
10559
11474
  });
10560
11475
 
10561
11476
  // ../machine-connector/dist/runtime/daemon.js
10562
- function isPermanentRelayFailure(error) {
10563
- return error instanceof MachineConnectionRevokedError || error instanceof RelayHttpError && (error.status === 400 || error.status === 401 || error.status === 403 || error.status === 404 || error.status === 409 || error.status === 410);
10564
- }
10565
11477
  async function withDeadline(operation, deadline) {
10566
11478
  if (deadline === void 0) {
10567
11479
  return await operation;
@@ -10582,7 +11494,7 @@ function delay4(milliseconds) {
10582
11494
  setTimeout(resolvePromise, milliseconds);
10583
11495
  });
10584
11496
  }
10585
- var import_node_os8, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
11497
+ var import_node_os8, import_node_crypto9, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds2, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
10586
11498
  var init_daemon = __esm({
10587
11499
  "../machine-connector/dist/runtime/daemon.js"() {
10588
11500
  "use strict";
@@ -10603,6 +11515,7 @@ var init_daemon = __esm({
10603
11515
  init_process_executor();
10604
11516
  init_shell_environment();
10605
11517
  init_relay_client();
11518
+ init_retry_backoff();
10606
11519
  init_runtime_logger();
10607
11520
  init_runtime_types();
10608
11521
  init_store();
@@ -10616,7 +11529,7 @@ var init_daemon = __esm({
10616
11529
  commandOutputFlushIntervalMilliseconds = 250;
10617
11530
  agentOutputLimitBytes = 2e6;
10618
11531
  defaultLeaseSeconds = 90;
10619
- defaultNetworkRetryMilliseconds = 2e3;
11532
+ defaultNetworkRetryMilliseconds2 = 2e3;
10620
11533
  defaultLeaseSafetyMarginMilliseconds = 1e4;
10621
11534
  defaultTerminalForegroundBudgetMilliseconds = 5e3;
10622
11535
  maximumEventUploadRetryMilliseconds = 6e4;
@@ -10647,6 +11560,7 @@ var init_daemon = __esm({
10647
11560
  settleLifetime;
10648
11561
  startupSettled;
10649
11562
  settleStartup;
11563
+ startupComplete = false;
10650
11564
  stopping = false;
10651
11565
  leaseSafetyMarginMilliseconds;
10652
11566
  leaseSeconds;
@@ -10668,7 +11582,7 @@ var init_daemon = __esm({
10668
11582
  this.shellEnvironmentManager = options.shellEnvironmentManager ?? new ShellEnvironmentManager();
10669
11583
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
10670
11584
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
10671
- this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds;
11585
+ this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds2;
10672
11586
  this.random = options.random ?? Math.random;
10673
11587
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
10674
11588
  }
@@ -10712,6 +11626,8 @@ var init_daemon = __esm({
10712
11626
  if (this.connections.length === 0) {
10713
11627
  await this.logger.info("No Local Machine connections are configured");
10714
11628
  }
11629
+ this.throwIfStopping();
11630
+ this.startupComplete = true;
10715
11631
  this.settleStartup();
10716
11632
  await Promise.all(this.connections.map(async (connection) => {
10717
11633
  await this.runConnection(connection);
@@ -10790,6 +11706,7 @@ var init_daemon = __esm({
10790
11706
  ...worker.status()
10791
11707
  })),
10792
11708
  pid: process.pid,
11709
+ startupComplete: this.startupComplete,
10793
11710
  startedAt: this.startedAt,
10794
11711
  shellEnvironment: this.shellEnvironmentManager.status(),
10795
11712
  version: connectorVersion
@@ -10811,7 +11728,10 @@ var init_daemon = __esm({
10811
11728
  ]);
10812
11729
  }
10813
11730
  async runLocalCodexRuntime(connection, relay) {
10814
- const worker = new LocalCodexRuntimeConnectionWorker(connection, relay, this.store, this.localCodexProcessPool(connection.machineId), this.shellEnvironmentManager.snapshot(), this.connectorInstanceId, this.logger);
11731
+ const worker = new LocalCodexRuntimeConnectionWorker(connection, relay, this.store, this.localCodexProcessPool(connection.machineId), this.shellEnvironmentManager.snapshot(), this.connectorInstanceId, this.logger, {
11732
+ networkRetryMilliseconds: this.networkRetryMilliseconds,
11733
+ random: this.random
11734
+ });
10815
11735
  this.localCodexWorkers.set(connection.connectionId, worker);
10816
11736
  if (this.stopping) {
10817
11737
  await worker.stop();
@@ -10841,9 +11761,11 @@ var init_daemon = __esm({
10841
11761
  return existing;
10842
11762
  }
10843
11763
  const relay = new MachineRelayClient(connection, this.store, {
11764
+ minimumRetryMilliseconds: this.networkRetryMilliseconds,
10844
11765
  onConnectionRevoked: async (error) => {
10845
11766
  await this.handleConnectionRevoked(connection, error);
10846
- }
11767
+ },
11768
+ random: this.random
10847
11769
  });
10848
11770
  this.relayClients.set(connection.connectionId, relay);
10849
11771
  return relay;
@@ -10873,7 +11795,7 @@ var init_daemon = __esm({
10873
11795
  protocolVersion: machineProtocolVersion
10874
11796
  });
10875
11797
  } catch (error) {
10876
- if (relay.isRevoked()) {
11798
+ if (this.stopping || relay.isRevoked()) {
10877
11799
  return;
10878
11800
  }
10879
11801
  await this.logger.error(`Heartbeat failed for connection ${connection.connectionId}`, error);
@@ -10882,6 +11804,7 @@ var init_daemon = __esm({
10882
11804
  }
10883
11805
  }
10884
11806
  async runClaimLoop(connection, relay) {
11807
+ const retryBackoff = this.createNetworkRetryBackoff();
10885
11808
  while (!this.stopping && !relay.isRevoked()) {
10886
11809
  try {
10887
11810
  const response = await relay.claim({
@@ -10897,17 +11820,19 @@ var init_daemon = __esm({
10897
11820
  }
10898
11821
  this.startClaimExecution(activeJob);
10899
11822
  }
11823
+ retryBackoff.reset();
10900
11824
  } catch (error) {
10901
- if (relay.isRevoked()) {
11825
+ if (this.stopping || relay.isRevoked()) {
10902
11826
  return;
10903
11827
  }
10904
11828
  await this.logger.error(`Job claim failed for connection ${connection.connectionId}`, error);
10905
- await this.waitUntilStop(this.networkRetryMilliseconds);
11829
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
10906
11830
  }
10907
11831
  }
10908
11832
  }
10909
11833
  async runControlLoop(connection, relay) {
10910
11834
  let cursor = 0;
11835
+ const retryBackoff = this.createNetworkRetryBackoff();
10911
11836
  while (!this.stopping && !relay.isRevoked()) {
10912
11837
  try {
10913
11838
  const response = await relay.pollControls({
@@ -10922,12 +11847,13 @@ var init_daemon = __esm({
10922
11847
  if (response.commands.length === 0) {
10923
11848
  cursor = response.nextCursor;
10924
11849
  }
11850
+ retryBackoff.reset();
10925
11851
  } catch (error) {
10926
- if (relay.isRevoked()) {
11852
+ if (this.stopping || relay.isRevoked()) {
10927
11853
  return;
10928
11854
  }
10929
11855
  await this.logger.error(`Control poll failed for connection ${connection.connectionId}`, error);
10930
- await this.waitUntilStop(this.networkRetryMilliseconds);
11856
+ await this.waitUntilStop(retryBackoff.nextDelayMilliseconds());
10931
11857
  }
10932
11858
  }
10933
11859
  }
@@ -11415,6 +12341,13 @@ var init_daemon = __esm({
11415
12341
  await delay4(Math.min(250, deadline - Date.now()));
11416
12342
  }
11417
12343
  }
12344
+ createNetworkRetryBackoff() {
12345
+ return new RetryBackoff({
12346
+ maximumMilliseconds: maximumTerminalRetryMilliseconds,
12347
+ minimumMilliseconds: this.networkRetryMilliseconds,
12348
+ random: this.random
12349
+ });
12350
+ }
11418
12351
  cancellationResult(activeJob) {
11419
12352
  const reason = activeJob.cancellation.currentReason();
11420
12353
  if (reason === ExecutionCancellationReason.LeaseLost) {
@@ -14149,6 +15082,8 @@ __export(dist_exports, {
14149
15082
  executeClaudeReply: () => executeClaudeReply,
14150
15083
  executeClaudeStart: () => executeClaudeStart,
14151
15084
  installUserService: () => installUserService,
15085
+ isPermanentRelayFailure: () => isPermanentRelayFailure,
15086
+ isRetryableRelayFailure: () => isRetryableRelayFailure,
14152
15087
  isTerminalJobStatus: () => isTerminalJobStatus,
14153
15088
  localCodexRuntimeEventsRequestBytes: () => localCodexRuntimeEventsRequestBytes,
14154
15089
  localMachineJobTargetRelationship: () => localMachineJobTargetRelationship,
@@ -14374,7 +15309,7 @@ function getApiKeyOrUndefined() {
14374
15309
 
14375
15310
  // src/utils/http.ts
14376
15311
  function getUserAgent() {
14377
- return `moxt-cli/${"0.10.0"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
15312
+ return `moxt-cli/${"0.11.0-beta.2"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
14378
15313
  }
14379
15314
  async function sendRequest(method, path4, init) {
14380
15315
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -27704,6 +28639,14 @@ var import_node_util6 = require("util");
27704
28639
  var MAX_DESC_LENGTH = 5e3;
27705
28640
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
27706
28641
  var MAX_COMMENT_CONTENT_BYTES = MAX_COMMENT_CONTENT_LENGTH * 4;
28642
+ function addTeammateAttributionOption(command) {
28643
+ return command.option("--as-teammate <teammateId>", "Attribute this Workflow write to a managed AI teammate");
28644
+ }
28645
+ function addTeammateAttribution(body, options) {
28646
+ const asTeammateId = parseOptionalPositiveInteger(options.asTeammate, "--as-teammate");
28647
+ if (asTeammateId !== void 0) body.asTeammateId = asTeammateId;
28648
+ return body;
28649
+ }
27707
28650
  var WorkflowOptionsError = class extends Error {
27708
28651
  constructor(message) {
27709
28652
  super(message);
@@ -27735,6 +28678,9 @@ function addPreferredAssigneeOptions(command) {
27735
28678
  }
27736
28679
  function parsePositiveInteger(raw, label) {
27737
28680
  const parsed = Number.parseInt(raw, 10);
28681
+ if (Number.isInteger(parsed) && !Number.isSafeInteger(parsed)) {
28682
+ throw new WorkflowOptionsError(`Error: ${label} must be a safe positive integer, got "${raw}".`);
28683
+ }
27738
28684
  if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {
27739
28685
  throw new WorkflowOptionsError(`Error: ${label} must be a positive integer, got "${raw}".`);
27740
28686
  }
@@ -27775,13 +28721,32 @@ function parseWorkflowScope(raw) {
27775
28721
  }
27776
28722
  function parseTaskScope(raw) {
27777
28723
  if (raw == null || raw === "") return "all";
27778
- if (raw === "all" || raw === "assigned_to_me" || raw === "subscribed_by_me" || raw === "owner_is_me") {
27779
- return raw;
28724
+ if (raw === "all" || raw === "assigned_to_me" || raw === "reported_by_me") return raw;
28725
+ throw new WorkflowOptionsError(
28726
+ 'Error: --scope must be "all", "assigned_to_me", or "reported_by_me".'
28727
+ );
28728
+ }
28729
+ function parseStatusTypeFilter(raw) {
28730
+ if (raw == null || raw === "") return void 0;
28731
+ if (raw === "todo") return 1;
28732
+ if (raw === "in-progress") return 2;
28733
+ if (raw === "done") return 3;
28734
+ throw new WorkflowOptionsError('Error: --status-type must be "todo", "in-progress", or "done".');
28735
+ }
28736
+ function parseTaskSortField(raw) {
28737
+ const value = raw ?? "default";
28738
+ if (value === "default" || value === "title" || value === "status" || value === "assignee" || value === "owner" || value === "priority" || value === "updated") {
28739
+ return value;
27780
28740
  }
27781
28741
  throw new WorkflowOptionsError(
27782
- 'Error: --scope must be "all", "assigned_to_me", "subscribed_by_me", or "owner_is_me".'
28742
+ 'Error: --sort-by must be "default", "title", "status", "assignee", "owner", "priority", or "updated".'
27783
28743
  );
27784
28744
  }
28745
+ function parseTaskSortDirection(raw) {
28746
+ const value = raw ?? "desc";
28747
+ if (value === "asc" || value === "desc") return value;
28748
+ throw new WorkflowOptionsError('Error: --sort-direction must be "asc" or "desc".');
28749
+ }
27785
28750
  function parseHttpUrl(raw, label = "--url") {
27786
28751
  const url = raw.trim();
27787
28752
  try {
@@ -27867,9 +28832,11 @@ function parseAssigneeBody(options, allowClear) {
27867
28832
  if (teammateId !== void 0) return { assigneeAiTeammateId: teammateId };
27868
28833
  return {};
27869
28834
  }
27870
- function parseTaskListFilterQuery(options) {
28835
+ function parseTaskListFilter(options, scope, currentHumanId) {
27871
28836
  const filterOwnerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28837
+ const filterReporterHumanId = parseOptionalPositiveInteger(options.reporterHumanId, "--reporter-human-id");
27872
28838
  const filterPriority = parsePriority(options.priority);
28839
+ const filterStatusType = parseStatusTypeFilter(options.statusType);
27873
28840
  const filterAssigneeHumanId = parseOptionalPositiveInteger(options.assigneeHumanId, "--assignee-human-id");
27874
28841
  const filterAssigneeAssistantId = parseOptionalPositiveInteger(
27875
28842
  options.assigneeAssistantId,
@@ -27883,14 +28850,57 @@ function parseTaskListFilterQuery(options) {
27883
28850
  if (assigneeFilterCount > 1) {
27884
28851
  throw new WorkflowOptionsError("Error: assignee filter options are mutually exclusive.");
27885
28852
  }
28853
+ if (scope === "assigned_to_me" && assigneeFilterCount > 0) {
28854
+ throw new WorkflowOptionsError("Error: --scope assigned_to_me cannot be combined with assignee filters.");
28855
+ }
28856
+ if (scope === "reported_by_me" && filterReporterHumanId !== void 0) {
28857
+ throw new WorkflowOptionsError(
28858
+ "Error: --scope reported_by_me cannot be combined with --reporter-human-id."
28859
+ );
28860
+ }
28861
+ if (scope !== "all" && currentHumanId === void 0) {
28862
+ throw new Error(`Current human ID is required for task scope: ${scope}`);
28863
+ }
27886
28864
  return {
27887
- filterOwnerHumanId,
27888
- filterPriority,
27889
- filterAssigneeHumanId,
27890
- filterAssigneeAssistantId,
27891
- filterAssigneeTeammateId
28865
+ ownerHumanIds: filterOwnerHumanId === void 0 ? null : [{ type: "human", humanId: filterOwnerHumanId }],
28866
+ reporterHumanIds: scope === "reported_by_me" ? [{ type: "human", humanId: currentHumanId }] : filterReporterHumanId === void 0 ? null : [{ type: "human", humanId: filterReporterHumanId }],
28867
+ 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,
28868
+ priorities: filterPriority === void 0 ? null : [filterPriority],
28869
+ statusTypes: filterStatusType === void 0 ? null : [filterStatusType],
28870
+ latestActAtAfter: null,
28871
+ latestActAtBefore: null
27892
28872
  };
27893
28873
  }
28874
+ function matchesMaskedEmail(email, maskedEmail) {
28875
+ const normalizedEmail = email.toLowerCase();
28876
+ const normalizedMask = maskedEmail.toLowerCase();
28877
+ return normalizedEmail.length === normalizedMask.length && [...normalizedMask].every((character, index2) => character === "*" || character === normalizedEmail[index2]);
28878
+ }
28879
+ async function resolveCurrentHumanId(workspaceId) {
28880
+ const [currentUserResponse, membersResponse] = await Promise.all([
28881
+ httpGet("/users/whoami"),
28882
+ httpGet(`/workspaces/${workspaceId}/members`)
28883
+ ]);
28884
+ if (!currentUserResponse.ok) failResponse(currentUserResponse);
28885
+ if (!membersResponse.ok) failResponse(membersResponse);
28886
+ const matchingMembers = membersResponse.data.members.filter(
28887
+ (member) => matchesMaskedEmail(member.email, currentUserResponse.data.email)
28888
+ );
28889
+ if (matchingMembers.length !== 1) {
28890
+ printError("Error: unable to uniquely resolve the current human ID in this workspace.");
28891
+ process.exit(1);
28892
+ }
28893
+ return matchingMembers[0].userId;
28894
+ }
28895
+ function parseReporterBody(options) {
28896
+ const reporterHumanId = parseOptionalPositiveInteger(options.reporterHumanId, "--reporter-human-id");
28897
+ if (options.clearReporter && reporterHumanId !== void 0) {
28898
+ throw new WorkflowOptionsError("Error: --clear-reporter cannot be used with --reporter-human-id.");
28899
+ }
28900
+ if (options.clearReporter) return { reporterHumanId: null };
28901
+ if (reporterHumanId !== void 0) return { reporterHumanId };
28902
+ return {};
28903
+ }
27894
28904
  function parsePreferredAssigneeBody(options) {
27895
28905
  const hasClear = options.clearPreferredAssignee === true;
27896
28906
  const humanId = parseOptionalPositiveInteger(options.preferredHumanId, "--preferred-human-id");
@@ -28069,7 +29079,7 @@ function printWorkflowDetail(item) {
28069
29079
  function printTaskSummary(item) {
28070
29080
  const runIds = item.runningAgentRuns.map((run) => run.pipelineId).join(",") || "-";
28071
29081
  print(
28072
- `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
29082
+ `${colors.bold}#${item.scopedId}${colors.reset} ${item.title} status=${item.statusScopedId} priority=${priorityLabel(item.priority)} reporter=${item.reporterHumanId ?? "-"} assignee=${formatAssignee(item.assignee)} runs=${runIds}`
28073
29083
  );
28074
29084
  }
28075
29085
  function printTaskDetail(item, linkedLinkTitles) {
@@ -28077,6 +29087,7 @@ function printTaskDetail(item, linkedLinkTitles) {
28077
29087
  printDetailField2("scopedId", item.scopedId);
28078
29088
  printDetailField2("workflowFileId", item.workflowFileId);
28079
29089
  printDetailField2("ownerHumanId", item.ownerHumanId);
29090
+ printDetailField2("reporterHumanId", item.reporterHumanId);
28080
29091
  printDetailField2("title", item.title);
28081
29092
  printDetailTextField2("desc", item.desc);
28082
29093
  printDetailField2("statusScopedId", item.statusScopedId);
@@ -28397,33 +29408,41 @@ function registerTransitionCommands(workflow) {
28397
29408
  function registerTaskCommands(workflow) {
28398
29409
  const task = workflow.command("task").description("Workflow task operations");
28399
29410
  addWorkspaceOption(
28400
- task.command("list").description("List workflow tasks").option("--workflow-file-id <workflowFileId>", "Filter by workflow file ID").option("--scope <scope>", "Task scope", "all").option("-l, --limit <limit>", "Maximum number of tasks to return", "50").option("--cursor <cursor>", "Pagination cursor").option("--priority <priority>", "Filter by priority: urgent, high, medium, or low").option("--owner-human-id <humanId>", "Filter by task owner human ID").option("--assignee-human-id <humanId>", "Filter by human assignee ID").option("--assignee-assistant-id <assistantId>", "Filter by AI assistant assignee ID").option("--assignee-teammate-id <teammateId>", "Filter by AI teammate assignee ID")
28401
- ).action(
28402
- async (options) => {
28403
- const query = runOrExit4(
28404
- () => buildQuery({
28405
- scope: parseTaskScope(options.scope),
28406
- limit: parseSearchLimit(options.limit, 50, 100),
28407
- cursor: options.cursor,
28408
- workflowFileId: options.workflowFileId,
28409
- ...parseTaskListFilterQuery(options)
28410
- })
28411
- );
28412
- startSpinner("Fetching workflow tasks...");
28413
- const response = await httpGet(`/workspaces/${options.workspace}/workflow-tasks-v4${query}`);
28414
- if (!response.ok) {
28415
- stopSpinner(false, "Failed");
28416
- failResponse(response);
28417
- }
28418
- if (response.data.tasks.length === 0) {
28419
- stopSpinner(true, "No workflow tasks found.");
28420
- return;
29411
+ 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(
29412
+ "--sort-by <field>",
29413
+ "Sort by default, title, status, assignee, owner, priority, or updated",
29414
+ "default"
29415
+ ).option("--sort-direction <direction>", "Sort direction: asc or desc", "desc")
29416
+ ).action(async (options) => {
29417
+ const scope = runOrExit4(() => parseTaskScope(options.scope));
29418
+ const currentHumanId = scope === "all" ? void 0 : await resolveCurrentHumanId(options.workspace);
29419
+ const body = runOrExit4(() => ({
29420
+ limit: parseSearchLimit(options.limit, 50, 100),
29421
+ cursor: options.cursor,
29422
+ workflowFileId: options.workflowFileId,
29423
+ filter: parseTaskListFilter(options, scope, currentHumanId),
29424
+ sort: {
29425
+ field: parseTaskSortField(options.sortBy),
29426
+ direction: parseTaskSortDirection(options.sortDirection)
28421
29427
  }
28422
- stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
28423
- for (const item of response.data.tasks) printTaskSummary(item);
28424
- if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
29428
+ }));
29429
+ startSpinner("Fetching workflow tasks...");
29430
+ const response = await httpPost(
29431
+ `/workspaces/${options.workspace}/workflow-tasks-v5`,
29432
+ body
29433
+ );
29434
+ if (!response.ok) {
29435
+ stopSpinner(false, "Failed");
29436
+ failResponse(response);
28425
29437
  }
28426
- );
29438
+ if (response.data.tasks.length === 0) {
29439
+ stopSpinner(true, "No workflow tasks found.");
29440
+ return;
29441
+ }
29442
+ stopSpinner(true, `Found ${response.data.tasks.length} task(s)`);
29443
+ for (const item of response.data.tasks) printTaskSummary(item);
29444
+ if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
29445
+ });
28427
29446
  addWorkspaceOption(
28428
29447
  task.command("get").description("Get a workflow task").argument("<workflowFileId>").argument("<taskScopedId>")
28429
29448
  ).action(async (workflowFileId, taskScopedId, options) => {
@@ -28439,7 +29458,7 @@ function registerTaskCommands(workflow) {
28439
29458
  });
28440
29459
  addAssigneeOptions(
28441
29460
  addWorkspaceOption(
28442
- task.command("create").description("Create a workflow task").argument("<workflowFileId>").requiredOption("--title <title>", "Task title").requiredOption("--status <statusScopedId>", "Status scoped ID").option("--priority <priority>", "Priority: urgent, high, medium, or low", "medium").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--owner-human-id <humanId>", "Task owner human ID")
29461
+ task.command("create").description("Create a workflow task").argument("<workflowFileId>").requiredOption("--title <title>", "Task title").requiredOption("--status <statusScopedId>", "Status scoped ID").option("--priority <priority>", "Priority: urgent, high, medium, or low", "medium").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--owner-human-id <humanId>", "Task owner human ID").option("--reporter-human-id <humanId>", "Task reporter human ID").option("--clear-reporter", "Create the task without a reporter")
28443
29462
  )
28444
29463
  ).action(
28445
29464
  async (workflowFileId, options) => {
@@ -28454,11 +29473,12 @@ function registerTaskCommands(workflow) {
28454
29473
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28455
29474
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
28456
29475
  Object.assign(next, parseAssigneeBody(options, false));
29476
+ Object.assign(next, parseReporterBody(options));
28457
29477
  return next;
28458
29478
  });
28459
29479
  startSpinner("Creating task...");
28460
29480
  const createResponse = await httpPost(
28461
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2`,
29481
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3`,
28462
29482
  body
28463
29483
  );
28464
29484
  if (!createResponse.ok) {
@@ -28479,7 +29499,7 @@ function registerTaskCommands(workflow) {
28479
29499
  }
28480
29500
  );
28481
29501
  addWorkspaceOption(
28482
- task.command("update").description("Update workflow task metadata").argument("<workflowFileId>").argument("<taskScopedId>").option("--title <title>", "Task title").option("--priority <priority>", "Priority: urgent, high, medium, or low").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--clear-desc", "Clear task description").option("--owner-human-id <humanId>", "Task owner human ID")
29502
+ addTeammateAttributionOption(task.command("update")).description("Update workflow task metadata").argument("<workflowFileId>").argument("<taskScopedId>").option("--title <title>", "Task title").option("--priority <priority>", "Priority: urgent, high, medium, or low").option("--desc-file <localPath>", "Local UTF-8 text file for task description").option("--clear-desc", "Clear task description").option("--owner-human-id <humanId>", "Task owner human ID").option("--reporter-human-id <humanId>", "Task reporter human ID").option("--clear-reporter", "Clear the task reporter")
28483
29503
  ).action(
28484
29504
  async (workflowFileId, taskScopedId, options) => {
28485
29505
  const body = runOrExit4(() => {
@@ -28495,13 +29515,14 @@ function registerTaskCommands(workflow) {
28495
29515
  if (options.clearDesc) next.desc = null;
28496
29516
  const ownerHumanId = parseOptionalPositiveInteger(options.ownerHumanId, "--owner-human-id");
28497
29517
  if (ownerHumanId !== void 0) next.ownerHumanId = ownerHumanId;
29518
+ Object.assign(next, parseReporterBody(options));
28498
29519
  assertNonEmptyBody(next);
28499
- return next;
29520
+ return addTeammateAttribution(next, options);
28500
29521
  });
28501
29522
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28502
29523
  startSpinner("Updating task...");
28503
29524
  const updateResponse = await httpPatch(
28504
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/metadata`,
29525
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v3/${id}/metadata`,
28505
29526
  body
28506
29527
  );
28507
29528
  if (!updateResponse.ok) {
@@ -28522,7 +29543,7 @@ function registerTaskCommands(workflow) {
28522
29543
  if (action === "add-linked-links") {
28523
29544
  command.option("--title <title>", "Optional link title");
28524
29545
  }
28525
- addWorkspaceOption(command).action(
29546
+ addWorkspaceOption(addTeammateAttributionOption(command)).action(
28526
29547
  async (workflowFileId, taskScopedId, options) => {
28527
29548
  const { id, link } = runOrExit4(() => ({
28528
29549
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
@@ -28531,9 +29552,10 @@ function registerTaskCommands(workflow) {
28531
29552
  url: parseHttpUrl(options.url)
28532
29553
  }
28533
29554
  }));
29555
+ const body = runOrExit4(() => addTeammateAttribution({ links: [link] }, options));
28534
29556
  startSpinner(action === "add-linked-links" ? "Adding linked URL..." : "Removing linked URL...");
28535
29557
  const path4 = `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/linked-links`;
28536
- const updateResponse = action === "add-linked-links" ? await httpPost(path4, { links: [link] }) : await httpDelete(path4, { links: [link] });
29558
+ const updateResponse = action === "add-linked-links" ? await httpPost(path4, body) : await httpDelete(path4, body);
28537
29559
  if (!updateResponse.ok) {
28538
29560
  stopSpinner(false, "Failed");
28539
29561
  failResponse(updateResponse);
@@ -28549,17 +29571,18 @@ function registerTaskCommands(workflow) {
28549
29571
  );
28550
29572
  }
28551
29573
  addWorkspaceOption(
28552
- task.command("move").description("Move a workflow task to another status").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID")
29574
+ addTeammateAttributionOption(task.command("move")).description("Move a workflow task to another status").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID")
28553
29575
  ).action(
28554
29576
  async (workflowFileId, taskScopedId, options) => {
28555
29577
  const { id, statusScopedId } = runOrExit4(() => ({
28556
29578
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28557
29579
  statusScopedId: parsePositiveInteger(options.status, "--status")
28558
29580
  }));
29581
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId }, options));
28559
29582
  startSpinner("Moving task...");
28560
29583
  const updateResponse = await httpPatch(
28561
29584
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/status`,
28562
- { statusScopedId }
29585
+ body
28563
29586
  );
28564
29587
  if (!updateResponse.ok) {
28565
29588
  stopSpinner(false, "Failed");
@@ -28575,7 +29598,7 @@ function registerTaskCommands(workflow) {
28575
29598
  }
28576
29599
  );
28577
29600
  addWorkspaceOption(
28578
- task.command("move-after").description("Move a workflow task after an anchor task within a Board column").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID").option("--after <taskScopedId>", "Anchor task scoped ID").option("--first", "Move to the top of the column")
29601
+ addTeammateAttributionOption(task.command("move-after")).description("Move a workflow task after an anchor task within a Board column").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--status <statusScopedId>", "Target status scoped ID").option("--after <taskScopedId>", "Anchor task scoped ID").option("--first", "Move to the top of the column")
28579
29602
  ).action(
28580
29603
  async (workflowFileId, taskScopedId, options) => {
28581
29604
  const { id, statusScopedId, anchorTaskScopedId } = runOrExit4(() => {
@@ -28591,10 +29614,11 @@ function registerTaskCommands(workflow) {
28591
29614
  anchorTaskScopedId: options.first ? null : parsePositiveInteger(options.after, "--after")
28592
29615
  };
28593
29616
  });
29617
+ const body = runOrExit4(() => addTeammateAttribution({ statusScopedId, anchorTaskScopedId }, options));
28594
29618
  startSpinner("Moving task...");
28595
29619
  const updateResponse = await httpPost(
28596
29620
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks-v2/${id}/move-after`,
28597
- { statusScopedId, anchorTaskScopedId }
29621
+ body
28598
29622
  );
28599
29623
  if (!updateResponse.ok) {
28600
29624
  stopSpinner(false, "Failed");
@@ -28611,14 +29635,14 @@ function registerTaskCommands(workflow) {
28611
29635
  );
28612
29636
  addAssigneeOptions(
28613
29637
  addWorkspaceOption(
28614
- task.command("assign").description("Update workflow task assignee").argument("<workflowFileId>").argument("<taskScopedId>").option("--clear", "Clear assignee")
29638
+ addTeammateAttributionOption(task.command("assign")).description("Update workflow task assignee").argument("<workflowFileId>").argument("<taskScopedId>").option("--clear", "Clear assignee")
28615
29639
  )
28616
29640
  ).action(
28617
29641
  async (workflowFileId, taskScopedId, options) => {
28618
29642
  const body = runOrExit4(() => {
28619
29643
  const next = parseAssigneeBody(options, true);
28620
29644
  if (Object.keys(next).length === 0 && options.clear !== true) assertNonEmptyBody(next);
28621
- return next;
29645
+ return addTeammateAttribution(next, options);
28622
29646
  });
28623
29647
  const id = runOrExit4(() => parsePositiveInteger(taskScopedId, "taskScopedId"));
28624
29648
  startSpinner("Updating task assignee...");
@@ -28656,23 +29680,23 @@ function registerTaskCommands(workflow) {
28656
29680
  }
28657
29681
  function getWorkflowTask(workspaceId, workflowFileId, taskScopedId) {
28658
29682
  return httpGet(
28659
- `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v3/${taskScopedId}`
29683
+ `/workspaces/${workspaceId}/workflows/${workflowFileId}/tasks-v4/${taskScopedId}`
28660
29684
  );
28661
29685
  }
28662
29686
  function registerCommentCommands(workflow) {
28663
29687
  const comment = workflow.command("comment").description("Workflow task comment operations");
28664
29688
  addWorkspaceOption(
28665
- comment.command("create").description("Create a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
29689
+ addTeammateAttributionOption(comment.command("create")).description("Create a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
28666
29690
  ).action(
28667
29691
  async (workflowFileId, taskScopedId, options) => {
28668
- const { id, content: content3 } = runOrExit4(() => ({
29692
+ const { id, body } = runOrExit4(() => ({
28669
29693
  id: parsePositiveInteger(taskScopedId, "taskScopedId"),
28670
- content: readCommentContentFile2(options.contentPath)
29694
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28671
29695
  }));
28672
29696
  startSpinner("Creating comment...");
28673
29697
  const response = await httpPost(
28674
29698
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${id}/comments`,
28675
- { content: content3 }
29699
+ body
28676
29700
  );
28677
29701
  if (!response.ok) {
28678
29702
  stopSpinner(false, "Failed");
@@ -28712,18 +29736,18 @@ function registerCommentCommands(workflow) {
28712
29736
  if (response.data.nextCursor) print(`${colors.dim}nextCursor=${response.data.nextCursor}${colors.reset}`);
28713
29737
  });
28714
29738
  addWorkspaceOption(
28715
- comment.command("update").description("Edit a workflow task comment authored by the current user").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
29739
+ addTeammateAttributionOption(comment.command("update")).description("Edit a workflow task comment authored by the current actor").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>").requiredOption("--content-path <localPath>", "Local UTF-8 text file for comment content")
28716
29740
  ).action(
28717
29741
  async (workflowFileId, taskScopedId, commentId, options) => {
28718
- const { task, comment: commentIdValue, content: content3 } = runOrExit4(() => ({
29742
+ const { task, comment: commentIdValue, body } = runOrExit4(() => ({
28719
29743
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28720
29744
  comment: parsePositiveInteger(commentId, "commentId"),
28721
- content: readCommentContentFile2(options.contentPath)
29745
+ body: addTeammateAttribution({ content: readCommentContentFile2(options.contentPath) }, options)
28722
29746
  }));
28723
29747
  startSpinner("Updating comment...");
28724
29748
  const response = await httpPatch(
28725
29749
  `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${task}/comments/${commentIdValue}`,
28726
- { content: content3 }
29750
+ body
28727
29751
  );
28728
29752
  if (!response.ok) {
28729
29753
  stopSpinner(false, "Failed");
@@ -28733,16 +29757,17 @@ function registerCommentCommands(workflow) {
28733
29757
  }
28734
29758
  );
28735
29759
  addWorkspaceOption(
28736
- comment.command("delete").description("Delete a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>")
29760
+ addTeammateAttributionOption(comment.command("delete")).description("Delete a workflow task comment").argument("<workflowFileId>").argument("<taskScopedId>").argument("<commentId>")
28737
29761
  ).action(
28738
29762
  async (workflowFileId, taskScopedId, commentId, options) => {
28739
29763
  const ids = runOrExit4(() => ({
28740
29764
  task: parsePositiveInteger(taskScopedId, "taskScopedId"),
28741
- comment: parsePositiveInteger(commentId, "commentId")
29765
+ comment: parsePositiveInteger(commentId, "commentId"),
29766
+ asTeammateId: parseOptionalPositiveInteger(options.asTeammate, "--as-teammate")
28742
29767
  }));
28743
29768
  startSpinner("Deleting comment...");
28744
29769
  const response = await httpDelete(
28745
- `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${ids.task}/comments/${ids.comment}`
29770
+ `/workspaces/${options.workspace}/workflows/${workflowFileId}/tasks/${ids.task}/comments/${ids.comment}${buildQuery({ asTeammateId: ids.asTeammateId })}`
28746
29771
  );
28747
29772
  if (!response.ok) {
28748
29773
  stopSpinner(false, "Failed");
@@ -28796,7 +29821,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
28796
29821
  var MAX_BATCH_SIZE = 100;
28797
29822
  function commonLabels() {
28798
29823
  return {
28799
- cli_version: "0.10.0",
29824
+ cli_version: "0.11.0-beta.2",
28800
29825
  node_version: process.versions.node,
28801
29826
  os: (0, import_node_os11.platform)(),
28802
29827
  arch: (0, import_node_os11.arch)(),
@@ -28842,7 +29867,7 @@ async function flush() {
28842
29867
  }
28843
29868
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
28844
29869
  const payload = {
28845
- release_id: "0.10.0",
29870
+ release_id: "0.11.0-beta.2",
28846
29871
  client_type: "cli",
28847
29872
  metric_data_list: batch.map((m) => ({
28848
29873
  profile: "cli",
@@ -29225,9 +30250,9 @@ function commandPath3(command) {
29225
30250
  }
29226
30251
 
29227
30252
  // src/index.ts
29228
- var program2 = createProgram("0.10.0");
29229
- installDaemonReconcileHook(program2, "0.10.0");
29230
- installUpdateHook(program2, "0.10.0");
30253
+ var program2 = createProgram("0.11.0-beta.2");
30254
+ installDaemonReconcileHook(program2, "0.11.0-beta.2");
30255
+ installUpdateHook(program2, "0.11.0-beta.2");
29231
30256
  instrumentProgram(program2);
29232
30257
  installExitHandler();
29233
30258
  program2.parseAsync(process.argv).then(async () => {