@amaster.ai/employee-runtime-connector 0.1.0-beta.32 → 0.1.0-beta.34

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.
@@ -3,9 +3,9 @@
3
3
 
4
4
  // src/amaster-runtime-daemon.mjs
5
5
  import { createHash as createHash8 } from "node:crypto";
6
- import { chmodSync as chmodSync5, copyFileSync as copyFileSync3, existsSync as existsSync10, lstatSync as lstatSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync8, readdirSync as readdirSync8, realpathSync as realpathSync3, renameSync as renameSync3, rmSync as rmSync6, statSync as statSync7, symlinkSync as symlinkSync3, unlinkSync, writeFileSync as writeFileSync6 } from "node:fs";
6
+ import { chmodSync as chmodSync5, copyFileSync as copyFileSync3, existsSync as existsSync11, lstatSync as lstatSync6, mkdirSync as mkdirSync7, readFileSync as readFileSync9, readdirSync as readdirSync8, realpathSync as realpathSync3, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync7, symlinkSync as symlinkSync3, unlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
7
7
  import { arch as arch3, homedir as homedir3, hostname as hostname2, platform as platform3 } from "node:os";
8
- import { basename as basename6, delimiter as delimiter2, dirname as dirname7, extname as extname2, isAbsolute as isAbsolute7, join as join11, relative as relative7, resolve as resolve10 } from "node:path";
8
+ import { basename as basename6, delimiter as delimiter2, dirname as dirname8, extname as extname2, isAbsolute as isAbsolute7, join as join12, relative as relative7, resolve as resolve10 } from "node:path";
9
9
  import { spawn, spawnSync as spawnSync5 } from "node:child_process";
10
10
 
11
11
  // src/amaster-runtime-daemon/common.mjs
@@ -4745,16 +4745,18 @@ function verifyDeclaredFiles(manifest, root, label, ignoredPaths = [], enforceCo
4745
4745
  }
4746
4746
  }
4747
4747
  if (!enforceComplete) return;
4748
- const ignored = new Set(ignoredPaths);
4748
+ const ignored = ignoredPaths.map((path) => path.split("\\").join("/"));
4749
4749
  const visit = (directory) => {
4750
4750
  for (const entry of readdirSync6(directory)) {
4751
4751
  const filePath = join9(directory, entry);
4752
- const relativePath = relative5(root, filePath);
4753
- if (ignored.has(relativePath)) continue;
4752
+ const relativePath = relative5(root, filePath).split("\\").join("/");
4754
4753
  const stat = lstatSync5(filePath);
4755
4754
  if (stat.isSymbolicLink()) {
4756
4755
  throw new Error(`pi_trusted_runtime_source_unsafe:${label}_file`);
4757
4756
  }
4757
+ if (ignored.some((path) => relativePath === path || relativePath.startsWith(`${path}/`))) {
4758
+ continue;
4759
+ }
4758
4760
  if (stat.isDirectory()) {
4759
4761
  visit(filePath);
4760
4762
  } else if (!stat.isFile() || !seen.has(relativePath)) {
@@ -5028,7 +5030,10 @@ function readTrustedPiRuntimeLocalDigests(input) {
5028
5030
  const seedManifest = JSON.parse(readFileSync6(seedManifestFile, "utf8"));
5029
5031
  const overlayManifest = JSON.parse(readFileSync6(overlayManifestFile, "utf8"));
5030
5032
  const policyManifest = JSON.parse(readFileSync6(policyFile, "utf8"));
5031
- verifyDeclaredFiles(seedManifest, seedRoot, "seed", ["seed-manifest.json"]);
5033
+ verifyDeclaredFiles(seedManifest, seedRoot, "seed", [
5034
+ "seed-manifest.json",
5035
+ "npm/node_modules"
5036
+ ]);
5032
5037
  verifyDeclaredFiles(overlayManifest, overlayRoot, "overlay", ["runtime-overlay-manifest.json"]);
5033
5038
  verifyDeclaredFiles(
5034
5039
  policyManifest,
@@ -5124,11 +5129,204 @@ function verifyTrustedPiRuntimeAssertion(input) {
5124
5129
  };
5125
5130
  }
5126
5131
 
5132
+ // src/amaster-runtime-daemon/pi-provider-config.mjs
5133
+ import { existsSync as existsSync9, mkdirSync as mkdirSync6, readFileSync as readFileSync7, renameSync as renameSync3, writeFileSync as writeFileSync6 } from "node:fs";
5134
+ import { dirname as dirname7, join as join10 } from "node:path";
5135
+ var AMASTER_API_KEY_ENV_REFERENCE = "${AMASTER_API_KEY}";
5136
+ var AMASTER_BILLING_HEADER_ENV_REFERENCES = Object.freeze({
5137
+ "x-pi-agent-oauth-token": "${AMASTER_PLATFORM_OAUTH_TOKEN}",
5138
+ "x-organization-id": "${AMASTER_PLATFORM_ORGANIZATION_ID}",
5139
+ "x-billing-turn-id": "${AMASTER_BILLING_TURN_ID}"
5140
+ });
5141
+ function isRecord(value) {
5142
+ return value && typeof value === "object" && !Array.isArray(value);
5143
+ }
5144
+ function readJsonFile2(filePath) {
5145
+ try {
5146
+ const parsed = JSON.parse(readFileSync7(filePath, "utf8"));
5147
+ return asRecord(parsed);
5148
+ } catch {
5149
+ return {};
5150
+ }
5151
+ }
5152
+ function writeJsonFileAtomic(filePath, value) {
5153
+ mkdirSync6(dirname7(filePath), { recursive: true });
5154
+ const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
5155
+ writeFileSync6(tmpPath, `${JSON.stringify(value, null, 2)}
5156
+ `, { mode: 384 });
5157
+ renameSync3(tmpPath, filePath);
5158
+ }
5159
+ function imageGenBaseUrlFromProviderBaseUrl(value) {
5160
+ const input = readString(value);
5161
+ if (!input) return void 0;
5162
+ try {
5163
+ const url = new URL(input);
5164
+ const pathname = url.pathname.replace(/\/+$/, "");
5165
+ if (pathname.toLowerCase().endsWith("/v1")) {
5166
+ url.pathname = pathname.slice(0, -"/v1".length) || "/";
5167
+ }
5168
+ return url.toString();
5169
+ } catch {
5170
+ return input.replace(/\/v1\/?$/, "");
5171
+ }
5172
+ }
5173
+ function ensureAmasterProviderModel(models, modelId, flash) {
5174
+ const id = readString(modelId);
5175
+ if (!id) return;
5176
+ const existing = Array.isArray(models) ? models : [];
5177
+ const index = existing.findIndex((entry) => asRecord(entry).id === id);
5178
+ if (index >= 0) {
5179
+ existing[index] = {
5180
+ ...asRecord(existing[index]),
5181
+ id,
5182
+ input: readStringArray(asRecord(existing[index]).input).length > 0 ? asRecord(existing[index]).input : ["text", "image"],
5183
+ reasoning: asRecord(existing[index]).reasoning ?? true,
5184
+ ...flash ? { flash: true } : {}
5185
+ };
5186
+ return;
5187
+ }
5188
+ existing.push({
5189
+ id,
5190
+ input: ["text", "image"],
5191
+ reasoning: true,
5192
+ ...flash ? { flash: true } : {}
5193
+ });
5194
+ }
5195
+ function withoutManagedBillingHeaders(value) {
5196
+ const headers = { ...asRecord(value) };
5197
+ for (const name of Object.keys(AMASTER_BILLING_HEADER_ENV_REFERENCES)) {
5198
+ delete headers[name];
5199
+ }
5200
+ return headers;
5201
+ }
5202
+ function syncManagedBillingHeaders(value, executorEnv) {
5203
+ const headers = withoutManagedBillingHeaders(value);
5204
+ if (readString(executorEnv.AMASTER_MODEL_ACCESS_MODE) === "billing_gateway") {
5205
+ Object.assign(headers, AMASTER_BILLING_HEADER_ENV_REFERENCES);
5206
+ }
5207
+ return Object.keys(headers).length > 0 ? headers : void 0;
5208
+ }
5209
+ function managedApiKeyConfigValue(executorEnv, apiKey) {
5210
+ return readString(executorEnv.AMASTER_MODEL_ACCESS_MODE) === "billing_gateway" ? AMASTER_API_KEY_ENV_REFERENCE : apiKey;
5211
+ }
5212
+ function syncAmasterProviderModels(agentDir, executorEnv) {
5213
+ const apiKey = readString(executorEnv.AMASTER_API_KEY);
5214
+ if (!apiKey) return false;
5215
+ const modelsPath = join10(agentDir, "models.json");
5216
+ const config = readJsonFile2(modelsPath);
5217
+ const providers = asRecord(config.providers);
5218
+ const amaster = { ...asRecord(providers.amaster) };
5219
+ amaster.apiKey = managedApiKeyConfigValue(executorEnv, apiKey);
5220
+ const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
5221
+ if (baseUrl) amaster.baseUrl = baseUrl;
5222
+ if (!readString(amaster.api)) amaster.api = "openai-completions";
5223
+ const headers = syncManagedBillingHeaders(amaster.headers, executorEnv);
5224
+ if (headers) amaster.headers = headers;
5225
+ else delete amaster.headers;
5226
+ const models = Array.isArray(amaster.models) ? [...amaster.models] : [];
5227
+ ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL, false);
5228
+ ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_FLASH_MODEL, true);
5229
+ if (models.length > 0) amaster.models = models;
5230
+ writeJsonFileAtomic(modelsPath, {
5231
+ ...config,
5232
+ providers: {
5233
+ ...providers,
5234
+ amaster
5235
+ }
5236
+ });
5237
+ return true;
5238
+ }
5239
+ function syncAmasterProviderSettings(agentDir, executorEnv) {
5240
+ const apiKey = readString(executorEnv.AMASTER_API_KEY);
5241
+ if (!apiKey) return false;
5242
+ const settingsPath = join10(agentDir, "settings.json");
5243
+ if (!existsSync9(settingsPath)) return false;
5244
+ const settings = readJsonFile2(settingsPath);
5245
+ const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
5246
+ const defaultModel = readString(executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL);
5247
+ const imageGenBaseUrl = imageGenBaseUrlFromProviderBaseUrl(baseUrl);
5248
+ let changed = false;
5249
+ if (defaultModel) {
5250
+ if (settings.defaultProvider !== "amaster") {
5251
+ settings.defaultProvider = "amaster";
5252
+ changed = true;
5253
+ }
5254
+ if (settings.defaultModel !== defaultModel) {
5255
+ settings.defaultModel = defaultModel;
5256
+ changed = true;
5257
+ }
5258
+ }
5259
+ const imageGen = settings["pi-image-gen"];
5260
+ if (isRecord(imageGen) && isRecord(imageGen.customProviders) && isRecord(imageGen.customProviders.amaster)) {
5261
+ const customProviders = imageGen.customProviders;
5262
+ const imageGenAmaster = { ...asRecord(customProviders.amaster) };
5263
+ const managedApiKey = managedApiKeyConfigValue(executorEnv, apiKey);
5264
+ if (imageGenAmaster.apiKey !== managedApiKey) {
5265
+ imageGenAmaster.apiKey = managedApiKey;
5266
+ changed = true;
5267
+ }
5268
+ if (imageGenBaseUrl && imageGenAmaster.baseUrl !== imageGenBaseUrl) {
5269
+ imageGenAmaster.baseUrl = imageGenBaseUrl;
5270
+ changed = true;
5271
+ }
5272
+ const imageGenHeaders = syncManagedBillingHeaders(imageGenAmaster.headers, executorEnv);
5273
+ if (JSON.stringify(imageGenHeaders) !== JSON.stringify(imageGenAmaster.headers)) {
5274
+ if (imageGenHeaders) imageGenAmaster.headers = imageGenHeaders;
5275
+ else delete imageGenAmaster.headers;
5276
+ changed = true;
5277
+ }
5278
+ settings["pi-image-gen"] = {
5279
+ ...asRecord(imageGen),
5280
+ customProviders: {
5281
+ ...customProviders,
5282
+ amaster: imageGenAmaster
5283
+ }
5284
+ };
5285
+ }
5286
+ const webAccess = settings["pi-web-access"];
5287
+ if (isRecord(webAccess) && isRecord(webAccess.providers)) {
5288
+ const webProviders = webAccess.providers;
5289
+ const nextWebProviders = { ...webProviders };
5290
+ for (const [name, rawProvider] of Object.entries(webProviders)) {
5291
+ if (!isRecord(rawProvider)) continue;
5292
+ const providerApiKey = readString(rawProvider.apiKey);
5293
+ const providerBaseUrl = readString(rawProvider.baseUrl);
5294
+ const looksAmasterBacked = name === "amaster" || name === "kimi" || providerApiKey === "${AMASTER_API_KEY}" || providerApiKey === "AMASTER_API_KEY" || providerBaseUrl?.includes("credits.helige") || providerBaseUrl?.includes("credits.amaster");
5295
+ if (!looksAmasterBacked) continue;
5296
+ const nextProvider = {
5297
+ ...rawProvider,
5298
+ apiKey: managedApiKeyConfigValue(executorEnv, apiKey),
5299
+ ...baseUrl ? { baseUrl } : {}
5300
+ };
5301
+ const webAccessHeaders = syncManagedBillingHeaders(rawProvider.headers, executorEnv);
5302
+ if (webAccessHeaders) nextProvider.headers = webAccessHeaders;
5303
+ else delete nextProvider.headers;
5304
+ if (JSON.stringify(nextProvider) !== JSON.stringify(rawProvider)) {
5305
+ nextWebProviders[name] = nextProvider;
5306
+ changed = true;
5307
+ }
5308
+ }
5309
+ settings["pi-web-access"] = {
5310
+ ...asRecord(webAccess),
5311
+ providers: nextWebProviders
5312
+ };
5313
+ }
5314
+ if (!changed) return false;
5315
+ writeJsonFileAtomic(settingsPath, settings);
5316
+ return true;
5317
+ }
5318
+ function syncAmasterProviderFiles(agentDir, executorEnv) {
5319
+ return {
5320
+ modelsSynced: syncAmasterProviderModels(agentDir, executorEnv),
5321
+ settingsSynced: syncAmasterProviderSettings(agentDir, executorEnv)
5322
+ };
5323
+ }
5324
+
5127
5325
  // src/amaster-runtime-daemon/workspace-status.mjs
5128
5326
  import { spawnSync as spawnSync4 } from "node:child_process";
5129
5327
  import { createHash as createHash7 } from "node:crypto";
5130
- import { existsSync as existsSync9, readdirSync as readdirSync7, readFileSync as readFileSync7, statSync as statSync6 } from "node:fs";
5131
- import { basename as basename5, extname, isAbsolute as isAbsolute6, join as join10, relative as relative6, resolve as resolve9 } from "node:path";
5328
+ import { existsSync as existsSync10, readdirSync as readdirSync7, readFileSync as readFileSync8, statSync as statSync6 } from "node:fs";
5329
+ import { basename as basename5, extname, isAbsolute as isAbsolute6, join as join11, relative as relative6, resolve as resolve9 } from "node:path";
5132
5330
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
5133
5331
  var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
5134
5332
  [".md", "markdown"],
@@ -5197,7 +5395,7 @@ function sanitizeTrackedChange(line) {
5197
5395
  return isSafeRelativePath(path) ? line : null;
5198
5396
  }
5199
5397
  function sha256File2(filePath) {
5200
- return createHash7("sha256").update(readFileSync7(filePath)).digest("hex");
5398
+ return createHash7("sha256").update(readFileSync8(filePath)).digest("hex");
5201
5399
  }
5202
5400
  function artifactHashCacheKey(relativePath, stat) {
5203
5401
  return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
@@ -5246,7 +5444,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
5246
5444
  if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
5247
5445
  if (entry.name === ".git") continue;
5248
5446
  }
5249
- const fullPath = join10(current, entry.name);
5447
+ const fullPath = join11(current, entry.name);
5250
5448
  const relativePath = normalizeRelativePath(root, fullPath);
5251
5449
  if (!isSafeRelativePath(relativePath)) continue;
5252
5450
  if (basename5(relativePath) === ".amaster-runtime.json") continue;
@@ -5325,10 +5523,10 @@ function sanitizeRuntimeService(entry) {
5325
5523
  };
5326
5524
  }
5327
5525
  function readRuntimeServicesSnapshot(cwd) {
5328
- const snapshotPath = join10(resolve9(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
5329
- if (!existsSync9(snapshotPath)) return [];
5526
+ const snapshotPath = join11(resolve9(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
5527
+ if (!existsSync10(snapshotPath)) return [];
5330
5528
  try {
5331
- const parsed = JSON.parse(readFileSync7(snapshotPath, "utf8"));
5529
+ const parsed = JSON.parse(readFileSync8(snapshotPath, "utf8"));
5332
5530
  const rawServices = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.services) ? parsed.services : [];
5333
5531
  return rawServices.map((entry) => sanitizeRuntimeService(entry)).filter((entry) => entry !== null).slice(0, 50);
5334
5532
  } catch {
@@ -5399,7 +5597,7 @@ function readWorkspaceStatus(cwd, opts = {}) {
5399
5597
  }
5400
5598
 
5401
5599
  // src/amaster-runtime-daemon.mjs
5402
- var CONNECTOR_VERSION = "0.1.0-beta.32";
5600
+ var CONNECTOR_VERSION = "0.1.0-beta.34";
5403
5601
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
5404
5602
  var MAX_CHECKPOINT_BYTES = 20 * 1024 * 1024;
5405
5603
  var CHECKPOINT_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -5423,6 +5621,7 @@ var activeRunManifestOutputFlusher = createManifestOutputFlusher({ updateWorkspa
5423
5621
  var piChildIdentityAllocator = null;
5424
5622
  var piChildIdentityAllocatorKey = null;
5425
5623
  var trustedPiRuntimeProvenanceCache = createTrustedPiRuntimeProvenanceCache();
5624
+ var lastPartialTrustedPiRuntimeSourceWarningKey = null;
5426
5625
  function configuredPiChildIdentityAllocator(config) {
5427
5626
  if (!(config.piChildUidBase > 0)) return null;
5428
5627
  const key = `${config.piChildUidBase}:${config.piChildUidSpan}`;
@@ -5446,11 +5645,11 @@ function updateActiveRunWorkspaceManifest(commandId, manifestPath, patch = {}) {
5446
5645
  }
5447
5646
  function resultOutboxPendingCount(config) {
5448
5647
  const dir = resultOutboxDir(config);
5449
- if (!existsSync10(dir)) return 0;
5648
+ if (!existsSync11(dir)) return 0;
5450
5649
  try {
5451
5650
  let pending = 0;
5452
5651
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json"))) {
5453
- if (readValidResultOutboxEntryOrQuarantine(config, file, join11(dir, file))) {
5652
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join12(dir, file))) {
5454
5653
  pending += 1;
5455
5654
  }
5456
5655
  }
@@ -5466,11 +5665,11 @@ function piCompletionOutputType(event) {
5466
5665
  }
5467
5666
  function resultOutboxActiveRunCommands(config) {
5468
5667
  const dir = resultOutboxDir(config);
5469
- if (!existsSync10(dir)) return [];
5668
+ if (!existsSync11(dir)) return [];
5470
5669
  const outboxPending = resultOutboxPendingCount(config);
5471
5670
  const entries = [];
5472
5671
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json")).sort()) {
5473
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join11(dir, file));
5672
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join12(dir, file));
5474
5673
  if (!entry) continue;
5475
5674
  const activeRun = asRecord(entry.activeRun);
5476
5675
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -5500,12 +5699,12 @@ function resultOutboxActiveRunCommands(config) {
5500
5699
  }
5501
5700
  function resultOutboxFailedRunCommands(config) {
5502
5701
  const dir = resultOutboxInvalidDir(config);
5503
- if (!existsSync10(dir)) return [];
5702
+ if (!existsSync11(dir)) return [];
5504
5703
  const entries = [];
5505
5704
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
5506
5705
  let entry;
5507
5706
  try {
5508
- entry = asRecord(JSON.parse(readFileSync8(join11(dir, file), "utf8")));
5707
+ entry = asRecord(JSON.parse(readFileSync9(join12(dir, file), "utf8")));
5509
5708
  } catch {
5510
5709
  continue;
5511
5710
  }
@@ -5569,7 +5768,7 @@ function safeExpandPath(value) {
5569
5768
  }
5570
5769
  function safeJsonObjectFromFile(filePath) {
5571
5770
  try {
5572
- const parsed = JSON.parse(readFileSync8(filePath, "utf8"));
5771
+ const parsed = JSON.parse(readFileSync9(filePath, "utf8"));
5573
5772
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
5574
5773
  } catch {
5575
5774
  return null;
@@ -5612,10 +5811,10 @@ function safeSkillRootSummary(kind, source, pathValue) {
5612
5811
  try {
5613
5812
  for (const name of readdirSync8(pathValue)) {
5614
5813
  if (name.startsWith(".")) continue;
5615
- const skillDir = join11(pathValue, name);
5814
+ const skillDir = join12(pathValue, name);
5616
5815
  try {
5617
5816
  if (!statSync7(skillDir).isDirectory()) continue;
5618
- if (!existsSync10(join11(skillDir, "SKILL.md"))) continue;
5817
+ if (!existsSync11(join12(skillDir, "SKILL.md"))) continue;
5619
5818
  skillCount += 1;
5620
5819
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
5621
5820
  truncated = true;
@@ -5666,7 +5865,7 @@ function objectKeyCount(value) {
5666
5865
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
5667
5866
  }
5668
5867
  function defaultPiCodingAgentDir() {
5669
- return join11(homedir3(), ".pi", "agent");
5868
+ return join12(homedir3(), ".pi", "agent");
5670
5869
  }
5671
5870
  function piCapabilitySourcesDiagnostics() {
5672
5871
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -5675,11 +5874,11 @@ function piCapabilitySourcesDiagnostics() {
5675
5874
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
5676
5875
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
5677
5876
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
5678
- const userSkillsPath = piAgentHome ? join11(piAgentHome, "skills") : null;
5679
- const marketplaceSkillsPath = safeExpandPath(process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR) ?? (piAgentHome ? join11(piAgentHome, "marketplace", "skills") : null);
5877
+ const userSkillsPath = piAgentHome ? join12(piAgentHome, "skills") : null;
5878
+ const marketplaceSkillsPath = safeExpandPath(process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR) ?? (piAgentHome ? join12(piAgentHome, "marketplace", "skills") : null);
5680
5879
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
5681
- const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join11(piAgentHome, "mcp.json") : null);
5682
- const settingsConfigPath = piCodingAgentDir ? join11(piCodingAgentDir, "settings.json") : null;
5880
+ const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join12(piAgentHome, "mcp.json") : null);
5881
+ const settingsConfigPath = piCodingAgentDir ? join12(piCodingAgentDir, "settings.json") : null;
5683
5882
  const skillRoots = [
5684
5883
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
5685
5884
  safeSkillRootSummary(
@@ -5795,13 +5994,28 @@ function buildExecutorReadiness(config) {
5795
5994
  return config.executors.filter((executor) => executor.kind === "codex" || executor.kind === "pi").map((executor) => executorReadinessFor(config, executor));
5796
5995
  }
5797
5996
  function trustedPiRuntimeProvenancePayload(config) {
5798
- const configured = [
5799
- config.piRuntimeSeedRoot,
5800
- config.piRuntimeOverlayRoot,
5801
- config.piRuntimeEffectivePolicyFile
5802
- ].filter(Boolean).length;
5803
- if (configured === 0) return {};
5804
- if (configured !== 3) throw new Error("pi_trusted_runtime_source_config_missing");
5997
+ const configuredSources = [
5998
+ Boolean(config.piRuntimeSeedRoot),
5999
+ Boolean(config.piRuntimeOverlayRoot),
6000
+ Boolean(config.piRuntimeEffectivePolicyFile)
6001
+ ];
6002
+ const configured = configuredSources.filter(Boolean).length;
6003
+ if (configured === 0) {
6004
+ lastPartialTrustedPiRuntimeSourceWarningKey = null;
6005
+ return {};
6006
+ }
6007
+ if (configured !== 3) {
6008
+ const warningKey = configuredSources.map((value) => value ? "1" : "0").join("");
6009
+ if (warningKey !== lastPartialTrustedPiRuntimeSourceWarningKey) {
6010
+ process.stderr.write(
6011
+ `AMaster daemon warning pi_trusted_runtime_source_config_partial: configured=${configured} required=3; ordinary heartbeat continues without trusted runtime provenance.
6012
+ `
6013
+ );
6014
+ lastPartialTrustedPiRuntimeSourceWarningKey = warningKey;
6015
+ }
6016
+ return {};
6017
+ }
6018
+ lastPartialTrustedPiRuntimeSourceWarningKey = null;
5805
6019
  return trustedPiRuntimeProvenanceCache.read(trustedPiRuntimeSources(config));
5806
6020
  }
5807
6021
  function buildRegisterPayload(config) {
@@ -5898,10 +6112,10 @@ function piAgentSystemDataDir(config) {
5898
6112
  return configured ? resolve10(expandHomePath(configured)) : null;
5899
6113
  }
5900
6114
  function readPiAgentLocalPlatformCredential(credentialsDir) {
5901
- const pointer = readJsonFile2(join11(credentialsDir, "latest.json"));
6115
+ const pointer = readJsonFile3(join12(credentialsDir, "latest.json"));
5902
6116
  const credentialRef = readString(pointer.credentialRef);
5903
6117
  if (!credentialRef || !/^[a-f0-9]{64}$/i.test(credentialRef)) return null;
5904
- const credential = readJsonFile2(join11(credentialsDir, `${credentialRef}.json`));
6118
+ const credential = readJsonFile3(join12(credentialsDir, `${credentialRef}.json`));
5905
6119
  const organizationId = readString(credential.organizationId);
5906
6120
  const apiKey = readString(credential.apiKey);
5907
6121
  if (credential.version !== 1 || !organizationId || !apiKey) return null;
@@ -5917,7 +6131,7 @@ function piAgentLocalPlatformCredentials(config) {
5917
6131
  if (!piAgentLocalPlatformRunnerEnabled(config)) return [];
5918
6132
  const systemDataDir = piAgentSystemDataDir(config);
5919
6133
  if (!systemDataDir) return [];
5920
- const companiesDir = join11(systemDataDir, "companies");
6134
+ const companiesDir = join12(systemDataDir, "companies");
5921
6135
  let entries = [];
5922
6136
  try {
5923
6137
  entries = readdirSync8(companiesDir, { withFileTypes: true });
@@ -5927,7 +6141,7 @@ function piAgentLocalPlatformCredentials(config) {
5927
6141
  const credentialsByOrganizationId = /* @__PURE__ */ new Map();
5928
6142
  for (const entry of entries) {
5929
6143
  if (!entry.isDirectory()) continue;
5930
- const credential = readPiAgentLocalPlatformCredential(join11(companiesDir, entry.name, "model-credentials"));
6144
+ const credential = readPiAgentLocalPlatformCredential(join12(companiesDir, entry.name, "model-credentials"));
5931
6145
  if (credential) credentialsByOrganizationId.set(credential.organizationId, credential);
5932
6146
  }
5933
6147
  return [...credentialsByOrganizationId.values()];
@@ -6101,7 +6315,7 @@ AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
6101
6315
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
6102
6316
  AMASTER_CAPABILITIES=${quoteShell(config.capabilities.join(","))}
6103
6317
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
6104
- AMASTER_DAEMON_STATE_FILE=${quoteShell(join11(homedir3(), ".amaster-employee", "runtime-connector-state.json"))}
6318
+ AMASTER_DAEMON_STATE_FILE=${quoteShell(join12(homedir3(), ".amaster-employee", "runtime-connector-state.json"))}
6105
6319
  EOF
6106
6320
 
6107
6321
  set -a
@@ -6289,10 +6503,10 @@ function buildActiveRunCommandStatus(config, entry) {
6289
6503
  const base = {
6290
6504
  ...entry,
6291
6505
  phase: readString(entry.phase) ?? "executing",
6292
- managedWorkdirPresent: entry.workspacePath ? existsSync10(entry.workspacePath) : false,
6506
+ managedWorkdirPresent: entry.workspacePath ? existsSync11(entry.workspacePath) : false,
6293
6507
  outboxPending: resultOutboxPendingCount(config)
6294
6508
  };
6295
- if (!entry.workspacePath || !existsSync10(entry.workspacePath)) return base;
6509
+ if (!entry.workspacePath || !existsSync11(entry.workspacePath)) return base;
6296
6510
  const manifestPath = entry.manifestPath ?? workspaceManifestPath(entry.workspacePath);
6297
6511
  const status = readWorkspaceStatus(entry.workspacePath, { hashCache: workspaceStatusHashCache });
6298
6512
  const artifactCandidates = status.artifacts.slice(0, 20);
@@ -6471,151 +6685,14 @@ function trustedPiRuntimeSources(config) {
6471
6685
  policyFile: config.piRuntimeEffectivePolicyFile
6472
6686
  };
6473
6687
  }
6474
- function readJsonFile2(filePath) {
6688
+ function readJsonFile3(filePath) {
6475
6689
  try {
6476
- const parsed = JSON.parse(readFileSync8(filePath, "utf8"));
6690
+ const parsed = JSON.parse(readFileSync9(filePath, "utf8"));
6477
6691
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
6478
6692
  } catch {
6479
6693
  return {};
6480
6694
  }
6481
6695
  }
6482
- function writeJsonFileAtomic(filePath, value) {
6483
- mkdirSync6(dirname7(filePath), { recursive: true });
6484
- const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
6485
- writeFileSync6(tmpPath, `${JSON.stringify(value, null, 2)}
6486
- `, { mode: 384 });
6487
- renameSync3(tmpPath, filePath);
6488
- }
6489
- function isPlainRecord(value) {
6490
- return value && typeof value === "object" && !Array.isArray(value);
6491
- }
6492
- function imageGenBaseUrlFromProviderBaseUrl(value) {
6493
- const input = readString(value);
6494
- if (!input) return void 0;
6495
- try {
6496
- const url = new URL(input);
6497
- const pathname = url.pathname.replace(/\/+$/, "");
6498
- if (pathname.toLowerCase().endsWith("/v1")) {
6499
- url.pathname = pathname.slice(0, -"/v1".length) || "/";
6500
- }
6501
- return url.toString();
6502
- } catch {
6503
- return input.replace(/\/v1\/?$/, "");
6504
- }
6505
- }
6506
- function ensureAmasterProviderModel(models, modelId, flash) {
6507
- const id = readString(modelId);
6508
- if (!id) return;
6509
- const existing = Array.isArray(models) ? models : [];
6510
- const index = existing.findIndex((entry) => asRecord(entry).id === id);
6511
- if (index >= 0) {
6512
- existing[index] = {
6513
- ...asRecord(existing[index]),
6514
- id,
6515
- input: readStringArray(asRecord(existing[index]).input).length > 0 ? asRecord(existing[index]).input : ["text", "image"],
6516
- reasoning: asRecord(existing[index]).reasoning ?? true,
6517
- ...flash ? { flash: true } : {}
6518
- };
6519
- return;
6520
- }
6521
- existing.push({
6522
- id,
6523
- input: ["text", "image"],
6524
- reasoning: true,
6525
- ...flash ? { flash: true } : {}
6526
- });
6527
- }
6528
- function syncAmasterProviderModels(agentDir, executorEnv) {
6529
- const apiKey = readString(executorEnv.AMASTER_API_KEY);
6530
- if (!apiKey) return false;
6531
- const modelsPath = join11(agentDir, "models.json");
6532
- const config = readJsonFile2(modelsPath);
6533
- const providers = asRecord(config.providers);
6534
- const amaster = { ...asRecord(providers.amaster) };
6535
- amaster.apiKey = apiKey;
6536
- const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
6537
- if (baseUrl) amaster.baseUrl = baseUrl;
6538
- if (!readString(amaster.api)) amaster.api = "openai-completions";
6539
- const models = Array.isArray(amaster.models) ? [...amaster.models] : [];
6540
- ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL, false);
6541
- ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_FLASH_MODEL, true);
6542
- if (models.length > 0) amaster.models = models;
6543
- writeJsonFileAtomic(modelsPath, {
6544
- ...config,
6545
- providers: {
6546
- ...providers,
6547
- amaster
6548
- }
6549
- });
6550
- return true;
6551
- }
6552
- function syncAmasterProviderSettings(agentDir, executorEnv) {
6553
- const apiKey = readString(executorEnv.AMASTER_API_KEY);
6554
- if (!apiKey) return false;
6555
- const settingsPath = join11(agentDir, "settings.json");
6556
- if (!existsSync10(settingsPath)) return false;
6557
- const settings = readJsonFile2(settingsPath);
6558
- const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
6559
- const defaultModel = readString(executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL);
6560
- const imageGenBaseUrl = imageGenBaseUrlFromProviderBaseUrl(baseUrl);
6561
- let changed = false;
6562
- if (defaultModel) {
6563
- if (settings.defaultProvider !== "amaster") {
6564
- settings.defaultProvider = "amaster";
6565
- changed = true;
6566
- }
6567
- if (settings.defaultModel !== defaultModel) {
6568
- settings.defaultModel = defaultModel;
6569
- changed = true;
6570
- }
6571
- }
6572
- const imageGen = settings["pi-image-gen"];
6573
- if (isPlainRecord(imageGen) && isPlainRecord(imageGen.customProviders) && isPlainRecord(imageGen.customProviders.amaster)) {
6574
- const imageGenAmaster = { ...imageGen.customProviders.amaster };
6575
- if (imageGenAmaster.apiKey !== apiKey) {
6576
- imageGenAmaster.apiKey = apiKey;
6577
- changed = true;
6578
- }
6579
- if (imageGenBaseUrl && imageGenAmaster.baseUrl !== imageGenBaseUrl) {
6580
- imageGenAmaster.baseUrl = imageGenBaseUrl;
6581
- changed = true;
6582
- }
6583
- settings["pi-image-gen"] = {
6584
- ...imageGen,
6585
- customProviders: {
6586
- ...imageGen.customProviders,
6587
- amaster: imageGenAmaster
6588
- }
6589
- };
6590
- }
6591
- const webAccess = settings["pi-web-access"];
6592
- if (isPlainRecord(webAccess) && isPlainRecord(webAccess.providers)) {
6593
- const nextWebProviders = { ...webAccess.providers };
6594
- for (const [name, rawProvider] of Object.entries(webAccess.providers)) {
6595
- if (!isPlainRecord(rawProvider)) continue;
6596
- const providerApiKey = readString(rawProvider.apiKey);
6597
- const providerBaseUrl = readString(rawProvider.baseUrl);
6598
- const looksAmasterBacked = name === "amaster" || name === "kimi" || providerApiKey === "${AMASTER_API_KEY}" || providerApiKey === "AMASTER_API_KEY" || providerBaseUrl?.includes("credits.helige") || providerBaseUrl?.includes("credits.amaster");
6599
- if (!looksAmasterBacked) continue;
6600
- const nextProvider = {
6601
- ...rawProvider,
6602
- apiKey,
6603
- ...baseUrl ? { baseUrl } : {}
6604
- };
6605
- if (JSON.stringify(nextProvider) !== JSON.stringify(rawProvider)) {
6606
- nextWebProviders[name] = nextProvider;
6607
- changed = true;
6608
- }
6609
- }
6610
- settings["pi-web-access"] = {
6611
- ...webAccess,
6612
- providers: nextWebProviders
6613
- };
6614
- }
6615
- if (!changed) return false;
6616
- writeJsonFileAtomic(settingsPath, settings);
6617
- return true;
6618
- }
6619
6696
  function resolvePiExecutorProviderConfig(config, command, executorEnv) {
6620
6697
  const localPlatformCredential = piAgentLocalPlatformCredentialForCommand(config, command);
6621
6698
  if (piAgentLocalPlatformRunnerEnabled(config) && !localPlatformCredential) {
@@ -6629,8 +6706,7 @@ function resolvePiExecutorProviderConfig(config, command, executorEnv) {
6629
6706
  async function syncPiExecutorProviderConfig(config, command, agentDir, resolvedProviderConfig) {
6630
6707
  if (!agentDir) return;
6631
6708
  const { providerConfig, credentialSource } = resolvedProviderConfig;
6632
- const modelsSynced = syncAmasterProviderModels(agentDir, providerConfig);
6633
- const settingsSynced = syncAmasterProviderSettings(agentDir, providerConfig);
6709
+ const { modelsSynced, settingsSynced } = syncAmasterProviderFiles(agentDir, providerConfig);
6634
6710
  if (modelsSynced || settingsSynced) {
6635
6711
  await ingestLog(config, command, "system", "info", "Synced AMaster provider config for pi executor", {
6636
6712
  modelsSynced,
@@ -6698,8 +6774,8 @@ async function materializeAgentInstructionsBundle(config, command, workspace) {
6698
6774
  if (!content) continue;
6699
6775
  const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
6700
6776
  if (!target) continue;
6701
- mkdirSync6(dirname7(target.targetPath), { recursive: true });
6702
- writeFileSync6(target.targetPath, content, "utf8");
6777
+ mkdirSync7(dirname8(target.targetPath), { recursive: true });
6778
+ writeFileSync7(target.targetPath, content, "utf8");
6703
6779
  materialized.push({
6704
6780
  path: target.relativePath,
6705
6781
  byteSize: Buffer.byteLength(content, "utf8")
@@ -6775,13 +6851,13 @@ function companyPiHomeRoot(baseEnv) {
6775
6851
  const explicitRoot = readString(baseEnv.AMASTER_COMPANY_PI_HOME_ROOT);
6776
6852
  if (explicitRoot) return resolve10(expandHomePath(explicitRoot));
6777
6853
  const configuredPiHome = readString(baseEnv.PI_AGENT_HOME) ?? readString(baseEnv.PI_CODING_AGENT_DIR);
6778
- if (configuredPiHome) return join11(dirname7(resolve10(expandHomePath(configuredPiHome))), "companies");
6779
- return join11(homedir3(), ".amaster-employee", "companies");
6854
+ if (configuredPiHome) return join12(dirname8(resolve10(expandHomePath(configuredPiHome))), "companies");
6855
+ return join12(homedir3(), ".amaster-employee", "companies");
6780
6856
  }
6781
6857
  function companyPiAgentHome(baseEnv, companyId) {
6782
6858
  const segment = safeCompanyPiHomeSegment(companyId);
6783
6859
  if (!segment) return null;
6784
- return join11(companyPiHomeRoot(baseEnv), segment, ".pi");
6860
+ return join12(companyPiHomeRoot(baseEnv), segment, ".pi");
6785
6861
  }
6786
6862
  function commandUsesPiExecutor(command) {
6787
6863
  return readString(asRecord(command.payload).executorKind) === "pi";
@@ -7280,7 +7356,7 @@ function realOrResolvedPath(value) {
7280
7356
  return resolve10(value);
7281
7357
  }
7282
7358
  }
7283
- var LSOF_COMMAND = process.platform === "darwin" && existsSync10("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
7359
+ var LSOF_COMMAND = process.platform === "darwin" && existsSync11("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
7284
7360
  function processCwdForPid(pid) {
7285
7361
  if (process.platform === "linux") {
7286
7362
  try {
@@ -7402,7 +7478,7 @@ function killWorkspaceResidentProcesses(cwd, processGroupId, options = {}) {
7402
7478
  }
7403
7479
  function walkManagedWorkdirs(root) {
7404
7480
  const workdirs = [];
7405
- if (!root || !existsSync10(root)) return workdirs;
7481
+ if (!root || !existsSync11(root)) return workdirs;
7406
7482
  const stack = [root];
7407
7483
  while (stack.length > 0) {
7408
7484
  const current = stack.pop();
@@ -7415,8 +7491,8 @@ function walkManagedWorkdirs(root) {
7415
7491
  }
7416
7492
  for (const entry of entries) {
7417
7493
  if (!entry.isDirectory()) continue;
7418
- const fullPath = join11(current, entry.name);
7419
- if (entry.name === "workdir" && existsSync10(workspaceManifestPath(fullPath))) {
7494
+ const fullPath = join12(current, entry.name);
7495
+ if (entry.name === "workdir" && existsSync11(workspaceManifestPath(fullPath))) {
7420
7496
  workdirs.push(fullPath);
7421
7497
  continue;
7422
7498
  }
@@ -7940,14 +8016,14 @@ async function completeCommand(config, command, status, result2, error) {
7940
8016
  function resultOutboxDir(config) {
7941
8017
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
7942
8018
  if (explicit) return resolve10(expandHomePath(explicit));
7943
- return join11(dirname7(stateFilePath(process.env)), "result-outbox");
8019
+ return join12(dirname8(stateFilePath(process.env)), "result-outbox");
7944
8020
  }
7945
8021
  function resultOutboxInvalidDir(config) {
7946
- return join11(resultOutboxDir(config), "invalid");
8022
+ return join12(resultOutboxDir(config), "invalid");
7947
8023
  }
7948
8024
  function writeResultOutboxEntry(config, entry) {
7949
8025
  const dir = resultOutboxDir(config);
7950
- mkdirSync6(dir, { recursive: true });
8026
+ mkdirSync7(dir, { recursive: true });
7951
8027
  const body = {
7952
8028
  version: 1,
7953
8029
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -7955,16 +8031,16 @@ function writeResultOutboxEntry(config, entry) {
7955
8031
  lastAttemptAt: null,
7956
8032
  ...entry
7957
8033
  };
7958
- writeFileSync6(join11(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
8034
+ writeFileSync7(join12(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
7959
8035
  `, { mode: 384 });
7960
8036
  }
7961
8037
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
7962
8038
  const invalidDir = resultOutboxInvalidDir(config);
7963
- mkdirSync6(invalidDir, { recursive: true });
7964
- const invalidPath = join11(invalidDir, file);
8039
+ mkdirSync7(invalidDir, { recursive: true });
8040
+ const invalidPath = join12(invalidDir, file);
7965
8041
  if (original === void 0) {
7966
8042
  try {
7967
- renameSync3(fullPath, invalidPath);
8043
+ renameSync4(fullPath, invalidPath);
7968
8044
  } catch {
7969
8045
  copyFileSync3(fullPath, invalidPath);
7970
8046
  unlinkSync(fullPath);
@@ -7977,14 +8053,14 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
7977
8053
  ...detail ? { detail: truncateText(detail, 1e3) } : {},
7978
8054
  original
7979
8055
  };
7980
- writeFileSync6(invalidPath, `${JSON.stringify(evidence, null, 2)}
8056
+ writeFileSync7(invalidPath, `${JSON.stringify(evidence, null, 2)}
7981
8057
  `, { mode: 384 });
7982
8058
  unlinkSync(fullPath);
7983
8059
  }
7984
8060
  function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
7985
8061
  let entry;
7986
8062
  try {
7987
- entry = JSON.parse(readFileSync8(fullPath, "utf8"));
8063
+ entry = JSON.parse(readFileSync9(fullPath, "utf8"));
7988
8064
  } catch (err) {
7989
8065
  const message = err instanceof Error ? err.message : String(err);
7990
8066
  moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
@@ -8014,13 +8090,13 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
8014
8090
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
8015
8091
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
8016
8092
  };
8017
- writeFileSync6(fullPath, `${JSON.stringify(next, null, 2)}
8093
+ writeFileSync7(fullPath, `${JSON.stringify(next, null, 2)}
8018
8094
  `, { mode: 384 });
8019
8095
  return next;
8020
8096
  }
8021
8097
  function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err) {
8022
8098
  const invalidDir = resultOutboxInvalidDir(config);
8023
- mkdirSync6(invalidDir, { recursive: true });
8099
+ mkdirSync7(invalidDir, { recursive: true });
8024
8100
  const body = {
8025
8101
  ...entry,
8026
8102
  invalidReason: reason,
@@ -8028,8 +8104,8 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
8028
8104
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
8029
8105
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
8030
8106
  };
8031
- const invalidPath = join11(invalidDir, file);
8032
- writeFileSync6(invalidPath, `${JSON.stringify(body, null, 2)}
8107
+ const invalidPath = join12(invalidDir, file);
8108
+ writeFileSync7(invalidPath, `${JSON.stringify(body, null, 2)}
8033
8109
  `, { mode: 384 });
8034
8110
  try {
8035
8111
  unlinkSync(fullPath);
@@ -8042,11 +8118,11 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
8042
8118
  }
8043
8119
  async function flushResultOutbox(config) {
8044
8120
  const dir = resultOutboxDir(config);
8045
- if (!existsSync10(dir)) return { attempted: 0, completed: 0 };
8121
+ if (!existsSync11(dir)) return { attempted: 0, completed: 0 };
8046
8122
  const files = readdirSync8(dir).filter((name) => name.endsWith(".json")).sort();
8047
8123
  let completed = 0;
8048
8124
  for (const file of files) {
8049
- const fullPath = join11(dir, file);
8125
+ const fullPath = join12(dir, file);
8050
8126
  const entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
8051
8127
  if (!entry) continue;
8052
8128
  try {
@@ -8243,8 +8319,8 @@ async function materializeIssueAttachments(config, command, workspace) {
8243
8319
  runtimeAuth,
8244
8320
  issueId
8245
8321
  );
8246
- const targetDir = join11(workspace.cwd, "input-attachments");
8247
- mkdirSync6(targetDir, { recursive: true });
8322
+ const targetDir = join12(workspace.cwd, "input-attachments");
8323
+ mkdirSync7(targetDir, { recursive: true });
8248
8324
  const usedFilenames = /* @__PURE__ */ new Set();
8249
8325
  const materialized = [];
8250
8326
  for (const [index, rawAttachment] of attachments.entries()) {
@@ -8258,9 +8334,9 @@ async function materializeIssueAttachments(config, command, workspace) {
8258
8334
  filename = `${stem}-${index + 1}${ext}`;
8259
8335
  }
8260
8336
  usedFilenames.add(filename);
8261
- const targetPath = join11(targetDir, filename);
8337
+ const targetPath = join12(targetDir, filename);
8262
8338
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
8263
- writeFileSync6(targetPath, body);
8339
+ writeFileSync7(targetPath, body);
8264
8340
  const attachmentId = readString(attachment.id);
8265
8341
  const actualSha256 = createHash8("sha256").update(body).digest("hex");
8266
8342
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
@@ -8334,9 +8410,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8334
8410
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
8335
8411
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
8336
8412
  }
8337
- const targetRoot = join11(workspace.cwd, "input-artifacts");
8413
+ const targetRoot = join12(workspace.cwd, "input-artifacts");
8338
8414
  rmSync6(targetRoot, { recursive: true, force: true });
8339
- mkdirSync6(targetRoot, { recursive: true });
8415
+ mkdirSync7(targetRoot, { recursive: true });
8340
8416
  const usedPaths = /* @__PURE__ */ new Set();
8341
8417
  const materialized = [];
8342
8418
  for (const [index, rawEntry] of manifest.entries.entries()) {
@@ -8365,17 +8441,17 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8365
8441
  id: attachmentId,
8366
8442
  originalFilename: readString(entry.originalFilename)
8367
8443
  }, index);
8368
- let relativePath = join11("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8444
+ let relativePath = join12("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8369
8445
  if (usedPaths.has(relativePath)) {
8370
8446
  const ext = extname2(filename);
8371
8447
  const stem = ext ? filename.slice(0, -ext.length) : filename;
8372
8448
  filename = `${stem}-${index + 1}${ext}`;
8373
- relativePath = join11("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8449
+ relativePath = join12("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8374
8450
  }
8375
8451
  usedPaths.add(relativePath);
8376
- const targetPath = join11(workspace.cwd, relativePath);
8377
- mkdirSync6(dirname7(targetPath), { recursive: true });
8378
- writeFileSync6(targetPath, body);
8452
+ const targetPath = join12(workspace.cwd, relativePath);
8453
+ mkdirSync7(dirname8(targetPath), { recursive: true });
8454
+ writeFileSync7(targetPath, body);
8379
8455
  chmodSync5(targetPath, 292);
8380
8456
  materialized.push({
8381
8457
  id: attachmentId,
@@ -8395,8 +8471,8 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8395
8471
  version: 1,
8396
8472
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
8397
8473
  };
8398
- const manifestPath = join11(targetRoot, "artifact-input-manifest.json");
8399
- writeFileSync6(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
8474
+ const manifestPath = join12(targetRoot, "artifact-input-manifest.json");
8475
+ writeFileSync7(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
8400
8476
  chmodSync5(manifestPath, 292);
8401
8477
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
8402
8478
  await ingestLog(config, command, "system", "info", `Materialized ${materialized.length} required artifact input(s) into the execution workspace`, {
@@ -8406,11 +8482,11 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8406
8482
  return materialized;
8407
8483
  }
8408
8484
  function issueCheckpointDir(workspace) {
8409
- return join11(dirname7(workspace.runDir), "checkpoint");
8485
+ return join12(dirname8(workspace.runDir), "checkpoint");
8410
8486
  }
8411
8487
  async function clearIssueCheckpoint(config, command, workspace, reason) {
8412
8488
  const checkpointDir = issueCheckpointDir(workspace);
8413
- if (!existsSync10(checkpointDir)) return false;
8489
+ if (!existsSync11(checkpointDir)) return false;
8414
8490
  rmSync6(checkpointDir, { recursive: true, force: true });
8415
8491
  await ingestLog(config, command, "system", "info", "Cleared issue continuation checkpoint", { reason });
8416
8492
  return true;
@@ -8424,15 +8500,15 @@ function safeCheckpointRelativePath(rawPath) {
8424
8500
  return normalized;
8425
8501
  }
8426
8502
  function hashFileSha256(filePath) {
8427
- return createHash8("sha256").update(readFileSync8(filePath)).digest("hex");
8503
+ return createHash8("sha256").update(readFileSync9(filePath)).digest("hex");
8428
8504
  }
8429
8505
  async function materializeIssueCheckpoint(config, command, workspace) {
8430
8506
  const checkpointDir = issueCheckpointDir(workspace);
8431
- const manifestPath = join11(checkpointDir, "manifest.json");
8432
- if (!existsSync10(manifestPath)) return [];
8507
+ const manifestPath = join12(checkpointDir, "manifest.json");
8508
+ if (!existsSync11(manifestPath)) return [];
8433
8509
  let manifest;
8434
8510
  try {
8435
- manifest = asRecord(JSON.parse(readFileSync8(manifestPath, "utf8")));
8511
+ manifest = asRecord(JSON.parse(readFileSync9(manifestPath, "utf8")));
8436
8512
  } catch (err) {
8437
8513
  rmSync6(checkpointDir, { recursive: true, force: true });
8438
8514
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
@@ -8445,7 +8521,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8445
8521
  try {
8446
8522
  const files = Array.isArray(manifest.files) ? manifest.files : [];
8447
8523
  if (files.length > 20) throw new Error("issue checkpoint manifest exceeds the limit of 20 files");
8448
- const filesRoot = realpathSync3(join11(checkpointDir, "files"));
8524
+ const filesRoot = realpathSync3(join12(checkpointDir, "files"));
8449
8525
  const workspaceRoot = realpathSync3(workspace.cwd);
8450
8526
  const validated = [];
8451
8527
  let totalBytes = 0;
@@ -8458,7 +8534,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8458
8534
  if (!pathWithin2(sourceCandidate, filesRoot) || !pathWithin2(target, workspaceRoot)) {
8459
8535
  throw new Error(`issue checkpoint path escapes its workspace: ${relativePath}`);
8460
8536
  }
8461
- if (!existsSync10(sourceCandidate)) throw new Error(`issue checkpoint file is missing: ${relativePath}`);
8537
+ if (!existsSync11(sourceCandidate)) throw new Error(`issue checkpoint file is missing: ${relativePath}`);
8462
8538
  const source = realpathSync3(sourceCandidate);
8463
8539
  if (!pathWithin2(source, filesRoot) || !statSync7(source).isFile()) {
8464
8540
  throw new Error(`issue checkpoint source escapes its storage root: ${relativePath}`);
@@ -8483,8 +8559,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8483
8559
  } catch (err) {
8484
8560
  if (err?.code !== "ENOENT") throw err;
8485
8561
  }
8486
- mkdirSync6(dirname7(target), { recursive: true });
8487
- const targetParent = realpathSync3(dirname7(target));
8562
+ mkdirSync7(dirname8(target), { recursive: true });
8563
+ const targetParent = realpathSync3(dirname8(target));
8488
8564
  if (!pathWithin2(targetParent, workspaceRoot)) {
8489
8565
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
8490
8566
  }
@@ -8512,16 +8588,16 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8512
8588
  }
8513
8589
  async function saveIssueCheckpoint(config, command, workspace, candidates) {
8514
8590
  const checkpointDir = issueCheckpointDir(workspace);
8515
- const filesDir = join11(checkpointDir, "files");
8591
+ const filesDir = join12(checkpointDir, "files");
8516
8592
  rmSync6(checkpointDir, { recursive: true, force: true });
8517
- mkdirSync6(filesDir, { recursive: true });
8593
+ mkdirSync7(filesDir, { recursive: true });
8518
8594
  const files = [];
8519
8595
  let totalBytes = 0;
8520
8596
  const workspaceRoot = realpathSync3(workspace.cwd);
8521
8597
  for (const candidate of candidates.slice(0, 20)) {
8522
8598
  const relativePath = safeCheckpointRelativePath(candidate.rawPath);
8523
8599
  const source = readString(candidate.filePath);
8524
- if (!relativePath || !source || !existsSync10(source) || !statSync7(source).isFile()) continue;
8600
+ if (!relativePath || !source || !existsSync11(source) || !statSync7(source).isFile()) continue;
8525
8601
  const ownedSource = realpathSync3(source);
8526
8602
  if (!pathWithin2(ownedSource, workspaceRoot)) {
8527
8603
  throw new Error(`issue checkpoint source escapes its execution workspace: ${relativePath}`);
@@ -8530,7 +8606,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
8530
8606
  if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) continue;
8531
8607
  const target = resolve10(filesDir, relativePath);
8532
8608
  if (!pathWithin2(target, filesDir)) continue;
8533
- mkdirSync6(dirname7(target), { recursive: true });
8609
+ mkdirSync7(dirname8(target), { recursive: true });
8534
8610
  copyFileSync3(ownedSource, target);
8535
8611
  totalBytes += byteSize;
8536
8612
  files.push({ path: relativePath, byteSize, sha256: hashFileSha256(ownedSource) });
@@ -8548,7 +8624,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
8548
8624
  totalBytes,
8549
8625
  files
8550
8626
  };
8551
- writeFileSync6(join11(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8627
+ writeFileSync7(join12(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8552
8628
  `);
8553
8629
  await ingestLog(config, command, "system", "warn", `Saved ${files.length} required deliverable(s) for continuation recovery`, manifest);
8554
8630
  return manifest;
@@ -8620,11 +8696,13 @@ async function executeRunCommand(config, command) {
8620
8696
  let managedMcpProfile = null;
8621
8697
  let managedMcpCleanup = null;
8622
8698
  let cleanupManagedMcpProfile = null;
8699
+ const providerProtectedValues = [];
8623
8700
  let piChildIsolation = null;
8624
8701
  let trustedPiRuntime = null;
8625
8702
  let trustedPiRuntimeSourcePaths = null;
8626
8703
  let trustedPiRuntimeProfile = null;
8627
8704
  let trustedPiRuntimeAudit = null;
8705
+ let piResolvedProviderConfig = null;
8628
8706
  if (executor.kind === "codex" && Object.keys(governedMcp).length > 0) {
8629
8707
  managedMcpProfile = prepareManagedCodexMcpProfile({
8630
8708
  commandId: command.commandId,
@@ -8649,7 +8727,13 @@ async function executeRunCommand(config, command) {
8649
8727
  delete executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL;
8650
8728
  delete executorEnv.AMASTER_PROVIDER_FLASH_MODEL;
8651
8729
  }
8652
- const resolvedProviderConfig = resolvePiExecutorProviderConfig(config, command, executorEnv);
8730
+ piResolvedProviderConfig = resolvePiExecutorProviderConfig(config, command, executorEnv);
8731
+ for (const envName of ["AMASTER_API_KEY", "AMASTER_PLATFORM_OAUTH_TOKEN"]) {
8732
+ const protectedValue = readString(piResolvedProviderConfig.providerConfig[envName]);
8733
+ if (protectedValue && !providerProtectedValues.includes(protectedValue)) {
8734
+ providerProtectedValues.push(protectedValue);
8735
+ }
8736
+ }
8653
8737
  if (Object.keys(governedMcp).length > 0) {
8654
8738
  managedMcpProfile = prepareManagedPiMcpProfile({
8655
8739
  commandId: command.commandId,
@@ -8666,28 +8750,11 @@ async function executeRunCommand(config, command) {
8666
8750
  extraArgs: splitExtraArgs(process.env.AMASTER_PI_EXTRA_ARGS)
8667
8751
  });
8668
8752
  cleanupManagedMcpProfile = cleanupManagedPiMcpProfile;
8669
- try {
8670
- await syncPiExecutorProviderConfig(
8671
- config,
8672
- command,
8673
- readString(managedMcpProfile.env.PI_CODING_AGENT_DIR) ?? readString(managedMcpProfile.env.PI_AGENT_HOME) ?? null,
8674
- resolvedProviderConfig
8675
- );
8676
- const providerCredential = readString(resolvedProviderConfig.providerConfig.AMASTER_API_KEY);
8677
- if (providerCredential && !managedMcpProfile.protectedValues.includes(providerCredential)) {
8678
- managedMcpProfile.protectedValues.push(providerCredential);
8753
+ for (const protectedValue of providerProtectedValues) {
8754
+ if (!managedMcpProfile.protectedValues.includes(protectedValue)) {
8755
+ managedMcpProfile.protectedValues.push(protectedValue);
8679
8756
  }
8680
- } catch (error) {
8681
- cleanupManagedMcpProfile(managedMcpProfile, {
8682
- commandId: command.commandId,
8683
- runId: commandRunId(command)
8684
- });
8685
- managedMcpProfile = null;
8686
- throw error;
8687
8757
  }
8688
- } else {
8689
- const agentDir = piAgentLocalPlatformRunnerEnabled(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;
8690
- await syncPiExecutorProviderConfig(config, command, agentDir, resolvedProviderConfig);
8691
8758
  }
8692
8759
  }
8693
8760
  if (managedMcpProfile) {
@@ -8729,7 +8796,7 @@ async function executeRunCommand(config, command) {
8729
8796
  executorEnv = {
8730
8797
  ...executorEnv,
8731
8798
  AMASTER_MANAGED_RUNTIME_ASSERTION_FD: "3",
8732
- AMASTER_MANAGED_RUNTIME_AUDIT_FILE: join11(
8799
+ AMASTER_MANAGED_RUNTIME_AUDIT_FILE: join12(
8733
8800
  managedMcpProfile.env.HOME,
8734
8801
  ".amaster-managed-runtime-audit.jsonl"
8735
8802
  ),
@@ -8754,6 +8821,26 @@ async function executeRunCommand(config, command) {
8754
8821
  inheritedEntries: trustedPiRuntimeProfile.facts.inheritedEntries
8755
8822
  });
8756
8823
  }
8824
+ if (executor.kind === "pi" && piResolvedProviderConfig) {
8825
+ const agentDir = managedMcpProfile ? readString(managedMcpProfile.env.PI_CODING_AGENT_DIR) ?? readString(managedMcpProfile.env.PI_AGENT_HOME) ?? null : piAgentLocalPlatformRunnerEnabled(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;
8826
+ try {
8827
+ await syncPiExecutorProviderConfig(
8828
+ config,
8829
+ command,
8830
+ agentDir,
8831
+ piResolvedProviderConfig
8832
+ );
8833
+ } catch (error) {
8834
+ if (managedMcpProfile && cleanupManagedMcpProfile) {
8835
+ cleanupManagedMcpProfile(managedMcpProfile, {
8836
+ commandId: command.commandId,
8837
+ runId: commandRunId(command)
8838
+ });
8839
+ managedMcpProfile = null;
8840
+ }
8841
+ throw error;
8842
+ }
8843
+ }
8757
8844
  if (piChildAllocator) {
8758
8845
  try {
8759
8846
  const profileRoot = piChildIsolationProfileRoot({
@@ -8804,7 +8891,7 @@ async function executeRunCommand(config, command) {
8804
8891
  });
8805
8892
  const abortController = new AbortController();
8806
8893
  const stopActiveRunHeartbeats = startActiveRunHeartbeats(config, command, abortController);
8807
- const protectedExecutorValues = managedMcpProfile?.protectedValues ?? (managedMcpProfile ? [governedMcp.sessionToken] : []);
8894
+ const protectedExecutorValues = managedMcpProfile?.protectedValues ?? providerProtectedValues;
8808
8895
  const runtimeArtifacts = [];
8809
8896
  const runtimeArtifactIngest = createRuntimeArtifactIngestQueue({
8810
8897
  ingest: (results) => ingestRuntimeArtifacts(config, command, cwd, results),
@@ -5,7 +5,7 @@ import { dirname, join, resolve } from "node:path";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { fileURLToPath } from "node:url";
7
7
 
8
- const CONNECTOR_VERSION = "0.1.0-beta.32";
8
+ const CONNECTOR_VERSION = "0.1.0-beta.34";
9
9
 
10
10
  const CAPABILITIES = [
11
11
  "remote_registration",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/employee-runtime-connector",
3
- "version": "0.1.0-beta.32",
3
+ "version": "0.1.0-beta.34",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",