@amaster.ai/employee-runtime-connector 0.1.0-beta.33 → 0.1.0-beta.35

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.33";
5600
+ var CONNECTOR_VERSION = "0.1.0-beta.35";
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;
@@ -5447,11 +5645,11 @@ function updateActiveRunWorkspaceManifest(commandId, manifestPath, patch = {}) {
5447
5645
  }
5448
5646
  function resultOutboxPendingCount(config) {
5449
5647
  const dir = resultOutboxDir(config);
5450
- if (!existsSync10(dir)) return 0;
5648
+ if (!existsSync11(dir)) return 0;
5451
5649
  try {
5452
5650
  let pending = 0;
5453
5651
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json"))) {
5454
- if (readValidResultOutboxEntryOrQuarantine(config, file, join11(dir, file))) {
5652
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join12(dir, file))) {
5455
5653
  pending += 1;
5456
5654
  }
5457
5655
  }
@@ -5467,11 +5665,11 @@ function piCompletionOutputType(event) {
5467
5665
  }
5468
5666
  function resultOutboxActiveRunCommands(config) {
5469
5667
  const dir = resultOutboxDir(config);
5470
- if (!existsSync10(dir)) return [];
5668
+ if (!existsSync11(dir)) return [];
5471
5669
  const outboxPending = resultOutboxPendingCount(config);
5472
5670
  const entries = [];
5473
5671
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json")).sort()) {
5474
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join11(dir, file));
5672
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join12(dir, file));
5475
5673
  if (!entry) continue;
5476
5674
  const activeRun = asRecord(entry.activeRun);
5477
5675
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -5501,12 +5699,12 @@ function resultOutboxActiveRunCommands(config) {
5501
5699
  }
5502
5700
  function resultOutboxFailedRunCommands(config) {
5503
5701
  const dir = resultOutboxInvalidDir(config);
5504
- if (!existsSync10(dir)) return [];
5702
+ if (!existsSync11(dir)) return [];
5505
5703
  const entries = [];
5506
5704
  for (const file of readdirSync8(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
5507
5705
  let entry;
5508
5706
  try {
5509
- entry = asRecord(JSON.parse(readFileSync8(join11(dir, file), "utf8")));
5707
+ entry = asRecord(JSON.parse(readFileSync9(join12(dir, file), "utf8")));
5510
5708
  } catch {
5511
5709
  continue;
5512
5710
  }
@@ -5570,7 +5768,7 @@ function safeExpandPath(value) {
5570
5768
  }
5571
5769
  function safeJsonObjectFromFile(filePath) {
5572
5770
  try {
5573
- const parsed = JSON.parse(readFileSync8(filePath, "utf8"));
5771
+ const parsed = JSON.parse(readFileSync9(filePath, "utf8"));
5574
5772
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
5575
5773
  } catch {
5576
5774
  return null;
@@ -5613,10 +5811,10 @@ function safeSkillRootSummary(kind, source, pathValue) {
5613
5811
  try {
5614
5812
  for (const name of readdirSync8(pathValue)) {
5615
5813
  if (name.startsWith(".")) continue;
5616
- const skillDir = join11(pathValue, name);
5814
+ const skillDir = join12(pathValue, name);
5617
5815
  try {
5618
5816
  if (!statSync7(skillDir).isDirectory()) continue;
5619
- if (!existsSync10(join11(skillDir, "SKILL.md"))) continue;
5817
+ if (!existsSync11(join12(skillDir, "SKILL.md"))) continue;
5620
5818
  skillCount += 1;
5621
5819
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
5622
5820
  truncated = true;
@@ -5667,7 +5865,7 @@ function objectKeyCount(value) {
5667
5865
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
5668
5866
  }
5669
5867
  function defaultPiCodingAgentDir() {
5670
- return join11(homedir3(), ".pi", "agent");
5868
+ return join12(homedir3(), ".pi", "agent");
5671
5869
  }
5672
5870
  function piCapabilitySourcesDiagnostics() {
5673
5871
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -5676,11 +5874,11 @@ function piCapabilitySourcesDiagnostics() {
5676
5874
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
5677
5875
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
5678
5876
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
5679
- const userSkillsPath = piAgentHome ? join11(piAgentHome, "skills") : null;
5680
- 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);
5681
5879
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
5682
- const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join11(piAgentHome, "mcp.json") : null);
5683
- 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;
5684
5882
  const skillRoots = [
5685
5883
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
5686
5884
  safeSkillRootSummary(
@@ -5914,10 +6112,10 @@ function piAgentSystemDataDir(config) {
5914
6112
  return configured ? resolve10(expandHomePath(configured)) : null;
5915
6113
  }
5916
6114
  function readPiAgentLocalPlatformCredential(credentialsDir) {
5917
- const pointer = readJsonFile2(join11(credentialsDir, "latest.json"));
6115
+ const pointer = readJsonFile3(join12(credentialsDir, "latest.json"));
5918
6116
  const credentialRef = readString(pointer.credentialRef);
5919
6117
  if (!credentialRef || !/^[a-f0-9]{64}$/i.test(credentialRef)) return null;
5920
- const credential = readJsonFile2(join11(credentialsDir, `${credentialRef}.json`));
6118
+ const credential = readJsonFile3(join12(credentialsDir, `${credentialRef}.json`));
5921
6119
  const organizationId = readString(credential.organizationId);
5922
6120
  const apiKey = readString(credential.apiKey);
5923
6121
  if (credential.version !== 1 || !organizationId || !apiKey) return null;
@@ -5933,7 +6131,7 @@ function piAgentLocalPlatformCredentials(config) {
5933
6131
  if (!piAgentLocalPlatformRunnerEnabled(config)) return [];
5934
6132
  const systemDataDir = piAgentSystemDataDir(config);
5935
6133
  if (!systemDataDir) return [];
5936
- const companiesDir = join11(systemDataDir, "companies");
6134
+ const companiesDir = join12(systemDataDir, "companies");
5937
6135
  let entries = [];
5938
6136
  try {
5939
6137
  entries = readdirSync8(companiesDir, { withFileTypes: true });
@@ -5943,7 +6141,7 @@ function piAgentLocalPlatformCredentials(config) {
5943
6141
  const credentialsByOrganizationId = /* @__PURE__ */ new Map();
5944
6142
  for (const entry of entries) {
5945
6143
  if (!entry.isDirectory()) continue;
5946
- const credential = readPiAgentLocalPlatformCredential(join11(companiesDir, entry.name, "model-credentials"));
6144
+ const credential = readPiAgentLocalPlatformCredential(join12(companiesDir, entry.name, "model-credentials"));
5947
6145
  if (credential) credentialsByOrganizationId.set(credential.organizationId, credential);
5948
6146
  }
5949
6147
  return [...credentialsByOrganizationId.values()];
@@ -6117,7 +6315,7 @@ AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
6117
6315
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
6118
6316
  AMASTER_CAPABILITIES=${quoteShell(config.capabilities.join(","))}
6119
6317
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
6120
- 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"))}
6121
6319
  EOF
6122
6320
 
6123
6321
  set -a
@@ -6305,10 +6503,10 @@ function buildActiveRunCommandStatus(config, entry) {
6305
6503
  const base = {
6306
6504
  ...entry,
6307
6505
  phase: readString(entry.phase) ?? "executing",
6308
- managedWorkdirPresent: entry.workspacePath ? existsSync10(entry.workspacePath) : false,
6506
+ managedWorkdirPresent: entry.workspacePath ? existsSync11(entry.workspacePath) : false,
6309
6507
  outboxPending: resultOutboxPendingCount(config)
6310
6508
  };
6311
- if (!entry.workspacePath || !existsSync10(entry.workspacePath)) return base;
6509
+ if (!entry.workspacePath || !existsSync11(entry.workspacePath)) return base;
6312
6510
  const manifestPath = entry.manifestPath ?? workspaceManifestPath(entry.workspacePath);
6313
6511
  const status = readWorkspaceStatus(entry.workspacePath, { hashCache: workspaceStatusHashCache });
6314
6512
  const artifactCandidates = status.artifacts.slice(0, 20);
@@ -6487,151 +6685,14 @@ function trustedPiRuntimeSources(config) {
6487
6685
  policyFile: config.piRuntimeEffectivePolicyFile
6488
6686
  };
6489
6687
  }
6490
- function readJsonFile2(filePath) {
6688
+ function readJsonFile3(filePath) {
6491
6689
  try {
6492
- const parsed = JSON.parse(readFileSync8(filePath, "utf8"));
6690
+ const parsed = JSON.parse(readFileSync9(filePath, "utf8"));
6493
6691
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
6494
6692
  } catch {
6495
6693
  return {};
6496
6694
  }
6497
6695
  }
6498
- function writeJsonFileAtomic(filePath, value) {
6499
- mkdirSync6(dirname7(filePath), { recursive: true });
6500
- const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}`;
6501
- writeFileSync6(tmpPath, `${JSON.stringify(value, null, 2)}
6502
- `, { mode: 384 });
6503
- renameSync3(tmpPath, filePath);
6504
- }
6505
- function isPlainRecord(value) {
6506
- return value && typeof value === "object" && !Array.isArray(value);
6507
- }
6508
- function imageGenBaseUrlFromProviderBaseUrl(value) {
6509
- const input = readString(value);
6510
- if (!input) return void 0;
6511
- try {
6512
- const url = new URL(input);
6513
- const pathname = url.pathname.replace(/\/+$/, "");
6514
- if (pathname.toLowerCase().endsWith("/v1")) {
6515
- url.pathname = pathname.slice(0, -"/v1".length) || "/";
6516
- }
6517
- return url.toString();
6518
- } catch {
6519
- return input.replace(/\/v1\/?$/, "");
6520
- }
6521
- }
6522
- function ensureAmasterProviderModel(models, modelId, flash) {
6523
- const id = readString(modelId);
6524
- if (!id) return;
6525
- const existing = Array.isArray(models) ? models : [];
6526
- const index = existing.findIndex((entry) => asRecord(entry).id === id);
6527
- if (index >= 0) {
6528
- existing[index] = {
6529
- ...asRecord(existing[index]),
6530
- id,
6531
- input: readStringArray(asRecord(existing[index]).input).length > 0 ? asRecord(existing[index]).input : ["text", "image"],
6532
- reasoning: asRecord(existing[index]).reasoning ?? true,
6533
- ...flash ? { flash: true } : {}
6534
- };
6535
- return;
6536
- }
6537
- existing.push({
6538
- id,
6539
- input: ["text", "image"],
6540
- reasoning: true,
6541
- ...flash ? { flash: true } : {}
6542
- });
6543
- }
6544
- function syncAmasterProviderModels(agentDir, executorEnv) {
6545
- const apiKey = readString(executorEnv.AMASTER_API_KEY);
6546
- if (!apiKey) return false;
6547
- const modelsPath = join11(agentDir, "models.json");
6548
- const config = readJsonFile2(modelsPath);
6549
- const providers = asRecord(config.providers);
6550
- const amaster = { ...asRecord(providers.amaster) };
6551
- amaster.apiKey = apiKey;
6552
- const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
6553
- if (baseUrl) amaster.baseUrl = baseUrl;
6554
- if (!readString(amaster.api)) amaster.api = "openai-completions";
6555
- const models = Array.isArray(amaster.models) ? [...amaster.models] : [];
6556
- ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL, false);
6557
- ensureAmasterProviderModel(models, executorEnv.AMASTER_PROVIDER_FLASH_MODEL, true);
6558
- if (models.length > 0) amaster.models = models;
6559
- writeJsonFileAtomic(modelsPath, {
6560
- ...config,
6561
- providers: {
6562
- ...providers,
6563
- amaster
6564
- }
6565
- });
6566
- return true;
6567
- }
6568
- function syncAmasterProviderSettings(agentDir, executorEnv) {
6569
- const apiKey = readString(executorEnv.AMASTER_API_KEY);
6570
- if (!apiKey) return false;
6571
- const settingsPath = join11(agentDir, "settings.json");
6572
- if (!existsSync10(settingsPath)) return false;
6573
- const settings = readJsonFile2(settingsPath);
6574
- const baseUrl = readString(executorEnv.AMASTER_PROVIDER_BASE_URL);
6575
- const defaultModel = readString(executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL);
6576
- const imageGenBaseUrl = imageGenBaseUrlFromProviderBaseUrl(baseUrl);
6577
- let changed = false;
6578
- if (defaultModel) {
6579
- if (settings.defaultProvider !== "amaster") {
6580
- settings.defaultProvider = "amaster";
6581
- changed = true;
6582
- }
6583
- if (settings.defaultModel !== defaultModel) {
6584
- settings.defaultModel = defaultModel;
6585
- changed = true;
6586
- }
6587
- }
6588
- const imageGen = settings["pi-image-gen"];
6589
- if (isPlainRecord(imageGen) && isPlainRecord(imageGen.customProviders) && isPlainRecord(imageGen.customProviders.amaster)) {
6590
- const imageGenAmaster = { ...imageGen.customProviders.amaster };
6591
- if (imageGenAmaster.apiKey !== apiKey) {
6592
- imageGenAmaster.apiKey = apiKey;
6593
- changed = true;
6594
- }
6595
- if (imageGenBaseUrl && imageGenAmaster.baseUrl !== imageGenBaseUrl) {
6596
- imageGenAmaster.baseUrl = imageGenBaseUrl;
6597
- changed = true;
6598
- }
6599
- settings["pi-image-gen"] = {
6600
- ...imageGen,
6601
- customProviders: {
6602
- ...imageGen.customProviders,
6603
- amaster: imageGenAmaster
6604
- }
6605
- };
6606
- }
6607
- const webAccess = settings["pi-web-access"];
6608
- if (isPlainRecord(webAccess) && isPlainRecord(webAccess.providers)) {
6609
- const nextWebProviders = { ...webAccess.providers };
6610
- for (const [name, rawProvider] of Object.entries(webAccess.providers)) {
6611
- if (!isPlainRecord(rawProvider)) continue;
6612
- const providerApiKey = readString(rawProvider.apiKey);
6613
- const providerBaseUrl = readString(rawProvider.baseUrl);
6614
- const looksAmasterBacked = name === "amaster" || name === "kimi" || providerApiKey === "${AMASTER_API_KEY}" || providerApiKey === "AMASTER_API_KEY" || providerBaseUrl?.includes("credits.helige") || providerBaseUrl?.includes("credits.amaster");
6615
- if (!looksAmasterBacked) continue;
6616
- const nextProvider = {
6617
- ...rawProvider,
6618
- apiKey,
6619
- ...baseUrl ? { baseUrl } : {}
6620
- };
6621
- if (JSON.stringify(nextProvider) !== JSON.stringify(rawProvider)) {
6622
- nextWebProviders[name] = nextProvider;
6623
- changed = true;
6624
- }
6625
- }
6626
- settings["pi-web-access"] = {
6627
- ...webAccess,
6628
- providers: nextWebProviders
6629
- };
6630
- }
6631
- if (!changed) return false;
6632
- writeJsonFileAtomic(settingsPath, settings);
6633
- return true;
6634
- }
6635
6696
  function resolvePiExecutorProviderConfig(config, command, executorEnv) {
6636
6697
  const localPlatformCredential = piAgentLocalPlatformCredentialForCommand(config, command);
6637
6698
  if (piAgentLocalPlatformRunnerEnabled(config) && !localPlatformCredential) {
@@ -6645,8 +6706,7 @@ function resolvePiExecutorProviderConfig(config, command, executorEnv) {
6645
6706
  async function syncPiExecutorProviderConfig(config, command, agentDir, resolvedProviderConfig) {
6646
6707
  if (!agentDir) return;
6647
6708
  const { providerConfig, credentialSource } = resolvedProviderConfig;
6648
- const modelsSynced = syncAmasterProviderModels(agentDir, providerConfig);
6649
- const settingsSynced = syncAmasterProviderSettings(agentDir, providerConfig);
6709
+ const { modelsSynced, settingsSynced } = syncAmasterProviderFiles(agentDir, providerConfig);
6650
6710
  if (modelsSynced || settingsSynced) {
6651
6711
  await ingestLog(config, command, "system", "info", "Synced AMaster provider config for pi executor", {
6652
6712
  modelsSynced,
@@ -6714,8 +6774,8 @@ async function materializeAgentInstructionsBundle(config, command, workspace) {
6714
6774
  if (!content) continue;
6715
6775
  const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
6716
6776
  if (!target) continue;
6717
- mkdirSync6(dirname7(target.targetPath), { recursive: true });
6718
- writeFileSync6(target.targetPath, content, "utf8");
6777
+ mkdirSync7(dirname8(target.targetPath), { recursive: true });
6778
+ writeFileSync7(target.targetPath, content, "utf8");
6719
6779
  materialized.push({
6720
6780
  path: target.relativePath,
6721
6781
  byteSize: Buffer.byteLength(content, "utf8")
@@ -6791,13 +6851,13 @@ function companyPiHomeRoot(baseEnv) {
6791
6851
  const explicitRoot = readString(baseEnv.AMASTER_COMPANY_PI_HOME_ROOT);
6792
6852
  if (explicitRoot) return resolve10(expandHomePath(explicitRoot));
6793
6853
  const configuredPiHome = readString(baseEnv.PI_AGENT_HOME) ?? readString(baseEnv.PI_CODING_AGENT_DIR);
6794
- if (configuredPiHome) return join11(dirname7(resolve10(expandHomePath(configuredPiHome))), "companies");
6795
- return join11(homedir3(), ".amaster-employee", "companies");
6854
+ if (configuredPiHome) return join12(dirname8(resolve10(expandHomePath(configuredPiHome))), "companies");
6855
+ return join12(homedir3(), ".amaster-employee", "companies");
6796
6856
  }
6797
6857
  function companyPiAgentHome(baseEnv, companyId) {
6798
6858
  const segment = safeCompanyPiHomeSegment(companyId);
6799
6859
  if (!segment) return null;
6800
- return join11(companyPiHomeRoot(baseEnv), segment, ".pi");
6860
+ return join12(companyPiHomeRoot(baseEnv), segment, ".pi");
6801
6861
  }
6802
6862
  function commandUsesPiExecutor(command) {
6803
6863
  return readString(asRecord(command.payload).executorKind) === "pi";
@@ -7296,7 +7356,7 @@ function realOrResolvedPath(value) {
7296
7356
  return resolve10(value);
7297
7357
  }
7298
7358
  }
7299
- 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";
7300
7360
  function processCwdForPid(pid) {
7301
7361
  if (process.platform === "linux") {
7302
7362
  try {
@@ -7418,7 +7478,7 @@ function killWorkspaceResidentProcesses(cwd, processGroupId, options = {}) {
7418
7478
  }
7419
7479
  function walkManagedWorkdirs(root) {
7420
7480
  const workdirs = [];
7421
- if (!root || !existsSync10(root)) return workdirs;
7481
+ if (!root || !existsSync11(root)) return workdirs;
7422
7482
  const stack = [root];
7423
7483
  while (stack.length > 0) {
7424
7484
  const current = stack.pop();
@@ -7431,8 +7491,8 @@ function walkManagedWorkdirs(root) {
7431
7491
  }
7432
7492
  for (const entry of entries) {
7433
7493
  if (!entry.isDirectory()) continue;
7434
- const fullPath = join11(current, entry.name);
7435
- if (entry.name === "workdir" && existsSync10(workspaceManifestPath(fullPath))) {
7494
+ const fullPath = join12(current, entry.name);
7495
+ if (entry.name === "workdir" && existsSync11(workspaceManifestPath(fullPath))) {
7436
7496
  workdirs.push(fullPath);
7437
7497
  continue;
7438
7498
  }
@@ -7956,14 +8016,14 @@ async function completeCommand(config, command, status, result2, error) {
7956
8016
  function resultOutboxDir(config) {
7957
8017
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
7958
8018
  if (explicit) return resolve10(expandHomePath(explicit));
7959
- return join11(dirname7(stateFilePath(process.env)), "result-outbox");
8019
+ return join12(dirname8(stateFilePath(process.env)), "result-outbox");
7960
8020
  }
7961
8021
  function resultOutboxInvalidDir(config) {
7962
- return join11(resultOutboxDir(config), "invalid");
8022
+ return join12(resultOutboxDir(config), "invalid");
7963
8023
  }
7964
8024
  function writeResultOutboxEntry(config, entry) {
7965
8025
  const dir = resultOutboxDir(config);
7966
- mkdirSync6(dir, { recursive: true });
8026
+ mkdirSync7(dir, { recursive: true });
7967
8027
  const body = {
7968
8028
  version: 1,
7969
8029
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -7971,16 +8031,16 @@ function writeResultOutboxEntry(config, entry) {
7971
8031
  lastAttemptAt: null,
7972
8032
  ...entry
7973
8033
  };
7974
- writeFileSync6(join11(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
8034
+ writeFileSync7(join12(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
7975
8035
  `, { mode: 384 });
7976
8036
  }
7977
8037
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
7978
8038
  const invalidDir = resultOutboxInvalidDir(config);
7979
- mkdirSync6(invalidDir, { recursive: true });
7980
- const invalidPath = join11(invalidDir, file);
8039
+ mkdirSync7(invalidDir, { recursive: true });
8040
+ const invalidPath = join12(invalidDir, file);
7981
8041
  if (original === void 0) {
7982
8042
  try {
7983
- renameSync3(fullPath, invalidPath);
8043
+ renameSync4(fullPath, invalidPath);
7984
8044
  } catch {
7985
8045
  copyFileSync3(fullPath, invalidPath);
7986
8046
  unlinkSync(fullPath);
@@ -7993,14 +8053,14 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
7993
8053
  ...detail ? { detail: truncateText(detail, 1e3) } : {},
7994
8054
  original
7995
8055
  };
7996
- writeFileSync6(invalidPath, `${JSON.stringify(evidence, null, 2)}
8056
+ writeFileSync7(invalidPath, `${JSON.stringify(evidence, null, 2)}
7997
8057
  `, { mode: 384 });
7998
8058
  unlinkSync(fullPath);
7999
8059
  }
8000
8060
  function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
8001
8061
  let entry;
8002
8062
  try {
8003
- entry = JSON.parse(readFileSync8(fullPath, "utf8"));
8063
+ entry = JSON.parse(readFileSync9(fullPath, "utf8"));
8004
8064
  } catch (err) {
8005
8065
  const message = err instanceof Error ? err.message : String(err);
8006
8066
  moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
@@ -8030,13 +8090,13 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
8030
8090
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
8031
8091
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
8032
8092
  };
8033
- writeFileSync6(fullPath, `${JSON.stringify(next, null, 2)}
8093
+ writeFileSync7(fullPath, `${JSON.stringify(next, null, 2)}
8034
8094
  `, { mode: 384 });
8035
8095
  return next;
8036
8096
  }
8037
8097
  function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err) {
8038
8098
  const invalidDir = resultOutboxInvalidDir(config);
8039
- mkdirSync6(invalidDir, { recursive: true });
8099
+ mkdirSync7(invalidDir, { recursive: true });
8040
8100
  const body = {
8041
8101
  ...entry,
8042
8102
  invalidReason: reason,
@@ -8044,8 +8104,8 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
8044
8104
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
8045
8105
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
8046
8106
  };
8047
- const invalidPath = join11(invalidDir, file);
8048
- writeFileSync6(invalidPath, `${JSON.stringify(body, null, 2)}
8107
+ const invalidPath = join12(invalidDir, file);
8108
+ writeFileSync7(invalidPath, `${JSON.stringify(body, null, 2)}
8049
8109
  `, { mode: 384 });
8050
8110
  try {
8051
8111
  unlinkSync(fullPath);
@@ -8058,11 +8118,11 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
8058
8118
  }
8059
8119
  async function flushResultOutbox(config) {
8060
8120
  const dir = resultOutboxDir(config);
8061
- if (!existsSync10(dir)) return { attempted: 0, completed: 0 };
8121
+ if (!existsSync11(dir)) return { attempted: 0, completed: 0 };
8062
8122
  const files = readdirSync8(dir).filter((name) => name.endsWith(".json")).sort();
8063
8123
  let completed = 0;
8064
8124
  for (const file of files) {
8065
- const fullPath = join11(dir, file);
8125
+ const fullPath = join12(dir, file);
8066
8126
  const entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
8067
8127
  if (!entry) continue;
8068
8128
  try {
@@ -8259,8 +8319,8 @@ async function materializeIssueAttachments(config, command, workspace) {
8259
8319
  runtimeAuth,
8260
8320
  issueId
8261
8321
  );
8262
- const targetDir = join11(workspace.cwd, "input-attachments");
8263
- mkdirSync6(targetDir, { recursive: true });
8322
+ const targetDir = join12(workspace.cwd, "input-attachments");
8323
+ mkdirSync7(targetDir, { recursive: true });
8264
8324
  const usedFilenames = /* @__PURE__ */ new Set();
8265
8325
  const materialized = [];
8266
8326
  for (const [index, rawAttachment] of attachments.entries()) {
@@ -8274,9 +8334,9 @@ async function materializeIssueAttachments(config, command, workspace) {
8274
8334
  filename = `${stem}-${index + 1}${ext}`;
8275
8335
  }
8276
8336
  usedFilenames.add(filename);
8277
- const targetPath = join11(targetDir, filename);
8337
+ const targetPath = join12(targetDir, filename);
8278
8338
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
8279
- writeFileSync6(targetPath, body);
8339
+ writeFileSync7(targetPath, body);
8280
8340
  const attachmentId = readString(attachment.id);
8281
8341
  const actualSha256 = createHash8("sha256").update(body).digest("hex");
8282
8342
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
@@ -8350,9 +8410,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8350
8410
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
8351
8411
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
8352
8412
  }
8353
- const targetRoot = join11(workspace.cwd, "input-artifacts");
8413
+ const targetRoot = join12(workspace.cwd, "input-artifacts");
8354
8414
  rmSync6(targetRoot, { recursive: true, force: true });
8355
- mkdirSync6(targetRoot, { recursive: true });
8415
+ mkdirSync7(targetRoot, { recursive: true });
8356
8416
  const usedPaths = /* @__PURE__ */ new Set();
8357
8417
  const materialized = [];
8358
8418
  for (const [index, rawEntry] of manifest.entries.entries()) {
@@ -8381,17 +8441,17 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8381
8441
  id: attachmentId,
8382
8442
  originalFilename: readString(entry.originalFilename)
8383
8443
  }, index);
8384
- let relativePath = join11("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8444
+ let relativePath = join12("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8385
8445
  if (usedPaths.has(relativePath)) {
8386
8446
  const ext = extname2(filename);
8387
8447
  const stem = ext ? filename.slice(0, -ext.length) : filename;
8388
8448
  filename = `${stem}-${index + 1}${ext}`;
8389
- relativePath = join11("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8449
+ relativePath = join12("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
8390
8450
  }
8391
8451
  usedPaths.add(relativePath);
8392
- const targetPath = join11(workspace.cwd, relativePath);
8393
- mkdirSync6(dirname7(targetPath), { recursive: true });
8394
- writeFileSync6(targetPath, body);
8452
+ const targetPath = join12(workspace.cwd, relativePath);
8453
+ mkdirSync7(dirname8(targetPath), { recursive: true });
8454
+ writeFileSync7(targetPath, body);
8395
8455
  chmodSync5(targetPath, 292);
8396
8456
  materialized.push({
8397
8457
  id: attachmentId,
@@ -8411,8 +8471,8 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8411
8471
  version: 1,
8412
8472
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
8413
8473
  };
8414
- const manifestPath = join11(targetRoot, "artifact-input-manifest.json");
8415
- 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");
8416
8476
  chmodSync5(manifestPath, 292);
8417
8477
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
8418
8478
  await ingestLog(config, command, "system", "info", `Materialized ${materialized.length} required artifact input(s) into the execution workspace`, {
@@ -8422,11 +8482,11 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
8422
8482
  return materialized;
8423
8483
  }
8424
8484
  function issueCheckpointDir(workspace) {
8425
- return join11(dirname7(workspace.runDir), "checkpoint");
8485
+ return join12(dirname8(workspace.runDir), "checkpoint");
8426
8486
  }
8427
8487
  async function clearIssueCheckpoint(config, command, workspace, reason) {
8428
8488
  const checkpointDir = issueCheckpointDir(workspace);
8429
- if (!existsSync10(checkpointDir)) return false;
8489
+ if (!existsSync11(checkpointDir)) return false;
8430
8490
  rmSync6(checkpointDir, { recursive: true, force: true });
8431
8491
  await ingestLog(config, command, "system", "info", "Cleared issue continuation checkpoint", { reason });
8432
8492
  return true;
@@ -8440,15 +8500,15 @@ function safeCheckpointRelativePath(rawPath) {
8440
8500
  return normalized;
8441
8501
  }
8442
8502
  function hashFileSha256(filePath) {
8443
- return createHash8("sha256").update(readFileSync8(filePath)).digest("hex");
8503
+ return createHash8("sha256").update(readFileSync9(filePath)).digest("hex");
8444
8504
  }
8445
8505
  async function materializeIssueCheckpoint(config, command, workspace) {
8446
8506
  const checkpointDir = issueCheckpointDir(workspace);
8447
- const manifestPath = join11(checkpointDir, "manifest.json");
8448
- if (!existsSync10(manifestPath)) return [];
8507
+ const manifestPath = join12(checkpointDir, "manifest.json");
8508
+ if (!existsSync11(manifestPath)) return [];
8449
8509
  let manifest;
8450
8510
  try {
8451
- manifest = asRecord(JSON.parse(readFileSync8(manifestPath, "utf8")));
8511
+ manifest = asRecord(JSON.parse(readFileSync9(manifestPath, "utf8")));
8452
8512
  } catch (err) {
8453
8513
  rmSync6(checkpointDir, { recursive: true, force: true });
8454
8514
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
@@ -8461,7 +8521,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8461
8521
  try {
8462
8522
  const files = Array.isArray(manifest.files) ? manifest.files : [];
8463
8523
  if (files.length > 20) throw new Error("issue checkpoint manifest exceeds the limit of 20 files");
8464
- const filesRoot = realpathSync3(join11(checkpointDir, "files"));
8524
+ const filesRoot = realpathSync3(join12(checkpointDir, "files"));
8465
8525
  const workspaceRoot = realpathSync3(workspace.cwd);
8466
8526
  const validated = [];
8467
8527
  let totalBytes = 0;
@@ -8474,7 +8534,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8474
8534
  if (!pathWithin2(sourceCandidate, filesRoot) || !pathWithin2(target, workspaceRoot)) {
8475
8535
  throw new Error(`issue checkpoint path escapes its workspace: ${relativePath}`);
8476
8536
  }
8477
- 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}`);
8478
8538
  const source = realpathSync3(sourceCandidate);
8479
8539
  if (!pathWithin2(source, filesRoot) || !statSync7(source).isFile()) {
8480
8540
  throw new Error(`issue checkpoint source escapes its storage root: ${relativePath}`);
@@ -8499,8 +8559,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8499
8559
  } catch (err) {
8500
8560
  if (err?.code !== "ENOENT") throw err;
8501
8561
  }
8502
- mkdirSync6(dirname7(target), { recursive: true });
8503
- const targetParent = realpathSync3(dirname7(target));
8562
+ mkdirSync7(dirname8(target), { recursive: true });
8563
+ const targetParent = realpathSync3(dirname8(target));
8504
8564
  if (!pathWithin2(targetParent, workspaceRoot)) {
8505
8565
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
8506
8566
  }
@@ -8528,16 +8588,16 @@ async function materializeIssueCheckpoint(config, command, workspace) {
8528
8588
  }
8529
8589
  async function saveIssueCheckpoint(config, command, workspace, candidates) {
8530
8590
  const checkpointDir = issueCheckpointDir(workspace);
8531
- const filesDir = join11(checkpointDir, "files");
8591
+ const filesDir = join12(checkpointDir, "files");
8532
8592
  rmSync6(checkpointDir, { recursive: true, force: true });
8533
- mkdirSync6(filesDir, { recursive: true });
8593
+ mkdirSync7(filesDir, { recursive: true });
8534
8594
  const files = [];
8535
8595
  let totalBytes = 0;
8536
8596
  const workspaceRoot = realpathSync3(workspace.cwd);
8537
8597
  for (const candidate of candidates.slice(0, 20)) {
8538
8598
  const relativePath = safeCheckpointRelativePath(candidate.rawPath);
8539
8599
  const source = readString(candidate.filePath);
8540
- if (!relativePath || !source || !existsSync10(source) || !statSync7(source).isFile()) continue;
8600
+ if (!relativePath || !source || !existsSync11(source) || !statSync7(source).isFile()) continue;
8541
8601
  const ownedSource = realpathSync3(source);
8542
8602
  if (!pathWithin2(ownedSource, workspaceRoot)) {
8543
8603
  throw new Error(`issue checkpoint source escapes its execution workspace: ${relativePath}`);
@@ -8546,7 +8606,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
8546
8606
  if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) continue;
8547
8607
  const target = resolve10(filesDir, relativePath);
8548
8608
  if (!pathWithin2(target, filesDir)) continue;
8549
- mkdirSync6(dirname7(target), { recursive: true });
8609
+ mkdirSync7(dirname8(target), { recursive: true });
8550
8610
  copyFileSync3(ownedSource, target);
8551
8611
  totalBytes += byteSize;
8552
8612
  files.push({ path: relativePath, byteSize, sha256: hashFileSha256(ownedSource) });
@@ -8564,7 +8624,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates) {
8564
8624
  totalBytes,
8565
8625
  files
8566
8626
  };
8567
- writeFileSync6(join11(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8627
+ writeFileSync7(join12(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
8568
8628
  `);
8569
8629
  await ingestLog(config, command, "system", "warn", `Saved ${files.length} required deliverable(s) for continuation recovery`, manifest);
8570
8630
  return manifest;
@@ -8636,11 +8696,13 @@ async function executeRunCommand(config, command) {
8636
8696
  let managedMcpProfile = null;
8637
8697
  let managedMcpCleanup = null;
8638
8698
  let cleanupManagedMcpProfile = null;
8699
+ const providerProtectedValues = [];
8639
8700
  let piChildIsolation = null;
8640
8701
  let trustedPiRuntime = null;
8641
8702
  let trustedPiRuntimeSourcePaths = null;
8642
8703
  let trustedPiRuntimeProfile = null;
8643
8704
  let trustedPiRuntimeAudit = null;
8705
+ let piResolvedProviderConfig = null;
8644
8706
  if (executor.kind === "codex" && Object.keys(governedMcp).length > 0) {
8645
8707
  managedMcpProfile = prepareManagedCodexMcpProfile({
8646
8708
  commandId: command.commandId,
@@ -8665,7 +8727,13 @@ async function executeRunCommand(config, command) {
8665
8727
  delete executorEnv.AMASTER_PROVIDER_DEFAULT_MODEL;
8666
8728
  delete executorEnv.AMASTER_PROVIDER_FLASH_MODEL;
8667
8729
  }
8668
- 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
+ }
8669
8737
  if (Object.keys(governedMcp).length > 0) {
8670
8738
  managedMcpProfile = prepareManagedPiMcpProfile({
8671
8739
  commandId: command.commandId,
@@ -8682,28 +8750,11 @@ async function executeRunCommand(config, command) {
8682
8750
  extraArgs: splitExtraArgs(process.env.AMASTER_PI_EXTRA_ARGS)
8683
8751
  });
8684
8752
  cleanupManagedMcpProfile = cleanupManagedPiMcpProfile;
8685
- try {
8686
- await syncPiExecutorProviderConfig(
8687
- config,
8688
- command,
8689
- readString(managedMcpProfile.env.PI_CODING_AGENT_DIR) ?? readString(managedMcpProfile.env.PI_AGENT_HOME) ?? null,
8690
- resolvedProviderConfig
8691
- );
8692
- const providerCredential = readString(resolvedProviderConfig.providerConfig.AMASTER_API_KEY);
8693
- if (providerCredential && !managedMcpProfile.protectedValues.includes(providerCredential)) {
8694
- managedMcpProfile.protectedValues.push(providerCredential);
8753
+ for (const protectedValue of providerProtectedValues) {
8754
+ if (!managedMcpProfile.protectedValues.includes(protectedValue)) {
8755
+ managedMcpProfile.protectedValues.push(protectedValue);
8695
8756
  }
8696
- } catch (error) {
8697
- cleanupManagedMcpProfile(managedMcpProfile, {
8698
- commandId: command.commandId,
8699
- runId: commandRunId(command)
8700
- });
8701
- managedMcpProfile = null;
8702
- throw error;
8703
8757
  }
8704
- } else {
8705
- 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;
8706
- await syncPiExecutorProviderConfig(config, command, agentDir, resolvedProviderConfig);
8707
8758
  }
8708
8759
  }
8709
8760
  if (managedMcpProfile) {
@@ -8745,7 +8796,7 @@ async function executeRunCommand(config, command) {
8745
8796
  executorEnv = {
8746
8797
  ...executorEnv,
8747
8798
  AMASTER_MANAGED_RUNTIME_ASSERTION_FD: "3",
8748
- AMASTER_MANAGED_RUNTIME_AUDIT_FILE: join11(
8799
+ AMASTER_MANAGED_RUNTIME_AUDIT_FILE: join12(
8749
8800
  managedMcpProfile.env.HOME,
8750
8801
  ".amaster-managed-runtime-audit.jsonl"
8751
8802
  ),
@@ -8770,6 +8821,26 @@ async function executeRunCommand(config, command) {
8770
8821
  inheritedEntries: trustedPiRuntimeProfile.facts.inheritedEntries
8771
8822
  });
8772
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
+ }
8773
8844
  if (piChildAllocator) {
8774
8845
  try {
8775
8846
  const profileRoot = piChildIsolationProfileRoot({
@@ -8820,7 +8891,7 @@ async function executeRunCommand(config, command) {
8820
8891
  });
8821
8892
  const abortController = new AbortController();
8822
8893
  const stopActiveRunHeartbeats = startActiveRunHeartbeats(config, command, abortController);
8823
- const protectedExecutorValues = managedMcpProfile?.protectedValues ?? (managedMcpProfile ? [governedMcp.sessionToken] : []);
8894
+ const protectedExecutorValues = managedMcpProfile?.protectedValues ?? providerProtectedValues;
8824
8895
  const runtimeArtifacts = [];
8825
8896
  const runtimeArtifactIngest = createRuntimeArtifactIngestQueue({
8826
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.33";
8
+ const CONNECTOR_VERSION = "0.1.0-beta.35";
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.33",
3
+ "version": "0.1.0-beta.35",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",