@amaster.ai/employee-runtime-connector 0.1.1-beta.226 → 0.1.1-beta.228

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.
@@ -4314,6 +4314,7 @@ var amasterRuntimeConnectorCreateCommandSchema = external_exports.object({
4314
4314
  var amasterRuntimeConnectorPollCommandsSchema = external_exports.object({
4315
4315
  limit: external_exports.number().int().min(1).max(50).default(1),
4316
4316
  maxConcurrentCommands: external_exports.number().int().min(1).max(50).optional(),
4317
+ maxConcurrentBusinessCommands: external_exports.number().int().min(1).max(3).optional(),
4317
4318
  leaseId: external_exports.string().trim().min(1).optional(),
4318
4319
  leaseSeconds: external_exports.number().int().min(1).max(3600).default(60)
4319
4320
  });
@@ -4606,6 +4607,7 @@ var issueLivePathOwnerRefSchema = external_exports.discriminatedUnion("kind", [
4606
4607
  external_exports.object({ kind: external_exports.literal("external_wait"), id: external_exports.string().min(1) }).strict(),
4607
4608
  external_exports.object({ kind: external_exports.literal("interaction"), id: external_exports.string().uuid() }).strict(),
4608
4609
  external_exports.object({ kind: external_exports.literal("approval"), id: external_exports.string().uuid() }).strict(),
4610
+ external_exports.object({ kind: external_exports.literal("prerequisite_binding"), id: external_exports.string().uuid() }).strict(),
4609
4611
  external_exports.object({ kind: external_exports.literal("dependency"), id: external_exports.string().uuid() }).strict(),
4610
4612
  external_exports.object({ kind: external_exports.literal("recovery_action"), id: external_exports.string().uuid() }).strict()
4611
4613
  ]);
@@ -4616,7 +4618,7 @@ var OWNER_KINDS_BY_PATH = {
4616
4618
  external_wait: ["external_wait"],
4617
4619
  pending_interaction: ["interaction"],
4618
4620
  pending_approval: ["approval"],
4619
- dependency_wait: ["dependency"],
4621
+ dependency_wait: ["dependency", "prerequisite_binding"],
4620
4622
  recovery: ["recovery_action"]
4621
4623
  };
4622
4624
  var issueLivePathTransitionInputSchema = external_exports.object({
@@ -8199,6 +8201,59 @@ var governedInputMutationReadSchema = governedInputReadSchema.extend({
8199
8201
  // ../shared/src/runtime-authority-gate.ts
8200
8202
  var DAY_MS = 24 * 60 * 60 * 1e3;
8201
8203
 
8204
+ // ../shared/src/mirrorx-prerequisite-requirements.ts
8205
+ var decidePrerequisiteRequirementCandidateSchema = external_exports.object({
8206
+ candidateId: external_exports.string().uuid(),
8207
+ expectedCandidateRevision: external_exports.number().int().positive(),
8208
+ expectedResolutionRevision: external_exports.number().int().nonnegative(),
8209
+ idempotencyKey: external_exports.string().trim().min(1).max(200),
8210
+ decision: external_exports.enum(["accept", "reject"]),
8211
+ reason: external_exports.string().trim().max(4e3).optional()
8212
+ }).strict();
8213
+ var boardRequirementDecisionReceiptSchema = external_exports.object({
8214
+ schemaVersion: external_exports.literal("board-requirement-decision-v1"),
8215
+ id: external_exports.string().uuid(),
8216
+ companyId: external_exports.string().uuid(),
8217
+ candidateId: external_exports.string().uuid(),
8218
+ candidateRevision: external_exports.number().int().positive(),
8219
+ interactionId: external_exports.string().uuid(),
8220
+ previousResolutionRevision: external_exports.number().int().nonnegative(),
8221
+ resolutionRevision: external_exports.number().int().positive(),
8222
+ targetIssueId: external_exports.string().uuid(),
8223
+ targetExecutionEpoch: external_exports.number().int().positive(),
8224
+ requirementKind: external_exports.string().min(1),
8225
+ decision: external_exports.enum(["accept", "reject"]),
8226
+ result: external_exports.enum(["accepted_new", "accepted_existing", "rejected"]),
8227
+ requirementId: external_exports.string().uuid().nullable(),
8228
+ requirementRevision: external_exports.number().int().positive().nullable(),
8229
+ idempotencyKey: external_exports.string().min(1),
8230
+ decidedByUserId: external_exports.string().min(1),
8231
+ reason: external_exports.string().nullable(),
8232
+ decidedAt: external_exports.string().datetime({ offset: true })
8233
+ }).strict().superRefine((receipt, ctx) => {
8234
+ const accepted = receipt.decision === "accept";
8235
+ if (receipt.result !== "rejected" !== accepted || receipt.requirementId !== null !== accepted || receipt.requirementRevision !== null !== accepted || receipt.resolutionRevision !== receipt.previousResolutionRevision + 1) {
8236
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Board decision receipt has inconsistent authority or resolution" });
8237
+ }
8238
+ });
8239
+ var prerequisiteRequirementProjectionSchema = external_exports.object({
8240
+ id: external_exports.string().uuid(),
8241
+ revision: external_exports.number().int().positive(),
8242
+ requirementKind: external_exports.string().min(1),
8243
+ targetExecutionEpoch: external_exports.number().int().positive(),
8244
+ requiredResponsibilityKey: external_exports.string().min(1),
8245
+ state: external_exports.enum(["open", "bound", "satisfied"])
8246
+ }).strict();
8247
+ var prerequisiteBindingStateSchema = external_exports.enum(["pending_delivery", "satisfied_parked", "released", "failed", "superseded"]);
8248
+ var prerequisiteBindingProjectionSchema = external_exports.object({
8249
+ id: external_exports.string().uuid(),
8250
+ requirementId: external_exports.string().uuid(),
8251
+ requirementRevision: external_exports.number().int().positive(),
8252
+ prerequisiteIssueId: external_exports.string().uuid(),
8253
+ targetExecutionEpoch: external_exports.number().int().positive(),
8254
+ state: prerequisiteBindingStateSchema
8255
+ }).strict();
8256
+
8202
8257
  // ../shared/src/goal-gap-contract.ts
8203
8258
  var GOAL_GAP_METRIC_KINDS = ["count", "amount", "ratio", "boolean_milestone"];
8204
8259
  var GOAL_GAP_STATUSES = ["open", "satisfied", "invalidated", "unknown"];
@@ -10596,6 +10651,7 @@ var workspaceFinalizeSettlementWarningSchema = external_exports.object({
10596
10651
  message: external_exports.string().trim().min(1).max(2e3)
10597
10652
  });
10598
10653
  var requestConfirmationResultSchema = external_exports.object({
10654
+ prerequisiteRequirementDecision: boardRequirementDecisionReceiptSchema.optional(),
10599
10655
  version: external_exports.literal(1),
10600
10656
  outcome: external_exports.enum([
10601
10657
  "accepted",
@@ -11412,6 +11468,60 @@ var issueDeliveryAcceptanceReadModelSchema = external_exports.object({
11412
11468
  coldStartFactCoverage: issueDeliveryColdStartFactCoverageContextSchema.nullable().default(null)
11413
11469
  }).strict();
11414
11470
 
11471
+ // ../shared/src/ceo-work-carrier.ts
11472
+ var targetSchema = external_exports.object({
11473
+ issueId: external_exports.string().uuid(),
11474
+ executionEpoch: external_exports.number().int().positive()
11475
+ }).strict();
11476
+ var attentionAuthoritySchema = external_exports.object({
11477
+ kind: external_exports.literal("task_attention"),
11478
+ id: external_exports.string().trim().min(1).max(200),
11479
+ revision: external_exports.string().trim().min(1).max(200)
11480
+ }).strict();
11481
+ var proposalSummarySchema = external_exports.string().trim().min(1).max(2e3);
11482
+ var ceoPeriodicWorkCarrierSchema = external_exports.discriminatedUnion("kind", [
11483
+ external_exports.object({ kind: external_exports.literal("independent") }).strict(),
11484
+ external_exports.object({
11485
+ kind: external_exports.literal("prerequisite_requirement_proposal"),
11486
+ target: targetSchema,
11487
+ authorityRef: attentionAuthoritySchema,
11488
+ proposedRequirementKind: external_exports.string().regex(/^[a-z0-9][a-z0-9._-]{0,127}$/u),
11489
+ proposalSummary: proposalSummarySchema
11490
+ }).strict(),
11491
+ external_exports.object({
11492
+ kind: external_exports.literal("prerequisite_delivery"),
11493
+ target: targetSchema,
11494
+ authorityRef: attentionAuthoritySchema,
11495
+ requirementRef: external_exports.object({ id: external_exports.string().uuid(), revision: external_exports.number().int().positive() }).strict(),
11496
+ proposalSummary: proposalSummarySchema.optional()
11497
+ }).strict()
11498
+ ]);
11499
+ var ceoCanonicalWorkSubjectRefSchema = external_exports.discriminatedUnion("kind", [
11500
+ external_exports.object({
11501
+ kind: external_exports.literal("issue_execution"),
11502
+ companyId: external_exports.string().uuid(),
11503
+ issueId: external_exports.string().uuid(),
11504
+ executionEpoch: external_exports.number().int().positive()
11505
+ }).strict(),
11506
+ external_exports.object({
11507
+ kind: external_exports.literal("work_family"),
11508
+ companyId: external_exports.string().uuid(),
11509
+ workFamilyKey: external_exports.string().min(1).max(200)
11510
+ }).strict(),
11511
+ external_exports.object({
11512
+ kind: external_exports.literal("goal_gap"),
11513
+ companyId: external_exports.string().uuid(),
11514
+ goalId: external_exports.string().uuid(),
11515
+ criterionId: external_exports.string().min(1).max(200),
11516
+ gapKey: external_exports.string().min(1).max(200),
11517
+ authorityRevision: external_exports.number().int().nonnegative()
11518
+ }).strict()
11519
+ ]);
11520
+ var ceoCanonicalWorkSubjectSchema = external_exports.object({
11521
+ role: external_exports.enum(["subject", "blocker", "blocked"]),
11522
+ ref: ceoCanonicalWorkSubjectRefSchema
11523
+ }).strict();
11524
+
11415
11525
  // ../shared/src/operating-accounting.ts
11416
11526
  var OPERATING_IDENTITY_MAPPING_VERSION = "operating-identity-v1";
11417
11527
  var OPERATING_OUTCOME_CLASSES = ["internal_enablement", "governed_decision", "external_action", "observed_business_result"];
@@ -11564,7 +11674,10 @@ var ceoPeriodicWorkSourceRefSchema = external_exports.object({
11564
11674
  id: external_exports.string().trim().min(1).max(200),
11565
11675
  revision: external_exports.string().trim().min(1).max(200)
11566
11676
  }).strict();
11677
+ var dependencyIssueSchema = external_exports.object({ id: external_exports.string().uuid(), identifier: external_exports.string().min(1), status: external_exports.string().min(1) }).strict();
11567
11678
  var ceoProjectedBusinessContextSchema = external_exports.object({
11679
+ canonicalSubjects: external_exports.array(ceoCanonicalWorkSubjectSchema).max(100),
11680
+ dependency: external_exports.object({ relationId: external_exports.string().uuid(), relation: external_exports.literal("blocks"), blockerIssue: dependencyIssueSchema, blockedIssue: dependencyIssueSchema }).strict().optional(),
11568
11681
  sourceRef: ceoPeriodicWorkSourceRefSchema,
11569
11682
  projector: external_exports.string().trim().regex(/^[a-z0-9][a-z0-9._-]{0,127}$/u),
11570
11683
  semanticKind: external_exports.enum(CEO_PERIODIC_PROJECTED_SEMANTIC_KINDS),
@@ -11598,7 +11711,7 @@ var ceoProjectedBusinessContextSchema = external_exports.object({
11598
11711
  id: external_exports.string().trim().min(1).max(240),
11599
11712
  revision: external_exports.string().trim().min(1).max(240).optional()
11600
11713
  }).strict()).max(40),
11601
- projectorRevision: external_exports.literal("ceo-business-context-v1"),
11714
+ projectorRevision: external_exports.literal("ceo-business-context-v2"),
11602
11715
  truncated: external_exports.boolean()
11603
11716
  }).strict().superRefine((value, ctx) => {
11604
11717
  if (value.projectionStatus === "unsupported" && !value.unsupportedReason) {
@@ -11719,6 +11832,7 @@ var ceoPeriodicPortfolioAdmissionSchema = external_exports.object({
11719
11832
  }
11720
11833
  });
11721
11834
  var ceoPeriodicDiscoveredWorkInputShape = {
11835
+ carrier: ceoPeriodicWorkCarrierSchema,
11722
11836
  title: external_exports.string().trim().min(1).max(240),
11723
11837
  description: external_exports.string().trim().min(1).max(8e3),
11724
11838
  whyNow: external_exports.string().trim().min(1).max(2e3),
@@ -11778,6 +11892,8 @@ var ceoPeriodicGoalGapCandidateSchema = external_exports.object({
11778
11892
  workClass: external_exports.enum(["internal_enablement", "governed_decision", "external_action", "observed_business_result"])
11779
11893
  }).strict();
11780
11894
  var ceoPeriodicTaskAttentionSchema = external_exports.object({
11895
+ prerequisiteRequirements: external_exports.array(prerequisiteRequirementProjectionSchema),
11896
+ prerequisiteBindings: external_exports.array(prerequisiteBindingProjectionSchema),
11781
11897
  attentionKey: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/u),
11782
11898
  attentionKind: external_exports.enum(["blocked", "review_stalled", "pending_input", "recovery", "due_wait"]),
11783
11899
  sourceIssueId: external_exports.string().uuid(),
@@ -12003,6 +12119,12 @@ var automaticWorkOperationalStateSchema = external_exports.object({
12003
12119
  countsByLifecycle: automaticWorkLifecycleCountsSchema
12004
12120
  }).strict(),
12005
12121
  metrics: external_exports.object({
12122
+ carrierAdmission24h: external_exports.object({
12123
+ sampleSize: external_exports.number().int().nonnegative(),
12124
+ rejectedCount: external_exports.number().int().nonnegative(),
12125
+ rejectionRate: external_exports.number().min(0).max(100),
12126
+ boardProposalCount: external_exports.number().int().nonnegative()
12127
+ }).strict(),
12006
12128
  sampleSize: external_exports.number().int().nonnegative(),
12007
12129
  acceptedOutcomeCount: external_exports.number().int().nonnegative(),
12008
12130
  acceptedOutcomeRate: external_exports.number().min(0).max(100),
@@ -12180,6 +12302,7 @@ var governedBusinessTaskLineageSchema = external_exports.discriminatedUnion("kin
12180
12302
  }).strict(),
12181
12303
  external_exports.object({
12182
12304
  kind: external_exports.literal("ceo_periodic_discovery"),
12305
+ carrier: ceoPeriodicWorkCarrierSchema,
12183
12306
  observationId: external_exports.string().uuid(),
12184
12307
  inputFingerprint: sha256Schema6,
12185
12308
  businessKey: external_exports.string().regex(/^ceo-work-v(1|2|3|4|5):[a-f0-9]{64}$/u),
@@ -12190,13 +12313,7 @@ var governedBusinessTaskLineageSchema = external_exports.discriminatedUnion("kin
12190
12313
  id: external_exports.string().trim().min(1).max(200),
12191
12314
  revision: external_exports.string().trim().min(1).max(200)
12192
12315
  }).strict()).min(1).max(20),
12193
- acceptanceIdentity: external_exports.union([
12194
- ceoPeriodicAcceptanceIdentitySchema,
12195
- external_exports.object({
12196
- deliverableKinds: external_exports.array(external_exports.enum(ISSUE_DELIVERY_ALLOWED_KINDS)).min(1).max(4),
12197
- conditionCodes: external_exports.array(stableIdentitySchema2).min(1).max(10)
12198
- }).strict()
12199
- ]),
12316
+ acceptanceIdentity: ceoPeriodicAcceptanceIdentitySchema,
12200
12317
  acceptanceContract: external_exports.object({
12201
12318
  family: stableIdentitySchema2,
12202
12319
  goalGapContractId: external_exports.string().uuid().nullable(),
@@ -23820,7 +23937,7 @@ function estimatedTokens(chars) {
23820
23937
  }
23821
23938
  function promptContextMode(input) {
23822
23939
  const nativeSession = asRecord(input.nativeSession);
23823
- if (nativeSession.mode === "governed_action_approval" || readString(input.context?.resumeFromRunId) || isRecoveryWakeReason(input.wakeReason) || CONTINUATION_WAKE_PATTERN.test(input.wakeReason ?? "")) return "continuation";
23940
+ if (nativeSession.mode === "governed_action_approval" || input.wakeReason === "continue_task" || readString(input.context?.resumeFromRunId) || isRecoveryWakeReason(input.wakeReason) || CONTINUATION_WAKE_PATTERN.test(input.wakeReason ?? "")) return "continuation";
23824
23941
  if (nativeSession.resume === true || Object.keys(asRecord(input.context?.paperclipContinuationSummary)).length > 0) {
23825
23942
  return "warm";
23826
23943
  }
@@ -23850,12 +23967,54 @@ function commentBodies(context) {
23850
23967
  const comments = Array.isArray(asRecord(context.paperclipWake).comments) ? asRecord(context.paperclipWake).comments : [];
23851
23968
  return comments.map((entry) => readString(asRecord(entry).body)).filter(Boolean);
23852
23969
  }
23853
- function continuationText(context) {
23970
+ function continuationText(context, { omitNextAction = false } = {}) {
23854
23971
  const summary = asRecord(context.paperclipContinuationSummary);
23855
- const body = readString(summary.body);
23972
+ const rawBody = readString(summary.body);
23973
+ const body = omitNextAction ? rawBody?.replace(/(?:^|\n)##[ \t]+Next Action[ \t]*\n[\s\S]*$/iu, "").trimEnd() : rawBody;
23856
23974
  if (!body) return "";
23857
23975
  return [readString(summary.title), body].filter(Boolean).join("\n");
23858
23976
  }
23977
+ function authoritativeContinuationNextAction(context, input) {
23978
+ if (input.wakeReason !== "continue_task") return null;
23979
+ const nextAction = readString(context.nextAction);
23980
+ const sourceRunId = readString(context.sourceRunId);
23981
+ const continuationChainId = readString(context.continuationChainId);
23982
+ const continuationIntentId = readString(context.continuationIntentId);
23983
+ if (!nextAction || !sourceRunId || !continuationChainId || !continuationIntentId) {
23984
+ throw promptBudgetError(
23985
+ "continuation_next_action_unavailable",
23986
+ "Continue Task wake requires an exact next action and complete continuation lineage"
23987
+ );
23988
+ }
23989
+ const rawCheckpointPaths = context.checkpointPaths;
23990
+ const checkpointPaths = rawCheckpointPaths === void 0 ? [] : Array.isArray(rawCheckpointPaths) ? rawCheckpointPaths.map((entry) => readString(entry)) : null;
23991
+ if (checkpointPaths === null || checkpointPaths.length > 20 || checkpointPaths.some((path) => !path) || new Set(checkpointPaths).size !== checkpointPaths.length) {
23992
+ throw promptBudgetError(
23993
+ "continuation_checkpoint_contract_invalid",
23994
+ "Continue Task wake contains invalid checkpoint path authority"
23995
+ );
23996
+ }
23997
+ return {
23998
+ sourceRef: [
23999
+ `run:${sourceRunId}`,
24000
+ `continuation-chain:${continuationChainId}`,
24001
+ `continuation-intent:${continuationIntentId}`
24002
+ ],
24003
+ content: [
24004
+ "The Server persisted this exact instruction when the predecessor Run yielded its execution slot.",
24005
+ "Execute this instruction as the current stage. Do not restart the original task or repeat completed predecessor work unless this instruction explicitly requires it.",
24006
+ "This instruction overrides any generic or inferred Next Action in the Continuation Summary.",
24007
+ ...checkpointPaths.length > 0 ? [
24008
+ `The Connector restored these exact predecessor checkpoint files into the current execution workspace: ${JSON.stringify(checkpointPaths)}.`,
24009
+ "Use only these paths as run-local file continuity evidence; other predecessor workspace files were not carried forward."
24010
+ ] : [
24011
+ "No predecessor run-local files were declared for carry-forward. Use Server-durable documents, artifacts, work products, or the exact instruction below instead of assuming an old workspace file exists."
24012
+ ],
24013
+ "",
24014
+ nextAction
24015
+ ].join("\n")
24016
+ };
24017
+ }
23859
24018
  var CONTINUATION_SUMMARY_TITLE_ALLOWLIST = /* @__PURE__ */ new Set(["Continuation Summary", "Predecessor Execution Summary"]);
23860
24019
  function continuationSectionTitle(context) {
23861
24020
  const title = readString(asRecord(context.paperclipContinuationSummary).title);
@@ -24748,7 +24907,7 @@ function runtimeAuthorizationText(context, mode, {
24748
24907
  const completionContract = !suppressOrdinaryCompletionContract && completionRole && completionDeliverable ? [
24749
24908
  workDisposition.mode === "required" ? "Before the first business mutation, ensure the current required work disposition is recorded. Read-only governed checks may precede it. If no current valid receipt exists, call runtime_action_describe for record_work_disposition and persist exactly one truthful disposition before upsert_document, update_parent, add_comment, create_interaction, publish_delivery_manifest, or any other business mutation. Before ending this run, persist durable progress through Runtime Actions; browser and tool history alone are not durable progress." : "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.",
24750
24909
  firstDocumentCheckpoint,
24751
- continueTaskEnabled ? "Treat one Run as one bounded, durable checkpoint. Once that checkpoint is persisted and another independent research, build, or revision phase remains, call continue_task immediately with a concrete nextAction and stable idempotencyKey instead of keeping the current Run open, then end the run. Do not split an unfinished atomic mutation or claim progress that is not durable. For a future time recheck use schedule_monitor; for an external person or system action use upsert_external_wait. These are mutually exclusive final live paths. Do not call update_parent with status: in_progress." : "If work remains in an ordinary productive run, call update_parent with status: in_progress and a concrete next action so bounded continuation recovery can preserve a live path. Status: todo does not queue a normal continuation from an ordinary productive run. Only a server-issued successful-run handoff recovery may use status: todo, and only according to its exact Recovery Instruction. Otherwise use a supported terminal or waiting disposition."
24910
+ continueTaskEnabled ? "Treat one Run as one bounded, durable checkpoint. Once that checkpoint is persisted and another independent research, build, or revision phase remains, call continue_task immediately with a concrete nextAction and stable idempotencyKey instead of keeping the current Run open, then end the run. If the nextAction depends on files created in this run, include their exact workspace-relative POSIX paths in checkpointPaths; only those files are integrity-checked and carried into the successor workspace. A run-local file omitted from checkpointPaths is not durable continuation state. Do not split an unfinished atomic mutation or claim progress that is not durable. For a future time recheck use schedule_monitor; for an external person or system action use upsert_external_wait. These are mutually exclusive final live paths. Do not call update_parent with status: in_progress." : "If work remains in an ordinary productive run, call update_parent with status: in_progress and a concrete next action so bounded continuation recovery can preserve a live path. Status: todo does not queue a normal continuation from an ordinary productive run. Only a server-issued successful-run handoff recovery may use status: todo, and only according to its exact Recovery Instruction. Otherwise use a supported terminal or waiting disposition."
24752
24911
  ].filter(Boolean).join(" ") : "";
24753
24912
  const businessOutcomeOwnershipContract = businessOutcome.mode === "required" ? evidenceAutoAcceptance ? [
24754
24913
  "Evidence-auto Business Outcome closure is owned by the Server terminal reconciler.",
@@ -25094,6 +25253,7 @@ var COMPANY_INITIALIZATION_PRE_AUTHORITY_SECTIONS = /* @__PURE__ */ new Set([
25094
25253
  "execution_review_contract",
25095
25254
  "governed_business_state",
25096
25255
  "continuation_postcondition_gap",
25256
+ "continuation_next_action",
25097
25257
  "continuation_summary",
25098
25258
  "resolved_dependencies",
25099
25259
  "runtime_delivery_readiness",
@@ -25433,8 +25593,12 @@ function compileCommandPromptWithManifest(input, options = {}) {
25433
25593
  `issue:${input.issueId ?? "unknown"}`,
25434
25594
  ...taskCommentIds.map((commentId) => `comment:${commentId}`)
25435
25595
  ];
25436
- const continuationSummary = continuationText(context);
25437
- const includeTask = mode === "cold" || !continuationSummary && asRecord(input.nativeSession).mode !== "governed_action_approval";
25596
+ const continuationNextAction = authoritativeContinuationNextAction(context, input);
25597
+ const rawContinuationSummary = continuationText(context);
25598
+ const continuationSummary = continuationText(context, {
25599
+ omitNextAction: Boolean(continuationNextAction)
25600
+ });
25601
+ const includeTask = mode === "cold" || !rawContinuationSummary && !continuationNextAction && asRecord(input.nativeSession).mode !== "governed_action_approval";
25438
25602
  const wakeBodies = commentBodies(context);
25439
25603
  const hasTaskCommentIds = Array.isArray(context.paperclipTaskMarkdownCommentIds);
25440
25604
  const commentsDuplicatedByTask = !hasTaskCommentIds && hasTask && wakeBodies.length > 0 && wakeBodies.every((body) => taskText.includes(body));
@@ -25486,6 +25650,7 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
25486
25650
  const rawSections = [
25487
25651
  { name: "recovery_instruction", title: "Recovery Instruction", priority: 100, sourceRef: `run:${input.runId ?? "unknown"}`, content: completeRecoveryInstruction, truncationReason: completeRecoveryInstruction ? null : "mode_selection" },
25488
25652
  { name: "approval_continuation", title: "Approved Runtime Action Continuation", priority: 99, sourceRef: `run:${input.runId ?? "unknown"}`, content: approvalContinuationText(input), truncationReason: mode === "continuation" ? null : "mode_selection" },
25653
+ ...continuationNextAction ? [{ name: "continuation_next_action", title: "Authoritative Continuation Next Action", priority: 100, ...continuationNextAction }] : [],
25489
25654
  { name: "wake_comments", title: wakeDeltaTitle, priority: interactionResolution ? 99 : 95, sourceRef: wakeDeltaSourceRefs, originalContent: wakeDeltaOriginal, content: wakeDeltaContent, truncationReason: commentsSelected ? null : "duplicate_task_context" },
25490
25655
  { 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" },
25491
25656
  ...taskAcceptanceContract ? [{ name: "task_acceptance_contract", title: "Task Acceptance Contract", priority: 100, ...taskAcceptanceContract }] : [],
@@ -26986,6 +27151,17 @@ var PI_TERMINATING_RUNTIME_ACTION_TOOLS = /* @__PURE__ */ new Set([
26986
27151
  "runtime_action.submit",
26987
27152
  "runtime_action.status"
26988
27153
  ]);
27154
+ function continuationCheckpointPaths(value) {
27155
+ if (value === void 0) return [];
27156
+ if (!Array.isArray(value) || value.length < 1 || value.length > 20) return null;
27157
+ const paths = value.map((entry) => readString(entry));
27158
+ if (paths.some((entry) => !entry)) return null;
27159
+ if (new Set(paths).size !== paths.length) return null;
27160
+ for (const path of paths) {
27161
+ if (path.includes("\\") || path.startsWith("/") || /^[A-Za-z]:\//.test(path) || path.split("/").some((segment) => !segment || segment === "." || segment === ".." || segment.startsWith(".")) || path.startsWith("input-attachments/") || ["AGENTS.md", "SOUL.md"].includes(path.split("/").at(-1) ?? "")) return null;
27162
+ }
27163
+ return paths;
27164
+ }
26989
27165
  function approvedMcpInvocationSucceeded(results, invocationId) {
26990
27166
  const approvedInvocationId = readString(invocationId);
26991
27167
  return Boolean(approvedInvocationId && (Array.isArray(results) ? results : []).some((rawResult) => {
@@ -27049,7 +27225,8 @@ function governedMcpToolResult(structuredContent) {
27049
27225
  const continuationExecutionEpoch = readNumber(effectResult.executionEpoch, 0);
27050
27226
  const continuationCount = readNumber(effectResult.continuationCount, 0);
27051
27227
  const maxContinuations = readNumber(effectResult.maxContinuations, 0);
27052
- const exactContinuation = runDisposition === "continuation_scheduled" && continuationChainId && continuationIntentId && continuationWakeId && Number.isSafeInteger(continuationExecutionEpoch) && continuationExecutionEpoch > 0 && Number.isSafeInteger(continuationCount) && continuationCount > 0 && Number.isSafeInteger(maxContinuations) && continuationCount <= maxContinuations;
27228
+ const continuationCheckpointPathList = continuationCheckpointPaths(effectResult.checkpointPaths);
27229
+ const exactContinuation = runDisposition === "continuation_scheduled" && continuationChainId && continuationIntentId && continuationWakeId && Number.isSafeInteger(continuationExecutionEpoch) && continuationExecutionEpoch > 0 && Number.isSafeInteger(continuationCount) && continuationCount > 0 && Number.isSafeInteger(maxContinuations) && continuationCount <= maxContinuations && continuationCheckpointPathList !== null;
27053
27230
  const exactQueuedWakeHandoff = runDisposition === "handoff_existing_live_path" && readString(existingOwner.kind) === "queued_wake" && Boolean(readString(existingOwner.id)) && ["pending_dispatch", "queued", "deferred_issue_execution"].includes(
27054
27231
  readString(existingOwner.status) ?? ""
27055
27232
  ) && Number.isSafeInteger(existingOwnerEpoch) && existingOwnerEpoch > 0 && readString(existingOwner.nextAction) === "end_current_run";
@@ -27071,7 +27248,8 @@ function governedMcpToolResult(structuredContent) {
27071
27248
  wakeId: continuationWakeId,
27072
27249
  executionEpoch: continuationExecutionEpoch,
27073
27250
  count: continuationCount,
27074
- max: maxContinuations
27251
+ max: maxContinuations,
27252
+ ...continuationCheckpointPathList.length > 0 ? { checkpointPaths: continuationCheckpointPathList } : {}
27075
27253
  }
27076
27254
  } : {},
27077
27255
  ...exactQueuedWakeHandoff ? {
@@ -27162,7 +27340,8 @@ function piTerminatingRunDispositionEvidence(results, expected = {}) {
27162
27340
  wakeId: readString(continuation.wakeId),
27163
27341
  executionEpoch: readNumber(continuation.executionEpoch, 0),
27164
27342
  count: readNumber(continuation.count, 0),
27165
- max: readNumber(continuation.max, 0)
27343
+ max: readNumber(continuation.max, 0),
27344
+ ...Array.isArray(continuation.checkpointPaths) ? { checkpointPaths: continuation.checkpointPaths.map((entry) => readString(entry)).filter(Boolean) } : {}
27166
27345
  }
27167
27346
  } : {},
27168
27347
  ...readString(existingOwner.kind) === "queued_wake" && readString(existingOwner.id) ? {
@@ -27841,14 +28020,11 @@ function piRuntimeWebEvidence(event) {
27841
28020
  }
27842
28021
  function parsePiJsonl(stdout) {
27843
28022
  let sessionId = null;
27844
- let errorMessage = null;
27845
28023
  let streamingText = "";
27846
28024
  let sawTurnEnd = false;
27847
28025
  let terminalEventType = null;
27848
28026
  let stopReason = null;
27849
28027
  let hasAssistantOutput = false;
27850
- let nonCleanupErrorCount = 0;
27851
- let nonCleanupErrorMessage = null;
27852
28028
  let terminalEventIndex = null;
27853
28029
  let sawAgentSettled = false;
27854
28030
  let settledEventIndex = null;
@@ -27857,12 +28033,45 @@ function parsePiJsonl(stdout) {
27857
28033
  const mcpToolResults = [];
27858
28034
  const cleanupDiagnostics = [];
27859
28035
  const diagnostics = [];
28036
+ const errorEvents = [];
28037
+ let retry = null;
28038
+ let turnStartIndex = -1;
28039
+ let successfulAssistantIndex = -1;
27860
28040
  const usage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 };
27861
28041
  for (const rawLine of String(stdout ?? "").split(/\r?\n/)) {
27862
28042
  const event = parseJsonLine(rawLine.trim());
27863
28043
  if (!event) continue;
27864
28044
  eventIndex += 1;
27865
28045
  mcpToolResults.push(...piMcpToolResults(event));
28046
+ if (event.type === "turn_start") turnStartIndex = eventIndex;
28047
+ if (event.type === "auto_retry_start") {
28048
+ const message = readString(event.errorMessage);
28049
+ const lastError = errorEvents.at(-1);
28050
+ const matched = Number.isSafeInteger(event.attempt) && event.attempt > 0 && (event.attempt === 1 || event.attempt === retry?.attempt + 1) && turnStartIndex >= 0 && lastError?.provider === true && lastError.message === message && lastError.eventIndex === terminalEventIndex && terminalEventType === "agent_end";
28051
+ const priorErrors = retry && event.attempt === retry.attempt + 1 ? retry.errors : [];
28052
+ retry = matched ? {
28053
+ attempt: event.attempt,
28054
+ startIndex: eventIndex,
28055
+ errors: [...priorErrors, ...errorEvents.filter((error) => error.eventIndex >= turnStartIndex && error.provider && error.message === message)]
28056
+ } : null;
28057
+ continue;
28058
+ }
28059
+ if (event.type === "auto_retry_end") {
28060
+ if (event.success === true && retry && event.attempt === retry.attempt && successfulAssistantIndex > retry.startIndex) {
28061
+ for (const error of retry.errors) error.recoveredAt = eventIndex;
28062
+ diagnostics.push({
28063
+ source: "provider",
28064
+ phase: "retry",
28065
+ severity: "info",
28066
+ code: "pi_provider_retry_recovered",
28067
+ attempt: retry.attempt,
28068
+ recoveredErrorEventCount: retry.errors.length,
28069
+ eventIndex
28070
+ });
28071
+ }
28072
+ retry = null;
28073
+ continue;
28074
+ }
27866
28075
  if (event.type === "session") {
27867
28076
  sessionId = readString(event.sessionId) ?? readString(event.id) ?? sessionId;
27868
28077
  continue;
@@ -27898,9 +28107,12 @@ function parsePiJsonl(stdout) {
27898
28107
  stopReason = readString(event.stopReason ?? event.stop_reason) ?? piNestedMessageStopReason(event) ?? stopReason;
27899
28108
  const terminalError = piStopReasonErrorText(event) ?? piNestedMessageErrorText(event);
27900
28109
  if (terminalError) {
27901
- nonCleanupErrorCount += 1;
27902
- nonCleanupErrorMessage = terminalError;
27903
- errorMessage = terminalError;
28110
+ errorEvents.push({
28111
+ message: terminalError,
28112
+ eventIndex,
28113
+ provider: classifyPiProviderError({ errorMessage: terminalError })?.errorFamily === "transient_upstream"
28114
+ });
28115
+ successfulAssistantIndex = -1;
27904
28116
  if (PI_PROVIDER_PROTOCOL_RE.test(terminalError)) {
27905
28117
  diagnostics.push({
27906
28118
  source: "provider",
@@ -27912,6 +28124,9 @@ function parsePiJsonl(stdout) {
27912
28124
  });
27913
28125
  }
27914
28126
  }
28127
+ if (event.type === "message_end" && asRecord(event.message).role === "assistant" && !terminalError && ["stop", "toolUse"].includes(piMessageStopReason(event.message))) {
28128
+ successfulAssistantIndex = eventIndex;
28129
+ }
27915
28130
  hasAssistantOutput = maybeCapturePiMessage(event, messages, usage) || hasAssistantOutput;
27916
28131
  continue;
27917
28132
  }
@@ -27931,11 +28146,9 @@ function parsePiJsonl(stdout) {
27931
28146
  ...diagnostic,
27932
28147
  eventIndex
27933
28148
  });
27934
- errorMessage = nonCleanupErrorMessage ?? eventError;
27935
28149
  } else {
27936
- nonCleanupErrorCount += 1;
27937
- nonCleanupErrorMessage = eventError;
27938
- errorMessage = eventError;
28150
+ errorEvents.push({ message: eventError, eventIndex, provider: false });
28151
+ successfulAssistantIndex = -1;
27939
28152
  if (PI_PROVIDER_PROTOCOL_RE.test(eventError)) {
27940
28153
  diagnostics.push({
27941
28154
  source: "provider",
@@ -27949,6 +28162,9 @@ function parsePiJsonl(stdout) {
27949
28162
  }
27950
28163
  }
27951
28164
  }
28165
+ const unresolvedErrors = errorEvents.filter((error) => !(Number.isInteger(error.recoveredAt) && terminalEventIndex > error.recoveredAt && sawAgentSettled && settledEventIndex > terminalEventIndex));
28166
+ const nonCleanupErrorCount = unresolvedErrors.length;
28167
+ const errorMessage = unresolvedErrors.at(-1)?.message ?? cleanupDiagnostics.at(-1)?.message ?? null;
27952
28168
  const uniqueMcpToolResults = dedupeGovernedMcpToolResults(mcpToolResults);
27953
28169
  return {
27954
28170
  sessionId,
@@ -29943,7 +30159,7 @@ function assertRequiredTaskAttachmentMaterialized(input, materialized) {
29943
30159
  }
29944
30160
 
29945
30161
  // src/amaster-runtime-daemon.mjs
29946
- var CONNECTOR_VERSION = "0.1.1-beta.226";
30162
+ var CONNECTOR_VERSION = "0.1.1-beta.228";
29947
30163
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
29948
30164
  var daemonRequire = createRequire(import.meta.url);
29949
30165
  var MAX_CHECKPOINT_BYTES = 20 * 1024 * 1024;
@@ -30783,6 +30999,10 @@ function maxConcurrentCommands(config) {
30783
30999
  capabilities: config.capabilities
30784
31000
  });
30785
31001
  }
31002
+ function maxConcurrentBusinessCommands(config) {
31003
+ const configured = Number(config.maxConcurrentCommands);
31004
+ return Number.isInteger(configured) && configured > 0 ? Math.min(configured, 3) : 1;
31005
+ }
30786
31006
  function activeRunCommandCount(config, options = {}) {
30787
31007
  const excludeCommandIds = new Set(readStringArray(options.excludeCommandIds));
30788
31008
  const commandIds = new Set([
@@ -31034,6 +31254,7 @@ async function poll(config) {
31034
31254
  const body = await postJson(config, `/api/amaster/runtime-connectors/${connectorId}/commands/poll`, {
31035
31255
  limit: Math.max(1, limit),
31036
31256
  maxConcurrentCommands: maxCommands,
31257
+ maxConcurrentBusinessCommands: maxConcurrentBusinessCommands(config),
31037
31258
  leaseId: `amaster-${Date.now()}`,
31038
31259
  leaseSeconds: config.leaseSeconds
31039
31260
  });
@@ -34762,10 +34983,36 @@ function safeCheckpointRelativePath(rawPath) {
34762
34983
  function hashFileSha256(filePath) {
34763
34984
  return createHash17("sha256").update(readFileSync18(filePath)).digest("hex");
34764
34985
  }
34986
+ function expectedContinuationCheckpoint(command) {
34987
+ const payload = asRecord(command.payload);
34988
+ const envelope = asRecord(payload.contextEnvelope);
34989
+ const context = asRecord(asRecord(envelope.runDecisionContext).content);
34990
+ if (readString(context.wakeReason) !== "continue_task") return null;
34991
+ const rawPaths = context.checkpointPaths;
34992
+ if (rawPaths === void 0) return null;
34993
+ if (!Array.isArray(rawPaths) || rawPaths.length < 1 || rawPaths.length > 20) {
34994
+ throw new Error("continuation_checkpoint_contract_invalid: checkpointPaths");
34995
+ }
34996
+ const paths = rawPaths.map((entry) => safeCheckpointRelativePath(readString(entry)));
34997
+ if (paths.some((entry) => !entry) || new Set(paths).size !== paths.length) {
34998
+ throw new Error("continuation_checkpoint_contract_invalid: checkpointPaths");
34999
+ }
35000
+ const sourceRunId = readString(context.sourceRunId);
35001
+ const continuationChainId = readString(context.continuationChainId);
35002
+ const continuationIntentId = readString(context.continuationIntentId);
35003
+ if (!sourceRunId || !continuationChainId || !continuationIntentId) {
35004
+ throw new Error("continuation_checkpoint_contract_invalid: lineage");
35005
+ }
35006
+ return { paths, sourceRunId, continuationChainId, continuationIntentId };
35007
+ }
34765
35008
  async function materializeIssueCheckpoint(config, command, workspace) {
34766
35009
  const checkpointDir = issueCheckpointDir(workspace);
34767
35010
  const manifestPath = join17(checkpointDir, "manifest.json");
34768
- if (!existsSync17(manifestPath)) return [];
35011
+ const expectedContinuation = expectedContinuationCheckpoint(command);
35012
+ if (!existsSync17(manifestPath)) {
35013
+ if (expectedContinuation) throw new Error("continuation_checkpoint_unavailable: manifest_missing");
35014
+ return [];
35015
+ }
34769
35016
  let manifest;
34770
35017
  try {
34771
35018
  manifest = asRecord(JSON.parse(readFileSync18(manifestPath, "utf8")));
@@ -34776,11 +35023,21 @@ async function materializeIssueCheckpoint(config, command, workspace) {
34776
35023
  const expiresAt = Date.parse(readString(manifest.expiresAt) ?? "");
34777
35024
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || readString(manifest.issueId) !== commandIssueId(command)) {
34778
35025
  rmSync9(checkpointDir, { recursive: true, force: true });
35026
+ if (expectedContinuation) throw new Error("continuation_checkpoint_unavailable: manifest_expired_or_mismatched");
34779
35027
  return [];
34780
35028
  }
34781
35029
  try {
35030
+ if (readString(manifest.kind) === "continue_task" && !expectedContinuation) {
35031
+ return [];
35032
+ }
34782
35033
  const files = Array.isArray(manifest.files) ? manifest.files : [];
34783
35034
  if (files.length > 20) throw new Error("issue checkpoint manifest exceeds the limit of 20 files");
35035
+ if (expectedContinuation) {
35036
+ const manifestPaths = files.map((entry) => safeCheckpointRelativePath(readString(asRecord(entry).path)));
35037
+ if (readString(manifest.kind) !== "continue_task" || readString(manifest.sourceRunId) !== expectedContinuation.sourceRunId || readString(manifest.continuationChainId) !== expectedContinuation.continuationChainId || readString(manifest.continuationIntentId) !== expectedContinuation.continuationIntentId || manifestPaths.some((entry) => !entry) || manifestPaths.length !== expectedContinuation.paths.length || manifestPaths.some((entry, index) => entry !== expectedContinuation.paths[index])) {
35038
+ throw new Error("continuation_checkpoint_lineage_mismatch");
35039
+ }
35040
+ }
34784
35041
  const filesRoot = realpathSync8(join17(checkpointDir, "files"));
34785
35042
  const workspaceRoot = realpathSync8(workspace.cwd);
34786
35043
  const validated = [];
@@ -34809,22 +35066,45 @@ async function materializeIssueCheckpoint(config, command, workspace) {
34809
35066
  }
34810
35067
  totalBytes += expectedByteSize;
34811
35068
  if (totalBytes > MAX_CHECKPOINT_BYTES) throw new Error("issue checkpoint exceeds the 20 MB restore limit");
34812
- validated.push({ relativePath, source, target });
35069
+ validated.push({
35070
+ relativePath,
35071
+ source,
35072
+ target,
35073
+ expectedSha256,
35074
+ expectedByteSize
35075
+ });
34813
35076
  }
34814
35077
  const materialized = [];
34815
- for (const { relativePath, source, target } of validated) {
34816
- try {
34817
- lstatSync11(target);
34818
- continue;
34819
- } catch (err) {
34820
- if (err?.code !== "ENOENT") throw err;
34821
- }
35078
+ for (const { relativePath, source, target, expectedSha256, expectedByteSize } of validated) {
34822
35079
  mkdirSync9(dirname11(target), { recursive: true });
34823
35080
  const targetParent = realpathSync8(dirname11(target));
34824
35081
  if (!pathWithin3(targetParent, workspaceRoot)) {
34825
35082
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
34826
35083
  }
34827
- copyFileSync2(source, target);
35084
+ let existingTarget = null;
35085
+ try {
35086
+ existingTarget = lstatSync11(target);
35087
+ } catch (err) {
35088
+ if (err?.code !== "ENOENT") throw err;
35089
+ }
35090
+ if (existingTarget && !existingTarget.isFile()) {
35091
+ throw new Error(`issue checkpoint target is not a regular file: ${relativePath}`);
35092
+ }
35093
+ if (existingTarget && existingTarget.size === expectedByteSize && hashFileSha256(target) === expectedSha256) {
35094
+ materialized.push(relativePath);
35095
+ continue;
35096
+ }
35097
+ const temporaryTarget = join17(targetParent, `.${basename8(target)}.checkpoint-${randomUUID()}.tmp`);
35098
+ try {
35099
+ copyFileSync2(source, temporaryTarget);
35100
+ const temporaryStat = lstatSync11(temporaryTarget);
35101
+ if (!temporaryStat.isFile() || temporaryStat.size !== expectedByteSize || hashFileSha256(temporaryTarget) !== expectedSha256) {
35102
+ throw new Error(`issue checkpoint target verification failed: ${relativePath}`);
35103
+ }
35104
+ renameSync10(temporaryTarget, target);
35105
+ } finally {
35106
+ rmSync9(temporaryTarget, { force: true });
35107
+ }
34828
35108
  materialized.push(relativePath);
34829
35109
  }
34830
35110
  if (materialized.length > 0) {
@@ -34846,48 +35126,112 @@ async function materializeIssueCheckpoint(config, command, workspace) {
34846
35126
  throw restoreErr;
34847
35127
  }
34848
35128
  }
34849
- async function saveIssueCheckpoint(config, command, workspace, candidates) {
35129
+ async function saveIssueCheckpoint(config, command, workspace, candidates, options = {}) {
34850
35130
  const checkpointDir = issueCheckpointDir(workspace);
34851
- const filesDir = join17(checkpointDir, "files");
34852
- rmSync9(checkpointDir, { recursive: true, force: true });
35131
+ const commandKey = readString(command.commandId)?.replace(/[^A-Za-z0-9_-]/g, "-") ?? randomUUID();
35132
+ const stagingDir = `${checkpointDir}.tmp-${commandKey}`;
35133
+ const backupDir = `${checkpointDir}.previous-${commandKey}`;
35134
+ const filesDir = join17(stagingDir, "files");
35135
+ rmSync9(stagingDir, { recursive: true, force: true });
35136
+ rmSync9(backupDir, { recursive: true, force: true });
34853
35137
  mkdirSync9(filesDir, { recursive: true });
34854
- const files = [];
34855
- let totalBytes = 0;
34856
- const workspaceRoot = realpathSync8(workspace.cwd);
34857
- for (const candidate of candidates.slice(0, 20)) {
34858
- const relativePath = safeCheckpointRelativePath(candidate.rawPath);
34859
- const source = readString(candidate.filePath);
34860
- if (!relativePath || !source || !existsSync17(source) || !statSync11(source).isFile()) continue;
34861
- const ownedSource = realpathSync8(source);
34862
- if (!pathWithin3(ownedSource, workspaceRoot)) {
34863
- throw new Error(`issue checkpoint source escapes its execution workspace: ${relativePath}`);
34864
- }
34865
- const byteSize = statSync11(ownedSource).size;
34866
- if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) continue;
34867
- const target = resolve16(filesDir, relativePath);
34868
- if (!pathWithin3(target, filesDir)) continue;
34869
- mkdirSync9(dirname11(target), { recursive: true });
34870
- copyFileSync2(ownedSource, target);
34871
- totalBytes += byteSize;
34872
- files.push({ path: relativePath, byteSize, sha256: hashFileSha256(ownedSource) });
34873
- }
34874
- if (files.length === 0) {
34875
- rmSync9(checkpointDir, { recursive: true, force: true });
34876
- return null;
34877
- }
34878
- const manifest = {
34879
- version: 1,
34880
- issueId: commandIssueId(command),
34881
- sourceRunId: commandRunId(command),
34882
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
34883
- expiresAt: new Date(Date.now() + CHECKPOINT_TTL_MS).toISOString(),
34884
- totalBytes,
34885
- files
34886
- };
34887
- writeFileSync11(join17(checkpointDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
35138
+ try {
35139
+ const files = [];
35140
+ let totalBytes = 0;
35141
+ const workspaceRoot = realpathSync8(workspace.cwd);
35142
+ const requiredPaths = Array.isArray(options.requiredPaths) ? options.requiredPaths : [];
35143
+ const selectedCandidates = requiredPaths.length > 0 ? requiredPaths.map((requiredPath) => {
35144
+ const normalized = safeCheckpointRelativePath(requiredPath);
35145
+ if (!normalized) {
35146
+ throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
35147
+ }
35148
+ const sourceCandidate = resolve16(workspaceRoot, normalized);
35149
+ if (!pathWithin3(sourceCandidate, workspaceRoot)) {
35150
+ throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
35151
+ }
35152
+ let sourceStat;
35153
+ try {
35154
+ sourceStat = lstatSync11(sourceCandidate);
35155
+ } catch (err) {
35156
+ if (err?.code === "ENOENT") {
35157
+ throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
35158
+ }
35159
+ throw err;
35160
+ }
35161
+ if (!sourceStat.isFile()) {
35162
+ throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
35163
+ }
35164
+ const ownedSource = realpathSync8(sourceCandidate);
35165
+ if (!pathWithin3(ownedSource, workspaceRoot)) {
35166
+ throw new Error(`issue checkpoint source escapes its execution workspace: ${normalized}`);
35167
+ }
35168
+ return { rawPath: normalized, filePath: ownedSource };
35169
+ }) : candidates.slice(0, 20);
35170
+ for (const candidate of selectedCandidates) {
35171
+ const relativePath = safeCheckpointRelativePath(candidate.rawPath);
35172
+ const source = readString(candidate.filePath);
35173
+ if (!relativePath || !source || !existsSync17(source) || !statSync11(source).isFile()) {
35174
+ if (requiredPaths.length > 0) throw new Error(`continuation_checkpoint_file_unavailable: ${candidate.rawPath}`);
35175
+ continue;
35176
+ }
35177
+ const ownedSource = realpathSync8(source);
35178
+ if (!pathWithin3(ownedSource, workspaceRoot)) {
35179
+ throw new Error(`issue checkpoint source escapes its execution workspace: ${relativePath}`);
35180
+ }
35181
+ const byteSize = statSync11(ownedSource).size;
35182
+ if (byteSize <= 0 || totalBytes + byteSize > MAX_CHECKPOINT_BYTES) {
35183
+ if (requiredPaths.length > 0) throw new Error(`continuation_checkpoint_file_size_invalid: ${relativePath}`);
35184
+ continue;
35185
+ }
35186
+ const target = resolve16(filesDir, relativePath);
35187
+ if (!pathWithin3(target, filesDir)) continue;
35188
+ mkdirSync9(dirname11(target), { recursive: true });
35189
+ copyFileSync2(ownedSource, target);
35190
+ const storedStat = lstatSync11(target);
35191
+ if (!storedStat.isFile() || storedStat.size !== byteSize) {
35192
+ throw new Error(`issue checkpoint copy verification failed: ${relativePath}`);
35193
+ }
35194
+ totalBytes += byteSize;
35195
+ files.push({ path: relativePath, byteSize, sha256: hashFileSha256(target) });
35196
+ }
35197
+ if (files.length === 0) {
35198
+ rmSync9(stagingDir, { recursive: true, force: true });
35199
+ rmSync9(checkpointDir, { recursive: true, force: true });
35200
+ return null;
35201
+ }
35202
+ const manifest = {
35203
+ version: options.continuation ? 2 : 1,
35204
+ issueId: commandIssueId(command),
35205
+ sourceRunId: commandRunId(command),
35206
+ ...options.continuation ? {
35207
+ kind: "continue_task",
35208
+ continuationChainId: options.continuation.chainId,
35209
+ continuationIntentId: options.continuation.intentId
35210
+ } : {},
35211
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
35212
+ expiresAt: new Date(Date.now() + CHECKPOINT_TTL_MS).toISOString(),
35213
+ totalBytes,
35214
+ files
35215
+ };
35216
+ writeFileSync11(join17(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
34888
35217
  `);
34889
- await ingestLog(config, command, "system", "warn", `Saved ${files.length} required deliverable(s) for continuation recovery`, manifest);
34890
- return manifest;
35218
+ const replacingExistingCheckpoint = existsSync17(checkpointDir);
35219
+ if (replacingExistingCheckpoint) renameSync10(checkpointDir, backupDir);
35220
+ try {
35221
+ renameSync10(stagingDir, checkpointDir);
35222
+ } catch (err) {
35223
+ if (replacingExistingCheckpoint && existsSync17(backupDir) && !existsSync17(checkpointDir)) {
35224
+ renameSync10(backupDir, checkpointDir);
35225
+ }
35226
+ throw err;
35227
+ }
35228
+ rmSync9(backupDir, { recursive: true, force: true });
35229
+ await ingestLog(config, command, "system", "info", `Saved ${files.length} issue checkpoint file(s) for continuation`, manifest);
35230
+ return manifest;
35231
+ } catch (err) {
35232
+ rmSync9(stagingDir, { recursive: true, force: true });
35233
+ throw err;
35234
+ }
34891
35235
  }
34892
35236
  function piOutputUsageMetadataMissing(parsed) {
34893
35237
  const usage = parsed?.usage ?? {};
@@ -34960,7 +35304,7 @@ async function executeRunCommand(config, command) {
34960
35304
  agentInstructionFiles: [...finalAgentInstructionFiles.values()].sort((left, right) => left.path.localeCompare(right.path)),
34961
35305
  workspaceProjectInstructionProjection: workspaceProjectInstructionReceipt
34962
35306
  });
34963
- await materializeIssueCheckpoint(config, command, workspace);
35307
+ const materializedCheckpointFiles = await materializeIssueCheckpoint(config, command, workspace);
34964
35308
  const requiredArtifactInputs = await materializeRequiredArtifactInputs(config, command, workspace);
34965
35309
  let materializedAttachments = requiredArtifactInputs;
34966
35310
  try {
@@ -35470,6 +35814,31 @@ async function executeRunCommand(config, command) {
35470
35814
  commandId: command.commandId,
35471
35815
  issueId: commandIssueId(command)
35472
35816
  }) : null;
35817
+ let continuationCheckpoint = null;
35818
+ if (readString(terminalRunDisposition?.disposition) === "continuation_scheduled") {
35819
+ const continuation = asRecord(terminalRunDisposition.continuation);
35820
+ const checkpointPaths = Array.isArray(continuation.checkpointPaths) ? continuation.checkpointPaths.map((entry) => readString(entry)).filter(Boolean) : [];
35821
+ if (checkpointPaths.length > 0) {
35822
+ continuationCheckpoint = await saveIssueCheckpoint(
35823
+ config,
35824
+ command,
35825
+ workspace,
35826
+ workspaceStatus.artifacts.map((artifact) => ({
35827
+ rawPath: artifact.relativePath,
35828
+ filePath: resolve16(cwd, artifact.relativePath)
35829
+ })),
35830
+ {
35831
+ requiredPaths: checkpointPaths,
35832
+ continuation: {
35833
+ chainId: readString(continuation.chainId),
35834
+ intentId: readString(continuation.intentId)
35835
+ }
35836
+ }
35837
+ );
35838
+ } else {
35839
+ await clearIssueCheckpoint(config, command, workspace, "continue_task_without_checkpoint_paths");
35840
+ }
35841
+ }
35473
35842
  if (terminalRunDisposition) {
35474
35843
  const disposition = readString(terminalRunDisposition.disposition);
35475
35844
  parsed.summary = disposition === "handoff_existing_live_path" ? "This run handed control to the existing queued live path and ended normally without creating a duplicate interaction." : disposition === "continuation_scheduled" ? "A bounded continuation was persisted; this run ended normally so another queued command can use the released execution slot." : disposition === "waiting_human" ? "The requested human interaction was persisted; this run ended normally and will resume only under its continuation policy." : disposition === "waiting_external" ? "The external wait was persisted; this run ended normally and will resume only after the recorded condition is satisfied." : "The monitor schedule was persisted; this run ended normally and will resume only at the scheduled check.";
@@ -35716,6 +36085,14 @@ async function executeRunCommand(config, command) {
35716
36085
  ...costUsage ? { costUsage } : {},
35717
36086
  ...terminalTextRepair ? { terminalTextRepair: terminalTextRepair.audit } : {},
35718
36087
  ...terminalRunDisposition ? { terminalRunDisposition } : {},
36088
+ ...continuationCheckpoint ? {
36089
+ continuationCheckpoint: {
36090
+ fileCount: continuationCheckpoint.files.length,
36091
+ totalBytes: continuationCheckpoint.totalBytes,
36092
+ paths: continuationCheckpoint.files.map((file) => file.path)
36093
+ }
36094
+ } : {},
36095
+ ...materializedCheckpointFiles.length > 0 ? { materializedCheckpointFiles } : {},
35719
36096
  ...runtimeArtifacts.length > 0 ? { runtimeArtifacts } : {},
35720
36097
  ...runtimeDocuments.length > 0 ? { runtimeDocuments } : {},
35721
36098
  outputTelemetry,
@@ -36023,6 +36400,7 @@ async function runOnce(config) {
36023
36400
  const polled = await postJson(config, `/api/amaster/runtime-connectors/${config.connectorId}/commands/poll`, {
36024
36401
  limit: Math.max(1, availableSlots),
36025
36402
  maxConcurrentCommands: maxConcurrentCommands(config),
36403
+ maxConcurrentBusinessCommands: maxConcurrentBusinessCommands(config),
36026
36404
  leaseId,
36027
36405
  leaseSeconds: config.leaseSeconds
36028
36406
  });
@@ -36059,6 +36437,7 @@ async function dispatchAvailableCommands(config, options = {}) {
36059
36437
  const polled = await postJson(config, `/api/amaster/runtime-connectors/${config.connectorId}/commands/poll`, {
36060
36438
  limit: Math.max(1, availableSlots),
36061
36439
  maxConcurrentCommands: maxConcurrentCommands(config),
36440
+ maxConcurrentBusinessCommands: maxConcurrentBusinessCommands(config),
36062
36441
  leaseId,
36063
36442
  leaseSeconds: config.leaseSeconds
36064
36443
  });
@@ -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.226";
10
+ const CONNECTOR_VERSION = "0.1.1-beta.228";
11
11
 
12
12
  const CONFIG_KEY_MAP = new Map([
13
13
  ["server_url", "AMASTER_EMPLOYEE_SERVER_URL"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amaster.ai/employee-runtime-connector",
3
- "version": "0.1.1-beta.226",
3
+ "version": "0.1.1-beta.228",
4
4
  "description": "MirrorX runtime connector CLI and daemon",
5
5
  "license": "MIT",
6
6
  "type": "module",