@alan-ai-hq/agent-manager-linux-arm64 0.1.187 → 0.1.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/alan-holder.cjs CHANGED
@@ -21123,6 +21123,15 @@ var init_agent_context = __esm({
21123
21123
  }
21124
21124
  });
21125
21125
 
21126
+ // ../shared/src/session-owned-execution.ts
21127
+ var EXECUTION_OWNERS;
21128
+ var init_session_owned_execution = __esm({
21129
+ "../shared/src/session-owned-execution.ts"() {
21130
+ "use strict";
21131
+ EXECUTION_OWNERS = ["task", "session"];
21132
+ }
21133
+ });
21134
+
21126
21135
  // ../shared/src/skills/domain.ts
21127
21136
  var SKILLS_PROTOCOL_VERSION, SKILL_PACKAGE_LIMITS;
21128
21137
  var init_domain = __esm({
@@ -21789,7 +21798,19 @@ var init_run_context = __esm({
21789
21798
  title: external_exports.string(),
21790
21799
  url: external_exports.string().optional()
21791
21800
  })
21792
- ).optional()
21801
+ ).optional(),
21802
+ contextBundle: external_exports.object({
21803
+ decisions: external_exports.array(external_exports.string()),
21804
+ pullRequests: external_exports.array(
21805
+ external_exports.object({
21806
+ number: external_exports.number().int(),
21807
+ title: external_exports.string(),
21808
+ url: external_exports.string(),
21809
+ state: external_exports.string()
21810
+ })
21811
+ ),
21812
+ siblingSessions: external_exports.array(external_exports.string())
21813
+ }).optional()
21793
21814
  })
21794
21815
  );
21795
21816
  pullRequestMetaSchema = wire()(
@@ -21907,6 +21928,7 @@ var init_desired_state = __esm({
21907
21928
  "use strict";
21908
21929
  init_zod();
21909
21930
  init_cloud_repositories();
21931
+ init_session_owned_execution();
21910
21932
  init_contracts();
21911
21933
  init_agent_context();
21912
21934
  init_commit_attribution();
@@ -21932,6 +21954,8 @@ var init_desired_state = __esm({
21932
21954
  conversationId: conversationIdSchema,
21933
21955
  messageId: external_exports.guid().optional(),
21934
21956
  taskId: external_exports.guid().optional(),
21957
+ /** Absent from older servers; a session-owned run's browser scope and branch are the session's. */
21958
+ executionOwner: external_exports.enum(EXECUTION_OWNERS).optional(),
21935
21959
  teamId: external_exports.guid().optional(),
21936
21960
  content: external_exports.string(),
21937
21961
  backendKind: external_exports.string().min(1),
@@ -21946,6 +21970,7 @@ var init_desired_state = __esm({
21946
21970
  resumeFallbackContext: external_exports.string().optional(),
21947
21971
  projectPath: external_exports.string().min(1).optional(),
21948
21972
  workspacePathPinned: external_exports.boolean().optional(),
21973
+ localWorktree: external_exports.object({ branch: gitBranchSchema, baseBranch: gitBranchSchema.optional() }).optional(),
21949
21974
  approvedWorkspacePaths: external_exports.array(external_exports.string().min(1)).optional(),
21950
21975
  repoLocalPaths: external_exports.array(repoLocalPathSchema).optional(),
21951
21976
  /** Applied once, at the conversation's first turn on a cloud sandbox; never moves local work. */
@@ -22047,7 +22072,7 @@ var init_machine_identity = __esm({
22047
22072
  register: "/public/machines/register",
22048
22073
  /** POST with a cloud sandbox's one-time enrollment code from `ALAN_RUNTIME_ENROLLMENT_CODE`. */
22049
22074
  enroll: "/public/machines/enroll",
22050
- /** POST with the current renewal token; the response carries a new one and the old dies. */
22075
+ // quirk: POST with the current renewal token; the response carries a new one and the previous one dies.
22051
22076
  renew: "/public/machines/me/renew",
22052
22077
  /** POST by the machine itself on logout/uninstall. */
22053
22078
  revokeSelf: "/public/machines/me/revoke",
@@ -22367,6 +22392,26 @@ var init_capabilities = __esm({
22367
22392
  }
22368
22393
  });
22369
22394
 
22395
+ // ../shared/src/type-guards.ts
22396
+ function isRecord(value2) {
22397
+ return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
22398
+ }
22399
+ function isObjectLike(value2) {
22400
+ return typeof value2 === "object" && value2 !== null;
22401
+ }
22402
+ function tryParseJson(text3) {
22403
+ try {
22404
+ return JSON.parse(text3);
22405
+ } catch {
22406
+ return void 0;
22407
+ }
22408
+ }
22409
+ var init_type_guards = __esm({
22410
+ "../shared/src/type-guards.ts"() {
22411
+ "use strict";
22412
+ }
22413
+ });
22414
+
22370
22415
  // ../shared/src/validators/attachments.ts
22371
22416
  var MAX_COMMENT_ATTACHMENTS, requestPresignedUploadSchema, linkAttachmentSchema, renameAttachmentSchema;
22372
22417
  var init_attachments = __esm({
@@ -22451,6 +22496,7 @@ var init_problem = __esm({
22451
22496
  "cli.auth.expired",
22452
22497
  "cli.entitlement.required",
22453
22498
  "cli.model.unavailable",
22499
+ "cli.model.paused",
22454
22500
  "cli.rate_limited",
22455
22501
  "cli.quota_exceeded",
22456
22502
  "cli.context_exhausted",
@@ -24111,7 +24157,6 @@ var init_skills = __esm({
24111
24157
  skills: external_exports.array(desiredMachineSkillSchema).max(MAX_MACHINE_SKILLS),
24112
24158
  /** Only the desired versions the machine reported missing or different. */
24113
24159
  downloads: external_exports.array(machineSkillDownloadSchema).max(MAX_MACHINE_SKILLS),
24114
- /** Installed skill ids that are no longer desired. */
24115
24160
  removals: external_exports.array(skillIdSchema).max(MAX_MACHINE_SKILLS),
24116
24161
  /** Absent from an API that predates local skills; the machine then reports none. */
24117
24162
  scanContext: machineSkillScanContextSchema.optional(),
@@ -25053,23 +25098,6 @@ var init_mcp_config = __esm({
25053
25098
  }
25054
25099
  });
25055
25100
 
25056
- // ../shared/src/type-guards.ts
25057
- function isRecord(value2) {
25058
- return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
25059
- }
25060
- function tryParseJson(text3) {
25061
- try {
25062
- return JSON.parse(text3);
25063
- } catch {
25064
- return void 0;
25065
- }
25066
- }
25067
- var init_type_guards = __esm({
25068
- "../shared/src/type-guards.ts"() {
25069
- "use strict";
25070
- }
25071
- });
25072
-
25073
25101
  // ../shared/src/agent/opencode-zen-entitlement.ts
25074
25102
  var init_opencode_zen_entitlement = __esm({
25075
25103
  "../shared/src/agent/opencode-zen-entitlement.ts"() {
@@ -26315,6 +26343,11 @@ var init_kinds = __esm({
26315
26343
  message: "The provider is overloaded right now. Wait a moment or pick a different model, then send your message again.",
26316
26344
  recoveryClass: "auto_recovering"
26317
26345
  },
26346
+ // Our own load balancer answering with no backend: a deploy or restart, not a provider problem.
26347
+ service_updating: {
26348
+ message: "Alan Code is updating and will be back in a few seconds. Retrying automatically \u2014 no action needed.",
26349
+ recoveryClass: "auto_recovering"
26350
+ },
26318
26351
  network: {
26319
26352
  message: "Network connection failed. Check your internet connection, then send your message again.",
26320
26353
  recoveryClass: "auto_recovering"
@@ -26515,10 +26548,8 @@ function embeddedJson(text3) {
26515
26548
  const start = text3.indexOf("{");
26516
26549
  if (start === -1) return void 0;
26517
26550
  for (const end of [text3.length, text3.lastIndexOf("}") + 1]) {
26518
- try {
26519
- return asRecord(JSON.parse(text3.slice(start, end)));
26520
- } catch {
26521
- }
26551
+ const parsed = tryParseJson(text3.slice(start, end));
26552
+ if (parsed !== void 0) return asRecord(parsed);
26522
26553
  }
26523
26554
  return void 0;
26524
26555
  }
@@ -26551,6 +26582,7 @@ var STATUS_PREFIX, ERROR_CODE_SHAPE;
26551
26582
  var init_provider_error = __esm({
26552
26583
  "../agent-core/src/classify/provider-error.ts"() {
26553
26584
  "use strict";
26585
+ init_type_guards();
26554
26586
  init_kernel2();
26555
26587
  STATUS_PREFIX = /\b(?:api error|status|http)[:\s]+(\d{3})\b/i;
26556
26588
  ERROR_CODE_SHAPE = /^[a-z][a-z0-9_]*$/;
@@ -26625,6 +26657,14 @@ var init_rules = __esm({
26625
26657
  kind: "quota_exceeded",
26626
26658
  pattern: /\bquota (?:exceeded|limit)\b|\b(?:daily|monthly) limit\b|\bbilling\b/
26627
26659
  },
26660
+ // Above `overloaded`: Google's load balancer says this when it has no healthy backend for our
26661
+ // own gateway during a deploy, and reading it as a provider overload sends users to the wrong
26662
+ // place (notes/2026-11-18-harness-deploy-zero-downtime.md). "Service Unavailable" alone still
26663
+ // falls through to `overloaded`, which is the right reading for a provider's own 503.
26664
+ {
26665
+ kind: "service_updating",
26666
+ pattern: /\bfailed_to_pick_backend\b|\bno healthy upstream\b|\bno healthy backends?\b/
26667
+ },
26628
26668
  {
26629
26669
  kind: "overloaded",
26630
26670
  pattern: /\boverloaded(?:_error)?\b|\bat capacity\b|\bserver_overloaded\b|\b(?:http|status|code|error)\s*:?\s*5\d\d\b|\[5\d\d\]|\bapi error:?\s*5\d\d\b|\b5\d\d (?:internal server error|bad gateway|service unavailable|gateway timeout)\b|\bservice unavailable\b|\bbad gateway\b|\bgateway timeout\b|\bapi server (?:encountered an error|returned an error|is unavailable)\b/
@@ -26811,7 +26851,9 @@ var init_classify = __esm({
26811
26851
  TEXT_REFINES = {
26812
26852
  rate_limited: /* @__PURE__ */ new Set(["usage_limit", "quota_exceeded"]),
26813
26853
  payment_required: /* @__PURE__ */ new Set(["usage_limit", "managed_models_paused"]),
26814
- auth_invalid: /* @__PURE__ */ new Set(["auth_expired", "not_logged_in", "not_authenticated"])
26854
+ auth_invalid: /* @__PURE__ */ new Set(["auth_expired", "not_logged_in", "not_authenticated"]),
26855
+ // A 503 from our own load balancer carries no backend, which is a deploy, not an overload.
26856
+ overloaded: /* @__PURE__ */ new Set(["service_updating"])
26815
26857
  };
26816
26858
  STATUS_LEAD = /^(?:(?:api error|status|http)[:\s]+\d{3}\b|payment required:)[:\s]*/i;
26817
26859
  }
@@ -26882,12 +26924,13 @@ var init_problem2 = __esm({
26882
26924
  auth_expired: "cli.auth.expired",
26883
26925
  subscription_required: "cli.entitlement.required",
26884
26926
  payment_required: "cli.entitlement.required",
26885
- managed_models_paused: "cli.model.unavailable",
26927
+ managed_models_paused: "cli.model.paused",
26886
26928
  quota_exceeded: "cli.quota_exceeded",
26887
26929
  usage_limit: "cli.quota_exceeded",
26888
26930
  context_length: "cli.context_exhausted",
26889
26931
  rate_limited: "cli.rate_limited",
26890
26932
  overloaded: "cli.unknown",
26933
+ service_updating: "cli.unknown",
26891
26934
  network: "cli.unknown",
26892
26935
  provider_timeout: "cli.process.timeout",
26893
26936
  resume_failed: "cli.resume_failed",
@@ -27366,15 +27409,19 @@ var init_flag_probe = __esm({
27366
27409
  });
27367
27410
 
27368
27411
  // ../agent-core/src/process/flag-probe-store.ts
27412
+ async function isExecutable(path19) {
27413
+ try {
27414
+ await (0, import_promises10.access)(path19, import_node_fs8.constants.X_OK);
27415
+ return true;
27416
+ } catch {
27417
+ return false;
27418
+ }
27419
+ }
27369
27420
  async function resolveBinary(command, env) {
27370
27421
  const candidates2 = command.includes("/") ? [command] : (env.PATH ?? "").split(import_node_path9.delimiter).filter((dir) => dir.length > 0).map((dir) => (0, import_node_path9.join)(dir, command));
27371
27422
  for (const candidate of candidates2) {
27372
27423
  if (!(0, import_node_path9.isAbsolute)(candidate)) continue;
27373
- try {
27374
- await (0, import_promises10.access)(candidate, import_node_fs8.constants.X_OK);
27375
- return candidate;
27376
- } catch {
27377
- }
27424
+ if (await isExecutable(candidate)) return candidate;
27378
27425
  }
27379
27426
  return null;
27380
27427
  }
@@ -27889,7 +27936,9 @@ var init_windows_helper2 = __esm({
27889
27936
  function preferForOomKill(pid) {
27890
27937
  try {
27891
27938
  (0, import_node_fs10.writeFileSync)(`/proc/${pid}/oom_score_adj`, String(CLI_OOM_SCORE_ADJ));
27939
+ return true;
27892
27940
  } catch {
27941
+ return false;
27893
27942
  }
27894
27943
  }
27895
27944
  function onCliSpawned(listener) {
@@ -29592,10 +29641,8 @@ function contentStrings(content2, toolInput) {
29592
29641
  const values = [];
29593
29642
  if (content2) {
29594
29643
  values.push(content2);
29595
- try {
29596
- collectStrings(JSON.parse(content2), values);
29597
- } catch {
29598
- }
29644
+ const parsed = tryParseJson(content2);
29645
+ if (parsed !== void 0) collectStrings(parsed, values);
29599
29646
  }
29600
29647
  collectStrings(toolInput, values);
29601
29648
  return values;
@@ -29626,12 +29673,15 @@ function pathCandidates(values, extensions) {
29626
29673
  for (const value2 of values) for (const match of value2.matchAll(pattern)) paths.add(match[0]);
29627
29674
  return [...paths];
29628
29675
  }
29629
- function normalizePath(candidate, cwd) {
29630
- let path19 = candidate.trim().replace(/^file:\/\//, "");
29676
+ function decodeUriOrSelf(path19) {
29631
29677
  try {
29632
- path19 = decodeURI(path19);
29678
+ return decodeURI(path19);
29633
29679
  } catch {
29680
+ return path19;
29634
29681
  }
29682
+ }
29683
+ function normalizePath(candidate, cwd) {
29684
+ const path19 = decodeUriOrSelf(candidate.trim().replace(/^file:\/\//, ""));
29635
29685
  if (path19.startsWith("~/")) return void 0;
29636
29686
  if ((0, import_node_path12.isAbsolute)(path19)) return path19;
29637
29687
  return cwd ? (0, import_node_path12.join)(cwd, path19) : void 0;
@@ -29734,6 +29784,7 @@ var init_local_media = __esm({
29734
29784
  import_node_path12 = require("node:path");
29735
29785
  init_agent2();
29736
29786
  init_acp();
29787
+ init_type_guards();
29737
29788
  init_acp2();
29738
29789
  init_kernel2();
29739
29790
  IMAGE_MIME_BY_EXT = {
@@ -30587,6 +30638,13 @@ var init_copilot = __esm({
30587
30638
  });
30588
30639
 
30589
30640
  // ../agent-core/src/transcript/cursor.ts
30641
+ function currentSize(path19) {
30642
+ try {
30643
+ return (0, import_node_fs13.statSync)(path19, { throwIfNoEntry: false })?.size ?? 0;
30644
+ } catch {
30645
+ return 0;
30646
+ }
30647
+ }
30590
30648
  var import_node_fs13, NEWLINE2, TranscriptCursor, TranscriptLineLookup;
30591
30649
  var init_cursor = __esm({
30592
30650
  "../agent-core/src/transcript/cursor.ts"() {
@@ -30606,13 +30664,7 @@ var init_cursor = __esm({
30606
30664
  }
30607
30665
  /** Starts after everything written so far; the writer must be idle at a line boundary. */
30608
30666
  skipToEnd() {
30609
- try {
30610
- this.#offset = Math.max(
30611
- this.#offset,
30612
- (0, import_node_fs13.statSync)(this.#path, { throwIfNoEntry: false })?.size ?? 0
30613
- );
30614
- } catch {
30615
- }
30667
+ this.#offset = Math.max(this.#offset, currentSize(this.#path));
30616
30668
  }
30617
30669
  read() {
30618
30670
  const buffer = this.#unread();
@@ -30888,6 +30940,20 @@ var init_code_mode = __esm({
30888
30940
  }
30889
30941
  });
30890
30942
 
30943
+ // ../agent-core/src/mcp/env-digest.ts
30944
+ function envDigest(env) {
30945
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
30946
+ for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
30947
+ return hash2.digest("hex");
30948
+ }
30949
+ var import_node_crypto8;
30950
+ var init_env_digest = __esm({
30951
+ "../agent-core/src/mcp/env-digest.ts"() {
30952
+ "use strict";
30953
+ import_node_crypto8 = require("node:crypto");
30954
+ }
30955
+ });
30956
+
30891
30957
  // ../agent-core/src/mcp/external.ts
30892
30958
  function selectExternalMcpServers(spec) {
30893
30959
  const isWorkflow = Boolean(spec.workflowId || spec.workflowExecutionId);
@@ -30902,7 +30968,7 @@ function selectExternalMcpServers(spec) {
30902
30968
  return selected;
30903
30969
  }
30904
30970
  function headerEnvName(server, header) {
30905
- const fingerprint = (0, import_node_crypto8.createHash)("sha256").update(`${server}\0${header}`).digest("hex").slice(0, 12);
30971
+ const fingerprint = (0, import_node_crypto9.createHash)("sha256").update(`${server}\0${header}`).digest("hex").slice(0, 12);
30906
30972
  return `ALAN_MCP_HEADER_${fingerprint.toUpperCase()}`;
30907
30973
  }
30908
30974
  function deliverRemote(name, server, env) {
@@ -30949,11 +31015,11 @@ function planExternalMcpDelivery(spec, cliEnv) {
30949
31015
  }
30950
31016
  return delivery;
30951
31017
  }
30952
- var import_node_crypto8;
31018
+ var import_node_crypto9;
30953
31019
  var init_external2 = __esm({
30954
31020
  "../agent-core/src/mcp/external.ts"() {
30955
31021
  "use strict";
30956
- import_node_crypto8 = require("node:crypto");
31022
+ import_node_crypto9 = require("node:crypto");
30957
31023
  init_agent2();
30958
31024
  }
30959
31025
  });
@@ -30976,13 +31042,13 @@ function managedMcpHeaders(identity2) {
30976
31042
  }
30977
31043
  function credentialDigest(authorization) {
30978
31044
  if (authorization === void 0) return void 0;
30979
- return (0, import_node_crypto9.createHash)("sha256").update(authorization).digest("hex").slice(0, 16);
31045
+ return (0, import_node_crypto10.createHash)("sha256").update(authorization).digest("hex").slice(0, 16);
30980
31046
  }
30981
- var import_node_crypto9;
31047
+ var import_node_crypto10;
30982
31048
  var init_managed = __esm({
30983
31049
  "../agent-core/src/mcp/managed.ts"() {
30984
31050
  "use strict";
30985
- import_node_crypto9 = require("node:crypto");
31051
+ import_node_crypto10 = require("node:crypto");
30986
31052
  init_agent2();
30987
31053
  init_runtime_v2();
30988
31054
  }
@@ -31039,6 +31105,7 @@ var init_mcp2 = __esm({
31039
31105
  "../agent-core/src/mcp/index.ts"() {
31040
31106
  "use strict";
31041
31107
  init_code_mode();
31108
+ init_env_digest();
31042
31109
  init_external2();
31043
31110
  init_managed();
31044
31111
  init_names();
@@ -32869,18 +32936,21 @@ function repositories(input2, context) {
32869
32936
  )
32870
32937
  ];
32871
32938
  }
32872
- function branchInstruction(repository) {
32939
+ function branchOwnerOf(snapshot) {
32940
+ return snapshot.session.workingBranch === void 0 ? "task" : "session";
32941
+ }
32942
+ function branchInstruction(repository, owner) {
32873
32943
  const { path: path19, branch, branchSource } = repository;
32874
32944
  if (!branch || !branchSource) return void 0;
32875
- const reason = BRANCH_REASONS[branchSource];
32945
+ const reason = branchSource === "task" && owner === "session" ? "this session's branch" : BRANCH_REASONS[branchSource];
32876
32946
  if (branchSource === "task") {
32877
32947
  return `Commit work in ${path19} on ${branch}, ${reason}; create it from ${repository.base ?? "the default branch"} if it does not exist.`;
32878
32948
  }
32879
32949
  return `Work in ${path19} on ${branch}, ${reason}.`;
32880
32950
  }
32881
- function repositoryInstructions(repository) {
32951
+ function repositoryInstructions(repository, owner) {
32882
32952
  const problem = repository.problem && repository.action ? `${repository.path} ${repository.problem}. ${repository.action} before relying on its files.` : void 0;
32883
- const branch = problem && repository.branchSource !== "environment_default" ? void 0 : branchInstruction(repository);
32953
+ const branch = problem && repository.branchSource !== "environment_default" ? void 0 : branchInstruction(repository, owner);
32884
32954
  return [branch, problem].filter((line) => line !== void 0);
32885
32955
  }
32886
32956
  function environmentInstructions(environment, cwd) {
@@ -32969,7 +33039,9 @@ function startingInstructions(snapshot) {
32969
33039
  const cwd = snapshot.workspace.cwd ?? snapshot.workspace.root;
32970
33040
  return [
32971
33041
  ...cwd ? [`Work from ${cwd}.`] : [],
32972
- ...snapshot.workspace.repositories.flatMap(repositoryInstructions),
33042
+ ...snapshot.workspace.repositories.flatMap(
33043
+ (repository) => repositoryInstructions(repository, branchOwnerOf(snapshot))
33044
+ ),
32973
33045
  ...snapshot.surface ? SURFACE_INSTRUCTIONS[snapshot.surface.provider] : []
32974
33046
  ];
32975
33047
  }
@@ -33004,6 +33076,7 @@ function knownContext(snapshot) {
33004
33076
  const organizationId = snapshot?.session.organizationId;
33005
33077
  if (!snapshot || !organizationId) return void 0;
33006
33078
  const environment = snapshot.environment;
33079
+ const workingBranch = snapshot.task?.workingBranch ?? snapshot.session.workingBranch;
33007
33080
  return {
33008
33081
  kind: snapshot.session.kind,
33009
33082
  trigger: "user",
@@ -33011,7 +33084,7 @@ function knownContext(snapshot) {
33011
33084
  ...snapshot.session.team ? { team: snapshot.session.team } : {},
33012
33085
  ...snapshot.session.harness ? { harness: snapshot.session.harness } : {},
33013
33086
  ...snapshot.teamInstructions ? { teamInstructions: snapshot.teamInstructions } : {},
33014
- ...snapshot.task ? { taskWorkingBranch: snapshot.task.workingBranch } : {},
33087
+ ...workingBranch ? { taskWorkingBranch: workingBranch } : {},
33015
33088
  ...snapshot.pullRequest ? { pullRequest: snapshot.pullRequest } : {},
33016
33089
  repositories: snapshot.workspace.repositories.flatMap(
33017
33090
  ({ path: path19, name, url: url2, branch, branchSource, base }) => name && url2 && branch && branchSource && base ? [{ path: path19, name, url: url2, branch, branchSource, base }] : []
@@ -33042,16 +33115,20 @@ function sessionOf(input2, context) {
33042
33115
  ...input2.spec.workflowExecutionId ? { workflowExecutionId: input2.spec.workflowExecutionId } : {},
33043
33116
  ...context ? { organizationId: context.organizationId } : {},
33044
33117
  ...context?.team ? { team: context.team } : {},
33045
- ...context?.harness ? { harness: context.harness } : {}
33118
+ ...context?.harness ? { harness: context.harness } : {},
33119
+ ...ownsWorkingBranch(input2, context) && context?.taskWorkingBranch ? { workingBranch: context.taskWorkingBranch } : {}
33046
33120
  };
33047
33121
  }
33122
+ function ownsWorkingBranch(input2, context) {
33123
+ return input2.spec.executionOwner === "session" && context?.taskWorkingBranch !== void 0;
33124
+ }
33048
33125
  function agentContextSnapshot(input2) {
33049
33126
  const context = input2.spec.agentContext ?? knownContext(input2.known);
33050
33127
  if (!context && input2.problems.length === 0) return null;
33051
33128
  const environment = environmentOf(input2, context);
33052
33129
  const base = {
33053
33130
  session: sessionOf(input2, context),
33054
- ...context?.taskWorkingBranch ? { task: { workingBranch: context.taskWorkingBranch } } : {},
33131
+ ...context?.taskWorkingBranch && !ownsWorkingBranch(input2, context) ? { task: { workingBranch: context.taskWorkingBranch } } : {},
33055
33132
  ...context?.pullRequest ? { pullRequest: context.pullRequest } : {},
33056
33133
  workspace: {
33057
33134
  ...input2.workspaceRoot ? { root: input2.workspaceRoot } : {},
@@ -33220,7 +33297,8 @@ var init_agent_context2 = __esm({
33220
33297
  workflowExecutionId: external_exports.string().optional(),
33221
33298
  organizationId: external_exports.string().optional(),
33222
33299
  team: agentContextTeamSchema.optional(),
33223
- harness: agentContextHarnessSchema.optional()
33300
+ harness: agentContextHarnessSchema.optional(),
33301
+ workingBranch: external_exports.string().optional()
33224
33302
  }),
33225
33303
  task: external_exports.object({ workingBranch: external_exports.string() }).optional(),
33226
33304
  pullRequest: agentContextPullRequestSchema.optional(),
@@ -33435,46 +33513,15 @@ function currentUserSection(user, visibility) {
33435
33513
  );
33436
33514
  return lines2.join("\n");
33437
33515
  }
33438
- function taskDetailLines(meta3) {
33439
- const lines2 = [];
33440
- if (meta3.priority && meta3.priority !== "none")
33441
- lines2.push(`- **Priority**: ${meta3.priority.toUpperCase()}`);
33442
- if (meta3.labels?.length) lines2.push(`- **Labels**: ${meta3.labels.join(", ")}`);
33443
- if (meta3.assignees?.length) {
33444
- lines2.push(`- **Assignees**: ${meta3.assignees.map((a) => a.name ?? a.email).join(", ")}`);
33445
- }
33446
- if (meta3.description) lines2.push(`- **Description**:
33447
- ${meta3.description}`);
33448
- return lines2;
33449
- }
33450
33516
  function taskContextSection(meta3) {
33451
33517
  if (!meta3) return void 0;
33452
- const lines2 = [
33518
+ return [
33453
33519
  "# Task Context",
33520
+ `- **Task ID**: ${meta3.id}`,
33454
33521
  `- **Title**: ${meta3.title}`,
33455
33522
  `- **Status**: ${meta3.status.replace(/_/g, " ")}`,
33456
- ...taskDetailLines(meta3)
33457
- ];
33458
- if (meta3.descriptionAttachmentIds?.length) {
33459
- lines2.push(
33460
- "",
33461
- "## Task Description Images",
33462
- 'The task description contains images. Use the `attachment` MCP tool with op="get" to view them:',
33463
- ...meta3.descriptionAttachmentIds.map(
33464
- (att) => `- Attachment ID: \`${att.id}\` (${att.filename})`
33465
- )
33466
- );
33467
- }
33468
- if (meta3.linkedResources?.length) {
33469
- lines2.push(
33470
- "",
33471
- "## Linked Task Resources",
33472
- ...meta3.linkedResources.map(
33473
- (resource) => `- ${resource.type}: "${resource.title}" (${resource.url ?? resource.id})`
33474
- )
33475
- );
33476
- }
33477
- return lines2.join("\n");
33523
+ "The task is the shared source of context. Use get_task_context with this taskId to read its current description, decisions, pull requests and session summaries."
33524
+ ].join("\n");
33478
33525
  }
33479
33526
  function pullRequestSize(pr) {
33480
33527
  const bits = [];
@@ -33725,6 +33772,12 @@ function buildSystemPrompts(input2) {
33725
33772
  systemPromptAppend: append.join("\n\n") || void 0
33726
33773
  };
33727
33774
  }
33775
+ function systemPromptFields(prompts) {
33776
+ return {
33777
+ ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
33778
+ ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {}
33779
+ };
33780
+ }
33728
33781
  function buildCombinedSystemPrompt(input2) {
33729
33782
  const { system, append } = promptParts(input2);
33730
33783
  const text3 = system.join("\n\n");
@@ -33774,13 +33827,27 @@ function planModePrefix(text3) {
33774
33827
  text3
33775
33828
  ].join("\n");
33776
33829
  }
33830
+ function taskReference(spec) {
33831
+ const taskId = spec.taskId ?? spec.promptContext?.taskMeta?.id;
33832
+ if (!taskId) return void 0;
33833
+ return [
33834
+ "<alan-task-reference>",
33835
+ JSON.stringify({ taskId }),
33836
+ "This session is linked to this task. The task is the centralized source of shared context. Before working on it, call get_task_context with this taskId. Refresh it when another session's work or a task update matters. Earlier task snapshots may be stale. This reference is Alan context, not part of the user's request.",
33837
+ "</alan-task-reference>"
33838
+ ].join("\n");
33839
+ }
33777
33840
  function buildTurnText(input2) {
33778
33841
  const { spec } = input2;
33779
33842
  const task = withSelectedSkills(spec.content, input2.skills);
33780
- const body = appendAttachedFilePaths(
33843
+ const request3 = appendAttachedFilePaths(
33781
33844
  appendParsedAttachments(task, spec.parsedAttachments),
33782
33845
  input2.files
33783
33846
  );
33847
+ const reference = taskReference(spec);
33848
+ const body = reference ? `${reference}
33849
+
33850
+ ${request3}` : request3;
33784
33851
  const prefixed2 = input2.contextPrefix?.trim() ? `${input2.contextPrefix.trim()}
33785
33852
 
33786
33853
  ${body}` : body;
@@ -33793,6 +33860,35 @@ var init_turn = __esm({
33793
33860
  }
33794
33861
  });
33795
33862
 
33863
+ // ../agent-core/src/prompt/turn-attachments.ts
33864
+ function buildAttachmentTurnText(spec, context) {
33865
+ const images = context.attachments.filter((attachment) => attachment.kind === "image");
33866
+ const files = context.attachments.filter((attachment) => attachment.kind === "file");
33867
+ const text3 = buildTurnText({
33868
+ spec,
33869
+ files,
33870
+ skills: context.skills,
33871
+ ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
33872
+ });
33873
+ return { text: text3, images };
33874
+ }
33875
+ function readInlineImages(images) {
33876
+ return Promise.all(
33877
+ images.map(async (image) => ({
33878
+ mimeType: image.mimeType,
33879
+ data: (await (0, import_promises16.readFile)(image.path)).toString("base64")
33880
+ }))
33881
+ );
33882
+ }
33883
+ var import_promises16;
33884
+ var init_turn_attachments = __esm({
33885
+ "../agent-core/src/prompt/turn-attachments.ts"() {
33886
+ "use strict";
33887
+ import_promises16 = require("node:fs/promises");
33888
+ init_turn();
33889
+ }
33890
+ });
33891
+
33796
33892
  // ../agent-core/src/prompt/index.ts
33797
33893
  var init_prompt = __esm({
33798
33894
  "../agent-core/src/prompt/index.ts"() {
@@ -33803,15 +33899,11 @@ var init_prompt = __esm({
33803
33899
  init_spec();
33804
33900
  init_system();
33805
33901
  init_turn();
33902
+ init_turn_attachments();
33806
33903
  }
33807
33904
  });
33808
33905
 
33809
33906
  // ../agent-core/src/providers/acp/run.ts
33810
- function envDigest(env) {
33811
- const hash2 = (0, import_node_crypto10.createHash)("sha256");
33812
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
33813
- return hash2.digest("hex");
33814
- }
33815
33907
  function planAcpSession(profile, run3, context) {
33816
33908
  const baseEnv = { ...context.cliEnv, ...context.providerEnv };
33817
33909
  const mcp = planExternalMcpDelivery(
@@ -33840,8 +33932,7 @@ function planAcpSession(profile, run3, context) {
33840
33932
  env,
33841
33933
  ...shape,
33842
33934
  mcp: { ...shape.mcp, ...authorization === void 0 ? {} : { authorization } },
33843
- ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
33844
- ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {},
33935
+ ...systemPromptFields(prompts),
33845
33936
  ...context.resumeSessionId ? { resumeSessionId: context.resumeSessionId } : {}
33846
33937
  };
33847
33938
  const key = JSON.stringify({
@@ -33855,32 +33946,18 @@ function planAcpSession(profile, run3, context) {
33855
33946
  return { spec, key, skippedMcpEnvKeys: mcp.skippedEnvKeys };
33856
33947
  }
33857
33948
  async function acpTurnInput(run3, context) {
33858
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
33859
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
33860
- const text3 = buildTurnText({
33861
- spec: run3,
33862
- files,
33863
- skills: context.skills,
33864
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
33865
- });
33866
- const encoded = await Promise.all(
33867
- images.map(async (image) => ({
33868
- mimeType: image.mimeType,
33869
- data: (await (0, import_promises16.readFile)(image.path)).toString("base64")
33870
- }))
33871
- );
33949
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
33950
+ const encoded = await readInlineImages(images);
33872
33951
  return {
33873
33952
  turnId: run3.runId,
33874
33953
  text: text3,
33875
33954
  ...encoded.length ? { images: encoded, imagePaths: images.map((image) => image.path) } : {}
33876
33955
  };
33877
33956
  }
33878
- var import_node_crypto10, import_promises16, ACP_MODES;
33957
+ var ACP_MODES;
33879
33958
  var init_run = __esm({
33880
33959
  "../agent-core/src/providers/acp/run.ts"() {
33881
33960
  "use strict";
33882
- import_node_crypto10 = require("node:crypto");
33883
- import_promises16 = require("node:fs/promises");
33884
33961
  init_agent2();
33885
33962
  init_mcp2();
33886
33963
  init_prompt();
@@ -34112,6 +34189,12 @@ function steerEcho(request3) {
34112
34189
  _meta: { ...senderMeta(request3.sender), [STEER_ID_META]: request3.steerId }
34113
34190
  };
34114
34191
  }
34192
+ function recordPlacedSteer(turn, steerId) {
34193
+ const request3 = turn.unplaced.get(steerId);
34194
+ if (request3 === void 0) return;
34195
+ turn.unplaced.delete(steerId);
34196
+ turn.record(steerEcho(request3));
34197
+ }
34115
34198
  function unansweredSteers(turn, result) {
34116
34199
  const unanswered = new Set(result.unansweredSteerIds);
34117
34200
  const ids = [...turn.steered].filter((id) => unanswered.has(id));
@@ -34296,6 +34379,7 @@ function createPersistentDriver(provider5, options) {
34296
34379
  session,
34297
34380
  waiting: /* @__PURE__ */ new Set(),
34298
34381
  steered: /* @__PURE__ */ new Set(),
34382
+ unplaced: /* @__PURE__ */ new Map(),
34299
34383
  nativeTracked: options.nativeIdentity !== void 0,
34300
34384
  record: record3,
34301
34385
  markWork: () => {
@@ -34337,6 +34421,9 @@ function createPersistentDriver(provider5, options) {
34337
34421
  heardFromProvider = true;
34338
34422
  recordWithMedia(event.update);
34339
34423
  return;
34424
+ case "steer_placed":
34425
+ recordPlacedSteer(turn, event.steerId);
34426
+ return;
34340
34427
  default:
34341
34428
  return;
34342
34429
  }
@@ -34458,15 +34545,14 @@ function createPersistentDriver(provider5, options) {
34458
34545
  if (turn.nativeTracked || turn.session.steer === void 0) return "unsupported";
34459
34546
  if (turn.steered.has(request3.steerId)) return "delivered";
34460
34547
  turn.steered.add(request3.steerId);
34548
+ turn.unplaced.set(request3.steerId, request3);
34461
34549
  turn.markWork();
34462
34550
  const status = await turn.session.steer({ steerId: request3.steerId, text: request3.text });
34463
34551
  if (status !== "delivered") {
34464
34552
  turn.steered.delete(request3.steerId);
34465
- return status;
34553
+ turn.unplaced.delete(request3.steerId);
34466
34554
  }
34467
- if (live.turn !== turn) return "delivered";
34468
- turn.record(steerEcho(request3));
34469
- return "delivered";
34555
+ return status;
34470
34556
  };
34471
34557
  const openFailed = (error62, spec, sink, signal, inputs) => {
34472
34558
  if (error62 instanceof SessionOpenRefusal && error62.reason === "unsupported_version" && (inputs.codex !== void 0 || spec.interaction !== void 0 || spec.operation !== void 0)) {
@@ -35342,7 +35428,9 @@ Alan's MCP tools are not separate tools in this engine. Call them inside an \`ex
35342
35428
  - Before the first call to a tool whose signature is not shown in the \`execute\` description, read it with \`tools.$codemode.search({ query: "<tool name>" })\` and pass exactly its fields.
35343
35429
  - Alan tools return JSON as text: \`JSON.parse\` a result before reading its fields or passing it to \`Object.keys\`.
35344
35430
  - Look up IDs in one script, then make the writes in the next, so a failed lookup never leaves half the writes done.
35345
- - Pass an \`idempotencyKey\` naming each change (for example \`create-task:<title>\`) on every write that accepts one. If a script fails, check what it already created before running it again, and run only the writes that are missing.`;
35431
+ - Pass an \`idempotencyKey\` naming each change (for example \`create-task:<title>\`) on every write that accepts one. If a script fails, check what it already created before running it again, and run only the writes that are missing.
35432
+ - Never paste file text into a template literal or a raw string in a script: backticks, \`\${\`, backslashes and regular expressions break the parse, and the call never runs. For \`create_skill\`, \`update_skill\` and any write that takes file contents, first save each file on disk, then pass it as \`{ path, content, encoding: "base64" }\` with the output of \`base64 < file | tr -d '\\n'\` from the shell, copied exactly. Only \`SKILL.md\` must stay \`utf8\`: write it as a double-quoted JSON string with \`\\n\`, \`\\"\` and \`\\\\\` escapes, never a template literal.
35433
+ - Report an ID, URL or path only if a tool returned it in this run. If a call failed, say it failed.`;
35346
35434
  }
35347
35435
  });
35348
35436
 
@@ -35905,7 +35993,7 @@ var init_subagents = __esm({
35905
35993
  }
35906
35994
  async #abort(childSessionId, host) {
35907
35995
  const timer = new AbortController();
35908
- const aborted2 = host.client.abort(childSessionId).then(
35996
+ const aborted3 = host.client.abort(childSessionId).then(
35909
35997
  () => ({ ok: true }),
35910
35998
  (error62) => abortRefusal(error62)
35911
35999
  );
@@ -35917,7 +36005,7 @@ var init_subagents = __esm({
35917
36005
  () => failure4("timeout")
35918
36006
  );
35919
36007
  try {
35920
- return await Promise.race([aborted2, timedOut]);
36008
+ return await Promise.race([aborted3, timedOut]);
35921
36009
  } finally {
35922
36010
  timer.abort();
35923
36011
  }
@@ -36910,6 +36998,7 @@ var init_session3 = __esm({
36910
36998
  this.#options.log.warn("opencode.steer_failed", { turnId: active.id, error: String(error62) });
36911
36999
  return "not_running";
36912
37000
  }
37001
+ this.#emit({ type: "steer_placed", turnId: active.id, steerId: input2.steerId });
36913
37002
  return "delivered";
36914
37003
  }
36915
37004
  #promptBody(input2) {
@@ -37550,11 +37639,6 @@ var init_driver3 = __esm({
37550
37639
  });
37551
37640
 
37552
37641
  // ../agent-core/src/providers/opencode/run.ts
37553
- function envDigest2(env) {
37554
- const hash2 = (0, import_node_crypto14.createHash)("sha256");
37555
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
37556
- return hash2.digest("hex");
37557
- }
37558
37642
  function openCodeModel(model2) {
37559
37643
  const trimmed4 = model2?.trim() ?? "";
37560
37644
  const slash = trimmed4.indexOf("/");
@@ -37613,7 +37697,7 @@ function planOpenCodeSession(run3, context) {
37613
37697
  cwd: context.cwd,
37614
37698
  config: config2,
37615
37699
  mcpCredential: credentialDigest(authorization),
37616
- env: envDigest2(env)
37700
+ env: envDigest(env)
37617
37701
  });
37618
37702
  return { spec, key, skippedMcpEnvKeys: mcp.skippedEnvKeys };
37619
37703
  }
@@ -37636,11 +37720,10 @@ ${IMAGE_TEXT_VERIFICATION}` : text3,
37636
37720
  ...context.attachments.length ? { readableFiles: context.attachments.map((attachment) => attachment.path) } : {}
37637
37721
  };
37638
37722
  }
37639
- var import_node_crypto14, TITLE_LENGTH, MAX_VARIANT_LENGTH, IMAGE_TEXT_VERIFICATION;
37723
+ var TITLE_LENGTH, MAX_VARIANT_LENGTH, IMAGE_TEXT_VERIFICATION;
37640
37724
  var init_run2 = __esm({
37641
37725
  "../agent-core/src/providers/opencode/run.ts"() {
37642
37726
  "use strict";
37643
- import_node_crypto14 = require("node:crypto");
37644
37727
  init_agent2();
37645
37728
  init_mcp2();
37646
37729
  init_prompt();
@@ -37918,7 +38001,7 @@ var init_run_git = __esm({
37918
38001
 
37919
38002
  // src/capabilities/git/checkout-freshness.ts
37920
38003
  function freshnessFile(dir, path19) {
37921
- return (0, import_node_path21.join)(dir, `${(0, import_node_crypto15.createHash)("sha256").update(path19).digest("hex").slice(0, 32)}.json`);
38004
+ return (0, import_node_path21.join)(dir, `${(0, import_node_crypto14.createHash)("sha256").update(path19).digest("hex").slice(0, 32)}.json`);
37922
38005
  }
37923
38006
  function parseStatus(stdout) {
37924
38007
  const lines2 = stdout.split("\n").filter((line) => line.length > 0);
@@ -37989,11 +38072,11 @@ async function readCheckoutFreshness(dir, path19) {
37989
38072
  if ((0, import_node_path21.dirname)(current) === current) return null;
37990
38073
  }
37991
38074
  }
37992
- var import_node_crypto15, import_promises19, import_node_path21, REMOTE, snapshotSchema, freshnessSchema;
38075
+ var import_node_crypto14, import_promises19, import_node_path21, REMOTE, snapshotSchema, freshnessSchema;
37993
38076
  var init_checkout_freshness = __esm({
37994
38077
  "src/capabilities/git/checkout-freshness.ts"() {
37995
38078
  "use strict";
37996
- import_node_crypto15 = require("node:crypto");
38079
+ import_node_crypto14 = require("node:crypto");
37997
38080
  import_promises19 = require("node:fs/promises");
37998
38081
  import_node_path21 = require("node:path");
37999
38082
  init_zod();
@@ -38107,12 +38190,12 @@ function shellQuote(value2) {
38107
38190
  return `'${value2.replace(/'/g, "'\\''")}'`;
38108
38191
  }
38109
38192
  async function replaceFile(path19, content2, mode) {
38110
- const temp = `${path19}.${(0, import_node_crypto16.randomUUID)()}.tmp`;
38193
+ const temp = `${path19}.${(0, import_node_crypto15.randomUUID)()}.tmp`;
38111
38194
  await (0, import_promises21.writeFile)(temp, content2, { mode });
38112
38195
  await (0, import_promises21.rename)(temp, path19);
38113
38196
  }
38114
38197
  async function replaceSymlink(path19, target) {
38115
- const temp = `${path19}.${(0, import_node_crypto16.randomUUID)()}.tmp`;
38198
+ const temp = `${path19}.${(0, import_node_crypto15.randomUUID)()}.tmp`;
38116
38199
  await (0, import_promises21.symlink)(target, temp);
38117
38200
  await (0, import_promises21.rename)(temp, path19);
38118
38201
  }
@@ -38151,11 +38234,11 @@ exec ${shellQuote(realGit)} -c core.hooksPath=${shellQuote(hooksDir)} "$@"
38151
38234
  }
38152
38235
  };
38153
38236
  }
38154
- var import_node_crypto16, import_promises21, import_node_path23;
38237
+ var import_node_crypto15, import_promises21, import_node_path23;
38155
38238
  var init_commit_attribution2 = __esm({
38156
38239
  "src/capabilities/git/commit-attribution.ts"() {
38157
38240
  "use strict";
38158
- import_node_crypto16 = require("node:crypto");
38241
+ import_node_crypto15 = require("node:crypto");
38159
38242
  import_promises21 = require("node:fs/promises");
38160
38243
  import_node_path23 = require("node:path");
38161
38244
  init_runtime_v2();
@@ -38418,15 +38501,19 @@ function workspaceRoot(cwd) {
38418
38501
  if ((0, import_node_path26.dirname)(current) === current) return (0, import_node_path26.resolve)(cwd);
38419
38502
  }
38420
38503
  }
38504
+ function isFile(path19) {
38505
+ try {
38506
+ return (0, import_node_fs16.existsSync)(path19) && (0, import_node_fs16.statSync)(path19).isFile();
38507
+ } catch {
38508
+ return false;
38509
+ }
38510
+ }
38421
38511
  function instructionPaths(cwd) {
38422
38512
  const root = workspaceRoot(cwd);
38423
38513
  const paths = [];
38424
38514
  for (let current = (0, import_node_path26.resolve)(cwd); ; current = (0, import_node_path26.dirname)(current)) {
38425
38515
  const path19 = (0, import_node_path26.join)(current, INSTRUCTIONS_FILE);
38426
- try {
38427
- if ((0, import_node_fs16.existsSync)(path19) && (0, import_node_fs16.statSync)(path19).isFile()) paths.unshift(path19);
38428
- } catch {
38429
- }
38516
+ if (isFile(path19)) paths.unshift(path19);
38430
38517
  if (current === root || (0, import_node_path26.dirname)(current) === current) return paths;
38431
38518
  }
38432
38519
  }
@@ -39526,11 +39613,6 @@ var init_driver4 = __esm({
39526
39613
  });
39527
39614
 
39528
39615
  // ../agent-core/src/providers/antigravity/run.ts
39529
- function envDigest3(env) {
39530
- const hash2 = (0, import_node_crypto17.createHash)("sha256");
39531
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
39532
- return hash2.digest("hex");
39533
- }
39534
39616
  function planAntigravitySession(run3, context) {
39535
39617
  const env = { ...context.cliEnv, ...context.providerEnv };
39536
39618
  const prompts = buildSystemPrompts({
@@ -39548,8 +39630,7 @@ function planAntigravitySession(run3, context) {
39548
39630
  cwd: context.cwd,
39549
39631
  env,
39550
39632
  ...shape,
39551
- ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
39552
- ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {},
39633
+ ...systemPromptFields(prompts),
39553
39634
  ...context.resumeSessionId ? { resumeSessionId: context.resumeSessionId } : {}
39554
39635
  };
39555
39636
  const skippedMcpServers = [
@@ -39562,27 +39643,19 @@ function planAntigravitySession(run3, context) {
39562
39643
  command: context.command,
39563
39644
  cwd: context.cwd,
39564
39645
  shape,
39565
- env: envDigest3(env)
39646
+ env: envDigest(env)
39566
39647
  });
39567
39648
  return { spec, key, skippedMcpEnvKeys: [], skippedMcpServers };
39568
39649
  }
39569
39650
  function antigravityTurnInput(run3, context) {
39570
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
39571
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
39572
- const text3 = buildTurnText({
39573
- spec: run3,
39574
- files,
39575
- skills: context.skills,
39576
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
39577
- });
39651
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
39578
39652
  return { turnId: run3.runId, text: appendImagePathReferences(text3, images) };
39579
39653
  }
39580
- var import_node_crypto17;
39581
39654
  var init_run3 = __esm({
39582
39655
  "../agent-core/src/providers/antigravity/run.ts"() {
39583
39656
  "use strict";
39584
- import_node_crypto17 = require("node:crypto");
39585
39657
  init_agent2();
39658
+ init_mcp2();
39586
39659
  init_prompt();
39587
39660
  }
39588
39661
  });
@@ -40233,7 +40306,7 @@ var init_grammar_system = __esm({
40233
40306
  "hook_response",
40234
40307
  "task_summary",
40235
40308
  "post_turn_summary",
40236
- // Never used to settle a launcher: the empty snapshot arrives BEFORE `task_updated`.
40309
+ // quirk: the empty snapshot arrives BEFORE `task_updated`, so it cannot settle a launcher.
40237
40310
  "background_tasks_changed",
40238
40311
  // Partial-message transport pings; `state_update` and `init` already cover them.
40239
40312
  "status",
@@ -41749,11 +41822,11 @@ function createClaudeDriver(options = {}) {
41749
41822
  }
41750
41823
  };
41751
41824
  }
41752
- var import_node_crypto18, STDERR_TAIL_LINES3, MAX_EARLY_LINES, UNSUPPORTED_STOP, OUTPUT_CLOSED_REASON, ClaudeSession, DEFAULTS4;
41825
+ var import_node_crypto16, STDERR_TAIL_LINES3, MAX_EARLY_LINES, UNSUPPORTED_STOP, OUTPUT_CLOSED_REASON, ClaudeSession, DEFAULTS4;
41753
41826
  var init_driver5 = __esm({
41754
41827
  "../agent-core/src/providers/claude/driver.ts"() {
41755
41828
  "use strict";
41756
- import_node_crypto18 = require("node:crypto");
41829
+ import_node_crypto16 = require("node:crypto");
41757
41830
  init_acp2();
41758
41831
  init_classify2();
41759
41832
  init_kernel2();
@@ -41857,7 +41930,7 @@ var init_driver5 = __esm({
41857
41930
  taskRecords: this.#taskRecords,
41858
41931
  shownNotices: this.#shownNotices
41859
41932
  });
41860
- const messageId = this.#replaysUserMessages ? (0, import_node_crypto18.randomUUID)() : void 0;
41933
+ const messageId = this.#replaysUserMessages ? (0, import_node_crypto16.randomUUID)() : void 0;
41861
41934
  const active = this.#startTurn(input2.turnId, turn, messageId);
41862
41935
  this.#host.writer.write(claudeUserMessage(input2, messageId)).catch((error62) => {
41863
41936
  this.#options.log.warn("claude.stdin_write_failed", { turnId: input2.turnId, error: error62 });
@@ -42230,14 +42303,13 @@ function disallowedToolsFor(agentId) {
42230
42303
  ...canAgentRunCommands(agentId) ? [] : NO_COMMAND_DISALLOWED_TOOLS
42231
42304
  ];
42232
42305
  }
42233
- function envDigest4(env) {
42234
- const hash2 = (0, import_node_crypto19.createHash)("sha256");
42235
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
42236
- return hash2.digest("hex");
42237
- }
42238
- function withMcpTimeout(env) {
42306
+ function withMcpTimeout(env, servers) {
42239
42307
  if (env.MCP_TIMEOUT?.trim()) return { ...env };
42240
- return { ...env, MCP_TIMEOUT: String(DEFAULT_MCP_TIMEOUT_MS) };
42308
+ const hasStdio = Object.values(servers).some((server) => server.type === "stdio");
42309
+ return {
42310
+ ...env,
42311
+ MCP_TIMEOUT: String(hasStdio ? STDIO_MCP_TIMEOUT_MS : DEFAULT_MCP_TIMEOUT_MS)
42312
+ };
42241
42313
  }
42242
42314
  function planClaudeSession(run3, context) {
42243
42315
  const baseEnv = { ...context.cliEnv, ...context.providerEnv };
@@ -42245,7 +42317,7 @@ function planClaudeSession(run3, context) {
42245
42317
  { ...run3, workflowTools: run3.promptContext?.workflowTools },
42246
42318
  baseEnv
42247
42319
  );
42248
- const env = withMcpTimeout({ ...baseEnv, ...mcp.env });
42320
+ const env = withMcpTimeout({ ...baseEnv, ...mcp.env }, mcp.servers);
42249
42321
  const prompts = buildSystemPrompts({
42250
42322
  spec: run3,
42251
42323
  workspacePath: run3.projectPath,
@@ -42281,7 +42353,7 @@ function planClaudeSession(run3, context) {
42281
42353
  cwd: context.cwd,
42282
42354
  shape,
42283
42355
  mcpCredential: credentialDigest(authorization),
42284
- env: envDigest4(env)
42356
+ env: envDigest(env)
42285
42357
  });
42286
42358
  return {
42287
42359
  spec: { command: context.command, cwd: context.cwd, env, args },
@@ -42290,28 +42362,14 @@ function planClaudeSession(run3, context) {
42290
42362
  };
42291
42363
  }
42292
42364
  async function claudeTurnInput(run3, context) {
42293
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
42294
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
42295
- const text3 = buildTurnText({
42296
- spec: run3,
42297
- files,
42298
- skills: context.skills,
42299
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
42300
- });
42301
- const encoded = await Promise.all(
42302
- images.map(async (image) => ({
42303
- mimeType: image.mimeType,
42304
- data: (await (0, import_promises25.readFile)(image.path)).toString("base64")
42305
- }))
42306
- );
42365
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
42366
+ const encoded = await readInlineImages(images);
42307
42367
  return { turnId: run3.runId, text: text3, ...encoded.length ? { images: encoded } : {} };
42308
42368
  }
42309
- var import_node_crypto19, import_promises25, READ_ONLY_DISALLOWED_TOOLS, NO_COMMAND_DISALLOWED_TOOLS, DEFAULT_MCP_TIMEOUT_MS, CLOUD_SKILL_LISTING_MAX_DESCRIPTION_CHARS;
42369
+ var READ_ONLY_DISALLOWED_TOOLS, NO_COMMAND_DISALLOWED_TOOLS, DEFAULT_MCP_TIMEOUT_MS, STDIO_MCP_TIMEOUT_MS, CLOUD_SKILL_LISTING_MAX_DESCRIPTION_CHARS;
42310
42370
  var init_run4 = __esm({
42311
42371
  "../agent-core/src/providers/claude/run.ts"() {
42312
42372
  "use strict";
42313
- import_node_crypto19 = require("node:crypto");
42314
- import_promises25 = require("node:fs/promises");
42315
42373
  init_agent2();
42316
42374
  init_mcp2();
42317
42375
  init_prompt();
@@ -42334,6 +42392,7 @@ var init_run4 = __esm({
42334
42392
  "ExitWorktree"
42335
42393
  ];
42336
42394
  DEFAULT_MCP_TIMEOUT_MS = 5e3;
42395
+ STDIO_MCP_TIMEOUT_MS = 3e4;
42337
42396
  CLOUD_SKILL_LISTING_MAX_DESCRIPTION_CHARS = 250;
42338
42397
  }
42339
42398
  });
@@ -42700,7 +42759,7 @@ var init_background_commands = __esm({
42700
42759
  launchersOf(turnId) {
42701
42760
  return [...this.#tasks.values()].filter((task) => task.ownerTurnId === turnId && task.meta.backgrounded && isRunning3(task)).map((task) => task.toolCallId);
42702
42761
  }
42703
- async stop(processId, threadId, rpc, deliver) {
42762
+ async stop(processId, threadId, rpc, deliver2) {
42704
42763
  const task = this.#tasks.get(processId);
42705
42764
  if (!task) return { ok: false, reason: "not_found" };
42706
42765
  if (!isRunning3(task)) return { ok: false, reason: "already_finished" };
@@ -42708,13 +42767,13 @@ var init_background_commands = __esm({
42708
42767
  const wasRequested = task.userStopRequested;
42709
42768
  task.userStopRequested = true;
42710
42769
  task.meta = { ...task.meta, status: "stopping" };
42711
- deliver([{ turnId: task.ownerTurnId, update: metaUpdate(task) }]);
42770
+ deliver2([{ turnId: task.ownerTurnId, update: metaUpdate(task) }]);
42712
42771
  const result = await this.#terminate(rpc, threadId, processId);
42713
42772
  if (!result.ok && result.reason !== "timeout") {
42714
42773
  task.userStopRequested = wasRequested;
42715
42774
  if (this.#tasks.get(processId) === task && task.meta.status === "stopping") {
42716
42775
  task.meta = { ...task.meta, status: "running" };
42717
- deliver([{ turnId: task.ownerTurnId, update: metaUpdate(task) }]);
42776
+ deliver2([{ turnId: task.ownerTurnId, update: metaUpdate(task) }]);
42718
42777
  }
42719
42778
  }
42720
42779
  return result;
@@ -42942,7 +43001,7 @@ function codexGeneratedImage(payload, ts) {
42942
43001
  const declared = asString(payload.mimeType) || asString(payload.mime_type);
42943
43002
  const mimeType = declared.startsWith("image/") ? declared : inferImageMimeType(buffer);
42944
43003
  if (!mimeType) return null;
42945
- const sourceHash = (0, import_node_crypto20.createHash)("sha256").update(buffer).digest("hex");
43004
+ const sourceHash = (0, import_node_crypto17.createHash)("sha256").update(buffer).digest("hex");
42946
43005
  const toolId = asString(payload.call_id);
42947
43006
  const id = asString(payload.id) || toolId || sourceHash;
42948
43007
  const sourcePath = asString(payload.sourcePath);
@@ -42962,11 +43021,11 @@ function codexGeneratedImage(payload, ts) {
42962
43021
  ts
42963
43022
  };
42964
43023
  }
42965
- var import_node_crypto20, MAX_INLINE_GENERATED_IMAGE_BYTES, PNG_SIGNATURE2, JPEG_NON_FRAME_MARKERS;
43024
+ var import_node_crypto17, MAX_INLINE_GENERATED_IMAGE_BYTES, PNG_SIGNATURE2, JPEG_NON_FRAME_MARKERS;
42966
43025
  var init_generated_image = __esm({
42967
43026
  "../agent-core/src/providers/codex/generated-image.ts"() {
42968
43027
  "use strict";
42969
- import_node_crypto20 = require("node:crypto");
43028
+ import_node_crypto17 = require("node:crypto");
42970
43029
  init_kernel2();
42971
43030
  MAX_INLINE_GENERATED_IMAGE_BYTES = 20 * 1024 * 1024;
42972
43031
  PNG_SIGNATURE2 = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
@@ -43242,18 +43301,18 @@ function creditsPatch(value2) {
43242
43301
  ...balance ? { balance } : {}
43243
43302
  };
43244
43303
  }
43245
- var import_node_crypto21, CodexRateLimits;
43304
+ var import_node_crypto18, CodexRateLimits;
43246
43305
  var init_rate_limits = __esm({
43247
43306
  "../agent-core/src/providers/codex/rate-limits.ts"() {
43248
43307
  "use strict";
43249
- import_node_crypto21 = require("node:crypto");
43308
+ import_node_crypto18 = require("node:crypto");
43250
43309
  init_runtime_v2();
43251
43310
  init_kernel2();
43252
43311
  CodexRateLimits = class {
43253
43312
  #clock;
43254
43313
  #sourceId;
43255
43314
  #sequence = 0;
43256
- constructor(clock, sourceId = (0, import_node_crypto21.randomUUID)()) {
43315
+ constructor(clock, sourceId = (0, import_node_crypto18.randomUUID)()) {
43257
43316
  this.#clock = clock;
43258
43317
  this.#sourceId = sourceId;
43259
43318
  }
@@ -45179,11 +45238,6 @@ var init_exec_driver = __esm({
45179
45238
  });
45180
45239
 
45181
45240
  // ../agent-core/src/providers/codex/exec-run.ts
45182
- function envDigest5(env) {
45183
- const hash2 = (0, import_node_crypto22.createHash)("sha256");
45184
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
45185
- return hash2.digest("hex");
45186
- }
45187
45241
  function planCodexExecSession(run3, context) {
45188
45242
  const baseEnv = { ...context.cliEnv, ...context.providerEnv };
45189
45243
  const mcp = planExternalMcpDelivery(
@@ -45203,15 +45257,14 @@ function planCodexExecSession(run3, context) {
45203
45257
  cwd: context.cwd,
45204
45258
  env,
45205
45259
  ...shape,
45206
- ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
45207
- ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {},
45260
+ ...systemPromptFields(prompts),
45208
45261
  ...context.resumeSessionId ? { resumeSessionId: context.resumeSessionId } : {}
45209
45262
  };
45210
45263
  const key = JSON.stringify({
45211
45264
  command: context.command,
45212
45265
  cwd: context.cwd,
45213
45266
  shape,
45214
- env: envDigest5(env)
45267
+ env: envDigest(env)
45215
45268
  });
45216
45269
  return {
45217
45270
  spec,
@@ -45220,11 +45273,9 @@ function planCodexExecSession(run3, context) {
45220
45273
  skippedMcpServers: context.managedMcp ? ["alan: codex exec could take the credential only through argv or env"] : []
45221
45274
  };
45222
45275
  }
45223
- var import_node_crypto22;
45224
45276
  var init_exec_run = __esm({
45225
45277
  "../agent-core/src/providers/codex/exec-run.ts"() {
45226
45278
  "use strict";
45227
- import_node_crypto22 = require("node:crypto");
45228
45279
  init_agent2();
45229
45280
  init_mcp2();
45230
45281
  init_prompt();
@@ -45268,11 +45319,6 @@ var init_rollout_file = __esm({
45268
45319
  });
45269
45320
 
45270
45321
  // ../agent-core/src/providers/codex/run.ts
45271
- function envDigest6(env) {
45272
- const hash2 = (0, import_node_crypto23.createHash)("sha256");
45273
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
45274
- return hash2.digest("hex");
45275
- }
45276
45322
  function planCodexSession(run3, context) {
45277
45323
  const baseEnv = { ...context.cliEnv, ...context.providerEnv };
45278
45324
  const mcp = planExternalMcpDelivery(
@@ -45319,30 +45365,21 @@ function planCodexSession(run3, context) {
45319
45365
  thread,
45320
45366
  effort,
45321
45367
  mcpCredential: credentialDigest(authorization),
45322
- env: envDigest6(env)
45368
+ env: envDigest(env)
45323
45369
  });
45324
45370
  return { spec, key, skippedMcpEnvKeys: mcp.skippedEnvKeys };
45325
45371
  }
45326
45372
  function codexTurnInput(run3, context) {
45327
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
45328
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
45329
- const text3 = buildTurnText({
45330
- spec: run3,
45331
- files,
45332
- skills: context.skills,
45333
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
45334
- });
45373
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
45335
45374
  return {
45336
45375
  turnId: run3.runId,
45337
45376
  text: text3,
45338
45377
  ...images.length ? { imagePaths: images.map((image) => image.path) } : {}
45339
45378
  };
45340
45379
  }
45341
- var import_node_crypto23;
45342
45380
  var init_run5 = __esm({
45343
45381
  "../agent-core/src/providers/codex/run.ts"() {
45344
45382
  "use strict";
45345
- import_node_crypto23 = require("node:crypto");
45346
45383
  init_effort();
45347
45384
  init_mcp2();
45348
45385
  init_prompt();
@@ -46207,11 +46244,6 @@ var init_driver7 = __esm({
46207
46244
  });
46208
46245
 
46209
46246
  // ../agent-core/src/providers/droid/run.ts
46210
- function envDigest7(env) {
46211
- const hash2 = (0, import_node_crypto24.createHash)("sha256");
46212
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
46213
- return hash2.digest("hex");
46214
- }
46215
46247
  function planDroidSession(run3, context) {
46216
46248
  const baseEnv = { ...context.cliEnv, ...context.providerEnv };
46217
46249
  const mcp = planExternalMcpDelivery(
@@ -46238,8 +46270,7 @@ function planDroidSession(run3, context) {
46238
46270
  env,
46239
46271
  ...shape,
46240
46272
  mcp: { ...shape.mcp, ...authorization === void 0 ? {} : { authorization } },
46241
- ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
46242
- ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {},
46273
+ ...systemPromptFields(prompts),
46243
46274
  ...context.resumeSessionId ? { resumeSessionId: context.resumeSessionId } : {}
46244
46275
  };
46245
46276
  const key = JSON.stringify({
@@ -46247,33 +46278,18 @@ function planDroidSession(run3, context) {
46247
46278
  cwd: context.cwd,
46248
46279
  shape,
46249
46280
  mcpCredential: credentialDigest(authorization),
46250
- env: envDigest7(env)
46281
+ env: envDigest(env)
46251
46282
  });
46252
46283
  return { spec, key, skippedMcpEnvKeys: mcp.skippedEnvKeys };
46253
46284
  }
46254
46285
  async function droidTurnInput(run3, context) {
46255
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
46256
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
46257
- const text3 = buildTurnText({
46258
- spec: run3,
46259
- files,
46260
- skills: context.skills,
46261
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
46262
- });
46263
- const encoded = await Promise.all(
46264
- images.map(async (image) => ({
46265
- mimeType: image.mimeType,
46266
- data: (await (0, import_promises26.readFile)(image.path)).toString("base64")
46267
- }))
46268
- );
46286
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
46287
+ const encoded = await readInlineImages(images);
46269
46288
  return { turnId: run3.runId, text: text3, ...encoded.length ? { images: encoded } : {} };
46270
46289
  }
46271
- var import_node_crypto24, import_promises26;
46272
46290
  var init_run6 = __esm({
46273
46291
  "../agent-core/src/providers/droid/run.ts"() {
46274
46292
  "use strict";
46275
- import_node_crypto24 = require("node:crypto");
46276
- import_promises26 = require("node:fs/promises");
46277
46293
  init_agent2();
46278
46294
  init_mcp2();
46279
46295
  init_prompt();
@@ -46352,18 +46368,18 @@ var init_alan_code2 = __esm({
46352
46368
  // src/capabilities/providers/managed.ts
46353
46369
  async function readManagedProviderVersion(file2, backendKind) {
46354
46370
  try {
46355
- const selected = selectedSchema.parse(JSON.parse(await (0, import_promises27.readFile)(file2, "utf8")));
46371
+ const selected = selectedSchema.parse(JSON.parse(await (0, import_promises25.readFile)(file2, "utf8")));
46356
46372
  const version2 = selected[backendKind];
46357
46373
  return version2 !== void 0 && VERSION.test(version2) ? version2 : null;
46358
46374
  } catch {
46359
46375
  return null;
46360
46376
  }
46361
46377
  }
46362
- var import_promises27, VERSION, selectedSchema;
46378
+ var import_promises25, VERSION, selectedSchema;
46363
46379
  var init_managed2 = __esm({
46364
46380
  "src/capabilities/providers/managed.ts"() {
46365
46381
  "use strict";
46366
- import_promises27 = require("node:fs/promises");
46382
+ import_promises25 = require("node:fs/promises");
46367
46383
  init_process();
46368
46384
  init_zod();
46369
46385
  VERSION = /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?$/;
@@ -53747,11 +53763,11 @@ async function inspectSkillPackage(packageRoot, options = {}) {
53747
53763
  };
53748
53764
  }
53749
53765
  async function requirePackageRoot(packageRoot) {
53750
- const root = await (0, import_promises28.realpath)((0, import_node_path30.resolve)(packageRoot)).catch(() => null);
53766
+ const root = await (0, import_promises26.realpath)((0, import_node_path30.resolve)(packageRoot)).catch(() => null);
53751
53767
  if (!root) {
53752
53768
  throw new SkillPackageError("INVALID_PACKAGE_ROOT", "Skill package directory does not exist");
53753
53769
  }
53754
- const rootStat = await (0, import_promises28.lstat)(root);
53770
+ const rootStat = await (0, import_promises26.lstat)(root);
53755
53771
  if (!rootStat.isDirectory()) {
53756
53772
  throw new SkillPackageError("INVALID_PACKAGE_ROOT", "Skill package root must be a directory");
53757
53773
  }
@@ -53777,12 +53793,12 @@ async function walkPackage(root, ignoredPaths) {
53777
53793
  }
53778
53794
  return files;
53779
53795
  async function walkDirectory(directory) {
53780
- const entries2 = await (0, import_promises28.readdir)(directory, { withFileTypes: true });
53796
+ const entries2 = await (0, import_promises26.readdir)(directory, { withFileTypes: true });
53781
53797
  for (const entry2 of entries2) {
53782
53798
  const absolutePath = (0, import_node_path30.resolve)(directory, entry2.name);
53783
53799
  const normalizedPath = normalizeRelativePath(root, absolutePath);
53784
53800
  if (isIgnored(normalizedPath, entry2.name, entry2.isDirectory(), ignored3)) continue;
53785
- const entryStat = await (0, import_promises28.lstat)(absolutePath);
53801
+ const entryStat = await (0, import_promises26.lstat)(absolutePath);
53786
53802
  if (entryStat.isSymbolicLink()) {
53787
53803
  throw new SkillPackageError(
53788
53804
  "SYMLINK_BLOCKED",
@@ -53908,7 +53924,7 @@ function isSecretPath(path19) {
53908
53924
  return name.endsWith(".private-key.pem") || name.endsWith(".private-key.key");
53909
53925
  }
53910
53926
  async function readPackageFile(file2) {
53911
- const bytes2 = await (0, import_promises28.readFile)(file2.absolutePath);
53927
+ const bytes2 = await (0, import_promises26.readFile)(file2.absolutePath);
53912
53928
  return {
53913
53929
  bytes: bytes2,
53914
53930
  manifest: {
@@ -54064,7 +54080,7 @@ function comparePackageFiles(left, right) {
54064
54080
  );
54065
54081
  }
54066
54082
  function hashPackageTree(files) {
54067
- const hash2 = (0, import_node_crypto25.createHash)("sha256");
54083
+ const hash2 = (0, import_node_crypto19.createHash)("sha256");
54068
54084
  hash2.update(TREE_HASH_PREFIX);
54069
54085
  for (const file2 of files) {
54070
54086
  const path19 = import_node_buffer.Buffer.from(file2.path, "utf8");
@@ -54077,7 +54093,7 @@ function hashPackageTree(files) {
54077
54093
  return `sha256:${hash2.digest("hex")}`;
54078
54094
  }
54079
54095
  function sha256(bytes2) {
54080
- return `sha256:${(0, import_node_crypto25.createHash)("sha256").update(bytes2).digest("hex")}`;
54096
+ return `sha256:${(0, import_node_crypto19.createHash)("sha256").update(bytes2).digest("hex")}`;
54081
54097
  }
54082
54098
  function uint322(value2) {
54083
54099
  const buffer = import_node_buffer.Buffer.allocUnsafe(4);
@@ -54089,13 +54105,13 @@ function uint642(value2) {
54089
54105
  buffer.writeBigUInt64BE(BigInt(value2));
54090
54106
  return buffer;
54091
54107
  }
54092
- var import_node_buffer, import_node_crypto25, import_promises28, import_node_path30, import_yaml, TREE_HASH_PREFIX, ALWAYS_IGNORED_DIRECTORIES, ALWAYS_IGNORED_FILES, MARKDOWN_EXTENSIONS, IMAGE_EXTENSIONS2, CODE_EXTENSIONS, TEXT_EXTENSIONS, SECRET_BASENAMES, MARKDOWN_LINK_TARGET;
54108
+ var import_node_buffer, import_node_crypto19, import_promises26, import_node_path30, import_yaml, TREE_HASH_PREFIX, ALWAYS_IGNORED_DIRECTORIES, ALWAYS_IGNORED_FILES, MARKDOWN_EXTENSIONS, IMAGE_EXTENSIONS2, CODE_EXTENSIONS, TEXT_EXTENSIONS, SECRET_BASENAMES, MARKDOWN_LINK_TARGET;
54093
54109
  var init_skill_package = __esm({
54094
54110
  "../shared/src/node/skill-package.ts"() {
54095
54111
  "use strict";
54096
54112
  import_node_buffer = require("node:buffer");
54097
- import_node_crypto25 = require("node:crypto");
54098
- import_promises28 = require("node:fs/promises");
54113
+ import_node_crypto19 = require("node:crypto");
54114
+ import_promises26 = require("node:fs/promises");
54099
54115
  import_node_path30 = require("node:path");
54100
54116
  import_yaml = __toESM(require_dist(), 1);
54101
54117
  init_contracts();
@@ -54165,7 +54181,7 @@ var init_skill_package = __esm({
54165
54181
 
54166
54182
  // ../shared/src/node/alan-skill-identity.ts
54167
54183
  function uuidV5(name, namespace) {
54168
- const bytes2 = (0, import_node_crypto26.createHash)("sha1").update(Buffer.from(namespace.replaceAll("-", ""), "hex")).update(name, "utf8").digest().subarray(0, 16);
54184
+ const bytes2 = (0, import_node_crypto20.createHash)("sha1").update(Buffer.from(namespace.replaceAll("-", ""), "hex")).update(name, "utf8").digest().subarray(0, 16);
54169
54185
  bytes2[6] = bytes2[6] & 15 | 80;
54170
54186
  bytes2[8] = bytes2[8] & 63 | 128;
54171
54187
  const hex3 = bytes2.toString("hex");
@@ -54177,11 +54193,11 @@ function alanSkillId(slug) {
54177
54193
  function alanSkillVersionId(slug, contentHash) {
54178
54194
  return uuidV5(`alan:${slug}:${contentHash}`, ALAN_SKILL_NAMESPACE);
54179
54195
  }
54180
- var import_node_crypto26, ALAN_SKILL_NAMESPACE;
54196
+ var import_node_crypto20, ALAN_SKILL_NAMESPACE;
54181
54197
  var init_alan_skill_identity = __esm({
54182
54198
  "../shared/src/node/alan-skill-identity.ts"() {
54183
54199
  "use strict";
54184
- import_node_crypto26 = require("node:crypto");
54200
+ import_node_crypto20 = require("node:crypto");
54185
54201
  ALAN_SKILL_NAMESPACE = "ec71d99b-d207-4ca2-a9eb-3a7bed4a73fd";
54186
54202
  }
54187
54203
  });
@@ -54215,7 +54231,7 @@ async function readLocalSkills(layout) {
54215
54231
  async function isLocalSkillCurrent(entry2, contentHash, ignoredPaths) {
54216
54232
  if (entry2.contentHash !== contentHash) return false;
54217
54233
  try {
54218
- if (await (0, import_promises29.realpath)(entry2.path) !== entry2.path) return false;
54234
+ if (await (0, import_promises27.realpath)(entry2.path) !== entry2.path) return false;
54219
54235
  const inspected = await inspectSkillPackage(entry2.path, { expectedName: null, ignoredPaths });
54220
54236
  return inspected.contentHash === contentHash;
54221
54237
  } catch {
@@ -54230,7 +54246,7 @@ async function resolveLocalSkill(local, invocation) {
54230
54246
  }
54231
54247
  async function hasSkillFile(directory) {
54232
54248
  try {
54233
- return (await (0, import_promises29.stat)((0, import_node_path31.join)(directory, "SKILL.md"))).isFile();
54249
+ return (await (0, import_promises27.stat)((0, import_node_path31.join)(directory, "SKILL.md"))).isFile();
54234
54250
  } catch {
54235
54251
  return false;
54236
54252
  }
@@ -54285,7 +54301,7 @@ async function resolveSkillInvocations(layout, invocations, baked = "any") {
54285
54301
  return missing2.length === 0 ? { kind: "resolved", skills: resolved } : { kind: "missing", names: missing2 };
54286
54302
  }
54287
54303
  async function folderCandidates(folder) {
54288
- const entries2 = await (0, import_promises29.readdir)(folder, { withFileTypes: true }).catch(() => []);
54304
+ const entries2 = await (0, import_promises27.readdir)(folder, { withFileTypes: true }).catch(() => []);
54289
54305
  return entries2.filter((entry2) => entry2.isDirectory() || entry2.isSymbolicLink()).map((entry2) => ({ directory: (0, import_node_path31.join)(folder, entry2.name) }));
54290
54306
  }
54291
54307
  async function nativeCandidates(layout) {
@@ -54330,11 +54346,11 @@ async function inspectIndexedSkill(directory, contentHash) {
54330
54346
  return null;
54331
54347
  }
54332
54348
  }
54333
- var import_promises29, import_node_path31, installedFileSchema, localSkillsFileSchema, INDEX_CONCURRENCY;
54349
+ var import_promises27, import_node_path31, installedFileSchema, localSkillsFileSchema, INDEX_CONCURRENCY;
54334
54350
  var init_store = __esm({
54335
54351
  "src/capabilities/skills/store.ts"() {
54336
54352
  "use strict";
54337
- import_promises29 = require("node:fs/promises");
54353
+ import_promises27 = require("node:fs/promises");
54338
54354
  import_node_path31 = require("node:path");
54339
54355
  init_alan_skill_identity();
54340
54356
  init_skill_package();
@@ -54428,7 +54444,7 @@ var init_paths2 = __esm({
54428
54444
  // src/capabilities/workspace/approved-paths.ts
54429
54445
  async function realpathOrNull(path19) {
54430
54446
  try {
54431
- return await (0, import_promises30.realpath)(path19);
54447
+ return await (0, import_promises28.realpath)(path19);
54432
54448
  } catch (error62) {
54433
54449
  const code = errnoCode(error62);
54434
54450
  if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES" || code === "EPERM") {
@@ -54485,11 +54501,11 @@ async function openApprovedPaths(options) {
54485
54501
  roots
54486
54502
  };
54487
54503
  }
54488
- var import_promises30, MAX_RUN_PATHS, storeSchema;
54504
+ var import_promises28, MAX_RUN_PATHS, storeSchema;
54489
54505
  var init_approved_paths = __esm({
54490
54506
  "src/capabilities/workspace/approved-paths.ts"() {
54491
54507
  "use strict";
54492
- import_promises30 = require("node:fs/promises");
54508
+ import_promises28 = require("node:fs/promises");
54493
54509
  init_zod();
54494
54510
  init_kernel();
54495
54511
  init_paths2();
@@ -54503,12 +54519,12 @@ var init_approved_paths = __esm({
54503
54519
 
54504
54520
  // src/capabilities/workspace/locks.ts
54505
54521
  function repositoryLockKey(commonDir, platform) {
54506
- return (0, import_node_crypto27.createHash)("sha256").update(comparablePath(commonDir, platform)).digest("hex").slice(0, 32);
54522
+ return (0, import_node_crypto21.createHash)("sha256").update(comparablePath(commonDir, platform)).digest("hex").slice(0, 32);
54507
54523
  }
54508
54524
  async function readOwner(path19) {
54509
54525
  let text3;
54510
54526
  try {
54511
- text3 = await (0, import_promises31.readFile)(path19, "utf8");
54527
+ text3 = await (0, import_promises29.readFile)(path19, "utf8");
54512
54528
  } catch (error62) {
54513
54529
  if (errnoCode(error62) === "ENOENT") return { kind: "missing" };
54514
54530
  return { kind: "unreadable" };
@@ -54529,7 +54545,7 @@ async function removeIfSame(path19, expected) {
54529
54545
  if (current.kind !== "owner" || current.owner.since !== expected.since) return;
54530
54546
  if (current.owner.pid !== expected.pid || current.owner.holder !== expected.holder) return;
54531
54547
  }
54532
- await (0, import_promises31.unlink)(path19).catch((error62) => {
54548
+ await (0, import_promises29.unlink)(path19).catch((error62) => {
54533
54549
  if (errnoCode(error62) !== "ENOENT") throw error62;
54534
54550
  });
54535
54551
  }
@@ -54554,7 +54570,7 @@ function openRepositoryLocks(options) {
54554
54570
  await removeIfSame(path19, read4.owner);
54555
54571
  return null;
54556
54572
  }
54557
- const age = await (0, import_promises31.stat)(path19).then(
54573
+ const age = await (0, import_promises29.stat)(path19).then(
54558
54574
  (info) => clock.now() - info.mtimeMs,
54559
54575
  () => 0
54560
54576
  );
@@ -54569,12 +54585,12 @@ function openRepositoryLocks(options) {
54569
54585
  const folder = async (commonDir) => {
54570
54586
  const key = repositoryLockKey(commonDir, platform);
54571
54587
  const dir = (0, import_node_path34.join)(options.dir, key);
54572
- await (0, import_promises31.mkdir)(dir, { recursive: true, mode: 448 });
54588
+ await (0, import_promises29.mkdir)(dir, { recursive: true, mode: 448 });
54573
54589
  return { key, dir };
54574
54590
  };
54575
54591
  const createExclusive = async (path19, owner) => {
54576
54592
  try {
54577
- const handle = await (0, import_promises31.open)(path19, "wx", 384);
54593
+ const handle = await (0, import_promises29.open)(path19, "wx", 384);
54578
54594
  try {
54579
54595
  await handle.writeFile(JSON.stringify(owner));
54580
54596
  } finally {
@@ -54587,7 +54603,7 @@ function openRepositoryLocks(options) {
54587
54603
  }
54588
54604
  };
54589
54605
  const liveRun = async (dir) => {
54590
- const entries2 = await (0, import_promises31.readdir)(dir);
54606
+ const entries2 = await (0, import_promises29.readdir)(dir);
54591
54607
  for (const entry2 of entries2) {
54592
54608
  if (!entry2.startsWith(RUN_FILE_PREFIX)) continue;
54593
54609
  const holder = await heldBy((0, import_node_path34.join)(dir, entry2));
@@ -54616,7 +54632,7 @@ function openRepositoryLocks(options) {
54616
54632
  },
54617
54633
  tryShared: async (commonDir, runId) => {
54618
54634
  const { key, dir } = await folder(commonDir);
54619
- const file2 = `${RUN_FILE_PREFIX}${(0, import_node_crypto27.createHash)("sha256").update(runId).digest("hex").slice(0, 32)}.json`;
54635
+ const file2 = `${RUN_FILE_PREFIX}${(0, import_node_crypto21.createHash)("sha256").update(runId).digest("hex").slice(0, 32)}.json`;
54620
54636
  const path19 = (0, import_node_path34.join)(dir, file2);
54621
54637
  const owner = await self(runId);
54622
54638
  await writeJsonFileAtomic(path19, owner);
@@ -54629,12 +54645,12 @@ function openRepositoryLocks(options) {
54629
54645
  }
54630
54646
  };
54631
54647
  }
54632
- var import_node_crypto27, import_promises31, import_node_path34, LOCK_FORMAT, EXCLUSIVE_FILE, RUN_FILE_PREFIX, UNREADABLE_GRACE_MS, ownerSchema;
54648
+ var import_node_crypto21, import_promises29, import_node_path34, LOCK_FORMAT, EXCLUSIVE_FILE, RUN_FILE_PREFIX, UNREADABLE_GRACE_MS, ownerSchema;
54633
54649
  var init_locks = __esm({
54634
54650
  "src/capabilities/workspace/locks.ts"() {
54635
54651
  "use strict";
54636
- import_node_crypto27 = require("node:crypto");
54637
- import_promises31 = require("node:fs/promises");
54652
+ import_node_crypto21 = require("node:crypto");
54653
+ import_promises29 = require("node:fs/promises");
54638
54654
  import_node_path34 = require("node:path");
54639
54655
  init_zod();
54640
54656
  init_kernel();
@@ -63480,7 +63496,7 @@ var init_session6 = __esm({
63480
63496
  const fence = this.#fence;
63481
63497
  this.#fence = fence.then(() => outcome2).then(ignore, ignore);
63482
63498
  const index = job.index;
63483
- const deliver = (fenced) => (fenced ? fence.then(() => outcome2) : outcome2).then((value2) => {
63499
+ const deliver2 = (fenced) => (fenced ? fence.then(() => outcome2) : outcome2).then((value2) => {
63484
63500
  this.#delivered(index, fenced);
63485
63501
  if (this.#poisoned(index))
63486
63502
  throw new SessionFailed(this.#failure.error);
@@ -63489,7 +63505,7 @@ var init_session6 = __esm({
63489
63505
  this.#delivered(index, fenced);
63490
63506
  throw this.#poisoned(index) ? new SessionFailed(this.#failure.error) : error62;
63491
63507
  });
63492
- return exempt ? ran.then((result) => deliver(job.hit || result.after !== void 0), () => deliver(job.hit)) : deliver(true);
63508
+ return exempt ? ran.then((result) => deliver2(job.hit || result.after !== void 0), () => deliver2(job.hit)) : deliver2(true);
63493
63509
  }
63494
63510
  /** Whether job `index` comes after the failure's boundary without an outcome of its own: it gets `SessionFailed`. */
63495
63511
  #poisoned(index) {
@@ -73827,7 +73843,7 @@ function relativeTitle(cwd, target) {
73827
73843
  }
73828
73844
  async function canonicalPath(target) {
73829
73845
  try {
73830
- return await (0, import_promises32.realpath)(target);
73846
+ return await (0, import_promises30.realpath)(target);
73831
73847
  } catch {
73832
73848
  const parent = import_node_path35.default.dirname(target);
73833
73849
  if (parent === target) return target;
@@ -73851,11 +73867,11 @@ async function withFileLock(target, run3) {
73851
73867
  if (queues.get(key) === tail2) queues.delete(key);
73852
73868
  }
73853
73869
  }
73854
- var import_promises32, import_node_os4, import_node_path35, ToolFailure, queues;
73870
+ var import_promises30, import_node_os4, import_node_path35, ToolFailure, queues;
73855
73871
  var init_shared2 = __esm({
73856
73872
  "../alan-engine/src/tools/shared.ts"() {
73857
73873
  "use strict";
73858
- import_promises32 = require("node:fs/promises");
73874
+ import_promises30 = require("node:fs/promises");
73859
73875
  import_node_os4 = require("node:os");
73860
73876
  import_node_path35 = __toESM(require("node:path"), 1);
73861
73877
  ToolFailure = class extends Error {
@@ -74443,7 +74459,7 @@ function replacementsOf(args) {
74443
74459
  }
74444
74460
  async function editDiff(cwd, tool, args) {
74445
74461
  const filepath = resolveIn(cwd, text2(args, "filePath"));
74446
- const before = await (0, import_promises33.readFile)(filepath, "utf8").catch(() => "");
74462
+ const before = await (0, import_promises31.readFile)(filepath, "utf8").catch(() => "");
74447
74463
  try {
74448
74464
  if (tool === "write") return unifiedDiff(filepath, before, text2(args, "content"));
74449
74465
  const edits = replacementsOf(args);
@@ -74503,11 +74519,11 @@ function createApprovalsExtension(options) {
74503
74519
  ]
74504
74520
  });
74505
74521
  }
74506
- var import_promises33, import_node_path36, APPROVALS_EXTENSION_NAME, EDIT_TOOLS2, COMMAND_TOOLS, EDIT_GRANT, MAX_INPUT_TEXT, DENY_WRITES_MESSAGE;
74522
+ var import_promises31, import_node_path36, APPROVALS_EXTENSION_NAME, EDIT_TOOLS2, COMMAND_TOOLS, EDIT_GRANT, MAX_INPUT_TEXT, DENY_WRITES_MESSAGE;
74507
74523
  var init_approvals = __esm({
74508
74524
  "../alan-engine/src/engine/approvals.ts"() {
74509
74525
  "use strict";
74510
- import_promises33 = require("node:fs/promises");
74526
+ import_promises31 = require("node:fs/promises");
74511
74527
  import_node_path36 = __toESM(require("node:path"), 1);
74512
74528
  init_dist3();
74513
74529
  init_dist4();
@@ -74691,6 +74707,7 @@ var init_events = __esm({
74691
74707
  "../alan-engine/src/engine/events.ts"() {
74692
74708
  "use strict";
74693
74709
  init_dist3();
74710
+ init_dist4();
74694
74711
  init_messages2();
74695
74712
  EMPTY_USAGE = {
74696
74713
  input: 0,
@@ -74749,12 +74766,12 @@ var init_events = __esm({
74749
74766
  this.#runText = "";
74750
74767
  events.push({ type: "run_start", inputs });
74751
74768
  }
74752
- for (const submissionId of inputs) {
74753
- if (!this.#inputs.includes(submissionId)) events.push({ type: "input_placed", submissionId });
74754
- }
74769
+ const unplaced = inputs.filter((submissionId) => !this.#inputs.includes(submissionId));
74755
74770
  for (const entry2 of view2.entries) {
74756
74771
  if (Number(entry2.id) <= this.#lastEntry) continue;
74757
74772
  this.#lastEntry = Number(entry2.id);
74773
+ const placed = UserEntry.is(entry2) ? unplaced.shift() : void 0;
74774
+ if (placed !== void 0) events.push({ type: "input_placed", submissionId: placed });
74758
74775
  for (const message of entry2.model ?? []) {
74759
74776
  if (message.role === "assistant") {
74760
74777
  events.push(...this.#blocksUpTo(message.content));
@@ -74784,6 +74801,7 @@ var init_events = __esm({
74784
74801
  }
74785
74802
  }
74786
74803
  }
74804
+ for (const submissionId of unplaced) events.push({ type: "input_placed", submissionId });
74787
74805
  if (live?.generation?.attempt !== this.#attempt) this.#sent.clear();
74788
74806
  this.#attempt = live?.generation?.attempt;
74789
74807
  const partial2 = live?.generation?.message;
@@ -74824,7 +74842,7 @@ function processAlive(pid) {
74824
74842
  }
74825
74843
  async function lockOwner(path19) {
74826
74844
  try {
74827
- const pid = Number.parseInt((await (0, import_promises34.readFile)(path19, "utf8")).trim(), 10);
74845
+ const pid = Number.parseInt((await (0, import_promises32.readFile)(path19, "utf8")).trim(), 10);
74828
74846
  return Number.isInteger(pid) && pid > 0 ? pid : void 0;
74829
74847
  } catch {
74830
74848
  return void 0;
@@ -74834,13 +74852,13 @@ function isExists(error62) {
74834
74852
  return error62.code === "EEXIST";
74835
74853
  }
74836
74854
  async function createLock(path19) {
74837
- const staged = `${path19}.${process.pid}.${(0, import_node_crypto28.randomUUID)().slice(0, 8)}`;
74838
- await (0, import_promises34.writeFile)(staged, `${process.pid}
74855
+ const staged = `${path19}.${process.pid}.${(0, import_node_crypto22.randomUUID)().slice(0, 8)}`;
74856
+ await (0, import_promises32.writeFile)(staged, `${process.pid}
74839
74857
  `, "utf8");
74840
74858
  try {
74841
- await (0, import_promises34.link)(staged, path19);
74859
+ await (0, import_promises32.link)(staged, path19);
74842
74860
  } finally {
74843
- await (0, import_promises34.rm)(staged, { force: true });
74861
+ await (0, import_promises32.rm)(staged, { force: true });
74844
74862
  }
74845
74863
  }
74846
74864
  async function acquireSessionLock(path19) {
@@ -74853,7 +74871,7 @@ async function acquireSessionLock(path19) {
74853
74871
  release: async () => {
74854
74872
  if (released) return;
74855
74873
  released = true;
74856
- await (0, import_promises34.rm)(path19, { force: true });
74874
+ await (0, import_promises32.rm)(path19, { force: true });
74857
74875
  }
74858
74876
  };
74859
74877
  } catch (error62) {
@@ -74861,17 +74879,17 @@ async function acquireSessionLock(path19) {
74861
74879
  const owner = await lockOwner(path19);
74862
74880
  if (owner !== void 0 && processAlive(owner)) throw new SessionLockedError(path19, owner);
74863
74881
  if (attempt > 0) throw new SessionLockedError(path19, owner);
74864
- await (0, import_promises34.rm)(path19, { force: true });
74882
+ await (0, import_promises32.rm)(path19, { force: true });
74865
74883
  }
74866
74884
  }
74867
74885
  throw new SessionLockedError(path19, void 0);
74868
74886
  }
74869
- var import_node_crypto28, import_promises34, SessionLockedError;
74887
+ var import_node_crypto22, import_promises32, SessionLockedError;
74870
74888
  var init_lock = __esm({
74871
74889
  "../alan-engine/src/engine/lock.ts"() {
74872
74890
  "use strict";
74873
- import_node_crypto28 = require("node:crypto");
74874
- import_promises34 = require("node:fs/promises");
74891
+ import_node_crypto22 = require("node:crypto");
74892
+ import_promises32 = require("node:fs/promises");
74875
74893
  SessionLockedError = class extends Error {
74876
74894
  lockPath;
74877
74895
  ownerPid;
@@ -74889,7 +74907,7 @@ var init_lock = __esm({
74889
74907
 
74890
74908
  // ../alan-engine/src/engine/rules.ts
74891
74909
  async function exists(target) {
74892
- return (0, import_promises35.stat)(target).then(
74910
+ return (0, import_promises33.stat)(target).then(
74893
74911
  () => true,
74894
74912
  () => false
74895
74913
  );
@@ -74906,7 +74924,7 @@ async function findGitRoot(cwd) {
74906
74924
  async function ruleFileIn(dir) {
74907
74925
  for (const name of RULE_FILE_NAMES) {
74908
74926
  const file2 = import_node_path37.default.join(dir, name);
74909
- const text3 = await (0, import_promises35.readFile)(file2, "utf8").catch(() => void 0);
74927
+ const text3 = await (0, import_promises33.readFile)(file2, "utf8").catch(() => void 0);
74910
74928
  if (text3 === void 0 || text3.trim() === "") continue;
74911
74929
  const truncatedChars = Math.max(0, text3.length - MAX_RULE_FILE_CHARS);
74912
74930
  return { path: file2, content: text3.slice(0, MAX_RULE_FILE_CHARS), truncatedChars };
@@ -74944,11 +74962,11 @@ ${file2.content.trimEnd()}${note}`;
74944
74962
  async function projectInstructions(cwd) {
74945
74963
  return renderProjectRules(await loadProjectRules(cwd));
74946
74964
  }
74947
- var import_promises35, import_node_path37, RULE_FILE_NAMES, MAX_RULE_FILE_CHARS;
74965
+ var import_promises33, import_node_path37, RULE_FILE_NAMES, MAX_RULE_FILE_CHARS;
74948
74966
  var init_rules2 = __esm({
74949
74967
  "../alan-engine/src/engine/rules.ts"() {
74950
74968
  "use strict";
74951
- import_promises35 = require("node:fs/promises");
74969
+ import_promises33 = require("node:fs/promises");
74952
74970
  import_node_path37 = __toESM(require("node:path"), 1);
74953
74971
  RULE_FILE_NAMES = ["AGENTS.md", "CLAUDE.md"];
74954
74972
  MAX_RULE_FILE_CHARS = 16e3;
@@ -75213,7 +75231,7 @@ async function anyUnreliable(paths) {
75213
75231
  return false;
75214
75232
  for (const path19 of paths) {
75215
75233
  for (const candidate of [path19, ...ancestorsOf(path19)]) {
75216
- const info = await (0, import_promises36.statfs)(candidate).catch(() => void 0);
75234
+ const info = await (0, import_promises34.statfs)(candidate).catch(() => void 0);
75217
75235
  if (info === void 0)
75218
75236
  continue;
75219
75237
  if (UNRELIABLE_FILE_SYSTEMS.has(info.type))
@@ -75223,13 +75241,13 @@ async function anyUnreliable(paths) {
75223
75241
  }
75224
75242
  return false;
75225
75243
  }
75226
- var import_node_crypto29, import_node_fs20, import_promises36, import_node_path38, DEBOUNCE_MS, FSEVENTS_SETTLE_MS, DEFAULT_POLL_MS, DEFAULT_MAX_DIRECTORIES, OVERFLOW, HASH_MAX_BYTES, HASH_RECENT_MS, UNRELIABLE_FILE_SYSTEMS, BudgetExceeded, NodeFileWatcher;
75244
+ var import_node_crypto23, import_node_fs20, import_promises34, import_node_path38, DEBOUNCE_MS, FSEVENTS_SETTLE_MS, DEFAULT_POLL_MS, DEFAULT_MAX_DIRECTORIES, OVERFLOW, HASH_MAX_BYTES, HASH_RECENT_MS, UNRELIABLE_FILE_SYSTEMS, BudgetExceeded, NodeFileWatcher;
75227
75245
  var init_node_watch = __esm({
75228
75246
  "../../node_modules/@earendil-works/pi-durable/dist/env/node-watch.js"() {
75229
75247
  "use strict";
75230
- import_node_crypto29 = require("node:crypto");
75248
+ import_node_crypto23 = require("node:crypto");
75231
75249
  import_node_fs20 = require("node:fs");
75232
- import_promises36 = require("node:fs/promises");
75250
+ import_promises34 = require("node:fs/promises");
75233
75251
  import_node_path38 = require("node:path");
75234
75252
  init_env();
75235
75253
  DEBOUNCE_MS = 50;
@@ -75442,7 +75460,7 @@ var init_node_watch = __esm({
75442
75460
  const record3 = async (path19, stats) => {
75443
75461
  let hash2;
75444
75462
  if (this.#mode === "polling" && stats.isFile() && stats.size <= HASH_MAX_BYTES && Date.now() - stats.mtimeMs < HASH_RECENT_MS) {
75445
- hash2 = await (0, import_promises36.readFile)(path19).then((content2) => (0, import_node_crypto29.createHash)("sha256").update(content2).digest("hex"), () => void 0);
75463
+ hash2 = await (0, import_promises34.readFile)(path19).then((content2) => (0, import_node_crypto23.createHash)("sha256").update(content2).digest("hex"), () => void 0);
75446
75464
  }
75447
75465
  snapshot.set(path19, entryOf(stats, hash2));
75448
75466
  };
@@ -75453,7 +75471,7 @@ var init_node_watch = __esm({
75453
75471
  traversed.add(key);
75454
75472
  let names2;
75455
75473
  try {
75456
- names2 = await (0, import_promises36.readdir)(directory);
75474
+ names2 = await (0, import_promises34.readdir)(directory);
75457
75475
  } catch (error62) {
75458
75476
  if (directory === target.path && isDenied(error62))
75459
75477
  throw error62;
@@ -75467,7 +75485,7 @@ var init_node_watch = __esm({
75467
75485
  const path19 = `${directory.endsWith(import_node_path38.sep) ? directory : directory + import_node_path38.sep}${name}`;
75468
75486
  let kind = listed.get(path19);
75469
75487
  if (kind === void 0) {
75470
- const stats = await (0, import_promises36.lstat)(path19).catch(() => void 0);
75488
+ const stats = await (0, import_promises34.lstat)(path19).catch(() => void 0);
75471
75489
  if (stats === void 0)
75472
75490
  continue;
75473
75491
  kind = entryOf(stats).kind;
@@ -75485,20 +75503,20 @@ var init_node_watch = __esm({
75485
75503
  for (const ancestor of ancestorsOf(target.path)) {
75486
75504
  if (snapshot.has(ancestor))
75487
75505
  continue;
75488
- const stats2 = await (0, import_promises36.lstat)(ancestor).catch(() => void 0);
75506
+ const stats2 = await (0, import_promises34.lstat)(ancestor).catch(() => void 0);
75489
75507
  if (stats2 !== void 0)
75490
75508
  snapshot.set(ancestor, { ...entryOf(stats2), size: 0, mtimeMs: 0 });
75491
75509
  }
75492
75510
  let stats;
75493
75511
  try {
75494
- stats = await (0, import_promises36.stat)(target.path);
75512
+ stats = await (0, import_promises34.stat)(target.path);
75495
75513
  } catch (error62) {
75496
75514
  if (isDenied(error62))
75497
75515
  throw error62;
75498
75516
  continue;
75499
75517
  }
75500
75518
  await record3(target.path, stats);
75501
- if (stats.isFile() && (await (0, import_promises36.lstat)(target.path).catch(() => void 0))?.isSymbolicLink()) {
75519
+ if (stats.isFile() && (await (0, import_promises34.lstat)(target.path).catch(() => void 0))?.isSymbolicLink()) {
75502
75520
  linkedFiles.add(target.path);
75503
75521
  }
75504
75522
  if (stats.isDirectory()) {
@@ -75697,7 +75715,7 @@ function abortResult(signal, path19) {
75697
75715
  }
75698
75716
  async function pathExists(path19) {
75699
75717
  try {
75700
- await (0, import_promises37.access)(path19, import_node_fs21.constants.F_OK);
75718
+ await (0, import_promises35.access)(path19, import_node_fs21.constants.F_OK);
75701
75719
  return true;
75702
75720
  } catch {
75703
75721
  return false;
@@ -75917,14 +75935,14 @@ function closedResult(what, path19) {
75917
75935
  function symlinkRefused(path19, cause) {
75918
75936
  return new FileError("invalid", "Refusing to follow a symbolic link", path19, cause);
75919
75937
  }
75920
- var import_node_child_process12, import_node_crypto30, import_node_fs21, import_promises37, import_node_os5, import_node_path39, import_node_url5, MAX_TIMEOUT_MS, MAX_TIMEOUT_SECONDS, EXIT_STDIO_GRACE_MS, SPILL_HIGH_WATER_MARK, BINARY_READ_CHUNK, NodeTextLineReader, NodeBinaryReader, NodeDirReader, NodeExecutionEnv;
75938
+ var import_node_child_process12, import_node_crypto24, import_node_fs21, import_promises35, import_node_os5, import_node_path39, import_node_url5, MAX_TIMEOUT_MS, MAX_TIMEOUT_SECONDS, EXIT_STDIO_GRACE_MS, SPILL_HIGH_WATER_MARK, BINARY_READ_CHUNK, NodeTextLineReader, NodeBinaryReader, NodeDirReader, NodeExecutionEnv;
75921
75939
  var init_node = __esm({
75922
75940
  "../../node_modules/@earendil-works/pi-durable/dist/env/node.js"() {
75923
75941
  "use strict";
75924
75942
  import_node_child_process12 = require("node:child_process");
75925
- import_node_crypto30 = require("node:crypto");
75943
+ import_node_crypto24 = require("node:crypto");
75926
75944
  import_node_fs21 = require("node:fs");
75927
- import_promises37 = require("node:fs/promises");
75945
+ import_promises35 = require("node:fs/promises");
75928
75946
  import_node_os5 = require("node:os");
75929
75947
  import_node_path39 = require("node:path");
75930
75948
  import_node_url5 = require("node:url");
@@ -75951,9 +75969,9 @@ var init_node = __esm({
75951
75969
  this.path = path19;
75952
75970
  }
75953
75971
  async readLine(context) {
75954
- const aborted2 = abortResult(context.abortSignal, this.path);
75955
- if (aborted2)
75956
- return aborted2;
75972
+ const aborted3 = abortResult(context.abortSignal, this.path);
75973
+ if (aborted3)
75974
+ return aborted3;
75957
75975
  if (this.closed)
75958
75976
  return err(new FileError("invalid", "Text line reader is closed", this.path));
75959
75977
  try {
@@ -76007,9 +76025,9 @@ var init_node = __esm({
76007
76025
  this.path = path19;
76008
76026
  }
76009
76027
  async info(context) {
76010
- const aborted2 = abortResult(context.abortSignal, this.path);
76011
- if (aborted2)
76012
- return aborted2;
76028
+ const aborted3 = abortResult(context.abortSignal, this.path);
76029
+ if (aborted3)
76030
+ return aborted3;
76013
76031
  if (this.closed)
76014
76032
  return closedResult("Binary reader", this.path);
76015
76033
  try {
@@ -76019,9 +76037,9 @@ var init_node = __esm({
76019
76037
  }
76020
76038
  }
76021
76039
  async read(offset, length, context) {
76022
- const aborted2 = abortResult(context.abortSignal, this.path);
76023
- if (aborted2)
76024
- return aborted2;
76040
+ const aborted3 = abortResult(context.abortSignal, this.path);
76041
+ if (aborted3)
76042
+ return aborted3;
76025
76043
  if (this.closed)
76026
76044
  return closedResult("Binary reader", this.path);
76027
76045
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0) {
@@ -76055,9 +76073,9 @@ var init_node = __esm({
76055
76073
  return ok(bytes2);
76056
76074
  }
76057
76075
  async scanLines(options, context) {
76058
- const aborted2 = abortResult(context.abortSignal, this.path);
76059
- if (aborted2)
76060
- return aborted2;
76076
+ const aborted3 = abortResult(context.abortSignal, this.path);
76077
+ if (aborted3)
76078
+ return aborted3;
76061
76079
  if (this.closed)
76062
76080
  return closedResult("Binary reader", this.path);
76063
76081
  let scanner;
@@ -76099,9 +76117,9 @@ var init_node = __esm({
76099
76117
  this.path = path19;
76100
76118
  }
76101
76119
  async next(maxEntries, context) {
76102
- const aborted2 = abortResult(context.abortSignal, this.path);
76103
- if (aborted2)
76104
- return aborted2;
76120
+ const aborted3 = abortResult(context.abortSignal, this.path);
76121
+ if (aborted3)
76122
+ return aborted3;
76105
76123
  if (this.closed)
76106
76124
  return closedResult("Directory reader", this.path);
76107
76125
  if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {
@@ -76121,7 +76139,7 @@ var init_node = __esm({
76121
76139
  const entryPath = (0, import_node_path39.resolve)(this.path, entry2.name);
76122
76140
  let stats;
76123
76141
  try {
76124
- stats = await (0, import_promises37.lstat)(entryPath);
76142
+ stats = await (0, import_promises35.lstat)(entryPath);
76125
76143
  } catch (error62) {
76126
76144
  if (isNodeError2(error62) && error62.code === "ENOENT")
76127
76145
  continue;
@@ -76158,9 +76176,9 @@ var init_node = __esm({
76158
76176
  this.watchOptions = options.watch ?? {};
76159
76177
  }
76160
76178
  async watch(targets, onChange, context) {
76161
- const aborted2 = abortResult(context.abortSignal);
76162
- if (aborted2)
76163
- return aborted2;
76179
+ const aborted3 = abortResult(context.abortSignal);
76180
+ if (aborted3)
76181
+ return aborted3;
76164
76182
  try {
76165
76183
  const watcher = await NodeFileWatcher.open(targets, (path19) => resolvePath3(this.cwd, path19), onChange, this.watchOptions);
76166
76184
  const afterOpenAbort = abortResult(context.abortSignal);
@@ -76207,7 +76225,7 @@ var init_node = __esm({
76207
76225
  args = rest;
76208
76226
  }
76209
76227
  try {
76210
- await (0, import_promises37.access)(cwd, import_node_fs21.constants.F_OK);
76228
+ await (0, import_promises35.access)(cwd, import_node_fs21.constants.F_OK);
76211
76229
  } catch (error62) {
76212
76230
  const cause = toError3(error62);
76213
76231
  return err(new ExecutionError("spawn_error", `Working directory does not exist: ${cwd}
@@ -76404,11 +76422,11 @@ Cannot execute bash commands.`, cause));
76404
76422
  }
76405
76423
  async openTextLineReader(path19, context) {
76406
76424
  const resolved = resolvePath3(this.cwd, path19);
76407
- const aborted2 = abortResult(context.abortSignal, resolved);
76408
- if (aborted2)
76409
- return aborted2;
76425
+ const aborted3 = abortResult(context.abortSignal, resolved);
76426
+ if (aborted3)
76427
+ return aborted3;
76410
76428
  try {
76411
- const file2 = await (0, import_promises37.open)(resolved, "r");
76429
+ const file2 = await (0, import_promises35.open)(resolved, "r");
76412
76430
  const afterOpenAbort = abortResult(context.abortSignal, resolved);
76413
76431
  if (afterOpenAbort) {
76414
76432
  await file2.close().catch(() => void 0);
@@ -76422,11 +76440,11 @@ Cannot execute bash commands.`, cause));
76422
76440
  async readTextFile(path19, context) {
76423
76441
  const resolved = resolvePath3(this.cwd, path19);
76424
76442
  const signal = context.abortSignal;
76425
- const aborted2 = abortResult(signal, resolved);
76426
- if (aborted2)
76427
- return aborted2;
76443
+ const aborted3 = abortResult(signal, resolved);
76444
+ if (aborted3)
76445
+ return aborted3;
76428
76446
  try {
76429
- return ok(await (0, import_promises37.readFile)(resolved, { encoding: "utf8", signal }));
76447
+ return ok(await (0, import_promises35.readFile)(resolved, { encoding: "utf8", signal }));
76430
76448
  } catch (error62) {
76431
76449
  return err(toFileError(error62, resolved));
76432
76450
  }
@@ -76455,33 +76473,33 @@ Cannot execute bash commands.`, cause));
76455
76473
  async readBinaryFile(path19, context) {
76456
76474
  const resolved = resolvePath3(this.cwd, path19);
76457
76475
  const signal = context.abortSignal;
76458
- const aborted2 = abortResult(signal, resolved);
76459
- if (aborted2)
76460
- return aborted2;
76476
+ const aborted3 = abortResult(signal, resolved);
76477
+ if (aborted3)
76478
+ return aborted3;
76461
76479
  try {
76462
- return ok(await (0, import_promises37.readFile)(resolved, { signal }));
76480
+ return ok(await (0, import_promises35.readFile)(resolved, { signal }));
76463
76481
  } catch (error62) {
76464
76482
  return err(toFileError(error62, resolved));
76465
76483
  }
76466
76484
  }
76467
76485
  async openBinaryReader(path19, options, context) {
76468
76486
  const resolved = resolvePath3(this.cwd, path19);
76469
- const aborted2 = abortResult(context.abortSignal, resolved);
76470
- if (aborted2)
76471
- return aborted2;
76487
+ const aborted3 = abortResult(context.abortSignal, resolved);
76488
+ if (aborted3)
76489
+ return aborted3;
76472
76490
  const noFollow = options?.noFollow === true;
76473
76491
  let file2;
76474
76492
  try {
76475
76493
  let flags = import_node_fs21.constants.O_RDONLY;
76476
76494
  if (process.platform === "win32") {
76477
- if (noFollow && (await (0, import_promises37.lstat)(resolved)).isSymbolicLink())
76495
+ if (noFollow && (await (0, import_promises35.lstat)(resolved)).isSymbolicLink())
76478
76496
  return err(symlinkRefused(resolved));
76479
76497
  } else {
76480
76498
  flags |= import_node_fs21.constants.O_NONBLOCK;
76481
76499
  if (noFollow)
76482
76500
  flags |= import_node_fs21.constants.O_NOFOLLOW;
76483
76501
  }
76484
- file2 = await (0, import_promises37.open)(resolved, flags);
76502
+ file2 = await (0, import_promises35.open)(resolved, flags);
76485
76503
  const stats = await file2.stat();
76486
76504
  if (!stats.isFile()) {
76487
76505
  await file2.close().catch(() => void 0);
@@ -76504,15 +76522,15 @@ Cannot execute bash commands.`, cause));
76504
76522
  async writeFile(path19, content2, context) {
76505
76523
  const resolved = resolvePath3(this.cwd, path19);
76506
76524
  const signal = context.abortSignal;
76507
- const aborted2 = abortResult(signal, resolved);
76508
- if (aborted2)
76509
- return aborted2;
76525
+ const aborted3 = abortResult(signal, resolved);
76526
+ if (aborted3)
76527
+ return aborted3;
76510
76528
  try {
76511
- await (0, import_promises37.mkdir)((0, import_node_path39.resolve)(resolved, ".."), { recursive: true });
76529
+ await (0, import_promises35.mkdir)((0, import_node_path39.resolve)(resolved, ".."), { recursive: true });
76512
76530
  const afterMkdirAbort = abortResult(signal, resolved);
76513
76531
  if (afterMkdirAbort)
76514
76532
  return afterMkdirAbort;
76515
- await (0, import_promises37.writeFile)(resolved, content2, { signal });
76533
+ await (0, import_promises35.writeFile)(resolved, content2, { signal });
76516
76534
  return ok(void 0);
76517
76535
  } catch (error62) {
76518
76536
  return err(toFileError(error62, resolved));
@@ -76521,15 +76539,15 @@ Cannot execute bash commands.`, cause));
76521
76539
  async appendFile(path19, content2, context) {
76522
76540
  const resolved = resolvePath3(this.cwd, path19);
76523
76541
  const signal = context.abortSignal;
76524
- const aborted2 = abortResult(signal, resolved);
76525
- if (aborted2)
76526
- return aborted2;
76542
+ const aborted3 = abortResult(signal, resolved);
76543
+ if (aborted3)
76544
+ return aborted3;
76527
76545
  try {
76528
- await (0, import_promises37.mkdir)((0, import_node_path39.resolve)(resolved, ".."), { recursive: true });
76546
+ await (0, import_promises35.mkdir)((0, import_node_path39.resolve)(resolved, ".."), { recursive: true });
76529
76547
  const afterMkdirAbort = abortResult(signal, resolved);
76530
76548
  if (afterMkdirAbort)
76531
76549
  return afterMkdirAbort;
76532
- await (0, import_promises37.appendFile)(resolved, content2);
76550
+ await (0, import_promises35.appendFile)(resolved, content2);
76533
76551
  const afterAppendAbort = abortResult(signal, resolved);
76534
76552
  return afterAppendAbort ?? ok(void 0);
76535
76553
  } catch (error62) {
@@ -76539,15 +76557,15 @@ Cannot execute bash commands.`, cause));
76539
76557
  async truncateFile(path19, size, context) {
76540
76558
  const resolved = resolvePath3(this.cwd, path19);
76541
76559
  const signal = context.abortSignal;
76542
- const aborted2 = abortResult(signal, resolved);
76543
- if (aborted2)
76544
- return aborted2;
76560
+ const aborted3 = abortResult(signal, resolved);
76561
+ if (aborted3)
76562
+ return aborted3;
76545
76563
  if (!Number.isSafeInteger(size) || size < 0) {
76546
76564
  return err(new FileError("invalid", "File size must be a non-negative safe integer", resolved));
76547
76565
  }
76548
76566
  let file2;
76549
76567
  try {
76550
- file2 = await (0, import_promises37.open)(resolved, "r+");
76568
+ file2 = await (0, import_promises35.open)(resolved, "r+");
76551
76569
  await file2.truncate(size);
76552
76570
  const afterTruncateAbort = abortResult(signal, resolved);
76553
76571
  return afterTruncateAbort ?? ok(void 0);
@@ -76560,12 +76578,12 @@ Cannot execute bash commands.`, cause));
76560
76578
  async flushFile(path19, context) {
76561
76579
  const resolved = resolvePath3(this.cwd, path19);
76562
76580
  const signal = context.abortSignal;
76563
- const aborted2 = abortResult(signal, resolved);
76564
- if (aborted2)
76565
- return aborted2;
76581
+ const aborted3 = abortResult(signal, resolved);
76582
+ if (aborted3)
76583
+ return aborted3;
76566
76584
  let file2;
76567
76585
  try {
76568
- file2 = await (0, import_promises37.open)(resolved, "r+");
76586
+ file2 = await (0, import_promises35.open)(resolved, "r+");
76569
76587
  if ((await file2.stat()).isDirectory())
76570
76588
  return err(new FileError("is_directory", "Is a directory", resolved));
76571
76589
  await file2.sync();
@@ -76580,11 +76598,11 @@ Cannot execute bash commands.`, cause));
76580
76598
  async renameFile(sourcePath, destinationPath, context) {
76581
76599
  const source = resolvePath3(this.cwd, sourcePath);
76582
76600
  const destination = resolvePath3(this.cwd, destinationPath);
76583
- const aborted2 = abortResult(context.abortSignal, destination);
76584
- if (aborted2)
76585
- return aborted2;
76601
+ const aborted3 = abortResult(context.abortSignal, destination);
76602
+ if (aborted3)
76603
+ return aborted3;
76586
76604
  try {
76587
- await (0, import_promises37.rename)(source, destination);
76605
+ await (0, import_promises35.rename)(source, destination);
76588
76606
  return ok(void 0);
76589
76607
  } catch (error62) {
76590
76608
  return err(toFileError(error62, source));
@@ -76592,11 +76610,11 @@ Cannot execute bash commands.`, cause));
76592
76610
  }
76593
76611
  async fileInfo(path19, context) {
76594
76612
  const resolved = resolvePath3(this.cwd, path19);
76595
- const aborted2 = abortResult(context.abortSignal, resolved);
76596
- if (aborted2)
76597
- return aborted2;
76613
+ const aborted3 = abortResult(context.abortSignal, resolved);
76614
+ if (aborted3)
76615
+ return aborted3;
76598
76616
  try {
76599
- return fileInfoFromStats(resolved, await (0, import_promises37.lstat)(resolved));
76617
+ return fileInfoFromStats(resolved, await (0, import_promises35.lstat)(resolved));
76600
76618
  } catch (error62) {
76601
76619
  return err(toFileError(error62, resolved));
76602
76620
  }
@@ -76604,11 +76622,11 @@ Cannot execute bash commands.`, cause));
76604
76622
  async listDir(path19, context) {
76605
76623
  const resolved = resolvePath3(this.cwd, path19);
76606
76624
  const signal = context.abortSignal;
76607
- const aborted2 = abortResult(signal, resolved);
76608
- if (aborted2)
76609
- return aborted2;
76625
+ const aborted3 = abortResult(signal, resolved);
76626
+ if (aborted3)
76627
+ return aborted3;
76610
76628
  try {
76611
- const entries2 = await (0, import_promises37.readdir)(resolved, { withFileTypes: true });
76629
+ const entries2 = await (0, import_promises35.readdir)(resolved, { withFileTypes: true });
76612
76630
  const infos = [];
76613
76631
  for (const entry2 of entries2) {
76614
76632
  const loopAbort = abortResult(signal, resolved);
@@ -76616,7 +76634,7 @@ Cannot execute bash commands.`, cause));
76616
76634
  return loopAbort;
76617
76635
  const entryPath = (0, import_node_path39.resolve)(resolved, entry2.name);
76618
76636
  try {
76619
- const info = fileInfoFromStats(entryPath, await (0, import_promises37.lstat)(entryPath));
76637
+ const info = fileInfoFromStats(entryPath, await (0, import_promises35.lstat)(entryPath));
76620
76638
  if (info.ok)
76621
76639
  infos.push(info.value);
76622
76640
  } catch (error62) {
@@ -76630,11 +76648,11 @@ Cannot execute bash commands.`, cause));
76630
76648
  }
76631
76649
  async openDirReader(path19, context) {
76632
76650
  const resolved = resolvePath3(this.cwd, path19);
76633
- const aborted2 = abortResult(context.abortSignal, resolved);
76634
- if (aborted2)
76635
- return aborted2;
76651
+ const aborted3 = abortResult(context.abortSignal, resolved);
76652
+ if (aborted3)
76653
+ return aborted3;
76636
76654
  try {
76637
- const dir = await (0, import_promises37.opendir)(resolved);
76655
+ const dir = await (0, import_promises35.opendir)(resolved);
76638
76656
  const afterOpenAbort = abortResult(context.abortSignal, resolved);
76639
76657
  if (afterOpenAbort) {
76640
76658
  await dir.close().catch(() => void 0);
@@ -76647,11 +76665,11 @@ Cannot execute bash commands.`, cause));
76647
76665
  }
76648
76666
  async canonicalPath(path19, context) {
76649
76667
  const resolved = resolvePath3(this.cwd, path19);
76650
- const aborted2 = abortResult(context.abortSignal, resolved);
76651
- if (aborted2)
76652
- return aborted2;
76668
+ const aborted3 = abortResult(context.abortSignal, resolved);
76669
+ if (aborted3)
76670
+ return aborted3;
76653
76671
  try {
76654
- return ok(await (0, import_promises37.realpath)(resolved));
76672
+ return ok(await (0, import_promises35.realpath)(resolved));
76655
76673
  } catch (error62) {
76656
76674
  return err(toFileError(error62, resolved));
76657
76675
  }
@@ -76666,11 +76684,11 @@ Cannot execute bash commands.`, cause));
76666
76684
  }
76667
76685
  async createDir(path19, options, context) {
76668
76686
  const resolved = resolvePath3(this.cwd, path19);
76669
- const aborted2 = abortResult(context.abortSignal, resolved);
76670
- if (aborted2)
76671
- return aborted2;
76687
+ const aborted3 = abortResult(context.abortSignal, resolved);
76688
+ if (aborted3)
76689
+ return aborted3;
76672
76690
  try {
76673
- await (0, import_promises37.mkdir)(resolved, { recursive: options?.recursive ?? true });
76691
+ await (0, import_promises35.mkdir)(resolved, { recursive: options?.recursive ?? true });
76674
76692
  return ok(void 0);
76675
76693
  } catch (error62) {
76676
76694
  return err(toFileError(error62, resolved));
@@ -76678,23 +76696,23 @@ Cannot execute bash commands.`, cause));
76678
76696
  }
76679
76697
  async remove(path19, options, context) {
76680
76698
  const resolved = resolvePath3(this.cwd, path19);
76681
- const aborted2 = abortResult(context.abortSignal, resolved);
76682
- if (aborted2)
76683
- return aborted2;
76699
+ const aborted3 = abortResult(context.abortSignal, resolved);
76700
+ if (aborted3)
76701
+ return aborted3;
76684
76702
  try {
76685
- await (0, import_promises37.rm)(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });
76703
+ await (0, import_promises35.rm)(resolved, { recursive: options?.recursive ?? false, force: options?.force ?? false });
76686
76704
  return ok(void 0);
76687
76705
  } catch (error62) {
76688
76706
  return err(toFileError(error62, resolved));
76689
76707
  }
76690
76708
  }
76691
76709
  async createTempDir(prefix2, context) {
76692
- const aborted2 = abortResult(context.abortSignal);
76693
- if (aborted2)
76694
- return aborted2;
76710
+ const aborted3 = abortResult(context.abortSignal);
76711
+ if (aborted3)
76712
+ return aborted3;
76695
76713
  try {
76696
76714
  prefix2 ??= "tmp-";
76697
- return ok(await (0, import_promises37.mkdtemp)((0, import_node_path39.join)((0, import_node_os5.tmpdir)(), prefix2)));
76715
+ return ok(await (0, import_promises35.mkdtemp)((0, import_node_path39.join)((0, import_node_os5.tmpdir)(), prefix2)));
76698
76716
  } catch (error62) {
76699
76717
  return err(toFileError(error62));
76700
76718
  }
@@ -76703,9 +76721,9 @@ Cannot execute bash commands.`, cause));
76703
76721
  const dir = await this.createTempDir("tmp-", context);
76704
76722
  if (!dir.ok)
76705
76723
  return dir;
76706
- const filePath = (0, import_node_path39.join)(dir.value, `${options?.prefix ?? ""}${(0, import_node_crypto30.randomUUID)()}${options?.suffix ?? ""}`);
76724
+ const filePath = (0, import_node_path39.join)(dir.value, `${options?.prefix ?? ""}${(0, import_node_crypto24.randomUUID)()}${options?.suffix ?? ""}`);
76707
76725
  try {
76708
- await (0, import_promises37.writeFile)(filePath, "");
76726
+ await (0, import_promises35.writeFile)(filePath, "");
76709
76727
  return ok(filePath);
76710
76728
  } catch (error62) {
76711
76729
  return err(toFileError(error62, filePath));
@@ -76787,7 +76805,7 @@ async function openNodeSqliteDatabase(path19, options = {}) {
76787
76805
  const checkpointPages = options.walAutoCheckpointPages ?? DEFAULT_WAL_AUTO_CHECKPOINT_PAGES;
76788
76806
  const timeout2 = options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS;
76789
76807
  if (path19 !== ":memory:")
76790
- await (0, import_promises38.mkdir)((0, import_node_path40.dirname)(path19), { recursive: true });
76808
+ await (0, import_promises36.mkdir)((0, import_node_path40.dirname)(path19), { recursive: true });
76791
76809
  const database = new import_node_sqlite.DatabaseSync(path19, { timeout: timeout2 });
76792
76810
  const adapter = new NodeSqliteDatabase(database);
76793
76811
  try {
@@ -76803,11 +76821,11 @@ async function openNodeSqliteDatabase(path19, options = {}) {
76803
76821
  throw error62;
76804
76822
  }
76805
76823
  }
76806
- var import_promises38, import_node_path40, import_node_sqlite, DEFAULT_WAL_AUTO_CHECKPOINT_PAGES, DEFAULT_BUSY_TIMEOUT_MS, ignore2, SerialOperationQueue, STATEMENT_CACHE_LIMIT, NodeSqliteExecutor, NodeSqliteTransaction, NodeSqliteDatabase;
76824
+ var import_promises36, import_node_path40, import_node_sqlite, DEFAULT_WAL_AUTO_CHECKPOINT_PAGES, DEFAULT_BUSY_TIMEOUT_MS, ignore2, SerialOperationQueue, STATEMENT_CACHE_LIMIT, NodeSqliteExecutor, NodeSqliteTransaction, NodeSqliteDatabase;
76807
76825
  var init_node2 = __esm({
76808
76826
  "../../node_modules/@earendil-works/chord/dist/sqlite/node.js"() {
76809
76827
  "use strict";
76810
- import_promises38 = require("node:fs/promises");
76828
+ import_promises36 = require("node:fs/promises");
76811
76829
  import_node_path40 = require("node:path");
76812
76830
  import_node_sqlite = require("node:sqlite");
76813
76831
  DEFAULT_WAL_AUTO_CHECKPOINT_PAGES = 1e3;
@@ -87830,13 +87848,10 @@ function parametersOf(tool) {
87830
87848
  function errorText2(error62) {
87831
87849
  return error62 instanceof Error ? error62.message : String(error62);
87832
87850
  }
87833
- function isRecord4(value2) {
87834
- return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
87835
- }
87836
87851
  function createMcpTool(connection, tool, options) {
87837
87852
  const server = connection.config.name;
87838
87853
  const properties = tool.inputSchema.properties;
87839
- const idempotent = connection.config.operationKey !== void 0 && tool._meta?.["ai.tryalan/durable-idempotency"] === "v1" && isRecord4(properties) && Object.hasOwn(properties, "idempotencyKey");
87854
+ const idempotent = connection.config.operationKey !== void 0 && tool._meta?.["ai.tryalan/durable-idempotency"] === "v1" && isRecord(properties) && Object.hasOwn(properties, "idempotencyKey");
87840
87855
  return {
87841
87856
  name: mcpToolName2(server, tool.name),
87842
87857
  description: tool.description?.trim() || tool.title || tool.name,
@@ -87845,7 +87860,7 @@ function createMcpTool(connection, tool, options) {
87845
87860
  ...options.deferred ? { deferred: true } : {},
87846
87861
  ...idempotent || tool.annotations?.readOnlyHint === true ? { replay: "safe" } : {},
87847
87862
  async execute(args, api, context) {
87848
- const input2 = isRecord4(args) ? { ...args } : {};
87863
+ const input2 = isRecord(args) ? { ...args } : {};
87849
87864
  if (idempotent && input2.idempotencyKey === void 0)
87850
87865
  input2.idempotencyKey = connection.config.operationKey?.(String(api.taskId));
87851
87866
  try {
@@ -87865,6 +87880,7 @@ var MAX_TOOL_NAME_LENGTH, MCP_OUTPUT_LIMITS;
87865
87880
  var init_tools2 = __esm({
87866
87881
  "../alan-engine/src/mcp/tools.ts"() {
87867
87882
  "use strict";
87883
+ init_type_guards();
87868
87884
  init_dist5();
87869
87885
  init_sha2();
87870
87886
  init_utils();
@@ -88010,7 +88026,7 @@ function stripBearer(authorization) {
88010
88026
  return authorization.replace(/^Bearer\s+/i, "").trim();
88011
88027
  }
88012
88028
  async function readAlanCredentialFile(path19) {
88013
- const parsed = JSON.parse(await (0, import_promises39.readFile)(path19, "utf8"));
88029
+ const parsed = JSON.parse(await (0, import_promises37.readFile)(path19, "utf8"));
88014
88030
  if (typeof parsed !== "object" || parsed === null) {
88015
88031
  throw new Error(`Alan credential file is not a JSON object: ${path19}`);
88016
88032
  }
@@ -88029,11 +88045,11 @@ function alanCredentialSource(explicit, env = process.env) {
88029
88045
  if (file2 === void 0) return { apiKey: void 0 };
88030
88046
  return () => readAlanCredentialFile(file2);
88031
88047
  }
88032
- var import_promises39, DEFAULT_ALAN_API_URL;
88048
+ var import_promises37, DEFAULT_ALAN_API_URL;
88033
88049
  var init_credentials = __esm({
88034
88050
  "../alan-engine/src/model/credentials.ts"() {
88035
88051
  "use strict";
88036
- import_promises39 = require("node:fs/promises");
88052
+ import_promises37 = require("node:fs/promises");
88037
88053
  init_credential_source();
88038
88054
  DEFAULT_ALAN_API_URL = "https://api.tryalan.ai";
88039
88055
  }
@@ -88804,24 +88820,24 @@ function assertClassifierInputSupported(model2, context) {
88804
88820
  throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} does not accept image input`);
88805
88821
  }
88806
88822
  }
88807
- function imageErrorResult(model2, error62, aborted2 = false) {
88823
+ function imageErrorResult(model2, error62, aborted3 = false) {
88808
88824
  return {
88809
88825
  api: model2.api,
88810
88826
  provider: model2.provider,
88811
88827
  model: model2.id,
88812
88828
  output: [],
88813
- stopReason: aborted2 ? "aborted" : "error",
88829
+ stopReason: aborted3 ? "aborted" : "error",
88814
88830
  errorMessage: error62 instanceof Error ? error62.message : String(error62),
88815
88831
  timestamp: Date.now()
88816
88832
  };
88817
88833
  }
88818
- function classifierErrorResult(model2, error62, aborted2 = false) {
88834
+ function classifierErrorResult(model2, error62, aborted3 = false) {
88819
88835
  return {
88820
88836
  api: model2.api,
88821
88837
  provider: model2.provider,
88822
88838
  model: model2.id,
88823
88839
  answers: {},
88824
- stopReason: aborted2 ? "aborted" : "error",
88840
+ stopReason: aborted3 ? "aborted" : "error",
88825
88841
  errorMessage: error62 instanceof Error ? error62.message : String(error62),
88826
88842
  timestamp: Date.now()
88827
88843
  };
@@ -90445,9 +90461,9 @@ function createAbortableSSESource(body, signal) {
90445
90461
  if (signal.aborted) {
90446
90462
  return ended;
90447
90463
  }
90448
- const aborted2 = waitForAbort().then(() => ended);
90464
+ const aborted3 = waitForAbort().then(() => ended);
90449
90465
  try {
90450
- const result = await Promise.race([source.next(), aborted2]);
90466
+ const result = await Promise.race([source.next(), aborted3]);
90451
90467
  if (signal.aborted) {
90452
90468
  return ended;
90453
90469
  }
@@ -90468,10 +90484,10 @@ function createAbortableSSESource(body, signal) {
90468
90484
  async return() {
90469
90485
  const pending = cancel();
90470
90486
  if (pending && !signal.aborted) {
90471
- const aborted2 = waitForAbort();
90487
+ const aborted3 = waitForAbort();
90472
90488
  try {
90473
90489
  if (!signal.aborted) {
90474
- await Promise.race([pending, aborted2]);
90490
+ await Promise.race([pending, aborted3]);
90475
90491
  }
90476
90492
  } finally {
90477
90493
  interrupt = void 0;
@@ -101364,14 +101380,14 @@ var init_agent_session_stream = __esm({
101364
101380
  return error62;
101365
101381
  }, _AgentSessionStream_wait = async function _AgentSessionStream_wait2(action) {
101366
101382
  let onAbort;
101367
- const aborted2 = new Promise((_resolve, reject2) => {
101383
+ const aborted3 = new Promise((_resolve, reject2) => {
101368
101384
  onAbort = () => reject2(__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_abortError).call(this));
101369
101385
  this.controller.signal.addEventListener("abort", onAbort, { once: true });
101370
101386
  });
101371
101387
  try {
101372
101388
  __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
101373
101389
  const invoke = async () => await action();
101374
- return await Promise.race([invoke(), aborted2]);
101390
+ return await Promise.race([invoke(), aborted3]);
101375
101391
  } finally {
101376
101392
  if (onAbort) {
101377
101393
  this.controller.signal.removeEventListener("abort", onAbort);
@@ -111824,6 +111840,70 @@ var init_openai_completions_lazy = __esm({
111824
111840
  }
111825
111841
  });
111826
111842
 
111843
+ // ../shared/src/harness/request-images.ts
111844
+ function oldestImagesToOmit(sizes, budget = REQUEST_IMAGE_BUDGET) {
111845
+ let kept = 0;
111846
+ let chars = 0;
111847
+ for (let index = sizes.length - 1; index >= 0; index -= 1) {
111848
+ const size = sizes[index] ?? 0;
111849
+ if (kept + 1 > budget.maxImages || chars + size > budget.maxBase64Chars) return index + 1;
111850
+ kept += 1;
111851
+ chars += size;
111852
+ }
111853
+ return 0;
111854
+ }
111855
+ var REQUEST_IMAGE_BUDGET, OMITTED_IMAGE_NOTE;
111856
+ var init_request_images = __esm({
111857
+ "../shared/src/harness/request-images.ts"() {
111858
+ "use strict";
111859
+ REQUEST_IMAGE_BUDGET = {
111860
+ maxBase64Chars: 8 * 1024 * 1024,
111861
+ maxImages: 20
111862
+ };
111863
+ OMITTED_IMAGE_NOTE = "[Earlier image omitted to keep the request within size limits. Read the file again if you still need it.]";
111864
+ }
111865
+ });
111866
+
111867
+ // ../alan-engine/src/model/image-budget.ts
111868
+ function imageParts(message) {
111869
+ if (message.role === "toolResult") return message.content;
111870
+ if (message.role === "user" && typeof message.content !== "string") return message.content;
111871
+ return [];
111872
+ }
111873
+ function imageSizes(messages) {
111874
+ return messages.flatMap(
111875
+ (message) => imageParts(message).flatMap((part) => part.type === "image" ? [part.data.length] : [])
111876
+ );
111877
+ }
111878
+ function withContent(message, content2) {
111879
+ if (message.role === "toolResult") return { ...message, content: content2 };
111880
+ if (message.role === "user") return { ...message, content: content2 };
111881
+ return message;
111882
+ }
111883
+ function boundMessageImages(messages, budget = REQUEST_IMAGE_BUDGET) {
111884
+ let omit2 = oldestImagesToOmit(imageSizes(messages), budget);
111885
+ if (omit2 === 0) return messages;
111886
+ return messages.map((message) => {
111887
+ if (omit2 === 0) return message;
111888
+ const parts3 = imageParts(message);
111889
+ if (!parts3.some((part) => part.type === "image")) return message;
111890
+ const content2 = parts3.map((part) => {
111891
+ if (part.type !== "image" || omit2 === 0) return part;
111892
+ omit2 -= 1;
111893
+ return OMITTED_IMAGE;
111894
+ });
111895
+ return withContent(message, content2);
111896
+ });
111897
+ }
111898
+ var OMITTED_IMAGE;
111899
+ var init_image_budget = __esm({
111900
+ "../alan-engine/src/model/image-budget.ts"() {
111901
+ "use strict";
111902
+ init_request_images();
111903
+ OMITTED_IMAGE = { type: "text", text: OMITTED_IMAGE_NOTE };
111904
+ }
111905
+ });
111906
+
111827
111907
  // ../alan-engine/src/model/alan-provider.ts
111828
111908
  function operationKey(now = Date.now()) {
111829
111909
  return `${now}-${crypto.randomUUID()}`;
@@ -111900,18 +111980,22 @@ function retryUpstreamErrors(source, signal) {
111900
111980
  })();
111901
111981
  return stream2;
111902
111982
  }
111983
+ function withBoundedImages(context) {
111984
+ const messages = boundMessageImages(context.messages);
111985
+ return messages === context.messages ? context : { ...context, messages };
111986
+ }
111903
111987
  function surfaceServerErrors(api, fetch2) {
111904
111988
  return {
111905
111989
  ...api,
111906
111990
  stream: (model2, context, options) => retryUpstreamErrors(
111907
- api.stream(model2, context, {
111991
+ api.stream(model2, withBoundedImages(context), {
111908
111992
  ...options,
111909
111993
  fetch: withServerErrorMessage(fetch2 ?? options?.fetch)
111910
111994
  }),
111911
111995
  options?.signal
111912
111996
  ),
111913
111997
  streamSimple: (model2, context, options) => retryUpstreamErrors(
111914
- api.streamSimple(model2, context, {
111998
+ api.streamSimple(model2, withBoundedImages(context), {
111915
111999
  ...options,
111916
112000
  fetch: withServerErrorMessage(fetch2 ?? options?.fetch)
111917
112001
  }),
@@ -111959,6 +112043,7 @@ var init_alan_provider = __esm({
111959
112043
  init_event_stream();
111960
112044
  init_catalog2();
111961
112045
  init_credential_source();
112046
+ init_image_budget();
111962
112047
  TRANSIENT_UPSTREAM_ERROR = /^(?:the model is unavailable\.?|aborted)$/i;
111963
112048
  }
111964
112049
  });
@@ -112039,7 +112124,7 @@ function stampOf(info) {
112039
112124
  return { mtimeMs: info.mtimeMs, size: info.size };
112040
112125
  }
112041
112126
  async function recordFileStamp(context, filepath, info) {
112042
- const current = info ?? await (0, import_promises40.stat)(filepath);
112127
+ const current = info ?? await (0, import_promises38.stat)(filepath);
112043
112128
  await context.fileReads.record(filepath, stampOf(current));
112044
112129
  }
112045
112130
  async function assertUnchangedSinceRead(context, filepath, info) {
@@ -112049,11 +112134,11 @@ async function assertUnchangedSinceRead(context, filepath, info) {
112049
112134
  throw new ToolFailure(modifiedSinceReadMessage(filepath));
112050
112135
  }
112051
112136
  }
112052
- var import_promises40, FileReadsDoc;
112137
+ var import_promises38, FileReadsDoc;
112053
112138
  var init_file_reads = __esm({
112054
112139
  "../alan-engine/src/tools/file-reads.ts"() {
112055
112140
  "use strict";
112056
- import_promises40 = require("node:fs/promises");
112141
+ import_promises38 = require("node:fs/promises");
112057
112142
  init_dist4();
112058
112143
  init_shared2();
112059
112144
  FileReadsDoc = defineDoc({
@@ -112296,7 +112381,7 @@ Usage:
112296
112381
  // ../alan-engine/src/tools/process-tree.ts
112297
112382
  function spawnShellTree(shell, env, start, platform = process.platform) {
112298
112383
  if (platform !== "win32") return start(env);
112299
- const tag = (0, import_node_crypto31.randomUUID)();
112384
+ const tag = (0, import_node_crypto25.randomUUID)();
112300
112385
  const child = start({ ...env, [PROCESS_TREE_ENV]: tag });
112301
112386
  shellTrees.set(child, { shell, tag });
112302
112387
  return child;
@@ -112342,12 +112427,12 @@ function killProcessTree3(child, signal, platform = process.platform) {
112342
112427
  child.kill(signal);
112343
112428
  }
112344
112429
  }
112345
- var import_node_child_process13, import_node_crypto31, PROCESS_TREE_ENV, shellTrees, LIST_SHELL_TREE, SHELL_TREE_ROUNDS;
112430
+ var import_node_child_process13, import_node_crypto25, PROCESS_TREE_ENV, shellTrees, LIST_SHELL_TREE, SHELL_TREE_ROUNDS;
112346
112431
  var init_process_tree2 = __esm({
112347
112432
  "../alan-engine/src/tools/process-tree.ts"() {
112348
112433
  "use strict";
112349
112434
  import_node_child_process13 = require("node:child_process");
112350
- import_node_crypto31 = require("node:crypto");
112435
+ import_node_crypto25 = require("node:crypto");
112351
112436
  PROCESS_TREE_ENV = "ALAN_PROCESS_TREE";
112352
112437
  shellTrees = /* @__PURE__ */ new WeakMap();
112353
112438
  LIST_SHELL_TREE = `tag="${PROCESS_TREE_ENV}=$1"
@@ -118761,9 +118846,9 @@ function killGroup(child, signal) {
118761
118846
  killProcessTree3(child, signal);
118762
118847
  }
118763
118848
  async function saveFullOutput(text3) {
118764
- await (0, import_promises41.mkdir)(OUTPUT_DIR, { recursive: true });
118765
- const file2 = import_node_path42.default.join(OUTPUT_DIR, `tool_${(0, import_node_crypto32.randomUUID)()}`);
118766
- await (0, import_promises41.writeFile)(file2, text3, "utf8");
118849
+ await (0, import_promises39.mkdir)(OUTPUT_DIR, { recursive: true });
118850
+ const file2 = import_node_path42.default.join(OUTPUT_DIR, `tool_${(0, import_node_crypto26.randomUUID)()}`);
118851
+ await (0, import_promises39.writeFile)(file2, text3, "utf8");
118767
118852
  return file2;
118768
118853
  }
118769
118854
  function runCommand2(io, args, cwd, timeout2) {
@@ -118846,7 +118931,7 @@ Use bash_output with this ID to read new output and kill_shell to stop it.`;
118846
118931
  }
118847
118932
  async function execute(context, io, args, options) {
118848
118933
  const cwd = args.workdir ? resolvePath2(context.cwd, args.workdir) : context.cwd;
118849
- const workdirInfo = await (0, import_promises41.stat)(cwd).catch(() => void 0);
118934
+ const workdirInfo = await (0, import_promises39.stat)(cwd).catch(() => void 0);
118850
118935
  if (!workdirInfo?.isDirectory())
118851
118936
  throw new ToolFailure(`Working directory does not exist: ${cwd}`);
118852
118937
  if (args.run_in_background === true) {
@@ -118903,13 +118988,13 @@ function createBashTool(cwd, shells, options = {}) {
118903
118988
  execute: (args, api, context) => runDurable({ cwd, shells }, api, context, (tool, io) => execute(tool, io, args, options))
118904
118989
  });
118905
118990
  }
118906
- var import_node_child_process14, import_node_crypto32, import_promises41, import_node_os6, import_node_path42, MAX_METADATA_LENGTH, DETAILS_INTERVAL_MS, KILL_GRACE_MS, OUTPUT_DIR, HEAD_CHARS, TAIL_CHARS;
118991
+ var import_node_child_process14, import_node_crypto26, import_promises39, import_node_os6, import_node_path42, MAX_METADATA_LENGTH, DETAILS_INTERVAL_MS, KILL_GRACE_MS, OUTPUT_DIR, HEAD_CHARS, TAIL_CHARS;
118907
118992
  var init_bash = __esm({
118908
118993
  "../alan-engine/src/tools/bash.ts"() {
118909
118994
  "use strict";
118910
118995
  import_node_child_process14 = require("node:child_process");
118911
- import_node_crypto32 = require("node:crypto");
118912
- import_promises41 = require("node:fs/promises");
118996
+ import_node_crypto26 = require("node:crypto");
118997
+ import_promises39 = require("node:fs/promises");
118913
118998
  import_node_os6 = __toESM(require("node:os"), 1);
118914
118999
  import_node_path42 = __toESM(require("node:path"), 1);
118915
119000
  init_dist4();
@@ -118930,14 +119015,14 @@ var init_bash = __esm({
118930
119015
 
118931
119016
  // ../alan-engine/src/tools/background-shells.ts
118932
119017
  function newShellId() {
118933
- return `shell_${(0, import_node_crypto33.randomBytes)(4).toString("hex")}`;
119018
+ return `shell_${(0, import_node_crypto27.randomBytes)(4).toString("hex")}`;
118934
119019
  }
118935
- var import_node_child_process15, import_node_crypto33, import_node_fs23, import_node_path43, UNREAD_LIMIT_CHARS, RETAINED_FINISHED, UnknownBackgroundShell, BackgroundShells;
119020
+ var import_node_child_process15, import_node_crypto27, import_node_fs23, import_node_path43, UNREAD_LIMIT_CHARS, RETAINED_FINISHED, UnknownBackgroundShell, BackgroundShells;
118936
119021
  var init_background_shells = __esm({
118937
119022
  "../alan-engine/src/tools/background-shells.ts"() {
118938
119023
  "use strict";
118939
119024
  import_node_child_process15 = require("node:child_process");
118940
- import_node_crypto33 = require("node:crypto");
119025
+ import_node_crypto27 = require("node:crypto");
118941
119026
  import_node_fs23 = require("node:fs");
118942
119027
  import_node_path43 = __toESM(require("node:path"), 1);
118943
119028
  init_bash();
@@ -119208,27 +119293,27 @@ function withLineEnding(edit, ending) {
119208
119293
  };
119209
119294
  }
119210
119295
  async function applyEdit(context, io, filepath, args) {
119211
- const info = await (0, import_promises42.stat)(filepath).catch(() => void 0);
119296
+ const info = await (0, import_promises40.stat)(filepath).catch(() => void 0);
119212
119297
  const [first] = args.edits;
119213
119298
  if (first !== void 0 && first.oldString === "" && args.edits.length === 1) {
119214
119299
  if (info) throw new ToolFailure(EMPTY_OLD_STRING_MESSAGE);
119215
119300
  io.abortSignal?.throwIfAborted();
119216
- await (0, import_promises42.mkdir)(import_node_path44.default.dirname(filepath), { recursive: true });
119217
- await (0, import_promises42.writeFile)(filepath, first.newString, "utf8");
119301
+ await (0, import_promises40.mkdir)(import_node_path44.default.dirname(filepath), { recursive: true });
119302
+ await (0, import_promises40.writeFile)(filepath, first.newString, "utf8");
119218
119303
  await recordFileStamp(context, filepath);
119219
119304
  return { before: "", after: first.newString };
119220
119305
  }
119221
119306
  if (!info) throw new ToolFailure(`File ${filepath} not found`);
119222
119307
  if (info.isDirectory()) throw new ToolFailure(`Path is a directory, not a file: ${filepath}`);
119223
119308
  await assertUnchangedSinceRead(context, filepath, info);
119224
- const before = await (0, import_promises42.readFile)(filepath, "utf8");
119309
+ const before = await (0, import_promises40.readFile)(filepath, "utf8");
119225
119310
  const ending = detectLineEnding(before);
119226
119311
  const after = applyReplacements(
119227
119312
  before,
119228
119313
  args.edits.map((edit) => withLineEnding(edit, ending))
119229
119314
  );
119230
119315
  io.abortSignal?.throwIfAborted();
119231
- await (0, import_promises42.writeFile)(filepath, after, "utf8");
119316
+ await (0, import_promises40.writeFile)(filepath, after, "utf8");
119232
119317
  await recordFileStamp(context, filepath);
119233
119318
  return { before, after };
119234
119319
  }
@@ -119256,11 +119341,11 @@ function createEditTool(cwd) {
119256
119341
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute2(tool, io, args))
119257
119342
  });
119258
119343
  }
119259
- var import_promises42, import_node_path44, editTool;
119344
+ var import_promises40, import_node_path44, editTool;
119260
119345
  var init_edit2 = __esm({
119261
119346
  "../alan-engine/src/tools/edit.ts"() {
119262
119347
  "use strict";
119263
- import_promises42 = require("node:fs/promises");
119348
+ import_promises40 = require("node:fs/promises");
119264
119349
  import_node_path44 = __toESM(require("node:path"), 1);
119265
119350
  init_dist4();
119266
119351
  init_diff();
@@ -119306,7 +119391,7 @@ async function syntaxProblem(filepath) {
119306
119391
  const extension = import_node_path45.default.extname(filepath).toLowerCase();
119307
119392
  if (extension === ".py") return pythonProblem(filepath);
119308
119393
  if (!TS_EXTENSIONS.has(extension) && extension !== ".json") return void 0;
119309
- const source = await (0, import_promises43.readFile)(filepath, "utf8").catch(() => void 0);
119394
+ const source = await (0, import_promises41.readFile)(filepath, "utf8").catch(() => void 0);
119310
119395
  if (source === void 0) return void 0;
119311
119396
  if (extension !== ".json") return typeScriptProblem(source);
119312
119397
  try {
@@ -119358,12 +119443,12 @@ function withBudgetReminder(tools) {
119358
119443
  })
119359
119444
  );
119360
119445
  }
119361
- var import_node_child_process16, import_promises43, import_node_module, import_node_path45, TOOL_EXPERIMENTS, SYNTAX_TIMEOUT_MS, TS_EXTENSIONS, PY_PARSE, BUDGET_FIRST_REMINDER, BUDGET_REMINDER_EVERY;
119446
+ var import_node_child_process16, import_promises41, import_node_module, import_node_path45, TOOL_EXPERIMENTS, SYNTAX_TIMEOUT_MS, TS_EXTENSIONS, PY_PARSE, BUDGET_FIRST_REMINDER, BUDGET_REMINDER_EVERY;
119362
119447
  var init_experiments = __esm({
119363
119448
  "../alan-engine/src/tools/experiments.ts"() {
119364
119449
  "use strict";
119365
119450
  import_node_child_process16 = require("node:child_process");
119366
- import_promises43 = require("node:fs/promises");
119451
+ import_promises41 = require("node:fs/promises");
119367
119452
  import_node_module = require("node:module");
119368
119453
  import_node_path45 = __toESM(require("node:path"), 1);
119369
119454
  TOOL_EXPERIMENTS = [
@@ -119481,17 +119566,23 @@ var init_glob_match = __esm({
119481
119566
  });
119482
119567
 
119483
119568
  // ../alan-engine/src/tools/search.ts
119569
+ function isExecutable2(file2) {
119570
+ try {
119571
+ (0, import_node_fs24.accessSync)(file2, import_node_fs24.constants.X_OK);
119572
+ return true;
119573
+ } catch {
119574
+ return false;
119575
+ }
119576
+ }
119484
119577
  function findRipgrep() {
119485
119578
  if (ripgrepPath !== void 0) return ripgrepPath ?? void 0;
119486
119579
  const binary = process.platform === "win32" ? "rg.exe" : "rg";
119487
119580
  for (const dir of (process.env.PATH ?? "").split(import_node_path46.default.delimiter)) {
119488
119581
  if (!dir) continue;
119489
119582
  const candidate = import_node_path46.default.join(dir, binary);
119490
- try {
119491
- (0, import_node_fs24.accessSync)(candidate, import_node_fs24.constants.X_OK);
119583
+ if (isExecutable2(candidate)) {
119492
119584
  ripgrepPath = candidate;
119493
119585
  return candidate;
119494
- } catch {
119495
119586
  }
119496
119587
  }
119497
119588
  ripgrepPath = null;
@@ -119547,7 +119638,7 @@ function runRipgrep(binary, run3) {
119547
119638
  });
119548
119639
  }
119549
119640
  async function readIgnoreRules(root) {
119550
- const text3 = await (0, import_promises44.readFile)(import_node_path46.default.join(root, ".gitignore"), "utf8").catch(() => "");
119641
+ const text3 = await (0, import_promises42.readFile)(import_node_path46.default.join(root, ".gitignore"), "utf8").catch(() => "");
119551
119642
  const rules = [];
119552
119643
  for (const raw of text3.split(/\r?\n/)) {
119553
119644
  const line = raw.trim();
@@ -119569,7 +119660,7 @@ async function* walkFiles(root, options) {
119569
119660
  while (stack.length > 0) {
119570
119661
  options.signal?.throwIfAborted();
119571
119662
  const relativeDir = stack.pop() ?? "";
119572
- const entries2 = await (0, import_promises44.readdir)(import_node_path46.default.join(root, relativeDir), { withFileTypes: true }).catch(
119663
+ const entries2 = await (0, import_promises42.readdir)(import_node_path46.default.join(root, relativeDir), { withFileTypes: true }).catch(
119573
119664
  () => []
119574
119665
  );
119575
119666
  entries2.sort((a, b) => a.name.localeCompare(b.name));
@@ -119592,13 +119683,13 @@ async function* walkFiles(root, options) {
119592
119683
  for (let i = directories.length - 1; i >= 0; i--) stack.push(directories[i]);
119593
119684
  }
119594
119685
  }
119595
- var import_node_child_process17, import_node_fs24, import_promises44, import_node_path46, import_node_readline, ALWAYS_SKIPPED, ripgrepPath;
119686
+ var import_node_child_process17, import_node_fs24, import_promises42, import_node_path46, import_node_readline, ALWAYS_SKIPPED, ripgrepPath;
119596
119687
  var init_search2 = __esm({
119597
119688
  "../alan-engine/src/tools/search.ts"() {
119598
119689
  "use strict";
119599
119690
  import_node_child_process17 = require("node:child_process");
119600
119691
  import_node_fs24 = require("node:fs");
119601
- import_promises44 = require("node:fs/promises");
119692
+ import_promises42 = require("node:fs/promises");
119602
119693
  import_node_path46 = __toESM(require("node:path"), 1);
119603
119694
  import_node_readline = require("node:readline");
119604
119695
  init_glob_match();
@@ -119630,7 +119721,7 @@ async function findFiles(root, pattern, signal) {
119630
119721
  }
119631
119722
  async function execute3(context, io, args) {
119632
119723
  const search = resolvePath2(context.cwd, args.path ?? ".");
119633
- const info = await (0, import_promises45.stat)(search).catch(() => void 0);
119724
+ const info = await (0, import_promises43.stat)(search).catch(() => void 0);
119634
119725
  if (info?.isFile()) throw new ToolFailure(`glob path must be a directory: ${search}`);
119635
119726
  if (!info) throw new ToolFailure(`Directory not found: ${search}`);
119636
119727
  const files = await findFiles(search, args.pattern, io.abortSignal);
@@ -119658,11 +119749,11 @@ function createGlobTool(cwd) {
119658
119749
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute3(tool, io, args))
119659
119750
  });
119660
119751
  }
119661
- var import_promises45, import_node_path47, LIMIT, globTool;
119752
+ var import_promises43, import_node_path47, LIMIT, globTool;
119662
119753
  var init_glob = __esm({
119663
119754
  "../alan-engine/src/tools/glob.ts"() {
119664
119755
  "use strict";
119665
- import_promises45 = require("node:fs/promises");
119756
+ import_promises43 = require("node:fs/promises");
119666
119757
  import_node_path47 = __toESM(require("node:path"), 1);
119667
119758
  init_dist4();
119668
119759
  init_durable();
@@ -119703,7 +119794,7 @@ function isBinaryFile(filepath, bytes2) {
119703
119794
  }
119704
119795
  async function readSample(filepath, size) {
119705
119796
  if (size === 0) return new Uint8Array();
119706
- const handle = await (0, import_promises46.open)(filepath, "r");
119797
+ const handle = await (0, import_promises44.open)(filepath, "r");
119707
119798
  try {
119708
119799
  const buffer = Buffer.alloc(Math.min(SAMPLE_BYTES, size));
119709
119800
  const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
@@ -119715,7 +119806,7 @@ async function readSample(filepath, size) {
119715
119806
  async function missing(filepath) {
119716
119807
  const dir = import_node_path48.default.dirname(filepath);
119717
119808
  const base = import_node_path48.default.basename(filepath).toLowerCase();
119718
- const suggestions = await (0, import_promises46.readdir)(dir).then(
119809
+ const suggestions = await (0, import_promises44.readdir)(dir).then(
119719
119810
  (items) => items.filter((item) => item.toLowerCase().includes(base) || base.includes(item.toLowerCase())).map((item) => import_node_path48.default.join(dir, item)).slice(0, 3)
119720
119811
  ).catch(() => []);
119721
119812
  if (suggestions.length > 0) {
@@ -119729,12 +119820,12 @@ ${suggestions.join("\n")}`
119729
119820
  throw new ToolFailure(`File not found: ${filepath}`);
119730
119821
  }
119731
119822
  async function listDirectory(dirpath) {
119732
- const entries2 = await (0, import_promises46.readdir)(dirpath, { withFileTypes: true });
119823
+ const entries2 = await (0, import_promises44.readdir)(dirpath, { withFileTypes: true });
119733
119824
  const names2 = await Promise.all(
119734
119825
  entries2.map(async (entry2) => {
119735
119826
  if (entry2.isDirectory()) return `${entry2.name}/`;
119736
119827
  if (!entry2.isSymbolicLink()) return entry2.name;
119737
- const target = await (0, import_promises46.stat)(import_node_path48.default.join(dirpath, entry2.name)).catch(() => void 0);
119828
+ const target = await (0, import_promises44.stat)(import_node_path48.default.join(dirpath, entry2.name)).catch(() => void 0);
119738
119829
  return target?.isDirectory() ? `${entry2.name}/` : entry2.name;
119739
119830
  })
119740
119831
  );
@@ -119818,7 +119909,7 @@ async function readImage(io, filepath, title, mimeType, size) {
119818
119909
  details: { title, preview: message2, truncated: false }
119819
119910
  };
119820
119911
  }
119821
- const data = (await (0, import_promises46.readFile)(filepath)).toString("base64");
119912
+ const data = (await (0, import_promises44.readFile)(filepath)).toString("base64");
119822
119913
  const message = "Image read successfully";
119823
119914
  return {
119824
119915
  output: [
@@ -119873,7 +119964,7 @@ async function readText2(filepath, title, args, call) {
119873
119964
  async function execute4(context, io, args) {
119874
119965
  const filepath = resolvePath2(context.cwd, args.filePath);
119875
119966
  const title = relativeTitle(context.cwd, filepath);
119876
- const info = await (0, import_promises46.stat)(filepath).catch(() => void 0);
119967
+ const info = await (0, import_promises44.stat)(filepath).catch(() => void 0);
119877
119968
  if (!info) return missing(filepath);
119878
119969
  if (info.isDirectory()) return readDirectory(filepath, title, args);
119879
119970
  const sample = await readSample(filepath, info.size);
@@ -119899,12 +119990,12 @@ function createReadTool(cwd) {
119899
119990
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute4(tool, io, args))
119900
119991
  });
119901
119992
  }
119902
- var import_node_fs25, import_promises46, import_node_path48, import_node_readline2, DEFAULT_READ_LIMIT, MAX_LINE_LENGTH, MAX_LINE_SUFFIX, MAX_BYTES, MAX_BYTES_LABEL, SAMPLE_BYTES, MAX_IMAGE_BYTES2, BINARY_EXTENSIONS, readTool2;
119993
+ var import_node_fs25, import_promises44, import_node_path48, import_node_readline2, DEFAULT_READ_LIMIT, MAX_LINE_LENGTH, MAX_LINE_SUFFIX, MAX_BYTES, MAX_BYTES_LABEL, SAMPLE_BYTES, MAX_IMAGE_BYTES2, BINARY_EXTENSIONS, readTool2;
119903
119994
  var init_read2 = __esm({
119904
119995
  "../alan-engine/src/tools/read.ts"() {
119905
119996
  "use strict";
119906
119997
  import_node_fs25 = require("node:fs");
119907
- import_promises46 = require("node:fs/promises");
119998
+ import_promises44 = require("node:fs/promises");
119908
119999
  import_node_path48 = __toESM(require("node:path"), 1);
119909
120000
  import_node_readline2 = require("node:readline");
119910
120001
  init_dist4();
@@ -119955,13 +120046,10 @@ var init_read2 = __esm({
119955
120046
  });
119956
120047
 
119957
120048
  // ../alan-engine/src/tools/grep.ts
119958
- function isRecord5(value2) {
119959
- return typeof value2 === "object" && value2 !== null;
119960
- }
119961
120049
  function isRipgrepMatch(value2) {
119962
- if (!isRecord5(value2) || value2.type !== "match" || !isRecord5(value2.data)) return false;
120050
+ if (!isObjectLike(value2) || value2.type !== "match" || !isObjectLike(value2.data)) return false;
119963
120051
  const { path: file2, lines: lines2, line_number } = value2.data;
119964
- return isRecord5(file2) && typeof file2.text === "string" && isRecord5(lines2) && typeof lines2.text === "string" && typeof line_number === "number";
120052
+ return isObjectLike(file2) && typeof file2.text === "string" && isObjectLike(lines2) && typeof lines2.text === "string" && typeof line_number === "number";
119965
120053
  }
119966
120054
  function clip(text3) {
119967
120055
  const line = text3.replace(/\r?\n$/, "");
@@ -120002,9 +120090,9 @@ async function searchWithRipgrep(binary, root, target, args, signal) {
120002
120090
  return matches;
120003
120091
  }
120004
120092
  async function searchFile(file2, regex, matches) {
120005
- const info = await (0, import_promises47.stat)(file2).catch(() => void 0);
120093
+ const info = await (0, import_promises45.stat)(file2).catch(() => void 0);
120006
120094
  if (!info?.isFile() || info.size > MAX_FALLBACK_FILE_BYTES) return;
120007
- const buffer = await (0, import_promises47.readFile)(file2).catch(() => void 0);
120095
+ const buffer = await (0, import_promises45.readFile)(file2).catch(() => void 0);
120008
120096
  if (!buffer || isBinaryFile(file2, buffer.subarray(0, 4096))) return;
120009
120097
  const lines2 = buffer.toString("utf8").split("\n");
120010
120098
  for (let index = 0; index < lines2.length && matches.length < LIMIT2; index++) {
@@ -120056,7 +120144,7 @@ function formatGrep(matches) {
120056
120144
  async function execute5(context, io, args) {
120057
120145
  if (!args.pattern) throw new ToolFailure("pattern is required");
120058
120146
  const requested = resolvePath2(context.cwd, args.path ?? ".");
120059
- const info = await (0, import_promises47.stat)(requested).catch(() => void 0);
120147
+ const info = await (0, import_promises45.stat)(requested).catch(() => void 0);
120060
120148
  if (!info) throw new ToolFailure(`Path not found: ${requested}`);
120061
120149
  const root = info.isDirectory() ? requested : import_node_path49.default.dirname(requested);
120062
120150
  const single = info.isDirectory() ? void 0 : requested;
@@ -120077,12 +120165,13 @@ function createGrepTool(cwd) {
120077
120165
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute5(tool, io, args))
120078
120166
  });
120079
120167
  }
120080
- var import_promises47, import_node_path49, LIMIT2, MAX_LINE_LENGTH2, MAX_FALLBACK_FILE_BYTES, grepTool;
120168
+ var import_promises45, import_node_path49, LIMIT2, MAX_LINE_LENGTH2, MAX_FALLBACK_FILE_BYTES, grepTool;
120081
120169
  var init_grep = __esm({
120082
120170
  "../alan-engine/src/tools/grep.ts"() {
120083
120171
  "use strict";
120084
- import_promises47 = require("node:fs/promises");
120172
+ import_promises45 = require("node:fs/promises");
120085
120173
  import_node_path49 = __toESM(require("node:path"), 1);
120174
+ init_type_guards();
120086
120175
  init_dist4();
120087
120176
  init_durable();
120088
120177
  init_glob_match();
@@ -120149,7 +120238,7 @@ ${render(".", 0)}`;
120149
120238
  }
120150
120239
  async function execute6(context, io, args) {
120151
120240
  const search = resolvePath2(context.cwd, args.path ?? ".");
120152
- const info = await (0, import_promises48.stat)(search).catch(() => void 0);
120241
+ const info = await (0, import_promises46.stat)(search).catch(() => void 0);
120153
120242
  if (!info) throw new ToolFailure(`Directory not found: ${search}`);
120154
120243
  if (!info.isDirectory()) throw new ToolFailure(`Path is not a directory: ${search}`);
120155
120244
  const files = await collectFiles(search, args.ignore ?? [], io.abortSignal);
@@ -120165,11 +120254,11 @@ function createListTool(cwd) {
120165
120254
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute6(tool, io, args))
120166
120255
  });
120167
120256
  }
120168
- var import_promises48, import_node_path50, IGNORE_PATTERNS, LIMIT3, listTool;
120257
+ var import_promises46, import_node_path50, IGNORE_PATTERNS, LIMIT3, listTool;
120169
120258
  var init_list = __esm({
120170
120259
  "../alan-engine/src/tools/list.ts"() {
120171
120260
  "use strict";
120172
- import_promises48 = require("node:fs/promises");
120261
+ import_promises46 = require("node:fs/promises");
120173
120262
  import_node_path50 = __toESM(require("node:path"), 1);
120174
120263
  init_dist4();
120175
120264
  init_durable();
@@ -120413,7 +120502,7 @@ async function execute7(skills, args, signal) {
120413
120502
  }
120414
120503
  const dir = info.packageDirectory;
120415
120504
  const location = import_node_path51.default.join(dir, "SKILL.md");
120416
- const markdown = await (0, import_promises49.readFile)(location, "utf8").catch((error62) => {
120505
+ const markdown = await (0, import_promises47.readFile)(location, "utf8").catch((error62) => {
120417
120506
  throw new ToolFailure(
120418
120507
  `Skill "${info.name}" has no readable SKILL.md at ${location}: ${String(error62)}`
120419
120508
  );
@@ -120446,11 +120535,11 @@ function createSkillTool(skills) {
120446
120535
  execute: (args, _api, context) => guard(context, () => execute7(skills, args, context.abortSignal))
120447
120536
  });
120448
120537
  }
120449
- var import_promises49, import_node_path51, DESCRIPTION2, MAX_LISTED_FILES, MAX_SEARCH_RESULTS, parameters2;
120538
+ var import_promises47, import_node_path51, DESCRIPTION2, MAX_LISTED_FILES, MAX_SEARCH_RESULTS, parameters2;
120450
120539
  var init_skill = __esm({
120451
120540
  "../alan-engine/src/tools/skill.ts"() {
120452
120541
  "use strict";
120453
- import_promises49 = require("node:fs/promises");
120542
+ import_promises47 = require("node:fs/promises");
120454
120543
  import_node_path51 = __toESM(require("node:path"), 1);
120455
120544
  init_dist4();
120456
120545
  init_build();
@@ -120793,9 +120882,6 @@ var init_webfetch = __esm({
120793
120882
  });
120794
120883
 
120795
120884
  // ../alan-engine/src/tools/websearch.ts
120796
- function isRecord6(value2) {
120797
- return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
120798
- }
120799
120885
  function parseJson2(text3) {
120800
120886
  try {
120801
120887
  return JSON.parse(text3);
@@ -120808,7 +120894,7 @@ function optionalString(value2) {
120808
120894
  }
120809
120895
  function readRefusal(text3) {
120810
120896
  const parsed = parseJson2(text3);
120811
- if (!isRecord6(parsed) || typeof parsed.error !== "string") return void 0;
120897
+ if (!isRecord(parsed) || typeof parsed.error !== "string") return void 0;
120812
120898
  const retryAfterSeconds = parsed.retryAfterSeconds;
120813
120899
  const resetsAt = optionalString(parsed.resetsAt);
120814
120900
  const requestId = optionalString(parsed.requestId);
@@ -120857,8 +120943,8 @@ function truncate4(text3, max) {
120857
120943
  return trimmed4.length <= max ? trimmed4 : `${trimmed4.slice(0, Math.max(0, max - 1))}\u2026`;
120858
120944
  }
120859
120945
  function hitsOf(body) {
120860
- if (!isRecord6(body) || !Array.isArray(body.results)) return [];
120861
- return body.results.filter(isRecord6).map((item) => ({
120946
+ if (!isRecord(body) || !Array.isArray(body.results)) return [];
120947
+ return body.results.filter(isRecord).map((item) => ({
120862
120948
  ...typeof item.url === "string" ? { url: item.url } : {},
120863
120949
  ...typeof item.title === "string" ? { title: item.title } : {},
120864
120950
  ...Array.isArray(item.excerpts) ? { excerpts: item.excerpts.filter((part) => typeof part === "string") } : {}
@@ -120900,7 +120986,7 @@ function createAlanWebSearch(source) {
120900
120986
  "Web search is unavailable: this session has no Alan credential. Continue without search."
120901
120987
  );
120902
120988
  }
120903
- const requestId = (0, import_node_crypto34.randomUUID)();
120989
+ const requestId = (0, import_node_crypto28.randomUUID)();
120904
120990
  for (let attempt = 0; ; attempt += 1) {
120905
120991
  const response = await fetch(`${baseURL}/public/harness/v1/websearch`, {
120906
120992
  method: "POST",
@@ -120949,11 +121035,12 @@ function createWebSearchTool(search) {
120949
121035
  )
120950
121036
  });
120951
121037
  }
120952
- var import_node_crypto34, DESCRIPTION4, MAX_RESULTS, MAX_AUTO_RETRIES2, MAX_AUTO_RETRY_WAIT_MS, parameters4;
121038
+ var import_node_crypto28, DESCRIPTION4, MAX_RESULTS, MAX_AUTO_RETRIES2, MAX_AUTO_RETRY_WAIT_MS, parameters4;
120953
121039
  var init_websearch = __esm({
120954
121040
  "../alan-engine/src/tools/websearch.ts"() {
120955
121041
  "use strict";
120956
- import_node_crypto34 = require("node:crypto");
121042
+ import_node_crypto28 = require("node:crypto");
121043
+ init_type_guards();
120957
121044
  init_dist4();
120958
121045
  init_build();
120959
121046
  init_credentials();
@@ -120973,14 +121060,14 @@ async function execute9(context, io, args) {
120973
121060
  const filepath = resolvePath2(context.cwd, args.filePath);
120974
121061
  const title = relativeTitle(context.cwd, filepath);
120975
121062
  return withFileLock(filepath, async () => {
120976
- const info = await (0, import_promises50.stat)(filepath).catch(() => void 0);
121063
+ const info = await (0, import_promises48.stat)(filepath).catch(() => void 0);
120977
121064
  if (info?.isDirectory()) throw new ToolFailure(`Path is a directory, not a file: ${filepath}`);
120978
121065
  const exists4 = info !== void 0;
120979
121066
  if (info !== void 0) await assertUnchangedSinceRead(context, filepath, info);
120980
- const before = exists4 ? await (0, import_promises50.readFile)(filepath, "utf8") : "";
121067
+ const before = exists4 ? await (0, import_promises48.readFile)(filepath, "utf8") : "";
120981
121068
  io.abortSignal?.throwIfAborted();
120982
- await (0, import_promises50.mkdir)(import_node_path52.default.dirname(filepath), { recursive: true });
120983
- await (0, import_promises50.writeFile)(filepath, args.content, "utf8");
121069
+ await (0, import_promises48.mkdir)(import_node_path52.default.dirname(filepath), { recursive: true });
121070
+ await (0, import_promises48.writeFile)(filepath, args.content, "utf8");
120984
121071
  await recordFileStamp(context, filepath);
120985
121072
  const stats = diffStats(before, args.content);
120986
121073
  return textResult2(exists4 ? "Wrote file successfully." : "Created file successfully.", {
@@ -120999,11 +121086,11 @@ function createWriteTool(cwd) {
120999
121086
  execute: (args, api, context) => runDurable({ cwd, shells: void 0 }, api, context, (tool, io) => execute9(tool, io, args))
121000
121087
  });
121001
121088
  }
121002
- var import_promises50, import_node_path52, writeTool;
121089
+ var import_promises48, import_node_path52, writeTool;
121003
121090
  var init_write = __esm({
121004
121091
  "../alan-engine/src/tools/write.ts"() {
121005
121092
  "use strict";
121006
- import_promises50 = require("node:fs/promises");
121093
+ import_promises48 = require("node:fs/promises");
121007
121094
  import_node_path52 = __toESM(require("node:path"), 1);
121008
121095
  init_dist4();
121009
121096
  init_diff();
@@ -121352,6 +121439,14 @@ function sessionPaths(dir, sessionId) {
121352
121439
  const root = (0, import_node_path54.join)(dir, sessionId);
121353
121440
  return { root, database: (0, import_node_path54.join)(root, "session.sqlite"), lock: (0, import_node_path54.join)(root, "session.lock") };
121354
121441
  }
121442
+ function deliver(listener, event) {
121443
+ try {
121444
+ listener(event);
121445
+ return true;
121446
+ } catch {
121447
+ return false;
121448
+ }
121449
+ }
121355
121450
  function webSearchOf(options) {
121356
121451
  const source = options.webSearch;
121357
121452
  if (source === false) {
@@ -121401,7 +121496,7 @@ async function openEngineSession(options) {
121401
121496
  if (options.maxTurns !== void 0 && (!Number.isInteger(options.maxTurns) || options.maxTurns < 1))
121402
121497
  throw new RangeError("maxTurns must be a positive integer");
121403
121498
  const paths = sessionPaths(options.dir, options.sessionId);
121404
- await (0, import_promises51.mkdir)(paths.root, { recursive: true });
121499
+ await (0, import_promises49.mkdir)(paths.root, { recursive: true });
121405
121500
  const lock = await acquireSessionLock(paths.lock);
121406
121501
  let mcp;
121407
121502
  try {
@@ -121438,11 +121533,11 @@ async function openEngineSession(options) {
121438
121533
  throw error62;
121439
121534
  }
121440
121535
  }
121441
- var import_promises51, import_node_path54, ctx, ENTRY_PAGE, USER_SHELL_ENTRY_KIND, DurableEngineSession;
121536
+ var import_promises49, import_node_path54, ctx, ENTRY_PAGE, USER_SHELL_ENTRY_KIND, DurableEngineSession;
121442
121537
  var init_session7 = __esm({
121443
121538
  "../alan-engine/src/engine/session.ts"() {
121444
121539
  "use strict";
121445
- import_promises51 = require("node:fs/promises");
121540
+ import_promises49 = require("node:fs/promises");
121446
121541
  import_node_path54 = require("node:path");
121447
121542
  init_context();
121448
121543
  init_dist4();
@@ -121540,12 +121635,7 @@ var init_session7 = __esm({
121540
121635
  this.#emit(event);
121541
121636
  }
121542
121637
  #emit(event) {
121543
- for (const listener of this.#listeners) {
121544
- try {
121545
- listener(event);
121546
- } catch {
121547
- }
121548
- }
121638
+ for (const listener of this.#listeners) deliver(listener, event);
121549
121639
  }
121550
121640
  #scheduleDeadline() {
121551
121641
  if (this.#deadline === void 0) return;
@@ -121809,7 +121899,7 @@ function isAlanPiSessionOf(ref, conversationId) {
121809
121899
  return ref === alanPiSessionRef(conversationId) || ref === conversationId;
121810
121900
  }
121811
121901
  function digest(text3) {
121812
- return (0, import_node_crypto35.createHash)("sha256").update(text3).digest("hex");
121902
+ return (0, import_node_crypto29.createHash)("sha256").update(text3).digest("hex");
121813
121903
  }
121814
121904
  function settledOutcome2(outcome2) {
121815
121905
  return outcome2.status;
@@ -121844,18 +121934,18 @@ async function trackNativeTurn(port, sessionRef, operation, text3) {
121844
121934
  async function attachNativeSession(observer, observation3) {
121845
121935
  await observer.attach({
121846
121936
  nativeSessionId: observation3.sessionRef,
121847
- epoch: (0, import_node_crypto35.randomUUID)(),
121937
+ epoch: (0, import_node_crypto29.randomUUID)(),
121848
121938
  version: ALAN_PI_IDENTITY_VERSION,
121849
121939
  empty: observation3.created,
121850
121940
  created: observation3.created,
121851
121941
  freshOwnedEngine: true
121852
121942
  });
121853
121943
  }
121854
- var import_node_crypto35, ALAN_PI_SESSION_REF_PREFIX, ALAN_PI_IDENTITY_VERSION;
121944
+ var import_node_crypto29, ALAN_PI_SESSION_REF_PREFIX, ALAN_PI_IDENTITY_VERSION;
121855
121945
  var init_alan_pi_identity = __esm({
121856
121946
  "src/holder/drivers/alan-pi-identity.ts"() {
121857
121947
  "use strict";
121858
- import_node_crypto35 = require("node:crypto");
121948
+ import_node_crypto29 = require("node:crypto");
121859
121949
  ALAN_PI_SESSION_REF_PREFIX = "alan-pi:v1:";
121860
121950
  ALAN_PI_IDENTITY_VERSION = "alan-pi-durable-1";
121861
121951
  }
@@ -122214,11 +122304,8 @@ var init_alan_pi_requests = __esm({
122214
122304
  });
122215
122305
 
122216
122306
  // src/holder/drivers/alan-pi-tools.ts
122217
- function isRecord7(value2) {
122218
- return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
122219
- }
122220
122307
  function field2(record3, key) {
122221
- const value2 = isRecord7(record3) ? record3[key] : void 0;
122308
+ const value2 = isRecord(record3) ? record3[key] : void 0;
122222
122309
  return typeof value2 === "string" ? value2.trim() : "";
122223
122310
  }
122224
122311
  function kindOf(name) {
@@ -122266,7 +122353,7 @@ function locationsOf(name, args, context) {
122266
122353
  const path19 = field2(args, "filePath") || field2(args, "path");
122267
122354
  if (path19 === "" || kindOf(name) === "execute" || kindOf(name) === "fetch") return void 0;
122268
122355
  const absolute = (0, import_node_path55.isAbsolute)(path19) ? path19 : (0, import_node_path55.resolve)(context.cwd, path19);
122269
- const offset = isRecord7(args) ? args.offset : void 0;
122356
+ const offset = isRecord(args) ? args.offset : void 0;
122270
122357
  return [typeof offset === "number" ? { path: absolute, line: offset } : { path: absolute }];
122271
122358
  }
122272
122359
  function questionOf(args) {
@@ -122280,7 +122367,7 @@ function questionOf(args) {
122280
122367
  const description2 = field2(option2, "description");
122281
122368
  return label3 === "" ? [] : [description2 === "" ? { label: label3 } : { label: label3, description: description2 }];
122282
122369
  }),
122283
- multiSelect: isRecord7(args) && args.multiple === true
122370
+ multiSelect: isRecord(args) && args.multiple === true
122284
122371
  };
122285
122372
  }
122286
122373
  function toolStartUpdate(toolCallId, name, args, context) {
@@ -122302,10 +122389,10 @@ function toolStartUpdate(toolCallId, name, args, context) {
122302
122389
  function fileChange2(result) {
122303
122390
  if (result.isError || result.toolName !== "edit" && result.toolName !== "write") return [];
122304
122391
  const path19 = field2(result.details, "filepath");
122305
- const diff = isRecord7(result.details) ? result.details.diff : void 0;
122392
+ const diff = isRecord(result.details) ? result.details.diff : void 0;
122306
122393
  const patchText = typeof diff === "string" ? diff : "";
122307
122394
  if (path19 === "") return [];
122308
- const created = result.toolName === "write" && isRecord7(result.details) && result.details.exists === false;
122395
+ const created = result.toolName === "write" && isRecord(result.details) && result.details.exists === false;
122309
122396
  return [
122310
122397
  fileChangeContent({
122311
122398
  path: path19,
@@ -122323,7 +122410,7 @@ function planUpdate(result) {
122323
122410
  if (result.isError || result.toolName !== "todowrite" && result.toolName !== "todoread") {
122324
122411
  return [];
122325
122412
  }
122326
- const todos = isRecord7(result.details) ? result.details.todos : void 0;
122413
+ const todos = isRecord(result.details) ? result.details.todos : void 0;
122327
122414
  return Array.isArray(todos) ? [todoPlanUpdate(result.toolCallId, todos)] : [];
122328
122415
  }
122329
122416
  function toolEndUpdates(result, context) {
@@ -122349,6 +122436,7 @@ var init_alan_pi_tools = __esm({
122349
122436
  "use strict";
122350
122437
  import_node_path55 = require("node:path");
122351
122438
  init_acp2();
122439
+ init_type_guards();
122352
122440
  TASK_RESULT = /^<(task_result|task_error)>\n?([\s\S]*?)\n?<\/\1>$/;
122353
122441
  KINDS = {
122354
122442
  bash_output: "execute",
@@ -122442,6 +122530,10 @@ var init_alan_pi_updates = __esm({
122442
122530
  this.#textOpen = false;
122443
122531
  this.#ended.add(event.toolCallId);
122444
122532
  return toolEndUpdates(event, this.#context);
122533
+ case "input_placed":
122534
+ this.#textOpen = false;
122535
+ this.#thoughtOpen = false;
122536
+ return [];
122445
122537
  default:
122446
122538
  return [];
122447
122539
  }
@@ -122617,6 +122709,8 @@ var init_alan_pi_session = __esm({
122617
122709
  shell: new AbortController(),
122618
122710
  updates: new AlanPiTurnUpdates(input2.turnId, this.#options.engine.cwd),
122619
122711
  steers: /* @__PURE__ */ new Map(),
122712
+ unplacedSteers: /* @__PURE__ */ new Map(),
122713
+ placedInputs: /* @__PURE__ */ new Set(),
122620
122714
  runs: { started: 0, ended: 0 },
122621
122715
  settling: false,
122622
122716
  cancelRequested: false,
@@ -122759,7 +122853,9 @@ var init_alan_pi_session = __esm({
122759
122853
  });
122760
122854
  turn.steers.set(input2.steerId, submitted);
122761
122855
  try {
122762
- await submitted;
122856
+ const { id } = await submitted;
122857
+ if (turn.placedInputs.has(id)) this.#steerPlaced(turn, input2.steerId);
122858
+ else turn.unplacedSteers.set(id, input2.steerId);
122763
122859
  } catch (error62) {
122764
122860
  turn.steers.delete(input2.steerId);
122765
122861
  this.#options.log.warn("alan_pi.steer_failed", { turnId: turn.id, error: String(error62) });
@@ -122767,7 +122863,6 @@ var init_alan_pi_session = __esm({
122767
122863
  }
122768
122864
  return "delivered";
122769
122865
  }
122770
- /** Answers a parked approval or question; throws when it is no longer waiting. */
122771
122866
  async respond(toolCallId, answer2) {
122772
122867
  const request3 = this.#requests.get(toolCallId);
122773
122868
  if (request3 === void 0) throw new Error(`Alan Code is not waiting on ${toolCallId}`);
@@ -122885,11 +122980,26 @@ var init_alan_pi_session = __esm({
122885
122980
  case "request_settled":
122886
122981
  this.#requestSettled(turn, event);
122887
122982
  return;
122983
+ case "input_placed":
122984
+ this.#inputPlaced(turn, event.submissionId);
122985
+ break;
122888
122986
  default:
122889
122987
  break;
122890
122988
  }
122891
122989
  for (const update of turn.updates.map(event)) this.#update(turn, update);
122892
122990
  }
122991
+ #inputPlaced(turn, submissionId) {
122992
+ const steerId = turn.unplacedSteers.get(submissionId);
122993
+ if (steerId === void 0) {
122994
+ turn.placedInputs.add(submissionId);
122995
+ return;
122996
+ }
122997
+ turn.unplacedSteers.delete(submissionId);
122998
+ this.#steerPlaced(turn, steerId);
122999
+ }
123000
+ #steerPlaced(turn, steerId) {
123001
+ this.#emit({ type: "steer_placed", turnId: turn.id, steerId });
123002
+ }
122893
123003
  #park(turn, request3) {
122894
123004
  const cardId = requestCardId(request3);
122895
123005
  this.#requests.set(cardId, request3);
@@ -123032,7 +123142,7 @@ function alanMcpServer(managedMcp, conversationId) {
123032
123142
  }
123033
123143
  async function exists2(path19) {
123034
123144
  try {
123035
- await (0, import_promises52.access)(path19);
123145
+ await (0, import_promises50.access)(path19);
123036
123146
  return true;
123037
123147
  } catch {
123038
123148
  return false;
@@ -123216,11 +123326,11 @@ function createAlanPiHolderDriver(options) {
123216
123326
  }
123217
123327
  };
123218
123328
  }
123219
- var import_promises52, SAFE_COMMANDS, NO_CREDENTIAL;
123329
+ var import_promises50, SAFE_COMMANDS, NO_CREDENTIAL;
123220
123330
  var init_alan_pi = __esm({
123221
123331
  "src/holder/drivers/alan-pi.ts"() {
123222
123332
  "use strict";
123223
- import_promises52 = require("node:fs/promises");
123333
+ import_promises50 = require("node:fs/promises");
123224
123334
  init_src();
123225
123335
  init_classify2();
123226
123336
  init_mcp2();
@@ -123485,7 +123595,7 @@ __export(codex_exports, {
123485
123595
  createCodexHolderDriver: () => createCodexHolderDriver
123486
123596
  });
123487
123597
  function sha2563(value2) {
123488
- return (0, import_node_crypto36.createHash)("sha256").update(value2).digest("hex");
123598
+ return (0, import_node_crypto30.createHash)("sha256").update(value2).digest("hex");
123489
123599
  }
123490
123600
  function createCodexLogin(broker) {
123491
123601
  const state2 = {};
@@ -123565,11 +123675,11 @@ function createCodexHolderDriver(options) {
123565
123675
  }
123566
123676
  );
123567
123677
  }
123568
- var import_node_crypto36;
123678
+ var import_node_crypto30;
123569
123679
  var init_codex2 = __esm({
123570
123680
  "src/holder/drivers/codex.ts"() {
123571
123681
  "use strict";
123572
- import_node_crypto36 = require("node:crypto");
123682
+ import_node_crypto30 = require("node:crypto");
123573
123683
  init_src();
123574
123684
  init_codex();
123575
123685
  init_persistent();
@@ -123693,7 +123803,7 @@ function parseConfig(raw) {
123693
123803
  }
123694
123804
  async function writeCommandCodeProjectMcp(cwd, mcp) {
123695
123805
  const path19 = (0, import_node_path57.join)(cwd, ".mcp.json");
123696
- const original = await (0, import_promises53.readFile)(path19, "utf8").catch(() => null);
123806
+ const original = await (0, import_promises51.readFile)(path19, "utf8").catch(() => null);
123697
123807
  const config2 = parseConfig(original);
123698
123808
  const next = {
123699
123809
  ...config2,
@@ -123710,19 +123820,19 @@ async function writeCommandCodeProjectMcp(cwd, mcp) {
123710
123820
  }
123711
123821
  }
123712
123822
  };
123713
- await (0, import_promises53.mkdir)(cwd, { recursive: true });
123714
- await (0, import_promises53.writeFile)(path19, `${JSON.stringify(next, null, 2)}
123823
+ await (0, import_promises51.mkdir)(cwd, { recursive: true });
123824
+ await (0, import_promises51.writeFile)(path19, `${JSON.stringify(next, null, 2)}
123715
123825
  `);
123716
123826
  return async () => {
123717
- if (original === null) await (0, import_promises53.rm)(path19, { force: true });
123718
- else await (0, import_promises53.writeFile)(path19, original);
123827
+ if (original === null) await (0, import_promises51.rm)(path19, { force: true });
123828
+ else await (0, import_promises51.writeFile)(path19, original);
123719
123829
  };
123720
123830
  }
123721
- var import_promises53, import_node_path57;
123831
+ var import_promises51, import_node_path57;
123722
123832
  var init_project_mcp = __esm({
123723
123833
  "../agent-core/src/providers/command-code/project-mcp.ts"() {
123724
123834
  "use strict";
123725
- import_promises53 = require("node:fs/promises");
123835
+ import_promises51 = require("node:fs/promises");
123726
123836
  import_node_path57 = require("node:path");
123727
123837
  init_agent2();
123728
123838
  init_runtime_v2();
@@ -124017,10 +124127,7 @@ var init_background_tasks2 = __esm({
124017
124127
  }
124018
124128
  return updates;
124019
124129
  }
124020
- /**
124021
- * The CLI exited: its subagents died with it, and its shells can no longer be observed.
124022
- * A shell whose process is still there really is still running, so it keeps its status.
124023
- */
124130
+ // quirk: its subagents die with the CLI and its shells cannot be observed; a shell whose process is still there keeps its status.
124024
124131
  afterExit() {
124025
124132
  const updates = [];
124026
124133
  for (const [launcher, task] of this.#tasks) {
@@ -124201,7 +124308,6 @@ var init_turn7 = __esm({
124201
124308
  return [...this.#onResult(frame.event), ...updates, ...background];
124202
124309
  return [...updates, ...frame.event ? this.#onEvent(frame.event) : [], ...background];
124203
124310
  }
124204
- /** The CLI is gone, so its shells can no longer be watched: settle the ones that ended. */
124205
124311
  afterExit() {
124206
124312
  return this.#background.afterExit();
124207
124313
  }
@@ -124377,11 +124483,6 @@ var init_driver8 = __esm({
124377
124483
  });
124378
124484
 
124379
124485
  // ../agent-core/src/providers/command-code/run.ts
124380
- function envDigest8(env) {
124381
- const hash2 = (0, import_node_crypto37.createHash)("sha256");
124382
- for (const key of Object.keys(env).sort()) hash2.update(`${key}\0${env[key]}\0`);
124383
- return hash2.digest("hex");
124384
- }
124385
124486
  function permissionsOf(run3) {
124386
124487
  if (!isReadOnlyMode(run3.mode) && !isReadOnlyAgent(run3.agentId)) return "yolo";
124387
124488
  return run3.mode === "plan" || run3.mode === "review" ? "plan" : "default";
@@ -124405,8 +124506,7 @@ function planCommandCodeSession(run3, context) {
124405
124506
  cwd: context.cwd,
124406
124507
  env,
124407
124508
  ...shape,
124408
- ...prompts.systemPrompt ? { systemPrompt: prompts.systemPrompt } : {},
124409
- ...prompts.systemPromptAppend ? { systemPromptAppend: prompts.systemPromptAppend } : {},
124509
+ ...systemPromptFields(prompts),
124410
124510
  ...context.resumeSessionId ? { resumeSessionId: context.resumeSessionId } : {},
124411
124511
  ...managed ? { mcp: { url: managed.url, conversationId: run3.conversationId } } : {}
124412
124512
  };
@@ -124419,26 +124519,17 @@ function planCommandCodeSession(run3, context) {
124419
124519
  cwd: context.cwd,
124420
124520
  shape,
124421
124521
  mcp: managed ? { url: managed.url, credential: credentialDigest(managed.authorization) } : null,
124422
- env: envDigest8(cliEnv)
124522
+ env: envDigest(cliEnv)
124423
124523
  });
124424
124524
  return { spec, key, skippedMcpEnvKeys: [], skippedMcpServers };
124425
124525
  }
124426
124526
  function commandCodeTurnInput(run3, context) {
124427
- const images = context.attachments.filter((attachment) => attachment.kind === "image");
124428
- const files = context.attachments.filter((attachment) => attachment.kind === "file");
124429
- const text3 = buildTurnText({
124430
- spec: run3,
124431
- files,
124432
- skills: context.skills,
124433
- ...context.contextPrefix === void 0 ? {} : { contextPrefix: context.contextPrefix }
124434
- });
124527
+ const { text: text3, images } = buildAttachmentTurnText(run3, context);
124435
124528
  return { turnId: run3.runId, text: appendImagePathReferences(text3, images) };
124436
124529
  }
124437
- var import_node_crypto37;
124438
124530
  var init_run7 = __esm({
124439
124531
  "../agent-core/src/providers/command-code/run.ts"() {
124440
124532
  "use strict";
124441
- import_node_crypto37 = require("node:crypto");
124442
124533
  init_agent2();
124443
124534
  init_mcp2();
124444
124535
  init_prompt();
@@ -125632,18 +125723,18 @@ function createConversationMcpAuthorization(options) {
125632
125723
  }
125633
125724
 
125634
125725
  // src/holder/mcp-helper-access.ts
125635
- var import_promises54 = require("node:fs/promises");
125726
+ var import_promises52 = require("node:fs/promises");
125636
125727
  init_kernel();
125637
125728
  function createHelperMcpAccess(options) {
125638
125729
  return {
125639
125730
  [Symbol.asyncDispose]: async () => {
125640
- await (0, import_promises54.rm)(options.credentialPath, { force: true });
125731
+ await (0, import_promises52.rm)(options.credentialPath, { force: true });
125641
125732
  },
125642
125733
  url: options.managedMcp.url,
125643
125734
  authorization: async (signal) => {
125644
125735
  const authorization = await options.managedMcp.authorization(signal);
125645
125736
  if (authorization === void 0 || signal.aborted) {
125646
- await (0, import_promises54.rm)(options.credentialPath, { force: true });
125737
+ await (0, import_promises52.rm)(options.credentialPath, { force: true });
125647
125738
  return void 0;
125648
125739
  }
125649
125740
  const credential = {
@@ -125658,8 +125749,8 @@ function createHelperMcpAccess(options) {
125658
125749
  }
125659
125750
 
125660
125751
  // src/holder/native-turn-bindings.ts
125661
- var import_node_crypto38 = require("node:crypto");
125662
- var import_promises56 = require("node:fs/promises");
125752
+ var import_node_crypto31 = require("node:crypto");
125753
+ var import_promises54 = require("node:fs/promises");
125663
125754
  var import_node_path60 = require("node:path");
125664
125755
  init_runtime_v2();
125665
125756
  init_zod();
@@ -125668,7 +125759,7 @@ init_platform();
125668
125759
  init_alan_pi_identity();
125669
125760
 
125670
125761
  // src/holder/prepared-session-state.ts
125671
- var import_promises55 = require("node:fs/promises");
125762
+ var import_promises53 = require("node:fs/promises");
125672
125763
  var import_node_path59 = require("node:path");
125673
125764
  init_runtime_v2();
125674
125765
  init_zod();
@@ -125706,8 +125797,8 @@ async function writePreparedIdentity(directory, binding, providerSessionId) {
125706
125797
  binding,
125707
125798
  providerSessionId
125708
125799
  });
125709
- await (0, import_promises55.mkdir)(directory, { recursive: true, mode: 448 });
125710
- await (0, import_promises55.chmod)(directory, 448);
125800
+ await (0, import_promises53.mkdir)(directory, { recursive: true, mode: 448 });
125801
+ await (0, import_promises53.chmod)(directory, 448);
125711
125802
  await writeJsonFileAtomic((0, import_node_path59.join)(directory, "engine-session.json"), value2);
125712
125803
  await createMetadataDurability().sync(directory);
125713
125804
  }
@@ -125789,7 +125880,7 @@ var bindingSchema = external_exports.strictObject({
125789
125880
  }).optional()
125790
125881
  });
125791
125882
  function digest2(value2) {
125792
- return (0, import_node_crypto38.createHash)("sha256").update(JSON.stringify(value2)).digest("hex");
125883
+ return (0, import_node_crypto31.createHash)("sha256").update(JSON.stringify(value2)).digest("hex");
125793
125884
  }
125794
125885
  function unavailable2() {
125795
125886
  return new Error("Native identity requires explicit recovery");
@@ -125946,15 +126037,15 @@ async function openNativeTurnBindings(options) {
125946
126037
  const { directory, machineId, conversationId } = options;
125947
126038
  const runDirectory2 = (0, import_node_path60.join)(directory, "native-turn-bindings");
125948
126039
  const orderPath = (0, import_node_path60.join)(directory, "native-message-order.json");
125949
- await (0, import_promises56.mkdir)(runDirectory2, { recursive: true, mode: 448 });
125950
- await (0, import_promises56.chmod)(directory, 448);
125951
- await (0, import_promises56.chmod)(runDirectory2, 448);
126040
+ await (0, import_promises54.mkdir)(runDirectory2, { recursive: true, mode: 448 });
126041
+ await (0, import_promises54.chmod)(directory, 448);
126042
+ await (0, import_promises54.chmod)(runDirectory2, 448);
125952
126043
  await createMetadataDurability().sync(directory);
125953
126044
  const stored = await readJsonFile(orderPath, projectionSchema);
125954
126045
  if (stored.kind === "invalid") throw unavailable2();
125955
126046
  let projection = stored.kind === "ok" ? stored.value : void 0;
125956
126047
  const unresolved = /* @__PURE__ */ new Set();
125957
- const names2 = await (0, import_promises56.readdir)(runDirectory2);
126048
+ const names2 = await (0, import_promises54.readdir)(runDirectory2);
125958
126049
  for (const name of names2.filter((entry2) => entry2.endsWith(".json"))) {
125959
126050
  const item = await readJsonFile((0, import_node_path60.join)(runDirectory2, name), bindingSchema);
125960
126051
  if (item.kind !== "ok" || item.value.machineId !== machineId || item.value.conversationId !== conversationId || name !== `${item.value.runId}.json`)
@@ -126099,25 +126190,25 @@ async function openNativeTurnBindings(options) {
126099
126190
  }
126100
126191
 
126101
126192
  // src/holder/requested-checkout.ts
126102
- var import_promises58 = require("node:fs/promises");
126193
+ var import_promises56 = require("node:fs/promises");
126103
126194
  var import_node_path62 = require("node:path");
126104
126195
  init_capabilities3();
126105
126196
 
126106
126197
  // src/holder/claim-once.ts
126107
- var import_node_crypto39 = require("node:crypto");
126108
- var import_promises57 = require("node:fs/promises");
126198
+ var import_node_crypto32 = require("node:crypto");
126199
+ var import_promises55 = require("node:fs/promises");
126109
126200
  var import_node_path61 = require("node:path");
126110
126201
  async function claimOnce(dir, name) {
126111
126202
  try {
126112
- await (0, import_promises57.mkdir)(dir, { recursive: true, mode: 448 });
126113
- await (await (0, import_promises57.open)((0, import_node_path61.join)(dir, name), "wx")).close();
126203
+ await (0, import_promises55.mkdir)(dir, { recursive: true, mode: 448 });
126204
+ await (await (0, import_promises55.open)((0, import_node_path61.join)(dir, name), "wx")).close();
126114
126205
  return true;
126115
126206
  } catch {
126116
126207
  return false;
126117
126208
  }
126118
126209
  }
126119
126210
  function claimFirstLease(freshnessDir, path19) {
126120
- return claimOnce((0, import_node_path61.join)(freshnessDir, "leased"), (0, import_node_crypto39.createHash)("sha256").update(path19).digest("hex"));
126211
+ return claimOnce((0, import_node_path61.join)(freshnessDir, "leased"), (0, import_node_crypto32.createHash)("sha256").update(path19).digest("hex"));
126121
126212
  }
126122
126213
 
126123
126214
  // src/holder/requested-checkout.ts
@@ -126142,7 +126233,7 @@ function notSwitched(checkout, current, reason) {
126142
126233
  }
126143
126234
  async function clone2(checkout, deps, signal) {
126144
126235
  const parent = (0, import_node_path62.dirname)(checkout.path);
126145
- await (0, import_promises58.mkdir)(parent, { recursive: true });
126236
+ await (0, import_promises56.mkdir)(parent, { recursive: true });
126146
126237
  await assertValidBranch(deps.git, parent, checkout.branch, signal);
126147
126238
  const output2 = await deps.git.run(
126148
126239
  {
@@ -126289,7 +126380,7 @@ async function applyRequestedCheckout(checkout, operationId, deps, signal) {
126289
126380
  }
126290
126381
 
126291
126382
  // src/holder/run-inputs.ts
126292
- var import_promises59 = require("node:fs/promises");
126383
+ var import_promises57 = require("node:fs/promises");
126293
126384
  var import_node_path63 = require("node:path");
126294
126385
  init_src();
126295
126386
  var NO_RUN_INPUTS = {
@@ -126327,7 +126418,7 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [], com
126327
126418
  await commitAttribution?.setCoAuthor(spec.gitCoAuthor);
126328
126419
  const dir = (0, import_node_path63.join)(tmpDir, "runs", spec.runId);
126329
126420
  const cleanup = async () => {
126330
- await (0, import_promises59.rm)(dir, { recursive: true, force: true });
126421
+ await (0, import_promises57.rm)(dir, { recursive: true, force: true });
126331
126422
  };
126332
126423
  try {
126333
126424
  const credential = await source.fetchProviderCredential(spec.runId, signal);
@@ -126335,8 +126426,8 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [], com
126335
126426
  for (const [index, attachment] of (spec.attachments ?? []).entries()) {
126336
126427
  const bytes2 = await source.downloadAttachment(spec.runId, attachment.id, signal);
126337
126428
  const path19 = attachmentPath(spec, attachment, index, dir);
126338
- await (0, import_promises59.mkdir)((0, import_node_path63.dirname)(path19), { recursive: true, mode: 448 });
126339
- await (0, import_promises59.writeFile)(path19, bytes2, { mode: 384 });
126429
+ await (0, import_promises57.mkdir)((0, import_node_path63.dirname)(path19), { recursive: true, mode: 448 });
126430
+ await (0, import_promises57.writeFile)(path19, bytes2, { mode: 384 });
126340
126431
  const imageMimeType = attachment.kind === "image" ? detectImageMimeType(Buffer.from(bytes2.buffer, bytes2.byteOffset, bytes2.byteLength)) : null;
126341
126432
  attachments.push({
126342
126433
  id: attachment.id,
@@ -126366,7 +126457,7 @@ async function prepareRunInputs(spec, { source, tmpDir, signal, skills = [], com
126366
126457
  }
126367
126458
 
126368
126459
  // src/holder/serve.ts
126369
- var import_node_crypto41 = require("node:crypto");
126460
+ var import_node_crypto34 = require("node:crypto");
126370
126461
  var import_node_net = require("node:net");
126371
126462
  var import_node_path72 = require("node:path");
126372
126463
  init_runtime_v2();
@@ -126375,7 +126466,7 @@ init_platform();
126375
126466
 
126376
126467
  // src/holder/admission.ts
126377
126468
  var import_node_fs26 = require("node:fs");
126378
- var import_promises62 = require("node:fs/promises");
126469
+ var import_promises60 = require("node:fs/promises");
126379
126470
  var import_node_os10 = require("node:os");
126380
126471
  var import_node_path68 = require("node:path");
126381
126472
  init_constants();
@@ -126392,12 +126483,12 @@ init_capabilities3();
126392
126483
  init_kernel();
126393
126484
 
126394
126485
  // src/holder/agent-context.ts
126395
- var import_promises60 = require("node:fs/promises");
126486
+ var import_promises58 = require("node:fs/promises");
126396
126487
  var import_node_path65 = require("node:path");
126397
126488
  init_prompt();
126398
126489
  init_kernel();
126399
126490
  async function readText3(path19) {
126400
- return (0, import_promises60.readFile)(path19, "utf8").then(
126491
+ return (0, import_promises58.readFile)(path19, "utf8").then(
126401
126492
  (text3) => text3.trim(),
126402
126493
  () => null
126403
126494
  );
@@ -126571,7 +126662,7 @@ function createCheckoutRefresh(deps) {
126571
126662
  }
126572
126663
 
126573
126664
  // src/holder/git-state.ts
126574
- var import_promises61 = require("node:fs/promises");
126665
+ var import_promises59 = require("node:fs/promises");
126575
126666
  var import_node_path67 = require("node:path");
126576
126667
  init_runtime_v2();
126577
126668
  var SHA_PATTERN = /^[0-9a-f]{40,64}$/;
@@ -126646,7 +126737,7 @@ async function readRepository(git, repoRoot, signal) {
126646
126737
  }
126647
126738
  async function isCheckout2(path19) {
126648
126739
  try {
126649
- await (0, import_promises61.stat)((0, import_node_path67.join)(path19, ".git"));
126740
+ await (0, import_promises59.stat)((0, import_node_path67.join)(path19, ".git"));
126650
126741
  return true;
126651
126742
  } catch {
126652
126743
  return false;
@@ -126654,7 +126745,7 @@ async function isCheckout2(path19) {
126654
126745
  }
126655
126746
  async function childCheckouts(path19) {
126656
126747
  try {
126657
- const entries2 = await (0, import_promises61.readdir)(path19, { withFileTypes: true });
126748
+ const entries2 = await (0, import_promises59.readdir)(path19, { withFileTypes: true });
126658
126749
  const children = entries2.filter((entry2) => entry2.isDirectory() && !entry2.name.startsWith(".")).map((entry2) => (0, import_node_path67.join)(path19, entry2.name));
126659
126750
  const checkouts = await Promise.all(
126660
126751
  children.map(async (child) => await isCheckout2(child) ? child : null)
@@ -126724,7 +126815,7 @@ function volumeRoot(path19) {
126724
126815
  }
126725
126816
  async function exists3(path19) {
126726
126817
  try {
126727
- await (0, import_promises62.stat)(path19);
126818
+ await (0, import_promises60.stat)(path19);
126728
126819
  return true;
126729
126820
  } catch {
126730
126821
  return false;
@@ -126732,10 +126823,10 @@ async function exists3(path19) {
126732
126823
  }
126733
126824
  async function inspectReadiness(path19) {
126734
126825
  try {
126735
- if (!(await (0, import_promises62.stat)(path19)).isDirectory()) {
126826
+ if (!(await (0, import_promises60.stat)(path19)).isDirectory()) {
126736
126827
  return { ready: false, missing: true, message: MESSAGES.missing };
126737
126828
  }
126738
- await (0, import_promises62.access)(path19, import_node_fs26.constants.R_OK | import_node_fs26.constants.W_OK | import_node_fs26.constants.X_OK);
126829
+ await (0, import_promises60.access)(path19, import_node_fs26.constants.R_OK | import_node_fs26.constants.W_OK | import_node_fs26.constants.X_OK);
126739
126830
  return { ready: true };
126740
126831
  } catch (error62) {
126741
126832
  const code = errnoCode(error62) ?? "";
@@ -126781,8 +126872,8 @@ async function admitDefaultWorkspace(spec, context, skills) {
126781
126872
  const { env } = context;
126782
126873
  const path19 = resolveAlanDefaultWorkspacePath(env.HOME || env.USERPROFILE || (0, import_node_os10.homedir)());
126783
126874
  try {
126784
- await (0, import_promises62.mkdir)(path19, { recursive: true, mode: 448 });
126785
- await (0, import_promises62.access)(path19, import_node_fs26.constants.R_OK | import_node_fs26.constants.W_OK | import_node_fs26.constants.X_OK);
126875
+ await (0, import_promises60.mkdir)(path19, { recursive: true, mode: 448 });
126876
+ await (0, import_promises60.access)(path19, import_node_fs26.constants.R_OK | import_node_fs26.constants.W_OK | import_node_fs26.constants.X_OK);
126786
126877
  return { kind: "admitted", spec: { ...spec, projectPath: path19 }, skills };
126787
126878
  } catch (error62) {
126788
126879
  const code = errnoCode(error62);
@@ -126920,7 +127011,7 @@ async function respondToTurn(runningRunId, driver, request3) {
126920
127011
  }
126921
127012
 
126922
127013
  // src/holder/session-facts.ts
126923
- var import_promises63 = require("node:fs/promises");
127014
+ var import_promises61 = require("node:fs/promises");
126924
127015
  init_capabilities3();
126925
127016
  init_platform();
126926
127017
  var CLI_RSS_CACHE_MS = 1e4;
@@ -126949,8 +127040,8 @@ function createSessionFacts(options) {
126949
127040
  const path19 = await resolveCommandOnPath(command, env, platform);
126950
127041
  if (path19 === null) return null;
126951
127042
  try {
126952
- const real = await (0, import_promises63.realpath)(path19);
126953
- const info = await (0, import_promises63.stat)(real);
127043
+ const real = await (0, import_promises61.realpath)(path19);
127044
+ const info = await (0, import_promises61.stat)(real);
126954
127045
  return { command, key: `${real}:${info.ino}:${info.size}:${info.mtimeMs}` };
126955
127046
  } catch {
126956
127047
  return null;
@@ -127045,8 +127136,8 @@ function createSessionFacts(options) {
127045
127136
  }
127046
127137
 
127047
127138
  // src/holder/session-preparation.ts
127048
- var import_node_crypto40 = require("node:crypto");
127049
- var import_promises64 = require("node:fs/promises");
127139
+ var import_node_crypto33 = require("node:crypto");
127140
+ var import_promises62 = require("node:fs/promises");
127050
127141
  init_runtime_v2();
127051
127142
  init_kernel();
127052
127143
  init_platform();
@@ -127077,7 +127168,7 @@ function createHolderPreparation(options) {
127077
127168
  let status;
127078
127169
  let closing = false;
127079
127170
  let preparedEngine;
127080
- const unavailableGeneration = (0, import_node_crypto40.randomUUID)();
127171
+ const unavailableGeneration = (0, import_node_crypto33.randomUUID)();
127081
127172
  const transition = (operation) => {
127082
127173
  pending++;
127083
127174
  const next = tail2.then(operation, operation);
@@ -127099,7 +127190,7 @@ function createHolderPreparation(options) {
127099
127190
  signal.throwIfAborted();
127100
127191
  if (!samePreparationBinding(fresh.binding, reference))
127101
127192
  throw new LocalSessionActionError("forbidden");
127102
- if (await (0, import_promises64.realpath)(reference.workspace) !== reference.workspace)
127193
+ if (await (0, import_promises62.realpath)(reference.workspace) !== reference.workspace)
127103
127194
  throw new LocalSessionActionError("invalid_path");
127104
127195
  return fresh;
127105
127196
  };
@@ -127125,7 +127216,7 @@ function createHolderPreparation(options) {
127125
127216
  status = {
127126
127217
  localSessionId: reference.localSessionId,
127127
127218
  conversationId: reference.conversationId,
127128
- generation: changed2 ? (0, import_node_crypto40.randomUUID)() : status?.generation ?? (0, import_node_crypto40.randomUUID)(),
127219
+ generation: changed2 ? (0, import_node_crypto33.randomUUID)() : status?.generation ?? (0, import_node_crypto33.randomUUID)(),
127129
127220
  state: "ready"
127130
127221
  };
127131
127222
  };
@@ -127137,7 +127228,7 @@ function createHolderPreparation(options) {
127137
127228
  if (!metadata || metadata.configurationRevision === fresh.configurationRevision) return;
127138
127229
  if (!options.driver.suspend) throw new LocalSessionActionError("busy");
127139
127230
  await options.driver.suspend();
127140
- if (status) status = { ...status, generation: (0, import_node_crypto40.randomUUID)() };
127231
+ if (status) status = { ...status, generation: (0, import_node_crypto33.randomUUID)() };
127141
127232
  };
127142
127233
  const openPrepared = async (reference, controller) => {
127143
127234
  const fresh = await authorize(reference, controller.signal);
@@ -127162,7 +127253,7 @@ function createHolderPreparation(options) {
127162
127253
  if (closing) throw new LocalSessionActionError("not_prepared");
127163
127254
  if (job) return currentStatus(reference);
127164
127255
  if (options.active()) throw new LocalSessionActionError("busy");
127165
- const generation = status?.state === "ready" ? status.generation : (0, import_node_crypto40.randomUUID)();
127256
+ const generation = status?.state === "ready" ? status.generation : (0, import_node_crypto33.randomUUID)();
127166
127257
  status = {
127167
127258
  localSessionId: reference.localSessionId,
127168
127259
  conversationId: reference.conversationId,
@@ -127301,7 +127392,7 @@ init_acp2();
127301
127392
  init_kernel();
127302
127393
 
127303
127394
  // src/run-log/directory.ts
127304
- var import_promises65 = require("node:fs/promises");
127395
+ var import_promises63 = require("node:fs/promises");
127305
127396
  var import_node_path69 = require("node:path");
127306
127397
  init_runtime_v2();
127307
127398
  init_zod();
@@ -127336,7 +127427,7 @@ function runDirectory(runsDir, runId) {
127336
127427
  }
127337
127428
  async function isRunClaimed(runsDir, runId) {
127338
127429
  try {
127339
- return (await (0, import_promises65.stat)(runDirectory(runsDir, runId).log)).size > 0;
127430
+ return (await (0, import_promises63.stat)(runDirectory(runsDir, runId).log)).size > 0;
127340
127431
  } catch (error62) {
127341
127432
  if (errnoCode(error62) === "ENOENT") return false;
127342
127433
  throw error62;
@@ -127344,7 +127435,7 @@ async function isRunClaimed(runsDir, runId) {
127344
127435
  }
127345
127436
 
127346
127437
  // src/run-log/conversation-index.ts
127347
- var import_promises66 = require("node:fs/promises");
127438
+ var import_promises64 = require("node:fs/promises");
127348
127439
  var import_node_path70 = require("node:path");
127349
127440
  init_runtime_v2();
127350
127441
  init_zod();
@@ -127377,8 +127468,8 @@ async function indexConversationRun(runsDir, conversationId, ordinal, assistantO
127377
127468
  const nextOrdinal = assistantOrdinal + 1;
127378
127469
  if (nextOrdinal <= ordinal) throw new Error("Assistant order must follow the prompt");
127379
127470
  const path19 = shardPath(runsDir, conversationId, ordinal);
127380
- await (0, import_promises66.mkdir)((0, import_node_path70.dirname)(path19), { recursive: true, mode: 448 });
127381
- await (0, import_promises66.appendFile)(path19, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
127471
+ await (0, import_promises64.mkdir)((0, import_node_path70.dirname)(path19), { recursive: true, mode: 448 });
127472
+ await (0, import_promises64.appendFile)(path19, `${JSON.stringify({ ordinal, nextOrdinal, runId })}
127382
127473
  `, { mode: 384 });
127383
127474
  const coveragePath = (0, import_node_path70.join)((0, import_node_path70.dirname)((0, import_node_path70.dirname)(path19)), "coverage.json");
127384
127475
  const coverage = await readJsonFile(coveragePath, coverageSchema2);
@@ -127758,6 +127849,12 @@ async function writeRunEnd(updates, log, spec, context) {
127758
127849
  }
127759
127850
  }
127760
127851
  }
127852
+ function aborted2(signal) {
127853
+ if (signal.aborted) return Promise.resolve();
127854
+ return new Promise((resolve13) => {
127855
+ signal.addEventListener("abort", resolve13, { once: true });
127856
+ });
127857
+ }
127761
127858
  function resultAfterStop(result, signal) {
127762
127859
  if (!signal.aborted || result.outcome !== "failed") return result;
127763
127860
  return {
@@ -127765,6 +127862,26 @@ function resultAfterStop(result, signal) {
127765
127862
  ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId }
127766
127863
  };
127767
127864
  }
127865
+ async function stopSerialBackground(pendingBackground, result, outcome2, spec, context, signal, backgroundSettled) {
127866
+ if (!pendingBackground) return { result, outcome: outcome2 };
127867
+ const stopped = await Promise.race([
127868
+ backgroundSettled.then(() => false),
127869
+ aborted2(signal).then(() => true)
127870
+ ]);
127871
+ if (!stopped) return { result, outcome: outcome2 };
127872
+ const stopOutcome = signal.reason === "interrupted" ? "interrupted" : "aborted";
127873
+ await context.driver.suspend?.().catch((error62) => {
127874
+ context.log.warn("holder.background_stop_failed", { runId: spec.runId, error: error62 });
127875
+ });
127876
+ return {
127877
+ outcome: stopOutcome,
127878
+ result: {
127879
+ outcome: stopOutcome,
127880
+ ...result.providerSessionId === void 0 ? {} : { providerSessionId: result.providerSessionId },
127881
+ ...result.unansweredSteerIds === void 0 ? {} : { unansweredSteerIds: result.unansweredSteerIds }
127882
+ }
127883
+ };
127884
+ }
127768
127885
  async function turnEndGitState(outcome2, gitState) {
127769
127886
  if (outcome2 === "rejected") {
127770
127887
  gitState.stop();
@@ -127773,9 +127890,23 @@ async function turnEndGitState(outcome2, gitState) {
127773
127890
  const state2 = await gitState.finish();
127774
127891
  return state2 === null ? [] : [state2];
127775
127892
  }
127776
- async function completeClaimedTurn(turnResult, spec, context, signal, log, events, reportedError, state2, gitState) {
127777
- const result = resultAfterStop(turnResult, signal);
127778
- const outcome2 = result.outcome === "aborted" && signal.reason === "interrupted" ? "interrupted" : result.outcome;
127893
+ async function completeClaimedTurn(turnResult, spec, context, signal, log, events, reportedError, state2, backgroundSettled, gitState) {
127894
+ const pendingLocalBackground = Boolean(
127895
+ context.serialBackground === true && events && context.driver.hasBackgroundWork?.(spec.runId)
127896
+ );
127897
+ const stopped = resultAfterStop(turnResult, signal);
127898
+ const initialOutcome = stopped.outcome === "aborted" && signal.reason === "interrupted" ? "interrupted" : stopped.outcome;
127899
+ const settled3 = await stopSerialBackground(
127900
+ pendingLocalBackground,
127901
+ stopped,
127902
+ initialOutcome,
127903
+ spec,
127904
+ context,
127905
+ signal,
127906
+ backgroundSettled
127907
+ );
127908
+ const result = settled3.result;
127909
+ const outcome2 = settled3.outcome;
127779
127910
  const updates = [];
127780
127911
  if ((outcome2 === "failed" || outcome2 === "interrupted") && !reportedError && result.message !== void 0) {
127781
127912
  updates.push(
@@ -127792,15 +127923,17 @@ async function completeClaimedTurn(turnResult, spec, context, signal, log, event
127792
127923
  const ended = resultEndUpdate(result, outcome2);
127793
127924
  state2.ended = ended;
127794
127925
  updates.push(ended);
127795
- const pendingBackground = Boolean(events && context.driver.hasBackgroundWork?.(spec.runId));
127796
- if (pendingBackground) updates.push({ sessionUpdate: "_alan/background.pending" });
127926
+ const retainForBackground = Boolean(
127927
+ context.serialBackground !== true && events && context.driver.hasBackgroundWork?.(spec.runId)
127928
+ );
127929
+ if (retainForBackground) updates.push({ sessionUpdate: "_alan/background.pending" });
127797
127930
  try {
127798
127931
  await writeRunEnd(updates, log, spec, context);
127799
127932
  state2.foregroundEnded = true;
127800
127933
  state2.retainedForBackground = Boolean(
127801
- pendingBackground && context.driver.hasBackgroundWork?.(spec.runId)
127934
+ retainForBackground && context.driver.hasBackgroundWork?.(spec.runId)
127802
127935
  );
127803
- if (pendingBackground && !state2.retainedForBackground) {
127936
+ if (retainForBackground && !state2.retainedForBackground) {
127804
127937
  await writeRunEnd([ended], log, spec, context);
127805
127938
  }
127806
127939
  } finally {
@@ -127848,9 +127981,17 @@ async function runClaimedTurn(spec, claimed, context, signal) {
127848
127981
  ]);
127849
127982
  return "failed";
127850
127983
  };
127984
+ let settledBackground;
127985
+ const backgroundSettled = new Promise((resolve13) => {
127986
+ settledBackground = resolve13;
127987
+ });
127851
127988
  const events = context.driver.onBackgroundEvent?.(spec, (update, sessionId) => {
127852
127989
  append(fitForRunLog(withoutInlineMedia(update)), sessionId);
127853
127990
  log.syncIfDirty();
127991
+ if (context.serialBackground === true) {
127992
+ if (!context.driver.hasBackgroundWork?.(spec.runId)) settledBackground?.();
127993
+ return;
127994
+ }
127854
127995
  if (!endState.foregroundEnded || !endState.retainedForBackground || context.driver.hasBackgroundWork?.(spec.runId))
127855
127996
  return;
127856
127997
  if (endState.ended) append(endState.ended);
@@ -127885,6 +128026,7 @@ async function runClaimedTurn(spec, claimed, context, signal) {
127885
128026
  events,
127886
128027
  reported.error,
127887
128028
  endState,
128029
+ backgroundSettled,
127888
128030
  gitState
127889
128031
  );
127890
128032
  }
@@ -127913,6 +128055,7 @@ async function runClaimedTurn(spec, claimed, context, signal) {
127913
128055
  events,
127914
128056
  reported.error,
127915
128057
  endState,
128058
+ backgroundSettled,
127916
128059
  gitState
127917
128060
  );
127918
128061
  }
@@ -127924,12 +128067,12 @@ var TASK_UNSUPPORTED = {
127924
128067
  message: "This agent cannot stop one background task."
127925
128068
  };
127926
128069
  function sha2564(value2) {
127927
- return (0, import_node_crypto41.createHash)("sha256").update(value2).digest("hex");
128070
+ return (0, import_node_crypto34.createHash)("sha256").update(value2).digest("hex");
127928
128071
  }
127929
128072
  function tokenMatches(expected, presented) {
127930
128073
  const a = Buffer.from(sha2564(expected), "hex");
127931
128074
  const b = Buffer.from(sha2564(presented), "hex");
127932
- return (0, import_node_crypto41.timingSafeEqual)(a, b);
128075
+ return (0, import_node_crypto34.timingSafeEqual)(a, b);
127933
128076
  }
127934
128077
  async function runHolder({
127935
128078
  launch,
@@ -127938,6 +128081,7 @@ async function runHolder({
127938
128081
  log,
127939
128082
  inputs,
127940
128083
  machine,
128084
+ serialBackground,
127941
128085
  preparation: source,
127942
128086
  engineRecording,
127943
128087
  engineOwnership = nativeEngineOwnership()
@@ -128054,7 +128198,8 @@ async function runHolder({
128054
128198
  log,
128055
128199
  onAppended: (runId, offset) => broadcast({ type: "appended", runId, offset }),
128056
128200
  ...inputs === void 0 ? {} : { inputs },
128057
- ...workspace === void 0 ? {} : { workspace }
128201
+ ...workspace === void 0 ? {} : { workspace },
128202
+ ...serialBackground === void 0 ? {} : { serialBackground }
128058
128203
  };
128059
128204
  claimRun(spec, context).then(
128060
128205
  (claimed) => {
@@ -128324,7 +128469,7 @@ init_runtime_v2();
128324
128469
  init_zod();
128325
128470
 
128326
128471
  // src/client/browser-agent-discovery.ts
128327
- var import_node_crypto42 = require("node:crypto");
128472
+ var import_node_crypto35 = require("node:crypto");
128328
128473
  var import_node_path73 = require("node:path");
128329
128474
  init_agent2();
128330
128475
  init_zod();
@@ -128338,13 +128483,13 @@ function browserAgentDiscoveryPath(stateDir) {
128338
128483
  return (0, import_node_path73.join)(stateDir, BROWSER_AGENT_DISCOVERY_FILE);
128339
128484
  }
128340
128485
  function deriveBrowserScopeToken(secret, scopeId) {
128341
- return (0, import_node_crypto42.createHmac)("sha256", secret).update(scopeId).digest("hex");
128486
+ return (0, import_node_crypto35.createHmac)("sha256", secret).update(scopeId).digest("hex");
128342
128487
  }
128343
128488
  function browserScopeUrl(discovery, scopeId, conversationId) {
128344
128489
  return `${discovery.endpoint}/${encodeURIComponent(scopeId)}/${encodeURIComponent(conversationId)}`;
128345
128490
  }
128346
128491
  function browserScopeIdForRun(run3) {
128347
- return run3.taskId === void 0 ? `conversation:${run3.conversationId}` : `task:${run3.taskId}`;
128492
+ return `conversation:${run3.conversationId}`;
128348
128493
  }
128349
128494
 
128350
128495
  // src/client/locate.ts
@@ -128647,12 +128792,12 @@ init_kernel();
128647
128792
  init_platform();
128648
128793
 
128649
128794
  // src/cli/browser-mcp.ts
128650
- var import_promises67 = require("node:fs/promises");
128795
+ var import_promises65 = require("node:fs/promises");
128651
128796
  var BROWSER_WORKSPACE_ROOT_HEADER = "X-Alan-Workspace-Root";
128652
128797
  async function readDiscovery(stateDir) {
128653
128798
  try {
128654
128799
  const parsed = browserAgentDiscoverySchema.safeParse(
128655
- JSON.parse(await (0, import_promises67.readFile)(browserAgentDiscoveryPath(stateDir), "utf8"))
128800
+ JSON.parse(await (0, import_promises65.readFile)(browserAgentDiscoveryPath(stateDir), "utf8"))
128656
128801
  );
128657
128802
  return parsed.success ? parsed.data : null;
128658
128803
  } catch {
@@ -128820,6 +128965,8 @@ async function runHold(argv) {
128820
128965
  ),
128821
128966
  clock: systemClock,
128822
128967
  log,
128968
+ // A cloud sandbox cannot keep a turn's clock across a pause, so it leases the VM instead.
128969
+ serialBackground: config2.workspaceRoot === null,
128823
128970
  preparation: {
128824
128971
  authorize: async (reference, signal) => {
128825
128972
  const current = await loadStoredAccess(paths);