@amaster.ai/employee-runtime-connector 0.1.1-beta.353 → 0.1.1-beta.354

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.
@@ -21,21 +21,37 @@ function canonicalGoalOutcomeValue(value) {
21
21
  var TASK_CONTEXT_MANIFEST_VERSION = "task-context-v1";
22
22
  var TASK_CONTEXT_V2 = "task-context-v2";
23
23
 
24
- // src/amaster-runtime-daemon/goal-context-attestation.mjs
25
- var hash = (value) => createHash("sha256").update(value).digest("hex");
26
- function goalAuthorityBlock(context) {
27
- const manifest = context?.taskContextManifest;
24
+ // ../shared/src/runtime-context-canonical.ts
25
+ var MIRRORX_GOAL_AUTHORITY_CONTRIBUTION_CONSTRAINT = "Execution contribution only. Parent owns Goal evaluation and business Outcome; this child does not claim independent completion.";
26
+ function record(value) {
27
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
28
+ }
29
+ function mirrorxGoalAuthorityPayload(manifestValue) {
30
+ const manifest = record(manifestValue);
28
31
  if (manifest?.version !== TASK_CONTEXT_V2) return null;
29
- if (!manifest.goalOutcomeContext?.binding || !manifest.goalOutcomeContext?.snapshotHash) throw new Error("goal_authority_context_missing");
30
- return "<mirrorx-goal-authority>\n" + canonicalGoalOutcomeValue({
32
+ const context = record(manifest.goalOutcomeContext);
33
+ if (!record(context?.binding) || !record(context?.snapshotHash)) throw new Error("goal_authority_context_missing");
34
+ return {
31
35
  version: manifest.version,
32
36
  freshness: manifest.freshness,
33
37
  goalOutcomeContext: manifest.goalOutcomeContext,
34
38
  ...manifest.contributionContext ? {
35
39
  contributionContext: manifest.contributionContext,
36
- constraint: "Execution contribution only. Parent owns Goal evaluation and business Outcome; this child does not claim independent completion."
40
+ constraint: MIRRORX_GOAL_AUTHORITY_CONTRIBUTION_CONSTRAINT
37
41
  } : {}
38
- }) + "\n</mirrorx-goal-authority>";
42
+ };
43
+ }
44
+ function renderMirrorxGoalAuthority(manifestValue) {
45
+ const payload = mirrorxGoalAuthorityPayload(manifestValue);
46
+ return payload ? `<mirrorx-goal-authority>
47
+ ${canonicalGoalOutcomeValue(payload)}
48
+ </mirrorx-goal-authority>` : null;
49
+ }
50
+
51
+ // src/amaster-runtime-daemon/goal-context-attestation.mjs
52
+ var hash = (value) => createHash("sha256").update(value).digest("hex");
53
+ function goalAuthorityBlock(context) {
54
+ return renderMirrorxGoalAuthority(context?.taskContextManifest);
39
55
  }
40
56
  function attestGoalContextDelivery({ authority, prompt, systemPrompt, commandId, runId, executorKind }) {
41
57
  if (!authority) return null;
@@ -18406,16 +18422,16 @@ var PI_TOOL_ARGUMENT_GUARD_DEFAULTS = Object.freeze({
18406
18422
  nearMissAmplificationThreshold: 8,
18407
18423
  nearMissReplayRatioThreshold: 0.75
18408
18424
  });
18409
- function record(value) {
18425
+ function record2(value) {
18410
18426
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
18411
18427
  }
18412
18428
  function toolCallContentArrays(event) {
18413
- const root = record(event);
18414
- const assistantEvent = record(root.assistantMessageEvent);
18429
+ const root = record2(event);
18430
+ const assistantEvent = record2(root.assistantMessageEvent);
18415
18431
  return [
18416
- record(assistantEvent.partial).content,
18417
- record(root.partial).content,
18418
- record(root.message).content
18432
+ record2(assistantEvent.partial).content,
18433
+ record2(root.partial).content,
18434
+ record2(root.message).content
18419
18435
  ].filter(Array.isArray);
18420
18436
  }
18421
18437
  function toolCallIdentity(item, index) {
@@ -18437,7 +18453,7 @@ function partialToolCalls(event) {
18437
18453
  const seen = /* @__PURE__ */ new Set();
18438
18454
  for (const content of toolCallContentArrays(event)) {
18439
18455
  for (let index = 0; index < content.length; index += 1) {
18440
- const item = record(content[index]);
18456
+ const item = record2(content[index]);
18441
18457
  if (readString(item.type)?.toLowerCase() !== "toolcall") continue;
18442
18458
  const snapshot = partialArgumentSnapshot(item);
18443
18459
  if (snapshot === null) continue;
@@ -18514,7 +18530,7 @@ function createPiToolArgumentAmplificationTracker(options = {}) {
18514
18530
  const calls = /* @__PURE__ */ new Map();
18515
18531
  let breach = null;
18516
18532
  const noteToolExecutionStart = (event) => {
18517
- const root = record(event);
18533
+ const root = record2(event);
18518
18534
  const id = readString(root.toolCallId) ?? readString(root.id) ?? readString(root.callId);
18519
18535
  const toolName = readString(root.toolName) ?? readString(root.name);
18520
18536
  for (const state of calls.values()) {
@@ -18585,12 +18601,12 @@ function createPiToolArgumentAmplificationTracker(options = {}) {
18585
18601
  }
18586
18602
 
18587
18603
  // src/amaster-runtime-daemon/pi-output-retention.mjs
18588
- function record2(value) {
18604
+ function record3(value) {
18589
18605
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
18590
18606
  }
18591
18607
  function compactIncrementalEvent(event) {
18592
18608
  if (event.type !== "message_update") return null;
18593
- const assistantEvent = record2(event.assistantMessageEvent);
18609
+ const assistantEvent = record3(event.assistantMessageEvent);
18594
18610
  const type = typeof assistantEvent.type === "string" ? assistantEvent.type : "";
18595
18611
  if (!type.endsWith("_delta") && type !== "text_end" && type !== "thinking_end") return null;
18596
18612
  const compact = { type: "message_update", assistantMessageEvent: { type } };
@@ -20409,7 +20425,7 @@ var SAFE_SHARED_PROVIDER_INTEGER_KEYS = /* @__PURE__ */ new Set([
20409
20425
  "websocket_connect_timeout_ms"
20410
20426
  ]);
20411
20427
  var BUILT_IN_MODEL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "amazon-bedrock", "ollama", "lmstudio"]);
20412
- function record3(value) {
20428
+ function record4(value) {
20413
20429
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
20414
20430
  }
20415
20431
  function nonEmpty(value, label) {
@@ -20456,7 +20472,7 @@ function findSessionRollout(sessionsRoot, sessionId) {
20456
20472
  return matches[0];
20457
20473
  }
20458
20474
  function restoreManagedCodexSessionRollout(input, codexHome, runDir, executorHome, authority) {
20459
- const session = record3(input.nativeSession);
20475
+ const session = record4(input.nativeSession);
20460
20476
  const governedApprovalContinuation = session.mode === "governed_action_approval" && session.required === true;
20461
20477
  const governedTaskSessionContinuation = session.mode === "task_session" && session.required === false;
20462
20478
  if (!governedApprovalContinuation && !governedTaskSessionContinuation) return null;
@@ -20510,7 +20526,7 @@ function resolveManagedCodexSessionRollout(input, codexHome, runDir, executorHom
20510
20526
  nativeSessionRestoreSkippedReason: null
20511
20527
  };
20512
20528
  } catch (error) {
20513
- if (record3(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("codex_managed_mcp_session_rollout_missing:")) {
20529
+ if (record4(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("codex_managed_mcp_session_rollout_missing:")) {
20514
20530
  return {
20515
20531
  restoredNativeSession: null,
20516
20532
  nativeSessionRestoreSkippedReason: "native_session_rollout_missing"
@@ -20551,14 +20567,14 @@ function sharedCodexModelRoute(sourceHome) {
20551
20567
  }
20552
20568
  const providerId = config.model_provider;
20553
20569
  if (!providerId) return { root, table: [], mode: config.model ? "shared_model" : "default", protectedValues: [] };
20554
- const selectedProvider = record3(config.model_providers)[providerId];
20570
+ const selectedProvider = record4(config.model_providers)[providerId];
20555
20571
  if (selectedProvider == null) {
20556
20572
  if (!BUILT_IN_MODEL_PROVIDERS.has(providerId)) {
20557
20573
  throw new Error(`codex_managed_mcp_source_provider_missing: ${providerId}`);
20558
20574
  }
20559
20575
  return { root, table: [], mode: "shared_builtin_provider", protectedValues: [] };
20560
20576
  }
20561
- if (Object.keys(record3(selectedProvider)).length === 0) {
20577
+ if (Object.keys(record4(selectedProvider)).length === 0) {
20562
20578
  throw new Error(`codex_managed_mcp_provider_config_invalid: model_providers.${providerId} must be a non-empty table`);
20563
20579
  }
20564
20580
  const projectedProvider = {};
@@ -20589,7 +20605,7 @@ function sharedCodexModelRoute(sourceHome) {
20589
20605
  continue;
20590
20606
  }
20591
20607
  if (key === "http_headers") {
20592
- const headers = record3(value);
20608
+ const headers = record4(value);
20593
20609
  if (Object.keys(headers).length === 0 || Object.values(headers).some((entry) => typeof entry !== "string")) {
20594
20610
  throw new Error("codex_managed_mcp_provider_config_invalid: http_headers must be a non-empty string table");
20595
20611
  }
@@ -20635,18 +20651,18 @@ function runAttestation(executorCommand, env, cwd, gatewayUrl, expectedHeaders)
20635
20651
  if (!Array.isArray(servers) || servers.length !== 1) {
20636
20652
  throw new Error(`codex_managed_mcp_attestation_failed: expected one MCP server, received ${Array.isArray(servers) ? servers.length : "non_array"}`);
20637
20653
  }
20638
- const server = record3(servers[0]);
20639
- const transport = record3(server.transport);
20640
- const effectiveHeaders = record3(transport.http_headers);
20654
+ const server = record4(servers[0]);
20655
+ const transport = record4(server.transport);
20656
+ const effectiveHeaders = record4(transport.http_headers);
20641
20657
  const headersMatch = Object.keys(effectiveHeaders).length === Object.keys(expectedHeaders).length && Object.entries(expectedHeaders).every(([name, value]) => effectiveHeaders[name] === value);
20642
- if (server.name !== SUPPORTED_SERVER_NAME || server.enabled !== true || transport.type !== "streamable_http" || transport.url !== gatewayUrl || !headersMatch || Object.keys(record3(transport.env_http_headers)).length !== 0 || transport.bearer_token_env_var != null) {
20658
+ if (server.name !== SUPPORTED_SERVER_NAME || server.enabled !== true || transport.type !== "streamable_http" || transport.url !== gatewayUrl || !headersMatch || Object.keys(record4(transport.env_http_headers)).length !== 0 || transport.bearer_token_env_var != null) {
20643
20659
  throw new Error("codex_managed_mcp_attestation_failed: effective MCP config does not match managed amaster Gateway");
20644
20660
  }
20645
20661
  return executorVersion;
20646
20662
  }
20647
20663
  function validateAuthority(input) {
20648
- const runtimeAuth = record3(input.runtimeAuth);
20649
- const gateway = record3(runtimeAuth.governedMcp);
20664
+ const runtimeAuth = record4(input.runtimeAuth);
20665
+ const gateway = record4(runtimeAuth.governedMcp);
20650
20666
  const runId = nonEmpty(input.runId, "runId");
20651
20667
  if (runtimeAuth.runId !== runId) throw new Error("codex_managed_mcp_owner_mismatch: command runId does not match runtime authority");
20652
20668
  if (gateway.schemaVersion !== SUPPORTED_SCHEMA_VERSION) throw new Error("codex_managed_mcp_invalid: unsupported schema version");
@@ -20662,7 +20678,7 @@ function validateAuthority(input) {
20662
20678
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() + 3e4) {
20663
20679
  throw new Error("codex_managed_mcp_session_expired: Gateway session must remain valid through spawn preflight");
20664
20680
  }
20665
- const headers = record3(gateway.headers);
20681
+ const headers = record4(gateway.headers);
20666
20682
  for (const name of REQUIRED_AUTHORITY_HEADERS) nonEmpty(headers[name], `headers.${name}`);
20667
20683
  const allowedHeaderNames = /* @__PURE__ */ new Set([...REQUIRED_AUTHORITY_HEADERS, ...runtimeAuth.issueId ? ["x-amaster-issue-id"] : []]);
20668
20684
  if (Object.keys(headers).some((name) => !allowedHeaderNames.has(name)) || Object.keys(headers).length !== allowedHeaderNames.size) {
@@ -20679,7 +20695,7 @@ function validateAuthority(input) {
20679
20695
  return { gateway, gatewayUrl, sessionToken, headers, runId };
20680
20696
  }
20681
20697
  function assertInvocationIsolation(input) {
20682
- for (const name of Object.keys(record3(input.commandEnv))) {
20698
+ for (const name of Object.keys(record4(input.commandEnv))) {
20683
20699
  if (FORBIDDEN_COMMAND_ENV.has(name)) throw new Error(`codex_managed_mcp_env_override_blocked: ${name}`);
20684
20700
  if (!ALLOWED_COMMAND_ENV.has(name)) throw new Error(`codex_managed_mcp_env_injection_blocked: ${name}`);
20685
20701
  }
@@ -20746,7 +20762,7 @@ function buildIsolatedEnvironment(baseEnv, commandEnv) {
20746
20762
  const value = safeProxyValue(baseEnv?.[name], name);
20747
20763
  if (value) env[name] = value;
20748
20764
  }
20749
- return { ...env, ...record3(commandEnv) };
20765
+ return { ...env, ...record4(commandEnv) };
20750
20766
  }
20751
20767
  function assertNoProjectAmasterOverride(cwd, runDir) {
20752
20768
  let cursor = resolve4(cwd);
@@ -20828,7 +20844,7 @@ function prepareManagedCodexMcpProfile(input) {
20828
20844
  const owner = Object.freeze({ commandId: input.commandId, runId });
20829
20845
  writePrivateFile(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot })}
20830
20846
  `);
20831
- const runtimeAuth = record3(input.runtimeAuth);
20847
+ const runtimeAuth = record4(input.runtimeAuth);
20832
20848
  const authority = Object.freeze({
20833
20849
  companyId: nonEmpty(runtimeAuth.companyId, "runtimeAuth.companyId"),
20834
20850
  agentId: nonEmpty(runtimeAuth.agentId, "runtimeAuth.agentId"),
@@ -21196,7 +21212,7 @@ var FULL_DIRECT_TYPED_V1_TOOL_NAMES = /* @__PURE__ */ new Set([
21196
21212
  ...FULL_DIRECT_TYPED_V1_WIKI_TOOL_NAMES,
21197
21213
  ...FULL_DIRECT_TYPED_V1_CONNECTOR_TOOL_NAMES
21198
21214
  ]);
21199
- function record4(value) {
21215
+ function record5(value) {
21200
21216
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21201
21217
  }
21202
21218
  function requiredString(value, label, fail2) {
@@ -21209,11 +21225,11 @@ function validateDirectTypedMcpCatalog(catalogValue, options = {}) {
21209
21225
  throw new Error(`${errorPrefix}: ${detail}`);
21210
21226
  };
21211
21227
  const admittedToolNames = options.admittedToolNames instanceof Set ? options.admittedToolNames : options.admittedToolNames == null ? null : new Set(options.admittedToolNames);
21212
- const catalog = record4(catalogValue);
21228
+ const catalog = record5(catalogValue);
21213
21229
  if (catalog.schemaVersion !== DIRECT_TYPED_MCP_CATALOG_SCHEMA_VERSION) {
21214
21230
  fail2("direct tool catalog schema mismatch");
21215
21231
  }
21216
- const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record4) : [];
21232
+ const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record5) : [];
21217
21233
  const names = /* @__PURE__ */ new Set();
21218
21234
  const exposedNames = /* @__PURE__ */ new Set();
21219
21235
  const tools = rawTools.map((tool) => {
@@ -21230,7 +21246,7 @@ function validateDirectTypedMcpCatalog(catalogValue, options = {}) {
21230
21246
  fail2(`direct tool exposed name collision for ${exposedName}`);
21231
21247
  }
21232
21248
  exposedNames.add(exposedName);
21233
- const inputSchema = record4(tool.inputSchema);
21249
+ const inputSchema = record5(tool.inputSchema);
21234
21250
  if (inputSchema.type !== "object" || inputSchema.additionalProperties !== false) {
21235
21251
  fail2(`direct tool schema is not strict for ${name}`);
21236
21252
  }
@@ -21429,7 +21445,7 @@ var CODEBUDDY_PROFILE_COMPATIBILITY_ALLOWLIST = Object.freeze([
21429
21445
  profileHash: "b310363c97f72b03debd1d6b90cbc49fa17565c1553a8a0c93ee0f29bfadf3c3"
21430
21446
  }
21431
21447
  ]);
21432
- function record5(value) {
21448
+ function record6(value) {
21433
21449
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21434
21450
  }
21435
21451
  function fail(detail) {
@@ -21460,12 +21476,12 @@ function assertFormalCatalogShape(rawTools) {
21460
21476
  if (!fullCatalog) fail("direct tool catalog size mismatch");
21461
21477
  }
21462
21478
  function validateCodebuddyFormalToolCatalog(gatewayValue) {
21463
- const gateway = record5(gatewayValue);
21479
+ const gateway = record6(gatewayValue);
21464
21480
  if ((gateway.mcpToolMode ?? "direct_typed") !== "direct_typed") {
21465
21481
  fail("direct tool mode required");
21466
21482
  }
21467
- const catalog = record5(gateway.toolCatalog);
21468
- const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record5) : [];
21483
+ const catalog = record6(gateway.toolCatalog);
21484
+ const rawTools = Array.isArray(catalog.tools) ? catalog.tools.map(record6) : [];
21469
21485
  assertFormalCatalogShape(rawTools);
21470
21486
  const validated = validateDirectTypedMcpCatalog(catalog, {
21471
21487
  admittedToolNames: FULL_DIRECT_TYPED_V1_TOOL_NAMES,
@@ -21496,9 +21512,9 @@ function schemaBytes(tools) {
21496
21512
  return tools.reduce((total, tool) => total + Buffer.byteLength(stablePiJson(tool.inputSchema)), 0);
21497
21513
  }
21498
21514
  function codebuddyProfileSchemaBytesMatchCatalog(catalogValue, attestationValue) {
21499
- const catalog = record5(catalogValue);
21500
- const attestation = record5(attestationValue);
21501
- const tools = Array.isArray(catalog.tools) ? catalog.tools.map(record5) : [];
21515
+ const catalog = record6(catalogValue);
21516
+ const attestation = record6(attestationValue);
21517
+ const tools = Array.isArray(catalog.tools) ? catalog.tools.map(record6) : [];
21502
21518
  const mcpMode = attestation.mcpMode;
21503
21519
  const total = attestation.totalMcpSchemaBytes;
21504
21520
  const direct = attestation.directMcpSchemaBytes;
@@ -21768,7 +21784,7 @@ var CODEBUDDY_PROVIDER_ENV = /* @__PURE__ */ new Set([
21768
21784
  "https_proxy",
21769
21785
  "all_proxy"
21770
21786
  ]);
21771
- function record6(value) {
21787
+ function record7(value) {
21772
21788
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21773
21789
  }
21774
21790
  function nonEmpty2(value, label) {
@@ -22004,7 +22020,7 @@ function codebuddyProjectKey(cwd) {
22004
22020
  return realpathSync5(cwd).replace(/^[/\\]+/, "").replace(/[\\/:]/g, "-").replace(/-+/g, "-");
22005
22021
  }
22006
22022
  function restoreManagedCodebuddySessionRollout(input, configDir, runDir, executorHome, authority) {
22007
- const session = record6(input.nativeSession);
22023
+ const session = record7(input.nativeSession);
22008
22024
  const governedApprovalContinuation = session.mode === "governed_action_approval" && session.required === true;
22009
22025
  const taskSessionContinuation = session.mode === "task_session" && session.required === false;
22010
22026
  if (!governedApprovalContinuation && !taskSessionContinuation) return null;
@@ -22048,7 +22064,7 @@ function resolveManagedCodebuddySessionRollout(input, configDir, runDir, executo
22048
22064
  nativeSessionRestoreSkippedReason: null
22049
22065
  };
22050
22066
  } catch (error) {
22051
- if (record6(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("codebuddy_managed_mcp_session_rollout_missing:")) {
22067
+ if (record7(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("codebuddy_managed_mcp_session_rollout_missing:")) {
22052
22068
  return { restoredNativeSession: null, nativeSessionRestoreSkippedReason: "native_session_rollout_missing" };
22053
22069
  }
22054
22070
  throw error;
@@ -22056,7 +22072,7 @@ function resolveManagedCodebuddySessionRollout(input, configDir, runDir, executo
22056
22072
  }
22057
22073
  function buildIsolatedEnvironment2(baseEnv, commandEnv) {
22058
22074
  const env = {};
22059
- for (const source of [record6(baseEnv), record6(commandEnv)]) {
22075
+ for (const source of [record7(baseEnv), record7(commandEnv)]) {
22060
22076
  for (const [key, value] of Object.entries(source)) {
22061
22077
  if (!SAFE_INHERITED_ENV2.has(key) || typeof value !== "string") continue;
22062
22078
  env[key] = value;
@@ -22066,8 +22082,8 @@ function buildIsolatedEnvironment2(baseEnv, commandEnv) {
22066
22082
  }
22067
22083
  function codebuddyAuthSelection(baseEnv, commandEnv) {
22068
22084
  const scopes = [
22069
- { name: "command_env", value: record6(commandEnv) },
22070
- { name: "daemon_env", value: record6(baseEnv) }
22085
+ { name: "command_env", value: record7(commandEnv) },
22086
+ { name: "daemon_env", value: record7(baseEnv) }
22071
22087
  ];
22072
22088
  for (const scope of scopes) {
22073
22089
  const apiKey = typeof scope.value.CODEBUDDY_API_KEY === "string" ? scope.value.CODEBUDDY_API_KEY.trim() : "";
@@ -22105,7 +22121,7 @@ function inspectCodebuddyProviderAuthReadiness(baseEnv = process.env, commandEnv
22105
22121
  };
22106
22122
  }
22107
22123
  function codebuddyProviderEnvironment(baseEnv, commandEnv) {
22108
- const source = { ...record6(baseEnv), ...record6(commandEnv) };
22124
+ const source = { ...record7(baseEnv), ...record7(commandEnv) };
22109
22125
  const selectedAuth = codebuddyAuthSelection(baseEnv, commandEnv);
22110
22126
  if (selectedAuth.conflict) {
22111
22127
  throw new Error("codebuddy_managed_mcp_auth_conflict: configure only one CodeBuddy authentication method");
@@ -22137,8 +22153,8 @@ function codebuddyProviderEnvironment(baseEnv, commandEnv) {
22137
22153
  };
22138
22154
  }
22139
22155
  function validateAuthority2(input) {
22140
- const runtimeAuth = record6(input.runtimeAuth);
22141
- const gateway = record6(runtimeAuth.governedMcp);
22156
+ const runtimeAuth = record7(input.runtimeAuth);
22157
+ const gateway = record7(runtimeAuth.governedMcp);
22142
22158
  const runId = nonEmpty2(input.runId, "runId");
22143
22159
  if (runtimeAuth.runId !== runId) {
22144
22160
  throw new Error("codebuddy_managed_mcp_owner_mismatch: command runId does not match runtime authority");
@@ -22156,7 +22172,7 @@ function validateAuthority2(input) {
22156
22172
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
22157
22173
  throw new Error("codebuddy_managed_mcp_session_expired");
22158
22174
  }
22159
- const headers = record6(gateway.headers);
22175
+ const headers = record7(gateway.headers);
22160
22176
  for (const name of REQUIRED_AUTHORITY_HEADERS2) nonEmpty2(headers[name], `headers.${name}`);
22161
22177
  if (headers["x-amaster-executor-kind"] !== "codebuddy") {
22162
22178
  throw new Error("codebuddy_managed_mcp_invalid: executor header must be codebuddy");
@@ -23624,7 +23640,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23624
23640
  const PI_VERSION_ATTESTATION_TIMEOUT_MS = 3e4;
23625
23641
  const PI_ATTESTATION_MAX_ATTEMPTS = 2;
23626
23642
  const livePiVersionProbes = /* @__PURE__ */ new Map();
23627
- function record10(value) {
23643
+ function record11(value) {
23628
23644
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
23629
23645
  }
23630
23646
  function readJsonObjectFile(filePath) {
@@ -23686,7 +23702,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23686
23702
  return matches[0];
23687
23703
  }
23688
23704
  function restoreManagedPiSessionRollout(input, sessionsRoot, runDir, executorHome, authority) {
23689
- const session = record10(input.nativeSession);
23705
+ const session = record11(input.nativeSession);
23690
23706
  const governedApprovalContinuation = session.mode === "governed_action_approval" && session.required === true;
23691
23707
  const governedTaskSessionContinuation = session.mode === "task_session" && session.required === false;
23692
23708
  if (!governedApprovalContinuation && !governedTaskSessionContinuation) return null;
@@ -23745,7 +23761,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23745
23761
  nativeSessionRestoreSkippedReason: null
23746
23762
  };
23747
23763
  } catch (error) {
23748
- if (record10(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("pi_managed_mcp_session_rollout_missing:")) {
23764
+ if (record11(input.nativeSession).mode === "task_session" && error instanceof Error && error.message.startsWith("pi_managed_mcp_session_rollout_missing:")) {
23749
23765
  return {
23750
23766
  restoredNativeSession: null,
23751
23767
  nativeSessionRestoreSkippedReason: "native_session_rollout_missing"
@@ -23817,7 +23833,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23817
23833
  return version;
23818
23834
  }
23819
23835
  function managedPiTelemetryExtension(sharedRuntime) {
23820
- const settings = record10(sharedRuntime.settings);
23836
+ const settings = record11(sharedRuntime.settings);
23821
23837
  const packages = Array.isArray(settings.packages) ? settings.packages : [];
23822
23838
  const configuredSources = packages.filter((source) => typeof source === "string" && (source === MANAGED_PI_TELEMETRY_PACKAGE_SOURCE || source.startsWith(`${MANAGED_PI_TELEMETRY_PACKAGE_SOURCE}@`)));
23823
23839
  if (configuredSources.length === 0) return null;
@@ -23838,7 +23854,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23838
23854
  if (!packageStat.isDirectory() || packageStat.isSymbolicLink()) throw new Error("unsafe package root");
23839
23855
  const packageJsonStat = lstatSync7(packageJsonPath);
23840
23856
  if (!packageJsonStat.isFile() || packageJsonStat.isSymbolicLink()) throw new Error("unsafe package manifest");
23841
- packageJson = record10(JSON.parse(readFileSync6(packageJsonPath, "utf8")));
23857
+ packageJson = record11(JSON.parse(readFileSync6(packageJsonPath, "utf8")));
23842
23858
  } catch {
23843
23859
  throw new Error("pi_managed_mcp_telemetry_package_unavailable");
23844
23860
  }
@@ -23849,7 +23865,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23849
23865
  if (!/^\d+\.\d+\.\d+(?:[-+].+)?$/.test(version)) {
23850
23866
  throw new Error("pi_managed_mcp_telemetry_package_version_invalid");
23851
23867
  }
23852
- const declaredExtensions = Array.isArray(record10(packageJson.pi).extensions) ? record10(packageJson.pi).extensions : [];
23868
+ const declaredExtensions = Array.isArray(record11(packageJson.pi).extensions) ? record11(packageJson.pi).extensions : [];
23853
23869
  if (declaredExtensions.length !== 1 || typeof declaredExtensions[0] !== "string") {
23854
23870
  throw new Error("pi_managed_mcp_telemetry_extension_invalid");
23855
23871
  }
@@ -23879,7 +23895,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23879
23895
  extensionPath,
23880
23896
  extensionSha256: sha2563(readFileSync6(extensionPath)),
23881
23897
  packageTreeSha256,
23882
- langfuseEnabled: record10(record10(settings["pi-telemetry"]).langfuse).enabled === true
23898
+ langfuseEnabled: record11(record11(settings["pi-telemetry"]).langfuse).enabled === true
23883
23899
  };
23884
23900
  }
23885
23901
  function adapterServerConfigHash(definition, adapterVersion) {
@@ -23938,8 +23954,8 @@ function createManagedPiMcpProfileApi(options = {}) {
23938
23954
  }
23939
23955
  }
23940
23956
  function validateAuthority3(input) {
23941
- const runtimeAuth = record10(input.runtimeAuth);
23942
- const gateway = record10(runtimeAuth.governedMcp);
23957
+ const runtimeAuth = record11(input.runtimeAuth);
23958
+ const gateway = record11(runtimeAuth.governedMcp);
23943
23959
  const runId = nonEmpty3(input.runId, "runId");
23944
23960
  if (runtimeAuth.runId !== runId) throw new Error("pi_managed_mcp_owner_mismatch: command runId does not match runtime authority");
23945
23961
  if (gateway.schemaVersion !== SUPPORTED_SCHEMA_VERSION3) throw new Error("pi_managed_mcp_invalid: unsupported schema version");
@@ -23955,7 +23971,7 @@ function createManagedPiMcpProfileApi(options = {}) {
23955
23971
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() + 3e4) {
23956
23972
  throw new Error("pi_managed_mcp_session_expired: Gateway session must remain valid through spawn preflight");
23957
23973
  }
23958
- const headers = record10(gateway.headers);
23974
+ const headers = record11(gateway.headers);
23959
23975
  for (const name of REQUIRED_AUTHORITY_HEADERS3) nonEmpty3(headers[name], `headers.${name}`);
23960
23976
  const allowedHeaderNames = /* @__PURE__ */ new Set([...REQUIRED_AUTHORITY_HEADERS3, ...runtimeAuth.issueId ? ["x-amaster-issue-id"] : []]);
23961
23977
  if (Object.keys(headers).some((name) => !allowedHeaderNames.has(name)) || Object.keys(headers).length !== allowedHeaderNames.size) {
@@ -24014,7 +24030,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24014
24030
  return env;
24015
24031
  }
24016
24032
  function assertInvocationIsolation2(input) {
24017
- for (const name of Object.keys(record10(input.commandEnv))) {
24033
+ for (const name of Object.keys(record11(input.commandEnv))) {
24018
24034
  if (FORBIDDEN_COMMAND_ENV2.has(name)) throw new Error(`pi_managed_mcp_env_override_blocked: ${name}`);
24019
24035
  if (!ALLOWED_COMMAND_ENV2.has(name)) throw new Error(`pi_managed_mcp_env_injection_blocked: ${name}`);
24020
24036
  }
@@ -24046,7 +24062,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24046
24062
  const value = safeProxyValue2(baseEnv?.[name], name);
24047
24063
  if (value) env[name] = value;
24048
24064
  }
24049
- return { ...env, ...record10(commandEnv) };
24065
+ return { ...env, ...record11(commandEnv) };
24050
24066
  }
24051
24067
  function projectMcpConfigHasContent(filePath) {
24052
24068
  if (!existsSync7(filePath)) return false;
@@ -24056,8 +24072,8 @@ function createManagedPiMcpProfileApi(options = {}) {
24056
24072
  } catch {
24057
24073
  return true;
24058
24074
  }
24059
- const config = record10(parsed);
24060
- return Object.keys(record10(config.mcpServers)).length > 0 || Object.keys(record10(config.servers)).length > 0 || Array.isArray(config.imports) && config.imports.length > 0;
24075
+ const config = record11(parsed);
24076
+ return Object.keys(record11(config.mcpServers)).length > 0 || Object.keys(record11(config.servers)).length > 0 || Array.isArray(config.imports) && config.imports.length > 0;
24061
24077
  }
24062
24078
  function walkProjectMcpConfigs(cwd, runDir, visit) {
24063
24079
  const start = resolve7(cwd);
@@ -24131,7 +24147,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24131
24147
  let settings = {};
24132
24148
  if (existsSync7(settingsPath)) {
24133
24149
  try {
24134
- settings = record10(JSON.parse(readFileSync6(settingsPath, "utf8")));
24150
+ settings = record11(JSON.parse(readFileSync6(settingsPath, "utf8")));
24135
24151
  } catch {
24136
24152
  throw new Error("pi_managed_mcp_attestation_failed: source Pi settings are invalid");
24137
24153
  }
@@ -24140,8 +24156,8 @@ function createManagedPiMcpProfileApi(options = {}) {
24140
24156
  const mcpPath = join10(home, "mcp.json");
24141
24157
  if (existsSync7(mcpPath)) {
24142
24158
  try {
24143
- userMcpServers = Object.fromEntries(Object.entries(record10(
24144
- record10(JSON.parse(readFileSync6(mcpPath, "utf8"))).mcpServers
24159
+ userMcpServers = Object.fromEntries(Object.entries(record11(
24160
+ record11(JSON.parse(readFileSync6(mcpPath, "utf8"))).mcpServers
24145
24161
  )).filter(([serverName]) => serverName !== SUPPORTED_SERVER_NAME3));
24146
24162
  } catch {
24147
24163
  userMcpServers = {};
@@ -24174,7 +24190,7 @@ function createManagedPiMcpProfileApi(options = {}) {
24174
24190
  return segments.join("/") === value ? value : null;
24175
24191
  }
24176
24192
  function parseManagedSkillBundle(rawBundle) {
24177
- const bundle = record10(rawBundle);
24193
+ const bundle = record11(rawBundle);
24178
24194
  if (Object.keys(bundle).length === 0) return null;
24179
24195
  if (bundle.version !== 1) {
24180
24196
  throw new Error("pi_managed_mcp_company_skill_bundle_invalid");
@@ -24184,13 +24200,13 @@ function createManagedPiMcpProfileApi(options = {}) {
24184
24200
  }
24185
24201
  let totalBytes = 0;
24186
24202
  const skills = bundle.skills.map((rawSkill) => {
24187
- const skill = record10(rawSkill);
24203
+ const skill = record11(rawSkill);
24188
24204
  if (typeof skill.key !== "string" || !skill.key || Buffer.byteLength(skill.key, "utf8") > 512 || /[\u0000-\u001f\u007f]/.test(skill.key) || typeof skill.runtimeName !== "string" || !MANAGED_SKILL_BUNDLE_RUNTIME_NAME.test(skill.runtimeName) || !Array.isArray(skill.files) || skill.files.length === 0 || skill.files.length > MANAGED_SKILL_BUNDLE_MAX_FILES) {
24189
24205
  throw new Error("pi_managed_mcp_company_skill_bundle_invalid");
24190
24206
  }
24191
24207
  const paths = /* @__PURE__ */ new Set();
24192
24208
  const files = skill.files.map((rawFile) => {
24193
- const file = record10(rawFile);
24209
+ const file = record11(rawFile);
24194
24210
  const relativePath = canonicalManagedSkillRelativePath(file.path);
24195
24211
  if (!relativePath || paths.has(relativePath) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || file.bytes > MANAGED_SKILL_BUNDLE_MAX_FILE_BYTES || typeof file.contentBase64 !== "string") {
24196
24212
  throw new Error("pi_managed_mcp_company_skill_bundle_invalid");
@@ -24457,7 +24473,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24457
24473
  const closureConfigBytes = Buffer.from(`${JSON.stringify({
24458
24474
  ...input.config,
24459
24475
  mcpServers: {
24460
- ...record10(input.config.mcpServers),
24476
+ ...record11(input.config.mcpServers),
24461
24477
  [SUPPORTED_SERVER_NAME3]: closureServerConfig
24462
24478
  }
24463
24479
  }, null, 2)}
@@ -24522,7 +24538,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24522
24538
  workspaceMcpConfigPath
24523
24539
  })}
24524
24540
  `);
24525
- const runtimeAuth = record10(input.runtimeAuth);
24541
+ const runtimeAuth = record11(input.runtimeAuth);
24526
24542
  const authority = Object.freeze({
24527
24543
  companyId: nonEmpty3(runtimeAuth.companyId, "runtimeAuth.companyId"),
24528
24544
  agentId: nonEmpty3(runtimeAuth.agentId, "runtimeAuth.agentId"),
@@ -24744,18 +24760,18 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24744
24760
  }
24745
24761
  function restoreManagedPiRunExitClosureBaseline2(input, expectedOwner) {
24746
24762
  if (!input) return { status: "not_required" };
24747
- const baseline = record10(input);
24763
+ const baseline = record11(input);
24748
24764
  if (baseline.schemaVersion !== "amaster.pi-run-exit-closure-baseline.v3") {
24749
24765
  throw new Error("pi_run_exit_closure_baseline_invalid: unsupported schema version");
24750
24766
  }
24751
- const owner = record10(baseline.owner);
24767
+ const owner = record11(baseline.owner);
24752
24768
  if (owner.commandId !== expectedOwner?.commandId || owner.runId !== expectedOwner?.runId) {
24753
24769
  throw new Error("pi_run_exit_closure_baseline_owner_mismatch");
24754
24770
  }
24755
24771
  const profileRoot = resolve7(nonEmpty3(baseline.profileRoot, "runExitClosureBaseline.profileRoot"));
24756
24772
  const cachePath = resolve7(nonEmpty3(baseline.cachePath, "runExitClosureBaseline.cachePath"));
24757
24773
  if (!within3(cachePath, profileRoot)) throw new Error("pi_run_exit_closure_baseline_path_mismatch");
24758
- const closureProfile = Object.keys(record10(baseline.closureProfile)).length > 0 ? record10(baseline.closureProfile) : null;
24774
+ const closureProfile = Object.keys(record11(baseline.closureProfile)).length > 0 ? record11(baseline.closureProfile) : null;
24759
24775
  const configPath = closureProfile ? resolve7(nonEmpty3(closureProfile.configPath, "closureProfile.configPath")) : null;
24760
24776
  for (const path of [cachePath, configPath].filter(Boolean)) {
24761
24777
  if (existsSync7(path)) {
@@ -24765,7 +24781,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24765
24781
  }
24766
24782
  }
24767
24783
  }
24768
- const baselineCacheOwnership = record10(baseline.cacheOwnership);
24784
+ const baselineCacheOwnership = record11(baseline.cacheOwnership);
24769
24785
  const cacheOwnership = Number.isSafeInteger(baselineCacheOwnership.uid) && baselineCacheOwnership.uid >= 0 && Number.isSafeInteger(baselineCacheOwnership.gid) && baselineCacheOwnership.gid >= 0 ? { uid: baselineCacheOwnership.uid, gid: baselineCacheOwnership.gid } : existsSync7(cachePath) ? ownershipStatSyncImpl(cachePath) : null;
24770
24786
  if (!cacheOwnership) {
24771
24787
  throw new Error("pi_run_exit_closure_baseline_cache_owner_missing");
@@ -24776,7 +24792,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24776
24792
  label: "config",
24777
24793
  path: configPath,
24778
24794
  bytes: Buffer.from(nonEmpty3(closureProfile.configContentsBase64, "closureProfile.configContentsBase64"), "base64"),
24779
- ownership: record10(closureProfile.configOwnership)
24795
+ ownership: record11(closureProfile.configOwnership)
24780
24796
  },
24781
24797
  {
24782
24798
  label: "cache",
@@ -24827,7 +24843,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24827
24843
  const owner = Object.freeze({ commandId: input.commandId, runId });
24828
24844
  writePrivateFile2(markerPath, `${JSON.stringify({ version: 1, ...owner, profileRoot, piCodingAgentDir })}
24829
24845
  `);
24830
- const runtimeAuth = record10(input.runtimeAuth);
24846
+ const runtimeAuth = record11(input.runtimeAuth);
24831
24847
  const authority = Object.freeze({
24832
24848
  companyId: nonEmpty3(runtimeAuth.companyId, "runtimeAuth.companyId"),
24833
24849
  agentId: nonEmpty3(runtimeAuth.agentId, "runtimeAuth.agentId"),
@@ -24854,7 +24870,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24854
24870
  const config = {
24855
24871
  ...sourceMcp,
24856
24872
  settings: {
24857
- ...record10(sourceMcp.settings),
24873
+ ...record11(sourceMcp.settings),
24858
24874
  // Governed catalog exposed names are already provider-safe and are the
24859
24875
  // exact identities attested by the Server. A desktop user's adapter
24860
24876
  // prefix is local presentation state and must not rename this run's
@@ -24863,7 +24879,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24863
24879
  ...directCatalog ? { directToolResultDetails: "bounded", freezeDirectTools: true } : {}
24864
24880
  },
24865
24881
  mcpServers: {
24866
- ...record10(sourceMcp.mcpServers),
24882
+ ...record11(sourceMcp.mcpServers),
24867
24883
  [SUPPORTED_SERVER_NAME3]: serverConfig
24868
24884
  }
24869
24885
  };
@@ -24906,7 +24922,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24906
24922
  );
24907
24923
  enabledRoleSkillMetadataBytes = roleSkills.serializedMetadataBytes;
24908
24924
  }
24909
- const userMcpServerNames = Object.keys(record10(sourceMcp.mcpServers)).filter((serverName) => serverName !== SUPPORTED_SERVER_NAME3);
24925
+ const userMcpServerNames = Object.keys(record11(sourceMcp.mcpServers)).filter((serverName) => serverName !== SUPPORTED_SERVER_NAME3);
24910
24926
  const adapterVersion = desktopAdapterReadiness?.ready ? desktopAdapterReadiness.adapterVersion : null;
24911
24927
  const {
24912
24928
  cachePath,
@@ -24929,7 +24945,7 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24929
24945
  });
24930
24946
  const env = {
24931
24947
  ...input.baseEnv,
24932
- ...record10(input.commandEnv),
24948
+ ...record11(input.commandEnv),
24933
24949
  AMASTER_RUNTIME_RUN_ID: authority.runId,
24934
24950
  AMASTER_RUNTIME_COMMAND_ID: authority.commandId,
24935
24951
  ...authority.issueId ? { AMASTER_RUNTIME_ISSUE_ID: authority.issueId } : {},
@@ -25467,8 +25483,8 @@ function resultOutboxFileName(commandId, now = Date.now()) {
25467
25483
  return `${now}-${safeCommandId}.json`;
25468
25484
  }
25469
25485
  function isValidResultOutboxEntry(entry) {
25470
- const record10 = asRecord(entry);
25471
- return record10.version === 1 && Boolean(readString(record10.path)) && Object.keys(asRecord(record10.payload)).length > 0;
25486
+ const record11 = asRecord(entry);
25487
+ return record11.version === 1 && Boolean(readString(record11.path)) && Object.keys(asRecord(record11.payload)).length > 0;
25472
25488
  }
25473
25489
  function resultOutboxEntryAgeMs(entry, nowMs) {
25474
25490
  const createdAt = Date.parse(readString(entry.createdAt) ?? "");
@@ -25532,7 +25548,7 @@ function nextRunCompletionPhase(phase, event) {
25532
25548
  // src/amaster-runtime-daemon/run-completion-state.mjs
25533
25549
  var RUN_COMPLETION_STATE_VERSION = 1;
25534
25550
  var RUN_COMPLETION_USAGE_SCHEMA_VERSION = "runtime-command-usage-v1";
25535
- function record7(value) {
25551
+ function record8(value) {
25536
25552
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
25537
25553
  }
25538
25554
  function nonEmptyString(value, label) {
@@ -25557,8 +25573,8 @@ function runCompletionStateFileName(commandId) {
25557
25573
  return `${safeCommandId}.json`;
25558
25574
  }
25559
25575
  function normalizeRunTurnUsage(turn) {
25560
- const source = record7(turn);
25561
- const nestedUsage = record7(source.usage);
25576
+ const source = record8(turn);
25577
+ const nestedUsage = record8(source.usage);
25562
25578
  const usage = Object.keys(nestedUsage).length > 0 ? nestedUsage : source;
25563
25579
  const allowedTurnKinds = /* @__PURE__ */ new Set([
25564
25580
  "primary",
@@ -25600,11 +25616,11 @@ function aggregateRunTurnUsage(turns) {
25600
25616
  };
25601
25617
  }
25602
25618
  function createRunCompletionState(input) {
25603
- const command = record7(input.command);
25619
+ const command = record8(input.command);
25604
25620
  const commandId = nonEmptyString(command.commandId ?? command.id, "command.commandId");
25605
25621
  const connectorId = nonEmptyString(input.connectorId ?? command.connectorId, "connectorId");
25606
25622
  const now = typeof input.now === "string" && input.now ? input.now : (/* @__PURE__ */ new Date()).toISOString();
25607
- const firstTurn = normalizeRunTurnUsage({ ...record7(input.turn), turn: "primary", recordedAt: now });
25623
+ const firstTurn = normalizeRunTurnUsage({ ...record8(input.turn), turn: "primary", recordedAt: now });
25608
25624
  return {
25609
25625
  version: RUN_COMPLETION_STATE_VERSION,
25610
25626
  commandId,
@@ -25617,10 +25633,10 @@ function createRunCompletionState(input) {
25617
25633
  terminalDisposition: 0
25618
25634
  },
25619
25635
  command,
25620
- executor: record7(input.executor),
25621
- completionRequest: record7(input.completionRequest),
25636
+ executor: record8(input.executor),
25637
+ completionRequest: record8(input.completionRequest),
25622
25638
  candidateStatus: nonEmptyString(input.candidateStatus, "candidateStatus"),
25623
- candidateResult: record7(input.candidateResult),
25639
+ candidateResult: record8(input.candidateResult),
25624
25640
  ...typeof input.candidateError === "string" && input.candidateError ? { candidateError: input.candidateError } : {},
25625
25641
  usageRecord: {
25626
25642
  schemaVersion: RUN_COMPLETION_USAGE_SCHEMA_VERSION,
@@ -25668,7 +25684,7 @@ function transitionRunCompletionState(state, event, patch = {}, now = (/* @__PUR
25668
25684
  }
25669
25685
  return assertValidRunCompletionState({
25670
25686
  ...current,
25671
- ...record7(patch),
25687
+ ...record8(patch),
25672
25688
  phase: nextPhase,
25673
25689
  updatedAt: now
25674
25690
  });
@@ -25681,24 +25697,24 @@ function markRunCompletionCostDelivered(state, receipt, now = (/* @__PURE__ */ n
25681
25697
  ...current.usageRecord,
25682
25698
  ingestStatus: "delivered",
25683
25699
  deliveredAt: now,
25684
- receipt: record7(receipt)
25700
+ receipt: record8(receipt)
25685
25701
  }
25686
25702
  }, "cost_ingest_delivered", {}, now);
25687
25703
  }
25688
25704
  function assertValidRunCompletionState(value) {
25689
- const state = record7(value);
25705
+ const state = record8(value);
25690
25706
  if (state.version !== RUN_COMPLETION_STATE_VERSION) throw new Error("run_completion_state_invalid:version");
25691
25707
  const commandId = nonEmptyString(state.commandId, "commandId");
25692
25708
  const connectorId = nonEmptyString(state.connectorId, "connectorId");
25693
25709
  if (!isRunCompletionPhase(state.phase)) throw new Error("run_completion_state_invalid:phase");
25694
- const command = record7(state.command);
25710
+ const command = record8(state.command);
25695
25711
  if (nonEmptyString(command.commandId ?? command.id, "command.commandId") !== commandId) {
25696
25712
  throw new Error("run_completion_state_invalid:command_binding");
25697
25713
  }
25698
25714
  if (nonEmptyString(command.connectorId, "command.connectorId") !== connectorId) {
25699
25715
  throw new Error("run_completion_state_invalid:connector_binding");
25700
25716
  }
25701
- const usageRecord = record7(state.usageRecord);
25717
+ const usageRecord = record8(state.usageRecord);
25702
25718
  if (usageRecord.schemaVersion !== RUN_COMPLETION_USAGE_SCHEMA_VERSION) {
25703
25719
  throw new Error("run_completion_state_invalid:usage_schema");
25704
25720
  }
@@ -25729,9 +25745,9 @@ function assertValidRunCompletionState(value) {
25729
25745
  commandId,
25730
25746
  connectorId,
25731
25747
  command,
25732
- executor: record7(state.executor),
25733
- completionRequest: record7(state.completionRequest),
25734
- candidateResult: record7(state.candidateResult),
25748
+ executor: record8(state.executor),
25749
+ completionRequest: record8(state.completionRequest),
25750
+ candidateResult: record8(state.candidateResult),
25735
25751
  usageRecord: {
25736
25752
  ...usageRecord,
25737
25753
  turns,
@@ -25771,7 +25787,7 @@ var FINALIZATION_PHASES = /* @__PURE__ */ new Set([
25771
25787
  "profile_cleanup",
25772
25788
  "result_post_pending"
25773
25789
  ]);
25774
- function record8(value) {
25790
+ function record9(value) {
25775
25791
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
25776
25792
  }
25777
25793
  function string(value) {
@@ -25784,13 +25800,13 @@ function truncate(value, limit = 1e3) {
25784
25800
  return truncateText(value instanceof Error ? value.message : String(value), limit);
25785
25801
  }
25786
25802
  function defaultErrorCode(error) {
25787
- const body = record8(error?.responseBody);
25788
- const details = record8(body.details);
25803
+ const body = record9(error?.responseBody);
25804
+ const details = record9(body.details);
25789
25805
  return string(details.code) ?? string(body.code);
25790
25806
  }
25791
25807
  function defaultTerminalStatus(error) {
25792
25808
  if (defaultErrorCode(error) !== "runtime_completion_check_command_not_acknowledged") return null;
25793
- const status = string(record8(record8(error?.responseBody).details).status);
25809
+ const status = string(record9(record9(error?.responseBody).details).status);
25794
25810
  return ["succeeded", "failed", "cancelled"].includes(status ?? "") ? status : null;
25795
25811
  }
25796
25812
  function defaultCompletionRetryable(error) {
@@ -25811,20 +25827,20 @@ function defaultCleanupOwnerMismatch(error) {
25811
25827
  return /^(?:pi|codex|codebuddy)_managed_mcp_cleanup_owner_mismatch:/.test(message) || /^pi_delegated_mcp_cleanup_owner_mismatch:/.test(message);
25812
25828
  }
25813
25829
  function runCompletionCheckRequest(state) {
25814
- const prior = record8(state.completionRequest);
25815
- const turns = Array.isArray(record8(state.usageRecord).turns) ? record8(state.usageRecord).turns.map(record8) : [];
25830
+ const prior = record9(state.completionRequest);
25831
+ const turns = Array.isArray(record9(state.usageRecord).turns) ? record9(state.usageRecord).turns.map(record9) : [];
25816
25832
  const terminalTextRepairAttempt = turns.some((turn) => turn.turn === "terminal_text_repair") ? 1 : 0;
25817
25833
  const closureAttempt = state.closureAttempt === 1 ? 1 : 0;
25818
25834
  const closureAttempts = {
25819
- workDisposition: number(record8(state.closureAttempts).workDisposition) === 1 ? 1 : 0,
25820
- livePath: number(record8(state.closureAttempts).livePath) === 1 ? 1 : 0,
25821
- terminalDisposition: number(record8(state.closureAttempts).terminalDisposition) === 1 ? 1 : 0
25835
+ workDisposition: number(record9(state.closureAttempts).workDisposition) === 1 ? 1 : 0,
25836
+ livePath: number(record9(state.closureAttempts).livePath) === 1 ? 1 : 0,
25837
+ terminalDisposition: number(record9(state.closureAttempts).terminalDisposition) === 1 ? 1 : 0
25822
25838
  };
25823
25839
  const v2 = prior.contractVersion === "amaster.runtime-connector.completion-check.v2";
25824
25840
  const closureTurnCount = v2 ? closureAttempts.workDisposition + closureAttempts.livePath + closureAttempts.terminalDisposition : closureAttempt;
25825
25841
  return {
25826
25842
  contractVersion: v2 ? "amaster.runtime-connector.completion-check.v2" : "amaster.runtime-connector.completion-check.v1",
25827
- ...string(record8(state.command).leaseId) ? { leaseId: string(record8(state.command).leaseId) } : {},
25843
+ ...string(record9(state.command).leaseId) ? { leaseId: string(record9(state.command).leaseId) } : {},
25828
25844
  proposedStatus: state.candidateStatus,
25829
25845
  resultSignals: {
25830
25846
  productiveSuccessfulRun: prior.resultSignals?.productiveSuccessfulRun === true,
@@ -25835,7 +25851,7 @@ function runCompletionCheckRequest(state) {
25835
25851
  };
25836
25852
  }
25837
25853
  function usageResult(state) {
25838
- const aggregate = record8(record8(state.usageRecord).aggregate);
25854
+ const aggregate = record9(record9(state.usageRecord).aggregate);
25839
25855
  const costUsd = number(aggregate.costUsd);
25840
25856
  return {
25841
25857
  inputTokens: number(aggregate.inputTokens),
@@ -25849,27 +25865,27 @@ function failedCandidate(state, errorCode, message, evidence, now) {
25849
25865
  candidateStatus: "failed",
25850
25866
  candidateError: message,
25851
25867
  candidateResult: {
25852
- ...record8(state.candidateResult),
25868
+ ...record9(state.candidateResult),
25853
25869
  errorCode,
25854
25870
  completionDeliveryFailure: {
25855
25871
  phase: state.phase,
25856
25872
  failedAt: now,
25857
- ...record8(evidence)
25873
+ ...record9(evidence)
25858
25874
  }
25859
25875
  }
25860
25876
  };
25861
25877
  }
25862
25878
  function resultPayload(state) {
25863
- const leaseId = string(record8(state.command).leaseId);
25879
+ const leaseId = string(record9(state.command).leaseId);
25864
25880
  return {
25865
25881
  ...leaseId ? { leaseId } : {},
25866
25882
  status: state.candidateStatus,
25867
- result: record8(state.candidateResult),
25883
+ result: record9(state.candidateResult),
25868
25884
  ...string(state.candidateError) ? { error: truncate(state.candidateError, 4e3) } : {}
25869
25885
  };
25870
25886
  }
25871
25887
  function closureAttemptKey(response) {
25872
- const phase = string(record8(response).closurePhase) ?? "disposition_closure";
25888
+ const phase = string(record9(response).closurePhase) ?? "disposition_closure";
25873
25889
  if (phase === "work_disposition_closure") return "workDisposition";
25874
25890
  if (phase === "live_path_closure") return "livePath";
25875
25891
  if (phase === "terminal_disposition_closure") return "terminalDisposition";
@@ -25895,7 +25911,7 @@ function createRunCompletionCoordinator(inputPorts) {
25895
25911
  completionCheckRetryDelayMs: 100,
25896
25912
  phaseMaxAttempts: 10,
25897
25913
  maxAgeMs: 7 * 24 * 60 * 60 * 1e3,
25898
- ...record8(ports.limits)
25914
+ ...record9(ports.limits)
25899
25915
  };
25900
25916
  const persist = (state) => ports.persistState(state);
25901
25917
  const now = () => ports.now();
@@ -25934,7 +25950,7 @@ function createRunCompletionCoordinator(inputPorts) {
25934
25950
  for (let attempt = 1; attempt <= limits.completionCheckMaxAttempts; attempt += 1) {
25935
25951
  try {
25936
25952
  const request = runCompletionCheckRequest(state);
25937
- const response = record8(await ports.completionAuthority({ state, request }));
25953
+ const response = record9(await ports.completionAuthority({ state, request }));
25938
25954
  if (![
25939
25955
  "amaster.runtime-connector.completion-check.v1",
25940
25956
  "amaster.runtime-connector.completion-check.v2"
@@ -25947,7 +25963,7 @@ function createRunCompletionCoordinator(inputPorts) {
25947
25963
  state = transitionRunCompletionState(state, event, {
25948
25964
  completionResponse: response,
25949
25965
  candidateResult: {
25950
- ...record8(state.candidateResult),
25966
+ ...record9(state.candidateResult),
25951
25967
  completionObservation: {
25952
25968
  outcome: response.outcome,
25953
25969
  enforcementMode: response.enforcementMode,
@@ -25969,7 +25985,7 @@ function createRunCompletionCoordinator(inputPorts) {
25969
25985
  candidateStatus: "failed",
25970
25986
  candidateError: message2,
25971
25987
  candidateResult: {
25972
- ...record8(state.candidateResult),
25988
+ ...record9(state.candidateResult),
25973
25989
  errorCode: ports.errorCode(error) ?? string(error?.code) ?? "runtime_completion_check_authority_rejected",
25974
25990
  completionCheckAbort: {
25975
25991
  httpStatus: Number(error?.httpStatus) || null,
@@ -26019,17 +26035,17 @@ function createRunCompletionCoordinator(inputPorts) {
26019
26035
  }
26020
26036
  if (state.phase === "cost_ingest_pending") {
26021
26037
  try {
26022
- const receipt = record8(await ports.costIngestor(state));
26038
+ const receipt = record9(await ports.costIngestor(state));
26023
26039
  const aggregateUsage = usageResult(state);
26024
- const aggregate = record8(record8(state.usageRecord).aggregate);
26040
+ const aggregate = record9(record9(state.usageRecord).aggregate);
26025
26041
  state = markRunCompletionCostDelivered({
26026
26042
  ...state,
26027
26043
  candidateResult: {
26028
- ...record8(state.candidateResult),
26044
+ ...record9(state.candidateResult),
26029
26045
  usage: aggregateUsage,
26030
- usageBreakdown: Array.isArray(record8(state.usageRecord).turns) ? record8(state.usageRecord).turns : [],
26046
+ usageBreakdown: Array.isArray(record9(state.usageRecord).turns) ? record9(state.usageRecord).turns : [],
26031
26047
  costUsage: {
26032
- idempotencyKey: string(record8(state.usageRecord).idempotencyKey),
26048
+ idempotencyKey: string(record9(state.usageRecord).idempotencyKey),
26033
26049
  ...string(receipt.costEventId) ? { costEventId: string(receipt.costEventId) } : {},
26034
26050
  ...aggregateUsage,
26035
26051
  costCents: number(aggregate.costCents)
@@ -26050,7 +26066,7 @@ function createRunCompletionCoordinator(inputPorts) {
26050
26066
  diagnose(`AMaster daemon retained cost_ingest_pending state for ${state.commandId}: ${message}`);
26051
26067
  return { pending: true, resultDelivered: false, state };
26052
26068
  }
26053
- const usageRecord = record8(state.usageRecord);
26069
+ const usageRecord = record9(state.usageRecord);
26054
26070
  state = persist(transitionRunCompletionState({
26055
26071
  ...state,
26056
26072
  usageRecord: {
@@ -26075,13 +26091,13 @@ function createRunCompletionCoordinator(inputPorts) {
26075
26091
  }
26076
26092
  if (state.phase === "profile_cleanup") {
26077
26093
  try {
26078
- const cleanup = record8(await ports.profileCleaner(state));
26079
- const candidateResult = record8(state.candidateResult);
26094
+ const cleanup = record9(await ports.profileCleaner(state));
26095
+ const candidateResult = record9(state.candidateResult);
26080
26096
  state = transitionRunCompletionState(state, "profile_cleaned", {
26081
26097
  managedMcpCleanup: cleanup,
26082
26098
  candidateResult: {
26083
26099
  ...candidateResult,
26084
- ...Object.keys(record8(candidateResult.managedMcp)).length > 0 ? { managedMcp: { ...record8(candidateResult.managedMcp), cleanup } } : {}
26100
+ ...Object.keys(record9(candidateResult.managedMcp)).length > 0 ? { managedMcp: { ...record9(candidateResult.managedMcp), cleanup } } : {}
26085
26101
  }
26086
26102
  }, now());
26087
26103
  state = persist(state);
@@ -26193,7 +26209,7 @@ function createRunCompletionCoordinator(inputPorts) {
26193
26209
  pending: false,
26194
26210
  resultDelivered: true,
26195
26211
  state,
26196
- managedMcpCleanup: record8(state.managedMcpCleanup)
26212
+ managedMcpCleanup: record9(state.managedMcpCleanup)
26197
26213
  };
26198
26214
  }
26199
26215
  async function coordinate(inputState, options = {}) {
@@ -26207,23 +26223,23 @@ function createRunCompletionCoordinator(inputPorts) {
26207
26223
  }
26208
26224
  if (checked.pending) return { pending: true, resultDelivered: false, state };
26209
26225
  while (state.phase === "disposition_required") {
26210
- const response = record8(state.completionResponse);
26226
+ const response = record9(state.completionResponse);
26211
26227
  const attemptKey = closureAttemptKey(response);
26212
26228
  const v2 = response.contractVersion === "amaster.runtime-connector.completion-check.v2";
26213
- const closureTurns = record8(state.closureTurns);
26229
+ const closureTurns = record9(state.closureTurns);
26214
26230
  const alreadyRecorded = attemptKey ? Boolean(closureTurns[attemptKey]) : state.closureTurnRecorded === true;
26215
26231
  const recoveryCount = number(state.closureRecoveryCount);
26216
26232
  const mayResumeUncertainClosure = recoveringClosure && !alreadyRecorded && recoveryCount < 1;
26217
- const priorAttempt = attemptKey ? number(record8(state.closureAttempts)[attemptKey]) : number(state.closureAttempt);
26233
+ const priorAttempt = attemptKey ? number(record9(state.closureAttempts)[attemptKey]) : number(state.closureAttempt);
26218
26234
  if (priorAttempt === 0 || mayResumeUncertainClosure) {
26219
- const nextAttempts = attemptKey ? { ...record8(state.closureAttempts), [attemptKey]: 1 } : record8(state.closureAttempts);
26235
+ const nextAttempts = attemptKey ? { ...record9(state.closureAttempts), [attemptKey]: 1 } : record9(state.closureAttempts);
26220
26236
  state = persist(transitionRunCompletionState(state, "closure_started", {
26221
26237
  ...v2 ? { closureAttempts: nextAttempts } : { closureAttempt: 1 },
26222
26238
  ...mayResumeUncertainClosure ? { closureRecoveryCount: recoveryCount + 1 } : {}
26223
26239
  }, now()));
26224
26240
  let closure;
26225
26241
  try {
26226
- closure = record8(await ports.closureExecutor({ state, options }));
26242
+ closure = record9(await ports.closureExecutor({ state, options }));
26227
26243
  } catch (error) {
26228
26244
  closure = {
26229
26245
  succeeded: false,
@@ -26237,24 +26253,24 @@ function createRunCompletionCoordinator(inputPorts) {
26237
26253
  }
26238
26254
  };
26239
26255
  }
26240
- const candidateResult = record8(state.candidateResult);
26256
+ const candidateResult = record9(state.candidateResult);
26241
26257
  state = appendRunCompletionUsageTurn({
26242
26258
  ...state,
26243
- ...attemptKey ? { closureTurns: { ...closureTurns, [attemptKey]: record8(closure.audit) } } : { closureTurnRecorded: true },
26259
+ ...attemptKey ? { closureTurns: { ...closureTurns, [attemptKey]: record9(closure.audit) } } : { closureTurnRecorded: true },
26244
26260
  candidateResult: {
26245
26261
  ...candidateResult,
26246
- closureTurn: record8(closure.audit),
26247
- ...attemptKey ? { closureTurns: { ...record8(candidateResult.closureTurns), [attemptKey]: record8(closure.audit) } } : {}
26262
+ closureTurn: record9(closure.audit),
26263
+ ...attemptKey ? { closureTurns: { ...record9(candidateResult.closureTurns), [attemptKey]: record9(closure.audit) } } : {}
26248
26264
  }
26249
26265
  }, {
26250
26266
  turn: closureTurnKind(attemptKey),
26251
- usage: record8(closure.usage),
26267
+ usage: record9(closure.usage),
26252
26268
  recordedAt: now()
26253
26269
  });
26254
26270
  state = persist({
26255
26271
  ...state,
26256
26272
  completionRequest: {
26257
- ...record8(state.completionRequest),
26273
+ ...record9(state.completionRequest),
26258
26274
  resultSignals: runCompletionCheckRequest(state).resultSignals
26259
26275
  }
26260
26276
  });
@@ -26269,9 +26285,9 @@ function createRunCompletionCoordinator(inputPorts) {
26269
26285
  break;
26270
26286
  }
26271
26287
  if (state.phase === "disposition_required") {
26272
- const candidateResult = record8(state.candidateResult);
26273
- const closureTurn = record8(candidateResult.closureTurn);
26274
- const response = record8(state.completionResponse);
26288
+ const candidateResult = record9(state.candidateResult);
26289
+ const closureTurn = record9(candidateResult.closureTurn);
26290
+ const response = record9(state.completionResponse);
26275
26291
  const closureFailure = failedCandidate(
26276
26292
  state,
26277
26293
  AMASTER_RUNTIME_COMPLETION_CLOSURE_EXHAUSTED_ERROR_CODE,
@@ -26283,7 +26299,7 @@ function createRunCompletionCoordinator(inputPorts) {
26283
26299
  ...closureFailure,
26284
26300
  candidateResult: {
26285
26301
  ...candidateResult,
26286
- ...record8(closureFailure.candidateResult),
26302
+ ...record9(closureFailure.candidateResult),
26287
26303
  errorCode: AMASTER_RUNTIME_COMPLETION_CLOSURE_EXHAUSTED_ERROR_CODE,
26288
26304
  ...Object.keys(closureTurn).length > 0 ? {} : {
26289
26305
  closureTurn: {
@@ -26299,7 +26315,7 @@ function createRunCompletionCoordinator(inputPorts) {
26299
26315
  attempt: 1,
26300
26316
  reasonCode: string(response.reasonCode) ?? "disposition_still_required",
26301
26317
  commandId: state.commandId,
26302
- runId: string(record8(state.command).runId) ?? string(record8(record8(state.command).payload).runId)
26318
+ runId: string(record9(state.command).runId) ?? string(record9(record9(state.command).payload).runId)
26303
26319
  }
26304
26320
  }
26305
26321
  }, now()));
@@ -26773,10 +26789,10 @@ function compactExecutorJsonlForTranscript(event) {
26773
26789
  const text2 = JSON.stringify(compactExecutorJsonValue(event, stringMaxChars));
26774
26790
  if (text2.length <= 15e3) return text2;
26775
26791
  }
26776
- const record10 = tcAsRecord(event);
26777
- const item = tcAsRecord(record10.item);
26792
+ const record11 = tcAsRecord(event);
26793
+ const item = tcAsRecord(record11.item);
26778
26794
  return JSON.stringify({
26779
- type: tcReadString(record10.type) ?? "executor.event",
26795
+ type: tcReadString(record11.type) ?? "executor.event",
26780
26796
  item: item.type ? {
26781
26797
  id: tcReadString(item.id),
26782
26798
  type: tcReadString(item.type),
@@ -26789,31 +26805,31 @@ function compactExecutorJsonlForTranscript(event) {
26789
26805
  });
26790
26806
  }
26791
26807
  function compactPiToolLifecycleForTranscript(event, readableSummary) {
26792
- const record10 = tcAsRecord(event);
26793
- const type = tcReadString(record10.type);
26808
+ const record11 = tcAsRecord(event);
26809
+ const type = tcReadString(record11.type);
26794
26810
  if (type !== "tool_execution_start" && type !== "tool_execution_end") return null;
26795
- const toolCallId = tcReadString(record10.toolCallId);
26811
+ const toolCallId = tcReadString(record11.toolCallId);
26796
26812
  if (!toolCallId) return null;
26797
- const toolName = tcReadString(record10.toolName) ?? "tool";
26813
+ const toolName = tcReadString(record11.toolName) ?? "tool";
26798
26814
  const summary = tcTruncateText(readableSummary || `${type === "tool_execution_start" ? "\u5DE5\u5177\u5F00\u59CB" : "\u5DE5\u5177\u5B8C\u6210"}\uFF1A${toolName}`, 500);
26799
26815
  return JSON.stringify(type === "tool_execution_start" ? {
26800
26816
  type,
26801
26817
  toolCallId,
26802
26818
  toolName,
26803
- args: record10.args == null ? { summary } : compactToolTranscriptPayload(record10.args)
26819
+ args: record11.args == null ? { summary } : compactToolTranscriptPayload(record11.args)
26804
26820
  } : {
26805
26821
  type,
26806
26822
  toolCallId,
26807
26823
  toolName,
26808
- result: record10.result == null ? summary : compactToolTranscriptPayload(record10.result),
26809
- isError: record10.isError === true
26824
+ result: record11.result == null ? summary : compactToolTranscriptPayload(record11.result),
26825
+ isError: record11.isError === true
26810
26826
  });
26811
26827
  }
26812
26828
  function summarizeTokenUsage(usage) {
26813
- const record10 = tcAsRecord(usage);
26814
- const inputTokens = tcReadNumber(record10.input_tokens ?? record10.inputTokens, 0);
26815
- const cachedInputTokens = tcReadNumber(record10.cached_input_tokens ?? record10.cachedInputTokens, 0);
26816
- const outputTokens = tcReadNumber(record10.output_tokens ?? record10.outputTokens, 0);
26829
+ const record11 = tcAsRecord(usage);
26830
+ const inputTokens = tcReadNumber(record11.input_tokens ?? record11.inputTokens, 0);
26831
+ const cachedInputTokens = tcReadNumber(record11.cached_input_tokens ?? record11.cachedInputTokens, 0);
26832
+ const outputTokens = tcReadNumber(record11.output_tokens ?? record11.outputTokens, 0);
26817
26833
  const parts = [];
26818
26834
  if (inputTokens > 0) parts.push(`\u8F93\u5165 ${inputTokens}`);
26819
26835
  if (cachedInputTokens > 0) parts.push(`\u7F13\u5B58 ${cachedInputTokens}`);
@@ -27075,8 +27091,8 @@ function summarizeClaudeEvent(event) {
27075
27091
  return null;
27076
27092
  }
27077
27093
  function tcPiMessageText(message) {
27078
- const record10 = tcAsRecord(message);
27079
- const content = record10.content;
27094
+ const record11 = tcAsRecord(message);
27095
+ const content = record11.content;
27080
27096
  if (typeof content === "string" && content.trim().length > 0) return content.trim();
27081
27097
  if (!Array.isArray(content)) return "";
27082
27098
  return content.map((entry) => {
@@ -27090,14 +27106,14 @@ function tcPiAssistantMessageEventText(assistantMessageEvent) {
27090
27106
  return tcReadString(event.content) ?? "";
27091
27107
  }
27092
27108
  function tcPiMessageStopReason(message) {
27093
- const record10 = tcAsRecord(message);
27094
- return tcReadString(record10.stopReason ?? record10.stop_reason);
27109
+ const record11 = tcAsRecord(message);
27110
+ return tcReadString(record11.stopReason ?? record11.stop_reason);
27095
27111
  }
27096
27112
  function tcPiMessageErrorText(message) {
27097
- const record10 = tcAsRecord(message);
27098
- const explicitError = tcReadString(record10.errorMessage ?? record10.error_message)?.trim();
27113
+ const record11 = tcAsRecord(message);
27114
+ const explicitError = tcReadString(record11.errorMessage ?? record11.error_message)?.trim();
27099
27115
  if (explicitError) return explicitError;
27100
- const stopReason = tcPiMessageStopReason(record10);
27116
+ const stopReason = tcPiMessageStopReason(record11);
27101
27117
  if (stopReason === "error" || stopReason === "failed" || stopReason === "exception") {
27102
27118
  return `Pi Agent message ended with stopReason=${stopReason}`;
27103
27119
  }
@@ -27509,16 +27525,16 @@ function structuredToolResults(value, depth = 0) {
27509
27525
  return [];
27510
27526
  }
27511
27527
  }
27512
- const record10 = asRecord(value);
27513
- const structuredContent = structuredToolResults(record10.structuredContent, depth + 1);
27528
+ const record11 = asRecord(value);
27529
+ const structuredContent = structuredToolResults(record11.structuredContent, depth + 1);
27514
27530
  if (structuredContent.length > 0) return structuredContent;
27515
- if (readString(record10.status)) return [record10];
27531
+ if (readString(record11.status)) return [record11];
27516
27532
  const candidates = [];
27517
27533
  for (const nested of [
27518
- record10.content,
27519
- record10.text,
27520
- record10.result,
27521
- record10.output
27534
+ record11.content,
27535
+ record11.text,
27536
+ record11.result,
27537
+ record11.output
27522
27538
  ]) {
27523
27539
  candidates.push(...structuredToolResults(nested, depth + 1));
27524
27540
  }
@@ -27604,10 +27620,10 @@ function createCodebuddyMcpToolResultTracker(options = {}) {
27604
27620
  },
27605
27621
  record(event) {
27606
27622
  if (trackingFailure) return [];
27607
- const record10 = asRecord(event);
27608
- const eventType = readString(record10.type);
27623
+ const record11 = asRecord(event);
27624
+ const eventType = readString(record11.type);
27609
27625
  if (eventType === "assistant") {
27610
- const message2 = asRecord(record10.message);
27626
+ const message2 = asRecord(record11.message);
27611
27627
  for (const rawBlock of Array.isArray(message2.content) ? message2.content : []) {
27612
27628
  const block = asRecord(rawBlock);
27613
27629
  if (["tool_use", "toolUse"].includes(readString(block.type) ?? "")) {
@@ -27622,18 +27638,18 @@ function createCodebuddyMcpToolResultTracker(options = {}) {
27622
27638
  }
27623
27639
  if (eventType === "function_call") {
27624
27640
  rememberToolUse(
27625
- record10.call_id ?? record10.tool_use_id ?? record10.id,
27626
- record10.name,
27627
- record10.input ?? record10.arguments
27641
+ record11.call_id ?? record11.tool_use_id ?? record11.id,
27642
+ record11.name,
27643
+ record11.input ?? record11.arguments
27628
27644
  );
27629
27645
  return [];
27630
27646
  }
27631
27647
  if (eventType === "function_call_result") {
27632
- const callId = readString(record10.call_id ?? record10.tool_use_id ?? record10.id);
27633
- return recordResult(callId, record10.output ?? record10.result);
27648
+ const callId = readString(record11.call_id ?? record11.tool_use_id ?? record11.id);
27649
+ return recordResult(callId, record11.output ?? record11.result);
27634
27650
  }
27635
27651
  if (eventType !== "user") return [];
27636
- const message = asRecord(record10.message);
27652
+ const message = asRecord(record11.message);
27637
27653
  const results = [];
27638
27654
  for (const rawBlock of Array.isArray(message.content) ? message.content : []) {
27639
27655
  const block = asRecord(rawBlock);
@@ -27953,8 +27969,8 @@ function classifyPiOutputFailure(input, options = {}) {
27953
27969
  };
27954
27970
  }
27955
27971
  function piMessageText(message) {
27956
- const record10 = asRecord(message);
27957
- const content = record10.content;
27972
+ const record11 = asRecord(message);
27973
+ const content = record11.content;
27958
27974
  if (typeof content === "string") return content.trim();
27959
27975
  if (!Array.isArray(content)) return "";
27960
27976
  return content.map((entry) => {
@@ -27963,10 +27979,10 @@ function piMessageText(message) {
27963
27979
  }).filter(Boolean).join("\n").trim();
27964
27980
  }
27965
27981
  function piAgentEndHasFinalAssistantText(event) {
27966
- const record10 = asRecord(event);
27967
- if (record10.type !== "agent_end") return false;
27968
- const messages = Array.isArray(record10.messages) ? [...record10.messages] : [];
27969
- if (Object.keys(asRecord(record10.message)).length > 0) messages.push(record10.message);
27982
+ const record11 = asRecord(event);
27983
+ if (record11.type !== "agent_end") return false;
27984
+ const messages = Array.isArray(record11.messages) ? [...record11.messages] : [];
27985
+ if (Object.keys(asRecord(record11.message)).length > 0) messages.push(record11.message);
27970
27986
  for (let index = messages.length - 1; index >= 0; index -= 1) {
27971
27987
  const message = asRecord(messages[index]);
27972
27988
  if (message.role !== "assistant") continue;
@@ -27975,9 +27991,9 @@ function piAgentEndHasFinalAssistantText(event) {
27975
27991
  return false;
27976
27992
  }
27977
27993
  function piTurnEndHasFinalAssistantText(event) {
27978
- const record10 = asRecord(event);
27979
- if (record10.type !== "turn_end") return false;
27980
- const message = asRecord(record10.message);
27994
+ const record11 = asRecord(event);
27995
+ if (record11.type !== "turn_end") return false;
27996
+ const message = asRecord(record11.message);
27981
27997
  return message.role === "assistant" && Boolean(piMessageText(message));
27982
27998
  }
27983
27999
  function piMessageHasToolCall(message) {
@@ -28005,10 +28021,10 @@ function piTextValue(value) {
28005
28021
  return typeof value === "string" && value.length > 0 ? value : "";
28006
28022
  }
28007
28023
  function piAssistantEventText(assistantEvent) {
28008
- const record10 = asRecord(assistantEvent);
28009
- const type = readString(record10.type);
28010
- if (type === "text_delta") return piTextValue(record10.delta);
28011
- if (type === "text_end") return piTextValue(record10.content);
28024
+ const record11 = asRecord(assistantEvent);
28025
+ const type = readString(record11.type);
28026
+ if (type === "text_delta") return piTextValue(record11.delta);
28027
+ if (type === "text_end") return piTextValue(record11.content);
28012
28028
  return "";
28013
28029
  }
28014
28030
  function piMessageUsage(message) {
@@ -28029,14 +28045,14 @@ function assignPiUsage(target, source) {
28029
28045
  if (source.costUsd > 0) target.costUsd = source.costUsd;
28030
28046
  }
28031
28047
  function piMessageStopReason(message) {
28032
- const record10 = asRecord(message);
28033
- return readString(record10.stopReason ?? record10.stop_reason);
28048
+ const record11 = asRecord(message);
28049
+ return readString(record11.stopReason ?? record11.stop_reason);
28034
28050
  }
28035
28051
  function piMessageErrorText(message) {
28036
- const record10 = asRecord(message);
28037
- const explicitError = readString(record10.errorMessage ?? record10.error_message)?.trim();
28052
+ const record11 = asRecord(message);
28053
+ const explicitError = readString(record11.errorMessage ?? record11.error_message)?.trim();
28038
28054
  if (explicitError) return explicitError;
28039
- const stopReason = piMessageStopReason(record10);
28055
+ const stopReason = piMessageStopReason(record11);
28040
28056
  if (stopReason === "error" || stopReason === "failed" || stopReason === "exception") {
28041
28057
  return `Pi Agent message ended with stopReason=${stopReason}`;
28042
28058
  }
@@ -28452,13 +28468,13 @@ function parseClaudeStreamJson(stdout) {
28452
28468
  }
28453
28469
  function openCodeErrorText(value) {
28454
28470
  if (typeof value === "string") return value;
28455
- const record10 = asRecord(value);
28456
- const message = readString(record10.message);
28471
+ const record11 = asRecord(value);
28472
+ const message = readString(record11.message);
28457
28473
  if (message) return message;
28458
- const data = asRecord(record10.data);
28474
+ const data = asRecord(record11.data);
28459
28475
  const nestedMessage = readString(data.message);
28460
28476
  if (nestedMessage) return nestedMessage;
28461
- return readString(record10.name) ?? readString(record10.code) ?? "";
28477
+ return readString(record11.name) ?? readString(record11.code) ?? "";
28462
28478
  }
28463
28479
  function parseOpenCodeJsonl(stdout) {
28464
28480
  let sessionId = null;
@@ -29351,19 +29367,19 @@ function promptContextMode(input) {
29351
29367
  }
29352
29368
  function filterDuplicatedTaskComments(context, mode) {
29353
29369
  if (mode !== "cold") return context;
29354
- const record10 = asRecord(context);
29370
+ const record11 = asRecord(context);
29355
29371
  const included = new Set(
29356
- (Array.isArray(record10.paperclipTaskMarkdownCommentIds) ? record10.paperclipTaskMarkdownCommentIds : []).map((entry) => readString(entry)).filter(Boolean)
29372
+ (Array.isArray(record11.paperclipTaskMarkdownCommentIds) ? record11.paperclipTaskMarkdownCommentIds : []).map((entry) => readString(entry)).filter(Boolean)
29357
29373
  );
29358
29374
  if (included.size === 0) return context;
29359
- const wake = asRecord(record10.paperclipWake);
29375
+ const wake = asRecord(record11.paperclipWake);
29360
29376
  const comments = Array.isArray(wake.comments) ? wake.comments : [];
29361
29377
  const kept = comments.filter((entry) => {
29362
29378
  const id = readString(asRecord(entry).id);
29363
29379
  return !id || !included.has(id);
29364
29380
  });
29365
29381
  if (kept.length === comments.length) return context;
29366
- return { ...record10, paperclipWake: { ...wake, comments: kept } };
29382
+ return { ...record11, paperclipWake: { ...wake, comments: kept } };
29367
29383
  }
29368
29384
  function commentRefs(context) {
29369
29385
  const comments = Array.isArray(asRecord(context.paperclipWake).comments) ? asRecord(context.paperclipWake).comments : [];
@@ -29550,8 +29566,8 @@ function governedReadSection(context) {
29550
29566
  const reads = Array.isArray(context.governedReadResults) ? context.governedReadResults : [];
29551
29567
  if (reads.length === 0) return { content: "", provenance: [] };
29552
29568
  const normalized = reads.map((entry, index) => {
29553
- const record10 = asRecord(entry);
29554
- const receipt = asRecord(record10.receipt);
29569
+ const record11 = asRecord(entry);
29570
+ const receipt = asRecord(record11.receipt);
29555
29571
  const provider = readString(receipt.provider) ?? readString(receipt.transport);
29556
29572
  const operation = readString(receipt.operation);
29557
29573
  const observedAt = readString(receipt.retrievedAt) ?? readString(receipt.observedAt);
@@ -29561,7 +29577,7 @@ function governedReadSection(context) {
29561
29577
  throw new Error(`governed_read_context_provenance_invalid: entry ${index} requires provider, operation, observedAt, and source`);
29562
29578
  }
29563
29579
  return {
29564
- content: record10.content,
29580
+ content: record11.content,
29565
29581
  receipt: {
29566
29582
  provider,
29567
29583
  operation,
@@ -29604,11 +29620,11 @@ function governedBusinessDetailRead(input, issueId) {
29604
29620
  return { mode: "canonical", tool: canonicalTool, arguments: argumentsValue };
29605
29621
  }
29606
29622
  function governedBusinessDecisionProjection(state, detailRead) {
29607
- const record10 = asRecord(state);
29608
- const snapshot = asRecord(record10.governed_state_snapshot);
29609
- const authoritativeObjectRefs = Array.isArray(record10.authoritative_object_refs) ? record10.authoritative_object_refs : [];
29610
- const capabilities = Array.isArray(record10.capabilities) ? record10.capabilities : [];
29611
- const availability = asRecord(record10.availability);
29623
+ const record11 = asRecord(state);
29624
+ const snapshot = asRecord(record11.governed_state_snapshot);
29625
+ const authoritativeObjectRefs = Array.isArray(record11.authoritative_object_refs) ? record11.authoritative_object_refs : [];
29626
+ const capabilities = Array.isArray(record11.capabilities) ? record11.capabilities : [];
29627
+ const availability = asRecord(record11.availability);
29612
29628
  const projection = {
29613
29629
  status: readString(availability.status) ?? null,
29614
29630
  objects: authoritativeObjectRefs.map((entry) => {
@@ -29623,7 +29639,7 @@ function governedBusinessDecisionProjection(state, detailRead) {
29623
29639
  }
29624
29640
  return compact;
29625
29641
  }),
29626
- missing: (Array.isArray(record10.missing_objects) ? record10.missing_objects : []).map((entry) => {
29642
+ missing: (Array.isArray(record11.missing_objects) ? record11.missing_objects : []).map((entry) => {
29627
29643
  const missing = asRecord(entry);
29628
29644
  return {
29629
29645
  kind: readString(missing.object_kind) ?? null,
@@ -29643,22 +29659,22 @@ function governedBusinessDecisionProjection(state, detailRead) {
29643
29659
  if (unavailableReads.length > 0) {
29644
29660
  projection.unavailable_reads = unavailableReads;
29645
29661
  }
29646
- const continuationId = readString(record10.continuation_id);
29662
+ const continuationId = readString(record11.continuation_id);
29647
29663
  if (continuationId) projection.continuation_id = continuationId;
29648
- if (Number.isInteger(record10.outcome_revision)) projection.outcome_revision = record10.outcome_revision;
29649
- const freeTextReason = readString(record10.free_text_reason);
29664
+ if (Number.isInteger(record11.outcome_revision)) projection.outcome_revision = record11.outcome_revision;
29665
+ const freeTextReason = readString(record11.free_text_reason);
29650
29666
  if (freeTextReason) projection.free_text_reason = freeTextReason;
29651
29667
  return projection;
29652
29668
  }
29653
29669
  function governedBusinessModelView(state, input) {
29654
- const record10 = asRecord(state);
29655
- const snapshot = asRecord(record10.governed_state_snapshot);
29670
+ const record11 = asRecord(state);
29671
+ const snapshot = asRecord(record11.governed_state_snapshot);
29656
29672
  const detailRead = governedBusinessDetailRead(
29657
29673
  input,
29658
29674
  readString(snapshot.issue_id) ?? readString(input.issueId)
29659
29675
  );
29660
29676
  if (detailRead.mode === "unavailable") {
29661
- const { task_acceptance_contract: _TaskAcceptanceContract, ...stateWithoutAcceptanceContract } = record10;
29677
+ const { task_acceptance_contract: _TaskAcceptanceContract, ...stateWithoutAcceptanceContract } = record11;
29662
29678
  return {
29663
29679
  mode: "full_snapshot",
29664
29680
  content: stateWithoutAcceptanceContract,
@@ -29667,7 +29683,7 @@ function governedBusinessModelView(state, input) {
29667
29683
  }
29668
29684
  return {
29669
29685
  mode: "decision_projection",
29670
- content: governedBusinessDecisionProjection(record10, detailRead),
29686
+ content: governedBusinessDecisionProjection(record11, detailRead),
29671
29687
  unavailableReason: null
29672
29688
  };
29673
29689
  }
@@ -29733,10 +29749,10 @@ ${bodies}`,
29733
29749
  }
29734
29750
  function canonicalJsonValue(value) {
29735
29751
  if (Array.isArray(value)) return value.map(canonicalJsonValue);
29736
- const record10 = asRecord(value);
29737
- if (Object.keys(record10).length === 0) return value;
29752
+ const record11 = asRecord(value);
29753
+ if (Object.keys(record11).length === 0) return value;
29738
29754
  return Object.fromEntries(
29739
- Object.keys(record10).sort().map((key) => [key, canonicalJsonValue(record10[key])])
29755
+ Object.keys(record11).sort().map((key) => [key, canonicalJsonValue(record11[key])])
29740
29756
  );
29741
29757
  }
29742
29758
  function resolvedDependencySections(context, input, contextScope, snapshotFreshness) {
@@ -33432,7 +33448,7 @@ var USAGE_FIELDS = Object.freeze({
33432
33448
  output: ["outputTokens", "output_tokens", "output"],
33433
33449
  total: ["totalTokens", "total_tokens"]
33434
33450
  });
33435
- function record9(value) {
33451
+ function record10(value) {
33436
33452
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
33437
33453
  }
33438
33454
  function stringValue(value) {
@@ -33484,7 +33500,7 @@ function aliasedUsageInteger(usage, aliases, label) {
33484
33500
  return { present: true, value: entries[0] };
33485
33501
  }
33486
33502
  function piUsageTotal(usageValue) {
33487
- const usage = record9(usageValue);
33503
+ const usage = record10(usageValue);
33488
33504
  const input = aliasedUsageInteger(usage, USAGE_FIELDS.input, "input");
33489
33505
  const cachedInput = aliasedUsageInteger(usage, USAGE_FIELDS.cachedInput, "cached input");
33490
33506
  const cacheCreationInput = aliasedUsageInteger(
@@ -33513,7 +33529,7 @@ function piUsageTotal(usageValue) {
33513
33529
  return Math.max(componentTotal, total.present ? total.value : 0);
33514
33530
  }
33515
33531
  function usageFromContainer(containerValue) {
33516
- const container = record9(containerValue);
33532
+ const container = record10(containerValue);
33517
33533
  if (!Object.prototype.hasOwnProperty.call(container, "usage")) return null;
33518
33534
  const usage = container.usage;
33519
33535
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) {
@@ -33525,7 +33541,7 @@ function usageFromContainer(containerValue) {
33525
33541
  return usage;
33526
33542
  }
33527
33543
  function measureRestoredPiNativeHistory(managedMcpProfile) {
33528
- const restored = record9(managedMcpProfile?.restoredNativeSession);
33544
+ const restored = record10(managedMcpProfile?.restoredNativeSession);
33529
33545
  const rolloutPath = stringValue(restored.rolloutPath);
33530
33546
  if (!rolloutPath) {
33531
33547
  return { status: "fresh", tokens: 0, rolloutBytes: 0, usageTokens: 0 };
@@ -33589,7 +33605,7 @@ function resolvePiModelContextBudget({
33589
33605
  managedMcpProfile
33590
33606
  }) {
33591
33607
  const instructionBytes = [...finalAgentInstructionFiles.values()].reduce((total, entry) => total + Number(entry.byteSize ?? 0), 0);
33592
- const profileAttestation = record9(managedMcpProfile?.attestation);
33608
+ const profileAttestation = record10(managedMcpProfile?.attestation);
33593
33609
  const observedToolSchemaBytes = Number(profileAttestation.catalogToolSchemaBytes);
33594
33610
  const toolSchemaBytes = Number.isSafeInteger(observedToolSchemaBytes) && observedToolSchemaBytes >= 0 ? observedToolSchemaBytes : 0;
33595
33611
  const observedSkillMetadataBytes = Number(profileAttestation.enabledSkillMetadataBytes ?? 0);
@@ -33956,7 +33972,7 @@ function assertRequiredTaskAttachmentMaterialized(input, materialized) {
33956
33972
  }
33957
33973
 
33958
33974
  // src/amaster-runtime-daemon.mjs
33959
- var CONNECTOR_VERSION = "0.1.1-beta.353";
33975
+ var CONNECTOR_VERSION = "0.1.1-beta.354";
33960
33976
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
33961
33977
  var SUPPORTED_TASK_CONTEXT_VERSIONS = Object.freeze([TASK_CONTEXT_MANIFEST_VERSION, TASK_CONTEXT_V2]);
33962
33978
  var daemonRequire = createRequire(import.meta.url);
@@ -35464,7 +35480,7 @@ function requireCommandContextEnvelope(command) {
35464
35480
  }
35465
35481
  const runDecisionContext = asRecord(envelope.runDecisionContext);
35466
35482
  const dynamicContext2 = asRecord(runDecisionContext.content);
35467
- const runDecisionHash = createHash19("sha256").update(canonicalContextJson(dynamicContext2), "utf8").digest("hex");
35483
+ const runDecisionHash = createHash19("sha256").update(canonicalGoalOutcomeValue(dynamicContext2), "utf8").digest("hex");
35468
35484
  if (!readString(runDecisionContext.revision) || !Number.isInteger(runDecisionContext.authorizationEpoch) || runDecisionContext.authorizationEpoch < 0 || runDecisionHash !== readString(runDecisionContext.contentSha256)) throw new Error("context_envelope_run_decision_invalid");
35469
35485
  if (!Array.isArray(envelope.selectedProcedures)) throw new Error("context_envelope_procedures_invalid");
35470
35486
  const toolProfile = asRecord(envelope.toolProfile);
@@ -35474,17 +35490,12 @@ function requireCommandContextEnvelope(command) {
35474
35490
  throw new Error("context_envelope_session_binding_invalid");
35475
35491
  }
35476
35492
  const envelopeHashInput = Object.fromEntries(Object.entries(envelope).filter(([key]) => key !== "envelopeSha256"));
35477
- const envelopeHash = createHash19("sha256").update(canonicalContextJson(envelopeHashInput), "utf8").digest("hex");
35493
+ const envelopeHash = createHash19("sha256").update(canonicalGoalOutcomeValue(envelopeHashInput), "utf8").digest("hex");
35478
35494
  if (envelopeHash !== readString(envelope.envelopeSha256)) {
35479
35495
  throw new Error("context_envelope_hash_mismatch");
35480
35496
  }
35481
35497
  return { envelope, instructions, files, dynamicContext: dynamicContext2 };
35482
35498
  }
35483
- function canonicalContextJson(value) {
35484
- if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
35485
- if (Array.isArray(value)) return `[${value.map(canonicalContextJson).join(",")}]`;
35486
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalContextJson(value[key])}`).join(",")}}`;
35487
- }
35488
35499
  async function materializeEffectiveAgentInstructions(config, command, workspace, instructionContract) {
35489
35500
  const files = asRecord(instructionContract.files);
35490
35501
  const materialized = [];