@amaster.ai/employee-runtime-connector 0.1.5 → 0.1.7

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.
@@ -4333,7 +4333,8 @@ var ISSUE_RECOVERY_ACTION_KINDS = [
4333
4333
  "active_run_watchdog",
4334
4334
  "issue_graph_liveness",
4335
4335
  "finalization_operator",
4336
- "initialization_no_progress"
4336
+ "initialization_no_progress",
4337
+ "runtime_delivery_exhausted"
4337
4338
  ];
4338
4339
  var ISSUE_PROGRESS_FINDING_CODES = [
4339
4340
  "terminal",
@@ -5345,7 +5346,7 @@ var mirrorxGoalContextDeliveryReceiptSchema = external_exports.object({
5345
5346
  promptSha256: external_exports.string().regex(/^[a-f0-9]{64}$/)
5346
5347
  }).strict();
5347
5348
  var amasterRuntimeConnectorCommandResultSchema = external_exports.object({
5348
- sessionId: external_exports.string().max(2048).optional(),
5349
+ sessionId: external_exports.string().max(2048).nullable().optional(),
5349
5350
  goalContextDeliveryReceipt: mirrorxGoalContextDeliveryReceiptSchema.optional()
5350
5351
  }).catchall(external_exports.unknown());
5351
5352
  var amasterRuntimeConnectorCompleteCommandSchema = external_exports.object({
@@ -5440,6 +5441,52 @@ var amasterRuntimeConnectorWorkspaceStatusIngestSchema = external_exports.object
5440
5441
  metadata: external_exports.record(external_exports.unknown()).default({})
5441
5442
  });
5442
5443
 
5444
+ // ../shared/src/external-wait-reasons.ts
5445
+ var EXTERNAL_WAIT_REASON_CODES = {
5446
+ browserMfaRequired: "browser_mfa_required",
5447
+ browserCaptchaRequired: "browser_captcha_required",
5448
+ browserSsoHandoffRequired: "browser_sso_handoff_required",
5449
+ browserHumanSessionHandoffRequired: "browser_human_session_handoff_required",
5450
+ wikiOperationContextMissing: "wiki_operation_context_missing",
5451
+ agentInsufficientBalance: "agent_insufficient_balance",
5452
+ heligeInsufficientBalance: "helige_insufficient_balance",
5453
+ businessDataSourceUnavailable: "business_data_source_unavailable",
5454
+ customerInputPending: "customer_input_pending",
5455
+ externalInputPending: "external_input_pending",
5456
+ externalApprovalPending: "external_approval_pending",
5457
+ externalDependencyPending: "external_dependency_pending",
5458
+ heligeGenerationInProgress: "helige_generation_in_progress",
5459
+ heligeNewTurnNotObserved: "helige_new_turn_not_observed",
5460
+ heligeGenerationStatusUnavailable: "helige_generation_status_unavailable"
5461
+ };
5462
+ var BROWSER_HUMAN_SESSION_HANDOFF_REASON_CODES = [
5463
+ EXTERNAL_WAIT_REASON_CODES.browserMfaRequired,
5464
+ EXTERNAL_WAIT_REASON_CODES.browserCaptchaRequired,
5465
+ EXTERNAL_WAIT_REASON_CODES.browserSsoHandoffRequired,
5466
+ EXTERNAL_WAIT_REASON_CODES.browserHumanSessionHandoffRequired
5467
+ ];
5468
+ var GENERIC_EXTERNAL_INPUT_WAIT_REASON_CODES = [
5469
+ EXTERNAL_WAIT_REASON_CODES.customerInputPending,
5470
+ EXTERNAL_WAIT_REASON_CODES.externalInputPending
5471
+ ];
5472
+ var GENERIC_EXTERNAL_APPROVAL_WAIT_REASON_CODES = [
5473
+ EXTERNAL_WAIT_REASON_CODES.externalApprovalPending
5474
+ ];
5475
+ var GENERIC_EXTERNAL_DEPENDENCY_WAIT_REASON_CODES = [
5476
+ EXTERNAL_WAIT_REASON_CODES.externalDependencyPending
5477
+ ];
5478
+ var HELIGE_GENERATION_MONITOR_REASON_CODES = [
5479
+ EXTERNAL_WAIT_REASON_CODES.heligeGenerationInProgress,
5480
+ EXTERNAL_WAIT_REASON_CODES.heligeNewTurnNotObserved,
5481
+ EXTERNAL_WAIT_REASON_CODES.heligeGenerationStatusUnavailable
5482
+ ];
5483
+
5484
+ // ../shared/src/amaster-billing-recovery.ts
5485
+ var BILLING_WAIT_REASONS = /* @__PURE__ */ new Set([
5486
+ EXTERNAL_WAIT_REASON_CODES.heligeInsufficientBalance,
5487
+ EXTERNAL_WAIT_REASON_CODES.agentInsufficientBalance
5488
+ ]);
5489
+
5443
5490
  // ../shared/src/validators/mirrorx-agent-sessions.ts
5444
5491
  var mirrorxAgentSessionGroupNameSchema = external_exports.string().trim().min(1).max(80);
5445
5492
  var MIRRORX_AGENT_SESSION_GROUP_LIMIT = 100;
@@ -8742,6 +8789,9 @@ function canonicalizeTaskResourceLocator(value) {
8742
8789
  if (parsed.username || parsed.password) {
8743
8790
  return { ok: false, code: "userinfo_forbidden" };
8744
8791
  }
8792
+ if (parsed.toString().length > 2048) {
8793
+ return { ok: false, code: "locator_too_long" };
8794
+ }
8745
8795
  if (parsed.hash) {
8746
8796
  return { ok: false, code: "fragment_forbidden" };
8747
8797
  }
@@ -9068,8 +9118,212 @@ var mirrorxDiscoveryTriageCandidateInputSchema = external_exports.object({
9068
9118
  }
9069
9119
  });
9070
9120
 
9121
+ // ../shared/src/task-resource-input.ts
9122
+ var ATTACHMENT_PREPARATION_VERSION = "attachment-preparation-v1";
9123
+ var ORIGINAL_ONLY_PARSER_VERSION = "original-only-v1";
9124
+ var TASK_RESOURCE_INPUT_STATES = [
9125
+ "declared",
9126
+ "preparing",
9127
+ "prepared",
9128
+ "blocked",
9129
+ "retired"
9130
+ ];
9131
+ var TASK_RESOURCE_LOCATOR_MAX_LENGTH = 2048;
9132
+ var ATTACHMENT_PREPARATION_FORMATS = ["text", "pdf", "docx", "xlsx", "pptx"];
9133
+ var BROWSER_CREDENTIAL_ROLES = ["username", "password"];
9134
+ var ONBOARDING_RESOURCE_LINK_PROVIDERS = [
9135
+ "feishu",
9136
+ "dingtalk",
9137
+ "wechat_work",
9138
+ "notion",
9139
+ "github_gitlab",
9140
+ "crm",
9141
+ "erp",
9142
+ "custom",
9143
+ "other"
9144
+ ];
9145
+ var ONBOARDING_RESOURCE_LINK_CREATED_FROM = [
9146
+ "current_system",
9147
+ "manual_link",
9148
+ "legacy_document_link"
9149
+ ];
9150
+ var sha256Schema5 = external_exports.string().regex(/^[a-f0-9]{64}$/u);
9151
+ var exactOriginSchema = external_exports.string().url().superRefine((value, context) => {
9152
+ const url = new URL(value);
9153
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash || value !== url.origin) {
9154
+ context.addIssue({
9155
+ code: external_exports.ZodIssueCode.custom,
9156
+ message: "Origin must be an exact credential-free HTTPS origin"
9157
+ });
9158
+ }
9159
+ });
9160
+ var taskResourceLocatorSchema = external_exports.string().trim().min(1).max(TASK_RESOURCE_LOCATOR_MAX_LENGTH).transform((value, context) => {
9161
+ const result2 = canonicalizeTaskResourceLocator(value);
9162
+ if (!result2.ok) {
9163
+ context.addIssue({
9164
+ code: external_exports.ZodIssueCode.custom,
9165
+ message: `Task resource locator rejected: ${result2.code}`
9166
+ });
9167
+ return external_exports.NEVER;
9168
+ }
9169
+ return result2.locator;
9170
+ });
9171
+ var userSuppliedResourceLinkIntakeSchema = external_exports.object({
9172
+ sourceMessageId: external_exports.string().trim().min(1).max(255),
9173
+ targetIssueId: external_exports.string().uuid(),
9174
+ targetKey: external_exports.string().trim().min(1).max(500),
9175
+ body: external_exports.string().max(1e5),
9176
+ primaryLocator: taskResourceLocatorSchema.optional()
9177
+ }).strict();
9178
+ var onboardingResourceLinkSchema = external_exports.object({
9179
+ clientKey: external_exports.string().trim().min(1).max(128),
9180
+ kind: external_exports.literal("web"),
9181
+ provider: external_exports.enum(ONBOARDING_RESOURCE_LINK_PROVIDERS),
9182
+ displayName: external_exports.string().trim().min(1).max(500),
9183
+ locator: taskResourceLocatorSchema,
9184
+ scope: external_exports.string().trim().max(2e3).default(""),
9185
+ accessHint: external_exports.enum(["public", "may_require_auth", "unknown"]),
9186
+ criticality: external_exports.enum(["critical", "supporting"]),
9187
+ declaredPageLocators: external_exports.array(taskResourceLocatorSchema).max(100).default([]),
9188
+ createdFrom: external_exports.enum(ONBOARDING_RESOURCE_LINK_CREATED_FROM)
9189
+ }).strict().superRefine((resource, context) => {
9190
+ if (typeof resource.locator !== "string") return;
9191
+ const resourceOrigin = new URL(resource.locator).origin;
9192
+ resource.declaredPageLocators.forEach((locator, index) => {
9193
+ if (typeof locator === "string" && new URL(locator).origin !== resourceOrigin) {
9194
+ context.addIssue({
9195
+ code: external_exports.ZodIssueCode.custom,
9196
+ path: ["declaredPageLocators", index],
9197
+ message: "Declared page locator must use the same origin as the resource link"
9198
+ });
9199
+ }
9200
+ });
9201
+ });
9202
+ var attachmentPreparationReceiptSchema = external_exports.object({
9203
+ parserVersion: external_exports.literal(ATTACHMENT_PREPARATION_VERSION),
9204
+ originalSha256: sha256Schema5,
9205
+ sidecarSha256: sha256Schema5,
9206
+ originalBytes: external_exports.number().int().nonnegative(),
9207
+ sidecarBytes: external_exports.number().int().positive(),
9208
+ format: external_exports.enum(ATTACHMENT_PREPARATION_FORMATS),
9209
+ truncated: external_exports.boolean(),
9210
+ metadata: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]))
9211
+ }).strict();
9212
+ var taskResourceInputBaseSchema = external_exports.object({
9213
+ inputFingerprint: external_exports.string().trim().min(1).max(255),
9214
+ state: external_exports.enum(TASK_RESOURCE_INPUT_STATES),
9215
+ failureCode: external_exports.string().trim().min(1).max(160).nullable().optional()
9216
+ });
9217
+ var taskResourceInputSchema = external_exports.discriminatedUnion("kind", [
9218
+ taskResourceInputBaseSchema.extend({
9219
+ kind: external_exports.literal("link"),
9220
+ displayName: external_exports.string().trim().min(1).max(255),
9221
+ locator: external_exports.string().url().max(TASK_RESOURCE_LOCATOR_MAX_LENGTH),
9222
+ scope: external_exports.string().trim().min(1).max(2e3),
9223
+ preparationReceipt: external_exports.null().optional()
9224
+ }).strict(),
9225
+ taskResourceInputBaseSchema.extend({
9226
+ kind: external_exports.literal("attachment"),
9227
+ attachmentId: external_exports.string().uuid(),
9228
+ assetId: external_exports.string().uuid(),
9229
+ byteSize: external_exports.number().int().nonnegative(),
9230
+ sha256: sha256Schema5,
9231
+ parserVersion: external_exports.string().trim().min(1).max(120).nullable().optional(),
9232
+ sidecarAssetId: external_exports.string().uuid().nullable().optional(),
9233
+ preparationReceipt: attachmentPreparationReceiptSchema.nullable().optional()
9234
+ }).strict()
9235
+ ]).superRefine((value, context) => {
9236
+ if (value.kind !== "attachment") return;
9237
+ const originalOnly = value.parserVersion === ORIGINAL_ONLY_PARSER_VERSION;
9238
+ if (value.state === "prepared" && !value.preparationReceipt && !originalOnly) {
9239
+ context.addIssue({
9240
+ code: external_exports.ZodIssueCode.custom,
9241
+ path: ["preparationReceipt"],
9242
+ message: "Prepared attachment input requires a complete preparation receipt"
9243
+ });
9244
+ }
9245
+ if (originalOnly && (value.preparationReceipt || value.sidecarAssetId)) {
9246
+ context.addIssue({
9247
+ code: external_exports.ZodIssueCode.custom,
9248
+ path: ["preparationReceipt"],
9249
+ message: "Original-only attachment input must not carry a preparation sidecar"
9250
+ });
9251
+ }
9252
+ if (value.preparationReceipt && (value.preparationReceipt.originalSha256 !== value.sha256 || value.preparationReceipt.originalBytes !== value.byteSize)) {
9253
+ context.addIssue({
9254
+ code: external_exports.ZodIssueCode.custom,
9255
+ path: ["preparationReceipt"],
9256
+ message: "Preparation receipt must match the exact original attachment"
9257
+ });
9258
+ }
9259
+ });
9260
+ var browserCredentialRefAuthoritySchema = external_exports.object({
9261
+ version: external_exports.literal(1),
9262
+ companyId: external_exports.string().uuid(),
9263
+ issueId: external_exports.string().uuid(),
9264
+ runId: external_exports.string().uuid(),
9265
+ commandId: external_exports.string().uuid(),
9266
+ interactionId: external_exports.string().uuid(),
9267
+ credentialKey: external_exports.string().trim().min(1).max(255),
9268
+ credentialVersion: external_exports.number().int().positive(),
9269
+ credentialRole: external_exports.enum(BROWSER_CREDENTIAL_ROLES),
9270
+ targetOrigin: exactOriginSchema,
9271
+ authenticationOrigin: exactOriginSchema,
9272
+ bindingId: external_exports.string().uuid(),
9273
+ browserLeaseId: external_exports.string().regex(/^browser-credential-(?:auth-write|agent-read)-[0-9a-f-]{36}$/iu)
9274
+ }).strict();
9275
+ var browserCredentialRefConsumeSchema = browserCredentialRefAuthoritySchema.extend({
9276
+ controlSemantic: external_exports.enum(["username", "email", "password"])
9277
+ }).strict();
9278
+ var runtimeWebEvidenceReceiptSchema = external_exports.object({
9279
+ issueId: external_exports.string().uuid(),
9280
+ runId: external_exports.string().uuid(),
9281
+ commandId: external_exports.string().uuid(),
9282
+ toolCallId: external_exports.string().trim().min(1).max(255),
9283
+ requestedUrl: external_exports.string().url().max(2048),
9284
+ finalUrl: external_exports.string().url().max(2048),
9285
+ capturedAt: external_exports.string().datetime({ offset: true }),
9286
+ mediaType: external_exports.string().trim().min(1).max(255),
9287
+ truncated: external_exports.boolean(),
9288
+ contentSha256: sha256Schema5,
9289
+ observedChars: external_exports.number().int().nonnegative(),
9290
+ observedBytes: external_exports.number().int().nonnegative(),
9291
+ evidenceAssetId: external_exports.string().uuid().nullable().optional(),
9292
+ taskResourceBinding: external_exports.object({
9293
+ inputId: external_exports.string().uuid(),
9294
+ inputFingerprint: external_exports.string().trim().min(1).max(255),
9295
+ retrievalRevision: external_exports.number().int().positive()
9296
+ }).strict().optional()
9297
+ }).strict();
9298
+ var runtimeWebEvidenceIngestSchema = external_exports.object({
9299
+ companyId: external_exports.string().uuid(),
9300
+ issueId: external_exports.string().uuid(),
9301
+ runId: external_exports.string().uuid(),
9302
+ commandId: external_exports.string().uuid(),
9303
+ toolCallId: external_exports.string().trim().min(1).max(255),
9304
+ requestedUrl: external_exports.string().url().max(8192),
9305
+ finalUrl: external_exports.string().url().max(8192),
9306
+ capturedAt: external_exports.string().datetime({ offset: true }),
9307
+ mediaType: external_exports.string().trim().min(1).max(255),
9308
+ normalizedText: external_exports.string().max(2e6),
9309
+ truncated: external_exports.boolean().optional(),
9310
+ taskResourceBinding: external_exports.object({
9311
+ inputId: external_exports.string().uuid(),
9312
+ inputFingerprint: external_exports.string().trim().min(1).max(255),
9313
+ retrievalRevision: external_exports.number().int().positive()
9314
+ }).strict().optional()
9315
+ }).strict();
9316
+ var createTaskResourceLinkRequestSchema = external_exports.object({
9317
+ displayName: external_exports.string().trim().min(1).max(500),
9318
+ locator: taskResourceLocatorSchema,
9319
+ scope: external_exports.string().trim().min(1).max(2e3),
9320
+ criticality: external_exports.enum(["critical", "supporting"]).default("supporting")
9321
+ }).strict();
9322
+ var finalizeTaskResourceAttachmentRequestSchema = external_exports.object({ inputId: external_exports.string().uuid() }).strict();
9323
+ var createTaskResourceAttachmentRequestSchema = external_exports.object({ attachmentId: external_exports.string().uuid() }).strict();
9324
+
9071
9325
  // ../shared/src/mirrorx-discovery-governance.ts
9072
- var sha256Schema5 = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
9326
+ var sha256Schema6 = external_exports.string().regex(/^sha256:[a-f0-9]{64}$/);
9073
9327
  var positiveBoundedInteger = (max) => external_exports.number().int().positive().max(max);
9074
9328
  var mirrorxDiscoveryPromotionModeSchema = external_exports.enum(["shadow", "board_gated"]);
9075
9329
  var customerFeedbackSourceBindingV1Schema = external_exports.object({
@@ -9077,7 +9331,7 @@ var customerFeedbackSourceBindingV1Schema = external_exports.object({
9077
9331
  connectionId: external_exports.string().uuid(),
9078
9332
  providerKey: external_exports.string().trim().min(1).max(160),
9079
9333
  objectType: external_exports.literal("customer_feedback"),
9080
- queryScopeHash: sha256Schema5,
9334
+ queryScopeHash: sha256Schema6,
9081
9335
  wikiId: external_exports.string().trim().min(1).max(160),
9082
9336
  wikiSpaceSlug: external_exports.string().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),
9083
9337
  wikiPagePath: external_exports.string().trim().min(1).max(500)
@@ -9098,48 +9352,72 @@ var customerFeedbackDiscoveryConfigurationV1Schema = external_exports.object({
9098
9352
  var openConnectorDiscoverySourceSchema = external_exports.object({
9099
9353
  service: external_exports.string().trim().min(1).max(128),
9100
9354
  connectionName: external_exports.string().trim().min(1).max(256).nullable(),
9101
- connectionKeyHash: sha256Schema5,
9355
+ connectionKeyHash: sha256Schema6,
9102
9356
  actions: external_exports.array(external_exports.object({
9103
9357
  actionId: external_exports.string().trim().min(1).max(256),
9104
- guideHash: sha256Schema5,
9358
+ guideHash: sha256Schema6,
9105
9359
  inputSchema: external_exports.record(external_exports.string(), external_exports.unknown())
9106
9360
  }).strict()).min(1).max(20)
9107
9361
  }).strict();
9108
9362
  var discoveryReadGrantsSchema = external_exports.array(external_exports.object({
9109
9363
  service: external_exports.string().trim().min(1).max(128),
9110
9364
  actionId: external_exports.string().trim().min(1).max(256),
9111
- guideHash: sha256Schema5
9365
+ guideHash: sha256Schema6
9112
9366
  }).strict()).max(100);
9113
9367
  var discoveryResearchSourceBindingV1Schema = external_exports.object({
9114
9368
  version: external_exports.literal(1),
9115
9369
  connectionId: external_exports.string().uuid(),
9116
9370
  providerKey: external_exports.string().trim().min(1).max(160),
9117
9371
  objectType: external_exports.string().trim().min(1).max(160).regex(/^[a-z0-9][a-z0-9._-]*$/),
9118
- queryScopeHash: sha256Schema5,
9372
+ queryScopeHash: sha256Schema6,
9119
9373
  openConnector: openConnectorDiscoverySourceSchema.optional()
9120
9374
  }).strict();
9121
9375
  var openConnectorDiscoveryActionV2Schema = external_exports.object({
9122
9376
  actionId: external_exports.string().trim().min(1).max(256),
9123
- guideHash: sha256Schema5,
9377
+ guideHash: sha256Schema6,
9124
9378
  inputSchema: external_exports.record(external_exports.string(), external_exports.unknown()),
9125
9379
  outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()),
9126
9380
  followUpActions: external_exports.array(external_exports.object({
9127
9381
  actionId: external_exports.string().trim().min(1).max(256)
9128
9382
  }).strict()).max(20)
9129
9383
  }).strict();
9130
- var discoveryResearchSourceBindingV2Schema = external_exports.object({
9384
+ var governedProviderDiscoverySourceBindingV2Schema = external_exports.object({
9131
9385
  version: external_exports.literal(2),
9132
9386
  connectionId: external_exports.string().uuid(),
9133
9387
  providerKey: external_exports.string().trim().min(1).max(160),
9134
9388
  objectType: external_exports.string().trim().min(1).max(160).regex(/^[a-z0-9][a-z0-9._-]*$/),
9135
- queryScopeHash: sha256Schema5,
9389
+ queryScopeHash: sha256Schema6,
9136
9390
  openConnector: external_exports.object({
9137
9391
  service: external_exports.string().trim().min(1).max(128),
9138
9392
  connectionName: external_exports.string().trim().min(1).max(256).nullable(),
9139
- connectionKeyHash: sha256Schema5,
9393
+ connectionKeyHash: sha256Schema6,
9140
9394
  actions: external_exports.array(openConnectorDiscoveryActionV2Schema).min(1).max(20)
9141
9395
  }).strict()
9142
9396
  }).strict();
9397
+ var taskResourceDiscoverySourceBindingV1Schema = external_exports.object({
9398
+ version: external_exports.literal(3),
9399
+ sourceKind: external_exports.literal("task_resource"),
9400
+ connectionId: external_exports.string().uuid(),
9401
+ inputId: external_exports.string().uuid(),
9402
+ targetIssueId: external_exports.string().uuid(),
9403
+ inputFingerprint: external_exports.string().trim().min(1).max(255),
9404
+ locator: external_exports.string().url().max(TASK_RESOURCE_LOCATOR_MAX_LENGTH),
9405
+ locatorFingerprint: external_exports.string().regex(/^[a-f0-9]{64}$/u),
9406
+ intent: external_exports.enum(["primary", "supporting"]),
9407
+ sourceMessageId: external_exports.string().trim().min(1).max(255),
9408
+ suppliedBy: external_exports.object({
9409
+ kind: external_exports.literal("user"),
9410
+ id: external_exports.string().trim().min(1).max(200)
9411
+ }).strict(),
9412
+ suppliedAt: external_exports.string().datetime({ offset: true }),
9413
+ retrievalRevision: external_exports.number().int().positive(),
9414
+ authority: external_exports.literal("user_supplied_context_only"),
9415
+ openConnector: external_exports.never().optional()
9416
+ }).strict();
9417
+ var discoveryResearchSourceBindingV2Schema = external_exports.union([
9418
+ governedProviderDiscoverySourceBindingV2Schema,
9419
+ taskResourceDiscoverySourceBindingV1Schema
9420
+ ]);
9143
9421
  var discoveryResearchBriefV1Schema = external_exports.object({
9144
9422
  version: external_exports.literal(1),
9145
9423
  objective: external_exports.string().trim().min(1).max(2e3),
@@ -9167,7 +9445,7 @@ var frozenDiscoveryResearchV1Schema = external_exports.object({
9167
9445
  goalId: external_exports.string().uuid(),
9168
9446
  goalRevision: external_exports.string().trim().min(1).max(160),
9169
9447
  criterionIndex: external_exports.number().int().min(0).max(1e3),
9170
- sourceBindingRevision: sha256Schema5,
9448
+ sourceBindingRevision: sha256Schema6,
9171
9449
  sourceBinding: discoveryResearchSourceBindingV1Schema,
9172
9450
  maxRuntimeMs: positiveBoundedInteger(864e5),
9173
9451
  maxProviderReads: positiveBoundedInteger(100),
@@ -9185,7 +9463,7 @@ var discoveryResearchTargetV2Schema = external_exports.object({
9185
9463
  gapId: external_exports.string().uuid().nullable(),
9186
9464
  gapAuthorityRevision: external_exports.number().int().positive().nullable(),
9187
9465
  selectionRevision: external_exports.number().int().positive(),
9188
- candidateSetHash: sha256Schema5,
9466
+ candidateSetHash: sha256Schema6,
9189
9467
  resetReason: external_exports.enum(["goal_revision_changed", "candidate_set_changed"]).nullable()
9190
9468
  }).strict().superRefine((value, ctx) => {
9191
9469
  if (value.kind === "gap" && (!value.gapId || !value.gapAuthorityRevision)) {
@@ -9204,7 +9482,7 @@ var frozenDiscoveryResearchV2Schema = external_exports.object({
9204
9482
  goalId: external_exports.string().uuid(),
9205
9483
  goalRevision: external_exports.string().trim().min(1).max(160),
9206
9484
  target: discoveryResearchTargetV2Schema,
9207
- sourceBindingRevision: sha256Schema5,
9485
+ sourceBindingRevision: sha256Schema6,
9208
9486
  sourceBinding: discoveryResearchSourceBindingV2Schema,
9209
9487
  coverageMode: external_exports.literal("targeted_goal_criterion"),
9210
9488
  maxProviderReads: positiveBoundedInteger(100),
@@ -9245,12 +9523,12 @@ var frozenDiscoveryResearchSchema = external_exports.union([
9245
9523
  ]);
9246
9524
  var discoveryProviderEvidenceReceiptV1Schema = external_exports.object({
9247
9525
  version: external_exports.literal(1),
9248
- sourceBindingRevision: sha256Schema5,
9526
+ sourceBindingRevision: sha256Schema6,
9249
9527
  providerReceipt: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
9250
9528
  evidence: external_exports.array(external_exports.object({
9251
9529
  externalObjectId: external_exports.string().uuid(),
9252
9530
  sourceRevision: external_exports.string().trim().min(1).max(500),
9253
- contentHash: sha256Schema5.optional(),
9531
+ contentHash: sha256Schema6.optional(),
9254
9532
  snapshot: external_exports.object({
9255
9533
  displayTitle: external_exports.string().nullable(),
9256
9534
  data: external_exports.record(external_exports.string(), external_exports.unknown())
@@ -9299,7 +9577,7 @@ var completeDiscoveryResearchInputV2Fields = {
9299
9577
  invocationId: external_exports.string().uuid(),
9300
9578
  externalObjectId: external_exports.string().uuid().nullable(),
9301
9579
  sourceRevision: external_exports.string().trim().min(1).max(500).nullable(),
9302
- contentHash: sha256Schema5.nullable()
9580
+ contentHash: sha256Schema6.nullable()
9303
9581
  }).strict()).max(1e4),
9304
9582
  coverageComplete: external_exports.boolean(),
9305
9583
  summary: external_exports.string().trim().min(1).max(4e3),
@@ -9541,7 +9819,7 @@ var mirrorxDiscoveryCoverageSchema = external_exports.object({
9541
9819
  currentRun: external_exports.object({
9542
9820
  routineRunId: external_exports.string().uuid(),
9543
9821
  state: external_exports.enum(["scheduled", "running", "waiting_retry", "finalizing"]),
9544
- windowKey: sha256Schema5,
9822
+ windowKey: sha256Schema6,
9545
9823
  nextAttemptAt: external_exports.string().datetime({ offset: true }).nullable()
9546
9824
  }).strict().nullable(),
9547
9825
  lastTerminal: external_exports.object({
@@ -9631,192 +9909,6 @@ function resolveMirrorxWorkKindPurpose(workKind) {
9631
9909
  return domain ? resolveMirrorxWorkPurposeSelection({ kind: "activation_domain", domain }) : { status: "unmapped", workKind };
9632
9910
  }
9633
9911
 
9634
- // ../shared/src/task-resource-input.ts
9635
- var ATTACHMENT_PREPARATION_VERSION = "attachment-preparation-v1";
9636
- var ORIGINAL_ONLY_PARSER_VERSION = "original-only-v1";
9637
- var TASK_RESOURCE_INPUT_STATES = [
9638
- "declared",
9639
- "preparing",
9640
- "prepared",
9641
- "blocked",
9642
- "retired"
9643
- ];
9644
- var ATTACHMENT_PREPARATION_FORMATS = ["text", "pdf", "docx", "xlsx", "pptx"];
9645
- var BROWSER_CREDENTIAL_ROLES = ["username", "password"];
9646
- var ONBOARDING_RESOURCE_LINK_PROVIDERS = [
9647
- "feishu",
9648
- "dingtalk",
9649
- "wechat_work",
9650
- "notion",
9651
- "github_gitlab",
9652
- "crm",
9653
- "erp",
9654
- "custom",
9655
- "other"
9656
- ];
9657
- var ONBOARDING_RESOURCE_LINK_CREATED_FROM = [
9658
- "current_system",
9659
- "manual_link",
9660
- "legacy_document_link"
9661
- ];
9662
- var sha256Schema6 = external_exports.string().regex(/^[a-f0-9]{64}$/u);
9663
- var exactOriginSchema = external_exports.string().url().superRefine((value, context) => {
9664
- const url = new URL(value);
9665
- if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash || value !== url.origin) {
9666
- context.addIssue({
9667
- code: external_exports.ZodIssueCode.custom,
9668
- message: "Origin must be an exact credential-free HTTPS origin"
9669
- });
9670
- }
9671
- });
9672
- var taskResourceLocatorSchema = external_exports.string().trim().min(1).max(8192).transform((value, context) => {
9673
- const result2 = canonicalizeTaskResourceLocator(value);
9674
- if (!result2.ok) {
9675
- context.addIssue({
9676
- code: external_exports.ZodIssueCode.custom,
9677
- message: `Task resource locator rejected: ${result2.code}`
9678
- });
9679
- return external_exports.NEVER;
9680
- }
9681
- return result2.locator;
9682
- });
9683
- var onboardingResourceLinkSchema = external_exports.object({
9684
- clientKey: external_exports.string().trim().min(1).max(128),
9685
- kind: external_exports.literal("web"),
9686
- provider: external_exports.enum(ONBOARDING_RESOURCE_LINK_PROVIDERS),
9687
- displayName: external_exports.string().trim().min(1).max(500),
9688
- locator: taskResourceLocatorSchema,
9689
- scope: external_exports.string().trim().max(2e3).default(""),
9690
- accessHint: external_exports.enum(["public", "may_require_auth", "unknown"]),
9691
- criticality: external_exports.enum(["critical", "supporting"]),
9692
- declaredPageLocators: external_exports.array(taskResourceLocatorSchema).max(100).default([]),
9693
- createdFrom: external_exports.enum(ONBOARDING_RESOURCE_LINK_CREATED_FROM)
9694
- }).strict().superRefine((resource, context) => {
9695
- if (typeof resource.locator !== "string") return;
9696
- const resourceOrigin = new URL(resource.locator).origin;
9697
- resource.declaredPageLocators.forEach((locator, index) => {
9698
- if (typeof locator === "string" && new URL(locator).origin !== resourceOrigin) {
9699
- context.addIssue({
9700
- code: external_exports.ZodIssueCode.custom,
9701
- path: ["declaredPageLocators", index],
9702
- message: "Declared page locator must use the same origin as the resource link"
9703
- });
9704
- }
9705
- });
9706
- });
9707
- var attachmentPreparationReceiptSchema = external_exports.object({
9708
- parserVersion: external_exports.literal(ATTACHMENT_PREPARATION_VERSION),
9709
- originalSha256: sha256Schema6,
9710
- sidecarSha256: sha256Schema6,
9711
- originalBytes: external_exports.number().int().nonnegative(),
9712
- sidecarBytes: external_exports.number().int().positive(),
9713
- format: external_exports.enum(ATTACHMENT_PREPARATION_FORMATS),
9714
- truncated: external_exports.boolean(),
9715
- metadata: external_exports.record(external_exports.string(), external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]))
9716
- }).strict();
9717
- var taskResourceInputBaseSchema = external_exports.object({
9718
- inputFingerprint: external_exports.string().trim().min(1).max(255),
9719
- state: external_exports.enum(TASK_RESOURCE_INPUT_STATES),
9720
- failureCode: external_exports.string().trim().min(1).max(160).nullable().optional()
9721
- });
9722
- var taskResourceInputSchema = external_exports.discriminatedUnion("kind", [
9723
- taskResourceInputBaseSchema.extend({
9724
- kind: external_exports.literal("link"),
9725
- displayName: external_exports.string().trim().min(1).max(255),
9726
- locator: external_exports.string().url().max(2048),
9727
- scope: external_exports.string().trim().min(1).max(2e3),
9728
- preparationReceipt: external_exports.null().optional()
9729
- }).strict(),
9730
- taskResourceInputBaseSchema.extend({
9731
- kind: external_exports.literal("attachment"),
9732
- attachmentId: external_exports.string().uuid(),
9733
- assetId: external_exports.string().uuid(),
9734
- byteSize: external_exports.number().int().nonnegative(),
9735
- sha256: sha256Schema6,
9736
- parserVersion: external_exports.string().trim().min(1).max(120).nullable().optional(),
9737
- sidecarAssetId: external_exports.string().uuid().nullable().optional(),
9738
- preparationReceipt: attachmentPreparationReceiptSchema.nullable().optional()
9739
- }).strict()
9740
- ]).superRefine((value, context) => {
9741
- if (value.kind !== "attachment") return;
9742
- const originalOnly = value.parserVersion === ORIGINAL_ONLY_PARSER_VERSION;
9743
- if (value.state === "prepared" && !value.preparationReceipt && !originalOnly) {
9744
- context.addIssue({
9745
- code: external_exports.ZodIssueCode.custom,
9746
- path: ["preparationReceipt"],
9747
- message: "Prepared attachment input requires a complete preparation receipt"
9748
- });
9749
- }
9750
- if (originalOnly && (value.preparationReceipt || value.sidecarAssetId)) {
9751
- context.addIssue({
9752
- code: external_exports.ZodIssueCode.custom,
9753
- path: ["preparationReceipt"],
9754
- message: "Original-only attachment input must not carry a preparation sidecar"
9755
- });
9756
- }
9757
- if (value.preparationReceipt && (value.preparationReceipt.originalSha256 !== value.sha256 || value.preparationReceipt.originalBytes !== value.byteSize)) {
9758
- context.addIssue({
9759
- code: external_exports.ZodIssueCode.custom,
9760
- path: ["preparationReceipt"],
9761
- message: "Preparation receipt must match the exact original attachment"
9762
- });
9763
- }
9764
- });
9765
- var browserCredentialRefAuthoritySchema = external_exports.object({
9766
- version: external_exports.literal(1),
9767
- companyId: external_exports.string().uuid(),
9768
- issueId: external_exports.string().uuid(),
9769
- runId: external_exports.string().uuid(),
9770
- commandId: external_exports.string().uuid(),
9771
- interactionId: external_exports.string().uuid(),
9772
- credentialKey: external_exports.string().trim().min(1).max(255),
9773
- credentialVersion: external_exports.number().int().positive(),
9774
- credentialRole: external_exports.enum(BROWSER_CREDENTIAL_ROLES),
9775
- targetOrigin: exactOriginSchema,
9776
- authenticationOrigin: exactOriginSchema,
9777
- bindingId: external_exports.string().uuid(),
9778
- browserLeaseId: external_exports.string().regex(/^browser-credential-(?:auth-write|agent-read)-[0-9a-f-]{36}$/iu)
9779
- }).strict();
9780
- var browserCredentialRefConsumeSchema = browserCredentialRefAuthoritySchema.extend({
9781
- controlSemantic: external_exports.enum(["username", "email", "password"])
9782
- }).strict();
9783
- var runtimeWebEvidenceReceiptSchema = external_exports.object({
9784
- issueId: external_exports.string().uuid(),
9785
- runId: external_exports.string().uuid(),
9786
- commandId: external_exports.string().uuid(),
9787
- toolCallId: external_exports.string().trim().min(1).max(255),
9788
- requestedUrl: external_exports.string().url().max(2048),
9789
- finalUrl: external_exports.string().url().max(2048),
9790
- capturedAt: external_exports.string().datetime({ offset: true }),
9791
- mediaType: external_exports.string().trim().min(1).max(255),
9792
- truncated: external_exports.boolean(),
9793
- contentSha256: sha256Schema6,
9794
- observedChars: external_exports.number().int().nonnegative(),
9795
- observedBytes: external_exports.number().int().nonnegative(),
9796
- evidenceAssetId: external_exports.string().uuid().nullable().optional()
9797
- }).strict();
9798
- var runtimeWebEvidenceIngestSchema = external_exports.object({
9799
- companyId: external_exports.string().uuid(),
9800
- issueId: external_exports.string().uuid(),
9801
- runId: external_exports.string().uuid(),
9802
- commandId: external_exports.string().uuid(),
9803
- toolCallId: external_exports.string().trim().min(1).max(255),
9804
- requestedUrl: external_exports.string().url().max(8192),
9805
- finalUrl: external_exports.string().url().max(8192),
9806
- capturedAt: external_exports.string().datetime({ offset: true }),
9807
- mediaType: external_exports.string().trim().min(1).max(255),
9808
- normalizedText: external_exports.string().max(2e6),
9809
- truncated: external_exports.boolean().optional()
9810
- }).strict();
9811
- var createTaskResourceLinkRequestSchema = external_exports.object({
9812
- displayName: external_exports.string().trim().min(1).max(500),
9813
- locator: taskResourceLocatorSchema,
9814
- scope: external_exports.string().trim().min(1).max(2e3),
9815
- criticality: external_exports.enum(["critical", "supporting"]).default("supporting")
9816
- }).strict();
9817
- var finalizeTaskResourceAttachmentRequestSchema = external_exports.object({ inputId: external_exports.string().uuid() }).strict();
9818
- var createTaskResourceAttachmentRequestSchema = external_exports.object({ attachmentId: external_exports.string().uuid() }).strict();
9819
-
9820
9912
  // ../shared/src/types/browser-session-binding.ts
9821
9913
  var BROWSER_SESSION_BINDING_STATUSES = [
9822
9914
  "preparing",
@@ -10181,7 +10273,7 @@ var businessDataSourceReadSchema = external_exports.object({
10181
10273
  evidence: external_exports.string().trim().min(1).max(1e3)
10182
10274
  }).strict().describe("Required only for business_data_source_unavailable. Record the actual authorized configuration/access/read failure, observation time and non-secret evidence. A read_succeeded observation (including empty results) cannot create this wait; report source-scoped zero or unknown coverage instead.");
10183
10275
  function refineBusinessDataSourceWait(value, ctx) {
10184
- if (value.reasonCode === "business_data_source_unavailable") {
10276
+ if (value.reasonCode === EXTERNAL_WAIT_REASON_CODES.businessDataSourceUnavailable) {
10185
10277
  if (!value.dataSourceRead || value.dataSourceRead.outcome === "read_succeeded") {
10186
10278
  ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["dataSourceRead"], message: "business_data_source_unavailable requires an observed access/configuration/read failure. A successful read, including an empty table, cannot block reports; report source-scoped zero or unknown coverage/baseline instead. Do not require non-empty records to restore access." });
10187
10279
  }
@@ -12739,6 +12831,34 @@ var issueDeliveryAcceptanceReferenceSchema = external_exports.object({
12739
12831
  state: external_exports.enum(ISSUE_DELIVERY_REFERENCE_STATES),
12740
12832
  href: external_exports.string().min(1).max(4e3).nullable()
12741
12833
  }).strict();
12834
+ var issueExecutionDecisionHistoryRecordSchema = external_exports.object({
12835
+ sequence: external_exports.number().int().positive(),
12836
+ reviewEvidenceStatus: external_exports.enum(["available", "absent", "invalid"]),
12837
+ decision: external_exports.object({
12838
+ id: uuidSchema3,
12839
+ companyId: uuidSchema3,
12840
+ issueId: uuidSchema3,
12841
+ stageId: uuidSchema3,
12842
+ stageType: external_exports.enum(ISSUE_EXECUTION_STAGE_TYPES),
12843
+ actorAgentId: uuidSchema3.nullable(),
12844
+ actorUserId: external_exports.string().min(1).nullable(),
12845
+ outcome: external_exports.enum(ISSUE_EXECUTION_DECISION_OUTCOMES),
12846
+ body: external_exports.string(),
12847
+ reviewEvidence: issueExecutionReviewEvidenceSchema.nullable(),
12848
+ createdByRunId: uuidSchema3.nullable(),
12849
+ createdAt: dateSchema2,
12850
+ updatedAt: dateSchema2
12851
+ }).strict(),
12852
+ inspectedReferences: external_exports.array(issueDeliveryAcceptanceReferenceSchema)
12853
+ }).strict();
12854
+ var issueExecutionDecisionHistoryEnvelopeSchema = external_exports.object({
12855
+ records: external_exports.array(external_exports.unknown()),
12856
+ totalCount: external_exports.number().int().nonnegative()
12857
+ }).strict();
12858
+ var issueExecutionDecisionHistoryResponseSchema = external_exports.object({
12859
+ records: external_exports.array(issueExecutionDecisionHistoryRecordSchema),
12860
+ totalCount: external_exports.number().int().nonnegative()
12861
+ }).strict();
12742
12862
  var issueDeliveryAcceptancePendingInteractionSchema = external_exports.object({
12743
12863
  interactionId: uuidSchema3,
12744
12864
  interactionKind: external_exports.enum(ISSUE_THREAD_INTERACTION_KINDS),
@@ -13367,12 +13487,36 @@ var ceoPeriodicGoalGapCandidateSchema = external_exports.object({
13367
13487
  businessSubjectScope: operatingNormalizedBusinessSubjectRefSchema,
13368
13488
  targetCondition: external_exports.object({ kind: external_exports.literal("boolean_milestone"), expected: external_exports.literal(true) }).strict(),
13369
13489
  window: external_exports.record(external_exports.string().min(1).max(80), external_exports.unknown()),
13370
- observationRef: goalGapObservationRefSchema,
13371
- sourceRefs: external_exports.array(ceoPeriodicWorkSourceRefSchema).min(1).max(20),
13490
+ observationRef: goalGapObservationRefSchema.describe(
13491
+ "Server-governed observation identity. For blocker_state or business_outcome candidates, use kind=governed_business_state and copy the primary sourceRef id/revision exactly; do not copy the primary sourceRef kind."
13492
+ ),
13493
+ sourceRefs: external_exports.array(ceoPeriodicWorkSourceRefSchema).min(1).max(20).describe(
13494
+ "Exact leased evidence refs. A provisional Goal Gap candidate must include a primary blocker_state or business_outcome ref whose id/revision exactly match observationRef."
13495
+ ),
13372
13496
  reasoningSummary: external_exports.string().trim().min(1).max(1e3),
13373
13497
  confidenceBand: external_exports.enum(["high", "medium", "low"]),
13374
13498
  workClass: external_exports.enum(["internal_enablement", "governed_decision", "external_action", "observed_business_result"])
13375
13499
  }).strict();
13500
+ var ceoPeriodicGoalGapCandidatesSchema = external_exports.array(ceoPeriodicGoalGapCandidateSchema).max(10).superRefine((candidates, ctx) => {
13501
+ for (const [index, candidate] of candidates.entries()) {
13502
+ const primarySource = candidate.sourceRefs.find((sourceRef) => ["blocker_state", "business_outcome"].includes(sourceRef.kind) && sourceRef.id === candidate.observationRef.id && sourceRef.revision === candidate.observationRef.revision);
13503
+ if (!primarySource) {
13504
+ ctx.addIssue({
13505
+ code: external_exports.ZodIssueCode.custom,
13506
+ path: [index, "observationRef"],
13507
+ message: "Goal Gap candidate observationRef must identify an exact sourceRef"
13508
+ });
13509
+ continue;
13510
+ }
13511
+ if (candidate.observationRef.kind !== "governed_business_state") {
13512
+ ctx.addIssue({
13513
+ code: external_exports.ZodIssueCode.custom,
13514
+ path: [index, "observationRef"],
13515
+ message: "Goal Gap candidates require a Server-verifiable blocker_state or business_outcome primary source"
13516
+ });
13517
+ }
13518
+ }
13519
+ });
13376
13520
  var ceoPeriodicTaskAttentionSchema = external_exports.object({
13377
13521
  prerequisiteRequirements: external_exports.array(prerequisiteRequirementProjectionSchema),
13378
13522
  prerequisiteBindings: external_exports.array(prerequisiteBindingProjectionSchema),
@@ -13441,7 +13585,7 @@ var ceoPeriodicDemandCandidatesSchema = external_exports.array(ceoPeriodicDemand
13441
13585
  var ceoPeriodicWorkDispatchInputSchema = external_exports.object({
13442
13586
  observationId: external_exports.string().uuid(),
13443
13587
  inputFingerprint: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/u),
13444
- goalGapCandidates: external_exports.array(ceoPeriodicGoalGapCandidateSchema).max(10).default([]),
13588
+ goalGapCandidates: ceoPeriodicGoalGapCandidatesSchema.default([]),
13445
13589
  continuations: external_exports.array(ceoPeriodicContinuationInputSchema).max(20).default([]),
13446
13590
  candidates: ceoPeriodicDemandCandidatesSchema.default([]),
13447
13591
  noWorkReason: ceoPeriodicNoWorkReasonSchema.optional(),
@@ -14854,7 +14998,7 @@ var FEEDBACK_TARGET_TYPES = ["issue_comment", "issue_document_revision"];
14854
14998
  var FEEDBACK_VOTE_VALUES = ["up", "down"];
14855
14999
  var FEEDBACK_DATA_SHARING_PREFERENCES = ["allowed", "not_allowed", "prompt"];
14856
15000
  var DEFAULT_FEEDBACK_DATA_SHARING_PREFERENCE = "prompt";
14857
- var FEEDBACK_TRACE_STATUSES = ["local_only", "pending", "sent", "failed"];
15001
+ var FEEDBACK_TRACE_STATUSES = ["local_only", "pending", "sent", "failed", "dead_letter"];
14858
15002
 
14859
15003
  // ../shared/src/validators/feedback.ts
14860
15004
  var feedbackTargetTypeSchema = external_exports.enum(FEEDBACK_TARGET_TYPES);
@@ -18592,9 +18736,9 @@ var wikiMentionListSchema = external_exports.object({
18592
18736
  });
18593
18737
 
18594
18738
  // src/amaster-runtime-daemon.mjs
18595
- import { chmodSync as chmodSync7, copyFileSync as copyFileSync2, existsSync as existsSync18, lstatSync as lstatSync13, mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, readFileSync as readFileSync19, readdirSync as readdirSync12, realpathSync as realpathSync12, renameSync as renameSync10, rmSync as rmSync11, statSync as statSync12, symlinkSync as symlinkSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync13 } from "node:fs";
18739
+ import { chmodSync as chmodSync8, copyFileSync as copyFileSync2, existsSync as existsSync18, lstatSync as lstatSync13, mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync5, readFileSync as readFileSync19, readdirSync as readdirSync12, realpathSync as realpathSync12, renameSync as renameSync11, rmSync as rmSync12, statSync as statSync12, symlinkSync as symlinkSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync14 } from "node:fs";
18596
18740
  import { arch as arch4, homedir as homedir6, hostname as hostname2, platform as platform4, tmpdir } from "node:os";
18597
- import { basename as basename8, delimiter as delimiter3, dirname as dirname11, extname as extname3, isAbsolute as isAbsolute12, join as join23, relative as relative9, resolve as resolve19 } from "node:path";
18741
+ import { basename as basename8, delimiter as delimiter3, dirname as dirname12, extname as extname3, isAbsolute as isAbsolute12, join as join24, relative as relative9, resolve as resolve19 } from "node:path";
18598
18742
  import { spawn, spawnSync as spawnSync5 } from "node:child_process";
18599
18743
 
18600
18744
  // src/amaster-runtime-daemon/common.mjs
@@ -24955,8 +25099,10 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24955
25099
  } : {}
24956
25100
  }
24957
25101
  } : {},
24958
- // CLI --tools remains unused so user-level tools stay available.
25102
+ // Normal governed runs preserve user-level tools. An exact task-resource
25103
+ // run narrows this later to direct governed tools plus its bound reader.
24959
25104
  toolAllowlist: null,
25105
+ directToolNames,
24960
25106
  directCatalogFrozen: Boolean(directCatalog),
24961
25107
  protectedValues: [.../* @__PURE__ */ new Set([
24962
25108
  sessionToken,
@@ -25237,7 +25383,9 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
25237
25383
  } : {}
25238
25384
  }
25239
25385
  } : {},
25386
+ // Exact task-resource runs narrow this after the run-owned reader exists.
25240
25387
  toolAllowlist: null,
25388
+ directToolNames,
25241
25389
  directCatalogFrozen: Boolean(directCatalog),
25242
25390
  protectedValues: [.../* @__PURE__ */ new Set([sessionToken, ...seededRuntime.protectedValues])],
25243
25391
  attestation: {
@@ -25480,6 +25628,180 @@ function selectExecutor(config, command) {
25480
25628
  return selected;
25481
25629
  }
25482
25630
 
25631
+ // src/amaster-runtime-daemon/web-evidence.mjs
25632
+ import { createHash as createHash10 } from "node:crypto";
25633
+ var SENSITIVE_QUERY_KEY_FRAGMENTS = [
25634
+ "apikey",
25635
+ "accesskey",
25636
+ "privatekey",
25637
+ "token",
25638
+ "secret",
25639
+ "signature",
25640
+ "credential",
25641
+ "password",
25642
+ "authorization",
25643
+ "session",
25644
+ "cookie",
25645
+ "oauth",
25646
+ "ticket",
25647
+ "assertion",
25648
+ "samlresponse",
25649
+ "relaystate",
25650
+ "jwt"
25651
+ ];
25652
+ var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set(["auth", "code", "key", "sig", "sid", "state"]);
25653
+ function isSensitiveQueryKey(key) {
25654
+ const compact = key.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/gu, "");
25655
+ return SENSITIVE_QUERY_KEYS.has(compact) || SENSITIVE_QUERY_KEY_FRAGMENTS.some((fragment) => compact.includes(fragment));
25656
+ }
25657
+ function safeUrl(raw) {
25658
+ const url = new URL(raw);
25659
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
25660
+ throw new Error("runtime_web_evidence_url_invalid");
25661
+ }
25662
+ for (const key of [...url.searchParams.keys()]) {
25663
+ if (isSensitiveQueryKey(key)) url.searchParams.delete(key);
25664
+ }
25665
+ url.hash = "";
25666
+ return url.toString();
25667
+ }
25668
+ function sanitizeRuntimeWebEvidence(input) {
25669
+ const allowed = /* @__PURE__ */ new Set(["toolCallId", "requestedUrl", "finalUrl", "capturedAt", "mediaType", "normalizedText", "truncated"]);
25670
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !allowed.has(key))) {
25671
+ throw new Error("runtime_web_evidence_invalid");
25672
+ }
25673
+ const cleanedText = typeof input.normalizedText === "string" ? input.normalizedText.replace(/\r\n?/gu, "\n").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/gu, "") : null;
25674
+ if (!cleanedText || typeof input.toolCallId !== "string" || !input.toolCallId.trim()) {
25675
+ throw new Error("runtime_web_evidence_invalid");
25676
+ }
25677
+ const normalizedText = cleanedText.slice(0, 2e5);
25678
+ const bytes = Buffer.from(normalizedText, "utf8");
25679
+ return {
25680
+ toolCallId: input.toolCallId.trim(),
25681
+ requestedUrl: safeUrl(input.requestedUrl),
25682
+ finalUrl: safeUrl(input.finalUrl),
25683
+ capturedAt: new Date(input.capturedAt).toISOString(),
25684
+ mediaType: typeof input.mediaType === "string" && input.mediaType.trim() ? input.mediaType.trim() : "text/plain",
25685
+ normalizedText,
25686
+ truncated: input.truncated === true || cleanedText.length > 2e5,
25687
+ contentSha256: createHash10("sha256").update(bytes).digest("hex"),
25688
+ observedChars: normalizedText.length,
25689
+ observedBytes: bytes.byteLength
25690
+ };
25691
+ }
25692
+ function assertExactTaskResourceWebEvidence(evidence) {
25693
+ if (evidence?.sourceToolName !== "amaster_exact_source_read") {
25694
+ throw new Error("runtime_exact_source_evidence_untrusted");
25695
+ }
25696
+ return evidence;
25697
+ }
25698
+ function runtimeWebEvidenceTaskResourceBinding(payload) {
25699
+ const binding = payload?.webEvidenceTaskResourceBinding;
25700
+ if (!binding || typeof binding.inputId !== "string" || !binding.inputId.trim() || typeof binding.inputFingerprint !== "string" || !binding.inputFingerprint.trim() || !Number.isInteger(binding.retrievalRevision) || binding.retrievalRevision < 1) return null;
25701
+ return {
25702
+ inputId: binding.inputId.trim(),
25703
+ inputFingerprint: binding.inputFingerprint.trim(),
25704
+ retrievalRevision: binding.retrievalRevision
25705
+ };
25706
+ }
25707
+ function runtimeExactTaskResourceBinding(payload) {
25708
+ const binding = payload?.webEvidenceTaskResourceBinding;
25709
+ if (!runtimeWebEvidenceTaskResourceBinding(payload) || typeof binding.locator !== "string" || !binding.locator.trim() || typeof binding.locatorFingerprint !== "string" || !/^[a-f0-9]{64}$/u.test(binding.locatorFingerprint)) return null;
25710
+ let locator;
25711
+ try {
25712
+ locator = safeUrl(binding.locator.trim());
25713
+ } catch {
25714
+ return null;
25715
+ }
25716
+ if (createHash10("sha256").update(locator).digest("hex") !== binding.locatorFingerprint) return null;
25717
+ return {
25718
+ locator,
25719
+ locatorFingerprint: binding.locatorFingerprint
25720
+ };
25721
+ }
25722
+
25723
+ // src/amaster-runtime-daemon/pi-exact-source-read.mjs
25724
+ import { chmodSync as chmodSync5, mkdirSync as mkdirSync7, renameSync as renameSync4, rmSync as rmSync6, writeFileSync as writeFileSync7, writeSync } from "node:fs";
25725
+ import { dirname as dirname6, join as join11 } from "node:path";
25726
+
25727
+ // src/amaster-runtime-daemon/public-network-scope.mjs
25728
+ import { BlockList, isIP } from "node:net";
25729
+ var blockedV4Addresses = new BlockList();
25730
+ for (const [network, prefix] of [
25731
+ ["0.0.0.0", 8],
25732
+ ["10.0.0.0", 8],
25733
+ ["100.64.0.0", 10],
25734
+ ["127.0.0.0", 8],
25735
+ ["169.254.0.0", 16],
25736
+ ["172.16.0.0", 12],
25737
+ ["192.0.0.0", 24],
25738
+ ["192.0.2.0", 24],
25739
+ ["192.88.99.0", 24],
25740
+ ["192.168.0.0", 16],
25741
+ ["198.18.0.0", 15],
25742
+ ["198.51.100.0", 24],
25743
+ ["203.0.113.0", 24],
25744
+ ["224.0.0.0", 4],
25745
+ ["240.0.0.0", 4]
25746
+ ]) {
25747
+ blockedV4Addresses.addSubnet(network, prefix, "ipv4");
25748
+ }
25749
+ var blockedV6Addresses = new BlockList();
25750
+ for (const [network, prefix] of [
25751
+ ["::", 128],
25752
+ ["::1", 128],
25753
+ ["::", 96],
25754
+ ["::ffff:0:0", 96],
25755
+ ["64:ff9b::", 96],
25756
+ ["64:ff9b:1::", 48],
25757
+ ["100::", 64],
25758
+ ["2001::", 32],
25759
+ ["2001:2::", 48],
25760
+ ["2001:db8::", 32],
25761
+ ["2001:10::", 28],
25762
+ ["2001:20::", 28],
25763
+ ["2002::", 16],
25764
+ ["fc00::", 7],
25765
+ ["fe80::", 10],
25766
+ ["fec0::", 10],
25767
+ ["ff00::", 8]
25768
+ ]) {
25769
+ blockedV6Addresses.addSubnet(network, prefix, "ipv6");
25770
+ }
25771
+
25772
+ // src/amaster-runtime-daemon/pi-exact-source-read.mjs
25773
+ var EXACT_SOURCE_READ_TOOL_NAME = "amaster_exact_source_read";
25774
+ var MAX_BYTES2 = 512 * 1024;
25775
+ function exactSourceToolAllowlist(profile) {
25776
+ const governedToolNames = Array.isArray(profile?.directToolNames) ? profile.directToolNames.filter((name) => typeof name === "string" && name) : [];
25777
+ return [.../* @__PURE__ */ new Set([...governedToolNames, EXACT_SOURCE_READ_TOOL_NAME])];
25778
+ }
25779
+ function managedPiExactSourceReadExtensionSource(binding, options = {}) {
25780
+ const runtimeModuleUrl = typeof options.runtimeModuleUrl === "string" && options.runtimeModuleUrl ? options.runtimeModuleUrl : import.meta.url;
25781
+ const readerModuleUrl = new URL("./pi-exact-source-read.mjs", runtimeModuleUrl).href;
25782
+ return `import { registerExactSourceReadTool } from ${JSON.stringify(readerModuleUrl)};
25783
+ const binding = ${JSON.stringify(binding)};
25784
+ export default function amasterExactSourceRead(pi) { registerExactSourceReadTool(pi, binding); }
25785
+ `;
25786
+ }
25787
+ function materializePiExactSourceReadExtension(profileRoot, binding) {
25788
+ const extensionPath = join11(profileRoot, "extensions", "amaster-exact-source-read.js");
25789
+ mkdirSync7(dirname6(extensionPath), { recursive: true, mode: 448 });
25790
+ const temporaryPath = `${extensionPath}.${process.pid}.tmp`;
25791
+ try {
25792
+ writeFileSync7(temporaryPath, managedPiExactSourceReadExtensionSource(binding), {
25793
+ encoding: "utf8",
25794
+ mode: 384,
25795
+ flag: "wx"
25796
+ });
25797
+ renameSync4(temporaryPath, extensionPath);
25798
+ chmodSync5(extensionPath, 384);
25799
+ return extensionPath;
25800
+ } finally {
25801
+ rmSync6(temporaryPath, { force: true });
25802
+ }
25803
+ }
25804
+
25483
25805
  // src/amaster-runtime-daemon/model-authority.mjs
25484
25806
  var TASK_SESSION_SNAPSHOT_KEY = "mirrorxRuntimeConnectorTaskSessionV1";
25485
25807
  function asRecord2(value) {
@@ -25716,8 +26038,8 @@ function isTerminalResultOutboxStatus(status) {
25716
26038
  }
25717
26039
 
25718
26040
  // src/amaster-runtime-daemon/run-completion-state.mjs
25719
- import { existsSync as existsSync8, mkdirSync as mkdirSync7, readFileSync as readFileSync8, readdirSync as readdirSync6, renameSync as renameSync4, unlinkSync, writeFileSync as writeFileSync7 } from "node:fs";
25720
- import { join as join11 } from "node:path";
26041
+ import { existsSync as existsSync8, mkdirSync as mkdirSync8, readFileSync as readFileSync8, readdirSync as readdirSync6, renameSync as renameSync5, unlinkSync, writeFileSync as writeFileSync8 } from "node:fs";
26042
+ import { join as join12 } from "node:path";
25721
26043
 
25722
26044
  // src/amaster-runtime-daemon/typed/run-completion-transitions.mjs
25723
26045
  var RUN_COMPLETION_PHASES = /* @__PURE__ */ new Set([
@@ -25979,12 +26301,12 @@ function assertValidRunCompletionState(value) {
25979
26301
  }
25980
26302
  function writeRunCompletionState(directory, state) {
25981
26303
  const valid = assertValidRunCompletionState(state);
25982
- mkdirSync7(directory, { recursive: true, mode: 448 });
25983
- const filePath = join11(directory, runCompletionStateFileName(valid.commandId));
26304
+ mkdirSync8(directory, { recursive: true, mode: 448 });
26305
+ const filePath = join12(directory, runCompletionStateFileName(valid.commandId));
25984
26306
  const temporaryPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
25985
- writeFileSync7(temporaryPath, `${JSON.stringify(valid, null, 2)}
26307
+ writeFileSync8(temporaryPath, `${JSON.stringify(valid, null, 2)}
25986
26308
  `, { mode: 384 });
25987
- renameSync4(temporaryPath, filePath);
26309
+ renameSync5(temporaryPath, filePath);
25988
26310
  return filePath;
25989
26311
  }
25990
26312
  function readRunCompletionState(filePath) {
@@ -25992,10 +26314,10 @@ function readRunCompletionState(filePath) {
25992
26314
  }
25993
26315
  function listRunCompletionStateFiles(directory) {
25994
26316
  if (!existsSync8(directory)) return [];
25995
- return readdirSync6(directory).filter((name) => name.endsWith(".json")).sort().map((name) => join11(directory, name));
26317
+ return readdirSync6(directory).filter((name) => name.endsWith(".json")).sort().map((name) => join12(directory, name));
25996
26318
  }
25997
26319
  function removeRunCompletionState(directory, commandId) {
25998
- const filePath = join11(directory, runCompletionStateFileName(commandId));
26320
+ const filePath = join12(directory, runCompletionStateFileName(commandId));
25999
26321
  if (existsSync8(filePath)) unlinkSync(filePath);
26000
26322
  }
26001
26323
 
@@ -27938,68 +28260,6 @@ function parseCodebuddyStreamJson(stdout, options = {}) {
27938
28260
  };
27939
28261
  }
27940
28262
 
27941
- // src/amaster-runtime-daemon/web-evidence.mjs
27942
- import { createHash as createHash10 } from "node:crypto";
27943
- var SENSITIVE_QUERY_KEY_FRAGMENTS = [
27944
- "apikey",
27945
- "accesskey",
27946
- "privatekey",
27947
- "token",
27948
- "secret",
27949
- "signature",
27950
- "credential",
27951
- "password",
27952
- "authorization",
27953
- "session",
27954
- "cookie",
27955
- "oauth",
27956
- "ticket",
27957
- "assertion",
27958
- "samlresponse",
27959
- "relaystate",
27960
- "jwt"
27961
- ];
27962
- var SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set(["auth", "code", "key", "sig", "sid", "state"]);
27963
- function isSensitiveQueryKey(key) {
27964
- const compact = key.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^a-z0-9]/gu, "");
27965
- return SENSITIVE_QUERY_KEYS.has(compact) || SENSITIVE_QUERY_KEY_FRAGMENTS.some((fragment) => compact.includes(fragment));
27966
- }
27967
- function safeUrl(raw) {
27968
- const url = new URL(raw);
27969
- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
27970
- throw new Error("runtime_web_evidence_url_invalid");
27971
- }
27972
- for (const key of [...url.searchParams.keys()]) {
27973
- if (isSensitiveQueryKey(key)) url.searchParams.delete(key);
27974
- }
27975
- url.hash = "";
27976
- return url.toString();
27977
- }
27978
- function sanitizeRuntimeWebEvidence(input) {
27979
- const allowed = /* @__PURE__ */ new Set(["toolCallId", "requestedUrl", "finalUrl", "capturedAt", "mediaType", "normalizedText", "truncated"]);
27980
- if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !allowed.has(key))) {
27981
- throw new Error("runtime_web_evidence_invalid");
27982
- }
27983
- const cleanedText = typeof input.normalizedText === "string" ? input.normalizedText.replace(/\r\n?/gu, "\n").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/gu, "") : null;
27984
- if (!cleanedText || typeof input.toolCallId !== "string" || !input.toolCallId.trim()) {
27985
- throw new Error("runtime_web_evidence_invalid");
27986
- }
27987
- const normalizedText = cleanedText.slice(0, 2e5);
27988
- const bytes = Buffer.from(normalizedText, "utf8");
27989
- return {
27990
- toolCallId: input.toolCallId.trim(),
27991
- requestedUrl: safeUrl(input.requestedUrl),
27992
- finalUrl: safeUrl(input.finalUrl),
27993
- capturedAt: new Date(input.capturedAt).toISOString(),
27994
- mediaType: typeof input.mediaType === "string" && input.mediaType.trim() ? input.mediaType.trim() : "text/plain",
27995
- normalizedText,
27996
- truncated: input.truncated === true || cleanedText.length > 2e5,
27997
- contentSha256: createHash10("sha256").update(bytes).digest("hex"),
27998
- observedChars: normalizedText.length,
27999
- observedBytes: bytes.byteLength
28000
- };
28001
- }
28002
-
28003
28263
  // src/amaster-runtime-daemon/executor-protocol/pi.mjs
28004
28264
  var PI_PROVIDER_AUTH_RE = /(?:(?:\b401\b|\b403\b)[^\n]*(?:unauthorized|forbidden|auth(?:entication|orization)?|api[_\s-]?key)|(?:invalid|missing|expired|revoked)\s+(?:provider\s+)?api[_\s-]?key|provider\s+authentication\s+required)/i;
28005
28265
  var PI_PROVIDER_QUOTA_EXHAUSTED_RE = /(?:\binsufficient[_\s-]?user[_\s-]?quota\b|河狸币余额不足|\b402\b[^\n]*(?:余额不足|insufficient[_\s-]?balance|payment\s+required))/i;
@@ -28403,7 +28663,10 @@ function piGovernedMcpUnavailableEvidence(event) {
28403
28663
  function piRuntimeWebEvidence(event) {
28404
28664
  if (readString(event?.type) === "amaster_web_evidence" && readString(event?.version) === "runtime_web_evidence_v1") {
28405
28665
  try {
28406
- return [sanitizeRuntimeWebEvidence(asRecord(event).evidence)];
28666
+ return [{
28667
+ ...sanitizeRuntimeWebEvidence(asRecord(event).evidence),
28668
+ sourceToolName: "amaster_exact_source_read"
28669
+ }];
28407
28670
  } catch {
28408
28671
  return [];
28409
28672
  }
@@ -28442,7 +28705,7 @@ function piRuntimeWebEvidence(event) {
28442
28705
  const identity = `${item.toolCallId}\0${item.contentSha256}`;
28443
28706
  if (!seen.has(identity)) {
28444
28707
  seen.add(identity);
28445
- evidence.push(item);
28708
+ evidence.push({ ...item, sourceToolName: toolName });
28446
28709
  }
28447
28710
  } catch {
28448
28711
  }
@@ -29252,6 +29515,9 @@ function resolveRuntimeCostModelIdentity({
29252
29515
  }
29253
29516
 
29254
29517
  // src/amaster-runtime-daemon/execution-lanes.mjs
29518
+ function isRuntimeStopCommand(command) {
29519
+ return command?.commandType === "cancel" || command?.commandType === "terminate";
29520
+ }
29255
29521
  function normalizeRuntimeExecutionLane(value) {
29256
29522
  return value === "conversation" ? "conversation" : "business";
29257
29523
  }
@@ -29273,6 +29539,10 @@ function selectRuntimeCommandsWithinLaneLimits(input) {
29273
29539
  }
29274
29540
  const selected = [];
29275
29541
  for (const command of Array.isArray(input.commands) ? input.commands : []) {
29542
+ if (isRuntimeStopCommand(command)) {
29543
+ selected.push(command);
29544
+ continue;
29545
+ }
29276
29546
  const lane = runtimeExecutionLaneForCapabilities(command?.executionLane, input.capabilities);
29277
29547
  if (lane === "conversation" && !supportsExecutionLanes) continue;
29278
29548
  const total = counts.business + counts.conversation;
@@ -31563,12 +31833,12 @@ ${resolvedDependencies.details.content}` : resolvedDependencies.details.content
31563
31833
 
31564
31834
  // src/amaster-runtime-daemon/agent-instruction-delivery.mjs
31565
31835
  import { createHash as createHash13, randomBytes } from "node:crypto";
31566
- import { existsSync as existsSync10, lstatSync as lstatSync8, mkdirSync as mkdirSync8, readFileSync as readFileSync10, readdirSync as readdirSync7, realpathSync as realpathSync9, renameSync as renameSync6, rmSync as rmSync7, writeFileSync as writeFileSync9 } from "node:fs";
31567
- import { dirname as dirname7, isAbsolute as isAbsolute6, join as join13, relative as relative4, resolve as resolve8 } from "node:path";
31836
+ import { existsSync as existsSync10, lstatSync as lstatSync8, mkdirSync as mkdirSync9, readFileSync as readFileSync10, readdirSync as readdirSync7, realpathSync as realpathSync9, renameSync as renameSync7, rmSync as rmSync8, writeFileSync as writeFileSync10 } from "node:fs";
31837
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join14, relative as relative4, resolve as resolve8 } from "node:path";
31568
31838
 
31569
31839
  // src/amaster-runtime-daemon/workspace-manifest.mjs
31570
- import { chownSync as chownSync3, existsSync as existsSync9, readFileSync as readFileSync9, renameSync as renameSync5, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync8 } from "node:fs";
31571
- import { basename as basename5, dirname as dirname6, join as join12 } from "node:path";
31840
+ import { chownSync as chownSync3, existsSync as existsSync9, readFileSync as readFileSync9, renameSync as renameSync6, rmSync as rmSync7, statSync as statSync5, writeFileSync as writeFileSync9 } from "node:fs";
31841
+ import { basename as basename5, dirname as dirname7, join as join13 } from "node:path";
31572
31842
  var WORKSPACE_MANIFEST_FILENAME = ".amaster-runtime.json";
31573
31843
  function syncManifestDirOwnership(manifestPath, deps = {}) {
31574
31844
  const stat = deps.statSync ?? statSync5;
@@ -31576,7 +31846,7 @@ function syncManifestDirOwnership(manifestPath, deps = {}) {
31576
31846
  const geteuid = deps.geteuid ?? (typeof process.geteuid === "function" ? process.geteuid.bind(process) : () => null);
31577
31847
  try {
31578
31848
  if (geteuid() !== 0) return false;
31579
- const dirStat = stat(dirname6(manifestPath));
31849
+ const dirStat = stat(dirname7(manifestPath));
31580
31850
  if (dirStat.uid === 0 && dirStat.gid === 0) return false;
31581
31851
  chown(manifestPath, dirStat.uid, dirStat.gid);
31582
31852
  return true;
@@ -31589,8 +31859,8 @@ function nowIso() {
31589
31859
  }
31590
31860
  function workspaceManifestPath(workspaceOrCwd) {
31591
31861
  if (!workspaceOrCwd) return null;
31592
- if (typeof workspaceOrCwd === "string") return join12(workspaceOrCwd, WORKSPACE_MANIFEST_FILENAME);
31593
- if (typeof workspaceOrCwd.cwd === "string") return join12(workspaceOrCwd.cwd, WORKSPACE_MANIFEST_FILENAME);
31862
+ if (typeof workspaceOrCwd === "string") return join13(workspaceOrCwd, WORKSPACE_MANIFEST_FILENAME);
31863
+ if (typeof workspaceOrCwd.cwd === "string") return join13(workspaceOrCwd.cwd, WORKSPACE_MANIFEST_FILENAME);
31594
31864
  return null;
31595
31865
  }
31596
31866
  function readWorkspaceManifest(manifestPath) {
@@ -31603,17 +31873,17 @@ function readWorkspaceManifest(manifestPath) {
31603
31873
  }
31604
31874
  }
31605
31875
  function writeWorkspaceManifest(manifestPath, manifest, deps) {
31606
- const tempPath = join12(
31607
- dirname6(manifestPath),
31876
+ const tempPath = join13(
31877
+ dirname7(manifestPath),
31608
31878
  `.${basename5(manifestPath)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
31609
31879
  );
31610
31880
  try {
31611
- writeFileSync8(tempPath, `${JSON.stringify(manifest, null, 2)}
31881
+ writeFileSync9(tempPath, `${JSON.stringify(manifest, null, 2)}
31612
31882
  `, { mode: 384 });
31613
- renameSync5(tempPath, manifestPath);
31883
+ renameSync6(tempPath, manifestPath);
31614
31884
  syncManifestDirOwnership(manifestPath, deps);
31615
31885
  } catch (err) {
31616
- rmSync6(tempPath, { force: true });
31886
+ rmSync7(tempPath, { force: true });
31617
31887
  throw err;
31618
31888
  }
31619
31889
  return manifest;
@@ -31701,7 +31971,7 @@ function isManagedExecutionDirectory(directory, managedWorkspacesRoot) {
31701
31971
  const managedRoot = canonicalExistingPath(managedWorkspacesRoot);
31702
31972
  const candidate = canonicalExistingPath(directory);
31703
31973
  if (!pathWithin(candidate, managedRoot)) return false;
31704
- const manifestPath = join13(candidate, WORKSPACE_MANIFEST_FILENAME);
31974
+ const manifestPath = join14(candidate, WORKSPACE_MANIFEST_FILENAME);
31705
31975
  const manifestStat = lstatIfPresent2(manifestPath);
31706
31976
  if (!manifestStat?.isFile() || manifestStat.isSymbolicLink()) return false;
31707
31977
  try {
@@ -31817,7 +32087,7 @@ ${repositoryBlock}
31817
32087
  }
31818
32088
  function assertProjectionTargetAncestors(targetPath, targetRoot) {
31819
32089
  const pending = [];
31820
- let current = dirname7(targetPath);
32090
+ let current = dirname8(targetPath);
31821
32091
  while (current !== targetRoot) {
31822
32092
  if (!pathWithin(current, targetRoot)) {
31823
32093
  throw instructionTopologyError(
@@ -31826,12 +32096,12 @@ function assertProjectionTargetAncestors(targetPath, targetRoot) {
31826
32096
  );
31827
32097
  }
31828
32098
  pending.push(current);
31829
- current = dirname7(current);
32099
+ current = dirname8(current);
31830
32100
  }
31831
32101
  pending.push(targetRoot);
31832
32102
  for (const directory of pending.reverse()) {
31833
32103
  if (!existsSync10(directory)) {
31834
- mkdirSync8(directory, { mode: 448 });
32104
+ mkdirSync9(directory, { mode: 448 });
31835
32105
  continue;
31836
32106
  }
31837
32107
  const stat = lstatSync8(directory);
@@ -31914,10 +32184,10 @@ function projectExternalWorkspaceProjectInstructions(sourceWorkspacePath, execut
31914
32184
  assertProjectionTargetAncestors(targetPath, targetRoot);
31915
32185
  const temporaryPath = `${targetPath}.mirrorx-${randomBytes(12).toString("hex")}.tmp`;
31916
32186
  try {
31917
- writeFileSync9(temporaryPath, projectedContent, { encoding: "utf8", flag: "wx", mode: 384 });
31918
- renameSync6(temporaryPath, targetPath);
32187
+ writeFileSync10(temporaryPath, projectedContent, { encoding: "utf8", flag: "wx", mode: 384 });
32188
+ renameSync7(temporaryPath, targetPath);
31919
32189
  } finally {
31920
- rmSync7(temporaryPath, { force: true });
32190
+ rmSync8(temporaryPath, { force: true });
31921
32191
  }
31922
32192
  modelFacingFile = "AGENTS.md";
31923
32193
  modelFacingBytes = Buffer.byteLength(projectedContent, "utf8");
@@ -31988,9 +32258,9 @@ function agentInstructionDeliveryAudit(bundle, delivery) {
31988
32258
  }
31989
32259
 
31990
32260
  // src/amaster-runtime-daemon/config-state.mjs
31991
- import { existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync11, renameSync as renameSync7, rmSync as rmSync8, writeFileSync as writeFileSync10 } from "node:fs";
32261
+ import { existsSync as existsSync11, mkdirSync as mkdirSync10, readFileSync as readFileSync11, renameSync as renameSync8, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
31992
32262
  import { homedir as homedir3, hostname } from "node:os";
31993
- import { dirname as dirname8, join as join14, parse as parse3, resolve as resolve9 } from "node:path";
32263
+ import { dirname as dirname9, join as join15, parse as parse3, resolve as resolve9 } from "node:path";
31994
32264
 
31995
32265
  // src/amaster-runtime-daemon/capability-registry.mjs
31996
32266
  var BUILD_SUPPORTED_CAPABILITIES = Object.freeze([
@@ -32126,19 +32396,19 @@ function defaultMachineId() {
32126
32396
  }
32127
32397
  function runtimeHome(env) {
32128
32398
  return expandHomePath(String(
32129
- env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME || join14(homedir3(), ".amaster-employee")
32399
+ env.AMASTER_RUNTIME_STATE_HOME || env.AMASTER_RUNTIME_HOME || join15(homedir3(), ".amaster-employee")
32130
32400
  ));
32131
32401
  }
32132
32402
  function runtimeTemplatesRoot(env, home) {
32133
32403
  const configured = String(env.AMASTER_RUNTIME_TEMPLATES_ROOT ?? "").trim();
32134
- const resolved = configured ? resolve9(expandHomePath(configured)) : resolve9(String(env.PI_CODING_AGENT_DIR ?? "")) === "/data/.pi" ? "/data/templates" : resolve9(join14(home, "templates"));
32404
+ const resolved = configured ? resolve9(expandHomePath(configured)) : resolve9(String(env.PI_CODING_AGENT_DIR ?? "")) === "/data/.pi" ? "/data/templates" : resolve9(join15(home, "templates"));
32135
32405
  if (resolved === parse3(resolved).root) {
32136
32406
  throw new Error("AMASTER_RUNTIME_TEMPLATES_ROOT must not be a filesystem root");
32137
32407
  }
32138
32408
  return resolved;
32139
32409
  }
32140
32410
  function stateFilePath(env) {
32141
- return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) : join14(runtimeHome(env), "runtime-connector-state.json");
32411
+ return env.AMASTER_DAEMON_STATE_FILE ? expandHomePath(String(env.AMASTER_DAEMON_STATE_FILE)) : join15(runtimeHome(env), "runtime-connector-state.json");
32142
32412
  }
32143
32413
  function corruptStatePath(path) {
32144
32414
  const timestamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/\D/g, "").slice(0, 14);
@@ -32161,7 +32431,7 @@ function readState(env) {
32161
32431
  } catch {
32162
32432
  const quarantinePath = corruptStatePath(path);
32163
32433
  try {
32164
- renameSync7(path, quarantinePath);
32434
+ renameSync8(path, quarantinePath);
32165
32435
  process.stderr.write(`AMaster runtime state was invalid and quarantined at ${quarantinePath}
32166
32436
  `);
32167
32437
  } catch (error) {
@@ -32175,17 +32445,17 @@ function readState(env) {
32175
32445
  }
32176
32446
  function writeState(env, state) {
32177
32447
  const path = stateFilePath(env);
32178
- mkdirSync9(dirname8(path), { recursive: true });
32448
+ mkdirSync10(dirname9(path), { recursive: true });
32179
32449
  const temporaryPath = `${path}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
32180
32450
  try {
32181
- writeFileSync10(temporaryPath, `${JSON.stringify(state, null, 2)}
32451
+ writeFileSync11(temporaryPath, `${JSON.stringify(state, null, 2)}
32182
32452
  `, {
32183
32453
  flag: "wx",
32184
32454
  mode: 384
32185
32455
  });
32186
- renameSync7(temporaryPath, path);
32456
+ renameSync8(temporaryPath, path);
32187
32457
  } finally {
32188
- rmSync8(temporaryPath, { force: true });
32458
+ rmSync9(temporaryPath, { force: true });
32189
32459
  }
32190
32460
  }
32191
32461
  function buildConfig(env = process.env, flags = {}) {
@@ -32198,10 +32468,10 @@ function buildConfig(env = process.env, flags = {}) {
32198
32468
  const home = runtimeHome(env);
32199
32469
  const templatesRoot = runtimeTemplatesRoot(env, home);
32200
32470
  const runtimeWorkspacesRoot = expandHomePath(
32201
- String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ?? join14(home, "workspaces"))
32471
+ String(flags.runtimeWorkspacesRoot ?? env.AMASTER_RUNTIME_WORKSPACES_ROOT ?? join15(home, "workspaces"))
32202
32472
  );
32203
32473
  const browserSessionStateRoot = expandHomePath(String(
32204
- flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ?? join14(home, "browser-auth")
32474
+ flags.browserSessionStateRoot ?? env.AMASTER_BROWSER_SESSION_STATE_ROOT ?? join15(home, "browser-auth")
32205
32475
  ));
32206
32476
  const piToolArgumentGuardModeValue = String(
32207
32477
  flags.piToolArgumentGuardMode ?? env.AMASTER_PI_TOOL_ARGUMENT_GUARD_MODE ?? "shadow"
@@ -32227,7 +32497,7 @@ function buildConfig(env = process.env, flags = {}) {
32227
32497
  "Pi tool argument enforce thresholds cannot be more aggressive than 8 MiB transport, 512 KiB materialized, and 16x amplification"
32228
32498
  );
32229
32499
  }
32230
- mkdirSync9(runtimeWorkspacesRoot, { recursive: true });
32500
+ mkdirSync10(runtimeWorkspacesRoot, { recursive: true });
32231
32501
  const workspaceBindings = splitList(
32232
32502
  flags.workspaceAllowlist ?? env.AMASTER_WORKSPACE_ALLOWLIST ?? env.AMASTER_WORKSPACE_BINDINGS ?? runtimeWorkspacesRoot
32233
32503
  ).map(expandHomePath);
@@ -32420,7 +32690,7 @@ function createManifestOutputFlusher(opts = {}) {
32420
32690
  import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
32421
32691
  var BROWSER_CREDENTIAL_REQUEST_FD = 5;
32422
32692
  var BROWSER_CREDENTIAL_RESPONSE_FD = 6;
32423
- var MAX_BYTES2 = 16 * 1024;
32693
+ var MAX_BYTES3 = 16 * 1024;
32424
32694
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
32425
32695
  var AUTHORITY_FIELDS = /* @__PURE__ */ new Set([
32426
32696
  "version",
@@ -32439,7 +32709,7 @@ var AUTHORITY_FIELDS = /* @__PURE__ */ new Set([
32439
32709
  ]);
32440
32710
  function encodeBrowserCredentialFrame(type, payload) {
32441
32711
  if (!/^[ACREV]$/u.test(type) || !Buffer.isBuffer(payload)) throw new Error("browser_credential_frame_invalid");
32442
- if (payload.length > MAX_BYTES2) throw new Error("browser_credential_frame_too_large");
32712
+ if (payload.length > MAX_BYTES3) throw new Error("browser_credential_frame_too_large");
32443
32713
  return Buffer.concat([Buffer.from(`${type}${payload.length}
32444
32714
  `, "ascii"), payload]);
32445
32715
  }
@@ -32455,7 +32725,7 @@ function parseFrames(input, allowPartial) {
32455
32725
  const match = /^([ACREV])([0-9]{1,6})$/u.exec(input.subarray(offset, newline).toString("ascii"));
32456
32726
  if (!match) throw new Error("browser_credential_frame_invalid");
32457
32727
  const length = Number(match[2]);
32458
- if (length > MAX_BYTES2) throw new Error("browser_credential_frame_too_large");
32728
+ if (length > MAX_BYTES3) throw new Error("browser_credential_frame_too_large");
32459
32729
  const end = newline + 1 + length;
32460
32730
  if (end > input.length) {
32461
32731
  if (allowPartial) break;
@@ -32559,7 +32829,7 @@ function createBrowserCredentialChannel({ consume }) {
32559
32829
  };
32560
32830
  const handleFrame = async (frame) => {
32561
32831
  if (frame.type === "A") return handleReceipt(frame);
32562
- if (frame.type !== "R" || frame.payload.length > MAX_BYTES2) return respondError("browser_credential_request_invalid");
32832
+ if (frame.type !== "R" || frame.payload.length > MAX_BYTES3) return respondError("browser_credential_request_invalid");
32563
32833
  let decoded;
32564
32834
  try {
32565
32835
  decoded = JSON.parse(frame.payload.toString("utf8"));
@@ -32577,7 +32847,7 @@ function createBrowserCredentialChannel({ consume }) {
32577
32847
  try {
32578
32848
  const value = await consume(request);
32579
32849
  bytes = Buffer.isBuffer(value) ? value : Buffer.from(value, "utf8");
32580
- if (bytes.length === 0 || bytes.length > MAX_BYTES2) throw new Error("browser_credential_value_invalid");
32850
+ if (bytes.length === 0 || bytes.length > MAX_BYTES3) throw new Error("browser_credential_value_invalid");
32581
32851
  responseFrame = encodeBrowserCredentialFrame("V", bytes);
32582
32852
  responsePipe.write(responseFrame, () => {
32583
32853
  responseFrame.fill(0);
@@ -32598,7 +32868,7 @@ function createBrowserCredentialChannel({ consume }) {
32598
32868
  requestPipe.on("data", (chunk) => {
32599
32869
  if (closed) return;
32600
32870
  requestBuffer = Buffer.concat([requestBuffer, Buffer.from(chunk)]);
32601
- if (requestBuffer.length > MAX_BYTES2 * 3) {
32871
+ if (requestBuffer.length > MAX_BYTES3 * 3) {
32602
32872
  closed = true;
32603
32873
  responsePipe.end();
32604
32874
  return;
@@ -32631,7 +32901,7 @@ function createBrowserCredentialChannel({ consume }) {
32631
32901
  // src/amaster-runtime-daemon/browser-credential-readiness.mjs
32632
32902
  import { existsSync as existsSync12, readFileSync as readFileSync12, statSync as statSync6 } from "node:fs";
32633
32903
  import { homedir as homedir4 } from "node:os";
32634
- import { isAbsolute as isAbsolute7, join as join15, relative as relative5, resolve as resolve10 } from "node:path";
32904
+ import { isAbsolute as isAbsolute7, join as join16, relative as relative5, resolve as resolve10 } from "node:path";
32635
32905
  var CAPABILITY = "browser_credential_auth_transaction_v1";
32636
32906
  var CREDENTIAL_BROWSER_TCB = Object.freeze({
32637
32907
  package: "chrome-devtools-mcp",
@@ -32643,13 +32913,13 @@ var CREDENTIAL_BROWSER_TCB = Object.freeze({
32643
32913
  var READINESS_CACHE_TTL_MS = 5e3;
32644
32914
  var readinessCache = /* @__PURE__ */ new Map();
32645
32915
  function inspectBrowserCredentialAuthReadiness(env = process.env) {
32646
- const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join15(homedir4(), ".pi", "agent")).trim();
32916
+ const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join16(homedir4(), ".pi", "agent")).trim();
32647
32917
  const now = Date.now();
32648
32918
  const cached = readinessCache.get(home);
32649
32919
  if (cached && cached.expiresAt > now) return { ...cached.readiness };
32650
32920
  const candidates = [
32651
- join15(home, "npm", "node_modules", "@amaster.ai", "pi-browser-use", "package.json"),
32652
- join15(home, "node_modules", "@amaster.ai", "pi-browser-use", "package.json")
32921
+ join16(home, "npm", "node_modules", "@amaster.ai", "pi-browser-use", "package.json"),
32922
+ join16(home, "node_modules", "@amaster.ai", "pi-browser-use", "package.json")
32653
32923
  ];
32654
32924
  const packageAttested = candidates.some(attestedPackageManifest);
32655
32925
  const readiness = {
@@ -32687,15 +32957,15 @@ function sameCredentialBrowserTcb(value) {
32687
32957
  // src/amaster-runtime-daemon/browser-credential-env-readiness.mjs
32688
32958
  import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
32689
32959
  import { homedir as homedir5 } from "node:os";
32690
- import { join as join16 } from "node:path";
32960
+ import { join as join17 } from "node:path";
32691
32961
  var CACHE_TTL_MS = 5e3;
32692
32962
  var cache = /* @__PURE__ */ new Map();
32693
32963
  function inspectBrowserCredentialEnvReadiness(env = process.env) {
32694
- const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join16(homedir5(), ".pi", "agent")).trim();
32964
+ const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join17(homedir5(), ".pi", "agent")).trim();
32695
32965
  const now = Date.now();
32696
32966
  const cached = cache.get(home);
32697
32967
  if (cached && cached.expiresAt > now) return { ...cached.readiness };
32698
- const extensionPath = join16(home, "extensions", "browser-credential-env.mjs");
32968
+ const extensionPath = join17(home, "extensions", "browser-credential-env.mjs");
32699
32969
  let extension = false;
32700
32970
  try {
32701
32971
  const stat = lstatSync9(extensionPath);
@@ -32710,8 +32980,8 @@ function inspectBrowserCredentialEnvReadiness(env = process.env) {
32710
32980
  }
32711
32981
 
32712
32982
  // src/amaster-runtime-daemon/browser-credential-env.mjs
32713
- import { chmodSync as chmodSync5, mkdtempSync as mkdtempSync3, renameSync as renameSync8, rmSync as rmSync9, writeFileSync as writeFileSync11 } from "node:fs";
32714
- import { join as join17, resolve as resolve11 } from "node:path";
32983
+ import { chmodSync as chmodSync6, mkdtempSync as mkdtempSync3, renameSync as renameSync9, rmSync as rmSync10, writeFileSync as writeFileSync12 } from "node:fs";
32984
+ import { join as join18, resolve as resolve11 } from "node:path";
32715
32985
  var BROWSER_CREDENTIAL_ENV_CAPABILITY = "browser_credential_env_read_v1";
32716
32986
  var BROWSER_CREDENTIAL_PRIVATE_CAPABILITY = "browser_credential_auth_transaction_v1";
32717
32987
  var BROWSER_CREDENTIAL_ENV_FILE = "PI_AGENT_BROWSER_CREDENTIAL_ENV_FILE";
@@ -32787,10 +33057,10 @@ async function materializeBrowserCredentialEnv(plan, options) {
32787
33057
  const rawRunDir = String(options.runDir ?? "").trim();
32788
33058
  if (!rawRunDir) fail2("browser_credential_env_run_dir_invalid");
32789
33059
  const runDir = resolve11(rawRunDir);
32790
- const credentialDir = mkdtempSync3(join17(runDir, ".browser-credentials-"));
32791
- chmodSync5(credentialDir, 448);
32792
- const targetPath = join17(credentialDir, "credentials.env");
32793
- const temporaryPath = join17(credentialDir, ".credentials.env.tmp");
33060
+ const credentialDir = mkdtempSync3(join18(runDir, ".browser-credentials-"));
33061
+ chmodSync6(credentialDir, 448);
33062
+ const targetPath = join18(credentialDir, "credentials.env");
33063
+ const temporaryPath = join18(credentialDir, ".credentials.env.tmp");
32794
33064
  const buffers = [];
32795
33065
  const protectedValues = [];
32796
33066
  try {
@@ -32804,20 +33074,20 @@ async function materializeBrowserCredentialEnv(plan, options) {
32804
33074
  if (!protectedValues.includes(value)) protectedValues.push(value);
32805
33075
  lines.push(`${entry.key}=${dotenvQuotedValue(value)}`);
32806
33076
  }
32807
- writeFileSync11(temporaryPath, `${lines.join("\n")}
33077
+ writeFileSync12(temporaryPath, `${lines.join("\n")}
32808
33078
  `, { encoding: "utf8", mode: 384, flag: "wx" });
32809
- renameSync8(temporaryPath, targetPath);
32810
- chmodSync5(targetPath, 384);
33079
+ renameSync9(temporaryPath, targetPath);
33080
+ chmodSync6(targetPath, 384);
32811
33081
  return {
32812
33082
  dirPath: credentialDir,
32813
33083
  filePath: targetPath,
32814
33084
  protectedValues,
32815
33085
  cleanup() {
32816
- rmSync9(credentialDir, { recursive: true, force: true });
33086
+ rmSync10(credentialDir, { recursive: true, force: true });
32817
33087
  }
32818
33088
  };
32819
33089
  } catch (error) {
32820
- rmSync9(credentialDir, { recursive: true, force: true });
33090
+ rmSync10(credentialDir, { recursive: true, force: true });
32821
33091
  throw error;
32822
33092
  } finally {
32823
33093
  for (const buffer of buffers) buffer.fill(0);
@@ -33205,8 +33475,8 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
33205
33475
 
33206
33476
  // src/amaster-runtime-daemon/workspace-guard.mjs
33207
33477
  import { createHash as createHash16 } from "node:crypto";
33208
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, realpathSync as realpathSync11, statSync as statSync7 } from "node:fs";
33209
- import { basename as basename6, join as join18, isAbsolute as isAbsolute9, relative as relative7, resolve as resolve13 } from "node:path";
33478
+ import { existsSync as existsSync13, mkdirSync as mkdirSync11, realpathSync as realpathSync11, statSync as statSync7 } from "node:fs";
33479
+ import { basename as basename6, join as join19, isAbsolute as isAbsolute9, relative as relative7, resolve as resolve13 } from "node:path";
33210
33480
  function pathWithin3(candidate, root) {
33211
33481
  const rel = relative7(root, candidate);
33212
33482
  return rel === "" || !rel.startsWith("..") && !isAbsolute9(rel);
@@ -33262,7 +33532,7 @@ function workspaceLabel(sourceWorkspacePath, payload) {
33262
33532
  }
33263
33533
  function workspacesRoot(config) {
33264
33534
  const root = resolve13(expandHomePath(config.runtimeWorkspacesRoot ?? "~/.amaster-employee/workspaces"));
33265
- mkdirSync10(root, { recursive: true });
33535
+ mkdirSync11(root, { recursive: true });
33266
33536
  return realpathSync11(root);
33267
33537
  }
33268
33538
  function resolveExecutionWorkspace(config, command, opts = {}) {
@@ -33275,11 +33545,11 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
33275
33545
  const workspaceKey = `${safeSegment(workspaceLabel(sourceWorkspacePath, payload), "workspace")}-${shortHash(sourceWorkspacePath)}`;
33276
33546
  const issueKey = `${safeSegment(issueLabel(command, payload), "issue")}-${shortHash(issueId, 8)}`;
33277
33547
  const runKey = `${safeSegment(runId, "run")}-${shortHash(runId, 8)}`;
33278
- const runDir = join18(root, workspaceKey, issueKey, runKey);
33279
- const cwd = join18(runDir, "workdir");
33280
- const executorHome = join18(runDir, "executors", safeSegment(executorKind, "executor"));
33281
- mkdirSync10(cwd, { recursive: true });
33282
- mkdirSync10(executorHome, { recursive: true });
33548
+ const runDir = join19(root, workspaceKey, issueKey, runKey);
33549
+ const cwd = join19(runDir, "workdir");
33550
+ const executorHome = join19(runDir, "executors", safeSegment(executorKind, "executor"));
33551
+ mkdirSync11(cwd, { recursive: true });
33552
+ mkdirSync11(executorHome, { recursive: true });
33283
33553
  const workspace = {
33284
33554
  managed: true,
33285
33555
  cwd,
@@ -33302,7 +33572,7 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
33302
33572
 
33303
33573
  // src/amaster-runtime-daemon/workspace-gc.mjs
33304
33574
  import { existsSync as existsSync14, readdirSync as readdirSync8, statSync as statSync8 } from "node:fs";
33305
- import { join as join19, resolve as resolve14 } from "node:path";
33575
+ import { join as join20, resolve as resolve14 } from "node:path";
33306
33576
  function readIsoTime(value) {
33307
33577
  if (typeof value !== "string" || !value.trim()) return null;
33308
33578
  const time2 = new Date(value).getTime();
@@ -33325,7 +33595,7 @@ function walkWorkdirs(root) {
33325
33595
  }
33326
33596
  for (const entry of entries) {
33327
33597
  if (!entry.isDirectory()) continue;
33328
- const fullPath = join19(current, entry.name);
33598
+ const fullPath = join20(current, entry.name);
33329
33599
  if (entry.name === "workdir" && existsSync14(workspaceManifestPath(fullPath))) {
33330
33600
  workdirs.push(fullPath);
33331
33601
  continue;
@@ -33357,7 +33627,7 @@ function directorySizeBytes(path) {
33357
33627
  continue;
33358
33628
  }
33359
33629
  for (const entry of entries) {
33360
- stack.push(join19(current, entry.name));
33630
+ stack.push(join20(current, entry.name));
33361
33631
  }
33362
33632
  continue;
33363
33633
  }
@@ -33432,21 +33702,21 @@ function planManagedWorkspaceGcDryRun(input) {
33432
33702
  import { createHash as createHash17 } from "node:crypto";
33433
33703
  import {
33434
33704
  accessSync,
33435
- chmodSync as chmodSync6,
33705
+ chmodSync as chmodSync7,
33436
33706
  constants as constants4,
33437
33707
  existsSync as existsSync15,
33438
33708
  lstatSync as lstatSync11,
33439
- mkdirSync as mkdirSync11,
33709
+ mkdirSync as mkdirSync12,
33440
33710
  mkdtempSync as mkdtempSync4,
33441
33711
  readFileSync as readFileSync15,
33442
33712
  readdirSync as readdirSync9,
33443
- renameSync as renameSync9,
33444
- rmSync as rmSync10,
33713
+ renameSync as renameSync10,
33714
+ rmSync as rmSync11,
33445
33715
  statSync as statSync9,
33446
33716
  unlinkSync as unlinkSync2,
33447
- writeFileSync as writeFileSync12
33717
+ writeFileSync as writeFileSync13
33448
33718
  } from "node:fs";
33449
- import { dirname as dirname9, extname, isAbsolute as isAbsolute10, join as join20, parse as parse4, resolve as resolve15, sep as sep4 } from "node:path";
33719
+ import { dirname as dirname10, extname, isAbsolute as isAbsolute10, join as join21, parse as parse4, resolve as resolve15, sep as sep4 } from "node:path";
33450
33720
  import { fileURLToPath } from "node:url";
33451
33721
  var PRESET_TEMPLATE_MANIFEST_FILE = ".mirrorx-preset-templates.json";
33452
33722
  var MAX_PRESET_TEMPLATE_FILES = 256;
@@ -33472,7 +33742,7 @@ function modeAllows(stat, identity, ownerBit, groupBit, otherBit) {
33472
33742
  function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
33473
33743
  if (!identity) {
33474
33744
  accessSync(targetDir, constants4.R_OK | constants4.X_OK);
33475
- for (const name of fileNames) accessSync(join20(targetDir, name), constants4.R_OK);
33745
+ for (const name of fileNames) accessSync(join21(targetDir, name), constants4.R_OK);
33476
33746
  return;
33477
33747
  }
33478
33748
  let current = targetDir;
@@ -33481,7 +33751,7 @@ function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
33481
33751
  if (!stat.isDirectory() || !modeAllows(stat, identity, 64, 8, 1)) {
33482
33752
  throw new Error(`preset_template_executor_path_unreadable: ${current}`);
33483
33753
  }
33484
- const parent = dirname9(current);
33754
+ const parent = dirname10(current);
33485
33755
  if (parent === current) break;
33486
33756
  current = parent;
33487
33757
  }
@@ -33490,7 +33760,7 @@ function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
33490
33760
  throw new Error(`preset_template_executor_catalog_unreadable: ${targetDir}`);
33491
33761
  }
33492
33762
  for (const name of fileNames) {
33493
- const path = join20(targetDir, name);
33763
+ const path = join21(targetDir, name);
33494
33764
  const stat = statSync9(path);
33495
33765
  if (!stat.isFile() || !modeAllows(stat, identity, 256, 32, 4)) {
33496
33766
  throw new Error(`preset_template_executor_file_unreadable: ${name}`);
@@ -33534,7 +33804,7 @@ function readManifest(manifestPath, { strict }) {
33534
33804
  }
33535
33805
  function verifiedBundleFiles(sourceDir, manifest) {
33536
33806
  return manifest.files.map((entry) => {
33537
- const sourcePath = join20(sourceDir, entry.name);
33807
+ const sourcePath = join21(sourceDir, entry.name);
33538
33808
  const stat = lstatSync11(sourcePath);
33539
33809
  if (!stat.isFile() || stat.isSymbolicLink()) {
33540
33810
  throw new Error(`preset_template_bundle_file_unsafe: ${entry.name}`);
@@ -33549,7 +33819,7 @@ function verifiedBundleFiles(sourceDir, manifest) {
33549
33819
  function removeRetiredPresetFiles(targetDir, previousManifest, nextNames) {
33550
33820
  for (const entry of previousManifest.files) {
33551
33821
  if (nextNames.has(entry.name)) continue;
33552
- const targetPath = join20(targetDir, entry.name);
33822
+ const targetPath = join21(targetDir, entry.name);
33553
33823
  if (!existsSync15(targetPath)) continue;
33554
33824
  const stat = lstatSync11(targetPath);
33555
33825
  if (stat.isDirectory()) {
@@ -33564,36 +33834,36 @@ function materializeBundledPresetTemplates(input) {
33564
33834
  if (sourceDir === targetDir || sourceDir.startsWith(`${targetDir}${sep4}`) || targetDir.startsWith(`${sourceDir}${sep4}`)) {
33565
33835
  throw new Error("preset_template_source_target_overlap");
33566
33836
  }
33567
- const manifest = readManifest(join20(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
33837
+ const manifest = readManifest(join21(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
33568
33838
  const verifiedFiles = verifiedBundleFiles(sourceDir, manifest);
33569
- mkdirSync11(dirname9(targetDir), { recursive: true, mode: 493 });
33839
+ mkdirSync12(dirname10(targetDir), { recursive: true, mode: 493 });
33570
33840
  const targetStat = lstatIfExists(targetDir);
33571
33841
  if (targetStat && (!targetStat.isDirectory() || targetStat.isSymbolicLink())) {
33572
33842
  throw new Error("preset_template_target_root_unsafe");
33573
33843
  }
33574
- mkdirSync11(targetDir, { recursive: true, mode: 493 });
33575
- const previousManifest = readManifest(join20(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
33576
- const stageDir = mkdtempSync4(join20(dirname9(targetDir), ".mirrorx-preset-templates-"));
33844
+ mkdirSync12(targetDir, { recursive: true, mode: 493 });
33845
+ const previousManifest = readManifest(join21(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
33846
+ const stageDir = mkdtempSync4(join21(dirname10(targetDir), ".mirrorx-preset-templates-"));
33577
33847
  try {
33578
33848
  for (const file of verifiedFiles) {
33579
- const stagedPath = join20(stageDir, file.name);
33580
- writeFileSync12(stagedPath, file.body, { mode: 292 });
33581
- chmodSync6(stagedPath, 292);
33582
- renameSync9(stagedPath, join20(targetDir, file.name));
33849
+ const stagedPath = join21(stageDir, file.name);
33850
+ writeFileSync13(stagedPath, file.body, { mode: 292 });
33851
+ chmodSync7(stagedPath, 292);
33852
+ renameSync10(stagedPath, join21(targetDir, file.name));
33583
33853
  }
33584
33854
  removeRetiredPresetFiles(targetDir, previousManifest, new Set(manifest.files.map((file) => file.name)));
33585
- const stagedManifest = join20(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
33586
- writeFileSync12(stagedManifest, `${JSON.stringify({
33855
+ const stagedManifest = join21(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
33856
+ writeFileSync13(stagedManifest, `${JSON.stringify({
33587
33857
  schemaVersion: manifest.schemaVersion,
33588
33858
  files: manifest.files
33589
33859
  }, null, 2)}
33590
33860
  `, { mode: 292 });
33591
- chmodSync6(stagedManifest, 292);
33592
- renameSync9(stagedManifest, join20(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
33861
+ chmodSync7(stagedManifest, 292);
33862
+ renameSync10(stagedManifest, join21(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
33593
33863
  } finally {
33594
- rmSync10(stageDir, { recursive: true, force: true });
33864
+ rmSync11(stageDir, { recursive: true, force: true });
33595
33865
  }
33596
- chmodSync6(targetDir, 493);
33866
+ chmodSync7(targetDir, 493);
33597
33867
  return {
33598
33868
  fileCount: manifest.files.length,
33599
33869
  totalBytes: manifest.totalBytes,
@@ -33607,11 +33877,11 @@ function materializeRuntimePresetTemplates(input) {
33607
33877
  targetDir: input.targetDir
33608
33878
  });
33609
33879
  const manifestBody = readFileSync15(
33610
- join20(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
33880
+ join21(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
33611
33881
  );
33612
33882
  const manifest = JSON.parse(manifestBody.toString("utf8"));
33613
33883
  for (const file of manifest.files) {
33614
- const body = readFileSync15(join20(materialized.targetDir, file.name));
33884
+ const body = readFileSync15(join21(materialized.targetDir, file.name));
33615
33885
  if (sha2562(body) !== file.sha256) {
33616
33886
  throw new Error(`preset_template_materialized_digest_mismatch: ${file.name}`);
33617
33887
  }
@@ -33635,7 +33905,7 @@ function materializeRuntimePresetTemplates(input) {
33635
33905
 
33636
33906
  // src/amaster-runtime-daemon/runtime-status-summary.mjs
33637
33907
  import { existsSync as existsSync16, readdirSync as readdirSync10, statSync as statSync10 } from "node:fs";
33638
- import { dirname as dirname10, join as join21, resolve as resolve16 } from "node:path";
33908
+ import { dirname as dirname11, join as join22, resolve as resolve16 } from "node:path";
33639
33909
  function runtimeStatusDirectoryEntries(path) {
33640
33910
  try {
33641
33911
  return readdirSync10(path, { withFileTypes: true });
@@ -33658,7 +33928,7 @@ function runtimeStatusDirectorySizeBytes(path) {
33658
33928
  if (!stat || stat.isSymbolicLink()) continue;
33659
33929
  if (stat.isDirectory()) {
33660
33930
  for (const entry of runtimeStatusDirectoryEntries(current)) {
33661
- stack.push(join21(current, entry.name));
33931
+ stack.push(join22(current, entry.name));
33662
33932
  }
33663
33933
  continue;
33664
33934
  }
@@ -33675,7 +33945,7 @@ function walkRuntimeStatusManagedWorkdirs(root) {
33675
33945
  if (!current) continue;
33676
33946
  for (const entry of runtimeStatusDirectoryEntries(current)) {
33677
33947
  if (!entry.isDirectory()) continue;
33678
- const fullPath = join21(current, entry.name);
33948
+ const fullPath = join22(current, entry.name);
33679
33949
  if (entry.name === "workdir" && existsSync16(workspaceManifestPath(fullPath))) {
33680
33950
  workdirs.push(fullPath);
33681
33951
  continue;
@@ -33717,7 +33987,7 @@ function summarizeRuntimeStatusRecentRun(workdir, manifest) {
33717
33987
  }
33718
33988
  function runtimeStatusOutboxDir(config) {
33719
33989
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
33720
- return join21(dirname10(stateFilePath({
33990
+ return join22(dirname11(stateFilePath({
33721
33991
  AMASTER_DAEMON_STATE_FILE: statePath
33722
33992
  })), "result-outbox");
33723
33993
  }
@@ -33725,7 +33995,7 @@ function runtimeStatusRunCompletionDir(config) {
33725
33995
  const explicit = config.AMASTER_RUN_COMPLETION_STATE_DIR ?? config.runCompletionStateDir;
33726
33996
  if (typeof explicit === "string" && explicit.trim()) return resolve16(explicit);
33727
33997
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
33728
- return join21(dirname10(stateFilePath({
33998
+ return join22(dirname11(stateFilePath({
33729
33999
  AMASTER_DAEMON_STATE_FILE: statePath
33730
34000
  })), "run-completion-state");
33731
34001
  }
@@ -33762,9 +34032,9 @@ function summarizeRuntimeLocalState(input) {
33762
34032
  }
33763
34033
  }
33764
34034
  const pendingOutboxDir = runtimeStatusOutboxDir(config);
33765
- const invalidOutboxDir = join21(pendingOutboxDir, "invalid");
34035
+ const invalidOutboxDir = join22(pendingOutboxDir, "invalid");
33766
34036
  const pendingRunCompletionDir = runtimeStatusRunCompletionDir(config);
33767
- const invalidRunCompletionDir = join21(pendingRunCompletionDir, "invalid");
34037
+ const invalidRunCompletionDir = join22(pendingRunCompletionDir, "invalid");
33768
34038
  return {
33769
34039
  managedWorkspacesRoot: root,
33770
34040
  managedWorkdirCount: workdirs.length,
@@ -34126,7 +34396,7 @@ export default function amasterProjectInstructions(pi) {
34126
34396
  import { spawnSync as spawnSync4 } from "node:child_process";
34127
34397
  import { createHash as createHash18 } from "node:crypto";
34128
34398
  import { existsSync as existsSync17, readdirSync as readdirSync11, readFileSync as readFileSync18, statSync as statSync11 } from "node:fs";
34129
- import { basename as basename7, extname as extname2, isAbsolute as isAbsolute11, join as join22, relative as relative8, resolve as resolve18 } from "node:path";
34399
+ import { basename as basename7, extname as extname2, isAbsolute as isAbsolute11, join as join23, relative as relative8, resolve as resolve18 } from "node:path";
34130
34400
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
34131
34401
  var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
34132
34402
  [".md", "markdown"],
@@ -34244,7 +34514,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
34244
34514
  if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
34245
34515
  if (entry.name === ".git") continue;
34246
34516
  }
34247
- const fullPath = join22(current, entry.name);
34517
+ const fullPath = join23(current, entry.name);
34248
34518
  const relativePath = normalizeRelativePath(root, fullPath);
34249
34519
  if (!isSafeRelativePath(relativePath)) continue;
34250
34520
  if (basename7(relativePath) === ".amaster-runtime.json") continue;
@@ -34322,7 +34592,7 @@ function sanitizeRuntimeService(entry) {
34322
34592
  };
34323
34593
  }
34324
34594
  function readRuntimeServicesSnapshot(cwd) {
34325
- const snapshotPath = join22(resolve18(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
34595
+ const snapshotPath = join23(resolve18(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
34326
34596
  if (!existsSync17(snapshotPath)) return [];
34327
34597
  try {
34328
34598
  const parsed = JSON.parse(readFileSync18(snapshotPath, "utf8"));
@@ -34427,7 +34697,7 @@ function assertRequiredTaskAttachmentMaterialized(input, materialized) {
34427
34697
  }
34428
34698
 
34429
34699
  // src/amaster-runtime-daemon.mjs
34430
- var CONNECTOR_VERSION = "0.1.5";
34700
+ var CONNECTOR_VERSION = "0.1.7";
34431
34701
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
34432
34702
  var SUPPORTED_TASK_CONTEXT_VERSIONS = Object.freeze([TASK_CONTEXT_MANIFEST_VERSION, TASK_CONTEXT_V2]);
34433
34703
  var daemonRequire = createRequire(import.meta.url);
@@ -34527,7 +34797,7 @@ function resultOutboxPendingCount(config) {
34527
34797
  try {
34528
34798
  let pending = 0;
34529
34799
  for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json"))) {
34530
- if (readValidResultOutboxEntryOrQuarantine(config, file, join23(dir, file))) {
34800
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join24(dir, file))) {
34531
34801
  pending += 1;
34532
34802
  }
34533
34803
  }
@@ -34539,17 +34809,17 @@ function resultOutboxPendingCount(config) {
34539
34809
  function runCompletionStateDir(config) {
34540
34810
  const explicit = readString(process.env.AMASTER_RUN_COMPLETION_STATE_DIR);
34541
34811
  if (explicit) return resolve19(expandHomePath(explicit));
34542
- return join23(dirname11(stateFilePath(process.env)), "run-completion-state");
34812
+ return join24(dirname12(stateFilePath(process.env)), "run-completion-state");
34543
34813
  }
34544
34814
  function runCompletionStateInvalidDir(config) {
34545
- return join23(runCompletionStateDir(config), "invalid");
34815
+ return join24(runCompletionStateDir(config), "invalid");
34546
34816
  }
34547
34817
  function quarantineInvalidRunCompletionState(config, filePath, reason) {
34548
34818
  const invalidDir = runCompletionStateInvalidDir(config);
34549
- mkdirSync12(invalidDir, { recursive: true, mode: 448 });
34550
- const destination = join23(invalidDir, basename8(filePath));
34819
+ mkdirSync13(invalidDir, { recursive: true, mode: 448 });
34820
+ const destination = join24(invalidDir, basename8(filePath));
34551
34821
  try {
34552
- renameSync10(filePath, destination);
34822
+ renameSync11(filePath, destination);
34553
34823
  } catch {
34554
34824
  copyFileSync2(filePath, destination);
34555
34825
  unlinkSync3(filePath);
@@ -34605,7 +34875,7 @@ function resultOutboxActiveRunCommands(config) {
34605
34875
  const outboxPending = resultOutboxPendingCount(config);
34606
34876
  const entries = [];
34607
34877
  for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json")).sort()) {
34608
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join23(dir, file));
34878
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join24(dir, file));
34609
34879
  if (!entry) continue;
34610
34880
  const activeRun = asRecord(entry.activeRun);
34611
34881
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -34641,7 +34911,7 @@ function resultOutboxFailedRunCommands(config) {
34641
34911
  for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
34642
34912
  let entry;
34643
34913
  try {
34644
- entry = asRecord(JSON.parse(readFileSync19(join23(dir, file), "utf8")));
34914
+ entry = asRecord(JSON.parse(readFileSync19(join24(dir, file), "utf8")));
34645
34915
  } catch {
34646
34916
  continue;
34647
34917
  }
@@ -34751,10 +35021,10 @@ function safeSkillRootSummary(kind, source, pathValue) {
34751
35021
  try {
34752
35022
  for (const name of readdirSync12(pathValue)) {
34753
35023
  if (name.startsWith(".")) continue;
34754
- const skillDir = join23(pathValue, name);
35024
+ const skillDir = join24(pathValue, name);
34755
35025
  try {
34756
35026
  if (!statSync12(skillDir).isDirectory()) continue;
34757
- if (!existsSync18(join23(skillDir, "SKILL.md"))) continue;
35027
+ if (!existsSync18(join24(skillDir, "SKILL.md"))) continue;
34758
35028
  skillCount += 1;
34759
35029
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
34760
35030
  truncated = true;
@@ -34805,7 +35075,7 @@ function objectKeyCount(value) {
34805
35075
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
34806
35076
  }
34807
35077
  function defaultPiCodingAgentDir() {
34808
- return join23(homedir6(), ".pi", "agent");
35078
+ return join24(homedir6(), ".pi", "agent");
34809
35079
  }
34810
35080
  function piCapabilitySourcesDiagnostics() {
34811
35081
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -34814,14 +35084,14 @@ function piCapabilitySourcesDiagnostics() {
34814
35084
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
34815
35085
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
34816
35086
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
34817
- const userSkillsPath = piAgentHome ? join23(piAgentHome, "skills") : null;
35087
+ const userSkillsPath = piAgentHome ? join24(piAgentHome, "skills") : null;
34818
35088
  const configuredMarketplaceSkillsPath = safeExpandPath(
34819
35089
  process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR
34820
35090
  );
34821
- const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join23(piAgentHome, "marketplace", "skills") : null);
35091
+ const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join24(piAgentHome, "marketplace", "skills") : null);
34822
35092
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
34823
- const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join23(piAgentHome, "mcp.json") : null);
34824
- const settingsConfigPath = piCodingAgentDir ? join23(piCodingAgentDir, "settings.json") : null;
35093
+ const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join24(piAgentHome, "mcp.json") : null);
35094
+ const settingsConfigPath = piCodingAgentDir ? join24(piCodingAgentDir, "settings.json") : null;
34825
35095
  const skillRoots = [
34826
35096
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
34827
35097
  safeSkillRootSummary(
@@ -35117,25 +35387,25 @@ function materializePiRuntimeSystemPrompt(config, promptRoot, commandId, content
35117
35387
  const normalizedCommandId = readString(commandId);
35118
35388
  if (!normalizedCommandId) throw new Error("pi_runtime_system_prompt_command_id_missing");
35119
35389
  const promptIdentity = createHash19("sha256").update(normalizedCommandId).digest("hex");
35120
- const promptDir = join23(promptRoot, "tmp");
35121
- mkdirSync12(promptDir, { recursive: true, mode: 448 });
35390
+ const promptDir = join24(promptRoot, "tmp");
35391
+ mkdirSync13(promptDir, { recursive: true, mode: 448 });
35122
35392
  const promptDirStat = lstatSync13(promptDir);
35123
35393
  if (!promptDirStat.isDirectory() || promptDirStat.isSymbolicLink()) {
35124
35394
  throw new Error("pi_runtime_system_prompt_directory_invalid");
35125
35395
  }
35126
- chmodSync7(promptDir, 448);
35127
- const promptPath = join23(promptDir, `runtime-system-${promptIdentity}.md`);
35128
- const temporaryPath = join23(promptDir, `.runtime-system.${process.pid}.${randomUUID2()}.tmp`);
35396
+ chmodSync8(promptDir, 448);
35397
+ const promptPath = join24(promptDir, `runtime-system-${promptIdentity}.md`);
35398
+ const temporaryPath = join24(promptDir, `.runtime-system.${process.pid}.${randomUUID2()}.tmp`);
35129
35399
  try {
35130
- writeFileSync13(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
35131
- renameSync10(temporaryPath, promptPath);
35132
- chmodSync7(promptPath, 384);
35400
+ writeFileSync14(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
35401
+ renameSync11(temporaryPath, promptPath);
35402
+ chmodSync8(promptPath, 384);
35133
35403
  const promptMode = statSync12(promptPath).mode & 511;
35134
35404
  if (promptMode !== 384) {
35135
35405
  throw new Error(`pi_runtime_system_prompt_permissions_failed: mode=${promptMode.toString(8)}`);
35136
35406
  }
35137
35407
  } finally {
35138
- rmSync11(temporaryPath, { force: true });
35408
+ rmSync12(temporaryPath, { force: true });
35139
35409
  }
35140
35410
  handoffPiRunPathsToChild(config, [promptDir, promptPath]);
35141
35411
  return promptPath;
@@ -35301,7 +35571,7 @@ AMASTER_MACHINE_ID=${quoteShell(config.machineId)}
35301
35571
  AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
35302
35572
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
35303
35573
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
35304
- AMASTER_DAEMON_STATE_FILE=${quoteShell(join23(homedir6(), ".amaster-employee", "runtime-connector-state.json"))}
35574
+ AMASTER_DAEMON_STATE_FILE=${quoteShell(join24(homedir6(), ".amaster-employee", "runtime-connector-state.json"))}
35305
35575
  EOF
35306
35576
 
35307
35577
  set -a
@@ -35779,21 +36049,21 @@ function browserSessionProfileIdentity(config, session) {
35779
36049
  function ensureBrowserSessionProfile(config, session) {
35780
36050
  const identity = browserSessionProfileIdentity(config, session);
35781
36051
  const profileRoot = resolve19(config.browserSessionStateRoot);
35782
- mkdirSync12(profileRoot, { recursive: true, mode: 448 });
36052
+ mkdirSync13(profileRoot, { recursive: true, mode: 448 });
35783
36053
  if (lstatSync13(profileRoot).isSymbolicLink() || !lstatSync13(profileRoot).isDirectory()) {
35784
36054
  throw new Error("browser_session_profile_path_invalid");
35785
36055
  }
35786
- chmodSync7(profileRoot, 448);
36056
+ chmodSync8(profileRoot, 448);
35787
36057
  const userDataDir = resolve19(profileRoot, identity.localOpaqueRef);
35788
36058
  if (!pathWithin3(userDataDir, profileRoot)) {
35789
36059
  throw new Error("browser_session_profile_path_invalid");
35790
36060
  }
35791
- mkdirSync12(userDataDir, { recursive: true, mode: 448 });
36061
+ mkdirSync13(userDataDir, { recursive: true, mode: 448 });
35792
36062
  if (lstatSync13(userDataDir).isSymbolicLink() || !lstatSync13(userDataDir).isDirectory()) {
35793
36063
  throw new Error("browser_session_profile_path_invalid");
35794
36064
  }
35795
- chmodSync7(userDataDir, 448);
35796
- const markerPath = join23(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36065
+ chmodSync8(userDataDir, 448);
36066
+ const markerPath = join24(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
35797
36067
  if (existsSync18(markerPath)) {
35798
36068
  if (lstatSync13(markerPath).isSymbolicLink()) {
35799
36069
  throw new Error("browser_session_profile_identity_invalid");
@@ -35803,15 +36073,15 @@ function ensureBrowserSessionProfile(config, session) {
35803
36073
  throw new Error("browser_session_profile_identity_invalid");
35804
36074
  }
35805
36075
  } else {
35806
- const temporaryPath = join23(
36076
+ const temporaryPath = join24(
35807
36077
  userDataDir,
35808
36078
  `.${BROWSER_SESSION_PROFILE_OWNER_MARKER}.${process.pid}.${createHash19("sha256").update(randomUUID2()).digest("hex")}`
35809
36079
  );
35810
- writeFileSync13(temporaryPath, `${JSON.stringify(identity)}
36080
+ writeFileSync14(temporaryPath, `${JSON.stringify(identity)}
35811
36081
  `, { mode: 384, flag: "wx" });
35812
- renameSync10(temporaryPath, markerPath);
36082
+ renameSync11(temporaryPath, markerPath);
35813
36083
  }
35814
- chmodSync7(markerPath, 384);
36084
+ chmodSync8(markerPath, 384);
35815
36085
  return { profileRoot, userDataDir, identity };
35816
36086
  }
35817
36087
  function cleanupBrowserSessionProfile(config, value) {
@@ -35825,14 +36095,14 @@ function cleanupBrowserSessionProfile(config, value) {
35825
36095
  if (lstatSync13(userDataDir).isSymbolicLink() || !lstatSync13(userDataDir).isDirectory()) {
35826
36096
  throw new Error("browser_session_profile_cleanup_invalid");
35827
36097
  }
35828
- const markerPath = join23(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36098
+ const markerPath = join24(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
35829
36099
  if (!existsSync18(markerPath) || lstatSync13(markerPath).isSymbolicLink()) {
35830
36100
  throw new Error("browser_session_profile_cleanup_invalid");
35831
36101
  }
35832
36102
  if (JSON.stringify(readJsonFile2(markerPath)) !== JSON.stringify(identity)) {
35833
36103
  throw new Error("browser_session_profile_cleanup_invalid");
35834
36104
  }
35835
- rmSync11(userDataDir, { recursive: true, force: false });
36105
+ rmSync12(userDataDir, { recursive: true, force: false });
35836
36106
  return { outcome: "deleted", identity };
35837
36107
  }
35838
36108
  function readJsonFile2(filePath) {
@@ -35848,8 +36118,8 @@ function syncPiExecutorProviderConfig(config, agentDir, providerConfig) {
35848
36118
  const { modelsSynced, settingsSynced } = syncAmasterProviderFiles(agentDir, providerConfig);
35849
36119
  if (!modelsSynced && !settingsSynced) return null;
35850
36120
  handoffPiRunPathsToChild(config, [
35851
- modelsSynced ? join23(agentDir, "models.json") : null,
35852
- settingsSynced ? join23(agentDir, "settings.json") : null
36121
+ modelsSynced ? join24(agentDir, "models.json") : null,
36122
+ settingsSynced ? join24(agentDir, "settings.json") : null
35853
36123
  ]);
35854
36124
  return { modelsSynced, settingsSynced };
35855
36125
  }
@@ -35966,17 +36236,17 @@ async function materializeEffectiveAgentInstructions(config, command, workspace,
35966
36236
  }
35967
36237
  const target = safeAgentInstructionMaterializationTarget(workspace, filePath);
35968
36238
  if (!target) throw new Error(`context_envelope_instruction_path_invalid: ${filePath}`);
35969
- mkdirSync12(dirname11(target.targetPath), { recursive: true });
36239
+ mkdirSync13(dirname12(target.targetPath), { recursive: true });
35970
36240
  const temporaryPath = `${target.targetPath}.mirrorx-${command.commandId}.tmp`;
35971
36241
  try {
35972
- writeFileSync13(temporaryPath, content, { encoding: "utf8", mode: 384 });
36242
+ writeFileSync14(temporaryPath, content, { encoding: "utf8", mode: 384 });
35973
36243
  const readBack = readFileSync19(temporaryPath, "utf8");
35974
36244
  if (readBack !== content) {
35975
36245
  throw new Error(`context_envelope_instruction_readback_mismatch: ${filePath}`);
35976
36246
  }
35977
- renameSync10(temporaryPath, target.targetPath);
36247
+ renameSync11(temporaryPath, target.targetPath);
35978
36248
  } finally {
35979
- rmSync11(temporaryPath, { force: true });
36249
+ rmSync12(temporaryPath, { force: true });
35980
36250
  }
35981
36251
  materialized.push({
35982
36252
  path: target.relativePath,
@@ -36010,7 +36280,7 @@ function wikiTreePathForCommand(command, workspaceBindings) {
36010
36280
  const candidates = [];
36011
36281
  if (root.endsWith("paperclipai.plugin-llm-wiki")) candidates.push(root);
36012
36282
  if (basename8(root) === "plugin-data" && companyId) {
36013
- candidates.push(join23(root, companyId, "paperclipai.plugin-llm-wiki"));
36283
+ candidates.push(join24(root, companyId, "paperclipai.plugin-llm-wiki"));
36014
36284
  }
36015
36285
  for (const candidate of candidates) {
36016
36286
  try {
@@ -36249,13 +36519,13 @@ function attachPiProjectInstructionExtension(profile, input) {
36249
36519
  "managed Pi profile is missing"
36250
36520
  );
36251
36521
  }
36252
- const projectInstructionExtensionPath = join23(
36522
+ const projectInstructionExtensionPath = join24(
36253
36523
  profile.profileRoot,
36254
36524
  "extensions",
36255
36525
  MANAGED_PI_PROJECT_INSTRUCTION_FILENAME
36256
36526
  );
36257
36527
  const contract = { projectInstructionPath: resolve19(input.cwd, "AGENTS.md") };
36258
- writeFileSync13(projectInstructionExtensionPath, managedPiProjectInstructionExtensionSource(contract), { mode: 384 });
36528
+ writeFileSync14(projectInstructionExtensionPath, managedPiProjectInstructionExtensionSource(contract), { mode: 384 });
36259
36529
  return projectInstructionExtensionPath;
36260
36530
  }
36261
36531
  function commandUsesPiExecutor(command) {
@@ -36298,18 +36568,18 @@ function buildExecutorEnv(config, command, workspace) {
36298
36568
  };
36299
36569
  }
36300
36570
  function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
36301
- const profileRoot = mkdtempSync5(join23(tmpdir(), "amaster-pi-model-call-"));
36302
- const home = join23(profileRoot, "home");
36303
- const sessionsDir = join23(profileRoot, "sessions");
36304
- const tempDir = join23(profileRoot, "tmp");
36571
+ const profileRoot = mkdtempSync5(join24(tmpdir(), "amaster-pi-model-call-"));
36572
+ const home = join24(profileRoot, "home");
36573
+ const sessionsDir = join24(profileRoot, "sessions");
36574
+ const tempDir = join24(profileRoot, "tmp");
36305
36575
  for (const directory of [home, sessionsDir, tempDir]) {
36306
- mkdirSync12(directory, { recursive: true, mode: 448 });
36576
+ mkdirSync13(directory, { recursive: true, mode: 448 });
36307
36577
  }
36308
36578
  try {
36309
36579
  const extensionArgs = [];
36310
36580
  if (options.responseContract) {
36311
- const extensionPath = join23(profileRoot, "model-call-output-contract.js");
36312
- writeFileSync13(
36581
+ const extensionPath = join24(profileRoot, "model-call-output-contract.js");
36582
+ writeFileSync14(
36313
36583
  extensionPath,
36314
36584
  modelCallOutputContractExtensionSource(options.responseContract.maxOutputTokens),
36315
36585
  { mode: 384 }
@@ -36329,12 +36599,12 @@ function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
36329
36599
  }
36330
36600
  };
36331
36601
  } catch (error) {
36332
- rmSync11(profileRoot, { recursive: true, force: true });
36602
+ rmSync12(profileRoot, { recursive: true, force: true });
36333
36603
  throw error;
36334
36604
  }
36335
36605
  }
36336
36606
  function cleanupPiModelCallProfile(profile) {
36337
- if (profile?.profileRoot) rmSync11(profile.profileRoot, { recursive: true, force: true });
36607
+ if (profile?.profileRoot) rmSync12(profile.profileRoot, { recursive: true, force: true });
36338
36608
  }
36339
36609
  function splitExtraArgs(value) {
36340
36610
  return splitList(value).flatMap((entry) => entry.split(/\s+/).filter(Boolean));
@@ -37328,7 +37598,7 @@ function walkManagedWorkdirs(root) {
37328
37598
  }
37329
37599
  for (const entry of entries) {
37330
37600
  if (!entry.isDirectory()) continue;
37331
- const fullPath = join23(current, entry.name);
37601
+ const fullPath = join24(current, entry.name);
37332
37602
  if (entry.name === "workdir" && existsSync18(workspaceManifestPath(fullPath))) {
37333
37603
  workdirs.push(fullPath);
37334
37604
  continue;
@@ -38331,14 +38601,14 @@ async function completeCommand(config, command, status, result2, error) {
38331
38601
  function resultOutboxDir(config) {
38332
38602
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
38333
38603
  if (explicit) return resolve19(expandHomePath(explicit));
38334
- return join23(dirname11(stateFilePath(process.env)), "result-outbox");
38604
+ return join24(dirname12(stateFilePath(process.env)), "result-outbox");
38335
38605
  }
38336
38606
  function resultOutboxInvalidDir(config) {
38337
- return join23(resultOutboxDir(config), "invalid");
38607
+ return join24(resultOutboxDir(config), "invalid");
38338
38608
  }
38339
38609
  function writeResultOutboxEntry(config, entry) {
38340
38610
  const dir = resultOutboxDir(config);
38341
- mkdirSync12(dir, { recursive: true });
38611
+ mkdirSync13(dir, { recursive: true });
38342
38612
  const pendingLogEntries = takeDeferredLiveLogEntries(entry.commandId);
38343
38613
  const body = {
38344
38614
  version: 1,
@@ -38348,16 +38618,16 @@ function writeResultOutboxEntry(config, entry) {
38348
38618
  ...entry,
38349
38619
  ...pendingLogEntries.length > 0 ? { pendingLogEntries } : {}
38350
38620
  };
38351
- writeFileSync13(join23(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
38621
+ writeFileSync14(join24(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
38352
38622
  `, { mode: 384 });
38353
38623
  }
38354
38624
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
38355
38625
  const invalidDir = resultOutboxInvalidDir(config);
38356
- mkdirSync12(invalidDir, { recursive: true });
38357
- const invalidPath = join23(invalidDir, file);
38626
+ mkdirSync13(invalidDir, { recursive: true });
38627
+ const invalidPath = join24(invalidDir, file);
38358
38628
  if (original === void 0) {
38359
38629
  try {
38360
- renameSync10(fullPath, invalidPath);
38630
+ renameSync11(fullPath, invalidPath);
38361
38631
  } catch {
38362
38632
  copyFileSync2(fullPath, invalidPath);
38363
38633
  unlinkSync3(fullPath);
@@ -38370,7 +38640,7 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
38370
38640
  ...detail ? { detail: truncateText(detail, 1e3) } : {},
38371
38641
  original
38372
38642
  };
38373
- writeFileSync13(invalidPath, `${JSON.stringify(evidence, null, 2)}
38643
+ writeFileSync14(invalidPath, `${JSON.stringify(evidence, null, 2)}
38374
38644
  `, { mode: 384 });
38375
38645
  unlinkSync3(fullPath);
38376
38646
  }
@@ -38410,13 +38680,13 @@ function updateResultOutboxAttempt(fullPath, entry, err) {
38410
38680
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
38411
38681
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
38412
38682
  };
38413
- writeFileSync13(fullPath, `${JSON.stringify(next, null, 2)}
38683
+ writeFileSync14(fullPath, `${JSON.stringify(next, null, 2)}
38414
38684
  `, { mode: 384 });
38415
38685
  return next;
38416
38686
  }
38417
38687
  function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err) {
38418
38688
  const invalidDir = resultOutboxInvalidDir(config);
38419
- mkdirSync12(invalidDir, { recursive: true });
38689
+ mkdirSync13(invalidDir, { recursive: true });
38420
38690
  const body = {
38421
38691
  ...entry,
38422
38692
  invalidReason: reason,
@@ -38424,8 +38694,8 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
38424
38694
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
38425
38695
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
38426
38696
  };
38427
- const invalidPath = join23(invalidDir, file);
38428
- writeFileSync13(invalidPath, `${JSON.stringify(body, null, 2)}
38697
+ const invalidPath = join24(invalidDir, file);
38698
+ writeFileSync14(invalidPath, `${JSON.stringify(body, null, 2)}
38429
38699
  `, { mode: 384 });
38430
38700
  try {
38431
38701
  unlinkSync3(fullPath);
@@ -38443,7 +38713,7 @@ async function flushResultOutbox(config) {
38443
38713
  const files = readdirSync12(dir).filter((name) => name.endsWith(".json")).sort();
38444
38714
  let completed = 0;
38445
38715
  for (const file of files) {
38446
- const fullPath = join23(dir, file);
38716
+ const fullPath = join24(dir, file);
38447
38717
  let entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
38448
38718
  if (!entry) continue;
38449
38719
  const pendingLogEntries = Array.isArray(entry.pendingLogEntries) ? entry.pendingLogEntries.filter((logEntry) => typeof asRecord(logEntry).message === "string") : [];
@@ -38458,7 +38728,7 @@ async function flushResultOutbox(config) {
38458
38728
  if (!isTerminalResultOutboxStatus(logHttpStatus)) {
38459
38729
  const logAttemptCount = readNumber(entry.logAttemptCount, 0) + 1;
38460
38730
  if (logAttemptCount < maxResultOutboxAttempts()) {
38461
- writeFileSync13(fullPath, `${JSON.stringify({ ...entry, logAttemptCount }, null, 2)}
38731
+ writeFileSync14(fullPath, `${JSON.stringify({ ...entry, logAttemptCount }, null, 2)}
38462
38732
  `, { mode: 384 });
38463
38733
  process.stderr.write(`AMaster daemon deferred live log delivery retry failed for ${entry.commandId ?? file}: ${logMessage}
38464
38734
  `);
@@ -38471,7 +38741,7 @@ async function flushResultOutbox(config) {
38471
38741
  entry = { ...entry };
38472
38742
  delete entry.pendingLogEntries;
38473
38743
  delete entry.logAttemptCount;
38474
- writeFileSync13(fullPath, `${JSON.stringify(entry, null, 2)}
38744
+ writeFileSync14(fullPath, `${JSON.stringify(entry, null, 2)}
38475
38745
  `, { mode: 384 });
38476
38746
  }
38477
38747
  try {
@@ -38682,8 +38952,8 @@ async function materializeIssueAttachments(config, command, workspace) {
38682
38952
  runtimeAuth,
38683
38953
  issueId
38684
38954
  );
38685
- const targetDir = join23(workspace.cwd, "input-attachments");
38686
- mkdirSync12(targetDir, { recursive: true });
38955
+ const targetDir = join24(workspace.cwd, "input-attachments");
38956
+ mkdirSync13(targetDir, { recursive: true });
38687
38957
  const usedFilenames = /* @__PURE__ */ new Set();
38688
38958
  const materialized = [];
38689
38959
  for (const [index, rawAttachment] of attachments.entries()) {
@@ -38696,12 +38966,12 @@ async function materializeIssueAttachments(config, command, workspace) {
38696
38966
  let filename = safeMaterializedAttachmentFilename(attachment, index);
38697
38967
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
38698
38968
  usedFilenames.add(filename);
38699
- const targetPath = join23(targetDir, filename);
38969
+ const targetPath = join24(targetDir, filename);
38700
38970
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
38701
38971
  if (attachment.initializationInput === true && (body.byteLength !== attachment.byteSize || createHash19("sha256").update(body).digest("hex") !== attachment.sha256)) {
38702
38972
  throw new Error("Initialization input content does not match its preparation receipt");
38703
38973
  }
38704
- writeFileSync13(targetPath, body);
38974
+ writeFileSync14(targetPath, body);
38705
38975
  const attachmentId = readString(attachment.id);
38706
38976
  const actualSha256 = createHash19("sha256").update(body).digest("hex");
38707
38977
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
@@ -38768,9 +39038,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
38768
39038
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
38769
39039
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
38770
39040
  }
38771
- const targetRoot = join23(workspace.cwd, "input-artifacts");
38772
- rmSync11(targetRoot, { recursive: true, force: true });
38773
- mkdirSync12(targetRoot, { recursive: true });
39041
+ const targetRoot = join24(workspace.cwd, "input-artifacts");
39042
+ rmSync12(targetRoot, { recursive: true, force: true });
39043
+ mkdirSync13(targetRoot, { recursive: true });
38774
39044
  const usedPaths = /* @__PURE__ */ new Set();
38775
39045
  const materialized = [];
38776
39046
  for (const [index, rawEntry] of manifest.entries.entries()) {
@@ -38799,18 +39069,18 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
38799
39069
  id: attachmentId,
38800
39070
  originalFilename: readString(entry.originalFilename)
38801
39071
  }, index);
38802
- let relativePath = join23("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39072
+ let relativePath = join24("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
38803
39073
  if (usedPaths.has(relativePath)) {
38804
39074
  const ext = extname3(filename);
38805
39075
  const stem = ext ? filename.slice(0, -ext.length) : filename;
38806
39076
  filename = `${stem}-${index + 1}${ext}`;
38807
- relativePath = join23("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39077
+ relativePath = join24("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
38808
39078
  }
38809
39079
  usedPaths.add(relativePath);
38810
- const targetPath = join23(workspace.cwd, relativePath);
38811
- mkdirSync12(dirname11(targetPath), { recursive: true });
38812
- writeFileSync13(targetPath, body);
38813
- chmodSync7(targetPath, 292);
39080
+ const targetPath = join24(workspace.cwd, relativePath);
39081
+ mkdirSync13(dirname12(targetPath), { recursive: true });
39082
+ writeFileSync14(targetPath, body);
39083
+ chmodSync8(targetPath, 292);
38814
39084
  materialized.push({
38815
39085
  id: attachmentId,
38816
39086
  workProductId,
@@ -38829,9 +39099,9 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
38829
39099
  version: 1,
38830
39100
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
38831
39101
  };
38832
- const manifestPath = join23(targetRoot, "artifact-input-manifest.json");
38833
- writeFileSync13(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
38834
- chmodSync7(manifestPath, 292);
39102
+ const manifestPath = join24(targetRoot, "artifact-input-manifest.json");
39103
+ writeFileSync14(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
39104
+ chmodSync8(manifestPath, 292);
38835
39105
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
38836
39106
  return materialized;
38837
39107
  }
@@ -38842,9 +39112,9 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
38842
39112
  const runtimeAuth = commandRuntimeAuth(command);
38843
39113
  const files = Array.isArray(mention.files) ? mention.files : [];
38844
39114
  if (files.length === 0 || !readString(runtimeAuth.apiUrl) || !readString(runtimeAuth.apiKey)) return empty;
38845
- const targetDir = join23(workspace.cwd, "input-artifacts", "mentioned");
38846
- rmSync11(targetDir, { recursive: true, force: true });
38847
- mkdirSync12(targetDir, { recursive: true });
39115
+ const targetDir = join24(workspace.cwd, "input-artifacts", "mentioned");
39116
+ rmSync12(targetDir, { recursive: true, force: true });
39117
+ mkdirSync13(targetDir, { recursive: true });
38848
39118
  const usedFilenames = /* @__PURE__ */ new Set();
38849
39119
  const materialized = [];
38850
39120
  const skipped = [];
@@ -38888,9 +39158,9 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
38888
39158
  }, index);
38889
39159
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
38890
39160
  usedFilenames.add(filename);
38891
- const targetPath = join23(targetDir, filename);
38892
- writeFileSync13(targetPath, body);
38893
- chmodSync7(targetPath, 292);
39161
+ const targetPath = join24(targetDir, filename);
39162
+ writeFileSync14(targetPath, body);
39163
+ chmodSync8(targetPath, 292);
38894
39164
  materialized.push({
38895
39165
  id: artifactId,
38896
39166
  name: readString(entry.title) ?? readString(entry.originalFilename) ?? filename,
@@ -38906,7 +39176,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
38906
39176
  return { materialized, skipped };
38907
39177
  }
38908
39178
  function issueCheckpointDir(workspace) {
38909
- return join23(dirname11(workspace.runDir), "checkpoint");
39179
+ return join24(dirname12(workspace.runDir), "checkpoint");
38910
39180
  }
38911
39181
  async function clearIssueCheckpoint(config, command, workspace, reason, consumedSource = null) {
38912
39182
  const checkpointDir = issueCheckpointDir(workspace);
@@ -38916,13 +39186,13 @@ async function clearIssueCheckpoint(config, command, workspace, reason, consumed
38916
39186
  if (!sourceRunId) return false;
38917
39187
  let manifest;
38918
39188
  try {
38919
- manifest = asRecord(JSON.parse(readFileSync19(join23(checkpointDir, "manifest.json"), "utf8")));
39189
+ manifest = asRecord(JSON.parse(readFileSync19(join24(checkpointDir, "manifest.json"), "utf8")));
38920
39190
  } catch {
38921
39191
  return false;
38922
39192
  }
38923
39193
  if (readString(manifest.issueId) !== commandIssueId(command) || readString(manifest.sourceRunId) !== sourceRunId) return false;
38924
39194
  }
38925
- rmSync11(checkpointDir, { recursive: true, force: true });
39195
+ rmSync12(checkpointDir, { recursive: true, force: true });
38926
39196
  await ingestLog(config, command, "system", "info", "Cleared issue continuation checkpoint", { reason });
38927
39197
  return true;
38928
39198
  }
@@ -38961,7 +39231,7 @@ function expectedContinuationCheckpoint(command) {
38961
39231
  }
38962
39232
  async function materializeIssueCheckpoint(config, command, workspace) {
38963
39233
  const checkpointDir = issueCheckpointDir(workspace);
38964
- const manifestPath = join23(checkpointDir, "manifest.json");
39234
+ const manifestPath = join24(checkpointDir, "manifest.json");
38965
39235
  const expectedContinuation = expectedContinuationCheckpoint(command);
38966
39236
  const nativeRequest = asRecord(asRecord(command.payload).nativeSession);
38967
39237
  let portableNativeSession;
@@ -38993,12 +39263,12 @@ async function materializeIssueCheckpoint(config, command, workspace) {
38993
39263
  try {
38994
39264
  manifest = asRecord(JSON.parse(readFileSync19(manifestPath, "utf8")));
38995
39265
  } catch (err) {
38996
- rmSync11(checkpointDir, { recursive: true, force: true });
39266
+ rmSync12(checkpointDir, { recursive: true, force: true });
38997
39267
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
38998
39268
  }
38999
39269
  const expiresAt = Date.parse(readString(manifest.expiresAt) ?? "");
39000
39270
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || readString(manifest.issueId) !== commandIssueId(command)) {
39001
- rmSync11(checkpointDir, { recursive: true, force: true });
39271
+ rmSync12(checkpointDir, { recursive: true, force: true });
39002
39272
  if (expectedContinuation) throw new Error("continuation_checkpoint_unavailable: manifest_expired_or_mismatched");
39003
39273
  return unavailable2;
39004
39274
  }
@@ -39022,7 +39292,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39022
39292
  throw new Error("continuation_checkpoint_lineage_mismatch");
39023
39293
  }
39024
39294
  }
39025
- const filesRoot = files.length > 0 ? realpathSync12(join23(checkpointDir, "files")) : null;
39295
+ const filesRoot = files.length > 0 ? realpathSync12(join24(checkpointDir, "files")) : null;
39026
39296
  const workspaceRoot = realpathSync12(workspace.cwd);
39027
39297
  const validated = [];
39028
39298
  let totalBytes = 0;
@@ -39060,8 +39330,8 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39060
39330
  }
39061
39331
  const materialized = [];
39062
39332
  for (const { relativePath, source, target, expectedSha256, expectedByteSize } of validated) {
39063
- mkdirSync12(dirname11(target), { recursive: true });
39064
- const targetParent = realpathSync12(dirname11(target));
39333
+ mkdirSync13(dirname12(target), { recursive: true });
39334
+ const targetParent = realpathSync12(dirname12(target));
39065
39335
  if (!pathWithin3(targetParent, workspaceRoot)) {
39066
39336
  throw new Error(`issue checkpoint target escapes its workspace: ${relativePath}`);
39067
39337
  }
@@ -39078,16 +39348,16 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39078
39348
  materialized.push(relativePath);
39079
39349
  continue;
39080
39350
  }
39081
- const temporaryTarget = join23(targetParent, `.${basename8(target)}.checkpoint-${randomUUID2()}.tmp`);
39351
+ const temporaryTarget = join24(targetParent, `.${basename8(target)}.checkpoint-${randomUUID2()}.tmp`);
39082
39352
  try {
39083
39353
  copyFileSync2(source, temporaryTarget);
39084
39354
  const temporaryStat = lstatSync13(temporaryTarget);
39085
39355
  if (!temporaryStat.isFile() || temporaryStat.size !== expectedByteSize || hashFileSha256(temporaryTarget) !== expectedSha256) {
39086
39356
  throw new Error(`issue checkpoint target verification failed: ${relativePath}`);
39087
39357
  }
39088
- renameSync10(temporaryTarget, target);
39358
+ renameSync11(temporaryTarget, target);
39089
39359
  } finally {
39090
- rmSync11(temporaryTarget, { force: true });
39360
+ rmSync12(temporaryTarget, { force: true });
39091
39361
  }
39092
39362
  materialized.push(relativePath);
39093
39363
  }
@@ -39114,10 +39384,10 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39114
39384
  const commandKey = readString(command.commandId)?.replace(/[^A-Za-z0-9_-]/g, "-") ?? randomUUID2();
39115
39385
  const stagingDir = `${checkpointDir}.tmp-${commandKey}`;
39116
39386
  const backupDir = `${checkpointDir}.previous-${commandKey}`;
39117
- const filesDir = join23(stagingDir, "files");
39118
- rmSync11(stagingDir, { recursive: true, force: true });
39119
- rmSync11(backupDir, { recursive: true, force: true });
39120
- mkdirSync12(filesDir, { recursive: true });
39387
+ const filesDir = join24(stagingDir, "files");
39388
+ rmSync12(stagingDir, { recursive: true, force: true });
39389
+ rmSync12(backupDir, { recursive: true, force: true });
39390
+ mkdirSync13(filesDir, { recursive: true });
39121
39391
  try {
39122
39392
  const files = [];
39123
39393
  let totalBytes = 0;
@@ -39168,7 +39438,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39168
39438
  }
39169
39439
  const target = resolve19(filesDir, relativePath);
39170
39440
  if (!pathWithin3(target, filesDir)) continue;
39171
- mkdirSync12(dirname11(target), { recursive: true });
39441
+ mkdirSync13(dirname12(target), { recursive: true });
39172
39442
  copyFileSync2(ownedSource, target);
39173
39443
  const storedStat = lstatSync13(target);
39174
39444
  if (!storedStat.isFile() || storedStat.size !== byteSize) {
@@ -39178,8 +39448,8 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39178
39448
  files.push({ path: relativePath, byteSize, sha256: hashFileSha256(target) });
39179
39449
  }
39180
39450
  if (files.length === 0 && !options.taskSession) {
39181
- rmSync11(stagingDir, { recursive: true, force: true });
39182
- rmSync11(checkpointDir, { recursive: true, force: true });
39451
+ rmSync12(stagingDir, { recursive: true, force: true });
39452
+ rmSync12(checkpointDir, { recursive: true, force: true });
39183
39453
  return null;
39184
39454
  }
39185
39455
  const checkpointCreatedAt = Date.now();
@@ -39204,26 +39474,26 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39204
39474
  totalBytes,
39205
39475
  files
39206
39476
  };
39207
- writeFileSync13(join23(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
39477
+ writeFileSync14(join24(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
39208
39478
  `);
39209
39479
  const replacingExistingCheckpoint = existsSync18(checkpointDir);
39210
- if (replacingExistingCheckpoint) renameSync10(checkpointDir, backupDir);
39480
+ if (replacingExistingCheckpoint) renameSync11(checkpointDir, backupDir);
39211
39481
  try {
39212
- renameSync10(stagingDir, checkpointDir);
39482
+ renameSync11(stagingDir, checkpointDir);
39213
39483
  } catch (err) {
39214
39484
  if (replacingExistingCheckpoint && existsSync18(backupDir) && !existsSync18(checkpointDir)) {
39215
- renameSync10(backupDir, checkpointDir);
39485
+ renameSync11(backupDir, checkpointDir);
39216
39486
  }
39217
39487
  throw err;
39218
39488
  }
39219
- rmSync11(backupDir, { recursive: true, force: true });
39489
+ rmSync12(backupDir, { recursive: true, force: true });
39220
39490
  if (config.checkpointUploadEnabled) {
39221
39491
  await uploadCheckpoint(config, command, checkpointDir, manifest, void 0, options.nativeSession);
39222
39492
  }
39223
39493
  await ingestLog(config, command, "system", "info", `Saved ${files.length} issue checkpoint file(s) for continuation`, manifest);
39224
39494
  return manifest;
39225
39495
  } catch (err) {
39226
- rmSync11(stagingDir, { recursive: true, force: true });
39496
+ rmSync12(stagingDir, { recursive: true, force: true });
39227
39497
  throw err;
39228
39498
  }
39229
39499
  }
@@ -39516,7 +39786,7 @@ async function executeRunCommand(config, command) {
39516
39786
  executorCommand: invocation.command,
39517
39787
  executorHome: workspace.executorHome,
39518
39788
  runDir: workspace.runDir,
39519
- runtimeCacheRoot: join23(dirname11(config.daemonStateFile), "cache"),
39789
+ runtimeCacheRoot: join24(dirname12(config.daemonStateFile), "cache"),
39520
39790
  cwd,
39521
39791
  runtimeAuth: commandRuntimeAuth(command),
39522
39792
  nativeSession: asRecord(asRecord(executionCommand.payload).nativeSession),
@@ -39732,6 +40002,25 @@ async function executeRunCommand(config, command) {
39732
40002
  invocation.args = [...invocation.args, "--extension", projectInstructionExtensionPath];
39733
40003
  handoffPiRunPathsToChild(config, [projectInstructionExtensionPath]);
39734
40004
  }
40005
+ const taskResourceReceiptBinding = runtimeWebEvidenceTaskResourceBinding(command.payload);
40006
+ const exactTaskResourceBinding = runtimeExactTaskResourceBinding(command.payload);
40007
+ if (taskResourceReceiptBinding && !exactTaskResourceBinding) {
40008
+ throw new Error("runtime_exact_source_binding_invalid");
40009
+ }
40010
+ if (exactTaskResourceBinding) {
40011
+ if (executor.kind !== "pi" || !managedMcpProfile) {
40012
+ throw new Error("runtime_exact_source_reader_unavailable");
40013
+ }
40014
+ const exactSourceExtensionPath = materializePiExactSourceReadExtension(
40015
+ managedMcpProfile.profileRoot,
40016
+ exactTaskResourceBinding
40017
+ );
40018
+ invocation.args = [...invocation.args, "--extension", exactSourceExtensionPath];
40019
+ invocation.args = applyManagedPiToolAllowlist(invocation.args, {
40020
+ toolAllowlist: exactSourceToolAllowlist(managedMcpProfile)
40021
+ });
40022
+ handoffPiRunPathsToChild(config, [exactSourceExtensionPath]);
40023
+ }
39735
40024
  const promptBudgetSummary = contextManifest.budget.totalChars === null ? `${contextManifest.budget.usedChars} characters (unbounded)` : `${contextManifest.budget.usedChars}/${contextManifest.budget.totalChars} characters`;
39736
40025
  enqueuePreparationLog("system", "info", `Compiled ${contextManifest.mode} prompt using ${promptBudgetSummary}`, {
39737
40026
  presentationKind: "context_manifest",
@@ -39836,11 +40125,10 @@ async function executeRunCommand(config, command) {
39836
40125
  },
39837
40126
  {
39838
40127
  piToolArgumentGuard: config.piToolArgumentGuard,
39839
- onWebEvidence: (evidence) => Promise.all(evidence.map((entry) => postRuntimeWebEvidence(
39840
- config,
39841
- requireConnectorId(config),
39842
- command.commandId,
39843
- {
40128
+ onWebEvidence: (evidence) => Promise.all(evidence.map((entry) => {
40129
+ const taskResourceBinding = runtimeWebEvidenceTaskResourceBinding(command.payload);
40130
+ if (taskResourceBinding) assertExactTaskResourceWebEvidence(entry);
40131
+ return postRuntimeWebEvidence(config, requireConnectorId(config), command.commandId, {
39844
40132
  companyId: readString(command.payload?.companyId),
39845
40133
  issueId: commandIssueId(command),
39846
40134
  runId: commandRunId(command),
@@ -39851,9 +40139,10 @@ async function executeRunCommand(config, command) {
39851
40139
  capturedAt: entry.capturedAt,
39852
40140
  mediaType: entry.mediaType,
39853
40141
  normalizedText: entry.normalizedText,
39854
- truncated: entry.truncated
39855
- }
39856
- ))),
40142
+ truncated: entry.truncated,
40143
+ ...taskResourceBinding ? { taskResourceBinding } : {}
40144
+ });
40145
+ })),
39857
40146
  codebuddyAuthorizedMcpToolNames: executor.kind === "codebuddy" ? asRecord(managedMcpProfile?.attestation).authorizedMcpToolNames : void 0
39858
40147
  }
39859
40148
  );
@@ -40459,7 +40748,7 @@ async function executeRunCommand(config, command) {
40459
40748
  } finally {
40460
40749
  await preparationLogChain;
40461
40750
  if (piRuntimeSystemPromptCleanupPath) {
40462
- rmSync11(piRuntimeSystemPromptCleanupPath, { force: true });
40751
+ rmSync12(piRuntimeSystemPromptCleanupPath, { force: true });
40463
40752
  }
40464
40753
  browserCredentialEnvMaterialization?.cleanup();
40465
40754
  if (managedMcpProfile && !managedMcpCleanup && !completionOwnsManagedMcpProfile) {
@@ -40644,7 +40933,7 @@ async function dispatchAvailableCommands(config, options = {}) {
40644
40933
  );
40645
40934
  for (const command of commands) {
40646
40935
  const commandId = readString(command.commandId) ?? readString(command.id);
40647
- if (commandId) {
40936
+ if (commandId && !isRuntimeStopCommand(command)) {
40648
40937
  localDispatchCommands.set(commandId, {
40649
40938
  commandId,
40650
40939
  executionLane: normalizeRuntimeExecutionLane(command.executionLane),
@@ -40688,7 +40977,7 @@ async function waitForConversationCommand(config) {
40688
40977
  );
40689
40978
  for (const command of commands) {
40690
40979
  const commandId = readString(command.commandId) ?? readString(command.id);
40691
- if (commandId) {
40980
+ if (commandId && !isRuntimeStopCommand(command)) {
40692
40981
  localDispatchCommands.set(commandId, {
40693
40982
  commandId,
40694
40983
  executionLane: "conversation",