@amaster.ai/employee-runtime-connector 0.1.1-beta.20 → 0.1.1-beta.21

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.
@@ -2,7 +2,7 @@
2
2
  // MirrorX runtime connector daemon bundle.
3
3
 
4
4
  // src/amaster-runtime-daemon.mjs
5
- import { createHash as createHash13 } from "node:crypto";
5
+ import { createHash as createHash14 } from "node:crypto";
6
6
  import { chmodSync as chmodSync6, copyFileSync as copyFileSync3, existsSync as existsSync14, lstatSync as lstatSync7, mkdirSync as mkdirSync9, mkdtempSync, readFileSync as readFileSync11, readdirSync as readdirSync9, realpathSync as realpathSync5, renameSync as renameSync6, rmSync as rmSync7, statSync as statSync8, symlinkSync as symlinkSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync9 } from "node:fs";
7
7
  import { arch as arch3, homedir as homedir3, hostname as hostname2, platform as platform3, tmpdir } from "node:os";
8
8
  import { basename as basename6, delimiter as delimiter3, dirname as dirname9, extname as extname2, isAbsolute as isAbsolute8, join as join15, relative as relative9, resolve as resolve12 } from "node:path";
@@ -4116,6 +4116,144 @@ function retainedSourceExecutorEntry(entry, executorKind) {
4116
4116
  };
4117
4117
  }
4118
4118
 
4119
+ // src/amaster-runtime-daemon/current-run-contract.mjs
4120
+ import { createHash as createHash4 } from "node:crypto";
4121
+ var CONTRACT_VERSION = "mirrorx.current-run-contract.v1";
4122
+ var REQUIRED_ACTIONS = [
4123
+ "amaster.read_issue_delivery",
4124
+ "amaster.read_issue",
4125
+ "amaster.read_issue_document",
4126
+ "publish_delivery_manifest"
4127
+ ];
4128
+ var FORBIDDEN_ACTIONS = [
4129
+ "upsert_document",
4130
+ "upsert_document_revision",
4131
+ "create_interaction:request_confirmation:review",
4132
+ "update_parent:done"
4133
+ ];
4134
+ var TERMINAL_DISPOSITION = "end_after_successful_manifest_publication";
4135
+ var OFFSET_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;
4136
+ function exactKeys(value, expected) {
4137
+ const keys = Object.keys(asRecord(value)).sort();
4138
+ const sortedExpected = [...expected].sort();
4139
+ return keys.length === sortedExpected.length && keys.every((key, index) => key === sortedExpected[index]);
4140
+ }
4141
+ function exactStringArray(value, expected) {
4142
+ return Array.isArray(value) && value.length === expected.length && value.every((entry, index) => entry === expected[index]);
4143
+ }
4144
+ function canonicalJson(value) {
4145
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
4146
+ if (value === void 0) return "null";
4147
+ if (!value || typeof value !== "object") return JSON.stringify(value) ?? "null";
4148
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
4149
+ }
4150
+ function semanticHash(contract) {
4151
+ const { contractHash: _contractHash, compiledAt: _compiledAt, ...semantic } = contract;
4152
+ return `sha256:${createHash4("sha256").update(canonicalJson(semantic)).digest("hex")}`;
4153
+ }
4154
+ function validateBlockingGaps(value) {
4155
+ return Array.isArray(value) && value.length === 0;
4156
+ }
4157
+ function validateAuthorityRefs(value) {
4158
+ if (!Array.isArray(value) || value.length === 0 || value.length > 100) return false;
4159
+ if (value.some((ref) => typeof ref !== "string" || ref.trim().length === 0 || ref.length > 500)) {
4160
+ return false;
4161
+ }
4162
+ const canonical = [...new Set(value)].sort();
4163
+ return canonical.length === value.length && canonical.every((ref, index) => ref === value[index]);
4164
+ }
4165
+ function validateContract(value) {
4166
+ if (value === void 0 || value === null) return { kind: "missing" };
4167
+ const contract = asRecord(value);
4168
+ const authority = asRecord(contract.authority);
4169
+ const execution = asRecord(contract.execution);
4170
+ const errors = [];
4171
+ if (!exactKeys(contract, [
4172
+ "schemaVersion",
4173
+ "rolloutMode",
4174
+ "contractHash",
4175
+ "compiledAt",
4176
+ "authority",
4177
+ "execution"
4178
+ ])) errors.push("shape_invalid");
4179
+ if (contract.schemaVersion !== CONTRACT_VERSION) errors.push("schema_version_invalid");
4180
+ if (contract.rolloutMode !== "shadow") errors.push("rollout_mode_invalid");
4181
+ if (!/^sha256:[a-f0-9]{64}$/u.test(readString(contract.contractHash) ?? "")) errors.push("contract_hash_invalid");
4182
+ const compiledAt = readString(contract.compiledAt);
4183
+ if (!compiledAt || !OFFSET_DATETIME_PATTERN.test(compiledAt) || Number.isNaN(Date.parse(compiledAt))) {
4184
+ errors.push("compiled_at_invalid");
4185
+ }
4186
+ if (!exactKeys(authority, ["sourceRefs"]) || !validateAuthorityRefs(authority.sourceRefs)) {
4187
+ errors.push("authority_invalid");
4188
+ }
4189
+ if (!exactKeys(execution, [
4190
+ "mode",
4191
+ "requiredActions",
4192
+ "forbiddenActions",
4193
+ "terminalDisposition",
4194
+ "blockingGaps"
4195
+ ]) || execution.mode !== "manifest_refresh_only" || !exactStringArray(execution.requiredActions, REQUIRED_ACTIONS) || !exactStringArray(execution.forbiddenActions, FORBIDDEN_ACTIONS) || execution.terminalDisposition !== TERMINAL_DISPOSITION || !validateBlockingGaps(execution.blockingGaps)) {
4196
+ errors.push("execution_invalid");
4197
+ }
4198
+ if (errors.length === 0 && semanticHash(contract) !== contract.contractHash) {
4199
+ errors.push("contract_hash_mismatch");
4200
+ }
4201
+ return errors.length > 0 ? { kind: "invalid", errors: [...new Set(errors)] } : { kind: "valid", contract };
4202
+ }
4203
+ function legacyManifestRefreshOnly(context) {
4204
+ const readiness = asRecord(asRecord(context).paperclipDeliveryReadiness);
4205
+ const currentManifest = asRecord(readiness.currentManifest);
4206
+ const findings = (Array.isArray(readiness.findings) ? readiness.findings : []).map((entry) => asRecord(entry)).filter((entry) => readString(entry.code));
4207
+ const manifestRefs = [
4208
+ currentManifest.primaryRef,
4209
+ ...Array.isArray(currentManifest.supportingRefs) ? currentManifest.supportingRefs : []
4210
+ ].map((entry) => asRecord(entry));
4211
+ const documentRefIds = new Set(manifestRefs.filter((ref) => readString(ref.kind) === "document").map((ref) => readString(ref.refId)).filter(Boolean));
4212
+ return readString(readiness.mode) === "required" && Number.isInteger(currentManifest.revision) && readString(currentManifest.requirementRevision) === readString(readiness.requirementRevision) && findings.length > 0 && findings.every((entry) => readString(entry.code) === "deliverable_ref_stale" && documentRefIds.has(readString(entry.refId)));
4213
+ }
4214
+ function auditCurrentRunContractShadow(value, context) {
4215
+ const expected = legacyManifestRefreshOnly(context);
4216
+ const validation = validateContract(value);
4217
+ const base = {
4218
+ schemaVersion: "mirrorx.current-run-contract-shadow-audit.v1",
4219
+ expectedMode: expected ? "manifest_refresh_only" : "none"
4220
+ };
4221
+ if (validation.kind === "missing") {
4222
+ return {
4223
+ ...base,
4224
+ status: expected ? "missing" : "match",
4225
+ receivedMode: "none",
4226
+ contractHash: null,
4227
+ validationErrors: []
4228
+ };
4229
+ }
4230
+ if (validation.kind === "invalid") {
4231
+ return {
4232
+ ...base,
4233
+ status: "invalid",
4234
+ receivedMode: "invalid",
4235
+ contractHash: readString(asRecord(value).contractHash) ?? null,
4236
+ validationErrors: validation.errors
4237
+ };
4238
+ }
4239
+ return {
4240
+ ...base,
4241
+ status: expected ? "match" : "unexpected",
4242
+ receivedMode: "manifest_refresh_only",
4243
+ contractHash: validation.contract.contractHash,
4244
+ validationErrors: []
4245
+ };
4246
+ }
4247
+ function attachCurrentRunContractShadowAudit(compilation, value, context) {
4248
+ return {
4249
+ ...compilation,
4250
+ manifest: {
4251
+ ...asRecord(compilation).manifest,
4252
+ currentRunContractShadow: auditCurrentRunContractShadow(value, context)
4253
+ }
4254
+ };
4255
+ }
4256
+
4119
4257
  // src/amaster-runtime-daemon/task-context-policy.mjs
4120
4258
  var TASK_CONTEXT_MANIFEST_VERSION = "task-context-v1";
4121
4259
  function resolveTaskContextMemoryPolicy(context) {
@@ -4828,17 +4966,6 @@ Runtime Action continuation is unavailable: managed Pi MCP tool mode is not prox
4828
4966
  return `${heading}
4829
4967
  Runtime Action continuation is unavailable: executor kind does not support a governed Runtime Action continuation. Do not guess a tool call.`;
4830
4968
  }
4831
- function isManifestRefreshOnly(context) {
4832
- const readiness = asRecord(context.paperclipDeliveryReadiness);
4833
- const currentManifest = asRecord(readiness.currentManifest);
4834
- const findings = (Array.isArray(readiness.findings) ? readiness.findings : []).map((entry) => asRecord(entry)).filter((entry) => readString(entry.code));
4835
- const manifestRefs = [
4836
- currentManifest.primaryRef,
4837
- ...Array.isArray(currentManifest.supportingRefs) ? currentManifest.supportingRefs : []
4838
- ].map((entry) => asRecord(entry));
4839
- const documentRefIds = new Set(manifestRefs.filter((ref) => readString(ref.kind) === "document").map((ref) => readString(ref.refId)).filter(Boolean));
4840
- return readString(readiness.mode) === "required" && Number.isInteger(currentManifest.revision) && readString(currentManifest.requirementRevision) === readString(readiness.requirementRevision) && findings.length > 0 && findings.every((entry) => readString(entry.code) === "deliverable_ref_stale" && documentRefIds.has(readString(entry.refId)));
4841
- }
4842
4969
  function runtimeAuthorizationText(context, mode, { suppressOrdinaryCompletionContract = false } = {}) {
4843
4970
  const envelope = asRecord(context.authorizationEnvelope);
4844
4971
  const allowed = new Set(
@@ -4856,7 +4983,7 @@ function runtimeAuthorizationText(context, mode, { suppressOrdinaryCompletionCon
4856
4983
  const businessOutcome = asRecord(requirements.businessOutcome);
4857
4984
  const completionRole = readString(completion.role);
4858
4985
  const completionDeliverable = readString(completion.deliverable);
4859
- const manifestRefreshOnly = isManifestRefreshOnly(context);
4986
+ const manifestRefreshOnly = legacyManifestRefreshOnly(context);
4860
4987
  const firstDocumentCheckpoint = completionDeliverable === "document_or_artifact" ? manifestRefreshOnly ? "The current deliverable content already exists and this run is limited to refreshing stale immutable Manifest refs. Do not create or revise a document unless a fresh Delivery readiness read proves a content or acceptance gap beyond stale refs." : mode === "cold" ? "Before the first external browse, search, or research action, call upsert_document with a stable key. Create a checkpoint skeleton containing the acceptance criteria, a source table, and known unknowns; update the same document with each piece of verified evidence instead of waiting until broad research is complete. Immediately after upsert_document, call update_parent with status: in_progress and a concrete next action; complete both control-plane writes before the first external browse, search, or research action." : "Before the first external browse, search, or research action, read the existing stable-key document. Preserve all still-valid verified rows, source URLs, conclusions, and known unknowns; do not replace a populated document with a blank skeleton or less-informative fallback. Only when the document does not exist may you create a checkpoint skeleton. Then call update_parent with status: in_progress and a concrete next action before the first external browse, search, or research action. Update the same document with each piece of verified evidence." : "";
4861
4988
  const completionContract = !suppressOrdinaryCompletionContract && completionRole && completionDeliverable ? [
4862
4989
  "Before ending this run, persist durable progress through Runtime Actions and record one explicit task disposition. Browser and tool history alone are not durable progress.",
@@ -4936,7 +5063,7 @@ function runtimeDeliveryReadinessText(context, input) {
4936
5063
  })).filter((entry) => entry.code);
4937
5064
  const manifestRequirementRevision = readString(currentManifest.requirementRevision);
4938
5065
  const requirementRevision = readString(readiness.requirementRevision);
4939
- const manifestRefreshOnly = isManifestRefreshOnly(context);
5066
+ const manifestRefreshOnly = legacyManifestRefreshOnly(context);
4940
5067
  const refSummary = (value) => {
4941
5068
  const ref = asRecord(value);
4942
5069
  return {
@@ -5323,6 +5450,68 @@ ${resolvedDependencies.details.content}` : ""
5323
5450
  return { prompt, manifest };
5324
5451
  }
5325
5452
 
5453
+ // src/amaster-runtime-daemon/agent-instruction-delivery.mjs
5454
+ var AUTO_LOAD_EXECUTOR_KINDS = /* @__PURE__ */ new Set(["codex", "pi"]);
5455
+ function resolveAgentInstructionDelivery(executorKind, options = {}) {
5456
+ const normalizedExecutorKind = typeof executorKind === "string" && executorKind.trim() ? executorKind.trim().toLowerCase() : "unknown";
5457
+ const runnerKind = typeof options.runnerKind === "string" && options.runnerKind.trim() ? options.runnerKind.trim().toLowerCase() : "unknown";
5458
+ const materializedFiles = Array.isArray(options.materializedFiles) ? [...new Set(options.materializedFiles.filter((path) => typeof path === "string" && path.trim()))].sort() : [];
5459
+ const suppliedFiles = Array.isArray(options.suppliedFiles) ? [...new Set(options.suppliedFiles.filter((path) => typeof path === "string" && path.trim()))].sort() : materializedFiles;
5460
+ const executorSupportsAutoLoad = AUTO_LOAD_EXECUTOR_KINDS.has(normalizedExecutorKind);
5461
+ const instructionsSupplied = suppliedFiles.length > 0;
5462
+ const entryFileSupplied = suppliedFiles.includes("AGENTS.md");
5463
+ const entryFileMaterialized = materializedFiles.includes("AGENTS.md");
5464
+ const autoLoaded = executorSupportsAutoLoad && entryFileSupplied && entryFileMaterialized;
5465
+ return {
5466
+ version: 1,
5467
+ runnerKind,
5468
+ executorKind: normalizedExecutorKind,
5469
+ mode: autoLoaded ? "executor_auto_load" : instructionsSupplied ? "explicit_read_required" : "not_applicable",
5470
+ channel: autoLoaded ? "workspace_project_instructions" : instructionsSupplied ? "user_prompt_pointer" : null,
5471
+ attestedBy: "runtime_executor_contract",
5472
+ reason: autoLoaded ? "executor_contract_and_materialization_attested" : !instructionsSupplied ? "agent_instructions_not_supplied" : !entryFileSupplied ? "agents_entry_not_supplied" : executorSupportsAutoLoad ? "agents_entry_not_materialized" : "executor_auto_load_not_supported",
5473
+ entryFileSupplied,
5474
+ entryFileMaterialized,
5475
+ materializedFileCount: materializedFiles.length,
5476
+ materializedFiles
5477
+ };
5478
+ }
5479
+ function agentInstructionFileNames(bundle) {
5480
+ const files = bundle && typeof bundle === "object" && bundle.files && typeof bundle.files === "object" ? bundle.files : {};
5481
+ return Object.keys(files).filter((path) => typeof files[path] === "string" && files[path].trim()).sort((left, right) => left === right ? 0 : left === "AGENTS.md" ? -1 : right === "AGENTS.md" ? 1 : left.localeCompare(right));
5482
+ }
5483
+ function renderAgentInstructionsBundle(bundle, delivery) {
5484
+ const names = agentInstructionFileNames(bundle);
5485
+ if (names.length === 0) return "";
5486
+ const resolvedDelivery = delivery ?? resolveAgentInstructionDelivery("unknown");
5487
+ const materialized = `Current agent instructions are materialized in the execution workspace as: ${names.map((name) => `./${name}`).join(", ")}.`;
5488
+ if (!names.includes("AGENTS.md")) {
5489
+ return [
5490
+ materialized,
5491
+ "No ./AGENTS.md entry is present. Read the listed instruction files before acting and follow them for the whole run."
5492
+ ].join("\n");
5493
+ }
5494
+ if (resolvedDelivery.mode === "executor_auto_load") {
5495
+ return [
5496
+ materialized,
5497
+ "This executor has already loaded ./AGENTS.md through its project-instruction channel. Follow it for the whole run; do not read it again merely to initialize. Read sibling instruction files only when ./AGENTS.md references them or the current task requires them."
5498
+ ].join("\n");
5499
+ }
5500
+ return [
5501
+ materialized,
5502
+ "Automatic project-instruction loading is not attested for this executor. Read ./AGENTS.md first and follow it (including any sibling files it references) for the whole run."
5503
+ ].join("\n");
5504
+ }
5505
+ function agentInstructionDeliveryAudit(bundle, delivery) {
5506
+ const files = agentInstructionFileNames(bundle);
5507
+ return {
5508
+ ...delivery ?? resolveAgentInstructionDelivery("unknown"),
5509
+ entryFile: files.includes("AGENTS.md") ? "AGENTS.md" : null,
5510
+ suppliedFileCount: files.length,
5511
+ suppliedFiles: files
5512
+ };
5513
+ }
5514
+
5326
5515
  // src/amaster-runtime-daemon/config-state.mjs
5327
5516
  import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync5, renameSync as renameSync3, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "node:fs";
5328
5517
  import { homedir as homedir2, hostname } from "node:os";
@@ -7202,7 +7391,7 @@ var postJsonWithRetry = postRuntimeConnectorJsonWithRetry;
7202
7391
  var bestEffortPostJson = bestEffortPostRuntimeConnectorJson;
7203
7392
 
7204
7393
  // src/amaster-runtime-daemon/runtime-artifact-upload.mjs
7205
- import { createHash as createHash4 } from "node:crypto";
7394
+ import { createHash as createHash5 } from "node:crypto";
7206
7395
  import { closeSync, constants, fstatSync, lstatSync as lstatSync3, openSync, readFileSync as readFileSync6, realpathSync as realpathSync3 } from "node:fs";
7207
7396
  import { isAbsolute as isAbsolute3, relative as relative3, resolve as resolve3 } from "node:path";
7208
7397
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
@@ -7292,7 +7481,7 @@ function prepareRuntimeArtifactUploads(cwd, mcpToolResults) {
7292
7481
  `Runtime Artifact ${intentId}`,
7293
7482
  { expectedByteSize }
7294
7483
  );
7295
- const actualSha256 = createHash4("sha256").update(body).digest("hex");
7484
+ const actualSha256 = createHash5("sha256").update(body).digest("hex");
7296
7485
  if (body.length !== expectedByteSize || actualSha256 !== expectedSha256) {
7297
7486
  throw new Error(`Runtime Artifact ${intentId} bytes do not match the governed ownership manifest`);
7298
7487
  }
@@ -7309,7 +7498,7 @@ function prepareRuntimeArtifactUploads(cwd, mcpToolResults) {
7309
7498
  }
7310
7499
 
7311
7500
  // src/amaster-runtime-daemon/runtime-document-upload.mjs
7312
- import { createHash as createHash5 } from "node:crypto";
7501
+ import { createHash as createHash6 } from "node:crypto";
7313
7502
 
7314
7503
  // src/amaster-runtime-daemon/workspace-sensitive-path.mjs
7315
7504
  var SENSITIVE_PATH_SEGMENTS = /* @__PURE__ */ new Set([
@@ -7384,7 +7573,7 @@ function prepareRuntimeDocumentUploads(cwd, mcpToolResults) {
7384
7573
  maxByteSize: MAX_WORKSPACE_DOCUMENT_BYTES
7385
7574
  }
7386
7575
  );
7387
- const actualSha256 = createHash5("sha256").update(body).digest("hex");
7576
+ const actualSha256 = createHash6("sha256").update(body).digest("hex");
7388
7577
  if (body.length !== expectedByteSize || actualSha256 !== expectedSha256) {
7389
7578
  throw new Error(`Runtime Document ${callId} bytes do not match the governed ownership manifest`);
7390
7579
  }
@@ -7510,7 +7699,7 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
7510
7699
  }
7511
7700
 
7512
7701
  // src/amaster-runtime-daemon/workspace-guard.mjs
7513
- import { createHash as createHash6 } from "node:crypto";
7702
+ import { createHash as createHash7 } from "node:crypto";
7514
7703
  import { existsSync as existsSync7, mkdirSync as mkdirSync6, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs";
7515
7704
  import { basename as basename4, join as join8, isAbsolute as isAbsolute4, relative as relative4, resolve as resolve4 } from "node:path";
7516
7705
 
@@ -7636,7 +7825,7 @@ function resolveWorkspaceCwd(config, command) {
7636
7825
  return cwd;
7637
7826
  }
7638
7827
  function shortHash(value, length = 12) {
7639
- return createHash6("sha256").update(String(value)).digest("hex").slice(0, length);
7828
+ return createHash7("sha256").update(String(value)).digest("hex").slice(0, length);
7640
7829
  }
7641
7830
  function safeSegment(value, fallback) {
7642
7831
  const raw = String(value ?? "").trim();
@@ -8080,7 +8269,7 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
8080
8269
  }
8081
8270
 
8082
8271
  // src/amaster-runtime-daemon/pi-child-isolation.mjs
8083
- import { createHash as createHash7 } from "node:crypto";
8272
+ import { createHash as createHash8 } from "node:crypto";
8084
8273
  import {
8085
8274
  chmodSync as chmodSync3,
8086
8275
  chownSync as chownSync2,
@@ -8091,7 +8280,7 @@ import {
8091
8280
  import { resolve as resolve7, sep } from "node:path";
8092
8281
  var defaultFs = { chmodSync: chmodSync3, chownSync: chownSync2, lchownSync, lstatSync: lstatSync4, readdirSync: readdirSync6 };
8093
8282
  function defaultHashRunId(runId) {
8094
- return Number.parseInt(createHash7("sha256").update(runId).digest("hex").slice(0, 8), 16);
8283
+ return Number.parseInt(createHash8("sha256").update(runId).digest("hex").slice(0, 8), 16);
8095
8284
  }
8096
8285
  function positiveInteger(value, label) {
8097
8286
  if (!Number.isSafeInteger(value) || value <= 0) {
@@ -8215,7 +8404,7 @@ function preparePiChildIsolation(input) {
8215
8404
  }
8216
8405
 
8217
8406
  // src/amaster-runtime-daemon/pi-company-memory.mjs
8218
- import { createHash as createHash8 } from "node:crypto";
8407
+ import { createHash as createHash9 } from "node:crypto";
8219
8408
  import {
8220
8409
  chmodSync as chmodSync4,
8221
8410
  chownSync as chownSync3,
@@ -8301,7 +8490,7 @@ function safeCompanyPiHomeSegment(companyId) {
8301
8490
  const raw = requiredString3(companyId, "companyId");
8302
8491
  if (/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/.test(raw)) return raw;
8303
8492
  const normalized = raw.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "").slice(0, 80);
8304
- const hash = createHash8("sha256").update(raw).digest("hex").slice(0, 12);
8493
+ const hash = createHash9("sha256").update(raw).digest("hex").slice(0, 12);
8305
8494
  return normalized ? `${normalized}-${hash}` : `company-${hash}`;
8306
8495
  }
8307
8496
  function ensureMemoryRoot(root, fs) {
@@ -8340,7 +8529,7 @@ function allocateCompanyGid(root, companyId, input, fs) {
8340
8529
  if (groups[companyId]) return groups[companyId];
8341
8530
  const used = new Set(Object.values(groups));
8342
8531
  const initialOffset = Number.parseInt(
8343
- createHash8("sha256").update(companyId).digest("hex").slice(0, 12),
8532
+ createHash9("sha256").update(companyId).digest("hex").slice(0, 12),
8344
8533
  16
8345
8534
  ) % gidSpan;
8346
8535
  let gid = null;
@@ -8442,7 +8631,7 @@ function prepareCompanyPiMemory(input, fs = defaultFs2) {
8442
8631
  }
8443
8632
 
8444
8633
  // src/amaster-runtime-daemon/pi-trusted-runtime-profile.mjs
8445
- import { createHash as createHash9 } from "node:crypto";
8634
+ import { createHash as createHash10 } from "node:crypto";
8446
8635
  import {
8447
8636
  chmodSync as chmodSync5,
8448
8637
  copyFileSync as copyFileSync2,
@@ -8482,7 +8671,7 @@ function sha256File(path, label) {
8482
8671
  if (!stat.isFile() || stat.isSymbolicLink()) {
8483
8672
  throw new Error(`pi_trusted_runtime_source_unsafe:${label}`);
8484
8673
  }
8485
- return createHash9("sha256").update(readFileSync9(path)).digest("hex");
8674
+ return createHash10("sha256").update(readFileSync9(path)).digest("hex");
8486
8675
  }
8487
8676
  function verifyDeclaredFiles(manifest, root, label, ignoredPaths = [], enforceComplete = true) {
8488
8677
  if (!Array.isArray(manifest.files) || manifest.files.length === 0) {
@@ -8750,12 +8939,12 @@ function materializeTrustedPiRuntimeProfile(input) {
8750
8939
  // bundle skills were enabled. Absent profile => main skills only.
8751
8940
  ...skillProfile ? {
8752
8941
  skillProfile,
8753
- enabledSkillsDigest: createHash9("sha256").update(JSON.stringify(enabledSkills)).digest("hex")
8942
+ enabledSkillsDigest: createHash10("sha256").update(JSON.stringify(enabledSkills)).digest("hex")
8754
8943
  } : {}
8755
8944
  };
8756
8945
  return {
8757
8946
  facts,
8758
- attestationId: createHash9("sha256").update(JSON.stringify(facts)).digest("hex")
8947
+ attestationId: createHash10("sha256").update(JSON.stringify(facts)).digest("hex")
8759
8948
  };
8760
8949
  }
8761
8950
  function assertAuditArgsRedacted(value) {
@@ -8951,7 +9140,7 @@ function verifyTrustedPiRuntimeAssertion(input) {
8951
9140
  if (hasSourceAssertion) {
8952
9141
  const exactTools = Array.isArray(record7(sourceProfile.tools).exactAllowlist) ? record7(sourceProfile.tools).exactAllowlist : [];
8953
9142
  const exactActions = Array.isArray(record7(sourceProfile.actions).exactAllowlist) ? record7(sourceProfile.actions).exactAllowlist : [];
8954
- const profileHash = createHash9("sha256").update(JSON.stringify(sourceProfile)).digest("hex");
9143
+ const profileHash = createHash10("sha256").update(JSON.stringify(sourceProfile)).digest("hex");
8955
9144
  if (assertion.unknownToolMode !== "deny" || maxCalls !== 0 || sourceAssertion.profileVersion !== sourceProfile.purpose || sourceAssertion.profileHash !== profileHash || sourceAssertion.retentionVersion !== sourceProfile.retention || JSON.stringify(sourceAssertion.exactTools) !== JSON.stringify(exactTools) || JSON.stringify(sourceAssertion.exactActions) !== JSON.stringify(exactActions) || sourceAssertion.sourceId !== sourceProfile.sourceId || sourceAssertion.sourceRevisionId !== sourceProfile.sourceRevisionId || sourceAssertion.sourceRevision !== sourceProfile.sourceRevision || sourceAssertion.attemptId !== sourceProfile.attemptId || sourceAssertion.epoch !== sourceProfile.epoch) {
8956
9145
  throw new Error("pi_trusted_runtime_assertion_binding_mismatch:sourceAcquisition");
8957
9146
  }
@@ -8980,7 +9169,7 @@ function verifyTrustedPiRuntimeAssertion(input) {
8980
9169
 
8981
9170
  // src/amaster-runtime-daemon/workspace-status.mjs
8982
9171
  import { spawnSync as spawnSync4 } from "node:child_process";
8983
- import { createHash as createHash10 } from "node:crypto";
9172
+ import { createHash as createHash11 } from "node:crypto";
8984
9173
  import { existsSync as existsSync12, readdirSync as readdirSync8, readFileSync as readFileSync10, statSync as statSync7 } from "node:fs";
8985
9174
  import { basename as basename5, extname, isAbsolute as isAbsolute7, join as join13, relative as relative7, resolve as resolve10 } from "node:path";
8986
9175
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
@@ -9051,7 +9240,7 @@ function sanitizeTrackedChange(line) {
9051
9240
  return isSafeRelativePath(path) ? line : null;
9052
9241
  }
9053
9242
  function sha256File2(filePath) {
9054
- return createHash10("sha256").update(readFileSync10(filePath)).digest("hex");
9243
+ return createHash11("sha256").update(readFileSync10(filePath)).digest("hex");
9055
9244
  }
9056
9245
  function artifactHashCacheKey(relativePath, stat) {
9057
9246
  return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
@@ -9252,7 +9441,7 @@ function readWorkspaceStatus(cwd, opts = {}) {
9252
9441
  }
9253
9442
 
9254
9443
  // src/amaster-runtime-daemon/pi-browser-session-adapter.mjs
9255
- import { createHash as createHash11 } from "node:crypto";
9444
+ import { createHash as createHash12 } from "node:crypto";
9256
9445
  import { spawn, spawnSync as spawnSync5 } from "node:child_process";
9257
9446
  import { existsSync as existsSync13 } from "node:fs";
9258
9447
  import {
@@ -9375,7 +9564,7 @@ function fail(code) {
9375
9564
  throw Object.assign(new Error(code), { code });
9376
9565
  }
9377
9566
  function profileName(identity2) {
9378
- return createHash11("sha256").update(`${identity2.companyId}\0${identity2.bindingId}\0${identity2.localOpaqueRef}`).digest("hex");
9567
+ return createHash12("sha256").update(`${identity2.companyId}\0${identity2.bindingId}\0${identity2.localOpaqueRef}`).digest("hex");
9379
9568
  }
9380
9569
  function expectedMarker(identity2) {
9381
9570
  return {
@@ -9774,7 +9963,7 @@ async function executeBrowserSessionCommand(command, dependencies = {}) {
9774
9963
  }
9775
9964
 
9776
9965
  // src/amaster-runtime-daemon/source-acquisition-invocation.mjs
9777
- import { createHash as createHash12 } from "node:crypto";
9966
+ import { createHash as createHash13 } from "node:crypto";
9778
9967
  var SOURCE_ACQUISITION_PUBLIC_TOOLS = Object.freeze([
9779
9968
  "source_open",
9780
9969
  "source_snapshot",
@@ -9811,7 +10000,7 @@ function serializeSourceAcquisitionProfile(profile) {
9811
10000
  const input = Buffer.from(JSON.stringify(profile), "utf8");
9812
10001
  return {
9813
10002
  input,
9814
- sha256: createHash12("sha256").update(input).digest("hex")
10003
+ sha256: createHash13("sha256").update(input).digest("hex")
9815
10004
  };
9816
10005
  }
9817
10006
  function sourceAcquisitionManagedInputs(options) {
@@ -9847,7 +10036,7 @@ function assertSourceAcquisitionRuntimeAuthority({
9847
10036
  }
9848
10037
 
9849
10038
  // src/amaster-runtime-daemon.mjs
9850
- var CONNECTOR_VERSION = "0.1.1-beta.20";
10039
+ var CONNECTOR_VERSION = "0.1.1-beta.21";
9851
10040
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
9852
10041
  var SOURCE_ACQUISITION_CAPABILITY = "source_acquisition_v1";
9853
10042
  var SOURCE_ACQUISITION_PROFILE_VERSION = "source_acquisition_v1";
@@ -11123,15 +11312,6 @@ ${body}${truncatedNote}`;
11123
11312
  function renderTaskMarkdown(context) {
11124
11313
  return readString(context.paperclipTaskMarkdown);
11125
11314
  }
11126
- function renderAgentInstructionsBundle(bundle) {
11127
- const files = asRecord(asRecord(bundle).files);
11128
- const names = Object.keys(files).filter((path) => readString(files[path])).sort((left, right) => left === right ? 0 : left === "AGENTS.md" ? -1 : right === "AGENTS.md" ? 1 : left.localeCompare(right));
11129
- if (names.length === 0) return "";
11130
- return [
11131
- `Current agent instructions are materialized in the execution workspace as: ${names.map((name) => `./${name}`).join(", ")}.`,
11132
- "They are authoritative for this run and are not inlined here. Read ./AGENTS.md first and follow it (including any sibling files it references) for the whole run."
11133
- ].join("\n");
11134
- }
11135
11315
  function commandRuntimeAuth(command) {
11136
11316
  const topLevel = asRecord(command.runtimeAuth);
11137
11317
  if (readString(topLevel.apiUrl) && readString(topLevel.apiKey)) return topLevel;
@@ -11190,7 +11370,7 @@ function sourceAcquisitionRuntimeProfile(config, command) {
11190
11370
  if (!companyId || !bindingId || !/^profile_[a-z0-9]{16,64}$/i.test(localOpaqueRef ?? "")) {
11191
11371
  throw new Error("source_acquisition_profile_invalid");
11192
11372
  }
11193
- const profileName2 = createHash13("sha256").update(`${companyId}\0${bindingId}\0${localOpaqueRef}`).digest("hex");
11373
+ const profileName2 = createHash14("sha256").update(`${companyId}\0${bindingId}\0${localOpaqueRef}`).digest("hex");
11194
11374
  const stateRoot = resolve12(config.browserSessionStateRoot);
11195
11375
  const userDataDir = resolve12(stateRoot, profileName2);
11196
11376
  if (!pathWithin2(userDataDir, stateRoot)) throw new Error("source_acquisition_browser_profile_invalid");
@@ -11354,7 +11534,13 @@ function buildCommandPrompt(command, workspace, materializedAttachments = [], op
11354
11534
  }
11355
11535
  );
11356
11536
  const taskMarkdown = renderTaskMarkdown(context);
11357
- const agentInstructions = renderAgentInstructionsBundle(asRecord(payload.agentInstructionsBundle));
11537
+ const agentInstructionsBundle = asRecord(payload.agentInstructionsBundle);
11538
+ const agentInstructionDelivery = resolveAgentInstructionDelivery(options.executorKind, {
11539
+ runnerKind: options.runnerKind,
11540
+ materializedFiles: options.materializedAgentInstructionFiles,
11541
+ suppliedFiles: agentInstructionFileNames(agentInstructionsBundle)
11542
+ });
11543
+ const agentInstructions = renderAgentInstructionsBundle(agentInstructionsBundle, agentInstructionDelivery);
11358
11544
  const runtimeAuth = commandRuntimeAuth(command);
11359
11545
  const hasGovernedMcp = Object.keys(asRecord(runtimeAuth.governedMcp)).length > 0;
11360
11546
  const attachmentsText = materializedAttachments.length > 0 ? [
@@ -11374,7 +11560,7 @@ function buildCommandPrompt(command, workspace, materializedAttachments = [], op
11374
11560
  return `- ${details}`;
11375
11561
  })
11376
11562
  ].join("\n") : "";
11377
- return compileCommandPromptWithManifest({
11563
+ const compilation = compileCommandPromptWithManifest({
11378
11564
  commandId: command.commandId,
11379
11565
  runId: commandRunId(command),
11380
11566
  issueId: commandIssueId(command),
@@ -11399,6 +11585,21 @@ function buildCommandPrompt(command, workspace, materializedAttachments = [], op
11399
11585
  treePath: wikiTreePathForCommand(command, options.workspaceBindings)
11400
11586
  }
11401
11587
  });
11588
+ const auditedCompilation = attachCurrentRunContractShadowAudit(
11589
+ compilation,
11590
+ payload.currentRunContract,
11591
+ context
11592
+ );
11593
+ return {
11594
+ ...auditedCompilation,
11595
+ manifest: {
11596
+ ...auditedCompilation.manifest,
11597
+ agentInstructionDelivery: agentInstructionDeliveryAudit(
11598
+ agentInstructionsBundle,
11599
+ agentInstructionDelivery
11600
+ )
11601
+ }
11602
+ };
11402
11603
  }
11403
11604
  function companyPiHomeRoot(baseEnv) {
11404
11605
  const explicitRoot = readString(baseEnv.AMASTER_COMPANY_PI_HOME_ROOT);
@@ -14001,7 +14202,7 @@ async function materializeIssueAttachments(config, command, workspace) {
14001
14202
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
14002
14203
  writeFileSync9(targetPath, body);
14003
14204
  const attachmentId = readString(attachment.id);
14004
- const actualSha256 = createHash13("sha256").update(body).digest("hex");
14205
+ const actualSha256 = createHash14("sha256").update(body).digest("hex");
14005
14206
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
14006
14207
  const lineage = selectAttachmentLineage(lineageCandidates, actualSha256);
14007
14208
  if (lineageCandidates.length > 0 && !lineage) {
@@ -14093,7 +14294,7 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
14093
14294
  throw new Error(`artifact_input_manifest_invalid: entry ${index} contentPath does not match attachmentId`);
14094
14295
  }
14095
14296
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
14096
- const actualSha256 = createHash13("sha256").update(body).digest("hex");
14297
+ const actualSha256 = createHash14("sha256").update(body).digest("hex");
14097
14298
  if (body.byteLength !== byteSize || actualSha256 !== sha256) {
14098
14299
  throw new Error(
14099
14300
  `artifact_input_integrity_mismatch: workProductId=${workProductId} expectedBytes=${byteSize} actualBytes=${body.byteLength} expectedSha256=${sha256} actualSha256=${actualSha256}`
@@ -14163,7 +14364,7 @@ function safeCheckpointRelativePath(rawPath) {
14163
14364
  return normalized;
14164
14365
  }
14165
14366
  function hashFileSha256(filePath) {
14166
- return createHash13("sha256").update(readFileSync11(filePath)).digest("hex");
14367
+ return createHash14("sha256").update(readFileSync11(filePath)).digest("hex");
14167
14368
  }
14168
14369
  async function materializeIssueCheckpoint(config, command, workspace) {
14169
14370
  const checkpointDir = issueCheckpointDir(workspace);
@@ -14332,8 +14533,9 @@ async function executeRunCommand(config, command) {
14332
14533
  asRecord(asRecord(command.payload).contextSnapshot)
14333
14534
  );
14334
14535
  const cwd = workspace.cwd;
14536
+ let materializedAgentInstructions = [];
14335
14537
  try {
14336
- await materializeAgentInstructionsBundle(config, command, workspace);
14538
+ materializedAgentInstructions = await materializeAgentInstructionsBundle(config, command, workspace);
14337
14539
  } catch (err) {
14338
14540
  await ingestLog(config, command, "system", "warn", `Failed to materialize agent instruction files: ${err instanceof Error ? err.message : String(err)}`, {
14339
14541
  error: err instanceof Error ? err.message : String(err)
@@ -14351,7 +14553,9 @@ async function executeRunCommand(config, command) {
14351
14553
  }
14352
14554
  await ingestWorkspaceStatus(config, command, cwd);
14353
14555
  const promptCompilation = buildCommandPrompt(command, workspace, materializedAttachments, {
14556
+ runnerKind: config.runnerKind,
14354
14557
  executorKind: executor.kind,
14558
+ materializedAgentInstructionFiles: materializedAgentInstructions.map((entry) => entry.path),
14355
14559
  managedMcpToolMode: executor.kind === "pi" && Object.keys(governedMcp).length > 0 ? readString(governedMcp.mcpToolMode) ?? MANAGED_PI_MCP_TOOL_MODE : null,
14356
14560
  managedMcpToolCatalog: asRecord(governedMcp.toolCatalog),
14357
14561
  artifactVerifierCommands: config.artifactVerifierCommands,
@@ -14606,6 +14810,12 @@ async function executeRunCommand(config, command) {
14606
14810
  presentationKind: "context_manifest",
14607
14811
  contextManifest
14608
14812
  });
14813
+ if (contextManifest.currentRunContractShadow.status !== "match") {
14814
+ await ingestLog(config, command, "system", "warn", "Current Run Contract shadow comparison did not match the legacy runtime inference", {
14815
+ presentationKind: "current_run_contract_shadow_audit",
14816
+ currentRunContractShadow: contextManifest.currentRunContractShadow
14817
+ });
14818
+ }
14609
14819
  await ackCommand(config, command, "spawned");
14610
14820
  await ingestLog(config, command, "system", "info", `Starting ${executor.kind} executor`, {
14611
14821
  executorKind: executor.kind,
@@ -14889,10 +15099,11 @@ async function executeRunCommand(config, command) {
14889
15099
  const sourceErrorCode = sourceAcquisition ? execution.timedOut ? "source_acquisition_timeout" : cancelled ? "source_acquisition_cancelled" : hasOutputFlood ? "source_acquisition_output_flood" : hasMemoryLimit ? "source_acquisition_memory_limit" : execution.spawnError ? "source_acquisition_executor_unavailable" : succeeded ? null : "source_acquisition_executor_failed" : null;
14890
15100
  const error = sourceAcquisition ? sourceErrorCode : unsafeError;
14891
15101
  const costUsage = parsedCostUsage(parsed.usage);
15102
+ const cleanPiTerminalOutputStop = succeeded && completionOutputStopped && execution.completionOutputType === "agent_end" && parsed.terminalEventType === "agent_end" && Number.isInteger(parsed.terminalEventIndex);
14892
15103
  const executorOutcome = {
14893
- status: cancelled ? "cancelled" : execution.timedOut ? "timed_out" : execution.exitCode === 0 && execution.signal === null ? "completed" : "failed",
14894
- exitCode: execution.exitCode,
14895
- signal: execution.signal,
15104
+ status: cancelled ? "cancelled" : execution.timedOut ? "timed_out" : cleanPiTerminalOutputStop || execution.exitCode === 0 && execution.signal === null ? "completed" : "failed",
15105
+ exitCode: cleanPiTerminalOutputStop ? 0 : execution.exitCode,
15106
+ signal: cleanPiTerminalOutputStop ? null : execution.signal,
14896
15107
  terminalEvent: ["agent_end", "turn_end"].includes(readString(parsed.terminalEventType) ?? "") ? readString(parsed.terminalEventType) : null,
14897
15108
  terminalEventIndex: Number.isInteger(parsed.terminalEventIndex) ? parsed.terminalEventIndex : null
14898
15109
  };
@@ -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.20";
9
+ const CONNECTOR_VERSION = "0.1.1-beta.21";
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.20",
3
+ "version": "0.1.1-beta.21",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",