@moxt-ai/cli 0.11.0-beta.5 → 0.11.0-beta.6

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
@@ -4976,7 +4976,7 @@ var init_version = __esm({
4976
4976
  });
4977
4977
 
4978
4978
  // ../machine-connector/dist/runtime/local-codex-runtime/contracts.js
4979
- var localCodexRuntimeProtocolVersion, localCodexRuntimeEventSchemaVersion, localCodexRuntimeEventRedactionVersion, LocalCodexComponentStatusWire, LocalCodexUnavailableReasonWire, LocalCodexTurnStatusWire, LocalCodexControlKindWire, LocalCodexControlOutcomeWire, LocalCodexDiscoveryKindWire, LocalCodexDiscoveryStatusWire, LocalCodexAttemptPhase, LocalCodexControlApplyPhase;
4979
+ var localCodexRuntimeProtocolVersion, localCodexRuntimeEventSchemaVersion, localCodexRuntimeEventRedactionVersion, LocalCodexComponentStatusWire, LocalCodexUnavailableReasonWire, LocalCodexTurnStatusWire, LocalCodexControlKindWire, LocalCodexControlOutcomeWire, LocalCodexDiscoveryKindWire, localFilesCapability, LocalCodexDiscoveryStatusWire, LocalCodexAttemptPhase, LocalCodexControlApplyPhase;
4980
4980
  var init_contracts2 = __esm({
4981
4981
  "../machine-connector/dist/runtime/local-codex-runtime/contracts.js"() {
4982
4982
  "use strict";
@@ -5016,8 +5016,13 @@ var init_contracts2 = __esm({
5016
5016
  })(LocalCodexControlOutcomeWire || (LocalCodexControlOutcomeWire = {}));
5017
5017
  (function(LocalCodexDiscoveryKindWire2) {
5018
5018
  LocalCodexDiscoveryKindWire2["DirectoryList"] = "directory_list";
5019
+ LocalCodexDiscoveryKindWire2["LocalFileList"] = "local_file_list";
5020
+ LocalCodexDiscoveryKindWire2["LocalFileRead"] = "local_file_read";
5021
+ LocalCodexDiscoveryKindWire2["LocalFileSearch"] = "local_file_search";
5022
+ LocalCodexDiscoveryKindWire2["LocalFileValidate"] = "local_file_validate";
5019
5023
  LocalCodexDiscoveryKindWire2["ModelList"] = "model_list";
5020
5024
  })(LocalCodexDiscoveryKindWire || (LocalCodexDiscoveryKindWire = {}));
5025
+ localFilesCapability = "local_files_v1";
5021
5026
  (function(LocalCodexDiscoveryStatusWire2) {
5022
5027
  LocalCodexDiscoveryStatusWire2["Failed"] = "failed";
5023
5028
  LocalCodexDiscoveryStatusWire2["Succeeded"] = "succeeded";
@@ -5078,7 +5083,7 @@ function extractKnownCodexVersion(userAgent) {
5078
5083
  return matched === null ? {} : { value: matched[1] };
5079
5084
  }
5080
5085
  async function probeCodexVersion(executable, processBaseDirectory, environment) {
5081
- const result = await new Promise((resolve10) => {
5086
+ const result = await new Promise((resolve11) => {
5082
5087
  (0, import_node_child_process2.execFile)(executable, ["--version"], {
5083
5088
  cwd: processBaseDirectory,
5084
5089
  encoding: "utf8",
@@ -5088,10 +5093,10 @@ async function probeCodexVersion(executable, processBaseDirectory, environment)
5088
5093
  windowsHide: true
5089
5094
  }, (error, stdout) => {
5090
5095
  if (error !== null || typeof stdout !== "string") {
5091
- resolve10({});
5096
+ resolve11({});
5092
5097
  return;
5093
5098
  }
5094
- resolve10({ output: stdout });
5099
+ resolve11({ output: stdout });
5095
5100
  });
5096
5101
  });
5097
5102
  if (result.output === void 0) {
@@ -5140,12 +5145,12 @@ async function completionWithinExit(child, milliseconds) {
5140
5145
  if (child.exitCode !== null || child.signalCode !== null) {
5141
5146
  return;
5142
5147
  }
5143
- await new Promise((resolve10) => {
5144
- const timeout = setTimeout(resolve10, milliseconds);
5148
+ await new Promise((resolve11) => {
5149
+ const timeout = setTimeout(resolve11, milliseconds);
5145
5150
  timeout.unref();
5146
5151
  child.once("close", () => {
5147
5152
  clearTimeout(timeout);
5148
- resolve10();
5153
+ resolve11();
5149
5154
  });
5150
5155
  });
5151
5156
  }
@@ -5155,8 +5160,8 @@ async function completionWithinProcessTreeExit(child, stopTarget, milliseconds)
5155
5160
  if (!await appServerProcessTreeIsRunning(child, stopTarget)) {
5156
5161
  return;
5157
5162
  }
5158
- await new Promise((resolve10) => {
5159
- setTimeout(resolve10, processTreePollMilliseconds);
5163
+ await new Promise((resolve11) => {
5164
+ setTimeout(resolve11, processTreePollMilliseconds);
5160
5165
  });
5161
5166
  }
5162
5167
  }
@@ -5290,7 +5295,7 @@ async function captureAppServerProcessTree(child) {
5290
5295
  };
5291
5296
  }
5292
5297
  async function appServerProcessTable() {
5293
- const listed = await new Promise((resolve10) => {
5298
+ const listed = await new Promise((resolve11) => {
5294
5299
  (0, import_node_child_process2.execFile)(processTableExecutable(), ["-axo", "pid=,ppid=,lstart="], {
5295
5300
  encoding: "utf8",
5296
5301
  maxBuffer: maximumProcessTableBytes,
@@ -5298,10 +5303,10 @@ async function appServerProcessTable() {
5298
5303
  windowsHide: true
5299
5304
  }, (error, stdout) => {
5300
5305
  if (error !== null || typeof stdout !== "string") {
5301
- resolve10({});
5306
+ resolve11({});
5302
5307
  return;
5303
5308
  }
5304
- resolve10({ output: stdout });
5309
+ resolve11({ output: stdout });
5305
5310
  });
5306
5311
  });
5307
5312
  if (listed.output === void 0) {
@@ -5352,8 +5357,8 @@ async function appServerProcessTableWithRetry() {
5352
5357
  return processTable;
5353
5358
  }
5354
5359
  if (attempt < maximumProcessTableAttempts) {
5355
- await new Promise((resolve10) => {
5356
- setTimeout(resolve10, processTableRetryMilliseconds);
5360
+ await new Promise((resolve11) => {
5361
+ setTimeout(resolve11, processTableRetryMilliseconds);
5357
5362
  });
5358
5363
  }
5359
5364
  }
@@ -5572,13 +5577,13 @@ var init_app_server_client = __esm({
5572
5577
  const id = this.nextRequestId;
5573
5578
  this.nextRequestId += 1;
5574
5579
  const key = String(id);
5575
- const response = new Promise((resolve10, reject) => {
5580
+ const response = new Promise((resolve11, reject) => {
5576
5581
  const timeout = setTimeout(() => {
5577
5582
  this.pending.delete(key);
5578
5583
  reject(new AppServerRequestTimeoutError(method));
5579
5584
  }, timeoutMilliseconds);
5580
5585
  timeout.unref();
5581
- this.pending.set(key, { reject, resolve: resolve10, timeout });
5586
+ this.pending.set(key, { reject, resolve: resolve11, timeout });
5582
5587
  });
5583
5588
  await this.write({ id, method, params });
5584
5589
  return await response;
@@ -5715,12 +5720,12 @@ var init_app_server_client = __esm({
5715
5720
  if (Buffer.byteLength(frame, "utf8") > maximumFrameBytes) {
5716
5721
  throw new AppServerProtocolError("Codex App Server request exceeds the size limit");
5717
5722
  }
5718
- const operation = this.writeQueue.then(async () => await new Promise((resolve10, reject) => {
5723
+ const operation = this.writeQueue.then(async () => await new Promise((resolve11, reject) => {
5719
5724
  this.child.stdin.write(frame, (error) => {
5720
5725
  if (error) {
5721
5726
  reject(error);
5722
5727
  } else {
5723
- resolve10();
5728
+ resolve11();
5724
5729
  }
5725
5730
  });
5726
5731
  }));
@@ -5800,8 +5805,9 @@ var init_app_server_client = __esm({
5800
5805
  return true;
5801
5806
  }
5802
5807
  async stop() {
5803
- await this.client.value?.stop();
5808
+ const client = this.client.value;
5804
5809
  this.client = {};
5810
+ await client?.stop();
5805
5811
  }
5806
5812
  async quarantineCurrentProcess(capture) {
5807
5813
  if (this.quarantinePromise !== void 0) {
@@ -5877,6 +5883,7 @@ async function executeCodex(processPool, ownerId, workingDirectory, environment,
5877
5883
  const route = new CodexToolRoute(processPool, callbacks, existingThreadId);
5878
5884
  processPool.register(ownerId, route);
5879
5885
  let slot;
5886
+ let threadLease;
5880
5887
  try {
5881
5888
  slot = await acquireExecutionSlot(processPool, ownerId, callbacks);
5882
5889
  if (slot === void 0) {
@@ -5887,7 +5894,8 @@ async function executeCodex(processPool, ownerId, workingDirectory, environment,
5887
5894
  if (!canContinue(callbacks)) {
5888
5895
  return cancelledResult(existingThreadId);
5889
5896
  }
5890
- const threadId = await prepareThread(processPool, client, workingDirectory, environment, existingThreadId);
5897
+ threadLease = await prepareThread(processPool, client, workingDirectory, environment, existingThreadId);
5898
+ const threadId = threadLease.threadId;
5891
5899
  route.setThreadId(threadId);
5892
5900
  await callbacks.onThreadPrepared(threadId);
5893
5901
  if (!canContinue(callbacks)) {
@@ -5937,10 +5945,14 @@ async function executeCodex(processPool, ownerId, workingDirectory, environment,
5937
5945
  } catch (error) {
5938
5946
  return failedResult(error, route.threadId() ?? existingThreadId);
5939
5947
  } finally {
5940
- if (slot !== void 0) {
5941
- processPool.releaseExecutionSlot(slot);
5948
+ try {
5949
+ if (slot !== void 0) {
5950
+ processPool.releaseExecutionSlot(slot);
5951
+ }
5952
+ processPool.unregister(ownerId);
5953
+ } finally {
5954
+ await threadLease?.release();
5942
5955
  }
5943
- processPool.unregister(ownerId);
5944
5956
  }
5945
5957
  }
5946
5958
  async function prepareThread(processPool, client, workingDirectory, environment, existingThreadId) {
@@ -5957,22 +5969,10 @@ async function prepareThread(processPool, client, workingDirectory, environment,
5957
5969
  ephemeral: false,
5958
5970
  sandbox: "danger-full-access"
5959
5971
  };
5960
- if (existingThreadId === void 0) {
5961
- const threadId = requireThreadId(await client.request("thread/start", parameters));
5962
- processPool.rememberThreadLoaded(threadId);
5963
- return threadId;
5964
- }
5965
- if (!processPool.isThreadLoaded(existingThreadId)) {
5966
- const threadId = requireThreadId(await client.request("thread/resume", {
5967
- ...parameters,
5968
- threadId: existingThreadId
5969
- }));
5970
- if (threadId !== existingThreadId) {
5971
- throw new Error("Codex App Server resumed another thread");
5972
- }
5973
- processPool.rememberThreadLoaded(threadId);
5974
- }
5975
- return existingThreadId;
5972
+ return await processPool.acquireThread(client, existingThreadId, async () => requireThreadId(existingThreadId === void 0 ? await client.request("thread/start", parameters) : await client.request("thread/resume", {
5973
+ ...parameters,
5974
+ threadId: existingThreadId
5975
+ })));
5976
5976
  }
5977
5977
  async function acquireExecutionSlot(processPool, ownerId, callbacks) {
5978
5978
  while (canContinue(callbacks)) {
@@ -8871,6 +8871,712 @@ var init_store = __esm({
8871
8871
  }
8872
8872
  });
8873
8873
 
8874
+ // ../machine-connector/node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js
8875
+ var require_ignore = __commonJS({
8876
+ "../machine-connector/node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"(exports2, module2) {
8877
+ "use strict";
8878
+ init_cjs_shims();
8879
+ function makeArray(subject) {
8880
+ return Array.isArray(subject) ? subject : [subject];
8881
+ }
8882
+ var UNDEFINED = void 0;
8883
+ var EMPTY = "";
8884
+ var SPACE = " ";
8885
+ var ESCAPE = "\\";
8886
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
8887
+ var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
8888
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
8889
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
8890
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
8891
+ var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
8892
+ var REGEX_TEST_TRAILING_SLASH = /\/$/;
8893
+ var SLASH = "/";
8894
+ var TMP_KEY_IGNORE = "node-ignore";
8895
+ if (typeof Symbol !== "undefined") {
8896
+ TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
8897
+ }
8898
+ var KEY_IGNORE = TMP_KEY_IGNORE;
8899
+ var define = (object, key, value) => {
8900
+ Object.defineProperty(object, key, { value });
8901
+ return value;
8902
+ };
8903
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
8904
+ var RETURN_FALSE = () => false;
8905
+ var sanitizeRange = (range) => range.replace(
8906
+ REGEX_REGEXP_RANGE,
8907
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
8908
+ );
8909
+ var cleanRangeBackSlash = (slashes) => {
8910
+ const { length } = slashes;
8911
+ return slashes.slice(0, length - length % 2);
8912
+ };
8913
+ var REPLACERS = [
8914
+ [
8915
+ // Remove BOM
8916
+ // TODO:
8917
+ // Other similar zero-width characters?
8918
+ /^\uFEFF/,
8919
+ () => EMPTY
8920
+ ],
8921
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
8922
+ [
8923
+ // (a\ ) -> (a )
8924
+ // (a ) -> (a)
8925
+ // (a ) -> (a)
8926
+ // (a \ ) -> (a )
8927
+ /((?:\\\\)*?)(\\?\s+)$/,
8928
+ (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
8929
+ ],
8930
+ // Replace (\ ) with ' '
8931
+ // (\ ) -> ' '
8932
+ // (\\ ) -> '\\ '
8933
+ // (\\\ ) -> '\\ '
8934
+ [
8935
+ /(\\+?)\s/g,
8936
+ (_, m1) => {
8937
+ const { length } = m1;
8938
+ return m1.slice(0, length - length % 2) + SPACE;
8939
+ }
8940
+ ],
8941
+ // Escape metacharacters
8942
+ // which is written down by users but means special for regular expressions.
8943
+ // > There are 12 characters with special meanings:
8944
+ // > - the backslash \,
8945
+ // > - the caret ^,
8946
+ // > - the dollar sign $,
8947
+ // > - the period or dot .,
8948
+ // > - the vertical bar or pipe symbol |,
8949
+ // > - the question mark ?,
8950
+ // > - the asterisk or star *,
8951
+ // > - the plus sign +,
8952
+ // > - the opening parenthesis (,
8953
+ // > - the closing parenthesis ),
8954
+ // > - and the opening square bracket [,
8955
+ // > - the opening curly brace {,
8956
+ // > These special characters are often called "metacharacters".
8957
+ [
8958
+ /[\\$.|*+(){^]/g,
8959
+ (match) => `\\${match}`
8960
+ ],
8961
+ [
8962
+ // > a question mark (?) matches a single character
8963
+ /(?!\\)\?/g,
8964
+ () => "[^/]"
8965
+ ],
8966
+ // leading slash
8967
+ [
8968
+ // > A leading slash matches the beginning of the pathname.
8969
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
8970
+ // A leading slash matches the beginning of the pathname
8971
+ /^\//,
8972
+ () => "^"
8973
+ ],
8974
+ // replace special metacharacter slash after the leading slash
8975
+ [
8976
+ /\//g,
8977
+ () => "\\/"
8978
+ ],
8979
+ [
8980
+ // > A leading "**" followed by a slash means match in all directories.
8981
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
8982
+ // > the same as pattern "foo".
8983
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
8984
+ // > under directory "foo".
8985
+ // Notice that the '*'s have been replaced as '\\*'
8986
+ /^\^*\\\*\\\*\\\//,
8987
+ // '**/foo' <-> 'foo'
8988
+ () => "^(?:.*\\/)?"
8989
+ ],
8990
+ // starting
8991
+ [
8992
+ // there will be no leading '/'
8993
+ // (which has been replaced by section "leading slash")
8994
+ // If starts with '**', adding a '^' to the regular expression also works
8995
+ /^(?=[^^])/,
8996
+ function startingReplacer() {
8997
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
8998
+ }
8999
+ ],
9000
+ // two globstars
9001
+ [
9002
+ // Use lookahead assertions so that we could match more than one `'/**'`
9003
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
9004
+ // Zero, one or several directories
9005
+ // should not use '*', or it will be replaced by the next replacer
9006
+ // Check if it is not the last `'/**'`
9007
+ (_, index2, str) => index2 + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
9008
+ ],
9009
+ // normal intermediate wildcards
9010
+ [
9011
+ // Never replace escaped '*'
9012
+ // ignore rule '\*' will match the path '*'
9013
+ // 'abc.*/' -> go
9014
+ // 'abc.*' -> skip this rule,
9015
+ // coz trailing single wildcard will be handed by [trailing wildcard]
9016
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
9017
+ // '*.js' matches '.js'
9018
+ // '*.js' doesn't match 'abc'
9019
+ (_, p1, p2) => {
9020
+ const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
9021
+ return p1 + unescaped;
9022
+ }
9023
+ ],
9024
+ [
9025
+ // unescape, revert step 3 except for back slash
9026
+ // For example, if a user escape a '\\*',
9027
+ // after step 3, the result will be '\\\\\\*'
9028
+ /\\\\\\(?=[$.|*+(){^])/g,
9029
+ () => ESCAPE
9030
+ ],
9031
+ [
9032
+ // '\\\\' -> '\\'
9033
+ /\\\\/g,
9034
+ () => ESCAPE
9035
+ ],
9036
+ [
9037
+ // > The range notation, e.g. [a-zA-Z],
9038
+ // > can be used to match one of the characters in a range.
9039
+ // `\` is escaped by step 3
9040
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
9041
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
9042
+ ],
9043
+ // ending
9044
+ [
9045
+ // 'js' will not match 'js.'
9046
+ // 'ab' will not match 'abc'
9047
+ /(?:[^*])$/,
9048
+ // WTF!
9049
+ // https://git-scm.com/docs/gitignore
9050
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
9051
+ // which re-fixes #24, #38
9052
+ // > If there is a separator at the end of the pattern then the pattern
9053
+ // > will only match directories, otherwise the pattern can match both
9054
+ // > files and directories.
9055
+ // 'js*' will not match 'a.js'
9056
+ // 'js/' will not match 'a.js'
9057
+ // 'js' will match 'a.js' and 'a.js/'
9058
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
9059
+ ]
9060
+ ];
9061
+ var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
9062
+ var MODE_IGNORE = "regex";
9063
+ var MODE_CHECK_IGNORE = "checkRegex";
9064
+ var UNDERSCORE = "_";
9065
+ var TRAILING_WILD_CARD_REPLACERS = {
9066
+ [MODE_IGNORE](_, p1) {
9067
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
9068
+ return `${prefix}(?=$|\\/$)`;
9069
+ },
9070
+ [MODE_CHECK_IGNORE](_, p1) {
9071
+ const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
9072
+ return `${prefix}(?=$|\\/$)`;
9073
+ }
9074
+ };
9075
+ var makeRegexPrefix = (pattern) => REPLACERS.reduce(
9076
+ (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
9077
+ pattern
9078
+ );
9079
+ var isString = (subject) => typeof subject === "string";
9080
+ var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
9081
+ var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
9082
+ var IgnoreRule = class {
9083
+ constructor(pattern, mark, body, ignoreCase, negative, prefix) {
9084
+ this.pattern = pattern;
9085
+ this.mark = mark;
9086
+ this.negative = negative;
9087
+ define(this, "body", body);
9088
+ define(this, "ignoreCase", ignoreCase);
9089
+ define(this, "regexPrefix", prefix);
9090
+ }
9091
+ get regex() {
9092
+ const key = UNDERSCORE + MODE_IGNORE;
9093
+ if (this[key]) {
9094
+ return this[key];
9095
+ }
9096
+ return this._make(MODE_IGNORE, key);
9097
+ }
9098
+ get checkRegex() {
9099
+ const key = UNDERSCORE + MODE_CHECK_IGNORE;
9100
+ if (this[key]) {
9101
+ return this[key];
9102
+ }
9103
+ return this._make(MODE_CHECK_IGNORE, key);
9104
+ }
9105
+ _make(mode, key) {
9106
+ const str = this.regexPrefix.replace(
9107
+ REGEX_REPLACE_TRAILING_WILDCARD,
9108
+ // It does not need to bind pattern
9109
+ TRAILING_WILD_CARD_REPLACERS[mode]
9110
+ );
9111
+ const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
9112
+ return define(this, key, regex);
9113
+ }
9114
+ };
9115
+ var createRule = ({
9116
+ pattern,
9117
+ mark
9118
+ }, ignoreCase) => {
9119
+ let negative = false;
9120
+ let body = pattern;
9121
+ if (body.indexOf("!") === 0) {
9122
+ negative = true;
9123
+ body = body.substr(1);
9124
+ }
9125
+ body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
9126
+ const regexPrefix = makeRegexPrefix(body);
9127
+ return new IgnoreRule(
9128
+ pattern,
9129
+ mark,
9130
+ body,
9131
+ ignoreCase,
9132
+ negative,
9133
+ regexPrefix
9134
+ );
9135
+ };
9136
+ var RuleManager = class {
9137
+ constructor(ignoreCase) {
9138
+ this._ignoreCase = ignoreCase;
9139
+ this._rules = [];
9140
+ }
9141
+ _add(pattern) {
9142
+ if (pattern && pattern[KEY_IGNORE]) {
9143
+ this._rules = this._rules.concat(pattern._rules._rules);
9144
+ this._added = true;
9145
+ return;
9146
+ }
9147
+ if (isString(pattern)) {
9148
+ pattern = {
9149
+ pattern
9150
+ };
9151
+ }
9152
+ if (checkPattern(pattern.pattern)) {
9153
+ const rule = createRule(pattern, this._ignoreCase);
9154
+ this._added = true;
9155
+ this._rules.push(rule);
9156
+ }
9157
+ }
9158
+ // @param {Array<string> | string | Ignore} pattern
9159
+ add(pattern) {
9160
+ this._added = false;
9161
+ makeArray(
9162
+ isString(pattern) ? splitPattern(pattern) : pattern
9163
+ ).forEach(this._add, this);
9164
+ return this._added;
9165
+ }
9166
+ // Test one single path without recursively checking parent directories
9167
+ //
9168
+ // - checkUnignored `boolean` whether should check if the path is unignored,
9169
+ // setting `checkUnignored` to `false` could reduce additional
9170
+ // path matching.
9171
+ // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
9172
+ // @returns {TestResult} true if a file is ignored
9173
+ test(path4, checkUnignored, mode) {
9174
+ let ignored = false;
9175
+ let unignored = false;
9176
+ let matchedRule;
9177
+ this._rules.forEach((rule) => {
9178
+ const { negative } = rule;
9179
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
9180
+ return;
9181
+ }
9182
+ const matched = rule[mode].test(path4);
9183
+ if (!matched) {
9184
+ return;
9185
+ }
9186
+ ignored = !negative;
9187
+ unignored = negative;
9188
+ matchedRule = negative ? UNDEFINED : rule;
9189
+ });
9190
+ const ret = {
9191
+ ignored,
9192
+ unignored
9193
+ };
9194
+ if (matchedRule) {
9195
+ ret.rule = matchedRule;
9196
+ }
9197
+ return ret;
9198
+ }
9199
+ };
9200
+ var throwError = (message, Ctor) => {
9201
+ throw new Ctor(message);
9202
+ };
9203
+ var checkPath = (path4, originalPath, doThrow) => {
9204
+ if (!isString(path4)) {
9205
+ return doThrow(
9206
+ `path must be a string, but got \`${originalPath}\``,
9207
+ TypeError
9208
+ );
9209
+ }
9210
+ if (!path4) {
9211
+ return doThrow(`path must not be empty`, TypeError);
9212
+ }
9213
+ if (checkPath.isNotRelative(path4)) {
9214
+ const r = "`path.relative()`d";
9215
+ return doThrow(
9216
+ `path should be a ${r} string, but got "${originalPath}"`,
9217
+ RangeError
9218
+ );
9219
+ }
9220
+ return true;
9221
+ };
9222
+ var isNotRelative = (path4) => REGEX_TEST_INVALID_PATH.test(path4);
9223
+ checkPath.isNotRelative = isNotRelative;
9224
+ checkPath.convert = (p) => p;
9225
+ var Ignore = class {
9226
+ constructor({
9227
+ ignorecase = true,
9228
+ ignoreCase = ignorecase,
9229
+ allowRelativePaths = false
9230
+ } = {}) {
9231
+ define(this, KEY_IGNORE, true);
9232
+ this._rules = new RuleManager(ignoreCase);
9233
+ this._strictPathCheck = !allowRelativePaths;
9234
+ this._initCache();
9235
+ }
9236
+ _initCache() {
9237
+ this._ignoreCache = /* @__PURE__ */ Object.create(null);
9238
+ this._testCache = /* @__PURE__ */ Object.create(null);
9239
+ }
9240
+ add(pattern) {
9241
+ if (this._rules.add(pattern)) {
9242
+ this._initCache();
9243
+ }
9244
+ return this;
9245
+ }
9246
+ // legacy
9247
+ addPattern(pattern) {
9248
+ return this.add(pattern);
9249
+ }
9250
+ // @returns {TestResult}
9251
+ _test(originalPath, cache, checkUnignored, slices) {
9252
+ const path4 = originalPath && checkPath.convert(originalPath);
9253
+ checkPath(
9254
+ path4,
9255
+ originalPath,
9256
+ this._strictPathCheck ? throwError : RETURN_FALSE
9257
+ );
9258
+ return this._t(path4, cache, checkUnignored, slices);
9259
+ }
9260
+ checkIgnore(path4) {
9261
+ if (!REGEX_TEST_TRAILING_SLASH.test(path4)) {
9262
+ return this.test(path4);
9263
+ }
9264
+ const slices = path4.split(SLASH).filter(Boolean);
9265
+ slices.pop();
9266
+ if (slices.length) {
9267
+ const parent = this._t(
9268
+ slices.join(SLASH) + SLASH,
9269
+ this._testCache,
9270
+ true,
9271
+ slices
9272
+ );
9273
+ if (parent.ignored) {
9274
+ return parent;
9275
+ }
9276
+ }
9277
+ return this._rules.test(path4, false, MODE_CHECK_IGNORE);
9278
+ }
9279
+ _t(path4, cache, checkUnignored, slices) {
9280
+ if (path4 in cache) {
9281
+ return cache[path4];
9282
+ }
9283
+ if (!slices) {
9284
+ slices = path4.split(SLASH).filter(Boolean);
9285
+ }
9286
+ slices.pop();
9287
+ if (!slices.length) {
9288
+ return cache[path4] = this._rules.test(path4, checkUnignored, MODE_IGNORE);
9289
+ }
9290
+ const parent = this._t(
9291
+ slices.join(SLASH) + SLASH,
9292
+ cache,
9293
+ checkUnignored,
9294
+ slices
9295
+ );
9296
+ return cache[path4] = parent.ignored ? parent : this._rules.test(path4, checkUnignored, MODE_IGNORE);
9297
+ }
9298
+ ignores(path4) {
9299
+ return this._test(path4, this._ignoreCache, false).ignored;
9300
+ }
9301
+ createFilter() {
9302
+ return (path4) => !this.ignores(path4);
9303
+ }
9304
+ filter(paths) {
9305
+ return makeArray(paths).filter(this.createFilter());
9306
+ }
9307
+ // @returns {TestResult}
9308
+ test(path4) {
9309
+ return this._test(path4, this._testCache, true);
9310
+ }
9311
+ };
9312
+ var factory = (options) => new Ignore(options);
9313
+ var isPathValid = (path4) => checkPath(path4 && checkPath.convert(path4), path4, RETURN_FALSE);
9314
+ var setupWindows = () => {
9315
+ const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
9316
+ checkPath.convert = makePosix;
9317
+ const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
9318
+ checkPath.isNotRelative = (path4) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path4) || isNotRelative(path4);
9319
+ };
9320
+ if (
9321
+ // Detect `process` so that it can run in browsers.
9322
+ typeof process !== "undefined" && process.platform === "win32"
9323
+ ) {
9324
+ setupWindows();
9325
+ }
9326
+ module2.exports = factory;
9327
+ factory.default = factory;
9328
+ module2.exports.isPathValid = isPathValid;
9329
+ define(module2.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
9330
+ }
9331
+ });
9332
+
9333
+ // ../machine-connector/dist/runtime/local-codex-runtime/local-file-source.js
9334
+ function resolveWithin(root, input) {
9335
+ if (input.length === 0 || input.includes("\0") || (0, import_node_path9.isAbsolute)(input) || import_node_path9.win32.isAbsolute(input) || /^[A-Za-z]:/.test(input) || input.split(/[\\/]/).includes("..")) {
9336
+ throw new Error("Local file path escapes its root");
9337
+ }
9338
+ const resolved = (0, import_node_path9.resolve)(root, input);
9339
+ assertContained(root, resolved);
9340
+ return resolved;
9341
+ }
9342
+ function assertContained(root, candidate) {
9343
+ const rel = (0, import_node_path9.relative)(root, candidate);
9344
+ if (rel === ".." || rel.startsWith(`..${import_node_path9.sep}`) || (0, import_node_path9.isAbsolute)(rel))
9345
+ throw new Error("Local file path escapes its root");
9346
+ }
9347
+ function portable(path4) {
9348
+ const value = path4.split(import_node_path9.sep).join("/");
9349
+ return value === "" ? "." : value;
9350
+ }
9351
+ function isGitPath(path4) {
9352
+ return path4.split("/").includes(".git");
9353
+ }
9354
+ function relativePortable(base, path4) {
9355
+ if (base === "." || base === "")
9356
+ return path4;
9357
+ if (path4 === base)
9358
+ return ".";
9359
+ return path4.startsWith(`${base}/`) ? path4.slice(base.length + 1) : void 0;
9360
+ }
9361
+ function page(entries, cursor, limit) {
9362
+ const offset = cursor === void 0 ? 0 : Number.parseInt(cursor, 10);
9363
+ if (!Number.isSafeInteger(offset) || offset < 0)
9364
+ throw new Error("Local file cursor is invalid");
9365
+ const selected = entries.slice(offset, offset + limit);
9366
+ const nextOffset = offset + selected.length;
9367
+ return { entries: selected, ...nextOffset < entries.length ? { nextCursor: String(nextOffset) } : {}, truncated: nextOffset < entries.length };
9368
+ }
9369
+ function clampLimit(limit) {
9370
+ if (!Number.isSafeInteger(limit) || limit < 1)
9371
+ return defaultPageSize;
9372
+ return Math.min(limit, maximumPageSize);
9373
+ }
9374
+ function compareEntries(left, right) {
9375
+ if (left.kind !== right.kind)
9376
+ return left.kind === "directory" ? -1 : 1;
9377
+ return left.name.localeCompare(right.name, void 0, { numeric: true, sensitivity: "base" });
9378
+ }
9379
+ function isMissing(error) {
9380
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
9381
+ }
9382
+ function isUtf8(buffer2) {
9383
+ try {
9384
+ new TextDecoder("utf-8", { fatal: true }).decode(buffer2);
9385
+ return true;
9386
+ } catch {
9387
+ return false;
9388
+ }
9389
+ }
9390
+ var import_promises12, import_node_path9, import_ignore, maximumReadBytes, defaultPageSize, maximumPageSize, searchScanBudget, LocalFileSource, ScopedIgnoreMatcher;
9391
+ var init_local_file_source = __esm({
9392
+ "../machine-connector/dist/runtime/local-codex-runtime/local-file-source.js"() {
9393
+ "use strict";
9394
+ init_cjs_shims();
9395
+ import_promises12 = require("fs/promises");
9396
+ import_node_path9 = require("path");
9397
+ import_ignore = __toESM(require_ignore(), 1);
9398
+ maximumReadBytes = 5 * 1024 * 1024;
9399
+ defaultPageSize = 100;
9400
+ maximumPageSize = 200;
9401
+ searchScanBudget = 1e4;
9402
+ LocalFileSource = class _LocalFileSource {
9403
+ pairedRoot;
9404
+ workingDirectory;
9405
+ constructor(pairedRoot, workingDirectory) {
9406
+ this.pairedRoot = pairedRoot;
9407
+ this.workingDirectory = workingDirectory;
9408
+ }
9409
+ static async create(pairedRoot, relativeWorkingDirectory) {
9410
+ const root = await (0, import_promises12.realpath)((0, import_node_path9.resolve)(pairedRoot));
9411
+ const requested = resolveWithin(root, relativeWorkingDirectory);
9412
+ const workingDirectory = await (0, import_promises12.realpath)(requested);
9413
+ assertContained(root, workingDirectory);
9414
+ const stat6 = await (0, import_promises12.lstat)(workingDirectory);
9415
+ if (!stat6.isDirectory())
9416
+ throw new Error("Local file working directory is not a directory");
9417
+ return new _LocalFileSource(root, workingDirectory);
9418
+ }
9419
+ async list(relativeDirectory = ".", cursor, requestedLimit = defaultPageSize) {
9420
+ const limit = clampLimit(requestedLimit);
9421
+ const directory = await this.resolveDirectory(relativeDirectory);
9422
+ const matcher = await this.ignoreMatcher(directory);
9423
+ const candidates2 = await Promise.all((await (0, import_promises12.readdir)(directory, { withFileTypes: true })).map(async (entry) => {
9424
+ if (entry.name.includes("\\"))
9425
+ return void 0;
9426
+ const absolute = (0, import_node_path9.join)(directory, entry.name);
9427
+ const path4 = portable((0, import_node_path9.relative)(this.workingDirectory, absolute));
9428
+ const rootPath = portable((0, import_node_path9.relative)(this.pairedRoot, absolute));
9429
+ if (matcher.ignores(rootPath) || isGitPath(rootPath))
9430
+ return void 0;
9431
+ if (entry.isDirectory())
9432
+ return { kind: "directory", name: entry.name, path: path4 };
9433
+ if (!entry.isFile())
9434
+ return void 0;
9435
+ const stat6 = await (0, import_promises12.lstat)(absolute);
9436
+ return { kind: "file", name: entry.name, path: path4, size: stat6.size };
9437
+ }));
9438
+ const entries = candidates2.filter((entry) => entry !== void 0).sort(compareEntries);
9439
+ return page(entries, cursor, limit);
9440
+ }
9441
+ async search(query, cursor, requestedLimit = defaultPageSize) {
9442
+ const normalizedQuery = query.trim().toLocaleLowerCase();
9443
+ const limit = clampLimit(requestedLimit);
9444
+ const matches = [];
9445
+ const pending = [this.workingDirectory];
9446
+ let scanned = 0;
9447
+ while (pending.length > 0 && scanned < searchScanBudget) {
9448
+ const directory = pending.shift();
9449
+ if (directory === void 0)
9450
+ break;
9451
+ const matcher = await this.ignoreMatcher(directory);
9452
+ for (const entry of await (0, import_promises12.readdir)(directory, { withFileTypes: true })) {
9453
+ scanned += 1;
9454
+ if (scanned > searchScanBudget)
9455
+ break;
9456
+ if (entry.name.includes("\\"))
9457
+ continue;
9458
+ const absolute = (0, import_node_path9.join)(directory, entry.name);
9459
+ const path4 = portable((0, import_node_path9.relative)(this.workingDirectory, absolute));
9460
+ const rootPath = portable((0, import_node_path9.relative)(this.pairedRoot, absolute));
9461
+ if (matcher.ignores(rootPath) || isGitPath(rootPath))
9462
+ continue;
9463
+ if (entry.isDirectory()) {
9464
+ pending.push(absolute);
9465
+ continue;
9466
+ }
9467
+ if (!entry.isFile())
9468
+ continue;
9469
+ if (normalizedQuery === "" || path4.toLocaleLowerCase().includes(normalizedQuery)) {
9470
+ const stat6 = await (0, import_promises12.lstat)(absolute);
9471
+ matches.push({ kind: "file", name: entry.name, path: path4, size: stat6.size });
9472
+ }
9473
+ }
9474
+ }
9475
+ matches.sort((left, right) => left.path.localeCompare(right.path, void 0, { numeric: true }));
9476
+ const result = page(matches, cursor, limit);
9477
+ return { ...result, truncated: result.truncated || scanned >= searchScanBudget };
9478
+ }
9479
+ async read(path4) {
9480
+ const file = await this.resolveFile(path4);
9481
+ const stat6 = await (0, import_promises12.lstat)(file);
9482
+ if (stat6.size > maximumReadBytes)
9483
+ throw new Error("Local file exceeds the preview size limit");
9484
+ const buffer2 = await (0, import_promises12.readFile)(file);
9485
+ const binary = buffer2.includes(0) || !isUtf8(buffer2);
9486
+ return {
9487
+ content: binary ? buffer2.toString("base64") : buffer2.toString("utf8"),
9488
+ encoding: binary ? "base64" : "utf8",
9489
+ name: (0, import_node_path9.basename)(file),
9490
+ path: portable((0, import_node_path9.relative)(this.workingDirectory, file)),
9491
+ size: stat6.size
9492
+ };
9493
+ }
9494
+ async validate(path4) {
9495
+ const file = await this.resolveFile(path4);
9496
+ const stat6 = await (0, import_promises12.lstat)(file);
9497
+ return {
9498
+ kind: "file",
9499
+ name: (0, import_node_path9.basename)(file),
9500
+ path: portable((0, import_node_path9.relative)(this.workingDirectory, file)),
9501
+ size: stat6.size
9502
+ };
9503
+ }
9504
+ async resolveDirectory(path4) {
9505
+ const absolute = resolveWithin(this.workingDirectory, path4);
9506
+ const directStat = await (0, import_promises12.lstat)(absolute);
9507
+ if (directStat.isSymbolicLink() || !directStat.isDirectory()) {
9508
+ throw new Error("Local file path is not a regular directory");
9509
+ }
9510
+ const canonical = await (0, import_promises12.realpath)(absolute);
9511
+ assertContained(this.workingDirectory, canonical);
9512
+ await this.assertVisible(canonical);
9513
+ return canonical;
9514
+ }
9515
+ async resolveFile(path4) {
9516
+ const absolute = resolveWithin(this.workingDirectory, path4);
9517
+ const directStat = await (0, import_promises12.lstat)(absolute);
9518
+ if (directStat.isSymbolicLink() || !directStat.isFile())
9519
+ throw new Error("Local file path is not a regular file");
9520
+ const canonical = await (0, import_promises12.realpath)(absolute);
9521
+ assertContained(this.workingDirectory, canonical);
9522
+ await this.assertVisible(canonical);
9523
+ return canonical;
9524
+ }
9525
+ async assertVisible(absolute) {
9526
+ const rootPath = portable((0, import_node_path9.relative)(this.pairedRoot, absolute));
9527
+ if (rootPath === ".")
9528
+ return;
9529
+ if (isGitPath(rootPath) || (await this.ignoreMatcher((0, import_node_path9.dirname)(absolute))).ignores(rootPath)) {
9530
+ throw new Error("Local file path is ignored");
9531
+ }
9532
+ }
9533
+ async ignoreMatcher(throughDirectory) {
9534
+ const matchers = [{ base: "", matcher: (0, import_ignore.default)().add(".git/").add(".git/**") }];
9535
+ const relativeThrough = (0, import_node_path9.relative)(this.pairedRoot, throughDirectory);
9536
+ const segments = relativeThrough === "" ? [] : relativeThrough.split(import_node_path9.sep);
9537
+ let directory = this.pairedRoot;
9538
+ for (let index2 = 0; index2 <= segments.length; index2 += 1) {
9539
+ const matcher = (0, import_ignore.default)();
9540
+ for (const name of [".gitignore", ".ignore"]) {
9541
+ try {
9542
+ const content3 = await (0, import_promises12.readFile)((0, import_node_path9.join)(directory, name), "utf8");
9543
+ matcher.add(content3);
9544
+ } catch (error) {
9545
+ if (!isMissing(error))
9546
+ throw error;
9547
+ }
9548
+ }
9549
+ matchers.push({ base: portable((0, import_node_path9.relative)(this.pairedRoot, directory)), matcher });
9550
+ const segment = segments[index2];
9551
+ if (segment !== void 0)
9552
+ directory = (0, import_node_path9.join)(directory, segment);
9553
+ }
9554
+ return new ScopedIgnoreMatcher(matchers);
9555
+ }
9556
+ };
9557
+ ScopedIgnoreMatcher = class {
9558
+ rules;
9559
+ constructor(rules) {
9560
+ this.rules = rules;
9561
+ }
9562
+ ignores(rootPath) {
9563
+ let ignored = false;
9564
+ for (const rule of this.rules) {
9565
+ const localPath = relativePortable(rule.base, rootPath);
9566
+ if (localPath === void 0 || localPath === ".")
9567
+ continue;
9568
+ const result = rule.matcher.test(localPath);
9569
+ if (result.ignored)
9570
+ ignored = true;
9571
+ if (result.unignored)
9572
+ ignored = false;
9573
+ }
9574
+ return ignored;
9575
+ }
9576
+ };
9577
+ }
9578
+ });
9579
+
8874
9580
  // ../machine-connector/dist/runtime/local-codex-runtime/durable-attempt.js
8875
9581
  function assertCompatibleClaim(persisted, connectionId, claim, allowRestartFenceRotation) {
8876
9582
  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) {
@@ -9353,10 +10059,10 @@ function redactPath(value, canonicalRoot) {
9353
10059
  if (value === canonicalRoot) {
9354
10060
  return ".";
9355
10061
  }
9356
- if (value.startsWith(`${canonicalRoot}${import_node_path9.sep}`)) {
9357
- return (0, import_node_path9.relative)(canonicalRoot, value);
10062
+ if (value.startsWith(`${canonicalRoot}${import_node_path10.sep}`)) {
10063
+ return (0, import_node_path10.relative)(canonicalRoot, value);
9358
10064
  }
9359
- if ((0, import_node_path9.isAbsolute)(value) || /^[A-Za-z]:[\\/]/.test(value)) {
10065
+ if ((0, import_node_path10.isAbsolute)(value) || /^[A-Za-z]:[\\/]/.test(value)) {
9360
10066
  return "[redacted-absolute-path]";
9361
10067
  }
9362
10068
  return value;
@@ -9405,12 +10111,12 @@ function recordValue(value) {
9405
10111
  function isRecord2(value) {
9406
10112
  return typeof value === "object" && value !== null && !Array.isArray(value);
9407
10113
  }
9408
- var import_node_path9;
10114
+ var import_node_path10;
9409
10115
  var init_event_normalizer = __esm({
9410
10116
  "../machine-connector/dist/runtime/local-codex-runtime/event-normalizer.js"() {
9411
10117
  "use strict";
9412
10118
  init_cjs_shims();
9413
- import_node_path9 = require("path");
10119
+ import_node_path10 = require("path");
9414
10120
  init_contracts2();
9415
10121
  }
9416
10122
  });
@@ -9427,12 +10133,12 @@ function isInactiveTurnInterruptResponse(error) {
9427
10133
  }
9428
10134
  function createActiveAttempt(claim, durable, workingDirectory) {
9429
10135
  let resolveTerminal = (_value) => void 0;
9430
- const terminal = new Promise((resolve10) => {
9431
- resolveTerminal = resolve10;
10136
+ const terminal = new Promise((resolve11) => {
10137
+ resolveTerminal = resolve11;
9432
10138
  });
9433
10139
  let resolveFatal = (_error) => void 0;
9434
- const fatal = new Promise((resolve10) => {
9435
- resolveFatal = resolve10;
10140
+ const fatal = new Promise((resolve11) => {
10141
+ resolveFatal = resolve11;
9436
10142
  });
9437
10143
  return {
9438
10144
  acceptedByAppServer: false,
@@ -9461,8 +10167,8 @@ function createActiveAttempt(claim, durable, workingDirectory) {
9461
10167
  }
9462
10168
  function createThreadTitleGenerationState(threadId) {
9463
10169
  let resolveCompletion = () => void 0;
9464
- const completion = new Promise((resolve10) => {
9465
- resolveCompletion = resolve10;
10170
+ const completion = new Promise((resolve11) => {
10171
+ resolveCompletion = resolve11;
9466
10172
  });
9467
10173
  const state = {
9468
10174
  completed: false,
@@ -9636,8 +10342,9 @@ function requireTurnId2(response) {
9636
10342
  }
9637
10343
  return id;
9638
10344
  }
9639
- function toCodexInput(items) {
9640
- return items.map((item) => {
10345
+ async function toCodexInput(items, pairedRoot, relativeWorkingDirectory) {
10346
+ const source = await LocalFileSource.create(pairedRoot, relativeWorkingDirectory);
10347
+ return await Promise.all(items.map(async (item) => {
9641
10348
  const payload = safeRecord2(item.payload);
9642
10349
  if (item.itemType === "text") {
9643
10350
  return {
@@ -9658,8 +10365,19 @@ function toCodexInput(items) {
9658
10365
  path: optionalString3(payload.path).value ?? ""
9659
10366
  };
9660
10367
  }
10368
+ if (item.itemType === "local_file") {
10369
+ const path4 = optionalString3(payload.path).value;
10370
+ if (path4 === void 0)
10371
+ throw new Error("Local file input has no path");
10372
+ await source.validate(path4);
10373
+ return {
10374
+ type: "text",
10375
+ text: `@${path4}`,
10376
+ text_elements: []
10377
+ };
10378
+ }
9661
10379
  throw new Error(`Unsupported Local Codex input ${item.itemType}`);
9662
- });
10380
+ }));
9663
10381
  }
9664
10382
  function localCodexInputItems(value) {
9665
10383
  if (!Array.isArray(value)) {
@@ -9814,7 +10532,7 @@ async function probeExecutable(executable, environment) {
9814
10532
  const output = [];
9815
10533
  child.stdout?.on("data", (chunk) => output.push(chunk));
9816
10534
  try {
9817
- const code = await new Promise((resolve10, reject) => {
10535
+ const code = await new Promise((resolve11, reject) => {
9818
10536
  const timeout = setTimeout(() => {
9819
10537
  child.kill("SIGTERM");
9820
10538
  reject(new Error("Executable probe timed out"));
@@ -9826,7 +10544,7 @@ async function probeExecutable(executable, environment) {
9826
10544
  });
9827
10545
  child.once("close", (exitCode) => {
9828
10546
  clearTimeout(timeout);
9829
- resolve10(exitCode ?? 1);
10547
+ resolve11(exitCode ?? 1);
9830
10548
  });
9831
10549
  });
9832
10550
  if (code !== 0) {
@@ -9847,11 +10565,11 @@ async function waitForAbort(signal, milliseconds) {
9847
10565
  if (signal.aborted) {
9848
10566
  return;
9849
10567
  }
9850
- await new Promise((resolve10) => {
10568
+ await new Promise((resolve11) => {
9851
10569
  const complete = () => {
9852
10570
  clearTimeout(timeout);
9853
10571
  signal.removeEventListener("abort", complete);
9854
- resolve10();
10572
+ resolve11();
9855
10573
  };
9856
10574
  const timeout = setTimeout(complete, milliseconds);
9857
10575
  timeout.unref();
@@ -9894,20 +10612,21 @@ function parseLeaseDeadline(value) {
9894
10612
  function routineLeaseRenewalDelayMilliseconds(remainingLeaseMilliseconds) {
9895
10613
  return Math.min(leaseRenewIntervalMilliseconds, Math.max(1, Math.floor(remainingLeaseMilliseconds / leaseRenewalIntervalsBeforeDeadline)));
9896
10614
  }
9897
- var import_node_child_process4, import_promises12, import_node_os7, import_node_path10, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewalIntervalsBeforeDeadline, defaultNetworkRetryMilliseconds, maximumNetworkRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryScanIntervalMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
10615
+ var import_node_child_process4, import_promises13, import_node_os7, import_node_path11, heartbeatIntervalMilliseconds, claimRetryMilliseconds, claimWaitSeconds, discoveryWaitSeconds, maximumDiscoveryDirectories, maximumDiscoveryModels, maximumModelListPages, eventUploadCoalesceMilliseconds, maximumEventUploadCount, preferredEventUploadRequestBytes, leaseRenewIntervalMilliseconds, leaseRenewalIntervalsBeforeDeadline, defaultNetworkRetryMilliseconds, maximumNetworkRetryMilliseconds, interactionTimeoutMilliseconds, executableProbeTimeoutMilliseconds, recoveryScanIntervalMilliseconds, initialThreadNameRetryMilliseconds, maximumThreadNameRetryMilliseconds, maximumInitialThreadNameAttempts, maximumThreadTitleCharacters, maximumThreadTitleSourceCharacters, threadTitleGenerationTimeoutMilliseconds, interruptedExecutionCleanupTimeoutMilliseconds, threadTitleGenerationInstructions, threadTitleGenerationOutputSchema, ThreadUnavailableError, LeaseLostError, SpoolPersistenceError, UnknownTurnStartResultError, WorkerStoppedError, LocalCodexRuntimeConnectionWorker;
9898
10616
  var init_runtime_worker = __esm({
9899
10617
  "../machine-connector/dist/runtime/local-codex-runtime/runtime-worker.js"() {
9900
10618
  "use strict";
9901
10619
  init_cjs_shims();
9902
10620
  import_node_child_process4 = require("child_process");
9903
- import_promises12 = require("fs/promises");
10621
+ import_promises13 = require("fs/promises");
9904
10622
  import_node_os7 = require("os");
9905
- import_node_path10 = require("path");
10623
+ import_node_path11 = require("path");
9906
10624
  init_process_executor();
9907
10625
  init_relay_client();
9908
10626
  init_retry_backoff();
9909
10627
  init_app_server_client();
9910
10628
  init_contracts2();
10629
+ init_local_file_source();
9911
10630
  init_durable_attempt();
9912
10631
  init_event_normalizer();
9913
10632
  heartbeatIntervalMilliseconds = 2e4;
@@ -10470,13 +11189,39 @@ var init_runtime_worker = __esm({
10470
11189
  status: LocalCodexDiscoveryStatusWire.Succeeded
10471
11190
  };
10472
11191
  }
11192
+ if (request2.kind === LocalCodexDiscoveryKindWire.LocalFileList || request2.kind === LocalCodexDiscoveryKindWire.LocalFileSearch || request2.kind === LocalCodexDiscoveryKindWire.LocalFileRead || request2.kind === LocalCodexDiscoveryKindWire.LocalFileValidate) {
11193
+ const source = await LocalFileSource.create(this.connection.rootPath, request2.workingDirectory ?? ".");
11194
+ if (request2.kind === LocalCodexDiscoveryKindWire.LocalFileList) {
11195
+ const result = await source.list(request2.relativeDirectory ?? ".", request2.cursor, request2.limit);
11196
+ return { ...result, requestId: request2.requestId, status: LocalCodexDiscoveryStatusWire.Succeeded };
11197
+ }
11198
+ if (request2.kind === LocalCodexDiscoveryKindWire.LocalFileSearch) {
11199
+ const result = await source.search(request2.query ?? "", request2.cursor, request2.limit);
11200
+ return { ...result, requestId: request2.requestId, status: LocalCodexDiscoveryStatusWire.Succeeded };
11201
+ }
11202
+ if (request2.kind === LocalCodexDiscoveryKindWire.LocalFileValidate) {
11203
+ return {
11204
+ entries: [await source.validate(request2.filePath ?? "")],
11205
+ requestId: request2.requestId,
11206
+ status: LocalCodexDiscoveryStatusWire.Succeeded
11207
+ };
11208
+ }
11209
+ const content3 = await source.read(request2.filePath ?? "");
11210
+ return {
11211
+ content: content3.content,
11212
+ encoding: content3.encoding,
11213
+ entries: [{ kind: "file", name: content3.name, path: content3.path, size: content3.size }],
11214
+ requestId: request2.requestId,
11215
+ status: LocalCodexDiscoveryStatusWire.Succeeded
11216
+ };
11217
+ }
10473
11218
  throw new Error("Unsupported Local Codex discovery kind");
10474
11219
  }
10475
11220
  async discoverModels() {
10476
11221
  const client = await this.processPool.ensureStarted();
10477
11222
  const models = /* @__PURE__ */ new Map();
10478
11223
  const cursor = {};
10479
- for (let page = 0; page < maximumModelListPages; page += 1) {
11224
+ for (let page2 = 0; page2 < maximumModelListPages; page2 += 1) {
10480
11225
  const response = await client.request("model/list", {
10481
11226
  cursor: cursor.value ?? null,
10482
11227
  includeHidden: false,
@@ -10499,7 +11244,7 @@ var init_runtime_worker = __esm({
10499
11244
  async discoverDirectories(relativeDirectory) {
10500
11245
  const canonicalRoot = await resolveCanonicalWorkingDirectory(this.connection.rootPath, ".");
10501
11246
  const canonicalDirectory = await resolveCanonicalWorkingDirectory(canonicalRoot, relativeDirectory);
10502
- const entries = (await (0, import_promises12.readdir)(canonicalDirectory, {
11247
+ const entries = (await (0, import_promises13.readdir)(canonicalDirectory, {
10503
11248
  withFileTypes: true
10504
11249
  })).filter((entry) => entry.isDirectory()).filter((entry) => !entry.name.includes("\\")).sort((left, right) => left.name.localeCompare(right.name, void 0, {
10505
11250
  numeric: true,
@@ -10507,11 +11252,11 @@ var init_runtime_worker = __esm({
10507
11252
  }));
10508
11253
  const eligibleDirectories = entries.map((entry) => ({
10509
11254
  name: entry.name,
10510
- relativePath: portableRelativeDirectory((0, import_node_path10.relative)(canonicalRoot, (0, import_node_path10.join)(canonicalDirectory, entry.name)))
11255
+ relativePath: portableRelativeDirectory((0, import_node_path11.relative)(canonicalRoot, (0, import_node_path11.join)(canonicalDirectory, entry.name)))
10511
11256
  })).filter((entry) => entry.name.length <= 255 && entry.relativePath.length <= 1024);
10512
11257
  const directories = eligibleDirectories.slice(0, maximumDiscoveryDirectories);
10513
11258
  return {
10514
- currentRelativeDirectory: portableRelativeDirectory((0, import_node_path10.relative)(canonicalRoot, canonicalDirectory)),
11259
+ currentRelativeDirectory: portableRelativeDirectory((0, import_node_path11.relative)(canonicalRoot, canonicalDirectory)),
10515
11260
  directories,
10516
11261
  truncated: eligibleDirectories.length > maximumDiscoveryDirectories
10517
11262
  };
@@ -10530,6 +11275,7 @@ var init_runtime_worker = __esm({
10530
11275
  this.activeAttempts.set(claim.attemptId, active);
10531
11276
  const leaseLoop = this.runLeaseLoop(active);
10532
11277
  const controlLoop = this.runControlLoop(active);
11278
+ let threadLease;
10533
11279
  try {
10534
11280
  active.workingDirectory = await resolveCanonicalWorkingDirectory(this.connection.rootPath, claim.relativeWorkingDirectory);
10535
11281
  if (active.fatalError !== void 0) {
@@ -10540,17 +11286,17 @@ var init_runtime_worker = __esm({
10540
11286
  throw active.fatalError;
10541
11287
  }
10542
11288
  const isNewThread = active.nativeThreadId === void 0;
10543
- let nativeThreadId;
10544
11289
  try {
10545
- nativeThreadId = await this.prepareThread(client, active);
11290
+ threadLease = await this.prepareThread(client, active);
10546
11291
  } catch (error) {
10547
11292
  if (!(error instanceof AppServerRequestTimeoutError) || error.method !== "thread/resume") {
10548
11293
  throw error;
10549
11294
  }
10550
11295
  await this.processPool.quarantineCurrentProcess();
10551
11296
  client = await this.processPool.ensureStarted();
10552
- nativeThreadId = await this.prepareThread(client, active);
11297
+ threadLease = await this.prepareThread(client, active);
10553
11298
  }
11299
+ const nativeThreadId = threadLease.threadId;
10554
11300
  active.nativeThreadId = nativeThreadId;
10555
11301
  active.appServerClient = client;
10556
11302
  if (active.fatalError !== void 0) {
@@ -10577,7 +11323,7 @@ var init_runtime_worker = __esm({
10577
11323
  approvalPolicy: claim.approvalPolicy,
10578
11324
  cwd: active.workingDirectory,
10579
11325
  effort: claim.reasoningEffort,
10580
- input: toCodexInput(claim.inputItems),
11326
+ input: await toCodexInput(claim.inputItems, this.connection.rootPath, claim.relativeWorkingDirectory),
10581
11327
  ...claim.model === void 0 ? {} : { model: claim.model },
10582
11328
  sandboxPolicy: toSandboxPolicy(claim.sandboxPolicy, active.workingDirectory),
10583
11329
  summary: "auto",
@@ -10673,7 +11419,11 @@ var init_runtime_worker = __esm({
10673
11419
  }
10674
11420
  await Promise.all([leaseLoop, controlLoop]);
10675
11421
  } finally {
10676
- this.activeAttempts.delete(claim.attemptId);
11422
+ try {
11423
+ await threadLease?.release();
11424
+ } finally {
11425
+ this.activeAttempts.delete(claim.attemptId);
11426
+ }
10677
11427
  }
10678
11428
  }
10679
11429
  }
@@ -10691,30 +11441,21 @@ var init_runtime_worker = __esm({
10691
11441
  sandbox: claim.sandboxPolicy
10692
11442
  };
10693
11443
  const preparedThreadId = active.nativeThreadId;
10694
- if (preparedThreadId === void 0) {
10695
- const startedThreadId = requireThreadId2(await client.request("thread/start", parameters));
10696
- this.processPool.rememberThreadLoaded(startedThreadId);
10697
- return startedThreadId;
10698
- }
10699
- if (this.processPool.isThreadLoaded(preparedThreadId)) {
10700
- return preparedThreadId;
10701
- }
10702
11444
  try {
10703
- const resumed = await client.request("thread/resume", {
10704
- ...parameters,
10705
- threadId: preparedThreadId
11445
+ return await this.processPool.acquireThread(client, preparedThreadId, async () => {
11446
+ if (preparedThreadId === void 0) {
11447
+ return requireThreadId2(await client.request("thread/start", parameters));
11448
+ }
11449
+ return requireThreadId2(await client.request("thread/resume", {
11450
+ ...parameters,
11451
+ threadId: preparedThreadId
11452
+ }));
10706
11453
  });
10707
- const resumedId = requireThreadId2(resumed);
10708
- if (resumedId !== preparedThreadId) {
10709
- throw new AppServerProtocolError("thread/resume returned another native thread");
10710
- }
10711
- this.processPool.rememberThreadLoaded(resumedId);
10712
- return resumedId;
10713
11454
  } catch (error) {
10714
11455
  if (error instanceof AppServerProcessLostError || error instanceof AppServerRequestTimeoutError) {
10715
11456
  throw error;
10716
11457
  }
10717
- if (error instanceof AppServerResponseError && isMissingThreadResponse(error.responseMessage, preparedThreadId)) {
11458
+ if (error instanceof AppServerResponseError && preparedThreadId !== void 0 && isMissingThreadResponse(error.responseMessage, preparedThreadId)) {
10718
11459
  throw new ThreadUnavailableError(errorMessage3(error));
10719
11460
  }
10720
11461
  throw error;
@@ -10929,8 +11670,8 @@ var init_runtime_worker = __esm({
10929
11670
  const retryBackoff = this.createNetworkRetryBackoff();
10930
11671
  while (!active.finished.signal.aborted && !this.lifetimeAbort.signal.aborted) {
10931
11672
  try {
10932
- const page = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
10933
- for (const control of page.controls) {
11673
+ const page2 = await this.relay.pollCodexRuntimeControls(active.claim.attemptId, fenceFor(active.claim, this.connectorInstanceId), active.controlCursor, 25, active.finished.signal);
11674
+ for (const control of page2.controls) {
10934
11675
  await this.applyControl(active, control);
10935
11676
  active.controlCursor = Math.max(active.controlCursor, control.cursor);
10936
11677
  }
@@ -10990,7 +11731,7 @@ var init_runtime_worker = __esm({
10990
11731
  const response = await client.request("turn/steer", {
10991
11732
  clientUserMessageId: clientMessageId,
10992
11733
  expectedTurnId: active.nativeTurnId,
10993
- input: toCodexInput(inputItems),
11734
+ input: await toCodexInput(inputItems, this.connection.rootPath, active.claim.relativeWorkingDirectory),
10994
11735
  threadId: active.nativeThreadId
10995
11736
  });
10996
11737
  if (response.turnId !== active.nativeTurnId) {
@@ -11199,6 +11940,7 @@ var init_runtime_worker = __esm({
11199
11940
  const moxt = await probeExecutable(process.env.MOXT_CLI_PATH ?? "moxt", this.environment);
11200
11941
  return await this.relay.heartbeatCodexRuntime({
11201
11942
  ...capability,
11943
+ capabilities: [localFilesCapability],
11202
11944
  connectorInstanceId: this.connectorInstanceId,
11203
11945
  moxtCliStatus: moxt.status,
11204
11946
  moxtCliVersion: moxt.version,
@@ -11404,6 +12146,15 @@ ${titleInput}`,
11404
12146
  });
11405
12147
 
11406
12148
  // ../machine-connector/dist/runtime/local-codex-runtime/process-pool.js
12149
+ function requireThreadUnsubscribeStatus(response) {
12150
+ if (typeof response !== "object" || response === null || !("status" in response)) {
12151
+ throw new Error("Codex App Server returned an invalid thread unsubscribe response");
12152
+ }
12153
+ const status = response.status;
12154
+ if (status !== "notLoaded" && status !== "notSubscribed" && status !== "unsubscribed") {
12155
+ throw new Error("Codex App Server returned an invalid thread unsubscribe status");
12156
+ }
12157
+ }
11407
12158
  function localCodexProcessPoolKey(environment, nativeStoreIdentitySeed) {
11408
12159
  return (0, import_node_crypto7.createHash)("sha256").update([
11409
12160
  String(process.getuid?.() ?? process.pid),
@@ -11425,16 +12176,23 @@ var init_process_pool = __esm({
11425
12176
  LocalCodexProcessPool = class {
11426
12177
  poolKey;
11427
12178
  logger;
12179
+ threadCacheCapacity;
11428
12180
  activeSlots = /* @__PURE__ */ new Map();
11429
- loadedThreadIds = /* @__PURE__ */ new Set();
12181
+ loadedThreads = /* @__PURE__ */ new Map();
12182
+ loadingThreads = /* @__PURE__ */ new Map();
11430
12183
  nextSlotId = 1;
11431
12184
  routes = /* @__PURE__ */ new Map();
11432
12185
  retiredTurnIds = /* @__PURE__ */ new Set();
11433
12186
  supervisor;
12187
+ threadCacheOperation = Promise.resolve();
11434
12188
  waitingOwners = [];
11435
- constructor(poolKey, environment, nativeStoreIdentitySeed, store, logger) {
12189
+ constructor(poolKey, environment, nativeStoreIdentitySeed, store, logger, threadCacheCapacity) {
11436
12190
  this.poolKey = poolKey;
11437
12191
  this.logger = logger;
12192
+ this.threadCacheCapacity = threadCacheCapacity;
12193
+ if (!Number.isSafeInteger(threadCacheCapacity) || threadCacheCapacity < 1) {
12194
+ throw new Error("Local Codex thread cache capacity must be a positive safe integer");
12195
+ }
11438
12196
  this.supervisor = new LocalCodexAppServerSupervisor(environment.HOME ?? process.cwd(), environment, nativeStoreIdentitySeed, {
11439
12197
  onNotification: async (message) => {
11440
12198
  await this.routeNotification(message);
@@ -11443,7 +12201,7 @@ var init_process_pool = __esm({
11443
12201
  if (!this.supervisor.markProcessLost(processGeneration)) {
11444
12202
  return;
11445
12203
  }
11446
- this.loadedThreadIds.clear();
12204
+ await this.clearThreadCache();
11447
12205
  await this.logger.error(`Shared Codex App Server generation ${processGeneration} exited`, error);
11448
12206
  await this.broadcastProcessExit(error);
11449
12207
  },
@@ -11518,18 +12276,70 @@ var init_process_pool = __esm({
11518
12276
  isRetiredTurn(nativeTurnId) {
11519
12277
  return this.retiredTurnIds.has(nativeTurnId);
11520
12278
  }
11521
- isThreadLoaded(nativeThreadId) {
11522
- return this.loadedThreadIds.has(nativeThreadId);
11523
- }
11524
- rememberThreadLoaded(nativeThreadId) {
11525
- this.loadedThreadIds.add(nativeThreadId);
11526
- if (this.loadedThreadIds.size <= 4096) {
11527
- return;
12279
+ async acquireThread(client, requestedThreadId, loadThread) {
12280
+ const acquisition = await this.withThreadCacheLock(() => {
12281
+ this.requireCurrentClient(client);
12282
+ this.discardOtherProcessGenerations(client.processGeneration);
12283
+ if (requestedThreadId !== void 0) {
12284
+ const loaded = this.loadedThreads.get(requestedThreadId);
12285
+ if (loaded !== void 0) {
12286
+ loaded.activeUses += 1;
12287
+ this.touchLoadedThread(requestedThreadId, loaded);
12288
+ return {
12289
+ kind: "leased",
12290
+ lease: this.createThreadLease(requestedThreadId, client.processGeneration)
12291
+ };
12292
+ }
12293
+ const loading = this.loadingThreads.get(requestedThreadId);
12294
+ if (loading !== void 0) {
12295
+ return {
12296
+ kind: "loading",
12297
+ loadedThreadId: loading.loadedThreadId
12298
+ };
12299
+ }
12300
+ }
12301
+ const loadedThreadId2 = Promise.resolve().then(loadThread);
12302
+ if (requestedThreadId !== void 0) {
12303
+ this.loadingThreads.set(requestedThreadId, {
12304
+ loadedThreadId: loadedThreadId2,
12305
+ processGeneration: client.processGeneration
12306
+ });
12307
+ }
12308
+ return {
12309
+ kind: "loading",
12310
+ loadedThreadId: loadedThreadId2
12311
+ };
12312
+ });
12313
+ if (acquisition.kind === "leased") {
12314
+ return acquisition.lease;
11528
12315
  }
11529
- const oldest = this.loadedThreadIds.values().next().value;
11530
- if (typeof oldest === "string") {
11531
- this.loadedThreadIds.delete(oldest);
12316
+ let loadedThreadId;
12317
+ try {
12318
+ loadedThreadId = await acquisition.loadedThreadId;
12319
+ } catch (error) {
12320
+ await this.removeLoadingThread(requestedThreadId, acquisition.loadedThreadId);
12321
+ throw error;
11532
12322
  }
12323
+ return await this.withThreadCacheLock(async () => {
12324
+ this.removeLoadingThreadWithoutLock(requestedThreadId, acquisition.loadedThreadId);
12325
+ this.requireCurrentClient(client);
12326
+ this.discardOtherProcessGenerations(client.processGeneration);
12327
+ if (requestedThreadId !== void 0 && requestedThreadId !== loadedThreadId) {
12328
+ throw new Error("Codex App Server loaded another thread");
12329
+ }
12330
+ const loaded = this.loadedThreads.get(loadedThreadId);
12331
+ if (loaded === void 0) {
12332
+ this.loadedThreads.set(loadedThreadId, {
12333
+ activeUses: 1,
12334
+ processGeneration: client.processGeneration
12335
+ });
12336
+ } else {
12337
+ loaded.activeUses += 1;
12338
+ this.touchLoadedThread(loadedThreadId, loaded);
12339
+ }
12340
+ await this.evictIdleThreads(client);
12341
+ return this.createThreadLease(loadedThreadId, client.processGeneration);
12342
+ });
11533
12343
  }
11534
12344
  status() {
11535
12345
  return this.supervisor.status();
@@ -11549,9 +12359,10 @@ var init_process_pool = __esm({
11549
12359
  }
11550
12360
  async quarantineCurrentProcess(capture) {
11551
12361
  const processGeneration = this.supervisor.currentClient().value?.processGeneration;
11552
- this.loadedThreadIds.clear();
12362
+ const quarantine = this.supervisor.quarantineCurrentProcess(capture);
12363
+ await this.clearThreadCache();
11553
12364
  try {
11554
- await this.supervisor.quarantineCurrentProcess(capture);
12365
+ await quarantine;
11555
12366
  } finally {
11556
12367
  if (processGeneration !== void 0) {
11557
12368
  await this.broadcastProcessExit(new AppServerProcessLostError(`Shared Codex App Server generation ${processGeneration} was quarantined`));
@@ -11566,8 +12377,99 @@ var init_process_pool = __esm({
11566
12377
  await client.stop(capture);
11567
12378
  }
11568
12379
  async stop() {
11569
- this.loadedThreadIds.clear();
11570
- await this.supervisor.stop();
12380
+ const stop = this.supervisor.stop();
12381
+ await this.clearThreadCache();
12382
+ await stop;
12383
+ }
12384
+ createThreadLease(threadId, processGeneration) {
12385
+ let released = false;
12386
+ return {
12387
+ threadId,
12388
+ release: async () => {
12389
+ if (released) {
12390
+ return;
12391
+ }
12392
+ released = true;
12393
+ await this.withThreadCacheLock(async () => {
12394
+ const loaded = this.loadedThreads.get(threadId);
12395
+ if (loaded === void 0 || loaded.processGeneration !== processGeneration) {
12396
+ return;
12397
+ }
12398
+ if (loaded.activeUses < 1) {
12399
+ throw new Error(`Local Codex thread ${threadId} has no active cache lease`);
12400
+ }
12401
+ loaded.activeUses -= 1;
12402
+ this.touchLoadedThread(threadId, loaded);
12403
+ const client = this.supervisor.currentClient().value;
12404
+ if (client !== void 0) {
12405
+ await this.evictIdleThreads(client);
12406
+ }
12407
+ });
12408
+ }
12409
+ };
12410
+ }
12411
+ async clearThreadCache() {
12412
+ await this.withThreadCacheLock(() => {
12413
+ this.loadedThreads.clear();
12414
+ this.loadingThreads.clear();
12415
+ });
12416
+ }
12417
+ discardOtherProcessGenerations(processGeneration) {
12418
+ for (const [threadId, loaded] of this.loadedThreads) {
12419
+ if (loaded.processGeneration !== processGeneration) {
12420
+ this.loadedThreads.delete(threadId);
12421
+ }
12422
+ }
12423
+ for (const [threadId, loading] of this.loadingThreads) {
12424
+ if (loading.processGeneration !== processGeneration) {
12425
+ this.loadingThreads.delete(threadId);
12426
+ }
12427
+ }
12428
+ }
12429
+ async evictIdleThreads(client) {
12430
+ while (this.loadedThreads.size > this.threadCacheCapacity) {
12431
+ const candidate = [...this.loadedThreads].find(([, loaded]) => loaded.activeUses === 0 && loaded.processGeneration === client.processGeneration);
12432
+ if (candidate === void 0) {
12433
+ return;
12434
+ }
12435
+ const [threadId] = candidate;
12436
+ try {
12437
+ const response = await client.request("thread/unsubscribe", { threadId });
12438
+ requireThreadUnsubscribeStatus(response);
12439
+ this.loadedThreads.delete(threadId);
12440
+ } catch (error) {
12441
+ await this.logger.error(`Failed to unsubscribe least-recently-used Local Codex thread ${threadId}`, error);
12442
+ return;
12443
+ }
12444
+ }
12445
+ }
12446
+ touchLoadedThread(threadId, loaded) {
12447
+ this.loadedThreads.delete(threadId);
12448
+ this.loadedThreads.set(threadId, loaded);
12449
+ }
12450
+ async removeLoadingThread(requestedThreadId, loadedThreadId) {
12451
+ await this.withThreadCacheLock(() => {
12452
+ this.removeLoadingThreadWithoutLock(requestedThreadId, loadedThreadId);
12453
+ });
12454
+ }
12455
+ removeLoadingThreadWithoutLock(requestedThreadId, loadedThreadId) {
12456
+ if (requestedThreadId === void 0) {
12457
+ return;
12458
+ }
12459
+ const loading = this.loadingThreads.get(requestedThreadId);
12460
+ if (loading?.loadedThreadId === loadedThreadId) {
12461
+ this.loadingThreads.delete(requestedThreadId);
12462
+ }
12463
+ }
12464
+ requireCurrentClient(client) {
12465
+ if (this.supervisor.currentClient().value !== client || client.isClosed()) {
12466
+ throw new AppServerProcessLostError(`Shared Codex App Server generation ${client.processGeneration} is no longer current`);
12467
+ }
12468
+ }
12469
+ async withThreadCacheLock(operation) {
12470
+ const result = this.threadCacheOperation.then(operation, operation);
12471
+ this.threadCacheOperation = result.then(() => void 0, () => void 0);
12472
+ return await result;
11571
12473
  }
11572
12474
  matchingRoutes(message) {
11573
12475
  return [...this.routes.values()].filter((route) => route.ownsMessage(message));
@@ -11649,7 +12551,7 @@ function delay3(milliseconds) {
11649
12551
  setTimeout(resolvePromise, milliseconds);
11650
12552
  });
11651
12553
  }
11652
- var import_node_os8, import_node_crypto8, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds2, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
12554
+ var import_node_os8, import_node_crypto8, claimTimeoutSeconds, controlTimeoutSeconds, eventUploadIntervalMilliseconds, commandOutputBatchMaxBytes, commandOutputFlushIntervalMilliseconds, agentOutputLimitBytes, defaultLeaseSeconds, defaultNetworkRetryMilliseconds2, defaultLocalCodexThreadCacheCapacity, defaultLeaseSafetyMarginMilliseconds, defaultTerminalForegroundBudgetMilliseconds, maximumEventUploadRetryMilliseconds, maximumTerminalRetryMilliseconds, TerminalUploadOutcome, EventUploadOutcome, MachineConnectorDaemon;
11653
12555
  var init_daemon = __esm({
11654
12556
  "../machine-connector/dist/runtime/daemon.js"() {
11655
12557
  "use strict";
@@ -11685,6 +12587,7 @@ var init_daemon = __esm({
11685
12587
  agentOutputLimitBytes = 2e6;
11686
12588
  defaultLeaseSeconds = 90;
11687
12589
  defaultNetworkRetryMilliseconds2 = 2e3;
12590
+ defaultLocalCodexThreadCacheCapacity = 64;
11688
12591
  defaultLeaseSafetyMarginMilliseconds = 1e4;
11689
12592
  defaultTerminalForegroundBudgetMilliseconds = 5e3;
11690
12593
  maximumEventUploadRetryMilliseconds = 6e4;
@@ -11720,6 +12623,7 @@ var init_daemon = __esm({
11720
12623
  leaseSafetyMarginMilliseconds;
11721
12624
  leaseSeconds;
11722
12625
  networkRetryMilliseconds;
12626
+ localCodexThreadCacheCapacity;
11723
12627
  random;
11724
12628
  terminalForegroundBudgetMilliseconds;
11725
12629
  cliVersion;
@@ -11738,6 +12642,7 @@ var init_daemon = __esm({
11738
12642
  this.leaseSafetyMarginMilliseconds = options.leaseSafetyMarginMilliseconds ?? defaultLeaseSafetyMarginMilliseconds;
11739
12643
  this.leaseSeconds = options.leaseSeconds ?? defaultLeaseSeconds;
11740
12644
  this.networkRetryMilliseconds = options.networkRetryMilliseconds ?? defaultNetworkRetryMilliseconds2;
12645
+ this.localCodexThreadCacheCapacity = options.localCodexThreadCacheCapacity ?? defaultLocalCodexThreadCacheCapacity;
11741
12646
  this.random = options.random ?? Math.random;
11742
12647
  this.terminalForegroundBudgetMilliseconds = options.terminalForegroundBudgetMilliseconds ?? defaultTerminalForegroundBudgetMilliseconds;
11743
12648
  }
@@ -11906,7 +12811,7 @@ var init_daemon = __esm({
11906
12811
  if (existing !== void 0) {
11907
12812
  return existing;
11908
12813
  }
11909
- const pool = new LocalCodexProcessPool(poolKey, environment, nativeStoreIdentitySeed, this.store, this.logger);
12814
+ const pool = new LocalCodexProcessPool(poolKey, environment, nativeStoreIdentitySeed, this.store, this.logger, this.localCodexThreadCacheCapacity);
11910
12815
  this.localCodexProcessPools.set(poolKey, pool);
11911
12816
  return pool;
11912
12817
  }
@@ -12764,12 +13669,12 @@ async function installUserService(store, request2, runtime = defaultServiceManag
12764
13669
  }
12765
13670
  function createServiceEnvironment(options) {
12766
13671
  const inheritedPath = options.environment.PATH ?? process.env.PATH ?? "";
12767
- const nodeDirectory = (0, import_node_path11.dirname)(options.nodePath);
12768
- const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path11.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
13672
+ const nodeDirectory = (0, import_node_path12.dirname)(options.nodePath);
13673
+ const pathEntries = [nodeDirectory, ...inheritedPath.split(import_node_path12.delimiter)].filter((entry, index2, entries) => entry.length > 0 && entries.indexOf(entry) === index2);
12769
13674
  return {
12770
13675
  ...options.environment,
12771
13676
  HOME: options.environment.HOME ?? process.env.HOME ?? (0, import_node_os9.homedir)(),
12772
- PATH: pathEntries.join(import_node_path11.delimiter)
13677
+ PATH: pathEntries.join(import_node_path12.delimiter)
12773
13678
  };
12774
13679
  }
12775
13680
  async function restartUserService(store, runtime = defaultServiceManagerRuntime) {
@@ -12963,7 +13868,7 @@ async function uninstallManager(manager, store, runtime) {
12963
13868
  "bootout",
12964
13869
  `gui/${process.getuid?.() ?? 0}/${launchAgentLabel}`
12965
13870
  ]);
12966
- await (0, import_promises13.rm)(launchAgentPath(), { force: true });
13871
+ await (0, import_promises14.rm)(launchAgentPath(), { force: true });
12967
13872
  return;
12968
13873
  }
12969
13874
  if (manager === UserServiceManager.Systemd) {
@@ -12973,7 +13878,7 @@ async function uninstallManager(manager, store, runtime) {
12973
13878
  "--now",
12974
13879
  "moxt-machine-connector.service"
12975
13880
  ]);
12976
- await (0, import_promises13.rm)(systemdUnitPath(), { force: true });
13881
+ await (0, import_promises14.rm)(systemdUnitPath(), { force: true });
12977
13882
  await runCommandIgnoringFailure(runtime, "systemctl", [
12978
13883
  "--user",
12979
13884
  "daemon-reload"
@@ -12990,7 +13895,7 @@ async function uninstallManager(manager, store, runtime) {
12990
13895
  ]);
12991
13896
  await waitForSupervisorExit(store, runtime, supervisorProcessId);
12992
13897
  }
12993
- await (0, import_promises13.rm)(supervisorDirectory(store), {
13898
+ await (0, import_promises14.rm)(supervisorDirectory(store), {
12994
13899
  force: true,
12995
13900
  recursive: true
12996
13901
  });
@@ -13016,7 +13921,7 @@ async function readStoredServiceManager(store) {
13016
13921
  }
13017
13922
  async function readManagedServiceDefinition(manager, store) {
13018
13923
  try {
13019
- return await (0, import_promises13.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
13924
+ return await (0, import_promises14.readFile)(managedServiceDefinitionPath(manager, store), "utf8");
13020
13925
  } catch (error) {
13021
13926
  if (isNodeErrorCode4(error, "ENOENT"))
13022
13927
  return void 0;
@@ -13025,8 +13930,8 @@ async function readManagedServiceDefinition(manager, store) {
13025
13930
  }
13026
13931
  async function restoreManagedServiceDefinition(manager, store, definition2, runtime) {
13027
13932
  const path4 = managedServiceDefinitionPath(manager, store);
13028
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
13029
- await (0, import_promises13.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
13933
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
13934
+ await (0, import_promises14.writeFile)(path4, definition2, { encoding: "utf8", mode: 384 });
13030
13935
  if (manager === UserServiceManager.Launchd) {
13031
13936
  const domain = `gui/${process.getuid?.() ?? 0}`;
13032
13937
  await runCommandIgnoringFailure(runtime, "launchctl", [
@@ -13075,7 +13980,7 @@ function parseProcessId(value) {
13075
13980
  async function persistServiceManager(store, manager, managedEntrypointPath, desiredState = ManagedServiceDesiredState.Running) {
13076
13981
  await store.writeServiceManager({
13077
13982
  desiredState,
13078
- ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path11.resolve)(managedEntrypointPath) } : {},
13983
+ ...managedEntrypointPath ? { managedEntrypointPath: (0, import_node_path12.resolve)(managedEntrypointPath) } : {},
13079
13984
  manager,
13080
13985
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
13081
13986
  });
@@ -13088,9 +13993,9 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
13088
13993
  const stored = (await store.readServiceManager()).value;
13089
13994
  if (!stored || stored.manager === UserServiceManager.None)
13090
13995
  return;
13091
- const candidate = (0, import_node_path11.resolve)(candidateEntrypointPath);
13996
+ const candidate = (0, import_node_path12.resolve)(candidateEntrypointPath);
13092
13997
  if (stored.managedEntrypointPath) {
13093
- if ((0, import_node_path11.resolve)(stored.managedEntrypointPath) !== candidate) {
13998
+ if ((0, import_node_path12.resolve)(stored.managedEntrypointPath) !== candidate) {
13094
13999
  throw new Error("The managed Connector belongs to a different CLI installation. Run service install from the owning CLI to transfer management.");
13095
14000
  }
13096
14001
  return;
@@ -13100,16 +14005,16 @@ async function assertManagedServiceProvenance(store, candidateEntrypointPath) {
13100
14005
  }
13101
14006
  }
13102
14007
  async function isInsideSourceCheckout(path4) {
13103
- let directory = (0, import_node_path11.dirname)(path4);
14008
+ let directory = (0, import_node_path12.dirname)(path4);
13104
14009
  while (true) {
13105
14010
  try {
13106
- await (0, import_promises13.stat)((0, import_node_path11.join)(directory, ".git"));
14011
+ await (0, import_promises14.stat)((0, import_node_path12.join)(directory, ".git"));
13107
14012
  return true;
13108
14013
  } catch (error) {
13109
14014
  if (!isNodeErrorCode4(error, "ENOENT"))
13110
14015
  throw error;
13111
14016
  }
13112
- const parent = (0, import_node_path11.dirname)(directory);
14017
+ const parent = (0, import_node_path12.dirname)(directory);
13113
14018
  if (parent === directory)
13114
14019
  return false;
13115
14020
  directory = parent;
@@ -13138,10 +14043,10 @@ function automaticSelectionDetail(manager) {
13138
14043
  }
13139
14044
  async function installLaunchAgent(store, options, runtime) {
13140
14045
  const path4 = launchAgentPath();
13141
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
14046
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
13142
14047
  const programArguments = [
13143
14048
  options.nodePath,
13144
- (0, import_node_path11.resolve)(options.entrypointPath),
14049
+ (0, import_node_path12.resolve)(options.entrypointPath),
13145
14050
  ...options.commandArguments
13146
14051
  ];
13147
14052
  const plist = `<?xml version="1.0" encoding="UTF-8"?>
@@ -13172,7 +14077,7 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
13172
14077
  </dict>
13173
14078
  </plist>
13174
14079
  `;
13175
- await (0, import_promises13.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
14080
+ await (0, import_promises14.writeFile)(path4, plist, { encoding: "utf8", mode: 384 });
13176
14081
  const domain = `gui/${process.getuid?.() ?? 0}`;
13177
14082
  await runCommandIgnoringFailure(runtime, "launchctl", [
13178
14083
  "bootout",
@@ -13188,10 +14093,10 @@ ${Object.entries(options.environment).map(([name, value]) => ` <key>${escapeX
13188
14093
  }
13189
14094
  async function installSystemdUserService(store, options, runtime) {
13190
14095
  const path4 = systemdUnitPath();
13191
- await (0, import_promises13.mkdir)((0, import_node_path11.dirname)(path4), { recursive: true });
14096
+ await (0, import_promises14.mkdir)((0, import_node_path12.dirname)(path4), { recursive: true });
13192
14097
  const command = [
13193
14098
  options.nodePath,
13194
- (0, import_node_path11.resolve)(options.entrypointPath),
14099
+ (0, import_node_path12.resolve)(options.entrypointPath),
13195
14100
  ...options.commandArguments
13196
14101
  ].map(escapeSystemdArgument).join(" ");
13197
14102
  const unit = `[Unit]
@@ -13210,7 +14115,7 @@ ${Object.entries(options.environment).map(([name, value]) => `Environment=${esca
13210
14115
  [Install]
13211
14116
  WantedBy=default.target
13212
14117
  `;
13213
- await (0, import_promises13.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
14118
+ await (0, import_promises14.writeFile)(path4, unit, { encoding: "utf8", mode: 384 });
13214
14119
  await runtime.run("systemctl", ["--user", "daemon-reload"]);
13215
14120
  await runtime.run("systemctl", [
13216
14121
  "--user",
@@ -13231,8 +14136,8 @@ WantedBy=default.target
13231
14136
  async function installSupervisorUserService(store, options, runtime) {
13232
14137
  const directory = supervisorDirectory(store);
13233
14138
  const configPath = supervisorConfigPath(store);
13234
- await (0, import_promises13.mkdir)(directory, { recursive: true, mode: 448 });
13235
- await (0, import_promises13.writeFile)(configPath, createSupervisorConfiguration(store, options), {
14139
+ await (0, import_promises14.mkdir)(directory, { recursive: true, mode: 448 });
14140
+ await (0, import_promises14.writeFile)(configPath, createSupervisorConfiguration(store, options), {
13236
14141
  encoding: "utf8",
13237
14142
  mode: 384
13238
14143
  });
@@ -13246,7 +14151,7 @@ async function installSupervisorUserService(store, options, runtime) {
13246
14151
  function createSupervisorConfiguration(store, options) {
13247
14152
  const command = [
13248
14153
  options.nodePath,
13249
- (0, import_node_path11.resolve)(options.entrypointPath),
14154
+ (0, import_node_path12.resolve)(options.entrypointPath),
13250
14155
  ...options.commandArguments
13251
14156
  ].map(escapeSupervisorArgument).join(" ");
13252
14157
  const environment = Object.entries(options.environment).map(([name, value]) => `${name}="${escapeSupervisorEnvironment(value)}"`).join(",");
@@ -13270,7 +14175,7 @@ serverurl=unix://${supervisorSocketPath(store)}
13270
14175
 
13271
14176
  [program:${supervisorProgramName}]
13272
14177
  command=${command}
13273
- directory=${escapeSupervisorPath((0, import_node_path11.dirname)((0, import_node_path11.resolve)(options.entrypointPath)))}
14178
+ directory=${escapeSupervisorPath((0, import_node_path12.dirname)((0, import_node_path12.resolve)(options.entrypointPath)))}
13274
14179
  environment=${environment}
13275
14180
  autostart=true
13276
14181
  autorestart=true
@@ -13303,8 +14208,8 @@ async function restartSupervisorUserService(store, runtime) {
13303
14208
  await startSupervisorUserService(store, runtime, supervisorProcessId, stoppedConnector.processId);
13304
14209
  }
13305
14210
  async function startSupervisorUserService(store, runtime, previousSupervisorProcessId, previousConnectorProcessId) {
13306
- await (0, import_promises13.rm)(supervisorSocketPath(store), { force: true });
13307
- await (0, import_promises13.rm)(supervisorPidPath(store), { force: true });
14211
+ await (0, import_promises14.rm)(supervisorSocketPath(store), { force: true });
14212
+ await (0, import_promises14.rm)(supervisorPidPath(store), { force: true });
13308
14213
  await runtime.run("supervisord", ["-c", supervisorConfigPath(store)], {
13309
14214
  environment: sanitizeEnvironment(process.env),
13310
14215
  timeoutMilliseconds: serviceManagerMutationTimeoutMilliseconds
@@ -13413,7 +14318,7 @@ async function currentSupervisorProcessId(store, runtime) {
13413
14318
  } catch {
13414
14319
  }
13415
14320
  try {
13416
- const processId = parseProcessId(await (0, import_promises13.readFile)(supervisorPidPath(store), "utf8"));
14321
+ const processId = parseProcessId(await (0, import_promises14.readFile)(supervisorPidPath(store), "utf8"));
13417
14322
  return processId !== void 0 && serviceProcessIsRunning(runtime, processId) ? processId : void 0;
13418
14323
  } catch (error) {
13419
14324
  if (isNodeErrorCode4(error, "ENOENT"))
@@ -13435,26 +14340,26 @@ async function currentSupervisorProgramProcessId(store, runtime) {
13435
14340
  }
13436
14341
  }
13437
14342
  function launchAgentPath() {
13438
- return (0, import_node_path11.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
14343
+ return (0, import_node_path12.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), "Library", "LaunchAgents", `${launchAgentLabel}.plist`);
13439
14344
  }
13440
14345
  function systemdUnitPath() {
13441
- const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path11.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), ".config");
13442
- return (0, import_node_path11.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
14346
+ const configHome = process.env.XDG_CONFIG_HOME ?? (0, import_node_path12.join)(process.env.HOME ?? (0, import_node_os9.homedir)(), ".config");
14347
+ return (0, import_node_path12.join)(configHome, "systemd", "user", "moxt-machine-connector.service");
13443
14348
  }
13444
14349
  function supervisorDirectory(store) {
13445
- return (0, import_node_path11.join)(store.baseDirectory, "supervisor");
14350
+ return (0, import_node_path12.join)(store.baseDirectory, "supervisor");
13446
14351
  }
13447
14352
  function supervisorConfigPath(store) {
13448
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.conf");
14353
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.conf");
13449
14354
  }
13450
14355
  function supervisorSocketPath(store) {
13451
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisor.sock");
14356
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisor.sock");
13452
14357
  }
13453
14358
  function supervisorPidPath(store) {
13454
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.pid");
14359
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.pid");
13455
14360
  }
13456
14361
  function supervisorLogPath(store) {
13457
- return (0, import_node_path11.join)(supervisorDirectory(store), "supervisord.log");
14362
+ return (0, import_node_path12.join)(supervisorDirectory(store), "supervisord.log");
13458
14363
  }
13459
14364
  async function commandSucceeds(runtime, command, argumentsList) {
13460
14365
  try {
@@ -13514,15 +14419,15 @@ function serviceManagerCurrentTime(runtime) {
13514
14419
  async function serviceManagerDelay(runtime, milliseconds) {
13515
14420
  await (runtime.delay?.(milliseconds) ?? delay4(milliseconds));
13516
14421
  }
13517
- var import_node_child_process5, import_promises13, import_node_os9, import_node_path11, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
14422
+ var import_node_child_process5, import_promises14, import_node_os9, import_node_path12, import_node_util2, execFileAsync, launchAgentLabel, serviceManagerProbeTimeoutMilliseconds, serviceManagerMutationTimeoutMilliseconds, supervisorProgramName, supervisorControlTimeoutMilliseconds, supervisorProgramStartSeconds, supervisorProgramStartRetries, supervisorProgramStopWaitSeconds, supervisorLifecycleBufferMilliseconds, supervisorExitTimeoutMilliseconds, supervisorProgramStartTimeoutMilliseconds, ServiceManagerPreference, UserServiceManager, defaultServiceManagerRuntime;
13518
14423
  var init_service_manager = __esm({
13519
14424
  "../machine-connector/dist/runtime/service-manager.js"() {
13520
14425
  "use strict";
13521
14426
  init_cjs_shims();
13522
14427
  import_node_child_process5 = require("child_process");
13523
- import_promises13 = require("fs/promises");
14428
+ import_promises14 = require("fs/promises");
13524
14429
  import_node_os9 = require("os");
13525
- import_node_path11 = require("path");
14430
+ import_node_path12 = require("path");
13526
14431
  import_node_util2 = require("util");
13527
14432
  init_runtime_types();
13528
14433
  init_shell_environment();
@@ -13617,9 +14522,9 @@ async function reconcileManagedDaemon(options, store = new MachineRuntimeStore()
13617
14522
  try {
13618
14523
  refresh = await refreshManagedUserService(store, {
13619
14524
  commandArguments: [...options.commandArguments],
13620
- entrypointPath: (0, import_node_path12.resolve)(options.entrypointPath),
14525
+ entrypointPath: (0, import_node_path13.resolve)(options.entrypointPath),
13621
14526
  environment: { ...options.environment },
13622
- nodePath: (0, import_node_path12.resolve)(options.nodePath)
14527
+ nodePath: (0, import_node_path13.resolve)(options.nodePath)
13623
14528
  });
13624
14529
  if (!refresh) {
13625
14530
  throw new Error("The Connector service is no longer managed by Moxt");
@@ -13655,10 +14560,10 @@ async function validateCliEntrypoint(options, store) {
13655
14560
  if (options.commandArguments.length !== 2 || options.commandArguments[0] !== "machine" || options.commandArguments[1] !== "daemon") {
13656
14561
  throw new Error("The managed daemon command must be `machine daemon`");
13657
14562
  }
13658
- const nodePath = await (0, import_promises14.realpath)((0, import_node_path12.resolve)(options.nodePath));
13659
- const entrypointPath = await (0, import_promises14.realpath)((0, import_node_path12.resolve)(options.entrypointPath));
13660
- await (0, import_promises14.access)(nodePath, import_promises14.constants.X_OK);
13661
- await (0, import_promises14.access)(entrypointPath, import_promises14.constants.R_OK);
14563
+ const nodePath = await (0, import_promises15.realpath)((0, import_node_path13.resolve)(options.nodePath));
14564
+ const entrypointPath = await (0, import_promises15.realpath)((0, import_node_path13.resolve)(options.entrypointPath));
14565
+ await (0, import_promises15.access)(nodePath, import_promises15.constants.X_OK);
14566
+ await (0, import_promises15.access)(entrypointPath, import_promises15.constants.R_OK);
13662
14567
  const probe = await execFileAsync2(nodePath, [entrypointPath, "--version"], {
13663
14568
  encoding: "utf8",
13664
14569
  env: {
@@ -13691,14 +14596,14 @@ function delay5(milliseconds) {
13691
14596
  function errorMessage5(error) {
13692
14597
  return error instanceof Error ? error.message : String(error);
13693
14598
  }
13694
- var import_node_child_process6, import_promises14, import_node_path12, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshStage, DaemonRefreshError;
14599
+ var import_node_child_process6, import_promises15, import_node_path13, import_node_util3, reconcileTimeoutMilliseconds, execFileAsync2, DaemonReconcileOutcome, DaemonRefreshStage, DaemonRefreshError;
13695
14600
  var init_daemon_reconcile = __esm({
13696
14601
  "../machine-connector/dist/runtime/daemon-reconcile.js"() {
13697
14602
  "use strict";
13698
14603
  init_cjs_shims();
13699
14604
  import_node_child_process6 = require("child_process");
13700
- import_promises14 = require("fs/promises");
13701
- import_node_path12 = require("path");
14605
+ import_promises15 = require("fs/promises");
14606
+ import_node_path13 = require("path");
13702
14607
  import_node_util3 = require("util");
13703
14608
  init_local_ipc();
13704
14609
  init_process_lock();
@@ -13761,7 +14666,7 @@ async function runMachineDoctor(store) {
13761
14666
  }
13762
14667
  for (const connection of connections) {
13763
14668
  try {
13764
- await (0, import_promises15.access)(connection.rootPath, import_node_fs3.constants.R_OK | import_node_fs3.constants.X_OK);
14669
+ await (0, import_promises16.access)(connection.rootPath, import_node_fs3.constants.R_OK | import_node_fs3.constants.X_OK);
13765
14670
  checks.push({
13766
14671
  detail: connection.rootPath,
13767
14672
  name: `root:${connection.connectionId}`,
@@ -13776,7 +14681,7 @@ async function runMachineDoctor(store) {
13776
14681
  }
13777
14682
  const relayUrl = new URL(connection.relayOrigin);
13778
14683
  try {
13779
- const address = await (0, import_promises16.lookup)(relayUrl.hostname);
14684
+ const address = await (0, import_promises17.lookup)(relayUrl.hostname);
13780
14685
  checks.push({
13781
14686
  detail: `${relayUrl.hostname} resolves to ${address.address}`,
13782
14687
  name: `dns:${connection.connectionId}`,
@@ -13858,15 +14763,15 @@ async function runMachineDoctor(store) {
13858
14763
  function errorMessage6(error) {
13859
14764
  return error instanceof Error ? error.message : String(error);
13860
14765
  }
13861
- var import_node_child_process7, import_promises15, import_node_fs3, import_promises16, import_node_util4, execFileAsync3, DoctorCheckStatus;
14766
+ var import_node_child_process7, import_promises16, import_node_fs3, import_promises17, import_node_util4, execFileAsync3, DoctorCheckStatus;
13862
14767
  var init_doctor = __esm({
13863
14768
  "../machine-connector/dist/runtime/doctor.js"() {
13864
14769
  "use strict";
13865
14770
  init_cjs_shims();
13866
14771
  import_node_child_process7 = require("child_process");
13867
- import_promises15 = require("fs/promises");
14772
+ import_promises16 = require("fs/promises");
13868
14773
  import_node_fs3 = require("fs");
13869
- import_promises16 = require("dns/promises");
14774
+ import_promises17 = require("dns/promises");
13870
14775
  import_node_util4 = require("util");
13871
14776
  init_local_ipc();
13872
14777
  execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process7.execFile);
@@ -14136,7 +15041,7 @@ async function readRecentLogLines(store) {
14136
15041
  }
14137
15042
  async function readOptionalFile(path4) {
14138
15043
  try {
14139
- return await (0, import_promises17.readFile)(path4, "utf8");
15044
+ return await (0, import_promises18.readFile)(path4, "utf8");
14140
15045
  } catch (error) {
14141
15046
  if (isMissingFile(error)) {
14142
15047
  return "";
@@ -14195,13 +15100,13 @@ function isMissingFile(error) {
14195
15100
  function errorMessage7(error) {
14196
15101
  return error instanceof Error ? error.message : String(error);
14197
15102
  }
14198
- var import_promises17, import_promises18, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
15103
+ var import_promises18, import_promises19, import_node_readline, alternateScreenEnter, alternateScreenExit, clearScreen, cursorHide, cursorShow, styleReset, styleHeader, styleSelected, refreshIntervalMilliseconds, maximumLogLines, MachineManagerView, MachineManagerAction, MachineManagerSnapshotDepth, InteractiveMachineManager;
14199
15104
  var init_machine_manager = __esm({
14200
15105
  "../machine-connector/dist/runtime/machine-manager.js"() {
14201
15106
  "use strict";
14202
15107
  init_cjs_shims();
14203
- import_promises17 = require("fs/promises");
14204
- import_promises18 = require("readline/promises");
15108
+ import_promises18 = require("fs/promises");
15109
+ import_promises19 = require("readline/promises");
14205
15110
  import_node_readline = require("readline");
14206
15111
  init_doctor();
14207
15112
  init_local_ipc();
@@ -14435,7 +15340,7 @@ var init_machine_manager = __esm({
14435
15340
  }
14436
15341
  async runCommandAction(action) {
14437
15342
  this.suspendTerminal();
14438
- const reader = (0, import_promises18.createInterface)({
15343
+ const reader = (0, import_promises19.createInterface)({
14439
15344
  input: process.stdin,
14440
15345
  output: process.stdout
14441
15346
  });
@@ -14676,7 +15581,7 @@ async function pairMachine(store, options) {
14676
15581
  throw new Error("Local Machine pairing expired");
14677
15582
  }
14678
15583
  function displayNameForRoot(canonicalRoot) {
14679
- const name = (0, import_node_path13.basename)(canonicalRoot);
15584
+ const name = (0, import_node_path14.basename)(canonicalRoot);
14680
15585
  return name.length > 0 ? name : canonicalRoot;
14681
15586
  }
14682
15587
  function getOperatingSystem() {
@@ -14698,7 +15603,7 @@ function delay6(milliseconds) {
14698
15603
  setTimeout(resolvePromise, milliseconds);
14699
15604
  });
14700
15605
  }
14701
- var import_node_child_process8, import_node_crypto10, import_node_os10, import_node_path13, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
15606
+ var import_node_child_process8, import_node_crypto10, import_node_os10, import_node_path14, connectedPairingStatus, rejectedPairingStatus, expiredPairingStatus, pairingPollMilliseconds;
14702
15607
  var init_pairing = __esm({
14703
15608
  "../machine-connector/dist/runtime/pairing.js"() {
14704
15609
  "use strict";
@@ -14706,7 +15611,7 @@ var init_pairing = __esm({
14706
15611
  import_node_child_process8 = require("child_process");
14707
15612
  import_node_crypto10 = require("crypto");
14708
15613
  import_node_os10 = require("os");
14709
- import_node_path13 = require("path");
15614
+ import_node_path14 = require("path");
14710
15615
  init_contracts();
14711
15616
  init_version();
14712
15617
  init_enums();
@@ -14794,7 +15699,7 @@ function isMachineLifecycleMutation(command, commandArguments) {
14794
15699
  async function connectCommand(store, argumentsList, entrypoint) {
14795
15700
  const options = parseOptions(argumentsList);
14796
15701
  const connectionCode = requiredOption(options, "code");
14797
- const rootPath = (0, import_node_path14.resolve)(options.root ?? process.cwd());
15702
+ const rootPath = (0, import_node_path15.resolve)(options.root ?? process.cwd());
14798
15703
  const serviceManagerPreference = requestedServiceManagerPreference(options);
14799
15704
  await validateExplicitServiceManagerPreference(serviceManagerPreference);
14800
15705
  await assertConnectionRuntimeCanConverge(store, serviceManagerPreference);
@@ -15146,7 +16051,7 @@ async function reachableRuntimeStatus2(store) {
15146
16051
  }
15147
16052
  async function readOptionalFile2(path4) {
15148
16053
  try {
15149
- return await (0, import_promises19.readFile)(path4, "utf8");
16054
+ return await (0, import_promises20.readFile)(path4, "utf8");
15150
16055
  } catch {
15151
16056
  return "";
15152
16057
  }
@@ -15175,13 +16080,13 @@ function delay7(milliseconds) {
15175
16080
  setTimeout(resolvePromise, milliseconds);
15176
16081
  });
15177
16082
  }
15178
- var import_promises19, import_node_path14, defaultRelayOrigin;
16083
+ var import_promises20, import_node_path15, defaultRelayOrigin;
15179
16084
  var init_cli = __esm({
15180
16085
  "../machine-connector/dist/cli.js"() {
15181
16086
  "use strict";
15182
16087
  init_cjs_shims();
15183
- import_promises19 = require("fs/promises");
15184
- import_node_path14 = require("path");
16088
+ import_promises20 = require("fs/promises");
16089
+ import_node_path15 = require("path");
15185
16090
  init_daemon();
15186
16091
  init_daemon_reconcile();
15187
16092
  init_doctor();
@@ -15478,7 +16383,7 @@ function getApiKeyOrUndefined() {
15478
16383
 
15479
16384
  // src/utils/http.ts
15480
16385
  function getUserAgent() {
15481
- return `moxt-cli/${"0.11.0-beta.5"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
16386
+ return `moxt-cli/${"0.11.0-beta.6"} (${(0, import_os.platform)()}/${(0, import_os.arch)()}) node/${process.versions.node}`;
15482
16387
  }
15483
16388
  async function sendRequest(method, path4, init) {
15484
16389
  return await fetch(`${getApiBaseUrl()}${path4}`, {
@@ -22390,10 +23295,10 @@ function resolveAll(constructs2, events, context) {
22390
23295
  const called = [];
22391
23296
  let index2 = -1;
22392
23297
  while (++index2 < constructs2.length) {
22393
- const resolve10 = constructs2[index2].resolveAll;
22394
- if (resolve10 && !called.includes(resolve10)) {
22395
- events = resolve10(events, context);
22396
- called.push(resolve10);
23298
+ const resolve11 = constructs2[index2].resolveAll;
23299
+ if (resolve11 && !called.includes(resolve11)) {
23300
+ events = resolve11(events, context);
23301
+ called.push(resolve11);
22397
23302
  }
22398
23303
  }
22399
23304
  return events;
@@ -28876,7 +29781,7 @@ function registerWorkspaceCommand(program3) {
28876
29781
  // src/commands/workflow.ts
28877
29782
  init_cjs_shims();
28878
29783
  var fs5 = __toESM(require("fs"), 1);
28879
- var import_node_path15 = require("path");
29784
+ var import_node_path16 = require("path");
28880
29785
  var import_node_util6 = require("util");
28881
29786
  var MAX_DESC_LENGTH = 5e3;
28882
29787
  var MAX_COMMENT_CONTENT_LENGTH = 5e3;
@@ -29370,7 +30275,7 @@ async function resolveLinkedLinkTitles(item, workspaceId) {
29370
30275
  `/files/read-by-url?url=${encodeURIComponent(link.url)}`
29371
30276
  );
29372
30277
  if (!response.ok || response.data.type !== "file") return link.url;
29373
- return import_node_path15.posix.basename(response.data.path) || link.url;
30278
+ return import_node_path16.posix.basename(response.data.path) || link.url;
29374
30279
  } catch {
29375
30280
  return link.url;
29376
30281
  }
@@ -30064,7 +30969,7 @@ var FLUSH_TIMEOUT_MS = 3e3;
30064
30969
  var MAX_BATCH_SIZE = 100;
30065
30970
  function commonLabels() {
30066
30971
  return {
30067
- cli_version: "0.11.0-beta.5",
30972
+ cli_version: "0.11.0-beta.6",
30068
30973
  node_version: process.versions.node,
30069
30974
  os: (0, import_node_os11.platform)(),
30070
30975
  arch: (0, import_node_os11.arch)(),
@@ -30110,7 +31015,7 @@ async function flush() {
30110
31015
  }
30111
31016
  const batch = buffer.splice(0, MAX_BATCH_SIZE);
30112
31017
  const payload = {
30113
- release_id: "0.11.0-beta.5",
31018
+ release_id: "0.11.0-beta.6",
30114
31019
  client_type: "cli",
30115
31020
  metric_data_list: batch.map((m) => ({
30116
31021
  profile: "cli",
@@ -30311,7 +31216,7 @@ function registryWorker() {
30311
31216
 
30312
31217
  // src/update/prompt.ts
30313
31218
  init_cjs_shims();
30314
- var import_promises20 = require("readline/promises");
31219
+ var import_promises21 = require("readline/promises");
30315
31220
  async function promptForUpdate(input, output, currentVersion, latestVersion, timeoutMs) {
30316
31221
  output.write(`
30317
31222
  A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion}
@@ -30324,7 +31229,7 @@ A new version of Moxt CLI is available: ${currentVersion} \u2192 ${latestVersion
30324
31229
  const controller = new AbortController();
30325
31230
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
30326
31231
  timeout.unref();
30327
- const readline = (0, import_promises20.createInterface)({ input, output, terminal: true });
31232
+ const readline = (0, import_promises21.createInterface)({ input, output, terminal: true });
30328
31233
  try {
30329
31234
  const answer = await readline.question("", { signal: controller.signal });
30330
31235
  if (answer.trim() === "1") return "update";
@@ -30427,7 +31332,7 @@ function commandPath2(command) {
30427
31332
 
30428
31333
  // src/update/daemon-reconcile-hook.ts
30429
31334
  init_cjs_shims();
30430
- var import_node_path16 = require("path");
31335
+ var import_node_path17 = require("path");
30431
31336
  function installDaemonReconcileHook(program3, cliVersion) {
30432
31337
  program3.hook("preAction", async (_thisCommand, actionCommand) => {
30433
31338
  if (!isEligible2(actionCommand)) return;
@@ -30449,9 +31354,9 @@ function installDaemonReconcileHook(program3, cliVersion) {
30449
31354
  await reconcileManagedDaemon2({
30450
31355
  cliVersion,
30451
31356
  commandArguments: ["machine", "daemon"],
30452
- entrypointPath: (0, import_node_path16.resolve)(entrypointPath),
31357
+ entrypointPath: (0, import_node_path17.resolve)(entrypointPath),
30453
31358
  environment: {},
30454
- nodePath: (0, import_node_path16.resolve)(process.execPath),
31359
+ nodePath: (0, import_node_path17.resolve)(process.execPath),
30455
31360
  onActiveJobs: (count) => {
30456
31361
  process.stderr.write(
30457
31362
  `Warning: restarting the managed Connector will interrupt ${count} active ${count === 1 ? "Job" : "Jobs"}.
@@ -30493,9 +31398,9 @@ function commandPath3(command) {
30493
31398
  }
30494
31399
 
30495
31400
  // src/index.ts
30496
- var program2 = createProgram("0.11.0-beta.5");
30497
- installDaemonReconcileHook(program2, "0.11.0-beta.5");
30498
- installUpdateHook(program2, "0.11.0-beta.5");
31401
+ var program2 = createProgram("0.11.0-beta.6");
31402
+ installDaemonReconcileHook(program2, "0.11.0-beta.6");
31403
+ installUpdateHook(program2, "0.11.0-beta.6");
30499
31404
  instrumentProgram(program2);
30500
31405
  installExitHandler();
30501
31406
  program2.parseAsync(process.argv).then(async () => {