@amaster.ai/employee-runtime-connector 0.1.13-beta.1 → 0.1.13-beta.2

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.
@@ -83,7 +83,7 @@ function withAuditCorrelationEnvironment(environment, command) {
83
83
  }
84
84
 
85
85
  // src/amaster-runtime-daemon.mjs
86
- import { createHash as createHash20, randomUUID as randomUUID2 } from "node:crypto";
86
+ import { createHash as createHash20, randomUUID as randomUUID3 } from "node:crypto";
87
87
  import { createRequire } from "node:module";
88
88
 
89
89
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
@@ -19214,10 +19214,10 @@ var MIRRORX_DRIVE_AGENT_RULES = [
19214
19214
  ].join("\n");
19215
19215
 
19216
19216
  // src/amaster-runtime-daemon.mjs
19217
- import { chmodSync as chmodSync8, copyFileSync as copyFileSync2, existsSync as existsSync18, lstatSync as lstatSync15, mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync5, readFileSync as readFileSync20, readdirSync as readdirSync13, realpathSync as realpathSync12, renameSync as renameSync11, rmSync as rmSync12, statSync as statSync12, symlinkSync as symlinkSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync14 } from "node:fs";
19217
+ import { chmodSync as chmodSync9, copyFileSync as copyFileSync2, existsSync as existsSync18, lstatSync as lstatSync16, mkdirSync as mkdirSync14, mkdtempSync as mkdtempSync5, readFileSync as readFileSync21, readdirSync as readdirSync14, realpathSync as realpathSync12, renameSync as renameSync12, rmSync as rmSync12, statSync as statSync12, symlinkSync as symlinkSync2, unlinkSync as unlinkSync4, writeFileSync as writeFileSync15 } from "node:fs";
19218
19218
  import { arch as arch4, homedir as homedir7, hostname as hostname2, platform as platform4, tmpdir } from "node:os";
19219
- import { basename as basename8, delimiter as delimiter3, dirname as dirname13, extname as extname3, isAbsolute as isAbsolute13, join as join25, relative as relative9, resolve as resolve19 } from "node:path";
19220
- import { spawn, spawnSync as spawnSync5 } from "node:child_process";
19219
+ import { basename as basename8, delimiter as delimiter3, dirname as dirname14, extname as extname3, isAbsolute as isAbsolute13, join as join26, relative as relative9, resolve as resolve20 } from "node:path";
19220
+ import { spawn, spawnSync as spawnSync6 } from "node:child_process";
19221
19221
 
19222
19222
  // src/amaster-runtime-daemon/common.mjs
19223
19223
  import { homedir } from "node:os";
@@ -19725,7 +19725,7 @@ async function postRuntimeConnectorJsonWithRetry(config, path, payload, options
19725
19725
  } catch (error) {
19726
19726
  lastError = error;
19727
19727
  if (attempt >= maxAttempts || !retryableRuntimeConnectorPost(error)) throw error;
19728
- if (delayMs > 0) await new Promise((resolve20) => setTimeout(resolve20, delayMs));
19728
+ if (delayMs > 0) await new Promise((resolve21) => setTimeout(resolve21, delayMs));
19729
19729
  }
19730
19730
  }
19731
19731
  throw lastError;
@@ -20106,12 +20106,167 @@ function preparePiExecutorAccess(input) {
20106
20106
  return { uid, gid };
20107
20107
  }
20108
20108
 
20109
+ // src/amaster-runtime-daemon/browser-session-profile.mjs
20110
+ import { randomUUID as randomUUID2 } from "node:crypto";
20111
+ import {
20112
+ chmodSync as chmodSync2,
20113
+ chownSync as chownSync2,
20114
+ lstatSync as lstatSync4,
20115
+ mkdirSync as mkdirSync3,
20116
+ readFileSync,
20117
+ readdirSync as readdirSync2,
20118
+ rmdirSync,
20119
+ unlinkSync,
20120
+ writeFileSync as writeFileSync3,
20121
+ renameSync as renameSync2
20122
+ } from "node:fs";
20123
+ import { parse, resolve as resolve4, join as join5, dirname as dirname2 } from "node:path";
20124
+ import { spawnSync } from "node:child_process";
20125
+ var MARKERS = ".owners";
20126
+ function statOrNull(path) {
20127
+ try {
20128
+ return lstatSync4(path);
20129
+ } catch (error) {
20130
+ if (error?.code === "ENOENT") return null;
20131
+ throw error;
20132
+ }
20133
+ }
20134
+ function fail() {
20135
+ throw new Error("browser_session_profile_path_invalid");
20136
+ }
20137
+ function assertRootControlledAncestors(path) {
20138
+ for (let current = resolve4(path); ; current = dirname2(current)) {
20139
+ const stat = statOrNull(current);
20140
+ if (!stat?.isDirectory() || stat.isSymbolicLink() || stat.uid !== 0 || (stat.mode & 18) !== 0) fail();
20141
+ if (current === parse(current).root) break;
20142
+ }
20143
+ }
20144
+ function assertDirectory(path, uid, gid, mode) {
20145
+ const stat = statOrNull(path);
20146
+ if (!stat?.isDirectory() || stat.isSymbolicLink() || stat.uid !== uid || stat.gid !== gid || (stat.mode & 511) !== mode) fail();
20147
+ }
20148
+ function markerPath(root, opaqueRef) {
20149
+ return join5(root, MARKERS, `${opaqueRef}.json`);
20150
+ }
20151
+ function assertIdentityMarker(path, identity) {
20152
+ const stat = statOrNull(path);
20153
+ if (!stat?.isFile() || stat.isSymbolicLink() || stat.uid !== 0 || (stat.mode & 511) !== 384) fail();
20154
+ let stored;
20155
+ try {
20156
+ stored = JSON.parse(readFileSync(path, "utf8"));
20157
+ } catch {
20158
+ fail();
20159
+ }
20160
+ if (JSON.stringify(stored) !== JSON.stringify(identity)) {
20161
+ throw new Error("browser_session_profile_identity_invalid");
20162
+ }
20163
+ }
20164
+ function assertInput(input) {
20165
+ const { root, identity, uid, gid } = input;
20166
+ if (process.getuid?.() !== 0 || !Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(gid) || gid <= 0 || !/^profile_[a-z0-9]{16,64}$/iu.test(identity?.localOpaqueRef ?? "") || resolve4(root) === parse(resolve4(root)).root) fail();
20167
+ return { root: resolve4(root), profile: join5(resolve4(root), identity.localOpaqueRef), marker: markerPath(resolve4(root), identity.localOpaqueRef) };
20168
+ }
20169
+ function assertRootPaths(root) {
20170
+ assertRootControlledAncestors(dirname2(root));
20171
+ const rootStat = statOrNull(root);
20172
+ if (rootStat && (!rootStat.isDirectory() || rootStat.isSymbolicLink() || rootStat.uid !== 0 || rootStat.gid !== 0 || (rootStat.mode & 18) !== 0)) fail();
20173
+ if (!rootStat) mkdirSync3(root, { mode: 448 });
20174
+ const registry = join5(root, MARKERS);
20175
+ const registryStat = statOrNull(registry);
20176
+ if (registryStat && (!registryStat.isDirectory() || registryStat.isSymbolicLink() || registryStat.uid !== 0 || registryStat.gid !== 0 || (registryStat.mode & 63) !== 0)) fail();
20177
+ if (!registryStat) mkdirSync3(registry, { mode: 448 });
20178
+ chmodSync2(registry, 448);
20179
+ chmodSync2(root, 457);
20180
+ assertDirectory(root, 0, 0, 457);
20181
+ assertDirectory(registry, 0, 0, 448);
20182
+ }
20183
+ function ensureUnprivilegedBrowserSessionProfile(input) {
20184
+ const { root, profile, marker } = assertInput(input);
20185
+ assertRootPaths(root);
20186
+ let profileStat = statOrNull(profile);
20187
+ let markerStat = statOrNull(marker);
20188
+ if (profileStat && !markerStat) {
20189
+ assertDirectory(profile, 0, 0, 448);
20190
+ if (readdirSync2(profile).length !== 0) fail();
20191
+ rmdirSync(profile);
20192
+ profileStat = null;
20193
+ }
20194
+ if (!profileStat && markerStat) {
20195
+ assertIdentityMarker(marker, input.identity);
20196
+ unlinkSync(marker);
20197
+ markerStat = null;
20198
+ }
20199
+ if (profileStat) {
20200
+ assertIdentityMarker(marker, input.identity);
20201
+ if (profileStat.uid === 0 && profileStat.gid === 0) {
20202
+ assertDirectory(profile, 0, 0, 448);
20203
+ if (readdirSync2(profile).length !== 0) fail();
20204
+ chownSync2(profile, input.uid, input.gid);
20205
+ }
20206
+ assertDirectory(profile, input.uid, input.gid, 448);
20207
+ } else {
20208
+ mkdirSync3(profile, { mode: 448 });
20209
+ assertDirectory(profile, 0, 0, 448);
20210
+ const temporary = `${marker}.${randomUUID2()}.tmp`;
20211
+ writeFileSync3(temporary, `${JSON.stringify(input.identity)}
20212
+ `, { mode: 384, flag: "wx" });
20213
+ renameSync2(temporary, marker);
20214
+ assertIdentityMarker(marker, input.identity);
20215
+ chownSync2(profile, input.uid, input.gid);
20216
+ assertDirectory(profile, input.uid, input.gid, 448);
20217
+ }
20218
+ return { profileRoot: root, userDataDir: profile, identity: input.identity };
20219
+ }
20220
+ function cleanupUnprivilegedBrowserSessionProfile(input) {
20221
+ const { root, profile, marker } = assertInput(input);
20222
+ assertRootPaths(root);
20223
+ const profileStat = statOrNull(profile);
20224
+ const markerStat = statOrNull(marker);
20225
+ if (!profileStat && !markerStat) return { outcome: "absent", identity: input.identity };
20226
+ if (!profileStat && markerStat) {
20227
+ assertIdentityMarker(marker, input.identity);
20228
+ unlinkSync(marker);
20229
+ return { outcome: "deleted", identity: input.identity };
20230
+ }
20231
+ if (profileStat && !markerStat) {
20232
+ assertDirectory(profile, 0, 0, 448);
20233
+ if (readdirSync2(profile).length !== 0) fail();
20234
+ rmdirSync(profile);
20235
+ return { outcome: "deleted", identity: input.identity };
20236
+ }
20237
+ assertIdentityMarker(marker, input.identity);
20238
+ if (profileStat.uid === 0 && profileStat.gid === 0) {
20239
+ assertDirectory(profile, 0, 0, 448);
20240
+ if (readdirSync2(profile).length !== 0) fail();
20241
+ rmdirSync(profile);
20242
+ unlinkSync(marker);
20243
+ return { outcome: "deleted", identity: input.identity };
20244
+ }
20245
+ assertDirectory(profile, input.uid, input.gid, 448);
20246
+ const cleanup = spawnSync(process.execPath, ["-e", `
20247
+ const fs = require('node:fs');
20248
+ const path = require('node:path');
20249
+ const root = process.argv[1];
20250
+ for (const name of fs.readdirSync(root)) fs.rmSync(path.join(root, name), { recursive: true, force: true });
20251
+ `, profile], {
20252
+ uid: input.uid,
20253
+ gid: input.gid,
20254
+ env: {},
20255
+ stdio: "ignore",
20256
+ timeout: 3e4
20257
+ });
20258
+ if (cleanup.status !== 0 || cleanup.error || readdirSync2(profile).length !== 0) fail();
20259
+ rmdirSync(profile);
20260
+ unlinkSync(marker);
20261
+ return { outcome: "deleted", identity: input.identity };
20262
+ }
20263
+
20109
20264
  // src/amaster-runtime-daemon/codex-managed-mcp-profile.mjs
20110
20265
  import { createHash as createHash5 } from "node:crypto";
20111
- import { chmodSync as chmodSync2, existsSync as existsSync3, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync, realpathSync as realpathSync4, readdirSync as readdirSync2, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync3 } from "node:fs";
20266
+ import { chmodSync as chmodSync3, existsSync as existsSync3, lstatSync as lstatSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync2, realpathSync as realpathSync4, readdirSync as readdirSync3, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync4 } from "node:fs";
20112
20267
  import { arch, platform } from "node:os";
20113
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join6, relative, resolve as resolve4 } from "node:path";
20114
- import { spawnSync as spawnSync2 } from "node:child_process";
20268
+ import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join7, relative, resolve as resolve5 } from "node:path";
20269
+ import { spawnSync as spawnSync3 } from "node:child_process";
20115
20270
 
20116
20271
  // ../../node_modules/.pnpm/smol-toml@1.7.0/node_modules/smol-toml/dist/date.js
20117
20272
  var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;
@@ -20728,7 +20883,7 @@ function peekTable(key, table, meta, type) {
20728
20883
  }
20729
20884
  return [k, t, state.c];
20730
20885
  }
20731
- function parse(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
20886
+ function parse2(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
20732
20887
  let res = {};
20733
20888
  let meta = {};
20734
20889
  let tbl = res;
@@ -20935,9 +21090,9 @@ function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
20935
21090
  }
20936
21091
 
20937
21092
  // src/amaster-runtime-daemon/executor-discovery.mjs
20938
- import { spawnSync } from "node:child_process";
21093
+ import { spawnSync as spawnSync2 } from "node:child_process";
20939
21094
  import { existsSync as existsSync2, realpathSync as realpathSync3, statSync } from "node:fs";
20940
- import { delimiter, isAbsolute, join as join5 } from "node:path";
21095
+ import { delimiter, isAbsolute, join as join6 } from "node:path";
20941
21096
 
20942
21097
  // src/amaster-runtime-daemon/codebuddy-isolation-env.mjs
20943
21098
  var CODEBUDDY_ISOLATION_ENV = Object.freeze({
@@ -21019,7 +21174,7 @@ function commandExists(command, env = process.env) {
21019
21174
  return Boolean(resolveExecutorCommand(command, env));
21020
21175
  }
21021
21176
  const commandEnv = executorDiscoveryEnv(env);
21022
- const result2 = spawnSync("sh", ["-lc", `command -v ${quoteShell(command)} >/dev/null 2>&1`], {
21177
+ const result2 = spawnSync2("sh", ["-lc", `command -v ${quoteShell(command)} >/dev/null 2>&1`], {
21023
21178
  env: commandEnv,
21024
21179
  stdio: "ignore"
21025
21180
  });
@@ -21029,7 +21184,7 @@ function commandVersion(command, env = process.env) {
21029
21184
  const commandEnv = executorDiscoveryEnv(env);
21030
21185
  const executable = resolveExecutorCommand(command, env);
21031
21186
  if (!executable) return void 0;
21032
- const result2 = spawnSync(executable, ["--version"], {
21187
+ const result2 = spawnSync2(executable, ["--version"], {
21033
21188
  env: commandEnv,
21034
21189
  encoding: "utf8",
21035
21190
  stdio: ["ignore", "pipe", "ignore"],
@@ -21052,7 +21207,7 @@ function resolveExecutorCommand(command, env = process.env) {
21052
21207
  return null;
21053
21208
  }
21054
21209
  const commandEnv = executorDiscoveryEnv(env);
21055
- const result2 = spawnSync("where.exe", [normalized], {
21210
+ const result2 = spawnSync2("where.exe", [normalized], {
21056
21211
  env: commandEnv,
21057
21212
  encoding: "utf8",
21058
21213
  stdio: ["ignore", "pipe", "ignore"]
@@ -21092,7 +21247,7 @@ function parseCodebuddyVersion(output) {
21092
21247
  function codebuddyExecutableIdentity(executable, env) {
21093
21248
  let candidate = executable;
21094
21249
  if (!isAbsolute(candidate) && !candidate.includes("/") && !candidate.includes("\\")) {
21095
- candidate = String(env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => join5(directory, candidate)).find((path) => {
21250
+ candidate = String(env.PATH ?? "").split(delimiter).filter(Boolean).map((directory) => join6(directory, candidate)).find((path) => {
21096
21251
  try {
21097
21252
  return statSync(path).isFile();
21098
21253
  } catch {
@@ -21139,7 +21294,7 @@ function attestCodebuddyCommand(command, env = process.env, cwd = void 0) {
21139
21294
  const cachedVersion = cachedCodebuddyAttestation(cacheKey, now);
21140
21295
  if (cachedVersion) return { executable, executorVersion: cachedVersion };
21141
21296
  const shell = isWindowsCommandShim(executable) ? { shell: true } : {};
21142
- const version = spawnSync(executable, ["--version"], {
21297
+ const version = spawnSync2(executable, ["--version"], {
21143
21298
  ...cwd ? { cwd } : {},
21144
21299
  env: commandEnv,
21145
21300
  encoding: "utf8",
@@ -21151,7 +21306,7 @@ function attestCodebuddyCommand(command, env = process.env, cwd = void 0) {
21151
21306
  throw new Error(`codebuddy_executor_attestation_failed: --version exit=${version.status ?? "spawn_error"}`);
21152
21307
  }
21153
21308
  const executorVersion = parseCodebuddyVersion(version.stdout);
21154
- const help2 = spawnSync(executable, ["--help"], {
21309
+ const help2 = spawnSync2(executable, ["--help"], {
21155
21310
  ...cwd ? { cwd } : {},
21156
21311
  env: commandEnv,
21157
21312
  encoding: "utf8",
@@ -21296,14 +21451,14 @@ function within(candidate, root) {
21296
21451
  return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
21297
21452
  }
21298
21453
  function writePrivateFile(filePath, contents) {
21299
- writeFileSync3(filePath, contents, { mode: 384, flag: "wx" });
21300
- chmodSync2(filePath, 384);
21454
+ writeFileSync4(filePath, contents, { mode: 384, flag: "wx" });
21455
+ chmodSync3(filePath, 384);
21301
21456
  const mode = statSync2(filePath).mode & 511;
21302
21457
  if (mode !== 384) throw new Error(`codex_managed_mcp_permissions_failed: ${filePath} mode=${mode.toString(8)}`);
21303
21458
  }
21304
21459
  function makePrivateDir(dirPath) {
21305
- mkdirSync3(dirPath, { recursive: true, mode: 448 });
21306
- chmodSync2(dirPath, 448);
21460
+ mkdirSync4(dirPath, { recursive: true, mode: 448 });
21461
+ chmodSync3(dirPath, 448);
21307
21462
  }
21308
21463
  function findSessionRollout(sessionsRoot, sessionId) {
21309
21464
  if (!existsSync3(sessionsRoot)) return null;
@@ -21311,12 +21466,12 @@ function findSessionRollout(sessionsRoot, sessionId) {
21311
21466
  const pending = [sessionsRoot];
21312
21467
  while (pending.length > 0) {
21313
21468
  const current = pending.pop();
21314
- const currentStat = lstatSync4(current);
21469
+ const currentStat = lstatSync5(current);
21315
21470
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) {
21316
21471
  throw new Error("codex_managed_mcp_session_rollout_unsafe: sessions path is not a private directory");
21317
21472
  }
21318
- for (const entry of readdirSync2(current, { withFileTypes: true })) {
21319
- const candidate = join6(current, entry.name);
21473
+ for (const entry of readdirSync3(current, { withFileTypes: true })) {
21474
+ const candidate = join7(current, entry.name);
21320
21475
  if (entry.isSymbolicLink()) throw new Error("codex_managed_mcp_session_rollout_unsafe: symlinks are forbidden");
21321
21476
  if (entry.isDirectory()) pending.push(candidate);
21322
21477
  else if (entry.isFile() && entry.name.endsWith(`-${sessionId}.jsonl`)) matches.push(candidate);
@@ -21340,33 +21495,33 @@ function restoreManagedCodexSessionRollout(input, codexHome, runDir, executorHom
21340
21495
  nonEmpty(session.invocationId, "nativeSession.invocationId");
21341
21496
  }
21342
21497
  const sourceWorkspacePath = nonEmpty(session.cwd, "nativeSession.cwd");
21343
- const issueRoot = dirname2(runDir);
21498
+ const issueRoot = dirname3(runDir);
21344
21499
  const managedSourceRunDirName = `${sourceRunId}-${createHash5("sha256").update(sourceRunId).digest("hex").slice(0, 8)}`;
21345
- const sourceRunDirs = readdirSync2(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) => join6(issueRoot, entry.name));
21500
+ const sourceRunDirs = readdirSync3(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) => join7(issueRoot, entry.name));
21346
21501
  if (sourceRunDirs.length !== 1) {
21347
21502
  throw new Error(`codex_managed_mcp_session_rollout_missing: expected one source run directory for ${sourceRunId}, received ${sourceRunDirs.length}`);
21348
21503
  }
21349
21504
  const executorRelativePath = relative(runDir, executorHome);
21350
- const cacheRoot = join6(sourceRunDirs[0], executorRelativePath, "session-rollout");
21351
- const markerPath = join6(cacheRoot, SESSION_ROLLOUT_MARKER);
21352
- if (!existsSync3(markerPath) || lstatSync4(markerPath).isSymbolicLink() || !lstatSync4(markerPath).isFile()) {
21505
+ const cacheRoot = join7(sourceRunDirs[0], executorRelativePath, "session-rollout");
21506
+ const markerPath2 = join7(cacheRoot, SESSION_ROLLOUT_MARKER);
21507
+ if (!existsSync3(markerPath2) || lstatSync5(markerPath2).isSymbolicLink() || !lstatSync5(markerPath2).isFile()) {
21353
21508
  throw new Error("codex_managed_mcp_session_rollout_missing: source rollout marker is unavailable");
21354
21509
  }
21355
- const marker = JSON.parse(readFileSync(markerPath, "utf8"));
21510
+ const marker = JSON.parse(readFileSync2(markerPath2, "utf8"));
21356
21511
  if (marker?.version !== 1 || marker?.companyId !== authority.companyId || marker?.agentId !== authority.agentId || marker?.issueId !== authority.issueId || marker?.sourceRunId !== sourceRunId || marker?.sourceCommandId !== sourceCommandId || marker?.sessionId !== sessionId || marker?.sourceWorkspacePath !== sourceWorkspacePath) {
21357
21512
  throw new Error("codex_managed_mcp_session_rollout_authority_mismatch: source rollout does not match the governed continuation");
21358
21513
  }
21359
- const sourceRollout = resolve4(cacheRoot, nonEmpty(marker.rolloutRelativePath, "rolloutRelativePath"));
21360
- if (!within(sourceRollout, cacheRoot) || lstatSync4(sourceRollout).isSymbolicLink() || !lstatSync4(sourceRollout).isFile()) {
21514
+ const sourceRollout = resolve5(cacheRoot, nonEmpty(marker.rolloutRelativePath, "rolloutRelativePath"));
21515
+ if (!within(sourceRollout, cacheRoot) || lstatSync5(sourceRollout).isSymbolicLink() || !lstatSync5(sourceRollout).isFile()) {
21361
21516
  throw new Error("codex_managed_mcp_session_rollout_unsafe: source rollout path is invalid");
21362
21517
  }
21363
- const targetSessionsRoot = join6(codexHome, "sessions");
21364
- const targetRollout = resolve4(targetSessionsRoot, marker.rolloutRelativePath);
21518
+ const targetSessionsRoot = join7(codexHome, "sessions");
21519
+ const targetRollout = resolve5(targetSessionsRoot, marker.rolloutRelativePath);
21365
21520
  if (!within(targetRollout, targetSessionsRoot)) {
21366
21521
  throw new Error("codex_managed_mcp_session_rollout_unsafe: target rollout path is invalid");
21367
21522
  }
21368
- makePrivateDir(dirname2(targetRollout));
21369
- writePrivateFile(targetRollout, readFileSync(sourceRollout));
21523
+ makePrivateDir(dirname3(targetRollout));
21524
+ writePrivateFile(targetRollout, readFileSync2(sourceRollout));
21370
21525
  return { sessionId, sourceRunId, sourceCommandId, rolloutPath: targetRollout, cacheRoot };
21371
21526
  }
21372
21527
  function resolveManagedCodexSessionRollout(input, codexHome, runDir, executorHome, authority) {
@@ -21404,12 +21559,12 @@ function collectAuthSecretStrings(value, output = []) {
21404
21559
  return output;
21405
21560
  }
21406
21561
  function sharedCodexModelRoute(sourceHome) {
21407
- const configPath = join6(sourceHome, "config.toml");
21562
+ const configPath = join7(sourceHome, "config.toml");
21408
21563
  if (!existsSync3(configPath)) return { root: [], table: [], mode: "default", protectedValues: [] };
21409
21564
  if (!statSync2(configPath).isFile()) throw new Error("codex_managed_mcp_source_config_invalid: config.toml is not a file");
21410
21565
  let config;
21411
21566
  try {
21412
- config = parse(readFileSync(configPath, "utf8"));
21567
+ config = parse2(readFileSync2(configPath, "utf8"));
21413
21568
  } catch {
21414
21569
  throw new Error("codex_managed_mcp_source_config_invalid: config.toml is not valid TOML");
21415
21570
  }
@@ -21489,12 +21644,12 @@ function parseCodexVersion(stdout) {
21489
21644
  function runAttestation(executorCommand, env, cwd, gatewayUrl, expectedHeaders) {
21490
21645
  const resolvedExecutorCommand = resolveExecutorCommand(executorCommand, env) ?? executorCommand;
21491
21646
  const shellOptions = isWindowsCommandShim(resolvedExecutorCommand) ? { shell: true } : {};
21492
- const versionResult = spawnSync2(resolvedExecutorCommand, ["--version"], { cwd, env, encoding: "utf8", timeout: 1e4, maxBuffer: 1024 * 1024, ...shellOptions });
21647
+ const versionResult = spawnSync3(resolvedExecutorCommand, ["--version"], { cwd, env, encoding: "utf8", timeout: 1e4, maxBuffer: 1024 * 1024, ...shellOptions });
21493
21648
  if (versionResult.error || versionResult.status !== 0) {
21494
21649
  throw new Error(`codex_managed_mcp_attestation_failed: --version exit=${versionResult.status ?? "spawn_error"}`);
21495
21650
  }
21496
21651
  const executorVersion = parseCodexVersion(versionResult.stdout);
21497
- const listResult = spawnSync2(resolvedExecutorCommand, ["mcp", "list", "--json"], { cwd, env, encoding: "utf8", timeout: 1e4, maxBuffer: 1024 * 1024, ...shellOptions });
21652
+ const listResult = spawnSync3(resolvedExecutorCommand, ["mcp", "list", "--json"], { cwd, env, encoding: "utf8", timeout: 1e4, maxBuffer: 1024 * 1024, ...shellOptions });
21498
21653
  if (listResult.error || listResult.status !== 0) {
21499
21654
  throw new Error(`codex_managed_mcp_attestation_failed: mcp list exit=${listResult.status ?? "spawn_error"}`);
21500
21655
  }
@@ -21621,32 +21776,32 @@ function buildIsolatedEnvironment(baseEnv, commandEnv) {
21621
21776
  return { ...env, ...record4(commandEnv) };
21622
21777
  }
21623
21778
  function assertNoProjectAmasterOverride(cwd, runDir) {
21624
- let cursor = resolve4(cwd);
21625
- const boundary = resolve4(runDir);
21779
+ let cursor = resolve5(cwd);
21780
+ const boundary = resolve5(runDir);
21626
21781
  if (!within(cursor, boundary)) throw new Error("codex_managed_mcp_owner_mismatch: cwd is outside the managed run");
21627
21782
  while (within(cursor, boundary)) {
21628
- const configPath = join6(cursor, ".codex", "config.toml");
21783
+ const configPath = join7(cursor, ".codex", "config.toml");
21629
21784
  if (existsSync3(configPath)) {
21630
- const source = readFileSync(configPath, "utf8");
21785
+ const source = readFileSync2(configPath, "utf8");
21631
21786
  const sameName = /mcp_servers\s*(?:\.\s*(?:["']amaster["']|amaster)|=\s*\{[\s\S]*?(?:["']amaster["']|amaster)\s*=)/m.test(source);
21632
21787
  if (sameName) throw new Error(`codex_managed_mcp_project_override_blocked: ${configPath}`);
21633
21788
  }
21634
21789
  if (cursor === boundary) break;
21635
- cursor = dirname2(cursor);
21790
+ cursor = dirname3(cursor);
21636
21791
  }
21637
21792
  }
21638
21793
  function seedCodexAuth(input, codexHome) {
21639
21794
  const apiKey = typeof input.commandEnv?.OPENAI_API_KEY === "string" ? input.commandEnv.OPENAI_API_KEY.trim() : "";
21640
- const target = join6(codexHome, "auth.json");
21795
+ const target = join7(codexHome, "auth.json");
21641
21796
  if (apiKey) {
21642
21797
  writePrivateFile(target, `${JSON.stringify({ OPENAI_API_KEY: apiKey })}
21643
21798
  `);
21644
21799
  return { authMode: "api_key", protectedValues: [apiKey], modelRoute: { root: [], table: [], mode: "command_api_key" } };
21645
21800
  }
21646
- const sourceHome = typeof input.baseEnv?.CODEX_HOME === "string" && input.baseEnv.CODEX_HOME.trim() ? resolve4(input.baseEnv.CODEX_HOME) : join6(typeof input.baseEnv?.HOME === "string" && input.baseEnv.HOME.trim() ? resolve4(input.baseEnv.HOME) : dirname2(resolve4(input.executorHome)), ".codex");
21647
- const source = join6(sourceHome, "auth.json");
21801
+ const sourceHome = typeof input.baseEnv?.CODEX_HOME === "string" && input.baseEnv.CODEX_HOME.trim() ? resolve5(input.baseEnv.CODEX_HOME) : join7(typeof input.baseEnv?.HOME === "string" && input.baseEnv.HOME.trim() ? resolve5(input.baseEnv.HOME) : dirname3(resolve5(input.executorHome)), ".codex");
21802
+ const source = join7(sourceHome, "auth.json");
21648
21803
  if (!existsSync3(source) || !statSync2(source).isFile()) throw new Error("codex_managed_mcp_auth_missing: isolated Codex run has no usable auth source");
21649
- const sourceContents = readFileSync(source);
21804
+ const sourceContents = readFileSync2(source);
21650
21805
  let parsedAuth;
21651
21806
  try {
21652
21807
  parsedAuth = JSON.parse(sourceContents.toString("utf8"));
@@ -21683,22 +21838,22 @@ function managedModelProviderConfig(commandEnv) {
21683
21838
  function prepareManagedCodexMcpProfile(input) {
21684
21839
  assertInvocationIsolation(input);
21685
21840
  const { gateway, gatewayUrl, sessionToken, headers, runId } = validateAuthority(input);
21686
- const runDir = resolve4(nonEmpty(input.runDir, "runDir"));
21687
- const executorHome = resolve4(nonEmpty(input.executorHome, "executorHome"));
21688
- if (!within(executorHome, join6(runDir, "executors"))) throw new Error("codex_managed_mcp_owner_mismatch: executorHome is outside the managed run");
21841
+ const runDir = resolve5(nonEmpty(input.runDir, "runDir"));
21842
+ const executorHome = resolve5(nonEmpty(input.executorHome, "executorHome"));
21843
+ if (!within(executorHome, join7(runDir, "executors"))) throw new Error("codex_managed_mcp_owner_mismatch: executorHome is outside the managed run");
21689
21844
  assertNoProjectAmasterOverride(nonEmpty(input.cwd, "cwd"), runDir);
21690
- const profileRoot = join6(executorHome, "managed-mcp");
21845
+ const profileRoot = join7(executorHome, "managed-mcp");
21691
21846
  if (existsSync3(profileRoot)) throw new Error(`codex_managed_mcp_profile_exists: ${profileRoot}`);
21692
- const home = join6(profileRoot, "home");
21693
- const codexHome = join6(profileRoot, "codex-home");
21694
- const tmp = join6(profileRoot, "tmp");
21695
- mkdirSync3(home, { recursive: true, mode: 448 });
21696
- mkdirSync3(codexHome, { recursive: true, mode: 448 });
21697
- mkdirSync3(tmp, { recursive: true, mode: 448 });
21847
+ const home = join7(profileRoot, "home");
21848
+ const codexHome = join7(profileRoot, "codex-home");
21849
+ const tmp = join7(profileRoot, "tmp");
21850
+ mkdirSync4(home, { recursive: true, mode: 448 });
21851
+ mkdirSync4(codexHome, { recursive: true, mode: 448 });
21852
+ mkdirSync4(tmp, { recursive: true, mode: 448 });
21698
21853
  try {
21699
- const markerPath = join6(profileRoot, PROFILE_MARKER);
21854
+ const markerPath2 = join7(profileRoot, PROFILE_MARKER);
21700
21855
  const owner = Object.freeze({ commandId: input.commandId, runId });
21701
- writePrivateFile(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot })}
21856
+ writePrivateFile(markerPath2, `${JSON.stringify({ version: 1, ...owner, profileRoot })}
21702
21857
  `);
21703
21858
  const runtimeAuth = record4(input.runtimeAuth);
21704
21859
  const authority = Object.freeze({
@@ -21713,7 +21868,7 @@ function prepareManagedCodexMcpProfile(input) {
21713
21868
  nativeSessionRestoreSkippedReason
21714
21869
  } = resolveManagedCodexSessionRollout(input, codexHome, runDir, executorHome, authority);
21715
21870
  const auth = seedCodexAuth(input, codexHome);
21716
- const configPath = join6(codexHome, "config.toml");
21871
+ const configPath = join7(codexHome, "config.toml");
21717
21872
  const allHeaders = { Authorization: `Bearer ${sessionToken}`, ...headers };
21718
21873
  const headerToml = Object.entries(allHeaders).map(([name, value]) => `${tomlString(name)} = ${tomlString(value)}`).join(", ");
21719
21874
  const modelProvider = managedModelProviderConfig(input.commandEnv);
@@ -21761,7 +21916,7 @@ function prepareManagedCodexMcpProfile(input) {
21761
21916
  return {
21762
21917
  profileRoot,
21763
21918
  configPath,
21764
- markerPath,
21919
+ markerPath: markerPath2,
21765
21920
  env,
21766
21921
  owner,
21767
21922
  authority,
@@ -21783,19 +21938,19 @@ function prepareManagedCodexMcpProfile(input) {
21783
21938
  function preserveManagedCodexSessionRollout(profile, input) {
21784
21939
  const sessionId = nonEmpty(input?.sessionId, "sessionId");
21785
21940
  const sourceWorkspacePath = nonEmpty(input?.sourceWorkspacePath, "sourceWorkspacePath");
21786
- const sessionsRoot = join6(resolve4(nonEmpty(profile?.env?.CODEX_HOME, "profile.env.CODEX_HOME")), "sessions");
21941
+ const sessionsRoot = join7(resolve5(nonEmpty(profile?.env?.CODEX_HOME, "profile.env.CODEX_HOME")), "sessions");
21787
21942
  const sourceRollout = findSessionRollout(sessionsRoot, sessionId);
21788
21943
  const rolloutRelativePath = relative(sessionsRoot, sourceRollout);
21789
21944
  if (!rolloutRelativePath || rolloutRelativePath.startsWith("..") || isAbsolute2(rolloutRelativePath)) {
21790
21945
  throw new Error("codex_managed_mcp_session_rollout_unsafe: rollout escaped the managed Codex home");
21791
21946
  }
21792
- const cacheRoot = join6(dirname2(resolve4(profile.profileRoot)), "session-rollout");
21947
+ const cacheRoot = join7(dirname3(resolve5(profile.profileRoot)), "session-rollout");
21793
21948
  if (existsSync3(cacheRoot)) rmSync3(cacheRoot, { recursive: true, force: false });
21794
21949
  makePrivateDir(cacheRoot);
21795
- const targetRollout = join6(cacheRoot, rolloutRelativePath);
21796
- makePrivateDir(dirname2(targetRollout));
21797
- writePrivateFile(targetRollout, readFileSync(sourceRollout));
21798
- writePrivateFile(join6(cacheRoot, SESSION_ROLLOUT_MARKER), `${JSON.stringify({
21950
+ const targetRollout = join7(cacheRoot, rolloutRelativePath);
21951
+ makePrivateDir(dirname3(targetRollout));
21952
+ writePrivateFile(targetRollout, readFileSync2(sourceRollout));
21953
+ writePrivateFile(join7(cacheRoot, SESSION_ROLLOUT_MARKER), `${JSON.stringify({
21799
21954
  version: 1,
21800
21955
  cacheRoot,
21801
21956
  preservedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -21814,17 +21969,17 @@ function preserveManagedCodexSessionRollout(profile, input) {
21814
21969
  function cleanupRestoredManagedCodexSessionRollout(profile) {
21815
21970
  const restored = profile?.restoredNativeSession;
21816
21971
  if (!restored?.cacheRoot) return { status: "not_restored" };
21817
- const cacheRoot = resolve4(restored.cacheRoot);
21972
+ const cacheRoot = resolve5(restored.cacheRoot);
21818
21973
  if (!existsSync3(cacheRoot)) return { status: "already_removed" };
21819
- const cacheStat = lstatSync4(cacheRoot);
21974
+ const cacheStat = lstatSync5(cacheRoot);
21820
21975
  if (!cacheStat.isDirectory() || cacheStat.isSymbolicLink()) {
21821
21976
  throw new Error("codex_managed_mcp_session_rollout_cleanup_unsafe: cache root is not a private directory");
21822
21977
  }
21823
- const markerPath = join6(cacheRoot, SESSION_ROLLOUT_MARKER);
21824
- if (!existsSync3(markerPath) || lstatSync4(markerPath).isSymbolicLink() || !lstatSync4(markerPath).isFile()) {
21978
+ const markerPath2 = join7(cacheRoot, SESSION_ROLLOUT_MARKER);
21979
+ if (!existsSync3(markerPath2) || lstatSync5(markerPath2).isSymbolicLink() || !lstatSync5(markerPath2).isFile()) {
21825
21980
  throw new Error("codex_managed_mcp_session_rollout_cleanup_unsafe: ownership marker is unavailable");
21826
21981
  }
21827
- const marker = JSON.parse(readFileSync(markerPath, "utf8"));
21982
+ const marker = JSON.parse(readFileSync2(markerPath2, "utf8"));
21828
21983
  if (marker?.companyId !== profile.authority.companyId || marker?.agentId !== profile.authority.agentId || marker?.issueId !== profile.authority.issueId || marker?.sourceRunId !== restored.sourceRunId || marker?.sourceCommandId !== restored.sourceCommandId || marker?.sessionId !== restored.sessionId) {
21829
21984
  throw new Error("codex_managed_mcp_session_rollout_cleanup_unsafe: ownership marker does not match restored authority");
21830
21985
  }
@@ -21833,20 +21988,20 @@ function cleanupRestoredManagedCodexSessionRollout(profile) {
21833
21988
  return { status: "removed" };
21834
21989
  }
21835
21990
  function cleanupManagedCodexMcpProfile(profile, owner) {
21836
- const profileRoot = resolve4(nonEmpty(profile?.profileRoot, "profileRoot"));
21991
+ const profileRoot = resolve5(nonEmpty(profile?.profileRoot, "profileRoot"));
21837
21992
  if (!existsSync3(profileRoot)) return { status: "already_removed", profileRoot };
21838
- const rootStat = lstatSync4(profileRoot);
21993
+ const rootStat = lstatSync5(profileRoot);
21839
21994
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
21840
21995
  throw new Error("codex_managed_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
21841
21996
  }
21842
- const markerPath = join6(profileRoot, PROFILE_MARKER);
21843
- const markerStat = existsSync3(markerPath) ? lstatSync4(markerPath) : null;
21997
+ const markerPath2 = join7(profileRoot, PROFILE_MARKER);
21998
+ const markerStat = existsSync3(markerPath2) ? lstatSync5(markerPath2) : null;
21844
21999
  if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
21845
22000
  throw new Error("codex_managed_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
21846
22001
  }
21847
22002
  let marker;
21848
22003
  try {
21849
- marker = JSON.parse(readFileSync(markerPath, "utf8"));
22004
+ marker = JSON.parse(readFileSync2(markerPath2, "utf8"));
21850
22005
  } catch {
21851
22006
  throw new Error("codex_managed_mcp_cleanup_owner_mismatch: ownership marker is invalid");
21852
22007
  }
@@ -21858,7 +22013,7 @@ function cleanupManagedCodexMcpProfile(profile, owner) {
21858
22013
  return { status: "removed", profileRoot };
21859
22014
  }
21860
22015
  function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
21861
- const root = resolve4(rootPath);
22016
+ const root = resolve5(rootPath);
21862
22017
  if (!existsSync3(root)) return { scanned: 0, removed: 0, removedProfiles: 0, removedRollouts: 0, failed: 0, failures: [] };
21863
22018
  const canonicalRoot = realpathSync4(root);
21864
22019
  const profileMarkers = [];
@@ -21866,10 +22021,10 @@ function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
21866
22021
  const pending = [root];
21867
22022
  while (pending.length > 0) {
21868
22023
  const current = pending.pop();
21869
- const currentStat = lstatSync4(current);
22024
+ const currentStat = lstatSync5(current);
21870
22025
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) continue;
21871
- for (const entry of readdirSync2(current, { withFileTypes: true })) {
21872
- const fullPath = join6(current, entry.name);
22026
+ for (const entry of readdirSync3(current, { withFileTypes: true })) {
22027
+ const fullPath = join7(current, entry.name);
21873
22028
  if (entry.isDirectory() && !entry.isSymbolicLink()) pending.push(fullPath);
21874
22029
  else if (entry.isFile() && entry.name === PROFILE_MARKER) profileMarkers.push(fullPath);
21875
22030
  else if (entry.isFile() && entry.name === SESSION_ROLLOUT_MARKER) rolloutMarkers.push(fullPath);
@@ -21880,11 +22035,11 @@ function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
21880
22035
  let removedRollouts = 0;
21881
22036
  const failures = [];
21882
22037
  const protectedCommandIds = new Set(Array.isArray(options.protectedCommandIds) ? options.protectedCommandIds.filter((value) => typeof value === "string" && value) : []);
21883
- for (const markerPath of profileMarkers) {
21884
- const profileRoot = dirname2(markerPath);
22038
+ for (const markerPath2 of profileMarkers) {
22039
+ const profileRoot = dirname3(markerPath2);
21885
22040
  try {
21886
- const marker = JSON.parse(readFileSync(markerPath, "utf8"));
21887
- const markerProfileRoot = typeof marker?.profileRoot === "string" ? resolve4(marker.profileRoot) : null;
22041
+ const marker = JSON.parse(readFileSync2(markerPath2, "utf8"));
22042
+ const markerProfileRoot = typeof marker?.profileRoot === "string" ? resolve5(marker.profileRoot) : null;
21888
22043
  if (!markerProfileRoot || !existsSync3(markerProfileRoot) || !within(realpathSync4(profileRoot), canonicalRoot) || realpathSync4(markerProfileRoot) !== realpathSync4(profileRoot)) {
21889
22044
  throw new Error("ownership marker root mismatch");
21890
22045
  }
@@ -21900,13 +22055,13 @@ function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
21900
22055
  }
21901
22056
  const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
21902
22057
  const rolloutTtlMs = Number.isFinite(options.sessionRolloutTtlMs) && options.sessionRolloutTtlMs > 0 ? options.sessionRolloutTtlMs : DEFAULT_SESSION_ROLLOUT_TTL_MS;
21903
- for (const markerPath of rolloutMarkers) {
21904
- const cacheRoot = dirname2(markerPath);
22058
+ for (const markerPath2 of rolloutMarkers) {
22059
+ const cacheRoot = dirname3(markerPath2);
21905
22060
  try {
21906
- const markerStat = lstatSync4(markerPath);
21907
- const cacheStat = lstatSync4(cacheRoot);
21908
- const marker = JSON.parse(readFileSync(markerPath, "utf8"));
21909
- const markerCacheRoot = typeof marker?.cacheRoot === "string" ? resolve4(marker.cacheRoot) : null;
22061
+ const markerStat = lstatSync5(markerPath2);
22062
+ const cacheStat = lstatSync5(cacheRoot);
22063
+ const marker = JSON.parse(readFileSync2(markerPath2, "utf8"));
22064
+ const markerCacheRoot = typeof marker?.cacheRoot === "string" ? resolve5(marker.cacheRoot) : null;
21910
22065
  if (!within(realpathSync4(cacheRoot), canonicalRoot) || basename(cacheRoot) !== "session-rollout" || markerStat.isSymbolicLink() || !markerStat.isFile() || cacheStat.isSymbolicLink() || !cacheStat.isDirectory() || marker?.version !== 1 || typeof marker?.companyId !== "string" || typeof marker?.agentId !== "string" || typeof marker?.sourceRunId !== "string" || typeof marker?.sourceCommandId !== "string" || typeof marker?.sessionId !== "string" || markerCacheRoot != null && (!existsSync3(markerCacheRoot) || realpathSync4(markerCacheRoot) !== realpathSync4(cacheRoot))) {
21911
22066
  throw new Error("session rollout ownership marker mismatch");
21912
22067
  }
@@ -21934,23 +22089,23 @@ function reconcileManagedCodexMcpProfiles(rootPath, options = {}) {
21934
22089
  // src/amaster-runtime-daemon/codebuddy-managed-mcp-profile.mjs
21935
22090
  import { createHash as createHash8 } from "node:crypto";
21936
22091
  import {
21937
- chmodSync as chmodSync3,
22092
+ chmodSync as chmodSync4,
21938
22093
  closeSync as closeSync3,
21939
22094
  constants as fsConstants,
21940
22095
  existsSync as existsSync4,
21941
22096
  fstatSync as fstatSync3,
21942
- lstatSync as lstatSync5,
21943
- mkdirSync as mkdirSync4,
22097
+ lstatSync as lstatSync6,
22098
+ mkdirSync as mkdirSync5,
21944
22099
  openSync as openSync3,
21945
- readFileSync as readFileSync2,
21946
- readdirSync as readdirSync3,
22100
+ readFileSync as readFileSync3,
22101
+ readdirSync as readdirSync4,
21947
22102
  realpathSync as realpathSync5,
21948
22103
  rmSync as rmSync4,
21949
22104
  statSync as statSync3,
21950
- writeFileSync as writeFileSync4
22105
+ writeFileSync as writeFileSync5
21951
22106
  } from "node:fs";
21952
22107
  import { arch as arch2, homedir as homedir2, platform as platform2 } from "node:os";
21953
- import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute3, join as join7, parse as parse2, relative as relative2, resolve as resolve5, sep as sep2 } from "node:path";
22108
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join8, parse as parse3, relative as relative2, resolve as resolve6, sep as sep2 } from "node:path";
21954
22109
 
21955
22110
  // src/amaster-runtime-daemon/codebuddy-profile-policy.mjs
21956
22111
  import { createHash as createHash7 } from "node:crypto";
@@ -22071,48 +22226,48 @@ var FULL_DIRECT_TYPED_V1_TOOL_NAMES = /* @__PURE__ */ new Set([
22071
22226
  function record5(value) {
22072
22227
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
22073
22228
  }
22074
- function requiredString(value, label, fail3) {
22075
- if (typeof value !== "string" || value.trim() === "") fail3(`${label} is required`);
22229
+ function requiredString(value, label, fail4) {
22230
+ if (typeof value !== "string" || value.trim() === "") fail4(`${label} is required`);
22076
22231
  return value.trim();
22077
22232
  }
22078
22233
  function validateDirectTypedMcpCatalog(catalogValue, options = {}) {
22079
22234
  const errorPrefix = typeof options.errorPrefix === "string" && options.errorPrefix ? options.errorPrefix : "direct_typed_mcp_invalid";
22080
- const fail3 = (detail) => {
22235
+ const fail4 = (detail) => {
22081
22236
  throw new Error(`${errorPrefix}: ${detail}`);
22082
22237
  };
22083
22238
  const admittedToolNames = options.admittedToolNames instanceof Set ? options.admittedToolNames : options.admittedToolNames == null ? null : new Set(options.admittedToolNames);
22084
22239
  const catalog = record5(catalogValue);
22085
22240
  if (catalog.schemaVersion !== DIRECT_TYPED_MCP_CATALOG_SCHEMA_VERSION) {
22086
- fail3("direct tool catalog schema mismatch");
22241
+ fail4("direct tool catalog schema mismatch");
22087
22242
  }
22088
22243
  const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record5) : [];
22089
22244
  const names = /* @__PURE__ */ new Set();
22090
22245
  const exposedNames = /* @__PURE__ */ new Set();
22091
22246
  const tools = rawTools.map((tool) => {
22092
- const name = requiredString(tool.name, "toolCatalog.tools.name", fail3);
22247
+ const name = requiredString(tool.name, "toolCatalog.tools.name", fail4);
22093
22248
  if (admittedToolNames && !admittedToolNames.has(name) || names.has(name)) {
22094
- fail3("direct tool catalog name mismatch");
22249
+ fail4("direct tool catalog name mismatch");
22095
22250
  }
22096
22251
  names.add(name);
22097
- const exposedName = requiredString(tool.exposedName, `toolCatalog.tools.exposedName:${name}`, fail3);
22252
+ const exposedName = requiredString(tool.exposedName, `toolCatalog.tools.exposedName:${name}`, fail4);
22098
22253
  if (!PROVIDER_SAFE_DIRECT_TOOL_NAME.test(exposedName)) {
22099
- fail3(`direct tool exposed name is unsafe for ${name}`);
22254
+ fail4(`direct tool exposed name is unsafe for ${name}`);
22100
22255
  }
22101
22256
  if (exposedNames.has(exposedName)) {
22102
- fail3(`direct tool exposed name collision for ${exposedName}`);
22257
+ fail4(`direct tool exposed name collision for ${exposedName}`);
22103
22258
  }
22104
22259
  exposedNames.add(exposedName);
22105
22260
  const inputSchema = record5(tool.inputSchema);
22106
22261
  if (inputSchema.type !== "object" || inputSchema.additionalProperties !== false) {
22107
- fail3(`direct tool schema is not strict for ${name}`);
22262
+ fail4(`direct tool schema is not strict for ${name}`);
22108
22263
  }
22109
22264
  const schemaHash = stablePiToolSchemaHash(inputSchema);
22110
22265
  if (tool.schemaHash !== schemaHash) {
22111
- fail3(`direct tool schema hash mismatch for ${name}`);
22266
+ fail4(`direct tool schema hash mismatch for ${name}`);
22112
22267
  }
22113
- const riskLevel = requiredString(tool.riskLevel, `toolCatalog.tools.riskLevel:${name}`, fail3);
22268
+ const riskLevel = requiredString(tool.riskLevel, `toolCatalog.tools.riskLevel:${name}`, fail4);
22114
22269
  if (!(/* @__PURE__ */ new Set(["read", "write", "destructive"])).has(riskLevel)) {
22115
- fail3(`direct tool risk level mismatch for ${name}`);
22270
+ fail4(`direct tool risk level mismatch for ${name}`);
22116
22271
  }
22117
22272
  return {
22118
22273
  name,
@@ -22130,7 +22285,7 @@ function validateDirectTypedMcpCatalog(catalogValue, options = {}) {
22130
22285
  schemaHash: tool.schemaHash,
22131
22286
  riskLevel: tool.riskLevel
22132
22287
  })));
22133
- if (catalog.setHash !== setHash) fail3("direct tool catalog set hash mismatch");
22288
+ if (catalog.setHash !== setHash) fail4("direct tool catalog set hash mismatch");
22134
22289
  return {
22135
22290
  setHash,
22136
22291
  tools: tools.sort((left, right) => left.name.localeCompare(right.name))
@@ -22304,7 +22459,7 @@ var CODEBUDDY_PROFILE_COMPATIBILITY_ALLOWLIST = Object.freeze([
22304
22459
  function record6(value) {
22305
22460
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
22306
22461
  }
22307
- function fail(detail) {
22462
+ function fail2(detail) {
22308
22463
  throw new Error(`codebuddy_managed_mcp_invalid: ${detail}`);
22309
22464
  }
22310
22465
  function sha256(value) {
@@ -22317,7 +22472,7 @@ function classifyCodebuddyFormalTool(tool) {
22317
22472
  const mustDirect = MUST_DIRECT_TOOL_NAMES.has(tool.name);
22318
22473
  const vettedRead = VETTED_DEFERRED_READ_TOOL_NAMES.has(tool.name);
22319
22474
  if (mustDirect === vettedRead || vettedRead && tool.riskLevel !== "read") {
22320
- fail(`direct tool classification mismatch for ${tool.name}`);
22475
+ fail2(`direct tool classification mismatch for ${tool.name}`);
22321
22476
  }
22322
22477
  return { mustDirect, vettedRead };
22323
22478
  }
@@ -22329,12 +22484,12 @@ function assertFormalCatalogShape(rawTools) {
22329
22484
  const hasWikiWrite = names.has(FULL_DIRECT_TYPED_V1_WIKI_WRITE_TOOL_NAME);
22330
22485
  const connectorCount = countIn(FULL_DIRECT_TYPED_V1_CONNECTOR_TOOL_NAMES);
22331
22486
  const fullCatalog = rawTools.length === FULL_DIRECT_TYPED_V1_BASE_TOOL_NAMES.size + wikiReadCount + (hasWikiWrite ? 1 : 0) + connectorCount && covers(FULL_DIRECT_TYPED_V1_BASE_TOOL_NAMES) && (wikiReadCount === 0 && !hasWikiWrite || wikiReadCount === FULL_DIRECT_TYPED_V1_WIKI_READ_TOOL_NAMES.size) && (connectorCount === 0 || connectorCount === FULL_DIRECT_TYPED_V1_CONNECTOR_TOOL_NAMES.size) && rawTools.every((tool) => FULL_DIRECT_TYPED_V1_TOOL_NAMES.has(tool.name));
22332
- if (!fullCatalog) fail("direct tool catalog size mismatch");
22487
+ if (!fullCatalog) fail2("direct tool catalog size mismatch");
22333
22488
  }
22334
22489
  function validateCodebuddyFormalToolCatalog(gatewayValue) {
22335
22490
  const gateway = record6(gatewayValue);
22336
22491
  if ((gateway.mcpToolMode ?? "direct_typed") !== "direct_typed") {
22337
- fail("direct tool mode required");
22492
+ fail2("direct tool mode required");
22338
22493
  }
22339
22494
  const catalog = record6(gateway.toolCatalog);
22340
22495
  const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record6) : [];
@@ -22392,14 +22547,14 @@ function codebuddyProfileSchemaBytesMatchCatalog(catalogValue, attestationValue)
22392
22547
  }
22393
22548
  function deriveCodebuddyProfilePolicy(input = {}) {
22394
22549
  const catalog = input.catalog;
22395
- if (!catalog || !Array.isArray(catalog.tools)) fail("validated catalog is required");
22550
+ if (!catalog || !Array.isArray(catalog.tools)) fail2("validated catalog is required");
22396
22551
  const mcpMode = input.mcpMode;
22397
22552
  const bashMode = input.bashMode;
22398
- if (!CODEBUDDY_MCP_MODES.includes(mcpMode)) fail("mcp mode mismatch");
22399
- if (!CODEBUDDY_BASH_MODES.includes(bashMode)) fail("bash mode mismatch");
22553
+ if (!CODEBUDDY_MCP_MODES.includes(mcpMode)) fail2("mcp mode mismatch");
22554
+ if (!CODEBUDDY_BASH_MODES.includes(bashMode)) fail2("bash mode mismatch");
22400
22555
  const targetPlatform = input.platform ?? hostPlatform();
22401
22556
  if (bashMode === "sandboxed" && !["darwin", "linux"].includes(targetPlatform)) {
22402
- fail("sandboxed Bash platform unsupported");
22557
+ fail2("sandboxed Bash platform unsupported");
22403
22558
  }
22404
22559
  const classifiedTools = catalog.tools.map((tool) => {
22405
22560
  const { vettedRead } = classifyCodebuddyFormalTool(tool);
@@ -22650,12 +22805,12 @@ function nonEmpty2(value, label) {
22650
22805
  return value.trim();
22651
22806
  }
22652
22807
  function privateDir(path) {
22653
- mkdirSync4(path, { recursive: true, mode: 448 });
22654
- chmodSync3(path, 448);
22808
+ mkdirSync5(path, { recursive: true, mode: 448 });
22809
+ chmodSync4(path, 448);
22655
22810
  }
22656
22811
  function privateFile(path, value) {
22657
- writeFileSync4(path, value, { flag: "wx", mode: 384 });
22658
- chmodSync3(path, 384);
22812
+ writeFileSync5(path, value, { flag: "wx", mode: 384 });
22813
+ chmodSync4(path, 384);
22659
22814
  if ((statSync3(path).mode & 511) !== 384) {
22660
22815
  throw new Error(`codebuddy_managed_mcp_permissions_failed: ${path}`);
22661
22816
  }
@@ -22666,16 +22821,16 @@ function within2(candidate, root) {
22666
22821
  }
22667
22822
  function codebuddyIsolatedAuthRelativePath(targetPlatform = platform2()) {
22668
22823
  if (targetPlatform === "darwin") {
22669
- return join7("Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth");
22824
+ return join8("Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth");
22670
22825
  }
22671
22826
  if (targetPlatform === "linux") {
22672
- return join7(".local", "share", "CodeBuddyExtension", "Data", "Public", "auth");
22827
+ return join8(".local", "share", "CodeBuddyExtension", "Data", "Public", "auth");
22673
22828
  }
22674
22829
  throw new Error(`codebuddy_managed_mcp_desktop_auth_unsupported: platform ${targetPlatform} is not supported`);
22675
22830
  }
22676
22831
  function codebuddyDesktopAuthDirectory(sourceHome, sourceEnv, targetPlatform) {
22677
22832
  if (targetPlatform === "darwin") {
22678
- return join7(sourceHome, codebuddyIsolatedAuthRelativePath(targetPlatform));
22833
+ return join8(sourceHome, codebuddyIsolatedAuthRelativePath(targetPlatform));
22679
22834
  }
22680
22835
  if (targetPlatform === "linux") {
22681
22836
  const xdgDataHome = typeof sourceEnv?.XDG_DATA_HOME === "string" ? sourceEnv.XDG_DATA_HOME.trim() : "";
@@ -22683,20 +22838,20 @@ function codebuddyDesktopAuthDirectory(sourceHome, sourceEnv, targetPlatform) {
22683
22838
  if (!isAbsolute3(xdgDataHome)) {
22684
22839
  throw new Error("codebuddy_managed_mcp_desktop_auth_xdg_invalid: XDG_DATA_HOME must be absolute");
22685
22840
  }
22686
- const resolvedXdgDataHome = resolve5(xdgDataHome);
22841
+ const resolvedXdgDataHome = resolve6(xdgDataHome);
22687
22842
  const canonicalXdgDataHome = existsSync4(resolvedXdgDataHome) ? realpathSync5(resolvedXdgDataHome) : resolvedXdgDataHome;
22688
- return join7(canonicalXdgDataHome, "CodeBuddyExtension", "Data", "Public", "auth");
22843
+ return join8(canonicalXdgDataHome, "CodeBuddyExtension", "Data", "Public", "auth");
22689
22844
  }
22690
- return join7(sourceHome, codebuddyIsolatedAuthRelativePath(targetPlatform));
22845
+ return join8(sourceHome, codebuddyIsolatedAuthRelativePath(targetPlatform));
22691
22846
  }
22692
22847
  throw new Error(`codebuddy_managed_mcp_desktop_auth_unsupported: platform ${targetPlatform} is not supported`);
22693
22848
  }
22694
22849
  function absolutePathChain(path) {
22695
- const absolute = resolve5(path);
22696
- const root = parse2(absolute).root;
22850
+ const absolute = resolve6(path);
22851
+ const root = parse3(absolute).root;
22697
22852
  const components = relative2(root, absolute).split(sep2).filter(Boolean);
22698
22853
  const chain = [root];
22699
- for (const component of components) chain.push(join7(chain.at(-1), component));
22854
+ for (const component of components) chain.push(join8(chain.at(-1), component));
22700
22855
  return chain;
22701
22856
  }
22702
22857
  function sameFileIdentity(left, right) {
@@ -22707,7 +22862,7 @@ function sameTrustedFileMetadata(left, right) {
22707
22862
  }
22708
22863
  function lstatIfPresent(path) {
22709
22864
  try {
22710
- return lstatSync5(path);
22865
+ return lstatSync6(path);
22711
22866
  } catch (error) {
22712
22867
  if (error && typeof error === "object" && error.code === "ENOENT") return null;
22713
22868
  throw error;
@@ -22715,12 +22870,12 @@ function lstatIfPresent(path) {
22715
22870
  }
22716
22871
  function inspectCodebuddyDesktopAuthDirectory(sourceHome = homedir2(), sourceEnv = process.env, targetPlatform = platform2()) {
22717
22872
  try {
22718
- const resolvedSourceHome = realpathSync5(resolve5(nonEmpty2(sourceHome, "desktopHome")));
22873
+ const resolvedSourceHome = realpathSync5(resolve6(nonEmpty2(sourceHome, "desktopHome")));
22719
22874
  const sourceAuthDir = codebuddyDesktopAuthDirectory(resolvedSourceHome, sourceEnv, targetPlatform);
22720
22875
  if (!lstatIfPresent(sourceAuthDir)) {
22721
22876
  return { available: false, source: CODEBUDDY_DESKTOP_AUTH_SOURCE, reasonCode: "desktop_auth_directory_missing" };
22722
22877
  }
22723
- const sourceAuthFile = join7(sourceAuthDir, CODEBUDDY_WORKBUDDY_AUTH_FILE);
22878
+ const sourceAuthFile = join8(sourceAuthDir, CODEBUDDY_WORKBUDDY_AUTH_FILE);
22724
22879
  if (!lstatIfPresent(sourceAuthFile)) {
22725
22880
  return { available: false, source: CODEBUDDY_DESKTOP_AUTH_SOURCE, reasonCode: "desktop_login_missing" };
22726
22881
  }
@@ -22731,7 +22886,7 @@ function inspectCodebuddyDesktopAuthDirectory(sourceHome = homedir2(), sourceEnv
22731
22886
  const currentUid = typeof process.getuid === "function" ? process.getuid() : null;
22732
22887
  const pathChain = [];
22733
22888
  for (const candidate of chain) {
22734
- const candidateStat = lstatSync5(candidate);
22889
+ const candidateStat = lstatSync6(candidate);
22735
22890
  const isAuthFile = candidate === sourceAuthFile;
22736
22891
  const isAuthDir = candidate === sourceAuthDir;
22737
22892
  if (candidateStat.isSymbolicLink() || (isAuthFile ? !candidateStat.isFile() : !candidateStat.isDirectory())) {
@@ -22810,7 +22965,7 @@ function snapshotCodebuddyDesktopAuth(sourceHome, sourceEnv, isolatedHome) {
22810
22965
  if (!openedStat.isFile() || openedStat.size <= 0 || openedStat.size > MAX_CODEBUDDY_DESKTOP_AUTH_BYTES) {
22811
22966
  throw new Error("codebuddy_managed_mcp_desktop_auth_unsafe: source auth file is invalid");
22812
22967
  }
22813
- authSnapshot = readFileSync2(fd);
22968
+ authSnapshot = readFileSync3(fd);
22814
22969
  const afterReadStat = fstatSync3(fd);
22815
22970
  if (!sameTrustedFileMetadata(openedStat, afterReadStat) || openedStat.size !== afterReadStat.size || openedStat.mtimeMs !== afterReadStat.mtimeMs || authSnapshot.length !== openedStat.size) {
22816
22971
  throw new Error("codebuddy_managed_mcp_desktop_auth_changed: source auth file changed during snapshot");
@@ -22818,7 +22973,7 @@ function snapshotCodebuddyDesktopAuth(sourceHome, sourceEnv, isolatedHome) {
22818
22973
  }
22819
22974
  }
22820
22975
  for (const entry of inspected.pathChain) {
22821
- const currentStat = lstatSync5(entry.path);
22976
+ const currentStat = lstatSync6(entry.path);
22822
22977
  if (currentStat.isSymbolicLink() || !sameTrustedFileMetadata(currentStat, entry.stat)) {
22823
22978
  throw new Error("codebuddy_managed_mcp_desktop_auth_changed: source path changed during snapshot");
22824
22979
  }
@@ -22826,9 +22981,9 @@ function snapshotCodebuddyDesktopAuth(sourceHome, sourceEnv, isolatedHome) {
22826
22981
  if (lstatIfPresent(`${inspected.sourceAuthFile}.logged-out`)) {
22827
22982
  throw new Error("codebuddy_managed_mcp_desktop_auth_changed: desktop session logged out during snapshot");
22828
22983
  }
22829
- const targetAuthDir = join7(isolatedHome, codebuddyIsolatedAuthRelativePath());
22984
+ const targetAuthDir = join8(isolatedHome, codebuddyIsolatedAuthRelativePath());
22830
22985
  privateDir(targetAuthDir);
22831
- const targetAuthFile = join7(targetAuthDir, CODEBUDDY_WORKBUDDY_AUTH_FILE);
22986
+ const targetAuthFile = join8(targetAuthDir, CODEBUDDY_WORKBUDDY_AUTH_FILE);
22832
22987
  privateFile(targetAuthFile, authSnapshot);
22833
22988
  return {
22834
22989
  authMode: CODEBUDDY_DESKTOP_AUTH_SOURCE,
@@ -22846,7 +23001,7 @@ function snapshotCodebuddyDesktopAuth(sourceHome, sourceEnv, isolatedHome) {
22846
23001
  }
22847
23002
  }
22848
23003
  function findCodebuddySession(configDir, sessionId) {
22849
- const projectsRoot = join7(configDir, "projects");
23004
+ const projectsRoot = join8(configDir, "projects");
22850
23005
  if (!existsSync4(projectsRoot)) {
22851
23006
  throw new Error(`codebuddy_managed_mcp_session_rollout_missing: projects root is unavailable for ${sessionId}`);
22852
23007
  }
@@ -22854,12 +23009,12 @@ function findCodebuddySession(configDir, sessionId) {
22854
23009
  const pending = [projectsRoot];
22855
23010
  while (pending.length > 0) {
22856
23011
  const current = pending.pop();
22857
- const currentStat = lstatSync5(current);
23012
+ const currentStat = lstatSync6(current);
22858
23013
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) {
22859
23014
  throw new Error("codebuddy_managed_mcp_session_rollout_unsafe: projects path is not a private directory");
22860
23015
  }
22861
- for (const entry of readdirSync3(current, { withFileTypes: true })) {
22862
- const candidate = join7(current, entry.name);
23016
+ for (const entry of readdirSync4(current, { withFileTypes: true })) {
23017
+ const candidate = join8(current, entry.name);
22863
23018
  if (entry.isSymbolicLink()) {
22864
23019
  throw new Error("codebuddy_managed_mcp_session_rollout_unsafe: symlinks are forbidden");
22865
23020
  }
@@ -22888,29 +23043,29 @@ function restoreManagedCodebuddySessionRollout(input, configDir, runDir, executo
22888
23043
  nonEmpty2(session.invocationId, "nativeSession.invocationId");
22889
23044
  }
22890
23045
  const sourceWorkspacePath = nonEmpty2(session.cwd, "nativeSession.cwd");
22891
- const issueRoot = dirname3(runDir);
23046
+ const issueRoot = dirname4(runDir);
22892
23047
  const managedSourceRunName = `${sourceRunId}-${createHash8("sha256").update(sourceRunId).digest("hex").slice(0, 8)}`;
22893
- const sourceRuns = readdirSync3(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && [sourceRunId, managedSourceRunName].includes(entry.name)).map((entry) => join7(issueRoot, entry.name));
23048
+ const sourceRuns = readdirSync4(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && [sourceRunId, managedSourceRunName].includes(entry.name)).map((entry) => join8(issueRoot, entry.name));
22894
23049
  if (sourceRuns.length !== 1) {
22895
23050
  throw new Error(`codebuddy_managed_mcp_session_rollout_missing: expected one source run directory for ${sourceRunId}, received ${sourceRuns.length}`);
22896
23051
  }
22897
23052
  const executorRelativePath = relative2(runDir, executorHome);
22898
- const cacheRoot = join7(sourceRuns[0], executorRelativePath, "session-rollout");
22899
- const markerPath = join7(cacheRoot, SESSION_ROLLOUT_MARKER2);
22900
- if (!existsSync4(markerPath) || lstatSync5(markerPath).isSymbolicLink() || !lstatSync5(markerPath).isFile()) {
23053
+ const cacheRoot = join8(sourceRuns[0], executorRelativePath, "session-rollout");
23054
+ const markerPath2 = join8(cacheRoot, SESSION_ROLLOUT_MARKER2);
23055
+ if (!existsSync4(markerPath2) || lstatSync6(markerPath2).isSymbolicLink() || !lstatSync6(markerPath2).isFile()) {
22901
23056
  throw new Error("codebuddy_managed_mcp_session_rollout_missing: source rollout marker is unavailable");
22902
23057
  }
22903
- const marker = JSON.parse(readFileSync2(markerPath, "utf8"));
23058
+ const marker = JSON.parse(readFileSync3(markerPath2, "utf8"));
22904
23059
  if (marker.version !== 1 || marker.companyId !== authority.companyId || marker.agentId !== authority.agentId || marker.issueId !== authority.issueId || marker.sourceRunId !== sourceRunId || marker.sourceCommandId !== sourceCommandId || marker.sessionId !== sessionId || marker.sourceWorkspacePath !== sourceWorkspacePath) {
22905
23060
  throw new Error("codebuddy_managed_mcp_session_rollout_authority_mismatch: source rollout does not match the governed continuation");
22906
23061
  }
22907
- const sourceRollout = resolve5(cacheRoot, nonEmpty2(marker.rolloutRelativePath, "rolloutRelativePath"));
22908
- if (!within2(sourceRollout, cacheRoot) || lstatSync5(sourceRollout).isSymbolicLink() || !lstatSync5(sourceRollout).isFile()) {
23062
+ const sourceRollout = resolve6(cacheRoot, nonEmpty2(marker.rolloutRelativePath, "rolloutRelativePath"));
23063
+ if (!within2(sourceRollout, cacheRoot) || lstatSync6(sourceRollout).isSymbolicLink() || !lstatSync6(sourceRollout).isFile()) {
22909
23064
  throw new Error("codebuddy_managed_mcp_session_rollout_unsafe: source rollout path is invalid");
22910
23065
  }
22911
- const targetRollout = join7(configDir, "projects", codebuddyProjectKey(input.cwd), `${sessionId}.jsonl`);
22912
- privateDir(dirname3(targetRollout));
22913
- privateFile(targetRollout, readFileSync2(sourceRollout));
23066
+ const targetRollout = join8(configDir, "projects", codebuddyProjectKey(input.cwd), `${sessionId}.jsonl`);
23067
+ privateDir(dirname4(targetRollout));
23068
+ privateFile(targetRollout, readFileSync3(sourceRollout));
22914
23069
  return { sessionId, sourceRunId, sourceCommandId, rolloutPath: targetRollout, cacheRoot };
22915
23070
  }
22916
23071
  function resolveManagedCodebuddySessionRollout(input, configDir, runDir, executorHome, authority) {
@@ -23049,7 +23204,7 @@ function attestCli(executorCommand, env, cwd) {
23049
23204
  return attestCodebuddyCommand(executorCommand, env, cwd).executorVersion;
23050
23205
  }
23051
23206
  function canonicalCodebuddyCwd(value) {
23052
- const requestedCwd = resolve5(nonEmpty2(value, "cwd"));
23207
+ const requestedCwd = resolve6(nonEmpty2(value, "cwd"));
23053
23208
  try {
23054
23209
  const canonicalCwd = realpathSync5(requestedCwd);
23055
23210
  if (!statSync3(canonicalCwd).isDirectory()) {
@@ -23065,19 +23220,19 @@ function canonicalCodebuddyCwd(value) {
23065
23220
  }
23066
23221
  function prepareManagedCodebuddyMcpProfile(input, options = {}) {
23067
23222
  const authority = validateAuthority2(input);
23068
- const runDir = resolve5(nonEmpty2(input.runDir, "runDir"));
23069
- const executorHome = resolve5(nonEmpty2(input.executorHome, "executorHome"));
23223
+ const runDir = resolve6(nonEmpty2(input.runDir, "runDir"));
23224
+ const executorHome = resolve6(nonEmpty2(input.executorHome, "executorHome"));
23070
23225
  const cwd = canonicalCodebuddyCwd(input.cwd);
23071
- if (!within2(executorHome, join7(runDir, "executors"))) {
23226
+ if (!within2(executorHome, join8(runDir, "executors"))) {
23072
23227
  throw new Error("codebuddy_managed_mcp_owner_mismatch: executorHome is outside the managed run");
23073
23228
  }
23074
- const profileRoot = join7(executorHome, "managed-mcp");
23229
+ const profileRoot = join8(executorHome, "managed-mcp");
23075
23230
  if (existsSync4(profileRoot)) throw new Error(`codebuddy_managed_mcp_profile_exists: ${profileRoot}`);
23076
23231
  privateDir(profileRoot);
23077
23232
  try {
23078
- const home = join7(profileRoot, "home");
23079
- const configDir = join7(profileRoot, "codebuddy-config");
23080
- const tmp = join7(profileRoot, "tmp");
23233
+ const home = join8(profileRoot, "home");
23234
+ const configDir = join8(profileRoot, "codebuddy-config");
23235
+ const tmp = join8(profileRoot, "tmp");
23081
23236
  privateDir(home);
23082
23237
  privateDir(configDir);
23083
23238
  privateDir(tmp);
@@ -23089,11 +23244,11 @@ function prepareManagedCodebuddyMcpProfile(input, options = {}) {
23089
23244
  runId: owner.runId,
23090
23245
  commandId: owner.commandId
23091
23246
  });
23092
- const markerPath = join7(profileRoot, PROFILE_MARKER2);
23093
- privateFile(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot })}
23247
+ const markerPath2 = join8(profileRoot, PROFILE_MARKER2);
23248
+ privateFile(markerPath2, `${JSON.stringify({ version: 1, ...owner, profileRoot })}
23094
23249
  `);
23095
- const mcpConfigPath = join7(profileRoot, "mcp.json");
23096
- const settingsPath = join7(profileRoot, "settings.json");
23250
+ const mcpConfigPath = join8(profileRoot, "mcp.json");
23251
+ const settingsPath = join8(profileRoot, "settings.json");
23097
23252
  const provider = codebuddyProviderEnvironment(input.baseEnv, input.commandEnv);
23098
23253
  const desktopAuthSnapshot = provider.authMode ? null : snapshotCodebuddyDesktopAuth(input.desktopHome ?? homedir2(), input.desktopEnv ?? process.env, home);
23099
23254
  const env = {
@@ -23190,7 +23345,7 @@ function prepareManagedCodebuddyMcpProfile(input, options = {}) {
23190
23345
  return {
23191
23346
  profileRoot,
23192
23347
  cwd,
23193
- markerPath,
23348
+ markerPath: markerPath2,
23194
23349
  mcpConfigPath,
23195
23350
  settingsPath,
23196
23351
  env,
@@ -23222,15 +23377,15 @@ function prepareManagedCodebuddyMcpProfile(input, options = {}) {
23222
23377
  function preserveManagedCodebuddySessionRollout(profile, input) {
23223
23378
  const sessionId = nonEmpty2(input?.sessionId, "sessionId");
23224
23379
  const sourceWorkspacePath = nonEmpty2(input?.sourceWorkspacePath, "sourceWorkspacePath");
23225
- const configDir = resolve5(nonEmpty2(profile?.env?.CODEBUDDY_CONFIG_DIR, "profile.env.CODEBUDDY_CONFIG_DIR"));
23380
+ const configDir = resolve6(nonEmpty2(profile?.env?.CODEBUDDY_CONFIG_DIR, "profile.env.CODEBUDDY_CONFIG_DIR"));
23226
23381
  const sourceSession = findCodebuddySession(configDir, sessionId);
23227
- const cacheRoot = join7(dirname3(resolve5(profile.profileRoot)), "session-rollout");
23382
+ const cacheRoot = join8(dirname4(resolve6(profile.profileRoot)), "session-rollout");
23228
23383
  if (existsSync4(cacheRoot)) rmSync4(cacheRoot, { recursive: true, force: false });
23229
23384
  privateDir(cacheRoot);
23230
23385
  const rolloutRelativePath = `${sessionId}.jsonl`;
23231
- const targetSession = join7(cacheRoot, rolloutRelativePath);
23232
- privateFile(targetSession, readFileSync2(sourceSession));
23233
- privateFile(join7(cacheRoot, SESSION_ROLLOUT_MARKER2), `${JSON.stringify({
23386
+ const targetSession = join8(cacheRoot, rolloutRelativePath);
23387
+ privateFile(targetSession, readFileSync3(sourceSession));
23388
+ privateFile(join8(cacheRoot, SESSION_ROLLOUT_MARKER2), `${JSON.stringify({
23234
23389
  version: 1,
23235
23390
  cacheRoot,
23236
23391
  preservedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -23249,16 +23404,16 @@ function preserveManagedCodebuddySessionRollout(profile, input) {
23249
23404
  function cleanupRestoredManagedCodebuddySessionRollout(profile) {
23250
23405
  const restored = profile?.restoredNativeSession;
23251
23406
  if (!restored?.cacheRoot) return { status: "not_restored" };
23252
- const cacheRoot = resolve5(restored.cacheRoot);
23407
+ const cacheRoot = resolve6(restored.cacheRoot);
23253
23408
  if (!existsSync4(cacheRoot)) return { status: "already_removed" };
23254
- if (!lstatSync5(cacheRoot).isDirectory() || lstatSync5(cacheRoot).isSymbolicLink()) {
23409
+ if (!lstatSync6(cacheRoot).isDirectory() || lstatSync6(cacheRoot).isSymbolicLink()) {
23255
23410
  throw new Error("codebuddy_managed_mcp_session_rollout_cleanup_unsafe: cache root is not a private directory");
23256
23411
  }
23257
- const markerPath = join7(cacheRoot, SESSION_ROLLOUT_MARKER2);
23258
- if (!existsSync4(markerPath) || lstatSync5(markerPath).isSymbolicLink() || !lstatSync5(markerPath).isFile()) {
23412
+ const markerPath2 = join8(cacheRoot, SESSION_ROLLOUT_MARKER2);
23413
+ if (!existsSync4(markerPath2) || lstatSync6(markerPath2).isSymbolicLink() || !lstatSync6(markerPath2).isFile()) {
23259
23414
  throw new Error("codebuddy_managed_mcp_session_rollout_cleanup_unsafe: ownership marker is unavailable");
23260
23415
  }
23261
- const marker = JSON.parse(readFileSync2(markerPath, "utf8"));
23416
+ const marker = JSON.parse(readFileSync3(markerPath2, "utf8"));
23262
23417
  if (marker.companyId !== profile.authority.companyId || marker.agentId !== profile.authority.agentId || marker.issueId !== profile.authority.issueId || marker.sourceRunId !== restored.sourceRunId || marker.sourceCommandId !== restored.sourceCommandId || marker.sessionId !== restored.sessionId) {
23263
23418
  throw new Error("codebuddy_managed_mcp_session_rollout_cleanup_unsafe: ownership marker does not match restored authority");
23264
23419
  }
@@ -23269,20 +23424,20 @@ function cleanupRestoredManagedCodebuddySessionRollout(profile) {
23269
23424
  return { status: "removed" };
23270
23425
  }
23271
23426
  function cleanupManagedCodebuddyMcpProfile(profile, expectedOwner) {
23272
- const profileRoot = resolve5(nonEmpty2(profile?.profileRoot, "profileRoot"));
23427
+ const profileRoot = resolve6(nonEmpty2(profile?.profileRoot, "profileRoot"));
23273
23428
  if (!existsSync4(profileRoot)) return { status: "already_removed", profileRoot };
23274
- const rootStat = lstatSync5(profileRoot);
23429
+ const rootStat = lstatSync6(profileRoot);
23275
23430
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
23276
23431
  throw new Error("codebuddy_managed_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
23277
23432
  }
23278
- const markerPath = join7(profileRoot, PROFILE_MARKER2);
23279
- const markerStat = existsSync4(markerPath) ? lstatSync5(markerPath) : null;
23433
+ const markerPath2 = join8(profileRoot, PROFILE_MARKER2);
23434
+ const markerStat = existsSync4(markerPath2) ? lstatSync6(markerPath2) : null;
23280
23435
  if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
23281
23436
  throw new Error("codebuddy_managed_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
23282
23437
  }
23283
23438
  let marker;
23284
23439
  try {
23285
- marker = JSON.parse(readFileSync2(markerPath, "utf8"));
23440
+ marker = JSON.parse(readFileSync3(markerPath2, "utf8"));
23286
23441
  } catch {
23287
23442
  throw new Error("codebuddy_managed_mcp_cleanup_owner_mismatch: ownership marker is invalid");
23288
23443
  }
@@ -23294,7 +23449,7 @@ function cleanupManagedCodebuddyMcpProfile(profile, expectedOwner) {
23294
23449
  return { status: "removed", profileRoot };
23295
23450
  }
23296
23451
  function reconcileManagedCodebuddyMcpProfiles(rootPath, options = {}) {
23297
- const root = resolve5(rootPath);
23452
+ const root = resolve6(rootPath);
23298
23453
  if (!existsSync4(root)) {
23299
23454
  return { scanned: 0, removed: 0, removedProfiles: 0, preservedProfiles: 0, removedRollouts: 0, failed: 0, failures: [] };
23300
23455
  }
@@ -23304,10 +23459,10 @@ function reconcileManagedCodebuddyMcpProfiles(rootPath, options = {}) {
23304
23459
  const pending = [root];
23305
23460
  while (pending.length > 0) {
23306
23461
  const current = pending.pop();
23307
- const currentStat = lstatSync5(current);
23462
+ const currentStat = lstatSync6(current);
23308
23463
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) continue;
23309
- for (const entry of readdirSync3(current, { withFileTypes: true })) {
23310
- const fullPath = join7(current, entry.name);
23464
+ for (const entry of readdirSync4(current, { withFileTypes: true })) {
23465
+ const fullPath = join8(current, entry.name);
23311
23466
  if (entry.isDirectory() && !entry.isSymbolicLink()) pending.push(fullPath);
23312
23467
  else if (entry.isFile() && entry.name === PROFILE_MARKER2) profileMarkers.push(fullPath);
23313
23468
  else if (entry.isFile() && entry.name === SESSION_ROLLOUT_MARKER2) rolloutMarkers.push(fullPath);
@@ -23318,11 +23473,11 @@ function reconcileManagedCodebuddyMcpProfiles(rootPath, options = {}) {
23318
23473
  let preservedProfiles = 0;
23319
23474
  let removedRollouts = 0;
23320
23475
  const failures = [];
23321
- for (const markerPath of profileMarkers) {
23322
- const profileRoot = dirname3(markerPath);
23476
+ for (const markerPath2 of profileMarkers) {
23477
+ const profileRoot = dirname4(markerPath2);
23323
23478
  try {
23324
- const marker = JSON.parse(readFileSync2(markerPath, "utf8"));
23325
- const markerProfileRoot = typeof marker.profileRoot === "string" ? resolve5(marker.profileRoot) : null;
23479
+ const marker = JSON.parse(readFileSync3(markerPath2, "utf8"));
23480
+ const markerProfileRoot = typeof marker.profileRoot === "string" ? resolve6(marker.profileRoot) : null;
23326
23481
  if (!markerProfileRoot || !existsSync4(markerProfileRoot) || !within2(realpathSync5(profileRoot), canonicalRoot) || realpathSync5(markerProfileRoot) !== realpathSync5(profileRoot)) throw new Error("ownership marker root mismatch");
23327
23482
  if (protectedCommandIds.has(marker.commandId)) {
23328
23483
  preservedProfiles += 1;
@@ -23339,13 +23494,13 @@ function reconcileManagedCodebuddyMcpProfiles(rootPath, options = {}) {
23339
23494
  }
23340
23495
  const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now();
23341
23496
  const rolloutTtlMs = Number.isFinite(options.sessionRolloutTtlMs) && options.sessionRolloutTtlMs > 0 ? options.sessionRolloutTtlMs : DEFAULT_SESSION_ROLLOUT_TTL_MS2;
23342
- for (const markerPath of rolloutMarkers) {
23343
- const cacheRoot = dirname3(markerPath);
23497
+ for (const markerPath2 of rolloutMarkers) {
23498
+ const cacheRoot = dirname4(markerPath2);
23344
23499
  try {
23345
- const markerStat = lstatSync5(markerPath);
23346
- const cacheStat = lstatSync5(cacheRoot);
23347
- const marker = JSON.parse(readFileSync2(markerPath, "utf8"));
23348
- if (!within2(realpathSync5(cacheRoot), canonicalRoot) || basename2(cacheRoot) !== "session-rollout" || markerStat.isSymbolicLink() || !markerStat.isFile() || cacheStat.isSymbolicLink() || !cacheStat.isDirectory() || marker.version !== 1 || resolve5(marker.cacheRoot) !== resolve5(cacheRoot)) throw new Error("session rollout ownership marker mismatch");
23500
+ const markerStat = lstatSync6(markerPath2);
23501
+ const cacheStat = lstatSync6(cacheRoot);
23502
+ const marker = JSON.parse(readFileSync3(markerPath2, "utf8"));
23503
+ if (!within2(realpathSync5(cacheRoot), canonicalRoot) || basename2(cacheRoot) !== "session-rollout" || markerStat.isSymbolicLink() || !markerStat.isFile() || cacheStat.isSymbolicLink() || !cacheStat.isDirectory() || marker.version !== 1 || resolve6(marker.cacheRoot) !== resolve6(cacheRoot)) throw new Error("session rollout ownership marker mismatch");
23349
23504
  const preservedAtMs = Date.parse(marker.preservedAt);
23350
23505
  const ageMs = nowMs - (Number.isFinite(preservedAtMs) ? preservedAtMs : markerStat.mtimeMs);
23351
23506
  if (ageMs < rolloutTtlMs) continue;
@@ -23373,14 +23528,14 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23373
23528
  const receipts = [];
23374
23529
  let stage = "upload";
23375
23530
  let callId;
23376
- const fail3 = (code, detail) => {
23531
+ const fail4 = (code, detail) => {
23377
23532
  throw Object.assign(new Error(code), { detail });
23378
23533
  };
23379
23534
  async function invoke(name, args) {
23380
- if (now() >= deadline) fail3("initialization_completion_deadline");
23535
+ if (now() >= deadline) fail4("initialization_completion_deadline");
23381
23536
  let envelope;
23382
23537
  for (let transportFailures = 0; ; ) {
23383
- if (now() >= deadline) fail3("initialization_completion_deadline");
23538
+ if (now() >= deadline) fail4("initialization_completion_deadline");
23384
23539
  try {
23385
23540
  envelope = await call(name, args, Math.min(45e3, deadline - now()));
23386
23541
  break;
@@ -23394,10 +23549,10 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23394
23549
  }
23395
23550
  const content = envelope?.content;
23396
23551
  if (!envelope?.invocationId || !content || typeof content !== "object" || content?.toolName !== name.replace("runtime_action_", "runtime_action.")) {
23397
- fail3("initialization_completion_receipt_mismatch");
23552
+ fail4("initialization_completion_receipt_mismatch");
23398
23553
  }
23399
23554
  if (envelope.status !== "succeeded" || !["accepted", "pending_reconcile"].includes(content.status)) {
23400
- fail3("initialization_completion_action_not_accepted", content.error ?? { status: envelope.status });
23555
+ fail4("initialization_completion_action_not_accepted", content.error ?? { status: envelope.status });
23401
23556
  }
23402
23557
  const result2 = content.result;
23403
23558
  await onReceipt(envelope);
@@ -23408,19 +23563,19 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23408
23563
  planId: result2?.planId,
23409
23564
  status: result2?.status
23410
23565
  });
23411
- if (!result2 || result2.error) fail3("initialization_completion_action_failed", result2?.error);
23566
+ if (!result2 || result2.error) fail4("initialization_completion_action_failed", result2?.error);
23412
23567
  return result2;
23413
23568
  }
23414
23569
  async function settleCall(value, actionType) {
23415
23570
  callId = value.callId;
23416
- if (!callId || value.actionType !== actionType) fail3("initialization_completion_call_mismatch");
23571
+ if (!callId || value.actionType !== actionType) fail4("initialization_completion_call_mismatch");
23417
23572
  for (let attempt = 0; ; attempt++) {
23418
- if (value.callId !== callId || value.actionType !== actionType) fail3("initialization_completion_call_mismatch");
23573
+ if (value.callId !== callId || value.actionType !== actionType) fail4("initialization_completion_call_mismatch");
23419
23574
  if (value.status === "succeeded") return value;
23420
23575
  if (!["pending_reconcile", "claimed", "executing"].includes(value.status)) {
23421
- fail3("initialization_completion_action_incomplete", { status: value.status, error: value.error });
23576
+ fail4("initialization_completion_action_incomplete", { status: value.status, error: value.error });
23422
23577
  }
23423
- if (now() >= deadline) fail3("initialization_completion_deadline");
23578
+ if (now() >= deadline) fail4("initialization_completion_deadline");
23424
23579
  await sleep(Math.min(1e3 * (attempt + 1), 5e3));
23425
23580
  value = await invoke("runtime_action_status", { callId });
23426
23581
  }
@@ -23429,7 +23584,7 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23429
23584
  const doc = plan.initializationDocument;
23430
23585
  const materialized = plan.initializationDocumentMaterialization;
23431
23586
  if (!plan.planId || !plan.revision || !["planned", "committing", "pending_reconcile", "completed"].includes(plan.status) || materialized?.status !== "materialized" || materialized.planId !== plan.planId || materialized.revision !== plan.revision || materialized.sha256 !== doc?.sha256 || materialized.byteSize !== doc?.byteSize || materialized.path !== doc?.path) {
23432
- fail3("initialization_completion_invalid_plan");
23587
+ fail4("initialization_completion_invalid_plan");
23433
23588
  }
23434
23589
  const prefix = "initialization-complete:" + plan.planId;
23435
23590
  const { createHash: createHash21 } = await import("node:crypto");
@@ -23450,13 +23605,13 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23450
23605
  }
23451
23606
  }), "upload_artifact");
23452
23607
  if (upload.postcondition?.artifactFinalized !== true || upload.postcondition?.attachmentReadback !== true || upload.postcondition?.workProductReadback !== true || upload.effectResult?.sha256 !== doc.sha256 || upload.effectResult?.byteSize !== doc.byteSize || !upload.effectResult?.attachmentId || !upload.effectResult?.workProductId) {
23453
- fail3("initialization_completion_artifact_mismatch");
23608
+ fail4("initialization_completion_artifact_mismatch");
23454
23609
  }
23455
23610
  stage = "commit";
23456
23611
  callId = void 0;
23457
23612
  const committed = await invoke("runtime_action_commit", { planId: plan.planId, revision: plan.revision });
23458
23613
  if (committed.planId !== plan.planId || committed.revision !== plan.revision || committed.status !== "completed" || committed.failure || committed.nextActionIndex !== committed.actionCount) {
23459
- fail3("initialization_completion_plan_incomplete", { status: committed.status, failure: committed.failure });
23614
+ fail4("initialization_completion_plan_incomplete", { status: committed.status, failure: committed.failure });
23460
23615
  }
23461
23616
  stage = "ready";
23462
23617
  const completed = await settleCall(await invoke("runtime_action_submit", {
@@ -23464,7 +23619,7 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
23464
23619
  action: { type: "update_parent", status: "done" }
23465
23620
  }), "update_parent");
23466
23621
  if (completed.effectResult?.issueId !== authority.issueId || completed.effectResult?.status !== "done" || completed.postcondition?.issuePersisted !== true || completed.postcondition?.status !== "done" || completed.postcondition?.issueTerminalizationDeferred === true) {
23467
- fail3("initialization_completion_ready_not_confirmed");
23622
+ fail4("initialization_completion_ready_not_confirmed");
23468
23623
  }
23469
23624
  return {
23470
23625
  status: "completed",
@@ -23723,29 +23878,29 @@ export default function(pi) {
23723
23878
  // src/amaster-runtime-daemon/pi-managed-mcp-profile.mjs
23724
23879
  import { createHash as createHash9 } from "node:crypto";
23725
23880
  import {
23726
- chmodSync as chmodSync4,
23727
- chownSync as chownSync2,
23881
+ chmodSync as chmodSync5,
23882
+ chownSync as chownSync3,
23728
23883
  copyFileSync,
23729
23884
  existsSync as existsSync7,
23730
- lstatSync as lstatSync7,
23731
- mkdirSync as mkdirSync6,
23732
- readFileSync as readFileSync6,
23885
+ lstatSync as lstatSync8,
23886
+ mkdirSync as mkdirSync7,
23887
+ readFileSync as readFileSync7,
23733
23888
  realpathSync as realpathSync8,
23734
- readdirSync as readdirSync4,
23735
- renameSync as renameSync3,
23889
+ readdirSync as readdirSync5,
23890
+ renameSync as renameSync4,
23736
23891
  rmSync as rmSync5,
23737
- rmdirSync,
23892
+ rmdirSync as rmdirSync2,
23738
23893
  statSync as statSync4,
23739
23894
  symlinkSync,
23740
- writeFileSync as writeFileSync6
23895
+ writeFileSync as writeFileSync7
23741
23896
  } from "node:fs";
23742
23897
  import { arch as arch3, platform as platform3 } from "node:os";
23743
- import { basename as basename3, delimiter as delimiter2, dirname as dirname5, isAbsolute as isAbsolute4, join as join10, relative as relative3, resolve as resolve7, sep as sep3 } from "node:path";
23744
- import { spawnSync as spawnSync3 } from "node:child_process";
23898
+ import { basename as basename3, delimiter as delimiter2, dirname as dirname6, isAbsolute as isAbsolute4, join as join11, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
23899
+ import { spawnSync as spawnSync4 } from "node:child_process";
23745
23900
 
23746
23901
  // src/amaster-runtime-daemon/pi-provider-config.mjs
23747
- import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync5 } from "node:fs";
23748
- import { dirname as dirname4, join as join8 } from "node:path";
23902
+ import { existsSync as existsSync5, mkdirSync as mkdirSync6, readFileSync as readFileSync4, renameSync as renameSync3, writeFileSync as writeFileSync6 } from "node:fs";
23903
+ import { dirname as dirname5, join as join9 } from "node:path";
23749
23904
  var AMASTER_API_KEY_ENV_REFERENCE = "${AMASTER_API_KEY}";
23750
23905
  var AMASTER_BILLING_TURN_HEADER_ENV_REFERENCE = "${AMASTER_BILLING_TURN_ID}";
23751
23906
  var AMASTER_BILLING_HEADER_ENV_REFERENCES = Object.freeze({
@@ -23787,18 +23942,18 @@ function isRecord(value) {
23787
23942
  }
23788
23943
  function readJsonFile(filePath) {
23789
23944
  try {
23790
- const parsed = JSON.parse(readFileSync3(filePath, "utf8"));
23945
+ const parsed = JSON.parse(readFileSync4(filePath, "utf8"));
23791
23946
  return asRecord(parsed);
23792
23947
  } catch {
23793
23948
  return {};
23794
23949
  }
23795
23950
  }
23796
23951
  function writeJsonFileAtomic(filePath, value) {
23797
- mkdirSync5(dirname4(filePath), { recursive: true });
23952
+ mkdirSync6(dirname5(filePath), { recursive: true });
23798
23953
  const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
23799
- writeFileSync5(tmpPath, `${JSON.stringify(value, null, 2)}
23954
+ writeFileSync6(tmpPath, `${JSON.stringify(value, null, 2)}
23800
23955
  `, { mode: 384 });
23801
- renameSync2(tmpPath, filePath);
23956
+ renameSync3(tmpPath, filePath);
23802
23957
  }
23803
23958
  function imageGenBaseUrlFromProviderBaseUrl(value) {
23804
23959
  const input = readString(value);
@@ -23836,7 +23991,7 @@ function managedApiKeyConfigValue(executorEnv, apiKey) {
23836
23991
  function syncAmasterProviderModels(agentDir, executorEnv) {
23837
23992
  const apiKey = readString(executorEnv.AMASTER_API_KEY);
23838
23993
  if (!apiKey) return false;
23839
- const modelsPath = join8(agentDir, "models.json");
23994
+ const modelsPath = join9(agentDir, "models.json");
23840
23995
  const config = readJsonFile(modelsPath);
23841
23996
  const providers = asRecord(config.providers);
23842
23997
  const amaster = { ...asRecord(providers.amaster) };
@@ -23859,7 +24014,7 @@ function syncAmasterProviderModels(agentDir, executorEnv) {
23859
24014
  function syncAmasterProviderSettings(agentDir, executorEnv) {
23860
24015
  const apiKey = readString(executorEnv.AMASTER_API_KEY);
23861
24016
  if (!apiKey) return false;
23862
- const settingsPath = join8(agentDir, "settings.json");
24017
+ const settingsPath = join9(agentDir, "settings.json");
23863
24018
  if (!existsSync5(settingsPath)) return false;
23864
24019
  const settings = readJsonFile(settingsPath);
23865
24020
  const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
@@ -23981,7 +24136,7 @@ function modelCallOutputContractExtensionSource(maxOutputTokens) {
23981
24136
  `;
23982
24137
  }
23983
24138
  function assertPiModelConfigured(agentDir, provider, model) {
23984
- const modelsPath = join8(agentDir, "models.json");
24139
+ const modelsPath = join9(agentDir, "models.json");
23985
24140
  const config = readJsonFile(modelsPath);
23986
24141
  const providers = asRecord(config.providers);
23987
24142
  const providerConfig = asRecord(providers[provider]);
@@ -24003,7 +24158,7 @@ function resolvePiModelCallTarget(agentDir, providerId, modelId, explicitSource
24003
24158
  let model = explicitModel;
24004
24159
  let source = explicitSource;
24005
24160
  if (!provider || !model) {
24006
- const settings = readJsonFile(join8(agentDir, "settings.json"));
24161
+ const settings = readJsonFile(join9(agentDir, "settings.json"));
24007
24162
  const defaultProvider = readString(settings.defaultProvider);
24008
24163
  const defaultModel = normalizePiModelId(settings.defaultModel);
24009
24164
  if (Boolean(defaultProvider) !== Boolean(defaultModel)) {
@@ -24021,7 +24176,7 @@ function resolvePiModelCallTarget(agentDir, providerId, modelId, explicitSource
24021
24176
  }
24022
24177
  function resolvePiRunModelContext(agentDir, providerId, modelId) {
24023
24178
  const target = resolvePiModelCallTarget(agentDir, providerId, modelId, "runtime_override");
24024
- const modelsPath = join8(agentDir, "models.json");
24179
+ const modelsPath = join9(agentDir, "models.json");
24025
24180
  const config = readJsonFile(modelsPath);
24026
24181
  const providerConfig = asRecord(asRecord(config.providers)[target.provider]);
24027
24182
  const configuredModel = (Array.isArray(providerConfig.models) ? providerConfig.models : []).map(asRecord).find((entry) => readString(entry.id) === target.model) ?? {};
@@ -24084,7 +24239,7 @@ function piMcpAdapterServerConfigIdentity(definition, adapterVersion) {
24084
24239
  }
24085
24240
 
24086
24241
  // src/amaster-runtime-daemon/pi-role-skills-visibility.mjs
24087
- import { readFileSync as readFileSync4, realpathSync as realpathSync6 } from "node:fs";
24242
+ import { readFileSync as readFileSync5, realpathSync as realpathSync6 } from "node:fs";
24088
24243
  var MANAGED_PI_ROLE_SKILLS_VISIBILITY_FILENAME = "amaster-role-skills-visibility.js";
24089
24244
  function hostYamlString(value) {
24090
24245
  const trimmed = value.trim();
@@ -24119,7 +24274,7 @@ function hostEscapeXml(value) {
24119
24274
  }
24120
24275
  function readManagedPiSkillMetadata(filePath) {
24121
24276
  const resolvedFilePath = realpathSync6(filePath);
24122
- const source = readFileSync4(resolvedFilePath, "utf8");
24277
+ const source = readFileSync5(resolvedFilePath, "utf8");
24123
24278
  const match = source.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
24124
24279
  if (!match) {
24125
24280
  return {
@@ -24186,15 +24341,15 @@ export default function amasterRoleSkillsVisibility(pi) {
24186
24341
  }
24187
24342
 
24188
24343
  // src/amaster-runtime-daemon/pi-mcp-adapter-readiness.mjs
24189
- import { existsSync as existsSync6, lstatSync as lstatSync6, readFileSync as readFileSync5, realpathSync as realpathSync7 } from "node:fs";
24190
- import { join as join9, resolve as resolve6 } from "node:path";
24344
+ import { existsSync as existsSync6, lstatSync as lstatSync7, readFileSync as readFileSync6, realpathSync as realpathSync7 } from "node:fs";
24345
+ import { join as join10, resolve as resolve7 } from "node:path";
24191
24346
  var ADAPTER_PACKAGE_NAME = "pi-mcp-adapter";
24192
24347
  function unavailable(reasonCode) {
24193
24348
  return { ready: false, reasonCode };
24194
24349
  }
24195
24350
  function safeRegularFile(filePath) {
24196
24351
  if (!existsSync6(filePath)) return false;
24197
- const stat = lstatSync6(filePath);
24352
+ const stat = lstatSync7(filePath);
24198
24353
  return stat.isFile() && !stat.isSymbolicLink();
24199
24354
  }
24200
24355
  function inspectDesktopPiMcpAdapterReadiness(input = {}) {
@@ -24202,27 +24357,27 @@ function inspectDesktopPiMcpAdapterReadiness(input = {}) {
24202
24357
  if (!configuredHome) return unavailable("desktop_pi_home_unavailable");
24203
24358
  let piHome;
24204
24359
  try {
24205
- piHome = resolve6(configuredHome);
24206
- const homeStat = lstatSync6(piHome);
24360
+ piHome = resolve7(configuredHome);
24361
+ const homeStat = lstatSync7(piHome);
24207
24362
  if (!homeStat.isDirectory() || homeStat.isSymbolicLink()) {
24208
24363
  return unavailable("desktop_pi_home_unsafe");
24209
24364
  }
24210
24365
  } catch {
24211
24366
  return unavailable("desktop_pi_home_unavailable");
24212
24367
  }
24213
- const configuredAdapterRoot = join9(piHome, "npm", "node_modules", ADAPTER_PACKAGE_NAME);
24368
+ const configuredAdapterRoot = join10(piHome, "npm", "node_modules", ADAPTER_PACKAGE_NAME);
24214
24369
  try {
24215
24370
  const adapterRoot = realpathSync7(configuredAdapterRoot);
24216
- const adapterRootStat = lstatSync6(adapterRoot);
24371
+ const adapterRootStat = lstatSync7(adapterRoot);
24217
24372
  if (!adapterRootStat.isDirectory() || adapterRootStat.isSymbolicLink()) {
24218
24373
  return unavailable("desktop_pi_mcp_adapter_unavailable");
24219
24374
  }
24220
- const packagePath = join9(adapterRoot, "package.json");
24221
- const extensionPath = join9(adapterRoot, "index.ts");
24375
+ const packagePath = join10(adapterRoot, "package.json");
24376
+ const extensionPath = join10(adapterRoot, "index.ts");
24222
24377
  if (![packagePath, extensionPath].every(safeRegularFile)) {
24223
24378
  return unavailable("desktop_pi_mcp_adapter_unavailable");
24224
24379
  }
24225
- const packageJson = JSON.parse(readFileSync5(packagePath, "utf8"));
24380
+ const packageJson = JSON.parse(readFileSync6(packagePath, "utf8"));
24226
24381
  const adapterVersion = typeof packageJson?.version === "string" ? packageJson.version.trim() : "";
24227
24382
  if (packageJson?.name !== ADAPTER_PACKAGE_NAME || !/^\d+\.\d+\.\d+(?:[-+].+)?$/.test(adapterVersion)) {
24228
24383
  return unavailable("desktop_pi_mcp_adapter_invalid");
@@ -24363,10 +24518,10 @@ function applyManagedPiRunExitClosureArgs(args, profile) {
24363
24518
  try {
24364
24519
  return realpathSync8(filePath);
24365
24520
  } catch {
24366
- return resolve7(filePath);
24521
+ return resolve8(filePath);
24367
24522
  }
24368
24523
  };
24369
- const roleSkillsVisibilityExtension = canonicalPath(resolve7(
24524
+ const roleSkillsVisibilityExtension = canonicalPath(resolve8(
24370
24525
  profile.profileRoot,
24371
24526
  "extensions",
24372
24527
  MANAGED_PI_ROLE_SKILLS_VISIBILITY_FILENAME
@@ -24382,29 +24537,29 @@ function applyManagedPiRunExitClosureArgs(args, profile) {
24382
24537
  return closureArgs;
24383
24538
  }
24384
24539
  function resolveManagedPiMcpAdapterExtension(adapterRoot) {
24385
- const adapterRootStat = lstatSync7(adapterRoot);
24540
+ const adapterRootStat = lstatSync8(adapterRoot);
24386
24541
  if (!adapterRootStat.isDirectory() || adapterRootStat.isSymbolicLink()) {
24387
24542
  throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24388
24543
  }
24389
- const adapterManifest = JSON.parse(readFileSync6(join10(adapterRoot, "package.json"), "utf8"));
24544
+ const adapterManifest = JSON.parse(readFileSync7(join11(adapterRoot, "package.json"), "utf8"));
24390
24545
  const entries = adapterManifest.pi?.extensions;
24391
24546
  const entry = entries === void 0 ? "index.ts" : Array.isArray(entries) && entries.length === 1 ? entries[0] : null;
24392
24547
  if (!["index.ts", "./index.ts", "index.js", "./index.js"].includes(entry)) {
24393
24548
  throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24394
24549
  }
24395
- const adapterExtensionPath = join10(adapterRoot, entry);
24550
+ const adapterExtensionPath = join11(adapterRoot, entry);
24396
24551
  if (!existsSync7(adapterExtensionPath)) {
24397
24552
  throw new Error("pi_managed_mcp_adapter_extension_missing");
24398
24553
  }
24399
- const adapterExtensionStat = lstatSync7(adapterExtensionPath);
24554
+ const adapterExtensionStat = lstatSync8(adapterExtensionPath);
24400
24555
  if (!adapterExtensionStat.isFile() || adapterExtensionStat.isSymbolicLink()) {
24401
24556
  throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24402
24557
  }
24403
24558
  return adapterExtensionPath;
24404
24559
  }
24405
24560
  function createManagedPiMcpProfileApi(options = {}) {
24406
- const spawnSyncImpl = typeof options.spawnSync === "function" ? options.spawnSync : spawnSync3;
24407
- const chownSyncImpl = typeof options.chownSync === "function" ? options.chownSync : chownSync2;
24561
+ const spawnSyncImpl = typeof options.spawnSync === "function" ? options.spawnSync : spawnSync4;
24562
+ const chownSyncImpl = typeof options.chownSync === "function" ? options.chownSync : chownSync3;
24408
24563
  const ownershipStatSyncImpl = typeof options.ownershipStatSync === "function" ? options.ownershipStatSync : statSync4;
24409
24564
  const nowImpl = typeof options.now === "function" ? options.now : Date.now;
24410
24565
  const SUPPORTED_SCHEMA_VERSION3 = "amaster.governed-mcp.v1";
@@ -24508,7 +24663,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24508
24663
  function readJsonObjectFile(filePath) {
24509
24664
  if (!existsSync7(filePath)) return {};
24510
24665
  try {
24511
- const value = JSON.parse(readFileSync6(filePath, "utf8"));
24666
+ const value = JSON.parse(readFileSync7(filePath, "utf8"));
24512
24667
  if (!value || typeof value !== "object" || Array.isArray(value)) {
24513
24668
  throw new Error("JSON value is not an object");
24514
24669
  }
@@ -24526,19 +24681,19 @@ function createManagedPiMcpProfileApi(options = {}) {
24526
24681
  return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
24527
24682
  }
24528
24683
  function writePrivateFile2(filePath, contents) {
24529
- writeFileSync6(filePath, contents, { mode: 384, flag: "wx" });
24530
- chmodSync4(filePath, 384);
24684
+ writeFileSync7(filePath, contents, { mode: 384, flag: "wx" });
24685
+ chmodSync5(filePath, 384);
24531
24686
  const mode = statSync4(filePath).mode & 511;
24532
24687
  if (mode !== 384) throw new Error(`pi_managed_mcp_permissions_failed: ${filePath} mode=${mode.toString(8)}`);
24533
24688
  }
24534
24689
  function copyPrivateFile(source, target) {
24535
24690
  if (!existsSync7(source)) return false;
24536
- const sourceStat = lstatSync7(source);
24691
+ const sourceStat = lstatSync8(source);
24537
24692
  if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
24538
24693
  throw new Error(`pi_managed_mcp_source_config_unsafe: ${source}`);
24539
24694
  }
24540
24695
  copyFileSync(source, target, 0);
24541
- chmodSync4(target, 384);
24696
+ chmodSync5(target, 384);
24542
24697
  return true;
24543
24698
  }
24544
24699
  function findPiSessionRollout(sessionsRoot, sessionId) {
@@ -24547,12 +24702,12 @@ function createManagedPiMcpProfileApi(options = {}) {
24547
24702
  const pending = [sessionsRoot];
24548
24703
  while (pending.length > 0) {
24549
24704
  const current = pending.pop();
24550
- const currentStat = lstatSync7(current);
24705
+ const currentStat = lstatSync8(current);
24551
24706
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) {
24552
24707
  throw new Error("pi_managed_mcp_session_rollout_unsafe: sessions path is not a private directory");
24553
24708
  }
24554
- for (const entry of readdirSync4(current, { withFileTypes: true })) {
24555
- const candidate = join10(current, entry.name);
24709
+ for (const entry of readdirSync5(current, { withFileTypes: true })) {
24710
+ const candidate = join11(current, entry.name);
24556
24711
  if (entry.isSymbolicLink()) throw new Error("pi_managed_mcp_session_rollout_unsafe: symlinks are forbidden");
24557
24712
  if (entry.isDirectory()) pending.push(candidate);
24558
24713
  else if (entry.isFile() && entry.name.endsWith(`_${sessionId}.jsonl`)) matches.push(candidate);
@@ -24583,31 +24738,31 @@ function createManagedPiMcpProfileApi(options = {}) {
24583
24738
  const installed = installPiSessionCheckpoint(sessionsRoot, input.portableNativeSession, sessionId);
24584
24739
  return { ...installed, sourceRunId, sourceCommandId, cacheRoot: null };
24585
24740
  }
24586
- const issueRoot = dirname5(runDir);
24741
+ const issueRoot = dirname6(runDir);
24587
24742
  const managedSourceRunDirName = `${sourceRunId}-${createHash9("sha256").update(sourceRunId).digest("hex").slice(0, 8)}`;
24588
- const sourceRunDirs = readdirSync4(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) => join10(issueRoot, entry.name));
24743
+ const sourceRunDirs = readdirSync5(issueRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && (entry.name === sourceRunId || entry.name === managedSourceRunDirName)).map((entry) => join11(issueRoot, entry.name));
24589
24744
  if (sourceRunDirs.length !== 1) {
24590
24745
  throw new Error(`pi_managed_mcp_session_rollout_missing: expected one source run directory for ${sourceRunId}, received ${sourceRunDirs.length}`);
24591
24746
  }
24592
- const cacheRoot = join10(sourceRunDirs[0], relative3(runDir, executorHome), "session-rollout");
24593
- const markerPath = join10(cacheRoot, SESSION_ROLLOUT_MARKER3);
24594
- if (!existsSync7(markerPath) || lstatSync7(markerPath).isSymbolicLink() || !lstatSync7(markerPath).isFile()) {
24747
+ const cacheRoot = join11(sourceRunDirs[0], relative3(runDir, executorHome), "session-rollout");
24748
+ const markerPath2 = join11(cacheRoot, SESSION_ROLLOUT_MARKER3);
24749
+ if (!existsSync7(markerPath2) || lstatSync8(markerPath2).isSymbolicLink() || !lstatSync8(markerPath2).isFile()) {
24595
24750
  throw new Error("pi_managed_mcp_session_rollout_missing: source rollout marker is unavailable");
24596
24751
  }
24597
- const marker = JSON.parse(readFileSync6(markerPath, "utf8"));
24752
+ const marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
24598
24753
  if (marker?.version !== 1 || marker?.companyId !== authority.companyId || marker?.agentId !== authority.agentId || marker?.issueId !== authority.issueId || marker?.sourceRunId !== sourceRunId || marker?.sourceCommandId !== sourceCommandId || marker?.sessionId !== sessionId || marker?.sourceWorkspacePath !== sourceWorkspacePath) {
24599
24754
  throw new Error("pi_managed_mcp_session_rollout_authority_mismatch: source rollout does not match the governed continuation");
24600
24755
  }
24601
- const sourceRollout = resolve7(cacheRoot, nonEmpty3(marker.rolloutRelativePath, "rolloutRelativePath"));
24602
- if (!within3(sourceRollout, cacheRoot) || lstatSync7(sourceRollout).isSymbolicLink() || !lstatSync7(sourceRollout).isFile()) {
24756
+ const sourceRollout = resolve8(cacheRoot, nonEmpty3(marker.rolloutRelativePath, "rolloutRelativePath"));
24757
+ if (!within3(sourceRollout, cacheRoot) || lstatSync8(sourceRollout).isSymbolicLink() || !lstatSync8(sourceRollout).isFile()) {
24603
24758
  throw new Error("pi_managed_mcp_session_rollout_unsafe: source rollout path is invalid");
24604
24759
  }
24605
- const targetRollout = resolve7(sessionsRoot, marker.rolloutRelativePath);
24760
+ const targetRollout = resolve8(sessionsRoot, marker.rolloutRelativePath);
24606
24761
  if (!within3(targetRollout, sessionsRoot)) {
24607
24762
  throw new Error("pi_managed_mcp_session_rollout_unsafe: target rollout path is invalid");
24608
24763
  }
24609
- mkdirSync6(dirname5(targetRollout), { recursive: true, mode: 448 });
24610
- writePrivateFile2(targetRollout, readFileSync6(sourceRollout));
24764
+ mkdirSync7(dirname6(targetRollout), { recursive: true, mode: 448 });
24765
+ writePrivateFile2(targetRollout, readFileSync7(sourceRollout));
24611
24766
  return { sessionId, sourceRunId, sourceCommandId, rolloutPath: targetRollout, cacheRoot };
24612
24767
  }
24613
24768
  function resolveManagedPiSessionRollout(input, sessionsRoot, runDir, executorHome, authority) {
@@ -24655,7 +24810,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24655
24810
  return createHash9("sha256").update(value).digest("hex");
24656
24811
  }
24657
24812
  function trustedTreeDigest(rootPath, options2 = {}) {
24658
- const root = resolve7(rootPath);
24813
+ const root = resolve8(rootPath);
24659
24814
  const ignoredRootEntries = new Set(Array.isArray(options2.ignoredRootEntries) ? options2.ignoredRootEntries : []);
24660
24815
  const hash3 = createHash9("sha256");
24661
24816
  hash3.update(`ignored-root:${[...ignoredRootEntries].sort().join(",")}
@@ -24663,28 +24818,28 @@ function createManagedPiMcpProfileApi(options = {}) {
24663
24818
  const pending = [root];
24664
24819
  while (pending.length > 0) {
24665
24820
  const current = pending.pop();
24666
- const currentStat = lstatSync7(current);
24821
+ const currentStat = lstatSync8(current);
24667
24822
  if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
24668
24823
  const relativePath = relative3(root, current).split(sep3).join("/");
24669
24824
  if (currentStat.isDirectory()) {
24670
24825
  hash3.update(`d:${relativePath}
24671
24826
  `);
24672
- const children = readdirSync4(current).filter((child) => current !== root || !ignoredRootEntries.has(child)).sort().reverse();
24673
- for (const child of children) pending.push(join10(current, child));
24827
+ const children = readdirSync5(current).filter((child) => current !== root || !ignoredRootEntries.has(child)).sort().reverse();
24828
+ for (const child of children) pending.push(join11(current, child));
24674
24829
  continue;
24675
24830
  }
24676
24831
  if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
24677
24832
  hash3.update(`f:${relativePath}:${currentStat.mode & 73 ? "x" : "-"}:`);
24678
- hash3.update(readFileSync6(current));
24833
+ hash3.update(readFileSync7(current));
24679
24834
  hash3.update("\n");
24680
24835
  }
24681
24836
  return hash3.digest("hex");
24682
24837
  }
24683
24838
  function piMcpAdapterVersion(piHome) {
24684
- const packagePath = join10(piHome, "npm", "node_modules", "pi-mcp-adapter", "package.json");
24839
+ const packagePath = join11(piHome, "npm", "node_modules", "pi-mcp-adapter", "package.json");
24685
24840
  let packageJson;
24686
24841
  try {
24687
- packageJson = JSON.parse(readFileSync6(packagePath, "utf8"));
24842
+ packageJson = JSON.parse(readFileSync7(packagePath, "utf8"));
24688
24843
  } catch {
24689
24844
  throw new Error("pi_managed_mcp_adapter_version_unavailable");
24690
24845
  }
@@ -24702,21 +24857,21 @@ function createManagedPiMcpProfileApi(options = {}) {
24702
24857
  if (configuredSources.length !== 1) {
24703
24858
  throw new Error("pi_managed_mcp_telemetry_package_source_invalid");
24704
24859
  }
24705
- const packageRoot = resolve7(
24860
+ const packageRoot = resolve8(
24706
24861
  sharedRuntime.home,
24707
24862
  "npm",
24708
24863
  "node_modules",
24709
24864
  "@amaster.ai",
24710
24865
  "pi-telemetry"
24711
24866
  );
24712
- const packageJsonPath = join10(packageRoot, "package.json");
24867
+ const packageJsonPath = join11(packageRoot, "package.json");
24713
24868
  let packageJson;
24714
24869
  try {
24715
- const packageStat = lstatSync7(packageRoot);
24870
+ const packageStat = lstatSync8(packageRoot);
24716
24871
  if (!packageStat.isDirectory() || packageStat.isSymbolicLink()) throw new Error("unsafe package root");
24717
- const packageJsonStat = lstatSync7(packageJsonPath);
24872
+ const packageJsonStat = lstatSync8(packageJsonPath);
24718
24873
  if (!packageJsonStat.isFile() || packageJsonStat.isSymbolicLink()) throw new Error("unsafe package manifest");
24719
- packageJson = record11(JSON.parse(readFileSync6(packageJsonPath, "utf8")));
24874
+ packageJson = record11(JSON.parse(readFileSync7(packageJsonPath, "utf8")));
24720
24875
  } catch {
24721
24876
  throw new Error("pi_managed_mcp_telemetry_package_unavailable");
24722
24877
  }
@@ -24731,12 +24886,12 @@ function createManagedPiMcpProfileApi(options = {}) {
24731
24886
  if (declaredExtensions.length !== 1 || typeof declaredExtensions[0] !== "string") {
24732
24887
  throw new Error("pi_managed_mcp_telemetry_extension_invalid");
24733
24888
  }
24734
- const extensionPath = resolve7(packageRoot, declaredExtensions[0]);
24889
+ const extensionPath = resolve8(packageRoot, declaredExtensions[0]);
24735
24890
  if (!within3(extensionPath, packageRoot)) {
24736
24891
  throw new Error("pi_managed_mcp_telemetry_extension_unsafe");
24737
24892
  }
24738
24893
  try {
24739
- const extensionStat = lstatSync7(extensionPath);
24894
+ const extensionStat = lstatSync8(extensionPath);
24740
24895
  if (!extensionStat.isFile() || extensionStat.isSymbolicLink()) throw new Error("unsafe extension entry");
24741
24896
  const realPackageRoot = realpathSync8(packageRoot);
24742
24897
  const realExtensionPath = realpathSync8(extensionPath);
@@ -24755,7 +24910,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24755
24910
  packageVersion: version,
24756
24911
  packageVersionSource: "installed_package_manifest",
24757
24912
  extensionPath,
24758
- extensionSha256: sha2563(readFileSync6(extensionPath)),
24913
+ extensionSha256: sha2563(readFileSync7(extensionPath)),
24759
24914
  packageTreeSha256,
24760
24915
  langfuseEnabled: record11(record11(settings["pi-telemetry"]).langfuse).enabled === true
24761
24916
  };
@@ -24786,8 +24941,8 @@ function createManagedPiMcpProfileApi(options = {}) {
24786
24941
  const pathEntries = String(env?.PATH ?? "").split(delimiter2).filter(Boolean);
24787
24942
  for (const entry of pathEntries) {
24788
24943
  try {
24789
- const candidate = realpathSync8(join10(entry, executorCommand));
24790
- const stat = lstatSync7(candidate);
24944
+ const candidate = realpathSync8(join11(entry, executorCommand));
24945
+ const stat = lstatSync8(candidate);
24791
24946
  if (stat.isFile() && !stat.isSymbolicLink()) return candidate;
24792
24947
  } catch {
24793
24948
  }
@@ -24797,16 +24952,16 @@ function createManagedPiMcpProfileApi(options = {}) {
24797
24952
  function piExecutableIdentity(executorPath) {
24798
24953
  try {
24799
24954
  const realPath = realpathSync8(executorPath);
24800
- const executableStat = lstatSync7(realPath);
24955
+ const executableStat = lstatSync8(realPath);
24801
24956
  if (!executableStat.isFile() || executableStat.isSymbolicLink()) {
24802
24957
  throw Object.assign(new Error("Pi executable is not a regular file"), { code: "EUNSAFE" });
24803
24958
  }
24804
- const contentSha256 = createHash9("sha256").update(readFileSync6(realPath)).digest("hex");
24959
+ const contentSha256 = createHash9("sha256").update(readFileSync7(realPath)).digest("hex");
24805
24960
  let packageManifestSha256 = null;
24806
- for (let directory = dirname5(realPath); dirname5(directory) !== directory; directory = dirname5(directory)) {
24807
- const packagePath = join10(directory, "package.json");
24961
+ for (let directory = dirname6(realPath); dirname6(directory) !== directory; directory = dirname6(directory)) {
24962
+ const packagePath = join11(directory, "package.json");
24808
24963
  if (!existsSync7(packagePath)) continue;
24809
- packageManifestSha256 = sha2563(readFileSync6(packagePath));
24964
+ packageManifestSha256 = sha2563(readFileSync7(packagePath));
24810
24965
  break;
24811
24966
  }
24812
24967
  return `sha256:${createHash9("sha256").update(JSON.stringify({ realPath, contentSha256, packageManifestSha256 })).digest("hex")}`;
@@ -24930,7 +25085,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24930
25085
  if (!existsSync7(filePath)) return false;
24931
25086
  let parsed;
24932
25087
  try {
24933
- parsed = JSON.parse(readFileSync6(filePath, "utf8"));
25088
+ parsed = JSON.parse(readFileSync7(filePath, "utf8"));
24934
25089
  } catch {
24935
25090
  return true;
24936
25091
  }
@@ -24938,32 +25093,32 @@ function createManagedPiMcpProfileApi(options = {}) {
24938
25093
  return Object.keys(record11(config.mcpServers)).length > 0 || Object.keys(record11(config.servers)).length > 0 || Array.isArray(config.imports) && config.imports.length > 0;
24939
25094
  }
24940
25095
  function walkProjectMcpConfigs(cwd, runDir, visit) {
24941
- const start = resolve7(cwd);
24942
- const boundary = resolve7(runDir);
25096
+ const start = resolve8(cwd);
25097
+ const boundary = resolve8(runDir);
24943
25098
  if (!within3(start, boundary)) throw new Error("pi_managed_mcp_owner_mismatch: cwd is outside the managed run");
24944
25099
  let cursor = start;
24945
25100
  while (within3(cursor, boundary)) {
24946
25101
  visit(cursor, cursor === start);
24947
25102
  if (cursor === boundary) break;
24948
- cursor = dirname5(cursor);
25103
+ cursor = dirname6(cursor);
24949
25104
  }
24950
25105
  }
24951
25106
  function assertNoProjectMcpOverride(cwd, runDir) {
24952
25107
  walkProjectMcpConfigs(cwd, runDir, (level) => {
24953
- for (const relativePath of [".mcp.json", join10(".pi", "mcp.json")]) {
24954
- const configPath = join10(level, relativePath);
25108
+ for (const relativePath of [".mcp.json", join11(".pi", "mcp.json")]) {
25109
+ const configPath = join11(level, relativePath);
24955
25110
  if (projectMcpConfigHasContent(configPath)) throw new Error(`pi_managed_mcp_project_override_blocked: ${configPath}`);
24956
25111
  }
24957
25112
  });
24958
25113
  }
24959
25114
  function assertWorkspaceMcpOverrideClear(cwd, runDir) {
24960
25115
  walkProjectMcpConfigs(cwd, runDir, (level, isCwd) => {
24961
- const sharedProjectConfig = join10(level, ".mcp.json");
25116
+ const sharedProjectConfig = join11(level, ".mcp.json");
24962
25117
  if (projectMcpConfigHasContent(sharedProjectConfig)) {
24963
25118
  throw new Error(`pi_managed_mcp_project_override_blocked: ${sharedProjectConfig}`);
24964
25119
  }
24965
25120
  if (!isCwd) {
24966
- const ancestorPiConfig = join10(level, ".pi", "mcp.json");
25121
+ const ancestorPiConfig = join11(level, ".pi", "mcp.json");
24967
25122
  if (projectMcpConfigHasContent(ancestorPiConfig)) {
24968
25123
  throw new Error(`pi_managed_mcp_project_override_blocked: ${ancestorPiConfig}`);
24969
25124
  }
@@ -24971,55 +25126,55 @@ function createManagedPiMcpProfileApi(options = {}) {
24971
25126
  });
24972
25127
  }
24973
25128
  function isWorkspaceMcpConfigPath(path) {
24974
- return resolve7(path).replaceAll("\\", "/").endsWith("/.pi/mcp.json");
25129
+ return resolve8(path).replaceAll("\\", "/").endsWith("/.pi/mcp.json");
24975
25130
  }
24976
25131
  function managedRunRootForProfile(profileRoot) {
24977
- const executorsRoot = dirname5(dirname5(resolve7(profileRoot)));
25132
+ const executorsRoot = dirname6(dirname6(resolve8(profileRoot)));
24978
25133
  if (basename3(executorsRoot) !== "executors") {
24979
25134
  throw new Error("pi_managed_mcp_cleanup_owner_mismatch: profile is outside a managed run");
24980
25135
  }
24981
- return dirname5(executorsRoot);
25136
+ return dirname6(executorsRoot);
24982
25137
  }
24983
25138
  function workspaceMcpConfigBelongsToProfile(configPath, profileRoot) {
24984
- const target = resolve7(configPath);
25139
+ const target = resolve8(configPath);
24985
25140
  return isWorkspaceMcpConfigPath(target) && within3(target, managedRunRootForProfile(profileRoot));
24986
25141
  }
24987
25142
  function writeOwnedFileAtomic(filePath, contents) {
24988
25143
  if (existsSync7(filePath)) {
24989
- const stat = lstatSync7(filePath);
25144
+ const stat = lstatSync8(filePath);
24990
25145
  if (!stat.isFile() || stat.isSymbolicLink()) {
24991
25146
  throw new Error(`pi_managed_mcp_workspace_config_unsafe: ${filePath}`);
24992
25147
  }
24993
25148
  }
24994
- mkdirSync6(dirname5(filePath), { recursive: true, mode: 448 });
25149
+ mkdirSync7(dirname6(filePath), { recursive: true, mode: 448 });
24995
25150
  const tempPath = `${filePath}.tmp.${process.pid}`;
24996
- writeFileSync6(tempPath, contents, { mode: 384 });
24997
- renameSync3(tempPath, filePath);
24998
- chmodSync4(filePath, 384);
25151
+ writeFileSync7(tempPath, contents, { mode: 384 });
25152
+ renameSync4(tempPath, filePath);
25153
+ chmodSync5(filePath, 384);
24999
25154
  const mode = statSync4(filePath).mode & 511;
25000
25155
  if (mode !== 384) throw new Error(`pi_managed_mcp_permissions_failed: ${filePath} mode=${mode.toString(8)}`);
25001
25156
  }
25002
25157
  function sharedPiHomeSettingsEnv(baseEnv) {
25003
- const home = resolve7(nonEmpty3(baseEnv?.PI_CODING_AGENT_DIR, "sourcePiHome: PI_CODING_AGENT_DIR"));
25004
- const homeStat = lstatSync7(home);
25158
+ const home = resolve8(nonEmpty3(baseEnv?.PI_CODING_AGENT_DIR, "sourcePiHome: PI_CODING_AGENT_DIR"));
25159
+ const homeStat = lstatSync8(home);
25005
25160
  if (!homeStat.isDirectory() || homeStat.isSymbolicLink()) {
25006
25161
  throw new Error("pi_managed_mcp_source_config_unsafe: Pi home");
25007
25162
  }
25008
- const settingsPath = join10(home, "settings.json");
25163
+ const settingsPath = join11(home, "settings.json");
25009
25164
  let settings = {};
25010
25165
  if (existsSync7(settingsPath)) {
25011
25166
  try {
25012
- settings = record11(JSON.parse(readFileSync6(settingsPath, "utf8")));
25167
+ settings = record11(JSON.parse(readFileSync7(settingsPath, "utf8")));
25013
25168
  } catch {
25014
25169
  throw new Error("pi_managed_mcp_attestation_failed: source Pi settings are invalid");
25015
25170
  }
25016
25171
  }
25017
25172
  let userMcpServers = {};
25018
- const mcpPath = join10(home, "mcp.json");
25173
+ const mcpPath = join11(home, "mcp.json");
25019
25174
  if (existsSync7(mcpPath)) {
25020
25175
  try {
25021
25176
  userMcpServers = Object.fromEntries(Object.entries(record11(
25022
- record11(JSON.parse(readFileSync6(mcpPath, "utf8"))).mcpServers
25177
+ record11(JSON.parse(readFileSync7(mcpPath, "utf8"))).mcpServers
25023
25178
  )).filter(([serverName]) => serverName !== SUPPORTED_SERVER_NAME3));
25024
25179
  } catch {
25025
25180
  userMcpServers = {};
@@ -25099,20 +25254,20 @@ function createManagedPiMcpProfileApi(options = {}) {
25099
25254
  function materializeManagedSkillBundle(profileRoot, rawBundle) {
25100
25255
  const bundle = parseManagedSkillBundle(rawBundle);
25101
25256
  if (!bundle) return { entries: [] };
25102
- const root = join10(profileRoot, "company-skills");
25103
- mkdirSync6(root, { recursive: true, mode: 448 });
25257
+ const root = join11(profileRoot, "company-skills");
25258
+ mkdirSync7(root, { recursive: true, mode: 448 });
25104
25259
  const entries = bundle.skills.map((skill) => {
25105
- const skillRoot = join10(root, skill.runtimeName);
25106
- mkdirSync6(skillRoot, { recursive: true, mode: 448 });
25260
+ const skillRoot = join11(root, skill.runtimeName);
25261
+ mkdirSync7(skillRoot, { recursive: true, mode: 448 });
25107
25262
  for (const file of skill.files) {
25108
- const target = resolve7(skillRoot, file.path);
25263
+ const target = resolve8(skillRoot, file.path);
25109
25264
  if (!within3(target, skillRoot)) {
25110
25265
  throw new Error(`pi_managed_mcp_company_skill_path_unsafe:${skill.runtimeName}:${file.path}`);
25111
25266
  }
25112
- mkdirSync6(dirname5(target), { recursive: true, mode: 448 });
25267
+ mkdirSync7(dirname6(target), { recursive: true, mode: 448 });
25113
25268
  writePrivateFile2(target, file.contents);
25114
25269
  }
25115
- const metadata = readManagedPiSkillMetadata(join10(skillRoot, "SKILL.md"));
25270
+ const metadata = readManagedPiSkillMetadata(join11(skillRoot, "SKILL.md"));
25116
25271
  return {
25117
25272
  name: metadata.name ?? skill.runtimeName,
25118
25273
  filePath: metadata.filePath
@@ -25121,22 +25276,22 @@ function createManagedPiMcpProfileApi(options = {}) {
25121
25276
  return { entries };
25122
25277
  }
25123
25278
  function readSkillProfile(piHome, skillProfile) {
25124
- const agentsRoot = resolve7(piHome, "agents");
25125
- const agentFile = resolve7(agentsRoot, `${skillProfile}.md`);
25279
+ const agentsRoot = resolve8(piHome, "agents");
25280
+ const agentFile = resolve8(agentsRoot, `${skillProfile}.md`);
25126
25281
  if (!SKILL_PROFILE_NAME.test(skillProfile) || !within3(agentFile, agentsRoot) || !existsSync7(agentFile)) {
25127
25282
  return [];
25128
25283
  }
25129
- const declared = readFileSync6(agentFile, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1].match(/^skills:\s*(.+)$/m)?.[1].split(",").map((entry) => entry.trim()).filter(Boolean) ?? [];
25130
- const bundlesRoot = resolve7(piHome, "bundles");
25284
+ const declared = readFileSync7(agentFile, "utf8").match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1].match(/^skills:\s*(.+)$/m)?.[1].split(",").map((entry) => entry.trim()).filter(Boolean) ?? [];
25285
+ const bundlesRoot = resolve8(piHome, "bundles");
25131
25286
  const profile = [];
25132
25287
  for (const name of declared) {
25133
- let source = join10(bundlesRoot, skillProfile, "skills", name);
25134
- if (!existsSync7(join10(source, "SKILL.md"))) {
25288
+ let source = join11(bundlesRoot, skillProfile, "skills", name);
25289
+ if (!existsSync7(join11(source, "SKILL.md"))) {
25135
25290
  const candidates = [];
25136
- for (const category of readdirSync4(bundlesRoot).sort()) {
25291
+ for (const category of readdirSync5(bundlesRoot).sort()) {
25137
25292
  if (category === skillProfile) continue;
25138
- const candidate = join10(bundlesRoot, category, "skills", name);
25139
- if (existsSync7(join10(candidate, "SKILL.md"))) candidates.push(candidate);
25293
+ const candidate = join11(bundlesRoot, category, "skills", name);
25294
+ if (existsSync7(join11(candidate, "SKILL.md"))) candidates.push(candidate);
25140
25295
  }
25141
25296
  source = candidates[0];
25142
25297
  }
@@ -25145,20 +25300,20 @@ function createManagedPiMcpProfileApi(options = {}) {
25145
25300
  return profile;
25146
25301
  }
25147
25302
  function readCommonRoleSkills(piHome) {
25148
- const skillsRoot = resolve7(piHome, "bundles", "common", "skills");
25303
+ const skillsRoot = resolve8(piHome, "bundles", "common", "skills");
25149
25304
  if (!existsSync7(skillsRoot)) return [];
25150
- return readdirSync4(skillsRoot).sort().flatMap((name) => {
25151
- const source = join10(skillsRoot, name);
25152
- return existsSync7(join10(source, "SKILL.md")) ? [{ name, source }] : [];
25305
+ return readdirSync5(skillsRoot).sort().flatMap((name) => {
25306
+ const source = join11(skillsRoot, name);
25307
+ return existsSync7(join11(source, "SKILL.md")) ? [{ name, source }] : [];
25153
25308
  });
25154
25309
  }
25155
25310
  function readMainSkills(piHome) {
25156
- const skillsRoot = resolve7(piHome, "skills");
25311
+ const skillsRoot = resolve8(piHome, "skills");
25157
25312
  if (!existsSync7(skillsRoot)) return [];
25158
25313
  const entriesByName = /* @__PURE__ */ new Map();
25159
- for (const directory of readdirSync4(skillsRoot).sort()) {
25160
- const source = join10(skillsRoot, directory);
25161
- const skillFilePath = join10(source, "SKILL.md");
25314
+ for (const directory of readdirSync5(skillsRoot).sort()) {
25315
+ const source = join11(skillsRoot, directory);
25316
+ const skillFilePath = join11(source, "SKILL.md");
25162
25317
  if (!existsSync7(skillFilePath)) continue;
25163
25318
  const metadata = readManagedPiSkillMetadata(skillFilePath);
25164
25319
  const name = metadata.name ?? directory;
@@ -25196,7 +25351,7 @@ function createManagedPiMcpProfileApi(options = {}) {
25196
25351
  }
25197
25352
  const entries = [...entriesByName.values()].map((entry) => ({
25198
25353
  name: entry.name,
25199
- filePath: entry.filePath ?? realpathSync8(join10(entry.source, "SKILL.md"))
25354
+ filePath: entry.filePath ?? realpathSync8(join11(entry.source, "SKILL.md"))
25200
25355
  }));
25201
25356
  const metadata = measureManagedPiRoleSkillMetadata(entries);
25202
25357
  return {
@@ -25214,26 +25369,26 @@ function createManagedPiMcpProfileApi(options = {}) {
25214
25369
  return requestedSkillProfiles(input);
25215
25370
  }
25216
25371
  function seedDelegatedPiRuntime(sourceHome, agentDir) {
25217
- const source = resolve7(nonEmpty3(sourceHome, "sourcePiHome"));
25218
- const sourceStat = lstatSync7(source);
25372
+ const source = resolve8(nonEmpty3(sourceHome, "sourcePiHome"));
25373
+ const sourceStat = lstatSync8(source);
25219
25374
  if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {
25220
25375
  throw new Error("pi_delegated_mcp_source_config_unsafe: Pi home");
25221
25376
  }
25222
25377
  const protectedValues = [];
25223
- for (const entry of readdirSync4(source, { withFileTypes: true })) {
25378
+ for (const entry of readdirSync5(source, { withFileTypes: true })) {
25224
25379
  if (entry.name === "mcp.json" || entry.name === "mcp-cache.json") continue;
25225
- const sourcePath = join10(source, entry.name);
25226
- const targetPath = join10(agentDir, entry.name);
25380
+ const sourcePath = join11(source, entry.name);
25381
+ const targetPath = join11(agentDir, entry.name);
25227
25382
  if (entry.isDirectory()) {
25228
25383
  symlinkSync(sourcePath, targetPath, platform3() === "win32" ? "junction" : "dir");
25229
25384
  } else if (entry.isFile()) {
25230
25385
  copyPrivateFile(sourcePath, targetPath);
25231
25386
  }
25232
25387
  }
25233
- const authSource = join10(source, "auth.json");
25388
+ const authSource = join11(source, "auth.json");
25234
25389
  if (existsSync7(authSource)) {
25235
25390
  try {
25236
- collectAuthSecretStrings2(JSON.parse(readFileSync6(authSource, "utf8")), protectedValues);
25391
+ collectAuthSecretStrings2(JSON.parse(readFileSync7(authSource, "utf8")), protectedValues);
25237
25392
  } catch {
25238
25393
  throw new Error("pi_delegated_mcp_attestation_failed: source Pi auth is invalid");
25239
25394
  }
@@ -25376,24 +25531,24 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25376
25531
  function prepareManagedPiMcpProfile2(input) {
25377
25532
  assertInvocationIsolation2(input);
25378
25533
  const { gateway, gatewayUrl, sessionToken, headers, runId, mcpToolMode, directCatalog } = validateAuthority3(input);
25379
- const runDir = resolve7(nonEmpty3(input.runDir, "runDir"));
25380
- const cwd = resolve7(nonEmpty3(input.cwd, "cwd"));
25381
- const executorHome = resolve7(nonEmpty3(input.executorHome, "executorHome"));
25382
- if (!within3(executorHome, join10(runDir, "executors"))) throw new Error("pi_managed_mcp_owner_mismatch: executorHome is outside the managed run");
25534
+ const runDir = resolve8(nonEmpty3(input.runDir, "runDir"));
25535
+ const cwd = resolve8(nonEmpty3(input.cwd, "cwd"));
25536
+ const executorHome = resolve8(nonEmpty3(input.executorHome, "executorHome"));
25537
+ if (!within3(executorHome, join11(runDir, "executors"))) throw new Error("pi_managed_mcp_owner_mismatch: executorHome is outside the managed run");
25383
25538
  assertWorkspaceMcpOverrideClear(cwd, runDir);
25384
- const profileRoot = join10(executorHome, "managed-mcp");
25539
+ const profileRoot = join11(executorHome, "managed-mcp");
25385
25540
  if (existsSync7(profileRoot)) throw new Error(`pi_managed_mcp_profile_exists: ${profileRoot}`);
25386
- const home = join10(profileRoot, "home");
25387
- const piAgentHome = join10(profileRoot, "pi-agent-home");
25388
- const sessionsRoot = join10(profileRoot, "sessions");
25389
- const tmp = join10(profileRoot, "tmp");
25390
- for (const directory of [home, piAgentHome, sessionsRoot, tmp]) mkdirSync6(directory, { recursive: true, mode: 448 });
25391
- const workspaceMcpConfigPath = join10(cwd, ".pi", "mcp.json");
25541
+ const home = join11(profileRoot, "home");
25542
+ const piAgentHome = join11(profileRoot, "pi-agent-home");
25543
+ const sessionsRoot = join11(profileRoot, "sessions");
25544
+ const tmp = join11(profileRoot, "tmp");
25545
+ for (const directory of [home, piAgentHome, sessionsRoot, tmp]) mkdirSync7(directory, { recursive: true, mode: 448 });
25546
+ const workspaceMcpConfigPath = join11(cwd, ".pi", "mcp.json");
25392
25547
  const configPath = workspaceMcpConfigPath;
25393
25548
  try {
25394
- const markerPath = join10(profileRoot, PROFILE_MARKER3);
25549
+ const markerPath2 = join11(profileRoot, PROFILE_MARKER3);
25395
25550
  const owner = Object.freeze({ commandId: input.commandId, runId });
25396
- writePrivateFile2(markerPath, `${JSON.stringify({
25551
+ writePrivateFile2(markerPath2, `${JSON.stringify({
25397
25552
  version: 1,
25398
25553
  ...owner,
25399
25554
  profileRoot,
@@ -25436,17 +25591,17 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25436
25591
  writeOwnedFileAtomic(configPath, `${JSON.stringify(config, null, 2)}
25437
25592
  `);
25438
25593
  const extensionArgs = [];
25439
- const profileExtensionsDir = join10(profileRoot, "extensions");
25594
+ const profileExtensionsDir = join11(profileRoot, "extensions");
25440
25595
  const writeProfileExtension = (fileName, source) => {
25441
- mkdirSync6(profileExtensionsDir, { recursive: true, mode: 448 });
25442
- const extensionPath = join10(profileExtensionsDir, fileName);
25596
+ mkdirSync7(profileExtensionsDir, { recursive: true, mode: 448 });
25597
+ const extensionPath = join11(profileExtensionsDir, fileName);
25443
25598
  writePrivateFile2(extensionPath, source);
25444
25599
  extensionArgs.push("--extension", extensionPath);
25445
25600
  return extensionPath;
25446
25601
  };
25447
25602
  if (directCatalog) {
25448
25603
  const adapterExtensionPath = resolveManagedPiMcpAdapterExtension(
25449
- join10(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter")
25604
+ join11(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter")
25450
25605
  );
25451
25606
  extensionArgs.push("--extension", adapterExtensionPath);
25452
25607
  writeProfileExtension(
@@ -25468,7 +25623,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25468
25623
  cachePath,
25469
25624
  directToolProfile
25470
25625
  } = prepareDirectPiToolProfile({
25471
- cachePath: join10(profileRoot, "mcp-cache.json"),
25626
+ cachePath: join11(profileRoot, "mcp-cache.json"),
25472
25627
  profileRoot,
25473
25628
  tmp,
25474
25629
  configPath,
@@ -25561,7 +25716,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25561
25716
  restoredNativeSession,
25562
25717
  nativeSessionRestoreSkippedReason,
25563
25718
  configPath,
25564
- markerPath,
25719
+ markerPath: markerPath2,
25565
25720
  env,
25566
25721
  extensionArgs,
25567
25722
  spawnIdentity,
@@ -25618,14 +25773,14 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25618
25773
  if (owner.commandId !== expectedOwner?.commandId || owner.runId !== expectedOwner?.runId) {
25619
25774
  throw new Error("pi_run_exit_closure_baseline_owner_mismatch");
25620
25775
  }
25621
- const profileRoot = resolve7(nonEmpty3(baseline.profileRoot, "runExitClosureBaseline.profileRoot"));
25622
- const cachePath = resolve7(nonEmpty3(baseline.cachePath, "runExitClosureBaseline.cachePath"));
25776
+ const profileRoot = resolve8(nonEmpty3(baseline.profileRoot, "runExitClosureBaseline.profileRoot"));
25777
+ const cachePath = resolve8(nonEmpty3(baseline.cachePath, "runExitClosureBaseline.cachePath"));
25623
25778
  if (!within3(cachePath, profileRoot)) throw new Error("pi_run_exit_closure_baseline_path_mismatch");
25624
25779
  const closureProfile = Object.keys(record11(baseline.closureProfile)).length > 0 ? record11(baseline.closureProfile) : null;
25625
- const configPath = closureProfile ? resolve7(nonEmpty3(closureProfile.configPath, "closureProfile.configPath")) : null;
25780
+ const configPath = closureProfile ? resolve8(nonEmpty3(closureProfile.configPath, "closureProfile.configPath")) : null;
25626
25781
  for (const path of [cachePath, configPath].filter(Boolean)) {
25627
25782
  if (existsSync7(path)) {
25628
- const stat = lstatSync7(path);
25783
+ const stat = lstatSync8(path);
25629
25784
  if (!stat.isFile() || stat.isSymbolicLink()) {
25630
25785
  throw new Error(`pi_run_exit_closure_baseline_unsafe: ${path}`);
25631
25786
  }
@@ -25676,22 +25831,22 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25676
25831
  function prepareDelegatedPiMcpProfile2(input) {
25677
25832
  assertInvocationIsolation2(input);
25678
25833
  const { gateway, gatewayUrl, sessionToken, headers, runId, mcpToolMode, directCatalog } = validateAuthority3(input);
25679
- const runDir = resolve7(nonEmpty3(input.runDir, "runDir"));
25680
- const cwd = resolve7(nonEmpty3(input.cwd, "cwd"));
25834
+ const runDir = resolve8(nonEmpty3(input.runDir, "runDir"));
25835
+ const cwd = resolve8(nonEmpty3(input.cwd, "cwd"));
25681
25836
  if (!within3(cwd, runDir)) throw new Error("pi_delegated_mcp_owner_mismatch: cwd is outside the managed run");
25682
25837
  assertNoProjectMcpOverride(cwd, runDir);
25683
- const executorHome = resolve7(nonEmpty3(input.executorHome, "executorHome"));
25684
- if (!within3(executorHome, join10(runDir, "executors"))) throw new Error("pi_delegated_mcp_owner_mismatch: executorHome is outside the managed run");
25685
- const profileRoot = join10(executorHome, "delegated-mcp");
25838
+ const executorHome = resolve8(nonEmpty3(input.executorHome, "executorHome"));
25839
+ if (!within3(executorHome, join11(runDir, "executors"))) throw new Error("pi_delegated_mcp_owner_mismatch: executorHome is outside the managed run");
25840
+ const profileRoot = join11(executorHome, "delegated-mcp");
25686
25841
  if (existsSync7(profileRoot)) throw new Error(`pi_delegated_mcp_profile_exists: ${profileRoot}`);
25687
- const piCodingAgentDir = join10(profileRoot, "pi-coding-agent-dir");
25688
- const sessionsRoot = join10(profileRoot, "sessions");
25689
- const tmp = join10(profileRoot, "tmp");
25690
- for (const directory of [profileRoot, piCodingAgentDir, sessionsRoot, tmp]) mkdirSync6(directory, { recursive: true, mode: 448 });
25842
+ const piCodingAgentDir = join11(profileRoot, "pi-coding-agent-dir");
25843
+ const sessionsRoot = join11(profileRoot, "sessions");
25844
+ const tmp = join11(profileRoot, "tmp");
25845
+ for (const directory of [profileRoot, piCodingAgentDir, sessionsRoot, tmp]) mkdirSync7(directory, { recursive: true, mode: 448 });
25691
25846
  try {
25692
- const markerPath = join10(profileRoot, DELEGATED_PROFILE_MARKER);
25847
+ const markerPath2 = join11(profileRoot, DELEGATED_PROFILE_MARKER);
25693
25848
  const owner = Object.freeze({ commandId: input.commandId, runId });
25694
- writePrivateFile2(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot, piCodingAgentDir })}
25849
+ writePrivateFile2(markerPath2, `${JSON.stringify({ version: 1, ...owner, profileRoot, piCodingAgentDir })}
25695
25850
  `);
25696
25851
  const runtimeAuth = record11(input.runtimeAuth);
25697
25852
  const authority = Object.freeze({
@@ -25701,14 +25856,14 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25701
25856
  runId,
25702
25857
  commandId: input.commandId
25703
25858
  });
25704
- const sourcePiHome = resolve7(nonEmpty3(input.baseEnv?.PI_CODING_AGENT_DIR ?? input.baseEnv?.PI_AGENT_HOME, "sourcePiHome"));
25705
- const sourceStat = lstatSync7(sourcePiHome);
25859
+ const sourcePiHome = resolve8(nonEmpty3(input.baseEnv?.PI_CODING_AGENT_DIR ?? input.baseEnv?.PI_AGENT_HOME, "sourcePiHome"));
25860
+ const sourceStat = lstatSync8(sourcePiHome);
25706
25861
  if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {
25707
25862
  throw new Error("pi_delegated_mcp_source_config_unsafe: Pi home");
25708
25863
  }
25709
25864
  const seededRuntime = seedDelegatedPiRuntime(sourcePiHome, piCodingAgentDir);
25710
- const sourceMcp = readJsonObjectFile(join10(sourcePiHome, "mcp.json"));
25711
- const configPath = join10(piCodingAgentDir, "mcp.json");
25865
+ const sourceMcp = readJsonObjectFile(join11(sourcePiHome, "mcp.json"));
25866
+ const configPath = join11(piCodingAgentDir, "mcp.json");
25712
25867
  const directToolNames = directCatalog?.tools.map((tool) => tool.exposedName) ?? [];
25713
25868
  const serverConfig = {
25714
25869
  type: "http",
@@ -25737,10 +25892,10 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25737
25892
  writePrivateFile2(configPath, `${JSON.stringify(config, null, 2)}
25738
25893
  `);
25739
25894
  const extensionArgs = [];
25740
- const profileExtensionsDir = join10(profileRoot, "extensions");
25895
+ const profileExtensionsDir = join11(profileRoot, "extensions");
25741
25896
  const writeProfileExtension = (fileName, source) => {
25742
- mkdirSync6(profileExtensionsDir, { recursive: true, mode: 448 });
25743
- const extensionPath = join10(profileExtensionsDir, fileName);
25897
+ mkdirSync7(profileExtensionsDir, { recursive: true, mode: 448 });
25898
+ const extensionPath = join11(profileExtensionsDir, fileName);
25744
25899
  writePrivateFile2(extensionPath, source);
25745
25900
  extensionArgs.push("--extension", extensionPath);
25746
25901
  return extensionPath;
@@ -25781,7 +25936,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25781
25936
  } = prepareDirectPiToolProfile({
25782
25937
  // Use the adapter's native path inside the isolated run home. Desktop
25783
25938
  // installs need no cache-override patch; never point this at sourcePiHome.
25784
- cachePath: join10(piCodingAgentDir, "mcp-cache.json"),
25939
+ cachePath: join11(piCodingAgentDir, "mcp-cache.json"),
25785
25940
  profileRoot,
25786
25941
  tmp,
25787
25942
  configPath,
@@ -25846,7 +26001,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25846
26001
  authority,
25847
26002
  restoredNativeSession: null,
25848
26003
  configPath,
25849
- markerPath,
26004
+ markerPath: markerPath2,
25850
26005
  env,
25851
26006
  extensionArgs,
25852
26007
  spawnIdentity,
@@ -25886,19 +26041,19 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25886
26041
  function preserveManagedPiSessionRollout2(profile, input) {
25887
26042
  const sessionId = nonEmpty3(input?.sessionId, "sessionId");
25888
26043
  const sourceWorkspacePath = nonEmpty3(input?.sourceWorkspacePath, "sourceWorkspacePath");
25889
- const sessionsRoot = resolve7(nonEmpty3(profile?.env?.["AMASTER-CLI_CODING_AGENT_SESSION_DIR"], "profile session dir"));
26044
+ const sessionsRoot = resolve8(nonEmpty3(profile?.env?.["AMASTER-CLI_CODING_AGENT_SESSION_DIR"], "profile session dir"));
25890
26045
  const sourceRollout = findPiSessionRollout(sessionsRoot, sessionId);
25891
26046
  const rolloutRelativePath = relative3(sessionsRoot, sourceRollout);
25892
26047
  if (!rolloutRelativePath || rolloutRelativePath.startsWith("..") || isAbsolute4(rolloutRelativePath)) {
25893
26048
  throw new Error("pi_managed_mcp_session_rollout_unsafe: rollout escaped the managed Pi home");
25894
26049
  }
25895
- const cacheRoot = join10(dirname5(resolve7(profile.profileRoot)), "session-rollout");
26050
+ const cacheRoot = join11(dirname6(resolve8(profile.profileRoot)), "session-rollout");
25896
26051
  if (existsSync7(cacheRoot)) rmSync5(cacheRoot, { recursive: true, force: false });
25897
- mkdirSync6(cacheRoot, { recursive: true, mode: 448 });
25898
- const targetRollout = join10(cacheRoot, rolloutRelativePath);
25899
- mkdirSync6(dirname5(targetRollout), { recursive: true, mode: 448 });
25900
- writePrivateFile2(targetRollout, readFileSync6(sourceRollout));
25901
- writePrivateFile2(join10(cacheRoot, SESSION_ROLLOUT_MARKER3), `${JSON.stringify({
26052
+ mkdirSync7(cacheRoot, { recursive: true, mode: 448 });
26053
+ const targetRollout = join11(cacheRoot, rolloutRelativePath);
26054
+ mkdirSync7(dirname6(targetRollout), { recursive: true, mode: 448 });
26055
+ writePrivateFile2(targetRollout, readFileSync7(sourceRollout));
26056
+ writePrivateFile2(join11(cacheRoot, SESSION_ROLLOUT_MARKER3), `${JSON.stringify({
25902
26057
  version: 1,
25903
26058
  cacheRoot,
25904
26059
  preservedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -25917,17 +26072,17 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25917
26072
  function cleanupRestoredManagedPiSessionRollout2(profile) {
25918
26073
  const restored = profile?.restoredNativeSession;
25919
26074
  if (!restored?.cacheRoot) return { status: "not_restored" };
25920
- const cacheRoot = resolve7(restored.cacheRoot);
26075
+ const cacheRoot = resolve8(restored.cacheRoot);
25921
26076
  if (!existsSync7(cacheRoot)) return { status: "already_removed" };
25922
- const cacheStat = lstatSync7(cacheRoot);
26077
+ const cacheStat = lstatSync8(cacheRoot);
25923
26078
  if (!cacheStat.isDirectory() || cacheStat.isSymbolicLink()) {
25924
26079
  throw new Error("pi_managed_mcp_session_rollout_cleanup_unsafe: cache root is not a private directory");
25925
26080
  }
25926
- const markerPath = join10(cacheRoot, SESSION_ROLLOUT_MARKER3);
25927
- if (!existsSync7(markerPath) || lstatSync7(markerPath).isSymbolicLink() || !lstatSync7(markerPath).isFile()) {
26081
+ const markerPath2 = join11(cacheRoot, SESSION_ROLLOUT_MARKER3);
26082
+ if (!existsSync7(markerPath2) || lstatSync8(markerPath2).isSymbolicLink() || !lstatSync8(markerPath2).isFile()) {
25928
26083
  throw new Error("pi_managed_mcp_session_rollout_cleanup_unsafe: ownership marker is unavailable");
25929
26084
  }
25930
- const marker = JSON.parse(readFileSync6(markerPath, "utf8"));
26085
+ const marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
25931
26086
  if (marker?.companyId !== profile.authority.companyId || marker?.agentId !== profile.authority.agentId || marker?.issueId !== profile.authority.issueId || marker?.sourceRunId !== restored.sourceRunId || marker?.sourceCommandId !== restored.sourceCommandId || marker?.sessionId !== restored.sessionId) {
25932
26087
  throw new Error("pi_managed_mcp_session_rollout_cleanup_unsafe: ownership marker does not match restored authority");
25933
26088
  }
@@ -25936,42 +26091,42 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25936
26091
  return { status: "removed" };
25937
26092
  }
25938
26093
  function removeWorkspaceMcpConfig(configPath, profileRoot) {
25939
- const target = resolve7(configPath);
26094
+ const target = resolve8(configPath);
25940
26095
  if (!workspaceMcpConfigBelongsToProfile(target, profileRoot)) {
25941
26096
  throw new Error(`pi_managed_mcp_workspace_config_unsafe: ${target}`);
25942
26097
  }
25943
26098
  try {
25944
- const stat = lstatSync7(target);
26099
+ const stat = lstatSync8(target);
25945
26100
  if (stat.isFile() && !stat.isSymbolicLink()) rmSync5(target);
25946
26101
  } catch (error) {
25947
26102
  if (error?.code !== "ENOENT") throw error;
25948
26103
  }
25949
26104
  try {
25950
- rmdirSync(dirname5(target));
26105
+ rmdirSync2(dirname6(target));
25951
26106
  } catch (error) {
25952
26107
  if (!["ENOENT", "ENOTEMPTY", "ENOTDIR"].includes(error?.code)) throw error;
25953
26108
  }
25954
26109
  }
25955
26110
  function cleanupManagedPiMcpProfile2(profile, owner) {
25956
- const profileRoot = resolve7(nonEmpty3(profile?.profileRoot, "profileRoot"));
26111
+ const profileRoot = resolve8(nonEmpty3(profile?.profileRoot, "profileRoot"));
25957
26112
  if (!existsSync7(profileRoot)) {
25958
26113
  if (typeof profile?.workspaceMcpConfigPath === "string") {
25959
26114
  removeWorkspaceMcpConfig(profile.workspaceMcpConfigPath, profileRoot);
25960
26115
  }
25961
26116
  return { status: "already_removed", profileRoot };
25962
26117
  }
25963
- const rootStat = lstatSync7(profileRoot);
26118
+ const rootStat = lstatSync8(profileRoot);
25964
26119
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
25965
26120
  throw new Error("pi_managed_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
25966
26121
  }
25967
- const markerPath = join10(profileRoot, PROFILE_MARKER3);
25968
- const markerStat = existsSync7(markerPath) ? lstatSync7(markerPath) : null;
26122
+ const markerPath2 = join11(profileRoot, PROFILE_MARKER3);
26123
+ const markerStat = existsSync7(markerPath2) ? lstatSync8(markerPath2) : null;
25969
26124
  if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
25970
26125
  throw new Error("pi_managed_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
25971
26126
  }
25972
26127
  let marker;
25973
26128
  try {
25974
- marker = JSON.parse(readFileSync6(markerPath, "utf8"));
26129
+ marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
25975
26130
  } catch {
25976
26131
  throw new Error("pi_managed_mcp_cleanup_owner_mismatch: ownership marker is invalid");
25977
26132
  }
@@ -25986,20 +26141,20 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25986
26141
  return { status: "removed", profileRoot };
25987
26142
  }
25988
26143
  function cleanupDelegatedPiMcpProfile2(profile, owner) {
25989
- const profileRoot = resolve7(nonEmpty3(profile?.profileRoot, "profileRoot"));
26144
+ const profileRoot = resolve8(nonEmpty3(profile?.profileRoot, "profileRoot"));
25990
26145
  if (!existsSync7(profileRoot)) return { status: "already_removed", profileRoot };
25991
- const rootStat = lstatSync7(profileRoot);
26146
+ const rootStat = lstatSync8(profileRoot);
25992
26147
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
25993
26148
  throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: profile root is not an owned directory");
25994
26149
  }
25995
- const markerPath = join10(profileRoot, DELEGATED_PROFILE_MARKER);
25996
- const markerStat = existsSync7(markerPath) ? lstatSync7(markerPath) : null;
26150
+ const markerPath2 = join11(profileRoot, DELEGATED_PROFILE_MARKER);
26151
+ const markerStat = existsSync7(markerPath2) ? lstatSync8(markerPath2) : null;
25997
26152
  if (!markerStat?.isFile() || markerStat.isSymbolicLink()) {
25998
26153
  throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: ownership marker is missing or unsafe");
25999
26154
  }
26000
26155
  let marker;
26001
26156
  try {
26002
- marker = JSON.parse(readFileSync6(markerPath, "utf8"));
26157
+ marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
26003
26158
  } catch {
26004
26159
  throw new Error("pi_delegated_mcp_cleanup_owner_mismatch: ownership marker is invalid");
26005
26160
  }
@@ -26011,7 +26166,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
26011
26166
  return { status: "removed", profileRoot };
26012
26167
  }
26013
26168
  function reconcileManagedPiMcpProfiles2(rootPath, options2 = {}) {
26014
- const root = resolve7(rootPath);
26169
+ const root = resolve8(rootPath);
26015
26170
  if (!existsSync7(root)) return { scanned: 0, removed: 0, removedProfiles: 0, removedRollouts: 0, failed: 0, failures: [] };
26016
26171
  const canonicalRoot = realpathSync8(root);
26017
26172
  const profileMarkers = [];
@@ -26019,10 +26174,10 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
26019
26174
  const pending = [root];
26020
26175
  while (pending.length > 0) {
26021
26176
  const current = pending.pop();
26022
- const currentStat = lstatSync7(current);
26177
+ const currentStat = lstatSync8(current);
26023
26178
  if (!currentStat.isDirectory() || currentStat.isSymbolicLink()) continue;
26024
- for (const entry of readdirSync4(current, { withFileTypes: true })) {
26025
- const fullPath = join10(current, entry.name);
26179
+ for (const entry of readdirSync5(current, { withFileTypes: true })) {
26180
+ const fullPath = join11(current, entry.name);
26026
26181
  if (entry.isDirectory() && !entry.isSymbolicLink()) pending.push(fullPath);
26027
26182
  else if (entry.isFile() && entry.name === PROFILE_MARKER3) profileMarkers.push(fullPath);
26028
26183
  else if (entry.isFile() && entry.name === SESSION_ROLLOUT_MARKER3) rolloutMarkers.push(fullPath);
@@ -26033,11 +26188,11 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
26033
26188
  let removedRollouts = 0;
26034
26189
  const failures = [];
26035
26190
  const protectedCommandIds = new Set(Array.isArray(options2.protectedCommandIds) ? options2.protectedCommandIds.filter((value) => typeof value === "string" && value) : []);
26036
- for (const markerPath of profileMarkers) {
26037
- const profileRoot = dirname5(markerPath);
26191
+ for (const markerPath2 of profileMarkers) {
26192
+ const profileRoot = dirname6(markerPath2);
26038
26193
  try {
26039
- const marker = JSON.parse(readFileSync6(markerPath, "utf8"));
26040
- const markerProfileRoot = typeof marker?.profileRoot === "string" ? resolve7(marker.profileRoot) : null;
26194
+ const marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
26195
+ const markerProfileRoot = typeof marker?.profileRoot === "string" ? resolve8(marker.profileRoot) : null;
26041
26196
  if (!markerProfileRoot || !existsSync7(markerProfileRoot) || !within3(realpathSync8(profileRoot), canonicalRoot) || realpathSync8(markerProfileRoot) !== realpathSync8(profileRoot)) throw new Error("ownership marker root mismatch");
26042
26197
  if (protectedCommandIds.has(marker?.commandId)) {
26043
26198
  preservedProfiles += 1;
@@ -26058,13 +26213,13 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
26058
26213
  }
26059
26214
  const nowMs = Number.isFinite(options2.nowMs) ? options2.nowMs : Date.now();
26060
26215
  const rolloutTtlMs = Number.isFinite(options2.sessionRolloutTtlMs) && options2.sessionRolloutTtlMs > 0 ? options2.sessionRolloutTtlMs : DEFAULT_SESSION_ROLLOUT_TTL_MS3;
26061
- for (const markerPath of rolloutMarkers) {
26062
- const cacheRoot = dirname5(markerPath);
26216
+ for (const markerPath2 of rolloutMarkers) {
26217
+ const cacheRoot = dirname6(markerPath2);
26063
26218
  try {
26064
- const markerStat = lstatSync7(markerPath);
26065
- const cacheStat = lstatSync7(cacheRoot);
26066
- const marker = JSON.parse(readFileSync6(markerPath, "utf8"));
26067
- const markerCacheRoot = typeof marker?.cacheRoot === "string" ? resolve7(marker.cacheRoot) : null;
26219
+ const markerStat = lstatSync8(markerPath2);
26220
+ const cacheStat = lstatSync8(cacheRoot);
26221
+ const marker = JSON.parse(readFileSync7(markerPath2, "utf8"));
26222
+ const markerCacheRoot = typeof marker?.cacheRoot === "string" ? resolve8(marker.cacheRoot) : null;
26068
26223
  if (!within3(realpathSync8(cacheRoot), canonicalRoot) || basename3(cacheRoot) !== "session-rollout" || markerStat.isSymbolicLink() || !markerStat.isFile() || cacheStat.isSymbolicLink() || !cacheStat.isDirectory() || marker?.version !== 1 || typeof marker?.companyId !== "string" || typeof marker?.agentId !== "string" || typeof marker?.sourceRunId !== "string" || typeof marker?.sourceCommandId !== "string" || typeof marker?.sessionId !== "string" || !markerCacheRoot || !existsSync7(markerCacheRoot) || realpathSync8(markerCacheRoot) !== realpathSync8(cacheRoot)) throw new Error("session rollout ownership marker mismatch");
26069
26224
  const preservedAtMs = typeof marker.preservedAt === "string" ? Date.parse(marker.preservedAt) : Number.NaN;
26070
26225
  const markerAgeMs = nowMs - (Number.isFinite(preservedAtMs) ? preservedAtMs : markerStat.mtimeMs);
@@ -26205,8 +26360,8 @@ function runtimeExactTaskResourceBinding(payload) {
26205
26360
  }
26206
26361
 
26207
26362
  // src/amaster-runtime-daemon/pi-exact-source-read.mjs
26208
- import { chmodSync as chmodSync5, mkdirSync as mkdirSync7, renameSync as renameSync4, rmSync as rmSync6, writeFileSync as writeFileSync7, writeSync } from "node:fs";
26209
- import { dirname as dirname6, join as join11 } from "node:path";
26363
+ import { chmodSync as chmodSync6, mkdirSync as mkdirSync8, renameSync as renameSync5, rmSync as rmSync6, writeFileSync as writeFileSync8, writeSync } from "node:fs";
26364
+ import { dirname as dirname7, join as join12 } from "node:path";
26210
26365
 
26211
26366
  // src/amaster-runtime-daemon/public-network-scope.mjs
26212
26367
  import { BlockList, isIP } from "node:net";
@@ -26269,17 +26424,17 @@ export default function amasterExactSourceRead(pi) { registerExactSourceReadTool
26269
26424
  `;
26270
26425
  }
26271
26426
  function materializePiExactSourceReadExtension(profileRoot, binding) {
26272
- const extensionPath = join11(profileRoot, "extensions", "amaster-exact-source-read.js");
26273
- mkdirSync7(dirname6(extensionPath), { recursive: true, mode: 448 });
26427
+ const extensionPath = join12(profileRoot, "extensions", "amaster-exact-source-read.js");
26428
+ mkdirSync8(dirname7(extensionPath), { recursive: true, mode: 448 });
26274
26429
  const temporaryPath = `${extensionPath}.${process.pid}.tmp`;
26275
26430
  try {
26276
- writeFileSync7(temporaryPath, managedPiExactSourceReadExtensionSource(binding), {
26431
+ writeFileSync8(temporaryPath, managedPiExactSourceReadExtensionSource(binding), {
26277
26432
  encoding: "utf8",
26278
26433
  mode: 384,
26279
26434
  flag: "wx"
26280
26435
  });
26281
- renameSync4(temporaryPath, extensionPath);
26282
- chmodSync5(extensionPath, 384);
26436
+ renameSync5(temporaryPath, extensionPath);
26437
+ chmodSync6(extensionPath, 384);
26283
26438
  return extensionPath;
26284
26439
  } finally {
26285
26440
  rmSync6(temporaryPath, { force: true });
@@ -26363,7 +26518,7 @@ function resolveCodebuddyCommandModel(command = {}, environmentModel = null) {
26363
26518
  }
26364
26519
 
26365
26520
  // src/amaster-runtime-daemon/executor-process.mjs
26366
- import { readdirSync as readdirSync5, readFileSync as readFileSync7 } from "node:fs";
26521
+ import { readdirSync as readdirSync6, readFileSync as readFileSync8 } from "node:fs";
26367
26522
  var TERMINAL_LINUX_PROCESS_STATES = /* @__PURE__ */ new Set(["Z", "X", "x"]);
26368
26523
  function processGroupIdForChild(child, processPlatform = process.platform) {
26369
26524
  return processPlatform === "win32" || typeof child.pid !== "number" || child.pid <= 0 ? null : child.pid;
@@ -26376,7 +26531,7 @@ function linuxProcState(stat) {
26376
26531
  const processGroupId = Number.parseInt(fields[2], 10);
26377
26532
  return Number.isInteger(processGroupId) ? { state: fields[0], processGroupId } : null;
26378
26533
  }
26379
- function linuxProcessGroupHasLiveMembers(processGroupId, procRoot = "/proc", fsApi = { readdirSync: readdirSync5, readFileSync: readFileSync7 }) {
26534
+ function linuxProcessGroupHasLiveMembers(processGroupId, procRoot = "/proc", fsApi = { readdirSync: readdirSync6, readFileSync: readFileSync8 }) {
26380
26535
  let entries;
26381
26536
  try {
26382
26537
  entries = fsApi.readdirSync(procRoot, { withFileTypes: true });
@@ -26423,7 +26578,7 @@ function isProcessIdAlive(pid, processApi = process) {
26423
26578
  processApi.kill(pid, 0);
26424
26579
  if (processApi.platform === "linux") {
26425
26580
  try {
26426
- const parsed = linuxProcState(readFileSync7(`/proc/${pid}/stat`, "utf8"));
26581
+ const parsed = linuxProcState(readFileSync8(`/proc/${pid}/stat`, "utf8"));
26427
26582
  if (parsed && TERMINAL_LINUX_PROCESS_STATES.has(parsed.state)) return false;
26428
26583
  } catch {
26429
26584
  }
@@ -26522,8 +26677,8 @@ function isTerminalResultOutboxStatus(status) {
26522
26677
  }
26523
26678
 
26524
26679
  // src/amaster-runtime-daemon/run-completion-state.mjs
26525
- import { existsSync as existsSync8, mkdirSync as mkdirSync8, readFileSync as readFileSync8, readdirSync as readdirSync6, renameSync as renameSync5, unlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
26526
- import { join as join12 } from "node:path";
26680
+ import { existsSync as existsSync8, mkdirSync as mkdirSync9, readFileSync as readFileSync9, readdirSync as readdirSync7, renameSync as renameSync6, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "node:fs";
26681
+ import { join as join13 } from "node:path";
26527
26682
 
26528
26683
  // src/amaster-runtime-daemon/typed/run-completion-transitions.mjs
26529
26684
  var RUN_COMPLETION_PHASES = /* @__PURE__ */ new Set([
@@ -26785,24 +26940,24 @@ function assertValidRunCompletionState(value) {
26785
26940
  }
26786
26941
  function writeRunCompletionState(directory, state) {
26787
26942
  const valid = assertValidRunCompletionState(state);
26788
- mkdirSync8(directory, { recursive: true, mode: 448 });
26789
- const filePath = join12(directory, runCompletionStateFileName(valid.commandId));
26943
+ mkdirSync9(directory, { recursive: true, mode: 448 });
26944
+ const filePath = join13(directory, runCompletionStateFileName(valid.commandId));
26790
26945
  const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
26791
- writeFileSync8(temporaryPath, `${JSON.stringify(valid, null, 2)}
26946
+ writeFileSync9(temporaryPath, `${JSON.stringify(valid, null, 2)}
26792
26947
  `, { mode: 384 });
26793
- renameSync5(temporaryPath, filePath);
26948
+ renameSync6(temporaryPath, filePath);
26794
26949
  return filePath;
26795
26950
  }
26796
26951
  function readRunCompletionState(filePath) {
26797
- return assertValidRunCompletionState(JSON.parse(readFileSync8(filePath, "utf8")));
26952
+ return assertValidRunCompletionState(JSON.parse(readFileSync9(filePath, "utf8")));
26798
26953
  }
26799
26954
  function listRunCompletionStateFiles(directory) {
26800
26955
  if (!existsSync8(directory)) return [];
26801
- return readdirSync6(directory).filter((name) => name.endsWith(".json")).sort().map((name) => join12(directory, name));
26956
+ return readdirSync7(directory).filter((name) => name.endsWith(".json")).sort().map((name) => join13(directory, name));
26802
26957
  }
26803
26958
  function removeRunCompletionState(directory, commandId) {
26804
- const filePath = join12(directory, runCompletionStateFileName(commandId));
26805
- if (existsSync8(filePath)) unlinkSync(filePath);
26959
+ const filePath = join13(directory, runCompletionStateFileName(commandId));
26960
+ if (existsSync8(filePath)) unlinkSync2(filePath);
26806
26961
  }
26807
26962
 
26808
26963
  // src/amaster-runtime-daemon/run-completion/coordinator.mjs
@@ -29851,7 +30006,7 @@ function createRunCompletionRuntimePorts(input) {
29851
30006
  outbox,
29852
30007
  limits,
29853
30008
  now = () => (/* @__PURE__ */ new Date()).toISOString(),
29854
- sleep = (delayMs) => new Promise((resolve20) => setTimeout(resolve20, delayMs)),
30009
+ sleep = (delayMs) => new Promise((resolve21) => setTimeout(resolve21, delayMs)),
29855
30010
  diagnostic = (message) => process.stderr.write(`${message}
29856
30011
  `)
29857
30012
  } = input;
@@ -32323,20 +32478,20 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
32323
32478
 
32324
32479
  // src/amaster-runtime-daemon/agent-instruction-delivery.mjs
32325
32480
  import { createHash as createHash13, randomBytes } from "node:crypto";
32326
- import { existsSync as existsSync10, lstatSync as lstatSync8, mkdirSync as mkdirSync9, readFileSync as readFileSync10, readdirSync as readdirSync7, realpathSync as realpathSync9, renameSync as renameSync7, rmSync as rmSync8, writeFileSync as writeFileSync10 } from "node:fs";
32327
- import { dirname as dirname8, isAbsolute as isAbsolute6, join as join14, relative as relative4, resolve as resolve8 } from "node:path";
32481
+ import { existsSync as existsSync10, lstatSync as lstatSync9, mkdirSync as mkdirSync10, readFileSync as readFileSync11, readdirSync as readdirSync8, realpathSync as realpathSync9, renameSync as renameSync8, rmSync as rmSync8, writeFileSync as writeFileSync11 } from "node:fs";
32482
+ import { dirname as dirname9, isAbsolute as isAbsolute6, join as join15, relative as relative4, resolve as resolve9 } from "node:path";
32328
32483
 
32329
32484
  // src/amaster-runtime-daemon/workspace-manifest.mjs
32330
- import { chownSync as chownSync3, existsSync as existsSync9, readFileSync as readFileSync9, renameSync as renameSync6, rmSync as rmSync7, statSync as statSync5, writeFileSync as writeFileSync9 } from "node:fs";
32331
- import { basename as basename5, dirname as dirname7, join as join13 } from "node:path";
32485
+ import { chownSync as chownSync4, existsSync as existsSync9, readFileSync as readFileSync10, renameSync as renameSync7, rmSync as rmSync7, statSync as statSync5, writeFileSync as writeFileSync10 } from "node:fs";
32486
+ import { basename as basename5, dirname as dirname8, join as join14 } from "node:path";
32332
32487
  var WORKSPACE_MANIFEST_FILENAME = ".amaster-runtime.json";
32333
32488
  function syncManifestDirOwnership(manifestPath, deps = {}) {
32334
32489
  const stat = deps.statSync ?? statSync5;
32335
- const chown = deps.chownSync ?? chownSync3;
32490
+ const chown = deps.chownSync ?? chownSync4;
32336
32491
  const geteuid = deps.geteuid ?? (typeof process.geteuid === "function" ? process.geteuid.bind(process) : () => null);
32337
32492
  try {
32338
32493
  if (geteuid() !== 0) return false;
32339
- const dirStat = stat(dirname7(manifestPath));
32494
+ const dirStat = stat(dirname8(manifestPath));
32340
32495
  if (dirStat.uid === 0 && dirStat.gid === 0) return false;
32341
32496
  chown(manifestPath, dirStat.uid, dirStat.gid);
32342
32497
  return true;
@@ -32349,28 +32504,28 @@ function nowIso() {
32349
32504
  }
32350
32505
  function workspaceManifestPath(workspaceOrCwd) {
32351
32506
  if (!workspaceOrCwd) return null;
32352
- if (typeof workspaceOrCwd === "string") return join13(workspaceOrCwd, WORKSPACE_MANIFEST_FILENAME);
32353
- if (typeof workspaceOrCwd.cwd === "string") return join13(workspaceOrCwd.cwd, WORKSPACE_MANIFEST_FILENAME);
32507
+ if (typeof workspaceOrCwd === "string") return join14(workspaceOrCwd, WORKSPACE_MANIFEST_FILENAME);
32508
+ if (typeof workspaceOrCwd.cwd === "string") return join14(workspaceOrCwd.cwd, WORKSPACE_MANIFEST_FILENAME);
32354
32509
  return null;
32355
32510
  }
32356
32511
  function readWorkspaceManifest(manifestPath) {
32357
32512
  if (!manifestPath || !existsSync9(manifestPath)) return null;
32358
32513
  try {
32359
- const parsed = JSON.parse(readFileSync9(manifestPath, "utf8"));
32514
+ const parsed = JSON.parse(readFileSync10(manifestPath, "utf8"));
32360
32515
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
32361
32516
  } catch {
32362
32517
  return null;
32363
32518
  }
32364
32519
  }
32365
32520
  function writeWorkspaceManifest(manifestPath, manifest, deps) {
32366
- const tempPath = join13(
32367
- dirname7(manifestPath),
32521
+ const tempPath = join14(
32522
+ dirname8(manifestPath),
32368
32523
  `.${basename5(manifestPath)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
32369
32524
  );
32370
32525
  try {
32371
- writeFileSync9(tempPath, `${JSON.stringify(manifest, null, 2)}
32526
+ writeFileSync10(tempPath, `${JSON.stringify(manifest, null, 2)}
32372
32527
  `, { mode: 384 });
32373
- renameSync6(tempPath, manifestPath);
32528
+ renameSync7(tempPath, manifestPath);
32374
32529
  syncManifestDirOwnership(manifestPath, deps);
32375
32530
  } catch (err) {
32376
32531
  rmSync7(tempPath, { force: true });
@@ -32443,7 +32598,7 @@ function pathWithin(candidate, root) {
32443
32598
  }
32444
32599
  function lstatIfPresent2(path) {
32445
32600
  try {
32446
- return lstatSync8(path);
32601
+ return lstatSync9(path);
32447
32602
  } catch (error) {
32448
32603
  if (error?.code === "ENOENT") return null;
32449
32604
  throw error;
@@ -32451,9 +32606,9 @@ function lstatIfPresent2(path) {
32451
32606
  }
32452
32607
  function canonicalExistingPath(path) {
32453
32608
  try {
32454
- return realpathSync9(resolve8(path));
32609
+ return realpathSync9(resolve9(path));
32455
32610
  } catch {
32456
- return resolve8(path);
32611
+ return resolve9(path);
32457
32612
  }
32458
32613
  }
32459
32614
  function isManagedExecutionDirectory(directory, managedWorkspacesRoot) {
@@ -32461,11 +32616,11 @@ function isManagedExecutionDirectory(directory, managedWorkspacesRoot) {
32461
32616
  const managedRoot = canonicalExistingPath(managedWorkspacesRoot);
32462
32617
  const candidate = canonicalExistingPath(directory);
32463
32618
  if (!pathWithin(candidate, managedRoot)) return false;
32464
- const manifestPath = join14(candidate, WORKSPACE_MANIFEST_FILENAME);
32619
+ const manifestPath = join15(candidate, WORKSPACE_MANIFEST_FILENAME);
32465
32620
  const manifestStat = lstatIfPresent2(manifestPath);
32466
32621
  if (!manifestStat?.isFile() || manifestStat.isSymbolicLink()) return false;
32467
32622
  try {
32468
- const manifest = JSON.parse(readFileSync10(manifestPath, "utf8"));
32623
+ const manifest = JSON.parse(readFileSync11(manifestPath, "utf8"));
32469
32624
  if (!manifest || typeof manifest !== "object" || Array.isArray(manifest) || manifest.managed !== true) {
32470
32625
  return false;
32471
32626
  }
@@ -32475,7 +32630,7 @@ function isManagedExecutionDirectory(directory, managedWorkspacesRoot) {
32475
32630
  }
32476
32631
  }
32477
32632
  function inspectExternalWorkspaceProjectInstructions(sourceWorkspacePath, options = {}) {
32478
- const root = resolve8(sourceWorkspacePath);
32633
+ const root = resolve9(sourceWorkspacePath);
32479
32634
  const pending = [root];
32480
32635
  const sources = [];
32481
32636
  const ignoredManagedExecutionDirectories = [];
@@ -32495,7 +32650,7 @@ function inspectExternalWorkspaceProjectInstructions(sourceWorkspacePath, option
32495
32650
  }
32496
32651
  let entries;
32497
32652
  try {
32498
- entries = readdirSync7(directory, { withFileTypes: true });
32653
+ entries = readdirSync8(directory, { withFileTypes: true });
32499
32654
  } catch (error) {
32500
32655
  throw instructionTopologyError(
32501
32656
  "workspace_project_instruction_discovery_incomplete",
@@ -32506,7 +32661,7 @@ function inspectExternalWorkspaceProjectInstructions(sourceWorkspacePath, option
32506
32661
  entries.sort((left, right) => left.name.localeCompare(right.name));
32507
32662
  for (const entry of entries) {
32508
32663
  if (entry.isDirectory() && PROJECT_INSTRUCTION_SCAN_IGNORED_DIRECTORIES.has(entry.name)) continue;
32509
- const absolutePath = resolve8(directory, entry.name);
32664
+ const absolutePath = resolve9(directory, entry.name);
32510
32665
  const relativePath = relative4(root, absolutePath).replaceAll("\\", "/");
32511
32666
  if (entry.isSymbolicLink()) {
32512
32667
  if (PROJECT_INSTRUCTION_NAMES.has(entry.name)) {
@@ -32522,14 +32677,14 @@ function inspectExternalWorkspaceProjectInstructions(sourceWorkspacePath, option
32522
32677
  continue;
32523
32678
  }
32524
32679
  if (!PROJECT_INSTRUCTION_NAMES.has(entry.name)) continue;
32525
- const stat = lstatSync8(absolutePath);
32680
+ const stat = lstatSync9(absolutePath);
32526
32681
  if (!stat.isFile()) {
32527
32682
  throw instructionTopologyError(
32528
32683
  "workspace_project_instruction_source_unsafe",
32529
32684
  `project instruction source is not a regular file: ${relativePath}`
32530
32685
  );
32531
32686
  }
32532
- const content = readFileSync10(absolutePath);
32687
+ const content = readFileSync11(absolutePath);
32533
32688
  sources.push({
32534
32689
  path: relativePath,
32535
32690
  scope: relativePath.includes("/") ? relativePath.slice(0, relativePath.lastIndexOf("/")) : ".",
@@ -32577,7 +32732,7 @@ ${repositoryBlock}
32577
32732
  }
32578
32733
  function assertProjectionTargetAncestors(targetPath, targetRoot) {
32579
32734
  const pending = [];
32580
- let current = dirname8(targetPath);
32735
+ let current = dirname9(targetPath);
32581
32736
  while (current !== targetRoot) {
32582
32737
  if (!pathWithin(current, targetRoot)) {
32583
32738
  throw instructionTopologyError(
@@ -32586,15 +32741,15 @@ function assertProjectionTargetAncestors(targetPath, targetRoot) {
32586
32741
  );
32587
32742
  }
32588
32743
  pending.push(current);
32589
- current = dirname8(current);
32744
+ current = dirname9(current);
32590
32745
  }
32591
32746
  pending.push(targetRoot);
32592
32747
  for (const directory of pending.reverse()) {
32593
32748
  if (!existsSync10(directory)) {
32594
- mkdirSync9(directory, { mode: 448 });
32749
+ mkdirSync10(directory, { mode: 448 });
32595
32750
  continue;
32596
32751
  }
32597
- const stat = lstatSync8(directory);
32752
+ const stat = lstatSync9(directory);
32598
32753
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
32599
32754
  throw instructionTopologyError(
32600
32755
  "workspace_project_instruction_projection_unsafe",
@@ -32604,8 +32759,8 @@ function assertProjectionTargetAncestors(targetPath, targetRoot) {
32604
32759
  }
32605
32760
  }
32606
32761
  function projectExternalWorkspaceProjectInstructions(sourceWorkspacePath, executionWorkspacePath, platformInstructions, options = {}) {
32607
- const sourceRoot = resolve8(sourceWorkspacePath);
32608
- const targetRoot = resolve8(executionWorkspacePath);
32762
+ const sourceRoot = resolve9(sourceWorkspacePath);
32763
+ const targetRoot = resolve9(executionWorkspacePath);
32609
32764
  if (sourceRoot === targetRoot || !platformInstructions?.trim()) {
32610
32765
  throw instructionTopologyError(
32611
32766
  "workspace_project_instruction_projection_invalid",
@@ -32621,21 +32776,21 @@ function projectExternalWorkspaceProjectInstructions(sourceWorkspacePath, execut
32621
32776
  }
32622
32777
  const projected = [];
32623
32778
  for (const source of inspection.sources) {
32624
- const sourcePath = resolve8(sourceRoot, source.path);
32779
+ const sourcePath = resolve9(sourceRoot, source.path);
32625
32780
  if (!pathWithin(sourcePath, sourceRoot)) {
32626
32781
  throw instructionTopologyError(
32627
32782
  "workspace_project_instruction_projection_unsafe",
32628
32783
  `project instruction escaped its workspace: ${source.path}`
32629
32784
  );
32630
32785
  }
32631
- const sourceStat = lstatSync8(sourcePath);
32786
+ const sourceStat = lstatSync9(sourcePath);
32632
32787
  if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
32633
32788
  throw instructionTopologyError(
32634
32789
  "workspace_project_instruction_source_unsafe",
32635
32790
  `project instruction source changed during projection: ${source.path}`
32636
32791
  );
32637
32792
  }
32638
- const sourceContent = readFileSync10(sourcePath, "utf8");
32793
+ const sourceContent = readFileSync11(sourcePath, "utf8");
32639
32794
  const sourceSha256 = createHash13("sha256").update(sourceContent, "utf8").digest("hex");
32640
32795
  if (sourceSha256 !== source.sha256) {
32641
32796
  throw instructionTopologyError(
@@ -32662,7 +32817,7 @@ function projectExternalWorkspaceProjectInstructions(sourceWorkspacePath, execut
32662
32817
  let modelFacingBytes = 0;
32663
32818
  let modelFacingSha256 = null;
32664
32819
  if (selectedSources.length > 0) {
32665
- const targetPath = resolve8(targetRoot, "AGENTS.md");
32820
+ const targetPath = resolve9(targetRoot, "AGENTS.md");
32666
32821
  const targetStat = lstatIfPresent2(targetPath);
32667
32822
  if (!pathWithin(targetPath, targetRoot) || targetStat?.isSymbolicLink()) {
32668
32823
  throw instructionTopologyError(
@@ -32674,8 +32829,8 @@ function projectExternalWorkspaceProjectInstructions(sourceWorkspacePath, execut
32674
32829
  assertProjectionTargetAncestors(targetPath, targetRoot);
32675
32830
  const temporaryPath = `${targetPath}.mirrorx-${randomBytes(12).toString("hex")}.tmp`;
32676
32831
  try {
32677
- writeFileSync10(temporaryPath, projectedContent, { encoding: "utf8", flag: "wx", mode: 384 });
32678
- renameSync7(temporaryPath, targetPath);
32832
+ writeFileSync11(temporaryPath, projectedContent, { encoding: "utf8", flag: "wx", mode: 384 });
32833
+ renameSync8(temporaryPath, targetPath);
32679
32834
  } finally {
32680
32835
  rmSync8(temporaryPath, { force: true });
32681
32836
  }
@@ -32748,9 +32903,9 @@ function agentInstructionDeliveryAudit(bundle, delivery) {
32748
32903
  }
32749
32904
 
32750
32905
  // src/amaster-runtime-daemon/config-state.mjs
32751
- import { existsSync as existsSync11, mkdirSync as mkdirSync10, readFileSync as readFileSync11, renameSync as renameSync8, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
32906
+ import { existsSync as existsSync11, mkdirSync as mkdirSync11, readFileSync as readFileSync12, renameSync as renameSync9, rmSync as rmSync9, writeFileSync as writeFileSync12 } from "node:fs";
32752
32907
  import { homedir as homedir3, hostname } from "node:os";
32753
- import { dirname as dirname9, join as join15, parse as parse3, resolve as resolve9 } from "node:path";
32908
+ import { dirname as dirname10, join as join16, parse as parse4, resolve as resolve10 } from "node:path";
32754
32909
 
32755
32910
  // src/amaster-runtime-daemon/capability-registry.mjs
32756
32911
  var BUILD_SUPPORTED_CAPABILITIES = Object.freeze([
@@ -32896,19 +33051,19 @@ function defaultMachineId() {
32896
33051
  }
32897
33052
  function runtimeHome(env) {
32898
33053
  return expandHomePath(String(
32899
- env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME || join15(homedir3(), ".amaster-employee")
33054
+ env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME || join16(homedir3(), ".amaster-employee")
32900
33055
  ));
32901
33056
  }
32902
33057
  function runtimeTemplatesRoot(env, home) {
32903
33058
  const configured = String(env.AMASTER_RUNTIME_TEMPLATES_ROOT ?? "").trim();
32904
- const resolved = configured ? resolve9(expandHomePath(configured)) : resolve9(String(env.PI_CODING_AGENT_DIR ?? "")) === "/data/.pi" ? "/data/templates" : resolve9(join15(home, "templates"));
32905
- if (resolved === parse3(resolved).root) {
33059
+ const resolved = configured ? resolve10(expandHomePath(configured)) : resolve10(String(env.PI_CODING_AGENT_DIR ?? "")) === "/data/.pi" ? "/data/templates" : resolve10(join16(home, "templates"));
33060
+ if (resolved === parse4(resolved).root) {
32906
33061
  throw new Error("AMASTER_RUNTIME_TEMPLATES_ROOT must not be a filesystem root");
32907
33062
  }
32908
33063
  return resolved;
32909
33064
  }
32910
33065
  function stateFilePath(env) {
32911
- return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) : join15(runtimeHome(env), "runtime-connector-state.json");
33066
+ return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) : join16(runtimeHome(env), "runtime-connector-state.json");
32912
33067
  }
32913
33068
  function corruptStatePath(path) {
32914
33069
  const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
@@ -32923,7 +33078,7 @@ function readState(env) {
32923
33078
  const path = stateFilePath(env);
32924
33079
  if (!existsSync11(path)) return {};
32925
33080
  try {
32926
- const state = JSON.parse(readFileSync11(path, "utf8"));
33081
+ const state = JSON.parse(readFileSync12(path, "utf8"));
32927
33082
  if (!state || typeof state !== "object" || Array.isArray(state)) {
32928
33083
  throw new TypeError("runtime connector state must be a JSON object");
32929
33084
  }
@@ -32931,7 +33086,7 @@ function readState(env) {
32931
33086
  } catch {
32932
33087
  const quarantinePath = corruptStatePath(path);
32933
33088
  try {
32934
- renameSync8(path, quarantinePath);
33089
+ renameSync9(path, quarantinePath);
32935
33090
  process.stderr.write(`AMaster runtime state was invalid and quarantined at ${quarantinePath}
32936
33091
  `);
32937
33092
  } catch (error) {
@@ -32945,15 +33100,15 @@ function readState(env) {
32945
33100
  }
32946
33101
  function writeState(env, state) {
32947
33102
  const path = stateFilePath(env);
32948
- mkdirSync10(dirname9(path), { recursive: true });
33103
+ mkdirSync11(dirname10(path), { recursive: true });
32949
33104
  const temporaryPath = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
32950
33105
  try {
32951
- writeFileSync11(temporaryPath, `${JSON.stringify(state, null, 2)}
33106
+ writeFileSync12(temporaryPath, `${JSON.stringify(state, null, 2)}
32952
33107
  `, {
32953
33108
  flag: "wx",
32954
33109
  mode: 384
32955
33110
  });
32956
- renameSync8(temporaryPath, path);
33111
+ renameSync9(temporaryPath, path);
32957
33112
  } finally {
32958
33113
  rmSync9(temporaryPath, { force: true });
32959
33114
  }
@@ -32968,10 +33123,10 @@ function buildConfig(env = process.env, flags = {}) {
32968
33123
  const home = runtimeHome(env);
32969
33124
  const templatesRoot = runtimeTemplatesRoot(env, home);
32970
33125
  const runtimeWorkspacesRoot = expandHomePath(
32971
- String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ?? join15(home, "workspaces"))
33126
+ String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ?? join16(home, "workspaces"))
32972
33127
  );
32973
33128
  const browserSessionStateRoot = expandHomePath(String(
32974
- flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ?? join15(home, "browser-auth")
33129
+ flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ?? join16(home, "browser-auth")
32975
33130
  ));
32976
33131
  const piToolArgumentGuardModeValue = String(
32977
33132
  flags.piToolArgumentGuardMode ?? env.AMASTER_PI_TOOL_ARGUMENT_GUARD_MODE ?? "shadow"
@@ -32997,7 +33152,7 @@ function buildConfig(env = process.env, flags = {}) {
32997
33152
  "Pi tool argument enforce thresholds cannot be more aggressive than 8 MiB transport, 512 KiB materialized, and 16x amplification"
32998
33153
  );
32999
33154
  }
33000
- mkdirSync10(runtimeWorkspacesRoot, { recursive: true });
33155
+ mkdirSync11(runtimeWorkspacesRoot, { recursive: true });
33001
33156
  const workspaceBindings = splitList(
33002
33157
  flags.workspaceAllowlist ?? env.AMASTER_WORKSPACE_ALLOWLIST ?? env.AMASTER_WORKSPACE_BINDINGS ?? runtimeWorkspacesRoot
33003
33158
  ).map(expandHomePath);
@@ -33425,10 +33580,10 @@ function createBrowserCredentialChannel({ consume, onFailure }) {
33425
33580
  }
33426
33581
 
33427
33582
  // src/amaster-runtime-daemon/browser-credential-readiness.mjs
33428
- import { existsSync as existsSync12, lstatSync as lstatSync9, readFileSync as readFileSync12, readdirSync as readdirSync8, statSync as statSync6 } from "node:fs";
33583
+ import { existsSync as existsSync12, lstatSync as lstatSync10, readFileSync as readFileSync13, readdirSync as readdirSync9, statSync as statSync6 } from "node:fs";
33429
33584
  import { createHash as createHash14 } from "node:crypto";
33430
33585
  import { homedir as homedir4 } from "node:os";
33431
- import { dirname as dirname10, isAbsolute as isAbsolute7, join as join16, relative as relative5, resolve as resolve10 } from "node:path";
33586
+ import { dirname as dirname11, isAbsolute as isAbsolute7, join as join17, relative as relative5, resolve as resolve11 } from "node:path";
33432
33587
  var CAPABILITY = "browser_credential_auth_transaction_v1";
33433
33588
  var CREDENTIAL_BROWSER_TCB = Object.freeze({
33434
33589
  package: "chrome-devtools-mcp",
@@ -33440,15 +33595,15 @@ var CREDENTIAL_BROWSER_PACKAGE_FILES = Object.freeze({
33440
33595
  "dist/config.js": "ed61ba70f3c2445db22fac31c432c86df2d9b3674bd36b34cce6f7a981f3926f",
33441
33596
  "dist/index.js": "e94fdec799848fc45942cc59868dfd12dd27597025f757eded3e1d7e3a8e0fb9"
33442
33597
  });
33443
- var CREDENTIAL_AUTH_EXTENSION_SHA256 = "c57dba1e1856bab8e44b55b5725dac2bcee7751522a1b87e0eef0144ad114cd7";
33598
+ var CREDENTIAL_AUTH_EXTENSION_SHA256 = "3ad9c39fc20d35e6486cdccaee832b986108919b678b98134f1386233560277e";
33444
33599
  var CREDENTIAL_BROWSER_PACKAGE_VERSION = "0.1.2-beta.80";
33445
33600
  var IMAGE_PI_HOME = "/opt/pi-cli-runtime/.pi";
33446
- var IMAGE_AUTH_EXTENSION_PATH = join16(IMAGE_PI_HOME, "extensions", "browser-credential-auth.mjs");
33447
- var BROWSER_AUTH_IMAGE_NODE_PATH = join16(IMAGE_PI_HOME, "npm", "node_modules");
33601
+ var IMAGE_AUTH_EXTENSION_PATH = join17(IMAGE_PI_HOME, "extensions", "browser-credential-auth.mjs");
33602
+ var BROWSER_AUTH_IMAGE_NODE_PATH = join17(IMAGE_PI_HOME, "npm", "node_modules");
33448
33603
  var READINESS_CACHE_TTL_MS = 5e3;
33449
33604
  var readinessCache = /* @__PURE__ */ new Map();
33450
33605
  function inspectBrowserCredentialAuthReadiness(env = process.env, expected = {}, options = {}) {
33451
- const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join16(homedir4(), ".pi", "agent")).trim();
33606
+ const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join17(homedir4(), ".pi", "agent")).trim();
33452
33607
  const packageHome = expected.packageHome ?? IMAGE_PI_HOME;
33453
33608
  const extensionPath = expected.authExtensionPath ?? IMAGE_AUTH_EXTENSION_PATH;
33454
33609
  const requireImageOwnership = options.requireImageOwnership !== false;
@@ -33457,8 +33612,8 @@ function inspectBrowserCredentialAuthReadiness(env = process.env, expected = {},
33457
33612
  const cached = readinessCache.get(cacheKey);
33458
33613
  if (!options.fresh && cached && cached.expiresAt > now) return { ...cached.readiness };
33459
33614
  const candidates = [
33460
- join16(packageHome, "npm", "node_modules", "@amaster.ai", "pi-browser-use", "package.json"),
33461
- join16(packageHome, "node_modules", "@amaster.ai", "pi-browser-use", "package.json")
33615
+ join17(packageHome, "npm", "node_modules", "@amaster.ai", "pi-browser-use", "package.json"),
33616
+ join17(packageHome, "node_modules", "@amaster.ai", "pi-browser-use", "package.json")
33462
33617
  ];
33463
33618
  const packageAttestation = candidates.map((manifestPath) => attestedPackageManifest(manifestPath, {
33464
33619
  browserTcb: expected.browserTcb ?? CREDENTIAL_BROWSER_TCB,
@@ -33492,34 +33647,34 @@ function browserCredentialAuthExtensionArgs(authority, env = process.env, expect
33492
33647
  function attestedAuthExtension(extensionPath, expectedSha256, requireImageOwnership) {
33493
33648
  try {
33494
33649
  if (typeof expectedSha256 !== "string" || !/^[a-f0-9]{64}$/u.test(expectedSha256)) return false;
33495
- const extensionStat = lstatSync9(extensionPath);
33650
+ const extensionStat = lstatSync10(extensionPath);
33496
33651
  if (!extensionStat.isFile() || extensionStat.isSymbolicLink()) return false;
33497
33652
  if (requireImageOwnership && !immutableImageFile(extensionPath)) return false;
33498
- const source = readFileSync12(extensionPath, "utf8");
33653
+ const source = readFileSync13(extensionPath, "utf8");
33499
33654
  return createHash14("sha256").update(source, "utf8").digest("hex") === expectedSha256 && source.includes("BrowserCredentialAuthBroker") && source.includes("browser_authenticate") && source.includes("AMASTER_BROWSER_CREDENTIAL_PRIVATE_CHANNEL");
33500
33655
  } catch {
33501
33656
  return false;
33502
33657
  }
33503
33658
  }
33504
33659
  function immutableImageFile(filePath) {
33505
- const fileStat = lstatSync9(filePath);
33660
+ const fileStat = lstatSync10(filePath);
33506
33661
  if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.uid !== 0 || (fileStat.mode & 18) !== 0) return false;
33507
- for (let directory = dirname10(filePath); directory !== dirname10(directory); directory = dirname10(directory)) {
33508
- const parentStat = lstatSync9(directory);
33662
+ for (let directory = dirname11(filePath); directory !== dirname11(directory); directory = dirname11(directory)) {
33663
+ const parentStat = lstatSync10(directory);
33509
33664
  if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || parentStat.uid !== 0 || (parentStat.mode & 18) !== 0) return false;
33510
33665
  }
33511
33666
  return true;
33512
33667
  }
33513
33668
  function fileSha256(path) {
33514
- return createHash14("sha256").update(readFileSync12(path)).digest("hex");
33669
+ return createHash14("sha256").update(readFileSync13(path)).digest("hex");
33515
33670
  }
33516
33671
  function treeAttestation(root, requireImageOwnership) {
33517
33672
  const files = [];
33518
33673
  const visit = (directory) => {
33519
- for (const entry of readdirSync8(directory, { withFileTypes: true })) {
33520
- const path = join16(directory, entry.name);
33674
+ for (const entry of readdirSync9(directory, { withFileTypes: true })) {
33675
+ const path = join17(directory, entry.name);
33521
33676
  if (entry.isDirectory()) visit(path);
33522
- else if (entry.isFile() && !lstatSync9(path).isSymbolicLink() && (!requireImageOwnership || immutableImageFile(path))) files.push(path);
33677
+ else if (entry.isFile() && !lstatSync10(path).isSymbolicLink() && (!requireImageOwnership || immutableImageFile(path))) files.push(path);
33523
33678
  else throw new Error("browser_credential_tcb_tree_invalid");
33524
33679
  }
33525
33680
  };
@@ -33529,14 +33684,14 @@ function treeAttestation(root, requireImageOwnership) {
33529
33684
  for (const path of files) {
33530
33685
  digest2.update(relative5(root, path).replaceAll("\\", "/"));
33531
33686
  digest2.update("\0");
33532
- digest2.update(readFileSync12(path));
33687
+ digest2.update(readFileSync13(path));
33533
33688
  }
33534
33689
  return digest2.digest("hex");
33535
33690
  }
33536
33691
  function attestedPackageManifest(manifestPath, expected, requireImageOwnership) {
33537
33692
  try {
33538
33693
  if (requireImageOwnership && !immutableImageFile(manifestPath)) return null;
33539
- const manifest = JSON.parse(readFileSync12(manifestPath, "utf8"));
33694
+ const manifest = JSON.parse(readFileSync13(manifestPath, "utf8"));
33540
33695
  if (manifest?.name !== "@amaster.ai/pi-browser-use" || manifest.version !== CREDENTIAL_BROWSER_PACKAGE_VERSION) return null;
33541
33696
  if (!Array.isArray(manifest.mirrorxCapabilities) || manifest.mirrorxCapabilities.length !== 1 || manifest.mirrorxCapabilities[0] !== CAPABILITY) {
33542
33697
  return null;
@@ -33544,18 +33699,18 @@ function attestedPackageManifest(manifestPath, expected, requireImageOwnership)
33544
33699
  if (!sameCredentialBrowserTcb(manifest.mirrorxCredentialBrowserTcb, expected.browserTcb)) return null;
33545
33700
  if (manifest.mirrorxCredentialAuthExtensionSha256 !== expected.authExtensionSha256) return null;
33546
33701
  if (typeof manifest.main !== "string" || !manifest.main.trim()) return null;
33547
- const packageDir = resolve10(manifestPath, "..");
33702
+ const packageDir = resolve11(manifestPath, "..");
33548
33703
  if (Object.entries(expected.packageFiles).some(([relativePath, sha2563]) => {
33549
- const path = resolve10(packageDir, relativePath);
33704
+ const path = resolve11(packageDir, relativePath);
33550
33705
  const relativePathFromPackage = relative5(packageDir, path);
33551
33706
  return !relativePathFromPackage || relativePathFromPackage.startsWith("..") || isAbsolute7(relativePathFromPackage) || !statSync6(path).isFile() || requireImageOwnership && !immutableImageFile(path) || fileSha256(path) !== sha2563;
33552
33707
  })) return null;
33553
- const browserPackageDir = resolve10(packageDir, "..", "..", "chrome-devtools-mcp");
33554
- const browserManifestPath = join16(browserPackageDir, "package.json");
33708
+ const browserPackageDir = resolve11(packageDir, "..", "..", "chrome-devtools-mcp");
33709
+ const browserManifestPath = join17(browserPackageDir, "package.json");
33555
33710
  if (requireImageOwnership && !immutableImageFile(browserManifestPath)) return null;
33556
- const browserPackage = JSON.parse(readFileSync12(browserManifestPath, "utf8"));
33557
- if (browserPackage.name !== expected.browserTcb.package || browserPackage.version !== expected.browserTcb.version || treeAttestation(join16(browserPackageDir, "build"), requireImageOwnership) !== expected.browserTcb.buildTreeSha256) return null;
33558
- const entrypoint = resolve10(packageDir, manifest.main);
33711
+ const browserPackage = JSON.parse(readFileSync13(browserManifestPath, "utf8"));
33712
+ if (browserPackage.name !== expected.browserTcb.package || browserPackage.version !== expected.browserTcb.version || treeAttestation(join17(browserPackageDir, "build"), requireImageOwnership) !== expected.browserTcb.buildTreeSha256) return null;
33713
+ const entrypoint = resolve11(packageDir, manifest.main);
33559
33714
  const relativeEntrypoint = relative5(packageDir, entrypoint);
33560
33715
  if (!relativeEntrypoint || relativeEntrypoint.startsWith("..") || isAbsolute7(relativeEntrypoint) || !existsSync12(entrypoint) || requireImageOwnership && !immutableImageFile(entrypoint)) return null;
33561
33716
  return statSync6(entrypoint).isFile() ? {} : null;
@@ -33568,21 +33723,21 @@ function sameCredentialBrowserTcb(value, expected) {
33568
33723
  }
33569
33724
 
33570
33725
  // src/amaster-runtime-daemon/browser-credential-env-readiness.mjs
33571
- import { lstatSync as lstatSync10, readFileSync as readFileSync13 } from "node:fs";
33726
+ import { lstatSync as lstatSync11, readFileSync as readFileSync14 } from "node:fs";
33572
33727
  import { homedir as homedir5 } from "node:os";
33573
- import { join as join17 } from "node:path";
33728
+ import { join as join18 } from "node:path";
33574
33729
  var CACHE_TTL_MS = 5e3;
33575
33730
  var cache = /* @__PURE__ */ new Map();
33576
33731
  function inspectBrowserCredentialEnvReadiness(env = process.env) {
33577
- const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join17(homedir5(), ".pi", "agent")).trim();
33732
+ const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join18(homedir5(), ".pi", "agent")).trim();
33578
33733
  const now = Date.now();
33579
33734
  const cached = cache.get(home);
33580
33735
  if (cached && cached.expiresAt > now) return { ...cached.readiness };
33581
- const extensionPath = join17(home, "extensions", "browser-credential-env.mjs");
33736
+ const extensionPath = join18(home, "extensions", "browser-credential-env.mjs");
33582
33737
  let extension = false;
33583
33738
  try {
33584
- const stat = lstatSync10(extensionPath);
33585
- const source = stat.isFile() && !stat.isSymbolicLink() ? readFileSync13(extensionPath, "utf8") : "";
33739
+ const stat = lstatSync11(extensionPath);
33740
+ const source = stat.isFile() && !stat.isSymbolicLink() ? readFileSync14(extensionPath, "utf8") : "";
33586
33741
  extension = /\bname\s*:\s*["']browser_read_credential["']/u.test(source) && /\bPI_AGENT_BROWSER_CREDENTIAL_ENV_FILE\b/u.test(source);
33587
33742
  } catch {
33588
33743
  extension = false;
@@ -33593,14 +33748,14 @@ function inspectBrowserCredentialEnvReadiness(env = process.env) {
33593
33748
  }
33594
33749
 
33595
33750
  // src/amaster-runtime-daemon/pi-web-search-readiness.mjs
33596
- import { lstatSync as lstatSync11, readFileSync as readFileSync14 } from "node:fs";
33751
+ import { lstatSync as lstatSync12, readFileSync as readFileSync15 } from "node:fs";
33597
33752
  import { homedir as homedir6 } from "node:os";
33598
- import { isAbsolute as isAbsolute8, join as join18 } from "node:path";
33753
+ import { isAbsolute as isAbsolute8, join as join19 } from "node:path";
33599
33754
  function readRegularJson(path) {
33600
33755
  try {
33601
- const stat = lstatSync11(path);
33756
+ const stat = lstatSync12(path);
33602
33757
  if (!stat.isFile() || stat.isSymbolicLink()) return null;
33603
- const value = JSON.parse(readFileSync14(path, "utf8"));
33758
+ const value = JSON.parse(readFileSync15(path, "utf8"));
33604
33759
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
33605
33760
  } catch {
33606
33761
  return null;
@@ -33608,23 +33763,23 @@ function readRegularJson(path) {
33608
33763
  }
33609
33764
  function isRegularFile(path) {
33610
33765
  try {
33611
- const stat = lstatSync11(path);
33766
+ const stat = lstatSync12(path);
33612
33767
  return stat.isFile() && !stat.isSymbolicLink();
33613
33768
  } catch {
33614
33769
  return false;
33615
33770
  }
33616
33771
  }
33617
33772
  function installedPiWebAccess(env) {
33618
- const home = String(env["AMASTER-CLI_CODING_AGENT_DIR"] ?? env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join18(homedir6(), ".pi", "agent")).trim();
33619
- const settings = readRegularJson(join18(home, "settings.json"));
33773
+ const home = String(env["AMASTER-CLI_CODING_AGENT_DIR"] ?? env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join19(homedir6(), ".pi", "agent")).trim();
33774
+ const settings = readRegularJson(join19(home, "settings.json"));
33620
33775
  const packages = Array.isArray(settings?.packages) ? settings.packages : [];
33621
33776
  const npmConfigured = packages.some((entry) => typeof entry === "string" && /^npm:@amaster\.ai\/pi-web-access(?:@|$)/u.test(entry));
33622
33777
  const manifests = [
33623
- join18(home, "npm", "node_modules", "@amaster.ai", "pi-web-access", "package.json"),
33624
- join18(home, "node_modules", "@amaster.ai", "pi-web-access", "package.json")
33778
+ join19(home, "npm", "node_modules", "@amaster.ai", "pi-web-access", "package.json"),
33779
+ join19(home, "node_modules", "@amaster.ai", "pi-web-access", "package.json")
33625
33780
  ];
33626
33781
  const npmInstalled = npmConfigured && manifests.some((path) => readRegularJson(path)?.name === "@amaster.ai/pi-web-access");
33627
- const localInstalled = packages.some((entry) => typeof entry === "string" && isAbsolute8(entry) && readRegularJson(join18(entry, "package.json"))?.name === "@amaster.ai/pi-web-access" && readRegularJson(join18(entry, "package.json"))?.pi?.extensions?.includes("./dist/index.js") && isRegularFile(join18(entry, "dist", "index.js")));
33782
+ const localInstalled = packages.some((entry) => typeof entry === "string" && isAbsolute8(entry) && readRegularJson(join19(entry, "package.json"))?.name === "@amaster.ai/pi-web-access" && readRegularJson(join19(entry, "package.json"))?.pi?.extensions?.includes("./dist/index.js") && isRegularFile(join19(entry, "dist", "index.js")));
33628
33783
  return { settings, installed: npmInstalled || localInstalled };
33629
33784
  }
33630
33785
  function inspectPiWebSearchReadiness(env = process.env) {
@@ -33639,8 +33794,8 @@ function inspectPiWebFetchReadiness(env = process.env) {
33639
33794
  }
33640
33795
 
33641
33796
  // src/amaster-runtime-daemon/browser-credential-env.mjs
33642
- import { chmodSync as chmodSync6, mkdtempSync as mkdtempSync3, renameSync as renameSync9, rmSync as rmSync10, writeFileSync as writeFileSync12 } from "node:fs";
33643
- import { join as join19, resolve as resolve11 } from "node:path";
33797
+ import { chmodSync as chmodSync7, mkdtempSync as mkdtempSync3, renameSync as renameSync10, rmSync as rmSync10, writeFileSync as writeFileSync13 } from "node:fs";
33798
+ import { join as join20, resolve as resolve12 } from "node:path";
33644
33799
  var BROWSER_CREDENTIAL_ENV_CAPABILITY = "browser_credential_env_read_v1";
33645
33800
  var BROWSER_CREDENTIAL_PRIVATE_CAPABILITY = "browser_credential_auth_transaction_v1";
33646
33801
  var BROWSER_CREDENTIAL_ENV_FILE = "PI_AGENT_BROWSER_CREDENTIAL_ENV_FILE";
@@ -33656,7 +33811,7 @@ function exactOrigin2(value) {
33656
33811
  return null;
33657
33812
  }
33658
33813
  }
33659
- function fail2(code) {
33814
+ function fail3(code) {
33660
33815
  const error = new Error(code);
33661
33816
  error.code = code;
33662
33817
  throw error;
@@ -33667,10 +33822,10 @@ function browserCredentialPresentation(command) {
33667
33822
  const capabilities = new Set(Array.isArray(command?.requiredCapabilities) ? command.requiredCapabilities : []);
33668
33823
  const envRequested = capabilities.has(BROWSER_CREDENTIAL_ENV_CAPABILITY);
33669
33824
  const privateRequested = capabilities.has(BROWSER_CREDENTIAL_PRIVATE_CAPABILITY);
33670
- if (envRequested && privateRequested) fail2("browser_credential_capability_conflict");
33825
+ if (envRequested && privateRequested) fail3("browser_credential_capability_conflict");
33671
33826
  if (envRequested) return "model_visible_env";
33672
33827
  if (privateRequested) return "private_channel";
33673
- fail2("browser_credential_capability_required");
33828
+ fail3("browser_credential_capability_required");
33674
33829
  }
33675
33830
  function browserCredentialEnvPlan(command, presentation = browserCredentialPresentation(command)) {
33676
33831
  if (presentation !== "model_visible_env") return null;
@@ -33678,11 +33833,11 @@ function browserCredentialEnvPlan(command, presentation = browserCredentialPrese
33678
33833
  const passwordRefs = refs.filter((ref2) => ref2?.credentialRole === "password");
33679
33834
  const usernameRefs = refs.filter((ref2) => ref2?.credentialRole === "username");
33680
33835
  if (passwordRefs.length !== 1 || usernameRefs.length > 1 || passwordRefs.length + usernameRefs.length !== refs.length) {
33681
- fail2("browser_credential_env_ref_set_invalid");
33836
+ fail3("browser_credential_env_ref_set_invalid");
33682
33837
  }
33683
33838
  const origin = exactOrigin2(passwordRefs[0]?.authenticationOrigin);
33684
33839
  if (!origin || refs.some((ref2) => ref2?.commandId !== command?.commandId || ref2?.authenticationOrigin !== origin || ref2?.targetOrigin !== origin)) {
33685
- fail2("browser_credential_env_origin_mismatch");
33840
+ fail3("browser_credential_env_origin_mismatch");
33686
33841
  }
33687
33842
  const entries = [
33688
33843
  ...usernameRefs.map((ref2) => ({ ref: ref2, key: BROWSER_CREDENTIAL_USERNAME_KEY, controlSemantic: "username" })),
@@ -33711,13 +33866,13 @@ function browserCredentialPrivateAuthority(command, presentation = browserCreden
33711
33866
  try {
33712
33867
  parsedTarget = new URL(targetUrl);
33713
33868
  } catch {
33714
- fail2("browser_credential_authority_invalid");
33869
+ fail3("browser_credential_authority_invalid");
33715
33870
  }
33716
33871
  const origin = parsedTarget.protocol === "https:" && !parsedTarget.username && !parsedTarget.password ? parsedTarget.origin : null;
33717
33872
  const passwordRefs = refs.filter((ref2) => ref2?.credentialRole === "password");
33718
33873
  const usernameRefs = refs.filter((ref2) => ref2?.credentialRole === "username");
33719
33874
  if (!origin || refs.length < 1 || refs.length > 2 || passwordRefs.length !== 1 || usernameRefs.length > 1 || !predicate || predicate.version !== 1 || predicate.type !== "snapshot_text_v1" || typeof predicate.requiredText !== "string" || predicate.requiredText !== predicate.requiredText.trim() || predicate.requiredText.length < 8 || predicate.requiredText.length > 256 || /[\u0000-\u001f\u007f]/u.test(predicate.requiredText) || refs.some((ref2) => ref2?.commandId !== command?.commandId || ref2?.bindingId !== session?.bindingId || ref2?.browserLeaseId !== session?.browserLeaseId || ref2?.targetOrigin !== origin || ref2?.authenticationOrigin !== origin)) {
33720
- fail2("browser_credential_authority_invalid");
33875
+ fail3("browser_credential_authority_invalid");
33721
33876
  }
33722
33877
  return Object.freeze({
33723
33878
  version: 1,
@@ -33730,13 +33885,13 @@ function attachTrustedBrowserExecutorEnv(env, { authority = null, userDataDir =
33730
33885
  const result2 = { ...env };
33731
33886
  delete result2[BROWSER_CREDENTIAL_AUTHORITY_ENV];
33732
33887
  delete result2[BROWSER_SESSION_USER_DATA_DIR_ENV];
33733
- if (authority && !userDataDir) fail2("browser_credential_authority_profile_required");
33888
+ if (authority && !userDataDir) fail3("browser_credential_authority_profile_required");
33734
33889
  if (userDataDir) result2[BROWSER_SESSION_USER_DATA_DIR_ENV] = userDataDir;
33735
33890
  if (authority) result2[BROWSER_CREDENTIAL_AUTHORITY_ENV] = JSON.stringify(authority);
33736
33891
  return result2;
33737
33892
  }
33738
33893
  function dotenvQuotedValue(value) {
33739
- if (value.includes("\0")) fail2("browser_credential_env_value_invalid");
33894
+ if (value.includes("\0")) fail3("browser_credential_env_value_invalid");
33740
33895
  return `"${value.replace(/[\\"\n\r\t$`]/gu, (char) => ({
33741
33896
  "\\": "\\\\",
33742
33897
  '"': '\\"',
@@ -33748,14 +33903,14 @@ function dotenvQuotedValue(value) {
33748
33903
  })[char])}"`;
33749
33904
  }
33750
33905
  async function materializeBrowserCredentialEnv(plan, options) {
33751
- if (!plan || typeof options?.consume !== "function") fail2("browser_credential_env_plan_required");
33906
+ if (!plan || typeof options?.consume !== "function") fail3("browser_credential_env_plan_required");
33752
33907
  const rawRunDir = String(options.runDir ?? "").trim();
33753
- if (!rawRunDir) fail2("browser_credential_env_run_dir_invalid");
33754
- const runDir = resolve11(rawRunDir);
33755
- const credentialDir = mkdtempSync3(join19(runDir, ".browser-credentials-"));
33756
- chmodSync6(credentialDir, 448);
33757
- const targetPath = join19(credentialDir, "credentials.env");
33758
- const temporaryPath = join19(credentialDir, ".credentials.env.tmp");
33908
+ if (!rawRunDir) fail3("browser_credential_env_run_dir_invalid");
33909
+ const runDir = resolve12(rawRunDir);
33910
+ const credentialDir = mkdtempSync3(join20(runDir, ".browser-credentials-"));
33911
+ chmodSync7(credentialDir, 448);
33912
+ const targetPath = join20(credentialDir, "credentials.env");
33913
+ const temporaryPath = join20(credentialDir, ".credentials.env.tmp");
33759
33914
  const buffers = [];
33760
33915
  const protectedValues = [];
33761
33916
  try {
@@ -33764,15 +33919,15 @@ async function materializeBrowserCredentialEnv(plan, options) {
33764
33919
  const consumed = await options.consume(entry.ref, entry.controlSemantic);
33765
33920
  const valueBuffer = Buffer.isBuffer(consumed) ? consumed : Buffer.from(String(consumed), "utf8");
33766
33921
  buffers.push(valueBuffer);
33767
- if (valueBuffer.length === 0 || valueBuffer.length > 16 * 1024) fail2("browser_credential_env_value_invalid");
33922
+ if (valueBuffer.length === 0 || valueBuffer.length > 16 * 1024) fail3("browser_credential_env_value_invalid");
33768
33923
  const value = valueBuffer.toString("utf8");
33769
33924
  if (!protectedValues.includes(value)) protectedValues.push(value);
33770
33925
  lines.push(`${entry.key}=${dotenvQuotedValue(value)}`);
33771
33926
  }
33772
- writeFileSync12(temporaryPath, `${lines.join("\n")}
33927
+ writeFileSync13(temporaryPath, `${lines.join("\n")}
33773
33928
  `, { encoding: "utf8", mode: 384, flag: "wx" });
33774
- renameSync9(temporaryPath, targetPath);
33775
- chmodSync6(targetPath, 384);
33929
+ renameSync10(temporaryPath, targetPath);
33930
+ chmodSync7(targetPath, 384);
33776
33931
  return {
33777
33932
  dirPath: credentialDir,
33778
33933
  filePath: targetPath,
@@ -33791,8 +33946,8 @@ async function materializeBrowserCredentialEnv(plan, options) {
33791
33946
 
33792
33947
  // src/amaster-runtime-daemon/runtime-artifact-upload.mjs
33793
33948
  import { createHash as createHash15 } from "node:crypto";
33794
- import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync4, lstatSync as lstatSync12, openSync as openSync4, readFileSync as readFileSync15, realpathSync as realpathSync10 } from "node:fs";
33795
- import { isAbsolute as isAbsolute9, relative as relative6, resolve as resolve12 } from "node:path";
33949
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync4, lstatSync as lstatSync13, openSync as openSync4, readFileSync as readFileSync16, realpathSync as realpathSync10 } from "node:fs";
33950
+ import { isAbsolute as isAbsolute9, relative as relative6, resolve as resolve13 } from "node:path";
33796
33951
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
33797
33952
  function requiredString2(value, name) {
33798
33953
  if (typeof value !== "string" || !value.trim()) throw new Error(`Runtime Artifact ${name} is required`);
@@ -33811,10 +33966,10 @@ function sameFileSnapshot(left, right) {
33811
33966
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
33812
33967
  }
33813
33968
  function readOwnedWorkspaceFile(rootPath, sourceRelativePath, label = "Runtime workspace file", options = {}) {
33814
- const root = realpathSync10(resolve12(rootPath));
33969
+ const root = realpathSync10(resolve13(rootPath));
33815
33970
  const relativePath = ownedRelativePath(sourceRelativePath);
33816
- const sourcePath = resolve12(root, relativePath);
33817
- const pathStat = lstatSync12(sourcePath);
33971
+ const sourcePath = resolve13(root, relativePath);
33972
+ const pathStat = lstatSync13(sourcePath);
33818
33973
  if (!pathStat.isFile() || pathStat.isSymbolicLink() || !pathWithin2(realpathSync10(sourcePath), root)) {
33819
33974
  throw new Error(`${label} source is not an owned regular file`);
33820
33975
  }
@@ -33843,10 +33998,10 @@ function readOwnedWorkspaceFile(rootPath, sourceRelativePath, label = "Runtime w
33843
33998
  );
33844
33999
  }
33845
34000
  }
33846
- const body = readFileSync15(descriptor);
34001
+ const body = readFileSync16(descriptor);
33847
34002
  options.afterRead?.({ sourcePath, descriptor });
33848
34003
  const after = fstatSync4(descriptor);
33849
- const pathAfter = lstatSync12(sourcePath);
34004
+ const pathAfter = lstatSync13(sourcePath);
33850
34005
  if (!sameFileSnapshot(before, after) || !sameFileSnapshot(pathAfter, after) || !pathAfter.isFile() || pathAfter.isSymbolicLink() || !pathWithin2(realpathSync10(sourcePath), root) || body.length !== after.size) {
33851
34006
  throw new Error(`${label} source changed during the governed read`);
33852
34007
  }
@@ -34170,8 +34325,8 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
34170
34325
 
34171
34326
  // src/amaster-runtime-daemon/workspace-guard.mjs
34172
34327
  import { createHash as createHash17 } from "node:crypto";
34173
- import { existsSync as existsSync13, mkdirSync as mkdirSync11, realpathSync as realpathSync11, statSync as statSync7 } from "node:fs";
34174
- import { basename as basename6, join as join20, isAbsolute as isAbsolute10, relative as relative7, resolve as resolve13 } from "node:path";
34328
+ import { existsSync as existsSync13, mkdirSync as mkdirSync12, realpathSync as realpathSync11, statSync as statSync7 } from "node:fs";
34329
+ import { basename as basename6, join as join21, isAbsolute as isAbsolute10, relative as relative7, resolve as resolve14 } from "node:path";
34175
34330
  function pathWithin3(candidate, root) {
34176
34331
  const rel = relative7(root, candidate);
34177
34332
  return rel === "" || !rel.startsWith("..") && !isAbsolute10(rel);
@@ -34180,10 +34335,10 @@ function resolveWorkspaceCwd(config, command) {
34180
34335
  const payload = asRecord(command.payload);
34181
34336
  const requested = readString(payload.workspacePath);
34182
34337
  const fallback = config.workspaceBindings[0] ?? process.cwd();
34183
- const cwd = realpathSync11(resolve13(expandHomePath(requested ?? fallback)));
34338
+ const cwd = realpathSync11(resolve14(expandHomePath(requested ?? fallback)));
34184
34339
  const allowlist = config.workspaceBindings.flatMap((entry) => {
34185
34340
  try {
34186
- return [realpathSync11(resolve13(expandHomePath(entry)))];
34341
+ return [realpathSync11(resolve14(expandHomePath(entry)))];
34187
34342
  } catch {
34188
34343
  return [];
34189
34344
  }
@@ -34226,8 +34381,8 @@ function workspaceLabel(sourceWorkspacePath, payload) {
34226
34381
  return readString(payload.workspaceName) ?? readString(payload.projectName) ?? readString(context.projectName) ?? basename6(sourceWorkspacePath) ?? "workspace";
34227
34382
  }
34228
34383
  function workspacesRoot(config) {
34229
- const root = resolve13(expandHomePath(config.runtimeWorkspacesRoot ?? "~/.amaster-employee/workspaces"));
34230
- mkdirSync11(root, { recursive: true });
34384
+ const root = resolve14(expandHomePath(config.runtimeWorkspacesRoot ?? "~/.amaster-employee/workspaces"));
34385
+ mkdirSync12(root, { recursive: true });
34231
34386
  return realpathSync11(root);
34232
34387
  }
34233
34388
  function resolveExecutionWorkspace(config, command, opts = {}) {
@@ -34240,11 +34395,11 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
34240
34395
  const workspaceKey = `${safeSegment(workspaceLabel(sourceWorkspacePath, payload), "workspace")}-${shortHash(sourceWorkspacePath)}`;
34241
34396
  const issueKey = `${safeSegment(issueLabel(command, payload), "issue")}-${shortHash(issueId, 8)}`;
34242
34397
  const runKey = `${safeSegment(runId, "run")}-${shortHash(runId, 8)}`;
34243
- const runDir = join20(root, workspaceKey, issueKey, runKey);
34244
- const cwd = join20(runDir, "workdir");
34245
- const executorHome = join20(runDir, "executors", safeSegment(executorKind, "executor"));
34246
- mkdirSync11(cwd, { recursive: true });
34247
- mkdirSync11(executorHome, { recursive: true });
34398
+ const runDir = join21(root, workspaceKey, issueKey, runKey);
34399
+ const cwd = join21(runDir, "workdir");
34400
+ const executorHome = join21(runDir, "executors", safeSegment(executorKind, "executor"));
34401
+ mkdirSync12(cwd, { recursive: true });
34402
+ mkdirSync12(executorHome, { recursive: true });
34248
34403
  const workspace = {
34249
34404
  managed: true,
34250
34405
  cwd,
@@ -34266,8 +34421,8 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
34266
34421
  }
34267
34422
 
34268
34423
  // src/amaster-runtime-daemon/workspace-gc.mjs
34269
- import { existsSync as existsSync14, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
34270
- import { join as join21, resolve as resolve14 } from "node:path";
34424
+ import { existsSync as existsSync14, readdirSync as readdirSync10, statSync as statSync8 } from "node:fs";
34425
+ import { join as join22, resolve as resolve15 } from "node:path";
34271
34426
  function readIsoTime(value) {
34272
34427
  if (typeof value !== "string" || !value.trim()) return null;
34273
34428
  const time2 = new Date(value).getTime();
@@ -34284,13 +34439,13 @@ function walkWorkdirs(root) {
34284
34439
  if (!current) continue;
34285
34440
  let entries = [];
34286
34441
  try {
34287
- entries = readdirSync9(current, { withFileTypes: true });
34442
+ entries = readdirSync10(current, { withFileTypes: true });
34288
34443
  } catch {
34289
34444
  continue;
34290
34445
  }
34291
34446
  for (const entry of entries) {
34292
34447
  if (!entry.isDirectory()) continue;
34293
- const fullPath = join21(current, entry.name);
34448
+ const fullPath = join22(current, entry.name);
34294
34449
  if (entry.name === "workdir" && existsSync14(workspaceManifestPath(fullPath))) {
34295
34450
  workdirs.push(fullPath);
34296
34451
  continue;
@@ -34317,12 +34472,12 @@ function directorySizeBytes(path) {
34317
34472
  if (stat.isDirectory()) {
34318
34473
  let entries = [];
34319
34474
  try {
34320
- entries = readdirSync9(current, { withFileTypes: true });
34475
+ entries = readdirSync10(current, { withFileTypes: true });
34321
34476
  } catch {
34322
34477
  continue;
34323
34478
  }
34324
34479
  for (const entry of entries) {
34325
- stack.push(join21(current, entry.name));
34480
+ stack.push(join22(current, entry.name));
34326
34481
  }
34327
34482
  continue;
34328
34483
  }
@@ -34349,7 +34504,7 @@ function summarizeWorkdir(path, manifest, nowMs) {
34349
34504
  };
34350
34505
  }
34351
34506
  function planManagedWorkspaceGcDryRun(input) {
34352
- const root = resolve14(String(input.root ?? ""));
34507
+ const root = resolve15(String(input.root ?? ""));
34353
34508
  const now = input.now instanceof Date ? input.now : /* @__PURE__ */ new Date();
34354
34509
  const nowMs = now.getTime();
34355
34510
  const ttlHours = Math.max(1, Number(input.ttlHours ?? 72));
@@ -34397,21 +34552,21 @@ function planManagedWorkspaceGcDryRun(input) {
34397
34552
  import { createHash as createHash18 } from "node:crypto";
34398
34553
  import {
34399
34554
  accessSync,
34400
- chmodSync as chmodSync7,
34555
+ chmodSync as chmodSync8,
34401
34556
  constants as constants4,
34402
34557
  existsSync as existsSync15,
34403
- lstatSync as lstatSync13,
34404
- mkdirSync as mkdirSync12,
34558
+ lstatSync as lstatSync14,
34559
+ mkdirSync as mkdirSync13,
34405
34560
  mkdtempSync as mkdtempSync4,
34406
- readFileSync as readFileSync16,
34407
- readdirSync as readdirSync10,
34408
- renameSync as renameSync10,
34561
+ readFileSync as readFileSync17,
34562
+ readdirSync as readdirSync11,
34563
+ renameSync as renameSync11,
34409
34564
  rmSync as rmSync11,
34410
34565
  statSync as statSync9,
34411
- unlinkSync as unlinkSync2,
34412
- writeFileSync as writeFileSync13
34566
+ unlinkSync as unlinkSync3,
34567
+ writeFileSync as writeFileSync14
34413
34568
  } from "node:fs";
34414
- import { dirname as dirname11, extname, isAbsolute as isAbsolute11, join as join22, parse as parse4, resolve as resolve15, sep as sep4 } from "node:path";
34569
+ import { dirname as dirname12, extname, isAbsolute as isAbsolute11, join as join23, parse as parse5, resolve as resolve16, sep as sep4 } from "node:path";
34415
34570
  import { fileURLToPath } from "node:url";
34416
34571
  var PRESET_TEMPLATE_MANIFEST_FILE = ".mirrorx-preset-templates.json";
34417
34572
  var MAX_PRESET_TEMPLATE_FILES = 256;
@@ -34422,7 +34577,7 @@ function sha2562(value) {
34422
34577
  }
34423
34578
  function lstatIfExists(path) {
34424
34579
  try {
34425
- return lstatSync13(path);
34580
+ return lstatSync14(path);
34426
34581
  } catch (error) {
34427
34582
  if (error?.code === "ENOENT") return null;
34428
34583
  throw error;
@@ -34437,7 +34592,7 @@ function modeAllows(stat, identity, ownerBit, groupBit, otherBit) {
34437
34592
  function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
34438
34593
  if (!identity) {
34439
34594
  accessSync(targetDir, constants4.R_OK | constants4.X_OK);
34440
- for (const name of fileNames) accessSync(join22(targetDir, name), constants4.R_OK);
34595
+ for (const name of fileNames) accessSync(join23(targetDir, name), constants4.R_OK);
34441
34596
  return;
34442
34597
  }
34443
34598
  let current = targetDir;
@@ -34446,7 +34601,7 @@ function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
34446
34601
  if (!stat.isDirectory() || !modeAllows(stat, identity, 64, 8, 1)) {
34447
34602
  throw new Error(`preset_template_executor_path_unreadable: ${current}`);
34448
34603
  }
34449
- const parent = dirname11(current);
34604
+ const parent = dirname12(current);
34450
34605
  if (parent === current) break;
34451
34606
  current = parent;
34452
34607
  }
@@ -34455,7 +34610,7 @@ function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
34455
34610
  throw new Error(`preset_template_executor_catalog_unreadable: ${targetDir}`);
34456
34611
  }
34457
34612
  for (const name of fileNames) {
34458
- const path = join22(targetDir, name);
34613
+ const path = join23(targetDir, name);
34459
34614
  const stat = statSync9(path);
34460
34615
  if (!stat.isFile() || !modeAllows(stat, identity, 256, 32, 4)) {
34461
34616
  throw new Error(`preset_template_executor_file_unreadable: ${name}`);
@@ -34467,11 +34622,11 @@ function hasAllowedTemplateExtension(name) {
34467
34622
  return ALLOWED_TEMPLATE_EXTENSIONS.has(extname(name).toLowerCase());
34468
34623
  }
34469
34624
  function validTemplateName(value) {
34470
- return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !value.includes("\0") && !value.includes("/") && !value.includes("\\") && !isAbsolute11(value) && parse4(value).base === value && hasAllowedTemplateExtension(value);
34625
+ return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !value.includes("\0") && !value.includes("/") && !value.includes("\\") && !isAbsolute11(value) && parse5(value).base === value && hasAllowedTemplateExtension(value);
34471
34626
  }
34472
34627
  function readManifest(manifestPath, { strict }) {
34473
34628
  try {
34474
- const parsed = JSON.parse(readFileSync16(manifestPath, "utf8"));
34629
+ const parsed = JSON.parse(readFileSync17(manifestPath, "utf8"));
34475
34630
  if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.files)) {
34476
34631
  throw new Error("preset_template_bundle_manifest_invalid");
34477
34632
  }
@@ -34499,12 +34654,12 @@ function readManifest(manifestPath, { strict }) {
34499
34654
  }
34500
34655
  function verifiedBundleFiles(sourceDir, manifest) {
34501
34656
  return manifest.files.map((entry) => {
34502
- const sourcePath = join22(sourceDir, entry.name);
34503
- const stat = lstatSync13(sourcePath);
34657
+ const sourcePath = join23(sourceDir, entry.name);
34658
+ const stat = lstatSync14(sourcePath);
34504
34659
  if (!stat.isFile() || stat.isSymbolicLink()) {
34505
34660
  throw new Error(`preset_template_bundle_file_unsafe: ${entry.name}`);
34506
34661
  }
34507
- const body = readFileSync16(sourcePath);
34662
+ const body = readFileSync17(sourcePath);
34508
34663
  if (body.byteLength !== entry.bytes || sha2562(body) !== entry.sha256) {
34509
34664
  throw new Error(`preset_template_bundle_digest_mismatch: ${entry.name}`);
34510
34665
  }
@@ -34514,51 +34669,51 @@ function verifiedBundleFiles(sourceDir, manifest) {
34514
34669
  function removeRetiredPresetFiles(targetDir, previousManifest, nextNames) {
34515
34670
  for (const entry of previousManifest.files) {
34516
34671
  if (nextNames.has(entry.name)) continue;
34517
- const targetPath = join22(targetDir, entry.name);
34672
+ const targetPath = join23(targetDir, entry.name);
34518
34673
  if (!existsSync15(targetPath)) continue;
34519
- const stat = lstatSync13(targetPath);
34674
+ const stat = lstatSync14(targetPath);
34520
34675
  if (stat.isDirectory()) {
34521
34676
  throw new Error(`preset_template_target_conflict: ${entry.name}`);
34522
34677
  }
34523
- unlinkSync2(targetPath);
34678
+ unlinkSync3(targetPath);
34524
34679
  }
34525
34680
  }
34526
34681
  function materializeBundledPresetTemplates(input) {
34527
- const sourceDir = resolve15(input.sourceDir);
34528
- const targetDir = resolve15(input.targetDir);
34682
+ const sourceDir = resolve16(input.sourceDir);
34683
+ const targetDir = resolve16(input.targetDir);
34529
34684
  if (sourceDir === targetDir || sourceDir.startsWith(`${targetDir}${sep4}`) || targetDir.startsWith(`${sourceDir}${sep4}`)) {
34530
34685
  throw new Error("preset_template_source_target_overlap");
34531
34686
  }
34532
- const manifest = readManifest(join22(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
34687
+ const manifest = readManifest(join23(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
34533
34688
  const verifiedFiles = verifiedBundleFiles(sourceDir, manifest);
34534
- mkdirSync12(dirname11(targetDir), { recursive: true, mode: 493 });
34689
+ mkdirSync13(dirname12(targetDir), { recursive: true, mode: 493 });
34535
34690
  const targetStat = lstatIfExists(targetDir);
34536
34691
  if (targetStat && (!targetStat.isDirectory() || targetStat.isSymbolicLink())) {
34537
34692
  throw new Error("preset_template_target_root_unsafe");
34538
34693
  }
34539
- mkdirSync12(targetDir, { recursive: true, mode: 493 });
34540
- const previousManifest = readManifest(join22(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
34541
- const stageDir = mkdtempSync4(join22(dirname11(targetDir), ".mirrorx-preset-templates-"));
34694
+ mkdirSync13(targetDir, { recursive: true, mode: 493 });
34695
+ const previousManifest = readManifest(join23(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
34696
+ const stageDir = mkdtempSync4(join23(dirname12(targetDir), ".mirrorx-preset-templates-"));
34542
34697
  try {
34543
34698
  for (const file of verifiedFiles) {
34544
- const stagedPath = join22(stageDir, file.name);
34545
- writeFileSync13(stagedPath, file.body, { mode: 292 });
34546
- chmodSync7(stagedPath, 292);
34547
- renameSync10(stagedPath, join22(targetDir, file.name));
34699
+ const stagedPath = join23(stageDir, file.name);
34700
+ writeFileSync14(stagedPath, file.body, { mode: 292 });
34701
+ chmodSync8(stagedPath, 292);
34702
+ renameSync11(stagedPath, join23(targetDir, file.name));
34548
34703
  }
34549
34704
  removeRetiredPresetFiles(targetDir, previousManifest, new Set(manifest.files.map((file) => file.name)));
34550
- const stagedManifest = join22(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
34551
- writeFileSync13(stagedManifest, `${JSON.stringify({
34705
+ const stagedManifest = join23(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
34706
+ writeFileSync14(stagedManifest, `${JSON.stringify({
34552
34707
  schemaVersion: manifest.schemaVersion,
34553
34708
  files: manifest.files
34554
34709
  }, null, 2)}
34555
34710
  `, { mode: 292 });
34556
- chmodSync7(stagedManifest, 292);
34557
- renameSync10(stagedManifest, join22(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
34711
+ chmodSync8(stagedManifest, 292);
34712
+ renameSync11(stagedManifest, join23(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
34558
34713
  } finally {
34559
34714
  rmSync11(stageDir, { recursive: true, force: true });
34560
34715
  }
34561
- chmodSync7(targetDir, 493);
34716
+ chmodSync8(targetDir, 493);
34562
34717
  return {
34563
34718
  fileCount: manifest.files.length,
34564
34719
  totalBytes: manifest.totalBytes,
@@ -34571,12 +34726,12 @@ function materializeRuntimePresetTemplates(input) {
34571
34726
  sourceDir,
34572
34727
  targetDir: input.targetDir
34573
34728
  });
34574
- const manifestBody = readFileSync16(
34575
- join22(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
34729
+ const manifestBody = readFileSync17(
34730
+ join23(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
34576
34731
  );
34577
34732
  const manifest = JSON.parse(manifestBody.toString("utf8"));
34578
34733
  for (const file of manifest.files) {
34579
- const body = readFileSync16(join22(materialized.targetDir, file.name));
34734
+ const body = readFileSync17(join23(materialized.targetDir, file.name));
34580
34735
  if (sha2562(body) !== file.sha256) {
34581
34736
  throw new Error(`preset_template_materialized_digest_mismatch: ${file.name}`);
34582
34737
  }
@@ -34599,11 +34754,11 @@ function materializeRuntimePresetTemplates(input) {
34599
34754
  }
34600
34755
 
34601
34756
  // src/amaster-runtime-daemon/runtime-status-summary.mjs
34602
- import { existsSync as existsSync16, readdirSync as readdirSync11, statSync as statSync10 } from "node:fs";
34603
- import { dirname as dirname12, join as join23, resolve as resolve16 } from "node:path";
34757
+ import { existsSync as existsSync16, readdirSync as readdirSync12, statSync as statSync10 } from "node:fs";
34758
+ import { dirname as dirname13, join as join24, resolve as resolve17 } from "node:path";
34604
34759
  function runtimeStatusDirectoryEntries(path) {
34605
34760
  try {
34606
- return readdirSync11(path, { withFileTypes: true });
34761
+ return readdirSync12(path, { withFileTypes: true });
34607
34762
  } catch {
34608
34763
  return [];
34609
34764
  }
@@ -34623,7 +34778,7 @@ function runtimeStatusDirectorySizeBytes(path) {
34623
34778
  if (!stat || stat.isSymbolicLink()) continue;
34624
34779
  if (stat.isDirectory()) {
34625
34780
  for (const entry of runtimeStatusDirectoryEntries(current)) {
34626
- stack.push(join23(current, entry.name));
34781
+ stack.push(join24(current, entry.name));
34627
34782
  }
34628
34783
  continue;
34629
34784
  }
@@ -34640,7 +34795,7 @@ function walkRuntimeStatusManagedWorkdirs(root) {
34640
34795
  if (!current) continue;
34641
34796
  for (const entry of runtimeStatusDirectoryEntries(current)) {
34642
34797
  if (!entry.isDirectory()) continue;
34643
- const fullPath = join23(current, entry.name);
34798
+ const fullPath = join24(current, entry.name);
34644
34799
  if (entry.name === "workdir" && existsSync16(workspaceManifestPath(fullPath))) {
34645
34800
  workdirs.push(fullPath);
34646
34801
  continue;
@@ -34682,15 +34837,15 @@ function summarizeRuntimeStatusRecentRun(workdir, manifest) {
34682
34837
  }
34683
34838
  function runtimeStatusOutboxDir(config) {
34684
34839
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
34685
- return join23(dirname12(stateFilePath({
34840
+ return join24(dirname13(stateFilePath({
34686
34841
  AMASTER_DAEMON_STATE_FILE: statePath
34687
34842
  })), "result-outbox");
34688
34843
  }
34689
34844
  function runtimeStatusRunCompletionDir(config) {
34690
34845
  const explicit = config.AMASTER_RUN_COMPLETION_STATE_DIR ?? config.runCompletionStateDir;
34691
- if (typeof explicit === "string" && explicit.trim()) return resolve16(explicit);
34846
+ if (typeof explicit === "string" && explicit.trim()) return resolve17(explicit);
34692
34847
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
34693
- return join23(dirname12(stateFilePath({
34848
+ return join24(dirname13(stateFilePath({
34694
34849
  AMASTER_DAEMON_STATE_FILE: statePath
34695
34850
  })), "run-completion-state");
34696
34851
  }
@@ -34700,7 +34855,7 @@ function countRuntimeStatusJsonEntries(dir) {
34700
34855
  }
34701
34856
  function summarizeRuntimeLocalState(input) {
34702
34857
  const config = input.config ?? {};
34703
- const root = resolve16(String(config.AMASTER_RUNTIME_WORKSPACES_ROOT ?? config.runtimeWorkspacesRoot ?? input.runtimeWorkspacesRoot ?? ""));
34858
+ const root = resolve17(String(config.AMASTER_RUNTIME_WORKSPACES_ROOT ?? config.runtimeWorkspacesRoot ?? input.runtimeWorkspacesRoot ?? ""));
34704
34859
  const now = input.now instanceof Date ? input.now : /* @__PURE__ */ new Date();
34705
34860
  const workdirs = walkRuntimeStatusManagedWorkdirs(root);
34706
34861
  let managedWorkdirBytes = 0;
@@ -34727,9 +34882,9 @@ function summarizeRuntimeLocalState(input) {
34727
34882
  }
34728
34883
  }
34729
34884
  const pendingOutboxDir = runtimeStatusOutboxDir(config);
34730
- const invalidOutboxDir = join23(pendingOutboxDir, "invalid");
34885
+ const invalidOutboxDir = join24(pendingOutboxDir, "invalid");
34731
34886
  const pendingRunCompletionDir = runtimeStatusRunCompletionDir(config);
34732
- const invalidRunCompletionDir = join23(pendingRunCompletionDir, "invalid");
34887
+ const invalidRunCompletionDir = join24(pendingRunCompletionDir, "invalid");
34733
34888
  return {
34734
34889
  managedWorkspacesRoot: root,
34735
34890
  managedWorkdirCount: workdirs.length,
@@ -34851,7 +35006,7 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
34851
35006
  }
34852
35007
 
34853
35008
  // src/amaster-runtime-daemon/pi-context-budget.mjs
34854
- import { readFileSync as readFileSync17 } from "node:fs";
35009
+ import { readFileSync as readFileSync18 } from "node:fs";
34855
35010
  var CONTEXT_ERROR_CODES = /* @__PURE__ */ new Set([
34856
35011
  "context_effective_tool_schema_attestation_mismatch",
34857
35012
  "context_output_reserve_exceeds_model_limit",
@@ -34966,7 +35121,7 @@ function measureRestoredPiNativeHistory(managedMcpProfile) {
34966
35121
  if (!rolloutPath) {
34967
35122
  return { status: "fresh", tokens: 0, rolloutBytes: 0, usageTokens: 0 };
34968
35123
  }
34969
- const rollout = readFileSync17(rolloutPath);
35124
+ const rollout = readFileSync18(rolloutPath);
34970
35125
  const maximumRolloutBytes = 64 * 1024 * 1024;
34971
35126
  if (rollout.byteLength > maximumRolloutBytes) {
34972
35127
  throw stableContextError(
@@ -35060,8 +35215,8 @@ function resolvePiModelContextBudget({
35060
35215
  }
35061
35216
 
35062
35217
  // src/amaster-runtime-daemon/pi-project-instruction-extension.mjs
35063
- import { lstatSync as lstatSync14, readFileSync as readFileSync18 } from "node:fs";
35064
- import { resolve as resolve17 } from "node:path";
35218
+ import { lstatSync as lstatSync15, readFileSync as readFileSync19 } from "node:fs";
35219
+ import { resolve as resolve18 } from "node:path";
35065
35220
  var MANAGED_PI_PROJECT_INSTRUCTION_FILENAME = "amaster-project-instructions.js";
35066
35221
  function requiredString4(value, name) {
35067
35222
  if (typeof value !== "string" || !value.trim()) {
@@ -35070,12 +35225,12 @@ function requiredString4(value, name) {
35070
35225
  return value.trim();
35071
35226
  }
35072
35227
  function managedPiProjectInstructionExtensionSource(input) {
35073
- const projectInstructionPath = resolve17(requiredString4(input.projectInstructionPath, "projectInstructionPath"));
35074
- const stat = lstatSync14(projectInstructionPath);
35228
+ const projectInstructionPath = resolve18(requiredString4(input.projectInstructionPath, "projectInstructionPath"));
35229
+ const stat = lstatSync15(projectInstructionPath);
35075
35230
  if (!stat.isFile() || stat.isSymbolicLink()) {
35076
35231
  throw new Error("pi_project_instruction_extension_invalid: unsafe projectInstructionPath");
35077
35232
  }
35078
- const projectInstructions = readFileSync18(projectInstructionPath, "utf8");
35233
+ const projectInstructions = readFileSync19(projectInstructionPath, "utf8");
35079
35234
  return String.raw`const PROJECT_INSTRUCTIONS = ${JSON.stringify(projectInstructions.trim())};
35080
35235
 
35081
35236
  export default function amasterProjectInstructions(pi) {
@@ -35088,10 +35243,10 @@ export default function amasterProjectInstructions(pi) {
35088
35243
  }
35089
35244
 
35090
35245
  // src/amaster-runtime-daemon/workspace-status.mjs
35091
- import { spawnSync as spawnSync4 } from "node:child_process";
35246
+ import { spawnSync as spawnSync5 } from "node:child_process";
35092
35247
  import { createHash as createHash19 } from "node:crypto";
35093
- import { existsSync as existsSync17, readdirSync as readdirSync12, readFileSync as readFileSync19, statSync as statSync11 } from "node:fs";
35094
- import { basename as basename7, extname as extname2, isAbsolute as isAbsolute12, join as join24, relative as relative8, resolve as resolve18 } from "node:path";
35248
+ import { existsSync as existsSync17, readdirSync as readdirSync13, readFileSync as readFileSync20, statSync as statSync11 } from "node:fs";
35249
+ import { basename as basename7, extname as extname2, isAbsolute as isAbsolute12, join as join25, relative as relative8, resolve as resolve19 } from "node:path";
35095
35250
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
35096
35251
  var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
35097
35252
  [".md", "markdown"],
@@ -35160,7 +35315,7 @@ function sanitizeTrackedChange(line) {
35160
35315
  return isSafeRelativePath(path) ? line : null;
35161
35316
  }
35162
35317
  function sha256File(filePath) {
35163
- return createHash19("sha256").update(readFileSync19(filePath)).digest("hex");
35318
+ return createHash19("sha256").update(readFileSync20(filePath)).digest("hex");
35164
35319
  }
35165
35320
  function artifactHashCacheKey(relativePath, stat) {
35166
35321
  return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
@@ -35188,7 +35343,7 @@ function artifactSha256(filePath, relativePath, stat, opts = {}) {
35188
35343
  return hash3;
35189
35344
  }
35190
35345
  function scanArtifactCandidates(cwd, opts = {}) {
35191
- const root = resolve18(cwd);
35346
+ const root = resolve19(cwd);
35192
35347
  const maxCandidates = opts.maxCandidates ?? MAX_CANDIDATES;
35193
35348
  const maxEntries = opts.maxEntries ?? MAX_SCAN_ENTRIES;
35194
35349
  const candidates = [];
@@ -35198,7 +35353,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
35198
35353
  const current = stack.pop();
35199
35354
  let entries;
35200
35355
  try {
35201
- entries = readdirSync12(current, { withFileTypes: true });
35356
+ entries = readdirSync13(current, { withFileTypes: true });
35202
35357
  } catch {
35203
35358
  continue;
35204
35359
  }
@@ -35209,7 +35364,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
35209
35364
  if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
35210
35365
  if (entry.name === ".git") continue;
35211
35366
  }
35212
- const fullPath = join24(current, entry.name);
35367
+ const fullPath = join25(current, entry.name);
35213
35368
  const relativePath = normalizeRelativePath(root, fullPath);
35214
35369
  if (!isSafeRelativePath(relativePath)) continue;
35215
35370
  if (basename7(relativePath) === ".amaster-runtime.json") continue;
@@ -35227,7 +35382,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
35227
35382
  } catch {
35228
35383
  continue;
35229
35384
  }
35230
- if (!statusPathWithin(resolve18(fullPath), root) || stat.size > MAX_HASH_BYTES) continue;
35385
+ if (!statusPathWithin(resolve19(fullPath), root) || stat.size > MAX_HASH_BYTES) continue;
35231
35386
  candidates.push({
35232
35387
  relativePath,
35233
35388
  name: basename7(fullPath),
@@ -35287,10 +35442,10 @@ function sanitizeRuntimeService(entry) {
35287
35442
  };
35288
35443
  }
35289
35444
  function readRuntimeServicesSnapshot(cwd) {
35290
- const snapshotPath = join24(resolve18(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
35445
+ const snapshotPath = join25(resolve19(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
35291
35446
  if (!existsSync17(snapshotPath)) return [];
35292
35447
  try {
35293
- const parsed = JSON.parse(readFileSync19(snapshotPath, "utf8"));
35448
+ const parsed = JSON.parse(readFileSync20(snapshotPath, "utf8"));
35294
35449
  const rawServices = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.services) ? parsed.services : [];
35295
35450
  return rawServices.map((entry) => sanitizeRuntimeService(entry)).filter((entry) => entry !== null).slice(0, 50);
35296
35451
  } catch {
@@ -35301,7 +35456,7 @@ function readWorkspaceStatus(cwd, opts = {}) {
35301
35456
  const artifactScan = scanArtifactCandidates(cwd, opts);
35302
35457
  const runtimeServices = readRuntimeServicesSnapshot(cwd);
35303
35458
  const serviceUrls = [...new Set(runtimeServices.flatMap((service) => service.url ? [service.url] : []))];
35304
- const status = spawnSync4("git", ["status", "--porcelain=v1"], {
35459
+ const status = spawnSync5("git", ["status", "--porcelain=v1"], {
35305
35460
  cwd,
35306
35461
  encoding: "utf8",
35307
35462
  stdio: ["ignore", "pipe", "ignore"],
@@ -35333,7 +35488,7 @@ function readWorkspaceStatus(cwd, opts = {}) {
35333
35488
  trackedChanges.push(safeChange);
35334
35489
  }
35335
35490
  }
35336
- const aheadBehind = spawnSync4("git", ["rev-list", "--left-right", "--count", "@{upstream}...HEAD"], {
35491
+ const aheadBehind = spawnSync5("git", ["rev-list", "--left-right", "--count", "@{upstream}...HEAD"], {
35337
35492
  cwd,
35338
35493
  encoding: "utf8",
35339
35494
  stdio: ["ignore", "pipe", "ignore"],
@@ -35392,7 +35547,7 @@ function assertRequiredTaskAttachmentMaterialized(input, materialized) {
35392
35547
  }
35393
35548
 
35394
35549
  // src/amaster-runtime-daemon.mjs
35395
- var CONNECTOR_VERSION = "0.1.13-beta.1";
35550
+ var CONNECTOR_VERSION = "0.1.13-beta.2";
35396
35551
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
35397
35552
  var SUPPORTED_TASK_CONTEXT_VERSIONS = Object.freeze([TASK_CONTEXT_MANIFEST_VERSION, TASK_CONTEXT_V2]);
35398
35553
  var daemonRequire = createRequire(import.meta.url);
@@ -35464,12 +35619,12 @@ function notifyDaemonLoop() {
35464
35619
  }
35465
35620
  function waitForDaemonLoop(timeoutMs, observedVersion) {
35466
35621
  if (daemonLoopWakeVersion !== observedVersion) return Promise.resolve();
35467
- return new Promise((resolve20) => {
35622
+ return new Promise((resolve21) => {
35468
35623
  const finish = () => {
35469
35624
  clearTimeout(timer);
35470
35625
  if (wakeDaemonLoop === finish) wakeDaemonLoop = () => {
35471
35626
  };
35472
- resolve20();
35627
+ resolve21();
35473
35628
  };
35474
35629
  const timer = setTimeout(finish, timeoutMs);
35475
35630
  wakeDaemonLoop = finish;
@@ -35491,8 +35646,8 @@ function resultOutboxPendingCount(config) {
35491
35646
  if (!existsSync18(dir)) return 0;
35492
35647
  try {
35493
35648
  let pending = 0;
35494
- for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json"))) {
35495
- if (readValidResultOutboxEntryOrQuarantine(config, file, join25(dir, file))) {
35649
+ for (const file of readdirSync14(dir).filter((name) => name.endsWith(".json"))) {
35650
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join26(dir, file))) {
35496
35651
  pending += 1;
35497
35652
  }
35498
35653
  }
@@ -35503,21 +35658,21 @@ function resultOutboxPendingCount(config) {
35503
35658
  }
35504
35659
  function runCompletionStateDir(config) {
35505
35660
  const explicit = readString(process.env.AMASTER_RUN_COMPLETION_STATE_DIR);
35506
- if (explicit) return resolve19(expandHomePath(explicit));
35507
- return join25(dirname13(stateFilePath(process.env)), "run-completion-state");
35661
+ if (explicit) return resolve20(expandHomePath(explicit));
35662
+ return join26(dirname14(stateFilePath(process.env)), "run-completion-state");
35508
35663
  }
35509
35664
  function runCompletionStateInvalidDir(config) {
35510
- return join25(runCompletionStateDir(config), "invalid");
35665
+ return join26(runCompletionStateDir(config), "invalid");
35511
35666
  }
35512
35667
  function quarantineInvalidRunCompletionState(config, filePath, reason) {
35513
35668
  const invalidDir = runCompletionStateInvalidDir(config);
35514
- mkdirSync13(invalidDir, { recursive: true, mode: 448 });
35515
- const destination = join25(invalidDir, basename8(filePath));
35669
+ mkdirSync14(invalidDir, { recursive: true, mode: 448 });
35670
+ const destination = join26(invalidDir, basename8(filePath));
35516
35671
  try {
35517
- renameSync11(filePath, destination);
35672
+ renameSync12(filePath, destination);
35518
35673
  } catch {
35519
35674
  copyFileSync2(filePath, destination);
35520
- unlinkSync3(filePath);
35675
+ unlinkSync4(filePath);
35521
35676
  }
35522
35677
  process.stderr.write(`AMaster daemon quarantined invalid run completion state ${basename8(filePath)}: ${reason}
35523
35678
  `);
@@ -35569,8 +35724,8 @@ function resultOutboxActiveRunCommands(config) {
35569
35724
  if (!existsSync18(dir)) return [];
35570
35725
  const outboxPending = resultOutboxPendingCount(config);
35571
35726
  const entries = [];
35572
- for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json")).sort()) {
35573
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join25(dir, file));
35727
+ for (const file of readdirSync14(dir).filter((name) => name.endsWith(".json")).sort()) {
35728
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join26(dir, file));
35574
35729
  if (!entry) continue;
35575
35730
  const activeRun = asRecord(entry.activeRun);
35576
35731
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -35603,10 +35758,10 @@ function resultOutboxFailedRunCommands(config) {
35603
35758
  const dir = resultOutboxInvalidDir(config);
35604
35759
  if (!existsSync18(dir)) return [];
35605
35760
  const entries = [];
35606
- for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
35761
+ for (const file of readdirSync14(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
35607
35762
  let entry;
35608
35763
  try {
35609
- entry = asRecord(JSON.parse(readFileSync20(join25(dir, file), "utf8")));
35764
+ entry = asRecord(JSON.parse(readFileSync21(join26(dir, file), "utf8")));
35610
35765
  } catch {
35611
35766
  continue;
35612
35767
  }
@@ -35669,11 +35824,11 @@ function piExtraArgsDiagnostics(value) {
35669
35824
  }
35670
35825
  function safeExpandPath(value) {
35671
35826
  const text2 = readString(value);
35672
- return text2 ? resolve19(expandHomePath(text2)) : null;
35827
+ return text2 ? resolve20(expandHomePath(text2)) : null;
35673
35828
  }
35674
35829
  function safeJsonObjectFromFile(filePath) {
35675
35830
  try {
35676
- const parsed = JSON.parse(readFileSync20(filePath, "utf8"));
35831
+ const parsed = JSON.parse(readFileSync21(filePath, "utf8"));
35677
35832
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
35678
35833
  } catch {
35679
35834
  return null;
@@ -35690,7 +35845,7 @@ function safeDirectorySummary(pathValue) {
35690
35845
  }
35691
35846
  let entryCount = 0;
35692
35847
  let truncated = false;
35693
- for (const name of readdirSync13(pathValue)) {
35848
+ for (const name of readdirSync14(pathValue)) {
35694
35849
  if (name.startsWith(".")) continue;
35695
35850
  entryCount += 1;
35696
35851
  if (entryCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
@@ -35714,12 +35869,12 @@ function safeSkillRootSummary(kind, source, pathValue) {
35714
35869
  let truncated = false;
35715
35870
  if (directory.available && pathValue) {
35716
35871
  try {
35717
- for (const name of readdirSync13(pathValue)) {
35872
+ for (const name of readdirSync14(pathValue)) {
35718
35873
  if (name.startsWith(".")) continue;
35719
- const skillDir = join25(pathValue, name);
35874
+ const skillDir = join26(pathValue, name);
35720
35875
  try {
35721
35876
  if (!statSync12(skillDir).isDirectory()) continue;
35722
- if (!existsSync18(join25(skillDir, "SKILL.md"))) continue;
35877
+ if (!existsSync18(join26(skillDir, "SKILL.md"))) continue;
35723
35878
  skillCount += 1;
35724
35879
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
35725
35880
  truncated = true;
@@ -35770,7 +35925,7 @@ function objectKeyCount(value) {
35770
35925
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
35771
35926
  }
35772
35927
  function defaultPiCodingAgentDir() {
35773
- return join25(homedir7(), ".pi", "agent");
35928
+ return join26(homedir7(), ".pi", "agent");
35774
35929
  }
35775
35930
  function piCapabilitySourcesDiagnostics() {
35776
35931
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -35779,14 +35934,14 @@ function piCapabilitySourcesDiagnostics() {
35779
35934
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
35780
35935
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
35781
35936
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
35782
- const userSkillsPath = piAgentHome ? join25(piAgentHome, "skills") : null;
35937
+ const userSkillsPath = piAgentHome ? join26(piAgentHome, "skills") : null;
35783
35938
  const configuredMarketplaceSkillsPath = safeExpandPath(
35784
35939
  process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR
35785
35940
  );
35786
- const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join25(piAgentHome, "marketplace", "skills") : null);
35941
+ const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join26(piAgentHome, "marketplace", "skills") : null);
35787
35942
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
35788
- const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join25(piAgentHome, "mcp.json") : null);
35789
- const settingsConfigPath = piCodingAgentDir ? join25(piCodingAgentDir, "settings.json") : null;
35943
+ const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join26(piAgentHome, "mcp.json") : null);
35944
+ const settingsConfigPath = piCodingAgentDir ? join26(piCodingAgentDir, "settings.json") : null;
35790
35945
  const skillRoots = [
35791
35946
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
35792
35947
  safeSkillRootSummary(
@@ -36084,19 +36239,19 @@ function materializePiRuntimeSystemPrompt(config, promptRoot, commandId, content
36084
36239
  const normalizedCommandId = readString(commandId);
36085
36240
  if (!normalizedCommandId) throw new Error("pi_runtime_system_prompt_command_id_missing");
36086
36241
  const promptIdentity = createHash20("sha256").update(normalizedCommandId).digest("hex");
36087
- const promptDir = join25(promptRoot, "tmp");
36088
- mkdirSync13(promptDir, { recursive: true, mode: 448 });
36089
- const promptDirStat = lstatSync15(promptDir);
36242
+ const promptDir = join26(promptRoot, "tmp");
36243
+ mkdirSync14(promptDir, { recursive: true, mode: 448 });
36244
+ const promptDirStat = lstatSync16(promptDir);
36090
36245
  if (!promptDirStat.isDirectory() || promptDirStat.isSymbolicLink()) {
36091
36246
  throw new Error("pi_runtime_system_prompt_directory_invalid");
36092
36247
  }
36093
- chmodSync8(promptDir, 448);
36094
- const promptPath = join25(promptDir, `runtime-system-${promptIdentity}.md`);
36095
- const temporaryPath = join25(promptDir, `.runtime-system.${process.pid}.${randomUUID2()}.tmp`);
36248
+ chmodSync9(promptDir, 448);
36249
+ const promptPath = join26(promptDir, `runtime-system-${promptIdentity}.md`);
36250
+ const temporaryPath = join26(promptDir, `.runtime-system.${process.pid}.${randomUUID3()}.tmp`);
36096
36251
  try {
36097
- writeFileSync14(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
36098
- renameSync11(temporaryPath, promptPath);
36099
- chmodSync8(promptPath, 384);
36252
+ writeFileSync15(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
36253
+ renameSync12(temporaryPath, promptPath);
36254
+ chmodSync9(promptPath, 384);
36100
36255
  const promptMode = statSync12(promptPath).mode & 511;
36101
36256
  if (promptMode !== 384) {
36102
36257
  throw new Error(`pi_runtime_system_prompt_permissions_failed: mode=${promptMode.toString(8)}`);
@@ -36268,7 +36423,7 @@ AMASTER_MACHINE_ID=${quoteShell(config.machineId)}
36268
36423
  AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
36269
36424
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
36270
36425
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
36271
- AMASTER_DAEMON_STATE_FILE=${quoteShell(join25(homedir7(), ".amaster-employee", "runtime-connector-state.json"))}
36426
+ AMASTER_DAEMON_STATE_FILE=${quoteShell(join26(homedir7(), ".amaster-employee", "runtime-connector-state.json"))}
36272
36427
  EOF
36273
36428
 
36274
36429
  set -a
@@ -36745,58 +36900,74 @@ function browserSessionProfileIdentity(config, session) {
36745
36900
  }
36746
36901
  function ensureBrowserSessionProfile(config, session) {
36747
36902
  const identity = browserSessionProfileIdentity(config, session);
36748
- const profileRoot = resolve19(config.browserSessionStateRoot);
36749
- mkdirSync13(profileRoot, { recursive: true, mode: 448 });
36750
- if (lstatSync15(profileRoot).isSymbolicLink() || !lstatSync15(profileRoot).isDirectory()) {
36903
+ if (config.piExecutorUid > 0) {
36904
+ return ensureUnprivilegedBrowserSessionProfile({
36905
+ root: config.browserSessionStateRoot,
36906
+ identity,
36907
+ uid: config.piExecutorUid,
36908
+ gid: config.piExecutorGid
36909
+ });
36910
+ }
36911
+ const profileRoot = resolve20(config.browserSessionStateRoot);
36912
+ mkdirSync14(profileRoot, { recursive: true, mode: 448 });
36913
+ if (lstatSync16(profileRoot).isSymbolicLink() || !lstatSync16(profileRoot).isDirectory()) {
36751
36914
  throw new Error("browser_session_profile_path_invalid");
36752
36915
  }
36753
- chmodSync8(profileRoot, 448);
36754
- const userDataDir = resolve19(profileRoot, identity.localOpaqueRef);
36916
+ chmodSync9(profileRoot, 448);
36917
+ const userDataDir = resolve20(profileRoot, identity.localOpaqueRef);
36755
36918
  if (!pathWithin3(userDataDir, profileRoot)) {
36756
36919
  throw new Error("browser_session_profile_path_invalid");
36757
36920
  }
36758
- mkdirSync13(userDataDir, { recursive: true, mode: 448 });
36759
- if (lstatSync15(userDataDir).isSymbolicLink() || !lstatSync15(userDataDir).isDirectory()) {
36921
+ mkdirSync14(userDataDir, { recursive: true, mode: 448 });
36922
+ if (lstatSync16(userDataDir).isSymbolicLink() || !lstatSync16(userDataDir).isDirectory()) {
36760
36923
  throw new Error("browser_session_profile_path_invalid");
36761
36924
  }
36762
- chmodSync8(userDataDir, 448);
36763
- const markerPath = join25(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36764
- if (existsSync18(markerPath)) {
36765
- if (lstatSync15(markerPath).isSymbolicLink()) {
36925
+ chmodSync9(userDataDir, 448);
36926
+ const markerPath2 = join26(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36927
+ if (existsSync18(markerPath2)) {
36928
+ if (lstatSync16(markerPath2).isSymbolicLink()) {
36766
36929
  throw new Error("browser_session_profile_identity_invalid");
36767
36930
  }
36768
- const existing = readJsonFile2(markerPath);
36931
+ const existing = readJsonFile2(markerPath2);
36769
36932
  if (JSON.stringify(existing) !== JSON.stringify(identity)) {
36770
36933
  throw new Error("browser_session_profile_identity_invalid");
36771
36934
  }
36772
36935
  } else {
36773
- const temporaryPath = join25(
36936
+ const temporaryPath = join26(
36774
36937
  userDataDir,
36775
- `.${BROWSER_SESSION_PROFILE_OWNER_MARKER}.${process.pid}.${createHash20("sha256").update(randomUUID2()).digest("hex")}`
36938
+ `.${BROWSER_SESSION_PROFILE_OWNER_MARKER}.${process.pid}.${createHash20("sha256").update(randomUUID3()).digest("hex")}`
36776
36939
  );
36777
- writeFileSync14(temporaryPath, `${JSON.stringify(identity)}
36940
+ writeFileSync15(temporaryPath, `${JSON.stringify(identity)}
36778
36941
  `, { mode: 384, flag: "wx" });
36779
- renameSync11(temporaryPath, markerPath);
36942
+ renameSync12(temporaryPath, markerPath2);
36780
36943
  }
36781
- chmodSync8(markerPath, 384);
36944
+ chmodSync9(markerPath2, 384);
36782
36945
  return { profileRoot, userDataDir, identity };
36783
36946
  }
36784
36947
  function cleanupBrowserSessionProfile(config, value) {
36785
36948
  const identity = browserSessionProfileIdentity(config, value);
36786
- const profileRoot = resolve19(config.browserSessionStateRoot);
36787
- const userDataDir = resolve19(profileRoot, identity.localOpaqueRef);
36949
+ if (config.piExecutorUid > 0) {
36950
+ return cleanupUnprivilegedBrowserSessionProfile({
36951
+ root: config.browserSessionStateRoot,
36952
+ identity,
36953
+ uid: config.piExecutorUid,
36954
+ gid: config.piExecutorGid
36955
+ });
36956
+ }
36957
+ const profileRoot = resolve20(config.browserSessionStateRoot);
36958
+ const userDataDir = resolve20(profileRoot, identity.localOpaqueRef);
36788
36959
  if (!pathWithin3(userDataDir, profileRoot)) {
36789
36960
  throw new Error("browser_session_profile_cleanup_invalid");
36790
36961
  }
36791
36962
  if (!existsSync18(userDataDir)) return { outcome: "absent", identity };
36792
- if (lstatSync15(userDataDir).isSymbolicLink() || !lstatSync15(userDataDir).isDirectory()) {
36963
+ if (lstatSync16(userDataDir).isSymbolicLink() || !lstatSync16(userDataDir).isDirectory()) {
36793
36964
  throw new Error("browser_session_profile_cleanup_invalid");
36794
36965
  }
36795
- const markerPath = join25(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36796
- if (!existsSync18(markerPath) || lstatSync15(markerPath).isSymbolicLink()) {
36966
+ const markerPath2 = join26(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36967
+ if (!existsSync18(markerPath2) || lstatSync16(markerPath2).isSymbolicLink()) {
36797
36968
  throw new Error("browser_session_profile_cleanup_invalid");
36798
36969
  }
36799
- if (JSON.stringify(readJsonFile2(markerPath)) !== JSON.stringify(identity)) {
36970
+ if (JSON.stringify(readJsonFile2(markerPath2)) !== JSON.stringify(identity)) {
36800
36971
  throw new Error("browser_session_profile_cleanup_invalid");
36801
36972
  }
36802
36973
  rmSync12(userDataDir, { recursive: true, force: false });
@@ -36804,7 +36975,7 @@ function cleanupBrowserSessionProfile(config, value) {
36804
36975
  }
36805
36976
  function readJsonFile2(filePath) {
36806
36977
  try {
36807
- const parsed = JSON.parse(readFileSync20(filePath, "utf8"));
36978
+ const parsed = JSON.parse(readFileSync21(filePath, "utf8"));
36808
36979
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
36809
36980
  } catch {
36810
36981
  return {};
@@ -36815,8 +36986,8 @@ function syncPiExecutorProviderConfig(config, agentDir, providerConfig) {
36815
36986
  const { modelsSynced, settingsSynced } = syncAmasterProviderFiles(agentDir, providerConfig);
36816
36987
  if (!modelsSynced && !settingsSynced) return null;
36817
36988
  handoffPiRunPathsToChild(config, [
36818
- modelsSynced ? join25(agentDir, "models.json") : null,
36819
- settingsSynced ? join25(agentDir, "settings.json") : null
36989
+ modelsSynced ? join26(agentDir, "models.json") : null,
36990
+ settingsSynced ? join26(agentDir, "settings.json") : null
36820
36991
  ]);
36821
36992
  return { modelsSynced, settingsSynced };
36822
36993
  }
@@ -36847,7 +37018,7 @@ function safeAgentInstructionMaterializationTarget(workspace, filePath) {
36847
37018
  const segments = normalized.split("/").filter(Boolean);
36848
37019
  if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) return null;
36849
37020
  const relativePath = segments.join("/");
36850
- const targetPath = resolve19(workspace.cwd, relativePath);
37021
+ const targetPath = resolve20(workspace.cwd, relativePath);
36851
37022
  if (!pathWithin3(targetPath, workspace.cwd)) return null;
36852
37023
  return { relativePath, targetPath };
36853
37024
  }
@@ -36933,15 +37104,15 @@ async function materializeEffectiveAgentInstructions(config, command, workspace,
36933
37104
  }
36934
37105
  const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
36935
37106
  if (!target) throw new Error(`context_envelope_instruction_path_invalid: ${filePath}`);
36936
- mkdirSync13(dirname13(target.targetPath), { recursive: true });
37107
+ mkdirSync14(dirname14(target.targetPath), { recursive: true });
36937
37108
  const temporaryPath = `${target.targetPath}.mirrorx-${command.commandId}.tmp`;
36938
37109
  try {
36939
- writeFileSync14(temporaryPath, content, { encoding: "utf8", mode: 384 });
36940
- const readBack = readFileSync20(temporaryPath, "utf8");
37110
+ writeFileSync15(temporaryPath, content, { encoding: "utf8", mode: 384 });
37111
+ const readBack = readFileSync21(temporaryPath, "utf8");
36941
37112
  if (readBack !== content) {
36942
37113
  throw new Error(`context_envelope_instruction_readback_mismatch: ${filePath}`);
36943
37114
  }
36944
- renameSync11(temporaryPath, target.targetPath);
37115
+ renameSync12(temporaryPath, target.targetPath);
36945
37116
  } finally {
36946
37117
  rmSync12(temporaryPath, { force: true });
36947
37118
  }
@@ -36953,7 +37124,7 @@ async function materializeEffectiveAgentInstructions(config, command, workspace,
36953
37124
  }
36954
37125
  const readBackFiles = Object.fromEntries(materialized.map((entry) => [
36955
37126
  entry.path,
36956
- readFileSync20(resolve19(workspace.cwd, entry.path), "utf8")
37127
+ readFileSync21(resolve20(workspace.cwd, entry.path), "utf8")
36957
37128
  ]));
36958
37129
  if (stableInstructionFilesHash(readBackFiles) !== readString(instructionContract.contentHash)) {
36959
37130
  throw new Error("context_envelope_materialized_hash_mismatch");
@@ -36977,7 +37148,7 @@ function wikiTreePathForCommand(command, workspaceBindings) {
36977
37148
  const candidates = [];
36978
37149
  if (root.endsWith("paperclipai.plugin-llm-wiki")) candidates.push(root);
36979
37150
  if (basename8(root) === "plugin-data" && companyId) {
36980
- candidates.push(join25(root, companyId, "paperclipai.plugin-llm-wiki"));
37151
+ candidates.push(join26(root, companyId, "paperclipai.plugin-llm-wiki"));
36981
37152
  }
36982
37153
  for (const candidate of candidates) {
36983
37154
  try {
@@ -37216,13 +37387,13 @@ function attachPiProjectInstructionExtension(profile, input) {
37216
37387
  "managed Pi profile is missing"
37217
37388
  );
37218
37389
  }
37219
- const projectInstructionExtensionPath = join25(
37390
+ const projectInstructionExtensionPath = join26(
37220
37391
  profile.profileRoot,
37221
37392
  "extensions",
37222
37393
  MANAGED_PI_PROJECT_INSTRUCTION_FILENAME
37223
37394
  );
37224
- const contract = { projectInstructionPath: resolve19(input.cwd, "AGENTS.md") };
37225
- writeFileSync14(projectInstructionExtensionPath, managedPiProjectInstructionExtensionSource(contract), { mode: 384 });
37395
+ const contract = { projectInstructionPath: resolve20(input.cwd, "AGENTS.md") };
37396
+ writeFileSync15(projectInstructionExtensionPath, managedPiProjectInstructionExtensionSource(contract), { mode: 384 });
37226
37397
  return projectInstructionExtensionPath;
37227
37398
  }
37228
37399
  function commandUsesPiExecutor(command) {
@@ -37265,18 +37436,18 @@ function buildExecutorEnv(config, command, workspace) {
37265
37436
  };
37266
37437
  }
37267
37438
  function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
37268
- const profileRoot = mkdtempSync5(join25(tmpdir(), "amaster-pi-model-call-"));
37269
- const home = join25(profileRoot, "home");
37270
- const sessionsDir = join25(profileRoot, "sessions");
37271
- const tempDir = join25(profileRoot, "tmp");
37439
+ const profileRoot = mkdtempSync5(join26(tmpdir(), "amaster-pi-model-call-"));
37440
+ const home = join26(profileRoot, "home");
37441
+ const sessionsDir = join26(profileRoot, "sessions");
37442
+ const tempDir = join26(profileRoot, "tmp");
37272
37443
  for (const directory of [home, sessionsDir, tempDir]) {
37273
- mkdirSync13(directory, { recursive: true, mode: 448 });
37444
+ mkdirSync14(directory, { recursive: true, mode: 448 });
37274
37445
  }
37275
37446
  try {
37276
37447
  const extensionArgs = [];
37277
37448
  if (options.responseContract) {
37278
- const extensionPath = join25(profileRoot, "model-call-output-contract.js");
37279
- writeFileSync14(
37449
+ const extensionPath = join26(profileRoot, "model-call-output-contract.js");
37450
+ writeFileSync15(
37280
37451
  extensionPath,
37281
37452
  modelCallOutputContractExtensionSource(options.responseContract.maxOutputTokens),
37282
37453
  { mode: 384 }
@@ -37341,7 +37512,7 @@ function resolveNativeSessionRequest(command, workspace) {
37341
37512
  try {
37342
37513
  cwdMatched = realpathSync12(requestedCwd) === realpathSync12(sourceWorkspacePath);
37343
37514
  } catch {
37344
- cwdMatched = resolve19(requestedCwd) === resolve19(sourceWorkspacePath);
37515
+ cwdMatched = resolve20(requestedCwd) === resolve20(sourceWorkspacePath);
37345
37516
  }
37346
37517
  }
37347
37518
  const used = Boolean(enabled && requested && sessionId && requestedCwd && cwdMatched);
@@ -38151,7 +38322,7 @@ function sampleProcessGroupRssBytes(processGroupId) {
38151
38322
  if (process.platform === "win32" || processGroupId === null) return null;
38152
38323
  const now = Date.now();
38153
38324
  if (!processGroupRssSampleCache || now - processGroupRssSampleCache.sampledAtMs >= PROCESS_GROUP_RSS_SAMPLE_MIN_INTERVAL_MS) {
38154
- const result2 = spawnSync5("ps", ["-axo", "pgid=,rss="], {
38325
+ const result2 = spawnSync6("ps", ["-axo", "pgid=,rss="], {
38155
38326
  encoding: "utf8",
38156
38327
  stdio: ["ignore", "pipe", "ignore"]
38157
38328
  });
@@ -38174,7 +38345,7 @@ function realOrResolvedPath(value) {
38174
38345
  try {
38175
38346
  return realpathSync12(value);
38176
38347
  } catch {
38177
- return resolve19(value);
38348
+ return resolve20(value);
38178
38349
  }
38179
38350
  }
38180
38351
  var LSOF_COMMAND = process.platform === "darwin" && existsSync18("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
@@ -38187,7 +38358,7 @@ function processCwdForPid(pid) {
38187
38358
  }
38188
38359
  }
38189
38360
  if (process.platform === "darwin") {
38190
- const result2 = spawnSync5(LSOF_COMMAND, ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
38361
+ const result2 = spawnSync6(LSOF_COMMAND, ["-a", "-p", String(pid), "-d", "cwd", "-Fn"], {
38191
38362
  encoding: "utf8",
38192
38363
  stdio: ["ignore", "pipe", "ignore"]
38193
38364
  });
@@ -38203,7 +38374,7 @@ function allProcessCwdsByPid() {
38203
38374
  if (process.platform === "linux") {
38204
38375
  const procEntries = (() => {
38205
38376
  try {
38206
- return readdirSync13("/proc", { withFileTypes: true });
38377
+ return readdirSync14("/proc", { withFileTypes: true });
38207
38378
  } catch {
38208
38379
  return [];
38209
38380
  }
@@ -38217,7 +38388,7 @@ function allProcessCwdsByPid() {
38217
38388
  return cwds;
38218
38389
  }
38219
38390
  if (process.platform === "darwin") {
38220
- const result2 = spawnSync5(LSOF_COMMAND, ["-nP", "-d", "cwd", "-Fp", "-Fn"], {
38391
+ const result2 = spawnSync6(LSOF_COMMAND, ["-nP", "-d", "cwd", "-Fp", "-Fn"], {
38221
38392
  encoding: "utf8",
38222
38393
  stdio: ["ignore", "pipe", "ignore"]
38223
38394
  });
@@ -38238,7 +38409,7 @@ function allProcessCwdsByPid() {
38238
38409
  }
38239
38410
  function allProcessRows() {
38240
38411
  if (process.platform === "win32") return [];
38241
- const result2 = spawnSync5("ps", ["-axo", "pid=,pgid=,command="], {
38412
+ const result2 = spawnSync6("ps", ["-axo", "pid=,pgid=,command="], {
38242
38413
  encoding: "utf8",
38243
38414
  stdio: ["ignore", "pipe", "ignore"]
38244
38415
  });
@@ -38296,13 +38467,13 @@ function walkManagedWorkdirs(root) {
38296
38467
  if (!current) continue;
38297
38468
  let entries = [];
38298
38469
  try {
38299
- entries = readdirSync13(current, { withFileTypes: true });
38470
+ entries = readdirSync14(current, { withFileTypes: true });
38300
38471
  } catch {
38301
38472
  continue;
38302
38473
  }
38303
38474
  for (const entry of entries) {
38304
38475
  if (!entry.isDirectory()) continue;
38305
- const fullPath = join25(current, entry.name);
38476
+ const fullPath = join26(current, entry.name);
38306
38477
  if (entry.name === "workdir" && existsSync18(workspaceManifestPath(fullPath))) {
38307
38478
  workdirs.push(fullPath);
38308
38479
  continue;
@@ -39311,15 +39482,15 @@ async function completeCommand(config, command, status, result2, error) {
39311
39482
  }
39312
39483
  function resultOutboxDir(config) {
39313
39484
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
39314
- if (explicit) return resolve19(expandHomePath(explicit));
39315
- return join25(dirname13(stateFilePath(process.env)), "result-outbox");
39485
+ if (explicit) return resolve20(expandHomePath(explicit));
39486
+ return join26(dirname14(stateFilePath(process.env)), "result-outbox");
39316
39487
  }
39317
39488
  function resultOutboxInvalidDir(config) {
39318
- return join25(resultOutboxDir(config), "invalid");
39489
+ return join26(resultOutboxDir(config), "invalid");
39319
39490
  }
39320
39491
  function writeResultOutboxEntry(config, entry) {
39321
39492
  const dir = resultOutboxDir(config);
39322
- mkdirSync13(dir, { recursive: true });
39493
+ mkdirSync14(dir, { recursive: true });
39323
39494
  const pendingLogEntries = takeDeferredLiveLogEntries(entry.commandId);
39324
39495
  const body = {
39325
39496
  version: 1,
@@ -39329,19 +39500,19 @@ function writeResultOutboxEntry(config, entry) {
39329
39500
  ...entry,
39330
39501
  ...pendingLogEntries.length > 0 ? { pendingLogEntries } : {}
39331
39502
  };
39332
- writeFileSync14(join25(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
39503
+ writeFileSync15(join26(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
39333
39504
  `, { mode: 384 });
39334
39505
  }
39335
39506
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
39336
39507
  const invalidDir = resultOutboxInvalidDir(config);
39337
- mkdirSync13(invalidDir, { recursive: true });
39338
- const invalidPath = join25(invalidDir, file);
39508
+ mkdirSync14(invalidDir, { recursive: true });
39509
+ const invalidPath = join26(invalidDir, file);
39339
39510
  if (original === void 0) {
39340
39511
  try {
39341
- renameSync11(fullPath, invalidPath);
39512
+ renameSync12(fullPath, invalidPath);
39342
39513
  } catch {
39343
39514
  copyFileSync2(fullPath, invalidPath);
39344
- unlinkSync3(fullPath);
39515
+ unlinkSync4(fullPath);
39345
39516
  }
39346
39517
  return;
39347
39518
  }
@@ -39351,14 +39522,14 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
39351
39522
  ...detail ? { detail: truncateText(detail, 1e3) } : {},
39352
39523
  original
39353
39524
  };
39354
- writeFileSync14(invalidPath, `${JSON.stringify(evidence, null, 2)}
39525
+ writeFileSync15(invalidPath, `${JSON.stringify(evidence, null, 2)}
39355
39526
  `, { mode: 384 });
39356
- unlinkSync3(fullPath);
39527
+ unlinkSync4(fullPath);
39357
39528
  }
39358
39529
  function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
39359
39530
  let entry;
39360
39531
  try {
39361
- entry = JSON.parse(readFileSync20(fullPath, "utf8"));
39532
+ entry = JSON.parse(readFileSync21(fullPath, "utf8"));
39362
39533
  } catch (err) {
39363
39534
  const message = err instanceof Error ? err.message : String(err);
39364
39535
  moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
@@ -39391,13 +39562,13 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
39391
39562
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
39392
39563
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
39393
39564
  };
39394
- writeFileSync14(fullPath, `${JSON.stringify(next, null, 2)}
39565
+ writeFileSync15(fullPath, `${JSON.stringify(next, null, 2)}
39395
39566
  `, { mode: 384 });
39396
39567
  return next;
39397
39568
  }
39398
39569
  function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err) {
39399
39570
  const invalidDir = resultOutboxInvalidDir(config);
39400
- mkdirSync13(invalidDir, { recursive: true });
39571
+ mkdirSync14(invalidDir, { recursive: true });
39401
39572
  const body = {
39402
39573
  ...entry,
39403
39574
  invalidReason: reason,
@@ -39405,11 +39576,11 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
39405
39576
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
39406
39577
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
39407
39578
  };
39408
- const invalidPath = join25(invalidDir, file);
39409
- writeFileSync14(invalidPath, `${JSON.stringify(body, null, 2)}
39579
+ const invalidPath = join26(invalidDir, file);
39580
+ writeFileSync15(invalidPath, `${JSON.stringify(body, null, 2)}
39410
39581
  `, { mode: 384 });
39411
39582
  try {
39412
- unlinkSync3(fullPath);
39583
+ unlinkSync4(fullPath);
39413
39584
  } catch (unlinkErr) {
39414
39585
  const message = unlinkErr instanceof Error ? unlinkErr.message : String(unlinkErr);
39415
39586
  process.stderr.write(`AMaster daemon could not remove quarantined result outbox entry ${file}: ${message}
@@ -39421,10 +39592,10 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
39421
39592
  async function flushResultOutbox(config) {
39422
39593
  const dir = resultOutboxDir(config);
39423
39594
  if (!existsSync18(dir)) return { attempted: 0, completed: 0 };
39424
- const files = readdirSync13(dir).filter((name) => name.endsWith(".json")).sort();
39595
+ const files = readdirSync14(dir).filter((name) => name.endsWith(".json")).sort();
39425
39596
  let completed = 0;
39426
39597
  for (const file of files) {
39427
- const fullPath = join25(dir, file);
39598
+ const fullPath = join26(dir, file);
39428
39599
  let entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
39429
39600
  if (!entry) continue;
39430
39601
  const pendingLogEntries = Array.isArray(entry.pendingLogEntries) ? entry.pendingLogEntries.filter((logEntry) => typeof asRecord(logEntry).message === "string") : [];
@@ -39439,7 +39610,7 @@ async function flushResultOutbox(config) {
39439
39610
  if (!isTerminalResultOutboxStatus(logHttpStatus)) {
39440
39611
  const logAttemptCount = readNumber(entry.logAttemptCount, 0) + 1;
39441
39612
  if (logAttemptCount < maxResultOutboxAttempts()) {
39442
- writeFileSync14(fullPath, `${JSON.stringify({ ...entry, logAttemptCount }, null, 2)}
39613
+ writeFileSync15(fullPath, `${JSON.stringify({ ...entry, logAttemptCount }, null, 2)}
39443
39614
  `, { mode: 384 });
39444
39615
  process.stderr.write(`AMaster daemon deferred live log delivery retry failed for ${entry.commandId ?? file}: ${logMessage}
39445
39616
  `);
@@ -39452,12 +39623,12 @@ async function flushResultOutbox(config) {
39452
39623
  entry = { ...entry };
39453
39624
  delete entry.pendingLogEntries;
39454
39625
  delete entry.logAttemptCount;
39455
- writeFileSync14(fullPath, `${JSON.stringify(entry, null, 2)}
39626
+ writeFileSync15(fullPath, `${JSON.stringify(entry, null, 2)}
39456
39627
  `, { mode: 384 });
39457
39628
  }
39458
39629
  try {
39459
39630
  await postJson(config, String(entry.path), entry.payload);
39460
- unlinkSync3(fullPath);
39631
+ unlinkSync4(fullPath);
39461
39632
  clearDeliveredResultOutboxCommand(config, entry);
39462
39633
  completed += 1;
39463
39634
  } catch (err) {
@@ -39663,8 +39834,8 @@ async function materializeIssueAttachments(config, command, workspace) {
39663
39834
  runtimeAuth,
39664
39835
  issueId
39665
39836
  );
39666
- const targetDir = join25(workspace.cwd, "input-attachments");
39667
- mkdirSync13(targetDir, { recursive: true });
39837
+ const targetDir = join26(workspace.cwd, "input-attachments");
39838
+ mkdirSync14(targetDir, { recursive: true });
39668
39839
  const usedFilenames = /* @__PURE__ */ new Set();
39669
39840
  const materialized = [];
39670
39841
  for (const [index, rawAttachment] of attachments.entries()) {
@@ -39677,12 +39848,12 @@ async function materializeIssueAttachments(config, command, workspace) {
39677
39848
  let filename = safeMaterializedAttachmentFilename(attachment, index);
39678
39849
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
39679
39850
  usedFilenames.add(filename);
39680
- const targetPath = join25(targetDir, filename);
39851
+ const targetPath = join26(targetDir, filename);
39681
39852
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
39682
39853
  if (attachment.initializationInput === true && (body.byteLength !== attachment.byteSize || createHash20("sha256").update(body).digest("hex") !== attachment.sha256)) {
39683
39854
  throw new Error("Initialization input content does not match its preparation receipt");
39684
39855
  }
39685
- writeFileSync14(targetPath, body);
39856
+ writeFileSync15(targetPath, body);
39686
39857
  const attachmentId = readString(attachment.id);
39687
39858
  const actualSha256 = createHash20("sha256").update(body).digest("hex");
39688
39859
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
@@ -39749,9 +39920,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39749
39920
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
39750
39921
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
39751
39922
  }
39752
- const targetRoot = join25(workspace.cwd, "input-artifacts");
39923
+ const targetRoot = join26(workspace.cwd, "input-artifacts");
39753
39924
  rmSync12(targetRoot, { recursive: true, force: true });
39754
- mkdirSync13(targetRoot, { recursive: true });
39925
+ mkdirSync14(targetRoot, { recursive: true });
39755
39926
  const usedPaths = /* @__PURE__ */ new Set();
39756
39927
  const materialized = [];
39757
39928
  for (const [index, rawEntry] of manifest.entries.entries()) {
@@ -39780,18 +39951,18 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39780
39951
  id: attachmentId,
39781
39952
  originalFilename: readString(entry.originalFilename)
39782
39953
  }, index);
39783
- let relativePath = join25("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39954
+ let relativePath = join26("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39784
39955
  if (usedPaths.has(relativePath)) {
39785
39956
  const ext = extname3(filename);
39786
39957
  const stem = ext ? filename.slice(0, -ext.length) : filename;
39787
39958
  filename = `${stem}-${index + 1}${ext}`;
39788
- relativePath = join25("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39959
+ relativePath = join26("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39789
39960
  }
39790
39961
  usedPaths.add(relativePath);
39791
- const targetPath = join25(workspace.cwd, relativePath);
39792
- mkdirSync13(dirname13(targetPath), { recursive: true });
39793
- writeFileSync14(targetPath, body);
39794
- chmodSync8(targetPath, 292);
39962
+ const targetPath = join26(workspace.cwd, relativePath);
39963
+ mkdirSync14(dirname14(targetPath), { recursive: true });
39964
+ writeFileSync15(targetPath, body);
39965
+ chmodSync9(targetPath, 292);
39795
39966
  materialized.push({
39796
39967
  id: attachmentId,
39797
39968
  workProductId,
@@ -39810,9 +39981,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39810
39981
  version: 1,
39811
39982
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
39812
39983
  };
39813
- const manifestPath = join25(targetRoot, "artifact-input-manifest.json");
39814
- writeFileSync14(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
39815
- chmodSync8(manifestPath, 292);
39984
+ const manifestPath = join26(targetRoot, "artifact-input-manifest.json");
39985
+ writeFileSync15(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
39986
+ chmodSync9(manifestPath, 292);
39816
39987
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
39817
39988
  return materialized;
39818
39989
  }
@@ -39823,9 +39994,9 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39823
39994
  const runtimeAuth = commandRuntimeAuth(command);
39824
39995
  const files = Array.isArray(mention.files) ? mention.files : [];
39825
39996
  if (files.length === 0 || !readString(runtimeAuth.apiUrl) || !readString(runtimeAuth.apiKey)) return empty;
39826
- const targetDir = join25(workspace.cwd, "input-artifacts", "mentioned");
39997
+ const targetDir = join26(workspace.cwd, "input-artifacts", "mentioned");
39827
39998
  rmSync12(targetDir, { recursive: true, force: true });
39828
- mkdirSync13(targetDir, { recursive: true });
39999
+ mkdirSync14(targetDir, { recursive: true });
39829
40000
  const usedFilenames = /* @__PURE__ */ new Set();
39830
40001
  const materialized = [];
39831
40002
  const skipped = [];
@@ -39869,9 +40040,9 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39869
40040
  }, index);
39870
40041
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
39871
40042
  usedFilenames.add(filename);
39872
- const targetPath = join25(targetDir, filename);
39873
- writeFileSync14(targetPath, body);
39874
- chmodSync8(targetPath, 292);
40043
+ const targetPath = join26(targetDir, filename);
40044
+ writeFileSync15(targetPath, body);
40045
+ chmodSync9(targetPath, 292);
39875
40046
  materialized.push({
39876
40047
  id: artifactId,
39877
40048
  name: readString(entry.title) ?? readString(entry.originalFilename) ?? filename,
@@ -39887,7 +40058,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39887
40058
  return { materialized, skipped };
39888
40059
  }
39889
40060
  function issueCheckpointDir(workspace) {
39890
- return join25(dirname13(workspace.runDir), "checkpoint");
40061
+ return join26(dirname14(workspace.runDir), "checkpoint");
39891
40062
  }
39892
40063
  async function clearIssueCheckpoint(config, command, workspace, reason, consumedSource = null) {
39893
40064
  const checkpointDir = issueCheckpointDir(workspace);
@@ -39897,7 +40068,7 @@ async function clearIssueCheckpoint(config, command, workspace, reason, consumed
39897
40068
  if (!sourceRunId) return false;
39898
40069
  let manifest;
39899
40070
  try {
39900
- manifest = asRecord(JSON.parse(readFileSync20(join25(checkpointDir, "manifest.json"), "utf8")));
40071
+ manifest = asRecord(JSON.parse(readFileSync21(join26(checkpointDir, "manifest.json"), "utf8")));
39901
40072
  } catch {
39902
40073
  return false;
39903
40074
  }
@@ -39916,7 +40087,7 @@ function safeCheckpointRelativePath(rawPath) {
39916
40087
  return normalized;
39917
40088
  }
39918
40089
  function hashFileSha256(filePath) {
39919
- return createHash20("sha256").update(readFileSync20(filePath)).digest("hex");
40090
+ return createHash20("sha256").update(readFileSync21(filePath)).digest("hex");
39920
40091
  }
39921
40092
  function expectedContinuationCheckpoint(command) {
39922
40093
  const payload = asRecord(command.payload);
@@ -39942,7 +40113,7 @@ function expectedContinuationCheckpoint(command) {
39942
40113
  }
39943
40114
  async function materializeIssueCheckpoint(config, command, workspace) {
39944
40115
  const checkpointDir = issueCheckpointDir(workspace);
39945
- const manifestPath = join25(checkpointDir, "manifest.json");
40116
+ const manifestPath = join26(checkpointDir, "manifest.json");
39946
40117
  const expectedContinuation = expectedContinuationCheckpoint(command);
39947
40118
  const nativeRequest = asRecord(asRecord(command.payload).nativeSession);
39948
40119
  let portableNativeSession;
@@ -39972,7 +40143,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39972
40143
  }
39973
40144
  let manifest;
39974
40145
  try {
39975
- manifest = asRecord(JSON.parse(readFileSync20(manifestPath, "utf8")));
40146
+ manifest = asRecord(JSON.parse(readFileSync21(manifestPath, "utf8")));
39976
40147
  } catch (err) {
39977
40148
  rmSync12(checkpointDir, { recursive: true, force: true });
39978
40149
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
@@ -40003,7 +40174,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
40003
40174
  throw new Error("continuation_checkpoint_lineage_mismatch");
40004
40175
  }
40005
40176
  }
40006
- const filesRoot = files.length > 0 ? realpathSync12(join25(checkpointDir, "files")) : null;
40177
+ const filesRoot = files.length > 0 ? realpathSync12(join26(checkpointDir, "files")) : null;
40007
40178
  const workspaceRoot = realpathSync12(workspace.cwd);
40008
40179
  const validated = [];
40009
40180
  let totalBytes = 0;
@@ -40011,8 +40182,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
40011
40182
  const file = asRecord(rawFile);
40012
40183
  const relativePath = safeCheckpointRelativePath(readString(file.path));
40013
40184
  if (!relativePath) throw new Error("issue checkpoint manifest contains an invalid file path");
40014
- const sourceCandidate = resolve19(filesRoot, relativePath);
40015
- const target = resolve19(workspaceRoot, relativePath);
40185
+ const sourceCandidate = resolve20(filesRoot, relativePath);
40186
+ const target = resolve20(workspaceRoot, relativePath);
40016
40187
  if (!pathWithin3(sourceCandidate, filesRoot) || !pathWithin3(target, workspaceRoot)) {
40017
40188
  throw new Error(`issue checkpoint path escapes its workspace: ${relativePath}`);
40018
40189
  }
@@ -40041,14 +40212,14 @@ async function materializeIssueCheckpoint(config, command, workspace) {
40041
40212
  }
40042
40213
  const materialized = [];
40043
40214
  for (const { relativePath, source, target, expectedSha256, expectedByteSize } of validated) {
40044
- mkdirSync13(dirname13(target), { recursive: true });
40045
- const targetParent = realpathSync12(dirname13(target));
40215
+ mkdirSync14(dirname14(target), { recursive: true });
40216
+ const targetParent = realpathSync12(dirname14(target));
40046
40217
  if (!pathWithin3(targetParent, workspaceRoot)) {
40047
40218
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
40048
40219
  }
40049
40220
  let existingTarget = null;
40050
40221
  try {
40051
- existingTarget = lstatSync15(target);
40222
+ existingTarget = lstatSync16(target);
40052
40223
  } catch (err) {
40053
40224
  if (err?.code !== "ENOENT") throw err;
40054
40225
  }
@@ -40059,14 +40230,14 @@ async function materializeIssueCheckpoint(config, command, workspace) {
40059
40230
  materialized.push(relativePath);
40060
40231
  continue;
40061
40232
  }
40062
- const temporaryTarget = join25(targetParent, `.${basename8(target)}.checkpoint-${randomUUID2()}.tmp`);
40233
+ const temporaryTarget = join26(targetParent, `.${basename8(target)}.checkpoint-${randomUUID3()}.tmp`);
40063
40234
  try {
40064
40235
  copyFileSync2(source, temporaryTarget);
40065
- const temporaryStat = lstatSync15(temporaryTarget);
40236
+ const temporaryStat = lstatSync16(temporaryTarget);
40066
40237
  if (!temporaryStat.isFile() || temporaryStat.size !== expectedByteSize || hashFileSha256(temporaryTarget) !== expectedSha256) {
40067
40238
  throw new Error(`issue checkpoint target verification failed: ${relativePath}`);
40068
40239
  }
40069
- renameSync11(temporaryTarget, target);
40240
+ renameSync12(temporaryTarget, target);
40070
40241
  } finally {
40071
40242
  rmSync12(temporaryTarget, { force: true });
40072
40243
  }
@@ -40092,13 +40263,13 @@ async function materializeIssueCheckpoint(config, command, workspace) {
40092
40263
  }
40093
40264
  async function saveIssueCheckpoint(config, command, workspace, candidates, options = {}) {
40094
40265
  const checkpointDir = issueCheckpointDir(workspace);
40095
- const commandKey = readString(command.commandId)?.replace(/[^A-Za-z0-9_-]/g, "-") ?? randomUUID2();
40266
+ const commandKey = readString(command.commandId)?.replace(/[^A-Za-z0-9_-]/g, "-") ?? randomUUID3();
40096
40267
  const stagingDir = `${checkpointDir}.tmp-${commandKey}`;
40097
40268
  const backupDir = `${checkpointDir}.previous-${commandKey}`;
40098
- const filesDir = join25(stagingDir, "files");
40269
+ const filesDir = join26(stagingDir, "files");
40099
40270
  rmSync12(stagingDir, { recursive: true, force: true });
40100
40271
  rmSync12(backupDir, { recursive: true, force: true });
40101
- mkdirSync13(filesDir, { recursive: true });
40272
+ mkdirSync14(filesDir, { recursive: true });
40102
40273
  try {
40103
40274
  const files = [];
40104
40275
  let totalBytes = 0;
@@ -40109,13 +40280,13 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
40109
40280
  if (!normalized) {
40110
40281
  throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
40111
40282
  }
40112
- const sourceCandidate = resolve19(workspaceRoot, normalized);
40283
+ const sourceCandidate = resolve20(workspaceRoot, normalized);
40113
40284
  if (!pathWithin3(sourceCandidate, workspaceRoot)) {
40114
40285
  throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
40115
40286
  }
40116
40287
  let sourceStat;
40117
40288
  try {
40118
- sourceStat = lstatSync15(sourceCandidate);
40289
+ sourceStat = lstatSync16(sourceCandidate);
40119
40290
  } catch (err) {
40120
40291
  if (err?.code === "ENOENT") {
40121
40292
  throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
@@ -40147,11 +40318,11 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
40147
40318
  if (requiredPaths.length > 0 || options.taskSession) throw new Error(`continuation_checkpoint_file_size_invalid: ${relativePath}`);
40148
40319
  continue;
40149
40320
  }
40150
- const target = resolve19(filesDir, relativePath);
40321
+ const target = resolve20(filesDir, relativePath);
40151
40322
  if (!pathWithin3(target, filesDir)) continue;
40152
- mkdirSync13(dirname13(target), { recursive: true });
40323
+ mkdirSync14(dirname14(target), { recursive: true });
40153
40324
  copyFileSync2(ownedSource, target);
40154
- const storedStat = lstatSync15(target);
40325
+ const storedStat = lstatSync16(target);
40155
40326
  if (!storedStat.isFile() || storedStat.size !== byteSize) {
40156
40327
  throw new Error(`issue checkpoint copy verification failed: ${relativePath}`);
40157
40328
  }
@@ -40185,15 +40356,15 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
40185
40356
  totalBytes,
40186
40357
  files
40187
40358
  };
40188
- writeFileSync14(join25(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
40359
+ writeFileSync15(join26(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
40189
40360
  `);
40190
40361
  const replacingExistingCheckpoint = existsSync18(checkpointDir);
40191
- if (replacingExistingCheckpoint) renameSync11(checkpointDir, backupDir);
40362
+ if (replacingExistingCheckpoint) renameSync12(checkpointDir, backupDir);
40192
40363
  try {
40193
- renameSync11(stagingDir, checkpointDir);
40364
+ renameSync12(stagingDir, checkpointDir);
40194
40365
  } catch (err) {
40195
40366
  if (replacingExistingCheckpoint && existsSync18(backupDir) && !existsSync18(checkpointDir)) {
40196
- renameSync11(backupDir, checkpointDir);
40367
+ renameSync12(backupDir, checkpointDir);
40197
40368
  }
40198
40369
  throw err;
40199
40370
  }
@@ -40520,7 +40691,7 @@ async function executeRunCommand(config, command) {
40520
40691
  executorCommand: invocation.command,
40521
40692
  executorHome: workspace.executorHome,
40522
40693
  runDir: workspace.runDir,
40523
- runtimeCacheRoot: join25(dirname13(config.daemonStateFile), "cache"),
40694
+ runtimeCacheRoot: join26(dirname14(config.daemonStateFile), "cache"),
40524
40695
  cwd,
40525
40696
  runtimeAuth: commandRuntimeAuth(command),
40526
40697
  nativeSession: asRecord(asRecord(executionCommand.payload).nativeSession),
@@ -40615,7 +40786,7 @@ async function executeRunCommand(config, command) {
40615
40786
  const sharedPiHome = readString(process.env.PI_CODING_AGENT_DIR) ?? readString(process.env.PI_AGENT_HOME) ?? null;
40616
40787
  let agentDir = managedMcpProfile ? readString(managedMcpProfile.env.PI_CODING_AGENT_DIR) ?? readString(managedMcpProfile.env.PI_AGENT_HOME) ?? null : desktopDelegatedRunnerEnabled(config) ? readString(executorEnv.PI_AGENT_HOME) ?? readString(executorEnv.PI_CODING_AGENT_DIR) ?? null : readString(executorEnv.PI_CODING_AGENT_DIR) ?? readString(executorEnv.PI_AGENT_HOME) ?? null;
40617
40788
  piAgentDirForContextBudget = agentDir;
40618
- if (agentDir && sharedPiHome && resolve19(agentDir) === resolve19(sharedPiHome)) {
40789
+ if (agentDir && sharedPiHome && resolve20(agentDir) === resolve20(sharedPiHome)) {
40619
40790
  agentDir = null;
40620
40791
  }
40621
40792
  try {
@@ -41030,7 +41201,7 @@ async function executeRunCommand(config, command) {
41030
41201
  workspace,
41031
41202
  workspaceStatus.artifacts.map((artifact) => ({
41032
41203
  rawPath: artifact.relativePath,
41033
- filePath: resolve19(cwd, artifact.relativePath)
41204
+ filePath: resolve20(cwd, artifact.relativePath)
41034
41205
  })),
41035
41206
  {
41036
41207
  requiredPaths: checkpointPaths,
@@ -41141,7 +41312,7 @@ async function executeRunCommand(config, command) {
41141
41312
  workspace,
41142
41313
  workspaceStatus.artifacts.map((artifact) => ({
41143
41314
  rawPath: artifact.relativePath,
41144
- filePath: resolve19(cwd, artifact.relativePath)
41315
+ filePath: resolve20(cwd, artifact.relativePath)
41145
41316
  }))
41146
41317
  ) : readString(terminalRunDisposition?.disposition) !== "continuation_scheduled" ? await saveIssueCheckpoint(config, command, workspace, [], {
41147
41318
  requiredPaths: taskSessionCheckpointPaths(workspaceStatus),