@alan-ai-hq/agent-manager-linux-x64 0.1.151 → 0.1.153

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/alan-agent.cjs +812 -1015
  2. package/alan-holder.cjs +284 -769
  3. package/package.json +1 -1
package/alan-holder.cjs CHANGED
@@ -19798,6 +19798,10 @@ var init_agent_context = __esm({
19798
19798
  installCommand: external_exports.string().max(8192).nullable(),
19799
19799
  startCommand: external_exports.string().max(8192).nullable(),
19800
19800
  imageBuildId: external_exports.guid().nullable(),
19801
+ /** The repository whose `.alan/` the image build reads; a branch build swaps only its branch. */
19802
+ primaryRepository: machinePathSchema.optional(),
19803
+ /** Where install steps and the start command run: the repository, or the workspace with several. */
19804
+ setupDirectory: machinePathSchema.optional(),
19801
19805
  /** The newest build when it is not the one sessions boot from. */
19802
19806
  pendingBuild: agentContextBuildSchema.optional(),
19803
19807
  /** Saved variable names; values never leave the API. */
@@ -20368,7 +20372,7 @@ var init_run_context = __esm({
20368
20372
  });
20369
20373
 
20370
20374
  // ../shared/dist/runtime-v2/desired-state.js
20371
- var repoLocalPathSchema, requestedCheckoutSchema, runSpecSchema, desiredRunSchema, desiredStateSchema;
20375
+ var repoLocalPathSchema, requestedCheckoutSchema, runSpecSchema, desiredRunSchema, pendingUploadSchema, desiredStateSchema;
20372
20376
  var init_desired_state = __esm({
20373
20377
  "../shared/dist/runtime-v2/desired-state.js"() {
20374
20378
  "use strict";
@@ -20438,10 +20442,17 @@ var init_desired_state = __esm({
20438
20442
  spec: runSpecSchema,
20439
20443
  abortRequested: external_exports.boolean()
20440
20444
  });
20445
+ pendingUploadSchema = external_exports.object({
20446
+ runId: runIdSchema,
20447
+ conversationId: conversationIdSchema,
20448
+ admittedOffset: external_exports.number().int().nonnegative()
20449
+ });
20441
20450
  desiredStateSchema = external_exports.object({
20442
20451
  runs: external_exports.array(desiredRunSchema),
20443
20452
  /** The machine's saved workspaces; replaces the previous server list on every read. */
20444
- approvedWorkspacePaths: external_exports.array(machinePathSchema).max(2e3).optional()
20453
+ approvedWorkspacePaths: external_exports.array(machinePathSchema).max(2e3).optional(),
20454
+ /** Absent from an older server: the runtime then uploads only on its own doorbell. */
20455
+ pendingUploads: external_exports.array(pendingUploadSchema).optional()
20445
20456
  });
20446
20457
  }
20447
20458
  });
@@ -22587,7 +22598,7 @@ function plan(command, args, options) {
22587
22598
  function captureOutput(command, args, options) {
22588
22599
  const launch = plan(command, args, options);
22589
22600
  if (launch === void 0) return Promise.resolve(NEVER_STARTED);
22590
- return new Promise((resolve9) => {
22601
+ return new Promise((resolve8) => {
22591
22602
  (0, import_child_process.execFile)(
22592
22603
  launch.file,
22593
22604
  [...launch.args],
@@ -22601,7 +22612,7 @@ function captureOutput(command, args, options) {
22601
22612
  },
22602
22613
  (error61, stdout, stderr) => {
22603
22614
  const code = error61 && typeof error61.code === "number" ? error61.code : error61 ? void 0 : 0;
22604
- resolve9({ stdout, stderr, exitCode: code });
22615
+ resolve8({ stdout, stderr, exitCode: code });
22605
22616
  }
22606
22617
  );
22607
22618
  });
@@ -22643,18 +22654,18 @@ function decode3(bytes, start, end) {
22643
22654
  }
22644
22655
  async function linuxStartTicks(pid) {
22645
22656
  try {
22646
- const stat16 = await (0, import_promises6.readFile)(`/proc/${pid}/stat`, "utf8");
22647
- const fields = stat16.slice(stat16.lastIndexOf(")") + 2).split(" ");
22657
+ const stat15 = await (0, import_promises6.readFile)(`/proc/${pid}/stat`, "utf8");
22658
+ const fields = stat15.slice(stat15.lastIndexOf(")") + 2).split(" ");
22648
22659
  return fields[19];
22649
22660
  } catch {
22650
22661
  return void 0;
22651
22662
  }
22652
22663
  }
22653
22664
  function psStartTime(pid) {
22654
- return new Promise((resolve9) => {
22665
+ return new Promise((resolve8) => {
22655
22666
  (0, import_child_process2.execFile)("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 2e3 }, (error61, stdout) => {
22656
22667
  const text2 = stdout.trim();
22657
- resolve9(error61 || !text2 ? void 0 : text2);
22668
+ resolve8(error61 || !text2 ? void 0 : text2);
22658
22669
  });
22659
22670
  });
22660
22671
  }
@@ -22683,12 +22694,12 @@ function parseProcessList(text2) {
22683
22694
  }
22684
22695
  function listProcesses(platform = process.platform) {
22685
22696
  if (platform === "win32") return Promise.resolve([]);
22686
- return new Promise((resolve9) => {
22697
+ return new Promise((resolve8) => {
22687
22698
  (0, import_child_process3.execFile)(
22688
22699
  "ps",
22689
22700
  ["-A", "-o", "pid=,ppid=,pgid=,lstart="],
22690
22701
  { timeout: 5e3, maxBuffer: 8 * 1024 * 1024 },
22691
- (error61, stdout) => resolve9(error61 ? [] : parseProcessList(stdout))
22702
+ (error61, stdout) => resolve8(error61 ? [] : parseProcessList(stdout))
22692
22703
  );
22693
22704
  });
22694
22705
  }
@@ -22728,11 +22739,11 @@ async function taskkill(pid, options) {
22728
22739
  stdio: "ignore",
22729
22740
  windowsHide: true
22730
22741
  });
22731
- const exited = new Promise((resolve9) => {
22732
- killer.once("error", (error210) => resolve9(error210));
22742
+ const exited = new Promise((resolve8) => {
22743
+ killer.once("error", (error210) => resolve8(error210));
22733
22744
  killer.once(
22734
22745
  "exit",
22735
- (code, signal) => resolve9(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22746
+ (code, signal) => resolve8(code === 0 ? void 0 : new Error(`taskkill failed: exit ${code}, signal ${signal}`))
22736
22747
  );
22737
22748
  });
22738
22749
  const timedOut = clock.sleep(options.timeoutMs ?? DEFAULT_TASKKILL_TIMEOUT_MS, timeout.signal).then(() => new Error("taskkill timed out")).catch(() => void 0);
@@ -22775,9 +22786,9 @@ function signalGroup(pgid, signal, onError) {
22775
22786
  if (!isAlreadyDead(error61)) onError?.("group", error61);
22776
22787
  }
22777
22788
  }
22778
- function liveEscapedGroups(snapshot2, rootPid, remembered) {
22779
- const leaders = new Map(snapshot2.map((entry) => [entry.pid, entry.startedAt]));
22780
- const groups = new Set(escapedGroups(snapshot2, rootPid).map((group) => group.pgid));
22789
+ function liveEscapedGroups(snapshot, rootPid, remembered) {
22790
+ const leaders = new Map(snapshot.map((entry) => [entry.pid, entry.startedAt]));
22791
+ const groups = new Set(escapedGroups(snapshot, rootPid).map((group) => group.pgid));
22781
22792
  for (const [pgid, startedAt] of remembered) {
22782
22793
  if (leaders.get(pgid) === startedAt) groups.add(pgid);
22783
22794
  }
@@ -22988,10 +22999,10 @@ function spawnCli(options) {
22988
22999
  function waitForSpawn(child, command) {
22989
23000
  if (isWindowsJob(child)) return waitForWindowsJob(child, command);
22990
23001
  if (child.pid !== void 0) return Promise.resolve();
22991
- return new Promise((resolve9, reject) => {
23002
+ return new Promise((resolve8, reject) => {
22992
23003
  const onSpawn = () => {
22993
23004
  child.off("error", onError);
22994
- resolve9();
23005
+ resolve8();
22995
23006
  };
22996
23007
  const onError = (error61) => {
22997
23008
  child.off("spawn", onSpawn);
@@ -23923,15 +23934,6 @@ var init_transcript_fold = __esm({
23923
23934
  }
23924
23935
  });
23925
23936
 
23926
- // ../shared/dist/agent/acp/transcript-live.js
23927
- var TRANSCRIPT_LIVE_BATCH_BYTES;
23928
- var init_transcript_live = __esm({
23929
- "../shared/dist/agent/acp/transcript-live.js"() {
23930
- "use strict";
23931
- TRANSCRIPT_LIVE_BATCH_BYTES = 32 * 1024;
23932
- }
23933
- });
23934
-
23935
23937
  // ../shared/dist/agent/acp/index.js
23936
23938
  var init_acp = __esm({
23937
23939
  "../shared/dist/agent/acp/index.js"() {
@@ -23952,7 +23954,6 @@ var init_acp = __esm({
23952
23954
  init_transcript_fold();
23953
23955
  init_transcript_http();
23954
23956
  init_transcript_ingestion();
23955
- init_transcript_live();
23956
23957
  init_types2();
23957
23958
  }
23958
23959
  });
@@ -24903,8 +24904,8 @@ function readMediaFiles(candidates2, cwd, mimeByExt, maxBytes) {
24903
24904
  seen.add(path);
24904
24905
  const mimeType = mimeByExt[(0, import_path3.extname)(path).toLowerCase()];
24905
24906
  if (!mimeType) continue;
24906
- const stat16 = (0, import_fs4.statSync)(path);
24907
- if (!stat16.isFile() || stat16.size <= 0 || stat16.size > maxBytes) continue;
24907
+ const stat15 = (0, import_fs4.statSync)(path);
24908
+ if (!stat15.isFile() || stat15.size <= 0 || stat15.size > maxBytes) continue;
24908
24909
  files.push({ path, mimeType, buffer: (0, import_fs4.readFileSync)(path) });
24909
24910
  }
24910
24911
  return files;
@@ -24979,8 +24980,8 @@ function createJsonRpcPeer(writer, handlers) {
24979
24980
  },
24980
24981
  request: (method, params = {}) => {
24981
24982
  const id = counter.next++;
24982
- return new Promise((resolve9, reject) => {
24983
- pending.set(id, { method, resolve: resolve9, reject });
24983
+ return new Promise((resolve8, reject) => {
24984
+ pending.set(id, { method, resolve: resolve8, reject });
24984
24985
  writer.write({ id, method, params }).catch((error61) => {
24985
24986
  pending.delete(id);
24986
24987
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -25093,7 +25094,7 @@ function createNdjsonWriter(stream) {
25093
25094
  get writable() {
25094
25095
  return stream.writable && !stream.destroyed && failure5.error === void 0;
25095
25096
  },
25096
- write: (value) => new Promise((resolve9, reject) => {
25097
+ write: (value) => new Promise((resolve8, reject) => {
25097
25098
  if (failure5.error) {
25098
25099
  reject(failure5.error);
25099
25100
  return;
@@ -25105,7 +25106,7 @@ function createNdjsonWriter(stream) {
25105
25106
  stream.write(`${JSON.stringify(value)}
25106
25107
  `, (error61) => {
25107
25108
  if (error61) reject(error61);
25108
- else resolve9();
25109
+ else resolve8();
25109
25110
  });
25110
25111
  }),
25111
25112
  end: () => {
@@ -25137,11 +25138,11 @@ function hostProcess(child, tree, options, handlers) {
25137
25138
  });
25138
25139
  child.stderr.on("data", (chunk) => stderr.push(chunk));
25139
25140
  child.stderr.once("end", () => stderr.flush());
25140
- const processExit = new Promise((resolve9) => {
25141
- child.once("exit", (code, signal) => resolve9({ code, signal }));
25141
+ const processExit = new Promise((resolve8) => {
25142
+ child.once("exit", (code, signal) => resolve8({ code, signal }));
25142
25143
  });
25143
- const outputEnded = new Promise((resolve9) => {
25144
- child.stdout.once("close", () => resolve9());
25144
+ const outputEnded = new Promise((resolve8) => {
25145
+ child.stdout.once("close", () => resolve8());
25145
25146
  });
25146
25147
  const watch = async () => {
25147
25148
  const { clock, stdoutDrainMs, log, name } = options;
@@ -25438,13 +25439,13 @@ var init_chunk_A2TG6ROT = __esm({
25438
25439
  const turnId = input2.turnId;
25439
25440
  let finish = () => {
25440
25441
  };
25441
- const done = new Promise((resolve9) => {
25442
+ const done = new Promise((resolve8) => {
25442
25443
  finish = (outcome2) => {
25443
25444
  if (this.#current?.id !== turnId) return;
25444
25445
  this.#current = void 0;
25445
25446
  if (this.#state === "busy") this.#state = "idle";
25446
25447
  this.#emit({ type: "turn_ended", turnId, outcome: outcome2 });
25447
- resolve9({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
25448
+ resolve8({ turnId, outcome: outcome2, providerSessionId: this.#sessionId });
25448
25449
  };
25449
25450
  });
25450
25451
  const pending = {
@@ -25673,7 +25674,7 @@ var init_chunk_J2KTV5FP = __esm({
25673
25674
  }
25674
25675
  });
25675
25676
 
25676
- // ../agent-core/dist/chunk-GI3ZGXTY.js
25677
+ // ../agent-core/dist/chunk-GW6CC6A3.js
25677
25678
  function repositories(input2, context) {
25678
25679
  const problems = new Map(input2.problems.map((problem) => [problem.path, problem]));
25679
25680
  const listed = context?.repositories ?? [];
@@ -25734,7 +25735,12 @@ function environmentInstructions(environment, cwd) {
25734
25735
  );
25735
25736
  } else if (build?.status === "failed") {
25736
25737
  lines.push(
25737
- `The latest image build (${build.id}) failed; sessions still boot from the previous image.`
25738
+ environment.imageBuildId ? `The latest image build (${build.id}) failed; sessions still boot from the previous image.` : `The latest image build (${build.id}) failed; this environment has no image yet.`
25739
+ );
25740
+ }
25741
+ if (environment.primaryRepository && environment.setupDirectory) {
25742
+ lines.push(
25743
+ `Image builds read .alan/ from ${environment.primaryRepository}; install steps and the start command run from ${environment.setupDirectory}.`
25738
25744
  );
25739
25745
  }
25740
25746
  if (environment.variables.length > 0) {
@@ -25742,18 +25748,18 @@ function environmentInstructions(environment, cwd) {
25742
25748
  }
25743
25749
  return lines;
25744
25750
  }
25745
- function instructionsFor(snapshot2) {
25746
- const cwd = snapshot2.workspace.cwd ?? snapshot2.workspace.root ?? "the workspace";
25751
+ function instructionsFor(snapshot) {
25752
+ const cwd = snapshot.workspace.cwd ?? snapshot.workspace.root ?? "the workspace";
25747
25753
  return [
25748
- ...snapshot2.session.trigger === "image_build" ? ["Alan sent this turn, not the user: it reports an image build result."] : [],
25749
- ...snapshot2.environment ? environmentInstructions(snapshot2.environment, cwd) : []
25754
+ ...snapshot.session.trigger === "image_build" ? ["Alan sent this turn, not the user: it reports an image build result."] : [],
25755
+ ...snapshot.environment ? environmentInstructions(snapshot.environment, cwd) : []
25750
25756
  ];
25751
25757
  }
25752
- function startingInstructions(snapshot2) {
25753
- const cwd = snapshot2.workspace.cwd ?? snapshot2.workspace.root;
25758
+ function startingInstructions(snapshot) {
25759
+ const cwd = snapshot.workspace.cwd ?? snapshot.workspace.root;
25754
25760
  return [
25755
25761
  ...cwd ? [`Work from ${cwd}.`] : [],
25756
- ...snapshot2.workspace.repositories.flatMap(repositoryInstructions)
25762
+ ...snapshot.workspace.repositories.flatMap(repositoryInstructions)
25757
25763
  ];
25758
25764
  }
25759
25765
  function sessionKind(input2, context) {
@@ -25761,6 +25767,12 @@ function sessionKind(input2, context) {
25761
25767
  if (input2.spec.workflowExecutionId) return "workflow";
25762
25768
  return input2.spec.taskId ? "task" : "chat";
25763
25769
  }
25770
+ function setupPathsOf(environment) {
25771
+ return {
25772
+ ...environment.primaryRepository ? { primaryRepository: environment.primaryRepository } : {},
25773
+ ...environment.setupDirectory ? { setupDirectory: environment.setupDirectory } : {}
25774
+ };
25775
+ }
25764
25776
  function environmentOf(input2, context) {
25765
25777
  const environment = context?.environment;
25766
25778
  if (!environment) return void 0;
@@ -25771,22 +25783,23 @@ function environmentOf(input2, context) {
25771
25783
  installCommand: environment.installCommand,
25772
25784
  startCommand: environment.startCommand,
25773
25785
  imageBuildId: environment.imageBuildId,
25786
+ ...setupPathsOf(environment),
25774
25787
  ...environment.pendingBuild ? { pendingBuild: environment.pendingBuild } : {},
25775
25788
  variables: environment.variables,
25776
25789
  ...start ? { start: start.state === "not_configured" ? start : { ...start, log: input2.startLogPath } } : {}
25777
25790
  };
25778
25791
  }
25779
- function knownContext(snapshot2) {
25780
- const organizationId = snapshot2?.session.organizationId;
25781
- if (!snapshot2 || !organizationId) return void 0;
25782
- const environment = snapshot2.environment;
25792
+ function knownContext(snapshot) {
25793
+ const organizationId = snapshot?.session.organizationId;
25794
+ if (!snapshot || !organizationId) return void 0;
25795
+ const environment = snapshot.environment;
25783
25796
  return {
25784
- kind: snapshot2.session.kind,
25797
+ kind: snapshot.session.kind,
25785
25798
  trigger: "user",
25786
25799
  organizationId,
25787
- ...snapshot2.task ? { taskWorkingBranch: snapshot2.task.workingBranch } : {},
25788
- ...snapshot2.pullRequest ? { pullRequest: snapshot2.pullRequest } : {},
25789
- repositories: snapshot2.workspace.repositories.flatMap(
25800
+ ...snapshot.task ? { taskWorkingBranch: snapshot.task.workingBranch } : {},
25801
+ ...snapshot.pullRequest ? { pullRequest: snapshot.pullRequest } : {},
25802
+ repositories: snapshot.workspace.repositories.flatMap(
25790
25803
  ({ path, name, url: url2, branch, branchSource, base }) => name && url2 && branch && branchSource && base ? [{ path, name, url: url2, branch, branchSource, base }] : []
25791
25804
  ),
25792
25805
  ...environment ? {
@@ -25796,6 +25809,7 @@ function knownContext(snapshot2) {
25796
25809
  installCommand: environment.installCommand,
25797
25810
  startCommand: environment.startCommand,
25798
25811
  imageBuildId: environment.imageBuildId,
25812
+ ...setupPathsOf(environment),
25799
25813
  ...environment.pendingBuild ? { pendingBuild: environment.pendingBuild } : {},
25800
25814
  variables: environment.variables
25801
25815
  }
@@ -25833,7 +25847,7 @@ function isScalar(value) {
25833
25847
  }
25834
25848
  function scalar(value) {
25835
25849
  if (typeof value !== "string") return String(value);
25836
- return PLAIN_SCALAR.test(value) ? value : JSON.stringify(value);
25850
+ return PLAIN_SCALAR.test(value) ? value : JSON.stringify(value).replaceAll("<", "\\u003c");
25837
25851
  }
25838
25852
  function snakeCase(key) {
25839
25853
  return key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
@@ -25913,15 +25927,15 @@ function updateBody(previous, next) {
25913
25927
  if (Object.keys(facts).length === 0) return void 0;
25914
25928
  return next.session.trigger === "user" ? facts : { session: { trigger: next.session.trigger }, ...facts };
25915
25929
  }
25916
- function renderAgentContext(snapshot2, previous) {
25930
+ function renderAgentContext(snapshot, previous) {
25917
25931
  const full = block("alan_agent_context", {
25918
- ...snapshot2,
25919
- ...snapshot2.environment ? { environment: withCommandPreviews(snapshot2.environment) } : {},
25920
- instructions: [...startingInstructions(snapshot2), ...snapshot2.instructions]
25932
+ ...snapshot,
25933
+ ...snapshot.environment ? { environment: withCommandPreviews(snapshot.environment) } : {},
25934
+ instructions: [...startingInstructions(snapshot), ...snapshot.instructions]
25921
25935
  });
25922
- const update = previous ? updateBody(previous, snapshot2) : void 0;
25936
+ const update = previous ? updateBody(previous, snapshot) : void 0;
25923
25937
  return {
25924
- snapshot: snapshot2,
25938
+ snapshot,
25925
25939
  full,
25926
25940
  ...update ? { update: block("alan_agent_context_update", update) } : {}
25927
25941
  };
@@ -26287,8 +26301,8 @@ ${body}` : body;
26287
26301
  return spec.mode === "plan" ? planModePrefix(prefixed) : prefixed;
26288
26302
  }
26289
26303
  var startCommandStateSchema, repositorySnapshotSchema, environmentSnapshotSchema, agentContextSnapshotSchema, BRANCH_REASONS, PLAIN_SCALAR, COMMAND_PREVIEW_CHARS, MAX_PARSED_ATTACHMENTS, MAX_PARSED_ATTACHMENT_CHARS, MAX_METADATA_CHARS, UNAVAILABLE, READ_ONLY_MODES, AGENT_MODES;
26290
- var init_chunk_GI3ZGXTY = __esm({
26291
- "../agent-core/dist/chunk-GI3ZGXTY.js"() {
26304
+ var init_chunk_GW6CC6A3 = __esm({
26305
+ "../agent-core/dist/chunk-GW6CC6A3.js"() {
26292
26306
  "use strict";
26293
26307
  init_runtime_v2();
26294
26308
  init_zod();
@@ -26317,6 +26331,8 @@ var init_chunk_GI3ZGXTY = __esm({
26317
26331
  installCommand: external_exports.string().nullable(),
26318
26332
  startCommand: external_exports.string().nullable(),
26319
26333
  imageBuildId: external_exports.string().nullable(),
26334
+ primaryRepository: external_exports.string().optional(),
26335
+ setupDirectory: external_exports.string().optional(),
26320
26336
  pendingBuild: agentContextBuildSchema.optional(),
26321
26337
  variables: external_exports.array(external_exports.string()),
26322
26338
  start: external_exports.intersection(startCommandStateSchema, external_exports.object({ log: external_exports.string().optional() })).optional()
@@ -27341,18 +27357,24 @@ function realCwd(cwd) {
27341
27357
  return cwd;
27342
27358
  }
27343
27359
  }
27360
+ function projectDirs(projectsRoot) {
27361
+ try {
27362
+ return (0, import_fs5.readdirSync)(projectsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
27363
+ } catch {
27364
+ return [];
27365
+ }
27366
+ }
27344
27367
  function claudeSessionLogExists(query) {
27345
27368
  if (!query.sessionId || !query.cwd) return false;
27346
- for (const cwd of /* @__PURE__ */ new Set([query.cwd, realCwd(query.cwd)])) {
27347
- const log = (0, import_path5.join)(
27348
- query.claudeHome,
27349
- "projects",
27350
- encodeProjectDir(cwd),
27351
- `${query.sessionId}.jsonl`
27352
- );
27353
- if ((0, import_fs5.existsSync)(log)) return true;
27354
- }
27355
- return false;
27369
+ const projectsRoot = (0, import_path5.join)(query.claudeHome, "projects");
27370
+ const fileName = `${query.sessionId}.jsonl`;
27371
+ const here = new Set([query.cwd, realCwd(query.cwd)].map(encodeProjectDir));
27372
+ for (const dir of here) {
27373
+ if ((0, import_fs5.existsSync)((0, import_path5.join)(projectsRoot, dir, fileName))) return true;
27374
+ }
27375
+ return projectDirs(projectsRoot).some(
27376
+ (dir) => !here.has(dir) && (0, import_fs5.existsSync)((0, import_path5.join)(projectsRoot, dir, fileName))
27377
+ );
27356
27378
  }
27357
27379
  function envDigest(env) {
27358
27380
  const hash2 = (0, import_crypto7.createHash)("sha256");
@@ -27434,7 +27456,7 @@ var init_claude = __esm({
27434
27456
  init_chunk_ZCTKXKYY();
27435
27457
  init_chunk_J2KTV5FP();
27436
27458
  init_chunk_XE7BX6YP();
27437
- init_chunk_GI3ZGXTY();
27459
+ init_chunk_GW6CC6A3();
27438
27460
  init_chunk_YXWJW7I5();
27439
27461
  init_effort();
27440
27462
  import_crypto6 = require("crypto");
@@ -28160,8 +28182,8 @@ var init_claude = __esm({
28160
28182
  }
28161
28183
  async #awaitTaskStop(requestId, taskId) {
28162
28184
  const timer = new AbortController();
28163
- const answered = new Promise((resolve9) => {
28164
- this.#taskStops.set(requestId, resolve9);
28185
+ const answered = new Promise((resolve8) => {
28186
+ this.#taskStops.set(requestId, resolve8);
28165
28187
  });
28166
28188
  const timeoutMs = this.#options.stopTaskTimeoutMs;
28167
28189
  const timedOut = this.#options.clock.sleep(timeoutMs, timer.signal).then(
@@ -28234,17 +28256,17 @@ var init_claude = __esm({
28234
28256
  };
28235
28257
  let markStarted = () => {
28236
28258
  };
28237
- const whenStarted = new Promise((resolve9) => {
28238
- markStarted = resolve9;
28259
+ const whenStarted = new Promise((resolve8) => {
28260
+ markStarted = resolve8;
28239
28261
  });
28240
- const done = new Promise((resolve9) => {
28262
+ const done = new Promise((resolve8) => {
28241
28263
  finish = (outcome2) => {
28242
28264
  if (this.#current?.id !== id) return;
28243
28265
  this.#current = void 0;
28244
28266
  this.#lastTurn = turn;
28245
28267
  if (this.#state === "busy") this.#state = "idle";
28246
28268
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
28247
- resolve9({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
28269
+ resolve8({ turnId: id, outcome: outcome2, providerSessionId: this.#providerSessionId });
28248
28270
  };
28249
28271
  });
28250
28272
  const active = {
@@ -28362,8 +28384,8 @@ var init_claude = __esm({
28362
28384
  void removeLaunchFiles(this.#launchFiles).catch((error61) => {
28363
28385
  this.#options.log.warn("claude.launch_files_cleanup_failed", { error: error61 });
28364
28386
  });
28365
- for (const resolve9 of this.#taskStops.values()) {
28366
- resolve9({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
28387
+ for (const resolve8 of this.#taskStops.values()) {
28388
+ resolve8({ ok: false, reason: "runtime_unavailable", message: "Claude Code exited." });
28367
28389
  }
28368
28390
  const active = this.#current;
28369
28391
  if (active) {
@@ -29652,7 +29674,7 @@ var init_codex = __esm({
29652
29674
  init_chunk_ZCTKXKYY();
29653
29675
  init_chunk_J2KTV5FP();
29654
29676
  init_chunk_XE7BX6YP();
29655
- init_chunk_GI3ZGXTY();
29677
+ init_chunk_GW6CC6A3();
29656
29678
  init_chunk_YXWJW7I5();
29657
29679
  import_fs6 = require("fs");
29658
29680
  import_path6 = require("path");
@@ -29860,7 +29882,7 @@ var init_codex = __esm({
29860
29882
  const buckets = asRecord(response?.rateLimitsByLimitId);
29861
29883
  if (buckets) {
29862
29884
  return Object.entries(buckets).flatMap(
29863
- ([limitId, snapshot2]) => this.#update(snapshot2, limitId)
29885
+ ([limitId, snapshot]) => this.#update(snapshot, limitId)
29864
29886
  );
29865
29887
  }
29866
29888
  return this.#update(response?.rateLimits);
@@ -29869,16 +29891,16 @@ var init_codex = __esm({
29869
29891
  return this.#update(params.rateLimits);
29870
29892
  }
29871
29893
  #update(value, bucketId) {
29872
- const snapshot2 = asRecord(value);
29873
- if (!snapshot2) return [];
29874
- const primary = windowPatch(snapshot2.primary);
29875
- const secondary = windowPatch(snapshot2.secondary);
29876
- const spend = spendPatch(snapshot2.individualLimit, snapshot2.spendControlReached);
29877
- const credits = creditsPatch(snapshot2.credits);
29878
- const planType = snapshot2.planType === null ? null : asString(snapshot2.planType) || void 0;
29894
+ const snapshot = asRecord(value);
29895
+ if (!snapshot) return [];
29896
+ const primary = windowPatch(snapshot.primary);
29897
+ const secondary = windowPatch(snapshot.secondary);
29898
+ const spend = spendPatch(snapshot.individualLimit, snapshot.spendControlReached);
29899
+ const credits = creditsPatch(snapshot.credits);
29900
+ const planType = snapshot.planType === null ? null : asString(snapshot.planType) || void 0;
29879
29901
  const parsed = runCodexRateLimitsUpdateSchema.safeParse({
29880
29902
  sessionUpdate: "_alan/codex.rate_limits",
29881
- limitId: bucketId ?? (asString(snapshot2.limitId) || "codex"),
29903
+ limitId: bucketId ?? (asString(snapshot.limitId) || "codex"),
29882
29904
  ...primary === void 0 ? {} : { primary },
29883
29905
  ...secondary === void 0 ? {} : { secondary },
29884
29906
  ...spend === void 0 ? {} : { spend },
@@ -30324,10 +30346,10 @@ var init_codex = __esm({
30324
30346
  };
30325
30347
  let identify = () => {
30326
30348
  };
30327
- const identified = new Promise((resolve9) => {
30328
- identify = resolve9;
30349
+ const identified = new Promise((resolve8) => {
30350
+ identify = resolve8;
30329
30351
  });
30330
- const done = new Promise((resolve9) => {
30352
+ const done = new Promise((resolve8) => {
30331
30353
  finish = (outcome2) => {
30332
30354
  if (this.#current?.id !== id) return;
30333
30355
  this.#current = void 0;
@@ -30335,7 +30357,7 @@ var init_codex = __esm({
30335
30357
  if (this.#state === "busy") this.#state = "idle";
30336
30358
  this.#host.scanDescendants(true);
30337
30359
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
30338
- resolve9({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
30360
+ resolve8({ turnId: id, outcome: outcome2, providerSessionId: this.#threadId });
30339
30361
  };
30340
30362
  });
30341
30363
  const active = {
@@ -30826,7 +30848,7 @@ function alanCodeConfigContent(existing, input2) {
30826
30848
  });
30827
30849
  }
30828
30850
  function readBody2(response) {
30829
- return new Promise((resolve9, reject) => {
30851
+ return new Promise((resolve8, reject) => {
30830
30852
  const chunks = [];
30831
30853
  let size = 0;
30832
30854
  response.on("data", (chunk) => {
@@ -30834,7 +30856,7 @@ function readBody2(response) {
30834
30856
  if (size > MAX_CATALOG_BYTES) response.destroy(new Error("catalog too large"));
30835
30857
  else chunks.push(chunk);
30836
30858
  });
30837
- response.on("end", () => resolve9(Buffer.concat(chunks).toString("utf8")));
30859
+ response.on("end", () => resolve8(Buffer.concat(chunks).toString("utf8")));
30838
30860
  response.on("error", reject);
30839
30861
  });
30840
30862
  }
@@ -30850,13 +30872,13 @@ function parseResponseBody(text2, status) {
30850
30872
  }
30851
30873
  function getJson(url2, headers, timeout, signal) {
30852
30874
  const request2 = url2.protocol === "https:" ? import_https.request : import_http3.request;
30853
- return new Promise((resolve9, reject) => {
30875
+ return new Promise((resolve8, reject) => {
30854
30876
  const outgoing = request2(url2, { method: "GET", headers, timeout, signal }, (response) => {
30855
30877
  const status = response.statusCode ?? 0;
30856
30878
  readBody2(response).then((text2) => {
30857
30879
  const body = parseResponseBody(text2, status);
30858
30880
  if (status < 200 || status >= 300) reject(new CatalogResponseError(status, body));
30859
- else resolve9(body);
30881
+ else resolve8(body);
30860
30882
  }).catch(reject);
30861
30883
  });
30862
30884
  outgoing.on("timeout", () => outgoing.destroy(new Error("catalog timed out")));
@@ -39089,12 +39111,12 @@ function shellStart(update, sessionId) {
39089
39111
  ];
39090
39112
  }
39091
39113
  function shellEnd(update) {
39092
- const snapshot2 = asRecord(update.task_snapshot);
39093
- const taskId = optional2(snapshot2?.task_id);
39094
- if (!snapshot2 || !taskId) return [];
39095
- const killed = snapshot2.explicitly_killed === true;
39096
- const exitCode = snapshot2.exit_code;
39097
- const failed = typeof exitCode === "number" && exitCode !== 0 || optional2(snapshot2.signal) !== void 0;
39114
+ const snapshot = asRecord(update.task_snapshot);
39115
+ const taskId = optional2(snapshot?.task_id);
39116
+ if (!snapshot || !taskId) return [];
39117
+ const killed = snapshot.explicitly_killed === true;
39118
+ const exitCode = snapshot.exit_code;
39119
+ const failed = typeof exitCode === "number" && exitCode !== 0 || optional2(snapshot.signal) !== void 0;
39098
39120
  const ending = killed ? "stopped" : failed ? "failed" : "completed";
39099
39121
  return [{ type: "end", taskId, ending }];
39100
39122
  }
@@ -39240,7 +39262,7 @@ var init_acp3 = __esm({
39240
39262
  init_chunk_ZCTKXKYY();
39241
39263
  init_chunk_J2KTV5FP();
39242
39264
  init_chunk_XE7BX6YP();
39243
- init_chunk_GI3ZGXTY();
39265
+ init_chunk_GW6CC6A3();
39244
39266
  init_chunk_YXWJW7I5();
39245
39267
  import_promises24 = require("fs/promises");
39246
39268
  import_path9 = require("path");
@@ -39766,7 +39788,7 @@ var init_acp3 = __esm({
39766
39788
  const turn = new AcpTurn(`acp-${this.#turns}-${id}`, this.#profile);
39767
39789
  let finish = () => {
39768
39790
  };
39769
- const done = new Promise((resolve9) => {
39791
+ const done = new Promise((resolve8) => {
39770
39792
  finish = (outcome2) => {
39771
39793
  if (this.#current?.id !== id) return;
39772
39794
  this.#current = void 0;
@@ -39774,7 +39796,7 @@ var init_acp3 = __esm({
39774
39796
  if (this.#state === "busy") this.#state = "idle";
39775
39797
  this.#host.scanDescendants(true);
39776
39798
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
39777
- resolve9({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
39799
+ resolve8({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
39778
39800
  };
39779
39801
  });
39780
39802
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -40359,12 +40381,11 @@ function createPersistentDriver(provider4, options) {
40359
40381
  log.warn("holder.history_rejected", { harness: provider4.harness });
40360
40382
  await session.suspend();
40361
40383
  };
40362
- const respond = async (request2, mayWrite) => {
40384
+ const respond = async (request2) => {
40363
40385
  const turn = live.turn;
40364
40386
  if (turn === void 0 || turn.runId !== request2.runId) return "unknown_run";
40365
40387
  const isWaiting = () => live.turn === turn && turn.waiting.has(request2.toolCallId);
40366
40388
  if (!isWaiting() || turn.session.respond === void 0) return "not_waiting";
40367
- if (!await mayWrite() || !isWaiting()) return "not_waiting";
40368
40389
  turn.waiting.delete(request2.toolCallId);
40369
40390
  try {
40370
40391
  await turn.session.respond(request2.toolCallId, request2.answer);
@@ -41106,7 +41127,7 @@ var init_opencode = __esm({
41106
41127
  init_chunk_ZCTKXKYY();
41107
41128
  init_chunk_J2KTV5FP();
41108
41129
  init_chunk_XE7BX6YP();
41109
- init_chunk_GI3ZGXTY();
41130
+ init_chunk_GW6CC6A3();
41110
41131
  init_chunk_YXWJW7I5();
41111
41132
  import_http4 = require("http");
41112
41133
  init_runtime_v2();
@@ -42590,8 +42611,8 @@ function createDroidPeer(writer, handlers) {
42590
42611
  },
42591
42612
  request: (method, params = {}) => {
42592
42613
  const id = `alan-${counter.next++}`;
42593
- return new Promise((resolve9, reject) => {
42594
- pending.set(id, { method, resolve: resolve9, reject });
42614
+ return new Promise((resolve8, reject) => {
42615
+ pending.set(id, { method, resolve: resolve8, reject });
42595
42616
  writer.write(envelope("request", { id, method, params })).catch((error61) => {
42596
42617
  pending.delete(id);
42597
42618
  reject(error61 instanceof Error ? error61 : new Error(String(error61)));
@@ -42940,7 +42961,7 @@ var init_droid = __esm({
42940
42961
  init_chunk_ZCTKXKYY();
42941
42962
  init_chunk_J2KTV5FP();
42942
42963
  init_chunk_XE7BX6YP();
42943
- init_chunk_GI3ZGXTY();
42964
+ init_chunk_GW6CC6A3();
42944
42965
  init_chunk_YXWJW7I5();
42945
42966
  init_runtime_v2();
42946
42967
  import_crypto16 = require("crypto");
@@ -43219,14 +43240,14 @@ var init_droid = __esm({
43219
43240
  const turn = new DroidTurn(sessionId, this.#memory);
43220
43241
  let finish = () => {
43221
43242
  };
43222
- const done = new Promise((resolve9) => {
43243
+ const done = new Promise((resolve8) => {
43223
43244
  finish = (outcome2) => {
43224
43245
  if (this.#current?.id !== id) return;
43225
43246
  this.#current = void 0;
43226
43247
  if (this.#state === "busy") this.#state = "idle";
43227
43248
  this.#host.scanDescendants(true);
43228
43249
  this.#emit({ type: "turn_ended", turnId: id, outcome: outcome2 });
43229
- resolve9({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
43250
+ resolve8({ turnId: id, outcome: outcome2, providerSessionId: this.#sessionId });
43230
43251
  };
43231
43252
  });
43232
43253
  const active = { id, turn, done, finish, cancelRequested: false };
@@ -44049,7 +44070,7 @@ var init_antigravity = __esm({
44049
44070
  init_chunk_XC5676SG();
44050
44071
  init_chunk_ZCTKXKYY();
44051
44072
  init_chunk_XE7BX6YP();
44052
- init_chunk_GI3ZGXTY();
44073
+ init_chunk_GW6CC6A3();
44053
44074
  init_chunk_YXWJW7I5();
44054
44075
  import_promises28 = require("fs/promises");
44055
44076
  import_path12 = require("path");
@@ -44754,7 +44775,7 @@ var init_command_code = __esm({
44754
44775
  init_chunk_ZCTKXKYY();
44755
44776
  init_chunk_J2KTV5FP();
44756
44777
  init_chunk_XE7BX6YP();
44757
- init_chunk_GI3ZGXTY();
44778
+ init_chunk_GW6CC6A3();
44758
44779
  init_chunk_YXWJW7I5();
44759
44780
  import_promises29 = require("fs/promises");
44760
44781
  import_path15 = require("path");
@@ -45551,46 +45572,6 @@ function openFileLog(path, level, clock) {
45551
45572
  };
45552
45573
  }
45553
45574
 
45554
- // src/kernel/maintenance.ts
45555
- function startMaintenance({ everyMs, jobs, clock, log }) {
45556
- const controller = new AbortController();
45557
- let running = Promise.resolve();
45558
- const runJobs = async () => {
45559
- for (const job of jobs) {
45560
- if (controller.signal.aborted) return;
45561
- try {
45562
- await job.run(controller.signal);
45563
- } catch (error61) {
45564
- if (!controller.signal.aborted)
45565
- log.warn("maintenance.job_failed", { job: job.name, error: error61 });
45566
- }
45567
- }
45568
- };
45569
- const tick = () => {
45570
- running = running.then(runJobs);
45571
- return running;
45572
- };
45573
- const loop = async () => {
45574
- while (!controller.signal.aborted) {
45575
- try {
45576
- await clock.sleep(everyMs, controller.signal);
45577
- } catch {
45578
- return;
45579
- }
45580
- await tick();
45581
- }
45582
- };
45583
- const looping = loop();
45584
- return {
45585
- runNow: tick,
45586
- [Symbol.asyncDispose]: async () => {
45587
- controller.abort();
45588
- await looping;
45589
- await running;
45590
- }
45591
- };
45592
- }
45593
-
45594
45575
  // src/api-client/http.ts
45595
45576
  var import_node_http = require("http");
45596
45577
  var import_node_https = require("https");
@@ -45618,7 +45599,7 @@ function transportFailure(request2, error61) {
45618
45599
  });
45619
45600
  }
45620
45601
  function readBody(incoming, url2, maxBytes) {
45621
- return new Promise((resolve9, reject) => {
45602
+ return new Promise((resolve8, reject) => {
45622
45603
  const declared = Number(incoming.headers["content-length"] ?? "0");
45623
45604
  if (maxBytes !== void 0 && declared > maxBytes) {
45624
45605
  incoming.destroy();
@@ -45637,7 +45618,7 @@ function readBody(incoming, url2, maxBytes) {
45637
45618
  chunks.push(chunk);
45638
45619
  });
45639
45620
  incoming.on("error", reject);
45640
- incoming.on("end", () => resolve9(Buffer.concat(chunks)));
45621
+ incoming.on("end", () => resolve8(Buffer.concat(chunks)));
45641
45622
  });
45642
45623
  }
45643
45624
  function isConnectionReset(error61) {
@@ -45645,7 +45626,7 @@ function isConnectionReset(error61) {
45645
45626
  }
45646
45627
  function exchange(request2, agents, attempt = 0) {
45647
45628
  const { signal, url: url2 } = request2;
45648
- return new Promise((resolve9, reject) => {
45629
+ return new Promise((resolve8, reject) => {
45649
45630
  if (signal.aborted) {
45650
45631
  reject(signal.reason);
45651
45632
  return;
@@ -45672,7 +45653,7 @@ function exchange(request2, agents, attempt = 0) {
45672
45653
  const stale = outgoing.reusedSocket && !responded && isConnectionReset(error61);
45673
45654
  if (stale && attempt < STALE_SOCKET_RETRIES && !signal.aborted) {
45674
45655
  settle();
45675
- resolve9(exchange(request2, agents, attempt + 1));
45656
+ resolve8(exchange(request2, agents, attempt + 1));
45676
45657
  return;
45677
45658
  }
45678
45659
  fail(error61);
@@ -45685,7 +45666,7 @@ function exchange(request2, agents, attempt = 0) {
45685
45666
  readBody(incoming, url2, isRedirect(status) ? void 0 : request2.maxBodyBytes).then(
45686
45667
  (body) => {
45687
45668
  settle();
45688
- resolve9({ status, headers: incoming.headers, body });
45669
+ resolve8({ status, headers: incoming.headers, body });
45689
45670
  },
45690
45671
  fail
45691
45672
  );
@@ -46004,7 +45985,7 @@ function createGitRunner(options) {
46004
45985
  }
46005
45986
  await killProcessTree(child.pid, { signal: "SIGKILL", child, platform });
46006
45987
  };
46007
- return new Promise((resolve9, reject) => {
45988
+ return new Promise((resolve8, reject) => {
46008
45989
  let ending = null;
46009
45990
  const stop = (next) => {
46010
45991
  if (ending !== null) return;
@@ -46029,7 +46010,7 @@ function createGitRunner(options) {
46029
46010
  signal.removeEventListener("abort", onAbort);
46030
46011
  const final = ending ?? last;
46031
46012
  if (final.kind === "exited") {
46032
- resolve9({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
46013
+ resolve8({ exitCode: final.exitCode, stdout: stdout.text(), stderr: stderr.text() });
46033
46014
  } else {
46034
46015
  reject(faultFor(final, command));
46035
46016
  }
@@ -46351,9 +46332,9 @@ function isProcessAlive(pid) {
46351
46332
  }
46352
46333
  }
46353
46334
  async function linuxStartTime(pid) {
46354
- const stat16 = await (0, import_promises10.readFile)(`/proc/${pid}/stat`, "utf8").catch(() => null);
46355
- if (stat16 === null) return null;
46356
- const fields = stat16.slice(stat16.lastIndexOf(")") + 2).split(" ");
46335
+ const stat15 = await (0, import_promises10.readFile)(`/proc/${pid}/stat`, "utf8").catch(() => null);
46336
+ if (stat15 === null) return null;
46337
+ const fields = stat15.slice(stat15.lastIndexOf(")") + 2).split(" ");
46357
46338
  return fields[19] ?? null;
46358
46339
  }
46359
46340
  async function linuxCommand(pid) {
@@ -46532,7 +46513,7 @@ function statusOf(error61) {
46532
46513
  }
46533
46514
  return 1;
46534
46515
  }
46535
- var systemExec = (request2) => new Promise((resolve9) => {
46516
+ var systemExec = (request2) => new Promise((resolve8) => {
46536
46517
  const child = (0, import_node_child_process5.execFile)(
46537
46518
  request2.command,
46538
46519
  [...request2.args],
@@ -46543,7 +46524,7 @@ var systemExec = (request2) => new Promise((resolve9) => {
46543
46524
  windowsHide: true
46544
46525
  },
46545
46526
  (error61, stdout, stderr) => {
46546
- resolve9({ status: statusOf(error61), stdout, stderr });
46527
+ resolve8({ status: statusOf(error61), stdout, stderr });
46547
46528
  }
46548
46529
  );
46549
46530
  child.stdin?.on("error", () => {
@@ -47507,7 +47488,7 @@ function openRepositoryLocks(options) {
47507
47488
 
47508
47489
  // src/cli/config.ts
47509
47490
  var import_node_os7 = require("os");
47510
- var import_node_path33 = require("path");
47491
+ var import_node_path31 = require("path");
47511
47492
  init_zod();
47512
47493
 
47513
47494
  // src/client/locate.ts
@@ -47528,9 +47509,9 @@ function defaultInstallDir({ platform, home, env }) {
47528
47509
 
47529
47510
  // src/sessions/index.ts
47530
47511
  var import_node_crypto16 = require("crypto");
47531
- var import_promises41 = require("fs/promises");
47512
+ var import_promises39 = require("fs/promises");
47532
47513
  var import_node_os6 = require("os");
47533
- var import_node_path32 = require("path");
47514
+ var import_node_path30 = require("path");
47534
47515
 
47535
47516
  // src/holder/control-client.ts
47536
47517
  var import_node_crypto12 = require("crypto");
@@ -47585,9 +47566,9 @@ function selectDriver(persistent, fallback) {
47585
47566
  suspend: async () => {
47586
47567
  await Promise.all([...drivers].map((driver) => driver.suspend?.()));
47587
47568
  },
47588
- respond: async (request2, mayWrite) => {
47569
+ respond: async (request2) => {
47589
47570
  for (const driver of drivers) {
47590
- const status = await driver.respond?.(request2, mayWrite);
47571
+ const status = await driver.respond?.(request2);
47591
47572
  if (status !== void 0 && status !== "unknown_run") return status;
47592
47573
  }
47593
47574
  return "unknown_run";
@@ -47627,9 +47608,9 @@ function createLazyDriver(load) {
47627
47608
  suspend: async () => {
47628
47609
  if (loaded.driver !== void 0) await (await loaded.driver).suspend?.();
47629
47610
  },
47630
- respond: async (request2, mayWrite) => {
47611
+ respond: async (request2) => {
47631
47612
  if (loaded.driver === void 0) return "unknown_run";
47632
- return await (await loaded.driver).respond?.(request2, mayWrite) ?? "unknown_run";
47613
+ return await (await loaded.driver).respond?.(request2) ?? "unknown_run";
47633
47614
  },
47634
47615
  stopTask: async (taskId) => {
47635
47616
  if (loaded.driver === void 0) return TASK_NOT_FOUND;
@@ -47844,14 +47825,14 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [] }) {
47844
47825
  var import_node_crypto15 = require("crypto");
47845
47826
  var import_node_fs11 = require("fs");
47846
47827
  var import_node_net2 = require("net");
47847
- var import_node_path31 = require("path");
47828
+ var import_node_path29 = require("path");
47848
47829
  init_runtime_v2();
47849
47830
 
47850
47831
  // src/holder/admission.ts
47851
47832
  var import_node_fs9 = require("fs");
47852
- var import_promises37 = require("fs/promises");
47833
+ var import_promises35 = require("fs/promises");
47853
47834
  var import_node_os5 = require("os");
47854
- var import_node_path27 = require("path");
47835
+ var import_node_path25 = require("path");
47855
47836
  init_constants();
47856
47837
 
47857
47838
  // ../shared/dist/node/local-workspace.js
@@ -47862,88 +47843,16 @@ function resolveAlanDefaultWorkspacePath(homeDirectory = (0, import_node_os4.hom
47862
47843
  return (0, import_node_path20.join)(homeDirectory, ".alan", "workspace");
47863
47844
  }
47864
47845
 
47865
- // src/holder/admission-relocation.ts
47846
+ // src/holder/agent-context.ts
47866
47847
  var import_promises32 = require("fs/promises");
47867
47848
  var import_node_path21 = require("path");
47868
- var MAX_RELOCATION_CANDIDATES = 200;
47869
- var RELOCATION_BUDGET_MS = 2e4;
47870
- function repositoryIdentity(url2) {
47871
- const trimmed4 = url2.trim().replace(/\/+$/, "").replace(/\.git$/i, "");
47872
- if (trimmed4.length === 0) return null;
47873
- const scp = /^(?:[^@/]+@)?([^:/]+):(.+)$/.exec(trimmed4);
47874
- if (scp !== null && !trimmed4.includes("://")) {
47875
- return `${scp[1]}/${scp[2]}`.toLowerCase();
47876
- }
47877
- try {
47878
- const parsed = new URL(trimmed4);
47879
- return `${parsed.hostname}${parsed.pathname}`.replace(/\/+$/, "").toLowerCase();
47880
- } catch {
47881
- return null;
47882
- }
47883
- }
47884
- function repositoryIdentities(urls) {
47885
- return new Set(
47886
- urls.map(repositoryIdentity).filter((identity) => identity !== null)
47887
- );
47888
- }
47889
- async function originIdentity(git, path, signal) {
47890
- try {
47891
- const output2 = await git.run(
47892
- { cwd: path, args: ["config", "--get", "remote.origin.url"], readOnly: true },
47893
- signal
47894
- );
47895
- return output2.exitCode === 0 ? repositoryIdentity(output2.stdout) : null;
47896
- } catch {
47897
- return null;
47898
- }
47899
- }
47900
- async function childDirectories(parent, limit) {
47901
- try {
47902
- const entries = await (0, import_promises32.readdir)(parent, { withFileTypes: true });
47903
- return entries.filter((entry) => entry.isDirectory()).slice(0, limit).map((entry) => (0, import_node_path21.join)(parent, entry.name));
47904
- } catch {
47905
- return [];
47906
- }
47907
- }
47908
- async function candidateFolders(search) {
47909
- const roots = /* @__PURE__ */ new Map();
47910
- for (const path of [search.missingPath, ...search.approvedWorkspacePaths]) {
47911
- const parent = (0, import_node_path21.dirname)((0, import_node_path21.resolve)(path));
47912
- roots.set(comparablePath(parent, search.platform), parent);
47913
- }
47914
- const candidates2 = /* @__PURE__ */ new Map();
47915
- for (const root of roots.values()) {
47916
- const remaining = MAX_RELOCATION_CANDIDATES - candidates2.size;
47917
- if (remaining <= 0) break;
47918
- for (const child of await childDirectories(root, remaining)) {
47919
- candidates2.set(comparablePath(child, search.platform), child);
47920
- }
47921
- }
47922
- return [...candidates2.values()];
47923
- }
47924
- async function discoverRelocatedWorkspace(search) {
47925
- if (search.expected.size === 0) return null;
47926
- const signal = AbortSignal.any([search.signal, AbortSignal.timeout(RELOCATION_BUDGET_MS)]);
47927
- const matches = [];
47928
- for (const candidate of await candidateFolders(search)) {
47929
- if (signal.aborted) return null;
47930
- const identity = await originIdentity(search.git, candidate, signal);
47931
- if (identity !== null && search.expected.has(identity)) matches.push(candidate);
47932
- if (matches.length > 1) return null;
47933
- }
47934
- return matches[0] ?? null;
47935
- }
47936
-
47937
- // src/holder/agent-context.ts
47938
- var import_promises33 = require("fs/promises");
47939
- var import_node_path22 = require("path");
47940
47849
 
47941
47850
  // ../agent-core/dist/prompt.js
47942
- init_chunk_GI3ZGXTY();
47851
+ init_chunk_GW6CC6A3();
47943
47852
 
47944
47853
  // src/holder/agent-context.ts
47945
47854
  async function readText2(path) {
47946
- return (0, import_promises33.readFile)(path, "utf8").then(
47855
+ return (0, import_promises32.readFile)(path, "utf8").then(
47947
47856
  (text2) => text2.trim(),
47948
47857
  () => null
47949
47858
  );
@@ -47958,15 +47867,15 @@ async function startCommandState(statusPath) {
47958
47867
  return code === 0 ? { state: "exited_ok" } : { state: "failed", exitCode: code };
47959
47868
  }
47960
47869
  function createAgentContext(deps) {
47961
- const statusPath = (0, import_node_path22.join)(deps.homeDir, ".alan", "start-commands.status");
47962
- const logPath = (0, import_node_path22.join)(deps.homeDir, ".alan", "start-commands.log");
47870
+ const statusPath = (0, import_node_path21.join)(deps.homeDir, ".alan", "start-commands.status");
47871
+ const logPath = (0, import_node_path21.join)(deps.homeDir, ".alan", "start-commands.log");
47963
47872
  return async (spec, problems) => {
47964
- const file2 = (0, import_node_path22.join)(deps.dir, `${spec.conversationId}.json`);
47873
+ const file2 = (0, import_node_path21.join)(deps.dir, `${spec.conversationId}.json`);
47965
47874
  const saved = await readJsonFile(file2, agentContextSnapshotSchema);
47966
47875
  const known = saved.kind === "ok" ? saved.value : void 0;
47967
47876
  const hasEnvironment = (spec.agentContext ?? known)?.environment !== void 0;
47968
47877
  const start = hasEnvironment ? await startCommandState(statusPath) : void 0;
47969
- const snapshot2 = agentContextSnapshot({
47878
+ const snapshot = agentContextSnapshot({
47970
47879
  spec,
47971
47880
  ...spec.approvedWorkspacePaths?.[0] ? { workspaceRoot: spec.approvedWorkspacePaths[0] } : {},
47972
47881
  problems,
@@ -47974,39 +47883,39 @@ function createAgentContext(deps) {
47974
47883
  startLogPath: logPath,
47975
47884
  ...known ? { known } : {}
47976
47885
  });
47977
- if (snapshot2 === null) return void 0;
47978
- const rendered = renderAgentContext(snapshot2, known);
47886
+ if (snapshot === null) return void 0;
47887
+ const rendered = renderAgentContext(snapshot, known);
47979
47888
  return {
47980
47889
  full: rendered.full,
47981
47890
  ...rendered.update ? { update: rendered.update } : {},
47982
- save: () => writeJsonFileAtomic(file2, snapshot2)
47891
+ save: () => writeJsonFileAtomic(file2, snapshot)
47983
47892
  };
47984
47893
  };
47985
47894
  }
47986
47895
 
47987
47896
  // src/holder/checkout-refresh.ts
47988
- var import_node_path25 = require("path");
47897
+ var import_node_path24 = require("path");
47989
47898
 
47990
47899
  // src/holder/claim-once.ts
47991
47900
  var import_node_crypto14 = require("crypto");
47992
- var import_promises34 = require("fs/promises");
47993
- var import_node_path23 = require("path");
47901
+ var import_promises33 = require("fs/promises");
47902
+ var import_node_path22 = require("path");
47994
47903
  async function claimOnce(dir, name) {
47995
47904
  try {
47996
- await (0, import_promises34.mkdir)(dir, { recursive: true, mode: 448 });
47997
- await (await (0, import_promises34.open)((0, import_node_path23.join)(dir, name), "wx")).close();
47905
+ await (0, import_promises33.mkdir)(dir, { recursive: true, mode: 448 });
47906
+ await (await (0, import_promises33.open)((0, import_node_path22.join)(dir, name), "wx")).close();
47998
47907
  return true;
47999
47908
  } catch {
48000
47909
  return false;
48001
47910
  }
48002
47911
  }
48003
47912
  function claimFirstLease(freshnessDir, path) {
48004
- return claimOnce((0, import_node_path23.join)(freshnessDir, "leased"), (0, import_node_crypto14.createHash)("sha256").update(path).digest("hex"));
47913
+ return claimOnce((0, import_node_path22.join)(freshnessDir, "leased"), (0, import_node_crypto14.createHash)("sha256").update(path).digest("hex"));
48005
47914
  }
48006
47915
 
48007
47916
  // src/holder/requested-checkout.ts
48008
- var import_promises35 = require("fs/promises");
48009
- var import_node_path24 = require("path");
47917
+ var import_promises34 = require("fs/promises");
47918
+ var import_node_path23 = require("path");
48010
47919
  var REMOTE2 = "origin";
48011
47920
  var REASON_MAX_CHARS = 200;
48012
47921
  function firstLine2(text2) {
@@ -48027,8 +47936,8 @@ function notSwitched(checkout, current, reason) {
48027
47936
  );
48028
47937
  }
48029
47938
  async function clone2(checkout, deps, signal) {
48030
- const parent = (0, import_node_path24.dirname)(checkout.path);
48031
- await (0, import_promises35.mkdir)(parent, { recursive: true });
47939
+ const parent = (0, import_node_path23.dirname)(checkout.path);
47940
+ await (0, import_promises34.mkdir)(parent, { recursive: true });
48032
47941
  await assertValidBranch(deps.git, parent, checkout.branch, signal);
48033
47942
  const output2 = await deps.git.run(
48034
47943
  {
@@ -48180,9 +48089,9 @@ async function applyRequestedCheckout(checkout, spec, deps, signal) {
48180
48089
  function short(sha) {
48181
48090
  return sha.slice(0, 12);
48182
48091
  }
48183
- function staleCheckout(path, snapshot2, tip) {
48184
- const checkout = snapshot2 === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot2.branch} (commit ${short(snapshot2.head)})`;
48185
- const base = snapshot2 === void 0 ? "its upstream" : `origin/${snapshot2.base}`;
48092
+ function staleCheckout(path, snapshot, tip) {
48093
+ const checkout = snapshot === void 0 ? "is the environment snapshot's checkout" : `is the environment snapshot's checkout of ${snapshot.branch} (commit ${short(snapshot.head)})`;
48094
+ const base = snapshot === void 0 ? "its upstream" : `origin/${snapshot.base}`;
48186
48095
  const remote = tip === void 0 ? "may be ahead" : `is ahead at ${short(tip)}`;
48187
48096
  return {
48188
48097
  path,
@@ -48193,18 +48102,18 @@ function staleCheckout(path, snapshot2, tip) {
48193
48102
  async function fastForward(freshness, operationId, deps, signal) {
48194
48103
  var _stack = [];
48195
48104
  try {
48196
- const { path: cwd, snapshot: snapshot2, tip } = freshness;
48197
- const attempt = await deps.locks.tryExclusive(snapshot2.commonDir, operationId);
48105
+ const { path: cwd, snapshot, tip } = freshness;
48106
+ const attempt = await deps.locks.tryExclusive(snapshot.commonDir, operationId);
48198
48107
  if (attempt.kind === "busy") return false;
48199
48108
  const _lock = __using(_stack, attempt.lock, true);
48200
48109
  const now = await readCheckoutStatus(deps.git, cwd, signal);
48201
- if (now === null || now.dirty || now.head !== snapshot2.head || now.branch !== snapshot2.branch) {
48110
+ if (now === null || now.dirty || now.head !== snapshot.head || now.branch !== snapshot.branch) {
48202
48111
  return false;
48203
48112
  }
48204
48113
  const git = (args) => deps.git.run({ cwd, args }, signal);
48205
48114
  if ((await git(["switch", "--quiet", "--detach", tip])).exitCode !== 0) return false;
48206
- const moved = await git(["update-ref", `refs/heads/${snapshot2.branch}`, tip, snapshot2.head]);
48207
- const back = await git(["switch", "--quiet", snapshot2.branch]);
48115
+ const moved = await git(["update-ref", `refs/heads/${snapshot.branch}`, tip, snapshot.head]);
48116
+ const back = await git(["switch", "--quiet", snapshot.branch]);
48208
48117
  return moved.exitCode === 0 && back.exitCode === 0;
48209
48118
  } catch (_) {
48210
48119
  var _error = _, _hasError = true;
@@ -48236,9 +48145,8 @@ function problemFor(freshness) {
48236
48145
  return staleCheckout(freshness.path, void 0);
48237
48146
  }
48238
48147
  }
48239
- async function checkoutsOf(spec, leaseTargets) {
48240
- if (leaseTargets.length > 0 || spec.projectPath === void 0) return [...leaseTargets];
48241
- return checkoutsUnder(spec.projectPath);
48148
+ async function checkoutsOf(spec) {
48149
+ return spec.projectPath === void 0 ? [] : checkoutsUnder(spec.projectPath);
48242
48150
  }
48243
48151
  function requestedCheckoutsOf(spec, log) {
48244
48152
  const roots = spec.approvedWorkspacePaths ?? [];
@@ -48266,7 +48174,7 @@ async function applyRequestedCheckouts(spec, deps, signal) {
48266
48174
  ...outcome2.kind === "moved" ? { how: outcome2.how } : {}
48267
48175
  });
48268
48176
  if (outcome2.kind === "on_branch") continue;
48269
- settled2.add((0, import_node_path25.resolve)(checkout.path));
48177
+ settled2.add((0, import_node_path24.resolve)(checkout.path));
48270
48178
  if (outcome2.kind === "noted") {
48271
48179
  problems.push({ path: checkout.path, problem: outcome2.problem, action: outcome2.action });
48272
48180
  }
@@ -48276,7 +48184,7 @@ async function applyRequestedCheckouts(spec, deps, signal) {
48276
48184
  async function refreshSnapshotCheckouts(spec, targets, settled2, deps, signal) {
48277
48185
  const problems = [];
48278
48186
  for (const target of targets) {
48279
- if (settled2.has((0, import_node_path25.resolve)(target))) continue;
48187
+ if (settled2.has((0, import_node_path24.resolve)(target))) continue;
48280
48188
  const freshness = await readCheckoutFreshness(deps.dir, target);
48281
48189
  if (freshness === null) continue;
48282
48190
  const outcome2 = await atFirstLease(freshness, spec, deps, signal).catch(
@@ -48293,11 +48201,11 @@ async function refreshSnapshotCheckouts(spec, targets, settled2, deps, signal) {
48293
48201
  return problems;
48294
48202
  }
48295
48203
  function createCheckoutRefresh(deps) {
48296
- return async (spec, leaseTargets, signal) => {
48204
+ return async (spec, signal) => {
48297
48205
  if (spec.providerSessionId !== void 0) return [];
48298
- if (!await claimOnce((0, import_node_path25.join)(deps.dir, "conversations"), spec.conversationId)) return [];
48206
+ if (!await claimOnce((0, import_node_path24.join)(deps.dir, "conversations"), spec.conversationId)) return [];
48299
48207
  const requested = await applyRequestedCheckouts(spec, deps, signal);
48300
- const targets = await checkoutsOf(spec, leaseTargets);
48208
+ const targets = await checkoutsOf(spec);
48301
48209
  return [
48302
48210
  ...requested.problems,
48303
48211
  ...await refreshSnapshotCheckouts(spec, targets, requested.settled, deps, signal)
@@ -48305,207 +48213,6 @@ function createCheckoutRefresh(deps) {
48305
48213
  };
48306
48214
  }
48307
48215
 
48308
- // src/holder/lease.ts
48309
- var import_promises36 = require("fs/promises");
48310
- var import_node_path26 = require("path");
48311
- var LEASE_CHECK_EVERY_MS = 5e3;
48312
- var MAX_TRANSIENT_FAILURES = 3;
48313
- var BACKOFF_BASE_MS = 1e3;
48314
- var BACKOFF_MAX_MS = 15e3;
48315
- var MESSAGES = {
48316
- workspace_lease_unavailable: "The workspace or Git checkout became unavailable while the run was active. Restore it and start a new run.",
48317
- workspace_lease_path_changed: "The selected workspace folder changed while the run was active. The run stopped before continuing; choose the correct folder and start a new run.",
48318
- workspace_lease_repository_changed: "The workspace now points to a different repository or worktree. The run stopped before continuing; restore the original checkout and start a new run."
48319
- };
48320
- function identityFailure(code, workspacePath) {
48321
- return { code, problemCode: "app.workspace.missing", message: MESSAGES[code], workspacePath };
48322
- }
48323
- async function fileIdentity(path) {
48324
- const canonical = await (0, import_promises36.realpath)(path);
48325
- const info = await (0, import_promises36.stat)(canonical, { bigint: true });
48326
- return `${canonical}:${info.dev}:${info.ino}`;
48327
- }
48328
- async function snapshot(git, path, signal) {
48329
- try {
48330
- const output2 = await git.run(
48331
- {
48332
- cwd: path,
48333
- args: ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"],
48334
- readOnly: true
48335
- },
48336
- signal
48337
- );
48338
- const [gitDir, commonDir] = output2.stdout.trim().split("\n");
48339
- if (output2.exitCode !== 0 || !gitDir || !commonDir) return null;
48340
- return {
48341
- workspace: await fileIdentity(path),
48342
- repository: await fileIdentity(commonDir),
48343
- worktree: await fileIdentity(gitDir),
48344
- commonDir: await (0, import_promises36.realpath)(commonDir)
48345
- };
48346
- } catch {
48347
- return null;
48348
- }
48349
- }
48350
- async function gitValue(git, path, args, signal) {
48351
- const output2 = await git.run({ cwd: path, args, readOnly: true }, signal).catch(() => null);
48352
- const value = output2?.exitCode === 0 ? output2.stdout.trim() : "";
48353
- return value.length > 0 ? value : null;
48354
- }
48355
- async function pathExists(path) {
48356
- try {
48357
- await (0, import_promises36.stat)(path);
48358
- return true;
48359
- } catch (error61) {
48360
- return errnoCode(error61) !== "ENOENT" && errnoCode(error61) !== "ENOTDIR";
48361
- }
48362
- }
48363
- async function hasGitMarker(path) {
48364
- let directory;
48365
- try {
48366
- directory = await (0, import_promises36.realpath)(path);
48367
- } catch {
48368
- return true;
48369
- }
48370
- for (; ; ) {
48371
- try {
48372
- await (0, import_promises36.stat)((0, import_node_path26.join)(directory, ".git"));
48373
- return true;
48374
- } catch (error61) {
48375
- const code = errnoCode(error61);
48376
- if (code !== "ENOENT" && code !== "ENOTDIR") return true;
48377
- }
48378
- const parent = (0, import_node_path26.dirname)(directory);
48379
- if (parent === directory) return false;
48380
- directory = parent;
48381
- }
48382
- }
48383
- async function probeCheckout(git, path, captured, signal) {
48384
- const current = await snapshot(git, path, signal);
48385
- if (current === null) {
48386
- const failure5 = identityFailure("workspace_lease_unavailable", path);
48387
- return await pathExists(path) ? { kind: "transient", failure: failure5 } : { kind: "failed", failure: failure5 };
48388
- }
48389
- if (current.workspace !== captured.workspace) {
48390
- return { kind: "failed", failure: identityFailure("workspace_lease_path_changed", path) };
48391
- }
48392
- if (current.repository !== captured.repository || current.worktree !== captured.worktree) {
48393
- return { kind: "failed", failure: identityFailure("workspace_lease_repository_changed", path) };
48394
- }
48395
- return { kind: "ok" };
48396
- }
48397
- async function releaseAll(locks) {
48398
- for (const lock of locks) await lock[Symbol.asyncDispose]();
48399
- }
48400
- async function captureOne(git, path, signal) {
48401
- const identity = await snapshot(git, path, signal);
48402
- if (identity === null) return identityFailure("workspace_lease_unavailable", path);
48403
- const branch = await gitValue(git, path, ["symbolic-ref", "-q", "--short", "HEAD"], signal);
48404
- const head = await gitValue(git, path, ["rev-parse", "-q", "--verify", "HEAD"], signal);
48405
- return { path, identity, checkout: { path, commonDir: identity.commonDir, branch, head } };
48406
- }
48407
- async function captureWorkspaceLease(runId, paths, deps, signal) {
48408
- const captured = [];
48409
- const locks = [];
48410
- const locked = /* @__PURE__ */ new Set();
48411
- for (const path of paths) {
48412
- const one = await captureOne(deps.git, path, signal);
48413
- if (!("identity" in one)) {
48414
- await releaseAll(locks);
48415
- return { kind: "failed", failure: one };
48416
- }
48417
- const key = comparablePath(one.identity.commonDir, deps.platform);
48418
- if (!locked.has(key)) {
48419
- const attempt = await deps.locks.tryShared(one.identity.commonDir, runId);
48420
- if (attempt.kind === "busy") {
48421
- await releaseAll(locks);
48422
- return {
48423
- kind: "failed",
48424
- failure: {
48425
- code: "workspace_busy",
48426
- problemCode: null,
48427
- message: "Alan is committing or pushing in this repository for a checkout switch. Try again when it finishes.",
48428
- workspacePath: path
48429
- }
48430
- };
48431
- }
48432
- locked.add(key);
48433
- locks.push(attempt.lock);
48434
- }
48435
- captured.push(one);
48436
- }
48437
- return { kind: "held", lease: holdLease(captured, locks, deps) };
48438
- }
48439
- function holdLease(captured, locks, deps) {
48440
- const lifetime = new AbortController();
48441
- const lost = new AbortController();
48442
- const state = { failure: null, inFlight: null, transientStreak: 0, nextCheckAt: 0 };
48443
- const probeOnce = async () => {
48444
- for (const { path, identity } of captured) {
48445
- const probe = await probeCheckout(deps.git, path, identity, lifetime.signal);
48446
- if (probe.kind !== "ok") return probe;
48447
- }
48448
- return { kind: "ok" };
48449
- };
48450
- const lose = (failure5) => {
48451
- if (state.failure !== null) return;
48452
- state.failure = failure5;
48453
- deps.log.warn("holder.workspace_lease_lost", {
48454
- code: failure5.code,
48455
- workspacePath: failure5.workspacePath
48456
- });
48457
- lost.abort(failure5);
48458
- };
48459
- const apply = (probe) => {
48460
- if (probe.kind === "ok") {
48461
- state.transientStreak = 0;
48462
- state.nextCheckAt = 0;
48463
- } else if (probe.kind === "failed") {
48464
- lose(probe.failure);
48465
- } else {
48466
- state.transientStreak += 1;
48467
- if (state.transientStreak >= MAX_TRANSIENT_FAILURES) lose(probe.failure);
48468
- else {
48469
- const backoff = BACKOFF_BASE_MS * 2 ** (state.transientStreak - 1);
48470
- state.nextCheckAt = deps.clock.monotonic() + Math.min(backoff, BACKOFF_MAX_MS);
48471
- }
48472
- }
48473
- return state.failure === null;
48474
- };
48475
- const check2 = () => {
48476
- if (state.failure !== null) return Promise.resolve(false);
48477
- state.inFlight ??= probeOnce().then((probe) => lifetime.signal.aborted ? state.failure === null : apply(probe)).finally(() => {
48478
- state.inFlight = null;
48479
- });
48480
- return state.inFlight;
48481
- };
48482
- const monitor = captured.length === 0 ? null : startMaintenance({
48483
- everyMs: deps.everyMs ?? LEASE_CHECK_EVERY_MS,
48484
- jobs: [
48485
- {
48486
- name: "holder.workspace_lease",
48487
- run: async () => {
48488
- if (state.failure !== null || deps.clock.monotonic() < state.nextCheckAt) return;
48489
- await check2();
48490
- }
48491
- }
48492
- ],
48493
- clock: deps.clock,
48494
- log: deps.log
48495
- });
48496
- return {
48497
- checkouts: captured.map((entry) => entry.checkout),
48498
- lost: lost.signal,
48499
- failure: () => state.failure,
48500
- verify: check2,
48501
- [Symbol.asyncDispose]: async () => {
48502
- lifetime.abort();
48503
- await monitor?.[Symbol.asyncDispose]();
48504
- await releaseAll(locks);
48505
- }
48506
- };
48507
- }
48508
-
48509
48216
  // src/holder/admission.ts
48510
48217
  var VOLUME_ERRORS = /* @__PURE__ */ new Set([
48511
48218
  "EIO",
@@ -48514,13 +48221,12 @@ var VOLUME_ERRORS = /* @__PURE__ */ new Set([
48514
48221
  "ENXIO",
48515
48222
  "ESTALE"
48516
48223
  ]);
48517
- var MESSAGES2 = {
48224
+ var MESSAGES = {
48518
48225
  missing: "This project folder was moved or removed. Locate it before starting the run.",
48519
48226
  permission: "Alan needs permission to access this project folder.",
48520
48227
  volume: "The drive containing this project is unavailable. Connect it and try again.",
48521
48228
  pinnedMissing: "This run must use exactly this project folder, and it was moved or removed. Restore it or choose another folder.",
48522
- notApproved: "This folder is not one of the workspaces approved on this computer.",
48523
- mismatch: "This folder belongs to a different repository. Choose the correct project folder and try again."
48229
+ notApproved: "This folder is not one of the workspaces approved on this computer."
48524
48230
  };
48525
48231
  function rejected(rejection, message) {
48526
48232
  return { kind: "rejected", rejection, message };
@@ -48539,7 +48245,7 @@ function volumeRoot(path) {
48539
48245
  }
48540
48246
  async function exists(path) {
48541
48247
  try {
48542
- await (0, import_promises37.stat)(path);
48248
+ await (0, import_promises35.stat)(path);
48543
48249
  return true;
48544
48250
  } catch {
48545
48251
  return false;
@@ -48547,30 +48253,23 @@ async function exists(path) {
48547
48253
  }
48548
48254
  async function inspectReadiness(path) {
48549
48255
  try {
48550
- if (!(await (0, import_promises37.stat)(path)).isDirectory()) {
48551
- return { ready: false, missing: true, message: MESSAGES2.missing };
48256
+ if (!(await (0, import_promises35.stat)(path)).isDirectory()) {
48257
+ return { ready: false, missing: true, message: MESSAGES.missing };
48552
48258
  }
48553
- await (0, import_promises37.access)(path, import_node_fs9.constants.R_OK | import_node_fs9.constants.W_OK | import_node_fs9.constants.X_OK);
48259
+ await (0, import_promises35.access)(path, import_node_fs9.constants.R_OK | import_node_fs9.constants.W_OK | import_node_fs9.constants.X_OK);
48554
48260
  return { ready: true };
48555
48261
  } catch (error61) {
48556
48262
  const code = errnoCode(error61) ?? "";
48557
48263
  if (code === "EACCES" || code === "EPERM") {
48558
- return { ready: false, missing: false, message: MESSAGES2.permission };
48264
+ return { ready: false, missing: false, message: MESSAGES.permission };
48559
48265
  }
48560
48266
  const root = volumeRoot(path);
48561
48267
  if (VOLUME_ERRORS.has(code) || code === "ENOENT" && root !== null && !await exists(root)) {
48562
- return { ready: false, missing: false, message: MESSAGES2.volume };
48268
+ return { ready: false, missing: false, message: MESSAGES.volume };
48563
48269
  }
48564
- return { ready: false, missing: true, message: MESSAGES2.missing };
48270
+ return { ready: false, missing: true, message: MESSAGES.missing };
48565
48271
  }
48566
48272
  }
48567
- function expectedRepositoryUrls(spec, projectPath, platform) {
48568
- const folder = comparablePath(projectPath, platform);
48569
- return [
48570
- ...(spec.repoLocalPaths ?? []).filter((repo) => comparablePath(repo.localPath, platform) === folder).map((repo) => repo.repoUrl),
48571
- ...spec.localRepoUrls ?? []
48572
- ];
48573
- }
48574
48273
  function resolveSelectedSkills(spec, context) {
48575
48274
  const invocations = spec.skillInvocations ?? [];
48576
48275
  if (context.skills === void 0) {
@@ -48597,51 +48296,18 @@ async function checkProvider(spec, context) {
48597
48296
  `The ${provider4.name} CLI (\`${provider4.command}\`) is not installed on this computer, or it is not on the PATH Alan uses. Install it and try again.`
48598
48297
  );
48599
48298
  }
48600
- async function locateWorkspace(spec, projectPath, expected, context, signal) {
48601
- const readiness = await inspectReadiness(projectPath);
48602
- if (readiness.ready) return { cwd: projectPath, relocated: null };
48603
- if (!readiness.missing) return rejected("workspace_unavailable", readiness.message);
48604
- if (spec.workspacePathPinned === true) {
48605
- return rejected("workspace_pinned_missing", MESSAGES2.pinnedMissing);
48606
- }
48607
- const found = await discoverRelocatedWorkspace({
48608
- missingPath: projectPath,
48609
- approvedWorkspacePaths: spec.approvedWorkspacePaths ?? [],
48610
- expected,
48611
- git: context.git,
48612
- platform: context.platform,
48613
- signal
48614
- });
48615
- if (found === null) return rejected("workspace_unavailable", readiness.message);
48616
- const moved = await inspectReadiness(found);
48617
- if (!moved.ready) return rejected("workspace_unavailable", moved.message);
48618
- return {
48619
- cwd: found,
48620
- relocated: {
48621
- sessionUpdate: "_alan/run.workspace_relocated",
48622
- previousPath: projectPath,
48623
- canonicalPath: found
48624
- }
48625
- };
48626
- }
48627
48299
  async function admitDefaultWorkspace(spec, context, skills) {
48628
48300
  const { env } = context;
48629
48301
  const path = resolveAlanDefaultWorkspacePath(env.HOME || env.USERPROFILE || (0, import_node_os5.homedir)());
48630
48302
  try {
48631
- await (0, import_promises37.mkdir)(path, { recursive: true, mode: 448 });
48632
- await (0, import_promises37.access)(path, import_node_fs9.constants.R_OK | import_node_fs9.constants.W_OK | import_node_fs9.constants.X_OK);
48633
- return {
48634
- kind: "admitted",
48635
- spec: { ...spec, projectPath: path },
48636
- relocated: null,
48637
- leaseTargets: [],
48638
- skills
48639
- };
48303
+ await (0, import_promises35.mkdir)(path, { recursive: true, mode: 448 });
48304
+ await (0, import_promises35.access)(path, import_node_fs9.constants.R_OK | import_node_fs9.constants.W_OK | import_node_fs9.constants.X_OK);
48305
+ return { kind: "admitted", spec: { ...spec, projectPath: path }, skills };
48640
48306
  } catch (error61) {
48641
48307
  const code = errnoCode(error61);
48642
48308
  return rejected(
48643
48309
  "workspace_unavailable",
48644
- code === "EACCES" || code === "EPERM" ? MESSAGES2.permission : MESSAGES2.missing
48310
+ code === "EACCES" || code === "EPERM" ? MESSAGES.permission : MESSAGES.missing
48645
48311
  );
48646
48312
  }
48647
48313
  }
@@ -48655,7 +48321,7 @@ async function withInstalledCloudSkills(spec, context) {
48655
48321
  }
48656
48322
  };
48657
48323
  }
48658
- async function admitRun(spec, context, signal) {
48324
+ async function admitRun(spec, context) {
48659
48325
  const provider4 = await checkProvider(spec, context);
48660
48326
  if (provider4 !== null) return provider4;
48661
48327
  const selected = await resolveSelectedSkills(spec, context);
@@ -48668,50 +48334,30 @@ async function admitRun(spec, context, signal) {
48668
48334
  const skills = selected.skills;
48669
48335
  spec = await withInstalledCloudSkills(spec, context);
48670
48336
  const projectPath = spec.projectPath;
48671
- if (projectPath === void 0) {
48672
- return { kind: "admitted", spec, relocated: null, leaseTargets: [], skills };
48673
- }
48337
+ if (projectPath === void 0) return { kind: "admitted", spec, skills };
48674
48338
  if (isAlanDefaultWorkspace(projectPath)) return admitDefaultWorkspace(spec, context, skills);
48675
- const { platform } = context;
48676
- const expected = repositoryIdentities(expectedRepositoryUrls(spec, projectPath, platform));
48677
- const located = await locateWorkspace(spec, projectPath, expected, context, signal);
48678
- if ("kind" in located) return located;
48679
- const { cwd, relocated } = located;
48339
+ const readiness = await inspectReadiness(projectPath);
48340
+ if (!readiness.ready) {
48341
+ return readiness.missing && spec.workspacePathPinned === true ? rejected("workspace_pinned_missing", MESSAGES.pinnedMissing) : rejected("workspace_unavailable", readiness.message);
48342
+ }
48680
48343
  const roots = [
48681
48344
  ...await context.approvedRoots(),
48682
48345
  projectPath,
48683
48346
  ...spec.approvedWorkspacePaths ?? [],
48684
- ...(spec.repoLocalPaths ?? []).map((repo) => repo.localPath),
48685
- ...relocated === null ? [] : [relocated.canonicalPath]
48347
+ ...(spec.repoLocalPaths ?? []).map((repo) => repo.localPath)
48686
48348
  ];
48687
- if (!await isApprovedPath(cwd, roots, platform)) {
48688
- return rejected("workspace_unavailable", MESSAGES2.notApproved);
48689
- }
48690
- if (expected.size > 0) {
48691
- const identity = await originIdentity(context.git, cwd, signal);
48692
- if (identity === null || !expected.has(identity)) {
48693
- return rejected("workspace_repository_mismatch", MESSAGES2.mismatch);
48694
- }
48349
+ if (!await isApprovedPath(projectPath, roots, context.platform)) {
48350
+ return rejected("workspace_unavailable", MESSAGES.notApproved);
48695
48351
  }
48696
- return {
48697
- kind: "admitted",
48698
- spec: relocated === null ? spec : { ...spec, projectPath: cwd },
48699
- relocated,
48700
- leaseTargets: await hasGitMarker(cwd) ? [cwd] : [],
48701
- skills
48702
- };
48352
+ return { kind: "admitted", spec, skills };
48703
48353
  }
48704
- var PROBE_TIMEOUT_MS2 = 5e3;
48705
48354
  var CHECKOUT_LOCAL_TIMEOUT_MS = 6e4;
48706
48355
  var CHECKOUT_NETWORK_TIMEOUT_MS = 12e4;
48707
48356
  function createHolderWorkspace(machine, clock, log) {
48708
48357
  const platform = machine.platform ?? process.platform;
48709
- const git = createGitRunner({ env: machine.env, platform, localTimeoutMs: PROBE_TIMEOUT_MS2 });
48710
- const locks = openRepositoryLocks({ dir: (0, import_node_path27.join)(machine.stateDir, "locks"), clock, platform });
48711
48358
  return {
48712
48359
  admission: {
48713
48360
  env: machine.env,
48714
- git,
48715
48361
  platform,
48716
48362
  skills: skillsLayout(
48717
48363
  machine.stateDir,
@@ -48719,14 +48365,13 @@ function createHolderWorkspace(machine, clock, log) {
48719
48365
  ),
48720
48366
  approvedRoots: async () => {
48721
48367
  const approved = await openApprovedPaths({
48722
- file: (0, import_node_path27.join)(machine.stateDir, "workspaces.json"),
48368
+ file: (0, import_node_path25.join)(machine.stateDir, "workspaces.json"),
48723
48369
  log,
48724
48370
  platform
48725
48371
  });
48726
48372
  return approved.roots();
48727
48373
  }
48728
48374
  },
48729
- lease: { git, locks, clock, log, platform },
48730
48375
  ...machine.refreshesFirstCheckout === true ? {
48731
48376
  refreshFirstCheckout: createCheckoutRefresh({
48732
48377
  git: createGitRunner({
@@ -48735,12 +48380,12 @@ function createHolderWorkspace(machine, clock, log) {
48735
48380
  localTimeoutMs: CHECKOUT_LOCAL_TIMEOUT_MS,
48736
48381
  networkTimeoutMs: CHECKOUT_NETWORK_TIMEOUT_MS
48737
48382
  }),
48738
- locks,
48383
+ locks: openRepositoryLocks({ dir: (0, import_node_path25.join)(machine.stateDir, "locks"), clock, platform }),
48739
48384
  log,
48740
- dir: (0, import_node_path27.join)(machine.stateDir, "checkout-freshness")
48385
+ dir: (0, import_node_path25.join)(machine.stateDir, "checkout-freshness")
48741
48386
  }),
48742
48387
  prepareAgentContext: createAgentContext({
48743
- dir: (0, import_node_path27.join)(machine.stateDir, "agent-context"),
48388
+ dir: (0, import_node_path25.join)(machine.stateDir, "agent-context"),
48744
48389
  homeDir: machine.env.HOME || (0, import_node_os5.homedir)()
48745
48390
  })
48746
48391
  } : {}
@@ -48748,28 +48393,14 @@ function createHolderWorkspace(machine, clock, log) {
48748
48393
  }
48749
48394
 
48750
48395
  // src/holder/respond.ts
48751
- function createAnswerGate() {
48752
- const state = { lease: null };
48753
- return {
48754
- allows: () => state.lease?.verify() ?? Promise.resolve(true),
48755
- guard: (lease) => {
48756
- state.lease = lease;
48757
- return {
48758
- [Symbol.dispose]: () => {
48759
- if (state.lease === lease) state.lease = null;
48760
- }
48761
- };
48762
- }
48763
- };
48764
- }
48765
- async function respondToTurn(runningRunId, gate, driver, request2) {
48396
+ async function respondToTurn(runningRunId, driver, request2) {
48766
48397
  if (runningRunId !== request2.runId) return "unknown_run";
48767
48398
  if (driver.respond === void 0) return "not_waiting";
48768
- return driver.respond(request2, () => gate.allows());
48399
+ return driver.respond(request2);
48769
48400
  }
48770
48401
 
48771
48402
  // src/holder/session-facts.ts
48772
- var import_promises38 = require("fs/promises");
48403
+ var import_promises36 = require("fs/promises");
48773
48404
  var CLI_RSS_CACHE_MS = 1e4;
48774
48405
  var LOGIN_PROBLEM_PREFIX = "cli.auth.";
48775
48406
  function isLoginFailure(result) {
@@ -48795,8 +48426,8 @@ function createSessionFacts(options) {
48795
48426
  const path = await resolveCommandOnPath(command, env, platform);
48796
48427
  if (path === null) return null;
48797
48428
  try {
48798
- const real = await (0, import_promises38.realpath)(path);
48799
- const info = await (0, import_promises38.stat)(real);
48429
+ const real = await (0, import_promises36.realpath)(path);
48430
+ const info = await (0, import_promises36.stat)(real);
48800
48431
  return { command, key: `${real}:${info.ino}:${info.size}:${info.mtimeMs}` };
48801
48432
  } catch {
48802
48433
  return null;
@@ -48883,8 +48514,8 @@ function createSessionFacts(options) {
48883
48514
  init_acp2();
48884
48515
 
48885
48516
  // src/run-log/directory.ts
48886
- var import_promises39 = require("fs/promises");
48887
- var import_node_path28 = require("path");
48517
+ var import_promises37 = require("fs/promises");
48518
+ var import_node_path26 = require("path");
48888
48519
  init_runtime_v2();
48889
48520
  init_zod();
48890
48521
  var runMetaSchema = external_exports.object({
@@ -48906,17 +48537,17 @@ var runMetaSchema = external_exports.object({
48906
48537
  }).optional()
48907
48538
  });
48908
48539
  function runDirectory(runsDir, runId) {
48909
- const dir = (0, import_node_path28.join)(runsDir, runId);
48540
+ const dir = (0, import_node_path26.join)(runsDir, runId);
48910
48541
  return {
48911
48542
  dir,
48912
- log: (0, import_node_path28.join)(dir, "log.jsonl"),
48913
- upload: (0, import_node_path28.join)(dir, "upload.json"),
48914
- meta: (0, import_node_path28.join)(dir, "run.json")
48543
+ log: (0, import_node_path26.join)(dir, "log.jsonl"),
48544
+ upload: (0, import_node_path26.join)(dir, "upload.json"),
48545
+ meta: (0, import_node_path26.join)(dir, "run.json")
48915
48546
  };
48916
48547
  }
48917
48548
  async function isRunClaimed(runsDir, runId) {
48918
48549
  try {
48919
- return (await (0, import_promises39.stat)(runDirectory(runsDir, runId).log)).size > 0;
48550
+ return (await (0, import_promises37.stat)(runDirectory(runsDir, runId).log)).size > 0;
48920
48551
  } catch (error61) {
48921
48552
  if (errnoCode(error61) === "ENOENT") return false;
48922
48553
  throw error61;
@@ -48924,8 +48555,8 @@ async function isRunClaimed(runsDir, runId) {
48924
48555
  }
48925
48556
 
48926
48557
  // src/run-log/conversation-index.ts
48927
- var import_promises40 = require("fs/promises");
48928
- var import_node_path29 = require("path");
48558
+ var import_promises38 = require("fs/promises");
48559
+ var import_node_path27 = require("path");
48929
48560
  init_runtime_v2();
48930
48561
  init_zod();
48931
48562
  var ORDINALS_PER_SHARD = 1e3;
@@ -48941,13 +48572,13 @@ var coverageSchema = external_exports.object({
48941
48572
  nextExpectedOrdinal: external_exports.number().int().positive()
48942
48573
  });
48943
48574
  function conversationsDirectory(runsDir) {
48944
- return (0, import_node_path29.join)((0, import_node_path29.dirname)(runsDir), "conversations");
48575
+ return (0, import_node_path27.join)((0, import_node_path27.dirname)(runsDir), "conversations");
48945
48576
  }
48946
48577
  function indexDirectory(runsDir, conversationId) {
48947
- return (0, import_node_path29.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
48578
+ return (0, import_node_path27.join)(conversationsDirectory(runsDir), conversationId, "turn-index");
48948
48579
  }
48949
48580
  function shardPath(runsDir, conversationId, ordinal) {
48950
- return (0, import_node_path29.join)(
48581
+ return (0, import_node_path27.join)(
48951
48582
  indexDirectory(runsDir, conversationId),
48952
48583
  `${Math.floor(ordinal / ORDINALS_PER_SHARD)}.jsonl`
48953
48584
  );
@@ -48956,10 +48587,10 @@ async function indexConversationRun(runsDir, conversationId, ordinal, assistantO
48956
48587
  const nextOrdinal = assistantOrdinal + 1;
48957
48588
  if (nextOrdinal <= ordinal) throw new Error("Assistant order must follow the prompt");
48958
48589
  const path = shardPath(runsDir, conversationId, ordinal);
48959
- await (0, import_promises40.mkdir)((0, import_node_path29.dirname)(path), { recursive: true, mode: 448 });
48960
- await (0, import_promises40.appendFile)(path, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
48590
+ await (0, import_promises38.mkdir)((0, import_node_path27.dirname)(path), { recursive: true, mode: 448 });
48591
+ await (0, import_promises38.appendFile)(path, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
48961
48592
  `, { mode: 384 });
48962
- const coveragePath = (0, import_node_path29.join)((0, import_node_path29.dirname)((0, import_node_path29.dirname)(path)), "coverage.json");
48593
+ const coveragePath = (0, import_node_path27.join)((0, import_node_path27.dirname)((0, import_node_path27.dirname)(path)), "coverage.json");
48963
48594
  const coverage = await readJsonFile(coveragePath, coverageSchema);
48964
48595
  const current = coverage.kind === "ok" ? coverage.value : null;
48965
48596
  const next = nextCoverage(current, ordinal, nextOrdinal);
@@ -49003,7 +48634,7 @@ var decoder = new TextDecoder();
49003
48634
 
49004
48635
  // src/run-log/writer.ts
49005
48636
  var import_node_fs10 = require("fs");
49006
- var import_node_path30 = require("path");
48637
+ var import_node_path28 = require("path");
49007
48638
  init_runtime_v2();
49008
48639
  function lastSeq(fd, size) {
49009
48640
  for (const length of tailWindows(size)) {
@@ -49019,7 +48650,7 @@ function lastSeq(fd, size) {
49019
48650
  throw new RuntimeFault("record_too_large", "Run log tail record is larger than any record");
49020
48651
  }
49021
48652
  function openRunLog(path, clock) {
49022
- (0, import_node_fs10.mkdirSync)((0, import_node_path30.dirname)(path), { recursive: true, mode: 448 });
48653
+ (0, import_node_fs10.mkdirSync)((0, import_node_path28.dirname)(path), { recursive: true, mode: 448 });
49023
48654
  const fd = (0, import_node_fs10.openSync)(path, "a+", 384);
49024
48655
  let size = (0, import_node_fs10.fstatSync)(fd).size;
49025
48656
  let seq = lastSeq(fd, size);
@@ -49056,107 +48687,6 @@ function openRunLog(path, clock) {
49056
48687
  };
49057
48688
  }
49058
48689
 
49059
- // src/holder/lease-gate.ts
49060
- init_acp();
49061
- var READ_ONLY_TOOL_KINDS = /* @__PURE__ */ new Set([
49062
- "read",
49063
- "search",
49064
- "think",
49065
- "fetch",
49066
- "switch_mode"
49067
- ]);
49068
- function gateWorkspaceWrites(sink, lease) {
49069
- const kinds = /* @__PURE__ */ new Map();
49070
- const state = { tail: Promise.resolve(), pending: 0, gate: null, blocked: 0 };
49071
- const writesFiles = (update) => {
49072
- if (!isUpdate(update, "tool_call_update")) return false;
49073
- if (typeof update.kind === "string") kinds.set(update.toolCallId, update.kind);
49074
- const kind = kinds.get(update.toolCallId);
49075
- return kind === void 0 || !READ_ONLY_TOOL_KINDS.has(kind);
49076
- };
49077
- const deliver = (event) => {
49078
- if (lease.failure() === null) {
49079
- sink.onEvent(event);
49080
- return;
49081
- }
49082
- if (event.update.sessionUpdate === "tool_call_update") state.blocked += 1;
49083
- };
49084
- const enqueue = (event, gate) => {
49085
- state.pending += 1;
49086
- state.tail = state.tail.then(async () => {
49087
- if (gate === null || await gate) deliver(event);
49088
- else if (event.update.sessionUpdate === "tool_call_update") state.blocked += 1;
49089
- }).finally(() => {
49090
- state.pending -= 1;
49091
- if (state.pending === 0) state.gate = null;
49092
- });
49093
- };
49094
- return {
49095
- onSpawned: (pid) => sink.onSpawned(pid),
49096
- onEvent: (event) => {
49097
- const write = writesFiles(event.update);
49098
- if (!write && state.pending === 0) {
49099
- deliver(event);
49100
- return;
49101
- }
49102
- if (write) state.gate ??= lease.verify();
49103
- enqueue(event, state.gate);
49104
- },
49105
- drain: async () => {
49106
- while (state.pending > 0) await state.tail;
49107
- },
49108
- blocked: () => state.blocked
49109
- };
49110
- }
49111
-
49112
- // src/holder/lease-turn.ts
49113
- function leaseNotice(failure5, blocked) {
49114
- const withheld = blocked === 0 ? "" : ` ${blocked} tool ${blocked === 1 ? "update was" : "updates were"} withheld.`;
49115
- return {
49116
- sessionUpdate: "notice",
49117
- severity: "error",
49118
- title: "The workspace changed while the agent was working",
49119
- description: `${failure5.message}${withheld}`,
49120
- _meta: {
49121
- "alan.dev/noticeKind": "workspace_lease_lost",
49122
- ...failure5.problemCode === null ? {} : { "alan.dev/problem": { domain: "application", code: failure5.problemCode } }
49123
- }
49124
- };
49125
- }
49126
- async function runLeased(spec, paths, turn, sink, signal, run) {
49127
- var _stack = [];
49128
- try {
49129
- const capture = await captureWorkspaceLease(spec.runId, paths, turn.lease, signal);
49130
- if (capture.kind === "failed") {
49131
- turn.log.warn("holder.workspace_lease_refused", {
49132
- runId: spec.runId,
49133
- code: capture.failure.code
49134
- });
49135
- return { outcome: "failed", message: capture.failure.message };
49136
- }
49137
- const lease = __using(_stack, capture.lease, true);
49138
- const _answers = __using(_stack, turn.answerGate?.guard(lease));
49139
- turn.log.info("holder.workspace_leased", { runId: spec.runId, checkouts: lease.checkouts });
49140
- const gated = gateWorkspaceWrites(sink, lease);
49141
- const result = await run(gated, AbortSignal.any([signal, lease.lost]));
49142
- await gated.drain();
49143
- const failure5 = lease.failure();
49144
- if (failure5 === null) return result;
49145
- sink.onEvent({ seq: 0, at: turn.clock.now(), update: leaseNotice(failure5, gated.blocked()) });
49146
- await turn.driver.suspend?.().catch((error61) => turn.log.warn("holder.driver_suspend_failed", { error: error61 }));
49147
- return {
49148
- outcome: "failed",
49149
- message: failure5.message,
49150
- ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId }
49151
- };
49152
- } catch (_) {
49153
- var _error = _, _hasError = true;
49154
- } finally {
49155
- var _promise2 = __callDispose(_stack, _error, _hasError);
49156
- _promise2 && await _promise2;
49157
- }
49158
- }
49159
-
49160
48690
  // src/holder/record-fit.ts
49161
48691
  init_acp2();
49162
48692
  init_runtime_v2();
@@ -49194,11 +48724,11 @@ function fitForRunLog(update) {
49194
48724
  }
49195
48725
 
49196
48726
  // src/holder/turn.ts
49197
- async function runWithInputs({ spec, leaseTargets, skills }, context, sink, signal) {
48727
+ async function runWithInputs({ spec, skills }, context, sink, signal) {
49198
48728
  var _stack = [];
49199
48729
  try {
49200
48730
  const workspace = context.workspace;
49201
- const sessionContext = (workspace?.refreshFirstCheckout?.(spec, leaseTargets, signal) ?? Promise.resolve([])).catch((error61) => {
48731
+ const sessionContext = (workspace?.refreshFirstCheckout?.(spec, signal) ?? Promise.resolve([])).catch((error61) => {
49202
48732
  context.log.warn("workspace.refresh_failed", { runId: spec.runId, error: error61 });
49203
48733
  return [];
49204
48734
  }).then((problems) => workspace?.prepareAgentContext?.(spec, problems)).catch((error61) => {
@@ -49217,35 +48747,24 @@ async function runWithInputs({ spec, leaseTargets, skills }, context, sink, sign
49217
48747
  }
49218
48748
  const agentContext = await sessionContext;
49219
48749
  const prepared = __using(_stack, inputs, true);
49220
- const run = async (turnSink, turnSignal) => {
49221
- const result = await context.driver.runTurn(
49222
- spec,
49223
- turnSink,
49224
- turnSignal,
49225
- agentContext === void 0 ? prepared : {
49226
- ...prepared,
49227
- agentContext: {
49228
- full: agentContext.full,
49229
- ...agentContext.update ? { update: agentContext.update } : {}
49230
- }
49231
- }
49232
- );
49233
- if (agentContext !== void 0 && result.outcome !== "rejected") {
49234
- await agentContext.save().catch((error61) => {
49235
- context.log.warn("holder.agent_context_save_failed", { runId: spec.runId, error: error61 });
49236
- });
49237
- }
49238
- return result;
49239
- };
49240
- if (workspace === void 0) return await run(sink, signal);
49241
- return await runLeased(
48750
+ const result = await context.driver.runTurn(
49242
48751
  spec,
49243
- leaseTargets,
49244
- { ...context, lease: workspace.lease },
49245
48752
  sink,
49246
48753
  signal,
49247
- run
48754
+ agentContext === void 0 ? prepared : {
48755
+ ...prepared,
48756
+ agentContext: {
48757
+ full: agentContext.full,
48758
+ ...agentContext.update ? { update: agentContext.update } : {}
48759
+ }
48760
+ }
49248
48761
  );
48762
+ if (agentContext !== void 0 && result.outcome !== "rejected") {
48763
+ await agentContext.save().catch((error61) => {
48764
+ context.log.warn("holder.agent_context_save_failed", { runId: spec.runId, error: error61 });
48765
+ });
48766
+ }
48767
+ return result;
49249
48768
  } catch (_) {
49250
48769
  var _error = _, _hasError = true;
49251
48770
  } finally {
@@ -49253,7 +48772,7 @@ async function runWithInputs({ spec, leaseTargets, skills }, context, sink, sign
49253
48772
  _promise2 && await _promise2;
49254
48773
  }
49255
48774
  }
49256
- async function admitAndRun(spec, context, append, sink, signal) {
48775
+ async function admitAndRun(spec, context, sink, signal) {
49257
48776
  if (context.workspace === void 0) {
49258
48777
  if (spec.skillInvocations?.length) {
49259
48778
  return {
@@ -49262,14 +48781,13 @@ async function admitAndRun(spec, context, append, sink, signal) {
49262
48781
  message: "Selected skills need this computer's skill sync, which this holder does not have."
49263
48782
  };
49264
48783
  }
49265
- return runWithInputs({ spec, leaseTargets: [], skills: [] }, context, sink, signal);
48784
+ return runWithInputs({ spec, skills: [] }, context, sink, signal);
49266
48785
  }
49267
- const admission = await admitRun(spec, context.workspace.admission, signal);
48786
+ const admission = await admitRun(spec, context.workspace.admission);
49268
48787
  if (admission.kind === "rejected") {
49269
48788
  context.log.info("holder.run_rejected", { runId: spec.runId, rejection: admission.rejection });
49270
48789
  return { outcome: "rejected", rejection: admission.rejection, message: admission.message };
49271
48790
  }
49272
- if (admission.relocated !== null) append(admission.relocated);
49273
48791
  return runWithInputs(admission, context, sink, signal);
49274
48792
  }
49275
48793
  async function claimRun(spec, context) {
@@ -49316,7 +48834,6 @@ async function runClaimedTurn(spec, claimed, context, signal) {
49316
48834
  result = await admitAndRun(
49317
48835
  spec,
49318
48836
  context,
49319
- append,
49320
48837
  {
49321
48838
  onSpawned: (pid) => append(runStarted({ pid })),
49322
48839
  // Base64 media in provider payloads and tool output never reaches the log (main 13590db369).
@@ -49379,12 +48896,11 @@ async function runHolder({
49379
48896
  try {
49380
48897
  const identity = await readProcessIdentity(process.pid);
49381
48898
  if (identity === null) throw new RuntimeFault("internal", "Cannot read own process identity");
49382
- const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path31.dirname)(launch.statusPath)), clock, log));
48899
+ const _engines = __using(_stack, recordSpawnedEngines(engineRecordsPath((0, import_node_path29.dirname)(launch.statusPath)), clock, log));
49383
48900
  const holder = {
49384
48901
  state: "idle",
49385
48902
  runId: null,
49386
48903
  turn: null,
49387
- answerGate: createAnswerGate(),
49388
48904
  clients: /* @__PURE__ */ new Set()
49389
48905
  };
49390
48906
  const exit = new AbortController();
@@ -49442,8 +48958,7 @@ async function runHolder({
49442
48958
  log,
49443
48959
  onAppended: (runId, offset) => broadcast({ type: "appended", runId, offset }),
49444
48960
  ...inputs === void 0 ? {} : { inputs },
49445
- ...workspace === void 0 ? {} : { workspace },
49446
- answerGate: holder.answerGate
48961
+ ...workspace === void 0 ? {} : { workspace }
49447
48962
  };
49448
48963
  claimRun(spec, context).then(
49449
48964
  (claimed) => {
@@ -49475,7 +48990,7 @@ async function runHolder({
49475
48990
  );
49476
48991
  };
49477
48992
  const respond = (request2, client) => {
49478
- respondToTurn(holder.runId, holder.answerGate, driver, request2).then((status) => {
48993
+ respondToTurn(holder.runId, driver, request2).then((status) => {
49479
48994
  log.info("holder.responded", { runId: request2.runId, status });
49480
48995
  writeMessage(client, { type: "responded", id: request2.id, status });
49481
48996
  }).catch((error61) => {
@@ -49521,12 +49036,12 @@ async function runHolder({
49521
49036
  return;
49522
49037
  case "status":
49523
49038
  void facts.snapshot().then(
49524
- (snapshot2) => writeMessage(client, {
49039
+ (snapshot) => writeMessage(client, {
49525
49040
  type: "status",
49526
49041
  id: request2.id,
49527
49042
  state: holder.state,
49528
49043
  runId: holder.runId,
49529
- facts: snapshot2
49044
+ facts: snapshot
49530
49045
  })
49531
49046
  );
49532
49047
  return;
@@ -49575,16 +49090,16 @@ async function runHolder({
49575
49090
  client.on("error", () => holder.clients.delete(client));
49576
49091
  });
49577
49092
  removeStaleEndpoint(launch.endpoint);
49578
- await new Promise((resolve9, reject) => {
49093
+ await new Promise((resolve8, reject) => {
49579
49094
  server.once("error", reject);
49580
- server.listen(launch.endpoint, () => resolve9());
49095
+ server.listen(launch.endpoint, () => resolve8());
49581
49096
  });
49582
49097
  await writeStatus();
49583
49098
  log.info("holder.ready", { conversationId: launch.conversationId, pid: identity.pid });
49584
- await new Promise((resolve9) => exit.signal.addEventListener("abort", () => resolve9()));
49099
+ await new Promise((resolve8) => exit.signal.addEventListener("abort", () => resolve8()));
49585
49100
  await driver.suspend?.().catch((error61) => log.warn("holder.driver_suspend_failed", { error: error61 }));
49586
49101
  for (const client of holder.clients) client.end();
49587
- await new Promise((resolve9) => server.close(() => resolve9()));
49102
+ await new Promise((resolve8) => server.close(() => resolve8()));
49588
49103
  (0, import_node_fs11.rmSync)(launch.statusPath, { force: true });
49589
49104
  log.info("holder.suspended", { conversationId: launch.conversationId });
49590
49105
  } catch (_) {
@@ -49724,7 +49239,7 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
49724
49239
  providerProbes: ALAN_RUNTIME_PROVIDER_PROBES === "on",
49725
49240
  providerToolchain: ALAN_RUNTIME_PROVIDER_NODE !== void 0 && ALAN_RUNTIME_PROVIDER_NPM_CLI !== void 0 ? { node: ALAN_RUNTIME_PROVIDER_NODE, npmCli: ALAN_RUNTIME_PROVIDER_NPM_CLI } : null,
49726
49241
  home,
49727
- configHome: XDG_CONFIG_HOME ?? (0, import_node_path33.join)(home, ".config"),
49242
+ configHome: XDG_CONFIG_HOME ?? (0, import_node_path31.join)(home, ".config"),
49728
49243
  codexHome: resolveCodexHome(CODEX_HOME, home),
49729
49244
  ...githubProxyConfig({ ALAN_RUNTIME_GITHUB_PROXY, XDG_CONFIG_HOME, GH_CONFIG_DIR }, home),
49730
49245
  gitGatewayUrl: ALAN_RUNTIME_GIT_GATEWAY_URL ?? null,
@@ -49734,13 +49249,13 @@ function loadRuntimeConfig(env = process.env, totalMemoryBytes = (0, import_node
49734
49249
  };
49735
49250
  }
49736
49251
  function resolveCodexHome(configuredHome, home) {
49737
- return configuredHome ?? (0, import_node_path33.join)(home, ".codex");
49252
+ return configuredHome ?? (0, import_node_path31.join)(home, ".codex");
49738
49253
  }
49739
49254
  function githubProxyConfig(env, home) {
49740
- const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path33.join)(home, ".config");
49255
+ const configHome = env.XDG_CONFIG_HOME ?? (0, import_node_path31.join)(home, ".config");
49741
49256
  return {
49742
49257
  githubProxy: env.ALAN_RUNTIME_GITHUB_PROXY === "on",
49743
- ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path33.join)(configHome, "gh")
49258
+ ghConfigDir: env.GH_CONFIG_DIR ?? (0, import_node_path31.join)(configHome, "gh")
49744
49259
  };
49745
49260
  }
49746
49261
  function serviceEnvironment(env, profile) {
@@ -49839,7 +49354,7 @@ async function loadStoredAccess(paths, access3 = { exec: systemExec }) {
49839
49354
  }
49840
49355
 
49841
49356
  // src/cli/commands/hold.ts
49842
- var import_node_path34 = require("path");
49357
+ var import_node_path32 = require("path");
49843
49358
  init_agent2();
49844
49359
  init_runtime_v2();
49845
49360
  async function machineAccess(paths, log, conversationId, transport) {
@@ -49897,7 +49412,7 @@ async function runHold(argv) {
49897
49412
  const config2 = loadRuntimeConfig();
49898
49413
  const paths = runtimePaths(config2.stateDir);
49899
49414
  const log = __using(_stack, openFileLog(
49900
- (0, import_node_path34.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
49415
+ (0, import_node_path32.join)(paths.logs, `holder-${launch.value.conversationId}.jsonl`),
49901
49416
  config2.logLevel,
49902
49417
  systemClock
49903
49418
  ));
@@ -49908,7 +49423,7 @@ async function runHold(argv) {
49908
49423
  );
49909
49424
  const transport = __using(_stack, createHttpTransport());
49910
49425
  const access3 = await machineAccess(paths, log, launch.value.conversationId, transport);
49911
- const credentialPath = (0, import_node_path34.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
49426
+ const credentialPath = (0, import_node_path32.join)(paths.tmp, "mcp", `${launch.value.conversationId}.json`);
49912
49427
  const managedMcp = __using(_stack, access3.managedMcp === void 0 ? void 0 : createHelperMcpAccess({
49913
49428
  managedMcp: access3.managedMcp,
49914
49429
  conversationId: launch.value.conversationId,