@amaster.ai/employee-runtime-connector 0.1.1-beta.85 → 0.1.1-beta.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (19) hide show
  1. package/dist/amaster-runtime-daemon.mjs +397 -239
  2. package/dist/amaster-runtime.mjs +1 -1
  3. package/dist/templates/.mirrorx-preset-templates.json +80 -0
  4. package/dist/templates//344/274/201/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277V0.1 /345/211/257/346/234/254.md" +449 -0
  5. package/dist/templates//344/275/216/347/251/272/347/273/217/346/265/216/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +447 -0
  6. package/dist/templates//345/205/203/345/256/207/345/256/231/344/270/216/346/225/260/345/255/227/345/206/205/345/256/271/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +281 -0
  7. package/dist/templates//345/206/234/344/270/232/344/270/216/351/243/237/345/223/201/346/267/261/345/212/240/345/267/245/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +443 -0
  8. package/dist/templates//345/214/273/347/226/227/345/201/245/345/272/267/344/270/216/347/224/237/345/221/275/347/247/221/345/255/246/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +451 -0
  9. package/dist/templates//345/220/210/346/210/220/347/224/237/347/211/251/345/255/246/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +273 -0
  10. package/dist/templates//345/225/206/344/270/232/350/210/252/345/244/251/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +374 -0
  11. package/dist/templates//345/273/272/347/255/221/344/270/216/346/210/277/345/234/260/344/272/247/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +435 -0
  12. package/dist/templates//346/226/207/346/227/205/344/270/216/346/226/207/344/275/223/346/225/231/350/202/262/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +441 -0
  13. package/dist/templates//346/266/210/350/264/271/344/270/216/351/233/266/345/224/256/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +433 -0
  14. package/dist/templates//347/211/251/346/265/201/344/270/216/344/276/233/345/272/224/351/223/276/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +429 -0
  15. package/dist/templates//347/247/221/346/212/200/344/270/216/344/272/222/350/201/224/347/275/221/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +409 -0
  16. package/dist/templates//350/203/275/346/272/220/344/270/216/347/216/257/344/277/235/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +423 -0
  17. package/dist/templates//351/207/221/350/236/215/344/270/216/344/270/223/344/270/232/346/234/215/345/212/241/350/241/214/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +413 -0
  18. package/dist/templates//351/253/230/347/253/257/344/270/216/345/205/210/350/277/233/345/210/266/351/200/240/344/270/232/346/210/230/347/225/245/350/247/204/345/210/222/346/250/241/346/235/277.md +443 -0
  19. package/package.json +1 -1
@@ -2,11 +2,11 @@
2
2
  // MirrorX runtime connector daemon bundle.
3
3
 
4
4
  // src/amaster-runtime-daemon.mjs
5
- import { createHash as createHash13 } from "node:crypto";
5
+ import { createHash as createHash14 } from "node:crypto";
6
6
  import { createRequire } from "node:module";
7
- import { chmodSync as chmodSync6, copyFileSync as copyFileSync2, existsSync as existsSync12, lstatSync as lstatSync6, mkdirSync as mkdirSync8, mkdtempSync, readFileSync as readFileSync12, readdirSync as readdirSync9, realpathSync as realpathSync5, renameSync as renameSync7, rmSync as rmSync7, statSync as statSync9, symlinkSync as symlinkSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "node:fs";
7
+ import { chmodSync as chmodSync7, copyFileSync as copyFileSync2, existsSync as existsSync13, lstatSync as lstatSync7, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync2, readFileSync as readFileSync13, readdirSync as readdirSync10, realpathSync as realpathSync5, renameSync as renameSync8, rmSync as rmSync8, statSync as statSync9, symlinkSync as symlinkSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync10 } from "node:fs";
8
8
  import { arch as arch3, homedir as homedir3, hostname as hostname2, platform as platform3, tmpdir } from "node:os";
9
- import { basename as basename6, delimiter as delimiter3, dirname as dirname9, extname as extname2, isAbsolute as isAbsolute6, join as join14, relative as relative7, resolve as resolve10 } from "node:path";
9
+ import { basename as basename6, delimiter as delimiter3, dirname as dirname10, extname as extname3, isAbsolute as isAbsolute7, join as join15, relative as relative7, resolve as resolve11 } from "node:path";
10
10
  import { spawn, spawnSync as spawnSync5 } from "node:child_process";
11
11
 
12
12
  // src/amaster-runtime-daemon/common.mjs
@@ -762,7 +762,7 @@ function skipVoid(str, ptr, banNewLines, banComments) {
762
762
  }
763
763
  return ptr;
764
764
  }
765
- function skipUntil(str, ptr, sep3, end, banNewLines = false) {
765
+ function skipUntil(str, ptr, sep4, end, banNewLines = false) {
766
766
  if (!end) {
767
767
  ptr = indexOfNewline(str, ptr);
768
768
  return ptr < 0 ? str.length : ptr;
@@ -771,7 +771,7 @@ function skipUntil(str, ptr, sep3, end, banNewLines = false) {
771
771
  let c = str[i];
772
772
  if (c === "#") {
773
773
  i = indexOfNewline(str, i);
774
- } else if (c === sep3) {
774
+ } else if (c === sep4) {
775
775
  return i + 1;
776
776
  } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) {
777
777
  return i;
@@ -3500,7 +3500,7 @@ function createManagedPiMcpProfileApi(options = {}) {
3500
3500
  if (!Number.isFinite(value)) throw new Error("pi_managed_mcp_attestation_failed: invalid attestation clock");
3501
3501
  return value;
3502
3502
  }
3503
- function sha2562(value) {
3503
+ function sha2563(value) {
3504
3504
  return createHash3("sha256").update(value).digest("hex");
3505
3505
  }
3506
3506
  function trustedTreeDigest(rootPath, options2 = {}) {
@@ -3590,20 +3590,20 @@ function createManagedPiMcpProfileApi(options = {}) {
3590
3590
  const loaderPath = join5(cursor, "dist", "core", "extensions", "loader.js");
3591
3591
  if (existsSync3(packagePath) && existsSync3(loaderPath)) {
3592
3592
  const packageJson = JSON.parse(readFileSync4(packagePath, "utf8"));
3593
- return sha2562(stablePiJson({
3593
+ return sha2563(stablePiJson({
3594
3594
  name: packageJson.name,
3595
3595
  version: packageJson.version,
3596
- loaderSha256: sha2562(readFileSync4(loaderPath))
3596
+ loaderSha256: sha2563(readFileSync4(loaderPath))
3597
3597
  }));
3598
3598
  }
3599
3599
  cursor = dirname4(cursor);
3600
3600
  }
3601
- return sha2562(readFileSync4(realpathSync2(executorPath)));
3601
+ return sha2563(readFileSync4(realpathSync2(executorPath)));
3602
3602
  }
3603
3603
  function effectiveToolsBootstrapKey(input, sharedRuntime, executorCommand) {
3604
3604
  const adapterRoot = join5(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter");
3605
3605
  const resolvedExecutorCommand = resolvePiExecutablePath(executorCommand, input.baseEnv);
3606
- return sha2562(stablePiJson({
3606
+ return sha2563(stablePiJson({
3607
3607
  schemaVersion: PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION,
3608
3608
  connectorVersion: nonEmpty2(input.connectorVersion, "connectorVersion"),
3609
3609
  executorIdentity: piExecutableIdentity(resolvedExecutorCommand),
@@ -3617,8 +3617,8 @@ function createManagedPiMcpProfileApi(options = {}) {
3617
3617
  // source; hash every package-owned adapter file while excluding that
3618
3618
  // dependency graph so ordinary npm links do not make the cache unusable.
3619
3619
  adapterTreeSha256: trustedTreeDigest(adapterRoot, { ignoredRootEntries: ["node_modules"] }),
3620
- attestorSourceSha256: sha2562(managedPiEffectiveToolsAttestorExtensionSource()),
3621
- argsNormalizerSourceSha256: sha2562(managedPiMcpArgsNormalizerExtensionSource())
3620
+ attestorSourceSha256: sha2563(managedPiEffectiveToolsAttestorExtensionSource()),
3621
+ argsNormalizerSourceSha256: sha2563(managedPiMcpArgsNormalizerExtensionSource())
3622
3622
  }));
3623
3623
  }
3624
3624
  function prepareEffectiveToolsBootstrapCache(input, sharedRuntime, executorCommand, tmpPath) {
@@ -3729,7 +3729,7 @@ function createManagedPiMcpProfileApi(options = {}) {
3729
3729
  }
3730
3730
  function adapterServerConfigHash(definition, adapterVersion) {
3731
3731
  const identity2 = piMcpAdapterServerConfigIdentity(definition, adapterVersion);
3732
- return sha2562(stablePiJson(identity2));
3732
+ return sha2563(stablePiJson(identity2));
3733
3733
  }
3734
3734
  function validateDirectCatalog(gateway, mcpToolMode) {
3735
3735
  const catalog = record6(gateway.toolCatalog);
@@ -4399,10 +4399,10 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4399
4399
  if (receipt.status !== "attested" || receipt.mode !== "probe" || receipt.proxyMode !== input.proxyMode || receipt.proxyPresent !== expectedProxyPresent || receipt.effectiveSetHash !== input.effectiveSetHash || receipt.attestorSourceSha256 !== input.attestorSourceSha256 || receipt.configSha256 !== input.configSha256 || receipt.cacheSha256 !== input.cacheSha256) {
4400
4400
  throw new Error("pi_managed_mcp_effective_tools_failed: probe receipt mismatch");
4401
4401
  }
4402
- if (sha2562(readFileSync4(input.configPath)) !== input.configSha256) {
4402
+ if (sha2563(readFileSync4(input.configPath)) !== input.configSha256) {
4403
4403
  throw new Error("pi_managed_mcp_effective_tools_failed: config drifted during probe");
4404
4404
  }
4405
- if (sha2562(readFileSync4(input.cachePath)) !== input.cacheSha256) {
4405
+ if (sha2563(readFileSync4(input.cachePath)) !== input.cacheSha256) {
4406
4406
  throw new Error("pi_managed_mcp_effective_tools_failed: cache drifted during probe");
4407
4407
  }
4408
4408
  if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
@@ -4411,7 +4411,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4411
4411
  effectiveToolProxyMode: receipt.proxyMode,
4412
4412
  effectiveToolProxyPresent: receipt.proxyPresent,
4413
4413
  effectiveToolSetHash: receipt.effectiveSetHash,
4414
- effectiveToolProbeDigest: sha2562(stablePiJson(receipt)),
4414
+ effectiveToolProbeDigest: sha2563(stablePiJson(receipt)),
4415
4415
  effectiveToolProbeAt: receipt.attestedAt,
4416
4416
  effectiveToolProbeElapsedMs: elapsedMs,
4417
4417
  effectiveToolProbeTimeoutMs: PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS,
@@ -4548,8 +4548,8 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4548
4548
  };
4549
4549
  writeOwnedFileAtomic(cachePath, `${JSON.stringify(cache, null, 2)}
4550
4550
  `);
4551
- const cacheSha256 = sha2562(readFileSync4(cachePath));
4552
- const attestorSourceSha256 = sha2562(managedPiEffectiveToolsAttestorExtensionSource());
4551
+ const cacheSha256 = sha2563(readFileSync4(cachePath));
4552
+ const attestorSourceSha256 = sha2563(managedPiEffectiveToolsAttestorExtensionSource());
4553
4553
  const manifestPath = join5(profileRoot, "effective-tools-manifest.json");
4554
4554
  const receiptPath = join5(tmp, "effective-tools-receipt.json");
4555
4555
  const phasePath = join5(tmp, "effective-tools-phase.json");
@@ -4568,7 +4568,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4568
4568
  }))),
4569
4569
  proxyMode: "forbidden",
4570
4570
  attestorSourceSha256,
4571
- configSha256: sha2562(readFileSync4(configPath)),
4571
+ configSha256: sha2563(readFileSync4(configPath)),
4572
4572
  cacheSha256,
4573
4573
  cacheSemanticHash: stablePiManagedMcpCacheSemanticHash(readFileSync4(cachePath))
4574
4574
  };
@@ -4616,19 +4616,19 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4616
4616
  name: tool.exposedName,
4617
4617
  schemaHash: tool.effectiveSchemaHash
4618
4618
  }))),
4619
- configSha256: sha2562(closureConfigBytes),
4620
- cacheSha256: sha2562(closureCacheBytes),
4619
+ configSha256: sha2563(closureConfigBytes),
4620
+ cacheSha256: sha2563(closureCacheBytes),
4621
4621
  cacheSemanticHash: stablePiManagedMcpCacheSemanticHash(closureCacheBytes)
4622
4622
  }, null, 2)}
4623
4623
  `;
4624
4624
  return {
4625
4625
  toolAllowlist: closureToolNames,
4626
4626
  cacheContentsBase64: closureCacheBytes.toString("base64"),
4627
- cacheSha256: sha2562(closureCacheBytes),
4627
+ cacheSha256: sha2563(closureCacheBytes),
4628
4628
  manifestContentsBase64: Buffer.from(closureManifestContents).toString("base64"),
4629
- manifestSha256: sha2562(Buffer.from(closureManifestContents)),
4629
+ manifestSha256: sha2563(Buffer.from(closureManifestContents)),
4630
4630
  configContentsBase64: closureConfigBytes.toString("base64"),
4631
- configSha256: sha2562(closureConfigBytes)
4631
+ configSha256: sha2563(closureConfigBytes)
4632
4632
  };
4633
4633
  })() : null;
4634
4634
  directAttestationInput = {
@@ -4639,7 +4639,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4639
4639
  cacheSha256,
4640
4640
  cacheContentsBase64: Buffer.from(readFileSync4(cachePath)).toString("base64"),
4641
4641
  configPath,
4642
- configSha256: sha2562(readFileSync4(configPath)),
4642
+ configSha256: sha2563(readFileSync4(configPath)),
4643
4643
  attestorSourceSha256,
4644
4644
  effectiveSetHash: manifest.effectiveSetHash,
4645
4645
  proxyMode: manifest.proxyMode,
@@ -4758,7 +4758,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4758
4758
  cacheContentsBase64: directAttestationInput.cacheContentsBase64,
4759
4759
  cacheOwnership: runExitClosureOwnership ? { uid: runExitClosureOwnership.cache.uid, gid: runExitClosureOwnership.cache.gid } : null,
4760
4760
  manifestPath: directAttestationInput.manifestPath,
4761
- manifestSha256: sha2562(readFileSync4(directAttestationInput.manifestPath)),
4761
+ manifestSha256: sha2563(readFileSync4(directAttestationInput.manifestPath)),
4762
4762
  configPath: directAttestationInput.configPath,
4763
4763
  configSha256: directAttestationInput.configSha256,
4764
4764
  receiptPath: directAttestationInput.receiptPath,
@@ -4827,7 +4827,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4827
4827
  );
4828
4828
  const cacheContents = Buffer.from(cacheContentsBase64, "base64");
4829
4829
  const cacheSha256 = nonEmpty2(baseline.cacheSha256, "runExitClosureBaseline.cacheSha256");
4830
- if (sha2562(cacheContents) !== cacheSha256) {
4830
+ if (sha2563(cacheContents) !== cacheSha256) {
4831
4831
  throw new Error("pi_run_exit_closure_baseline_cache_digest_mismatch");
4832
4832
  }
4833
4833
  const baselineCacheOwnership = record6(baseline.cacheOwnership);
@@ -4840,7 +4840,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4840
4840
  if (closureToolAllowlist && (closureToolAllowlist.length !== RUN_EXIT_CLOSURE_DIRECT_TYPED_TOOL_NAMES.size || new Set(closureToolAllowlist).size !== RUN_EXIT_CLOSURE_DIRECT_TYPED_TOOL_NAMES.size || closureToolAllowlist.some((name) => !PROVIDER_SAFE_TOOL_NAME.test(name)))) {
4841
4841
  throw new Error("pi_run_exit_closure_baseline_tool_allowlist_invalid");
4842
4842
  }
4843
- const currentManifestSha256 = sha2562(readFileSync4(manifestPath));
4843
+ const currentManifestSha256 = sha2563(readFileSync4(manifestPath));
4844
4844
  const acceptedManifestDigests = /* @__PURE__ */ new Set([
4845
4845
  nonEmpty2(baseline.manifestSha256, "runExitClosureBaseline.manifestSha256"),
4846
4846
  ...closureProfile ? [nonEmpty2(closureProfile.manifestSha256, "closureProfile.manifestSha256")] : []
@@ -4848,7 +4848,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4848
4848
  if (!acceptedManifestDigests.has(currentManifestSha256)) {
4849
4849
  throw new Error("pi_run_exit_closure_baseline_manifest_drift");
4850
4850
  }
4851
- const currentConfigSha256 = sha2562(readFileSync4(configPath));
4851
+ const currentConfigSha256 = sha2563(readFileSync4(configPath));
4852
4852
  const acceptedConfigDigests = /* @__PURE__ */ new Set([
4853
4853
  nonEmpty2(baseline.configSha256, "runExitClosureBaseline.configSha256"),
4854
4854
  ...closureProfile ? [nonEmpty2(closureProfile.configSha256, "closureProfile.configSha256")] : []
@@ -4887,7 +4887,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4887
4887
  }];
4888
4888
  if (existsSync3(receiptPath)) rmSync3(receiptPath);
4889
4889
  for (const entry of phaseContents) {
4890
- if (sha2562(entry.bytes) !== entry.expectedSha256) {
4890
+ if (sha2563(entry.bytes) !== entry.expectedSha256) {
4891
4891
  throw new Error(`pi_run_exit_closure_${entry.label}_digest_mismatch`);
4892
4892
  }
4893
4893
  const recordedOwnership = Number.isSafeInteger(entry.ownership.uid) && entry.ownership.uid >= 0 && Number.isSafeInteger(entry.ownership.gid) && entry.ownership.gid >= 0 ? { uid: entry.ownership.uid, gid: entry.ownership.gid } : entry.path === cachePath ? cacheOwnership : ownershipStatSyncImpl(entry.path);
@@ -4896,7 +4896,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
4896
4896
  if (replacedStat.uid !== recordedOwnership.uid || replacedStat.gid !== recordedOwnership.gid) {
4897
4897
  chownSyncImpl(entry.path, recordedOwnership.uid, recordedOwnership.gid);
4898
4898
  }
4899
- if (sha2562(readFileSync4(entry.path)) !== entry.expectedSha256) {
4899
+ if (sha2563(readFileSync4(entry.path)) !== entry.expectedSha256) {
4900
4900
  throw new Error(`pi_run_exit_closure_${entry.label}_restore_failed`);
4901
4901
  }
4902
4902
  const restoredStat = ownershipStatSyncImpl(entry.path);
@@ -5038,7 +5038,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
5038
5038
  sessionId: gateway.sessionId,
5039
5039
  sourcePiHome,
5040
5040
  piCodingAgentDir,
5041
- configSha256: sha2562(readFileSync4(configPath)),
5041
+ configSha256: sha2563(readFileSync4(configPath)),
5042
5042
  ...skillProfilesAttestation(skillProfiles, enabledRoleSkills)
5043
5043
  };
5044
5044
  return {
@@ -8978,9 +8978,9 @@ function governedMcpToolResult(structuredContent) {
8978
8978
  const intentId = readString(effectResult.artifactIntentId);
8979
8979
  const manifestId = readString(effectResult.manifestId);
8980
8980
  const sourceRelativePath = readString(effectResult.sourceRelativePath);
8981
- const sha2562 = readString(effectResult.sha256);
8981
+ const sha2563 = readString(effectResult.sha256);
8982
8982
  const byteSize = readNumber(effectResult.byteSize, 0);
8983
- const artifactIntent = providerStatus === "pending_reconcile" && intentId && manifestId && sourceRelativePath && /^[a-f0-9]{64}$/.test(sha2562 ?? "") && Number.isSafeInteger(byteSize) && byteSize > 0 ? { intentId, manifestId, sourceRelativePath, sha256: sha2562, byteSize } : null;
8983
+ const artifactIntent = providerStatus === "pending_reconcile" && intentId && manifestId && sourceRelativePath && /^[a-f0-9]{64}$/.test(sha2563 ?? "") && Number.isSafeInteger(byteSize) && byteSize > 0 ? { intentId, manifestId, sourceRelativePath, sha256: sha2563, byteSize } : null;
8984
8984
  const workspaceDocumentEffect = asRecord(effectResult.workspaceDocumentIntent);
8985
8985
  const workspaceDocumentCallId = readString(workspaceDocumentEffect.callId);
8986
8986
  const workspaceDocumentManifestId = readString(workspaceDocumentEffect.manifestId);
@@ -10013,7 +10013,7 @@ async function postRuntimeConnectorJsonWithRetry(config, path, payload, options
10013
10013
  } catch (error) {
10014
10014
  lastError = error;
10015
10015
  if (attempt >= maxAttempts || !retryableRuntimeConnectorPost(error)) throw error;
10016
- if (delayMs > 0) await new Promise((resolve11) => setTimeout(resolve11, delayMs));
10016
+ if (delayMs > 0) await new Promise((resolve12) => setTimeout(resolve12, delayMs));
10017
10017
  }
10018
10018
  }
10019
10019
  throw lastError;
@@ -10245,9 +10245,9 @@ function createRuntimeDocumentIngestQueue({ ingest }) {
10245
10245
  let queue = Promise.resolve();
10246
10246
  const documentIdentity = (intent) => {
10247
10247
  const sourceRelativePath = readString(asRecord(intent).sourceRelativePath);
10248
- const sha2562 = readString(asRecord(intent).sha256);
10248
+ const sha2563 = readString(asRecord(intent).sha256);
10249
10249
  const byteSize = asRecord(intent).byteSize;
10250
- return sourceRelativePath && sha2562 && Number.isSafeInteger(byteSize) && byteSize > 0 ? `document:${sourceRelativePath}\0${sha2562}\0${byteSize}` : null;
10250
+ return sourceRelativePath && sha2563 && Number.isSafeInteger(byteSize) && byteSize > 0 ? `document:${sourceRelativePath}\0${sha2563}\0${byteSize}` : null;
10251
10251
  };
10252
10252
  const retainReceipts = (nextReceipts) => {
10253
10253
  receipts.push(...nextReceipts);
@@ -10322,9 +10322,9 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
10322
10322
  let queue = Promise.resolve();
10323
10323
  const artifactIdentity = (intent) => {
10324
10324
  const sourceRelativePath = readString(asRecord(intent).sourceRelativePath);
10325
- const sha2562 = readString(asRecord(intent).sha256);
10325
+ const sha2563 = readString(asRecord(intent).sha256);
10326
10326
  const byteSize = asRecord(intent).byteSize;
10327
- return sourceRelativePath && sha2562 && Number.isSafeInteger(byteSize) && byteSize > 0 ? `${sourceRelativePath}\0${sha2562}\0${byteSize}` : null;
10327
+ return sourceRelativePath && sha2563 && Number.isSafeInteger(byteSize) && byteSize > 0 ? `${sourceRelativePath}\0${sha2563}\0${byteSize}` : null;
10328
10328
  };
10329
10329
  const retainReceipts = (receipts) => {
10330
10330
  artifacts.push(...receipts);
@@ -10691,12 +10691,159 @@ function planManagedWorkspaceGcDryRun(input) {
10691
10691
  return result3;
10692
10692
  }
10693
10693
 
10694
+ // src/amaster-runtime-daemon/preset-templates.mjs
10695
+ import { createHash as createHash11 } from "node:crypto";
10696
+ import {
10697
+ chmodSync as chmodSync5,
10698
+ existsSync as existsSync9,
10699
+ lstatSync as lstatSync5,
10700
+ mkdirSync as mkdirSync7,
10701
+ mkdtempSync,
10702
+ readFileSync as readFileSync10,
10703
+ readdirSync as readdirSync7,
10704
+ renameSync as renameSync7,
10705
+ rmSync as rmSync6,
10706
+ unlinkSync as unlinkSync2,
10707
+ writeFileSync as writeFileSync8
10708
+ } from "node:fs";
10709
+ import { dirname as dirname7, extname, isAbsolute as isAbsolute5, join as join11, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
10710
+ import { fileURLToPath } from "node:url";
10711
+ var PRESET_TEMPLATE_MANIFEST_FILE = ".mirrorx-preset-templates.json";
10712
+ var MAX_PRESET_TEMPLATE_FILES = 256;
10713
+ var MAX_PRESET_TEMPLATE_FILE_BYTES = 20 * 1024 * 1024;
10714
+ var MAX_PRESET_TEMPLATE_TOTAL_BYTES = 50 * 1024 * 1024;
10715
+ function sha2562(value) {
10716
+ return createHash11("sha256").update(value).digest("hex");
10717
+ }
10718
+ function lstatIfExists(path) {
10719
+ try {
10720
+ return lstatSync5(path);
10721
+ } catch (error) {
10722
+ if (error?.code === "ENOENT") return null;
10723
+ throw error;
10724
+ }
10725
+ }
10726
+ function validTemplateName(value) {
10727
+ return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !value.includes("\0") && !value.includes("/") && !value.includes("\\") && !isAbsolute5(value) && parse2(value).base === value && extname(value).toLowerCase() === ".md";
10728
+ }
10729
+ function readManifest(manifestPath, { strict }) {
10730
+ try {
10731
+ const parsed = JSON.parse(readFileSync10(manifestPath, "utf8"));
10732
+ if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.files)) {
10733
+ throw new Error("preset_template_bundle_manifest_invalid");
10734
+ }
10735
+ if (parsed.files.length > MAX_PRESET_TEMPLATE_FILES) {
10736
+ throw new Error("preset_template_bundle_file_limit_exceeded");
10737
+ }
10738
+ const seen = /* @__PURE__ */ new Set();
10739
+ let totalBytes = 0;
10740
+ const files = parsed.files.map((file) => {
10741
+ if (!validTemplateName(file?.name) || !Number.isSafeInteger(file?.bytes) || file.bytes < 0 || file.bytes > MAX_PRESET_TEMPLATE_FILE_BYTES || typeof file?.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(file.sha256) || seen.has(file.name)) {
10742
+ throw new Error("preset_template_bundle_manifest_invalid");
10743
+ }
10744
+ seen.add(file.name);
10745
+ totalBytes += file.bytes;
10746
+ if (totalBytes > MAX_PRESET_TEMPLATE_TOTAL_BYTES) {
10747
+ throw new Error("preset_template_bundle_size_limit_exceeded");
10748
+ }
10749
+ return { name: file.name, bytes: file.bytes, sha256: file.sha256 };
10750
+ });
10751
+ return { schemaVersion: 1, files, totalBytes };
10752
+ } catch (error) {
10753
+ if (strict) throw error;
10754
+ return { schemaVersion: 1, files: [], totalBytes: 0 };
10755
+ }
10756
+ }
10757
+ function verifiedBundleFiles(sourceDir, manifest) {
10758
+ return manifest.files.map((entry) => {
10759
+ const sourcePath = join11(sourceDir, entry.name);
10760
+ const stat = lstatSync5(sourcePath);
10761
+ if (!stat.isFile() || stat.isSymbolicLink()) {
10762
+ throw new Error(`preset_template_bundle_file_unsafe: ${entry.name}`);
10763
+ }
10764
+ const body = readFileSync10(sourcePath);
10765
+ if (body.byteLength !== entry.bytes || sha2562(body) !== entry.sha256) {
10766
+ throw new Error(`preset_template_bundle_digest_mismatch: ${entry.name}`);
10767
+ }
10768
+ return { ...entry, body };
10769
+ });
10770
+ }
10771
+ function removeRetiredPresetFiles(targetDir, previousManifest, nextNames) {
10772
+ for (const entry of previousManifest.files) {
10773
+ if (nextNames.has(entry.name)) continue;
10774
+ const targetPath = join11(targetDir, entry.name);
10775
+ if (!existsSync9(targetPath)) continue;
10776
+ const stat = lstatSync5(targetPath);
10777
+ if (stat.isDirectory()) {
10778
+ throw new Error(`preset_template_target_conflict: ${entry.name}`);
10779
+ }
10780
+ unlinkSync2(targetPath);
10781
+ }
10782
+ }
10783
+ function materializeBundledPresetTemplates(input) {
10784
+ const sourceDir = resolve7(input.sourceDir);
10785
+ const targetDir = resolve7(input.targetDir);
10786
+ if (sourceDir === targetDir || sourceDir.startsWith(`${targetDir}${sep3}`) || targetDir.startsWith(`${sourceDir}${sep3}`)) {
10787
+ throw new Error("preset_template_source_target_overlap");
10788
+ }
10789
+ const manifest = readManifest(join11(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
10790
+ const verifiedFiles = verifiedBundleFiles(sourceDir, manifest);
10791
+ mkdirSync7(dirname7(targetDir), { recursive: true, mode: 493 });
10792
+ const targetStat = lstatIfExists(targetDir);
10793
+ if (targetStat && (!targetStat.isDirectory() || targetStat.isSymbolicLink())) {
10794
+ throw new Error("preset_template_target_root_unsafe");
10795
+ }
10796
+ mkdirSync7(targetDir, { recursive: true, mode: 493 });
10797
+ const previousManifest = readManifest(join11(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
10798
+ const stageDir = mkdtempSync(join11(dirname7(targetDir), ".mirrorx-preset-templates-"));
10799
+ try {
10800
+ for (const file of verifiedFiles) {
10801
+ const stagedPath = join11(stageDir, file.name);
10802
+ writeFileSync8(stagedPath, file.body, { mode: 292 });
10803
+ chmodSync5(stagedPath, 292);
10804
+ renameSync7(stagedPath, join11(targetDir, file.name));
10805
+ }
10806
+ removeRetiredPresetFiles(targetDir, previousManifest, new Set(manifest.files.map((file) => file.name)));
10807
+ const stagedManifest = join11(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
10808
+ writeFileSync8(stagedManifest, `${JSON.stringify({
10809
+ schemaVersion: manifest.schemaVersion,
10810
+ files: manifest.files
10811
+ }, null, 2)}
10812
+ `, { mode: 292 });
10813
+ chmodSync5(stagedManifest, 292);
10814
+ renameSync7(stagedManifest, join11(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
10815
+ } finally {
10816
+ rmSync6(stageDir, { recursive: true, force: true });
10817
+ }
10818
+ chmodSync5(targetDir, 493);
10819
+ return {
10820
+ fileCount: manifest.files.length,
10821
+ totalBytes: manifest.totalBytes,
10822
+ targetDir
10823
+ };
10824
+ }
10825
+ function runtimePresetTemplateTarget(env = process.env) {
10826
+ const configured = typeof env.AMASTER_RUNTIME_TEMPLATES_ROOT === "string" ? env.AMASTER_RUNTIME_TEMPLATES_ROOT.trim() : "";
10827
+ if (configured) return resolve7(configured);
10828
+ const piHome = typeof env.PI_CODING_AGENT_DIR === "string" ? resolve7(env.PI_CODING_AGENT_DIR) : null;
10829
+ return piHome === "/data/.pi" ? "/data/templates" : null;
10830
+ }
10831
+ function materializeRuntimePresetTemplates(env = process.env, options = {}) {
10832
+ const targetDir = options.targetDir ?? runtimePresetTemplateTarget(env);
10833
+ if (!targetDir) return { status: "skipped", reason: "not_pi_cli_runtime" };
10834
+ const sourceDir = options.sourceDir ?? fileURLToPath(new URL("./templates/", import.meta.url));
10835
+ return {
10836
+ status: "ready",
10837
+ ...materializeBundledPresetTemplates({ sourceDir, targetDir })
10838
+ };
10839
+ }
10840
+
10694
10841
  // src/amaster-runtime-daemon/runtime-status-summary.mjs
10695
- import { existsSync as existsSync9, readdirSync as readdirSync7, statSync as statSync6 } from "node:fs";
10696
- import { dirname as dirname7, join as join11, resolve as resolve7 } from "node:path";
10842
+ import { existsSync as existsSync10, readdirSync as readdirSync8, statSync as statSync6 } from "node:fs";
10843
+ import { dirname as dirname8, join as join12, resolve as resolve8 } from "node:path";
10697
10844
  function runtimeStatusDirectoryEntries(path) {
10698
10845
  try {
10699
- return readdirSync7(path, { withFileTypes: true });
10846
+ return readdirSync8(path, { withFileTypes: true });
10700
10847
  } catch {
10701
10848
  return [];
10702
10849
  }
@@ -10716,7 +10863,7 @@ function runtimeStatusDirectorySizeBytes(path) {
10716
10863
  if (!stat || stat.isSymbolicLink()) continue;
10717
10864
  if (stat.isDirectory()) {
10718
10865
  for (const entry of runtimeStatusDirectoryEntries(current)) {
10719
- stack.push(join11(current, entry.name));
10866
+ stack.push(join12(current, entry.name));
10720
10867
  }
10721
10868
  continue;
10722
10869
  }
@@ -10726,15 +10873,15 @@ function runtimeStatusDirectorySizeBytes(path) {
10726
10873
  }
10727
10874
  function walkRuntimeStatusManagedWorkdirs(root) {
10728
10875
  const workdirs = [];
10729
- if (!root || !existsSync9(root)) return workdirs;
10876
+ if (!root || !existsSync10(root)) return workdirs;
10730
10877
  const stack = [root];
10731
10878
  while (stack.length > 0) {
10732
10879
  const current = stack.pop();
10733
10880
  if (!current) continue;
10734
10881
  for (const entry of runtimeStatusDirectoryEntries(current)) {
10735
10882
  if (!entry.isDirectory()) continue;
10736
- const fullPath = join11(current, entry.name);
10737
- if (entry.name === "workdir" && existsSync9(workspaceManifestPath(fullPath))) {
10883
+ const fullPath = join12(current, entry.name);
10884
+ if (entry.name === "workdir" && existsSync10(workspaceManifestPath(fullPath))) {
10738
10885
  workdirs.push(fullPath);
10739
10886
  continue;
10740
10887
  }
@@ -10775,25 +10922,25 @@ function summarizeRuntimeStatusRecentRun(workdir, manifest) {
10775
10922
  }
10776
10923
  function runtimeStatusOutboxDir(config) {
10777
10924
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
10778
- return join11(dirname7(stateFilePath({
10925
+ return join12(dirname8(stateFilePath({
10779
10926
  AMASTER_DAEMON_STATE_FILE: statePath
10780
10927
  })), "result-outbox");
10781
10928
  }
10782
10929
  function runtimeStatusRunCompletionDir(config) {
10783
10930
  const explicit = config.AMASTER_RUN_COMPLETION_STATE_DIR ?? config.runCompletionStateDir;
10784
- if (typeof explicit === "string" && explicit.trim()) return resolve7(explicit);
10931
+ if (typeof explicit === "string" && explicit.trim()) return resolve8(explicit);
10785
10932
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
10786
- return join11(dirname7(stateFilePath({
10933
+ return join12(dirname8(stateFilePath({
10787
10934
  AMASTER_DAEMON_STATE_FILE: statePath
10788
10935
  })), "run-completion-state");
10789
10936
  }
10790
10937
  function countRuntimeStatusJsonEntries(dir) {
10791
- if (!existsSync9(dir)) return 0;
10938
+ if (!existsSync10(dir)) return 0;
10792
10939
  return runtimeStatusDirectoryEntries(dir).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).length;
10793
10940
  }
10794
10941
  function summarizeRuntimeLocalState(input) {
10795
10942
  const config = input.config ?? {};
10796
- const root = resolve7(String(config.AMASTER_RUNTIME_WORKSPACES_ROOT ?? config.runtimeWorkspacesRoot ?? input.runtimeWorkspacesRoot ?? ""));
10943
+ const root = resolve8(String(config.AMASTER_RUNTIME_WORKSPACES_ROOT ?? config.runtimeWorkspacesRoot ?? input.runtimeWorkspacesRoot ?? ""));
10797
10944
  const now = input.now instanceof Date ? input.now : /* @__PURE__ */ new Date();
10798
10945
  const workdirs = walkRuntimeStatusManagedWorkdirs(root);
10799
10946
  let managedWorkdirBytes = 0;
@@ -10820,9 +10967,9 @@ function summarizeRuntimeLocalState(input) {
10820
10967
  }
10821
10968
  }
10822
10969
  const pendingOutboxDir = runtimeStatusOutboxDir(config);
10823
- const invalidOutboxDir = join11(pendingOutboxDir, "invalid");
10970
+ const invalidOutboxDir = join12(pendingOutboxDir, "invalid");
10824
10971
  const pendingRunCompletionDir = runtimeStatusRunCompletionDir(config);
10825
- const invalidRunCompletionDir = join11(pendingRunCompletionDir, "invalid");
10972
+ const invalidRunCompletionDir = join12(pendingRunCompletionDir, "invalid");
10826
10973
  return {
10827
10974
  managedWorkspacesRoot: root,
10828
10975
  managedWorkdirCount: workdirs.length,
@@ -10945,9 +11092,9 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
10945
11092
 
10946
11093
  // src/amaster-runtime-daemon/workspace-status.mjs
10947
11094
  import { spawnSync as spawnSync4 } from "node:child_process";
10948
- import { createHash as createHash11 } from "node:crypto";
10949
- import { existsSync as existsSync10, readdirSync as readdirSync8, readFileSync as readFileSync10, statSync as statSync7 } from "node:fs";
10950
- import { basename as basename5, extname, isAbsolute as isAbsolute5, join as join12, relative as relative5, resolve as resolve8 } from "node:path";
11095
+ import { createHash as createHash12 } from "node:crypto";
11096
+ import { existsSync as existsSync11, readdirSync as readdirSync9, readFileSync as readFileSync11, statSync as statSync7 } from "node:fs";
11097
+ import { basename as basename5, extname as extname2, isAbsolute as isAbsolute6, join as join13, relative as relative5, resolve as resolve9 } from "node:path";
10951
11098
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
10952
11099
  var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
10953
11100
  [".md", "markdown"],
@@ -10993,7 +11140,7 @@ var SAFE_RUNTIME_SERVICE_HEALTH_STATUSES = /* @__PURE__ */ new Set(["unknown", "
10993
11140
  var SAFE_RUNTIME_SERVICE_LIFECYCLES = /* @__PURE__ */ new Set(["shared", "ephemeral"]);
10994
11141
  function statusPathWithin(candidate, root) {
10995
11142
  const rel = relative5(root, candidate);
10996
- return rel === "" || !rel.startsWith("..") && !isAbsolute5(rel);
11143
+ return rel === "" || !rel.startsWith("..") && !isAbsolute6(rel);
10997
11144
  }
10998
11145
  function normalizeRelativePath(root, filePath) {
10999
11146
  return relative5(root, filePath).split(/[\\/]+/).join("/");
@@ -11016,7 +11163,7 @@ function sanitizeTrackedChange(line) {
11016
11163
  return isSafeRelativePath(path) ? line : null;
11017
11164
  }
11018
11165
  function sha256File(filePath) {
11019
- return createHash11("sha256").update(readFileSync10(filePath)).digest("hex");
11166
+ return createHash12("sha256").update(readFileSync11(filePath)).digest("hex");
11020
11167
  }
11021
11168
  function artifactHashCacheKey(relativePath, stat) {
11022
11169
  return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
@@ -11044,7 +11191,7 @@ function artifactSha256(filePath, relativePath, stat, opts = {}) {
11044
11191
  return hash;
11045
11192
  }
11046
11193
  function scanArtifactCandidates(cwd, opts = {}) {
11047
- const root = resolve8(cwd);
11194
+ const root = resolve9(cwd);
11048
11195
  const maxCandidates = opts.maxCandidates ?? MAX_CANDIDATES;
11049
11196
  const maxEntries = opts.maxEntries ?? MAX_SCAN_ENTRIES;
11050
11197
  const candidates = [];
@@ -11054,7 +11201,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
11054
11201
  const current = stack.pop();
11055
11202
  let entries;
11056
11203
  try {
11057
- entries = readdirSync8(current, { withFileTypes: true });
11204
+ entries = readdirSync9(current, { withFileTypes: true });
11058
11205
  } catch {
11059
11206
  continue;
11060
11207
  }
@@ -11065,7 +11212,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
11065
11212
  if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
11066
11213
  if (entry.name === ".git") continue;
11067
11214
  }
11068
- const fullPath = join12(current, entry.name);
11215
+ const fullPath = join13(current, entry.name);
11069
11216
  const relativePath = normalizeRelativePath(root, fullPath);
11070
11217
  if (!isSafeRelativePath(relativePath)) continue;
11071
11218
  if (basename5(relativePath) === ".amaster-runtime.json") continue;
@@ -11075,7 +11222,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
11075
11222
  continue;
11076
11223
  }
11077
11224
  if (!entry.isFile()) continue;
11078
- const ext = extname(entry.name).toLowerCase();
11225
+ const ext = extname2(entry.name).toLowerCase();
11079
11226
  const type = ARTIFACT_EXTENSIONS.get(ext) ?? "file";
11080
11227
  let stat;
11081
11228
  try {
@@ -11083,7 +11230,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
11083
11230
  } catch {
11084
11231
  continue;
11085
11232
  }
11086
- if (!statusPathWithin(resolve8(fullPath), root) || stat.size > MAX_HASH_BYTES) continue;
11233
+ if (!statusPathWithin(resolve9(fullPath), root) || stat.size > MAX_HASH_BYTES) continue;
11087
11234
  candidates.push({
11088
11235
  relativePath,
11089
11236
  name: basename5(fullPath),
@@ -11143,10 +11290,10 @@ function sanitizeRuntimeService(entry) {
11143
11290
  };
11144
11291
  }
11145
11292
  function readRuntimeServicesSnapshot(cwd) {
11146
- const snapshotPath = join12(resolve8(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
11147
- if (!existsSync10(snapshotPath)) return [];
11293
+ const snapshotPath = join13(resolve9(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
11294
+ if (!existsSync11(snapshotPath)) return [];
11148
11295
  try {
11149
- const parsed = JSON.parse(readFileSync10(snapshotPath, "utf8"));
11296
+ const parsed = JSON.parse(readFileSync11(snapshotPath, "utf8"));
11150
11297
  const rawServices = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.services) ? parsed.services : [];
11151
11298
  return rawServices.map((entry) => sanitizeRuntimeService(entry)).filter((entry) => entry !== null).slice(0, 50);
11152
11299
  } catch {
@@ -11376,18 +11523,18 @@ async function executeBrowserSessionCommand(command, dependencies = {}) {
11376
11523
  }
11377
11524
 
11378
11525
  // src/amaster-runtime-daemon/browser-session-broker.mjs
11379
- import { createHash as createHash12 } from "node:crypto";
11526
+ import { createHash as createHash13 } from "node:crypto";
11380
11527
  import {
11381
- chmodSync as chmodSync5,
11382
- existsSync as existsSync11,
11383
- lstatSync as lstatSync5,
11384
- mkdirSync as mkdirSync7,
11385
- readFileSync as readFileSync11,
11386
- rmSync as rmSync6,
11528
+ chmodSync as chmodSync6,
11529
+ existsSync as existsSync12,
11530
+ lstatSync as lstatSync6,
11531
+ mkdirSync as mkdirSync8,
11532
+ readFileSync as readFileSync12,
11533
+ rmSync as rmSync7,
11387
11534
  statSync as statSync8,
11388
- writeFileSync as writeFileSync8
11535
+ writeFileSync as writeFileSync9
11389
11536
  } from "node:fs";
11390
- import { dirname as dirname8, join as join13, relative as relative6, resolve as resolve9 } from "node:path";
11537
+ import { dirname as dirname9, join as join14, relative as relative6, resolve as resolve10 } from "node:path";
11391
11538
  var MARKER_NAME = ".amaster-browser-session.json";
11392
11539
  var HUMAN_LEASE_HARD_CAP_MS = 2 * 60 * 60 * 1e3;
11393
11540
  function brokerError(code) {
@@ -11407,19 +11554,19 @@ function ensureExecutable(path) {
11407
11554
  }
11408
11555
  }
11409
11556
  function ensurePrivateRoot(stateRoot) {
11410
- const root = resolve9(stateRoot);
11411
- if (existsSync11(root) && lstatSync5(root).isSymbolicLink()) {
11557
+ const root = resolve10(stateRoot);
11558
+ if (existsSync12(root) && lstatSync6(root).isSymbolicLink()) {
11412
11559
  throw brokerError("browser_session_profile_root_symlink");
11413
11560
  }
11414
- mkdirSync7(root, { recursive: true, mode: 448 });
11415
- chmodSync5(root, 448);
11416
- if (lstatSync5(root).isSymbolicLink()) {
11561
+ mkdirSync8(root, { recursive: true, mode: 448 });
11562
+ chmodSync6(root, 448);
11563
+ if (lstatSync6(root).isSymbolicLink()) {
11417
11564
  throw brokerError("browser_session_profile_root_symlink");
11418
11565
  }
11419
11566
  return root;
11420
11567
  }
11421
11568
  function profileName(payload) {
11422
- return createHash12("sha256").update(`${payload.companyId}\0${payload.bindingId}\0${payload.localOpaqueRef}`).digest("hex");
11569
+ return createHash13("sha256").update(`${payload.companyId}\0${payload.bindingId}\0${payload.localOpaqueRef}`).digest("hex");
11423
11570
  }
11424
11571
  function expectedOwner(payload) {
11425
11572
  return {
@@ -11433,30 +11580,30 @@ function expectedOwner(payload) {
11433
11580
  }
11434
11581
  function exactProfile(stateRoot, payload, { create = false } = {}) {
11435
11582
  const root = ensurePrivateRoot(stateRoot);
11436
- const profilePath = resolve9(root, profileName(payload));
11437
- if (!pathWithin3(profilePath, root) || dirname8(profilePath) !== root) {
11583
+ const profilePath = resolve10(root, profileName(payload));
11584
+ if (!pathWithin3(profilePath, root) || dirname9(profilePath) !== root) {
11438
11585
  throw brokerError("browser_session_profile_path_invalid");
11439
11586
  }
11440
- if (existsSync11(profilePath) && lstatSync5(profilePath).isSymbolicLink()) {
11587
+ if (existsSync12(profilePath) && lstatSync6(profilePath).isSymbolicLink()) {
11441
11588
  throw brokerError("browser_session_profile_symlink");
11442
11589
  }
11443
- if (!existsSync11(profilePath)) {
11590
+ if (!existsSync12(profilePath)) {
11444
11591
  if (!create) throw brokerError("browser_session_profile_not_found");
11445
- mkdirSync7(profilePath, { mode: 448 });
11446
- chmodSync5(profilePath, 448);
11447
- writeFileSync8(
11448
- join13(profilePath, MARKER_NAME),
11592
+ mkdirSync8(profilePath, { mode: 448 });
11593
+ chmodSync6(profilePath, 448);
11594
+ writeFileSync9(
11595
+ join14(profilePath, MARKER_NAME),
11449
11596
  `${JSON.stringify(expectedOwner(payload))}
11450
11597
  `,
11451
11598
  { encoding: "utf8", mode: 384, flag: "wx" }
11452
11599
  );
11453
11600
  }
11454
- if (!lstatSync5(profilePath).isDirectory() || lstatSync5(profilePath).isSymbolicLink()) {
11601
+ if (!lstatSync6(profilePath).isDirectory() || lstatSync6(profilePath).isSymbolicLink()) {
11455
11602
  throw brokerError("browser_session_profile_path_invalid");
11456
11603
  }
11457
11604
  let owner;
11458
11605
  try {
11459
- owner = JSON.parse(readFileSync11(join13(profilePath, MARKER_NAME), "utf8"));
11606
+ owner = JSON.parse(readFileSync12(join14(profilePath, MARKER_NAME), "utf8"));
11460
11607
  } catch {
11461
11608
  throw brokerError("browser_session_profile_owner_invalid");
11462
11609
  }
@@ -11607,7 +11754,7 @@ function createBrowserSessionBroker({
11607
11754
  await existing.context.close();
11608
11755
  active.delete(payload.localOpaqueRef);
11609
11756
  }
11610
- rmSync6(profilePath, { recursive: true, force: false });
11757
+ rmSync7(profilePath, { recursive: true, force: false });
11611
11758
  return {
11612
11759
  bindingId: payload.bindingId,
11613
11760
  localOpaqueRef: payload.localOpaqueRef,
@@ -11632,11 +11779,11 @@ function createBrowserSessionBroker({
11632
11779
  throw brokerError("browser_session_agent_lease_expired");
11633
11780
  }
11634
11781
  const root = ensurePrivateRoot(stateRoot);
11635
- const expectedPath = resolve9(root, profileName(payload));
11636
- if (resolve9(payload.userDataDir) !== expectedPath) {
11782
+ const expectedPath = resolve10(root, profileName(payload));
11783
+ if (resolve10(payload.userDataDir) !== expectedPath) {
11637
11784
  throw brokerError("browser_session_profile_path_invalid");
11638
11785
  }
11639
- const marker = JSON.parse(readFileSync11(join13(expectedPath, MARKER_NAME), "utf8"));
11786
+ const marker = JSON.parse(readFileSync12(join14(expectedPath, MARKER_NAME), "utf8"));
11640
11787
  if (marker.version !== 1 || typeof marker.provider !== "string" || !marker.provider.trim() || marker.companyId !== payload.companyId || marker.bindingId !== payload.bindingId || marker.localOpaqueRef !== payload.localOpaqueRef || marker.origin !== payload.origin) {
11641
11788
  throw brokerError("browser_session_profile_owner_mismatch");
11642
11789
  }
@@ -11686,7 +11833,7 @@ var source_acquisition_compatibility_default = {
11686
11833
  };
11687
11834
 
11688
11835
  // src/amaster-runtime-daemon.mjs
11689
- var CONNECTOR_VERSION = "0.1.1-beta.85";
11836
+ var CONNECTOR_VERSION = "0.1.1-beta.87";
11690
11837
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
11691
11838
  var SOURCE_ACQUISITION_CAPABILITY = source_acquisition_compatibility_default.profileVersion;
11692
11839
  var daemonRequire = createRequire(import.meta.url);
@@ -11726,11 +11873,11 @@ function updateActiveRunWorkspaceManifest(commandId, manifestPath, patch = {}) {
11726
11873
  }
11727
11874
  function resultOutboxPendingCount(config) {
11728
11875
  const dir = resultOutboxDir(config);
11729
- if (!existsSync12(dir)) return 0;
11876
+ if (!existsSync13(dir)) return 0;
11730
11877
  try {
11731
11878
  let pending = 0;
11732
- for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json"))) {
11733
- if (readValidResultOutboxEntryOrQuarantine(config, file, join14(dir, file))) {
11879
+ for (const file of readdirSync10(dir).filter((name) => name.endsWith(".json"))) {
11880
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join15(dir, file))) {
11734
11881
  pending += 1;
11735
11882
  }
11736
11883
  }
@@ -11741,21 +11888,21 @@ function resultOutboxPendingCount(config) {
11741
11888
  }
11742
11889
  function runCompletionStateDir(config) {
11743
11890
  const explicit = readString(process.env.AMASTER_RUN_COMPLETION_STATE_DIR);
11744
- if (explicit) return resolve10(expandHomePath(explicit));
11745
- return join14(dirname9(stateFilePath(process.env)), "run-completion-state");
11891
+ if (explicit) return resolve11(expandHomePath(explicit));
11892
+ return join15(dirname10(stateFilePath(process.env)), "run-completion-state");
11746
11893
  }
11747
11894
  function runCompletionStateInvalidDir(config) {
11748
- return join14(runCompletionStateDir(config), "invalid");
11895
+ return join15(runCompletionStateDir(config), "invalid");
11749
11896
  }
11750
11897
  function quarantineInvalidRunCompletionState(config, filePath, reason) {
11751
11898
  const invalidDir = runCompletionStateInvalidDir(config);
11752
- mkdirSync8(invalidDir, { recursive: true, mode: 448 });
11753
- const destination = join14(invalidDir, basename6(filePath));
11899
+ mkdirSync9(invalidDir, { recursive: true, mode: 448 });
11900
+ const destination = join15(invalidDir, basename6(filePath));
11754
11901
  try {
11755
- renameSync7(filePath, destination);
11902
+ renameSync8(filePath, destination);
11756
11903
  } catch {
11757
11904
  copyFileSync2(filePath, destination);
11758
- unlinkSync2(filePath);
11905
+ unlinkSync3(filePath);
11759
11906
  }
11760
11907
  process.stderr.write(`AMaster daemon quarantined invalid run completion state ${basename6(filePath)}: ${reason}
11761
11908
  `);
@@ -11803,11 +11950,11 @@ function piCompletionOutputType(event) {
11803
11950
  }
11804
11951
  function resultOutboxActiveRunCommands(config) {
11805
11952
  const dir = resultOutboxDir(config);
11806
- if (!existsSync12(dir)) return [];
11953
+ if (!existsSync13(dir)) return [];
11807
11954
  const outboxPending = resultOutboxPendingCount(config);
11808
11955
  const entries = [];
11809
- for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json")).sort()) {
11810
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join14(dir, file));
11956
+ for (const file of readdirSync10(dir).filter((name) => name.endsWith(".json")).sort()) {
11957
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join15(dir, file));
11811
11958
  if (!entry) continue;
11812
11959
  const activeRun = asRecord(entry.activeRun);
11813
11960
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -11837,12 +11984,12 @@ function resultOutboxActiveRunCommands(config) {
11837
11984
  }
11838
11985
  function resultOutboxFailedRunCommands(config) {
11839
11986
  const dir = resultOutboxInvalidDir(config);
11840
- if (!existsSync12(dir)) return [];
11987
+ if (!existsSync13(dir)) return [];
11841
11988
  const entries = [];
11842
- for (const file of readdirSync9(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
11989
+ for (const file of readdirSync10(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
11843
11990
  let entry;
11844
11991
  try {
11845
- entry = asRecord(JSON.parse(readFileSync12(join14(dir, file), "utf8")));
11992
+ entry = asRecord(JSON.parse(readFileSync13(join15(dir, file), "utf8")));
11846
11993
  } catch {
11847
11994
  continue;
11848
11995
  }
@@ -11905,11 +12052,11 @@ function piExtraArgsDiagnostics(value) {
11905
12052
  }
11906
12053
  function safeExpandPath(value) {
11907
12054
  const text = readString(value);
11908
- return text ? resolve10(expandHomePath(text)) : null;
12055
+ return text ? resolve11(expandHomePath(text)) : null;
11909
12056
  }
11910
12057
  function safeJsonObjectFromFile(filePath) {
11911
12058
  try {
11912
- const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
12059
+ const parsed = JSON.parse(readFileSync13(filePath, "utf8"));
11913
12060
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
11914
12061
  } catch {
11915
12062
  return null;
@@ -11926,7 +12073,7 @@ function safeDirectorySummary(pathValue) {
11926
12073
  }
11927
12074
  let entryCount = 0;
11928
12075
  let truncated = false;
11929
- for (const name of readdirSync9(pathValue)) {
12076
+ for (const name of readdirSync10(pathValue)) {
11930
12077
  if (name.startsWith(".")) continue;
11931
12078
  entryCount += 1;
11932
12079
  if (entryCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
@@ -11950,12 +12097,12 @@ function safeSkillRootSummary(kind, source, pathValue) {
11950
12097
  let truncated = false;
11951
12098
  if (directory.available && pathValue) {
11952
12099
  try {
11953
- for (const name of readdirSync9(pathValue)) {
12100
+ for (const name of readdirSync10(pathValue)) {
11954
12101
  if (name.startsWith(".")) continue;
11955
- const skillDir = join14(pathValue, name);
12102
+ const skillDir = join15(pathValue, name);
11956
12103
  try {
11957
12104
  if (!statSync9(skillDir).isDirectory()) continue;
11958
- if (!existsSync12(join14(skillDir, "SKILL.md"))) continue;
12105
+ if (!existsSync13(join15(skillDir, "SKILL.md"))) continue;
11959
12106
  skillCount += 1;
11960
12107
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
11961
12108
  truncated = true;
@@ -12006,7 +12153,7 @@ function objectKeyCount(value) {
12006
12153
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
12007
12154
  }
12008
12155
  function defaultPiCodingAgentDir() {
12009
- return join14(homedir3(), ".pi", "agent");
12156
+ return join15(homedir3(), ".pi", "agent");
12010
12157
  }
12011
12158
  function piCapabilitySourcesDiagnostics() {
12012
12159
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -12015,14 +12162,14 @@ function piCapabilitySourcesDiagnostics() {
12015
12162
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
12016
12163
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
12017
12164
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
12018
- const userSkillsPath = piAgentHome ? join14(piAgentHome, "skills") : null;
12165
+ const userSkillsPath = piAgentHome ? join15(piAgentHome, "skills") : null;
12019
12166
  const configuredMarketplaceSkillsPath = safeExpandPath(
12020
12167
  process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR
12021
12168
  );
12022
- const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join14(piAgentHome, "marketplace", "skills") : null);
12169
+ const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join15(piAgentHome, "marketplace", "skills") : null);
12023
12170
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
12024
- const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join14(piAgentHome, "mcp.json") : null);
12025
- const settingsConfigPath = piCodingAgentDir ? join14(piCodingAgentDir, "settings.json") : null;
12171
+ const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join15(piAgentHome, "mcp.json") : null);
12172
+ const settingsConfigPath = piCodingAgentDir ? join15(piCodingAgentDir, "settings.json") : null;
12026
12173
  const skillRoots = [
12027
12174
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
12028
12175
  safeSkillRootSummary(
@@ -12142,22 +12289,22 @@ function buildExecutorReadiness(config) {
12142
12289
  function sourceAcquisitionPackageMetadata(packageName) {
12143
12290
  const agentDir = readString(process.env.PI_CODING_AGENT_DIR ?? process.env.PI_AGENT_HOME);
12144
12291
  if (!agentDir) return null;
12145
- const packagePath = join14(
12146
- resolve10(expandHomePath(agentDir)),
12292
+ const packagePath = join15(
12293
+ resolve11(expandHomePath(agentDir)),
12147
12294
  "npm",
12148
12295
  "node_modules",
12149
12296
  ...packageName.split("/"),
12150
12297
  "package.json"
12151
12298
  );
12152
- if (!existsSync12(packagePath)) return null;
12153
- const stat = lstatSync6(packagePath);
12299
+ if (!existsSync13(packagePath)) return null;
12300
+ const stat = lstatSync7(packagePath);
12154
12301
  if (!stat.isFile() || stat.isSymbolicLink()) return null;
12155
12302
  const metadata = readJsonFile2(packagePath);
12156
12303
  return metadata.name === packageName && readString(metadata.version) ? metadata : null;
12157
12304
  }
12158
12305
  function sourceAcquisitionBrowserExecutableReady() {
12159
12306
  const executable = readString(process.env.AMASTER_BROWSER_EXECUTABLE_PATH);
12160
- if (!executable || !isAbsolute6(executable)) return false;
12307
+ if (!executable || !isAbsolute7(executable)) return false;
12161
12308
  try {
12162
12309
  const stat = statSync9(executable);
12163
12310
  return stat.isFile() && (stat.mode & 73) !== 0;
@@ -12248,7 +12395,7 @@ function browserSessionRuntimeReadiness(config) {
12248
12395
  }
12249
12396
  var browserSessionBrokers = /* @__PURE__ */ new Map();
12250
12397
  function browserSessionBrokerFor(config) {
12251
- const key = resolve10(config.browserSessionStateRoot);
12398
+ const key = resolve11(config.browserSessionStateRoot);
12252
12399
  let broker = browserSessionBrokers.get(key);
12253
12400
  if (!broker) {
12254
12401
  const { chromium } = daemonRequire("playwright-core");
@@ -12263,7 +12410,7 @@ function browserSessionBrokerFor(config) {
12263
12410
  }
12264
12411
  function browserSessionRuntimeStatus(config) {
12265
12412
  const readiness = browserSessionRuntimeReadiness(config);
12266
- const broker = browserSessionBrokers.get(resolve10(config.browserSessionStateRoot));
12413
+ const broker = browserSessionBrokers.get(resolve11(config.browserSessionStateRoot));
12267
12414
  return broker ? { ...readiness, ...broker.status() } : readiness;
12268
12415
  }
12269
12416
  function runtimeAdvertisedCapabilities(config, sourceAcquisition, browserSessionBroker) {
@@ -12529,7 +12676,7 @@ AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
12529
12676
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
12530
12677
  AMASTER_CAPABILITIES=${quoteShell(config.capabilities.join(","))}
12531
12678
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
12532
- AMASTER_DAEMON_STATE_FILE=${quoteShell(join14(homedir3(), ".amaster-employee", "runtime-connector-state.json"))}
12679
+ AMASTER_DAEMON_STATE_FILE=${quoteShell(join15(homedir3(), ".amaster-employee", "runtime-connector-state.json"))}
12533
12680
  EOF
12534
12681
 
12535
12682
  set -a
@@ -12755,10 +12902,10 @@ function buildActiveRunCommandStatus(config, entry) {
12755
12902
  const base = {
12756
12903
  ...entry,
12757
12904
  phase: readString(entry.phase) ?? "executing",
12758
- managedWorkdirPresent: entry.workspacePath ? existsSync12(entry.workspacePath) : false,
12905
+ managedWorkdirPresent: entry.workspacePath ? existsSync13(entry.workspacePath) : false,
12759
12906
  outboxPending: resultOutboxPendingCount(config)
12760
12907
  };
12761
- if (!entry.workspacePath || !existsSync12(entry.workspacePath)) return base;
12908
+ if (!entry.workspacePath || !existsSync13(entry.workspacePath)) return base;
12762
12909
  const manifestPath = entry.manifestPath ?? workspaceManifestPath(entry.workspacePath);
12763
12910
  const status = readWorkspaceStatus(entry.workspacePath, { hashCache: workspaceStatusHashCache });
12764
12911
  const artifactCandidates = status.artifacts.slice(0, 20);
@@ -12981,12 +13128,12 @@ async function sourceAcquisitionRuntimeProfile(config, command) {
12981
13128
  throw new Error("source_acquisition_profile_invalid");
12982
13129
  }
12983
13130
  const exactOrigin = sourceAcquisitionExactOrigin(access.exactLocator);
12984
- const profileName2 = createHash13("sha256").update(`${companyId}\0${bindingId}\0${localOpaqueRef}`).digest("hex");
12985
- const stateRoot = resolve10(config.browserSessionStateRoot);
12986
- const userDataDir = resolve10(stateRoot, profileName2);
13131
+ const profileName2 = createHash14("sha256").update(`${companyId}\0${bindingId}\0${localOpaqueRef}`).digest("hex");
13132
+ const stateRoot = resolve11(config.browserSessionStateRoot);
13133
+ const userDataDir = resolve11(stateRoot, profileName2);
12987
13134
  if (!pathWithin2(userDataDir, stateRoot)) throw new Error("source_acquisition_browser_profile_invalid");
12988
- const markerPath = join14(userDataDir, ".amaster-browser-session.json");
12989
- if (!existsSync12(userDataDir) || lstatSync6(userDataDir).isSymbolicLink() || !lstatSync6(userDataDir).isDirectory() || !existsSync12(markerPath) || lstatSync6(markerPath).isSymbolicLink()) throw new Error("source_acquisition_browser_profile_invalid");
13135
+ const markerPath = join15(userDataDir, ".amaster-browser-session.json");
13136
+ if (!existsSync13(userDataDir) || lstatSync7(userDataDir).isSymbolicLink() || !lstatSync7(userDataDir).isDirectory() || !existsSync13(markerPath) || lstatSync7(markerPath).isSymbolicLink()) throw new Error("source_acquisition_browser_profile_invalid");
12990
13137
  const marker = readJsonFile2(markerPath);
12991
13138
  if (marker.version !== 1 || marker.companyId !== companyId || marker.bindingId !== bindingId || marker.localOpaqueRef !== localOpaqueRef || !readString(marker.provider) || marker.origin !== exactOrigin || Object.keys(marker).length !== 6) {
12992
13139
  throw new Error("source_acquisition_browser_profile_invalid");
@@ -13004,7 +13151,7 @@ async function sourceAcquisitionRuntimeProfile(config, command) {
13004
13151
  }
13005
13152
  function readJsonFile2(filePath) {
13006
13153
  try {
13007
- const parsed = JSON.parse(readFileSync12(filePath, "utf8"));
13154
+ const parsed = JSON.parse(readFileSync13(filePath, "utf8"));
13008
13155
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
13009
13156
  } catch {
13010
13157
  return {};
@@ -13045,11 +13192,11 @@ function safeAgentInstructionMaterializationTarget(workspace, filePath) {
13045
13192
  const raw = readString(filePath);
13046
13193
  if (!raw || raw.includes("\0")) return null;
13047
13194
  const normalized = raw.replace(/\\/g, "/");
13048
- if (isAbsolute6(normalized)) return null;
13195
+ if (isAbsolute7(normalized)) return null;
13049
13196
  const segments = normalized.split("/").filter(Boolean);
13050
13197
  if (segments.length === 0 || segments.some((segment) => segment === "." || segment === "..")) return null;
13051
13198
  const relativePath = segments.join("/");
13052
- const targetPath = resolve10(workspace.cwd, relativePath);
13199
+ const targetPath = resolve11(workspace.cwd, relativePath);
13053
13200
  if (!pathWithin2(targetPath, workspace.cwd)) return null;
13054
13201
  return { relativePath, targetPath };
13055
13202
  }
@@ -13063,8 +13210,8 @@ async function materializeAgentInstructionsBundle(config, command, workspace, bu
13063
13210
  if (!content) continue;
13064
13211
  const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
13065
13212
  if (!target) continue;
13066
- mkdirSync8(dirname9(target.targetPath), { recursive: true });
13067
- writeFileSync9(target.targetPath, content, "utf8");
13213
+ mkdirSync9(dirname10(target.targetPath), { recursive: true });
13214
+ writeFileSync10(target.targetPath, content, "utf8");
13068
13215
  materialized.push({
13069
13216
  path: target.relativePath,
13070
13217
  byteSize: Buffer.byteLength(content, "utf8")
@@ -13091,11 +13238,11 @@ function wikiTreePathForCommand(command, workspaceBindings) {
13091
13238
  const candidates = [];
13092
13239
  if (root.endsWith("paperclipai.plugin-llm-wiki")) candidates.push(root);
13093
13240
  if (basename6(root) === "plugin-data" && companyId) {
13094
- candidates.push(join14(root, companyId, "paperclipai.plugin-llm-wiki"));
13241
+ candidates.push(join15(root, companyId, "paperclipai.plugin-llm-wiki"));
13095
13242
  }
13096
13243
  for (const candidate of candidates) {
13097
13244
  try {
13098
- if (existsSync12(candidate)) return candidate;
13245
+ if (existsSync13(candidate)) return candidate;
13099
13246
  } catch {
13100
13247
  }
13101
13248
  }
@@ -13235,18 +13382,18 @@ function buildExecutorEnv(config, command, workspace) {
13235
13382
  };
13236
13383
  }
13237
13384
  function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
13238
- const profileRoot = mkdtempSync(join14(tmpdir(), "amaster-pi-model-call-"));
13239
- const home = join14(profileRoot, "home");
13240
- const sessionsDir = join14(profileRoot, "sessions");
13241
- const tempDir = join14(profileRoot, "tmp");
13385
+ const profileRoot = mkdtempSync2(join15(tmpdir(), "amaster-pi-model-call-"));
13386
+ const home = join15(profileRoot, "home");
13387
+ const sessionsDir = join15(profileRoot, "sessions");
13388
+ const tempDir = join15(profileRoot, "tmp");
13242
13389
  for (const directory of [home, sessionsDir, tempDir]) {
13243
- mkdirSync8(directory, { recursive: true, mode: 448 });
13390
+ mkdirSync9(directory, { recursive: true, mode: 448 });
13244
13391
  }
13245
13392
  try {
13246
13393
  const extensionArgs = [];
13247
13394
  if (options.responseContract) {
13248
- const extensionPath = join14(profileRoot, "model-call-output-contract.js");
13249
- writeFileSync9(
13395
+ const extensionPath = join15(profileRoot, "model-call-output-contract.js");
13396
+ writeFileSync10(
13250
13397
  extensionPath,
13251
13398
  modelCallOutputContractExtensionSource(options.responseContract.maxOutputTokens),
13252
13399
  { mode: 384 }
@@ -13266,12 +13413,12 @@ function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
13266
13413
  }
13267
13414
  };
13268
13415
  } catch (error) {
13269
- rmSync7(profileRoot, { recursive: true, force: true });
13416
+ rmSync8(profileRoot, { recursive: true, force: true });
13270
13417
  throw error;
13271
13418
  }
13272
13419
  }
13273
13420
  function cleanupPiModelCallProfile(profile) {
13274
- if (profile?.profileRoot) rmSync7(profile.profileRoot, { recursive: true, force: true });
13421
+ if (profile?.profileRoot) rmSync8(profile.profileRoot, { recursive: true, force: true });
13275
13422
  }
13276
13423
  function splitExtraArgs(value) {
13277
13424
  return splitList(value).flatMap((entry) => entry.split(/\s+/).filter(Boolean));
@@ -13311,7 +13458,7 @@ function resolveNativeSessionRequest(command, workspace) {
13311
13458
  try {
13312
13459
  cwdMatched = realpathSync5(requestedCwd) === realpathSync5(sourceWorkspacePath);
13313
13460
  } catch {
13314
- cwdMatched = resolve10(requestedCwd) === resolve10(sourceWorkspacePath);
13461
+ cwdMatched = resolve11(requestedCwd) === resolve11(sourceWorkspacePath);
13315
13462
  }
13316
13463
  }
13317
13464
  const used = Boolean(enabled && requested && sessionId && requestedCwd && cwdMatched);
@@ -13896,10 +14043,10 @@ function realOrResolvedPath(value) {
13896
14043
  try {
13897
14044
  return realpathSync5(value);
13898
14045
  } catch {
13899
- return resolve10(value);
14046
+ return resolve11(value);
13900
14047
  }
13901
14048
  }
13902
- var LSOF_COMMAND = process.platform === "darwin" && existsSync12("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
14049
+ var LSOF_COMMAND = process.platform === "darwin" && existsSync13("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
13903
14050
  function processCwdForPid(pid) {
13904
14051
  if (process.platform === "linux") {
13905
14052
  try {
@@ -13925,7 +14072,7 @@ function allProcessCwdsByPid() {
13925
14072
  if (process.platform === "linux") {
13926
14073
  const procEntries = (() => {
13927
14074
  try {
13928
- return readdirSync9("/proc", { withFileTypes: true });
14075
+ return readdirSync10("/proc", { withFileTypes: true });
13929
14076
  } catch {
13930
14077
  return [];
13931
14078
  }
@@ -14021,21 +14168,21 @@ function killWorkspaceResidentProcesses(cwd, processGroupId, options = {}) {
14021
14168
  }
14022
14169
  function walkManagedWorkdirs(root) {
14023
14170
  const workdirs = [];
14024
- if (!root || !existsSync12(root)) return workdirs;
14171
+ if (!root || !existsSync13(root)) return workdirs;
14025
14172
  const stack = [root];
14026
14173
  while (stack.length > 0) {
14027
14174
  const current = stack.pop();
14028
14175
  if (!current) continue;
14029
14176
  let entries = [];
14030
14177
  try {
14031
- entries = readdirSync9(current, { withFileTypes: true });
14178
+ entries = readdirSync10(current, { withFileTypes: true });
14032
14179
  } catch {
14033
14180
  continue;
14034
14181
  }
14035
14182
  for (const entry of entries) {
14036
14183
  if (!entry.isDirectory()) continue;
14037
- const fullPath = join14(current, entry.name);
14038
- if (entry.name === "workdir" && existsSync12(workspaceManifestPath(fullPath))) {
14184
+ const fullPath = join15(current, entry.name);
14185
+ if (entry.name === "workdir" && existsSync13(workspaceManifestPath(fullPath))) {
14039
14186
  workdirs.push(fullPath);
14040
14187
  continue;
14041
14188
  }
@@ -14074,7 +14221,7 @@ function manifestMatchesActiveRuntimeRef(manifest, refs, workdir = null) {
14074
14221
  function buildOrphanReaperSample(root, workdir, manifest, residents) {
14075
14222
  const relativeWorkdir = (() => {
14076
14223
  const value = relative7(root, workdir);
14077
- return value && !value.startsWith("..") && !isAbsolute6(value) ? value : basename6(workdir);
14224
+ return value && !value.startsWith("..") && !isAbsolute7(value) ? value : basename6(workdir);
14078
14225
  })();
14079
14226
  return {
14080
14227
  workdir: relativeWorkdir,
@@ -15539,7 +15686,7 @@ async function flushRunCompletionStates(config) {
15539
15686
  for (const { filePath, state: listedState } of runCompletionStateEntries(config)) {
15540
15687
  try {
15541
15688
  if (runCompletionFlights.has(listedState.commandId)) continue;
15542
- if (!existsSync12(filePath)) continue;
15689
+ if (!existsSync13(filePath)) continue;
15543
15690
  const state = readValidRunCompletionStateOrQuarantine(config, filePath);
15544
15691
  if (!state) continue;
15545
15692
  const outcome = await coordinateRunCompletionSingleFlight(config, state);
@@ -15726,15 +15873,15 @@ async function completeCommand(config, command, status, result3, error) {
15726
15873
  }
15727
15874
  function resultOutboxDir(config) {
15728
15875
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
15729
- if (explicit) return resolve10(expandHomePath(explicit));
15730
- return join14(dirname9(stateFilePath(process.env)), "result-outbox");
15876
+ if (explicit) return resolve11(expandHomePath(explicit));
15877
+ return join15(dirname10(stateFilePath(process.env)), "result-outbox");
15731
15878
  }
15732
15879
  function resultOutboxInvalidDir(config) {
15733
- return join14(resultOutboxDir(config), "invalid");
15880
+ return join15(resultOutboxDir(config), "invalid");
15734
15881
  }
15735
15882
  function writeResultOutboxEntry(config, entry) {
15736
15883
  const dir = resultOutboxDir(config);
15737
- mkdirSync8(dir, { recursive: true });
15884
+ mkdirSync9(dir, { recursive: true });
15738
15885
  const body = {
15739
15886
  version: 1,
15740
15887
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -15742,19 +15889,19 @@ function writeResultOutboxEntry(config, entry) {
15742
15889
  lastAttemptAt: null,
15743
15890
  ...entry
15744
15891
  };
15745
- writeFileSync9(join14(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
15892
+ writeFileSync10(join15(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
15746
15893
  `, { mode: 384 });
15747
15894
  }
15748
15895
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
15749
15896
  const invalidDir = resultOutboxInvalidDir(config);
15750
- mkdirSync8(invalidDir, { recursive: true });
15751
- const invalidPath = join14(invalidDir, file);
15897
+ mkdirSync9(invalidDir, { recursive: true });
15898
+ const invalidPath = join15(invalidDir, file);
15752
15899
  if (original === void 0) {
15753
15900
  try {
15754
- renameSync7(fullPath, invalidPath);
15901
+ renameSync8(fullPath, invalidPath);
15755
15902
  } catch {
15756
15903
  copyFileSync2(fullPath, invalidPath);
15757
- unlinkSync2(fullPath);
15904
+ unlinkSync3(fullPath);
15758
15905
  }
15759
15906
  return;
15760
15907
  }
@@ -15764,14 +15911,14 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
15764
15911
  ...detail ? { detail: truncateText(detail, 1e3) } : {},
15765
15912
  original
15766
15913
  };
15767
- writeFileSync9(invalidPath, `${JSON.stringify(evidence, null, 2)}
15914
+ writeFileSync10(invalidPath, `${JSON.stringify(evidence, null, 2)}
15768
15915
  `, { mode: 384 });
15769
- unlinkSync2(fullPath);
15916
+ unlinkSync3(fullPath);
15770
15917
  }
15771
15918
  function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
15772
15919
  let entry;
15773
15920
  try {
15774
- entry = JSON.parse(readFileSync12(fullPath, "utf8"));
15921
+ entry = JSON.parse(readFileSync13(fullPath, "utf8"));
15775
15922
  } catch (err) {
15776
15923
  const message = err instanceof Error ? err.message : String(err);
15777
15924
  moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
@@ -15801,13 +15948,13 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
15801
15948
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
15802
15949
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
15803
15950
  };
15804
- writeFileSync9(fullPath, `${JSON.stringify(next, null, 2)}
15951
+ writeFileSync10(fullPath, `${JSON.stringify(next, null, 2)}
15805
15952
  `, { mode: 384 });
15806
15953
  return next;
15807
15954
  }
15808
15955
  function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err) {
15809
15956
  const invalidDir = resultOutboxInvalidDir(config);
15810
- mkdirSync8(invalidDir, { recursive: true });
15957
+ mkdirSync9(invalidDir, { recursive: true });
15811
15958
  const body = {
15812
15959
  ...entry,
15813
15960
  invalidReason: reason,
@@ -15815,11 +15962,11 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
15815
15962
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
15816
15963
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
15817
15964
  };
15818
- const invalidPath = join14(invalidDir, file);
15819
- writeFileSync9(invalidPath, `${JSON.stringify(body, null, 2)}
15965
+ const invalidPath = join15(invalidDir, file);
15966
+ writeFileSync10(invalidPath, `${JSON.stringify(body, null, 2)}
15820
15967
  `, { mode: 384 });
15821
15968
  try {
15822
- unlinkSync2(fullPath);
15969
+ unlinkSync3(fullPath);
15823
15970
  } catch (unlinkErr) {
15824
15971
  const message = unlinkErr instanceof Error ? unlinkErr.message : String(unlinkErr);
15825
15972
  process.stderr.write(`AMaster daemon could not remove quarantined result outbox entry ${file}: ${message}
@@ -15830,16 +15977,16 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
15830
15977
  }
15831
15978
  async function flushResultOutbox(config) {
15832
15979
  const dir = resultOutboxDir(config);
15833
- if (!existsSync12(dir)) return { attempted: 0, completed: 0 };
15834
- const files = readdirSync9(dir).filter((name) => name.endsWith(".json")).sort();
15980
+ if (!existsSync13(dir)) return { attempted: 0, completed: 0 };
15981
+ const files = readdirSync10(dir).filter((name) => name.endsWith(".json")).sort();
15835
15982
  let completed = 0;
15836
15983
  for (const file of files) {
15837
- const fullPath = join14(dir, file);
15984
+ const fullPath = join15(dir, file);
15838
15985
  const entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
15839
15986
  if (!entry) continue;
15840
15987
  try {
15841
15988
  await postJson(config, String(entry.path), entry.payload);
15842
- unlinkSync2(fullPath);
15989
+ unlinkSync3(fullPath);
15843
15990
  clearDeliveredResultOutboxCommand(config, entry);
15844
15991
  completed += 1;
15845
15992
  } catch (err) {
@@ -16031,8 +16178,8 @@ async function materializeIssueAttachments(config, command, workspace) {
16031
16178
  runtimeAuth,
16032
16179
  issueId
16033
16180
  );
16034
- const targetDir = join14(workspace.cwd, "input-attachments");
16035
- mkdirSync8(targetDir, { recursive: true });
16181
+ const targetDir = join15(workspace.cwd, "input-attachments");
16182
+ mkdirSync9(targetDir, { recursive: true });
16036
16183
  const usedFilenames = /* @__PURE__ */ new Set();
16037
16184
  const materialized = [];
16038
16185
  for (const [index, rawAttachment] of attachments.entries()) {
@@ -16041,16 +16188,16 @@ async function materializeIssueAttachments(config, command, workspace) {
16041
16188
  if (!contentPath) continue;
16042
16189
  let filename = safeMaterializedAttachmentFilename(attachment, index);
16043
16190
  if (usedFilenames.has(filename)) {
16044
- const ext = extname2(filename);
16191
+ const ext = extname3(filename);
16045
16192
  const stem = ext ? filename.slice(0, -ext.length) : filename;
16046
16193
  filename = `${stem}-${index + 1}${ext}`;
16047
16194
  }
16048
16195
  usedFilenames.add(filename);
16049
- const targetPath = join14(targetDir, filename);
16196
+ const targetPath = join15(targetDir, filename);
16050
16197
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
16051
- writeFileSync9(targetPath, body);
16198
+ writeFileSync10(targetPath, body);
16052
16199
  const attachmentId = readString(attachment.id);
16053
- const actualSha256 = createHash13("sha256").update(body).digest("hex");
16200
+ const actualSha256 = createHash14("sha256").update(body).digest("hex");
16054
16201
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
16055
16202
  const lineage = selectAttachmentLineage(lineageCandidates, actualSha256);
16056
16203
  if (lineageCandidates.length > 0 && !lineage) {
@@ -16122,19 +16269,19 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16122
16269
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
16123
16270
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
16124
16271
  }
16125
- const targetRoot = join14(workspace.cwd, "input-artifacts");
16126
- rmSync7(targetRoot, { recursive: true, force: true });
16127
- mkdirSync8(targetRoot, { recursive: true });
16272
+ const targetRoot = join15(workspace.cwd, "input-artifacts");
16273
+ rmSync8(targetRoot, { recursive: true, force: true });
16274
+ mkdirSync9(targetRoot, { recursive: true });
16128
16275
  const usedPaths = /* @__PURE__ */ new Set();
16129
16276
  const materialized = [];
16130
16277
  for (const [index, rawEntry] of manifest.entries.entries()) {
16131
16278
  const entry = asRecord(rawEntry);
16132
16279
  const workProductId = readString(entry.workProductId);
16133
16280
  const attachmentId = readString(entry.attachmentId);
16134
- const sha2562 = readString(entry.sha256);
16281
+ const sha2563 = readString(entry.sha256);
16135
16282
  const contentPath = readString(entry.contentPath);
16136
16283
  const byteSize = readNumber(entry.byteSize, null);
16137
- if (!workProductId || !attachmentId || !/^[a-f0-9]{64}$/i.test(sha2562 ?? "") || !contentPath || byteSize === null) {
16284
+ if (!workProductId || !attachmentId || !/^[a-f0-9]{64}$/i.test(sha2563 ?? "") || !contentPath || byteSize === null) {
16138
16285
  throw new Error(`artifact_input_manifest_invalid: entry ${index} is incomplete`);
16139
16286
  }
16140
16287
  const expectedContentPath = `/api/attachments/${attachmentId}/content`;
@@ -16142,10 +16289,10 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16142
16289
  throw new Error(`artifact_input_manifest_invalid: entry ${index} contentPath does not match attachmentId`);
16143
16290
  }
16144
16291
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
16145
- const actualSha256 = createHash13("sha256").update(body).digest("hex");
16146
- if (body.byteLength !== byteSize || actualSha256 !== sha2562) {
16292
+ const actualSha256 = createHash14("sha256").update(body).digest("hex");
16293
+ if (body.byteLength !== byteSize || actualSha256 !== sha2563) {
16147
16294
  throw new Error(
16148
- `artifact_input_integrity_mismatch: workProductId=${workProductId} expectedBytes=${byteSize} actualBytes=${body.byteLength} expectedSha256=${sha2562} actualSha256=${actualSha256}`
16295
+ `artifact_input_integrity_mismatch: workProductId=${workProductId} expectedBytes=${byteSize} actualBytes=${body.byteLength} expectedSha256=${sha2563} actualSha256=${actualSha256}`
16149
16296
  );
16150
16297
  }
16151
16298
  const sourceDir = safeArtifactInputSourceDir(entry, index);
@@ -16153,18 +16300,18 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16153
16300
  id: attachmentId,
16154
16301
  originalFilename: readString(entry.originalFilename)
16155
16302
  }, index);
16156
- let relativePath = join14("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
16303
+ let relativePath = join15("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
16157
16304
  if (usedPaths.has(relativePath)) {
16158
- const ext = extname2(filename);
16305
+ const ext = extname3(filename);
16159
16306
  const stem = ext ? filename.slice(0, -ext.length) : filename;
16160
16307
  filename = `${stem}-${index + 1}${ext}`;
16161
- relativePath = join14("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
16308
+ relativePath = join15("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
16162
16309
  }
16163
16310
  usedPaths.add(relativePath);
16164
- const targetPath = join14(workspace.cwd, relativePath);
16165
- mkdirSync8(dirname9(targetPath), { recursive: true });
16166
- writeFileSync9(targetPath, body);
16167
- chmodSync6(targetPath, 292);
16311
+ const targetPath = join15(workspace.cwd, relativePath);
16312
+ mkdirSync9(dirname10(targetPath), { recursive: true });
16313
+ writeFileSync10(targetPath, body);
16314
+ chmodSync7(targetPath, 292);
16168
16315
  materialized.push({
16169
16316
  id: attachmentId,
16170
16317
  workProductId,
@@ -16175,7 +16322,7 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16175
16322
  relativePath,
16176
16323
  contentType: readString(entry.contentType),
16177
16324
  byteSize: body.byteLength,
16178
- sha256: sha2562,
16325
+ sha256: sha2563,
16179
16326
  contentPath
16180
16327
  });
16181
16328
  }
@@ -16183,9 +16330,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16183
16330
  version: 1,
16184
16331
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
16185
16332
  };
16186
- const manifestPath = join14(targetRoot, "artifact-input-manifest.json");
16187
- writeFileSync9(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
16188
- chmodSync6(manifestPath, 292);
16333
+ const manifestPath = join15(targetRoot, "artifact-input-manifest.json");
16334
+ writeFileSync10(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
16335
+ chmodSync7(manifestPath, 292);
16189
16336
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
16190
16337
  await ingestLog(config, command, "system", "info", `Materialized ${materialized.length} required artifact input(s) into the execution workspace`, {
16191
16338
  artifactInputCount: materialized.length,
@@ -16194,46 +16341,46 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
16194
16341
  return materialized;
16195
16342
  }
16196
16343
  function issueCheckpointDir(workspace) {
16197
- return join14(dirname9(workspace.runDir), "checkpoint");
16344
+ return join15(dirname10(workspace.runDir), "checkpoint");
16198
16345
  }
16199
16346
  async function clearIssueCheckpoint(config, command, workspace, reason) {
16200
16347
  const checkpointDir = issueCheckpointDir(workspace);
16201
- if (!existsSync12(checkpointDir)) return false;
16202
- rmSync7(checkpointDir, { recursive: true, force: true });
16348
+ if (!existsSync13(checkpointDir)) return false;
16349
+ rmSync8(checkpointDir, { recursive: true, force: true });
16203
16350
  await ingestLog(config, command, "system", "info", "Cleared issue continuation checkpoint", { reason });
16204
16351
  return true;
16205
16352
  }
16206
16353
  function safeCheckpointRelativePath(rawPath) {
16207
16354
  const raw = String(rawPath ?? "").trim();
16208
- if (isAbsolute6(raw) || /^[A-Za-z]:[\\/]/.test(raw)) return null;
16355
+ if (isAbsolute7(raw) || /^[A-Za-z]:[\\/]/.test(raw)) return null;
16209
16356
  const normalized = raw.split(/[\\/]+/).filter(Boolean).join("/");
16210
16357
  if (!normalized || normalized.startsWith("../") || normalized.split("/").some((segment) => segment.startsWith("."))) return null;
16211
16358
  if (normalized.startsWith("input-attachments/") || isRuntimeMetadataArtifactPath(normalized)) return null;
16212
16359
  return normalized;
16213
16360
  }
16214
16361
  function hashFileSha256(filePath) {
16215
- return createHash13("sha256").update(readFileSync12(filePath)).digest("hex");
16362
+ return createHash14("sha256").update(readFileSync13(filePath)).digest("hex");
16216
16363
  }
16217
16364
  async function materializeIssueCheckpoint(config, command, workspace) {
16218
16365
  const checkpointDir = issueCheckpointDir(workspace);
16219
- const manifestPath = join14(checkpointDir, "manifest.json");
16220
- if (!existsSync12(manifestPath)) return [];
16366
+ const manifestPath = join15(checkpointDir, "manifest.json");
16367
+ if (!existsSync13(manifestPath)) return [];
16221
16368
  let manifest;
16222
16369
  try {
16223
- manifest = asRecord(JSON.parse(readFileSync12(manifestPath, "utf8")));
16370
+ manifest = asRecord(JSON.parse(readFileSync13(manifestPath, "utf8")));
16224
16371
  } catch (err) {
16225
- rmSync7(checkpointDir, { recursive: true, force: true });
16372
+ rmSync8(checkpointDir, { recursive: true, force: true });
16226
16373
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
16227
16374
  }
16228
16375
  const expiresAt = Date.parse(readString(manifest.expiresAt) ?? "");
16229
16376
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || readString(manifest.issueId) !== commandIssueId(command)) {
16230
- rmSync7(checkpointDir, { recursive: true, force: true });
16377
+ rmSync8(checkpointDir, { recursive: true, force: true });
16231
16378
  return [];
16232
16379
  }
16233
16380
  try {
16234
16381
  const files = Array.isArray(manifest.files) ? manifest.files : [];
16235
16382
  if (files.length > 20) throw new Error("issue checkpoint manifest exceeds the limit of 20 files");
16236
- const filesRoot = realpathSync5(join14(checkpointDir, "files"));
16383
+ const filesRoot = realpathSync5(join15(checkpointDir, "files"));
16237
16384
  const workspaceRoot = realpathSync5(workspace.cwd);
16238
16385
  const validated = [];
16239
16386
  let totalBytes = 0;
@@ -16241,12 +16388,12 @@ async function materializeIssueCheckpoint(config, command, workspace) {
16241
16388
  const file = asRecord(rawFile);
16242
16389
  const relativePath = safeCheckpointRelativePath(readString(file.path));
16243
16390
  if (!relativePath) throw new Error("issue checkpoint manifest contains an invalid file path");
16244
- const sourceCandidate = resolve10(filesRoot, relativePath);
16245
- const target = resolve10(workspaceRoot, relativePath);
16391
+ const sourceCandidate = resolve11(filesRoot, relativePath);
16392
+ const target = resolve11(workspaceRoot, relativePath);
16246
16393
  if (!pathWithin2(sourceCandidate, filesRoot) || !pathWithin2(target, workspaceRoot)) {
16247
16394
  throw new Error(`issue checkpoint path escapes its workspace: ${relativePath}`);
16248
16395
  }
16249
- if (!existsSync12(sourceCandidate)) throw new Error(`issue checkpoint file is missing: ${relativePath}`);
16396
+ if (!existsSync13(sourceCandidate)) throw new Error(`issue checkpoint file is missing: ${relativePath}`);
16250
16397
  const source = realpathSync5(sourceCandidate);
16251
16398
  if (!pathWithin2(source, filesRoot) || !statSync9(source).isFile()) {
16252
16399
  throw new Error(`issue checkpoint source escapes its storage root: ${relativePath}`);
@@ -16266,13 +16413,13 @@ async function materializeIssueCheckpoint(config, command, workspace) {
16266
16413
  const materialized = [];
16267
16414
  for (const { relativePath, source, target } of validated) {
16268
16415
  try {
16269
- lstatSync6(target);
16416
+ lstatSync7(target);
16270
16417
  continue;
16271
16418
  } catch (err) {
16272
16419
  if (err?.code !== "ENOENT") throw err;
16273
16420
  }
16274
- mkdirSync8(dirname9(target), { recursive: true });
16275
- const targetParent = realpathSync5(dirname9(target));
16421
+ mkdirSync9(dirname10(target), { recursive: true });
16422
+ const targetParent = realpathSync5(dirname10(target));
16276
16423
  if (!pathWithin2(targetParent, workspaceRoot)) {
16277
16424
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
16278
16425
  }
@@ -16300,31 +16447,31 @@ async function materializeIssueCheckpoint(config, command, workspace) {
16300
16447
  }
16301
16448
  async function saveIssueCheckpoint(config, command, workspace, candidates) {
16302
16449
  const checkpointDir = issueCheckpointDir(workspace);
16303
- const filesDir = join14(checkpointDir, "files");
16304
- rmSync7(checkpointDir, { recursive: true, force: true });
16305
- mkdirSync8(filesDir, { recursive: true });
16450
+ const filesDir = join15(checkpointDir, "files");
16451
+ rmSync8(checkpointDir, { recursive: true, force: true });
16452
+ mkdirSync9(filesDir, { recursive: true });
16306
16453
  const files = [];
16307
16454
  let totalBytes = 0;
16308
16455
  const workspaceRoot = realpathSync5(workspace.cwd);
16309
16456
  for (const candidate of candidates.slice(0, 20)) {
16310
16457
  const relativePath = safeCheckpointRelativePath(candidate.rawPath);
16311
16458
  const source = readString(candidate.filePath);
16312
- if (!relativePath || !source || !existsSync12(source) || !statSync9(source).isFile()) continue;
16459
+ if (!relativePath || !source || !existsSync13(source) || !statSync9(source).isFile()) continue;
16313
16460
  const ownedSource = realpathSync5(source);
16314
16461
  if (!pathWithin2(ownedSource, workspaceRoot)) {
16315
16462
  throw new Error(`issue checkpoint source escapes its execution workspace: ${relativePath}`);
16316
16463
  }
16317
16464
  const byteSize = statSync9(ownedSource).size;
16318
16465
  if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) continue;
16319
- const target = resolve10(filesDir, relativePath);
16466
+ const target = resolve11(filesDir, relativePath);
16320
16467
  if (!pathWithin2(target, filesDir)) continue;
16321
- mkdirSync8(dirname9(target), { recursive: true });
16468
+ mkdirSync9(dirname10(target), { recursive: true });
16322
16469
  copyFileSync2(ownedSource, target);
16323
16470
  totalBytes += byteSize;
16324
16471
  files.push({ path: relativePath, byteSize, sha256: hashFileSha256(ownedSource) });
16325
16472
  }
16326
16473
  if (files.length === 0) {
16327
- rmSync7(checkpointDir, { recursive: true, force: true });
16474
+ rmSync8(checkpointDir, { recursive: true, force: true });
16328
16475
  return null;
16329
16476
  }
16330
16477
  const manifest = {
@@ -16336,7 +16483,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
16336
16483
  totalBytes,
16337
16484
  files
16338
16485
  };
16339
- writeFileSync9(join14(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
16486
+ writeFileSync10(join15(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
16340
16487
  `);
16341
16488
  await ingestLog(config, command, "system", "warn", `Saved ${files.length} required deliverable(s) for continuation recovery`, manifest);
16342
16489
  return manifest;
@@ -16507,7 +16654,7 @@ async function executeRunCommand(config, command) {
16507
16654
  executorCommand: invocation.command,
16508
16655
  executorHome: workspace.executorHome,
16509
16656
  runDir: workspace.runDir,
16510
- runtimeCacheRoot: join14(dirname9(config.daemonStateFile), "cache"),
16657
+ runtimeCacheRoot: join15(dirname10(config.daemonStateFile), "cache"),
16511
16658
  cwd,
16512
16659
  runtimeAuth: commandRuntimeAuth(command),
16513
16660
  nativeSession: asRecord(asRecord(command.payload).nativeSession),
@@ -16567,7 +16714,7 @@ async function executeRunCommand(config, command) {
16567
16714
  if (executor.kind === "pi" && piResolvedProviderConfig) {
16568
16715
  const sharedPiHome = readString(process.env.PI_CODING_AGENT_DIR) ?? readString(process.env.PI_AGENT_HOME) ?? null;
16569
16716
  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;
16570
- if (agentDir && sharedPiHome && resolve10(agentDir) === resolve10(sharedPiHome)) {
16717
+ if (agentDir && sharedPiHome && resolve11(agentDir) === resolve11(sharedPiHome)) {
16571
16718
  agentDir = null;
16572
16719
  }
16573
16720
  try {
@@ -16849,7 +16996,7 @@ async function executeRunCommand(config, command) {
16849
16996
  workspace,
16850
16997
  workspaceStatus.artifacts.map((artifact) => ({
16851
16998
  rawPath: artifact.relativePath,
16852
- filePath: resolve10(cwd, artifact.relativePath)
16999
+ filePath: resolve11(cwd, artifact.relativePath)
16853
17000
  }))
16854
17001
  );
16855
17002
  nativeSessionRollout = {
@@ -17283,6 +17430,11 @@ function reconcileStaleManagedMcpProfiles(config) {
17283
17430
  }
17284
17431
  }
17285
17432
  async function runOnce(config) {
17433
+ const templates = materializeRuntimePresetTemplates(process.env);
17434
+ if (templates.status === "ready") {
17435
+ process.stderr.write(`MirrorX preset templates ready: files=${templates.fileCount} target=${templates.targetDir}
17436
+ `);
17437
+ }
17286
17438
  reconcileStaleManagedMcpProfiles(config);
17287
17439
  config = await ensureRegistered(config);
17288
17440
  try {
@@ -17408,6 +17560,11 @@ function statusSummary(config) {
17408
17560
  `);
17409
17561
  }
17410
17562
  async function runLoop(config) {
17563
+ const templates = materializeRuntimePresetTemplates(process.env);
17564
+ if (templates.status === "ready") {
17565
+ process.stderr.write(`MirrorX preset templates ready: files=${templates.fileCount} target=${templates.targetDir}
17566
+ `);
17567
+ }
17411
17568
  process.stderr.write(
17412
17569
  `AMaster daemon runtime safety controls resolved: pi_guard_mode=${config.piToolArgumentGuard.mode}
17413
17570
  `
@@ -17427,7 +17584,7 @@ async function runLoop(config) {
17427
17584
  ${message}
17428
17585
  `);
17429
17586
  }
17430
- await new Promise((resolve11) => setTimeout(resolve11, config.pollIntervalSeconds * 1e3));
17587
+ await new Promise((resolve12) => setTimeout(resolve12, config.pollIntervalSeconds * 1e3));
17431
17588
  }
17432
17589
  }
17433
17590
  function help() {
@@ -17454,6 +17611,7 @@ Key env:
17454
17611
  AMASTER_NETWORK_DOMAINS, AMASTER_CONNECTOR_ID, AMASTER_DAEMON_STATE_FILE,
17455
17612
  AMASTER_MAX_CONCURRENT_COMMANDS, AMASTER_EXECUTOR_MAX_RSS_MB (default 0, disabled),
17456
17613
  AMASTER_RUNTIME_ORPHAN_REAPER_INTERVAL_SECONDS (default 300, set 0 to disable),
17614
+ AMASTER_RUNTIME_TEMPLATES_ROOT (optional; defaults to /data/templates in pi-cli-runtime),
17457
17615
  AMASTER_AGENT_INSTRUCTION_SYSTEM_KERNEL_MODE (shadow|canary; default shadow),
17458
17616
  AMASTER_AGENT_INSTRUCTION_SYSTEM_KERNEL_CANARY_AGENT_IDS / _RUN_IDS,
17459
17617
  AMASTER_AGENT_INSTRUCTION_SYSTEM_KERNEL_SOURCE_SHA256_ALLOWLIST