@amaster.ai/employee-runtime-connector 0.1.1-beta.16 → 0.1.1-beta.18

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.
@@ -2183,6 +2183,42 @@ function insertSingleMissingObjectPropertyComma(value) {
2183
2183
  return value;
2184
2184
  }
2185
2185
  }
2186
+ function appendSingleMissingClosingDelimiter(value) {
2187
+ const stack = [];
2188
+ let inString = false;
2189
+ let escaped = false;
2190
+ for (const character of value) {
2191
+ if (inString) {
2192
+ if (escaped) {
2193
+ escaped = false;
2194
+ } else if (character === "\\") {
2195
+ escaped = true;
2196
+ } else if (character === '"') {
2197
+ inString = false;
2198
+ }
2199
+ continue;
2200
+ }
2201
+ if (character === '"') {
2202
+ inString = true;
2203
+ continue;
2204
+ }
2205
+ if (character === "{" || character === "[") {
2206
+ stack.push(character);
2207
+ continue;
2208
+ }
2209
+ if (character === "}" || character === "]") {
2210
+ const expected = character === "}" ? "{" : "[";
2211
+ if (stack.pop() !== expected) return value;
2212
+ }
2213
+ }
2214
+ if (inString || stack.length !== 1) return value;
2215
+ const candidate = `${value}${stack[0] === "{" ? "}" : "]"}`;
2216
+ try {
2217
+ return isJsonObject(JSON.parse(candidate)) ? candidate : value;
2218
+ } catch {
2219
+ return value;
2220
+ }
2221
+ }
2186
2222
  function normalizePiMcpProxyArgs(value) {
2187
2223
  if (typeof value !== "string") return { value, repaired: false };
2188
2224
  try {
@@ -2200,7 +2236,9 @@ function normalizePiMcpProxyArgs(value) {
2200
2236
  }
2201
2237
  }
2202
2238
  const commaRepairedValue = insertSingleMissingObjectPropertyComma(repairedControlCharacters);
2203
- return commaRepairedValue !== value ? { value: commaRepairedValue, repaired: true } : { value, repaired: false };
2239
+ if (commaRepairedValue !== value) return { value: commaRepairedValue, repaired: true };
2240
+ const closingDelimiterRepairedValue = appendSingleMissingClosingDelimiter(repairedControlCharacters);
2241
+ return closingDelimiterRepairedValue !== value ? { value: closingDelimiterRepairedValue, repaired: true } : { value, repaired: false };
2204
2242
  }
2205
2243
  }
2206
2244
  function registerManagedPiMcpArgsNormalizer(pi) {
@@ -2216,6 +2254,7 @@ function managedPiMcpArgsNormalizerExtensionSource() {
2216
2254
  escapeLiteralJsonStringControlCharacters.toString(),
2217
2255
  escapeLikelyLiteralJsonStringQuotes.toString(),
2218
2256
  insertSingleMissingObjectPropertyComma.toString(),
2257
+ appendSingleMissingClosingDelimiter.toString(),
2219
2258
  normalizePiMcpProxyArgs.toString(),
2220
2259
  `export default ${registerManagedPiMcpArgsNormalizer.toString()};`,
2221
2260
  ""
@@ -2469,6 +2508,11 @@ function createManagedPiMcpProfileApi(options = {}) {
2469
2508
  "amaster.read_company_diagnosis",
2470
2509
  "amaster.publish_company_diagnosis_brief"
2471
2510
  ]);
2511
+ const DIAGNOSIS_WIKI_READ_DIRECT_TYPED_V1_TOOL_NAMES = /* @__PURE__ */ new Set([
2512
+ "wiki_search",
2513
+ "wiki_read_page",
2514
+ "wiki_list_pages"
2515
+ ]);
2472
2516
  const HYBRID_DIRECT_TYPED_V1_TOOL_NAMES = /* @__PURE__ */ new Set([
2473
2517
  "amaster.read_company_snapshot",
2474
2518
  "runtime_action.describe",
@@ -2481,29 +2525,6 @@ function createManagedPiMcpProfileApi(options = {}) {
2481
2525
  const MINIMUM_MCP_ADAPTER_VERSION = [2, 6, 1];
2482
2526
  const MANAGED_BROWSER_USE_PACKAGE = "@amaster.ai/pi-browser-use";
2483
2527
  const MANAGED_BROWSER_USE_PLUGIN = "browser-use";
2484
- const MANAGED_WEB_ACCESS_PACKAGE = "@amaster.ai/pi-web-access";
2485
- const MANAGED_TELEMETRY_PACKAGE = "@amaster.ai/pi-telemetry";
2486
- const MANAGED_TELEMETRY_ENV_NAMES = [
2487
- "PI_TELEMETRY_TASK_RUN_ID",
2488
- "PI_TELEMETRY_SERVICE_NAME",
2489
- "PI_TELEMETRY_SERVICE_VERSION",
2490
- "PI_TELEMETRY_INCLUDE_PAYLOADS",
2491
- "PI_TELEMETRY_LANGFUSE_ENABLED",
2492
- "PI_TELEMETRY_LANGFUSE_PUBLIC_KEY",
2493
- "PI_TELEMETRY_LANGFUSE_SECRET_KEY",
2494
- "PI_TELEMETRY_LANGFUSE_BASE_URL",
2495
- "PI_TELEMETRY_LANGFUSE_FLUSH_AT",
2496
- "PI_TELEMETRY_LANGFUSE_FLUSH_INTERVAL_MS",
2497
- "PI_TELEMETRY_OTEL_ENABLED",
2498
- "PI_TELEMETRY_OTEL_ENDPOINT",
2499
- "PI_TELEMETRY_OTEL_HEADERS",
2500
- "PI_TELEMETRY_OTEL_FLUSH_AT",
2501
- "PI_TELEMETRY_OTEL_FLUSH_INTERVAL_MS"
2502
- ];
2503
- const MANAGED_TELEMETRY_PROTECTED_ENV_NAMES = [
2504
- "PI_TELEMETRY_LANGFUSE_SECRET_KEY",
2505
- "PI_TELEMETRY_OTEL_HEADERS"
2506
- ];
2507
2528
  const MANAGED_BROWSER_USE_BOOLEAN_SETTINGS = [
2508
2529
  "headless",
2509
2530
  "categoryNetwork",
@@ -2530,6 +2551,12 @@ function createManagedPiMcpProfileApi(options = {}) {
2530
2551
  "AMASTER-CLI_CODING_AGENT_SESSION_DIR",
2531
2552
  "PI_AGENT_MCP_SERVERS_FILE"
2532
2553
  ]);
2554
+ const RUN_OWNED_SETTINGS_ENV = /* @__PURE__ */ new Set([
2555
+ ...FORBIDDEN_COMMAND_ENV2,
2556
+ "MCP_DIRECT_TOOLS",
2557
+ "PAPERCLIP_API_KEY",
2558
+ "AMASTER_BOARD_API_KEY"
2559
+ ]);
2533
2560
  const ALLOWED_COMMAND_ENV2 = new Set(MANAGED_PI_PROVIDER_ENV_NAMES);
2534
2561
  const SAFE_INHERITED_ENV2 = /* @__PURE__ */ new Set([
2535
2562
  "PATH",
@@ -2555,8 +2582,7 @@ function createManagedPiMcpProfileApi(options = {}) {
2555
2582
  "PAPERCLIP_TASK_ID",
2556
2583
  "PAPERCLIP_AGENT_ID",
2557
2584
  "PAPERCLIP_COMPANY_ID",
2558
- "AMASTER_EMPLOYEE_COMPANY_ID",
2559
- ...MANAGED_TELEMETRY_ENV_NAMES
2585
+ "AMASTER_EMPLOYEE_COMPANY_ID"
2560
2586
  ]);
2561
2587
  const FORBIDDEN_ARGV = /* @__PURE__ */ new Set([
2562
2588
  "--no-tools",
@@ -2731,8 +2757,9 @@ function createManagedPiMcpProfileApi(options = {}) {
2731
2757
  throw new Error("pi_managed_mcp_invalid: direct tool catalog schema mismatch");
2732
2758
  }
2733
2759
  const tools = Array.isArray(catalog.tools) ? catalog.tools.map(record8) : [];
2734
- const admittedToolNames = mcpToolMode === MANAGED_PI_HYBRID_MCP_TOOL_MODE ? HYBRID_DIRECT_TYPED_V1_TOOL_NAMES : DIRECT_TYPED_V1_TOOL_NAMES;
2735
- if (tools.length !== admittedToolNames.size) {
2760
+ const admittedToolNames = mcpToolMode === MANAGED_PI_HYBRID_MCP_TOOL_MODE ? HYBRID_DIRECT_TYPED_V1_TOOL_NAMES : /* @__PURE__ */ new Set([...DIRECT_TYPED_V1_TOOL_NAMES, ...DIAGNOSIS_WIKI_READ_DIRECT_TYPED_V1_TOOL_NAMES]);
2761
+ const directTypedSizeValid = mcpToolMode !== MANAGED_PI_DIRECT_TYPED_MCP_TOOL_MODE || tools.length === DIRECT_TYPED_V1_TOOL_NAMES.size || tools.length === DIRECT_TYPED_V1_TOOL_NAMES.size + DIAGNOSIS_WIKI_READ_DIRECT_TYPED_V1_TOOL_NAMES.size;
2762
+ if (!directTypedSizeValid || mcpToolMode === MANAGED_PI_HYBRID_MCP_TOOL_MODE && tools.length !== admittedToolNames.size) {
2736
2763
  throw new Error("pi_managed_mcp_invalid: direct tool catalog size mismatch");
2737
2764
  }
2738
2765
  const names = /* @__PURE__ */ new Set();
@@ -2777,6 +2804,15 @@ function createManagedPiMcpProfileApi(options = {}) {
2777
2804
  effectiveSchemaHash: stablePiToolSchemaHash(inputSchema, { adapterNormalized: true })
2778
2805
  };
2779
2806
  });
2807
+ if (mcpToolMode === MANAGED_PI_DIRECT_TYPED_MCP_TOOL_MODE) {
2808
+ for (const name of DIRECT_TYPED_V1_TOOL_NAMES) {
2809
+ if (!names.has(name)) throw new Error("pi_managed_mcp_invalid: direct tool catalog name mismatch");
2810
+ }
2811
+ const wikiReadCount = [...DIAGNOSIS_WIKI_READ_DIRECT_TYPED_V1_TOOL_NAMES].filter((name) => names.has(name)).length;
2812
+ if (wikiReadCount !== 0 && wikiReadCount !== DIAGNOSIS_WIKI_READ_DIRECT_TYPED_V1_TOOL_NAMES.size) {
2813
+ throw new Error("pi_managed_mcp_invalid: diagnosis wiki read catalog incomplete");
2814
+ }
2815
+ }
2780
2816
  const setHash = stablePiDirectCatalogSetHash(normalized.map((tool) => ({
2781
2817
  name: tool.name,
2782
2818
  exposedName: tool.exposedName,
@@ -2877,13 +2913,38 @@ function createManagedPiMcpProfileApi(options = {}) {
2877
2913
  return /^(?:(?:access|refresh|id)_)?token$/.test(normalized) || normalized.includes("api_key") || normalized.includes("secret") || normalized.includes("password") || normalized.includes("credential") || normalized.includes("authorization") || normalized.includes("cookie");
2878
2914
  }
2879
2915
  function collectAuthSecretStrings2(value, output = []) {
2880
- if (!value || typeof value !== "object" || Array.isArray(value)) return output;
2916
+ if (!value || typeof value !== "object") return output;
2917
+ if (Array.isArray(value)) {
2918
+ for (const entry of value) collectAuthSecretStrings2(entry, output);
2919
+ return output;
2920
+ }
2881
2921
  for (const [key, entry] of Object.entries(value)) {
2882
2922
  if (typeof entry === "string" && entry && isSensitiveAuthKey2(key)) output.push(entry);
2883
- else if (entry && typeof entry === "object" && !Array.isArray(entry)) collectAuthSecretStrings2(entry, output);
2923
+ else if (entry && typeof entry === "object") collectAuthSecretStrings2(entry, output);
2884
2924
  }
2885
2925
  return output;
2886
2926
  }
2927
+ function referencedSettingsEnvironment(settings, baseEnv) {
2928
+ const names = /* @__PURE__ */ new Set();
2929
+ const visit = (value) => {
2930
+ if (typeof value === "string") {
2931
+ for (const match of value.matchAll(/\$(?:\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}|([A-Za-z_][A-Za-z0-9_]*))/g)) {
2932
+ names.add(match[1] ?? match[2]);
2933
+ }
2934
+ } else if (Array.isArray(value)) {
2935
+ for (const entry of value) visit(entry);
2936
+ } else if (value && typeof value === "object") {
2937
+ for (const entry of Object.values(value)) visit(entry);
2938
+ }
2939
+ };
2940
+ visit(settings);
2941
+ const env = {};
2942
+ for (const name of names) {
2943
+ if (RUN_OWNED_SETTINGS_ENV.has(name)) continue;
2944
+ if (typeof baseEnv?.[name] === "string" && baseEnv[name]) env[name] = baseEnv[name];
2945
+ }
2946
+ return env;
2947
+ }
2887
2948
  function assertInvocationIsolation2(input) {
2888
2949
  for (const name of Object.keys(record8(input.commandEnv))) {
2889
2950
  if (FORBIDDEN_COMMAND_ENV2.has(name)) throw new Error(`pi_managed_mcp_env_override_blocked: ${name}`);
@@ -2993,49 +3054,7 @@ function createManagedPiMcpProfileApi(options = {}) {
2993
3054
  }
2994
3055
  };
2995
3056
  }
2996
- function selectManagedWebAccess(sourceSettings, npmSource) {
2997
- const packageSpec = Array.isArray(sourceSettings.packages) ? sourceSettings.packages.find((entry) => npmPackageName(entry) === MANAGED_WEB_ACCESS_PACKAGE) : null;
2998
- if (typeof packageSpec !== "string") return null;
2999
- const packagePath = join4(npmSource, "node_modules", ...MANAGED_WEB_ACCESS_PACKAGE.split("/"), "package.json");
3000
- if (!existsSync3(packagePath) || lstatSync2(packagePath).isSymbolicLink() || !lstatSync2(packagePath).isFile()) {
3001
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_WEB_ACCESS_PACKAGE} package is unavailable`);
3002
- }
3003
- let packageMetadata;
3004
- try {
3005
- packageMetadata = JSON.parse(readFileSync3(packagePath, "utf8"));
3006
- } catch {
3007
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_WEB_ACCESS_PACKAGE} package metadata is invalid`);
3008
- }
3009
- if (!packageMetadata || packageMetadata.name !== MANAGED_WEB_ACCESS_PACKAGE) {
3010
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_WEB_ACCESS_PACKAGE} package identity mismatch`);
3011
- }
3012
- return {
3013
- packageSpec,
3014
- config: record8(sourceSettings["pi-web-access"])
3015
- };
3016
- }
3017
- function selectManagedTelemetry(sourceSettings, npmSource) {
3018
- const packageSpec = Array.isArray(sourceSettings.packages) ? sourceSettings.packages.find((entry) => npmPackageName(entry) === MANAGED_TELEMETRY_PACKAGE) : null;
3019
- if (typeof packageSpec !== "string") return null;
3020
- const packagePath = join4(npmSource, "node_modules", ...MANAGED_TELEMETRY_PACKAGE.split("/"), "package.json");
3021
- if (!existsSync3(packagePath) || lstatSync2(packagePath).isSymbolicLink() || !lstatSync2(packagePath).isFile()) {
3022
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_TELEMETRY_PACKAGE} package is unavailable`);
3023
- }
3024
- let packageMetadata;
3025
- try {
3026
- packageMetadata = JSON.parse(readFileSync3(packagePath, "utf8"));
3027
- } catch {
3028
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_TELEMETRY_PACKAGE} package metadata is invalid`);
3029
- }
3030
- if (packageMetadata.name !== MANAGED_TELEMETRY_PACKAGE) {
3031
- throw new Error(`pi_managed_mcp_attestation_failed: configured ${MANAGED_TELEMETRY_PACKAGE} package identity mismatch`);
3032
- }
3033
- return {
3034
- packageSpec,
3035
- config: record8(sourceSettings["pi-telemetry"])
3036
- };
3037
- }
3038
- function seedPiRuntime(sourceHome, agentDir, sourceAcquisition = null, mcpToolMode = MANAGED_PI_MCP_TOOL_MODE) {
3057
+ function seedPiRuntime(sourceHome, agentDir, sourceAcquisition = null, mcpToolMode = MANAGED_PI_MCP_TOOL_MODE, baseEnv = {}) {
3039
3058
  const source = resolve2(nonEmpty2(sourceHome, "sourcePiHome"));
3040
3059
  const sourceStat = lstatSync2(source);
3041
3060
  if (!sourceStat.isDirectory() || sourceStat.isSymbolicLink()) {
@@ -3063,30 +3082,20 @@ function createManagedPiMcpProfileApi(options = {}) {
3063
3082
  throw new Error("pi_managed_mcp_attestation_failed: source Pi settings are invalid");
3064
3083
  }
3065
3084
  }
3066
- const browserUse = selectManagedBrowserUse(sourceSettings, npmSource);
3067
- const webAccess = sourceAcquisition ? null : selectManagedWebAccess(sourceSettings, npmSource);
3068
- const telemetry = selectManagedTelemetry(sourceSettings, npmSource);
3085
+ const browserUse = sourceAcquisition ? selectManagedBrowserUse(sourceSettings, npmSource) : null;
3069
3086
  if (sourceAcquisition && !browserUse) {
3070
3087
  throw new Error("pi_managed_mcp_source_acquisition_packages_missing");
3071
3088
  }
3072
- const settings = {
3089
+ const sourcePackages = Array.isArray(sourceSettings.packages) ? [...sourceSettings.packages] : [];
3090
+ const settings = sourceAcquisition ? {
3073
3091
  ...typeof sourceSettings.defaultProvider === "string" ? { defaultProvider: sourceSettings.defaultProvider } : {},
3074
3092
  ...typeof sourceSettings.defaultModel === "string" ? { defaultModel: sourceSettings.defaultModel } : {},
3075
- packages: [
3076
- "npm:pi-mcp-adapter",
3077
- ...telemetry ? [telemetry.packageSpec] : [],
3078
- ...webAccess ? [webAccess.packageSpec] : [],
3079
- ...!sourceAcquisition && browserUse ? [browserUse.packageSpec] : []
3080
- ],
3081
- ...telemetry ? { "pi-telemetry": telemetry.config } : {},
3082
- ...webAccess ? { "pi-web-access": webAccess.config } : {},
3083
- ...!sourceAcquisition && browserUse ? {
3084
- plugins: {
3085
- [MANAGED_BROWSER_USE_PLUGIN]: browserUse.plugin
3086
- },
3087
- "pi-browser-use": browserUse.config
3088
- } : {}
3093
+ packages: ["npm:pi-mcp-adapter"]
3094
+ } : {
3095
+ ...sourceSettings,
3096
+ packages: sourcePackages.some((entry) => npmPackageName(entry) === "pi-mcp-adapter") ? sourcePackages : ["npm:pi-mcp-adapter", ...sourcePackages]
3089
3097
  };
3098
+ const settingsEnv = sourceAcquisition ? {} : referencedSettingsEnvironment(settings, baseEnv);
3090
3099
  writePrivateFile2(join4(agentDir, "settings.json"), `${JSON.stringify(settings, null, 2)}
3091
3100
  `);
3092
3101
  const extensionsDir = join4(agentDir, "extensions");
@@ -3112,7 +3121,10 @@ function createManagedPiMcpProfileApi(options = {}) {
3112
3121
  copyPrivateFile(join4(source, "models.json"), join4(agentDir, "models.json"));
3113
3122
  copyPrivateFile(join4(source, "SYSTEM.md"), join4(agentDir, "SYSTEM.md"));
3114
3123
  const authSource = join4(source, "auth.json");
3115
- const protectedValues = [];
3124
+ const protectedValues = collectAuthSecretStrings2(settings);
3125
+ for (const [name, value] of Object.entries(settingsEnv)) {
3126
+ if (isSensitiveAuthKey2(name)) protectedValues.push(value);
3127
+ }
3116
3128
  if (copyPrivateFile(authSource, join4(agentDir, "auth.json"))) {
3117
3129
  try {
3118
3130
  collectAuthSecretStrings2(JSON.parse(readFileSync3(authSource, "utf8")), protectedValues);
@@ -3123,7 +3135,7 @@ function createManagedPiMcpProfileApi(options = {}) {
3123
3135
  const npmStat = lstatSync2(npmSource);
3124
3136
  if (!npmStat.isDirectory() || npmStat.isSymbolicLink()) throw new Error("pi_managed_mcp_source_config_unsafe: Pi npm root");
3125
3137
  symlinkSync(npmSource, join4(agentDir, "npm"), "dir");
3126
- return { adapterVersion, protectedValues };
3138
+ return { adapterVersion, protectedValues, settingsEnv };
3127
3139
  }
3128
3140
  function seedDelegatedPiRuntime(sourceHome, agentDir) {
3129
3141
  const source = resolve2(nonEmpty2(sourceHome, "sourcePiHome"));
@@ -3309,7 +3321,13 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3309
3321
  commandId: input.commandId
3310
3322
  });
3311
3323
  const sourcePiHome = nonEmpty2(input.baseEnv?.PI_CODING_AGENT_DIR ?? input.baseEnv?.PI_AGENT_HOME, "sourcePiHome");
3312
- const seededRuntime = seedPiRuntime(sourcePiHome, piCodingAgentDir, input.sourceAcquisition, mcpToolMode);
3324
+ const seededRuntime = seedPiRuntime(
3325
+ sourcePiHome,
3326
+ piCodingAgentDir,
3327
+ input.sourceAcquisition,
3328
+ mcpToolMode,
3329
+ input.baseEnv
3330
+ );
3313
3331
  const restoredNativeSession = restoreManagedPiSessionRollout(input, sessionsRoot, runDir, executorHome, authority);
3314
3332
  const configPath = join4(piCodingAgentDir, "mcp.json");
3315
3333
  const directToolNames = directCatalog?.tools.map((tool) => tool.exposedName) ?? [];
@@ -3388,6 +3406,7 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3388
3406
  };
3389
3407
  }
3390
3408
  const env = {
3409
+ ...seededRuntime.settingsEnv,
3391
3410
  ...buildIsolatedEnvironment2(input.baseEnv, input.commandEnv),
3392
3411
  HOME: home,
3393
3412
  PI_AGENT_HOME: piAgentHome,
@@ -3442,7 +3461,6 @@ ${result3.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
3442
3461
  protectedValues: [.../* @__PURE__ */ new Set([
3443
3462
  sessionToken,
3444
3463
  ...seededRuntime.protectedValues,
3445
- ...MANAGED_TELEMETRY_PROTECTED_ENV_NAMES.map((name) => input.baseEnv?.[name]).filter((value) => typeof value === "string" && value.length > 0),
3446
3464
  ...MANAGED_PI_PROVIDER_PROTECTED_ENV_NAMES.map((name) => input.commandEnv?.[name]).filter((value) => typeof value === "string" && value.length > 0)
3447
3465
  ])],
3448
3466
  attestation: {
@@ -4415,24 +4433,56 @@ function resolvedDependencySections(context, input, contextScope, snapshotFreshn
4415
4433
  overflowRefs
4416
4434
  };
4417
4435
  }
4418
- function verifiedCompanyContextSection(context) {
4419
- const companyContext = asRecord(context.verifiedCompanyContext);
4420
- if (Object.keys(companyContext).length === 0) return { content: "", sourceRef: [], observedAt: [] };
4436
+ function projectModelFactRecord(value, seenFacts) {
4437
+ return Object.fromEntries(Object.entries(asRecord(value)).sort(([left], [right]) => left.localeCompare(right)).flatMap(([key, rawValue]) => {
4438
+ if (typeof rawValue !== "string" || !rawValue.trim()) return [];
4439
+ const normalizedValue = rawValue.trim();
4440
+ const fingerprint = `${key}\0${normalizedValue}`;
4441
+ if (seenFacts.has(fingerprint)) return [];
4442
+ seenFacts.add(fingerprint);
4443
+ return [[key, normalizedValue]];
4444
+ }));
4445
+ }
4446
+ function projectVerifiedCompanyContextForModel(value) {
4447
+ const companyContext = asRecord(value);
4448
+ if (Object.keys(companyContext).length === 0) return {};
4421
4449
  if (companyContext.schemaVersion !== "mirrorx.verified-company-context.v1") {
4422
4450
  throw new Error("verified_company_context_invalid: unsupported schemaVersion");
4423
4451
  }
4424
4452
  const company = asRecord(companyContext.company);
4425
- const registration = asRecord(companyContext.registration);
4426
4453
  const companyId = readString(company.id);
4427
4454
  const companyName = readString(company.name);
4428
4455
  if (!companyId || !companyName) {
4429
4456
  throw new Error("verified_company_context_invalid: company id and name are required");
4430
4457
  }
4458
+ const seenFacts = /* @__PURE__ */ new Set([`companyName\0${companyName}`]);
4459
+ const confirmedProfileFacts = projectModelFactRecord(companyContext.confirmedProfileFacts, seenFacts);
4460
+ const confirmedOnboardingFacts = projectModelFactRecord(companyContext.confirmedOnboardingFacts, seenFacts);
4461
+ const verifiedRegistrationFacts = projectModelFactRecord(
4462
+ asRecord(companyContext.registration).facts,
4463
+ seenFacts
4464
+ );
4465
+ const knownUnknowns = Array.isArray(companyContext.unavailableFromCurrentVerification) ? [...new Set(companyContext.unavailableFromCurrentVerification.map(readString).filter(Boolean))] : [];
4466
+ return {
4467
+ companyName,
4468
+ ...Object.keys(confirmedProfileFacts).length > 0 ? { confirmedProfileFacts } : {},
4469
+ ...Object.keys(confirmedOnboardingFacts).length > 0 ? { confirmedOnboardingFacts } : {},
4470
+ ...Object.keys(verifiedRegistrationFacts).length > 0 ? { verifiedRegistrationFacts } : {},
4471
+ ...knownUnknowns.length > 0 ? { knownUnknowns } : {}
4472
+ };
4473
+ }
4474
+ function verifiedCompanyContextSection(context) {
4475
+ const companyContext = asRecord(context.verifiedCompanyContext);
4476
+ const modelContext = projectVerifiedCompanyContextForModel(companyContext);
4477
+ if (Object.keys(modelContext).length === 0) return { content: "", sourceRef: [], observedAt: [] };
4478
+ const company = asRecord(companyContext.company);
4479
+ const registration = asRecord(companyContext.registration);
4480
+ const companyId = readString(company.id);
4431
4481
  return {
4432
4482
  content: [
4433
4483
  "Use these server-snapshotted current Company facts as authoritative context for this run.",
4434
- "The current verification contract does not supply shareholder structure or a financial baseline; treat them as unknown unless separate evidence is present, and do not describe the verified registration facts below as missing.",
4435
- jsonText(companyContext)
4484
+ "Treat fields listed under knownUnknowns as unknown unless separate evidence is present; do not describe the supplied verified facts as missing.",
4485
+ jsonText(modelContext)
4436
4486
  ].join("\n"),
4437
4487
  sourceRef: [
4438
4488
  `company:${companyId}`,
@@ -4528,7 +4578,7 @@ function taskContextAuthoritySection(context) {
4528
4578
  if (sourceRefs.length === 0) return null;
4529
4579
  return {
4530
4580
  content: [
4531
- "Immutable Task admission context authority. It identifies admitted sources and automatic memory policy; it does not replace the runtime Context Manifest below.",
4581
+ "Immutable Task admission context authority. It identifies admitted sources and automatic memory policy; it is model-visible execution input and is distinct from the audit-only runtime Context Manifest.",
4532
4582
  jsonText({
4533
4583
  version: manifest.version,
4534
4584
  memoryScope: readString(manifest.memoryScope),
@@ -4799,7 +4849,9 @@ function runtimeDecompositionRequirementText(context) {
4799
4849
  return [
4800
4850
  "This issue has a server-enforced typed decomposition requirement.",
4801
4851
  "Create the complete real direct child graph before doing any substantial source work.",
4802
- "Before browsing, searching, commenting, or doing any source work, call runtime_action.describe for create_child_task, persist the complete child graph with runtime_action.plan, and execute it with runtime_action.commit.",
4852
+ "Before browsing, searching, commenting, or doing any source work, call runtime_action.describe for record_work_disposition with dispositionKind create_children and for every child action type you need.",
4853
+ "Persist one immutable runtime_action.plan whose first action is record_work_disposition kind create_children and whose remaining actions are exactly the complete child graph referenced by that disposition. Do not append update_parent, add_comment, upsert_document, or any other action after the child graph.",
4854
+ "Execute that exact plan with runtime_action.commit.",
4803
4855
  "Once runtime_action.commit succeeds, the committed required child graph is this parent run's durable delegated live disposition.",
4804
4856
  "After runtime_action.commit succeeds, yield and end the parent run immediately. Do not browse, search, research, or execute any delegated child acceptance scope, and do not poll child runs. Child assignment runs are the sole execution path for delegated child scope.",
4805
4857
  "Each executable child must have an owner, dependencies where needed, and acceptance criteria. Do not create probe or test children.",
@@ -4973,14 +5025,86 @@ function manifestEntry(section) {
4973
5025
  truncationReason: section.truncationReason ?? null
4974
5026
  };
4975
5027
  }
4976
- function renderPrompt(sections, manifest, compactManifest = false) {
5028
+ var CONTEXT_AVAILABILITY_SECTION_TITLES = Object.freeze({
5029
+ recovery_instruction: "Recovery Instruction",
5030
+ approval_continuation: "Approved Runtime Action Continuation",
5031
+ wake_comments: "Wake Delta",
5032
+ task: "Task Context",
5033
+ continuation_summary: "Continuation Summary",
5034
+ resolved_dependencies: "Resolved Dependency Outputs",
5035
+ runtime_delivery_readiness: "Current Delivery Readiness",
5036
+ runtime_authorization: "Runtime Action Contract",
5037
+ runtime_decomposition_requirement: "Required Task Decomposition",
5038
+ task_context_authority: "Task Context Authority",
5039
+ verified_company_context: "Verified Company Context",
5040
+ pi_mcp_proxy_examples: "Pi MCP Proxy Examples",
5041
+ governed_reads: "Governed External Reads",
5042
+ optional_task_wiki_context: "Optional Company Wiki Context",
5043
+ agent_instructions: "Agent Instructions",
5044
+ attachments: "Materialized Inputs",
5045
+ on_demand_refs: "On-demand Context References",
5046
+ raw_snapshot: "Raw Context Snapshot"
5047
+ });
5048
+ function contextAvailabilitySectionTitle(sectionName) {
5049
+ return CONTEXT_AVAILABILITY_SECTION_TITLES[sectionName] ?? sectionName.replaceAll("_", " ");
5050
+ }
5051
+ function projectModelContextAvailability(manifestSections) {
5052
+ const entries = Array.isArray(manifestSections) ? manifestSections.map(asRecord) : [];
5053
+ const bySection = new Map(entries.map((entry) => [readString(entry.section), entry]));
5054
+ const lines = [];
5055
+ const coveredSections = [];
5056
+ const wikiEntry = bySection.get("optional_task_wiki_context");
5057
+ const wikiReason = readString(wikiEntry?.truncationReason);
5058
+ if (wikiEntry?.omitted === true && wikiReason?.startsWith("wiki_optional_context_gap:")) {
5059
+ const gapCode = wikiReason.slice("wiki_optional_context_gap:".length);
5060
+ lines.push(
5061
+ gapCode === "wiki_zero_hit" ? "Optional Company Wiki lookup completed with no matching result." : "Optional Company Wiki context was unavailable for this run. Do not assume that no relevant Wiki material exists."
5062
+ );
5063
+ coveredSections.push("optional_task_wiki_context");
5064
+ }
5065
+ const budgetOmissions = entries.filter((entry) => entry.omitted === true && entry.truncationReason === "unified_context_budget").map((entry) => readString(entry.section)).filter(Boolean);
5066
+ if (budgetOmissions.length > 0) {
5067
+ lines.push(
5068
+ `The prompt budget omitted these context sections: ${budgetOmissions.map(contextAvailabilitySectionTitle).join(", ")}. Do not assume that the underlying material is absent; use managed typed reads when an applicable reference is available.`
5069
+ );
5070
+ coveredSections.push(...budgetOmissions);
5071
+ }
5072
+ const rawSnapshot = bySection.get("raw_snapshot");
5073
+ const onDemandRefs2 = bySection.get("on_demand_refs");
5074
+ if (rawSnapshot?.omitted === true && rawSnapshot.truncationReason === "on_demand_large_object" && Number(rawSnapshot.originalChars ?? 0) > 0 && (!onDemandRefs2 || onDemandRefs2.omitted === true)) {
5075
+ lines.push(
5076
+ "Additional raw run context was intentionally not inlined and no managed on-demand reference was provided. Do not assume that omitted details are absent."
5077
+ );
5078
+ coveredSections.push("raw_snapshot");
5079
+ }
5080
+ return {
5081
+ content: lines.join("\n"),
5082
+ coveredSections: [...new Set(coveredSections)]
5083
+ };
5084
+ }
5085
+ function modelSectionsWithAvailability(sections) {
5086
+ const manifestEntries = sections.map(manifestEntry);
5087
+ const projection = projectModelContextAvailability(manifestEntries);
5088
+ if (!projection.content) return sections;
5089
+ const covered = new Set(projection.coveredSections);
4977
5090
  return [
4978
- ...sections.map(sectionText).filter(Boolean),
4979
- "## Context Manifest",
4980
- "```json",
4981
- compactManifest ? JSON.stringify(manifest) : jsonText(manifest),
4982
- "```"
4983
- ].join("\n");
5091
+ ...sections,
5092
+ {
5093
+ name: "context_availability",
5094
+ title: "Context Availability",
5095
+ priority: 100,
5096
+ sourceRef: manifestEntries.filter((entry) => covered.has(entry.section)).flatMap((entry) => Array.isArray(entry.sourceRef) ? entry.sourceRef : [entry.sourceRef]).filter(Boolean),
5097
+ observedAt: null,
5098
+ freshness: { kind: "run_snapshot" },
5099
+ scope: null,
5100
+ content: projection.content,
5101
+ originalChars: sectionText({ title: "Context Availability", content: projection.content }).length,
5102
+ truncationReason: null
5103
+ }
5104
+ ];
5105
+ }
5106
+ function renderPrompt(sections) {
5107
+ return sections.map(sectionText).filter(Boolean).join("\n");
4984
5108
  }
4985
5109
  function buildManifest(mode, maxChars, sections, governedReadProvenance, usedChars) {
4986
5110
  return {
@@ -5102,50 +5226,38 @@ ${resolvedDependencies.details.content}` : ""
5102
5226
  truncationReason: section.content ? section.truncationReason : section.truncationReason ?? "source_absent"
5103
5227
  }));
5104
5228
  let prompt = "";
5105
- let compactManifest = false;
5106
- let manifest = buildManifest(mode, maxChars, sections, governedReads.provenance, 0);
5229
+ let modelSections = modelSectionsWithAvailability(sections);
5230
+ let manifest = buildManifest(mode, maxChars, modelSections, governedReads.provenance, 0);
5107
5231
  if (maxChars === null) {
5108
- for (let telemetryPass = 0; telemetryPass < 20; telemetryPass += 1) {
5109
- prompt = renderPrompt(sections, manifest);
5110
- if (manifest.budget.usedChars === prompt.length) return { prompt, manifest };
5111
- manifest = buildManifest(mode, null, sections, governedReads.provenance, prompt.length);
5112
- }
5113
- throw new Error("Prompt compiler could not stabilize the unbounded Context Manifest");
5232
+ prompt = renderPrompt(modelSections);
5233
+ manifest = buildManifest(mode, null, modelSections, governedReads.provenance, prompt.length);
5234
+ return { prompt, manifest };
5114
5235
  }
5115
5236
  for (let pass = 0; pass < 20; pass += 1) {
5116
- let usedChars = 0;
5117
- for (let telemetryPass = 0; telemetryPass < 3; telemetryPass += 1) {
5118
- manifest = buildManifest(mode, maxChars, sections, governedReads.provenance, usedChars);
5119
- prompt = renderPrompt(sections, manifest, compactManifest);
5120
- if (prompt.length === usedChars) break;
5121
- usedChars = prompt.length;
5122
- }
5123
- if (prompt.length <= maxChars && manifest.budget.usedChars === prompt.length) break;
5237
+ modelSections = modelSectionsWithAvailability(sections);
5238
+ prompt = renderPrompt(modelSections);
5239
+ manifest = buildManifest(mode, maxChars, modelSections, governedReads.provenance, prompt.length);
5240
+ if (prompt.length <= maxChars) break;
5124
5241
  const overflow = Math.max(1, prompt.length - maxChars);
5125
5242
  const candidate = [...sections].filter(
5126
5243
  (section) => section.priority < 100 && section.content.length > (section.mandatoryContent?.length ?? 0)
5127
5244
  ).sort((left, right) => left.priority - right.priority)[0];
5128
5245
  if (!candidate) {
5129
- if (!compactManifest) {
5130
- compactManifest = true;
5131
- manifest = buildManifest(mode, maxChars, sections, governedReads.provenance, 0);
5132
- continue;
5133
- }
5134
- const fixedChars = sections.filter((section) => section.priority === 100).map(sectionText).join("\n").length;
5135
- const manifestChars = JSON.stringify(manifest).length;
5246
+ const fixedChars = modelSections.filter((section) => section.priority === 100).map(sectionText).join("\n").length;
5247
+ const availabilitySection = modelSections.find((section) => section.name === "context_availability");
5248
+ const availabilityChars = availabilitySection ? sectionText(availabilitySection).length : 0;
5136
5249
  if (resolvedDependencies.required.tupleCount > 0) {
5137
5250
  throw promptBudgetError(
5138
5251
  "resolved_dependencies_budget_exceeded",
5139
- `Resolved dependency mandatory read tuples exceed the unified ${maxChars}-character prompt budget: tupleCount=${resolvedDependencies.required.tupleCount} promptChars=${prompt.length} fixedChars=${fixedChars} manifestChars=${manifestChars}`
5252
+ `Resolved dependency mandatory read tuples exceed the unified ${maxChars}-character prompt budget: tupleCount=${resolvedDependencies.required.tupleCount} promptChars=${prompt.length} fixedChars=${fixedChars} availabilityChars=${availabilityChars}`
5140
5253
  );
5141
5254
  }
5142
5255
  throw promptBudgetError(
5143
5256
  "prompt_budget_exceeded",
5144
- `Prompt fixed sections exceed the unified ${maxChars}-character budget: promptChars=${prompt.length} fixedChars=${fixedChars} manifestChars=${manifestChars}`
5257
+ `Prompt fixed sections exceed the unified ${maxChars}-character budget: promptChars=${prompt.length} fixedChars=${fixedChars} availabilityChars=${availabilityChars}`
5145
5258
  );
5146
5259
  }
5147
5260
  truncateSection(candidate, Math.max(0, candidate.content.length - overflow - 32));
5148
- manifest = buildManifest(mode, maxChars, sections, governedReads.provenance, 0);
5149
5261
  }
5150
5262
  if (prompt.length > maxChars || manifest.budget.usedChars !== prompt.length) {
5151
5263
  throw promptBudgetError(
@@ -9680,7 +9792,7 @@ function assertSourceAcquisitionRuntimeAuthority({
9680
9792
  }
9681
9793
 
9682
9794
  // src/amaster-runtime-daemon.mjs
9683
- var CONNECTOR_VERSION = "0.1.1-beta.16";
9795
+ var CONNECTOR_VERSION = "0.1.1-beta.18";
9684
9796
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
9685
9797
  var SOURCE_ACQUISITION_CAPABILITY = "source_acquisition_v1";
9686
9798
  var SOURCE_ACQUISITION_PROFILE_VERSION = "source_acquisition_v1";
@@ -6,7 +6,7 @@ import { basename, dirname, join, resolve } from "node:path";
6
6
  import { homedir, hostname } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
 
9
- const CONNECTOR_VERSION = "0.1.1-beta.16";
9
+ const CONNECTOR_VERSION = "0.1.1-beta.18";
10
10
 
11
11
  const CAPABILITIES = [
12
12
  "remote_registration",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/employee-runtime-connector",
3
- "version": "0.1.1-beta.16",
3
+ "version": "0.1.1-beta.18",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",