@amaster.ai/employee-runtime-connector 0.1.1-beta.155 → 0.1.1-beta.157

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.
@@ -4121,7 +4121,13 @@ var source_acquisition_compatibility_default = {
4121
4121
  "source_acquisition_prompt_authority_invalid",
4122
4122
  "source_acquisition_direct_tools_unavailable",
4123
4123
  "source_acquisition_profile_canonicalization_failed",
4124
- "source_acquisition_governed_profile_required"
4124
+ "source_acquisition_governed_profile_required",
4125
+ "context_output_reserve_exceeds_model_limit",
4126
+ "model_context_attestation_unavailable",
4127
+ "model_context_fixed_inputs_exceed_budget",
4128
+ "native_session_history_attestation_invalid",
4129
+ "native_session_history_attestation_unavailable",
4130
+ "native_session_history_exceeds_measurement_limit"
4125
4131
  ],
4126
4132
  reasonCodes: [
4127
4133
  "source_profile_setup_failed",
@@ -8370,7 +8376,8 @@ var ISSUE_RECOVERY_ACTION_KINDS = [
8370
8376
  "workspace_validation",
8371
8377
  "active_run_watchdog",
8372
8378
  "issue_graph_liveness",
8373
- "finalization_operator"
8379
+ "finalization_operator",
8380
+ "initialization_no_progress"
8374
8381
  ];
8375
8382
  var ISSUE_PROGRESS_FINDING_CODES = [
8376
8383
  "terminal",
@@ -10476,11 +10483,33 @@ var requestConfirmationResultSchema = external_exports.object({
10476
10483
  "accepted",
10477
10484
  "changes_requested",
10478
10485
  "rejected",
10486
+ "deferred",
10479
10487
  "superseded_by_comment",
10480
10488
  "superseded_by_confirmation",
10481
10489
  "stale_target"
10482
10490
  ]),
10483
10491
  reason: external_exports.string().trim().max(4e3).nullable().optional(),
10492
+ decision: external_exports.enum([
10493
+ "confirm_open",
10494
+ "mark_not_applicable",
10495
+ "confirm_observed_effect",
10496
+ "not_observed",
10497
+ "attribute_to_criterion",
10498
+ "not_goal_effect",
10499
+ "correct_facts",
10500
+ "defer"
10501
+ ]).nullable().optional(),
10502
+ evaluationDecision: external_exports.enum([
10503
+ "satisfied",
10504
+ "waiting_for_observation",
10505
+ "unsupported",
10506
+ "no_action",
10507
+ "deferred"
10508
+ ]).nullable().optional(),
10509
+ remindAt: external_exports.string().datetime({ offset: true }).nullable().optional(),
10510
+ idempotencyKey: external_exports.string().trim().min(1).max(200).nullable().optional(),
10511
+ resultingContractId: external_exports.string().uuid().nullable().optional(),
10512
+ resultingAuthorityRevision: external_exports.number().int().positive().nullable().optional(),
10484
10513
  supplementalComment: external_exports.string().trim().min(1).max(4e3).nullable().optional(),
10485
10514
  commentId: external_exports.string().uuid().nullable().optional(),
10486
10515
  supersededByInteractionId: external_exports.string().uuid().nullable().optional(),
@@ -11181,6 +11210,22 @@ var issueDeliveryAcceptanceGovernanceFindingSchema = external_exports.object({
11181
11210
  code: external_exports.literal("business_outcome_acceptance_policy_mismatch"),
11182
11211
  message: external_exports.string().min(1)
11183
11212
  }).strict();
11213
+ var terminalProducerBlockingRefSchema = external_exports.object({
11214
+ kind: external_exports.enum(["action_call", "artifact_intent", "tool_invocation"]),
11215
+ id: uuidSchema3,
11216
+ status: external_exports.string().min(1),
11217
+ code: external_exports.string().min(1).nullable()
11218
+ }).strict();
11219
+ var terminalProducerCleanlinessSchema = external_exports.object({
11220
+ clean: external_exports.boolean(),
11221
+ reasonCode: external_exports.enum([
11222
+ "terminal_producer_action_rejected",
11223
+ "terminal_producer_effect_pending",
11224
+ "terminal_producer_effect_unknown"
11225
+ ]).nullable(),
11226
+ diagnosticCode: external_exports.literal("terminal_producer_correlation_unknown").nullable(),
11227
+ blockingRefs: external_exports.array(terminalProducerBlockingRefSchema)
11228
+ }).strict();
11184
11229
  var issueDeliveryColdStartFactCoverageContextSchema = external_exports.object({
11185
11230
  worksetId: uuidSchema3,
11186
11231
  worksetItemId: uuidSchema3,
@@ -11206,13 +11251,22 @@ var issueDeliveryAcceptanceReadModelSchema = external_exports.object({
11206
11251
  outcome: external_exports.object({
11207
11252
  current: runtimeBusinessOutcomeReceiptSchema.nullable(),
11208
11253
  latestAcceptance: runtimeBusinessOutcomeAcceptanceRecordSchema.nullable(),
11209
- acceptanceIsCurrent: external_exports.boolean()
11254
+ acceptanceIsCurrent: external_exports.boolean(),
11255
+ terminalProducerCleanliness: terminalProducerCleanlinessSchema.nullable().optional()
11210
11256
  }).strict(),
11211
11257
  pendingInteractions: external_exports.array(issueDeliveryAcceptancePendingInteractionSchema),
11212
11258
  forceDone: issueForceDoneEvidenceSchema.nullable(),
11213
11259
  nextOwner: issueDeliveryAcceptanceNextOwnerSchema,
11214
11260
  coldStartFactCoverage: issueDeliveryColdStartFactCoverageContextSchema.nullable().default(null)
11215
11261
  }).strict();
11262
+ var issueDeliveryAcceptanceReconciliationResponseSchema = external_exports.object({
11263
+ result: external_exports.object({
11264
+ outcome: external_exports.enum(["created", "replayed", "not_eligible", "missing_issue"]),
11265
+ interactionId: uuidSchema3.nullable(),
11266
+ reason: external_exports.string().nullable()
11267
+ }).strict(),
11268
+ deliveryAcceptance: issueDeliveryAcceptanceReadModelSchema
11269
+ }).strict();
11216
11270
 
11217
11271
  // ../shared/src/operating-accounting.ts
11218
11272
  var OPERATING_IDENTITY_MAPPING_VERSION = "operating-identity-v1";
@@ -11313,6 +11367,11 @@ var operatingAccountingReadModelSchema = external_exports.object({
11313
11367
  var GOAL_GAP_METRIC_KINDS = ["count", "amount", "ratio", "boolean_milestone"];
11314
11368
  var GOAL_GAP_STATUSES = ["open", "satisfied", "invalidated", "unknown"];
11315
11369
  var GOAL_GAP_PROJECTOR_MODES = ["off", "shadow", "enforce"];
11370
+ var GOAL_GAP_EVALUATION_TYPES = [
11371
+ "deliverable_milestone",
11372
+ "observed_business_state",
11373
+ "human_judgment"
11374
+ ];
11316
11375
  var GOAL_GAP_PROJECTOR_DECISIONS = [
11317
11376
  "disabled",
11318
11377
  "shadow",
@@ -11378,6 +11437,41 @@ var goalGapAcceptanceContractSchema = external_exports.discriminatedUnion("verdi
11378
11437
  acceptanceAuthority: external_exports.object({ kind: external_exports.literal("company_board") }).strict()
11379
11438
  }).strict()
11380
11439
  ]);
11440
+ var goalGapEvaluationContractSchema = external_exports.object({
11441
+ schemaVersion: external_exports.literal("goal-gap-evaluation-v1"),
11442
+ criterionIndex: external_exports.number().int().min(0).max(9),
11443
+ evaluationType: external_exports.enum(GOAL_GAP_EVALUATION_TYPES),
11444
+ machineVerifiable: external_exports.boolean(),
11445
+ businessSubjectScope: boundedRecordSchema,
11446
+ targetCondition: goalGapTargetConditionSchema,
11447
+ window: boundedRecordSchema,
11448
+ observationPolicy: external_exports.object({
11449
+ kind: external_exports.enum([
11450
+ "accepted_causal_delivery",
11451
+ "independent_readback",
11452
+ "board_or_independent_readback",
11453
+ "board_judgment"
11454
+ ])
11455
+ }).strict(),
11456
+ compilerRevision: external_exports.string().min(1).max(120),
11457
+ evaluationContractHash: sha256Schema4,
11458
+ targetHash: sha256Schema4
11459
+ }).strict().superRefine((value, ctx) => {
11460
+ if (value.evaluationType === "human_judgment" && value.machineVerifiable) {
11461
+ ctx.addIssue({
11462
+ code: external_exports.ZodIssueCode.custom,
11463
+ path: ["machineVerifiable"],
11464
+ message: "Human judgment cannot be marked machine-verifiable"
11465
+ });
11466
+ }
11467
+ if (value.evaluationType !== "human_judgment" && !value.machineVerifiable) {
11468
+ ctx.addIssue({
11469
+ code: external_exports.ZodIssueCode.custom,
11470
+ path: ["machineVerifiable"],
11471
+ message: "Automatic evaluation requires a machine-verifiable target"
11472
+ });
11473
+ }
11474
+ });
11381
11475
  var deterministicGoalGapAcceptanceContract = {
11382
11476
  verdictRequirement: "deterministic_evidence",
11383
11477
  acceptanceAuthority: null
@@ -11391,7 +11485,8 @@ var goalGapDefinitionSchema = external_exports.object({
11391
11485
  window: boundedRecordSchema,
11392
11486
  currentObservationRef: goalGapObservationRefSchema.nullable(),
11393
11487
  status: external_exports.enum(GOAL_GAP_STATUSES),
11394
- acceptanceContract: goalGapAcceptanceContractSchema.default(deterministicGoalGapAcceptanceContract)
11488
+ acceptanceContract: goalGapAcceptanceContractSchema.default(deterministicGoalGapAcceptanceContract),
11489
+ evaluationContract: goalGapEvaluationContractSchema.nullable().optional().default(null)
11395
11490
  }).strict().superRefine((value, ctx) => {
11396
11491
  const targetKind = value.targetCondition.kind;
11397
11492
  if (targetKind !== value.metricOrStateKind) {
@@ -11401,10 +11496,64 @@ var goalGapDefinitionSchema = external_exports.object({
11401
11496
  ctx.addIssue({ code: "custom", path: ["currentObservationRef"], message: "A determinate status requires an observation ref" });
11402
11497
  }
11403
11498
  });
11499
+ var boardGoalGapSourceRefSchema = external_exports.object({
11500
+ kind: external_exports.string().trim().min(1).max(80),
11501
+ id: external_exports.string().trim().min(1).max(240),
11502
+ revision: external_exports.string().trim().min(1).max(240)
11503
+ }).strict();
11504
+ var boardGoalGapObservationBaseSchema = external_exports.object({
11505
+ expectedAuthorityRevision: external_exports.number().int().positive(),
11506
+ expectedContractId: external_exports.string().uuid(),
11507
+ gapKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/),
11508
+ evaluationContractHash: sha256Schema4,
11509
+ targetHash: sha256Schema4,
11510
+ observedAt: external_exports.string().datetime({ offset: true }),
11511
+ sourceRefs: external_exports.array(boardGoalGapSourceRefSchema).max(20),
11512
+ rationale: external_exports.string().trim().min(1).max(2e3),
11513
+ interactionId: external_exports.string().uuid(),
11514
+ resolutionRevision: external_exports.number().int().positive(),
11515
+ idempotencyKey: external_exports.string().trim().min(1).max(200)
11516
+ });
11517
+ var boardObserveGoalGapEffectSchema = external_exports.discriminatedUnion("decision", [
11518
+ boardGoalGapObservationBaseSchema.extend({
11519
+ decision: external_exports.literal("confirm_observed_effect"),
11520
+ observedValue: external_exports.boolean()
11521
+ }).strict(),
11522
+ boardGoalGapObservationBaseSchema.extend({
11523
+ decision: external_exports.literal("not_observed"),
11524
+ observedValue: external_exports.boolean()
11525
+ }).strict(),
11526
+ boardGoalGapObservationBaseSchema.extend({
11527
+ decision: external_exports.literal("correct_facts"),
11528
+ observedValue: external_exports.boolean().optional()
11529
+ }).strict(),
11530
+ boardGoalGapObservationBaseSchema.extend({
11531
+ decision: external_exports.literal("defer"),
11532
+ observedValue: external_exports.boolean().optional(),
11533
+ remindAt: external_exports.string().datetime({ offset: true }).optional()
11534
+ }).strict()
11535
+ ]);
11536
+ var goalGapCausalSourceSchema = external_exports.discriminatedUnion("kind", [
11537
+ external_exports.object({ kind: external_exports.literal("work_family"), workFamilyKey: sha256Schema4 }).strict(),
11538
+ external_exports.object({
11539
+ kind: external_exports.literal("board_direct"),
11540
+ interactionId: external_exports.string().uuid(),
11541
+ resolutionRevision: external_exports.number().int().positive()
11542
+ }).strict()
11543
+ ]);
11544
+ var goalGapWorkIdentitySchema = external_exports.object({
11545
+ schemaVersion: external_exports.literal("goal-gap-work-identity-v1"),
11546
+ intentFamilyKey: sha256Schema4,
11547
+ workPurposeKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/),
11548
+ workFamilyKey: sha256Schema4,
11549
+ workInstanceKey: sha256Schema4,
11550
+ admissionObservationKey: sha256Schema4,
11551
+ relationshipToExisting: external_exports.enum(["new", "follow_on", "replacement", "reopen"])
11552
+ }).strict();
11404
11553
  var replaceGoalGapContractBaseSchema = external_exports.object({
11405
11554
  expectedAuthorityRevision: external_exports.number().int().min(0),
11406
11555
  idempotencyKey: external_exports.string().min(1).max(200),
11407
- sourceKind: external_exports.enum(["board_confirmed", "supported_projector"]),
11556
+ sourceKind: external_exports.enum(["board_confirmed", "supported_projector", "supported_evaluator"]),
11408
11557
  gaps: external_exports.array(goalGapDefinitionSchema).max(10)
11409
11558
  }).strict();
11410
11559
  function validateUniqueGapIdentities(value, ctx) {
@@ -11417,6 +11566,58 @@ function validateUniqueGapIdentities(value, ctx) {
11417
11566
  }
11418
11567
  var replaceGoalGapContractSchema = replaceGoalGapContractBaseSchema.superRefine(validateUniqueGapIdentities);
11419
11568
  var boardReplaceGoalGapContractSchema = replaceGoalGapContractBaseSchema.omit({ sourceKind: true }).superRefine(validateUniqueGapIdentities);
11569
+ var boardDecideGoalGapPortfolioSchema = external_exports.object({
11570
+ expectedAuthorityRevision: external_exports.number().int().min(0),
11571
+ expectedContractId: external_exports.string().uuid().nullable(),
11572
+ criterionIndex: external_exports.number().int().min(0).max(9),
11573
+ decision: external_exports.enum(["confirm_open", "mark_not_applicable"]),
11574
+ rationale: external_exports.string().trim().min(1).max(2e3),
11575
+ observedAt: external_exports.string().datetime({ offset: true }),
11576
+ idempotencyKey: external_exports.string().trim().min(1).max(200)
11577
+ }).strict();
11578
+ var boardResolveGoalGapAuthorityBaseSchema = external_exports.object({
11579
+ expectedAuthorityRevision: external_exports.number().int().min(0),
11580
+ expectedContractId: external_exports.string().uuid().nullable(),
11581
+ criterionIndex: external_exports.number().int().min(0).max(9),
11582
+ candidateGapKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/),
11583
+ rationale: external_exports.string().trim().min(1).max(2e3),
11584
+ observedAt: external_exports.string().datetime({ offset: true }),
11585
+ interactionId: external_exports.string().uuid(),
11586
+ resolutionRevision: external_exports.number().int().positive(),
11587
+ idempotencyKey: external_exports.string().trim().min(1).max(200)
11588
+ });
11589
+ var boardResolveGoalGapAuthoritySchema = external_exports.discriminatedUnion("decision", [
11590
+ boardResolveGoalGapAuthorityBaseSchema.extend({ decision: external_exports.literal("confirm_open") }).strict(),
11591
+ boardResolveGoalGapAuthorityBaseSchema.extend({ decision: external_exports.literal("mark_not_applicable") }).strict(),
11592
+ boardResolveGoalGapAuthorityBaseSchema.extend({ decision: external_exports.literal("correct_facts") }).strict(),
11593
+ boardResolveGoalGapAuthorityBaseSchema.extend({
11594
+ decision: external_exports.literal("defer"),
11595
+ remindAt: external_exports.string().datetime({ offset: true }).optional()
11596
+ }).strict()
11597
+ ]);
11598
+ var boardResolveLegacyOutcomeGapBaseSchema = external_exports.object({
11599
+ expectedAuthorityRevision: external_exports.number().int().min(0),
11600
+ expectedContractId: external_exports.string().uuid().nullable(),
11601
+ readinessStateId: external_exports.string().uuid(),
11602
+ expectedReadinessRevision: external_exports.number().int().positive(),
11603
+ interactionId: external_exports.string().uuid(),
11604
+ resolutionRevision: external_exports.number().int().positive(),
11605
+ rationale: external_exports.string().trim().min(1).max(2e3),
11606
+ observedAt: external_exports.string().datetime({ offset: true }),
11607
+ idempotencyKey: external_exports.string().trim().min(1).max(200)
11608
+ });
11609
+ var boardResolveLegacyOutcomeGapSchema = external_exports.discriminatedUnion("decision", [
11610
+ boardResolveLegacyOutcomeGapBaseSchema.extend({
11611
+ decision: external_exports.literal("attribute_to_criterion"),
11612
+ criterionIndex: external_exports.number().int().min(0).max(9)
11613
+ }).strict(),
11614
+ boardResolveLegacyOutcomeGapBaseSchema.extend({ decision: external_exports.literal("not_goal_effect") }).strict(),
11615
+ boardResolveLegacyOutcomeGapBaseSchema.extend({ decision: external_exports.literal("correct_facts") }).strict(),
11616
+ boardResolveLegacyOutcomeGapBaseSchema.extend({
11617
+ decision: external_exports.literal("defer"),
11618
+ remindAt: external_exports.string().datetime({ offset: true }).optional()
11619
+ }).strict()
11620
+ ]);
11420
11621
  var transitionGoalGapSchema = external_exports.object({
11421
11622
  expectedAuthorityRevision: external_exports.number().int().min(0),
11422
11623
  expectedContractId: external_exports.string().uuid().nullable(),
@@ -11455,7 +11656,7 @@ var goalGapContractRevisionSchema = external_exports.object({
11455
11656
  goalId: external_exports.string().uuid(),
11456
11657
  authorityRevision: external_exports.number().int().positive(),
11457
11658
  compilerRevision: external_exports.string().min(1),
11458
- sourceKind: external_exports.enum(["board_confirmed", "supported_projector"]),
11659
+ sourceKind: external_exports.enum(["board_confirmed", "supported_projector", "supported_evaluator"]),
11459
11660
  contractHash: sha256Schema4,
11460
11661
  status: external_exports.enum(["current", "superseded"]),
11461
11662
  idempotencyKey: external_exports.string().min(1),
@@ -11514,8 +11715,59 @@ var goalGapProjectorReceiptSchema = external_exports.object({
11514
11715
  }).strict();
11515
11716
  var goalGapContractReadResponseSchema = external_exports.object({
11516
11717
  contract: goalGapContractRevisionSchema.nullable(),
11718
+ gapEvidence: external_exports.array(external_exports.object({
11719
+ gapKey: external_exports.string(),
11720
+ reasonSummary: external_exports.string().min(1),
11721
+ observedAt: external_exports.string().datetime().nullable(),
11722
+ sourceName: external_exports.string().nullable(),
11723
+ relatedWork: external_exports.array(external_exports.object({
11724
+ issueId: external_exports.string().uuid(),
11725
+ identifier: external_exports.string().min(1),
11726
+ title: external_exports.string().min(1),
11727
+ status: external_exports.string().min(1)
11728
+ }).strict()).max(20)
11729
+ }).strict()),
11517
11730
  readiness: external_exports.array(goalGapReadinessStateSchema.omit({ materialHash: true })),
11518
- projectorReceipts: external_exports.array(goalGapProjectorReceiptSchema)
11731
+ projectorReceipts: external_exports.array(goalGapProjectorReceiptSchema),
11732
+ pendingDecisions: external_exports.array(external_exports.discriminatedUnion("kind", [
11733
+ external_exports.object({
11734
+ kind: external_exports.literal("observed_effect"),
11735
+ interactionId: external_exports.string().uuid(),
11736
+ gapKey: external_exports.string(),
11737
+ title: external_exports.string(),
11738
+ summary: external_exports.string(),
11739
+ resolutionRevision: external_exports.number().int().nonnegative(),
11740
+ evaluationContractHash: sha256Schema4,
11741
+ targetHash: sha256Schema4,
11742
+ stale: external_exports.boolean(),
11743
+ href: external_exports.string().min(1)
11744
+ }).strict(),
11745
+ external_exports.object({
11746
+ kind: external_exports.literal("gap_authority"),
11747
+ interactionId: external_exports.string().uuid(),
11748
+ gapKey: external_exports.string(),
11749
+ criterionIndex: external_exports.number().int().min(0).max(9),
11750
+ title: external_exports.string(),
11751
+ summary: external_exports.string(),
11752
+ resolutionRevision: external_exports.number().int().nonnegative(),
11753
+ stale: external_exports.boolean(),
11754
+ href: external_exports.string().min(1)
11755
+ }).strict(),
11756
+ external_exports.object({
11757
+ kind: external_exports.literal("legacy_outcome_attribution"),
11758
+ interactionId: external_exports.string().uuid(),
11759
+ readinessStateId: external_exports.string().uuid(),
11760
+ readinessRevision: external_exports.number().int().positive(),
11761
+ outcomeId: external_exports.string().uuid(),
11762
+ sourceIssueId: external_exports.string().uuid(),
11763
+ sourceIssueTitle: external_exports.string().min(1),
11764
+ title: external_exports.string(),
11765
+ summary: external_exports.string(),
11766
+ resolutionRevision: external_exports.number().int().nonnegative(),
11767
+ stale: external_exports.boolean(),
11768
+ href: external_exports.string().min(1)
11769
+ }).strict()
11770
+ ]))
11519
11771
  }).strict();
11520
11772
 
11521
11773
  // ../shared/src/ceo-periodic-auto-work.ts
@@ -11688,6 +11940,48 @@ var ceoPeriodicRoutingRosterEntrySchema = external_exports.object({
11688
11940
  maxQueuedWorkCount: external_exports.number().int().nonnegative().max(CEO_PERIODIC_MAX_CANDIDATES_PER_OBSERVATION),
11689
11941
  unacceptedOutcomeCount: external_exports.number().int().nonnegative()
11690
11942
  }).strict();
11943
+ var ceoPeriodicPortfolioAdmissionSchema = external_exports.object({
11944
+ outcomeClass: external_exports.enum(["internal_enablement", "governed_decision", "external_action", "observed_business_result"]),
11945
+ outcomeFamilyIdentity: external_exports.object({
11946
+ normalizedBusinessSubjectRef: operatingNormalizedBusinessSubjectRefSchema
11947
+ }).strict(),
11948
+ expectedBusinessChange: operatingStateTransitionSchema,
11949
+ causalGoalGapRef: external_exports.object({
11950
+ gapKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/u),
11951
+ authorityRevision: external_exports.number().int().min(0),
11952
+ observationRef: external_exports.object({
11953
+ kind: external_exports.enum(["provider_object", "governed_business_state", "effect_event", "board_assertion"]),
11954
+ id: external_exports.string().min(1).max(240),
11955
+ revision: external_exports.string().min(1).max(240)
11956
+ }).strict()
11957
+ }).strict(),
11958
+ relationshipToExisting: external_exports.enum(["new", "continuation", "follow_on", "replacement", "reopen"]).transform((value) => value === "continuation" ? "follow_on" : value),
11959
+ promotionReason: external_exports.object({
11960
+ kind: external_exports.literal("unlocks_external_execution"),
11961
+ blockerRef: ceoPeriodicWorkSourceRefSchema
11962
+ }).strict().nullable(),
11963
+ observationPolicy: external_exports.object({
11964
+ kind: external_exports.enum(["none", "provider_readback", "governed_state_readback", "board_verification"]),
11965
+ dueAt: external_exports.string().datetime({ offset: true }).nullable()
11966
+ }).strict()
11967
+ }).strict().superRefine((value, ctx) => {
11968
+ if (value.outcomeClass === "internal_enablement" && !value.promotionReason) {
11969
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["promotionReason"], message: "Internal enablement must identify the external execution blocker it unlocks" });
11970
+ }
11971
+ if (value.outcomeClass !== "internal_enablement" && value.promotionReason) {
11972
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["promotionReason"], message: "Only internal enablement uses a promotion reason" });
11973
+ }
11974
+ if (["external_action", "observed_business_result"].includes(value.outcomeClass) && value.observationPolicy.kind === "none") {
11975
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["observationPolicy", "kind"], message: "External results require an authoritative readback policy" });
11976
+ }
11977
+ if (value.causalGoalGapRef.authorityRevision === 0 && !["internal_enablement", "governed_decision"].includes(value.outcomeClass)) {
11978
+ ctx.addIssue({
11979
+ code: external_exports.ZodIssueCode.custom,
11980
+ path: ["causalGoalGapRef", "authorityRevision"],
11981
+ message: "Only low-risk work may cite a provisional Goal Gap candidate"
11982
+ });
11983
+ }
11984
+ });
11691
11985
  var ceoPeriodicDiscoveredWorkInputSchema = external_exports.object({
11692
11986
  workKind: external_exports.string().trim().regex(/^[a-z0-9][a-z0-9._-]{0,127}$/u),
11693
11987
  title: external_exports.string().trim().min(1).max(240),
@@ -11701,49 +11995,25 @@ var ceoPeriodicDiscoveredWorkInputSchema = external_exports.object({
11701
11995
  capabilityNeeds: external_exports.array(external_exports.string().trim().regex(/^[a-z0-9][a-z0-9._-]{0,159}$/u)).max(20).default([]),
11702
11996
  expectedOutcomeAt: external_exports.string().datetime({ offset: true }),
11703
11997
  priority: external_exports.enum(["critical", "high", "medium", "low"]).default("medium"),
11704
- portfolioAdmission: external_exports.object({
11705
- outcomeClass: external_exports.enum(["internal_enablement", "governed_decision", "external_action", "observed_business_result"]),
11706
- outcomeFamilyIdentity: external_exports.object({
11707
- normalizedBusinessSubjectRef: operatingNormalizedBusinessSubjectRefSchema
11708
- }).strict(),
11709
- expectedBusinessChange: operatingStateTransitionSchema,
11710
- causalGoalGapRef: external_exports.object({
11711
- gapKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/u),
11712
- authorityRevision: external_exports.number().int().min(0),
11713
- observationRef: external_exports.object({
11714
- kind: external_exports.enum(["provider_object", "governed_business_state", "effect_event", "board_assertion"]),
11715
- id: external_exports.string().min(1).max(240),
11716
- revision: external_exports.string().min(1).max(240)
11717
- }).strict()
11718
- }).strict(),
11719
- relationshipToExisting: external_exports.enum(["new", "continuation", "replacement", "reopen"]),
11720
- promotionReason: external_exports.object({
11721
- kind: external_exports.literal("unlocks_external_execution"),
11722
- blockerRef: ceoPeriodicWorkSourceRefSchema
11723
- }).strict().nullable(),
11724
- observationPolicy: external_exports.object({
11725
- kind: external_exports.enum(["none", "provider_readback", "governed_state_readback", "board_verification"]),
11726
- dueAt: external_exports.string().datetime({ offset: true }).nullable()
11727
- }).strict()
11728
- }).strict().superRefine((value, ctx) => {
11729
- if (value.outcomeClass === "internal_enablement" && !value.promotionReason) {
11730
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["promotionReason"], message: "Internal enablement must identify the external execution blocker it unlocks" });
11731
- }
11732
- if (value.outcomeClass !== "internal_enablement" && value.promotionReason) {
11733
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["promotionReason"], message: "Only internal enablement uses a promotion reason" });
11734
- }
11735
- if (["external_action", "observed_business_result"].includes(value.outcomeClass) && value.observationPolicy.kind === "none") {
11736
- ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["observationPolicy", "kind"], message: "External results require an authoritative readback policy" });
11737
- }
11738
- if (value.causalGoalGapRef.authorityRevision === 0 && !["internal_enablement", "governed_decision"].includes(value.outcomeClass)) {
11739
- ctx.addIssue({
11740
- code: external_exports.ZodIssueCode.custom,
11741
- path: ["causalGoalGapRef", "authorityRevision"],
11742
- message: "Only low-risk work may cite a provisional Goal Gap candidate"
11743
- });
11744
- }
11745
- }).optional()
11746
- }).strict();
11998
+ executionShape: external_exports.enum(["direct", "team_decomposition", "agent_decides"]).default("agent_decides"),
11999
+ completionStrategy: external_exports.enum(["single_aggregation", "multi_acceptance"]).nullable().default(null),
12000
+ portfolioAdmission: ceoPeriodicPortfolioAdmissionSchema.optional()
12001
+ }).strict().superRefine((value, ctx) => {
12002
+ if (value.executionShape === "team_decomposition" && !value.completionStrategy) {
12003
+ ctx.addIssue({
12004
+ code: external_exports.ZodIssueCode.custom,
12005
+ path: ["completionStrategy"],
12006
+ message: "Team decomposition requires an explicit completion strategy"
12007
+ });
12008
+ }
12009
+ if (value.executionShape !== "team_decomposition" && value.completionStrategy !== null) {
12010
+ ctx.addIssue({
12011
+ code: external_exports.ZodIssueCode.custom,
12012
+ path: ["completionStrategy"],
12013
+ message: "Only team decomposition may declare a completion strategy"
12014
+ });
12015
+ }
12016
+ });
11747
12017
  var ceoPeriodicGoalGapCandidateSchema = external_exports.object({
11748
12018
  candidateGapKey: external_exports.string().regex(/^[a-z0-9][a-z0-9._:-]{0,119}$/u),
11749
12019
  criterionIndex: external_exports.number().int().min(0).max(9),
@@ -12181,10 +12451,16 @@ var governedBusinessTaskLineageSchema = external_exports.discriminatedUnion("kin
12181
12451
  authorityRevision: external_exports.number().int().positive().nullable(),
12182
12452
  contractHash: sha256Schema5.nullable(),
12183
12453
  gapKey: stableIdentitySchema2.nullable(),
12184
- sourceKind: external_exports.enum(["board_confirmed", "supported_projector"]).nullable(),
12454
+ sourceKind: external_exports.enum(["board_confirmed", "supported_projector", "supported_evaluator"]).nullable(),
12185
12455
  projectedVerdictRequirement: external_exports.enum(["deterministic_evidence", "human_verdict_required"]),
12186
12456
  effectiveVerdictRequirement: external_exports.enum(["deterministic_evidence", "human_verdict_required"])
12187
12457
  }).strict().optional(),
12458
+ controllerIssueId: external_exports.string().uuid().optional(),
12459
+ routineRunId: external_exports.string().uuid().nullable().optional(),
12460
+ workPurposeKey: stableIdentitySchema2.optional(),
12461
+ intentFamilyKey: sha256Schema5.optional(),
12462
+ workFamilyKey: sha256Schema5.optional(),
12463
+ workInstanceKey: sha256Schema5.optional(),
12188
12464
  supersedesDiscoveredWorkId: external_exports.string().uuid().optional(),
12189
12465
  replacementContractRevision: stableIdentitySchema2.optional(),
12190
12466
  requiredResponsibilityKey: stableIdentitySchema2.optional(),
@@ -24440,7 +24716,10 @@ function runtimeAuthorizationText(context, mode, {
24440
24716
  ].join("\n") : "";
24441
24717
  const initializationAuthorization = asRecord(envelope.initializationAuthorization);
24442
24718
  const initializationAuthority = asRecord(context.companyInitializationAuthority);
24443
- const initializationPlanAuthorizationWithoutExactReplay = readString(envelope.sourceKind) === COMPANY_INITIALIZATION_ORIGIN_KIND && readString(initializationAuthorization.runId) && readString(initializationAuthorization.signature) && readString(initializationAuthority.schemaVersion) === "mirrorx.company-initialization-authority.v1" && (!Array.isArray(envelope.authorizedOrganizationIntents) || envelope.authorizedOrganizationIntents.length === 0);
24719
+ const organizationMutationAuthorityMode = readString(
24720
+ initializationAuthority.organizationMutationAuthorityMode
24721
+ );
24722
+ const initializationPlanAuthorizationWithoutExactReplay = readString(envelope.sourceKind) === COMPANY_INITIALIZATION_ORIGIN_KIND && readString(initializationAuthority.schemaVersion) === "mirrorx.company-initialization-authority.v1" && (organizationMutationAuthorityMode === "initialization_plan" || organizationMutationAuthorityMode === null && readString(initializationAuthorization.runId) && readString(initializationAuthorization.signature)) && (!Array.isArray(envelope.authorizedOrganizationIntents) || envelope.authorizedOrganizationIntents.length === 0);
24444
24723
  const exactOrganizationReplay = replayAlreadyInTask || initializationPlanAuthorizationWithoutExactReplay ? "" : renderExactOrganizationIntentReplayBlock(envelope);
24445
24724
  return [
24446
24725
  completionContract,
@@ -24759,6 +25038,64 @@ function sectionText(section) {
24759
25038
  return section.title ? `## ${section.title}
24760
25039
  ${section.content}` : section.content;
24761
25040
  }
25041
+ var COMPANY_INITIALIZATION_PRE_AUTHORITY_SECTIONS = /* @__PURE__ */ new Set([
25042
+ "recovery_instruction",
25043
+ "approval_continuation",
25044
+ "wake_comments",
25045
+ "task",
25046
+ "task_acceptance_contract",
25047
+ "governed_business_state",
25048
+ "continuation_postcondition_gap",
25049
+ "continuation_summary",
25050
+ "resolved_dependencies",
25051
+ "runtime_delivery_readiness",
25052
+ "verified_company_context",
25053
+ "governed_reads",
25054
+ "optional_task_wiki_context",
25055
+ "attachments"
25056
+ ]);
25057
+ var COMPANY_INITIALIZATION_POST_AUTHORITY_SECTIONS = /* @__PURE__ */ new Set([
25058
+ "runtime_rules",
25059
+ "runtime_authorization",
25060
+ "runtime_decomposition_requirement",
25061
+ "task_context_authority",
25062
+ "pi_mcp_usage",
25063
+ "runtime_template_catalog",
25064
+ "agent_instructions",
25065
+ "on_demand_refs",
25066
+ "raw_snapshot"
25067
+ ]);
25068
+ function companyInitializationAuthoritySectionClass(name) {
25069
+ if (name === "company_initialization_authority") return "current_authority_sink";
25070
+ if (COMPANY_INITIALIZATION_PRE_AUTHORITY_SECTIONS.has(name)) return "historical_prose";
25071
+ if (COMPANY_INITIALIZATION_POST_AUTHORITY_SECTIONS.has(name)) return "runtime_contract";
25072
+ return null;
25073
+ }
25074
+ function validateCompanyInitializationAuthoritySectionOrder(sections) {
25075
+ const sinkIndexes = sections.flatMap((section, index) => section?.name === "company_initialization_authority" ? [index] : []);
25076
+ if (sinkIndexes.length === 0) return;
25077
+ if (sinkIndexes.length !== 1) {
25078
+ const error = new Error("Company initialization prompt must contain exactly one final authority sink");
25079
+ error.code = "company_initialization_authority_section_order_invalid";
25080
+ throw error;
25081
+ }
25082
+ const sinkIndex = sinkIndexes[0];
25083
+ for (const [index, section] of sections.entries()) {
25084
+ const name = readString(section?.name);
25085
+ const sectionClass = companyInitializationAuthoritySectionClass(name);
25086
+ if (sectionClass === "current_authority_sink") continue;
25087
+ if (!sectionClass) {
25088
+ const error = new Error(`Unclassified Company initialization prompt section: ${name ?? "missing"}`);
25089
+ error.code = "company_initialization_authority_section_unclassified";
25090
+ throw error;
25091
+ }
25092
+ if (sectionClass === "historical_prose" && index > sinkIndex || sectionClass === "runtime_contract" && index < sinkIndex) {
25093
+ const error = new Error(`Company initialization prompt section is on the wrong side of the final authority sink: ${name}`);
25094
+ error.code = "company_initialization_authority_section_order_invalid";
25095
+ throw error;
25096
+ }
25097
+ }
25098
+ }
24762
25099
  function companyInitializationAuthoritySection(context) {
24763
25100
  const authority = asRecord(context.companyInitializationAuthority);
24764
25101
  const authorization = asRecord(context.authorizationEnvelope);
@@ -24769,6 +25106,13 @@ function companyInitializationAuthoritySection(context) {
24769
25106
  const targetAgentCount = Number(authority.targetAgentCount);
24770
25107
  const maxAgentCount = Number(authority.maxAgentCount);
24771
25108
  const sourceRevision = readString(authorization.sourceRevision);
25109
+ const rawOrganizationMutationAuthorityMode = authority.organizationMutationAuthorityMode;
25110
+ const organizationMutationAuthorityMode = readString(rawOrganizationMutationAuthorityMode);
25111
+ if (rawOrganizationMutationAuthorityMode != null && organizationMutationAuthorityMode !== "initialization_plan" && organizationMutationAuthorityMode !== "exact_intent_replay") {
25112
+ const error = new Error("Matched Company initialization authority has an unsupported organization mutation mode");
25113
+ error.code = "company_initialization_authority_mode_unsupported";
25114
+ throw error;
25115
+ }
24772
25116
  if (readString(authority.schemaVersion) !== "mirrorx.company-initialization-authority.v1" || readString(authorization.sourceKind) !== "company_initialization" || readString(authorization.sourceId) !== initializationId || sourceRevision !== `${revision}:${organizationVersion}` || !initializationId || !Number.isInteger(revision) || revision < 1 || !Number.isInteger(organizationVersion) || organizationVersion < 1 || !Number.isInteger(minAgentCount) || !Number.isInteger(targetAgentCount) || !Number.isInteger(maxAgentCount) || minAgentCount < 1 || targetAgentCount < minAgentCount || targetAgentCount > maxAgentCount) return null;
24773
25117
  const executionPolicy = asRecord(authority.executionPolicy);
24774
25118
  const executionPolicyRef = readString(executionPolicy.ref);
@@ -24783,6 +25127,13 @@ function companyInitializationAuthoritySection(context) {
24783
25127
  error.code = "company_initialization_authority_not_fresh";
24784
25128
  throw error;
24785
25129
  }
25130
+ const exactOrganizationIntentCount = Array.isArray(authorization.authorizedOrganizationIntents) ? authorization.authorizedOrganizationIntents.length : 0;
25131
+ const organizationMutationAuthorized = Array.isArray(authorization.allowedActionClasses) && authorization.allowedActionClasses.includes("organization_mutation");
25132
+ if (organizationMutationAuthorityMode && (!organizationMutationAuthorized || organizationMutationAuthorityMode === "initialization_plan" && exactOrganizationIntentCount !== 0 || organizationMutationAuthorityMode === "exact_intent_replay" && exactOrganizationIntentCount === 0)) {
25133
+ const error = new Error("Matched Company initialization authority mode conflicts with its authorization envelope");
25134
+ error.code = "company_initialization_authority_mode_mismatch";
25135
+ throw error;
25136
+ }
24786
25137
  const remainingReadyPostconditions = Array.isArray(authority.remainingReadyPostconditions) ? authority.remainingReadyPostconditions.map(asRecord).flatMap((postcondition) => {
24787
25138
  const key = readString(postcondition.key);
24788
25139
  return key ? [{ key }] : [];
@@ -24796,6 +25147,10 @@ function companyInitializationAuthoritySection(context) {
24796
25147
  `- Initialization id: ${JSON.stringify(initializationId)}`,
24797
25148
  `- Input revision: ${revision}`,
24798
25149
  `- Organization version: ${organizationVersion}`,
25150
+ ...organizationMutationAuthorityMode ? [
25151
+ `- Organization mutation authority mode: ${organizationMutationAuthorityMode}`,
25152
+ `- Exact organization-intent replay required for this run: ${organizationMutationAuthorityMode === "exact_intent_replay" ? "true" : "false"}`
25153
+ ] : [],
24799
25154
  `- Team mode: ${JSON.stringify(mode)}`,
24800
25155
  agentCountLine,
24801
25156
  `- Organization Plan artifact state: ${artifactStateKind ?? "unknown"}`,
@@ -25117,7 +25472,6 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
25117
25472
  { name: "approval_continuation", title: "Approved Runtime Action Continuation", priority: 99, sourceRef: `run:${input.runId ?? "unknown"}`, content: approvalContinuationText(input), truncationReason: mode === "continuation" ? null : "mode_selection" },
25118
25473
  { name: "wake_comments", title: wakeDeltaTitle, priority: interactionResolution ? 99 : 95, sourceRef: wakeDeltaSourceRefs, originalContent: wakeDeltaOriginal, content: wakeDeltaContent, truncationReason: commentsSelected ? null : "duplicate_task_context" },
25119
25474
  { name: "task", title: "Task Context", priority: 90, sourceRef: taskSourceRefs, originalContent: [taskText, taskCommentRefGuidance(input, taskText)].filter(Boolean).join("\n"), content: includeTask ? [taskText, taskCommentRefGuidance(input, taskText)].filter(Boolean).join("\n") : "", truncationReason: includeTask ? null : "mode_selection" },
25120
- ...companyInitializationAuthority && !includeTask ? [companyInitializationAuthority] : [],
25121
25475
  ...taskAcceptanceContract ? [{ name: "task_acceptance_contract", title: "Task Acceptance Contract", priority: 100, ...taskAcceptanceContract }] : [],
25122
25476
  ...governedBusinessState ? [{ name: "governed_business_state", title: "Governed Business State", priority: 99, ...governedBusinessState }] : [],
25123
25477
  ...continuationPostconditionGap ? [{ name: "continuation_postcondition_gap", title: "Continuation Postcondition Gap", priority: 100, ...continuationPostconditionGap }] : [],
@@ -25129,6 +25483,7 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
25129
25483
  ...resolvedDependencySection
25130
25484
  }] : [],
25131
25485
  ...deliveryReadinessContent ? [{ name: "runtime_delivery_readiness", title: "Current Delivery Readiness", priority: 99, sourceRef: `issue:${input.issueId ?? "unknown"}:delivery`, content: deliveryReadinessContent }] : [],
25486
+ ...companyInitializationAuthority && !includeTask ? [companyInitializationAuthority] : [],
25132
25487
  { name: "runtime_rules", title: "", priority: 100, sourceRef: `command:${input.commandId}`, content: fixedRules(input, !hasTask) },
25133
25488
  { name: "runtime_authorization", title: "Runtime Action Contract", priority: 98, sourceRef: `run:${input.runId ?? "unknown"}`, content: runtimeAuthorizationText(context, mode, {
25134
25489
  replayAlreadyInTask: includeTask && taskText.includes(EXACT_ORGANIZATION_INTENT_REPLAY_MARKER),
@@ -25162,6 +25517,20 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
25162
25517
  },
25163
25518
  { name: "raw_snapshot", title: "Raw Context Snapshot", priority: 0, sourceRef: `run:${input.runId ?? "unknown"}`, originalChars: jsonCharLength(context), content: "", truncationReason: "on_demand_large_object" }
25164
25519
  ];
25520
+ if (rawSections.some((section) => section.name === "company_initialization_authority")) {
25521
+ const rank = {
25522
+ historical_prose: 0,
25523
+ current_authority_sink: 1,
25524
+ runtime_contract: 2
25525
+ };
25526
+ rawSections.sort((left, right) => {
25527
+ const leftClass = companyInitializationAuthoritySectionClass(left.name);
25528
+ const rightClass = companyInitializationAuthoritySectionClass(right.name);
25529
+ if (!leftClass || !rightClass) return 0;
25530
+ return rank[leftClass] - rank[rightClass];
25531
+ });
25532
+ }
25533
+ validateCompanyInitializationAuthoritySectionOrder(rawSections);
25165
25534
  for (const section of rawSections) {
25166
25535
  section.scope ??= contextScope;
25167
25536
  section.freshness ??= snapshotFreshness;
@@ -28673,12 +29042,113 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
28673
29042
 
28674
29043
  // src/amaster-runtime-daemon/pi-context-budget.mjs
28675
29044
  import { readFileSync as readFileSync16 } from "node:fs";
29045
+ var CONTEXT_ERROR_CODES = /* @__PURE__ */ new Set([
29046
+ "context_output_reserve_exceeds_model_limit",
29047
+ "model_context_attestation_unavailable",
29048
+ "model_context_fixed_inputs_exceed_budget",
29049
+ "native_session_history_attestation_invalid",
29050
+ "native_session_history_attestation_unavailable",
29051
+ "native_session_history_exceeds_measurement_limit"
29052
+ ]);
29053
+ var USAGE_FIELDS = Object.freeze({
29054
+ input: ["inputTokens", "input_tokens", "input"],
29055
+ cachedInput: ["cachedInputTokens", "cached_input_tokens", "cacheRead"],
29056
+ cacheCreationInput: ["cacheCreationInputTokens", "cache_creation_input_tokens", "cacheWrite"],
29057
+ output: ["outputTokens", "output_tokens", "output"],
29058
+ total: ["totalTokens", "total_tokens"]
29059
+ });
28676
29060
  function record6(value) {
28677
29061
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
28678
29062
  }
28679
29063
  function stringValue(value) {
28680
29064
  return typeof value === "string" && value.trim() ? value.trim() : null;
28681
29065
  }
29066
+ function stableContextError(code, details = "") {
29067
+ if (!CONTEXT_ERROR_CODES.has(code)) {
29068
+ throw new Error("context_error_code_invalid");
29069
+ }
29070
+ const error = new Error(details ? `${code}: ${details}` : code);
29071
+ Object.defineProperty(error, "code", {
29072
+ configurable: false,
29073
+ enumerable: true,
29074
+ value: code,
29075
+ writable: false
29076
+ });
29077
+ return error;
29078
+ }
29079
+ function contextErrorCodeFromMessage(message) {
29080
+ if (typeof message !== "string") return null;
29081
+ const code = message.match(
29082
+ /^((?:model_context|native_session_history|context_output_reserve)_[a-z0-9_]{1,109})(?::|$)/
29083
+ )?.[1];
29084
+ return code && /^[a-z][a-z0-9_]{0,127}$/.test(code) ? code : null;
29085
+ }
29086
+ function assertPiModelContextAttestationInputs(managedMcpProfile, piAgentDir) {
29087
+ if (!managedMcpProfile || !stringValue(piAgentDir)) {
29088
+ throw stableContextError(
29089
+ "model_context_attestation_unavailable",
29090
+ "managed Pi profile or Pi config home is missing"
29091
+ );
29092
+ }
29093
+ }
29094
+ function aliasedUsageInteger(usage, aliases, label) {
29095
+ const entries = aliases.filter((key) => Object.prototype.hasOwnProperty.call(usage, key)).map((key) => usage[key]);
29096
+ if (entries.length === 0) return { present: false, value: 0 };
29097
+ if (entries.some((value) => typeof value !== "number" || !Number.isSafeInteger(value) || value < 0)) {
29098
+ throw stableContextError(
29099
+ "native_session_history_attestation_invalid",
29100
+ `usage ${label} must be a non-negative safe integer`
29101
+ );
29102
+ }
29103
+ if (entries.some((value) => value !== entries[0])) {
29104
+ throw stableContextError(
29105
+ "native_session_history_attestation_invalid",
29106
+ `usage ${label} aliases disagree`
29107
+ );
29108
+ }
29109
+ return { present: true, value: entries[0] };
29110
+ }
29111
+ function piUsageTotal(usageValue) {
29112
+ const usage = record6(usageValue);
29113
+ const input = aliasedUsageInteger(usage, USAGE_FIELDS.input, "input");
29114
+ const cachedInput = aliasedUsageInteger(usage, USAGE_FIELDS.cachedInput, "cached input");
29115
+ const cacheCreationInput = aliasedUsageInteger(
29116
+ usage,
29117
+ USAGE_FIELDS.cacheCreationInput,
29118
+ "cache creation input"
29119
+ );
29120
+ const output = aliasedUsageInteger(usage, USAGE_FIELDS.output, "output");
29121
+ const total = aliasedUsageInteger(usage, USAGE_FIELDS.total, "total");
29122
+ if (![input, cachedInput, cacheCreationInput, output, total].some((field) => field.present)) {
29123
+ return null;
29124
+ }
29125
+ if (!input.present && !total.present) {
29126
+ throw stableContextError(
29127
+ "native_session_history_attestation_invalid",
29128
+ "usage requires input or explicit total tokens"
29129
+ );
29130
+ }
29131
+ const componentTotal = input.value + cachedInput.value + cacheCreationInput.value + output.value;
29132
+ if (!Number.isSafeInteger(componentTotal)) {
29133
+ throw stableContextError(
29134
+ "native_session_history_attestation_invalid",
29135
+ "usage component total exceeds the safe integer range"
29136
+ );
29137
+ }
29138
+ return Math.max(componentTotal, total.present ? total.value : 0);
29139
+ }
29140
+ function usageFromContainer(containerValue) {
29141
+ const container = record6(containerValue);
29142
+ if (!Object.prototype.hasOwnProperty.call(container, "usage")) return null;
29143
+ const usage = container.usage;
29144
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) {
29145
+ throw stableContextError(
29146
+ "native_session_history_attestation_invalid",
29147
+ "usage must be an object"
29148
+ );
29149
+ }
29150
+ return usage;
29151
+ }
28682
29152
  function measureRestoredPiNativeHistory(managedMcpProfile) {
28683
29153
  const restored = record6(managedMcpProfile?.restoredNativeSession);
28684
29154
  const rolloutPath = stringValue(restored.rolloutPath);
@@ -28688,7 +29158,10 @@ function measureRestoredPiNativeHistory(managedMcpProfile) {
28688
29158
  const rollout = readFileSync16(rolloutPath);
28689
29159
  const maximumRolloutBytes = 64 * 1024 * 1024;
28690
29160
  if (rollout.byteLength > maximumRolloutBytes) {
28691
- throw new Error(`native_session_history_exceeds_measurement_limit: bytes=${rollout.byteLength}`);
29161
+ throw stableContextError(
29162
+ "native_session_history_exceeds_measurement_limit",
29163
+ `bytes=${rollout.byteLength}`
29164
+ );
28692
29165
  }
28693
29166
  let latestUsageTokens = null;
28694
29167
  for (const line of rollout.toString("utf8").split("\n")) {
@@ -28697,27 +29170,27 @@ function measureRestoredPiNativeHistory(managedMcpProfile) {
28697
29170
  try {
28698
29171
  event = JSON.parse(line);
28699
29172
  } catch {
28700
- throw new Error("native_session_history_attestation_invalid: rollout contains invalid JSONL");
29173
+ throw stableContextError(
29174
+ "native_session_history_attestation_invalid",
29175
+ "rollout contains invalid JSONL"
29176
+ );
28701
29177
  }
28702
- const candidates = [
28703
- record6(event.usage),
28704
- record6(record6(event.message).usage),
28705
- record6(record6(event.turn).usage)
28706
- ];
28707
- for (const usage of candidates) {
28708
- const inputTokens = Number(usage.inputTokens ?? usage.input_tokens ?? usage.input);
28709
- const outputTokens = Number(usage.outputTokens ?? usage.output_tokens ?? usage.output ?? 0);
28710
- if (Number.isSafeInteger(inputTokens) && inputTokens >= 0 && Number.isSafeInteger(outputTokens) && outputTokens >= 0) {
28711
- latestUsageTokens = inputTokens + outputTokens;
28712
- }
29178
+ for (const container of [event, event.message, event.turn]) {
29179
+ const usage = usageFromContainer(container);
29180
+ if (!usage) continue;
29181
+ const usageTotal = piUsageTotal(usage);
29182
+ if (usageTotal !== null) latestUsageTokens = usageTotal;
28713
29183
  }
28714
29184
  }
28715
29185
  if (!Number.isSafeInteger(latestUsageTokens)) {
28716
- throw new Error("native_session_history_attestation_unavailable: rollout has no usage-bearing turn");
29186
+ throw stableContextError(
29187
+ "native_session_history_attestation_unavailable",
29188
+ "rollout has no usage-bearing turn"
29189
+ );
28717
29190
  }
28718
29191
  return {
28719
29192
  status: "restored_measured",
28720
- tokens: Math.max(rollout.byteLength, latestUsageTokens),
29193
+ tokens: latestUsageTokens,
28721
29194
  rolloutBytes: rollout.byteLength,
28722
29195
  usageTokens: latestUsageTokens
28723
29196
  };
@@ -28729,19 +29202,26 @@ function resolvePiModelContextBudget({
28729
29202
  managedMcpProfile
28730
29203
  }) {
28731
29204
  if (outputReserveTokens > modelContext.maxOutputTokens) {
28732
- throw new Error(
28733
- `context_output_reserve_exceeds_model_limit: reserve=${outputReserveTokens} modelMax=${modelContext.maxOutputTokens}`
29205
+ throw stableContextError(
29206
+ "context_output_reserve_exceeds_model_limit",
29207
+ `reserve=${outputReserveTokens} modelMax=${modelContext.maxOutputTokens}`
28734
29208
  );
28735
29209
  }
28736
29210
  const instructionBytes = [...finalAgentInstructionFiles.values()].reduce((total, entry) => total + Number(entry.byteSize ?? 0), 0);
28737
29211
  const profileAttestation = record6(managedMcpProfile?.attestation);
28738
29212
  const toolSchemaBytes = Number(profileAttestation.finalEffectiveToolSchemaBytes);
28739
29213
  if (!Number.isSafeInteger(toolSchemaBytes) || toolSchemaBytes < 1) {
28740
- throw new Error("model_context_attestation_unavailable: final tool schema size is missing");
29214
+ throw stableContextError(
29215
+ "model_context_attestation_unavailable",
29216
+ "final tool schema size is missing"
29217
+ );
28741
29218
  }
28742
29219
  const skillMetadataBytes = Number(profileAttestation.enabledSkillMetadataBytes ?? 0);
28743
29220
  if (!Number.isSafeInteger(skillMetadataBytes) || skillMetadataBytes < 0) {
28744
- throw new Error("model_context_attestation_unavailable: skill metadata size is invalid");
29221
+ throw stableContextError(
29222
+ "model_context_attestation_unavailable",
29223
+ "skill metadata size is invalid"
29224
+ );
28745
29225
  }
28746
29226
  const nativeHistory = measureRestoredPiNativeHistory(managedMcpProfile);
28747
29227
  const executorBaseReserveTokens = Math.max(32768, Math.floor(modelContext.contextWindowTokens * 0.05));
@@ -28750,8 +29230,16 @@ function resolvePiModelContextBudget({
28750
29230
  const dynamicInputTokens = modelContext.contextWindowTokens - outputReserveTokens - executorBaseReserveTokens - nativeHistoryReserveTokens - knownFixedInputTokens;
28751
29231
  const dynamicPromptMaxChars = Math.floor(dynamicInputTokens / 4);
28752
29232
  if (dynamicPromptMaxChars < 8192) {
28753
- throw new Error(
28754
- `model_context_fixed_inputs_exceed_budget: context=${modelContext.contextWindowTokens} fixed=${knownFixedInputTokens}`
29233
+ throw stableContextError(
29234
+ "model_context_fixed_inputs_exceed_budget",
29235
+ [
29236
+ `context=${modelContext.contextWindowTokens}`,
29237
+ `output=${outputReserveTokens}`,
29238
+ `base=${executorBaseReserveTokens}`,
29239
+ `history=${nativeHistoryReserveTokens}`,
29240
+ `fixed=${knownFixedInputTokens}`,
29241
+ `dynamic=${dynamicInputTokens}`
29242
+ ].join(" ")
28755
29243
  );
28756
29244
  }
28757
29245
  return {
@@ -29940,7 +30428,7 @@ function createSourceCompletionStopPolicy({
29940
30428
  }
29941
30429
 
29942
30430
  // src/amaster-runtime-daemon.mjs
29943
- var CONNECTOR_VERSION = "0.1.1-beta.155";
30431
+ var CONNECTOR_VERSION = "0.1.1-beta.157";
29944
30432
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
29945
30433
  var SOURCE_ACQUISITION_CAPABILITY2 = source_acquisition_compatibility_default.profileVersion;
29946
30434
  var daemonRequire = createRequire(import.meta.url);
@@ -31521,10 +32009,18 @@ function attachPiOutputReserve(profile, outputReserveTokens) {
31521
32009
  return profile;
31522
32010
  }
31523
32011
  function attachPiFinalContextAttestor(profile, input) {
31524
- if (!profile?.profileRoot) throw new Error("model_context_attestation_unavailable: managed Pi profile is missing");
32012
+ if (!profile?.profileRoot) {
32013
+ throw stableContextError(
32014
+ "model_context_attestation_unavailable",
32015
+ "managed Pi profile is missing"
32016
+ );
32017
+ }
31525
32018
  const projectInstruction = input.finalAgentInstructionFiles.get("AGENTS.md");
31526
32019
  if (!projectInstruction || !/^[a-f0-9]{64}$/.test(readString(projectInstruction.sha256) ?? "")) {
31527
- throw new Error("model_context_attestation_unavailable: final AGENTS.md receipt is missing");
32020
+ throw stableContextError(
32021
+ "model_context_attestation_unavailable",
32022
+ "final AGENTS.md receipt is missing"
32023
+ );
31528
32024
  }
31529
32025
  const extensionPath = join18(profile.profileRoot, "extensions", MANAGED_PI_FINAL_CONTEXT_ATTESTOR_FILENAME);
31530
32026
  const projectInstructionExtensionPath = join18(
@@ -33087,7 +33583,7 @@ function commandFailureErrorCode(error) {
33087
33583
  const explicit = readString(asRecord(error).code);
33088
33584
  if (explicit && /^[a-z][a-z0-9_]{0,127}$/.test(explicit)) return explicit;
33089
33585
  const message = error instanceof Error ? error.message : String(error);
33090
- const prefix = message.match(/^(codex_managed_mcp_[a-z0-9_]{1,109})(?::|$)/)?.[1];
33586
+ const prefix = message.match(/^(codex_managed_mcp_[a-z0-9_]{1,109})(?::|$)/)?.[1] ?? contextErrorCodeFromMessage(message);
33091
33587
  return prefix && /^[a-z][a-z0-9_]{0,127}$/.test(prefix) ? prefix : null;
33092
33588
  }
33093
33589
  function terminalCommandStatusFromCompletionCheckError(error) {
@@ -35198,9 +35694,7 @@ async function executeRunCommand(config, command) {
35198
35694
  }
35199
35695
  };
35200
35696
  }
35201
- if (!managedMcpProfile || !piAgentDirForContextBudget) {
35202
- throw new Error("model_context_attestation_unavailable: managed Pi profile or Pi config home is missing");
35203
- }
35697
+ assertPiModelContextAttestationInputs(managedMcpProfile, piAgentDirForContextBudget);
35204
35698
  const modelContext = resolvePiRunModelContext(
35205
35699
  piAgentDirForContextBudget,
35206
35700
  readString(process.env.AMASTER_PI_PROVIDER),
@@ -7,7 +7,7 @@ import { homedir, hostname } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { BUILD_SUPPORTED_CAPABILITIES } from "./amaster-runtime-daemon/capability-registry.mjs";
9
9
 
10
- const CONNECTOR_VERSION = "0.1.1-beta.155";
10
+ const CONNECTOR_VERSION = "0.1.1-beta.157";
11
11
 
12
12
  const CONFIG_KEY_MAP = new Map([
13
13
  ["server_url", "AMASTER_EMPLOYEE_SERVER_URL"],
@@ -67,7 +67,13 @@
67
67
  "source_acquisition_prompt_authority_invalid",
68
68
  "source_acquisition_direct_tools_unavailable",
69
69
  "source_acquisition_profile_canonicalization_failed",
70
- "source_acquisition_governed_profile_required"
70
+ "source_acquisition_governed_profile_required",
71
+ "context_output_reserve_exceeds_model_limit",
72
+ "model_context_attestation_unavailable",
73
+ "model_context_fixed_inputs_exceed_budget",
74
+ "native_session_history_attestation_invalid",
75
+ "native_session_history_attestation_unavailable",
76
+ "native_session_history_exceeds_measurement_limit"
71
77
  ],
72
78
  "reasonCodes": [
73
79
  "source_profile_setup_failed",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/employee-runtime-connector",
3
- "version": "0.1.1-beta.155",
3
+ "version": "0.1.1-beta.157",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",