@alan-ai-hq/agent-manager-darwin-arm64 0.1.145 → 0.1.147

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.
Files changed (3) hide show
  1. package/alan-agent.cjs +895 -410
  2. package/alan-holder.cjs +894 -396
  3. package/package.json +7 -2
package/alan-agent.cjs CHANGED
@@ -12529,7 +12529,7 @@ function compileValidator(schema, parser) {
12529
12529
  function compile(schema, options) {
12530
12530
  try {
12531
12531
  const parser = compileFn(schema);
12532
- const clone2 = clone(schema);
12532
+ const clone3 = clone(schema);
12533
12533
  const liveRun = schema._zod.run;
12534
12534
  const originalRun = liveRun.__originalRun ?? liveRun;
12535
12535
  const wrapped = (payload, ctx) => {
@@ -12549,12 +12549,12 @@ function compile(schema, options) {
12549
12549
  return originalRun(payload, ctx);
12550
12550
  };
12551
12551
  wrapped.__originalRun = originalRun;
12552
- clone2._zod.bag.fallbackRun = originalRun;
12553
- clone2._zod.bag.validator = compileValidator(schema, parser);
12554
- clone2._zod.run = wrapped;
12552
+ clone3._zod.bag.fallbackRun = originalRun;
12553
+ clone3._zod.bag.validator = compileValidator(schema, parser);
12554
+ clone3._zod.run = wrapped;
12555
12555
  if (!liveRun.__originalRun)
12556
- installCompiledUserMethods(clone2, schema, parser);
12557
- return clone2;
12556
+ installCompiledUserMethods(clone3, schema, parser);
12557
+ return clone3;
12558
12558
  } catch (err) {
12559
12559
  if (options?.strict)
12560
12560
  throw err;
@@ -20312,7 +20312,7 @@ var init_workspace = __esm({
20312
20312
  });
20313
20313
 
20314
20314
  // ../shared/dist/runtime-v2/desired-state.js
20315
- var repoLocalPathSchema, runSpecSchema, desiredRunSchema, desiredStateSchema;
20315
+ var repoLocalPathSchema, requestedCheckoutSchema, runSpecSchema, desiredRunSchema, desiredStateSchema;
20316
20316
  var init_desired_state = __esm({
20317
20317
  "../shared/dist/runtime-v2/desired-state.js"() {
20318
20318
  "use strict";
@@ -20327,6 +20327,11 @@ var init_desired_state = __esm({
20327
20327
  localPath: external_exports.string().min(1),
20328
20328
  branch: external_exports.string().min(1).optional()
20329
20329
  });
20330
+ requestedCheckoutSchema = external_exports.object({
20331
+ path: machinePathSchema,
20332
+ repoUrl: gitRemoteUrlSchema,
20333
+ branch: gitBranchSchema
20334
+ });
20330
20335
  runSpecSchema = external_exports.object({
20331
20336
  runId: runIdSchema,
20332
20337
  conversationId: conversationIdSchema,
@@ -20345,6 +20350,8 @@ var init_desired_state = __esm({
20345
20350
  workspacePathPinned: external_exports.boolean().optional(),
20346
20351
  approvedWorkspacePaths: external_exports.array(external_exports.string().min(1)).optional(),
20347
20352
  repoLocalPaths: external_exports.array(repoLocalPathSchema).optional(),
20353
+ /** Applied once, at the conversation's first turn on a cloud sandbox; never moves local work. */
20354
+ requestedCheckouts: external_exports.array(requestedCheckoutSchema).max(64).optional(),
20348
20355
  workflowId: external_exports.guid().optional(),
20349
20356
  workflowExecutionId: external_exports.guid().optional(),
20350
20357
  agentId: external_exports.string().min(1).optional(),
@@ -20510,7 +20517,9 @@ var init_machine_identity = __esm({
20510
20517
  runCodexCredentialSchema = external_exports.object({
20511
20518
  accessToken: external_exports.string().min(1),
20512
20519
  chatgptAccountId: external_exports.string().min(1),
20513
- chatgptPlanType: external_exports.string().nullable()
20520
+ chatgptPlanType: external_exports.string().nullable(),
20521
+ credentialId: external_exports.uuid().optional(),
20522
+ providerUserId: external_exports.string().min(1).optional()
20514
20523
  });
20515
20524
  runCodexCredentialRefreshRequestSchema = external_exports.object({
20516
20525
  /** sha256 hex of the access token Codex was refused with; a newer stored token is returned instead of rotating. */
@@ -20519,7 +20528,7 @@ var init_machine_identity = __esm({
20519
20528
  runProviderCredentialSchema = external_exports.object({
20520
20529
  /** Environment variables for the agent CLI, e.g. ANTHROPIC_API_KEY; empty when the CLI's own login is used. */
20521
20530
  env: external_exports.record(external_exports.string(), external_exports.string()),
20522
- /** The team's Codex login for a cloud sandbox; absent where the CLI's own login is used. */
20531
+ /** The bound Codex login for a cloud sandbox; absent where the CLI's own login is used. */
20523
20532
  codex: runCodexCredentialSchema.optional()
20524
20533
  });
20525
20534
  }
@@ -20970,6 +20979,73 @@ var init_problem = __esm({
20970
20979
  }
20971
20980
  });
20972
20981
 
20982
+ // ../shared/dist/cli-usage.js
20983
+ var usagePercentSchema, usageTimestampSchema, usageAmountSchema, usageObservationShape, cliUsageWindowPatchSchema, cliUsageWindowSchema, cliUsageSpendPatchSchema, cliUsageSpendSchema, cliUsageCreditsPatchSchema, cliUsageCreditsSchema, cliUsageBucketSchema, cliUsageSnapshotSchema;
20984
+ var init_cli_usage = __esm({
20985
+ "../shared/dist/cli-usage.js"() {
20986
+ "use strict";
20987
+ init_zod();
20988
+ usagePercentSchema = external_exports.number().min(0).max(100);
20989
+ usageTimestampSchema = external_exports.iso.datetime();
20990
+ usageAmountSchema = external_exports.string().min(1);
20991
+ usageObservationShape = {
20992
+ observedAt: usageTimestampSchema,
20993
+ receivedAt: usageTimestampSchema,
20994
+ sourceId: external_exports.string().min(1),
20995
+ sequence: external_exports.number().int().nonnegative()
20996
+ };
20997
+ cliUsageWindowPatchSchema = external_exports.object({
20998
+ usedPercent: usagePercentSchema.nullable().optional(),
20999
+ windowMinutes: external_exports.number().positive().nullable().optional(),
21000
+ resetsAt: usageTimestampSchema.nullable().optional()
21001
+ });
21002
+ cliUsageWindowSchema = external_exports.object({
21003
+ usedPercent: usagePercentSchema.optional(),
21004
+ windowMinutes: external_exports.number().positive().optional(),
21005
+ resetsAt: usageTimestampSchema.optional(),
21006
+ ...usageObservationShape
21007
+ });
21008
+ cliUsageSpendPatchSchema = external_exports.object({
21009
+ reached: external_exports.boolean(),
21010
+ limit: usageAmountSchema.nullable().optional(),
21011
+ used: usageAmountSchema.nullable().optional(),
21012
+ remaining: usageAmountSchema.nullable().optional(),
21013
+ usedPercent: usagePercentSchema.nullable().optional(),
21014
+ resetsAt: usageTimestampSchema.nullable().optional()
21015
+ });
21016
+ cliUsageSpendSchema = external_exports.object({
21017
+ reached: external_exports.boolean(),
21018
+ limit: usageAmountSchema.optional(),
21019
+ used: usageAmountSchema.optional(),
21020
+ remaining: usageAmountSchema.optional(),
21021
+ usedPercent: usagePercentSchema.optional(),
21022
+ resetsAt: usageTimestampSchema.optional(),
21023
+ ...usageObservationShape
21024
+ });
21025
+ cliUsageCreditsPatchSchema = external_exports.object({
21026
+ hasCredits: external_exports.boolean(),
21027
+ unlimited: external_exports.boolean(),
21028
+ balance: usageAmountSchema.nullable().optional()
21029
+ });
21030
+ cliUsageCreditsSchema = external_exports.object({
21031
+ hasCredits: external_exports.boolean(),
21032
+ unlimited: external_exports.boolean(),
21033
+ balance: usageAmountSchema.optional(),
21034
+ ...usageObservationShape
21035
+ });
21036
+ cliUsageBucketSchema = external_exports.object({
21037
+ primary: cliUsageWindowSchema.optional(),
21038
+ secondary: cliUsageWindowSchema.optional(),
21039
+ spend: cliUsageSpendSchema.optional(),
21040
+ credits: cliUsageCreditsSchema.optional(),
21041
+ planType: external_exports.string().min(1).nullable().optional()
21042
+ });
21043
+ cliUsageSnapshotSchema = external_exports.object({
21044
+ buckets: external_exports.record(external_exports.string().min(1), cliUsageBucketSchema)
21045
+ });
21046
+ }
21047
+ });
21048
+
20973
21049
  // ../shared/dist/runtime-v2/run-log.js
20974
21050
  function isRunLifecycleKind(sessionUpdate) {
20975
21051
  return RUN_LIFECYCLE_KINDS.has(sessionUpdate);
@@ -20977,12 +21053,13 @@ function isRunLifecycleKind(sessionUpdate) {
20977
21053
  function alignedLength(bytes) {
20978
21054
  return bytes.lastIndexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
20979
21055
  }
20980
- var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_LOG_RECORD_SEPARATOR, runAcceptedUpdateSchema, runStartedUpdateSchema, runWorkspaceRelocatedUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, RUN_LIFECYCLE_KINDS, runLogRecordSchema;
21056
+ var RUN_LOG_PROTOCOL, RUN_LOG_PROTOCOL_HEADER, RUN_LOG_RECORD_SEPARATOR, runAcceptedUpdateSchema, runStartedUpdateSchema, runCodexRateLimitsUpdateSchema, runWorkspaceRelocatedUpdateSchema, runOutcomeSchema, runRejectionCodeSchema, runEndedUpdateSchema, runLifecycleUpdateSchema, RUN_LIFECYCLE_KINDS, runLogRecordSchema;
20981
21057
  var init_run_log = __esm({
20982
21058
  "../shared/dist/runtime-v2/run-log.js"() {
20983
21059
  "use strict";
20984
21060
  init_zod();
20985
21061
  init_problem();
21062
+ init_cli_usage();
20986
21063
  init_ids();
20987
21064
  RUN_LOG_PROTOCOL = 2;
20988
21065
  RUN_LOG_PROTOCOL_HEADER = "x-alan-log-protocol";
@@ -20997,6 +21074,18 @@ var init_run_log = __esm({
20997
21074
  providerSessionId: external_exports.string().min(1).optional(),
20998
21075
  pid: external_exports.number().int().positive().optional()
20999
21076
  });
21077
+ runCodexRateLimitsUpdateSchema = external_exports.object({
21078
+ sessionUpdate: external_exports.literal("_alan/codex.rate_limits"),
21079
+ limitId: external_exports.string().min(1),
21080
+ primary: cliUsageWindowPatchSchema.nullable().optional(),
21081
+ secondary: cliUsageWindowPatchSchema.nullable().optional(),
21082
+ spend: cliUsageSpendPatchSchema.nullable().optional(),
21083
+ credits: cliUsageCreditsPatchSchema.nullable().optional(),
21084
+ planType: external_exports.string().min(1).nullable().optional(),
21085
+ observedAt: external_exports.iso.datetime(),
21086
+ sourceId: external_exports.string().min(1),
21087
+ sequence: external_exports.number().int().nonnegative()
21088
+ });
21000
21089
  runWorkspaceRelocatedUpdateSchema = external_exports.object({
21001
21090
  sessionUpdate: external_exports.literal("_alan/run.workspace_relocated"),
21002
21091
  previousPath: external_exports.string().min(1).max(4096),
@@ -21059,7 +21148,7 @@ var init_holder_protocol = __esm({
21059
21148
  init_ids();
21060
21149
  init_link();
21061
21150
  init_run_log();
21062
- HOLDER_PROTOCOL = 1;
21151
+ HOLDER_PROTOCOL = 2;
21063
21152
  holderAbortOutcomeSchema = external_exports.enum(["aborted", "interrupted"]);
21064
21153
  holderRequestSchema = external_exports.discriminatedUnion("type", [
21065
21154
  external_exports.object({ type: external_exports.literal("auth"), token: external_exports.string().min(1) }),
@@ -22537,7 +22626,7 @@ function plan(command, args, options) {
22537
22626
  function captureOutput(command, args, options) {
22538
22627
  const launch = plan(command, args, options);
22539
22628
  if (launch === void 0) return Promise.resolve(NEVER_STARTED);
22540
- return new Promise((resolve13) => {
22629
+ return new Promise((resolve14) => {
22541
22630
  (0, import_child_process.execFile)(
22542
22631
  launch.file,
22543
22632
  [...launch.args],
@@ -22551,7 +22640,7 @@ function captureOutput(command, args, options) {
22551
22640
  },
22552
22641
  (error61, stdout, stderr) => {
22553
22642
  const code = error61 && typeof error61.code === "number" ? error61.code : error61 ? void 0 : 0;
22554
- resolve13({ stdout, stderr, exitCode: code });
22643
+ resolve14({ stdout, stderr, exitCode: code });
22555
22644
  }
22556
22645
  );
22557
22646
  });
@@ -22601,10 +22690,10 @@ async function linuxStartTicks(pid) {
22601
22690
  }
22602
22691
  }
22603
22692
  function psStartTime(pid) {
22604
- return new Promise((resolve13) => {
22693
+ return new Promise((resolve14) => {
22605
22694
  (0, import_child_process2.execFile)("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 2e3 }, (error61, stdout) => {
22606
22695
  const text3 = stdout.trim();
22607
- resolve13(error61 || !text3 ? void 0 : text3);
22696
+ resolve14(error61 || !text3 ? void 0 : text3);
22608
22697
  });
22609
22698
  });
22610
22699
  }
@@ -22633,12 +22722,12 @@ function parseProcessList(text3) {
22633
22722
  }
22634
22723
  function listProcesses(platform3 = process.platform) {
22635
22724
  if (platform3 === "win32") return Promise.resolve([]);
22636
- return new Promise((resolve13) => {
22725
+ return new Promise((resolve14) => {
22637
22726
  (0, import_child_process3.execFile)(
22638
22727
  "ps",
22639
22728
  ["-A", "-o", "pid=,ppid=,pgid=,lstart="],
22640
22729
  { timeout: 5e3, maxBuffer: 8 * 1024 * 1024 },
22641
- (error61, stdout) => resolve13(error61 ? [] : parseProcessList(stdout))
22730
+ (error61, stdout) => resolve14(error61 ? [] : parseProcessList(stdout))
22642
22731
  );
22643
22732
  });
22644
22733
  }
@@ -22678,11 +22767,11 @@ async function taskkill(pid, options) {
22678
22767
  stdio: "ignore",
22679
22768
  windowsHide: true
22680
22769
  });
22681
- const exited = new Promise((resolve13) => {
22682
- killer.once("error", (error210) => resolve13(error210));
22770
+ const exited = new Promise((resolve14) => {
22771
+ killer.once("error", (error210) => resolve14(error210));
22683
22772
  killer.once(
22684
22773
  "exit",
22685
- (code, signal) => resolve13(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22774
+ (code, signal) => resolve14(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22686
22775
  );
22687
22776
  });
22688
22777
  const timedOut = clock.sleep(options.timeoutMs ?? DEFAULT_TASKKILL_TIMEOUT_MS, timeout.signal).then(() => new Error("taskkill timed out")).catch(() => void 0);
@@ -22938,10 +23027,10 @@ function spawnCli(options) {
22938
23027
  function waitForSpawn(child, command) {
22939
23028
  if (isWindowsJob(child)) return waitForWindowsJob(child, command);
22940
23029
  if (child.pid !== void 0) return Promise.resolve();
22941
- return new Promise((resolve13, reject) => {
23030
+ return new Promise((resolve14, reject) => {
22942
23031
  const onSpawn = () => {
22943
23032
  child.off("error", onError);
22944
- resolve13();
23033
+ resolve14();
22945
23034
  };
22946
23035
  const onError = (error61) => {
22947
23036
  child.off("spawn", onSpawn);
@@ -25885,7 +25974,18 @@ var init_chunk_SBT5W7L4 = __esm({
25885
25974
  }
25886
25975
  });
25887
25976
 
25888
- // ../agent-core/dist/chunk-54ZRJOQP.js
25977
+ // ../agent-core/dist/chunk-HBIPWAUI.js
25978
+ function readCapReset(text3) {
25979
+ const epoch = EPOCH_RESET.exec(text3);
25980
+ if (epoch) return { resetsAt: new Date(Number(epoch[1]) * 1e3).toISOString() };
25981
+ const codex = CODEX_RESET.exec(text3);
25982
+ if (codex) {
25983
+ const milliseconds = Date.parse(codex[1].replace(/(\d)(?:st|nd|rd|th)\b/gi, "$1"));
25984
+ if (Number.isFinite(milliseconds)) return { resetsAt: new Date(milliseconds).toISOString() };
25985
+ }
25986
+ const worded = WORDED_RESET.exec(text3);
25987
+ return worded ? { resetHint: worded[1].trim() } : {};
25988
+ }
25889
25989
  function specForErrorKind(errorKind) {
25890
25990
  const spec = ERROR_SPECS[errorKind];
25891
25991
  return { message: spec.message, errorKind, recoveryClass: spec.recoveryClass };
@@ -25946,15 +26046,6 @@ function normalizeCodexCliErrorMessage(message2) {
25946
26046
  }
25947
26047
  return message2;
25948
26048
  }
25949
- function readCapReset(text3) {
25950
- const epoch = EPOCH_RESET.exec(text3);
25951
- if (epoch) {
25952
- const seconds = Number(epoch[1]);
25953
- return { resetsAt: new Date(seconds * 1e3).toISOString() };
25954
- }
25955
- const worded = WORDED_RESET.exec(text3);
25956
- return worded ? { resetHint: worded[1].trim() } : {};
25957
- }
25958
26049
  function lineMatching(text3, pattern) {
25959
26050
  return text3.split("\n").map((line) => line.trim()).find((line) => pattern.test(line));
25960
26051
  }
@@ -25966,10 +26057,11 @@ function withCapReset(classified, text3) {
25966
26057
  if (classified.errorKind !== "usage_limit") return classified;
25967
26058
  const reset = readCapReset(text3);
25968
26059
  if (reset.resetsAt) {
26060
+ const own22 = lineMatching(text3, /\btry again at\b/i);
25969
26061
  return {
25970
26062
  ...classified,
25971
26063
  ...reset,
25972
- message: `Provider usage limit reached. It resets at ${reset.resetsAt}; switch model or wait, then retry.`
26064
+ message: own22 ?? `Provider usage limit reached. It resets at ${reset.resetsAt}; switch model or wait, then retry.`
25973
26065
  };
25974
26066
  }
25975
26067
  const own2 = lineMatching(text3, /usage limit/i);
@@ -26088,13 +26180,16 @@ function createCliProblem(observed, options) {
26088
26180
  ...classified.resetsAt ? { resetsAt: classified.resetsAt } : {}
26089
26181
  });
26090
26182
  }
26091
- var import_crypto2, ERROR_SPECS, AGENT_ERROR_KINDS, AGENT_SIGN_IN_BY_HARNESS, STATUS_PREFIX, TEXT_RULES, CODEX_TIMEOUT_MESSAGE, CODEX_EXPIRED_MESSAGE, EPOCH_RESET, WORDED_RESET, COMMAND_NOT_FOUND, CODE_RULES, TEXT_REFINES, STATUS_LEAD, CLI_PROBLEM_CODE_BY_ERROR_KIND, KEY_REJECTION_KINDS;
26092
- var init_chunk_54ZRJOQP = __esm({
26093
- "../agent-core/dist/chunk-54ZRJOQP.js"() {
26183
+ var import_crypto2, EPOCH_RESET, WORDED_RESET, CODEX_RESET, ERROR_SPECS, AGENT_ERROR_KINDS, AGENT_SIGN_IN_BY_HARNESS, STATUS_PREFIX, TEXT_RULES, CODEX_TIMEOUT_MESSAGE, CODEX_EXPIRED_MESSAGE, COMMAND_NOT_FOUND, CODE_RULES, TEXT_REFINES, STATUS_LEAD, CLI_PROBLEM_CODE_BY_ERROR_KIND, KEY_REJECTION_KINDS;
26184
+ var init_chunk_HBIPWAUI = __esm({
26185
+ "../agent-core/dist/chunk-HBIPWAUI.js"() {
26094
26186
  "use strict";
26095
26187
  init_chunk_YXWJW7I5();
26096
26188
  import_crypto2 = require("crypto");
26097
26189
  init_agent2();
26190
+ EPOCH_RESET = /\|\s*(\d{10})\b/;
26191
+ WORDED_RESET = /\bresets?\s+(?:at\s+)?([^.\n]{1,60}?)\s*(?:$|[.\n])/i;
26192
+ CODEX_RESET = /\btry again at\s+([A-Za-z]{3,9}\s+\d{1,2}(?:st|nd|rd|th)?,?\s+\d{4}\s+\d{1,2}:\d{2}\s*[AP]M(?:\s+(?:UTC|GMT)(?:[+-]\d{1,2}(?::?\d{2})?)?)?)/i;
26098
26193
  ERROR_SPECS = {
26099
26194
  model_mismatch: {
26100
26195
  message: "The selected model isn't available, or you don't have access to it. Pick a different model, then send your message again.",
@@ -26248,7 +26343,7 @@ var init_chunk_54ZRJOQP = __esm({
26248
26343
  // #44604), or a trailing assistant message (opencode #19517).
26249
26344
  {
26250
26345
  kind: "history_rejected",
26251
- pattern: /\btext content blocks must be non-empty\b|\bcontent field in the message object\b|\bids were found without `?tool_result`? blocks\b|\bunexpected `?tool_use_id`?|\btool use concurrency issues\b|\bno tool output found for\b|\bdoes not support assistant message prefill\b/
26346
+ pattern: /\btext content blocks must be non-empty\b|\bcontent field in the message object\b|\bids were found without `?tool_result`? blocks\b|\bunexpected `?tool_use_id`?|\btool use concurrency issues\b|\bno tool output found for\b|\bdoes not support assistant message prefill\b|\binvalid_encrypted_content\b|organization_id did not match the target organization/
26252
26347
  },
26253
26348
  // Claude: "No conversation found with session ID"; Codex: "no rollout found for thread id";
26254
26349
  // Copilot: "No session, task, or name matched"; Kimi/Cursor ACP: `Session "<id>" not found`.
@@ -26297,8 +26392,6 @@ var init_chunk_54ZRJOQP = __esm({
26297
26392
  ];
26298
26393
  CODEX_TIMEOUT_MESSAGE = "Codex connection to OpenAI timed out while waiting for the turn to continue. Retry the message; if it repeats, check network/API latency or reduce slow MCP/tool calls in the turn.";
26299
26394
  CODEX_EXPIRED_MESSAGE = "Codex CLI connection expired. Re-authenticate the Codex CLI on this computer (run `codex login`) or reconnect it in Cloud settings, then retry.";
26300
- EPOCH_RESET = /\|\s*(\d{10})\b/;
26301
- WORDED_RESET = /\bresets?\s+(?:at\s+)?([^.\n]{1,60}?)\s*(?:$|[.\n])/i;
26302
26395
  COMMAND_NOT_FOUND = /\bcommand not found\b|\bno such file or directory\b/i;
26303
26396
  CODE_RULES = [
26304
26397
  { pattern: /model_not_found|model_not_available/, kind: "model_mismatch" },
@@ -26353,7 +26446,7 @@ var init_chunk_54ZRJOQP = __esm({
26353
26446
  }
26354
26447
  });
26355
26448
 
26356
- // ../agent-core/dist/chunk-72NSEYHK.js
26449
+ // ../agent-core/dist/chunk-4G77APXN.js
26357
26450
  function detectImageMimeType(buffer) {
26358
26451
  if (buffer.length >= 8 && buffer.subarray(0, 8).equals(PNG_SIGNATURE)) return "image/png";
26359
26452
  if (buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) {
@@ -26535,8 +26628,8 @@ function createJsonRpcPeer(writer, handlers) {
26535
26628
  },
26536
26629
  request: (method, params = {}) => {
26537
26630
  const id = counter.next++;
26538
- return new Promise((resolve13, reject) => {
26539
- pending.set(id, { method, resolve: resolve13, reject });
26631
+ return new Promise((resolve14, reject) => {
26632
+ pending.set(id, { method, resolve: resolve14, reject });
26540
26633
  writer.write({ id, method, params }).catch((error61) => {
26541
26634
  pending.delete(id);
26542
26635
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -26649,7 +26742,7 @@ function createNdjsonWriter(stream) {
26649
26742
  get writable() {
26650
26743
  return stream.writable && !stream.destroyed && failure6.error === void 0;
26651
26744
  },
26652
- write: (value2) => new Promise((resolve13, reject) => {
26745
+ write: (value2) => new Promise((resolve14, reject) => {
26653
26746
  if (failure6.error) {
26654
26747
  reject(failure6.error);
26655
26748
  return;
@@ -26661,7 +26754,7 @@ function createNdjsonWriter(stream) {
26661
26754
  stream.write(`${JSON.stringify(value2)}
26662
26755
  `, (error61) => {
26663
26756
  if (error61) reject(error61);
26664
- else resolve13();
26757
+ else resolve14();
26665
26758
  });
26666
26759
  }),
26667
26760
  end: () => {
@@ -26677,11 +26770,11 @@ function hostProcess(child, tree, options, handlers) {
26677
26770
  const stderr = new LineSplitter((line) => handlers.onStderrLine(line));
26678
26771
  child.stderr.on("data", (chunk) => stderr.push(chunk));
26679
26772
  child.stderr.once("end", () => stderr.flush());
26680
- const processExit = new Promise((resolve13) => {
26681
- child.once("exit", (code, signal) => resolve13({ code, signal }));
26773
+ const processExit = new Promise((resolve14) => {
26774
+ child.once("exit", (code, signal) => resolve14({ code, signal }));
26682
26775
  });
26683
- const outputEnded = new Promise((resolve13) => {
26684
- child.stdout.once("close", () => resolve13());
26776
+ const outputEnded = new Promise((resolve14) => {
26777
+ child.stdout.once("close", () => resolve14());
26685
26778
  });
26686
26779
  const watch = async () => {
26687
26780
  const { clock, stdoutDrainMs, log, name } = options;
@@ -26737,11 +26830,11 @@ function silentStartError(name, timeoutMs) {
26737
26830
  };
26738
26831
  }
26739
26832
  var import_crypto3, import_fs4, import_path3, PNG_SIGNATURE, IMAGE_MIME_BY_EXT, VIDEO_MIME_BY_EXT, IMAGE_EXTENSIONS, VIDEO_EXTENSIONS, MAX_IMAGE_BYTES, MAX_VIDEO_BYTES, AGENT_BROWSER_MENTION, LocalMediaReader, SessionOpenRefusal, JsonRpcError, ACP_PROTOCOL_VERSION, ACP_ERROR, STDERR_TAIL_LINES, RESULT_EXIT_GRACE_MS, PerTurnSession;
26740
- var init_chunk_72NSEYHK = __esm({
26741
- "../agent-core/dist/chunk-72NSEYHK.js"() {
26833
+ var init_chunk_4G77APXN = __esm({
26834
+ "../agent-core/dist/chunk-4G77APXN.js"() {
26742
26835
  "use strict";
26743
26836
  init_chunk_XC5676SG();
26744
- init_chunk_54ZRJOQP();
26837
+ init_chunk_HBIPWAUI();
26745
26838
  init_chunk_M6YHY2EZ();
26746
26839
  init_chunk_YXWJW7I5();
26747
26840
  import_crypto3 = require("crypto");
@@ -26971,13 +27064,13 @@ var init_chunk_72NSEYHK = __esm({
26971
27064
  const turnId = input2.turnId;
26972
27065
  let finish = () => {
26973
27066
  };
26974
- const done = new Promise((resolve13) => {
27067
+ const done = new Promise((resolve14) => {
26975
27068
  finish = (outcome2) => {
26976
27069
  if (this.#current?.id !== turnId) return;
26977
27070
  this.#current = void 0;
26978
27071
  if (this.#state === "busy") this.#state = "idle";
26979
27072
  this.#emit({ type: "turn_ended", turnId, outcome: outcome2 });
26980
- resolve13({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
27073
+ resolve14({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
26981
27074
  };
26982
27075
  });
26983
27076
  const pending = {
@@ -28842,9 +28935,9 @@ var init_claude = __esm({
28842
28935
  "../agent-core/dist/providers/claude.js"() {
28843
28936
  "use strict";
28844
28937
  init_chunk_SBT5W7L4();
28845
- init_chunk_72NSEYHK();
28938
+ init_chunk_4G77APXN();
28846
28939
  init_chunk_XC5676SG();
28847
- init_chunk_54ZRJOQP();
28940
+ init_chunk_HBIPWAUI();
28848
28941
  init_chunk_J2KTV5FP();
28849
28942
  init_chunk_M6YHY2EZ();
28850
28943
  init_chunk_FPGAN4XO();
@@ -29570,8 +29663,8 @@ var init_claude = __esm({
29570
29663
  }
29571
29664
  async #awaitTaskStop(requestId, taskId) {
29572
29665
  const timer = new AbortController();
29573
- const answered = new Promise((resolve13) => {
29574
- this.#taskStops.set(requestId, resolve13);
29666
+ const answered = new Promise((resolve14) => {
29667
+ this.#taskStops.set(requestId, resolve14);
29575
29668
  });
29576
29669
  const timeoutMs = this.#options.stopTaskTimeoutMs;
29577
29670
  const timedOut = this.#options.clock.sleep(timeoutMs, timer.signal).then(
@@ -29644,17 +29737,17 @@ var init_claude = __esm({
29644
29737
  };
29645
29738
  let markStarted = () => {
29646
29739
  };
29647
- const whenStarted = new Promise((resolve13) => {
29648
- markStarted = resolve13;
29740
+ const whenStarted = new Promise((resolve14) => {
29741
+ markStarted = resolve14;
29649
29742
  });
29650
- const done = new Promise((resolve13) => {
29743
+ const done = new Promise((resolve14) => {
29651
29744
  finish = (outcome2) => {
29652
29745
  if (this.#current?.id !== id) return;
29653
29746
  this.#current = void 0;
29654
29747
  this.#lastTurn = turn;
29655
29748
  if (this.#state === "busy") this.#state = "idle";
29656
29749
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
29657
- resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
29750
+ resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
29658
29751
  };
29659
29752
  });
29660
29753
  const active = {
@@ -29772,8 +29865,8 @@ var init_claude = __esm({
29772
29865
  void removeLaunchFiles(this.#launchFiles).catch((error61) => {
29773
29866
  this.#options.log.warn("claude.launch_files_cleanup_failed", { error: error61 });
29774
29867
  });
29775
- for (const resolve13 of this.#taskStops.values()) {
29776
- resolve13({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
29868
+ for (const resolve14 of this.#taskStops.values()) {
29869
+ resolve14({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
29777
29870
  }
29778
29871
  const active = this.#current;
29779
29872
  if (active) {
@@ -30169,6 +30262,67 @@ function imageKey(update) {
30169
30262
  const image = asRecord(update.image);
30170
30263
  return asString(image?.sourceHash) || asString(image?.id) || void 0;
30171
30264
  }
30265
+ function windowPatch(value2) {
30266
+ if (value2 === null) return null;
30267
+ const record2 = asRecord(value2);
30268
+ if (!record2) return void 0;
30269
+ const patch = {};
30270
+ const usedPercent = asFiniteNumber(record2.usedPercent);
30271
+ if (usedPercent !== void 0 && usedPercent >= 0 && usedPercent <= 100) {
30272
+ patch.usedPercent = usedPercent;
30273
+ } else if (record2.usedPercent === null) {
30274
+ patch.usedPercent = null;
30275
+ }
30276
+ const duration3 = asFiniteNumber(record2.windowDurationMins);
30277
+ if (duration3 !== void 0 && duration3 > 0) patch.windowMinutes = duration3;
30278
+ else if (record2.windowDurationMins === null) patch.windowMinutes = null;
30279
+ const seconds = asFiniteNumber(record2.resetsAt);
30280
+ if (seconds !== void 0 && seconds >= 0) {
30281
+ const reset = new Date(seconds * 1e3);
30282
+ if (Number.isFinite(reset.getTime())) patch.resetsAt = reset.toISOString();
30283
+ } else if (record2.resetsAt === null) {
30284
+ patch.resetsAt = null;
30285
+ }
30286
+ return patch;
30287
+ }
30288
+ function amount(value2) {
30289
+ const text3 = asString(value2).trim();
30290
+ return text3.length > 0 ? text3 : void 0;
30291
+ }
30292
+ function spendPatch(limit, reached) {
30293
+ const record2 = asRecord(limit);
30294
+ const reachedFlag = reached === true;
30295
+ if (!record2)
30296
+ return limit === null && !reachedFlag ? null : reachedFlag ? { reached: true } : void 0;
30297
+ const patch = { reached: reachedFlag };
30298
+ const limitAmount = amount(record2.limit);
30299
+ const usedAmount = amount(record2.used);
30300
+ if (limitAmount) patch.limit = limitAmount;
30301
+ if (usedAmount) patch.used = usedAmount;
30302
+ const remainingPercent = asFiniteNumber(record2.remainingPercent);
30303
+ if (remainingPercent !== void 0) {
30304
+ patch.usedPercent = Math.min(100, Math.max(0, 100 - remainingPercent));
30305
+ }
30306
+ const seconds = asFiniteNumber(record2.resetsAt);
30307
+ if (seconds !== void 0 && seconds >= 0) {
30308
+ const reset = new Date(seconds * 1e3);
30309
+ if (Number.isFinite(reset.getTime())) patch.resetsAt = reset.toISOString();
30310
+ }
30311
+ return patch;
30312
+ }
30313
+ function creditsPatch(value2) {
30314
+ if (value2 === null) return null;
30315
+ const record2 = asRecord(value2);
30316
+ if (!record2 || typeof record2.hasCredits !== "boolean" || typeof record2.unlimited !== "boolean") {
30317
+ return void 0;
30318
+ }
30319
+ const balance = amount(record2.balance);
30320
+ return {
30321
+ hasCredits: record2.hasCredits,
30322
+ unlimited: record2.unlimited,
30323
+ ...balance ? { balance } : {}
30324
+ };
30325
+ }
30172
30326
  function isApprovalRequest(method) {
30173
30327
  return COMMAND_OR_FILE.has(method) || LEGACY.has(method);
30174
30328
  }
@@ -30580,7 +30734,10 @@ function classifyCodexError(error61) {
30580
30734
  const message2 = asString(error61?.message);
30581
30735
  const known = typeof info === "string" ? INFO_KINDS.get(info) : void 0;
30582
30736
  const own2 = normalizeCodexCliErrorMessage(message2.trim());
30583
- if (known) return own2 ? { ...specForErrorKind(known), message: own2 } : specForErrorKind(known);
30737
+ if (known) {
30738
+ const classified = own2 ? { ...specForErrorKind(known), message: own2 } : specForErrorKind(known);
30739
+ return known === "usage_limit" ? { ...classified, ...readCapReset(message2) } : classified;
30740
+ }
30584
30741
  const status = httpStatusOf(info);
30585
30742
  return classifyProviderError(message2, status === void 0 ? {} : { status });
30586
30743
  }
@@ -30664,7 +30821,7 @@ async function handshake(session, spec, log) {
30664
30821
  }
30665
30822
  await session.rpc.notify("initialized");
30666
30823
  }
30667
- async function preflight(session, spec) {
30824
+ async function preflight(session, spec, log) {
30668
30825
  if (spec.externalAuth) {
30669
30826
  const tokens2 = await spec.externalAuth.current();
30670
30827
  await session.rpc.request("account/login/start", {
@@ -30682,6 +30839,13 @@ async function preflight(session, spec) {
30682
30839
  specForErrorKind("not_logged_in")
30683
30840
  );
30684
30841
  }
30842
+ if (spec.externalAuth) {
30843
+ try {
30844
+ session.observeRateLimits(await session.rpc.request("account/rateLimits/read", {}));
30845
+ } catch {
30846
+ log.warn("codex.rate_limits_unavailable", {});
30847
+ }
30848
+ }
30685
30849
  }
30686
30850
  function threadOf(result) {
30687
30851
  const thread = asRecord(asRecord(result)?.thread);
@@ -30743,7 +30907,7 @@ function createCodexDriver(options = {}) {
30743
30907
  try {
30744
30908
  const opening = (async () => {
30745
30909
  await handshake(session, spec, resolved.log);
30746
- await preflight(session, spec);
30910
+ await preflight(session, spec, resolved.log);
30747
30911
  return openThread(session, spec, resolved.log);
30748
30912
  })();
30749
30913
  const thread = await withDeadline(
@@ -30894,7 +31058,7 @@ function createCodexExecDriver(options = {}) {
30894
31058
  };
30895
31059
  }
30896
31060
  function envDigest2(env) {
30897
- const hash2 = (0, import_crypto9.createHash)("sha256");
31061
+ const hash2 = (0, import_crypto10.createHash)("sha256");
30898
31062
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
30899
31063
  return hash2.digest("hex");
30900
31064
  }
@@ -31556,7 +31720,7 @@ function readCodexRolloutTurns(chunk, baseOffset, skipped) {
31556
31720
  return readTranscriptTurns(codexRolloutFile, chunk, baseOffset, skipped);
31557
31721
  }
31558
31722
  function envDigest22(env) {
31559
- const hash2 = (0, import_crypto10.createHash)("sha256");
31723
+ const hash2 = (0, import_crypto11.createHash)("sha256");
31560
31724
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
31561
31725
  return hash2.digest("hex");
31562
31726
  }
@@ -31625,14 +31789,14 @@ function codexTurnInput(run2, context) {
31625
31789
  ...images.length ? { imagePaths: images.map((image) => image.path) } : {}
31626
31790
  };
31627
31791
  }
31628
- var import_fs6, import_path6, import_crypto8, import_crypto9, import_crypto10, TokenRefresher, MCP_STARTUP_TIMEOUT_SEC, FIELD_TYPES, YES_NO, ACCEPT_DECLINE, MAX_INLINE_GENERATED_IMAGE_BYTES, PNG_SIGNATURE2, JPEG_NON_FRAME_MARKERS, IMAGE_GEN_CALL, PROMPT_LITERAL, RELOCATE_EVERY_MS, CodexImageGenerationFold, CodexRolloutImages, USER_INPUT_METHOD, PERMISSIONS_METHOD, ELICITATION_METHOD, COMMAND_OR_FILE, LEGACY, DECISIONS, COORDINATION_TOOLS, SETTLED_AGENT, STATUS, CHANGE_OPERATIONS, SILENT_ON_START, IGNORED_ITEMS, PLAN_STATUS, WORKER_LIFECYCLE, INFO_KINDS, SILENT, CodexTurn, STDERR_TAIL_LINES3, MAX_BETWEEN_UPDATES, UNSUPPORTED_REQUEST, DECLINED_ELICITATION, IMAGE_CATCH_UP_MS, IMAGE_POLL_MS, CodexSession, CODEX_MIN_VERSION, CODEX_REQUIREMENT, CODEX_TESTED_LINE, DEFAULTS2, CLIENT_INFO, STATUS2, EXITED_WITHOUT_RESPONSE, CodexExecTurn, DEFAULTS22, CodexExecSession, INJECTED_USER_PREFIXES, SHELL_TOOL_NAMES, ANNOUNCING_ITEM_TYPES, OUTPUT_MARKER, OPEN_PAGE_ACTIONS, FIND_IN_PAGE_ACTIONS, FILE_OPERATIONS, UNDERSTOOD_ITEM_TYPES, PRELUDE_TYPES2, PRELUDE_EVENTS, codexRolloutFile;
31792
+ var import_fs6, import_path6, import_crypto8, import_crypto9, import_crypto10, import_crypto11, TokenRefresher, MCP_STARTUP_TIMEOUT_SEC, FIELD_TYPES, YES_NO, ACCEPT_DECLINE, MAX_INLINE_GENERATED_IMAGE_BYTES, PNG_SIGNATURE2, JPEG_NON_FRAME_MARKERS, IMAGE_GEN_CALL, PROMPT_LITERAL, RELOCATE_EVERY_MS, CodexImageGenerationFold, CodexRolloutImages, CodexRateLimits, USER_INPUT_METHOD, PERMISSIONS_METHOD, ELICITATION_METHOD, COMMAND_OR_FILE, LEGACY, DECISIONS, COORDINATION_TOOLS, SETTLED_AGENT, STATUS, CHANGE_OPERATIONS, SILENT_ON_START, IGNORED_ITEMS, PLAN_STATUS, WORKER_LIFECYCLE, INFO_KINDS, SILENT, CodexTurn, STDERR_TAIL_LINES3, MAX_BETWEEN_UPDATES, UNSUPPORTED_REQUEST, DECLINED_ELICITATION, IMAGE_CATCH_UP_MS, IMAGE_POLL_MS, CodexSession, CODEX_MIN_VERSION, CODEX_REQUIREMENT, CODEX_TESTED_LINE, DEFAULTS2, CLIENT_INFO, STATUS2, EXITED_WITHOUT_RESPONSE, CodexExecTurn, DEFAULTS22, CodexExecSession, INJECTED_USER_PREFIXES, SHELL_TOOL_NAMES, ANNOUNCING_ITEM_TYPES, OUTPUT_MARKER, OPEN_PAGE_ACTIONS, FIND_IN_PAGE_ACTIONS, FILE_OPERATIONS, UNDERSTOOD_ITEM_TYPES, PRELUDE_TYPES2, PRELUDE_EVENTS, codexRolloutFile;
31629
31793
  var init_codex = __esm({
31630
31794
  "../agent-core/dist/providers/codex.js"() {
31631
31795
  "use strict";
31632
31796
  init_chunk_SBT5W7L4();
31633
- init_chunk_72NSEYHK();
31797
+ init_chunk_4G77APXN();
31634
31798
  init_chunk_XC5676SG();
31635
- init_chunk_54ZRJOQP();
31799
+ init_chunk_HBIPWAUI();
31636
31800
  init_chunk_J2KTV5FP();
31637
31801
  init_chunk_M6YHY2EZ();
31638
31802
  init_chunk_FPGAN4XO();
@@ -31641,10 +31805,12 @@ var init_codex = __esm({
31641
31805
  import_path6 = require("path");
31642
31806
  init_effort();
31643
31807
  import_crypto8 = require("crypto");
31644
- init_agent2();
31645
31808
  import_crypto9 = require("crypto");
31809
+ init_runtime_v2();
31646
31810
  init_agent2();
31647
31811
  import_crypto10 = require("crypto");
31812
+ init_agent2();
31813
+ import_crypto11 = require("crypto");
31648
31814
  init_effort();
31649
31815
  TokenRefresher = class {
31650
31816
  #auth;
@@ -31828,6 +31994,50 @@ var init_codex = __esm({
31828
31994
  return this.#cursor;
31829
31995
  }
31830
31996
  };
31997
+ CodexRateLimits = class {
31998
+ #clock;
31999
+ #sourceId;
32000
+ #sequence = 0;
32001
+ constructor(clock, sourceId = (0, import_crypto9.randomUUID)()) {
32002
+ this.#clock = clock;
32003
+ this.#sourceId = sourceId;
32004
+ }
32005
+ read(value2) {
32006
+ const response = asRecord(value2);
32007
+ const buckets = asRecord(response?.rateLimitsByLimitId);
32008
+ if (buckets) {
32009
+ return Object.entries(buckets).flatMap(
32010
+ ([limitId, snapshot2]) => this.#update(snapshot2, limitId)
32011
+ );
32012
+ }
32013
+ return this.#update(response?.rateLimits);
32014
+ }
32015
+ notification(params) {
32016
+ return this.#update(params.rateLimits);
32017
+ }
32018
+ #update(value2, bucketId) {
32019
+ const snapshot2 = asRecord(value2);
32020
+ if (!snapshot2) return [];
32021
+ const primary = windowPatch(snapshot2.primary);
32022
+ const secondary = windowPatch(snapshot2.secondary);
32023
+ const spend = spendPatch(snapshot2.individualLimit, snapshot2.spendControlReached);
32024
+ const credits = creditsPatch(snapshot2.credits);
32025
+ const planType = snapshot2.planType === null ? null : asString(snapshot2.planType) || void 0;
32026
+ const parsed = runCodexRateLimitsUpdateSchema.safeParse({
32027
+ sessionUpdate: "_alan/codex.rate_limits",
32028
+ limitId: bucketId ?? (asString(snapshot2.limitId) || "codex"),
32029
+ ...primary === void 0 ? {} : { primary },
32030
+ ...secondary === void 0 ? {} : { secondary },
32031
+ ...spend === void 0 ? {} : { spend },
32032
+ ...credits === void 0 ? {} : { credits },
32033
+ ...planType === void 0 ? {} : { planType },
32034
+ observedAt: new Date(this.#clock.now()).toISOString(),
32035
+ sourceId: this.#sourceId,
32036
+ sequence: this.#sequence++
32037
+ });
32038
+ return parsed.success ? [parsed.data] : [];
32039
+ }
32040
+ };
31831
32041
  USER_INPUT_METHOD = "item/tool/requestUserInput";
31832
32042
  PERMISSIONS_METHOD = "item/permissions/requestApproval";
31833
32043
  ELICITATION_METHOD = "mcpServer/elicitation/request";
@@ -31897,7 +32107,6 @@ var init_codex = __esm({
31897
32107
  "thread/closed",
31898
32108
  "hook/started",
31899
32109
  "hook/completed",
31900
- "account/rateLimits/updated",
31901
32110
  "account/updated",
31902
32111
  "account/login/completed",
31903
32112
  "remoteControl/status/changed",
@@ -32092,6 +32301,7 @@ var init_codex = __esm({
32092
32301
  #listeners = createListeners();
32093
32302
  #options;
32094
32303
  #memory;
32304
+ #rateLimits;
32095
32305
  #stderr = [];
32096
32306
  #approvals = /* @__PURE__ */ new Map();
32097
32307
  /** Session-level updates (thread start warnings, MCP startup) that open the next turn's log. */
@@ -32108,6 +32318,7 @@ var init_codex = __esm({
32108
32318
  constructor(child, tree, memory, options) {
32109
32319
  this.#options = options;
32110
32320
  this.#memory = memory;
32321
+ this.#rateLimits = new CodexRateLimits(options.clock);
32111
32322
  this.#lastTurn = new CodexTurn(memory, options.clock);
32112
32323
  this.#host = hostProcess(
32113
32324
  child,
@@ -32142,6 +32353,9 @@ var init_codex = __esm({
32142
32353
  configure(config2) {
32143
32354
  this.#config = config2;
32144
32355
  }
32356
+ observeRateLimits(response) {
32357
+ this.#recordRateLimits(this.#rateLimits.read(response));
32358
+ }
32145
32359
  attachThread(threadId, rolloutPath) {
32146
32360
  if (threadId === this.#threadId) return;
32147
32361
  this.#threadId = threadId;
@@ -32254,10 +32468,10 @@ var init_codex = __esm({
32254
32468
  };
32255
32469
  let identify = () => {
32256
32470
  };
32257
- const identified = new Promise((resolve13) => {
32258
- identify = resolve13;
32471
+ const identified = new Promise((resolve14) => {
32472
+ identify = resolve14;
32259
32473
  });
32260
- const done = new Promise((resolve13) => {
32474
+ const done = new Promise((resolve14) => {
32261
32475
  finish = (outcome2) => {
32262
32476
  if (this.#current?.id !== id) return;
32263
32477
  this.#current = void 0;
@@ -32265,7 +32479,7 @@ var init_codex = __esm({
32265
32479
  if (this.#state === "busy") this.#state = "idle";
32266
32480
  this.#host.scanDescendants(true);
32267
32481
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
32268
- resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
32482
+ resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
32269
32483
  };
32270
32484
  });
32271
32485
  const active = {
@@ -32308,6 +32522,10 @@ var init_codex = __esm({
32308
32522
  return known === void 0 || known === turnId ? active : void 0;
32309
32523
  }
32310
32524
  #onNotification(notification) {
32525
+ if (notification.method === "account/rateLimits/updated") {
32526
+ this.#recordRateLimits(this.#rateLimits.notification(notification.params));
32527
+ return;
32528
+ }
32311
32529
  if (notification.method === "serverRequest/resolved") this.#dropResolved(notification);
32312
32530
  const active = this.#ownerOf(notification);
32313
32531
  const reader = active?.turn ?? this.#lastTurn;
@@ -32334,6 +32552,14 @@ var init_codex = __esm({
32334
32552
  void this.#stopTurn(active);
32335
32553
  }
32336
32554
  }
32555
+ #recordRateLimits(updates) {
32556
+ const active = this.#current;
32557
+ if (active) this.#emitUpdates(active, updates);
32558
+ else {
32559
+ this.#between.push(...updates);
32560
+ this.#between.splice(0, Math.max(0, this.#between.length - MAX_BETWEEN_UPDATES));
32561
+ }
32562
+ }
32337
32563
  #emitUpdates(active, updates) {
32338
32564
  for (const update of updates) this.#emit({ type: "update", turnId: active.id, update });
32339
32565
  }
@@ -32808,7 +33034,7 @@ function alanCodeConfigContent(existing, input2) {
32808
33034
  });
32809
33035
  }
32810
33036
  function readBody2(response) {
32811
- return new Promise((resolve13, reject) => {
33037
+ return new Promise((resolve14, reject) => {
32812
33038
  const chunks = [];
32813
33039
  let size = 0;
32814
33040
  response.on("data", (chunk) => {
@@ -32816,7 +33042,7 @@ function readBody2(response) {
32816
33042
  if (size > MAX_CATALOG_BYTES) response.destroy(new Error("catalog too large"));
32817
33043
  else chunks.push(chunk);
32818
33044
  });
32819
- response.on("end", () => resolve13(Buffer.concat(chunks).toString("utf8")));
33045
+ response.on("end", () => resolve14(Buffer.concat(chunks).toString("utf8")));
32820
33046
  response.on("error", reject);
32821
33047
  });
32822
33048
  }
@@ -32832,13 +33058,13 @@ function parseResponseBody(text3, status) {
32832
33058
  }
32833
33059
  function getJson(url3, headers, timeout, signal) {
32834
33060
  const request2 = url3.protocol === "https:" ? import_https.request : import_http9.request;
32835
- return new Promise((resolve13, reject) => {
33061
+ return new Promise((resolve14, reject) => {
32836
33062
  const outgoing = request2(url3, { method: "GET", headers, timeout, signal }, (response) => {
32837
33063
  const status = response.statusCode ?? 0;
32838
33064
  readBody2(response).then((text3) => {
32839
33065
  const body = parseResponseBody(text3, status);
32840
33066
  if (status < 200 || status >= 300) reject(new CatalogResponseError(status, body));
32841
- else resolve13(body);
33067
+ else resolve14(body);
32842
33068
  }).catch(reject);
32843
33069
  });
32844
33070
  outgoing.on("timeout", () => outgoing.destroy(new Error("catalog timed out")));
@@ -33052,9 +33278,9 @@ function alanCodeEngineEnv(input2) {
33052
33278
  };
33053
33279
  }
33054
33280
  async function writePlugin(directory, apiOrigin) {
33055
- const origin = (0, import_crypto11.createHash)("sha256").update(apiOrigin).digest("hex").slice(0, 12);
33281
+ const origin = (0, import_crypto12.createHash)("sha256").update(apiOrigin).digest("hex").slice(0, 12);
33056
33282
  const target = (0, import_path8.join)(directory, `engine-plugin-v${ALAN_CODE_ENGINE_PLUGIN_VERSION}-${origin}.mjs`);
33057
- const temporary = `${target}.${(0, import_crypto11.randomUUID)()}.tmp`;
33283
+ const temporary = `${target}.${(0, import_crypto12.randomUUID)()}.tmp`;
33058
33284
  await (0, import_promises34.mkdir)(directory, { recursive: true, mode: 448 });
33059
33285
  await (0, import_promises34.writeFile)(temporary, alanCodeEnginePluginSource(apiOrigin), { mode: 384 });
33060
33286
  await (0, import_promises34.rename)(temporary, target);
@@ -33086,7 +33312,7 @@ function alanCodeSystemPrompt(alanSystemPrompt) {
33086
33312
 
33087
33313
  ${instructions}` : ALAN_CODE_TOOL_NAMING_PROMPT;
33088
33314
  }
33089
- var import_http9, import_https, import_fs7, import_path7, import_crypto11, import_promises34, import_path8, import_url, ALAN_CODE_BASELINE_PROMPT, ALAN_CODE_ENGINE_PROVIDER_ID, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_OUTPUT_TOKENS, ALAN_CODE_API_KEY_ENV, ALAN_CODE_CONVERSATION_ID_ENV, ALAN_CODE_PROXY_PATH, ALAN_CODE_WEBSEARCH_PATH, ALAN_CODE_CATALOG_PATH, CATALOG_TIMEOUT_MS, MAX_CATALOG_BYTES, ACTIVATION_WAIT_MS, ACTIVATION_POLL_MS, CatalogResponseError, ALAN_CODE_ENGINE_PATH_ENV, ALAN_CODE_ENGINE_COMMAND, ALAN_CODE_ENGINE_NAME, WINDOWS_RUNNABLE_EXTENSION, ALAN_CODE_ENGINE_PLUGIN_VERSION, ALAN_CODE_TOOL_NAMING_PROMPT;
33315
+ var import_http9, import_https, import_fs7, import_path7, import_crypto12, import_promises34, import_path8, import_url, ALAN_CODE_BASELINE_PROMPT, ALAN_CODE_ENGINE_PROVIDER_ID, DEFAULT_CONTEXT_WINDOW, DEFAULT_MAX_OUTPUT_TOKENS, ALAN_CODE_API_KEY_ENV, ALAN_CODE_CONVERSATION_ID_ENV, ALAN_CODE_PROXY_PATH, ALAN_CODE_WEBSEARCH_PATH, ALAN_CODE_CATALOG_PATH, CATALOG_TIMEOUT_MS, MAX_CATALOG_BYTES, ACTIVATION_WAIT_MS, ACTIVATION_POLL_MS, CatalogResponseError, ALAN_CODE_ENGINE_PATH_ENV, ALAN_CODE_ENGINE_COMMAND, ALAN_CODE_ENGINE_NAME, WINDOWS_RUNNABLE_EXTENSION, ALAN_CODE_ENGINE_PLUGIN_VERSION, ALAN_CODE_TOOL_NAMING_PROMPT;
33090
33316
  var init_alan_code = __esm({
33091
33317
  "../agent-core/dist/providers/alan-code.js"() {
33092
33318
  "use strict";
@@ -33099,7 +33325,7 @@ var init_alan_code = __esm({
33099
33325
  import_fs7 = require("fs");
33100
33326
  import_path7 = require("path");
33101
33327
  init_runtime_v2();
33102
- import_crypto11 = require("crypto");
33328
+ import_crypto12 = require("crypto");
33103
33329
  import_promises34 = require("fs/promises");
33104
33330
  import_path8 = require("path");
33105
33331
  import_url = require("url");
@@ -41714,8 +41940,8 @@ var require_streamx = __commonJS({
41714
41940
  return this;
41715
41941
  },
41716
41942
  next() {
41717
- return new Promise(function(resolve13, reject) {
41718
- promiseResolve = resolve13;
41943
+ return new Promise(function(resolve14, reject) {
41944
+ promiseResolve = resolve14;
41719
41945
  promiseReject = reject;
41720
41946
  const data = stream.read();
41721
41947
  if (data !== null) ondata(data);
@@ -41748,11 +41974,11 @@ var require_streamx = __commonJS({
41748
41974
  }
41749
41975
  function destroy(err) {
41750
41976
  stream.destroy(err);
41751
- return new Promise((resolve13, reject) => {
41752
- if (stream._duplexState & DESTROYED) return resolve13({ value: void 0, done: true });
41977
+ return new Promise((resolve14, reject) => {
41978
+ if (stream._duplexState & DESTROYED) return resolve14({ value: void 0, done: true });
41753
41979
  stream.once("close", function() {
41754
41980
  if (err) reject(err);
41755
- else resolve13({ value: void 0, done: true });
41981
+ else resolve14({ value: void 0, done: true });
41756
41982
  });
41757
41983
  });
41758
41984
  }
@@ -41796,8 +42022,8 @@ var require_streamx = __commonJS({
41796
42022
  const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0);
41797
42023
  if (writes === 0) return Promise.resolve(true);
41798
42024
  if (state.drains === null) state.drains = [];
41799
- return new Promise((resolve13) => {
41800
- state.drains.push({ writes, resolve: resolve13 });
42025
+ return new Promise((resolve14) => {
42026
+ state.drains.push({ writes, resolve: resolve14 });
41801
42027
  });
41802
42028
  }
41803
42029
  write(data) {
@@ -41902,10 +42128,10 @@ var require_streamx = __commonJS({
41902
42128
  cb(null);
41903
42129
  }
41904
42130
  function pipelinePromise(...streams) {
41905
- return new Promise((resolve13, reject) => {
42131
+ return new Promise((resolve14, reject) => {
41906
42132
  return pipeline(...streams, (err) => {
41907
42133
  if (err) return reject(err);
41908
- resolve13();
42134
+ resolve14();
41909
42135
  });
41910
42136
  });
41911
42137
  }
@@ -42577,16 +42803,16 @@ var require_extract = __commonJS({
42577
42803
  entryCallback = null;
42578
42804
  cb(err);
42579
42805
  }
42580
- function onnext(resolve13, reject) {
42806
+ function onnext(resolve14, reject) {
42581
42807
  if (error61) {
42582
42808
  return reject(error61);
42583
42809
  }
42584
42810
  if (entryStream) {
42585
- resolve13({ value: entryStream, done: false });
42811
+ resolve14({ value: entryStream, done: false });
42586
42812
  entryStream = null;
42587
42813
  return;
42588
42814
  }
42589
- promiseResolve = resolve13;
42815
+ promiseResolve = resolve14;
42590
42816
  promiseReject = reject;
42591
42817
  consumeCallback(null);
42592
42818
  if (extract2._finished && promiseResolve) {
@@ -42614,11 +42840,11 @@ var require_extract = __commonJS({
42614
42840
  function destroy(err) {
42615
42841
  extract2.destroy(err);
42616
42842
  consumeCallback(err);
42617
- return new Promise((resolve13, reject) => {
42618
- if (extract2.destroyed) return resolve13({ value: void 0, done: true });
42843
+ return new Promise((resolve14, reject) => {
42844
+ if (extract2.destroyed) return resolve14({ value: void 0, done: true });
42619
42845
  extract2.once("close", function() {
42620
42846
  if (err) reject(err);
42621
- else resolve13({ value: void 0, done: true });
42847
+ else resolve14({ value: void 0, done: true });
42622
42848
  });
42623
42849
  });
42624
42850
  }
@@ -42905,9 +43131,9 @@ var require_tar_stream = __commonJS({
42905
43131
  var init_dist = __esm({
42906
43132
  "../agent-core/dist/index.js"() {
42907
43133
  "use strict";
42908
- init_chunk_72NSEYHK();
43134
+ init_chunk_4G77APXN();
42909
43135
  init_chunk_XC5676SG();
42910
- init_chunk_54ZRJOQP();
43136
+ init_chunk_HBIPWAUI();
42911
43137
  init_chunk_M6YHY2EZ();
42912
43138
  init_chunk_YXWJW7I5();
42913
43139
  }
@@ -43581,7 +43807,7 @@ function isAcpBackendKind(value2) {
43581
43807
  return Object.hasOwn(ACP_PROFILES, value2);
43582
43808
  }
43583
43809
  function envDigest3(env) {
43584
- const hash2 = (0, import_crypto12.createHash)("sha256");
43810
+ const hash2 = (0, import_crypto13.createHash)("sha256");
43585
43811
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
43586
43812
  return hash2.digest("hex");
43587
43813
  }
@@ -43648,13 +43874,13 @@ async function acpTurnInput(run2, context) {
43648
43874
  ...encoded.length ? { images: encoded, imagePaths: images.map((image) => image.path) } : {}
43649
43875
  };
43650
43876
  }
43651
- var import_promises49, import_path9, import_crypto12, import_promises50, CURSOR_ASK_QUESTION, copilotAcpProfile, cursorAcpProfile, MODEL_REJECTED, MAX_READ_BYTES, FsDenied, ENV_REFERENCE, AcpBackgroundTasks, CURSOR_CREATE_PLAN, STATUSES2, READ_KINDS, ALLOW_KINDS, REJECT_KINDS, CANCELLED_PERMISSION, STOP_REASONS, CHUNKS, ECHOES, AcpTurn, STDERR_TAIL_LINES4, MAX_BETWEEN_UPDATES2, AcpSession, DEFAULTS3, CLIENT_INFO2, TASK_BACKGROUNDED, TASK_COMPLETED, SESSION_NOTIFICATION, KILLED_STATUSES, SUCCESS_STATUSES, SUBAGENT_ID, grokTaskDialect, grokAcpProfile, kimiAcpProfile, ACP_PROFILES, ACP_MODES;
43877
+ var import_promises49, import_path9, import_crypto13, import_promises50, CURSOR_ASK_QUESTION, copilotAcpProfile, cursorAcpProfile, MODEL_REJECTED, MAX_READ_BYTES, FsDenied, ENV_REFERENCE, AcpBackgroundTasks, CURSOR_CREATE_PLAN, STATUSES2, READ_KINDS, ALLOW_KINDS, REJECT_KINDS, CANCELLED_PERMISSION, STOP_REASONS, CHUNKS, ECHOES, AcpTurn, STDERR_TAIL_LINES4, MAX_BETWEEN_UPDATES2, AcpSession, DEFAULTS3, CLIENT_INFO2, TASK_BACKGROUNDED, TASK_COMPLETED, SESSION_NOTIFICATION, KILLED_STATUSES, SUCCESS_STATUSES, SUBAGENT_ID, grokTaskDialect, grokAcpProfile, kimiAcpProfile, ACP_PROFILES, ACP_MODES;
43652
43878
  var init_acp3 = __esm({
43653
43879
  "../agent-core/dist/providers/acp.js"() {
43654
43880
  "use strict";
43655
- init_chunk_72NSEYHK();
43881
+ init_chunk_4G77APXN();
43656
43882
  init_chunk_XC5676SG();
43657
- init_chunk_54ZRJOQP();
43883
+ init_chunk_HBIPWAUI();
43658
43884
  init_chunk_J2KTV5FP();
43659
43885
  init_chunk_M6YHY2EZ();
43660
43886
  init_chunk_FPGAN4XO();
@@ -43663,7 +43889,7 @@ var init_acp3 = __esm({
43663
43889
  import_path9 = require("path");
43664
43890
  init_effort();
43665
43891
  init_acp();
43666
- import_crypto12 = require("crypto");
43892
+ import_crypto13 = require("crypto");
43667
43893
  import_promises50 = require("fs/promises");
43668
43894
  init_agent2();
43669
43895
  CURSOR_ASK_QUESTION = "cursor/ask_question";
@@ -44180,7 +44406,7 @@ var init_acp3 = __esm({
44180
44406
  const turn = new AcpTurn(`acp-${this.#turns}-${id}`, this.#profile);
44181
44407
  let finish = () => {
44182
44408
  };
44183
- const done = new Promise((resolve13) => {
44409
+ const done = new Promise((resolve14) => {
44184
44410
  finish = (outcome2) => {
44185
44411
  if (this.#current?.id !== id) return;
44186
44412
  this.#current = void 0;
@@ -44188,7 +44414,7 @@ var init_acp3 = __esm({
44188
44414
  if (this.#state === "busy") this.#state = "idle";
44189
44415
  this.#host.scanDescendants(true);
44190
44416
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
44191
- resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
44417
+ resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
44192
44418
  };
44193
44419
  });
44194
44420
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -44469,7 +44695,7 @@ var init_acp3 = __esm({
44469
44695
  var init_classify = __esm({
44470
44696
  "../agent-core/dist/classify.js"() {
44471
44697
  "use strict";
44472
- init_chunk_54ZRJOQP();
44698
+ init_chunk_HBIPWAUI();
44473
44699
  init_chunk_YXWJW7I5();
44474
44700
  }
44475
44701
  });
@@ -44679,7 +44905,10 @@ function createPersistentDriver(provider4, options) {
44679
44905
  return "delivered";
44680
44906
  };
44681
44907
  const openFailed = (error61, spec, sink, signal, inputs) => {
44682
- if (error61 instanceof SessionOpenRefusal && error61.reason === "unsupported_version" && options.fallback) {
44908
+ if (error61 instanceof SessionOpenRefusal && error61.reason === "unsupported_version" && inputs.codex !== void 0) {
44909
+ return { outcome: "failed", message: error61.message };
44910
+ }
44911
+ if (error61 instanceof SessionOpenRefusal && error61.reason === "unsupported_version" && options.fallback && inputs.codex === void 0) {
44683
44912
  log.warn("holder.persistent_unsupported", {
44684
44913
  harness: provider4.harness,
44685
44914
  message: error61.message
@@ -44696,7 +44925,7 @@ function createPersistentDriver(provider4, options) {
44696
44925
  };
44697
44926
  return {
44698
44927
  runTurn: async (spec, sink, signal, inputs) => {
44699
- if (live.fallbackOnly && options.fallback)
44928
+ if (live.fallbackOnly && options.fallback && inputs.codex === void 0)
44700
44929
  return options.fallback.runTurn(spec, sink, signal, inputs);
44701
44930
  if (signal.aborted) return { outcome: "aborted" };
44702
44931
  const managedMcp = await managedMcpAccess(signal);
@@ -45286,7 +45515,7 @@ function createOpenCodeDriver(options = {}) {
45286
45515
  await authorization?.remove();
45287
45516
  };
45288
45517
  const spec = { ...planned, env: launchEnv(planned, authorization) };
45289
- const password = options.password?.() ?? (0, import_crypto13.randomBytes)(24).toString("base64url");
45518
+ const password = options.password?.() ?? (0, import_crypto14.randomBytes)(24).toString("base64url");
45290
45519
  try {
45291
45520
  const session = await openWithRetries(spec, password, resolved);
45292
45521
  void session.exited.then(removeAuthorization).catch((error61) => {
@@ -45301,7 +45530,7 @@ function createOpenCodeDriver(options = {}) {
45301
45530
  };
45302
45531
  }
45303
45532
  function envDigest4(env) {
45304
- const hash2 = (0, import_crypto14.createHash)("sha256");
45533
+ const hash2 = (0, import_crypto15.createHash)("sha256");
45305
45534
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
45306
45535
  return hash2.digest("hex");
45307
45536
  }
@@ -45382,20 +45611,20 @@ function openCodeTurnInput(run2, context) {
45382
45611
  ...images.length ? { imagePaths: images.map((image) => image.path) } : {}
45383
45612
  };
45384
45613
  }
45385
- var import_http10, import_crypto13, import_promises51, import_path10, import_path11, import_url2, import_crypto14, IDLE_SOCKET_MS3, OpenCodeHttpError, OpenCodeClient, OPENCODE_CONFIG_ENV, OPENCODE_ENGINE, TEXT_PARTS, STEP_PARTS, STOPPED_BY_USER, OpenCodeSubagents, NAMED_KINDS, OPENCODE_ABORTED_ERROR, PROVIDER_EVENT_META, TASK_TOOL_NAME, TASK_RESULT_TAG, TASK_ERROR_TAG, PERMISSION_DENIED, FILE_OPERATIONS2, PartReader, NOTHING, NON_INTERACTIVE_PERMISSIONS, CONTENT_FILTER_FINISHES, OUTPUT_PARTS, OpenCodeTurn, LISTENING, OUTPUT_TAIL_LINES, IMAGE_TYPES, OpenCodeSession, OPENCODE_MIN_VERSION, OPENCODE_REQUIREMENT, OPENCODE_TESTED_LINE, OPENCODE_SUPPORTED_MAJOR, DEFAULTS4, STORE_LOCKED, NON_INTERACTIVE_RULES, TITLE_LENGTH, MAX_VARIANT_LENGTH;
45614
+ var import_http10, import_crypto14, import_promises51, import_path10, import_path11, import_url2, import_crypto15, IDLE_SOCKET_MS3, OpenCodeHttpError, OpenCodeClient, OPENCODE_CONFIG_ENV, OPENCODE_ENGINE, TEXT_PARTS, STEP_PARTS, STOPPED_BY_USER, OpenCodeSubagents, NAMED_KINDS, OPENCODE_ABORTED_ERROR, PROVIDER_EVENT_META, TASK_TOOL_NAME, TASK_RESULT_TAG, TASK_ERROR_TAG, PERMISSION_DENIED, FILE_OPERATIONS2, PartReader, NOTHING, NON_INTERACTIVE_PERMISSIONS, CONTENT_FILTER_FINISHES, OUTPUT_PARTS, OpenCodeTurn, LISTENING, OUTPUT_TAIL_LINES, IMAGE_TYPES, OpenCodeSession, OPENCODE_MIN_VERSION, OPENCODE_REQUIREMENT, OPENCODE_TESTED_LINE, OPENCODE_SUPPORTED_MAJOR, DEFAULTS4, STORE_LOCKED, NON_INTERACTIVE_RULES, TITLE_LENGTH, MAX_VARIANT_LENGTH;
45386
45615
  var init_opencode = __esm({
45387
45616
  "../agent-core/dist/providers/opencode.js"() {
45388
45617
  "use strict";
45389
- init_chunk_72NSEYHK();
45618
+ init_chunk_4G77APXN();
45390
45619
  init_chunk_XC5676SG();
45391
- init_chunk_54ZRJOQP();
45620
+ init_chunk_HBIPWAUI();
45392
45621
  init_chunk_J2KTV5FP();
45393
45622
  init_chunk_M6YHY2EZ();
45394
45623
  init_chunk_FPGAN4XO();
45395
45624
  init_chunk_YXWJW7I5();
45396
45625
  import_http10 = require("http");
45397
45626
  init_runtime_v2();
45398
- import_crypto13 = require("crypto");
45627
+ import_crypto14 = require("crypto");
45399
45628
  import_promises51 = require("fs/promises");
45400
45629
  import_path10 = require("path");
45401
45630
  init_agent2();
@@ -45403,7 +45632,7 @@ var init_opencode = __esm({
45403
45632
  import_url2 = require("url");
45404
45633
  init_acp();
45405
45634
  init_acp();
45406
- import_crypto14 = require("crypto");
45635
+ import_crypto15 = require("crypto");
45407
45636
  init_agent2();
45408
45637
  IDLE_SOCKET_MS3 = 4e3;
45409
45638
  OpenCodeHttpError = class extends Error {
@@ -46699,11 +46928,11 @@ function createCodexLogin(broker) {
46699
46928
  }
46700
46929
  };
46701
46930
  }
46702
- function withLogin(planned, externalAuth, accountId) {
46931
+ function withLogin(planned, externalAuth, credentialKey) {
46703
46932
  return {
46704
46933
  ...planned,
46705
46934
  spec: { ...planned.spec, externalAuth },
46706
- key: JSON.stringify([planned.key, accountId])
46935
+ key: JSON.stringify([planned.key, credentialKey])
46707
46936
  };
46708
46937
  }
46709
46938
  function createCodexHolderDriver(options) {
@@ -46725,7 +46954,11 @@ function createCodexHolderDriver(options) {
46725
46954
  });
46726
46955
  if (inputs.codex === void 0) return planned;
46727
46956
  login.forTurn(spec.runId, inputs.codex);
46728
- return withLogin(planned, login.externalAuth, inputs.codex.chatgptAccountId);
46957
+ return withLogin(
46958
+ planned,
46959
+ login.externalAuth,
46960
+ inputs.codex.credentialId ?? inputs.codex.chatgptAccountId
46961
+ );
46729
46962
  },
46730
46963
  canResume: () => true,
46731
46964
  open: async (spec) => {
@@ -46857,8 +47090,8 @@ function createDroidPeer(writer, handlers) {
46857
47090
  },
46858
47091
  request: (method, params = {}) => {
46859
47092
  const id = `alan-${counter.next++}`;
46860
- return new Promise((resolve13, reject) => {
46861
- pending.set(id, { method, resolve: resolve13, reject });
47093
+ return new Promise((resolve14, reject) => {
47094
+ pending.set(id, { method, resolve: resolve14, reject });
46862
47095
  writer.write(envelope("request", { id, method, params })).catch((error61) => {
46863
47096
  pending.delete(id);
46864
47097
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -47138,7 +47371,7 @@ function createDroidDriver(options = {}) {
47138
47371
  };
47139
47372
  }
47140
47373
  function envDigest5(env) {
47141
- const hash2 = (0, import_crypto15.createHash)("sha256");
47374
+ const hash2 = (0, import_crypto16.createHash)("sha256");
47142
47375
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
47143
47376
  return hash2.digest("hex");
47144
47377
  }
@@ -47198,19 +47431,19 @@ async function droidTurnInput(run2, context) {
47198
47431
  );
47199
47432
  return { turnId: run2.runId, text: text3, ...encoded.length ? { images: encoded } : {} };
47200
47433
  }
47201
- var import_crypto15, import_promises52, FACTORY_API_VERSION, FACTORY_PROTOCOL_VERSION, SUBAGENT_TOOLS, TASK_OUTPUT_TOOLS, TASK_STOP_TOOLS, SILENT2, DroidTurn, STDERR_TAIL_LINES5, UNSUPPORTED_REQUEST2, DroidSession, DEFAULTS5, DROID_REQUIREMENT, DROID_JSONRPC_ARGS;
47434
+ var import_crypto16, import_promises52, FACTORY_API_VERSION, FACTORY_PROTOCOL_VERSION, SUBAGENT_TOOLS, TASK_OUTPUT_TOOLS, TASK_STOP_TOOLS, SILENT2, DroidTurn, STDERR_TAIL_LINES5, UNSUPPORTED_REQUEST2, DroidSession, DEFAULTS5, DROID_REQUIREMENT, DROID_JSONRPC_ARGS;
47202
47435
  var init_droid = __esm({
47203
47436
  "../agent-core/dist/providers/droid.js"() {
47204
47437
  "use strict";
47205
- init_chunk_72NSEYHK();
47438
+ init_chunk_4G77APXN();
47206
47439
  init_chunk_XC5676SG();
47207
- init_chunk_54ZRJOQP();
47440
+ init_chunk_HBIPWAUI();
47208
47441
  init_chunk_J2KTV5FP();
47209
47442
  init_chunk_M6YHY2EZ();
47210
47443
  init_chunk_FPGAN4XO();
47211
47444
  init_chunk_YXWJW7I5();
47212
47445
  init_runtime_v2();
47213
- import_crypto15 = require("crypto");
47446
+ import_crypto16 = require("crypto");
47214
47447
  import_promises52 = require("fs/promises");
47215
47448
  init_agent2();
47216
47449
  FACTORY_API_VERSION = "1.0.0";
@@ -47483,14 +47716,14 @@ var init_droid = __esm({
47483
47716
  const turn = new DroidTurn(sessionId, this.#memory);
47484
47717
  let finish = () => {
47485
47718
  };
47486
- const done = new Promise((resolve13) => {
47719
+ const done = new Promise((resolve14) => {
47487
47720
  finish = (outcome2) => {
47488
47721
  if (this.#current?.id !== id) return;
47489
47722
  this.#current = void 0;
47490
47723
  if (this.#state === "busy") this.#state = "idle";
47491
47724
  this.#host.scanDescendants(true);
47492
47725
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
47493
- resolve13({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
47726
+ resolve14({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
47494
47727
  };
47495
47728
  });
47496
47729
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -48258,7 +48491,7 @@ ${output2.stderr}`).join("\n")
48258
48491
  };
48259
48492
  }
48260
48493
  function envDigest6(env) {
48261
- const hash2 = (0, import_crypto16.createHash)("sha256");
48494
+ const hash2 = (0, import_crypto17.createHash)("sha256");
48262
48495
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
48263
48496
  return hash2.digest("hex");
48264
48497
  }
@@ -48304,14 +48537,14 @@ function antigravityTurnInput(run2, context) {
48304
48537
  });
48305
48538
  return { turnId: run2.runId, text: appendImagePathReferences(text3, images) };
48306
48539
  }
48307
- var import_promises53, import_path12, import_fs8, import_path13, import_path14, import_url3, import_crypto16, NO_ANTIGRAVITY_CAPABILITIES, INSTRUCTIONS_FILE, MAX_INSTRUCTION_CHARS, SHORTENED_NOTE, DIFF_BLOCK_START, DIFF_BLOCK_END, HUNK_HEADER, TRANSCRIPT_FILE, FULL_TRANSCRIPT_FILE, LOG_DIRS, TOOL_RESULT_TYPES, BrainTranscript, AntigravityTranscripts, ANTIGRAVITY_GRAMMAR_NAME, AntigravityGrammar, ignored, HANDLERS, SUCCESSFUL_STATUSES, SESSION_START_TYPES, RESULT_TYPES, SUBAGENT_START_TYPES, RESUME_FORKED, EXITED_WITHOUT_RESULT, AntigravityTurn, DEFAULTS6, AntigravitySession, WINDOWS_LINE_MARGIN;
48540
+ var import_promises53, import_path12, import_fs8, import_path13, import_path14, import_url3, import_crypto17, NO_ANTIGRAVITY_CAPABILITIES, INSTRUCTIONS_FILE, MAX_INSTRUCTION_CHARS, SHORTENED_NOTE, DIFF_BLOCK_START, DIFF_BLOCK_END, HUNK_HEADER, TRANSCRIPT_FILE, FULL_TRANSCRIPT_FILE, LOG_DIRS, TOOL_RESULT_TYPES, BrainTranscript, AntigravityTranscripts, ANTIGRAVITY_GRAMMAR_NAME, AntigravityGrammar, ignored, HANDLERS, SUCCESSFUL_STATUSES, SESSION_START_TYPES, RESULT_TYPES, SUBAGENT_START_TYPES, RESUME_FORKED, EXITED_WITHOUT_RESULT, AntigravityTurn, DEFAULTS6, AntigravitySession, WINDOWS_LINE_MARGIN;
48308
48541
  var init_antigravity = __esm({
48309
48542
  "../agent-core/dist/providers/antigravity.js"() {
48310
48543
  "use strict";
48311
48544
  init_chunk_SBT5W7L4();
48312
- init_chunk_72NSEYHK();
48545
+ init_chunk_4G77APXN();
48313
48546
  init_chunk_XC5676SG();
48314
- init_chunk_54ZRJOQP();
48547
+ init_chunk_HBIPWAUI();
48315
48548
  init_chunk_M6YHY2EZ();
48316
48549
  init_chunk_FPGAN4XO();
48317
48550
  init_chunk_YXWJW7I5();
@@ -48323,7 +48556,7 @@ var init_antigravity = __esm({
48323
48556
  init_effort();
48324
48557
  import_path14 = require("path");
48325
48558
  import_url3 = require("url");
48326
- import_crypto16 = require("crypto");
48559
+ import_crypto17 = require("crypto");
48327
48560
  init_agent2();
48328
48561
  NO_ANTIGRAVITY_CAPABILITIES = {
48329
48562
  structuredPrint: false,
@@ -48957,7 +49190,7 @@ function createCommandCodeDriver(options = {}) {
48957
49190
  };
48958
49191
  }
48959
49192
  function envDigest7(env) {
48960
- const hash2 = (0, import_crypto17.createHash)("sha256");
49193
+ const hash2 = (0, import_crypto18.createHash)("sha256");
48961
49194
  for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
48962
49195
  return hash2.digest("hex");
48963
49196
  }
@@ -49009,13 +49242,13 @@ function commandCodeTurnInput(run2, context) {
49009
49242
  });
49010
49243
  return { turnId: run2.runId, text: appendImagePathReferences(text3, images) };
49011
49244
  }
49012
- var import_promises54, import_path15, import_crypto17, COMMAND_CODE_GRAMMAR_NAME, SILENT3, CommandCodeGrammar, SHELL_TOOL, STOP_TOOLS, REPORTED_STATUS, SHELL_STATUS, SWEEP_INTERVAL_MS, CommandCodeBackgroundTasks, EXITED_WITHOUT_RESULT2, CommandCodeTurn, COMMAND_CODE_MAX_TURNS, DEFAULTS7, CommandCodeSession;
49245
+ var import_promises54, import_path15, import_crypto18, COMMAND_CODE_GRAMMAR_NAME, SILENT3, CommandCodeGrammar, SHELL_TOOL, STOP_TOOLS, REPORTED_STATUS, SHELL_STATUS, SWEEP_INTERVAL_MS, CommandCodeBackgroundTasks, EXITED_WITHOUT_RESULT2, CommandCodeTurn, COMMAND_CODE_MAX_TURNS, DEFAULTS7, CommandCodeSession;
49013
49246
  var init_command_code = __esm({
49014
49247
  "../agent-core/dist/providers/command-code.js"() {
49015
49248
  "use strict";
49016
- init_chunk_72NSEYHK();
49249
+ init_chunk_4G77APXN();
49017
49250
  init_chunk_XC5676SG();
49018
- init_chunk_54ZRJOQP();
49251
+ init_chunk_HBIPWAUI();
49019
49252
  init_chunk_J2KTV5FP();
49020
49253
  init_chunk_M6YHY2EZ();
49021
49254
  init_chunk_FPGAN4XO();
@@ -49025,7 +49258,7 @@ var init_command_code = __esm({
49025
49258
  init_agent2();
49026
49259
  init_runtime_v2();
49027
49260
  init_acp();
49028
- import_crypto17 = require("crypto");
49261
+ import_crypto18 = require("crypto");
49029
49262
  init_agent2();
49030
49263
  COMMAND_CODE_GRAMMAR_NAME = "command_code_cli";
49031
49264
  SILENT3 = /* @__PURE__ */ new Set([
@@ -54416,7 +54649,7 @@ var require_websocket_server = __commonJS({
54416
54649
  // package.json
54417
54650
  var package_default = {
54418
54651
  name: "@alan-ai-hq/agent-manager",
54419
- version: "0.1.145",
54652
+ version: "0.1.147",
54420
54653
  private: true,
54421
54654
  type: "module",
54422
54655
  description: "Alan machine runtime (alan-agent): identity, link, reconciler, session holders, run log, uploader, local API",
@@ -54466,7 +54699,7 @@ var package_default = {
54466
54699
 
54467
54700
  // src/cli/commands/compat.ts
54468
54701
  var import_node_crypto32 = require("crypto");
54469
- var import_promises68 = require("fs/promises");
54702
+ var import_promises69 = require("fs/promises");
54470
54703
  init_runtime_v2();
54471
54704
  init_zod();
54472
54705
 
@@ -54625,8 +54858,8 @@ async function writeJsonFileAtomic(path4, value2) {
54625
54858
  var LIFECYCLE_DRAIN_MS = 5e3;
54626
54859
  function createGate() {
54627
54860
  const opened = {};
54628
- const promise2 = new Promise((resolve13) => {
54629
- opened.resolve = resolve13;
54861
+ const promise2 = new Promise((resolve14) => {
54862
+ opened.resolve = resolve14;
54630
54863
  });
54631
54864
  return { promise: promise2, open: () => opened.resolve?.() };
54632
54865
  }
@@ -54853,7 +55086,7 @@ function transportFailure(request2, error61) {
54853
55086
  });
54854
55087
  }
54855
55088
  function readBody(incoming, url3, maxBytes) {
54856
- return new Promise((resolve13, reject) => {
55089
+ return new Promise((resolve14, reject) => {
54857
55090
  const declared = Number(incoming.headers["content-length"] ?? "0");
54858
55091
  if (maxBytes !== void 0 && declared > maxBytes) {
54859
55092
  incoming.destroy();
@@ -54872,7 +55105,7 @@ function readBody(incoming, url3, maxBytes) {
54872
55105
  chunks.push(chunk);
54873
55106
  });
54874
55107
  incoming.on("error", reject);
54875
- incoming.on("end", () => resolve13(Buffer.concat(chunks)));
55108
+ incoming.on("end", () => resolve14(Buffer.concat(chunks)));
54876
55109
  });
54877
55110
  }
54878
55111
  function isConnectionReset(error61) {
@@ -54880,7 +55113,7 @@ function isConnectionReset(error61) {
54880
55113
  }
54881
55114
  function exchange(request2, agents, attempt2 = 0) {
54882
55115
  const { signal, url: url3 } = request2;
54883
- return new Promise((resolve13, reject) => {
55116
+ return new Promise((resolve14, reject) => {
54884
55117
  if (signal.aborted) {
54885
55118
  reject(signal.reason);
54886
55119
  return;
@@ -54907,7 +55140,7 @@ function exchange(request2, agents, attempt2 = 0) {
54907
55140
  const stale = outgoing.reusedSocket && !responded && isConnectionReset(error61);
54908
55141
  if (stale && attempt2 < STALE_SOCKET_RETRIES && !signal.aborted) {
54909
55142
  settle();
54910
- resolve13(exchange(request2, agents, attempt2 + 1));
55143
+ resolve14(exchange(request2, agents, attempt2 + 1));
54911
55144
  return;
54912
55145
  }
54913
55146
  fail(error61);
@@ -54920,7 +55153,7 @@ function exchange(request2, agents, attempt2 = 0) {
54920
55153
  readBody(incoming, url3, isRedirect(status) ? void 0 : request2.maxBodyBytes).then(
54921
55154
  (body) => {
54922
55155
  settle();
54923
- resolve13({ status, headers: incoming.headers, body });
55156
+ resolve14({ status, headers: incoming.headers, body });
54924
55157
  },
54925
55158
  fail
54926
55159
  );
@@ -55165,8 +55398,8 @@ function isBodyless(method) {
55165
55398
  return method === "GET" || method === "HEAD";
55166
55399
  }
55167
55400
  function exchange2(send2, options, input2) {
55168
- return new Promise((resolve13, reject) => {
55169
- const outgoing = send2({ ...options, method: input2.method, signal: input2.signal }, resolve13);
55401
+ return new Promise((resolve14, reject) => {
55402
+ const outgoing = send2({ ...options, method: input2.method, signal: input2.signal }, resolve14);
55170
55403
  outgoing.on("error", reject);
55171
55404
  if (isBodyless(input2.method)) {
55172
55405
  input2.body.resume();
@@ -55234,7 +55467,18 @@ function createGitHubProxyForwarder(options) {
55234
55467
 
55235
55468
  // src/api-client/holder-client.ts
55236
55469
  init_runtime_v2();
55470
+ init_zod();
55237
55471
  var REQUEST_TIMEOUT_MS3 = 3e4;
55472
+ var credentialRefusalSchema = external_exports.object({ message: external_exports.string().trim().min(1) });
55473
+ function credentialFailureMessage(response, fallback) {
55474
+ if (response.status !== 409) return fallback;
55475
+ try {
55476
+ const parsed = credentialRefusalSchema.safeParse(jsonBody(response));
55477
+ return parsed.success ? parsed.data.message : fallback;
55478
+ } catch {
55479
+ return fallback;
55480
+ }
55481
+ }
55238
55482
  function createHolderApiClient({
55239
55483
  apiUrl,
55240
55484
  accessToken,
@@ -55267,7 +55511,10 @@ function createHolderApiClient({
55267
55511
  if (!isOk(response)) {
55268
55512
  throw new RuntimeFault(
55269
55513
  "io_failed",
55270
- `Provider credential request failed: ${response.status}`
55514
+ credentialFailureMessage(
55515
+ response,
55516
+ `Provider credential request failed: ${response.status}`
55517
+ )
55271
55518
  );
55272
55519
  }
55273
55520
  return runProviderCredentialSchema.parse(jsonBody(response));
@@ -55275,7 +55522,10 @@ function createHolderApiClient({
55275
55522
  refreshCodexCredential: async (runId, body, signal) => {
55276
55523
  const response = await request2("POST", runCodexCredentialRefreshPath(runId), signal, body);
55277
55524
  if (!isOk(response)) {
55278
- throw new RuntimeFault("io_failed", `Codex sign-in refresh failed: ${response.status}`);
55525
+ throw new RuntimeFault(
55526
+ "io_failed",
55527
+ credentialFailureMessage(response, `Codex sign-in refresh failed: ${response.status}`)
55528
+ );
55279
55529
  }
55280
55530
  return runCodexCredentialSchema.parse(jsonBody(response));
55281
55531
  },
@@ -56635,7 +56885,7 @@ function createGitRunner(options) {
56635
56885
  }
56636
56886
  await killProcessTree(child.pid, { signal: "SIGKILL", child, platform: platform3 });
56637
56887
  };
56638
- return new Promise((resolve13, reject) => {
56888
+ return new Promise((resolve14, reject) => {
56639
56889
  let ending = null;
56640
56890
  const stop = (next) => {
56641
56891
  if (ending !== null) return;
@@ -56660,7 +56910,7 @@ function createGitRunner(options) {
56660
56910
  signal.removeEventListener("abort", onAbort);
56661
56911
  const final = ending ?? last;
56662
56912
  if (final.kind === "exited") {
56663
- resolve13({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
56913
+ resolve14({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
56664
56914
  } else {
56665
56915
  reject(faultFor(final, command));
56666
56916
  }
@@ -56873,6 +57123,9 @@ async function checkSnapshotCheckouts(root, deps, signal) {
56873
57123
  })
56874
57124
  );
56875
57125
  }
57126
+ async function recordCheckoutKept(dir, path4, reason) {
57127
+ await writeJsonFileAtomic(freshnessFile(dir, path4), { state: "kept", path: path4, reason });
57128
+ }
56876
57129
  async function readCheckoutFreshness(dir, path4) {
56877
57130
  for (let current = path4; ; current = (0, import_node_path7.dirname)(current)) {
56878
57131
  const read = await readJsonFile(freshnessFile(dir, current), freshnessSchema);
@@ -58177,7 +58430,7 @@ function statusOf(error61) {
58177
58430
  }
58178
58431
  return 1;
58179
58432
  }
58180
- var systemExec = (request2) => new Promise((resolve13) => {
58433
+ var systemExec = (request2) => new Promise((resolve14) => {
58181
58434
  const child = (0, import_node_child_process6.execFile)(
58182
58435
  request2.command,
58183
58436
  [...request2.args],
@@ -58188,7 +58441,7 @@ var systemExec = (request2) => new Promise((resolve13) => {
58188
58441
  windowsHide: true
58189
58442
  },
58190
58443
  (error61, stdout, stderr) => {
58191
- resolve13({ status: statusOf(error61), stdout, stderr });
58444
+ resolve14({ status: statusOf(error61), stdout, stderr });
58192
58445
  }
58193
58446
  );
58194
58447
  child.stdin?.on("error", () => {
@@ -59378,11 +59631,11 @@ async function startGitCredentialServer(options) {
59378
59631
  });
59379
59632
  });
59380
59633
  removeStaleEndpoint(options.endpoint);
59381
- await new Promise((resolve13, reject) => {
59634
+ await new Promise((resolve14, reject) => {
59382
59635
  server.once("error", reject);
59383
59636
  server.listen(options.endpoint, () => {
59384
59637
  server.off("error", reject);
59385
- resolve13();
59638
+ resolve14();
59386
59639
  });
59387
59640
  });
59388
59641
  options.log.info("git.credential_server_listening", { endpoint: options.endpoint });
@@ -59390,7 +59643,7 @@ async function startGitCredentialServer(options) {
59390
59643
  endpoint: options.endpoint,
59391
59644
  [Symbol.asyncDispose]: async () => {
59392
59645
  closing.abort();
59393
- await new Promise((resolve13) => server.close(() => resolve13()));
59646
+ await new Promise((resolve14) => server.close(() => resolve14()));
59394
59647
  removeStaleEndpoint(options.endpoint);
59395
59648
  }
59396
59649
  };
@@ -59464,13 +59717,13 @@ authorityKeyIdentifier = keyid
59464
59717
  `;
59465
59718
  }
59466
59719
  function openssl(args, cwd) {
59467
- return new Promise((resolve13, reject) => {
59720
+ return new Promise((resolve14, reject) => {
59468
59721
  (0, import_node_child_process9.execFile)(
59469
59722
  "openssl",
59470
59723
  [...args],
59471
59724
  { cwd, timeout: OPENSSL_TIMEOUT_MS },
59472
59725
  (error61, _stdout, stderr) => {
59473
- if (error61 === null) resolve13();
59726
+ if (error61 === null) resolve14();
59474
59727
  else
59475
59728
  reject(new Error(`openssl ${args[0] ?? ""} failed: ${stderr.trim() || error61.message}`));
59476
59729
  }
@@ -59647,21 +59900,21 @@ function relayTo(forward, log) {
59647
59900
  };
59648
59901
  }
59649
59902
  function listen(server, target) {
59650
- return new Promise((resolve13, reject) => {
59903
+ return new Promise((resolve14, reject) => {
59651
59904
  server.once("error", reject);
59652
59905
  const done = () => {
59653
59906
  server.off("error", reject);
59654
- resolve13();
59907
+ resolve14();
59655
59908
  };
59656
59909
  if (typeof target === "string") server.listen(target, done);
59657
59910
  else server.listen(target.port, target.host, done);
59658
59911
  });
59659
59912
  }
59660
59913
  function close(server, sockets = /* @__PURE__ */ new Set()) {
59661
- return new Promise((resolve13) => {
59914
+ return new Promise((resolve14) => {
59662
59915
  for (const socket of sockets) socket.destroy();
59663
59916
  server.closeAllConnections();
59664
- server.close(() => resolve13());
59917
+ server.close(() => resolve14());
59665
59918
  });
59666
59919
  }
59667
59920
  function portOf(server) {
@@ -62444,7 +62697,7 @@ async function startNativeIngest(deps) {
62444
62697
  };
62445
62698
  const settleIdle = () => {
62446
62699
  if (workers.size > 0) return;
62447
- for (const resolve13 of idleWaiters) resolve13();
62700
+ for (const resolve14 of idleWaiters) resolve14();
62448
62701
  idleWaiters.clear();
62449
62702
  };
62450
62703
  const retryDelay = (worker) => {
@@ -62687,7 +62940,7 @@ async function startNativeIngest(deps) {
62687
62940
  sweep: sweep2,
62688
62941
  whenIdle: () => {
62689
62942
  if (workers.size === 0) return Promise.resolve();
62690
- return new Promise((resolve13) => idleWaiters.add(resolve13));
62943
+ return new Promise((resolve14) => idleWaiters.add(resolve14));
62691
62944
  },
62692
62945
  [Symbol.asyncDispose]: async () => {
62693
62946
  shutdown.abort();
@@ -62835,7 +63088,7 @@ function captureProbe(command, args, options) {
62835
63088
  const launch = directLaunch(command, args, options);
62836
63089
  if (launch === void 0) return Promise.resolve({ stdout: "", stderr: "", exitCode: void 0 });
62837
63090
  const env = platform3 === "win32" ? withWindowsHelper(canonicalWindowsEnvironment(options.env)) : options.env;
62838
- return new Promise((resolve13) => {
63091
+ return new Promise((resolve14) => {
62839
63092
  const limit = options.maxBufferBytes ?? DEFAULT_MAX_BYTES;
62840
63093
  const stdout = [];
62841
63094
  const stderr = [];
@@ -62870,7 +63123,7 @@ function captureProbe(command, args, options) {
62870
63123
  settled2 = true;
62871
63124
  deadlineController.abort();
62872
63125
  options.signal?.removeEventListener("abort", abort);
62873
- resolve13({
63126
+ resolve14({
62874
63127
  stdout: Buffer.concat(stdout).toString("utf8"),
62875
63128
  stderr: Buffer.concat(stderr).toString("utf8"),
62876
63129
  exitCode
@@ -63002,7 +63255,7 @@ function cursorAccountLabel(output2) {
63002
63255
  function waitForAbort(signal) {
63003
63256
  if (signal.aborted) return Promise.resolve();
63004
63257
  return new Promise(
63005
- (resolve13) => signal.addEventListener("abort", () => resolve13(), { once: true })
63258
+ (resolve14) => signal.addEventListener("abort", () => resolve14(), { once: true })
63006
63259
  );
63007
63260
  }
63008
63261
  function idlePrompt(signal) {
@@ -63080,14 +63333,14 @@ async function codexLabel(executable, env) {
63080
63333
  windowsVerbatimArguments: launch.windowsVerbatimArguments
63081
63334
  });
63082
63335
  const timeout = AbortSignal.timeout(ACCOUNT_TIMEOUT_MS);
63083
- return new Promise((resolve13) => {
63336
+ return new Promise((resolve14) => {
63084
63337
  let finished = false;
63085
63338
  let buffer = "";
63086
63339
  const finish = (label) => {
63087
63340
  if (finished) return;
63088
63341
  finished = true;
63089
63342
  child.kill();
63090
- resolve13(label);
63343
+ resolve14(label);
63091
63344
  };
63092
63345
  const send2 = (value2) => {
63093
63346
  child.stdin.write(`${JSON.stringify(value2)}
@@ -63596,11 +63849,11 @@ async function resolveCliEnvironment(options) {
63596
63849
  }
63597
63850
  async function openCliEnvironment(options) {
63598
63851
  const decorate = options.decorate ?? ((env) => env);
63599
- const resolve13 = async () => {
63852
+ const resolve14 = async () => {
63600
63853
  const resolved = await resolveCliEnvironmentDetailed(options);
63601
63854
  return { env: decorate(resolved.env), source: resolved.source };
63602
63855
  };
63603
- let state = await resolve13();
63856
+ let state = await resolve14();
63604
63857
  let retryAt = options.clock.now() + DEGRADED_RETRY_MS;
63605
63858
  return {
63606
63859
  current: () => state.env,
@@ -63609,7 +63862,7 @@ async function openCliEnvironment(options) {
63609
63862
  if (state.source === "login_shell" || options.platform === "win32") return false;
63610
63863
  if (options.clock.now() < retryAt) return false;
63611
63864
  retryAt = options.clock.now() + DEGRADED_RETRY_MS;
63612
- const next = await resolve13();
63865
+ const next = await resolve14();
63613
63866
  const changed = envValue(next.env, "PATH") !== envValue(state.env, "PATH");
63614
63867
  state = next;
63615
63868
  return changed;
@@ -63686,11 +63939,11 @@ async function installVersion2(backendKind, requested, options, signal) {
63686
63939
  }
63687
63940
  return exact;
63688
63941
  }
63689
- const resolve13 = options.resolveVersion;
63690
- if (resolve13 === void 0) throw new Error("Latest version lookup is unavailable");
63942
+ const resolve14 = options.resolveVersion;
63943
+ if (resolve14 === void 0) throw new Error("Latest version lookup is unavailable");
63691
63944
  const packageName = packageFor(backendKind).name;
63692
63945
  return checkedVersion(
63693
- await resolve13(backendKind === "opencode_serve" ? `${packageName}@1` : packageName, signal)
63946
+ await resolve14(backendKind === "opencode_serve" ? `${packageName}@1` : packageName, signal)
63694
63947
  );
63695
63948
  }
63696
63949
  function selection(root, backendKind, version2) {
@@ -65257,8 +65510,8 @@ async function collectStream(stream) {
65257
65510
  return import_node_buffer2.Buffer.concat(chunks);
65258
65511
  }
65259
65512
  function addArchiveEntry(archive, header, bytes) {
65260
- return new Promise((resolve13, reject) => {
65261
- archive.entry(header, bytes, (error61) => error61 ? reject(error61) : resolve13());
65513
+ return new Promise((resolve14, reject) => {
65514
+ archive.entry(header, bytes, (error61) => error61 ? reject(error61) : resolve14());
65262
65515
  });
65263
65516
  }
65264
65517
  async function decompressBounded(archiveBytes) {
@@ -65284,7 +65537,7 @@ async function extractTar(tarBytes, destination) {
65284
65537
  const extractor = (0, import_tar_stream.extract)();
65285
65538
  let fileCount = 0;
65286
65539
  let totalBytes = 0;
65287
- const completion = new Promise((resolve13, reject) => {
65540
+ const completion = new Promise((resolve14, reject) => {
65288
65541
  extractor.on("entry", (header, stream, next) => {
65289
65542
  void extractEntry(header, stream, destination, {
65290
65543
  addFile(size) {
@@ -65299,7 +65552,7 @@ async function extractTar(tarBytes, destination) {
65299
65552
  }
65300
65553
  }).then(next, (error61) => extractor.destroy(error61 instanceof Error ? error61 : new Error(String(error61))));
65301
65554
  });
65302
- extractor.once("finish", resolve13);
65555
+ extractor.once("finish", resolve14);
65303
65556
  extractor.once("error", reject);
65304
65557
  });
65305
65558
  import_node_stream.Readable.from(tarBytes).pipe(extractor);
@@ -65782,9 +66035,9 @@ async function syncOnce(env, local, onRecorded, signal) {
65782
66035
  return report2;
65783
66036
  }
65784
66037
  function aborted2(signal) {
65785
- return new Promise((resolve13) => {
65786
- if (signal.aborted) resolve13(null);
65787
- else signal.addEventListener("abort", () => resolve13(null), { once: true });
66038
+ return new Promise((resolve14) => {
66039
+ if (signal.aborted) resolve14(null);
66040
+ else signal.addEventListener("abort", () => resolve14(null), { once: true });
65788
66041
  });
65789
66042
  }
65790
66043
  function openMachineSkills(options) {
@@ -65873,11 +66126,11 @@ function openMachineSkills(options) {
65873
66126
  if ((await resolveSkillInvocations(layout, named, "exact")).kind === "resolved") return;
65874
66127
  }
65875
66128
  };
65876
- const recordedUntilResolved = (named, until) => new Promise((resolve13) => {
66129
+ const recordedUntilResolved = (named, until) => new Promise((resolve14) => {
65877
66130
  const done = () => {
65878
66131
  recordWatchers.delete(check3);
65879
66132
  until.removeEventListener("abort", done);
65880
- resolve13();
66133
+ resolve14();
65881
66134
  };
65882
66135
  const check3 = () => {
65883
66136
  void resolveSkillInvocations(layout, named, "exact").then((resolution) => {
@@ -65885,7 +66138,7 @@ function openMachineSkills(options) {
65885
66138
  });
65886
66139
  };
65887
66140
  if (until.aborted) {
65888
- resolve13();
66141
+ resolve14();
65889
66142
  return;
65890
66143
  }
65891
66144
  recordWatchers.add(check3);
@@ -66381,7 +66634,7 @@ async function openWorkspaces(options) {
66381
66634
 
66382
66635
  // src/cli/config.ts
66383
66636
  var import_node_os11 = require("os");
66384
- var import_node_path67 = require("path");
66637
+ var import_node_path69 = require("path");
66385
66638
  init_zod();
66386
66639
 
66387
66640
  // src/client/contract.ts
@@ -66799,8 +67052,8 @@ function nextOffsetOf(response) {
66799
67052
  async function pause(ms, signal) {
66800
67053
  const either = AbortSignal.any([signal, AbortSignal.timeout(ms)]);
66801
67054
  if (either.aborted) return;
66802
- await new Promise((resolve13) => {
66803
- either.addEventListener("abort", () => resolve13(), { once: true });
67055
+ await new Promise((resolve14) => {
67056
+ either.addEventListener("abort", () => resolve14(), { once: true });
66804
67057
  });
66805
67058
  }
66806
67059
  function jittered(backoff, failures) {
@@ -67109,9 +67362,9 @@ async function sendNativeHookSignal(discoveryPath, hookSignal, signal) {
67109
67362
 
67110
67363
  // src/sessions/index.ts
67111
67364
  var import_node_crypto31 = require("crypto");
67112
- var import_promises66 = require("fs/promises");
67365
+ var import_promises67 = require("fs/promises");
67113
67366
  var import_node_os10 = require("os");
67114
- var import_node_path66 = require("path");
67367
+ var import_node_path68 = require("path");
67115
67368
  init_runtime_v2();
67116
67369
 
67117
67370
  // src/holder/control-client.ts
@@ -67162,8 +67415,8 @@ function isReply(message2) {
67162
67415
  async function connectHolder(endpoint, token, onEvent) {
67163
67416
  const socket = (0, import_node_net2.connect)(endpoint);
67164
67417
  const pending = /* @__PURE__ */ new Map();
67165
- const closed = new Promise((resolve13) => socket.once("close", () => resolve13()));
67166
- const ready = new Promise((resolve13, reject) => {
67418
+ const closed = new Promise((resolve14) => socket.once("close", () => resolve14()));
67419
+ const ready = new Promise((resolve14, reject) => {
67167
67420
  socket.once("error", reject);
67168
67421
  socket.once(
67169
67422
  "close",
@@ -67171,7 +67424,7 @@ async function connectHolder(endpoint, token, onEvent) {
67171
67424
  );
67172
67425
  readMessages(socket, holderMessageSchema, {
67173
67426
  onMessage: (message2) => {
67174
- if (message2.type === "ready") resolve13(message2.pid);
67427
+ if (message2.type === "ready") resolve14(message2.pid);
67175
67428
  else if (isReply(message2)) {
67176
67429
  const id = message2.id;
67177
67430
  if (id === null) return;
@@ -67186,13 +67439,13 @@ async function connectHolder(endpoint, token, onEvent) {
67186
67439
  const pid = await ready;
67187
67440
  const request2 = (body) => {
67188
67441
  const id = (0, import_node_crypto26.randomUUID)();
67189
- return new Promise((resolve13, reject) => {
67442
+ return new Promise((resolve14, reject) => {
67190
67443
  const timer = AbortSignal.timeout(REQUEST_TIMEOUT_MS7);
67191
67444
  timer.addEventListener("abort", () => {
67192
67445
  pending.delete(id);
67193
67446
  reject(new RuntimeFault("io_failed", "Holder did not answer"));
67194
67447
  });
67195
- pending.set(id, resolve13);
67448
+ pending.set(id, resolve14);
67196
67449
  writeMessage(socket, { ...body, id });
67197
67450
  });
67198
67451
  };
@@ -67529,14 +67782,14 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [] }) {
67529
67782
  var import_node_crypto30 = require("crypto");
67530
67783
  var import_node_fs22 = require("fs");
67531
67784
  var import_node_net3 = require("net");
67532
- var import_node_path65 = require("path");
67785
+ var import_node_path67 = require("path");
67533
67786
  init_runtime_v2();
67534
67787
 
67535
67788
  // src/holder/admission.ts
67536
67789
  var import_node_fs19 = require("fs");
67537
- var import_promises60 = require("fs/promises");
67790
+ var import_promises61 = require("fs/promises");
67538
67791
  var import_node_os9 = require("os");
67539
- var import_node_path59 = require("path");
67792
+ var import_node_path61 = require("path");
67540
67793
  init_constants();
67541
67794
 
67542
67795
  // ../shared/dist/node/local-workspace.js
@@ -67620,18 +67873,12 @@ async function discoverRelocatedWorkspace(search) {
67620
67873
  }
67621
67874
 
67622
67875
  // src/holder/checkout-refresh.ts
67876
+ var import_node_path59 = require("path");
67877
+
67878
+ // src/holder/claim-once.ts
67623
67879
  var import_node_crypto28 = require("crypto");
67624
67880
  var import_promises58 = require("fs/promises");
67625
67881
  var import_node_path57 = require("path");
67626
- function short(sha) {
67627
- return sha.slice(0, 12);
67628
- }
67629
- function staleLine(path4, snapshot2, tip) {
67630
- const checkout = snapshot2 === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot2.branch} (commit ${short(snapshot2.head)})`;
67631
- const base = snapshot2 === void 0 ? "its upstream" : `origin/${snapshot2.base}`;
67632
- const remote = tip === void 0 ? "may be ahead" : `is ahead at ${short(tip)}`;
67633
- return `Note: ${path4} ${checkout}; ${base} ${remote}. Run \`git pull --ff-only\` there before relying on its files.`;
67634
- }
67635
67882
  async function claimOnce(dir, name) {
67636
67883
  try {
67637
67884
  await (0, import_promises58.mkdir)(dir, { recursive: true, mode: 448 });
@@ -67641,6 +67888,199 @@ async function claimOnce(dir, name) {
67641
67888
  return false;
67642
67889
  }
67643
67890
  }
67891
+ function claimFirstLease(freshnessDir, path4) {
67892
+ return claimOnce((0, import_node_path57.join)(freshnessDir, "leased"), (0, import_node_crypto28.createHash)("sha256").update(path4).digest("hex"));
67893
+ }
67894
+
67895
+ // src/holder/requested-checkout.ts
67896
+ var import_promises59 = require("fs/promises");
67897
+ var import_node_path58 = require("path");
67898
+ var REMOTE2 = "origin";
67899
+ var REASON_MAX_CHARS = 200;
67900
+ function firstLine3(text3) {
67901
+ return (text3.trim().split("\n")[0] ?? "").slice(0, REASON_MAX_CHARS);
67902
+ }
67903
+ function reasonOf(output2, command) {
67904
+ return firstLine3(output2.stderr) || `git ${command} exited ${output2.exitCode}`;
67905
+ }
67906
+ function noted(checkout, situation, reason, action) {
67907
+ return {
67908
+ kind: "noted",
67909
+ line: `Note: ${checkout.path} ${situation}: ${reason}. ${action} before relying on its files.`
67910
+ };
67911
+ }
67912
+ function notSwitched(checkout, current, reason) {
67913
+ const on2 = current ?? "a detached HEAD";
67914
+ return noted(
67915
+ checkout,
67916
+ `is on ${on2}, not ${checkout.branch}, the branch picked for this chat`,
67917
+ reason,
67918
+ `Switch it to ${checkout.branch}`
67919
+ );
67920
+ }
67921
+ async function clone2(checkout, deps, signal) {
67922
+ const parent = (0, import_node_path58.dirname)(checkout.path);
67923
+ await (0, import_promises59.mkdir)(parent, { recursive: true });
67924
+ await assertValidBranch(deps.git, parent, checkout.branch, signal);
67925
+ const output2 = await deps.git.run(
67926
+ {
67927
+ cwd: parent,
67928
+ args: [
67929
+ "clone",
67930
+ "--quiet",
67931
+ "--no-tags",
67932
+ "--depth=1",
67933
+ "--branch",
67934
+ checkout.branch,
67935
+ "--",
67936
+ checkout.repoUrl,
67937
+ checkout.path
67938
+ ],
67939
+ network: true
67940
+ },
67941
+ signal
67942
+ );
67943
+ if (output2.exitCode === 0) return { kind: "moved", how: "cloned" };
67944
+ return noted(
67945
+ checkout,
67946
+ `is missing, and cloning it on ${checkout.branch}, the branch picked for this chat, failed`,
67947
+ reasonOf(output2, "clone"),
67948
+ `Clone ${checkout.repoUrl} there`
67949
+ );
67950
+ }
67951
+ var SWITCHED = { kind: "moved", how: "switched" };
67952
+ function coversBranch(fetchConfig, branch) {
67953
+ return fetchConfig.split("\n").some(
67954
+ (refspec) => refspec === `+refs/heads/*:refs/remotes/${REMOTE2}/*` || refspec === `+refs/heads/${branch}:refs/remotes/${REMOTE2}/${branch}`
67955
+ );
67956
+ }
67957
+ async function fetchBranch(checkout, git, shallow, current) {
67958
+ const { branch } = checkout;
67959
+ const tracking = `refs/remotes/${REMOTE2}/${branch}`;
67960
+ const fetchConfig = await git(["config", "--get-all", `remote.${REMOTE2}.fetch`], {
67961
+ readOnly: true
67962
+ });
67963
+ if (!coversBranch(fetchConfig.stdout, branch)) {
67964
+ const added = await git(["remote", "set-branches", "--add", REMOTE2, branch]);
67965
+ if (added.exitCode !== 0) return notSwitched(checkout, current, reasonOf(added, "remote"));
67966
+ }
67967
+ const depth = shallow ? ["--depth=1"] : [];
67968
+ const fetched = await git(
67969
+ ["fetch", "--no-tags", "--quiet", ...depth, REMOTE2, `refs/heads/${branch}:${tracking}`],
67970
+ { network: true }
67971
+ );
67972
+ if (fetched.exitCode !== 0) return notSwitched(checkout, current, reasonOf(fetched, "fetch"));
67973
+ const tip = await git(["rev-parse", "--verify", tracking], { readOnly: true });
67974
+ if (tip.exitCode !== 0) return notSwitched(checkout, current, reasonOf(tip, "rev-parse"));
67975
+ return { kind: "fetched", tip: tip.stdout.trim() };
67976
+ }
67977
+ async function moveOnto(checkout, git, tip, current) {
67978
+ const { branch } = checkout;
67979
+ const local = await git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], {
67980
+ readOnly: true
67981
+ });
67982
+ if (local.exitCode !== 0) {
67983
+ const created = await git([
67984
+ "switch",
67985
+ "--quiet",
67986
+ "-c",
67987
+ branch,
67988
+ "--track",
67989
+ `${REMOTE2}/${branch}`
67990
+ ]);
67991
+ return created.exitCode === 0 ? SWITCHED : notSwitched(checkout, current, reasonOf(created, "switch"));
67992
+ }
67993
+ const localHead = local.stdout.trim();
67994
+ const ancestor = localHead === tip || (await git(["merge-base", "--is-ancestor", localHead, tip], { readOnly: true })).exitCode === 0;
67995
+ if (!ancestor) {
67996
+ return notSwitched(
67997
+ checkout,
67998
+ current,
67999
+ `its local ${branch} has diverged from ${REMOTE2}/${branch}`
68000
+ );
68001
+ }
68002
+ const switched = await git(["switch", "--quiet", branch]);
68003
+ if (switched.exitCode !== 0) return notSwitched(checkout, current, reasonOf(switched, "switch"));
68004
+ if (localHead === tip) return SWITCHED;
68005
+ const merged = await git(["merge", "--quiet", "--ff-only", tip]);
68006
+ return merged.exitCode === 0 ? SWITCHED : noted(
68007
+ checkout,
68008
+ `is on ${branch} but behind ${REMOTE2}/${branch}`,
68009
+ reasonOf(merged, "merge"),
68010
+ "Run `git pull --ff-only` there"
68011
+ );
68012
+ }
68013
+ async function switchTo(checkout, current, operationId, deps, signal) {
68014
+ var _stack = [];
68015
+ try {
68016
+ const cwd = checkout.path;
68017
+ const git = (args, invocation = {}) => deps.git.run({ cwd, args, ...invocation }, signal);
68018
+ await assertValidBranch(deps.git, cwd, checkout.branch, signal);
68019
+ const refs = await git(
68020
+ ["rev-parse", "--path-format=absolute", "--git-common-dir", "--is-shallow-repository"],
68021
+ { readOnly: true }
68022
+ );
68023
+ if (refs.exitCode !== 0) return notSwitched(checkout, current, reasonOf(refs, "rev-parse"));
68024
+ const [commonDir = "", shallow] = refs.stdout.trim().split("\n");
68025
+ const attempt2 = await deps.locks.tryExclusive(commonDir, operationId);
68026
+ if (attempt2.kind === "busy") {
68027
+ return notSwitched(checkout, current, "another git operation holds the checkout");
68028
+ }
68029
+ const _lock = __using(_stack, attempt2.lock, true);
68030
+ const now = await readCheckoutStatus(deps.git, cwd, signal);
68031
+ if (now === null || now.dirty) {
68032
+ return notSwitched(checkout, now?.branch ?? current, "it has uncommitted changes");
68033
+ }
68034
+ const fetched = await fetchBranch(checkout, git, shallow === "true", now.branch);
68035
+ if (fetched.kind !== "fetched") return fetched;
68036
+ const outcome2 = await moveOnto(checkout, git, fetched.tip, now.branch);
68037
+ const after = await readCheckoutStatus(deps.git, cwd, signal);
68038
+ if (after?.branch === checkout.branch) {
68039
+ await recordCheckoutKept(deps.dir, cwd, "requested_branch");
68040
+ }
68041
+ return outcome2;
68042
+ } catch (_) {
68043
+ var _error = _, _hasError = true;
68044
+ } finally {
68045
+ var _promise2 = __callDispose(_stack, _error, _hasError);
68046
+ _promise2 && await _promise2;
68047
+ }
68048
+ }
68049
+ async function applyRequestedCheckout(checkout, spec, deps, signal) {
68050
+ try {
68051
+ if (!await isCheckout(checkout.path)) return await clone2(checkout, deps, signal);
68052
+ const status = await readCheckoutStatus(deps.git, checkout.path, signal);
68053
+ if (status === null) return notSwitched(checkout, null, "git status failed");
68054
+ if (status.branch === checkout.branch) return { kind: "on_branch" };
68055
+ if (status.dirty) return notSwitched(checkout, status.branch, "it has uncommitted changes");
68056
+ if (!await claimFirstLease(deps.dir, checkout.path)) {
68057
+ return notSwitched(
68058
+ checkout,
68059
+ status.branch,
68060
+ "an earlier conversation on this machine already uses it"
68061
+ );
68062
+ }
68063
+ return await switchTo(checkout, status.branch, `checkout-${spec.runId}`, deps, signal);
68064
+ } catch (error61) {
68065
+ return noted(
68066
+ checkout,
68067
+ `could not be put on ${checkout.branch}, the branch picked for this chat`,
68068
+ firstLine3(error61 instanceof Error ? error61.message : String(error61)) || "unknown error",
68069
+ "Check it"
68070
+ );
68071
+ }
68072
+ }
68073
+
68074
+ // src/holder/checkout-refresh.ts
68075
+ function short(sha) {
68076
+ return sha.slice(0, 12);
68077
+ }
68078
+ function staleLine(path4, snapshot2, tip) {
68079
+ const checkout = snapshot2 === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot2.branch} (commit ${short(snapshot2.head)})`;
68080
+ const base = snapshot2 === void 0 ? "its upstream" : `origin/${snapshot2.base}`;
68081
+ const remote = tip === void 0 ? "may be ahead" : `is ahead at ${short(tip)}`;
68082
+ return `Note: ${path4} ${checkout}; ${base} ${remote}. Run \`git pull --ff-only\` there before relying on its files.`;
68083
+ }
67644
68084
  async function fastForward(freshness, operationId, deps, signal) {
67645
68085
  var _stack = [];
67646
68086
  try {
@@ -67665,10 +68105,7 @@ async function fastForward(freshness, operationId, deps, signal) {
67665
68105
  }
67666
68106
  }
67667
68107
  async function atFirstLease(freshness, spec, deps, signal) {
67668
- const first = await claimOnce(
67669
- (0, import_node_path57.join)(deps.dir, "leased"),
67670
- (0, import_node_crypto28.createHash)("sha256").update(freshness.path).digest("hex")
67671
- );
68108
+ const first = await claimFirstLease(deps.dir, freshness.path);
67672
68109
  switch (freshness.state) {
67673
68110
  case "current":
67674
68111
  case "kept":
@@ -67694,32 +68131,73 @@ async function checkoutsOf(spec, leaseTargets) {
67694
68131
  if (leaseTargets.length > 0 || spec.projectPath === void 0) return [...leaseTargets];
67695
68132
  return checkoutsUnder(spec.projectPath);
67696
68133
  }
67697
- function createCheckoutRefresh(deps) {
67698
- return async (spec, leaseTargets, signal) => {
67699
- if (spec.providerSessionId !== void 0) return void 0;
67700
- if (!await claimOnce((0, import_node_path57.join)(deps.dir, "conversations"), spec.conversationId)) return void 0;
67701
- const lines2 = [];
67702
- for (const target of await checkoutsOf(spec, leaseTargets)) {
67703
- const freshness = await readCheckoutFreshness(deps.dir, target);
67704
- if (freshness === null) continue;
67705
- const outcome2 = await atFirstLease(freshness, spec, deps, signal).catch(
67706
- () => "noted"
67707
- );
67708
- if (outcome2 === "noted") lines2.push(lineFor(freshness));
67709
- deps.log.info("workspace.refresh", {
68134
+ function requestedCheckoutsOf(spec, log) {
68135
+ const roots = spec.approvedWorkspacePaths ?? [];
68136
+ return (spec.requestedCheckouts ?? []).filter((checkout) => {
68137
+ const approved = roots.some((root) => isWithin(root, checkout.path, process.platform));
68138
+ if (!approved) {
68139
+ log.warn("workspace.requested_checkout_outside_workspace", {
67710
68140
  runId: spec.runId,
67711
- path: freshness.path,
67712
- state: freshness.state,
67713
- outcome: outcome2
68141
+ path: checkout.path
67714
68142
  });
67715
68143
  }
68144
+ return approved;
68145
+ });
68146
+ }
68147
+ async function applyRequestedCheckouts(spec, deps, signal) {
68148
+ const settled2 = /* @__PURE__ */ new Set();
68149
+ const lines2 = [];
68150
+ for (const checkout of requestedCheckoutsOf(spec, deps.log)) {
68151
+ const outcome2 = await applyRequestedCheckout(checkout, spec, deps, signal);
68152
+ deps.log.info("workspace.requested_checkout", {
68153
+ runId: spec.runId,
68154
+ path: checkout.path,
68155
+ branch: checkout.branch,
68156
+ outcome: outcome2.kind,
68157
+ ...outcome2.kind === "moved" ? { how: outcome2.how } : {}
68158
+ });
68159
+ if (outcome2.kind === "on_branch") continue;
68160
+ settled2.add((0, import_node_path59.resolve)(checkout.path));
68161
+ if (outcome2.kind === "noted") lines2.push(outcome2.line);
68162
+ }
68163
+ return { settled: settled2, lines: lines2 };
68164
+ }
68165
+ async function refreshSnapshotCheckouts(spec, targets, settled2, deps, signal) {
68166
+ const lines2 = [];
68167
+ for (const target of targets) {
68168
+ if (settled2.has((0, import_node_path59.resolve)(target))) continue;
68169
+ const freshness = await readCheckoutFreshness(deps.dir, target);
68170
+ if (freshness === null) continue;
68171
+ const outcome2 = await atFirstLease(freshness, spec, deps, signal).catch(
68172
+ () => "noted"
68173
+ );
68174
+ if (outcome2 === "noted") lines2.push(lineFor(freshness));
68175
+ deps.log.info("workspace.refresh", {
68176
+ runId: spec.runId,
68177
+ path: freshness.path,
68178
+ state: freshness.state,
68179
+ outcome: outcome2
68180
+ });
68181
+ }
68182
+ return lines2;
68183
+ }
68184
+ function createCheckoutRefresh(deps) {
68185
+ return async (spec, leaseTargets, signal) => {
68186
+ if (spec.providerSessionId !== void 0) return void 0;
68187
+ if (!await claimOnce((0, import_node_path59.join)(deps.dir, "conversations"), spec.conversationId)) return void 0;
68188
+ const requested = await applyRequestedCheckouts(spec, deps, signal);
68189
+ const targets = await checkoutsOf(spec, leaseTargets);
68190
+ const lines2 = [
68191
+ ...requested.lines,
68192
+ ...await refreshSnapshotCheckouts(spec, targets, requested.settled, deps, signal)
68193
+ ];
67716
68194
  return lines2.length === 0 ? void 0 : lines2.join("\n");
67717
68195
  };
67718
68196
  }
67719
68197
 
67720
68198
  // src/holder/lease.ts
67721
- var import_promises59 = require("fs/promises");
67722
- var import_node_path58 = require("path");
68199
+ var import_promises60 = require("fs/promises");
68200
+ var import_node_path60 = require("path");
67723
68201
  var LEASE_CHECK_EVERY_MS = 5e3;
67724
68202
  var MAX_TRANSIENT_FAILURES = 3;
67725
68203
  var BACKOFF_BASE_MS = 1e3;
@@ -67733,8 +68211,8 @@ function identityFailure(code, workspacePath) {
67733
68211
  return { code, problemCode: "app.workspace.missing", message: MESSAGES[code], workspacePath };
67734
68212
  }
67735
68213
  async function fileIdentity(path4) {
67736
- const canonical = await (0, import_promises59.realpath)(path4);
67737
- const info = await (0, import_promises59.stat)(canonical, { bigint: true });
68214
+ const canonical = await (0, import_promises60.realpath)(path4);
68215
+ const info = await (0, import_promises60.stat)(canonical, { bigint: true });
67738
68216
  return `${canonical}:${info.dev}:${info.ino}`;
67739
68217
  }
67740
68218
  async function snapshot(git, path4, signal) {
@@ -67753,7 +68231,7 @@ async function snapshot(git, path4, signal) {
67753
68231
  workspace: await fileIdentity(path4),
67754
68232
  repository: await fileIdentity(commonDir),
67755
68233
  worktree: await fileIdentity(gitDir),
67756
- commonDir: await (0, import_promises59.realpath)(commonDir)
68234
+ commonDir: await (0, import_promises60.realpath)(commonDir)
67757
68235
  };
67758
68236
  } catch {
67759
68237
  return null;
@@ -67766,7 +68244,7 @@ async function gitValue(git, path4, args, signal) {
67766
68244
  }
67767
68245
  async function pathExists(path4) {
67768
68246
  try {
67769
- await (0, import_promises59.stat)(path4);
68247
+ await (0, import_promises60.stat)(path4);
67770
68248
  return true;
67771
68249
  } catch (error61) {
67772
68250
  return errnoCode(error61) !== "ENOENT" && errnoCode(error61) !== "ENOTDIR";
@@ -67775,19 +68253,19 @@ async function pathExists(path4) {
67775
68253
  async function hasGitMarker(path4) {
67776
68254
  let directory;
67777
68255
  try {
67778
- directory = await (0, import_promises59.realpath)(path4);
68256
+ directory = await (0, import_promises60.realpath)(path4);
67779
68257
  } catch {
67780
68258
  return true;
67781
68259
  }
67782
68260
  for (; ; ) {
67783
68261
  try {
67784
- await (0, import_promises59.stat)((0, import_node_path58.join)(directory, ".git"));
68262
+ await (0, import_promises60.stat)((0, import_node_path60.join)(directory, ".git"));
67785
68263
  return true;
67786
68264
  } catch (error61) {
67787
68265
  const code = errnoCode(error61);
67788
68266
  if (code !== "ENOENT" && code !== "ENOTDIR") return true;
67789
68267
  }
67790
- const parent = (0, import_node_path58.dirname)(directory);
68268
+ const parent = (0, import_node_path60.dirname)(directory);
67791
68269
  if (parent === directory) return false;
67792
68270
  directory = parent;
67793
68271
  }
@@ -67951,7 +68429,7 @@ function volumeRoot(path4) {
67951
68429
  }
67952
68430
  async function exists4(path4) {
67953
68431
  try {
67954
- await (0, import_promises60.stat)(path4);
68432
+ await (0, import_promises61.stat)(path4);
67955
68433
  return true;
67956
68434
  } catch {
67957
68435
  return false;
@@ -67959,10 +68437,10 @@ async function exists4(path4) {
67959
68437
  }
67960
68438
  async function inspectReadiness(path4) {
67961
68439
  try {
67962
- if (!(await (0, import_promises60.stat)(path4)).isDirectory()) {
68440
+ if (!(await (0, import_promises61.stat)(path4)).isDirectory()) {
67963
68441
  return { ready: false, missing: true, message: MESSAGES2.missing };
67964
68442
  }
67965
- await (0, import_promises60.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
68443
+ await (0, import_promises61.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
67966
68444
  return { ready: true };
67967
68445
  } catch (error61) {
67968
68446
  const code = errnoCode(error61) ?? "";
@@ -68040,8 +68518,8 @@ async function admitDefaultWorkspace(spec, context, skills) {
68040
68518
  const { env } = context;
68041
68519
  const path4 = resolveAlanDefaultWorkspacePath(env.HOME || env.USERPROFILE || (0, import_node_os9.homedir)());
68042
68520
  try {
68043
- await (0, import_promises60.mkdir)(path4, { recursive: true, mode: 448 });
68044
- await (0, import_promises60.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
68521
+ await (0, import_promises61.mkdir)(path4, { recursive: true, mode: 448 });
68522
+ await (0, import_promises61.access)(path4, import_node_fs19.constants.R_OK | import_node_fs19.constants.W_OK | import_node_fs19.constants.X_OK);
68045
68523
  return {
68046
68524
  kind: "admitted",
68047
68525
  spec: { ...spec, projectPath: path4 },
@@ -68114,10 +68592,12 @@ async function admitRun(spec, context, signal) {
68114
68592
  };
68115
68593
  }
68116
68594
  var PROBE_TIMEOUT_MS2 = 5e3;
68595
+ var CHECKOUT_LOCAL_TIMEOUT_MS = 6e4;
68596
+ var CHECKOUT_NETWORK_TIMEOUT_MS = 12e4;
68117
68597
  function createHolderWorkspace(machine, clock, log) {
68118
68598
  const platform3 = machine.platform ?? process.platform;
68119
68599
  const git = createGitRunner({ env: machine.env, platform: platform3, localTimeoutMs: PROBE_TIMEOUT_MS2 });
68120
- const locks = openRepositoryLocks({ dir: (0, import_node_path59.join)(machine.stateDir, "locks"), clock, platform: platform3 });
68600
+ const locks = openRepositoryLocks({ dir: (0, import_node_path61.join)(machine.stateDir, "locks"), clock, platform: platform3 });
68121
68601
  return {
68122
68602
  admission: {
68123
68603
  env: machine.env,
@@ -68129,7 +68609,7 @@ function createHolderWorkspace(machine, clock, log) {
68129
68609
  ),
68130
68610
  approvedRoots: async () => {
68131
68611
  const approved = await openApprovedPaths({
68132
- file: (0, import_node_path59.join)(machine.stateDir, "workspaces.json"),
68612
+ file: (0, import_node_path61.join)(machine.stateDir, "workspaces.json"),
68133
68613
  log,
68134
68614
  platform: platform3
68135
68615
  });
@@ -68139,10 +68619,15 @@ function createHolderWorkspace(machine, clock, log) {
68139
68619
  lease: { git, locks, clock, log, platform: platform3 },
68140
68620
  ...machine.refreshesFirstCheckout === true ? {
68141
68621
  refreshFirstCheckout: createCheckoutRefresh({
68142
- git,
68622
+ git: createGitRunner({
68623
+ env: machine.env,
68624
+ platform: platform3,
68625
+ localTimeoutMs: CHECKOUT_LOCAL_TIMEOUT_MS,
68626
+ networkTimeoutMs: CHECKOUT_NETWORK_TIMEOUT_MS
68627
+ }),
68143
68628
  locks,
68144
68629
  log,
68145
- dir: (0, import_node_path59.join)(machine.stateDir, "checkout-freshness")
68630
+ dir: (0, import_node_path61.join)(machine.stateDir, "checkout-freshness")
68146
68631
  })
68147
68632
  } : {}
68148
68633
  };
@@ -68170,7 +68655,7 @@ async function respondToTurn(runningRunId, gate, driver, request2) {
68170
68655
  }
68171
68656
 
68172
68657
  // src/holder/session-facts.ts
68173
- var import_promises61 = require("fs/promises");
68658
+ var import_promises62 = require("fs/promises");
68174
68659
  var CLI_RSS_CACHE_MS = 1e4;
68175
68660
  var LOGIN_PROBLEM_PREFIX = "cli.auth.";
68176
68661
  function isLoginFailure(result) {
@@ -68196,8 +68681,8 @@ function createSessionFacts(options) {
68196
68681
  const path4 = await resolveCommandOnPath(command, env, platform3);
68197
68682
  if (path4 === null) return null;
68198
68683
  try {
68199
- const real = await (0, import_promises61.realpath)(path4);
68200
- const info = await (0, import_promises61.stat)(real);
68684
+ const real = await (0, import_promises62.realpath)(path4);
68685
+ const info = await (0, import_promises62.stat)(real);
68201
68686
  return { command, key: `${real}:${info.ino}:${info.size}:${info.mtimeMs}` };
68202
68687
  } catch {
68203
68688
  return null;
@@ -68284,12 +68769,12 @@ function createSessionFacts(options) {
68284
68769
  init_acp2();
68285
68770
 
68286
68771
  // src/run-log/archive.ts
68287
- var import_promises62 = require("fs/promises");
68288
- var import_node_path60 = require("path");
68772
+ var import_promises63 = require("fs/promises");
68773
+ var import_node_path62 = require("path");
68289
68774
  init_runtime_v2();
68290
68775
  async function openRunArchive(runsDir) {
68291
- const path4 = (0, import_node_path60.join)((0, import_node_path60.dirname)(runsDir), "archived-runs.txt");
68292
- const text3 = await (0, import_promises62.readFile)(path4, "utf8").catch((error61) => {
68776
+ const path4 = (0, import_node_path62.join)((0, import_node_path62.dirname)(runsDir), "archived-runs.txt");
68777
+ const text3 = await (0, import_promises63.readFile)(path4, "utf8").catch((error61) => {
68293
68778
  if (errnoCode(error61) === "ENOENT") return "";
68294
68779
  throw error61;
68295
68780
  });
@@ -68303,7 +68788,7 @@ async function openRunArchive(runsDir) {
68303
68788
  add: async (runIds) => {
68304
68789
  const added = runIds.filter((runId) => !archived.has(runId));
68305
68790
  if (added.length === 0) return;
68306
- await (0, import_promises62.appendFile)(path4, `
68791
+ await (0, import_promises63.appendFile)(path4, `
68307
68792
  ${added.join("\n")}
68308
68793
  `, { mode: 384 });
68309
68794
  for (const runId of added) archived.add(runId);
@@ -68314,11 +68799,11 @@ ${added.join("\n")}
68314
68799
  // src/run-log/complete.ts
68315
68800
  var import_node_crypto29 = require("crypto");
68316
68801
  var import_node_fs20 = require("fs");
68317
- var import_node_path62 = require("path");
68802
+ var import_node_path64 = require("path");
68318
68803
 
68319
68804
  // src/run-log/directory.ts
68320
- var import_promises63 = require("fs/promises");
68321
- var import_node_path61 = require("path");
68805
+ var import_promises64 = require("fs/promises");
68806
+ var import_node_path63 = require("path");
68322
68807
  init_runtime_v2();
68323
68808
  init_zod();
68324
68809
  var runMetaSchema = external_exports.object({
@@ -68344,17 +68829,17 @@ async function readRunMeta(path4) {
68344
68829
  return read.kind === "ok" ? read.value : null;
68345
68830
  }
68346
68831
  function runDirectory(runsDir, runId) {
68347
- const dir = (0, import_node_path61.join)(runsDir, runId);
68832
+ const dir = (0, import_node_path63.join)(runsDir, runId);
68348
68833
  return {
68349
68834
  dir,
68350
- log: (0, import_node_path61.join)(dir, "log.jsonl"),
68351
- upload: (0, import_node_path61.join)(dir, "upload.json"),
68352
- meta: (0, import_node_path61.join)(dir, "run.json")
68835
+ log: (0, import_node_path63.join)(dir, "log.jsonl"),
68836
+ upload: (0, import_node_path63.join)(dir, "upload.json"),
68837
+ meta: (0, import_node_path63.join)(dir, "run.json")
68353
68838
  };
68354
68839
  }
68355
68840
  async function isRunClaimed(runsDir, runId) {
68356
68841
  try {
68357
- return (await (0, import_promises63.stat)(runDirectory(runsDir, runId).log)).size > 0;
68842
+ return (await (0, import_promises64.stat)(runDirectory(runsDir, runId).log)).size > 0;
68358
68843
  } catch (error61) {
68359
68844
  if (errnoCode(error61) === "ENOENT") return false;
68360
68845
  throw error61;
@@ -68363,7 +68848,7 @@ async function isRunClaimed(runsDir, runId) {
68363
68848
 
68364
68849
  // src/run-log/complete.ts
68365
68850
  function writeLogFile(path4, dir, text3) {
68366
- const temp = (0, import_node_path62.join)(dir, `.log.${(0, import_node_crypto29.randomUUID)()}.tmp`);
68851
+ const temp = (0, import_node_path64.join)(dir, `.log.${(0, import_node_crypto29.randomUUID)()}.tmp`);
68367
68852
  const fd = (0, import_node_fs20.openSync)(temp, "wx", 384);
68368
68853
  try {
68369
68854
  (0, import_node_fs20.writeSync)(fd, text3);
@@ -68392,8 +68877,8 @@ async function writeCompleteRunLog(runsDir, meta3, records) {
68392
68877
  }
68393
68878
 
68394
68879
  // src/run-log/conversation-index.ts
68395
- var import_promises64 = require("fs/promises");
68396
- var import_node_path63 = require("path");
68880
+ var import_promises65 = require("fs/promises");
68881
+ var import_node_path65 = require("path");
68397
68882
  init_runtime_v2();
68398
68883
  init_zod();
68399
68884
  var ORDINALS_PER_SHARD = 1e3;
@@ -68410,13 +68895,13 @@ var coverageSchema = external_exports.object({
68410
68895
  nextExpectedOrdinal: external_exports.number().int().positive()
68411
68896
  });
68412
68897
  function conversationsDirectory(runsDir) {
68413
- return (0, import_node_path63.join)((0, import_node_path63.dirname)(runsDir), "conversations");
68898
+ return (0, import_node_path65.join)((0, import_node_path65.dirname)(runsDir), "conversations");
68414
68899
  }
68415
68900
  function indexDirectory(runsDir, conversationId) {
68416
- return (0, import_node_path63.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
68901
+ return (0, import_node_path65.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
68417
68902
  }
68418
68903
  function shardPath(runsDir, conversationId, ordinal) {
68419
- return (0, import_node_path63.join)(
68904
+ return (0, import_node_path65.join)(
68420
68905
  indexDirectory(runsDir, conversationId),
68421
68906
  `${Math.floor(ordinal / ORDINALS_PER_SHARD)}.jsonl`
68422
68907
  );
@@ -68425,10 +68910,10 @@ async function indexConversationRun(runsDir, conversationId, ordinal, assistantO
68425
68910
  const nextOrdinal = assistantOrdinal + 1;
68426
68911
  if (nextOrdinal <= ordinal) throw new Error("Assistant order must follow the prompt");
68427
68912
  const path4 = shardPath(runsDir, conversationId, ordinal);
68428
- await (0, import_promises64.mkdir)((0, import_node_path63.dirname)(path4), { recursive: true, mode: 448 });
68429
- await (0, import_promises64.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
68913
+ await (0, import_promises65.mkdir)((0, import_node_path65.dirname)(path4), { recursive: true, mode: 448 });
68914
+ await (0, import_promises65.appendFile)(path4, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
68430
68915
  `, { mode: 384 });
68431
- const coveragePath = (0, import_node_path63.join)((0, import_node_path63.dirname)((0, import_node_path63.dirname)(path4)), "coverage.json");
68916
+ const coveragePath = (0, import_node_path65.join)((0, import_node_path65.dirname)((0, import_node_path65.dirname)(path4)), "coverage.json");
68432
68917
  const coverage = await readJsonFile(coveragePath, coverageSchema);
68433
68918
  const current = coverage.kind === "ok" ? coverage.value : null;
68434
68919
  const next = nextCoverage(current, ordinal, nextOrdinal);
@@ -68443,13 +68928,13 @@ function nextCoverage(current, ordinal, nextOrdinal) {
68443
68928
  return null;
68444
68929
  }
68445
68930
  async function readConversationIndexCoverage(runsDir, conversationId) {
68446
- const path4 = (0, import_node_path63.join)((0, import_node_path63.dirname)(indexDirectory(runsDir, conversationId)), "coverage.json");
68931
+ const path4 = (0, import_node_path65.join)((0, import_node_path65.dirname)(indexDirectory(runsDir, conversationId)), "coverage.json");
68447
68932
  const result = await readJsonFile(path4, coverageSchema);
68448
68933
  return result.kind === "ok" ? result.value : null;
68449
68934
  }
68450
68935
  async function readConversationRunIndex(runsDir, conversationId, before, limit) {
68451
68936
  const directory = indexDirectory(runsDir, conversationId);
68452
- const names = await (0, import_promises64.readdir)(directory).catch((error61) => {
68937
+ const names = await (0, import_promises65.readdir)(directory).catch((error61) => {
68453
68938
  if (error61.code === "ENOENT") return [];
68454
68939
  throw error61;
68455
68940
  });
@@ -68458,7 +68943,7 @@ async function readConversationRunIndex(runsDir, conversationId, before, limit)
68458
68943
  ).sort((left, right) => right - left);
68459
68944
  const selected = [];
68460
68945
  for (const shard of shards) {
68461
- const text3 = await (0, import_promises64.readFile)((0, import_node_path63.join)(directory, `${shard}.jsonl`), "utf8");
68946
+ const text3 = await (0, import_promises65.readFile)((0, import_node_path65.join)(directory, `${shard}.jsonl`), "utf8");
68462
68947
  const records = text3.split("\n").flatMap((line) => {
68463
68948
  if (!line) return [];
68464
68949
  const parsed = indexRecordSchema.parse(JSON.parse(line));
@@ -68483,7 +68968,7 @@ async function readIndexableRun(runsDir, name) {
68483
68968
  return { conversationId: meta3.conversationId, ordinal, assistantOrdinal, runId: runId.data };
68484
68969
  }
68485
68970
  async function readIndexableRuns(runsDir) {
68486
- const names = await (0, import_promises64.readdir)(runsDir).catch(() => []);
68971
+ const names = await (0, import_promises65.readdir)(runsDir).catch(() => []);
68487
68972
  const byConversation = /* @__PURE__ */ new Map();
68488
68973
  let next = 0;
68489
68974
  const worker = async () => {
@@ -68513,21 +68998,21 @@ async function writeConversationIndex(directory, runs) {
68513
68998
  else lines2.push(line);
68514
68999
  coverage = nextCoverage(coverage, run2.ordinal, nextOrdinal) ?? coverage;
68515
69000
  }
68516
- await (0, import_promises64.mkdir)((0, import_node_path63.join)(directory, "turn-index"), { recursive: true, mode: 448 });
69001
+ await (0, import_promises65.mkdir)((0, import_node_path65.join)(directory, "turn-index"), { recursive: true, mode: 448 });
68517
69002
  for (const [shard, lines2] of shards) {
68518
- await (0, import_promises64.writeFile)((0, import_node_path63.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
69003
+ await (0, import_promises65.writeFile)((0, import_node_path65.join)(directory, "turn-index", `${shard}.jsonl`), `${lines2.join("\n")}
68519
69004
  `, {
68520
69005
  mode: 384
68521
69006
  });
68522
69007
  }
68523
- await (0, import_promises64.writeFile)((0, import_node_path63.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
69008
+ await (0, import_promises65.writeFile)((0, import_node_path65.join)(directory, "coverage.json"), `${JSON.stringify(coverage)}
68524
69009
  `, {
68525
69010
  mode: 384
68526
69011
  });
68527
69012
  }
68528
69013
  async function rebuildConversationIndexes(runsDir) {
68529
69014
  const root = conversationsDirectory(runsDir);
68530
- const exists6 = await (0, import_promises64.stat)(root).then(
69015
+ const exists6 = await (0, import_promises65.stat)(root).then(
68531
69016
  () => true,
68532
69017
  (error61) => {
68533
69018
  if (errnoCode(error61) === "ENOENT") return false;
@@ -68536,18 +69021,18 @@ async function rebuildConversationIndexes(runsDir) {
68536
69021
  );
68537
69022
  if (exists6) return 0;
68538
69023
  const building = `${root}.rebuilding`;
68539
- await (0, import_promises64.rm)(building, { recursive: true, force: true });
68540
- await (0, import_promises64.mkdir)(building, { recursive: true, mode: 448 });
69024
+ await (0, import_promises65.rm)(building, { recursive: true, force: true });
69025
+ await (0, import_promises65.mkdir)(building, { recursive: true, mode: 448 });
68541
69026
  const byConversation = await readIndexableRuns(runsDir);
68542
69027
  for (const [conversationId, runs] of byConversation) {
68543
- await writeConversationIndex((0, import_node_path63.join)(building, conversationId), runs);
69028
+ await writeConversationIndex((0, import_node_path65.join)(building, conversationId), runs);
68544
69029
  }
68545
- await (0, import_promises64.rename)(building, root);
69030
+ await (0, import_promises65.rename)(building, root);
68546
69031
  return byConversation.size;
68547
69032
  }
68548
69033
 
68549
69034
  // src/run-log/reader.ts
68550
- var import_promises65 = require("fs/promises");
69035
+ var import_promises66 = require("fs/promises");
68551
69036
  init_runtime_v2();
68552
69037
 
68553
69038
  // src/run-log/tail.ts
@@ -68570,7 +69055,7 @@ function firstRecordLength(bytes) {
68570
69055
  return bytes.indexOf(RUN_LOG_RECORD_SEPARATOR) + 1;
68571
69056
  }
68572
69057
  async function openRunLogReader(path4) {
68573
- const handle = await (0, import_promises65.open)(path4, "r");
69058
+ const handle = await (0, import_promises66.open)(path4, "r");
68574
69059
  const readAt = async (position, length) => {
68575
69060
  const buffer = Buffer.alloc(length);
68576
69061
  const { bytesRead } = await handle.read(buffer, 0, length, position);
@@ -68604,7 +69089,7 @@ async function openRunLogReader(path4) {
68604
69089
  };
68605
69090
  }
68606
69091
  async function readLastRecord(path4) {
68607
- const handle = await (0, import_promises65.open)(path4, "r").catch(() => null);
69092
+ const handle = await (0, import_promises66.open)(path4, "r").catch(() => null);
68608
69093
  if (handle === null) return null;
68609
69094
  try {
68610
69095
  const { size } = await handle.stat();
@@ -68638,7 +69123,7 @@ var decoder = new TextDecoder();
68638
69123
 
68639
69124
  // src/run-log/writer.ts
68640
69125
  var import_node_fs21 = require("fs");
68641
- var import_node_path64 = require("path");
69126
+ var import_node_path66 = require("path");
68642
69127
  init_runtime_v2();
68643
69128
  function lastSeq(fd, size) {
68644
69129
  for (const length of tailWindows(size)) {
@@ -68654,7 +69139,7 @@ function lastSeq(fd, size) {
68654
69139
  throw new RuntimeFault("record_too_large", "Run log tail record is larger than any record");
68655
69140
  }
68656
69141
  function openRunLog(path4, clock) {
68657
- (0, import_node_fs21.mkdirSync)((0, import_node_path64.dirname)(path4), { recursive: true, mode: 448 });
69142
+ (0, import_node_fs21.mkdirSync)((0, import_node_path66.dirname)(path4), { recursive: true, mode: 448 });
68658
69143
  const fd = (0, import_node_fs21.openSync)(path4, "a+", 384);
68659
69144
  let size = (0, import_node_fs21.fstatSync)(fd).size;
68660
69145
  let seq = lastSeq(fd, size);
@@ -68990,7 +69475,7 @@ async function runHolder({
68990
69475
  try {
68991
69476
  const identity = await readProcessIdentity(process.pid);
68992
69477
  if (identity === null) throw new RuntimeFault("internal", "Cannot read own process identity");
68993
- const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path65.dirname)(launch.statusPath)), clock, log));
69478
+ const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path67.dirname)(launch.statusPath)), clock, log));
68994
69479
  const holder = {
68995
69480
  state: "idle",
68996
69481
  runId: null,
@@ -69186,16 +69671,16 @@ async function runHolder({
69186
69671
  client.on("error", () => holder.clients.delete(client));
69187
69672
  });
69188
69673
  removeStaleEndpoint(launch.endpoint);
69189
- await new Promise((resolve13, reject) => {
69674
+ await new Promise((resolve14, reject) => {
69190
69675
  server.once("error", reject);
69191
- server.listen(launch.endpoint, () => resolve13());
69676
+ server.listen(launch.endpoint, () => resolve14());
69192
69677
  });
69193
69678
  await writeStatus();
69194
69679
  log.info("holder.ready", { conversationId: launch.conversationId, pid: identity.pid });
69195
- await new Promise((resolve13) => exit.signal.addEventListener("abort", () => resolve13()));
69680
+ await new Promise((resolve14) => exit.signal.addEventListener("abort", () => resolve14()));
69196
69681
  await driver.suspend?.().catch((error61) => log.warn("holder.driver_suspend_failed", { error: error61 }));
69197
69682
  for (const client of holder.clients) client.end();
69198
- await new Promise((resolve13) => server.close(() => resolve13()));
69683
+ await new Promise((resolve14) => server.close(() => resolve14()));
69199
69684
  (0, import_node_fs22.rmSync)(launch.statusPath, { force: true });
69200
69685
  log.info("holder.suspended", { conversationId: launch.conversationId });
69201
69686
  } catch (_) {
@@ -69284,7 +69769,7 @@ var DEFAULT_MAX_ACTIVE_RUNS = 32;
69284
69769
  var HOLDER_BUSY = "busy";
69285
69770
  async function listIds(dir, schema) {
69286
69771
  const ids = [];
69287
- for (const name of await (0, import_promises66.readdir)(dir).catch(() => [])) {
69772
+ for (const name of await (0, import_promises67.readdir)(dir).catch(() => [])) {
69288
69773
  const parsed = schema.safeParse(name);
69289
69774
  if (parsed.success) ids.push(parsed.data);
69290
69775
  }
@@ -69298,14 +69783,14 @@ function holderIdentity(status) {
69298
69783
  return command === void 0 ? { pid, startedAt } : { pid, startedAt, command };
69299
69784
  }
69300
69785
  function sessionFiles(paths, conversationId) {
69301
- const dir = (0, import_node_path66.join)(paths.sessions, conversationId);
69302
- return { dir, launch: (0, import_node_path66.join)(dir, "launch.json"), status: (0, import_node_path66.join)(dir, "holder.json") };
69786
+ const dir = (0, import_node_path68.join)(paths.sessions, conversationId);
69787
+ return { dir, launch: (0, import_node_path68.join)(dir, "launch.json"), status: (0, import_node_path68.join)(dir, "holder.json") };
69303
69788
  }
69304
69789
  async function removeHolderFiles(files) {
69305
69790
  for (const path4 of [files.launch, files.status, engineRecordsPath(files.dir)]) {
69306
- await (0, import_promises66.rm)(path4, { force: true });
69791
+ await (0, import_promises67.rm)(path4, { force: true });
69307
69792
  }
69308
- await (0, import_promises66.rmdir)(files.dir).catch((error61) => {
69793
+ await (0, import_promises67.rmdir)(files.dir).catch((error61) => {
69309
69794
  if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(errnoCode(error61) ?? "")) throw error61;
69310
69795
  });
69311
69796
  }
@@ -69495,7 +69980,7 @@ async function openSessions(deps) {
69495
69980
  const meta3 = await readRunMeta(dir.meta);
69496
69981
  const last = await readLastRecord(dir.log);
69497
69982
  if (meta3 === null || last === null) return null;
69498
- const logged = await (0, import_promises66.stat)(dir.log).catch((error61) => {
69983
+ const logged = await (0, import_promises67.stat)(dir.log).catch((error61) => {
69499
69984
  if (errnoCode(error61) === "ENOENT") return null;
69500
69985
  throw error61;
69501
69986
  });
@@ -69807,7 +70292,7 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
69807
70292
  providerProbes: ALAN_RUNTIME_PROVIDER_PROBES === "on",
69808
70293
  providerToolchain: ALAN_RUNTIME_PROVIDER_NODE !== void 0 && ALAN_RUNTIME_PROVIDER_NPM_CLI !== void 0 ? { node: ALAN_RUNTIME_PROVIDER_NODE, npmCli: ALAN_RUNTIME_PROVIDER_NPM_CLI } : null,
69809
70294
  home,
69810
- configHome: XDG_CONFIG_HOME ?? (0, import_node_path67.join)(home, ".config"),
70295
+ configHome: XDG_CONFIG_HOME ?? (0, import_node_path69.join)(home, ".config"),
69811
70296
  codexHome: resolveCodexHome(CODEX_HOME, home),
69812
70297
  ...githubProxyConfig({ ALAN_RUNTIME_GITHUB_PROXY, XDG_CONFIG_HOME, GH_CONFIG_DIR }, home),
69813
70298
  gitGatewayUrl: ALAN_RUNTIME_GIT_GATEWAY_URL ?? null,
@@ -69817,13 +70302,13 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
69817
70302
  };
69818
70303
  }
69819
70304
  function resolveCodexHome(configuredHome, home) {
69820
- return configuredHome ?? (0, import_node_path67.join)(home, ".codex");
70305
+ return configuredHome ?? (0, import_node_path69.join)(home, ".codex");
69821
70306
  }
69822
70307
  function githubProxyConfig(env, home) {
69823
- const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path67.join)(home, ".config");
70308
+ const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path69.join)(home, ".config");
69824
70309
  return {
69825
70310
  githubProxy: env.ALAN_RUNTIME_GITHUB_PROXY === "on",
69826
- ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path67.join)(configHome, "gh")
70311
+ ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path69.join)(configHome, "gh")
69827
70312
  };
69828
70313
  }
69829
70314
  function serviceEnvironment2(env, profile) {
@@ -69881,9 +70366,9 @@ function takeEnrollmentCodeFromEnv(env = process.env) {
69881
70366
  }
69882
70367
 
69883
70368
  // src/cli/context.ts
69884
- var import_promises67 = require("fs/promises");
70369
+ var import_promises68 = require("fs/promises");
69885
70370
  var import_node_os12 = require("os");
69886
- var import_node_path68 = require("path");
70371
+ var import_node_path70 = require("path");
69887
70372
  var DESKTOP_BUNDLE_IDS = {
69888
70373
  production: ["com.alan-ai.desktop"],
69889
70374
  staging: ["com.alan-ai.desktop.staging"],
@@ -69923,7 +70408,7 @@ function serviceSpec({ config: config2, paths, self }) {
69923
70408
  profile: config2.profile,
69924
70409
  program: serviceCommand(config2.host, self, launcher),
69925
70410
  environment: config2.serviceEnvironment,
69926
- logPath: (0, import_node_path68.join)(paths.logs, "service.log"),
70411
+ logPath: (0, import_node_path70.join)(paths.logs, "service.log"),
69927
70412
  associatedBundleIds: DESKTOP_BUNDLE_IDS[config2.profile]
69928
70413
  };
69929
70414
  }
@@ -69931,7 +70416,7 @@ async function installedServiceSpec(ctx) {
69931
70416
  const spec = serviceSpec(ctx);
69932
70417
  if (ctx.config.host === "app") return spec;
69933
70418
  const layout = installLayout(ctx.config.installDir, ctx.config.profile);
69934
- const installed = await (0, import_promises67.access)(layout.launcher).then(
70419
+ const installed = await (0, import_promises68.access)(layout.launcher).then(
69935
70420
  () => true,
69936
70421
  () => false
69937
70422
  );
@@ -70059,7 +70544,7 @@ var manifestRevisionSchema = external_exports.object({ revision: external_export
70059
70544
  async function manifestRevision(path4) {
70060
70545
  let raw;
70061
70546
  try {
70062
- raw = JSON.parse(await (0, import_promises68.readFile)(path4, "utf8"));
70547
+ raw = JSON.parse(await (0, import_promises69.readFile)(path4, "utf8"));
70063
70548
  } catch (error61) {
70064
70549
  throw new RuntimeFault("invalid_file", `Cannot read the skill manifest at ${path4}`, {
70065
70550
  cause: error61
@@ -70113,8 +70598,8 @@ async function runSkills(argv) {
70113
70598
  }
70114
70599
 
70115
70600
  // src/cli/commands/doctor.ts
70116
- var import_promises71 = require("fs/promises");
70117
- var import_node_path72 = require("path");
70601
+ var import_promises72 = require("fs/promises");
70602
+ var import_node_path74 = require("path");
70118
70603
  init_runtime_v2();
70119
70604
 
70120
70605
  // src/identity/credential.ts
@@ -70291,18 +70776,18 @@ async function authorizeDevice(input2) {
70291
70776
  }
70292
70777
 
70293
70778
  // src/identity/enroll.ts
70294
- var import_promises69 = require("fs/promises");
70779
+ var import_promises70 = require("fs/promises");
70295
70780
  init_runtime_v2();
70296
70781
 
70297
70782
  // src/identity/installation.ts
70298
70783
  var import_node_crypto33 = require("crypto");
70299
- var import_node_path69 = require("path");
70784
+ var import_node_path71 = require("path");
70300
70785
  init_zod();
70301
70786
  var installationFileSchema = external_exports.object({
70302
70787
  installationId: external_exports.uuid()
70303
70788
  });
70304
70789
  function installationPath(paths) {
70305
- return (0, import_node_path69.join)(paths.stateDir, "installation.json");
70790
+ return (0, import_node_path71.join)(paths.stateDir, "installation.json");
70306
70791
  }
70307
70792
  async function ensureInstallationId(paths) {
70308
70793
  const path4 = installationPath(paths);
@@ -70395,13 +70880,13 @@ async function enrollFromGrantFile(input2) {
70395
70880
  clock: input2.clock,
70396
70881
  access: input2.access
70397
70882
  });
70398
- await (0, import_promises69.rm)(input2.grantPath, { force: true });
70883
+ await (0, import_promises70.rm)(input2.grantPath, { force: true });
70399
70884
  return machine;
70400
70885
  }
70401
70886
 
70402
70887
  // src/identity/migrate-v1.ts
70403
- var import_promises70 = require("fs/promises");
70404
- var import_node_path70 = require("path");
70888
+ var import_promises71 = require("fs/promises");
70889
+ var import_node_path72 = require("path");
70405
70890
  init_runtime_v2();
70406
70891
  init_zod();
70407
70892
  var EXIT_POLL_MS = 200;
@@ -70422,11 +70907,11 @@ var ownerLeaseSchema = external_exports.looseObject({ pid: external_exports.numb
70422
70907
  function legacyConfigPath(home, profile) {
70423
70908
  switch (profile) {
70424
70909
  case "production":
70425
- return (0, import_node_path70.join)(home, ".alan", "agent", "config.json");
70910
+ return (0, import_node_path72.join)(home, ".alan", "agent", "config.json");
70426
70911
  case "staging":
70427
- return (0, import_node_path70.join)(home, ".alan-staging", "agent", "config.json");
70912
+ return (0, import_node_path72.join)(home, ".alan-staging", "agent", "config.json");
70428
70913
  default:
70429
- return (0, import_node_path70.join)(home, ".alan-dev", "agent", "config.json");
70914
+ return (0, import_node_path72.join)(home, ".alan-dev", "agent", "config.json");
70430
70915
  }
70431
70916
  }
70432
70917
  async function findLegacyInstall(home, profile) {
@@ -70451,8 +70936,8 @@ async function scrubLegacyInstall(install2) {
70451
70936
  const scrubbed = { ...install2.config, migratedToRuntimeV2: true };
70452
70937
  for (const key of SCRUBBED_KEYS) delete scrubbed[key];
70453
70938
  await writeJsonFileAtomic(`${install2.configPath}.migrated-v1`, scrubbed);
70454
- await (0, import_promises70.rm)(install2.configPath, { force: true });
70455
- await (0, import_promises70.rm)(install2.ownerLeasePath, { force: true });
70939
+ await (0, import_promises71.rm)(install2.configPath, { force: true });
70940
+ await (0, import_promises71.rm)(install2.ownerLeasePath, { force: true });
70456
70941
  }
70457
70942
  async function exchangeCredential(deps) {
70458
70943
  const { config: config2 } = deps.install;
@@ -70561,7 +71046,7 @@ async function loadIdentity(paths, options = {}) {
70561
71046
  }
70562
71047
 
70563
71048
  // src/cli/commands/status.ts
70564
- var import_node_path71 = require("path");
71049
+ var import_node_path73 = require("path");
70565
71050
  async function serviceStatus(ctx) {
70566
71051
  try {
70567
71052
  return await createServiceManager(ctx.host, ctx.config.profile).status();
@@ -70588,7 +71073,7 @@ async function runtimeState(ctx) {
70588
71073
  const running = await readRunningRuntime(ctx.paths.lock);
70589
71074
  if (running === null) return { state: "offline", pid: null, localApi: null };
70590
71075
  const discovery = await readJsonFile(
70591
- (0, import_node_path71.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE),
71076
+ (0, import_node_path73.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE),
70592
71077
  localApiDiscoverySchema
70593
71078
  );
70594
71079
  const localApi = discovery.kind === "ok" && discovery.value.pid === running.pid ? {
@@ -70809,7 +71294,7 @@ async function runtimeCheck(ctx, status) {
70809
71294
  return check2("runtime", "warn", "No runtime is running for this profile");
70810
71295
  }
70811
71296
  const client = createRuntimeClient({
70812
- discoveryPath: (0, import_node_path72.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE)
71297
+ discoveryPath: (0, import_node_path74.join)(ctx.paths.stateDir, LOCAL_API_DISCOVERY_FILE)
70813
71298
  });
70814
71299
  try {
70815
71300
  const live = await client.status(AbortSignal.timeout(LOCAL_TIMEOUT_MS));
@@ -70836,7 +71321,7 @@ async function runtimeCheck(ctx, status) {
70836
71321
  }
70837
71322
  }
70838
71323
  async function probeHolder(dir, conversationId) {
70839
- const launch = await readJsonFile((0, import_node_path72.join)(dir, "launch.json"), holderLaunchSchema);
71324
+ const launch = await readJsonFile((0, import_node_path74.join)(dir, "launch.json"), holderLaunchSchema);
70840
71325
  if (launch.kind !== "ok") return null;
70841
71326
  try {
70842
71327
  const reply2 = await withTimeout(
@@ -70861,8 +71346,8 @@ async function probeHolder(dir, conversationId) {
70861
71346
  }
70862
71347
  }
70863
71348
  async function holdersCheck(ctx) {
70864
- const names = await (0, import_promises71.readdir)(ctx.paths.sessions).catch(() => []);
70865
- const holders = (await Promise.all(names.map((name) => probeHolder((0, import_node_path72.join)(ctx.paths.sessions, name), name)))).filter((facts) => facts !== null);
71349
+ const names = await (0, import_promises72.readdir)(ctx.paths.sessions).catch(() => []);
71350
+ const holders = (await Promise.all(names.map((name) => probeHolder((0, import_node_path74.join)(ctx.paths.sessions, name), name)))).filter((facts) => facts !== null);
70866
71351
  const dead = holders.filter((holder) => !holder.alive).length;
70867
71352
  return check2(
70868
71353
  "holders",
@@ -70873,10 +71358,10 @@ async function holdersCheck(ctx) {
70873
71358
  }
70874
71359
  async function freeBytesAt(path4) {
70875
71360
  try {
70876
- const stats = await (0, import_promises71.statfs)(path4);
71361
+ const stats = await (0, import_promises72.statfs)(path4);
70877
71362
  return { path: path4, freeBytes: stats.bavail * stats.bsize };
70878
71363
  } catch (error61) {
70879
- const parent = (0, import_node_path72.dirname)(path4);
71364
+ const parent = (0, import_node_path74.dirname)(path4);
70880
71365
  if (parent === path4) throw error61;
70881
71366
  return freeBytesAt(parent);
70882
71367
  }
@@ -70894,9 +71379,9 @@ async function diskCheck(ctx) {
70894
71379
  }
70895
71380
  }
70896
71381
  var resolveFromLoginShell = (own2) => resolveCliEnvironment({ env: own2, platform: process.platform });
70897
- async function cliDiscoveryCheck(resolve13) {
71382
+ async function cliDiscoveryCheck(resolve14) {
70898
71383
  const own2 = readCliEnvironment();
70899
- const env = await resolve13(own2);
71384
+ const env = await resolve14(own2);
70900
71385
  const delimiter = process.platform === "win32" ? ";" : ":";
70901
71386
  const ownDirs = new Set((own2.PATH ?? "").split(delimiter));
70902
71387
  const added = (env.PATH ?? "").split(delimiter).filter((dir) => dir.length > 0 && !ownDirs.has(dir));
@@ -71012,7 +71497,7 @@ async function runDoctor(argv, context = cliContext) {
71012
71497
  }
71013
71498
 
71014
71499
  // src/cli/commands/git-credential.ts
71015
- var import_promises72 = require("fs/promises");
71500
+ var import_promises73 = require("fs/promises");
71016
71501
  var import_node_net4 = require("net");
71017
71502
  var MAX_RESPONSE_BYTES = 64 * 1024;
71018
71503
  async function readAll(stream) {
@@ -71030,7 +71515,7 @@ function processIo() {
71030
71515
  };
71031
71516
  }
71032
71517
  function askGitCredentialSocket(endpoint, request2, signal) {
71033
- return new Promise((resolve13, reject) => {
71518
+ return new Promise((resolve14, reject) => {
71034
71519
  const socket = (0, import_node_net4.createConnection)(endpoint);
71035
71520
  let buffered = "";
71036
71521
  const fail = (error61) => {
@@ -71057,7 +71542,7 @@ function askGitCredentialSocket(endpoint, request2, signal) {
71057
71542
  signal.removeEventListener("abort", onAbort);
71058
71543
  try {
71059
71544
  const line = buffered.split("\n", 1)[0] ?? "";
71060
- resolve13(gitCredentialSocketResponseSchema.parse(JSON.parse(line)));
71545
+ resolve14(gitCredentialSocketResponseSchema.parse(JSON.parse(line)));
71061
71546
  } catch (error61) {
71062
71547
  reject(
71063
71548
  new RuntimeFault("io_failed", "the Alan runtime sent an invalid reply", { cause: error61 })
@@ -71122,7 +71607,7 @@ async function configure(argv) {
71122
71607
  }
71123
71608
  async function configureGitGateway(config2, gatewayUrl, signal) {
71124
71609
  const { launcher } = installLayout(config2.installDir, config2.profile);
71125
- const installed = await (0, import_promises72.access)(launcher).then(
71610
+ const installed = await (0, import_promises73.access)(launcher).then(
71126
71611
  () => true,
71127
71612
  () => false
71128
71613
  );
@@ -71149,7 +71634,7 @@ async function runGitCredential(argv) {
71149
71634
  }
71150
71635
 
71151
71636
  // src/cli/commands/hold.ts
71152
- var import_node_path73 = require("path");
71637
+ var import_node_path75 = require("path");
71153
71638
  init_agent2();
71154
71639
  init_runtime_v2();
71155
71640
  async function machineAccess(paths, log, conversationId, transport) {
@@ -71207,7 +71692,7 @@ async function runHold(argv) {
71207
71692
  const config2 = loadRuntimeConfig();
71208
71693
  const paths = runtimePaths(config2.stateDir);
71209
71694
  const log = __using(_stack, openFileLog(
71210
- (0, import_node_path73.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
71695
+ (0, import_node_path75.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
71211
71696
  config2.logLevel,
71212
71697
  systemClock
71213
71698
  ));
@@ -71218,7 +71703,7 @@ async function runHold(argv) {
71218
71703
  );
71219
71704
  const transport = __using(_stack, createHttpTransport());
71220
71705
  const access7 = await machineAccess(paths, log, launch.value.conversationId, transport);
71221
- const credentialPath = (0, import_node_path73.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
71706
+ const credentialPath = (0, import_node_path75.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
71222
71707
  const managedMcp = __using(_stack, access7.managedMcp === void 0 ? void 0 : createHelperMcpAccess({
71223
71708
  managedMcp: access7.managedMcp,
71224
71709
  conversationId: launch.value.conversationId,
@@ -71259,7 +71744,7 @@ async function runHold(argv) {
71259
71744
  }
71260
71745
 
71261
71746
  // src/cli/commands/hook.ts
71262
- var import_node_path74 = require("path");
71747
+ var import_node_path76 = require("path");
71263
71748
  var RUNTIME_ANSWER_MS = 2e3;
71264
71749
  var DEBUG_VARIABLE = "ALAN_HOOK_DEBUG";
71265
71750
  function flag(argv, name) {
@@ -71291,7 +71776,7 @@ async function forwardHook(argv, io) {
71291
71776
  return "transcript outside provider root";
71292
71777
  }
71293
71778
  const verdict = await io.send(
71294
- (0, import_node_path74.join)(io.stateDir, LOCAL_API_DISCOVERY_FILE),
71779
+ (0, import_node_path76.join)(io.stateDir, LOCAL_API_DISCOVERY_FILE),
71295
71780
  hookSignal,
71296
71781
  AbortSignal.timeout(RUNTIME_ANSWER_MS)
71297
71782
  );
@@ -71327,7 +71812,7 @@ async function runHook(argv, overrides = {}) {
71327
71812
  }
71328
71813
 
71329
71814
  // src/cli/commands/ingestion-hooks.ts
71330
- var import_promises73 = require("fs/promises");
71815
+ var import_promises74 = require("fs/promises");
71331
71816
  var CODEX_TRUST_NOTE = "Codex runs new hooks only after you review them: open /hooks in Codex.";
71332
71817
  function isAction(value2) {
71333
71818
  return value2 === "enable" || value2 === "disable" || value2 === "status";
@@ -71350,7 +71835,7 @@ function errorMessage2(error61) {
71350
71835
  return error61 instanceof Error ? error61.message : String(error61);
71351
71836
  }
71352
71837
  async function exists5(path4) {
71353
- return (0, import_promises73.access)(path4).then(
71838
+ return (0, import_promises74.access)(path4).then(
71354
71839
  () => true,
71355
71840
  () => false
71356
71841
  );
@@ -71453,10 +71938,10 @@ async function runIntegrationsCommand(argv) {
71453
71938
  }
71454
71939
 
71455
71940
  // src/cli/commands/legacy.ts
71456
- var import_node_path76 = require("path");
71941
+ var import_node_path78 = require("path");
71457
71942
 
71458
71943
  // src/cli/commands/setup.ts
71459
- var import_node_path75 = require("path");
71944
+ var import_node_path77 = require("path");
71460
71945
  init_zod();
71461
71946
 
71462
71947
  // src/cli/legacy.ts
@@ -71538,7 +72023,7 @@ async function grantFileCredential(argv, grantPath, ctx, deps) {
71538
72023
  return enrollFromGrantFile({
71539
72024
  paths: ctx.paths,
71540
72025
  storeKind: credentialStoreFlag(argv) ?? ctx.config.credentialStore,
71541
- grantPath: (0, import_node_path75.resolve)(grantPath),
72026
+ grantPath: (0, import_node_path77.resolve)(grantPath),
71542
72027
  clock: deps.clock,
71543
72028
  access: ctx.access
71544
72029
  });
@@ -71614,7 +72099,7 @@ async function runSetup(argv, signal) {
71614
72099
  var _stack = [];
71615
72100
  try {
71616
72101
  const ctx = cliContext();
71617
- const log = __using(_stack, openFileLog((0, import_node_path75.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72102
+ const log = __using(_stack, openFileLog((0, import_node_path77.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
71618
72103
  const result = await setupMachine(argv, ctx, {
71619
72104
  enrollment: (apiUrl) => createEnrollmentClient({ apiUrl }),
71620
72105
  isProcessAlive,
@@ -71697,7 +72182,7 @@ async function runToken(argv, signal) {
71697
72182
  );
71698
72183
  }
71699
72184
  const ctx = cliContext();
71700
- const log = __using(_stack, openFileLog((0, import_node_path76.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72185
+ const log = __using(_stack, openFileLog((0, import_node_path78.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
71701
72186
  const result = await rotateMachineCredential(ctx, { clock: systemClock, log, signal });
71702
72187
  process.stdout.write(`${rotationMessage(result)}
71703
72188
  `);
@@ -71709,8 +72194,8 @@ async function runToken(argv, signal) {
71709
72194
  }
71710
72195
 
71711
72196
  // src/cli/commands/logout.ts
71712
- var import_promises74 = require("fs/promises");
71713
- var import_node_path77 = require("path");
72197
+ var import_promises75 = require("fs/promises");
72198
+ var import_node_path79 = require("path");
71714
72199
  init_runtime_v2();
71715
72200
  var RUNTIME_EXIT_WAIT_MS = 35e3;
71716
72201
  var TURN_END_WAIT_MS = 3e4;
@@ -71769,9 +72254,9 @@ async function stopHolder(launch, deps, outcome2) {
71769
72254
  }
71770
72255
  async function stopHeldRuns(ctx, deps, outcome2 = "aborted") {
71771
72256
  const stopped = [];
71772
- for (const name of await (0, import_promises74.readdir)(ctx.paths.sessions).catch(() => [])) {
72257
+ for (const name of await (0, import_promises75.readdir)(ctx.paths.sessions).catch(() => [])) {
71773
72258
  const launch = await readJsonFile(
71774
- (0, import_node_path77.join)(ctx.paths.sessions, name, "launch.json"),
72259
+ (0, import_node_path79.join)(ctx.paths.sessions, name, "launch.json"),
71775
72260
  holderLaunchSchema
71776
72261
  );
71777
72262
  if (launch.kind !== "ok") continue;
@@ -71808,13 +72293,13 @@ async function forgetMachineLocally(ctx) {
71808
72293
  const machine = await readMachineFile(ctx.paths);
71809
72294
  if (machine === null) return;
71810
72295
  await credentialStoreFor(ctx.paths, machine.credentialStore, ctx.access).clear();
71811
- await (0, import_promises74.rm)(ctx.paths.machine, { force: true });
72296
+ await (0, import_promises75.rm)(ctx.paths.machine, { force: true });
71812
72297
  }
71813
72298
  async function runLogout(argv, signal) {
71814
72299
  var _stack = [];
71815
72300
  try {
71816
72301
  const ctx = cliContext();
71817
- const log = __using(_stack, openFileLog((0, import_node_path77.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
72302
+ const log = __using(_stack, openFileLog((0, import_node_path79.join)(ctx.paths.logs, "cli.jsonl"), ctx.config.logLevel, systemClock));
71818
72303
  const result = await logoutMachine(argv, ctx, {
71819
72304
  api: (apiUrl, accessToken) => createApiClient({ apiUrl, accessToken }),
71820
72305
  stopHeldRuns,
@@ -71832,7 +72317,7 @@ async function runLogout(argv, signal) {
71832
72317
 
71833
72318
  // src/cli/commands/run.ts
71834
72319
  var import_node_fs24 = require("fs");
71835
- var import_node_path81 = require("path");
72320
+ var import_node_path83 = require("path");
71836
72321
 
71837
72322
  // src/local-api/app-attachments.ts
71838
72323
  function createAppAttachments(clock) {
@@ -71872,7 +72357,7 @@ function createRunAppends() {
71872
72357
  const pending = waiters.get(runId);
71873
72358
  if (pending === void 0) return;
71874
72359
  waiters.delete(runId);
71875
- for (const resolve13 of pending) resolve13();
72360
+ for (const resolve14 of pending) resolve14();
71876
72361
  };
71877
72362
  return {
71878
72363
  notify: wake,
@@ -71890,13 +72375,13 @@ function createRunAppends() {
71890
72375
  },
71891
72376
  nextAppend: (runId, signal) => {
71892
72377
  if (signal.aborted) return Promise.resolve();
71893
- return new Promise((resolve13) => {
72378
+ return new Promise((resolve14) => {
71894
72379
  const done = () => {
71895
72380
  signal.removeEventListener("abort", done);
71896
72381
  const pending2 = waiters.get(runId);
71897
72382
  pending2?.delete(done);
71898
72383
  if (pending2?.size === 0) waiters.delete(runId);
71899
- resolve13();
72384
+ resolve14();
71900
72385
  };
71901
72386
  const pending = waiters.get(runId) ?? /* @__PURE__ */ new Set();
71902
72387
  pending.add(done);
@@ -71909,9 +72394,9 @@ function createRunAppends() {
71909
72394
 
71910
72395
  // src/local-api/server.ts
71911
72396
  var import_node_crypto35 = require("crypto");
71912
- var import_promises75 = require("fs/promises");
72397
+ var import_promises76 = require("fs/promises");
71913
72398
  var import_node_http4 = require("http");
71914
- var import_node_path78 = require("path");
72399
+ var import_node_path80 = require("path");
71915
72400
 
71916
72401
  // src/local-api/guard.ts
71917
72402
  var import_node_crypto34 = require("crypto");
@@ -71988,11 +72473,11 @@ id: ${event.id}
71988
72473
  ${data}
71989
72474
  `);
71990
72475
  if (accepted || res.destroyed) return;
71991
- await new Promise((resolve13) => {
72476
+ await new Promise((resolve14) => {
71992
72477
  const done = () => {
71993
72478
  res.off("drain", done);
71994
72479
  res.off("close", done);
71995
- resolve13();
72480
+ resolve14();
71996
72481
  };
71997
72482
  res.once("drain", done);
71998
72483
  res.once("close", done);
@@ -72220,9 +72705,9 @@ async function readChangedTurn(deps, conversationId, runId, slot) {
72220
72705
  }
72221
72706
  async function nextChangedRuns(bell, signal) {
72222
72707
  if (bell.pending.size === 0) {
72223
- await new Promise((resolve13) => {
72224
- bell.wake = resolve13;
72225
- if (signal.aborted || bell.pending.size > 0) resolve13();
72708
+ await new Promise((resolve14) => {
72709
+ bell.wake = resolve14;
72710
+ if (signal.aborted || bell.pending.size > 0) resolve14();
72226
72711
  });
72227
72712
  bell.wake = void 0;
72228
72713
  }
@@ -72539,9 +73024,9 @@ var streamStatus = async ({ feed, appAttachments }, { res, signal }) => {
72539
73024
  latest = event;
72540
73025
  writing = writing.then(flush);
72541
73026
  }));
72542
- await new Promise((resolve13) => {
72543
- if (signal.aborted) resolve13();
72544
- signal.addEventListener("abort", () => resolve13(), { once: true });
73027
+ await new Promise((resolve14) => {
73028
+ if (signal.aborted) resolve14();
73029
+ signal.addEventListener("abort", () => resolve14(), { once: true });
72545
73030
  });
72546
73031
  await writing;
72547
73032
  } catch (_) {
@@ -72864,11 +73349,11 @@ function localRequestSignal(path4, closed) {
72864
73349
  ]);
72865
73350
  }
72866
73351
  async function listenOnLoopback(server) {
72867
- await new Promise((resolve13, reject) => {
73352
+ await new Promise((resolve14, reject) => {
72868
73353
  server.once("error", reject);
72869
73354
  server.listen(0, "127.0.0.1", () => {
72870
73355
  server.off("error", reject);
72871
- resolve13();
73356
+ resolve14();
72872
73357
  });
72873
73358
  }).catch((error61) => {
72874
73359
  throw new RuntimeFault("io_failed", "The local API could not listen on loopback", {
@@ -72883,7 +73368,7 @@ async function listenOnLoopback(server) {
72883
73368
  }
72884
73369
  async function closeServer(server) {
72885
73370
  server.closeAllConnections();
72886
- await new Promise((resolve13) => server.close(() => resolve13()));
73371
+ await new Promise((resolve14) => server.close(() => resolve14()));
72887
73372
  }
72888
73373
  async function serveLocalApi(deps) {
72889
73374
  const limits = { ...DEFAULT_LIMITS, ...deps.limits };
@@ -72954,7 +73439,7 @@ async function serveLocalApi(deps) {
72954
73439
  startedAtMs,
72955
73440
  runtimeVersion: deps.runtimeVersion
72956
73441
  };
72957
- const discoveryPath = (0, import_node_path78.join)(deps.stateDir, LOCAL_API_DISCOVERY_FILE);
73442
+ const discoveryPath = (0, import_node_path80.join)(deps.stateDir, LOCAL_API_DISCOVERY_FILE);
72958
73443
  await writeJsonFileAtomic(discoveryPath, discovery);
72959
73444
  const followers = startMaintenance({
72960
73445
  everyMs: limits.refreshEveryMs,
@@ -72988,7 +73473,7 @@ async function serveLocalApi(deps) {
72988
73473
  await watchedStatus[Symbol.asyncDispose]();
72989
73474
  const current = await readJsonFile(discoveryPath, localApiDiscoverySchema);
72990
73475
  if (current.kind === "ok" && current.value.token === token) {
72991
- await (0, import_promises75.rm)(discoveryPath, { force: true });
73476
+ await (0, import_promises76.rm)(discoveryPath, { force: true });
72992
73477
  }
72993
73478
  await closeServer(server);
72994
73479
  log.info("local_api.closed", {});
@@ -73073,7 +73558,7 @@ function machineFeatureActions(deps) {
73073
73558
  }
73074
73559
 
73075
73560
  // src/cli/commands/machine-plane.ts
73076
- var import_node_path80 = require("path");
73561
+ var import_node_path82 = require("path");
73077
73562
 
73078
73563
  // src/link/index.ts
73079
73564
  init_runtime_v2();
@@ -75640,9 +76125,9 @@ var Socket2 = class extends Emitter {
75640
76125
  * @return a Promise that will be fulfilled when the server acknowledges the event
75641
76126
  */
75642
76127
  emitWithAck(ev, ...args) {
75643
- return new Promise((resolve13, reject) => {
76128
+ return new Promise((resolve14, reject) => {
75644
76129
  const fn = (arg1, arg2) => {
75645
- return arg1 ? reject(arg1) : resolve13(arg2);
76130
+ return arg1 ? reject(arg1) : resolve14(arg2);
75646
76131
  };
75647
76132
  fn.withError = true;
75648
76133
  args.push(fn);
@@ -76741,7 +77226,7 @@ function refusalFailure(refusal2) {
76741
77226
  }
76742
77227
 
76743
77228
  // src/link/probe.ts
76744
- var import_promises76 = require("dns/promises");
77229
+ var import_promises77 = require("dns/promises");
76745
77230
  var import_node_net5 = require("net");
76746
77231
  var import_node_tls2 = require("tls");
76747
77232
  var PROBE_TIMEOUT_MS4 = 5e3;
@@ -76761,9 +77246,9 @@ async function connectOnce(url3, clock) {
76761
77246
  const timer = new AbortController();
76762
77247
  try {
76763
77248
  return await Promise.race([
76764
- new Promise((resolve13) => {
76765
- socket.once(ready, () => resolve13(null));
76766
- socket.once("error", (error61) => resolve13(classifyTransportFailure(error61)));
77249
+ new Promise((resolve14) => {
77250
+ socket.once(ready, () => resolve14(null));
77251
+ socket.once("error", (error61) => resolve14(classifyTransportFailure(error61)));
76767
77252
  }),
76768
77253
  clock.sleep(PROBE_TIMEOUT_MS4, timer.signal).then(
76769
77254
  () => "connection_timeout",
@@ -76777,7 +77262,7 @@ async function connectOnce(url3, clock) {
76777
77262
  }
76778
77263
  async function probeEndpoint(url3, clock) {
76779
77264
  try {
76780
- await (0, import_promises76.lookup)(url3.hostname);
77265
+ await (0, import_promises77.lookup)(url3.hostname);
76781
77266
  } catch (error61) {
76782
77267
  const reason = classifyTransportFailure(error61);
76783
77268
  return reason === "other" ? "dns" : reason;
@@ -77226,7 +77711,7 @@ function createReconciler(host, lifecycle, log, signal) {
77226
77711
  }
77227
77712
 
77228
77713
  // src/uploader/index.ts
77229
- var import_promises77 = require("fs/promises");
77714
+ var import_promises78 = require("fs/promises");
77230
77715
  init_runtime_v2();
77231
77716
  init_zod();
77232
77717
  var RETRY_DELAYS_MS = [250, 500, 1e3, 2e3, 5e3, 1e4, 3e4];
@@ -77374,7 +77859,7 @@ function startUploader({ api, runsDir, clock, log, archive }) {
77374
77859
  };
77375
77860
  const unsealedRunIds = async () => {
77376
77861
  const runIds = [];
77377
- for (const name of await (0, import_promises77.readdir)(runsDir).catch(() => [])) {
77862
+ for (const name of await (0, import_promises78.readdir)(runsDir).catch(() => [])) {
77378
77863
  const runId = runIdSchema.safeParse(name);
77379
77864
  if (runId.success && !sealed.has(runId.data) && !archive?.has(runId.data))
77380
77865
  runIds.push(runId.data);
@@ -77389,13 +77874,13 @@ function startUploader({ api, runsDir, clock, log, archive }) {
77389
77874
  const dir = runDirectory(runsDir, runId);
77390
77875
  const progress = await readJsonFile(dir.upload, uploadProgressSchema);
77391
77876
  if (progress.kind !== "ok" || !progress.value.sealed) return false;
77392
- const sealedAt = (await (0, import_promises77.stat)(dir.upload)).mtimeMs;
77877
+ const sealedAt = (await (0, import_promises78.stat)(dir.upload)).mtimeMs;
77393
77878
  if (clock.now() - sealedAt < options.sealedForMs) return false;
77394
77879
  return (await readLastRecord(dir.log))?.update.sessionUpdate === "_alan/run.ended";
77395
77880
  };
77396
77881
  const archivable = async (options) => {
77397
77882
  const found = [];
77398
- for (const name of await (0, import_promises77.readdir)(runsDir).catch(() => [])) {
77883
+ for (const name of await (0, import_promises78.readdir)(runsDir).catch(() => [])) {
77399
77884
  const runId = runIdSchema.safeParse(name);
77400
77885
  if (!runId.success || archive?.has(runId.data)) continue;
77401
77886
  try {
@@ -77596,12 +78081,12 @@ async function startMachineNativeIngest(deps) {
77596
78081
  }
77597
78082
 
77598
78083
  // src/cli/commands/run-updates.ts
77599
- var import_node_path79 = require("path");
78084
+ var import_node_path81 = require("path");
77600
78085
  init_runtime_v2();
77601
78086
  var UPDATE_CHECK_EVERY_MS = 6 * 60 * 60 * 1e3;
77602
78087
  var DEFERRED_RETRY_MS = 5 * 60 * 1e3;
77603
78088
  function isInstalledBundle(layout, bundlePath) {
77604
- return (0, import_node_path79.resolve)((0, import_node_path79.dirname)((0, import_node_path79.dirname)(bundlePath))) === (0, import_node_path79.resolve)(layout.versions);
78089
+ return (0, import_node_path81.resolve)((0, import_node_path81.dirname)((0, import_node_path81.dirname)(bundlePath))) === (0, import_node_path81.resolve)(layout.versions);
77605
78090
  }
77606
78091
  async function settleUpgradeOnStart({
77607
78092
  layout,
@@ -77708,7 +78193,7 @@ function startRuntimeUpdates(options) {
77708
78193
  layout,
77709
78194
  release: npmRelease,
77710
78195
  tarball: await options.downloader.download(npmRelease.dist.tarball, signal),
77711
- tmpDir: (0, import_node_path79.join)(layout.root, ".downloads")
78196
+ tmpDir: (0, import_node_path81.join)(layout.root, ".downloads")
77712
78197
  });
77713
78198
  await lifecycle.exclusive("upgrade", async () => {
77714
78199
  await recordPendingUpgrade(layout, currentVersion2, version2, clock.now());
@@ -77939,7 +78424,7 @@ async function startMachinePlane(deps) {
77939
78424
  [ALAN_MANAGED_SESSION_ENV]: "1"
77940
78425
  },
77941
78426
  cwd: paths.stateDir,
77942
- outputPath: (0, import_node_path80.join)(paths.logs, "holders.log")
78427
+ outputPath: (0, import_node_path82.join)(paths.logs, "holders.log")
77943
78428
  },
77944
78429
  deps.holderIsolation
77945
78430
  );
@@ -77976,7 +78461,7 @@ async function startMachinePlane(deps) {
77976
78461
  }),
77977
78462
  local: { home: config2.home, machineId: identity.machineId },
77978
78463
  // Only a cloud sandbox's runtime has a git gateway; a person's own ~/.codex is theirs.
77979
- ...config2.gitGatewayUrl === null ? {} : { codexSkillsDir: (0, import_node_path80.join)(config2.codexHome, "skills") },
78464
+ ...config2.gitGatewayUrl === null ? {} : { codexSkillsDir: (0, import_node_path82.join)(config2.codexHome, "skills") },
77980
78465
  log
77981
78466
  })
77982
78467
  );
@@ -78174,7 +78659,7 @@ async function startMachinePlane(deps) {
78174
78659
  git: createGitRunner({ env: cliEnvironment }),
78175
78660
  clock,
78176
78661
  log,
78177
- dir: (0, import_node_path80.join)(paths.stateDir, "checkout-freshness")
78662
+ dir: (0, import_node_path82.join)(paths.stateDir, "checkout-freshness")
78178
78663
  },
78179
78664
  stopped.signal
78180
78665
  );
@@ -78436,11 +78921,11 @@ function createMachineSlot(deps) {
78436
78921
 
78437
78922
  // src/cli/commands/run-exit.ts
78438
78923
  function firstAborted(signals) {
78439
- return new Promise((resolve13) => {
78924
+ return new Promise((resolve14) => {
78440
78925
  for (const reason of ["stop", "restart"]) {
78441
78926
  const signal = signals[reason];
78442
- if (signal.aborted) resolve13(reason);
78443
- signal.addEventListener("abort", () => resolve13(reason), { once: true });
78927
+ if (signal.aborted) resolve14(reason);
78928
+ signal.addEventListener("abort", () => resolve14(reason), { once: true });
78444
78929
  }
78445
78930
  });
78446
78931
  }
@@ -78468,7 +78953,7 @@ function lockWaitMs(argv) {
78468
78953
  }
78469
78954
  async function openManagedProviders(config2, paths) {
78470
78955
  const providerEnv = readCliEnvironment();
78471
- const bundledNpm = (0, import_node_path81.join)((0, import_node_path81.dirname)(process.execPath), "npm", "bin", "npm-cli.js");
78956
+ const bundledNpm = (0, import_node_path83.join)((0, import_node_path83.dirname)(process.execPath), "npm", "bin", "npm-cli.js");
78472
78957
  const providerToolchain = config2.providerToolchain ?? (process.platform === "win32" && (0, import_node_fs24.existsSync)(bundledNpm) ? { node: process.execPath, npmCli: bundledNpm } : null);
78473
78958
  const npmPath = providerToolchain?.node ?? await resolveCommandOnPath("npm", providerEnv, process.platform);
78474
78959
  const npmOptions = npmPath === null || process.platform === "win32" && providerToolchain === null ? null : {
@@ -78476,7 +78961,7 @@ async function openManagedProviders(config2, paths) {
78476
78961
  ...providerToolchain === null ? {} : { argsBeforeNpm: [providerToolchain.npmCli] },
78477
78962
  env: providerEnv
78478
78963
  };
78479
- const providerNodeDir = providerToolchain?.node === void 0 ? void 0 : (0, import_node_path81.dirname)(providerToolchain.node);
78964
+ const providerNodeDir = providerToolchain?.node === void 0 ? void 0 : (0, import_node_path83.dirname)(providerToolchain.node);
78480
78965
  const probeEnv = providerNodeDir === void 0 ? providerEnv : {
78481
78966
  ...providerEnv,
78482
78967
  PATH: `${providerNodeDir}${pathDelimiter(process.platform)}${envValue(providerEnv, "PATH")}`
@@ -78486,7 +78971,7 @@ async function openManagedProviders(config2, paths) {
78486
78971
  throw new Error("Provider installer is unavailable on this computer");
78487
78972
  };
78488
78973
  const managed = createManagedProviderClis({
78489
- root: (0, import_node_path81.join)(paths.stateDir, "provider-clis"),
78974
+ root: (0, import_node_path83.join)(paths.stateDir, "provider-clis"),
78490
78975
  resolveVersion: npmOptions === null ? unavailable : createNpmVersionResolver(npmOptions),
78491
78976
  installPackage: npmOptions === null ? unavailable : createNpmPackageInstaller(npmOptions),
78492
78977
  probe: (executable, backendKind) => probeManagedProvider(executable, backendKind, canonicalProbeEnv)
@@ -78518,7 +79003,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
78518
79003
  waitMs: lockWaitMs(argv),
78519
79004
  signal: stop
78520
79005
  }));
78521
- const log = __using(_stack, openFileLog((0, import_node_path81.join)(paths.logs, "runtime.jsonl"), config2.logLevel, clock));
79006
+ const log = __using(_stack, openFileLog((0, import_node_path83.join)(paths.logs, "runtime.jsonl"), config2.logLevel, clock));
78522
79007
  const lifecycle = createLifecycleQueue({ clock, log });
78523
79008
  const install2 = installLayout(config2.installDir, config2.profile);
78524
79009
  const bundlePath = process.argv[1] ?? "";
@@ -78552,7 +79037,7 @@ async function runService(argv, stop, restart = new AbortController().signal) {
78552
79037
  openCliEnvironment({
78553
79038
  env: readCliEnvironment(),
78554
79039
  platform: process.platform,
78555
- lastKnownGoodFile: (0, import_node_path81.join)(paths.stateDir, "login-path.json"),
79040
+ lastKnownGoodFile: (0, import_node_path83.join)(paths.stateDir, "login-path.json"),
78556
79041
  clock,
78557
79042
  decorate: (env) => withPackagedAlanCodeEngine(env, bundlePath, process.platform)
78558
79043
  })
@@ -78729,17 +79214,17 @@ async function runServiceCommand(argv, ctx = cliContext()) {
78729
79214
  }
78730
79215
 
78731
79216
  // src/cli/commands/upgrade.ts
78732
- var import_promises78 = require("fs/promises");
78733
- var import_node_path82 = require("path");
79217
+ var import_promises79 = require("fs/promises");
79218
+ var import_node_path84 = require("path");
78734
79219
  function isNotNewer(version2, installed) {
78735
79220
  return installed !== null && isReleaseVersion(version2) && isReleaseVersion(installed) && compareVersions(version2, installed) <= 0;
78736
79221
  }
78737
79222
  async function installFromSource(source) {
78738
79223
  const { layout, from, ifNewer } = source;
78739
- const isTarball = (await (0, import_promises78.stat)(from)).isFile();
78740
- const downloads = (0, import_node_path82.join)(layout.root, ".downloads");
78741
- if (isTarball) await (0, import_promises78.mkdir)(downloads, { recursive: true, mode: 448 });
78742
- const scratch = isTarball ? await (0, import_promises78.mkdtemp)((0, import_node_path82.join)(downloads, "upgrade-")) : null;
79224
+ const isTarball = (await (0, import_promises79.stat)(from)).isFile();
79225
+ const downloads = (0, import_node_path84.join)(layout.root, ".downloads");
79226
+ if (isTarball) await (0, import_promises79.mkdir)(downloads, { recursive: true, mode: 448 });
79227
+ const scratch = isTarball ? await (0, import_promises79.mkdtemp)((0, import_node_path84.join)(downloads, "upgrade-")) : null;
78743
79228
  try {
78744
79229
  const sourceDir = scratch === null ? from : await extractPackageTarball(from, scratch);
78745
79230
  const version2 = await readPackageVersion(sourceDir);
@@ -78747,7 +79232,7 @@ async function installFromSource(source) {
78747
79232
  if (ifNewer && isNotNewer(version2, installed)) return { kind: "skipped", version: version2, installed };
78748
79233
  return { kind: "installed", ...await installVersion(layout, sourceDir) };
78749
79234
  } finally {
78750
- if (scratch !== null) await (0, import_promises78.rm)(scratch, { recursive: true, force: true });
79235
+ if (scratch !== null) await (0, import_promises79.rm)(scratch, { recursive: true, force: true });
78751
79236
  }
78752
79237
  }
78753
79238
  async function runUpgrade(argv) {
@@ -78759,7 +79244,7 @@ async function runUpgrade(argv) {
78759
79244
  const layout = installLayout(config2.installDir, config2.profile);
78760
79245
  const outcome2 = await installFromSource({
78761
79246
  layout,
78762
- from: (0, import_node_path82.resolve)(from),
79247
+ from: (0, import_node_path84.resolve)(from),
78763
79248
  ifNewer: hasFlag(argv, "--if-newer")
78764
79249
  });
78765
79250
  if (outcome2.kind === "skipped") {