@ai-development-environment/control-agent 0.0.53 → 0.0.54

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.
@@ -4182,7 +4182,7 @@ var require_cross_spawn = __commonJS({
4182
4182
  var cp3 = __require("child_process");
4183
4183
  var parse2 = require_parse();
4184
4184
  var enoent = require_enoent();
4185
- function spawn7(command3, args, options) {
4185
+ function spawn8(command3, args, options) {
4186
4186
  const parsed = parse2(command3, args, options);
4187
4187
  const spawned = cp3.spawn(parsed.command, parsed.args, parsed.options);
4188
4188
  enoent.hookChildProcess(spawned, parsed);
@@ -4194,18 +4194,14 @@ var require_cross_spawn = __commonJS({
4194
4194
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
4195
4195
  return result;
4196
4196
  }
4197
- module.exports = spawn7;
4198
- module.exports.spawn = spawn7;
4197
+ module.exports = spawn8;
4198
+ module.exports.spawn = spawn8;
4199
4199
  module.exports.sync = spawnSync2;
4200
4200
  module.exports._parse = parse2;
4201
4201
  module.exports._enoent = enoent;
4202
4202
  }
4203
4203
  });
4204
4204
 
4205
- // src/index.ts
4206
- import { execFile as execFile5 } from "node:child_process";
4207
- import { promisify as promisify5 } from "node:util";
4208
-
4209
4205
  // src/config.ts
4210
4206
  import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
4211
4207
  import { homedir } from "node:os";
@@ -4252,8 +4248,6 @@ async function saveConfig(config, path = configPath()) {
4252
4248
  }
4253
4249
 
4254
4250
  // ../agent-contract/src/index.ts
4255
- var TUNNEL_NAME_PATTERN = "[A-Za-z0-9][A-Za-z0-9_-]{0,127}";
4256
- var TUNNEL_NAME_REGEX = new RegExp(`^${TUNNEL_NAME_PATTERN}$`);
4257
4251
  var CCUSAGE_REPORT_JOB_KIND = "ccusage.report";
4258
4252
  var DEFAULT_AGENT_HEARTBEAT_INTERVAL_SECONDS = 15;
4259
4253
  var MIN_AGENT_HEARTBEAT_INTERVAL_SECONDS = 5;
@@ -5180,7 +5174,7 @@ var AgentGraphQLClient = class {
5180
5174
  { agentId }
5181
5175
  );
5182
5176
  return data.agentJobs.filter(
5183
- (job) => job.status === "QUEUED" || job.status === "RUNNING" || job.status === "CANCELLED"
5177
+ (job) => job.status === "QUEUED" || job.status === "RUNNING" || job.status === "CANCELLING" || job.status === "CANCELLED"
5184
5178
  );
5185
5179
  }
5186
5180
  async cadenceSettings(agentId) {
@@ -5236,6 +5230,14 @@ var AgentGraphQLClient = class {
5236
5230
  { jobId, logs: [log] }
5237
5231
  );
5238
5232
  }
5233
+ appendCommandOutput(jobId, attemptId, chunks) {
5234
+ return this.request(
5235
+ `mutation AppendCommandRunOutput($jobId: ID!, $attemptId: ID!, $chunks: [CommandRunOutputInput!]!) {
5236
+ appendCommandRunOutput(jobId: $jobId, attemptId: $attemptId, chunks: $chunks) { id }
5237
+ }`,
5238
+ { jobId, attemptId, chunks }
5239
+ );
5240
+ }
5239
5241
  reportBuildProgress(input) {
5240
5242
  return this.request(
5241
5243
  `mutation ReportBuildProgress($input: BuildProgressInput!) {
@@ -5244,12 +5246,12 @@ var AgentGraphQLClient = class {
5244
5246
  { input }
5245
5247
  );
5246
5248
  }
5247
- appendBuildLogs(buildId, events) {
5249
+ appendBuildLogChunks(buildId, chunks) {
5248
5250
  return this.request(
5249
- `mutation AppendBuildLogs($buildId: ID!, $events: [BuildLogEventInput!]!) {
5250
- appendBuildLogEvents(buildId: $buildId, events: $events) { id }
5251
+ `mutation AppendBuildLogChunks($buildId: ID!, $chunks: [BuildLogChunkInput!]!) {
5252
+ appendBuildLogChunks(buildId: $buildId, chunks: $chunks) { id }
5251
5253
  }`,
5252
- { buildId, events }
5254
+ { buildId, chunks }
5253
5255
  );
5254
5256
  }
5255
5257
  async uploadBuildArtifact(input) {
@@ -7782,10 +7784,58 @@ function parseWorkflowGitCheckpointPayload(value) {
7782
7784
  };
7783
7785
  }
7784
7786
 
7787
+ // ../agent-contract/src/commands.ts
7788
+ var COMMAND_RUN_JOB_KIND = "command.run";
7789
+ function objectValue10(value, name) {
7790
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
7791
+ throw new Error(`${name} must be an object`);
7792
+ }
7793
+ return value;
7794
+ }
7795
+ function stringValue10(value, name, maximum) {
7796
+ if (typeof value !== "string" || !value.length || value.length > maximum) {
7797
+ throw new Error(
7798
+ `${name} must be a non-empty string of at most ${maximum} characters`
7799
+ );
7800
+ }
7801
+ return value;
7802
+ }
7803
+ function parseCommandRunPayload(value) {
7804
+ const payload = objectValue10(value, "command run payload");
7805
+ const targetKind = stringValue10(payload.targetKind, "targetKind", 20);
7806
+ if (targetKind !== "AGENT_HOME" && targetKind !== "WORKTREE") {
7807
+ throw new Error("targetKind must be AGENT_HOME or WORKTREE");
7808
+ }
7809
+ const cwd = payload.cwd === null || payload.cwd === void 0 ? null : stringValue10(payload.cwd, "cwd", 1e4);
7810
+ if (targetKind === "WORKTREE" && !cwd) {
7811
+ throw new Error("Worktree commands require cwd");
7812
+ }
7813
+ if (targetKind === "AGENT_HOME" && cwd !== null) {
7814
+ throw new Error("Agent-home commands cannot provide cwd");
7815
+ }
7816
+ const allowed = /* @__PURE__ */ new Set([
7817
+ "commandRunId",
7818
+ "attemptId",
7819
+ "targetKind",
7820
+ "cwd",
7821
+ "script"
7822
+ ]);
7823
+ const unexpected = Object.keys(payload).find((key) => !allowed.has(key));
7824
+ if (unexpected)
7825
+ throw new Error(`Unsupported command payload field: ${unexpected}`);
7826
+ return {
7827
+ commandRunId: stringValue10(payload.commandRunId, "commandRunId", 200),
7828
+ attemptId: stringValue10(payload.attemptId, "attemptId", 200),
7829
+ targetKind,
7830
+ cwd,
7831
+ script: stringValue10(payload.script, "script", 1e6)
7832
+ };
7833
+ }
7834
+
7785
7835
  // src/inventory.ts
7786
7836
  var AGENT_VERSION = "0.1.0";
7787
7837
  var AGENT_CAPABILITIES = [
7788
- "cloudflared.runTunnel",
7838
+ COMMAND_RUN_JOB_KIND,
7789
7839
  CCUSAGE_REPORT_JOB_KIND,
7790
7840
  ...BUILD_DATA_JOB_KINDS,
7791
7841
  ...CODEBASE_JOB_KINDS,
@@ -7817,148 +7867,186 @@ function collectInventory() {
7817
7867
  };
7818
7868
  }
7819
7869
 
7820
- // src/process-runner.ts
7870
+ // src/handlers/commands.ts
7821
7871
  import { spawn } from "node:child_process";
7822
- async function runProcess(options) {
7823
- return new Promise((resolve7, reject) => {
7824
- let sequence = 0;
7825
- let timedOut = false;
7826
- let cancelled = false;
7827
- let settled = false;
7828
- let logChain = Promise.resolve();
7829
- const detached = process.platform !== "win32";
7830
- const child = spawn(options.command, options.args, {
7831
- shell: false,
7832
- stdio: ["ignore", "pipe", "pipe"],
7833
- cwd: options.cwd,
7834
- env: options.env ?? process.env,
7835
- // A separate process group lets cancellation terminate scripts and all
7836
- // descendants instead of leaving a child holding stdout/stderr open.
7837
- detached
7838
- });
7839
- const emit = (stream, message) => {
7840
- const log = {
7841
- sequence: sequence++,
7842
- stream,
7843
- message,
7844
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
7845
- };
7846
- logChain = logChain.then(async () => {
7872
+ import { chmod as chmod2, mkdtemp, realpath, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
7873
+ import { homedir as homedir2, tmpdir } from "node:os";
7874
+ import { join as join2 } from "node:path";
7875
+ var MAX_BATCH_BYTES = 128 * 1024;
7876
+ var FLUSH_DELAY_MS = 25;
7877
+ var runCommand = async (rawPayload, _timeoutMs, signal, _onLog, context) => {
7878
+ const payload = parseCommandRunPayload(rawPayload);
7879
+ if (!context?.appendCommandOutput) {
7880
+ throw new Error("Command output uploader is unavailable");
7881
+ }
7882
+ const directory = await mkdtemp(join2(tmpdir(), "aide-command-"));
7883
+ const scriptPath = join2(directory, "command.sh");
7884
+ await writeFile2(scriptPath, payload.script, {
7885
+ encoding: "utf8",
7886
+ mode: 384
7887
+ });
7888
+ await chmod2(scriptPath, 384);
7889
+ const cwd = payload.targetKind === "AGENT_HOME" ? homedir2() : await realpath(payload.cwd);
7890
+ let sequence = 0;
7891
+ let queuedBytes = 0;
7892
+ let pending = [];
7893
+ let timer;
7894
+ let uploadChain = Promise.resolve();
7895
+ const upload = (chunks) => {
7896
+ if (!chunks.length) return;
7897
+ const bytes = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
7898
+ uploadChain = uploadChain.then(async () => {
7899
+ let retry = 0;
7900
+ while (true) {
7847
7901
  try {
7848
- await options.onLog(log);
7902
+ await context.appendCommandOutput?.(payload.attemptId, chunks);
7903
+ queuedBytes -= bytes;
7904
+ return;
7849
7905
  } catch (error) {
7906
+ if (signal.aborted) return;
7907
+ const delay = Math.min(3e4, 500 * 2 ** Math.min(retry++, 6));
7850
7908
  console.error(
7851
- `Could not append process log ${log.sequence}:`,
7909
+ `Could not append command output; retrying in ${delay}ms:`,
7852
7910
  error instanceof Error ? error.message : error
7853
7911
  );
7912
+ await new Promise((resolve7) => {
7913
+ const onAbort = () => {
7914
+ clearTimeout(retryTimer);
7915
+ resolve7();
7916
+ };
7917
+ const retryTimer = setTimeout(() => {
7918
+ signal.removeEventListener("abort", onAbort);
7919
+ resolve7();
7920
+ }, delay);
7921
+ retryTimer.unref();
7922
+ signal.addEventListener("abort", onAbort, { once: true });
7923
+ if (signal.aborted) onAbort();
7924
+ });
7925
+ if (signal.aborted) return;
7854
7926
  }
7855
- });
7927
+ }
7928
+ });
7929
+ };
7930
+ const flush = () => {
7931
+ if (timer) clearTimeout(timer);
7932
+ timer = void 0;
7933
+ const batch = pending;
7934
+ pending = [];
7935
+ upload(batch);
7936
+ };
7937
+ const enqueue = (stream, bytes) => {
7938
+ const chunk = {
7939
+ sequence: sequence++,
7940
+ stream,
7941
+ dataBase64: bytes.toString("base64"),
7942
+ byteLength: bytes.length,
7943
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
7856
7944
  };
7857
- const attach = (stream, kind) => {
7858
- let remainder = "";
7859
- stream.setEncoding("utf8");
7860
- stream.on("data", (chunk) => {
7861
- const parts = `${remainder}${chunk}`.split(/\r?\n/);
7862
- remainder = parts.pop() ?? "";
7863
- for (const line of parts) emit(kind, line);
7945
+ pending.push(chunk);
7946
+ queuedBytes += bytes.length;
7947
+ if (pending.reduce((total, item) => total + item.byteLength, 0) >= MAX_BATCH_BYTES) {
7948
+ flush();
7949
+ } else if (!timer) {
7950
+ timer = setTimeout(flush, FLUSH_DELAY_MS);
7951
+ timer.unref();
7952
+ }
7953
+ };
7954
+ try {
7955
+ return await new Promise((resolve7, reject) => {
7956
+ let cancelled = false;
7957
+ let settled = false;
7958
+ const child = spawn(process.env.SHELL || "/bin/sh", ["-l", scriptPath], {
7959
+ cwd,
7960
+ detached: process.platform !== "win32",
7961
+ env: {
7962
+ ...process.env,
7963
+ TERM: "xterm-256color",
7964
+ COLORTERM: "truecolor",
7965
+ FORCE_COLOR: "1",
7966
+ CLICOLOR_FORCE: "1"
7967
+ },
7968
+ shell: false,
7969
+ stdio: ["ignore", "pipe", "pipe"]
7864
7970
  });
7865
- stream.on("end", () => {
7866
- if (remainder) emit(kind, remainder);
7971
+ const pauseForPressure = () => {
7972
+ if (queuedBytes < 4 * 1024 * 1024) return;
7973
+ child.stdout.pause();
7974
+ child.stderr.pause();
7975
+ void uploadChain.finally(() => {
7976
+ child.stdout.resume();
7977
+ child.stderr.resume();
7978
+ });
7979
+ };
7980
+ child.stdout.on("data", (bytes) => {
7981
+ enqueue("STDOUT", bytes);
7982
+ pauseForPressure();
7867
7983
  });
7868
- };
7869
- attach(child.stdout, "STDOUT");
7870
- attach(child.stderr, "STDERR");
7871
- const sendSignal = (signal) => {
7872
- if (detached && child.pid) {
7984
+ child.stderr.on("data", (bytes) => {
7985
+ enqueue("STDERR", bytes);
7986
+ pauseForPressure();
7987
+ });
7988
+ const sendSignal = (name) => {
7989
+ if (child.exitCode !== null) return;
7873
7990
  try {
7874
- process.kill(-child.pid, signal);
7875
- return;
7991
+ if (process.platform !== "win32" && child.pid)
7992
+ process.kill(-child.pid, name);
7993
+ else child.kill(name);
7876
7994
  } catch (error) {
7877
7995
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH") {
7878
7996
  throw error;
7879
7997
  }
7880
7998
  }
7881
- }
7882
- child.kill(signal);
7883
- };
7884
- const terminate = () => {
7885
- if (child.exitCode !== null || child.killed) return;
7886
- sendSignal("SIGTERM");
7887
- const killTimer = setTimeout(() => sendSignal("SIGKILL"), 5e3);
7888
- killTimer.unref();
7889
- };
7890
- const timeout = setTimeout(() => {
7891
- timedOut = true;
7892
- emit(
7893
- "SYSTEM",
7894
- `Process exceeded its ${Math.round(options.timeoutMs / 1e3)} second timeout`
7895
- );
7896
- terminate();
7897
- }, options.timeoutMs);
7898
- timeout.unref();
7899
- const abort = () => {
7900
- cancelled = true;
7901
- emit("SYSTEM", "Cancellation requested");
7902
- terminate();
7903
- };
7904
- options.signal.addEventListener("abort", abort, { once: true });
7905
- child.once("error", (error) => {
7906
- if (settled) return;
7907
- settled = true;
7908
- clearTimeout(timeout);
7909
- options.signal.removeEventListener("abort", abort);
7910
- reject(error);
7911
- });
7912
- child.once("close", (exitCode, signal) => {
7913
- if (settled) return;
7914
- settled = true;
7915
- clearTimeout(timeout);
7916
- options.signal.removeEventListener("abort", abort);
7917
- void logChain.then(
7918
- () => resolve7({ exitCode, signal, timedOut, cancelled })
7919
- );
7999
+ };
8000
+ const abort = () => {
8001
+ if (cancelled) return;
8002
+ cancelled = true;
8003
+ enqueue("SYSTEM", Buffer.from("\r\nCancellation requested\r\n"));
8004
+ sendSignal("SIGTERM");
8005
+ const killTimer = setTimeout(() => sendSignal("SIGKILL"), 5e3);
8006
+ killTimer.unref();
8007
+ };
8008
+ signal.addEventListener("abort", abort, { once: true });
8009
+ if (signal.aborted) abort();
8010
+ child.once("error", (error) => {
8011
+ if (settled) return;
8012
+ settled = true;
8013
+ signal.removeEventListener("abort", abort);
8014
+ reject(error);
8015
+ });
8016
+ child.once("close", (exitCode, closeSignal) => {
8017
+ if (settled) return;
8018
+ settled = true;
8019
+ signal.removeEventListener("abort", abort);
8020
+ flush();
8021
+ void uploadChain.then(
8022
+ () => resolve7({
8023
+ exitCode,
8024
+ signal: closeSignal,
8025
+ timedOut: false,
8026
+ cancelled
8027
+ })
8028
+ );
8029
+ });
7920
8030
  });
7921
- });
7922
- }
7923
-
7924
- // src/handlers/cloudflared.ts
7925
- function validateCloudflaredPayload(payload) {
7926
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
7927
- throw new Error("Cloudflared payload must be an object");
7928
- }
7929
- const value = payload;
7930
- if (typeof value.tunnelName !== "string" || !TUNNEL_NAME_REGEX.test(value.tunnelName)) {
7931
- throw new Error("Invalid Cloudflared tunnel name");
7932
- }
7933
- if (Object.keys(value).some((key) => key !== "tunnelName")) {
7934
- throw new Error("Cloudflared payload contains an unsupported field");
8031
+ } finally {
8032
+ if (timer) clearTimeout(timer);
8033
+ await rm2(directory, { force: true, recursive: true });
7935
8034
  }
7936
- return { tunnelName: value.tunnelName };
7937
- }
7938
- function runCloudflared(payload, timeoutMs, signal, onLog) {
7939
- const { tunnelName } = validateCloudflaredPayload(payload);
7940
- return runProcess({
7941
- command: "cloudflared",
7942
- args: ["tunnel", "run", tunnelName],
7943
- timeoutMs,
7944
- signal,
7945
- onLog
7946
- });
7947
- }
8035
+ };
7948
8036
 
7949
8037
  // src/handlers/signing.ts
7950
8038
  import { createHash as createHash3, randomUUID, X509Certificate } from "node:crypto";
7951
8039
  import {
7952
8040
  mkdir as mkdir2,
7953
- mkdtemp,
8041
+ mkdtemp as mkdtemp2,
7954
8042
  readFile as readFile2,
7955
8043
  readdir,
7956
- rm as rm2,
8044
+ rm as rm3,
7957
8045
  stat as stat2,
7958
- writeFile as writeFile2
8046
+ writeFile as writeFile3
7959
8047
  } from "node:fs/promises";
7960
- import { homedir as homedir2, tmpdir } from "node:os";
7961
- import { basename, join as join2, relative, sep } from "node:path";
8048
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "node:os";
8049
+ import { basename, join as join3, relative, sep } from "node:path";
7962
8050
 
7963
8051
  // ../agent-contract/src/plist.ts
7964
8052
  function xmlEscape(value) {
@@ -8193,15 +8281,15 @@ function captureCommand(options) {
8193
8281
 
8194
8282
  // src/handlers/signing.ts
8195
8283
  var PROFILE_DIRECTORIES = [
8196
- join2(
8197
- homedir2(),
8284
+ join3(
8285
+ homedir3(),
8198
8286
  "Library",
8199
8287
  "Developer",
8200
8288
  "Xcode",
8201
8289
  "UserData",
8202
8290
  "Provisioning Profiles"
8203
8291
  ),
8204
- join2(homedir2(), "Library", "MobileDevice", "Provisioning Profiles")
8292
+ join3(homedir3(), "Library", "MobileDevice", "Provisioning Profiles")
8205
8293
  ];
8206
8294
  var PROFILE_EXTENSIONS = [".mobileprovision", ".provisionprofile"];
8207
8295
  function text(value) {
@@ -8294,7 +8382,7 @@ async function readProfiles(timeoutMs, signal) {
8294
8382
  continue;
8295
8383
  signal.throwIfAborted();
8296
8384
  const raw = await decodeProfile(
8297
- join2(directory, entry),
8385
+ join3(directory, entry),
8298
8386
  timeoutMs,
8299
8387
  signal
8300
8388
  );
@@ -8328,7 +8416,7 @@ async function decodedProfiles(timeoutMs, signal, strict = false) {
8328
8416
  continue;
8329
8417
  }
8330
8418
  signal.throwIfAborted();
8331
- const path = join2(directory, entry);
8419
+ const path = join3(directory, entry);
8332
8420
  const raw = await decodeProfile(path, timeoutMs, signal, strict);
8333
8421
  if (!raw) continue;
8334
8422
  let content;
@@ -8484,7 +8572,7 @@ async function readCertificates(timeoutMs, signal, strict = false) {
8484
8572
  );
8485
8573
  }
8486
8574
  async function readArchiveBundles(archivePath, timeoutMs, signal) {
8487
- const products = join2(archivePath, "Products");
8575
+ const products = join3(archivePath, "Products");
8488
8576
  const bundles = [];
8489
8577
  const queue = [products];
8490
8578
  while (queue.length) {
@@ -8498,7 +8586,7 @@ async function readArchiveBundles(archivePath, timeoutMs, signal) {
8498
8586
  }
8499
8587
  for (const entry of entries) {
8500
8588
  if (entry.isSymbolicLink() || !entry.isDirectory()) continue;
8501
- const path = join2(current, entry.name);
8589
+ const path = join3(current, entry.name);
8502
8590
  const signable = /\.(app|appex)$/.test(entry.name);
8503
8591
  if (!signable) {
8504
8592
  if (!/\.[A-Za-z0-9]+$/.test(entry.name)) queue.push(path);
@@ -8530,7 +8618,7 @@ async function bundleIdentifier(bundlePath, timeoutMs, signal) {
8530
8618
  "raw",
8531
8619
  "-o",
8532
8620
  "-",
8533
- join2(bundlePath, "Info.plist")
8621
+ join3(bundlePath, "Info.plist")
8534
8622
  ],
8535
8623
  timeoutMs: Math.min(timeoutMs, 5e3),
8536
8624
  signal
@@ -8546,7 +8634,7 @@ async function embeddedProfile(bundlePath, timeoutMs, signal) {
8546
8634
  "embedded.mobileprovision",
8547
8635
  "embedded.provisionprofile"
8548
8636
  ]) {
8549
- const path = join2(bundlePath, name);
8637
+ const path = join3(bundlePath, name);
8550
8638
  try {
8551
8639
  await stat2(path);
8552
8640
  } catch {
@@ -8593,7 +8681,7 @@ async function inspectSigningAssets(archivePath, timeoutMs, signal) {
8593
8681
  }
8594
8682
  var inspectIosSigning = async (payload, timeoutMs, signal) => {
8595
8683
  const input = parseBuildSigningInspectPayload(payload);
8596
- const archivePath = join2(input.artifactDirectory, input.archiveRelativePath);
8684
+ const archivePath = join3(input.artifactDirectory, input.archiveRelativePath);
8597
8685
  const inspection = await inspectSigningAssets(archivePath, timeoutMs, signal);
8598
8686
  return {
8599
8687
  exitCode: 0,
@@ -8655,21 +8743,21 @@ var installSigningProfile = async (payload, timeoutMs, signal) => {
8655
8743
  const { contentBase64 } = signingProfileInstallPayload(payload);
8656
8744
  const content = Buffer.from(contentBase64, "base64");
8657
8745
  if (!content.length) throw new Error("Provisioning profile is empty");
8658
- const temporaryRoot = await mkdtemp(join2(tmpdir(), "ade-profile-"));
8659
- const temporaryPath = join2(temporaryRoot, `${randomUUID()}.mobileprovision`);
8746
+ const temporaryRoot = await mkdtemp2(join3(tmpdir2(), "ade-profile-"));
8747
+ const temporaryPath = join3(temporaryRoot, `${randomUUID()}.mobileprovision`);
8660
8748
  try {
8661
- await writeFile2(temporaryPath, content, { mode: 384 });
8749
+ await writeFile3(temporaryPath, content, { mode: 384 });
8662
8750
  const raw = await decodeProfile(temporaryPath, timeoutMs, signal);
8663
8751
  if (!raw) throw new Error("Provisioning profile is invalid or unsigned");
8664
8752
  const uuid = text(raw.UUID);
8665
8753
  if (!uuid) throw new Error("Provisioning profile UUID is missing");
8666
8754
  const directory = PROFILE_DIRECTORIES[0];
8667
8755
  await mkdir2(directory, { recursive: true, mode: 448 });
8668
- const destination = join2(directory, `${uuid}.mobileprovision`);
8669
- await writeFile2(destination, content, { mode: 384 });
8756
+ const destination = join3(directory, `${uuid}.mobileprovision`);
8757
+ await writeFile3(destination, content, { mode: 384 });
8670
8758
  return { ...successfulProcess, uuid };
8671
8759
  } finally {
8672
- await rm2(temporaryRoot, { recursive: true, force: true });
8760
+ await rm3(temporaryRoot, { recursive: true, force: true });
8673
8761
  }
8674
8762
  };
8675
8763
  var deleteSigningProfile = async (payload, timeoutMs, signal) => {
@@ -8679,7 +8767,7 @@ var deleteSigningProfile = async (payload, timeoutMs, signal) => {
8679
8767
  );
8680
8768
  for (const profile of matches) {
8681
8769
  signal.throwIfAborted();
8682
- await rm2(profile.path, { force: false });
8770
+ await rm3(profile.path, { force: false });
8683
8771
  }
8684
8772
  return { ...successfulProcess, uuid, deleted: matches.length };
8685
8773
  };
@@ -8693,10 +8781,10 @@ var importSigningIdentity = async (payload, timeoutMs, signal, _onLog, context)
8693
8781
  const hash = createHash3("sha256").update(p12).digest("hex").toUpperCase();
8694
8782
  if (hash !== input.sha256)
8695
8783
  throw new Error("Signing identity transfer changed");
8696
- const temporaryRoot = await mkdtemp(join2(tmpdir(), "ade-identity-"));
8697
- const path = join2(temporaryRoot, "identity.p12");
8784
+ const temporaryRoot = await mkdtemp2(join3(tmpdir2(), "ade-identity-"));
8785
+ const path = join3(temporaryRoot, "identity.p12");
8698
8786
  try {
8699
- await writeFile2(path, p12, { mode: 384 });
8787
+ await writeFile3(path, p12, { mode: 384 });
8700
8788
  const result = await captureCommand({
8701
8789
  command: "/usr/bin/security",
8702
8790
  args: [
@@ -8719,7 +8807,7 @@ var importSigningIdentity = async (payload, timeoutMs, signal, _onLog, context)
8719
8807
  }
8720
8808
  return { ...successfulProcess, sha256: input.sha256 };
8721
8809
  } finally {
8722
- await rm2(temporaryRoot, { recursive: true, force: true });
8810
+ await rm3(temporaryRoot, { recursive: true, force: true });
8723
8811
  }
8724
8812
  };
8725
8813
  var deleteSigningIdentity = async (payload, timeoutMs, signal) => {
@@ -8740,6 +8828,112 @@ var deleteSigningIdentity = async (payload, timeoutMs, signal) => {
8740
8828
 
8741
8829
  // src/handlers/ccusage.ts
8742
8830
  import { Buffer as Buffer2 } from "node:buffer";
8831
+
8832
+ // src/process-runner.ts
8833
+ import { spawn as spawn3 } from "node:child_process";
8834
+ async function runProcess(options) {
8835
+ return new Promise((resolve7, reject) => {
8836
+ let sequence = 0;
8837
+ let timedOut = false;
8838
+ let cancelled = false;
8839
+ let settled = false;
8840
+ let logChain = Promise.resolve();
8841
+ const detached = process.platform !== "win32";
8842
+ const child = spawn3(options.command, options.args, {
8843
+ shell: false,
8844
+ stdio: ["ignore", "pipe", "pipe"],
8845
+ cwd: options.cwd,
8846
+ env: options.env ?? process.env,
8847
+ // A separate process group lets cancellation terminate scripts and all
8848
+ // descendants instead of leaving a child holding stdout/stderr open.
8849
+ detached
8850
+ });
8851
+ const emit = (stream, message) => {
8852
+ const log = {
8853
+ sequence: sequence++,
8854
+ stream,
8855
+ message,
8856
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
8857
+ };
8858
+ logChain = logChain.then(async () => {
8859
+ try {
8860
+ await options.onLog(log);
8861
+ } catch (error) {
8862
+ console.error(
8863
+ `Could not append process log ${log.sequence}:`,
8864
+ error instanceof Error ? error.message : error
8865
+ );
8866
+ }
8867
+ });
8868
+ };
8869
+ const attach = (stream, kind) => {
8870
+ let remainder = "";
8871
+ stream.setEncoding("utf8");
8872
+ stream.on("data", (chunk) => {
8873
+ const parts = `${remainder}${chunk}`.split(/\r?\n/);
8874
+ remainder = parts.pop() ?? "";
8875
+ for (const line of parts) emit(kind, line);
8876
+ });
8877
+ stream.on("end", () => {
8878
+ if (remainder) emit(kind, remainder);
8879
+ });
8880
+ };
8881
+ attach(child.stdout, "STDOUT");
8882
+ attach(child.stderr, "STDERR");
8883
+ const sendSignal = (signal) => {
8884
+ if (detached && child.pid) {
8885
+ try {
8886
+ process.kill(-child.pid, signal);
8887
+ return;
8888
+ } catch (error) {
8889
+ if (!(error instanceof Error) || !("code" in error) || error.code !== "ESRCH") {
8890
+ throw error;
8891
+ }
8892
+ }
8893
+ }
8894
+ child.kill(signal);
8895
+ };
8896
+ const terminate = () => {
8897
+ if (child.exitCode !== null || child.killed) return;
8898
+ sendSignal("SIGTERM");
8899
+ const killTimer = setTimeout(() => sendSignal("SIGKILL"), 5e3);
8900
+ killTimer.unref();
8901
+ };
8902
+ const timeout = setTimeout(() => {
8903
+ timedOut = true;
8904
+ emit(
8905
+ "SYSTEM",
8906
+ `Process exceeded its ${Math.round(options.timeoutMs / 1e3)} second timeout`
8907
+ );
8908
+ terminate();
8909
+ }, options.timeoutMs);
8910
+ timeout.unref();
8911
+ const abort = () => {
8912
+ cancelled = true;
8913
+ emit("SYSTEM", "Cancellation requested");
8914
+ terminate();
8915
+ };
8916
+ options.signal.addEventListener("abort", abort, { once: true });
8917
+ child.once("error", (error) => {
8918
+ if (settled) return;
8919
+ settled = true;
8920
+ clearTimeout(timeout);
8921
+ options.signal.removeEventListener("abort", abort);
8922
+ reject(error);
8923
+ });
8924
+ child.once("close", (exitCode, signal) => {
8925
+ if (settled) return;
8926
+ settled = true;
8927
+ clearTimeout(timeout);
8928
+ options.signal.removeEventListener("abort", abort);
8929
+ void logChain.then(
8930
+ () => resolve7({ exitCode, signal, timedOut, cancelled })
8931
+ );
8932
+ });
8933
+ });
8934
+ }
8935
+
8936
+ // src/handlers/ccusage.ts
8743
8937
  var MAX_CCUSAGE_STDOUT_BYTES = 16 * 1024 * 1024;
8744
8938
  function validateCcusagePayload(payload) {
8745
8939
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
@@ -8793,9 +8987,9 @@ async function runCcusage(payload, timeoutMs, signal, onLog) {
8793
8987
  }
8794
8988
 
8795
8989
  // src/handlers/build-data.ts
8796
- import { lstat, opendir, readdir as readdir2, realpath, rm as rm3 } from "node:fs/promises";
8797
- import { homedir as homedir3 } from "node:os";
8798
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join3, resolve } from "node:path";
8990
+ import { lstat, opendir, readdir as readdir2, realpath as realpath2, rm as rm4 } from "node:fs/promises";
8991
+ import { homedir as homedir4 } from "node:os";
8992
+ import { basename as basename2, dirname as dirname2, isAbsolute, join as join4, resolve } from "node:path";
8799
8993
  var successfulProcess2 = {
8800
8994
  exitCode: 0,
8801
8995
  signal: null,
@@ -8812,7 +9006,7 @@ function safeRelativePath3(value) {
8812
9006
  }
8813
9007
  async function configuredRoots(payload) {
8814
9008
  if (payload.mode === "DEFAULT") {
8815
- return [join3(homedir3(), "Library", "Developer", "Xcode", "DerivedData")];
9009
+ return [join4(homedir4(), "Library", "Developer", "Xcode", "DerivedData")];
8816
9010
  }
8817
9011
  if (payload.mode === "ABSOLUTE") {
8818
9012
  if (!payload.path || !isAbsolute(payload.path)) {
@@ -8849,7 +9043,7 @@ async function scanRoot(configuredRoot, timeoutMs, signal) {
8849
9043
  signal.throwIfAborted();
8850
9044
  let rootPath2;
8851
9045
  try {
8852
- rootPath2 = await realpath(configuredRoot);
9046
+ rootPath2 = await realpath2(configuredRoot);
8853
9047
  } catch (error) {
8854
9048
  if (error.code === "ENOENT") {
8855
9049
  return { entries: [], warning: null };
@@ -8872,9 +9066,9 @@ async function scanRoot(configuredRoot, timeoutMs, signal) {
8872
9066
  for (const child of children) {
8873
9067
  signal.throwIfAborted();
8874
9068
  if (!child.isDirectory()) continue;
8875
- const path = join3(rootPath2, child.name);
9069
+ const path = join4(rootPath2, child.name);
8876
9070
  const projectPath = await workspacePath(
8877
- join3(path, "info.plist"),
9071
+ join4(path, "info.plist"),
8878
9072
  timeoutMs,
8879
9073
  signal
8880
9074
  );
@@ -8890,14 +9084,14 @@ async function scanRoot(configuredRoot, timeoutMs, signal) {
8890
9084
  return { entries, warning: null };
8891
9085
  }
8892
9086
  async function scanDeviceSupport(signal) {
8893
- const configuredRoot = join3(
8894
- process.env.ADE_IOS_DEVICE_SUPPORT_DIRECTORY ?? homedir3(),
9087
+ const configuredRoot = join4(
9088
+ process.env.ADE_IOS_DEVICE_SUPPORT_DIRECTORY ?? homedir4(),
8895
9089
  ...process.env.ADE_IOS_DEVICE_SUPPORT_DIRECTORY ? [] : ["Library", "Developer", "Xcode", "iOS DeviceSupport"]
8896
9090
  );
8897
9091
  signal.throwIfAborted();
8898
9092
  let rootPath2;
8899
9093
  try {
8900
- rootPath2 = await realpath(configuredRoot);
9094
+ rootPath2 = await realpath2(configuredRoot);
8901
9095
  } catch (error) {
8902
9096
  if (error.code === "ENOENT") {
8903
9097
  return { entries: [], warning: null };
@@ -8911,7 +9105,7 @@ async function scanDeviceSupport(signal) {
8911
9105
  const children = await readdir2(rootPath2, { withFileTypes: true });
8912
9106
  return {
8913
9107
  entries: children.filter((child) => child.isDirectory() && !child.isSymbolicLink()).map((child) => ({
8914
- path: join3(rootPath2, child.name),
9108
+ path: join4(rootPath2, child.name),
8915
9109
  rootPath: rootPath2,
8916
9110
  name: child.name,
8917
9111
  kind: "DEVICE_SUPPORT",
@@ -8936,7 +9130,7 @@ var scanBuildData = async (rawPayload, timeoutMs, signal) => {
8936
9130
  signal.throwIfAborted();
8937
9131
  let canonical = root;
8938
9132
  try {
8939
- canonical = await realpath(root);
9133
+ canonical = await realpath2(root);
8940
9134
  } catch {
8941
9135
  }
8942
9136
  if (canonicalRoots.has(canonical)) continue;
@@ -8970,7 +9164,7 @@ async function allocatedBytes(path, signal) {
8970
9164
  try {
8971
9165
  for await (const entry of directory) {
8972
9166
  signal.throwIfAborted();
8973
- total += await allocatedBytes(join3(path, entry.name), signal);
9167
+ total += await allocatedBytes(join4(path, entry.name), signal);
8974
9168
  }
8975
9169
  } finally {
8976
9170
  await directory.close().catch(() => void 0);
@@ -8984,7 +9178,7 @@ var sizeBuildData = async (rawPayload, _timeoutMs, signal) => {
8984
9178
  signal.throwIfAborted();
8985
9179
  try {
8986
9180
  assertDirectChild(target2.rootPath, target2.path);
8987
- const rootPath2 = await realpath(target2.rootPath);
9181
+ const rootPath2 = await realpath2(target2.rootPath);
8988
9182
  if (rootPath2 !== resolve(target2.rootPath) || dirname2(resolve(target2.path)) !== rootPath2) {
8989
9183
  throw new Error("Build Data root changed since the scan");
8990
9184
  }
@@ -9015,7 +9209,7 @@ var deleteBuildData = async (rawPayload, _timeoutMs, signal) => {
9015
9209
  signal.throwIfAborted();
9016
9210
  try {
9017
9211
  assertDirectChild(target2.rootPath, target2.path);
9018
- const rootPath2 = await realpath(target2.rootPath);
9212
+ const rootPath2 = await realpath2(target2.rootPath);
9019
9213
  if (rootPath2 !== resolve(target2.rootPath) || dirname2(resolve(target2.path)) !== rootPath2) {
9020
9214
  throw new Error("Build Data root changed since the scan");
9021
9215
  }
@@ -9023,7 +9217,7 @@ var deleteBuildData = async (rawPayload, _timeoutMs, signal) => {
9023
9217
  if (!stats.isDirectory() || stats.isSymbolicLink()) {
9024
9218
  throw new Error("Build Data target is not a directory");
9025
9219
  }
9026
- await rm3(target2.path, { recursive: true, force: false, maxRetries: 3 });
9220
+ await rm4(target2.path, { recursive: true, force: false, maxRetries: 3 });
9027
9221
  deleted.push({ path: target2.path, deleted: true, error: null });
9028
9222
  } catch (error) {
9029
9223
  signal.throwIfAborted();
@@ -9038,9 +9232,9 @@ var deleteBuildData = async (rawPayload, _timeoutMs, signal) => {
9038
9232
  };
9039
9233
 
9040
9234
  // src/handlers/codebases.ts
9041
- import { readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
9042
- import { homedir as homedir4 } from "node:os";
9043
- import { dirname as dirname3, join as join4, resolve as resolve2 } from "node:path";
9235
+ import { readdir as readdir3, realpath as realpath3, stat as stat3 } from "node:fs/promises";
9236
+ import { homedir as homedir5 } from "node:os";
9237
+ import { dirname as dirname3, join as join5, resolve as resolve2 } from "node:path";
9044
9238
  var successfulProcess3 = {
9045
9239
  exitCode: 0,
9046
9240
  signal: null,
@@ -9117,7 +9311,7 @@ function baseSnapshot(folder) {
9117
9311
  }
9118
9312
  async function fetchedAt(commonDirectory) {
9119
9313
  try {
9120
- return (await stat3(join4(commonDirectory, "FETCH_HEAD"))).mtime.toISOString();
9314
+ return (await stat3(join5(commonDirectory, "FETCH_HEAD"))).mtime.toISOString();
9121
9315
  } catch {
9122
9316
  return null;
9123
9317
  }
@@ -9127,7 +9321,7 @@ async function inspectCodebaseProcess(selectedFolder, timeoutMs, signal, expecte
9127
9321
  const base = baseSnapshot(fallbackFolder);
9128
9322
  let selected;
9129
9323
  try {
9130
- selected = await realpath2(fallbackFolder);
9324
+ selected = await realpath3(fallbackFolder);
9131
9325
  if (!(await stat3(selected)).isDirectory())
9132
9326
  throw new Error("Folder is not a directory");
9133
9327
  } catch (error) {
@@ -9160,7 +9354,7 @@ async function inspectCodebaseProcess(selectedFolder, timeoutMs, signal, expecte
9160
9354
  }
9161
9355
  };
9162
9356
  }
9163
- const folder = await realpath2(rootResult.stdout.trim());
9357
+ const folder = await realpath3(rootResult.stdout.trim());
9164
9358
  const bare = await git(
9165
9359
  folder,
9166
9360
  ["rev-parse", "--is-bare-repository"],
@@ -9211,8 +9405,8 @@ async function inspectCodebaseProcess(selectedFolder, timeoutMs, signal, expecte
9211
9405
  };
9212
9406
  }
9213
9407
  const origin2 = normalizeGitOrigin(originResult.stdout.trim());
9214
- const gitDirectory2 = await realpath2(gitDirectoryResult.stdout.trim());
9215
- const commonDirectory = await realpath2(commonDirectoryResult.stdout.trim());
9408
+ const gitDirectory2 = await realpath3(gitDirectoryResult.stdout.trim());
9409
+ const commonDirectory = await realpath3(commonDirectoryResult.stdout.trim());
9216
9410
  const linkedWorktree = gitDirectory2 !== commonDirectory;
9217
9411
  const branchResult = await git(
9218
9412
  folder,
@@ -9296,8 +9490,8 @@ async function inspectCodebase(selectedFolder, timeoutMs, signal, expectedOrigin
9296
9490
  }
9297
9491
  var browseCodebaseDirectories = async (payload) => {
9298
9492
  const input = codebaseBrowsePayload(payload);
9299
- const homePath = await realpath2(homedir4());
9300
- const path = await realpath2(input.path ? resolve2(input.path) : homePath);
9493
+ const homePath = await realpath3(homedir5());
9494
+ const path = await realpath3(input.path ? resolve2(input.path) : homePath);
9301
9495
  if (!(await stat3(path)).isDirectory())
9302
9496
  throw new Error("Path is not a directory");
9303
9497
  const candidates = await readdir3(path, { withFileTypes: true });
@@ -9306,12 +9500,12 @@ var browseCodebaseDirectories = async (payload) => {
9306
9500
  if (candidate.isDirectory()) {
9307
9501
  entries.push({
9308
9502
  name: candidate.name,
9309
- path: join4(path, candidate.name),
9503
+ path: join5(path, candidate.name),
9310
9504
  hidden: candidate.name.startsWith(".")
9311
9505
  });
9312
9506
  } else if (candidate.isSymbolicLink()) {
9313
9507
  try {
9314
- const target2 = join4(path, candidate.name);
9508
+ const target2 = join5(path, candidate.name);
9315
9509
  if ((await stat3(target2)).isDirectory()) {
9316
9510
  entries.push({
9317
9511
  name: candidate.name,
@@ -9913,19 +10107,19 @@ import { execFile } from "node:child_process";
9913
10107
  import { randomUUID as randomUUID2 } from "node:crypto";
9914
10108
  import {
9915
10109
  access,
9916
- chmod as chmod2,
10110
+ chmod as chmod3,
9917
10111
  lstat as lstat2,
9918
10112
  mkdir as mkdir3,
9919
10113
  readFile as readFile3,
9920
- realpath as realpath3,
10114
+ realpath as realpath4,
9921
10115
  readdir as readdir4,
9922
10116
  rename as rename2,
9923
- rm as rm4,
10117
+ rm as rm5,
9924
10118
  stat as stat4,
9925
- writeFile as writeFile3
10119
+ writeFile as writeFile4
9926
10120
  } from "node:fs/promises";
9927
- import { homedir as homedir5 } from "node:os";
9928
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
10121
+ import { homedir as homedir6 } from "node:os";
10122
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join6, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
9929
10123
  import { promisify } from "node:util";
9930
10124
  var executeFile = promisify(execFile);
9931
10125
  var successfulProcess4 = {
@@ -9986,17 +10180,17 @@ async function directoryExists(path) {
9986
10180
  }
9987
10181
  }
9988
10182
  async function configuredTools(tools) {
9989
- const homePath = homedir5();
10183
+ const homePath = homedir6();
9990
10184
  return Promise.all(
9991
10185
  AI_TOOLS.filter((tool) => tools.includes(tool)).map(async (tool) => ({
9992
10186
  tool,
9993
- configured: await directoryExists(join5(homePath, ...CONFIG_PATHS[tool])),
10187
+ configured: await directoryExists(join6(homePath, ...CONFIG_PATHS[tool])),
9994
10188
  homePath
9995
10189
  }))
9996
10190
  );
9997
10191
  }
9998
10192
  function rootPath(location) {
9999
- const base = location.scope === "GLOBAL" ? homedir5() : location.folder;
10193
+ const base = location.scope === "GLOBAL" ? homedir6() : location.folder;
10000
10194
  const parts = location.scope === "GLOBAL" ? GLOBAL_ROOTS[location.rootKind] : PROJECT_ROOTS[location.rootKind];
10001
10195
  const path = resolve3(base, ...parts);
10002
10196
  const normalizedBase = resolve3(base);
@@ -10013,7 +10207,7 @@ async function listPackageFiles(skillDirectory) {
10013
10207
  let totalBytes = 0;
10014
10208
  const visit = async (directory) => {
10015
10209
  for (const entry of await readdir4(directory, { withFileTypes: true })) {
10016
- const path = join5(directory, entry.name);
10210
+ const path = join6(directory, entry.name);
10017
10211
  const metadata = await lstat2(path);
10018
10212
  if (metadata.isSymbolicLink()) {
10019
10213
  throw new Error(
@@ -10049,7 +10243,7 @@ async function readPackage(directory) {
10049
10243
  const metadata = await lstat2(directory);
10050
10244
  let resolvedDirectory = directory;
10051
10245
  if (metadata.isSymbolicLink()) {
10052
- resolvedDirectory = await realpath3(directory);
10246
+ resolvedDirectory = await realpath4(directory);
10053
10247
  } else if (!metadata.isDirectory()) {
10054
10248
  throw new Error("Skill path is not a directory");
10055
10249
  }
@@ -10102,7 +10296,7 @@ async function scanRoot2(location, configured, targets, warnings) {
10102
10296
  const installations = [];
10103
10297
  for (const entry of await readdir4(root, { withFileTypes: true })) {
10104
10298
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
10105
- const directory = join5(root, entry.name);
10299
+ const directory = join6(root, entry.name);
10106
10300
  try {
10107
10301
  const skillPackage = await readPackage(directory);
10108
10302
  const relativeDirectory = location.folder ? relative2(location.folder, directory).split(sep2).join("/") : "";
@@ -10181,7 +10375,7 @@ var readSkills = async (payload) => {
10181
10375
  }
10182
10376
  packages.push({
10183
10377
  ...request,
10184
- package: await readPackage(join5(root, request.skillName))
10378
+ package: await readPackage(join6(root, request.skillName))
10185
10379
  });
10186
10380
  }
10187
10381
  return { ...successfulProcess4, packages };
@@ -10222,7 +10416,7 @@ async function updateManagedExclude(folder, relativeSkillPath, present) {
10222
10416
  const block = managed.size ? `${MANAGED_EXCLUDE_START}
10223
10417
  ${[...managed].sort().join("\n")}
10224
10418
  ${MANAGED_EXCLUDE_END}` : "";
10225
- await writeFile3(
10419
+ await writeFile4(
10226
10420
  excludePath,
10227
10421
  `${[before, block, after].filter(Boolean).join("\n\n")}
10228
10422
  `,
@@ -10243,11 +10437,11 @@ async function writePackage(location, skillPackage) {
10243
10437
  throw new Error("New skill copies may only be written to shared roots");
10244
10438
  }
10245
10439
  const root = rootPath(location);
10246
- const destination = join5(root, skillPackage.name);
10440
+ const destination = join6(root, skillPackage.name);
10247
10441
  await assertUntracked(location, destination);
10248
10442
  await mkdir3(root, { recursive: true });
10249
- const temporary = join5(root, `.${skillPackage.name}.${randomUUID2()}.tmp`);
10250
- const backup = join5(root, `.${skillPackage.name}.${randomUUID2()}.bak`);
10443
+ const temporary = join6(root, `.${skillPackage.name}.${randomUUID2()}.tmp`);
10444
+ const backup = join6(root, `.${skillPackage.name}.${randomUUID2()}.bak`);
10251
10445
  await mkdir3(temporary, { recursive: true });
10252
10446
  try {
10253
10447
  for (const file of skillPackage.files) {
@@ -10255,8 +10449,8 @@ async function writePackage(location, skillPackage) {
10255
10449
  if (!path.startsWith(`${temporary}${sep2}`))
10256
10450
  throw new Error("Skill file escaped temporary directory");
10257
10451
  await mkdir3(dirname4(path), { recursive: true });
10258
- await writeFile3(path, Buffer.from(file.contentsBase64, "base64"));
10259
- await chmod2(path, file.executable ? 493 : 420);
10452
+ await writeFile4(path, Buffer.from(file.contentsBase64, "base64"));
10453
+ await chmod3(path, file.executable ? 493 : 420);
10260
10454
  }
10261
10455
  let hadDestination = false;
10262
10456
  try {
@@ -10268,14 +10462,14 @@ async function writePackage(location, skillPackage) {
10268
10462
  }
10269
10463
  try {
10270
10464
  await rename2(temporary, destination);
10271
- if (hadDestination) await rm4(backup, { recursive: true, force: true });
10465
+ if (hadDestination) await rm5(backup, { recursive: true, force: true });
10272
10466
  } catch (error) {
10273
10467
  if (hadDestination) await rename2(backup, destination);
10274
10468
  throw error;
10275
10469
  }
10276
10470
  } finally {
10277
- await rm4(temporary, { recursive: true, force: true });
10278
- await rm4(backup, { recursive: true, force: true });
10471
+ await rm5(temporary, { recursive: true, force: true });
10472
+ await rm5(backup, { recursive: true, force: true });
10279
10473
  }
10280
10474
  return destination;
10281
10475
  }
@@ -10285,7 +10479,7 @@ var applySkills = async (payload) => {
10285
10479
  for (const operation of operations) {
10286
10480
  const root = rootPath(operation);
10287
10481
  const skillName = operation.kind === "WRITE" ? operation.package.name : operation.skillName;
10288
- const destination = join5(root, skillName);
10482
+ const destination = join6(root, skillName);
10289
10483
  await assertUntracked(operation, destination);
10290
10484
  if (operation.kind === "WRITE") {
10291
10485
  await writePackage(operation, operation.package);
@@ -10295,7 +10489,7 @@ var applySkills = async (payload) => {
10295
10489
  packageHash: operation.package.packageHash
10296
10490
  });
10297
10491
  } else {
10298
- await rm4(destination, { recursive: true, force: true });
10492
+ await rm5(destination, { recursive: true, force: true });
10299
10493
  results.push({
10300
10494
  kind: operation.kind,
10301
10495
  path: destination,
@@ -10315,8 +10509,8 @@ var applySkills = async (payload) => {
10315
10509
 
10316
10510
  // src/handlers/runs.ts
10317
10511
  import { readFile as readFile4, readdir as readdir5, stat as stat5 } from "node:fs/promises";
10318
- import { homedir as homedir6 } from "node:os";
10319
- import { join as join6 } from "node:path";
10512
+ import { homedir as homedir7 } from "node:os";
10513
+ import { join as join7 } from "node:path";
10320
10514
  var successfulProcess5 = {
10321
10515
  exitCode: 0,
10322
10516
  signal: null,
@@ -10331,7 +10525,7 @@ async function fileExists(path) {
10331
10525
  }
10332
10526
  }
10333
10527
  async function findClaudeSessionFile(nativeId, home) {
10334
- const projectsDir = join6(home, ".claude", "projects");
10528
+ const projectsDir = join7(home, ".claude", "projects");
10335
10529
  let entries;
10336
10530
  try {
10337
10531
  entries = await readdir5(projectsDir, { withFileTypes: true });
@@ -10341,13 +10535,13 @@ async function findClaudeSessionFile(nativeId, home) {
10341
10535
  const target2 = `${nativeId}.jsonl`;
10342
10536
  for (const entry of entries) {
10343
10537
  if (!entry.isDirectory()) continue;
10344
- const candidate = join6(projectsDir, entry.name, target2);
10538
+ const candidate = join7(projectsDir, entry.name, target2);
10345
10539
  if (await fileExists(candidate)) return candidate;
10346
10540
  }
10347
10541
  return null;
10348
10542
  }
10349
10543
  async function findCodexSessionFile(nativeId, home) {
10350
- const sessionsDir = join6(home, ".codex", "sessions");
10544
+ const sessionsDir = join7(home, ".codex", "sessions");
10351
10545
  const suffix = `-${nativeId}.jsonl`;
10352
10546
  const walk = async (dir) => {
10353
10547
  let entries;
@@ -10357,7 +10551,7 @@ async function findCodexSessionFile(nativeId, home) {
10357
10551
  return null;
10358
10552
  }
10359
10553
  for (const entry of entries) {
10360
- const path = join6(dir, entry.name);
10554
+ const path = join7(dir, entry.name);
10361
10555
  if (entry.isDirectory()) {
10362
10556
  const found = await walk(path);
10363
10557
  if (found) return found;
@@ -10374,7 +10568,7 @@ async function locateSessionFile(payload, home) {
10374
10568
  }
10375
10569
  var readRunSession = async (payload) => {
10376
10570
  const input = parseRunSessionReadPayload(payload);
10377
- const path = await locateSessionFile(input, homedir6());
10571
+ const path = await locateSessionFile(input, homedir7());
10378
10572
  if (!path) {
10379
10573
  throw new Error(
10380
10574
  `No ${input.provider === "CLAUDE" ? "Claude" : "Codex"} session file found for this run on this agent`
@@ -10396,21 +10590,21 @@ var readRunSession = async (payload) => {
10396
10590
 
10397
10591
  // src/handlers/workflows.ts
10398
10592
  import {
10399
- mkdtemp as mkdtemp4,
10593
+ mkdtemp as mkdtemp5,
10400
10594
  readFile as readFile6,
10401
- realpath as realpath5,
10402
- rm as rm7,
10595
+ realpath as realpath6,
10596
+ rm as rm8,
10403
10597
  stat as stat7,
10404
- writeFile as writeFile5
10598
+ writeFile as writeFile6
10405
10599
  } from "node:fs/promises";
10406
- import { tmpdir as tmpdir4 } from "node:os";
10407
- import { join as join9 } from "node:path";
10600
+ import { tmpdir as tmpdir5 } from "node:os";
10601
+ import { join as join10 } from "node:path";
10408
10602
 
10409
10603
  // src/runs/git-checkpoint.ts
10410
10604
  import { execFile as execFile2 } from "node:child_process";
10411
- import { copyFile, mkdtemp as mkdtemp2, rm as rm5 } from "node:fs/promises";
10412
- import { tmpdir as tmpdir2 } from "node:os";
10413
- import { join as join7 } from "node:path";
10605
+ import { copyFile, mkdtemp as mkdtemp3, rm as rm6 } from "node:fs/promises";
10606
+ import { tmpdir as tmpdir3 } from "node:os";
10607
+ import { join as join8 } from "node:path";
10414
10608
  import { promisify as promisify2 } from "node:util";
10415
10609
  var execFileAsync = promisify2(execFile2);
10416
10610
  async function git2(cwd, args, env) {
@@ -10525,12 +10719,12 @@ async function captureGitCheckpoint(cwd, runId, kind) {
10525
10719
  const manifest = await optionalGit(cwd, ["status", "--porcelain=v2", "-z"]);
10526
10720
  const staged = await optionalGit(cwd, ["diff", "--cached", "--stat", "HEAD"]);
10527
10721
  const unstaged = await optionalGit(cwd, ["diff", "--stat", "HEAD"]);
10528
- const directory = await mkdtemp2(join7(tmpdir2(), "aide-run-index-"));
10722
+ const directory = await mkdtemp3(join8(tmpdir3(), "aide-run-index-"));
10529
10723
  let worktreeTree = null;
10530
10724
  let refName = null;
10531
10725
  try {
10532
10726
  const actualIndex = await git2(cwd, ["rev-parse", "--git-path", "index"]);
10533
- const temporaryIndex = join7(directory, "index");
10727
+ const temporaryIndex = join8(directory, "index");
10534
10728
  try {
10535
10729
  await copyFile(actualIndex, temporaryIndex);
10536
10730
  } catch {
@@ -10562,7 +10756,7 @@ async function captureGitCheckpoint(cwd, runId, kind) {
10562
10756
  refName = `refs/aide/runs/${runId}/${Date.now()}-${kind.toLowerCase()}`;
10563
10757
  await git2(cwd, ["update-ref", refName, checkpointCommit]);
10564
10758
  } finally {
10565
- await rm5(directory, { recursive: true, force: true });
10759
+ await rm6(directory, { recursive: true, force: true });
10566
10760
  }
10567
10761
  return {
10568
10762
  kind,
@@ -10591,36 +10785,37 @@ import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypt
10591
10785
  import {
10592
10786
  cp,
10593
10787
  mkdir as mkdir4,
10594
- mkdtemp as mkdtemp3,
10788
+ mkdtemp as mkdtemp4,
10595
10789
  open,
10596
10790
  readdir as readdir6,
10597
10791
  readFile as readFile5,
10598
- realpath as realpath4,
10792
+ realpath as realpath5,
10599
10793
  rename as rename3,
10600
- rm as rm6,
10794
+ rm as rm7,
10601
10795
  stat as stat6,
10602
- writeFile as writeFile4
10796
+ writeFile as writeFile5
10603
10797
  } from "node:fs/promises";
10604
10798
  import { createReadStream as createReadStream3, createWriteStream } from "node:fs";
10605
- import { tmpdir as tmpdir3 } from "node:os";
10799
+ import { tmpdir as tmpdir4 } from "node:os";
10606
10800
  import { pipeline } from "node:stream/promises";
10801
+ import { StringDecoder } from "node:string_decoder";
10607
10802
  import {
10608
10803
  basename as basename3,
10609
10804
  dirname as dirname5,
10610
10805
  isAbsolute as isAbsolute4,
10611
- join as join8,
10806
+ join as join9,
10612
10807
  relative as relative4,
10613
10808
  resolve as resolve5,
10614
10809
  sep as sep4
10615
10810
  } from "node:path";
10616
- import { spawn as spawn4 } from "node:child_process";
10811
+ import { spawn as spawn5 } from "node:child_process";
10617
10812
 
10618
10813
  // src/git-code-state.ts
10619
10814
  import { createHash as createHash4 } from "node:crypto";
10620
10815
  import { createReadStream as createReadStream2 } from "node:fs";
10621
10816
  import { lstat as lstat3, readlink } from "node:fs/promises";
10622
10817
  import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve4, sep as sep3 } from "node:path";
10623
- import { spawn as spawn3 } from "node:child_process";
10818
+ import { spawn as spawn4 } from "node:child_process";
10624
10819
  function gitEnvironment() {
10625
10820
  return {
10626
10821
  ...process.env,
@@ -10643,7 +10838,7 @@ function hashGitDiff(hash, folder, timeoutMs, signal) {
10643
10838
  return new Promise((resolveResult, reject) => {
10644
10839
  let settled = false;
10645
10840
  let timedOut = false;
10646
- const child = spawn3(
10841
+ const child = spawn4(
10647
10842
  "git",
10648
10843
  [
10649
10844
  "-C",
@@ -10862,7 +11057,7 @@ function requireSuccess2(result, fallback) {
10862
11057
  return result;
10863
11058
  }
10864
11059
  async function validateWorktree(input, timeoutMs, signal) {
10865
- const folder = await realpath4(input.folder);
11060
+ const folder = await realpath5(input.folder);
10866
11061
  if (!(await stat6(folder)).isDirectory())
10867
11062
  throw new Error("Worktree is missing");
10868
11063
  const gitDirectory2 = requireSuccess2(
@@ -10876,7 +11071,7 @@ async function validateWorktree(input, timeoutMs, signal) {
10876
11071
  ),
10877
11072
  "Could not resolve the worktree Git directory"
10878
11073
  ).stdout.trim();
10879
- if (await realpath4(gitDirectory2) !== input.gitDirectory) {
11074
+ if (await realpath5(gitDirectory2) !== input.gitDirectory) {
10880
11075
  throw new Error("Worktree identity changed; refresh the page");
10881
11076
  }
10882
11077
  const origin2 = requireSuccess2(
@@ -10905,7 +11100,7 @@ function containedPath2(root, relativePath) {
10905
11100
  }
10906
11101
  async function validateSource(root, source) {
10907
11102
  const target2 = containedPath2(root, source.relativePath);
10908
- const resolved = await realpath4(target2);
11103
+ const resolved = await realpath5(target2);
10909
11104
  const difference = relative4(root, resolved);
10910
11105
  if (difference === ".." || difference.startsWith(`..${sep4}`) || isAbsolute4(difference)) {
10911
11106
  throw new Error("Build source resolves outside the worktree");
@@ -10926,7 +11121,7 @@ async function discoverSourcesInFolder(folder) {
10926
11121
  const current = queue.shift();
10927
11122
  for (const entry of await readdir6(current, { withFileTypes: true })) {
10928
11123
  if (entry.isSymbolicLink()) continue;
10929
- const absolute = join8(current, entry.name);
11124
+ const absolute = join9(current, entry.name);
10930
11125
  const path = relative4(folder, absolute).split(sep4).join("/");
10931
11126
  if (entry.isDirectory()) {
10932
11127
  if (entry.name.endsWith(".xcodeproj")) {
@@ -10997,7 +11192,7 @@ function metadataFromList(value) {
10997
11192
  };
10998
11193
  }
10999
11194
  async function workspaceProjectPaths(workspacePath2, folder) {
11000
- const contentsPath = join8(workspacePath2, "contents.xcworkspacedata");
11195
+ const contentsPath = join9(workspacePath2, "contents.xcworkspacedata");
11001
11196
  let contents;
11002
11197
  try {
11003
11198
  contents = await readFile5(contentsPath, "utf8");
@@ -11024,7 +11219,7 @@ async function workspaceProjectPaths(workspacePath2, folder) {
11024
11219
  continue;
11025
11220
  }
11026
11221
  try {
11027
- const resolved = await realpath4(candidate);
11222
+ const resolved = await realpath5(candidate);
11028
11223
  const resolvedDifference = relative4(folder, resolved);
11029
11224
  if (resolvedDifference === ".." || resolvedDifference.startsWith(`..${sep4}`) || isAbsolute4(resolvedDifference) || !(await stat6(resolved)).isDirectory()) {
11030
11225
  continue;
@@ -11217,7 +11412,7 @@ async function dependentSigningRequirements(source, absolutePath, folder, rootTa
11217
11412
  for (const project of projects.slice(0, 50)) {
11218
11413
  const converted = await command(
11219
11414
  "plutil",
11220
- ["-convert", "json", "-o", "-", join8(project, "project.pbxproj")],
11415
+ ["-convert", "json", "-o", "-", join9(project, "project.pbxproj")],
11221
11416
  Math.min(timeoutMs, 15e3),
11222
11417
  signal,
11223
11418
  folder
@@ -11454,8 +11649,8 @@ function genericBuildDestinations(action) {
11454
11649
  ];
11455
11650
  }
11456
11651
  async function listPhysicalDevices(timeoutMs, signal) {
11457
- const directory = await mkdtemp3(join8(tmpdir3(), "ade-devices-"));
11458
- const output = join8(directory, "devices.json");
11652
+ const directory = await mkdtemp4(join9(tmpdir4(), "ade-devices-"));
11653
+ const output = join9(directory, "devices.json");
11459
11654
  try {
11460
11655
  const result = await command(
11461
11656
  "xcrun",
@@ -11475,7 +11670,7 @@ async function listPhysicalDevices(timeoutMs, signal) {
11475
11670
  if (result.exitCode !== 0) return [];
11476
11671
  return physicalDestinations(JSON.parse(await readFile5(output, "utf8")));
11477
11672
  } finally {
11478
- await rm6(directory, { recursive: true, force: true });
11673
+ await rm7(directory, { recursive: true, force: true });
11479
11674
  }
11480
11675
  }
11481
11676
  var inspectBuildDestinations = async (payload, timeoutMs, signal) => {
@@ -11562,7 +11757,7 @@ function createRedactor(env) {
11562
11757
  );
11563
11758
  };
11564
11759
  }
11565
- var BuildLogger = class {
11760
+ var BuildLogger = class _BuildLogger {
11566
11761
  constructor(buildId, context, rawLogPath, env) {
11567
11762
  this.buildId = buildId;
11568
11763
  this.context = context;
@@ -11571,51 +11766,67 @@ var BuildLogger = class {
11571
11766
  }
11572
11767
  buildId;
11573
11768
  context;
11769
+ static MAX_CHUNK_BYTES = 128 * 1024;
11770
+ static MAX_BATCH_BYTES = 128 * 1024;
11574
11771
  stream;
11575
11772
  redact;
11576
11773
  sequence = 0;
11577
11774
  pending = [];
11775
+ pendingBytes = 0;
11578
11776
  flushChain = Promise.resolve();
11579
11777
  timer = null;
11580
11778
  closePromise = null;
11581
11779
  redactingPrivateKey = false;
11582
11780
  emit(phase, stream, message, scope = "BUILD", scopeId = this.buildId, extraStream) {
11781
+ this.write(phase, stream, `${message}\r
11782
+ `, scope, scopeId, extraStream);
11783
+ }
11784
+ write(phase, stream, output, scope = "BUILD", scopeId = this.buildId, extraStream) {
11785
+ const ending = output.match(/(?:\r\n|\r|\n)$/)?.[0] ?? "";
11786
+ const message = ending ? output.slice(0, -ending.length) : output;
11583
11787
  const startsPrivateKey = /-----BEGIN [^-]*PRIVATE KEY-----/i.test(message);
11584
11788
  const endsPrivateKey = /-----END [^-]*PRIVATE KEY-----/i.test(message);
11585
11789
  if (startsPrivateKey) this.redactingPrivateKey = true;
11586
11790
  const sanitized = this.redactingPrivateKey ? "[REDACTED PRIVATE KEY]" : this.redact(message);
11587
11791
  if (endsPrivateKey) this.redactingPrivateKey = false;
11588
11792
  const createdAt = (/* @__PURE__ */ new Date()).toISOString();
11589
- const line = `[${createdAt}] [${phase}] [${stream}] ${sanitized}
11590
- `;
11793
+ const terminalOutput = `${sanitized}${ending}`;
11794
+ const line = `[${createdAt}] [${phase}] [${stream}] ${sanitized}${ending || "\n"}`;
11591
11795
  this.stream.write(line);
11592
11796
  extraStream?.write(line);
11593
- this.pending.push({
11594
- scope,
11595
- scopeId,
11596
- sequence: this.sequence++,
11597
- phase,
11598
- level: stream === "STDERR" || /\berror\b/i.test(sanitized) ? "ERROR" : /\bwarning\b/i.test(sanitized) ? "WARNING" : "INFO",
11599
- stream,
11600
- message: sanitized,
11601
- createdAt
11602
- });
11603
- if (this.pending.length >= 100) this.flush();
11604
- else if (!this.timer) {
11605
- this.timer = setTimeout(() => this.flush(), 250);
11797
+ for (const data of splitUtf8(terminalOutput, _BuildLogger.MAX_CHUNK_BYTES)) {
11798
+ const bytes = Buffer.from(data, "utf8");
11799
+ this.pending.push({
11800
+ scope,
11801
+ scopeId,
11802
+ sequence: this.sequence++,
11803
+ phase,
11804
+ stream,
11805
+ dataBase64: bytes.toString("base64"),
11806
+ byteLength: bytes.byteLength,
11807
+ createdAt
11808
+ });
11809
+ this.pendingBytes += bytes.byteLength;
11810
+ if (this.pending.length >= 200 || this.pendingBytes >= _BuildLogger.MAX_BATCH_BYTES) {
11811
+ this.flush();
11812
+ }
11813
+ }
11814
+ if (this.pending.length && !this.timer) {
11815
+ this.timer = setTimeout(() => this.flush(), 25);
11606
11816
  this.timer.unref();
11607
11817
  }
11608
11818
  }
11609
11819
  flush() {
11610
11820
  if (this.timer) clearTimeout(this.timer);
11611
11821
  this.timer = null;
11612
- const events = this.pending.splice(0);
11613
- if (!events.length || !this.context?.appendBuildLogs) return;
11822
+ const chunks = this.pending.splice(0);
11823
+ this.pendingBytes = 0;
11824
+ if (!chunks.length || !this.context?.appendBuildLogChunks) return;
11614
11825
  this.flushChain = this.flushChain.then(async () => {
11615
11826
  try {
11616
- await this.context.appendBuildLogs(this.buildId, events);
11827
+ await this.context.appendBuildLogChunks(this.buildId, chunks);
11617
11828
  } catch (error) {
11618
- console.error("Could not append build logs:", cleanError2(error));
11829
+ console.error("Could not append build log chunks:", cleanError2(error));
11619
11830
  }
11620
11831
  });
11621
11832
  }
@@ -11628,6 +11839,24 @@ var BuildLogger = class {
11628
11839
  return this.closePromise;
11629
11840
  }
11630
11841
  };
11842
+ function splitUtf8(value, maximumBytes) {
11843
+ if (!value) return [];
11844
+ const parts = [];
11845
+ let part = "";
11846
+ let byteLength = 0;
11847
+ for (const character of value) {
11848
+ const characterBytes = Buffer.byteLength(character, "utf8");
11849
+ if (part && byteLength + characterBytes > maximumBytes) {
11850
+ parts.push(part);
11851
+ part = "";
11852
+ byteLength = 0;
11853
+ }
11854
+ part += character;
11855
+ byteLength += characterBytes;
11856
+ }
11857
+ if (part) parts.push(part);
11858
+ return parts;
11859
+ }
11631
11860
  function terminateProcess(child) {
11632
11861
  if (child.exitCode !== null || child.killed) return null;
11633
11862
  try {
@@ -11661,9 +11890,15 @@ function runLoggedCommand(options) {
11661
11890
  mode: 384
11662
11891
  });
11663
11892
  }
11664
- const child = spawn4(options.command, options.args, {
11893
+ const child = spawn5(options.command, options.args, {
11665
11894
  cwd: options.cwd,
11666
- env: options.env,
11895
+ env: {
11896
+ ...options.env,
11897
+ TERM: "xterm-256color",
11898
+ COLORTERM: "truecolor",
11899
+ FORCE_COLOR: "1",
11900
+ CLICOLOR_FORCE: "1"
11901
+ },
11667
11902
  shell: false,
11668
11903
  detached: true,
11669
11904
  stdio: ["ignore", "pipe", "pipe"]
@@ -11677,36 +11912,36 @@ function runLoggedCommand(options) {
11677
11912
  extraStream
11678
11913
  );
11679
11914
  const attach = (stream, kind) => {
11915
+ const decoder = new StringDecoder("utf8");
11680
11916
  let remainder = "";
11681
- stream.setEncoding("utf8");
11682
- stream.on("data", (chunk) => {
11683
- const parts = `${remainder}${chunk}`.split(/\r?\n/);
11684
- remainder = parts.pop() ?? "";
11685
- for (const line of parts) {
11686
- output = `${output}${line}
11687
- `.slice(-64e3);
11688
- options.logger.emit(
11917
+ const drain = (final = false) => {
11918
+ while (remainder) {
11919
+ const delimiter = remainder.search(/[\r\n]/);
11920
+ if (delimiter < 0 && !final) return;
11921
+ let end = delimiter < 0 ? remainder.length : delimiter + 1;
11922
+ if (remainder[delimiter] === "\r" && remainder[delimiter + 1] === "\n") {
11923
+ end += 1;
11924
+ }
11925
+ const record = remainder.slice(0, end);
11926
+ remainder = remainder.slice(end);
11927
+ output = `${output}${record}`.slice(-64e3);
11928
+ options.logger.write(
11689
11929
  options.phase,
11690
11930
  kind,
11691
- line,
11931
+ record,
11692
11932
  options.scope,
11693
11933
  options.scopeId,
11694
11934
  extraStream
11695
11935
  );
11696
11936
  }
11937
+ };
11938
+ stream.on("data", (chunk) => {
11939
+ remainder += decoder.write(chunk);
11940
+ drain();
11697
11941
  });
11698
11942
  stream.on("end", () => {
11699
- if (remainder) {
11700
- output = `${output}${remainder}`.slice(-64e3);
11701
- options.logger.emit(
11702
- options.phase,
11703
- kind,
11704
- remainder,
11705
- options.scope,
11706
- options.scopeId,
11707
- extraStream
11708
- );
11709
- }
11943
+ remainder += decoder.end();
11944
+ drain(true);
11710
11945
  });
11711
11946
  };
11712
11947
  attach(child.stdout, "STDOUT");
@@ -11853,7 +12088,7 @@ function actionArgument(action) {
11853
12088
  }[action];
11854
12089
  }
11855
12090
  function xcodeBuildArguments(input) {
11856
- const resultBundle = join8(input.artifactDirectory, "result.xcresult");
12091
+ const resultBundle = join9(input.artifactDirectory, "result.xcresult");
11857
12092
  const sourcePath = containedPath2(input.folder, input.source.relativePath);
11858
12093
  const usesCapturedTestProducts = input.action === "TEST_WITHOUT_BUILDING";
11859
12094
  const args = [
@@ -11875,13 +12110,13 @@ function xcodeBuildArguments(input) {
11875
12110
  if (input.action === "ARCHIVE") {
11876
12111
  args.push(
11877
12112
  "-archivePath",
11878
- join8(input.artifactDirectory, "archive.xcarchive")
12113
+ join9(input.artifactDirectory, "archive.xcarchive")
11879
12114
  );
11880
12115
  }
11881
12116
  if (input.action === "BUILD_FOR_TESTING") {
11882
12117
  args.push(
11883
12118
  "-testProductsPath",
11884
- join8(input.artifactDirectory, "test-products.xctestproducts")
12119
+ join9(input.artifactDirectory, "test-products.xctestproducts")
11885
12120
  );
11886
12121
  }
11887
12122
  if (input.action === "TEST_WITHOUT_BUILDING" && input.advancedSettings.priorTestProductsPath) {
@@ -11944,27 +12179,27 @@ function classifyFailure(output) {
11944
12179
  }
11945
12180
  async function runHook(options) {
11946
12181
  const phaseDirectory = options.phase === "PRE_BUILD" ? "pre" : "post";
11947
- const directory = join8(
12182
+ const directory = join9(
11948
12183
  options.input.artifactDirectory,
11949
12184
  "hooks",
11950
12185
  phaseDirectory
11951
12186
  );
11952
12187
  const prefix = `${String(options.script.position).padStart(3, "0")}-${options.script.id}`;
11953
- const file = join8(directory, `${prefix}.mjs`);
11954
- const runner = join8(directory, `${prefix}.runner.mjs`);
11955
- const log = join8(directory, `${prefix}.log`);
12188
+ const file = join9(directory, `${prefix}.mjs`);
12189
+ const runner = join9(directory, `${prefix}.runner.mjs`);
12190
+ const log = join9(directory, `${prefix}.log`);
11956
12191
  const started = Date.now();
11957
12192
  try {
11958
12193
  await mkdir4(directory, { recursive: true, mode: 448 });
11959
- await writeFile4(file, `${options.source}
12194
+ await writeFile5(file, `${options.source}
11960
12195
  `, { mode: 384 });
11961
- await writeFile4(
12196
+ await writeFile5(
11962
12197
  options.contextPath,
11963
12198
  `${JSON.stringify(options.hookContext, null, 2)}
11964
12199
  `,
11965
12200
  { mode: 384 }
11966
12201
  );
11967
- await writeFile4(
12202
+ await writeFile5(
11968
12203
  runner,
11969
12204
  `import { readFile } from "node:fs/promises";
11970
12205
  const hookModule = await import(${JSON.stringify(`./${basename3(file)}`)});
@@ -12050,7 +12285,7 @@ async function pathSize(path) {
12050
12285
  let size = 0;
12051
12286
  for (const entry of await readdir6(path, { withFileTypes: true })) {
12052
12287
  if (entry.isSymbolicLink()) continue;
12053
- size += await pathSize(join8(path, entry.name));
12288
+ size += await pathSize(join9(path, entry.name));
12054
12289
  }
12055
12290
  return size;
12056
12291
  }
@@ -12080,7 +12315,7 @@ async function plistString(plistPath, keyPath, timeoutMs, signal) {
12080
12315
  }
12081
12316
  }
12082
12317
  async function archiveApplicationProperties(archivePath, timeoutMs, signal) {
12083
- const plistPath = join8(archivePath, "Info.plist");
12318
+ const plistPath = join9(archivePath, "Info.plist");
12084
12319
  const read = (key) => plistString(plistPath, `ApplicationProperties.${key}`, timeoutMs, signal);
12085
12320
  const [bundleIdentifier2, bundleShortVersion, bundleVersion, applicationPath] = await Promise.all([
12086
12321
  read("CFBundleIdentifier"),
@@ -12239,9 +12474,9 @@ function normalizeCoverage(value) {
12239
12474
  };
12240
12475
  }
12241
12476
  async function writeJsonReport(input, kind, timeoutMs, signal) {
12242
- const resultBundle = join8(input.artifactDirectory, "result.xcresult");
12477
+ const resultBundle = join9(input.artifactDirectory, "result.xcresult");
12243
12478
  const filename = kind === "TEST_RESULTS" ? "test-results.json" : "code-coverage.json";
12244
- const destination = join8(input.artifactDirectory, filename);
12479
+ const destination = join9(input.artifactDirectory, filename);
12245
12480
  const temporary = `${destination}.tmp-${randomUUID3()}`;
12246
12481
  try {
12247
12482
  if (!await pathExists(resultBundle)) {
@@ -12285,7 +12520,7 @@ async function writeJsonReport(input, kind, timeoutMs, signal) {
12285
12520
  error: null
12286
12521
  };
12287
12522
  } catch (error) {
12288
- await rm6(temporary, { force: true });
12523
+ await rm7(temporary, { force: true });
12289
12524
  return {
12290
12525
  kind,
12291
12526
  status: "FAILED",
@@ -12376,7 +12611,7 @@ async function snapshotCoverageChanges(input, folder, timeoutMs, signal) {
12376
12611
  const types = changeTypesFromStatus(status2.stdout);
12377
12612
  for (const path of untracked.stdout.split("\0").filter(Boolean)) {
12378
12613
  try {
12379
- const contents = await readFile5(join8(folder, path));
12614
+ const contents = await readFile5(join9(folder, path));
12380
12615
  if (contents.includes(0)) continue;
12381
12616
  const lineCount = contents.length ? contents.toString("utf8").split("\n").length - (contents.toString("utf8").endsWith("\n") ? 1 : 0) : 0;
12382
12617
  lines.set(
@@ -12410,7 +12645,7 @@ async function addChangedCoverage(report, changes, input, folder, timeoutMs, sig
12410
12645
  let covered = 0;
12411
12646
  let executable = 0;
12412
12647
  if (coveragePath && change.lines.length) {
12413
- const temporary2 = join8(
12648
+ const temporary2 = join9(
12414
12649
  input.artifactDirectory,
12415
12650
  `.changed-coverage-${randomUUID3()}.json`
12416
12651
  );
@@ -12451,7 +12686,7 @@ async function addChangedCoverage(report, changes, input, folder, timeoutMs, sig
12451
12686
  }
12452
12687
  }
12453
12688
  } finally {
12454
- await rm6(temporary2, { force: true });
12689
+ await rm7(temporary2, { force: true });
12455
12690
  }
12456
12691
  }
12457
12692
  changedCoveredLines += covered;
@@ -12471,9 +12706,9 @@ async function addChangedCoverage(report, changes, input, folder, timeoutMs, sig
12471
12706
  changedLineCoverage: changedExecutableLines ? changedCoveredLines / changedExecutableLines : null
12472
12707
  };
12473
12708
  const data = { ...report.data, changedFiles };
12474
- const destination = join8(input.artifactDirectory, "worktree-coverage.json");
12709
+ const destination = join9(input.artifactDirectory, "worktree-coverage.json");
12475
12710
  const temporary = `${destination}.tmp-${randomUUID3()}`;
12476
- await writeFile4(temporary, JSON.stringify({ summary, data }, null, 2), {
12711
+ await writeFile5(temporary, JSON.stringify({ summary, data }, null, 2), {
12477
12712
  mode: 384
12478
12713
  });
12479
12714
  await rename3(temporary, destination);
@@ -12525,7 +12760,7 @@ async function findFiles(root, predicate, limit = 20) {
12525
12760
  }
12526
12761
  for (const entry of entries) {
12527
12762
  if (entry.isSymbolicLink()) continue;
12528
- const path = join8(current, entry.name);
12763
+ const path = join9(current, entry.name);
12529
12764
  if (entry.isDirectory()) queue.push(path);
12530
12765
  else if (entry.isFile() && predicate(entry.name)) results.push(path);
12531
12766
  if (results.length >= limit) break;
@@ -12535,7 +12770,7 @@ async function findFiles(root, predicate, limit = 20) {
12535
12770
  }
12536
12771
  async function captureArtifacts(input, folder, signal, includeProducts = true) {
12537
12772
  const artifacts = [];
12538
- const resultBundle = join8(input.artifactDirectory, "result.xcresult");
12773
+ const resultBundle = join9(input.artifactDirectory, "result.xcresult");
12539
12774
  if (await pathExists(resultBundle)) {
12540
12775
  const coverageProbe = await command(
12541
12776
  "xcrun",
@@ -12562,7 +12797,7 @@ async function captureArtifacts(input, folder, signal, includeProducts = true) {
12562
12797
  );
12563
12798
  }
12564
12799
  if (!includeProducts) return artifacts;
12565
- const archivePath = join8(input.artifactDirectory, "archive.xcarchive");
12800
+ const archivePath = join9(input.artifactDirectory, "archive.xcarchive");
12566
12801
  if (await pathExists(archivePath)) {
12567
12802
  artifacts.push(
12568
12803
  await artifact(input.artifactDirectory, "ARCHIVE", archivePath)
@@ -12585,12 +12820,12 @@ async function captureArtifacts(input, folder, signal, includeProducts = true) {
12585
12820
  if (apps.length === 1) {
12586
12821
  const settings = apps[0].buildSettings;
12587
12822
  const productName = settings.FULL_PRODUCT_NAME ?? settings.WRAPPER_NAME;
12588
- const source = settings.TARGET_BUILD_DIR && productName ? join8(settings.TARGET_BUILD_DIR, productName) : null;
12823
+ const source = settings.TARGET_BUILD_DIR && productName ? join9(settings.TARGET_BUILD_DIR, productName) : null;
12589
12824
  if (source && await pathExists(source)) {
12590
- const productDirectory = join8(input.artifactDirectory, "products");
12591
- const destination = join8(productDirectory, basename3(source));
12825
+ const productDirectory = join9(input.artifactDirectory, "products");
12826
+ const destination = join9(productDirectory, basename3(source));
12592
12827
  await mkdir4(productDirectory, { recursive: true, mode: 448 });
12593
- await rm6(destination, { recursive: true, force: true });
12828
+ await rm7(destination, { recursive: true, force: true });
12594
12829
  await cp(source, destination, {
12595
12830
  recursive: true,
12596
12831
  preserveTimestamps: true
@@ -12605,7 +12840,7 @@ async function captureArtifacts(input, folder, signal, includeProducts = true) {
12605
12840
  }
12606
12841
  }
12607
12842
  if (input.action === "BUILD_FOR_TESTING") {
12608
- const testDirectory = join8(
12843
+ const testDirectory = join9(
12609
12844
  input.artifactDirectory,
12610
12845
  "test-products.xctestproducts"
12611
12846
  );
@@ -12656,11 +12891,11 @@ var runIosBuild = async (payload, timeoutMs, signal, onLog, context) => {
12656
12891
  signal
12657
12892
  );
12658
12893
  await mkdir4(input.artifactDirectory, { recursive: true, mode: 448 });
12659
- const rawLog = join8(input.artifactDirectory, "build.log");
12894
+ const rawLog = join9(input.artifactDirectory, "build.log");
12660
12895
  const logger = new BuildLogger(input.buildId, context, rawLog, process.env);
12661
12896
  try {
12662
12897
  const scriptExecutions = [];
12663
- const contextPath = join8(input.artifactDirectory, "context.json");
12898
+ const contextPath = join9(input.artifactDirectory, "context.json");
12664
12899
  const baseHookContext = {
12665
12900
  buildId: input.buildId,
12666
12901
  branch: input.branch ?? null,
@@ -12919,7 +13154,7 @@ var generateIosBuildReport = async (payload, timeoutMs, signal, onLog) => {
12919
13154
  var deleteIosBuild = async (payload, _timeoutMs, signal, onLog) => {
12920
13155
  const input = parseBuildDeletePayload(payload);
12921
13156
  if (signal.aborted) return { ...successfulProcess6, cancelled: true };
12922
- await rm6(input.artifactDirectory, { recursive: true, force: true });
13157
+ await rm7(input.artifactDirectory, { recursive: true, force: true });
12923
13158
  await onLog({
12924
13159
  sequence: 0,
12925
13160
  stream: "SYSTEM",
@@ -12933,8 +13168,8 @@ var downloadIosBuildArtifact = async (payload, timeoutMs, signal, onLog, context
12933
13168
  if (!context?.uploadBuildArtifact) {
12934
13169
  throw new Error("This agent cannot upload build artifacts");
12935
13170
  }
12936
- const root = await realpath4(input.artifactDirectory);
12937
- const target2 = await realpath4(
13171
+ const root = await realpath5(input.artifactDirectory);
13172
+ const target2 = await realpath5(
12938
13173
  containedPath2(root, input.artifactRelativePath)
12939
13174
  );
12940
13175
  const difference = relative4(root, target2);
@@ -12948,8 +13183,8 @@ var downloadIosBuildArtifact = async (payload, timeoutMs, signal, onLog, context
12948
13183
  let temporaryArchive = null;
12949
13184
  try {
12950
13185
  if (information.isDirectory()) {
12951
- temporaryArchive = join8(
12952
- tmpdir3(),
13186
+ temporaryArchive = join9(
13187
+ tmpdir4(),
12953
13188
  `ade-build-artifact-${randomUUID3()}.tar.gz`
12954
13189
  );
12955
13190
  requireSuccess2(
@@ -12982,7 +13217,7 @@ var downloadIosBuildArtifact = async (payload, timeoutMs, signal, onLog, context
12982
13217
  return successfulProcess6;
12983
13218
  } finally {
12984
13219
  if (temporaryArchive) {
12985
- await rm6(temporaryArchive, { force: true });
13220
+ await rm7(temporaryArchive, { force: true });
12986
13221
  }
12987
13222
  }
12988
13223
  };
@@ -13018,24 +13253,24 @@ var deployIosBuild = async (payload, timeoutMs, signal, _onLog, context) => {
13018
13253
  if (!await pathExists(appPath) || !appPath.endsWith(".app")) {
13019
13254
  throw new Error("Runnable app artifact is missing");
13020
13255
  }
13021
- const deploymentsDirectory = join8(input.artifactDirectory, "deployments");
13256
+ const deploymentsDirectory = join9(input.artifactDirectory, "deployments");
13022
13257
  await mkdir4(deploymentsDirectory, { recursive: true, mode: 448 });
13023
13258
  const logger = new BuildLogger(
13024
13259
  input.buildId,
13025
13260
  context,
13026
- join8(deploymentsDirectory, "deployments.log"),
13261
+ join9(deploymentsDirectory, "deployments.log"),
13027
13262
  process.env
13028
13263
  );
13029
13264
  try {
13030
13265
  const outcomes = [];
13031
13266
  for (const deployment of input.deployments) {
13032
- const directory = join8(
13267
+ const directory = join9(
13033
13268
  input.artifactDirectory,
13034
13269
  "deployments",
13035
13270
  deployment.id
13036
13271
  );
13037
13272
  await mkdir4(directory, { recursive: true, mode: 448 });
13038
- const logPath = join8(directory, "deployment.log");
13273
+ const logPath = join9(directory, "deployment.log");
13039
13274
  const started = Date.now();
13040
13275
  let failure = null;
13041
13276
  try {
@@ -13250,15 +13485,15 @@ var exportIosArchive = async (payload, timeoutMs, signal, _onLog, context) => {
13250
13485
  if (!await pathExists(archivePath) || !archivePath.endsWith(".xcarchive")) {
13251
13486
  throw new Error("Archive artifact is missing");
13252
13487
  }
13253
- const exportDirectory = join8(
13488
+ const exportDirectory = join9(
13254
13489
  input.artifactDirectory,
13255
13490
  "exports",
13256
13491
  input.exportId
13257
13492
  );
13258
13493
  await mkdir4(exportDirectory, { recursive: true, mode: 448 });
13259
- const plistPath = join8(exportDirectory, "ExportOptions.plist");
13260
- const logPath = join8(exportDirectory, "export.log");
13261
- await writeFile4(plistPath, exportPlist(input.settings), { mode: 384 });
13494
+ const plistPath = join9(exportDirectory, "ExportOptions.plist");
13495
+ const logPath = join9(exportDirectory, "export.log");
13496
+ await writeFile5(plistPath, exportPlist(input.settings), { mode: 384 });
13262
13497
  const logger = new BuildLogger(input.buildId, context, logPath, process.env);
13263
13498
  try {
13264
13499
  const result = await runLoggedCommand({
@@ -13324,18 +13559,18 @@ var success = {
13324
13559
  };
13325
13560
  var runWorkflowTerminal = async (payloadValue, timeoutMs, signal, onLog, context) => {
13326
13561
  const payload = parseWorkflowTerminalPayload(payloadValue);
13327
- const cwd = await realpath5(payload.cwd);
13562
+ const cwd = await realpath6(payload.cwd);
13328
13563
  const information = await stat7(cwd);
13329
13564
  if (!information.isDirectory())
13330
13565
  throw new Error("Workflow working directory is not a directory");
13331
- const directory = await mkdtemp4(join9(tmpdir4(), "aide-workflow-"));
13566
+ const directory = await mkdtemp5(join10(tmpdir5(), "aide-workflow-"));
13332
13567
  const extension2 = payload.interpreter === "NODE" ? "mjs" : "sh";
13333
- const scriptPath = join9(directory, `step.${extension2}`);
13334
- const sessionPath = join9(directory, "session.json");
13568
+ const scriptPath = join10(directory, `step.${extension2}`);
13569
+ const sessionPath = join10(directory, "session.json");
13335
13570
  try {
13336
- await writeFile5(scriptPath, `${payload.script}
13571
+ await writeFile6(scriptPath, `${payload.script}
13337
13572
  `, { mode: 384 });
13338
- await writeFile5(
13573
+ await writeFile6(
13339
13574
  sessionPath,
13340
13575
  `${JSON.stringify(payload.sessionData, null, 2)}
13341
13576
  `,
@@ -13379,13 +13614,13 @@ var runWorkflowTerminal = async (payloadValue, timeoutMs, signal, onLog, context
13379
13614
  }
13380
13615
  return { ...result, sessionData };
13381
13616
  } finally {
13382
- await rm7(directory, { recursive: true, force: true });
13617
+ await rm8(directory, { recursive: true, force: true });
13383
13618
  }
13384
13619
  };
13385
13620
  var runWorkflowGitCheckpoint = async (payloadValue, _timeoutMs, signal) => {
13386
13621
  const payload = parseWorkflowGitCheckpointPayload(payloadValue);
13387
13622
  if (signal.aborted) return { ...success, exitCode: null, cancelled: true };
13388
- const cwd = await realpath5(payload.cwd);
13623
+ const cwd = await realpath6(payload.cwd);
13389
13624
  if (payload.operation === "CAPTURE") {
13390
13625
  const checkpoint2 = await captureGitCheckpoint(
13391
13626
  cwd,
@@ -13422,10 +13657,10 @@ var runWorkflowGitCheckpoint = async (payloadValue, _timeoutMs, signal) => {
13422
13657
 
13423
13658
  // src/handlers/worktrees.ts
13424
13659
  import { createWriteStream as createWriteStream2, watch } from "node:fs";
13425
- import { mkdtemp as mkdtemp5, open as open2, readFile as readFile7, realpath as realpath6, rm as rm8, stat as stat8 } from "node:fs/promises";
13426
- import { tmpdir as tmpdir5 } from "node:os";
13427
- import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute5, join as join10, relative as relative5 } from "node:path";
13428
- import { spawn as spawn5 } from "node:child_process";
13660
+ import { mkdtemp as mkdtemp6, open as open2, readFile as readFile7, realpath as realpath7, rm as rm9, stat as stat8 } from "node:fs/promises";
13661
+ import { tmpdir as tmpdir6 } from "node:os";
13662
+ import { basename as basename4, dirname as dirname6, isAbsolute as isAbsolute5, join as join11, relative as relative5 } from "node:path";
13663
+ import { spawn as spawn6 } from "node:child_process";
13429
13664
  var successfulProcess7 = {
13430
13665
  exitCode: 0,
13431
13666
  signal: null,
@@ -13479,7 +13714,7 @@ async function rebaseInProgress(folder, timeoutMs, signal) {
13479
13714
  const candidate = pathResult.stdout.trim();
13480
13715
  if (!candidate) continue;
13481
13716
  try {
13482
- await stat8(isAbsolute5(candidate) ? candidate : join10(folder, candidate));
13717
+ await stat8(isAbsolute5(candidate) ? candidate : join11(folder, candidate));
13483
13718
  return true;
13484
13719
  } catch {
13485
13720
  }
@@ -13499,7 +13734,7 @@ async function rebaseBranch(folder, timeoutMs, signal) {
13499
13734
  if (!candidate) continue;
13500
13735
  try {
13501
13736
  const headName = (await readFile7(
13502
- isAbsolute5(candidate) ? candidate : join10(folder, candidate),
13737
+ isAbsolute5(candidate) ? candidate : join11(folder, candidate),
13503
13738
  "utf8"
13504
13739
  )).trim();
13505
13740
  if (headName.startsWith("refs/heads/")) {
@@ -13682,7 +13917,7 @@ async function gitDirectory(folder, timeoutMs, signal) {
13682
13917
  ),
13683
13918
  "Could not resolve the worktree Git directory"
13684
13919
  );
13685
- return realpath6(result.stdout.trim());
13920
+ return realpath7(result.stdout.trim());
13686
13921
  }
13687
13922
  async function origin(folder, timeoutMs, signal) {
13688
13923
  const result = requireSuccess3(
@@ -13692,7 +13927,7 @@ async function origin(folder, timeoutMs, signal) {
13692
13927
  return normalizeGitOrigin(result.stdout.trim()).canonicalOrigin;
13693
13928
  }
13694
13929
  async function validateWorktree2(input, timeoutMs, signal) {
13695
- const folder = await realpath6(input.folder);
13930
+ const folder = await realpath7(input.folder);
13696
13931
  if (!(await stat8(folder)).isDirectory())
13697
13932
  throw new Error("Worktree is missing");
13698
13933
  const observedGitDirectory = await gitDirectory(folder, timeoutMs, signal);
@@ -13739,7 +13974,7 @@ async function worktreePushStatus(folder, branch, changes, timeoutMs, signal) {
13739
13974
  async function inspectWorktreeItem(folderValue2, rootFolder, baseBranch, primary, timeoutMs, signal) {
13740
13975
  const checkedAt = (/* @__PURE__ */ new Date()).toISOString();
13741
13976
  try {
13742
- const folder = await realpath6(folderValue2);
13977
+ const folder = await realpath7(folderValue2);
13743
13978
  const [gitDir, branchResult, headResult, statusResult, rebasing] = await Promise.all([
13744
13979
  gitDirectory(folder, timeoutMs, signal),
13745
13980
  git3(
@@ -13839,7 +14074,7 @@ async function inspectWorktreeItem(folderValue2, rootFolder, baseBranch, primary
13839
14074
  }
13840
14075
  }
13841
14076
  async function discoverWorktrees(rootFolderValue, baseOverrides, knownDefaultBranch, timeoutMs, signal) {
13842
- const rootFolder = await realpath6(rootFolderValue);
14077
+ const rootFolder = await realpath7(rootFolderValue);
13843
14078
  const list = requireSuccess3(
13844
14079
  await git3(
13845
14080
  rootFolder,
@@ -14145,7 +14380,7 @@ async function comparisonSides(input, folder, timeoutMs, signal) {
14145
14380
  if (!input.path) return { before: null, after: null };
14146
14381
  const path = input.path;
14147
14382
  const previousPath = input.previousPath ?? path;
14148
- const currentPath = join10(folder, path);
14383
+ const currentPath = join11(folder, path);
14149
14384
  if (input.scope === "UNTRACKED") {
14150
14385
  return { before: null, after: { kind: "FILE", path: currentPath } };
14151
14386
  }
@@ -14228,7 +14463,7 @@ async function availableSide(side, folder, timeoutMs, signal) {
14228
14463
  return gitObjectExists(folder, side.specification, timeoutMs, signal);
14229
14464
  }
14230
14465
  try {
14231
- const resolved = await realpath6(side.path);
14466
+ const resolved = await realpath7(side.path);
14232
14467
  const difference = relative5(folder, resolved);
14233
14468
  return difference !== ".." && !difference.startsWith("../") && (await stat8(resolved)).isFile();
14234
14469
  } catch {
@@ -14301,7 +14536,7 @@ async function inspectRequestedDiff(input, folder, timeoutMs, signal) {
14301
14536
  let patch;
14302
14537
  if (input.scope === "UNTRACKED") {
14303
14538
  const bounded = await readBoundedFile(
14304
- join10(folder, input.path),
14539
+ join11(folder, input.path),
14305
14540
  MAX_DIFF_BYTES
14306
14541
  );
14307
14542
  const contents = bounded.contents;
@@ -14405,7 +14640,7 @@ function imageContentType(path) {
14405
14640
  }
14406
14641
  async function writeGitObject(folder, specification, destination, timeoutMs, signal) {
14407
14642
  await new Promise((resolvePromise, rejectPromise) => {
14408
- const child = spawn5(
14643
+ const child = spawn6(
14409
14644
  "git",
14410
14645
  ["-C", folder, "cat-file", "blob", specification],
14411
14646
  { stdio: ["ignore", "pipe", "pipe"] }
@@ -14471,7 +14706,7 @@ var downloadWorktreeDiffAsset = async (payload, timeoutMs, signal, _onLog, conte
14471
14706
  let temporaryDirectory = null;
14472
14707
  try {
14473
14708
  if (selected.kind === "FILE") {
14474
- uploadPath = await realpath6(selected.path);
14709
+ uploadPath = await realpath7(selected.path);
14475
14710
  const difference = relative5(folder, uploadPath);
14476
14711
  if (difference === ".." || difference.startsWith("../")) {
14477
14712
  throw new Error("Diff image resolves outside the worktree");
@@ -14489,8 +14724,8 @@ var downloadWorktreeDiffAsset = async (payload, timeoutMs, signal, _onLog, conte
14489
14724
  if (!/^\d+$/.test(size) || Number(size) > 20 * 1024 * 1024) {
14490
14725
  throw new Error("Diff image exceeds the 20 MiB limit");
14491
14726
  }
14492
- temporaryDirectory = await mkdtemp5(join10(tmpdir5(), "ade-diff-image-"));
14493
- uploadPath = join10(temporaryDirectory, basename4(input.path));
14727
+ temporaryDirectory = await mkdtemp6(join11(tmpdir6(), "ade-diff-image-"));
14728
+ uploadPath = join11(temporaryDirectory, basename4(input.path));
14494
14729
  await writeGitObject(
14495
14730
  folder,
14496
14731
  selected.specification,
@@ -14512,7 +14747,7 @@ var downloadWorktreeDiffAsset = async (payload, timeoutMs, signal, _onLog, conte
14512
14747
  return successfulProcess7;
14513
14748
  } finally {
14514
14749
  if (temporaryDirectory) {
14515
- await rm8(temporaryDirectory, { recursive: true, force: true });
14750
+ await rm9(temporaryDirectory, { recursive: true, force: true });
14516
14751
  }
14517
14752
  }
14518
14753
  };
@@ -14689,7 +14924,7 @@ async function chooseNewBranch(folder, candidates, allowedCurrentBranch, timeout
14689
14924
  throw new Error("Every generated ticket branch name is already taken");
14690
14925
  }
14691
14926
  async function validateBranchRoot(input, timeoutMs, signal) {
14692
- const rootFolder = await realpath6(input.rootFolder);
14927
+ const rootFolder = await realpath7(input.rootFolder);
14693
14928
  if (!(await stat8(rootFolder)).isDirectory()) {
14694
14929
  throw new Error("Base repository is missing");
14695
14930
  }
@@ -14753,7 +14988,7 @@ var branchWorktree = async (payload, timeoutMs, signal) => {
14753
14988
  timeoutMs,
14754
14989
  signal
14755
14990
  ) : input.candidates[0];
14756
- const targetFolder = input.action === "CREATE" ? join10(
14991
+ const targetFolder = input.action === "CREATE" ? join11(
14757
14992
  dirname6(rootFolder),
14758
14993
  `${basename4(rootFolder)}-${branch.replaceAll("/", "-")}`
14759
14994
  ) : changeFolder;
@@ -14993,7 +15228,7 @@ var checkoutMovedWorktree = async (payload, timeoutMs, signal) => {
14993
15228
  `Branch ${input.branch} is already checked out in ${occupiedFolder}`
14994
15229
  );
14995
15230
  }
14996
- targetFolder = join10(
15231
+ targetFolder = join11(
14997
15232
  dirname6(rootFolder),
14998
15233
  `${basename4(rootFolder)}-${input.branch.replaceAll("/", "-")}`
14999
15234
  );
@@ -15044,7 +15279,7 @@ var checkoutMovedWorktree = async (payload, timeoutMs, signal) => {
15044
15279
  const targetBranch = await currentBranch(targetFolder, timeoutMs, signal);
15045
15280
  const targetChanges = await statusState(targetFolder, timeoutMs, signal);
15046
15281
  if (occupiedFolder) {
15047
- const occupied = await realpath6(occupiedFolder);
15282
+ const occupied = await realpath7(occupiedFolder);
15048
15283
  if (occupied !== targetFolder) {
15049
15284
  throw new Error(
15050
15285
  `Branch ${input.branch} is checked out in another destination worktree`
@@ -15158,7 +15393,7 @@ var checkoutMovedWorktree = async (payload, timeoutMs, signal) => {
15158
15393
  };
15159
15394
  var deleteWorktree = async (payload, timeoutMs, signal) => {
15160
15395
  const input = worktreeDeleteJobPayload(payload);
15161
- const rootFolder = await realpath6(input.rootFolder);
15396
+ const rootFolder = await realpath7(input.rootFolder);
15162
15397
  if (!(await stat8(rootFolder)).isDirectory()) {
15163
15398
  throw new Error("Base repository is missing");
15164
15399
  }
@@ -15401,7 +15636,7 @@ var operateWorktree = async (payload, timeoutMs, signal) => {
15401
15636
 
15402
15637
  // src/handlers/index.ts
15403
15638
  var handlers = {
15404
- "cloudflared.runTunnel": runCloudflared,
15639
+ [COMMAND_RUN_JOB_KIND]: runCommand,
15405
15640
  [CCUSAGE_REPORT_JOB_KIND]: runCcusage,
15406
15641
  [BUILD_DATA_SCAN_JOB_KIND]: scanBuildData,
15407
15642
  [BUILD_DATA_SIZE_JOB_KIND]: sizeBuildData,
@@ -15489,7 +15724,9 @@ var JobExecutor = class {
15489
15724
  this.running.set(job.id, { controller, task });
15490
15725
  }
15491
15726
  cancel(jobId) {
15492
- this.running.get(jobId)?.controller.abort();
15727
+ const running = this.running.get(jobId);
15728
+ running?.controller.abort();
15729
+ return Boolean(running);
15493
15730
  }
15494
15731
  async cancelAll() {
15495
15732
  this.stopping = true;
@@ -15524,10 +15761,11 @@ var JobExecutor = class {
15524
15761
  {
15525
15762
  reportWorktreeActivity: (input) => this.client.reportWorktreeActivity(input),
15526
15763
  reportBuildProgress: (input) => this.client.reportBuildProgress(input),
15527
- appendBuildLogs: (buildId, events) => this.client.appendBuildLogs(buildId, events),
15764
+ appendBuildLogChunks: (buildId, chunks) => this.client.appendBuildLogChunks(buildId, chunks),
15528
15765
  uploadBuildArtifact: (input) => this.client.uploadBuildArtifact(input),
15529
15766
  claimSigningSecretTransfer: (transferId) => this.client.claimSigningSecretTransfer(transferId),
15530
- claimWorkflowJobSecrets: () => this.client.claimWorkflowJobSecrets(claimed.id)
15767
+ claimWorkflowJobSecrets: () => this.client.claimWorkflowJobSecrets(claimed.id),
15768
+ appendCommandOutput: (attemptId, chunks) => this.client.appendCommandOutput(claimed.id, attemptId, chunks)
15531
15769
  }
15532
15770
  );
15533
15771
  const codebaseId = claimed.payload && typeof claimed.payload === "object" && !Array.isArray(claimed.payload) && typeof claimed.payload.codebaseId === "string" ? String(claimed.payload.codebaseId) : null;
@@ -15703,8 +15941,8 @@ var CodebaseMonitor = class {
15703
15941
 
15704
15942
  // src/runs/run-manager.ts
15705
15943
  import { execFile as execFile4 } from "node:child_process";
15706
- import { mkdir as mkdir6, rm as rm12 } from "node:fs/promises";
15707
- import { dirname as dirname8, join as join14 } from "node:path";
15944
+ import { mkdir as mkdir6, rm as rm13 } from "node:fs/promises";
15945
+ import { dirname as dirname8, join as join15 } from "node:path";
15708
15946
  import { promisify as promisify4 } from "node:util";
15709
15947
 
15710
15948
  // src/runs/journal.ts
@@ -15714,10 +15952,10 @@ import {
15714
15952
  mkdir as mkdir5,
15715
15953
  readFile as readFile8,
15716
15954
  rename as rename4,
15717
- rm as rm9,
15718
- writeFile as writeFile6
15955
+ rm as rm10,
15956
+ writeFile as writeFile7
15719
15957
  } from "node:fs/promises";
15720
- import { dirname as dirname7, join as join11 } from "node:path";
15958
+ import { dirname as dirname7, join as join12 } from "node:path";
15721
15959
  var RunJournal = class {
15722
15960
  constructor(runId, attemptId) {
15723
15961
  this.runId = runId;
@@ -15736,13 +15974,13 @@ var RunJournal = class {
15736
15974
  this.attemptId = attemptId;
15737
15975
  }
15738
15976
  get directory() {
15739
- return join11(dirname7(configPath()), "runs", this.runId);
15977
+ return join12(dirname7(configPath()), "runs", this.runId);
15740
15978
  }
15741
15979
  get eventsPath() {
15742
- return join11(this.directory, "events.jsonl");
15980
+ return join12(this.directory, "events.jsonl");
15743
15981
  }
15744
15982
  get statePath() {
15745
- return join11(this.directory, "state.json");
15983
+ return join12(this.directory, "state.json");
15746
15984
  }
15747
15985
  async load() {
15748
15986
  if (this.loaded) return;
@@ -15843,10 +16081,10 @@ var RunJournal = class {
15843
16081
  const operation = this.saving.then(async () => {
15844
16082
  const temporary = `${this.statePath}.${process.pid}.${randomUUID4()}.tmp`;
15845
16083
  try {
15846
- await writeFile6(temporary, contents, { mode: 384 });
16084
+ await writeFile7(temporary, contents, { mode: 384 });
15847
16085
  await rename4(temporary, this.statePath);
15848
16086
  } catch (error) {
15849
- await rm9(temporary, { force: true }).catch(() => void 0);
16087
+ await rm10(temporary, { force: true }).catch(() => void 0);
15850
16088
  throw error;
15851
16089
  }
15852
16090
  });
@@ -25020,7 +25258,7 @@ function Yy(e) {
25020
25258
  var l = {};
25021
25259
  lt(l, { xid: () => u9, void: () => I9, uuidv7: () => n9, uuidv6: () => r9, uuidv4: () => t9, uuid: () => e9, url: () => o9, uppercase: () => Fl, unknown: () => Ke, union: () => $e, undefined: () => C9, ulid: () => l9, uint64: () => A9, uint32: () => w9, tuple: () => L9, trim: () => Wl, treeifyError: () => Yd, transform: () => jv, toUpperCase: () => Zl, toLowerCase: () => Kl, toJSONSchema: () => Js, templateLiteral: () => q9, symbol: () => O9, superRefine: () => ER, success: () => B9, stringbool: () => W9, stringFormat: () => x9, string: () => k, strictObject: () => N9, startsWith: () => Hl, size: () => $l, setErrorMap: () => J9, set: () => $9, safeParseAsync: () => gv, safeParse: () => mv, registry: () => hl, regexes: () => wo, regex: () => jl, refine: () => SR, record: () => je, readonly: () => hR, property: () => iv, promise: () => G9, prettifyError: () => Xd, preprocess: () => Km, prefault: () => lR, positive: () => tv, pipe: () => Fm, partialRecord: () => M9, parseAsync: () => fv, parse: () => dv, overwrite: () => Vn, optional: () => Ve, object: () => G, number: () => Ce, nullish: () => F9, nullable: () => zm, null: () => Bm, normalize: () => Vl, nonpositive: () => nv, nonoptional: () => uR, nonnegative: () => ov, never: () => Hm, negative: () => rv, nativeEnum: () => j9, nanoid: () => s9, nan: () => H9, multipleOf: () => wi, minSize: () => Ti, minLength: () => Ao, mime: () => Gl, maxSize: () => Ws, maxLength: () => Ks, map: () => U9, lte: () => Ur, lt: () => qn, lowercase: () => zl, looseObject: () => Bt, locales: () => Gs, literal: () => Z, length: () => Zs, lazy: () => bR, ksuid: () => p9, keyof: () => D9, jwt: () => b9, json: () => K9, iso: () => Ys, ipv6: () => f9, ipv4: () => d9, intersection: () => ru, int64: () => k9, int32: () => E9, int: () => hv, instanceof: () => V9, includes: () => Bl, guid: () => QZ, gte: () => ar, gt: () => Gn, globalRegistry: () => sr, getErrorMap: () => Y9, function: () => Dm, formatError: () => js, float64: () => S9, float32: () => v9, flattenError: () => $s, file: () => z9, enum: () => Jt, endsWith: () => ql, emoji: () => i9, email: () => XZ, e164: () => y9, discriminatedUnion: () => Vm, date: () => P9, custom: () => Hv, cuid2: () => c9, cuid: () => a9, core: () => Qr, config: () => ut, coerce: () => qv, clone: () => Ft, cidrv6: () => g9, cidrv4: () => m9, check: () => vR, catch: () => fR, boolean: () => ht, bigint: () => T9, base64url: () => _9, base64: () => h9, array: () => he, any: () => R9, _default: () => aR, _ZodString: () => _v, ZodXID: () => Tv, ZodVoid: () => JC, ZodUnknown: () => KC, ZodUnion: () => Mv, ZodUndefined: () => GC, ZodUUID: () => Wn, ZodURL: () => bv, ZodULID: () => wv, ZodType: () => de, ZodTuple: () => eR, ZodTransform: () => $v, ZodTemplateLiteral: () => _R, ZodSymbol: () => qC, ZodSuccess: () => pR, ZodStringFormat: () => Ge, ZodString: () => Xl, ZodSet: () => rR, ZodRecord: () => Uv, ZodRealError: () => Xs, ZodReadonly: () => gR, ZodPromise: () => xR, ZodPrefault: () => cR, ZodPipe: () => Bv, ZodOptional: () => zv, ZodObject: () => Gm, ZodNumberFormat: () => Qs, ZodNumber: () => Ql, ZodNullable: () => iR, ZodNull: () => VC, ZodNonOptional: () => Fv, ZodNever: () => ZC, ZodNanoID: () => vv, ZodNaN: () => mR, ZodMap: () => tR, ZodLiteral: () => nR, ZodLazy: () => yR, ZodKSUID: () => kv, ZodJWT: () => Nv, ZodIssueCode: () => Z9, ZodIntersection: () => QC, ZodISOTime: () => Um, ZodISODuration: () => $m, ZodISODateTime: () => Lm, ZodISODate: () => Mm, ZodIPv6: () => Ov, ZodIPv4: () => Av, ZodGUID: () => jm, ZodFile: () => oR, ZodError: () => JZ, ZodEnum: () => Yl, ZodEmoji: () => xv, ZodEmail: () => yv, ZodE164: () => Dv, ZodDiscriminatedUnion: () => XC, ZodDefault: () => sR, ZodDate: () => qm, ZodCustomStringFormat: () => HC, ZodCustom: () => Wm, ZodCatch: () => dR, ZodCUID2: () => Ev, ZodCUID: () => Sv, ZodCIDRv6: () => Rv, ZodCIDRv4: () => Cv, ZodBoolean: () => eu, ZodBigIntFormat: () => Lv, ZodBigInt: () => tu, ZodBase64URL: () => Pv, ZodBase64: () => Iv, ZodArray: () => YC, ZodAny: () => WC, TimePrecision: () => lm, NEVER: () => Kd, $output: () => sm, $input: () => am, $brand: () => Zd });
25022
25260
  var Qr = {};
25023
- lt(Qr, { version: () => tx, util: () => M, treeifyError: () => Yd, toJSONSchema: () => Js, toDotPath: () => yC, safeParseAsync: () => Eo, safeParse: () => So, registry: () => hl, regexes: () => wo, prettifyError: () => Xd, parseAsync: () => xi, parse: () => bi, locales: () => Gs, isValidJWT: () => MC, isValidBase64URL: () => LC, isValidBase64: () => ax, globalRegistry: () => sr, globalConfig: () => tl, function: () => Dm, formatError: () => js, flattenError: () => $s, config: () => ut, clone: () => Ft, _xid: () => Ol, _void: () => Tm, _uuidv7: () => vl, _uuidv6: () => xl, _uuidv4: () => bl, _uuid: () => yl, _url: () => Sl, _uppercase: () => Fl, _unknown: () => Ei, _union: () => OZ, _undefined: () => vm, _ulid: () => Al, _uint64: () => bm, _uint32: () => gm, _tuple: () => sv, _trim: () => Wl, _transform: () => UZ, _toUpperCase: () => Zl, _toLowerCase: () => Kl, _templateLiteral: () => VZ, _symbol: () => xm, _success: () => BZ, _stringbool: () => Im, _stringFormat: () => Pm, _string: () => cm, _startsWith: () => Hl, _size: () => $l, _set: () => DZ, _safeParseAsync: () => rf, _safeParse: () => tf, _regex: () => jl, _refine: () => Rm, _record: () => IZ, _readonly: () => GZ, _property: () => iv, _promise: () => KZ, _positive: () => tv, _pipe: () => qZ, _parseAsync: () => ef, _parse: () => Qd, _overwrite: () => Vn, _optional: () => $Z, _number: () => um, _nullable: () => jZ, _null: () => Sm, _normalize: () => Vl, _nonpositive: () => nv, _nonoptional: () => FZ, _nonnegative: () => ov, _never: () => wm, _negative: () => rv, _nativeEnum: () => LZ, _nanoid: () => wl, _nan: () => Am, _multipleOf: () => wi, _minSize: () => Ti, _minLength: () => Ao, _min: () => ar, _mime: () => Gl, _maxSize: () => Ws, _maxLength: () => Ks, _max: () => Ur, _map: () => PZ, _lte: () => Ur, _lt: () => qn, _lowercase: () => zl, _literal: () => MZ, _length: () => Zs, _lazy: () => WZ, _ksuid: () => Cl, _jwt: () => Ul, _isoTime: () => Zx, _isoDuration: () => Jx, _isoDateTime: () => Wx, _isoDate: () => Kx, _ipv6: () => Il, _ipv4: () => Rl, _intersection: () => RZ, _int64: () => ym, _int32: () => mm, _int: () => pm, _includes: () => Bl, _guid: () => Vs, _gte: () => ar, _gt: () => Gn, _float64: () => fm, _float32: () => dm, _file: () => Om, _enum: () => NZ, _endsWith: () => ql, _emoji: () => El, _email: () => _l, _e164: () => Ml, _discriminatedUnion: () => CZ, _default: () => zZ, _date: () => km, _custom: () => Cm, _cuid2: () => kl, _cuid: () => Tl, _coercedString: () => Vx, _coercedNumber: () => Yx, _coercedDate: () => ev, _coercedBoolean: () => Xx, _coercedBigint: () => Qx, _cidrv6: () => Dl, _cidrv4: () => Pl, _catch: () => HZ, _boolean: () => hm, _bigint: () => _m, _base64url: () => Ll, _base64: () => Nl, _array: () => Jl, _any: () => Em, TimePrecision: () => lm, NEVER: () => Kd, JSONSchemaGenerator: () => Nm, JSONSchema: () => zC, Doc: () => af, $output: () => sm, $input: () => am, $constructor: () => S, $brand: () => Zd, $ZodXID: () => bf, $ZodVoid: () => Uf, $ZodUnknown: () => Si, $ZodUnion: () => fl, $ZodUndefined: () => Df, $ZodUUID: () => pf, $ZodURL: () => ff, $ZodULID: () => yf, $ZodType: () => ie, $ZodTuple: () => ko, $ZodTransform: () => Hs, $ZodTemplateLiteral: () => rm10, $ZodSymbol: () => Pf, $ZodSuccess: () => Xf, $ZodStringFormat: () => Ue, $ZodString: () => To, $ZodSet: () => Hf, $ZodRegistry: () => gl, $ZodRecord: () => Ff, $ZodRealError: () => Us, $ZodReadonly: () => tm, $ZodPromise: () => nm, $ZodPrefault: () => Jf, $ZodPipe: () => qs, $ZodOptional: () => Wf, $ZodObject: () => dl, $ZodNumberFormat: () => Rf, $ZodNumber: () => ul, $ZodNullable: () => Kf, $ZodNull: () => Nf, $ZodNonOptional: () => Yf, $ZodNever: () => Mf, $ZodNanoID: () => gf, $ZodNaN: () => em, $ZodMap: () => Bf, $ZodLiteral: () => Gf, $ZodLazy: () => om, $ZodKSUID: () => xf, $ZodJWT: () => Of, $ZodIntersection: () => zf, $ZodISOTime: () => ix, $ZodISODuration: () => sx, $ZodISODateTime: () => nx, $ZodISODate: () => ox, $ZodIPv6: () => Sf, $ZodIPv4: () => vf, $ZodGUID: () => uf, $ZodFunction: () => av, $ZodFile: () => Vf, $ZodError: () => ll, $ZodEnum: () => qf, $ZodEmoji: () => mf, $ZodEmail: () => df, $ZodE164: () => Af, $ZodDiscriminatedUnion: () => jf, $ZodDefault: () => Zf, $ZodDate: () => $f, $ZodCustomStringFormat: () => Cf, $ZodCustom: () => im, $ZodCheckUpperCase: () => Kb, $ZodCheckStringFormat: () => zs, $ZodCheckStartsWith: () => Jb, $ZodCheckSizeEquals: () => Bb, $ZodCheckRegex: () => Vb, $ZodCheckProperty: () => Xb, $ZodCheckOverwrite: () => ex, $ZodCheckNumberFormat: () => $b, $ZodCheckMultipleOf: () => Ub, $ZodCheckMinSize: () => Fb, $ZodCheckMinLength: () => qb, $ZodCheckMimeType: () => Qb, $ZodCheckMaxSize: () => zb, $ZodCheckMaxLength: () => Hb, $ZodCheckLowerCase: () => Wb, $ZodCheckLessThan: () => of, $ZodCheckLengthEquals: () => Gb, $ZodCheckIncludes: () => Zb, $ZodCheckGreaterThan: () => sf, $ZodCheckEndsWith: () => Yb, $ZodCheckBigIntFormat: () => jb, $ZodCheck: () => Xe, $ZodCatch: () => Qf, $ZodCUID2: () => _f, $ZodCUID: () => hf, $ZodCIDRv6: () => wf, $ZodCIDRv4: () => Ef, $ZodBoolean: () => Fs, $ZodBigIntFormat: () => If, $ZodBigInt: () => pl, $ZodBase64URL: () => kf, $ZodBase64: () => Tf, $ZodAsyncError: () => Bn, $ZodArray: () => Bs, $ZodAny: () => Lf });
25261
+ lt(Qr, { version: () => tx, util: () => M, treeifyError: () => Yd, toJSONSchema: () => Js, toDotPath: () => yC, safeParseAsync: () => Eo, safeParse: () => So, registry: () => hl, regexes: () => wo, prettifyError: () => Xd, parseAsync: () => xi, parse: () => bi, locales: () => Gs, isValidJWT: () => MC, isValidBase64URL: () => LC, isValidBase64: () => ax, globalRegistry: () => sr, globalConfig: () => tl, function: () => Dm, formatError: () => js, flattenError: () => $s, config: () => ut, clone: () => Ft, _xid: () => Ol, _void: () => Tm, _uuidv7: () => vl, _uuidv6: () => xl, _uuidv4: () => bl, _uuid: () => yl, _url: () => Sl, _uppercase: () => Fl, _unknown: () => Ei, _union: () => OZ, _undefined: () => vm, _ulid: () => Al, _uint64: () => bm, _uint32: () => gm, _tuple: () => sv, _trim: () => Wl, _transform: () => UZ, _toUpperCase: () => Zl, _toLowerCase: () => Kl, _templateLiteral: () => VZ, _symbol: () => xm, _success: () => BZ, _stringbool: () => Im, _stringFormat: () => Pm, _string: () => cm, _startsWith: () => Hl, _size: () => $l, _set: () => DZ, _safeParseAsync: () => rf, _safeParse: () => tf, _regex: () => jl, _refine: () => Rm, _record: () => IZ, _readonly: () => GZ, _property: () => iv, _promise: () => KZ, _positive: () => tv, _pipe: () => qZ, _parseAsync: () => ef, _parse: () => Qd, _overwrite: () => Vn, _optional: () => $Z, _number: () => um, _nullable: () => jZ, _null: () => Sm, _normalize: () => Vl, _nonpositive: () => nv, _nonoptional: () => FZ, _nonnegative: () => ov, _never: () => wm, _negative: () => rv, _nativeEnum: () => LZ, _nanoid: () => wl, _nan: () => Am, _multipleOf: () => wi, _minSize: () => Ti, _minLength: () => Ao, _min: () => ar, _mime: () => Gl, _maxSize: () => Ws, _maxLength: () => Ks, _max: () => Ur, _map: () => PZ, _lte: () => Ur, _lt: () => qn, _lowercase: () => zl, _literal: () => MZ, _length: () => Zs, _lazy: () => WZ, _ksuid: () => Cl, _jwt: () => Ul, _isoTime: () => Zx, _isoDuration: () => Jx, _isoDateTime: () => Wx, _isoDate: () => Kx, _ipv6: () => Il, _ipv4: () => Rl, _intersection: () => RZ, _int64: () => ym, _int32: () => mm, _int: () => pm, _includes: () => Bl, _guid: () => Vs, _gte: () => ar, _gt: () => Gn, _float64: () => fm, _float32: () => dm, _file: () => Om, _enum: () => NZ, _endsWith: () => ql, _emoji: () => El, _email: () => _l, _e164: () => Ml, _discriminatedUnion: () => CZ, _default: () => zZ, _date: () => km, _custom: () => Cm, _cuid2: () => kl, _cuid: () => Tl, _coercedString: () => Vx, _coercedNumber: () => Yx, _coercedDate: () => ev, _coercedBoolean: () => Xx, _coercedBigint: () => Qx, _cidrv6: () => Dl, _cidrv4: () => Pl, _catch: () => HZ, _boolean: () => hm, _bigint: () => _m, _base64url: () => Ll, _base64: () => Nl, _array: () => Jl, _any: () => Em, TimePrecision: () => lm, NEVER: () => Kd, JSONSchemaGenerator: () => Nm, JSONSchema: () => zC, Doc: () => af, $output: () => sm, $input: () => am, $constructor: () => S, $brand: () => Zd, $ZodXID: () => bf, $ZodVoid: () => Uf, $ZodUnknown: () => Si, $ZodUnion: () => fl, $ZodUndefined: () => Df, $ZodUUID: () => pf, $ZodURL: () => ff, $ZodULID: () => yf, $ZodType: () => ie, $ZodTuple: () => ko, $ZodTransform: () => Hs, $ZodTemplateLiteral: () => rm11, $ZodSymbol: () => Pf, $ZodSuccess: () => Xf, $ZodStringFormat: () => Ue, $ZodString: () => To, $ZodSet: () => Hf, $ZodRegistry: () => gl, $ZodRecord: () => Ff, $ZodRealError: () => Us, $ZodReadonly: () => tm, $ZodPromise: () => nm, $ZodPrefault: () => Jf, $ZodPipe: () => qs, $ZodOptional: () => Wf, $ZodObject: () => dl, $ZodNumberFormat: () => Rf, $ZodNumber: () => ul, $ZodNullable: () => Kf, $ZodNull: () => Nf, $ZodNonOptional: () => Yf, $ZodNever: () => Mf, $ZodNanoID: () => gf, $ZodNaN: () => em, $ZodMap: () => Bf, $ZodLiteral: () => Gf, $ZodLazy: () => om, $ZodKSUID: () => xf, $ZodJWT: () => Of, $ZodIntersection: () => zf, $ZodISOTime: () => ix, $ZodISODuration: () => sx, $ZodISODateTime: () => nx, $ZodISODate: () => ox, $ZodIPv6: () => Sf, $ZodIPv4: () => vf, $ZodGUID: () => uf, $ZodFunction: () => av, $ZodFile: () => Vf, $ZodError: () => ll, $ZodEnum: () => qf, $ZodEmoji: () => mf, $ZodEmail: () => df, $ZodE164: () => Af, $ZodDiscriminatedUnion: () => jf, $ZodDefault: () => Zf, $ZodDate: () => $f, $ZodCustomStringFormat: () => Cf, $ZodCustom: () => im, $ZodCheckUpperCase: () => Kb, $ZodCheckStringFormat: () => zs, $ZodCheckStartsWith: () => Jb, $ZodCheckSizeEquals: () => Bb, $ZodCheckRegex: () => Vb, $ZodCheckProperty: () => Xb, $ZodCheckOverwrite: () => ex, $ZodCheckNumberFormat: () => $b, $ZodCheckMultipleOf: () => Ub, $ZodCheckMinSize: () => Fb, $ZodCheckMinLength: () => qb, $ZodCheckMimeType: () => Qb, $ZodCheckMaxSize: () => zb, $ZodCheckMaxLength: () => Hb, $ZodCheckLowerCase: () => Wb, $ZodCheckLessThan: () => of, $ZodCheckLengthEquals: () => Gb, $ZodCheckIncludes: () => Zb, $ZodCheckGreaterThan: () => sf, $ZodCheckEndsWith: () => Yb, $ZodCheckBigIntFormat: () => jb, $ZodCheck: () => Xe, $ZodCatch: () => Qf, $ZodCUID2: () => _f, $ZodCUID: () => hf, $ZodCIDRv6: () => wf, $ZodCIDRv4: () => Ef, $ZodBoolean: () => Fs, $ZodBigIntFormat: () => If, $ZodBigInt: () => pl, $ZodBase64URL: () => kf, $ZodBase64: () => Tf, $ZodAsyncError: () => Bn, $ZodArray: () => Bs, $ZodAny: () => Lf });
25024
25262
  var Kd = Object.freeze({ status: "aborted" });
25025
25263
  function S(e, t, r) {
25026
25264
  function n(a, c) {
@@ -26568,7 +26806,7 @@ var tm = S("$ZodReadonly", (e, t) => {
26568
26806
  function DC(e) {
26569
26807
  return e.value = Object.freeze(e.value), e;
26570
26808
  }
26571
- var rm10 = S("$ZodTemplateLiteral", (e, t) => {
26809
+ var rm11 = S("$ZodTemplateLiteral", (e, t) => {
26572
26810
  ie.init(e, t);
26573
26811
  let r = [];
26574
26812
  for (let n of t.parts) if (n instanceof ie) {
@@ -30375,7 +30613,7 @@ function hR(e) {
30375
30613
  return new gR({ type: "readonly", innerType: e });
30376
30614
  }
30377
30615
  var _R = S("ZodTemplateLiteral", (e, t) => {
30378
- rm10.init(e, t), de.init(e, t);
30616
+ rm11.init(e, t), de.init(e, t);
30379
30617
  });
30380
30618
  function q9(e, t) {
30381
30619
  return new _R({ type: "template_literal", parts: e, ...M.normalizeParams(t) });
@@ -41994,11 +42232,11 @@ var ClaudeAdapter = class {
41994
42232
  // src/runs/codex-adapter.ts
41995
42233
  import {
41996
42234
  execFile as execFile3,
41997
- spawn as spawn6
42235
+ spawn as spawn7
41998
42236
  } from "node:child_process";
41999
- import { mkdtemp as mkdtemp6, rm as rm11, writeFile as writeFile7 } from "node:fs/promises";
42000
- import { tmpdir as tmpdir6 } from "node:os";
42001
- import { join as join13 } from "node:path";
42237
+ import { mkdtemp as mkdtemp7, rm as rm12, writeFile as writeFile8 } from "node:fs/promises";
42238
+ import { tmpdir as tmpdir7 } from "node:os";
42239
+ import { join as join14 } from "node:path";
42002
42240
  import { createInterface } from "node:readline";
42003
42241
  import { promisify as promisify3 } from "node:util";
42004
42242
  var SUPPORTED_CODEX_APP_SERVER_MINORS = ["0.144", "0.145"];
@@ -42056,7 +42294,7 @@ var CodexAppServer = class {
42056
42294
  async start() {
42057
42295
  const modelCatalogPath = await this.createBundledModelCatalog();
42058
42296
  const modelCatalogDirectory = this.modelCatalogDirectory;
42059
- const child = spawn6("codex", codexAppServerArgs(modelCatalogPath), {
42297
+ const child = spawn7("codex", codexAppServerArgs(modelCatalogPath), {
42060
42298
  stdio: ["pipe", "pipe", "pipe"],
42061
42299
  env: process.env
42062
42300
  });
@@ -42125,7 +42363,7 @@ var CodexAppServer = class {
42125
42363
  }
42126
42364
  }
42127
42365
  async createBundledModelCatalog() {
42128
- const directory = await mkdtemp6(join13(tmpdir6(), "aide-codex-models-"));
42366
+ const directory = await mkdtemp7(join14(tmpdir7(), "aide-codex-models-"));
42129
42367
  try {
42130
42368
  const { stdout } = await execFileAsync2(
42131
42369
  "codex",
@@ -42135,12 +42373,12 @@ var CodexAppServer = class {
42135
42373
  maxBuffer: 16 * 1024 * 1024
42136
42374
  }
42137
42375
  );
42138
- const catalogPath = join13(directory, "models.json");
42139
- await writeFile7(catalogPath, stdout, "utf8");
42376
+ const catalogPath = join14(directory, "models.json");
42377
+ await writeFile8(catalogPath, stdout, "utf8");
42140
42378
  this.modelCatalogDirectory = directory;
42141
42379
  return catalogPath;
42142
42380
  } catch (error) {
42143
- await rm11(directory, { recursive: true, force: true }).catch(
42381
+ await rm12(directory, { recursive: true, force: true }).catch(
42144
42382
  () => void 0
42145
42383
  );
42146
42384
  throw error;
@@ -42151,7 +42389,7 @@ var CodexAppServer = class {
42151
42389
  if (this.modelCatalogDirectory === directory) {
42152
42390
  this.modelCatalogDirectory = void 0;
42153
42391
  }
42154
- await rm11(directory, { recursive: true, force: true }).catch(
42392
+ await rm12(directory, { recursive: true, force: true }).catch(
42155
42393
  () => void 0
42156
42394
  );
42157
42395
  }
@@ -48829,7 +49067,7 @@ var RunManager = class {
48829
49067
  5
48830
49068
  );
48831
49069
  await this.completeCommand(command3.id, "SUCCEEDED");
48832
- await rm12(join14(dirname8(configPath()), "runs", run.id, "attachments"), {
49070
+ await rm13(join15(dirname8(configPath()), "runs", run.id, "attachments"), {
48833
49071
  recursive: true,
48834
49072
  force: true
48835
49073
  }).catch(() => void 0);
@@ -49010,7 +49248,7 @@ var RunManager = class {
49010
49248
  this.active.delete(run.id);
49011
49249
  this.interruptionRequests.delete(run.id);
49012
49250
  this.executingCommands.delete(command3.id);
49013
- await rm12(join14(dirname8(configPath()), "runs", run.id, "attachments"), {
49251
+ await rm13(join15(dirname8(configPath()), "runs", run.id, "attachments"), {
49014
49252
  recursive: true,
49015
49253
  force: true
49016
49254
  }).catch(() => void 0);
@@ -49238,11 +49476,11 @@ var RunManager = class {
49238
49476
  }
49239
49477
  async stageAttachments(runId, attachments) {
49240
49478
  if (!attachments.length) return [];
49241
- const directory = join14(dirname8(configPath()), "runs", runId, "attachments");
49479
+ const directory = join15(dirname8(configPath()), "runs", runId, "attachments");
49242
49480
  await mkdir6(directory, { recursive: true, mode: 448 });
49243
49481
  return Promise.all(
49244
49482
  attachments.map(async (attachment) => {
49245
- const path = join14(
49483
+ const path = join15(
49246
49484
  directory,
49247
49485
  `${attachment.id}-${safeFilename(attachment.filename)}`
49248
49486
  );
@@ -49399,6 +49637,12 @@ async function runAgent(config, signal) {
49399
49637
  executor.cancel(job.id);
49400
49638
  return;
49401
49639
  }
49640
+ if (job.status === "CANCELLING") {
49641
+ if (!executor.cancel(job.id)) {
49642
+ await client2.completeJob(job.id, "CANCELLED");
49643
+ }
49644
+ return;
49645
+ }
49402
49646
  if (job.status !== "RUNNING" || !recoverInterrupted && !interruptedJobs.has(job.id)) {
49403
49647
  executor.execute(job);
49404
49648
  return;
@@ -49699,7 +49943,6 @@ function redactedRequestHeaders(headers) {
49699
49943
  }
49700
49944
 
49701
49945
  // src/index.ts
49702
- var execFileAsync4 = promisify5(execFile5);
49703
49946
  function flags(args) {
49704
49947
  const result = {};
49705
49948
  const headerValues = [];
@@ -49802,22 +50045,6 @@ async function doctor() {
49802
50045
  detail: error instanceof Error ? error.message : String(error)
49803
50046
  });
49804
50047
  }
49805
- try {
49806
- const { stdout, stderr } = await execFileAsync4("cloudflared", [
49807
- "--version"
49808
- ]);
49809
- checks.push({
49810
- check: "cloudflared",
49811
- ok: true,
49812
- detail: (stdout || stderr).trim()
49813
- });
49814
- } catch (error) {
49815
- checks.push({
49816
- check: "cloudflared",
49817
- ok: false,
49818
- detail: error instanceof Error ? error.message : String(error)
49819
- });
49820
- }
49821
50048
  for (const check of checks)
49822
50049
  console.log(
49823
50050
  `${check.ok ? "PASS" : "FAIL"} ${check.check}: ${check.detail}`
@@ -49835,21 +50062,26 @@ async function main() {
49835
50062
  if (command3 === "doctor") return doctor();
49836
50063
  if (command3 === "run" || command3 === "dev") {
49837
50064
  const controller = new AbortController();
49838
- process.once("SIGINT", () => controller.abort());
49839
- process.once("SIGTERM", () => controller.abort());
49840
- if (command3 === "dev") {
49841
- const options = flags(args).values;
49842
- const server = options.server ?? process.env.CONTROL_AGENT_DEV_SERVER ?? `http://127.0.0.1:${process.env.PORT ?? "3000"}`;
49843
- return runDevelopmentAgent(
49844
- {
49845
- server,
49846
- websocketServer: options["websocket-server"] ?? process.env.CONTROL_AGENT_DEV_WEBSOCKET_SERVER ?? process.env.NEXT_PUBLIC_AGENT_WS_URL,
49847
- name: options.name
49848
- },
49849
- controller.signal
49850
- );
50065
+ const stop2 = () => controller.abort();
50066
+ const shutdownSignals = ["SIGINT", "SIGTERM", "SIGHUP"];
50067
+ for (const signal of shutdownSignals) process.once(signal, stop2);
50068
+ try {
50069
+ if (command3 === "dev") {
50070
+ const options = flags(args).values;
50071
+ const server = options.server ?? process.env.CONTROL_AGENT_DEV_SERVER ?? `http://127.0.0.1:${process.env.PORT ?? "3000"}`;
50072
+ return await runDevelopmentAgent(
50073
+ {
50074
+ server,
50075
+ websocketServer: options["websocket-server"] ?? process.env.CONTROL_AGENT_DEV_WEBSOCKET_SERVER ?? process.env.NEXT_PUBLIC_AGENT_WS_URL,
50076
+ name: options.name
50077
+ },
50078
+ controller.signal
50079
+ );
50080
+ }
50081
+ return await runAgent(await loadConfig(), controller.signal);
50082
+ } finally {
50083
+ for (const signal of shutdownSignals) process.off(signal, stop2);
49851
50084
  }
49852
- return runAgent(await loadConfig(), controller.signal);
49853
50085
  }
49854
50086
  throw new Error(`Unknown command: ${command3}`);
49855
50087
  }