@amaster.ai/employee-runtime-connector 0.1.1-beta.65 → 0.1.1-beta.67

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.
@@ -761,7 +761,7 @@ function skipVoid(str, ptr, banNewLines, banComments) {
761
761
  }
762
762
  return ptr;
763
763
  }
764
- function skipUntil(str, ptr, sep2, end, banNewLines = false) {
764
+ function skipUntil(str, ptr, sep3, end, banNewLines = false) {
765
765
  if (!end) {
766
766
  ptr = indexOfNewline(str, ptr);
767
767
  return ptr < 0 ? str.length : ptr;
@@ -770,7 +770,7 @@ function skipUntil(str, ptr, sep2, end, banNewLines = false) {
770
770
  let c = str[i];
771
771
  if (c === "#") {
772
772
  i = indexOfNewline(str, i);
773
- } else if (c === sep2) {
773
+ } else if (c === sep3) {
774
774
  return i + 1;
775
775
  } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i + 1] === "\n")) {
776
776
  return i;
@@ -1952,7 +1952,7 @@ import {
1952
1952
  writeFileSync as writeFileSync3
1953
1953
  } from "node:fs";
1954
1954
  import { arch as arch2, platform as platform2 } from "node:os";
1955
- import { basename as basename2, delimiter, dirname as dirname3, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve3 } from "node:path";
1955
+ import { basename as basename2, delimiter, dirname as dirname3, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve3, sep as sep2 } from "node:path";
1956
1956
  import { spawnSync as spawnSync2 } from "node:child_process";
1957
1957
 
1958
1958
  // src/amaster-runtime-daemon/pi-provider-config.mjs
@@ -2568,7 +2568,7 @@ function stablePiManagedMcpCacheSemanticHash(value) {
2568
2568
  }
2569
2569
  function managedPiEffectiveToolsAttestorExtensionSource() {
2570
2570
  return String.raw`import { createHash } from "node:crypto";
2571
- import { readFileSync, writeFileSync } from "node:fs";
2571
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2572
2572
  import { fileURLToPath } from "node:url";
2573
2573
  import { Value } from "typebox/value";
2574
2574
 
@@ -2623,6 +2623,27 @@ function safeWriteReceipt(receiptPath, receipt) {
2623
2623
  writeFileSync(receiptPath, JSON.stringify(receipt) + "\n", { encoding: "utf8", mode: 0o600 });
2624
2624
  }
2625
2625
 
2626
+ function safeWritePhase(phasePath, phase) {
2627
+ if (!phasePath) return;
2628
+ let history = [];
2629
+ if (existsSync(phasePath)) {
2630
+ try {
2631
+ const previous = JSON.parse(readFileSync(phasePath, "utf8"));
2632
+ history = Array.isArray(previous.history) ? previous.history.slice(0, 16) : [];
2633
+ } catch {
2634
+ history = [];
2635
+ }
2636
+ }
2637
+ const attemptValue = Number(process.env.AMASTER_PI_EFFECTIVE_TOOLS_ATTEMPT);
2638
+ const attempt = Number.isSafeInteger(attemptValue) && attemptValue > 0 ? attemptValue : 1;
2639
+ const atMs = Date.now();
2640
+ history.push({ phase, attempt, atMs });
2641
+ writeFileSync(phasePath, JSON.stringify({ phase, attempt, atMs, history }) + "\n", {
2642
+ encoding: "utf8",
2643
+ mode: 0o600,
2644
+ });
2645
+ }
2646
+
2626
2647
  function validationErrorPath(error) {
2627
2648
  if (typeof error.path === "string" && error.path) return error.path;
2628
2649
  const base = typeof error.instancePath === "string" ? error.instancePath : "";
@@ -2645,10 +2666,13 @@ export default function amasterEffectiveToolsAttestor(pi) {
2645
2666
  if (mode !== "probe" && mode !== "enforce") return;
2646
2667
  const manifestPath = requiredPath("AMASTER_PI_EFFECTIVE_TOOLS_MANIFEST");
2647
2668
  const receiptPath = requiredPath("AMASTER_PI_EFFECTIVE_TOOLS_RECEIPT");
2669
+ const phasePath = process.env.AMASTER_PI_EFFECTIVE_TOOLS_PHASE?.trim() || null;
2648
2670
  const cachePath = requiredPath("AMASTER_PI_EFFECTIVE_TOOLS_CACHE");
2649
2671
  const configPath = requiredPath("AMASTER_PI_EFFECTIVE_TOOLS_CONFIG");
2672
+ safeWritePhase(phasePath, "loader_ready");
2650
2673
 
2651
2674
  pi.on("session_start", async () => {
2675
+ safeWritePhase(phasePath, "session_start");
2652
2676
  let receipt;
2653
2677
  try {
2654
2678
  const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
@@ -2747,6 +2771,7 @@ export default function amasterEffectiveToolsAttestor(pi) {
2747
2771
  attestedAt: new Date().toISOString(),
2748
2772
  };
2749
2773
  safeWriteReceipt(receiptPath, receipt);
2774
+ safeWritePhase(phasePath, "attested");
2750
2775
  if (mode === "probe") process.exit(0);
2751
2776
  } catch (error) {
2752
2777
  receipt = {
@@ -2758,6 +2783,7 @@ export default function amasterEffectiveToolsAttestor(pi) {
2758
2783
  attestedAt: new Date().toISOString(),
2759
2784
  };
2760
2785
  safeWriteReceipt(receiptPath, receipt);
2786
+ safeWritePhase(phasePath, "rejected");
2761
2787
  process.exit(78);
2762
2788
  }
2763
2789
  });
@@ -3058,9 +3084,16 @@ function createManagedPiMcpProfileApi(options = {}) {
3058
3084
  const DEFAULT_SESSION_ROLLOUT_TTL_MS2 = 24 * 60 * 60 * 1e3;
3059
3085
  const PI_VERSION_ATTESTATION_TIMEOUT_MS = 1e4;
3060
3086
  const PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS = 6e4;
3087
+ const PI_EFFECTIVE_TOOLS_RETRY_TIMEOUT_MS = 3e4;
3088
+ const PI_EFFECTIVE_TOOLS_TOTAL_TIMEOUT_MS = PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS + PI_EFFECTIVE_TOOLS_RETRY_TIMEOUT_MS;
3089
+ const PI_EFFECTIVE_TOOLS_SOFT_SLOW_MS = 3e4;
3090
+ const PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION = 1;
3091
+ const PI_EFFECTIVE_TOOLS_CIRCUIT_FAILURE_THRESHOLD = Number.isInteger(options.probeCircuitFailureThreshold) && options.probeCircuitFailureThreshold > 0 ? options.probeCircuitFailureThreshold : 3;
3092
+ const PI_EFFECTIVE_TOOLS_CIRCUIT_COOLDOWN_MS = Number.isFinite(options.probeCircuitCooldownMs) && options.probeCircuitCooldownMs > 0 ? Math.floor(options.probeCircuitCooldownMs) : 6e4;
3061
3093
  const PI_ATTESTATION_MAX_ATTEMPTS = 2;
3062
3094
  const PI_ATTESTATION_RECENT_LIVE_TTL_MS = Number.isFinite(options.recentLiveTtlMs) && options.recentLiveTtlMs > 0 ? options.recentLiveTtlMs : 30 * 60 * 1e3;
3063
3095
  const recentLivePiVersionProbes = /* @__PURE__ */ new Map();
3096
+ const effectiveToolsProbeCircuits = /* @__PURE__ */ new Map();
3064
3097
  function record6(value) {
3065
3098
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
3066
3099
  }
@@ -3180,6 +3213,216 @@ function createManagedPiMcpProfileApi(options = {}) {
3180
3213
  function sha2562(value) {
3181
3214
  return createHash3("sha256").update(value).digest("hex");
3182
3215
  }
3216
+ function trustedTreeDigest(rootPath, options2 = {}) {
3217
+ const root = resolve3(rootPath);
3218
+ const ignoredRootEntries = new Set(Array.isArray(options2.ignoredRootEntries) ? options2.ignoredRootEntries : []);
3219
+ const hash = createHash3("sha256");
3220
+ hash.update(`ignored-root:${[...ignoredRootEntries].sort().join(",")}
3221
+ `);
3222
+ const pending = [root];
3223
+ while (pending.length > 0) {
3224
+ const current = pending.pop();
3225
+ const currentStat = lstatSync3(current);
3226
+ if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3227
+ const relativePath = relative2(root, current).split(sep2).join("/");
3228
+ if (currentStat.isDirectory()) {
3229
+ hash.update(`d:${relativePath}
3230
+ `);
3231
+ const children = readdirSync3(current).filter((child) => current !== root || !ignoredRootEntries.has(child)).sort().reverse();
3232
+ for (const child of children) pending.push(join4(current, child));
3233
+ continue;
3234
+ }
3235
+ if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3236
+ hash.update(`f:${relativePath}:${currentStat.mode & 73 ? "x" : "-"}:`);
3237
+ hash.update(readFileSync3(current));
3238
+ hash.update("\n");
3239
+ }
3240
+ return hash.digest("hex");
3241
+ }
3242
+ function copyTrustedTree(sourcePath, targetPath) {
3243
+ const source = resolve3(sourcePath);
3244
+ const sourceStat = lstatSync3(source);
3245
+ if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {
3246
+ throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${source}`);
3247
+ }
3248
+ mkdirSync3(targetPath, { recursive: true, mode: 448 });
3249
+ chmodSync3(targetPath, 448);
3250
+ for (const entry of readdirSync3(source, { withFileTypes: true })) {
3251
+ const from = join4(source, entry.name);
3252
+ const to = join4(targetPath, entry.name);
3253
+ if (entry.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${from}`);
3254
+ if (entry.isDirectory()) {
3255
+ copyTrustedTree(from, to);
3256
+ continue;
3257
+ }
3258
+ if (!entry.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${from}`);
3259
+ copyFileSync(from, to, 0);
3260
+ chmodSync3(to, 384 | lstatSync3(from).mode & 73);
3261
+ }
3262
+ }
3263
+ function makeTrustedTreeReadOnly(rootPath) {
3264
+ const root = resolve3(rootPath);
3265
+ const pending = [root];
3266
+ const directories = [];
3267
+ while (pending.length > 0) {
3268
+ const current = pending.pop();
3269
+ const currentStat = lstatSync3(current);
3270
+ if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3271
+ if (currentStat.isDirectory()) {
3272
+ directories.push(current);
3273
+ for (const entry of readdirSync3(current)) pending.push(join4(current, entry));
3274
+ continue;
3275
+ }
3276
+ if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3277
+ chmodSync3(current, 256 | currentStat.mode & 73);
3278
+ }
3279
+ for (const directory of directories.reverse()) chmodSync3(directory, 320);
3280
+ }
3281
+ function makeTrustedTreeWritable(rootPath) {
3282
+ const pending = [resolve3(rootPath)];
3283
+ while (pending.length > 0) {
3284
+ const current = pending.pop();
3285
+ const currentStat = lstatSync3(current);
3286
+ if (currentStat.isSymbolicLink()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3287
+ if (currentStat.isDirectory()) {
3288
+ chmodSync3(current, 448);
3289
+ for (const entry of readdirSync3(current)) pending.push(join4(current, entry));
3290
+ continue;
3291
+ }
3292
+ if (!currentStat.isFile()) throw new Error(`pi_managed_mcp_bootstrap_cache_unsafe: ${current}`);
3293
+ chmodSync3(current, 384 | currentStat.mode & 73);
3294
+ }
3295
+ }
3296
+ function piLoaderIdentity(executorPath) {
3297
+ let cursor = dirname3(realpathSync2(executorPath));
3298
+ for (let depth = 0; depth < 4; depth += 1) {
3299
+ const packagePath = join4(cursor, "package.json");
3300
+ const loaderPath = join4(cursor, "dist", "core", "extensions", "loader.js");
3301
+ if (existsSync3(packagePath) && existsSync3(loaderPath)) {
3302
+ const packageJson = JSON.parse(readFileSync3(packagePath, "utf8"));
3303
+ return sha2562(stablePiJson({
3304
+ name: packageJson.name,
3305
+ version: packageJson.version,
3306
+ loaderSha256: sha2562(readFileSync3(loaderPath))
3307
+ }));
3308
+ }
3309
+ cursor = dirname3(cursor);
3310
+ }
3311
+ return sha2562(readFileSync3(realpathSync2(executorPath)));
3312
+ }
3313
+ function effectiveToolsBootstrapKey(input, sharedRuntime, executorCommand) {
3314
+ const adapterRoot = join4(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter");
3315
+ const resolvedExecutorCommand = resolvePiExecutablePath(executorCommand, input.baseEnv);
3316
+ return sha2562(stablePiJson({
3317
+ schemaVersion: PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION,
3318
+ connectorVersion: nonEmpty2(input.connectorVersion, "connectorVersion"),
3319
+ executorIdentity: piExecutableIdentity(resolvedExecutorCommand),
3320
+ loaderIdentity: piLoaderIdentity(resolvedExecutorCommand),
3321
+ nodeVersion: process.version,
3322
+ nodeModulesAbi: process.versions.modules,
3323
+ platform: platform2(),
3324
+ arch: arch2(),
3325
+ // npm may install dependency symlinks under the adapter's nested
3326
+ // node_modules. They resolve at runtime and are not Jiti-owned compiled
3327
+ // source; hash every package-owned adapter file while excluding that
3328
+ // dependency graph so ordinary npm links do not make the cache unusable.
3329
+ adapterTreeSha256: trustedTreeDigest(adapterRoot, { ignoredRootEntries: ["node_modules"] }),
3330
+ attestorSourceSha256: sha2562(managedPiEffectiveToolsAttestorExtensionSource()),
3331
+ argsNormalizerSourceSha256: sha2562(managedPiMcpArgsNormalizerExtensionSource())
3332
+ }));
3333
+ }
3334
+ function prepareEffectiveToolsBootstrapCache(input, sharedRuntime, executorCommand, tmpPath) {
3335
+ const cacheRoot = resolve3(nonEmpty2(input.runtimeCacheRoot ?? join4(dirname3(input.runDir), ".runtime-cache"), "runtimeCacheRoot"));
3336
+ const bootstrapRoot = join4(cacheRoot, "pi-effective-tools-jiti-v1");
3337
+ mkdirSync3(bootstrapRoot, { recursive: true, mode: 448 });
3338
+ const bootstrapRootStat = lstatSync3(bootstrapRoot);
3339
+ if (!bootstrapRootStat.isDirectory() || bootstrapRootStat.isSymbolicLink()) {
3340
+ throw new Error("pi_managed_mcp_bootstrap_cache_unsafe: root");
3341
+ }
3342
+ const key = effectiveToolsBootstrapKey(input, sharedRuntime, executorCommand);
3343
+ const entryPath = join4(bootstrapRoot, key);
3344
+ const markerPath = join4(entryPath, "manifest.json");
3345
+ const sourceCachePath = join4(entryPath, "jiti");
3346
+ const runCachePath = join4(tmpPath, "jiti");
3347
+ let status = "miss";
3348
+ if (existsSync3(entryPath)) {
3349
+ try {
3350
+ const entryStat = lstatSync3(entryPath);
3351
+ const markerStat = lstatSync3(markerPath);
3352
+ const marker = JSON.parse(readFileSync3(markerPath, "utf8"));
3353
+ if (!entryStat.isDirectory() || entryStat.isSymbolicLink() || !markerStat.isFile() || markerStat.isSymbolicLink() || marker.schemaVersion !== PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION || marker.key !== key || marker.treeSha256 !== trustedTreeDigest(sourceCachePath)) throw new Error("bootstrap marker mismatch");
3354
+ copyTrustedTree(sourceCachePath, runCachePath);
3355
+ status = "hit";
3356
+ } catch {
3357
+ const resolvedEntry = resolve3(entryPath);
3358
+ if (!within2(resolvedEntry, bootstrapRoot) || resolvedEntry === bootstrapRoot) {
3359
+ throw new Error("pi_managed_mcp_bootstrap_cache_unsafe: entry");
3360
+ }
3361
+ makeTrustedTreeWritable(resolvedEntry);
3362
+ rmSync2(resolvedEntry, { recursive: true, force: true });
3363
+ status = "invalidated";
3364
+ }
3365
+ }
3366
+ return { bootstrapRoot, entryPath, key, runCachePath, status };
3367
+ }
3368
+ function publishEffectiveToolsBootstrapCache(cache) {
3369
+ if (cache.status === "hit") return "hit";
3370
+ if (!existsSync3(cache.runCachePath)) return `${cache.status}_unavailable`;
3371
+ const runCacheStat = lstatSync3(cache.runCachePath);
3372
+ if (!runCacheStat.isDirectory() || runCacheStat.isSymbolicLink()) {
3373
+ throw new Error("pi_managed_mcp_bootstrap_cache_unsafe: run cache");
3374
+ }
3375
+ if (existsSync3(cache.entryPath)) return "hit_raced";
3376
+ const stagingPath = `${cache.entryPath}.tmp-${process.pid}-${currentTimeMs()}`;
3377
+ try {
3378
+ mkdirSync3(stagingPath, { mode: 448 });
3379
+ const stagingCachePath = join4(stagingPath, "jiti");
3380
+ copyTrustedTree(cache.runCachePath, stagingCachePath);
3381
+ writePrivateFile2(join4(stagingPath, "manifest.json"), `${JSON.stringify({
3382
+ schemaVersion: PI_EFFECTIVE_TOOLS_BOOTSTRAP_SCHEMA_VERSION,
3383
+ key: cache.key,
3384
+ treeSha256: trustedTreeDigest(stagingCachePath)
3385
+ })}
3386
+ `);
3387
+ try {
3388
+ renameSync2(stagingPath, cache.entryPath);
3389
+ makeTrustedTreeReadOnly(cache.entryPath);
3390
+ } catch (error) {
3391
+ if (error?.code !== "EEXIST" && error?.code !== "ENOTEMPTY") throw error;
3392
+ }
3393
+ } finally {
3394
+ if (existsSync3(stagingPath)) {
3395
+ makeTrustedTreeWritable(stagingPath);
3396
+ rmSync2(stagingPath, { recursive: true, force: true });
3397
+ }
3398
+ }
3399
+ return existsSync3(cache.entryPath) ? `${cache.status}_published` : `${cache.status}_unavailable`;
3400
+ }
3401
+ function writeEffectiveToolsProbePhase(phasePath, phase, attempt) {
3402
+ let history = [];
3403
+ if (existsSync3(phasePath)) {
3404
+ try {
3405
+ const parsed = JSON.parse(readFileSync3(phasePath, "utf8"));
3406
+ history = Array.isArray(parsed.history) ? parsed.history.slice(0, 16) : [];
3407
+ } catch {
3408
+ history = [];
3409
+ }
3410
+ }
3411
+ const atMs = currentTimeMs();
3412
+ history.push({ phase, attempt, atMs });
3413
+ const contents = `${JSON.stringify({ phase, attempt, atMs, history })}
3414
+ `;
3415
+ if (existsSync3(phasePath)) {
3416
+ const phaseStat = lstatSync3(phasePath);
3417
+ if (!phaseStat.isFile() || phaseStat.isSymbolicLink()) {
3418
+ throw new Error("pi_managed_mcp_probe_phase_unsafe");
3419
+ }
3420
+ writeFileSync3(phasePath, contents, { encoding: "utf8", mode: 384 });
3421
+ chmodSync3(phasePath, 384);
3422
+ return;
3423
+ }
3424
+ writeOwnedFileAtomic(phasePath, contents);
3425
+ }
3183
3426
  function piMcpAdapterVersion(piHome) {
3184
3427
  const packagePath = join4(piHome, "npm", "node_modules", "pi-mcp-adapter", "package.json");
3185
3428
  let packageJson;
@@ -3708,58 +3951,131 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3708
3951
  liveProbeAgeMs
3709
3952
  };
3710
3953
  }
3711
- function inspectEffectiveToolsProbeReceipt(receiptPath) {
3712
- if (!existsSync3(receiptPath)) return { phase: "missing", receipt: null };
3954
+ function inspectEffectiveToolsProbeReceipt(receiptPath, phasePath) {
3955
+ let phase = "missing";
3956
+ let history = [];
3957
+ if (existsSync3(phasePath)) {
3958
+ try {
3959
+ const phaseState = JSON.parse(readFileSync3(phasePath, "utf8"));
3960
+ phase = typeof phaseState.phase === "string" ? phaseState.phase : "present";
3961
+ history = Array.isArray(phaseState.history) ? phaseState.history : [];
3962
+ } catch {
3963
+ phase = "invalid";
3964
+ }
3965
+ }
3966
+ if (!existsSync3(receiptPath)) return { phase, history, receipt: null };
3713
3967
  try {
3714
3968
  const receipt = JSON.parse(readFileSync3(receiptPath, "utf8"));
3715
- const phase = receipt?.status === "attested" || receipt?.status === "rejected" ? receipt.status : "present";
3716
- return { phase, receipt };
3969
+ const receiptPhase = receipt?.status === "attested" || receipt?.status === "rejected" ? receipt.status : phase === "missing" ? "present" : phase;
3970
+ return { phase: receiptPhase, history, receipt };
3717
3971
  } catch {
3718
- return { phase: "invalid", receipt: null };
3972
+ return { phase: "invalid", history, receipt: null };
3719
3973
  }
3720
3974
  }
3721
- function attestDirectPiTools(executorCommand, env, input, spawnIdentity = null) {
3975
+ function effectiveToolsProbePhaseDurations(history, attempt) {
3976
+ const entries = history.filter((entry) => entry?.attempt === attempt && typeof entry.phase === "string" && Number.isFinite(entry.atMs)).sort((left, right) => left.atMs - right.atMs);
3977
+ const at = (phase) => entries.find((entry) => entry.phase === phase)?.atMs;
3978
+ const terminalAt = at("attested") ?? at("rejected");
3979
+ const spawnedAt = at("spawned");
3980
+ const loaderReadyAt = at("loader_ready");
3981
+ const sessionStartAt = at("session_start");
3982
+ return {
3983
+ ...Number.isFinite(spawnedAt) && Number.isFinite(loaderReadyAt) ? { spawnedToLoaderReadyMs: Math.max(0, loaderReadyAt - spawnedAt) } : {},
3984
+ ...Number.isFinite(loaderReadyAt) && Number.isFinite(sessionStartAt) ? { loaderReadyToSessionStartMs: Math.max(0, sessionStartAt - loaderReadyAt) } : {},
3985
+ ...Number.isFinite(sessionStartAt) && Number.isFinite(terminalAt) ? { sessionStartToTerminalMs: Math.max(0, terminalAt - sessionStartAt) } : {}
3986
+ };
3987
+ }
3988
+ function attestDirectPiTools(executorCommand, env, input, spawnIdentity = null, circuitKey = null) {
3989
+ const circuit = circuitKey ? effectiveToolsProbeCircuits.get(circuitKey) : null;
3990
+ if (circuit?.open === true) {
3991
+ const retryAfterMs = Math.max(0, circuit.retryAtMs - currentTimeMs());
3992
+ if (retryAfterMs > 0) {
3993
+ const error = new Error(
3994
+ `pi_managed_mcp_probe_circuit_open: connector generation probe circuit is open failures=${circuit.failures} lastPhase=${circuit.lastPhase} retryAfterMs=${retryAfterMs}`
3995
+ );
3996
+ error.code = "pi_managed_mcp_probe_circuit_open";
3997
+ error.retryAfterMs = retryAfterMs;
3998
+ throw error;
3999
+ }
4000
+ effectiveToolsProbeCircuits.set(circuitKey, { ...circuit, open: false, halfOpen: true });
4001
+ }
3722
4002
  const startedAtMs = currentTimeMs();
3723
- const result3 = spawnSyncImpl(executorCommand, [
3724
- "--no-session",
3725
- "--no-approve",
3726
- "--no-skills",
3727
- "--no-context-files",
3728
- "--no-builtin-tools",
3729
- // The enforcement extensions live in the run profile, not an agent dir,
3730
- // so the probe must load them explicitly to measure the real run surface.
3731
- ...Array.isArray(input.extensionArgs) ? input.extensionArgs : [],
3732
- "--print",
3733
- "probe effective tools"
3734
- ], {
3735
- cwd: env.AMASTER_RUNTIME_EXECUTION_WORKDIR,
3736
- env: { ...env, AMASTER_PI_EFFECTIVE_TOOLS_MODE: "probe" },
3737
- encoding: "utf8",
3738
- timeout: PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS,
3739
- killSignal: "SIGKILL",
3740
- maxBuffer: 1024 * 1024,
3741
- ...spawnIdentity ?? {}
3742
- });
4003
+ const attempts = [PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS, PI_EFFECTIVE_TOOLS_RETRY_TIMEOUT_MS];
4004
+ let result3;
4005
+ let completedAttempts = 0;
4006
+ for (let index = 0; index < attempts.length; index += 1) {
4007
+ const attempt = index + 1;
4008
+ const timeout = attempts[index];
4009
+ completedAttempts = attempt;
4010
+ writeEffectiveToolsProbePhase(input.phasePath, "spawned", attempt);
4011
+ result3 = spawnSyncImpl(executorCommand, [
4012
+ "--no-session",
4013
+ "--no-approve",
4014
+ "--no-skills",
4015
+ "--no-context-files",
4016
+ "--no-builtin-tools",
4017
+ // The enforcement extensions live in the run profile, not an agent dir,
4018
+ // so the probe must load them explicitly to measure the real run surface.
4019
+ ...Array.isArray(input.extensionArgs) ? input.extensionArgs : [],
4020
+ "--print",
4021
+ "probe effective tools"
4022
+ ], {
4023
+ cwd: env.AMASTER_RUNTIME_EXECUTION_WORKDIR,
4024
+ env: {
4025
+ ...env,
4026
+ AMASTER_PI_EFFECTIVE_TOOLS_MODE: "probe",
4027
+ AMASTER_PI_EFFECTIVE_TOOLS_ATTEMPT: String(attempt)
4028
+ },
4029
+ encoding: "utf8",
4030
+ timeout,
4031
+ killSignal: "SIGKILL",
4032
+ maxBuffer: 1024 * 1024,
4033
+ ...spawnIdentity ?? {}
4034
+ });
4035
+ if (result3.error?.code === "ETIMEDOUT" && attempt < attempts.length) continue;
4036
+ break;
4037
+ }
3743
4038
  const elapsedMs = Math.max(0, currentTimeMs() - startedAtMs);
3744
4039
  if (result3.error) {
3745
4040
  const code = typeof result3.error.code === "string" ? result3.error.code : "UNKNOWN";
3746
- const receiptDiagnostic = inspectEffectiveToolsProbeReceipt(input.receiptPath);
4041
+ const receiptDiagnostic = inspectEffectiveToolsProbeReceipt(input.receiptPath, input.phasePath);
4042
+ if (code === "ETIMEDOUT" && circuitKey) {
4043
+ if (receiptDiagnostic.phase === "missing" || receiptDiagnostic.phase === "spawned") {
4044
+ const previous = effectiveToolsProbeCircuits.get(circuitKey);
4045
+ const failures = (previous?.failures ?? 0) + 1;
4046
+ const shouldOpen = previous?.halfOpen === true || failures >= PI_EFFECTIVE_TOOLS_CIRCUIT_FAILURE_THRESHOLD;
4047
+ const observedAtMs = currentTimeMs();
4048
+ effectiveToolsProbeCircuits.set(circuitKey, {
4049
+ failures,
4050
+ lastPhase: receiptDiagnostic.phase,
4051
+ open: shouldOpen,
4052
+ halfOpen: false,
4053
+ retryAtMs: shouldOpen ? observedAtMs + PI_EFFECTIVE_TOOLS_CIRCUIT_COOLDOWN_MS : null
4054
+ });
4055
+ } else {
4056
+ effectiveToolsProbeCircuits.delete(circuitKey);
4057
+ }
4058
+ } else if (circuitKey) {
4059
+ effectiveToolsProbeCircuits.delete(circuitKey);
4060
+ }
3747
4061
  const error = new Error(
3748
- `pi_managed_mcp_effective_tools_failed: probe error=${code} elapsedMs=${elapsedMs} timeoutMs=${PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS} receiptPhase=${receiptDiagnostic.phase}`
4062
+ `pi_managed_mcp_effective_tools_failed: probe error=${code} elapsedMs=${elapsedMs} timeoutMs=${PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS} retryTimeoutMs=${PI_EFFECTIVE_TOOLS_RETRY_TIMEOUT_MS} totalBudgetMs=${PI_EFFECTIVE_TOOLS_TOTAL_TIMEOUT_MS} attempts=${completedAttempts} receiptPhase=${receiptDiagnostic.phase}`
3749
4063
  );
3750
4064
  if (code === "ETIMEDOUT") error.code = "pi_managed_mcp_probe_timeout";
3751
4065
  throw error;
3752
4066
  }
3753
4067
  if (result3.status !== 0) {
3754
- const receiptDiagnostic = inspectEffectiveToolsProbeReceipt(input.receiptPath);
4068
+ if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
4069
+ const receiptDiagnostic = inspectEffectiveToolsProbeReceipt(input.receiptPath, input.phasePath);
3755
4070
  let receiptError = "receipt unavailable";
3756
4071
  if (typeof receiptDiagnostic.receipt?.error === "string" && receiptDiagnostic.receipt.error.length > 0) {
3757
4072
  receiptError = receiptDiagnostic.receipt.error.slice(0, 512);
3758
4073
  }
3759
4074
  throw new Error(
3760
- `pi_managed_mcp_effective_tools_failed: probe exit=${result3.status ?? "unknown"} elapsedMs=${elapsedMs} timeoutMs=${PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS} receiptPhase=${receiptDiagnostic.phase} reason=${receiptError}`
4075
+ `pi_managed_mcp_effective_tools_failed: probe exit=${result3.status ?? "unknown"} elapsedMs=${elapsedMs} timeoutMs=${PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS} retryTimeoutMs=${PI_EFFECTIVE_TOOLS_RETRY_TIMEOUT_MS} totalBudgetMs=${PI_EFFECTIVE_TOOLS_TOTAL_TIMEOUT_MS} attempts=${completedAttempts} receiptPhase=${receiptDiagnostic.phase} reason=${receiptError}`
3761
4076
  );
3762
4077
  }
4078
+ if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
3763
4079
  let receipt;
3764
4080
  try {
3765
4081
  receipt = JSON.parse(readFileSync3(input.receiptPath, "utf8"));
@@ -3776,6 +4092,8 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3776
4092
  if (sha2562(readFileSync3(input.cachePath)) !== input.cacheSha256) {
3777
4093
  throw new Error("pi_managed_mcp_effective_tools_failed: cache drifted during probe");
3778
4094
  }
4095
+ if (circuitKey) effectiveToolsProbeCircuits.delete(circuitKey);
4096
+ const phaseDiagnostic = inspectEffectiveToolsProbeReceipt(input.receiptPath, input.phasePath);
3779
4097
  return {
3780
4098
  effectiveToolProxyMode: receipt.proxyMode,
3781
4099
  effectiveToolProxyPresent: receipt.proxyPresent,
@@ -3784,6 +4102,16 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3784
4102
  effectiveToolProbeAt: receipt.attestedAt,
3785
4103
  effectiveToolProbeElapsedMs: elapsedMs,
3786
4104
  effectiveToolProbeTimeoutMs: PI_EFFECTIVE_TOOLS_ATTESTATION_TIMEOUT_MS,
4105
+ effectiveToolProbeTotalBudgetMs: PI_EFFECTIVE_TOOLS_TOTAL_TIMEOUT_MS,
4106
+ effectiveToolProbeCircuitCooldownMs: PI_EFFECTIVE_TOOLS_CIRCUIT_COOLDOWN_MS,
4107
+ effectiveToolProbeAttempts: completedAttempts,
4108
+ effectiveToolProbeSoftSlow: elapsedMs >= PI_EFFECTIVE_TOOLS_SOFT_SLOW_MS,
4109
+ effectiveToolProbePhase: phaseDiagnostic.phase,
4110
+ effectiveToolProbePhaseHistory: phaseDiagnostic.history,
4111
+ effectiveToolProbePhaseDurationsMs: effectiveToolsProbePhaseDurations(
4112
+ phaseDiagnostic.history,
4113
+ completedAttempts
4114
+ ),
3787
4115
  effectiveToolBindings: receipt.effectiveToolBindings
3788
4116
  };
3789
4117
  }
@@ -3902,6 +4230,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3902
4230
  const attestorSourceSha256 = sha2562(managedPiEffectiveToolsAttestorExtensionSource());
3903
4231
  const manifestPath = join4(profileRoot, "effective-tools-manifest.json");
3904
4232
  const receiptPath = join4(tmp, "effective-tools-receipt.json");
4233
+ const phasePath = join4(tmp, "effective-tools-phase.json");
3905
4234
  const manifest = {
3906
4235
  schemaVersion: MANAGED_PI_EFFECTIVE_TOOLS_SCHEMA_VERSION,
3907
4236
  serverName: SUPPORTED_SERVER_NAME2,
@@ -3927,6 +4256,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3927
4256
  cachePath,
3928
4257
  manifestPath,
3929
4258
  receiptPath,
4259
+ phasePath,
3930
4260
  cacheSha256,
3931
4261
  cacheContentsBase64: Buffer.from(readFileSync3(cachePath)).toString("base64"),
3932
4262
  configPath,
@@ -3961,11 +4291,21 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3961
4291
  AMASTER_PI_EFFECTIVE_TOOLS_MODE: "enforce",
3962
4292
  AMASTER_PI_EFFECTIVE_TOOLS_MANIFEST: directAttestationInput.manifestPath,
3963
4293
  AMASTER_PI_EFFECTIVE_TOOLS_RECEIPT: directAttestationInput.receiptPath,
4294
+ AMASTER_PI_EFFECTIVE_TOOLS_PHASE: directAttestationInput.phasePath,
3964
4295
  AMASTER_PI_EFFECTIVE_TOOLS_CACHE: directAttestationInput.cachePath,
3965
4296
  AMASTER_PI_EFFECTIVE_TOOLS_CONFIG: directAttestationInput.configPath
3966
4297
  } : {},
3967
4298
  ...input.sourceAcquisition ? sourceAcquisitionBrowserEnvironment(input.sourceAcquisition, input.baseEnv) : {}
3968
4299
  };
4300
+ if (directAttestationInput) {
4301
+ writeEffectiveToolsProbePhase(directAttestationInput.phasePath, "prepared", 0);
4302
+ }
4303
+ const effectiveToolsBootstrapCache = directAttestationInput ? prepareEffectiveToolsBootstrapCache(
4304
+ input,
4305
+ sharedRuntime,
4306
+ nonEmpty2(input.executorCommand, "executorCommand"),
4307
+ tmp
4308
+ ) : null;
3969
4309
  const spawnIdentity = typeof input.prepareExecutorAccess === "function" ? input.prepareExecutorAccess({ profileRoot, workspaceRoot: cwd }) : null;
3970
4310
  const executorAttestation = attestPi(
3971
4311
  nonEmpty2(input.executorCommand, "executorCommand"),
@@ -3978,8 +4318,10 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3978
4318
  nonEmpty2(input.executorCommand, "executorCommand"),
3979
4319
  env,
3980
4320
  directAttestationInput,
3981
- spawnIdentity
4321
+ spawnIdentity,
4322
+ effectiveToolsBootstrapCache?.key ?? null
3982
4323
  ) : {};
4324
+ const effectiveToolProbeBootstrapCache = effectiveToolsBootstrapCache ? publishEffectiveToolsBootstrapCache(effectiveToolsBootstrapCache) : null;
3983
4325
  const runExitClosureCacheOwnership = directAttestationInput ? ownershipStatSyncImpl(directAttestationInput.cachePath) : null;
3984
4326
  const attestationFacts = {
3985
4327
  connectorVersion: nonEmpty2(input.connectorVersion, "connectorVersion"),
@@ -3990,7 +4332,9 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3990
4332
  mcpArgsNormalization: mcpToolMode === MANAGED_PI_DIRECT_TYPED_MCP_TOOL_MODE ? "none" : MANAGED_PI_MCP_ARGS_NORMALIZATION,
3991
4333
  ...directCatalog ? {
3992
4334
  catalogSetHash: directCatalog.setHash,
3993
- ...effectiveToolsAttestation
4335
+ ...effectiveToolsAttestation,
4336
+ effectiveToolProbeBootstrapKey: effectiveToolsBootstrapCache?.key ?? null,
4337
+ effectiveToolProbeBootstrapCache
3994
4338
  } : {},
3995
4339
  configMode: MANAGED_PI_CONFIG_MODE_SHARED,
3996
4340
  namespace: SUPPORTED_SERVER_NAME2,
@@ -10535,7 +10879,7 @@ var source_acquisition_compatibility_default = {
10535
10879
  };
10536
10880
 
10537
10881
  // src/amaster-runtime-daemon.mjs
10538
- var CONNECTOR_VERSION = "0.1.1-beta.65";
10882
+ var CONNECTOR_VERSION = "0.1.1-beta.67";
10539
10883
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
10540
10884
  var SOURCE_ACQUISITION_CAPABILITY = source_acquisition_compatibility_default.profileVersion;
10541
10885
  var SOURCE_ACQUISITION_PROFILE_VERSION = source_acquisition_compatibility_default.profileVersion;
@@ -15240,6 +15584,7 @@ async function executeRunCommand(config, command) {
15240
15584
  executorCommand: invocation.command,
15241
15585
  executorHome: workspace.executorHome,
15242
15586
  runDir: workspace.runDir,
15587
+ runtimeCacheRoot: join12(dirname7(config.daemonStateFile), "cache"),
15243
15588
  cwd,
15244
15589
  runtimeAuth: commandRuntimeAuth(command),
15245
15590
  nativeSession: asRecord(asRecord(command.payload).nativeSession),
@@ -6,7 +6,7 @@ import { basename, dirname, join, resolve } from "node:path";
6
6
  import { homedir, hostname } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
 
9
- const CONNECTOR_VERSION = "0.1.1-beta.65";
9
+ const CONNECTOR_VERSION = "0.1.1-beta.67";
10
10
 
11
11
  const CAPABILITIES = [
12
12
  "remote_registration",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/employee-runtime-connector",
3
- "version": "0.1.1-beta.65",
3
+ "version": "0.1.1-beta.67",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",