@amaster.ai/employee-runtime-connector 0.1.9 → 0.1.10

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.
@@ -83,7 +83,7 @@ function withAuditCorrelationEnvironment(environment, command) {
83
83
  }
84
84
 
85
85
  // src/amaster-runtime-daemon.mjs
86
- import { createHash as createHash19, randomUUID as randomUUID2 } from "node:crypto";
86
+ import { createHash as createHash20, randomUUID as randomUUID2 } from "node:crypto";
87
87
  import { createRequire } from "node:module";
88
88
 
89
89
  // ../../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js
@@ -4589,6 +4589,7 @@ var SECRET_BINDING_TARGET_TYPES = [
4589
4589
  "run",
4590
4590
  "tool_connection",
4591
4591
  "system",
4592
+ "browser_login_identity",
4592
4593
  "browser_session"
4593
4594
  ];
4594
4595
  var STORAGE_PROVIDERS = ["local_disk", "s3"];
@@ -4652,6 +4653,11 @@ var HUMAN_COMPANY_MEMBERSHIP_ROLES = [
4652
4653
  "operator",
4653
4654
  "viewer"
4654
4655
  ];
4656
+ var HUMAN_TASK_VISIBILITY_SCOPES = [
4657
+ "company",
4658
+ "project_and_related",
4659
+ "related_only"
4660
+ ];
4655
4661
  var INVITE_JOIN_TYPES = ["human", "agent", "both"];
4656
4662
  var JOIN_REQUEST_TYPES = ["human", "agent"];
4657
4663
  var JOIN_REQUEST_STATUSES = ["pending_approval", "approved", "rejected"];
@@ -4939,7 +4945,8 @@ var AMASTER_RUNTIME_CONNECTOR_CAPABILITIES = [
4939
4945
  "execution_lanes_v1",
4940
4946
  "mirrorx_initialization_context_v1",
4941
4947
  "mirrorx_initialization_completion_v1",
4942
- "native_session_checkpoint_v1"
4948
+ "native_session_checkpoint_v1",
4949
+ "pi_web_public_search_v1"
4943
4950
  ];
4944
4951
  var RUNTIME_EXECUTION_LANES = ["business", "conversation"];
4945
4952
  var runtimeExecutionLaneSchema = external_exports.enum(RUNTIME_EXECUTION_LANES);
@@ -5459,12 +5466,18 @@ var EXTERNAL_WAIT_REASON_CODES = {
5459
5466
  heligeNewTurnNotObserved: "helige_new_turn_not_observed",
5460
5467
  heligeGenerationStatusUnavailable: "helige_generation_status_unavailable"
5461
5468
  };
5462
- var BROWSER_HUMAN_SESSION_HANDOFF_REASON_CODES = [
5469
+ var LEGACY_BROWSER_HANDOFF_REASON_CODES = [
5463
5470
  EXTERNAL_WAIT_REASON_CODES.browserMfaRequired,
5464
5471
  EXTERNAL_WAIT_REASON_CODES.browserCaptchaRequired,
5465
- EXTERNAL_WAIT_REASON_CODES.browserSsoHandoffRequired,
5472
+ EXTERNAL_WAIT_REASON_CODES.browserSsoHandoffRequired
5473
+ ];
5474
+ var BROWSER_HUMAN_SESSION_HANDOFF_REASON_CODES = [
5475
+ ...LEGACY_BROWSER_HANDOFF_REASON_CODES,
5466
5476
  EXTERNAL_WAIT_REASON_CODES.browserHumanSessionHandoffRequired
5467
5477
  ];
5478
+ var GENERIC_EXTERNAL_DEPENDENCY_WAIT_REASON_CODES = [
5479
+ EXTERNAL_WAIT_REASON_CODES.externalDependencyPending
5480
+ ];
5468
5481
  var GENERIC_EXTERNAL_INPUT_WAIT_REASON_CODES = [
5469
5482
  EXTERNAL_WAIT_REASON_CODES.customerInputPending,
5470
5483
  EXTERNAL_WAIT_REASON_CODES.externalInputPending
@@ -5472,9 +5485,6 @@ var GENERIC_EXTERNAL_INPUT_WAIT_REASON_CODES = [
5472
5485
  var GENERIC_EXTERNAL_APPROVAL_WAIT_REASON_CODES = [
5473
5486
  EXTERNAL_WAIT_REASON_CODES.externalApprovalPending
5474
5487
  ];
5475
- var GENERIC_EXTERNAL_DEPENDENCY_WAIT_REASON_CODES = [
5476
- EXTERNAL_WAIT_REASON_CODES.externalDependencyPending
5477
- ];
5478
5488
  var HELIGE_GENERATION_MONITOR_REASON_CODES = [
5479
5489
  EXTERNAL_WAIT_REASON_CODES.heligeGenerationInProgress,
5480
5490
  EXTERNAL_WAIT_REASON_CODES.heligeNewTurnNotObserved,
@@ -5634,6 +5644,337 @@ var issueLivePathReleaseInputSchema = external_exports.object({
5634
5644
  terminalReceipt: external_exports.record(external_exports.unknown())
5635
5645
  }).strict();
5636
5646
 
5647
+ // ../shared/src/validators/secure-interaction.ts
5648
+ var SECURE_INTERACTION_CREDENTIAL_SHAPED_LABEL = /\b(?:password|passwd|passcode|pin|otp|cookie|token|secret|credential|authorization|bearer|api[-_ ]?key|private[-_ ]?key)\b\s*[:=]/iu;
5649
+ var secureInteractionAccountLabelSchema = external_exports.string().transform((value) => value.trim().normalize("NFKC")).pipe(external_exports.string().min(1).max(160)).superRefine((value, context) => {
5650
+ if (/[\u0000-\u001f\u007f]/u.test(value)) {
5651
+ context.addIssue({
5652
+ code: external_exports.ZodIssueCode.custom,
5653
+ message: "Secure interaction account label must contain only visible characters"
5654
+ });
5655
+ }
5656
+ if (SECURE_INTERACTION_CREDENTIAL_SHAPED_LABEL.test(value)) {
5657
+ context.addIssue({
5658
+ code: external_exports.ZodIssueCode.custom,
5659
+ message: "Secure interaction account label must not contain credential material",
5660
+ params: { code: "browser_auth_account_label_credential_forbidden" }
5661
+ });
5662
+ }
5663
+ });
5664
+ var secureInteractionFormFieldTypeSchema = external_exports.enum([
5665
+ "text",
5666
+ "email",
5667
+ "tel",
5668
+ "textarea",
5669
+ "secret",
5670
+ "file"
5671
+ ]);
5672
+ var browserCredentialOriginSchema = external_exports.string().superRefine((value, context) => {
5673
+ let url;
5674
+ try {
5675
+ url = new URL(value);
5676
+ } catch {
5677
+ context.addIssue({
5678
+ code: external_exports.ZodIssueCode.custom,
5679
+ message: "Browser credential origin must be an exact credential-free HTTPS origin"
5680
+ });
5681
+ return;
5682
+ }
5683
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash || value !== url.origin) {
5684
+ context.addIssue({
5685
+ code: external_exports.ZodIssueCode.custom,
5686
+ message: "Browser credential origin must be an exact credential-free HTTPS origin"
5687
+ });
5688
+ }
5689
+ });
5690
+ var secureInteractionFormFieldSchema = external_exports.object({
5691
+ id: external_exports.string().trim().min(1).max(120),
5692
+ label: external_exports.string().trim().min(1).max(120),
5693
+ type: secureInteractionFormFieldTypeSchema.optional(),
5694
+ placeholder: external_exports.string().trim().max(240).nullable().optional(),
5695
+ required: external_exports.boolean().optional(),
5696
+ browserOrigin: browserCredentialOriginSchema.optional()
5697
+ }).superRefine((value, context) => {
5698
+ if (value.browserOrigin && value.type !== "secret") {
5699
+ context.addIssue({
5700
+ code: external_exports.ZodIssueCode.custom,
5701
+ message: "Browser credential origin is allowed only on a secret field",
5702
+ path: ["browserOrigin"]
5703
+ });
5704
+ }
5705
+ });
5706
+ var secureInteractionSecretRefSchema = external_exports.object({
5707
+ secretId: external_exports.string().uuid(),
5708
+ name: external_exports.string().trim().min(1).max(512),
5709
+ key: external_exports.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9_.-]+$/).optional(),
5710
+ version: external_exports.number().int().positive().optional()
5711
+ });
5712
+ var RESERVED_OTHER_OPTION_LABEL = /^(?:(?:其他|其它)(?:选项|方案|回答|情况|内容)?(?:请)?(?:说明|填写|输入|补充|补充说明)?|自定义(?:选项|方案|回答|内容)?(?:请)?(?:说明|填写|输入|补充|补充说明)?|以上都不是|other(?:option|answer|choice|pleasespecify|specify)?|custom(?:option|answer|choice)?|noneoftheabove|somethingelse)$/iu;
5713
+ function isReservedOtherOptionLabel(label) {
5714
+ const normalized = label.toLowerCase().replace(/[\p{P}\p{S}\s]+/gu, "");
5715
+ return RESERVED_OTHER_OPTION_LABEL.test(normalized);
5716
+ }
5717
+
5718
+ // ../shared/src/mirrorx-connector-oauth.ts
5719
+ var connectorOAuthServiceIdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{1,128}$/);
5720
+ var connectorOAuthConnectionNameSchema = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);
5721
+ var connectorOAuthAuthorizationIdSchema = external_exports.string().uuid();
5722
+ var connectorOAuthProfileSchema = external_exports.object({
5723
+ accountId: external_exports.string().optional(),
5724
+ displayName: external_exports.string().optional(),
5725
+ accountLabel: external_exports.string().optional()
5726
+ });
5727
+ var connectorOAuthConnectionSchema = external_exports.object({
5728
+ connectionName: connectorOAuthConnectionNameSchema,
5729
+ profile: connectorOAuthProfileSchema.nullable()
5730
+ });
5731
+ var connectorOAuthAuthorizationResponseSchema = external_exports.object({
5732
+ authorizationId: connectorOAuthAuthorizationIdSchema,
5733
+ connectionName: connectorOAuthConnectionNameSchema,
5734
+ authorizationUrl: external_exports.string().url()
5735
+ });
5736
+ var connectorOAuthFinalizeResponseSchema = external_exports.object({
5737
+ status: external_exports.enum(["pending", "connected", "reauthorization_required"]),
5738
+ profile: connectorOAuthProfileSchema.nullable()
5739
+ });
5740
+
5741
+ // ../shared/src/form-spec.ts
5742
+ var FORM_SPEC_PROTOTYPE_KEYS = /* @__PURE__ */ new Set([...Object.getOwnPropertyNames(Object.prototype), "prototype"]);
5743
+ var formSpecFieldIdSchema = external_exports.string().trim().min(1).max(160).regex(/^[\p{L}\p{N}][\p{L}\p{N}._:/-]*$/u).refine((value) => !FORM_SPEC_PROTOTYPE_KEYS.has(value), {
5744
+ message: "fieldId must not be an Object prototype member name"
5745
+ });
5746
+ var formSpecElementKeySchema = external_exports.string().min(1).max(120).refine((value) => !FORM_SPEC_PROTOTYPE_KEYS.has(value), {
5747
+ message: "element key must not be an Object prototype member name"
5748
+ });
5749
+ var FORM_SPEC_OTHER_VALUE = "__other__";
5750
+ var formSpecOtherTextsSchema = external_exports.record(
5751
+ formSpecFieldIdSchema,
5752
+ external_exports.string().trim().min(1).max(2e3)
5753
+ );
5754
+ var formSpecOptionSchema = external_exports.object({
5755
+ id: external_exports.string().trim().min(1).max(120),
5756
+ label: external_exports.string().trim().min(1).max(240)
5757
+ }).strict();
5758
+ var fieldBaseProps = {
5759
+ fieldId: formSpecFieldIdSchema,
5760
+ label: external_exports.string().trim().min(1).max(240),
5761
+ required: external_exports.boolean().optional(),
5762
+ helpText: external_exports.string().trim().max(1e3).nullable().optional()
5763
+ };
5764
+ var placeholderProp = external_exports.string().trim().max(240).nullable().optional();
5765
+ var formSpecComponentPropsSchemas = {
5766
+ Stack: external_exports.object({
5767
+ gap: external_exports.enum(["sm", "md", "lg"]).optional()
5768
+ }).strict(),
5769
+ Card: external_exports.object({
5770
+ title: external_exports.string().trim().max(240).nullable().optional()
5771
+ }).strict(),
5772
+ Heading: external_exports.object({
5773
+ text: external_exports.string().trim().min(1).max(240)
5774
+ }).strict(),
5775
+ Text: external_exports.object({
5776
+ text: external_exports.string().trim().min(1).max(2e3)
5777
+ }).strict(),
5778
+ TextField: external_exports.object({
5779
+ ...fieldBaseProps,
5780
+ placeholder: placeholderProp
5781
+ }).strict(),
5782
+ Textarea: external_exports.object({
5783
+ ...fieldBaseProps,
5784
+ placeholder: placeholderProp,
5785
+ rows: external_exports.number().int().min(2).max(20).optional()
5786
+ }).strict(),
5787
+ Select: external_exports.object({
5788
+ ...fieldBaseProps,
5789
+ placeholder: placeholderProp,
5790
+ options: external_exports.array(formSpecOptionSchema).min(1).max(10)
5791
+ }).strict(),
5792
+ MultiSelect: external_exports.object({
5793
+ ...fieldBaseProps,
5794
+ options: external_exports.array(formSpecOptionSchema).min(1).max(10),
5795
+ maxSelections: external_exports.number().int().min(1).max(10).optional()
5796
+ }).strict(),
5797
+ DateField: external_exports.object({ ...fieldBaseProps }).strict(),
5798
+ AttachmentField: external_exports.object({
5799
+ ...fieldBaseProps,
5800
+ maxFiles: external_exports.number().int().min(1).max(20).optional()
5801
+ }).strict(),
5802
+ SecretField: external_exports.object({
5803
+ ...fieldBaseProps,
5804
+ placeholder: placeholderProp,
5805
+ credentialRole: external_exports.enum(["username", "password"]).optional(),
5806
+ browserOrigin: browserCredentialOriginSchema.optional()
5807
+ }).strict(),
5808
+ OAuthAuthorizationField: external_exports.object({
5809
+ ...fieldBaseProps,
5810
+ service: connectorOAuthServiceIdSchema,
5811
+ connectionName: connectorOAuthConnectionNameSchema.optional()
5812
+ }).strict()
5813
+ };
5814
+ var credentialFieldEnglishNamePattern = /^(?:(?:please )?(?:enter|provide|submit|input) (?:your )?)?(?:(?:login|account|user|browser|api|access|refresh|private|client) )?(?:password|passwd|passphrase|passcode|one time code|otp|api key|access key|access token|refresh token|private key|client secret|secret|token|credentials?)(?: (?:value|text|code|received|provided|confirmed))?$/iu;
5815
+ var credentialFieldChineseNamePattern = /^(?:请(?:提供|输入|填写))?(?:登录|账户|账号|用户|浏览器|API)?(?:密码|口令|验证码|密钥|令牌|凭据|私钥)(?:值|内容|已提供|已提交)?$/iu;
5816
+ function isCredentialFieldName(name) {
5817
+ const normalized = name.trim().normalize("NFKC").replace(/[._:/-]+/gu, " ").replace(/\s+/gu, " ");
5818
+ return credentialFieldEnglishNamePattern.test(normalized) || credentialFieldChineseNamePattern.test(normalized);
5819
+ }
5820
+ var FORM_SPEC_COMPONENT_TYPES = Object.keys(formSpecComponentPropsSchemas);
5821
+ var FORM_SPEC_FIELD_COMPONENT_TYPES = [
5822
+ "TextField",
5823
+ "Textarea",
5824
+ "Select",
5825
+ "MultiSelect",
5826
+ "DateField",
5827
+ "AttachmentField",
5828
+ "SecretField",
5829
+ "OAuthAuthorizationField"
5830
+ ];
5831
+ var FORM_SPEC_FIELD_COMPONENT_TYPE_SET = new Set(FORM_SPEC_FIELD_COMPONENT_TYPES);
5832
+ var FORM_SPEC_LAYOUT_CONTAINER_TYPES = /* @__PURE__ */ new Set(["Stack", "Card"]);
5833
+ var FORM_SPEC_MAX_ELEMENTS = 50;
5834
+ var FORM_SPEC_MAX_DEPTH = 8;
5835
+ var formSpecElementSchema = external_exports.object({
5836
+ type: external_exports.enum(FORM_SPEC_COMPONENT_TYPES),
5837
+ props: external_exports.record(external_exports.string(), external_exports.unknown()),
5838
+ children: external_exports.array(formSpecElementKeySchema).max(FORM_SPEC_MAX_ELEMENTS).optional()
5839
+ }).strict();
5840
+ var formSpecSchema = external_exports.object({
5841
+ root: formSpecElementKeySchema,
5842
+ elements: external_exports.record(formSpecElementKeySchema, formSpecElementSchema)
5843
+ }).strict().superRefine((spec, ctx) => {
5844
+ const elementEntries = Object.entries(spec.elements);
5845
+ if (elementEntries.length === 0) {
5846
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements"], message: "Form spec must declare at least one element" });
5847
+ return;
5848
+ }
5849
+ if (elementEntries.length > FORM_SPEC_MAX_ELEMENTS) {
5850
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements"], message: `Form spec supports at most ${FORM_SPEC_MAX_ELEMENTS} elements` });
5851
+ }
5852
+ const root = Object.hasOwn(spec.elements, spec.root) ? spec.elements[spec.root] : void 0;
5853
+ if (!root) {
5854
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["root"], message: "Form spec root element is not present in elements" });
5855
+ return;
5856
+ }
5857
+ for (const [key, element] of elementEntries) {
5858
+ const propsSchema = formSpecComponentPropsSchemas[element.type];
5859
+ const parsed = propsSchema.safeParse(element.props);
5860
+ if (!parsed.success) {
5861
+ for (const issue of parsed.error.issues) {
5862
+ ctx.addIssue({
5863
+ code: external_exports.ZodIssueCode.custom,
5864
+ path: ["elements", key, "props", ...issue.path],
5865
+ message: `${element.type}: ${issue.message}`
5866
+ });
5867
+ }
5868
+ } else if (element.type === "Select" || element.type === "MultiSelect") {
5869
+ const options = parsed.data.options;
5870
+ for (const [optionIndex, option] of options.entries()) {
5871
+ if (isReservedOtherOptionLabel(option.label)) {
5872
+ ctx.addIssue({
5873
+ code: external_exports.ZodIssueCode.custom,
5874
+ path: ["elements", key, "props", "options", optionIndex, "label"],
5875
+ message: "Do not declare an Other/custom option; the UI always appends one with a free-text input"
5876
+ });
5877
+ }
5878
+ if (option.id === FORM_SPEC_OTHER_VALUE) {
5879
+ ctx.addIssue({
5880
+ code: external_exports.ZodIssueCode.custom,
5881
+ path: ["elements", key, "props", "options", optionIndex, "id"],
5882
+ message: `Option id ${FORM_SPEC_OTHER_VALUE} is reserved for the UI-appended Other option`
5883
+ });
5884
+ }
5885
+ }
5886
+ }
5887
+ if (element.children && element.children.length > 0 && !FORM_SPEC_LAYOUT_CONTAINER_TYPES.has(element.type)) {
5888
+ ctx.addIssue({
5889
+ code: external_exports.ZodIssueCode.custom,
5890
+ path: ["elements", key, "children"],
5891
+ message: "Only Stack and Card elements may have children"
5892
+ });
5893
+ }
5894
+ for (const childKey of element.children ?? []) {
5895
+ if (!Object.hasOwn(spec.elements, childKey)) {
5896
+ ctx.addIssue({
5897
+ code: external_exports.ZodIssueCode.custom,
5898
+ path: ["elements", key, "children"],
5899
+ message: `Form spec child element not found: ${childKey}`
5900
+ });
5901
+ }
5902
+ }
5903
+ }
5904
+ const parentCount = /* @__PURE__ */ new Map();
5905
+ for (const [, element] of elementEntries) {
5906
+ for (const childKey of element.children ?? []) {
5907
+ parentCount.set(childKey, (parentCount.get(childKey) ?? 0) + 1);
5908
+ }
5909
+ }
5910
+ for (const [childKey, count2] of parentCount) {
5911
+ if (count2 > 1) {
5912
+ ctx.addIssue({
5913
+ code: external_exports.ZodIssueCode.custom,
5914
+ path: ["elements", childKey],
5915
+ message: `Form spec element must have exactly one parent (shared subtrees are not allowed): ${childKey}`
5916
+ });
5917
+ }
5918
+ }
5919
+ const reachable = /* @__PURE__ */ new Set();
5920
+ const walk = (key, depth, path) => {
5921
+ if (path.has(key)) {
5922
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements", key], message: `Form spec contains a cycle at element: ${key}` });
5923
+ return;
5924
+ }
5925
+ if (reachable.has(key)) return;
5926
+ if (depth > FORM_SPEC_MAX_DEPTH) {
5927
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements", key], message: `Form spec exceeds the maximum nesting depth of ${FORM_SPEC_MAX_DEPTH}` });
5928
+ return;
5929
+ }
5930
+ reachable.add(key);
5931
+ path.add(key);
5932
+ for (const childKey of spec.elements[key]?.children ?? []) walk(childKey, depth + 1, path);
5933
+ path.delete(key);
5934
+ };
5935
+ walk(spec.root, 0, /* @__PURE__ */ new Set());
5936
+ for (const key of Object.keys(spec.elements)) {
5937
+ if (!reachable.has(key)) {
5938
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements", key], message: "Form spec element is not reachable from root" });
5939
+ }
5940
+ }
5941
+ const fieldIds = /* @__PURE__ */ new Set();
5942
+ let requiredFieldCount = 0;
5943
+ for (const [key, element] of elementEntries) {
5944
+ if (!FORM_SPEC_FIELD_COMPONENT_TYPE_SET.has(element.type)) continue;
5945
+ const parsed = formSpecComponentPropsSchemas[element.type].safeParse(element.props);
5946
+ if (!parsed.success) continue;
5947
+ const props = parsed.data;
5948
+ if (element.type !== "SecretField" && element.type !== "OAuthAuthorizationField" && [props.fieldId, props.label].some(isCredentialFieldName)) {
5949
+ ctx.addIssue({
5950
+ code: external_exports.ZodIssueCode.custom,
5951
+ path: ["elements", key, "props", "fieldId"],
5952
+ message: `${element.type} collects a credential-shaped name; use a SecretField instead: ${props.fieldId}`
5953
+ });
5954
+ }
5955
+ if (fieldIds.has(props.fieldId)) {
5956
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements", key, "props", "fieldId"], message: `Form spec fieldId must be unique: ${props.fieldId}` });
5957
+ }
5958
+ fieldIds.add(props.fieldId);
5959
+ if (props.required === true) requiredFieldCount += 1;
5960
+ }
5961
+ if (fieldIds.size === 0) {
5962
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements"], message: "Form spec must declare at least one input field" });
5963
+ }
5964
+ if (requiredFieldCount === 0) {
5965
+ ctx.addIssue({ code: external_exports.ZodIssueCode.custom, path: ["elements"], message: "Form spec must declare at least one required field" });
5966
+ }
5967
+ });
5968
+ var formSpecSubmissionValueSchema = external_exports.union([
5969
+ external_exports.string().max(2e4),
5970
+ external_exports.array(external_exports.string().trim().min(1).max(120)).max(11),
5971
+ external_exports.array(external_exports.string().uuid()).max(20)
5972
+ ]);
5973
+ var formSpecSubmissionValuesSchema = external_exports.record(
5974
+ formSpecFieldIdSchema,
5975
+ formSpecSubmissionValueSchema
5976
+ );
5977
+
5637
5978
  // ../shared/src/company-cold-start.ts
5638
5979
  var COMPANY_COLD_START_PHASES = [
5639
5980
  "not_started",
@@ -7324,17 +7665,23 @@ var operatingIdentityProposalSchema = external_exports.object({
7324
7665
  recurrenceWindow: operatingRecurrenceSchema.optional(),
7325
7666
  outcomeClass: external_exports.enum(["internal_enablement", "governed_decision", "external_action", "observed_business_result"])
7326
7667
  }).strict();
7327
- var goalOutcomeRequestSchema = external_exports.discriminatedUnion("relation", [
7668
+ var goalOutcomeRequestBase = {
7669
+ relation: external_exports.literal("direct_criterion"),
7670
+ criterionId: external_exports.string().uuid(),
7671
+ evaluationIntent: external_exports.enum(["full_criterion_claim", "partial_contribution", "effect_observation_trigger"]),
7672
+ mappings: external_exports.array(external_exports.object({ requirementId: ref, taskAcceptanceRefs: external_exports.array(ref).min(1), coverage: external_exports.enum(["full", "partial"]) }).strict()).min(1).max(20),
7673
+ operatingProposal: operatingIdentityProposalSchema
7674
+ };
7675
+ var goalOutcomeRequestSchema = external_exports.union([
7328
7676
  external_exports.object({ relation: external_exports.literal("goal_supporting"), operatingProposal: operatingIdentityProposalSchema.optional() }).strict(),
7329
7677
  external_exports.object({ relation: external_exports.literal("no_goal_effect"), operatingProposal: operatingIdentityProposalSchema.optional() }).strict(),
7330
7678
  external_exports.object({
7331
- relation: external_exports.literal("direct_criterion"),
7332
- criterionId: external_exports.string().uuid(),
7333
- goalRevision: external_exports.number().int().positive(),
7334
- evaluationIntent: external_exports.enum(["full_criterion_claim", "partial_contribution", "effect_observation_trigger"]),
7335
- mappings: external_exports.array(external_exports.object({ requirementId: ref, taskAcceptanceRefs: external_exports.array(ref).min(1), coverage: external_exports.enum(["full", "partial"]) }).strict()).min(1).max(20),
7336
- operatingProposal: operatingIdentityProposalSchema
7337
- }).strict()
7679
+ ...goalOutcomeRequestBase,
7680
+ gapContractRevision: external_exports.number().int().positive(),
7681
+ criterionRevision: external_exports.number().int().positive()
7682
+ }).strict(),
7683
+ // Read-only compatibility for persisted v1 requests. Fresh direct admission must use both v2 revisions.
7684
+ external_exports.object({ ...goalOutcomeRequestBase, goalRevision: external_exports.number().int().positive() }).strict()
7338
7685
  ]);
7339
7686
  var criterionEvidenceRequirementSchema = external_exports.object({
7340
7687
  requirementId: ref,
@@ -8217,7 +8564,7 @@ var ISSUE_EXECUTION_REVIEW_EVIDENCE_SCHEMA_VERSION = "mirrorx.execution-review-e
8217
8564
  var issueExecutionReviewEvidenceSchema = external_exports.object({
8218
8565
  schemaVersion: external_exports.literal(ISSUE_EXECUTION_REVIEW_EVIDENCE_SCHEMA_VERSION),
8219
8566
  manifest: issueDeliveryManifestIdentitySchema,
8220
- inspectedRefIds: external_exports.array(external_exports.string().trim().min(1).max(240)).min(1).max(101),
8567
+ inspectedRefIds: external_exports.array(external_exports.string().trim().min(1).max(240)).max(101),
8221
8568
  acceptanceFindings: external_exports.array(external_exports.object({
8222
8569
  acceptanceRef: acceptanceRefSchema,
8223
8570
  outcome: external_exports.enum(["passed", "failed"]),
@@ -9220,6 +9567,8 @@ var taskResourceInputSchema = external_exports.discriminatedUnion("kind", [
9220
9567
  displayName: external_exports.string().trim().min(1).max(255),
9221
9568
  locator: external_exports.string().url().max(TASK_RESOURCE_LOCATOR_MAX_LENGTH),
9222
9569
  scope: external_exports.string().trim().min(1).max(2e3),
9570
+ browserLoginIdentityId: external_exports.string().uuid().nullable().optional(),
9571
+ browserLoginIdentityMode: external_exports.enum(["discover", "new", "reuse"]).optional(),
9223
9572
  preparationReceipt: external_exports.null().optional()
9224
9573
  }).strict(),
9225
9574
  taskResourceInputBaseSchema.extend({
@@ -9233,7 +9582,17 @@ var taskResourceInputSchema = external_exports.discriminatedUnion("kind", [
9233
9582
  preparationReceipt: attachmentPreparationReceiptSchema.nullable().optional()
9234
9583
  }).strict()
9235
9584
  ]).superRefine((value, context) => {
9236
- if (value.kind !== "attachment") return;
9585
+ if (value.kind === "link") {
9586
+ const mode = value.browserLoginIdentityMode ?? "discover";
9587
+ if (mode === "reuse" !== Boolean(value.browserLoginIdentityId)) {
9588
+ context.addIssue({
9589
+ code: external_exports.ZodIssueCode.custom,
9590
+ path: ["browserLoginIdentityId"],
9591
+ message: "A reused browser login identity must be explicitly bound"
9592
+ });
9593
+ }
9594
+ return;
9595
+ }
9237
9596
  const originalOnly = value.parserVersion === ORIGINAL_ONLY_PARSER_VERSION;
9238
9597
  if (value.state === "prepared" && !value.preparationReceipt && !originalOnly) {
9239
9598
  context.addIssue({
@@ -9317,7 +9676,24 @@ var createTaskResourceLinkRequestSchema = external_exports.object({
9317
9676
  displayName: external_exports.string().trim().min(1).max(500),
9318
9677
  locator: taskResourceLocatorSchema,
9319
9678
  scope: external_exports.string().trim().min(1).max(2e3),
9320
- criticality: external_exports.enum(["critical", "supporting"]).default("supporting")
9679
+ criticality: external_exports.enum(["critical", "supporting"]).default("supporting"),
9680
+ browserLoginIdentityId: external_exports.string().uuid().optional(),
9681
+ createNewBrowserLoginIdentity: external_exports.boolean().optional()
9682
+ }).strict().superRefine((value, context) => {
9683
+ if (value.browserLoginIdentityId && value.createNewBrowserLoginIdentity) {
9684
+ context.addIssue({
9685
+ code: external_exports.ZodIssueCode.custom,
9686
+ path: ["browserLoginIdentityId"],
9687
+ message: "Choose an existing browser login identity or create a new one, not both"
9688
+ });
9689
+ }
9690
+ });
9691
+ var browserLoginIdentitySummarySchema = external_exports.object({
9692
+ id: external_exports.string().uuid(),
9693
+ provider: external_exports.literal("chromium"),
9694
+ authenticationOrigin: exactOriginSchema,
9695
+ targetOrigin: exactOriginSchema,
9696
+ policyRevision: external_exports.number().int().positive()
9321
9697
  }).strict();
9322
9698
  var finalizeTaskResourceAttachmentRequestSchema = external_exports.object({ inputId: external_exports.string().uuid() }).strict();
9323
9699
  var createTaskResourceAttachmentRequestSchema = external_exports.object({ attachmentId: external_exports.string().uuid() }).strict();
@@ -9941,54 +10317,6 @@ var browserSessionOriginSchema = external_exports.string().trim().min(1).max(204
9941
10317
  }
9942
10318
  );
9943
10319
 
9944
- // ../shared/src/validators/secure-interaction.ts
9945
- var SECURE_INTERACTION_CREDENTIAL_SHAPED_LABEL = /\b(?:password|passwd|passcode|pin|otp|cookie|token|secret|credential|authorization|bearer|api[-_ ]?key|private[-_ ]?key)\b\s*[:=]/iu;
9946
- var secureInteractionAccountLabelSchema = external_exports.string().transform((value) => value.trim().normalize("NFKC")).pipe(external_exports.string().min(1).max(160)).superRefine((value, context) => {
9947
- if (/[\u0000-\u001f\u007f]/u.test(value)) {
9948
- context.addIssue({
9949
- code: external_exports.ZodIssueCode.custom,
9950
- message: "Secure interaction account label must contain only visible characters"
9951
- });
9952
- }
9953
- if (SECURE_INTERACTION_CREDENTIAL_SHAPED_LABEL.test(value)) {
9954
- context.addIssue({
9955
- code: external_exports.ZodIssueCode.custom,
9956
- message: "Secure interaction account label must not contain credential material",
9957
- params: { code: "browser_auth_account_label_credential_forbidden" }
9958
- });
9959
- }
9960
- });
9961
- var secureInteractionFormFieldTypeSchema = external_exports.enum([
9962
- "text",
9963
- "email",
9964
- "tel",
9965
- "textarea",
9966
- "secret",
9967
- "file"
9968
- ]);
9969
- var secureInteractionFormFieldSchema = external_exports.object({
9970
- id: external_exports.string().trim().min(1).max(120),
9971
- label: external_exports.string().trim().min(1).max(120),
9972
- type: secureInteractionFormFieldTypeSchema.optional(),
9973
- placeholder: external_exports.string().trim().max(240).nullable().optional(),
9974
- required: external_exports.boolean().optional(),
9975
- browserOrigin: external_exports.string().url().superRefine((value, context) => {
9976
- const url = new URL(value);
9977
- if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash || value !== url.origin) {
9978
- context.addIssue({
9979
- code: external_exports.ZodIssueCode.custom,
9980
- message: "Browser credential origin must be an exact credential-free HTTPS origin"
9981
- });
9982
- }
9983
- }).optional()
9984
- });
9985
- var secureInteractionSecretRefSchema = external_exports.object({
9986
- secretId: external_exports.string().uuid(),
9987
- name: external_exports.string().trim().min(1).max(512),
9988
- key: external_exports.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9_.-]+$/).optional(),
9989
- version: external_exports.number().int().positive().optional()
9990
- });
9991
-
9992
10320
  // ../shared/src/types/attachment-preparation.ts
9993
10321
  var ATTACHMENT_PREPARATION_MAX_REDACTION_AUDITS = 2e4;
9994
10322
  var ATTACHMENT_PREPARATION_BLOCK_KINDS = [
@@ -10624,29 +10952,6 @@ var issueDelegationContextSchema = external_exports.object({
10624
10952
  createdAt: external_exports.string().datetime()
10625
10953
  }).strict();
10626
10954
 
10627
- // ../shared/src/mirrorx-connector-oauth.ts
10628
- var connectorOAuthServiceIdSchema = external_exports.string().regex(/^[A-Za-z0-9_-]{1,128}$/);
10629
- var connectorOAuthConnectionNameSchema = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/);
10630
- var connectorOAuthAuthorizationIdSchema = external_exports.string().uuid();
10631
- var connectorOAuthProfileSchema = external_exports.object({
10632
- accountId: external_exports.string().optional(),
10633
- displayName: external_exports.string().optional(),
10634
- accountLabel: external_exports.string().optional()
10635
- });
10636
- var connectorOAuthConnectionSchema = external_exports.object({
10637
- connectionName: connectorOAuthConnectionNameSchema,
10638
- profile: connectorOAuthProfileSchema.nullable()
10639
- });
10640
- var connectorOAuthAuthorizationResponseSchema = external_exports.object({
10641
- authorizationId: connectorOAuthAuthorizationIdSchema,
10642
- connectionName: connectorOAuthConnectionNameSchema,
10643
- authorizationUrl: external_exports.string().url()
10644
- });
10645
- var connectorOAuthFinalizeResponseSchema = external_exports.object({
10646
- status: external_exports.enum(["pending", "connected", "reauthorization_required"]),
10647
- profile: connectorOAuthProfileSchema.nullable()
10648
- });
10649
-
10650
10955
  // ../shared/src/validators/issue.ts
10651
10956
  var requiredReasonString = external_exports.string().trim().min(1);
10652
10957
  var ISSUE_PROGRESS_REASON_PARAM_SCHEMAS = {
@@ -11447,7 +11752,7 @@ var reconcileWikiIssueDocumentPublicationSchema = external_exports.discriminated
11447
11752
  ]);
11448
11753
  var upsertIssueExternalWaitSchema = external_exports.object({
11449
11754
  ownerType: external_exports.enum(["external", "user"]),
11450
- actionKind: external_exports.enum(["approval", "input", "dependency", "other"]),
11755
+ actionKind: external_exports.enum(["dependency", "other"]),
11451
11756
  reasonCode: external_exports.string().trim().min(1).max(120),
11452
11757
  reviewAt: external_exports.string().datetime().nullable().optional(),
11453
11758
  dataSourceRead: businessDataSourceReadSchema.optional()
@@ -11702,11 +12007,6 @@ var suggestTasksResultSchema = external_exports.object({
11702
12007
  rejectionReason: external_exports.string().trim().max(4e3).nullable().optional()
11703
12008
  });
11704
12009
  var askUserQuestionsFormFieldSchema = secureInteractionFormFieldSchema;
11705
- var RESERVED_OTHER_OPTION_LABEL = /^(?:(?:其他|其它)(?:选项|方案|回答|情况|内容)?(?:请)?(?:说明|填写|输入|补充|补充说明)?|自定义(?:选项|方案|回答|内容)?(?:请)?(?:说明|填写|输入|补充|补充说明)?|以上都不是|other(?:option|answer|choice|pleasespecify|specify)?|custom(?:option|answer|choice)?|noneoftheabove|somethingelse)$/iu;
11706
- function isReservedOtherOptionLabel(label) {
11707
- const normalized = label.toLowerCase().replace(/[\p{P}\p{S}\s]+/gu, "");
11708
- return RESERVED_OTHER_OPTION_LABEL.test(normalized);
11709
- }
11710
12010
  var askUserQuestionsQuestionOptionSchema = external_exports.object({
11711
12011
  id: external_exports.string().trim().min(1).max(120),
11712
12012
  label: external_exports.string().trim().min(1).max(120).describe(
@@ -12222,7 +12522,7 @@ var requestInputItemSchema = external_exports.object({
12222
12522
  });
12223
12523
  }
12224
12524
  });
12225
- var requestInputsPayloadSchema = external_exports.object({
12525
+ var requestInputsPayloadV1Schema = external_exports.object({
12226
12526
  version: external_exports.literal(1),
12227
12527
  items: external_exports.array(requestInputItemSchema).min(1).max(50)
12228
12528
  }).strict().superRefine((value, ctx) => {
@@ -12245,6 +12545,16 @@ var requestInputsPayloadSchema = external_exports.object({
12245
12545
  });
12246
12546
  }
12247
12547
  });
12548
+ var requestInputsPayloadV2Schema = external_exports.object({
12549
+ version: external_exports.literal(2),
12550
+ spec: formSpecSchema,
12551
+ submitLabel: external_exports.string().trim().max(120).nullable().optional(),
12552
+ dueAt: external_exports.string().datetime({ offset: true }).nullable().optional()
12553
+ }).strict();
12554
+ var requestInputsPayloadSchema = external_exports.union([
12555
+ requestInputsPayloadV1Schema,
12556
+ requestInputsPayloadV2Schema
12557
+ ]);
12248
12558
  var requestInputItemResultSchema = external_exports.object({
12249
12559
  id: requestInputStableCodeSchema,
12250
12560
  status: external_exports.enum(["open", "satisfied", "waived_by_authorized_actor", "cancelled"]),
@@ -12253,10 +12563,22 @@ var requestInputItemResultSchema = external_exports.object({
12253
12563
  oauthConnectionName: connectorOAuthConnectionNameSchema.nullable().optional(),
12254
12564
  waiverReason: external_exports.string().trim().min(1).max(4e3).nullable().optional()
12255
12565
  }).strict();
12256
- var requestInputsResultSchema = external_exports.object({
12566
+ var requestInputsResultV1Schema = external_exports.object({
12257
12567
  version: external_exports.literal(1),
12258
12568
  items: external_exports.array(requestInputItemResultSchema).max(50)
12259
12569
  }).strict();
12570
+ var requestInputsResultV2Schema = external_exports.object({
12571
+ version: external_exports.literal(2),
12572
+ values: formSpecSubmissionValuesSchema,
12573
+ otherTexts: formSpecOtherTextsSchema.optional(),
12574
+ secretRefs: external_exports.record(formSpecFieldIdSchema, secureInteractionSecretRefSchema).optional(),
12575
+ cancelled: external_exports.literal(true).optional(),
12576
+ cancellationReason: external_exports.string().trim().min(1).max(4e3).optional()
12577
+ }).strict();
12578
+ var requestInputsResultSchema = external_exports.discriminatedUnion("version", [
12579
+ requestInputsResultV1Schema,
12580
+ requestInputsResultV2Schema
12581
+ ]);
12260
12582
  var staffingEscalationTargetSchema = external_exports.discriminatedUnion("kind", [
12261
12583
  external_exports.object({
12262
12584
  kind: external_exports.literal("agent"),
@@ -12317,7 +12639,7 @@ var submitRequestInputItemSchema = external_exports.object({
12317
12639
  });
12318
12640
  }
12319
12641
  });
12320
- var submitRequestInputItemsSchema = external_exports.object({
12642
+ var submitRequestInputItemsLegacySchema = external_exports.object({
12321
12643
  items: external_exports.array(submitRequestInputItemSchema).min(1, "At least one request input item submission is required").max(50)
12322
12644
  }).strict().superRefine((value, ctx) => {
12323
12645
  const itemIds = /* @__PURE__ */ new Set();
@@ -12332,6 +12654,21 @@ var submitRequestInputItemsSchema = external_exports.object({
12332
12654
  itemIds.add(item.id);
12333
12655
  }
12334
12656
  });
12657
+ var submitRequestInputFormValuesSchema = external_exports.object({
12658
+ version: external_exports.literal(2),
12659
+ values: formSpecSubmissionValuesSchema,
12660
+ otherTexts: formSpecOtherTextsSchema.optional(),
12661
+ secretValues: external_exports.record(formSpecFieldIdSchema, external_exports.string().max(4e3)).optional(),
12662
+ oauthEvidence: external_exports.record(formSpecFieldIdSchema, external_exports.object({
12663
+ connectionName: connectorOAuthConnectionNameSchema,
12664
+ authorizationId: connectorOAuthAuthorizationIdSchema,
12665
+ replaceConnectionName: connectorOAuthConnectionNameSchema.optional()
12666
+ }).strict()).optional()
12667
+ }).strict();
12668
+ var submitRequestInputItemsSchema = external_exports.union([
12669
+ submitRequestInputItemsLegacySchema,
12670
+ submitRequestInputFormValuesSchema
12671
+ ]);
12335
12672
  var requestInputAttentionMetadataItemUpdateSchema = external_exports.object({
12336
12673
  id: requestInputStableCodeSchema,
12337
12674
  owner: requestInputOwnerSchema.optional(),
@@ -12809,6 +13146,16 @@ var admitSuccessorExecutionEpochSchema = external_exports.object({
12809
13146
  idempotencyKey: external_exports.string().trim().min(1).max(200)
12810
13147
  }).strict();
12811
13148
 
13149
+ // ../shared/src/goal-task-reauthorization.ts
13150
+ var reauthorizeGoalTaskSchema = external_exports.object({
13151
+ expectedExecutionEpoch: external_exports.number().int().positive(),
13152
+ expectedDeliveryEpoch: external_exports.number().int().positive(),
13153
+ expectedEnrollmentId: external_exports.string().uuid(),
13154
+ expectedGoalGrantHash: external_exports.string().regex(/^sha256:[a-f0-9]{64}$/),
13155
+ reason: external_exports.string().trim().min(1).max(2e3),
13156
+ idempotencyKey: external_exports.string().trim().min(1).max(200)
13157
+ }).strict();
13158
+
12812
13159
  // ../shared/src/issue-delivery-acceptance.ts
12813
13160
  var uuidSchema3 = external_exports.string().uuid();
12814
13161
  var dateSchema2 = external_exports.union([external_exports.string().datetime({ offset: true }), external_exports.date()]);
@@ -13349,6 +13696,20 @@ var ceoPeriodicReachableAcceptanceIdentitySchema = external_exports.object({
13349
13696
  ...ceoPeriodicAcceptanceIdentityShape,
13350
13697
  deliveryIntent: ceoPeriodicAgentOutputDeliveryIntentSchema
13351
13698
  }).strict().superRefine(validateCeoPeriodicAcceptanceIdentity);
13699
+ var ceoExecutionAffordanceKeySchema = external_exports.string().trim().regex(/^[a-z0-9][a-z0-9._:-]{0,159}$/u);
13700
+ var ceoExecutionAffordanceSchema = external_exports.object({
13701
+ key: ceoExecutionAffordanceKeySchema,
13702
+ label: external_exports.string().trim().min(1).max(160),
13703
+ status: external_exports.enum(["available", "confirmation_required", "unavailable"]),
13704
+ effectKinds: external_exports.array(external_exports.enum(["read", "download", "upload", "external_write", "readback"])).min(1).max(5),
13705
+ source: external_exports.object({
13706
+ kind: external_exports.enum(["pi_runtime", "browser_session", "helige", "governed_mcp"]),
13707
+ ref: external_exports.string().trim().min(1).max(240),
13708
+ revision: external_exports.string().trim().min(1).max(240)
13709
+ }).strict(),
13710
+ confirmationPolicy: external_exports.enum(["none", "company_policy"]),
13711
+ evidenceKinds: external_exports.array(external_exports.enum(["web_evidence", "browser_receipt", "provider_receipt", "provider_readback"])).max(4)
13712
+ }).strict();
13352
13713
  var ceoPeriodicRoutingRosterEntrySchema = external_exports.object({
13353
13714
  agentId: external_exports.string().uuid(),
13354
13715
  roleSlot: external_exports.object({
@@ -13360,6 +13721,9 @@ var ceoPeriodicRoutingRosterEntrySchema = external_exports.object({
13360
13721
  runtimeReady: external_exports.boolean(),
13361
13722
  capabilitiesDeclared: external_exports.boolean(),
13362
13723
  capabilities: external_exports.array(external_exports.string().trim().min(1).max(160)).max(40),
13724
+ // Optional for persisted pre-affordance observation contexts. New snapshots
13725
+ // always write this independently from employee-declared professional skills.
13726
+ executionAffordanceKeys: external_exports.array(ceoExecutionAffordanceKeySchema).max(40).optional(),
13363
13727
  liveExecutionCount: external_exports.number().int().nonnegative(),
13364
13728
  queuedWorkCount: external_exports.number().int().nonnegative(),
13365
13729
  maxQueuedWorkCount: external_exports.number().int().nonnegative().max(CEO_PERIODIC_MAX_CANDIDATES_PER_OBSERVATION),
@@ -14471,6 +14835,7 @@ var mirrorXIssueCurrentProgressSchema = external_exports.discriminatedUnion("cod
14471
14835
  progressBranch("waiting_external_input", "needs_action", "external_input_required"),
14472
14836
  progressBranch("waiting_external_owner", "waiting", "external_owner"),
14473
14837
  progressBranch("waiting_source_acquisition_runtime", "waiting", "source_acquisition_runtime_unavailable"),
14838
+ progressBranch("result_disposition_required", "needs_action", "missing_successful_run_disposition"),
14474
14839
  progressBranch("recovery_needs_action", "needs_action", "active_recovery_action"),
14475
14840
  progressBranch("recovery_active", "active", "recovery_run_active"),
14476
14841
  progressBranch("execution_active", "active", "execution_active"),
@@ -14677,6 +15042,7 @@ var mirrorXIssueHandlingListCardSchema = external_exports.object({
14677
15042
  projectId: external_exports.string().uuid().nullable(),
14678
15043
  projectWorkspaceId: external_exports.string().uuid().nullable(),
14679
15044
  parentId: external_exports.string().uuid().nullable(),
15045
+ parentVisibilityRestricted: external_exports.boolean().optional(),
14680
15046
  title: external_exports.string(),
14681
15047
  description: external_exports.string().nullable(),
14682
15048
  status: external_exports.enum(ISSUE_STATUSES),
@@ -14689,6 +15055,7 @@ var mirrorXIssueHandlingListCardSchema = external_exports.object({
14689
15055
  identifier: external_exports.string().nullable(),
14690
15056
  originKind: external_exports.string().optional(),
14691
15057
  originId: external_exports.string().nullable().optional(),
15058
+ discoverySource: governedBusinessTaskDiscoverySourceSchema.nullable().optional(),
14692
15059
  executionWorkspaceId: external_exports.string().uuid().nullable(),
14693
15060
  routineStatus: external_exports.object({
14694
15061
  code: external_exports.enum([
@@ -17368,16 +17735,43 @@ var updateMemberPermissionsSchema = external_exports.object({
17368
17735
  var editableMembershipStatuses = ["pending", "active", "suspended"];
17369
17736
  var updateCompanyMemberSchema = external_exports.object({
17370
17737
  membershipRole: external_exports.enum(HUMAN_COMPANY_MEMBERSHIP_ROLES).optional().nullable(),
17371
- status: external_exports.enum(editableMembershipStatuses).optional()
17372
- }).refine((value) => value.membershipRole !== void 0 || value.status !== void 0, {
17373
- message: "membershipRole or status is required"
17738
+ status: external_exports.enum(editableMembershipStatuses).optional(),
17739
+ taskVisibilityScope: external_exports.enum(HUMAN_TASK_VISIBILITY_SCOPES).optional().nullable()
17740
+ }).refine((value) => value.membershipRole !== void 0 || value.status !== void 0 || value.taskVisibilityScope !== void 0, {
17741
+ message: "membershipRole, status, or taskVisibilityScope is required"
17374
17742
  });
17375
17743
  var updateCompanyMemberWithPermissionsSchema = external_exports.object({
17376
17744
  membershipRole: external_exports.enum(HUMAN_COMPANY_MEMBERSHIP_ROLES).optional().nullable(),
17377
17745
  status: external_exports.enum(editableMembershipStatuses).optional(),
17746
+ taskVisibilityScope: external_exports.enum(HUMAN_TASK_VISIBILITY_SCOPES).optional().nullable(),
17378
17747
  grants: updateMemberPermissionsSchema.shape.grants.default([])
17379
- }).refine((value) => value.membershipRole !== void 0 || value.status !== void 0, {
17380
- message: "membershipRole or status is required"
17748
+ }).refine((value) => value.membershipRole !== void 0 || value.status !== void 0 || value.taskVisibilityScope !== void 0, {
17749
+ message: "membershipRole, status, or taskVisibilityScope is required"
17750
+ });
17751
+ var createProjectAccessGrantSchema = external_exports.object({
17752
+ userId: external_exports.string().trim().min(1).max(320)
17753
+ });
17754
+ var createIssueAccessGrantSchema = external_exports.object({
17755
+ userId: external_exports.string().trim().min(1).max(320),
17756
+ includeDescendants: external_exports.boolean().optional().default(false)
17757
+ });
17758
+ var reconcileIssueAccessGrantsSchema = external_exports.object({
17759
+ issueIds: external_exports.array(external_exports.string().uuid()).max(2e3).optional()
17760
+ });
17761
+ var applyTaskVisibilityMigrationSchema = external_exports.object({
17762
+ previewRevision: external_exports.string().trim().length(64),
17763
+ members: external_exports.array(external_exports.object({
17764
+ memberId: external_exports.string().uuid(),
17765
+ taskVisibilityScope: external_exports.enum(HUMAN_TASK_VISIBILITY_SCOPES),
17766
+ currentReadableIssueCount: external_exports.number().int().nonnegative(),
17767
+ suggestedReadableIssueCount: external_exports.number().int().nonnegative(),
17768
+ blockers: external_exports.array(external_exports.enum([
17769
+ "active_assignment_without_access",
17770
+ "stage_participant_without_access",
17771
+ "pending_interaction_without_access"
17772
+ ])).max(3)
17773
+ })).max(1e4),
17774
+ finalize: external_exports.boolean().optional().default(false)
17381
17775
  });
17382
17776
  var archiveCompanyMemberSchema = external_exports.object({
17383
17777
  reassignment: external_exports.object({
@@ -18735,10 +19129,57 @@ var wikiMentionListSchema = external_exports.object({
18735
19129
  nextCursor: external_exports.string().nullable()
18736
19130
  });
18737
19131
 
19132
+ // ../shared/src/mirrorx-drive.ts
19133
+ var driveResourceRefSchema = external_exports.object({
19134
+ kind: external_exports.literal("file"),
19135
+ companyId: external_exports.string().uuid(),
19136
+ fileId: external_exports.string().uuid(),
19137
+ revisionId: external_exports.string().uuid()
19138
+ });
19139
+ var driveSaveSchema = external_exports.object({
19140
+ name: external_exports.string().min(1).max(240),
19141
+ parentId: external_exports.string().uuid().optional(),
19142
+ fileId: external_exports.string().uuid().optional(),
19143
+ expectedRevisionId: external_exports.string().uuid().optional(),
19144
+ visibility: external_exports.enum(["company_shared"]).default("company_shared")
19145
+ }).strict();
19146
+ var driveMutationSchema = external_exports.discriminatedUnion("operation", [
19147
+ external_exports.object({
19148
+ operation: external_exports.literal("rename"),
19149
+ metadataVersion: external_exports.number().int().positive(),
19150
+ name: external_exports.string().min(1).max(240)
19151
+ }),
19152
+ external_exports.object({
19153
+ operation: external_exports.literal("move"),
19154
+ metadataVersion: external_exports.number().int().positive(),
19155
+ parentId: external_exports.string().uuid()
19156
+ }),
19157
+ external_exports.object({
19158
+ operation: external_exports.literal("trash"),
19159
+ metadataVersion: external_exports.number().int().positive()
19160
+ }),
19161
+ external_exports.object({
19162
+ operation: external_exports.literal("restore"),
19163
+ metadataVersion: external_exports.number().int().positive()
19164
+ }),
19165
+ external_exports.object({
19166
+ operation: external_exports.literal("restore_version"),
19167
+ expectedRevisionId: external_exports.string().uuid(),
19168
+ revisionId: external_exports.string().uuid()
19169
+ })
19170
+ ]);
19171
+ var MIRRORX_DRIVE_AGENT_RULES = [
19172
+ "\u641C\u7D22\u3001\u8BFB\u53D6\u5F53\u524D\u516C\u53F8\u6709\u6743\u8BBF\u95EE\u7684\u8D44\u6599\uFF0C\u4F7F\u7528\u5DE5\u5177\u8FD4\u56DE\u7684\u5F15\u7528\u3002",
19173
+ "\u6587\u4EF6\u4FDD\u5B58\u5230\u672C\u4EFB\u52A1\u5DE5\u4F5C\u6587\u4EF6\uFF0C\u7EE7\u7EED\u4FEE\u6539\u540C\u4E00\u6587\u4EF6\uFF0C\u4E0D\u9020\u7248\u672C\u540E\u7F00\u3002",
19174
+ "\u66F4\u65B0\u5171\u4EAB\u8D44\u6599\u63D0\u4EA4\u5019\u9009\uFF0C\u7B49\u4EBA\u91C7\u7EB3\uFF0C\u4E0D\u76F4\u63A5\u6539\u539F\u4EF6\u6216\u6574\u7406\u76EE\u5F55\u3002",
19175
+ "\u6210\u679C\u8D70\u4EFB\u52A1\u4EA4\u4ED8\u5DE5\u5177\uFF0C\u77E5\u8BC6\u66F4\u65B0\u8D70\u4E13\u7528\u77E5\u8BC6\u7EF4\u62A4\u8BF7\u6C42\u3002",
19176
+ "\u51B2\u7A81\u6309\u63D0\u793A\u8BFB\u53D6\u6700\u65B0\u7248\u5E76\u91CD\u65B0\u6574\u7406\uFF1B\u65E0\u6743\u9650\u505C\u6B62\uFF1B\u5F52\u6863\u6210\u529F\u56DE\u6267\u624D\u4EE3\u8868\u5DF2\u4FDD\u5B58\u3002"
19177
+ ].join("\n");
19178
+
18738
19179
  // src/amaster-runtime-daemon.mjs
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";
18740
- import { arch as arch4, homedir as homedir6, hostname as hostname2, platform as platform4, tmpdir } from "node:os";
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";
19180
+ import { chmodSync as chmodSync8, copyFileSync as copyFileSync2, existsSync as existsSync18, lstatSync as lstatSync15, mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync5, readFileSync as readFileSync20, readdirSync as readdirSync13, realpathSync as realpathSync12, renameSync as renameSync11, rmSync as rmSync12, statSync as statSync12, symlinkSync as symlinkSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync14 } from "node:fs";
19181
+ import { arch as arch4, homedir as homedir7, hostname as hostname2, platform as platform4, tmpdir } from "node:os";
19182
+ import { basename as basename8, delimiter as delimiter3, dirname as dirname12, extname as extname3, isAbsolute as isAbsolute12, join as join25, relative as relative9, resolve as resolve19 } from "node:path";
18742
19183
  import { spawn, spawnSync as spawnSync5 } from "node:child_process";
18743
19184
 
18744
19185
  // src/amaster-runtime-daemon/common.mjs
@@ -22954,8 +23395,8 @@ async function runInitializationCompletion({ plan, authority, call, sleep, now,
22954
23395
  fail3("initialization_completion_invalid_plan");
22955
23396
  }
22956
23397
  const prefix = "initialization-complete:" + plan.planId;
22957
- const { createHash: createHash20 } = await import("node:crypto");
22958
- const uploadKey = prefix + ":upload:" + createHash20("sha256").update(materialized.path).digest("hex");
23398
+ const { createHash: createHash21 } = await import("node:crypto");
23399
+ const uploadKey = prefix + ":upload:" + createHash21("sha256").update(materialized.path).digest("hex");
22959
23400
  const upload = await settleCall(await invoke("runtime_action_submit", {
22960
23401
  idempotencyKey: uploadKey,
22961
23402
  action: {
@@ -23903,6 +24344,27 @@ function applyManagedPiRunExitClosureArgs(args, profile) {
23903
24344
  }
23904
24345
  return closureArgs;
23905
24346
  }
24347
+ function resolveManagedPiMcpAdapterExtension(adapterRoot) {
24348
+ const adapterRootStat = lstatSync7(adapterRoot);
24349
+ if (!adapterRootStat.isDirectory() || adapterRootStat.isSymbolicLink()) {
24350
+ throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24351
+ }
24352
+ const adapterManifest = JSON.parse(readFileSync6(join10(adapterRoot, "package.json"), "utf8"));
24353
+ const entries = adapterManifest.pi?.extensions;
24354
+ const entry = entries === void 0 ? "index.ts" : Array.isArray(entries) && entries.length === 1 ? entries[0] : null;
24355
+ if (!["index.ts", "./index.ts", "index.js", "./index.js"].includes(entry)) {
24356
+ throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24357
+ }
24358
+ const adapterExtensionPath = join10(adapterRoot, entry);
24359
+ if (!existsSync7(adapterExtensionPath)) {
24360
+ throw new Error("pi_managed_mcp_adapter_extension_missing");
24361
+ }
24362
+ const adapterExtensionStat = lstatSync7(adapterExtensionPath);
24363
+ if (!adapterExtensionStat.isFile() || adapterExtensionStat.isSymbolicLink()) {
24364
+ throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24365
+ }
24366
+ return adapterExtensionPath;
24367
+ }
23906
24368
  function createManagedPiMcpProfileApi(options = {}) {
23907
24369
  const spawnSyncImpl = typeof options.spawnSync === "function" ? options.spawnSync : spawnSync3;
23908
24370
  const chownSyncImpl = typeof options.chownSync === "function" ? options.chownSync : chownSync2;
@@ -24946,24 +25408,9 @@ ${result2.stderr ?? ""}`, "Pi", MINIMUM_PI_VERSION);
24946
25408
  return extensionPath;
24947
25409
  };
24948
25410
  if (directCatalog) {
24949
- const adapterExtensionPath = join10(
24950
- sharedRuntime.home,
24951
- "npm",
24952
- "node_modules",
24953
- "pi-mcp-adapter",
24954
- "index.ts"
25411
+ const adapterExtensionPath = resolveManagedPiMcpAdapterExtension(
25412
+ join10(sharedRuntime.home, "npm", "node_modules", "pi-mcp-adapter")
24955
25413
  );
24956
- if (!existsSync7(adapterExtensionPath)) {
24957
- throw new Error("pi_managed_mcp_adapter_extension_missing");
24958
- }
24959
- const adapterRootStat = lstatSync7(dirname5(adapterExtensionPath));
24960
- if (!adapterRootStat.isDirectory() || adapterRootStat.isSymbolicLink()) {
24961
- throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24962
- }
24963
- const adapterExtensionStat = lstatSync7(adapterExtensionPath);
24964
- if (!adapterExtensionStat.isFile() || adapterExtensionStat.isSymbolicLink()) {
24965
- throw new Error("pi_managed_mcp_adapter_extension_unsafe");
24966
- }
24967
25414
  extensionArgs.push("--extension", adapterExtensionPath);
24968
25415
  writeProfileExtension(
24969
25416
  MANAGED_PI_RUN_TERMINATION_FILENAME,
@@ -32287,9 +32734,14 @@ var BUILD_SUPPORTED_CAPABILITIES = Object.freeze([
32287
32734
  "execution_lanes_v1",
32288
32735
  "mirrorx_initialization_context_v1",
32289
32736
  "mirrorx_initialization_completion_v1",
32290
- "native_session_checkpoint_v1"
32737
+ "native_session_checkpoint_v1",
32738
+ "pi_web_public_search_v1"
32291
32739
  ]);
32292
32740
  var DYNAMIC_READINESS = Object.freeze({
32741
+ pi_web_public_search_v1: {
32742
+ reasonCode: "pi_web_search_extension_unavailable",
32743
+ ready: (input) => input.executors.some((executor) => executor.kind === "pi") && input.piWebSearchReady === true
32744
+ },
32293
32745
  browser_credential_env_read_v1: {
32294
32746
  reasonCode: "browser_credential_env_runtime_incomplete",
32295
32747
  ready: (input) => input.executors.some((executor) => executor.kind === "pi") && input.browserCredentialEnv?.extension === true && input.runnerKind === "cloud_managed" && Number.isSafeInteger(input.piExecutorUid) && Number.isSafeInteger(input.piExecutorGid) && input.piExecutorUid > 0 && input.piExecutorGid > 0 && Number.isSafeInteger(input.connectorUid) && input.piExecutorUid !== input.connectorUid
@@ -32883,10 +33335,13 @@ function createBrowserCredentialChannel({ consume }) {
32883
33335
  return;
32884
33336
  }
32885
33337
  requestBuffer = Buffer.from(parsed.remainder);
32886
- for (const frame of parsed.frames) sequence = sequence.then(() => handleFrame(frame));
33338
+ for (const frame of parsed.frames) {
33339
+ sequence = sequence.then(() => handleFrame(frame)).catch(() => respondError("browser_credential_request_invalid"));
33340
+ }
32887
33341
  });
32888
33342
  },
32889
- receipts() {
33343
+ async receipts() {
33344
+ await sequence;
32890
33345
  return authReceipts.map((receipt) => ({ ...receipt, credentialRoles: [...receipt.credentialRoles] }));
32891
33346
  },
32892
33347
  close() {
@@ -32899,7 +33354,8 @@ function createBrowserCredentialChannel({ consume }) {
32899
33354
  }
32900
33355
 
32901
33356
  // src/amaster-runtime-daemon/browser-credential-readiness.mjs
32902
- import { existsSync as existsSync12, readFileSync as readFileSync12, statSync as statSync6 } from "node:fs";
33357
+ import { existsSync as existsSync12, lstatSync as lstatSync9, readFileSync as readFileSync12, readdirSync as readdirSync8, statSync as statSync6 } from "node:fs";
33358
+ import { createHash as createHash14 } from "node:crypto";
32903
33359
  import { homedir as homedir4 } from "node:os";
32904
33360
  import { isAbsolute as isAbsolute7, join as join16, relative as relative5, resolve as resolve10 } from "node:path";
32905
33361
  var CAPABILITY = "browser_credential_auth_transaction_v1";
@@ -32907,12 +33363,16 @@ var CREDENTIAL_BROWSER_TCB = Object.freeze({
32907
33363
  package: "chrome-devtools-mcp",
32908
33364
  version: "1.6.0",
32909
33365
  mode: "puppeteer_pipe",
32910
- buildFileCount: 348,
32911
- buildTreeSha256: "b7f34fe406693fb9abac325a2c32cbb94c2096aafbed1cac2fee63a47eb1aff0"
33366
+ buildTreeSha256: "5bd07cd7ea92141441db12d1e84c4829dd4e2a45ea77f719878be9f4a42925d7"
33367
+ });
33368
+ var CREDENTIAL_BROWSER_PACKAGE_FILES = Object.freeze({
33369
+ "dist/config.js": "ed61ba70f3c2445db22fac31c432c86df2d9b3674bd36b34cce6f7a981f3926f",
33370
+ "dist/index.js": "7530da9aaa0ee272fa6e10ff80059f42a45aee6fff8d8c7cbce05c2cb24e180c"
32912
33371
  });
33372
+ var CREDENTIAL_AUTH_EXTENSION_SHA256 = "14088f0a7761a2a0884477ac2f300dcf615e4ba78b7753e4aec8078b344ab9b9";
32913
33373
  var READINESS_CACHE_TTL_MS = 5e3;
32914
33374
  var readinessCache = /* @__PURE__ */ new Map();
32915
- function inspectBrowserCredentialAuthReadiness(env = process.env) {
33375
+ function inspectBrowserCredentialAuthReadiness(env = process.env, expected = {}) {
32916
33376
  const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join16(homedir4(), ".pi", "agent")).trim();
32917
33377
  const now = Date.now();
32918
33378
  const cached = readinessCache.get(home);
@@ -32921,41 +33381,92 @@ function inspectBrowserCredentialAuthReadiness(env = process.env) {
32921
33381
  join16(home, "npm", "node_modules", "@amaster.ai", "pi-browser-use", "package.json"),
32922
33382
  join16(home, "node_modules", "@amaster.ai", "pi-browser-use", "package.json")
32923
33383
  ];
32924
- const packageAttested = candidates.some(attestedPackageManifest);
33384
+ const packageAttestation = candidates.map((manifestPath) => attestedPackageManifest(manifestPath, {
33385
+ browserTcb: expected.browserTcb ?? CREDENTIAL_BROWSER_TCB,
33386
+ packageFiles: expected.packageFiles ?? CREDENTIAL_BROWSER_PACKAGE_FILES,
33387
+ authExtensionSha256: expected.authExtensionSha256 ?? CREDENTIAL_AUTH_EXTENSION_SHA256
33388
+ })).find(Boolean) ?? null;
33389
+ const packageAttested = Boolean(packageAttestation);
33390
+ const authExtensionAttested = attestedAuthExtension(
33391
+ join16(home, "extensions", "browser-credential-auth.mjs"),
33392
+ packageAttestation ? expected.authExtensionSha256 ?? CREDENTIAL_AUTH_EXTENSION_SHA256 : null
33393
+ );
32925
33394
  const readiness = {
32926
33395
  privateChannel: true,
32927
33396
  executorClient: packageAttested,
32928
- sealedGate: packageAttested,
32929
- atomicTransaction: packageAttested,
32930
- trustedProfileInjection: true
33397
+ sealedGate: packageAttested && authExtensionAttested,
33398
+ atomicTransaction: packageAttested && authExtensionAttested,
33399
+ trustedProfileInjection: packageAttested
32931
33400
  };
32932
33401
  readinessCache.set(home, { readiness, expiresAt: now + READINESS_CACHE_TTL_MS });
32933
33402
  return { ...readiness };
32934
33403
  }
32935
- function attestedPackageManifest(manifestPath) {
33404
+ function attestedAuthExtension(extensionPath, expectedSha256) {
33405
+ try {
33406
+ if (typeof expectedSha256 !== "string" || !/^[a-f0-9]{64}$/u.test(expectedSha256)) return false;
33407
+ if (!statSync6(extensionPath).isFile()) return false;
33408
+ const source = readFileSync12(extensionPath, "utf8");
33409
+ return createHash14("sha256").update(source, "utf8").digest("hex") === expectedSha256 && source.includes("BrowserCredentialAuthBroker") && source.includes("browser_authenticate") && source.includes("AMASTER_BROWSER_CREDENTIAL_PRIVATE_CHANNEL");
33410
+ } catch {
33411
+ return false;
33412
+ }
33413
+ }
33414
+ function fileSha256(path) {
33415
+ return createHash14("sha256").update(readFileSync12(path)).digest("hex");
33416
+ }
33417
+ function treeAttestation(root) {
33418
+ const files = [];
33419
+ const visit = (directory) => {
33420
+ for (const entry of readdirSync8(directory, { withFileTypes: true })) {
33421
+ const path = join16(directory, entry.name);
33422
+ if (entry.isDirectory()) visit(path);
33423
+ else if (entry.isFile() && !lstatSync9(path).isSymbolicLink()) files.push(path);
33424
+ else throw new Error("browser_credential_tcb_tree_invalid");
33425
+ }
33426
+ };
33427
+ visit(root);
33428
+ files.sort();
33429
+ const digest2 = createHash14("sha256");
33430
+ for (const path of files) {
33431
+ digest2.update(relative5(root, path).replaceAll("\\", "/"));
33432
+ digest2.update("\0");
33433
+ digest2.update(readFileSync12(path));
33434
+ }
33435
+ return digest2.digest("hex");
33436
+ }
33437
+ function attestedPackageManifest(manifestPath, expected) {
32936
33438
  try {
32937
33439
  const manifest = JSON.parse(readFileSync12(manifestPath, "utf8"));
32938
- if (manifest?.name !== "@amaster.ai/pi-browser-use") return false;
33440
+ if (manifest?.name !== "@amaster.ai/pi-browser-use") return null;
32939
33441
  if (!Array.isArray(manifest.mirrorxCapabilities) || !manifest.mirrorxCapabilities.includes(CAPABILITY)) {
32940
- return false;
33442
+ return null;
32941
33443
  }
32942
- if (!sameCredentialBrowserTcb(manifest.mirrorxCredentialBrowserTcb)) return false;
32943
- if (typeof manifest.main !== "string" || !manifest.main.trim()) return false;
33444
+ if (!sameCredentialBrowserTcb(manifest.mirrorxCredentialBrowserTcb, expected.browserTcb)) return null;
33445
+ if (manifest.mirrorxCredentialAuthExtensionSha256 !== expected.authExtensionSha256) return null;
33446
+ if (typeof manifest.main !== "string" || !manifest.main.trim()) return null;
32944
33447
  const packageDir = resolve10(manifestPath, "..");
33448
+ if (Object.entries(expected.packageFiles).some(([relativePath, sha2563]) => {
33449
+ const path = resolve10(packageDir, relativePath);
33450
+ const relativePathFromPackage = relative5(packageDir, path);
33451
+ return !relativePathFromPackage || relativePathFromPackage.startsWith("..") || isAbsolute7(relativePathFromPackage) || !statSync6(path).isFile() || fileSha256(path) !== sha2563;
33452
+ })) return null;
33453
+ const browserPackageDir = resolve10(packageDir, "..", "..", "chrome-devtools-mcp");
33454
+ const browserPackage = JSON.parse(readFileSync12(join16(browserPackageDir, "package.json"), "utf8"));
33455
+ if (browserPackage.name !== expected.browserTcb.package || browserPackage.version !== expected.browserTcb.version || treeAttestation(join16(browserPackageDir, "build")) !== expected.browserTcb.buildTreeSha256) return null;
32945
33456
  const entrypoint = resolve10(packageDir, manifest.main);
32946
33457
  const relativeEntrypoint = relative5(packageDir, entrypoint);
32947
- if (!relativeEntrypoint || relativeEntrypoint.startsWith("..") || isAbsolute7(relativeEntrypoint) || !existsSync12(entrypoint)) return false;
32948
- return statSync6(entrypoint).isFile();
33458
+ if (!relativeEntrypoint || relativeEntrypoint.startsWith("..") || isAbsolute7(relativeEntrypoint) || !existsSync12(entrypoint)) return null;
33459
+ return statSync6(entrypoint).isFile() ? {} : null;
32949
33460
  } catch {
32950
- return false;
33461
+ return null;
32951
33462
  }
32952
33463
  }
32953
- function sameCredentialBrowserTcb(value) {
32954
- return value && typeof value === "object" && Object.entries(CREDENTIAL_BROWSER_TCB).every(([key, expected]) => value[key] === expected) && Object.keys(value).length === Object.keys(CREDENTIAL_BROWSER_TCB).length;
33464
+ function sameCredentialBrowserTcb(value, expected) {
33465
+ return value && typeof value === "object" && Object.entries(expected).every(([key, expectedValue]) => value[key] === expectedValue) && Object.keys(value).length === Object.keys(expected).length;
32955
33466
  }
32956
33467
 
32957
33468
  // src/amaster-runtime-daemon/browser-credential-env-readiness.mjs
32958
- import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
33469
+ import { lstatSync as lstatSync10, readFileSync as readFileSync13 } from "node:fs";
32959
33470
  import { homedir as homedir5 } from "node:os";
32960
33471
  import { join as join17 } from "node:path";
32961
33472
  var CACHE_TTL_MS = 5e3;
@@ -32968,7 +33479,7 @@ function inspectBrowserCredentialEnvReadiness(env = process.env) {
32968
33479
  const extensionPath = join17(home, "extensions", "browser-credential-env.mjs");
32969
33480
  let extension = false;
32970
33481
  try {
32971
- const stat = lstatSync9(extensionPath);
33482
+ const stat = lstatSync10(extensionPath);
32972
33483
  const source = stat.isFile() && !stat.isSymbolicLink() ? readFileSync13(extensionPath, "utf8") : "";
32973
33484
  extension = /\bname\s*:\s*["']browser_read_credential["']/u.test(source) && /\bPI_AGENT_BROWSER_CREDENTIAL_ENV_FILE\b/u.test(source);
32974
33485
  } catch {
@@ -32979,12 +33490,41 @@ function inspectBrowserCredentialEnvReadiness(env = process.env) {
32979
33490
  return { ...readiness };
32980
33491
  }
32981
33492
 
33493
+ // src/amaster-runtime-daemon/pi-web-search-readiness.mjs
33494
+ import { lstatSync as lstatSync11, readFileSync as readFileSync14 } from "node:fs";
33495
+ import { homedir as homedir6 } from "node:os";
33496
+ import { join as join18 } from "node:path";
33497
+ function readRegularJson(path) {
33498
+ try {
33499
+ const stat = lstatSync11(path);
33500
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
33501
+ const value = JSON.parse(readFileSync14(path, "utf8"));
33502
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
33503
+ } catch {
33504
+ return null;
33505
+ }
33506
+ }
33507
+ function inspectPiWebSearchReadiness(env = process.env) {
33508
+ const home = String(env.PI_CODING_AGENT_DIR ?? env.PI_AGENT_HOME ?? join18(homedir6(), ".pi", "agent")).trim();
33509
+ const settings = readRegularJson(join18(home, "settings.json"));
33510
+ const packages = Array.isArray(settings?.packages) ? settings.packages : [];
33511
+ const configured = packages.some((entry) => typeof entry === "string" && /^npm:@amaster\.ai\/pi-web-access(?:@|$)/u.test(entry));
33512
+ const providers = settings?.["pi-web-access"]?.providers;
33513
+ if (!configured || !providers || typeof providers !== "object" || Array.isArray(providers) || Object.keys(providers).length === 0) return false;
33514
+ const manifests = [
33515
+ join18(home, "npm", "node_modules", "@amaster.ai", "pi-web-access", "package.json"),
33516
+ join18(home, "node_modules", "@amaster.ai", "pi-web-access", "package.json")
33517
+ ];
33518
+ return manifests.some((path) => readRegularJson(path)?.name === "@amaster.ai/pi-web-access");
33519
+ }
33520
+
32982
33521
  // src/amaster-runtime-daemon/browser-credential-env.mjs
32983
33522
  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";
33523
+ import { join as join19, resolve as resolve11 } from "node:path";
32985
33524
  var BROWSER_CREDENTIAL_ENV_CAPABILITY = "browser_credential_env_read_v1";
32986
33525
  var BROWSER_CREDENTIAL_PRIVATE_CAPABILITY = "browser_credential_auth_transaction_v1";
32987
33526
  var BROWSER_CREDENTIAL_ENV_FILE = "PI_AGENT_BROWSER_CREDENTIAL_ENV_FILE";
33527
+ var BROWSER_CREDENTIAL_AUTHORITY_ENV = "AMASTER_BROWSER_CREDENTIAL_AUTHORITY_JSON";
32988
33528
  var BROWSER_CREDENTIAL_USERNAME_KEY = "BROWSER_USERNAME";
32989
33529
  var BROWSER_CREDENTIAL_PASSWORD_KEY = "BROWSER_PASSWORD";
32990
33530
  function exactOrigin2(value) {
@@ -33040,6 +33580,31 @@ function browserCredentialEnvPlan(command, presentation = browserCredentialPrese
33040
33580
  availableKeys: Object.freeze(availableKeys)
33041
33581
  });
33042
33582
  }
33583
+ function browserCredentialPrivateAuthority(command, presentation = browserCredentialPresentation(command)) {
33584
+ if (presentation !== "private_channel") return null;
33585
+ const refs = Array.isArray(command?.payload?.browserCredentialRefs) ? command.payload.browserCredentialRefs : [];
33586
+ const session = command?.payload?.browserSession;
33587
+ const targetUrl = typeof session?.targetUrl === "string" ? session.targetUrl : "";
33588
+ const predicate = session?.authenticatedPredicate;
33589
+ let parsedTarget;
33590
+ try {
33591
+ parsedTarget = new URL(targetUrl);
33592
+ } catch {
33593
+ fail2("browser_credential_authority_invalid");
33594
+ }
33595
+ const origin = parsedTarget.protocol === "https:" && !parsedTarget.username && !parsedTarget.password ? parsedTarget.origin : null;
33596
+ const passwordRefs = refs.filter((ref2) => ref2?.credentialRole === "password");
33597
+ const usernameRefs = refs.filter((ref2) => ref2?.credentialRole === "username");
33598
+ if (!origin || refs.length < 1 || refs.length > 2 || passwordRefs.length !== 1 || usernameRefs.length > 1 || !predicate || predicate.version !== 1 || predicate.type !== "snapshot_text_v1" || typeof predicate.requiredText !== "string" || predicate.requiredText !== predicate.requiredText.trim() || predicate.requiredText.length < 8 || predicate.requiredText.length > 256 || /[\u0000-\u001f\u007f]/u.test(predicate.requiredText) || refs.some((ref2) => ref2?.commandId !== command?.commandId || ref2?.bindingId !== session?.bindingId || ref2?.browserLeaseId !== session?.browserLeaseId || ref2?.targetOrigin !== origin || ref2?.authenticationOrigin !== origin)) {
33599
+ fail2("browser_credential_authority_invalid");
33600
+ }
33601
+ return Object.freeze({
33602
+ version: 1,
33603
+ targetUrl: parsedTarget.href,
33604
+ authenticatedPredicate: Object.freeze({ ...predicate }),
33605
+ refs: Object.freeze(refs.map((ref2) => Object.freeze({ ...ref2 })))
33606
+ });
33607
+ }
33043
33608
  function dotenvQuotedValue(value) {
33044
33609
  if (value.includes("\0")) fail2("browser_credential_env_value_invalid");
33045
33610
  return `"${value.replace(/[\\"\n\r\t$`]/gu, (char) => ({
@@ -33057,10 +33622,10 @@ async function materializeBrowserCredentialEnv(plan, options) {
33057
33622
  const rawRunDir = String(options.runDir ?? "").trim();
33058
33623
  if (!rawRunDir) fail2("browser_credential_env_run_dir_invalid");
33059
33624
  const runDir = resolve11(rawRunDir);
33060
- const credentialDir = mkdtempSync3(join18(runDir, ".browser-credentials-"));
33625
+ const credentialDir = mkdtempSync3(join19(runDir, ".browser-credentials-"));
33061
33626
  chmodSync6(credentialDir, 448);
33062
- const targetPath = join18(credentialDir, "credentials.env");
33063
- const temporaryPath = join18(credentialDir, ".credentials.env.tmp");
33627
+ const targetPath = join19(credentialDir, "credentials.env");
33628
+ const temporaryPath = join19(credentialDir, ".credentials.env.tmp");
33064
33629
  const buffers = [];
33065
33630
  const protectedValues = [];
33066
33631
  try {
@@ -33095,8 +33660,8 @@ async function materializeBrowserCredentialEnv(plan, options) {
33095
33660
  }
33096
33661
 
33097
33662
  // src/amaster-runtime-daemon/runtime-artifact-upload.mjs
33098
- import { createHash as createHash14 } from "node:crypto";
33099
- import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync4, lstatSync as lstatSync10, openSync as openSync4, readFileSync as readFileSync14, realpathSync as realpathSync10 } from "node:fs";
33663
+ import { createHash as createHash15 } from "node:crypto";
33664
+ import { closeSync as closeSync4, constants as constants3, fstatSync as fstatSync4, lstatSync as lstatSync12, openSync as openSync4, readFileSync as readFileSync15, realpathSync as realpathSync10 } from "node:fs";
33100
33665
  import { isAbsolute as isAbsolute8, relative as relative6, resolve as resolve12 } from "node:path";
33101
33666
  var SHA256_PATTERN = /^[a-f0-9]{64}$/;
33102
33667
  function requiredString2(value, name) {
@@ -33119,7 +33684,7 @@ function readOwnedWorkspaceFile(rootPath, sourceRelativePath, label = "Runtime w
33119
33684
  const root = realpathSync10(resolve12(rootPath));
33120
33685
  const relativePath = ownedRelativePath(sourceRelativePath);
33121
33686
  const sourcePath = resolve12(root, relativePath);
33122
- const pathStat = lstatSync10(sourcePath);
33687
+ const pathStat = lstatSync12(sourcePath);
33123
33688
  if (!pathStat.isFile() || pathStat.isSymbolicLink() || !pathWithin2(realpathSync10(sourcePath), root)) {
33124
33689
  throw new Error(`${label} source is not an owned regular file`);
33125
33690
  }
@@ -33148,10 +33713,10 @@ function readOwnedWorkspaceFile(rootPath, sourceRelativePath, label = "Runtime w
33148
33713
  );
33149
33714
  }
33150
33715
  }
33151
- const body = readFileSync14(descriptor);
33716
+ const body = readFileSync15(descriptor);
33152
33717
  options.afterRead?.({ sourcePath, descriptor });
33153
33718
  const after = fstatSync4(descriptor);
33154
- const pathAfter = lstatSync10(sourcePath);
33719
+ const pathAfter = lstatSync12(sourcePath);
33155
33720
  if (!sameFileSnapshot(before, after) || !sameFileSnapshot(pathAfter, after) || !pathAfter.isFile() || pathAfter.isSymbolicLink() || !pathWithin2(realpathSync10(sourcePath), root) || body.length !== after.size) {
33156
33721
  throw new Error(`${label} source changed during the governed read`);
33157
33722
  }
@@ -33185,7 +33750,7 @@ function prepareRuntimeArtifactUploads(cwd, mcpToolResults) {
33185
33750
  `Runtime Artifact ${intentId}`,
33186
33751
  { expectedByteSize }
33187
33752
  );
33188
- const actualSha256 = createHash14("sha256").update(body).digest("hex");
33753
+ const actualSha256 = createHash15("sha256").update(body).digest("hex");
33189
33754
  if (body.length !== expectedByteSize || actualSha256 !== expectedSha256) {
33190
33755
  throw new Error(`Runtime Artifact ${intentId} bytes do not match the governed ownership manifest`);
33191
33756
  }
@@ -33202,7 +33767,7 @@ function prepareRuntimeArtifactUploads(cwd, mcpToolResults) {
33202
33767
  }
33203
33768
 
33204
33769
  // src/amaster-runtime-daemon/runtime-document-upload.mjs
33205
- import { createHash as createHash15 } from "node:crypto";
33770
+ import { createHash as createHash16 } from "node:crypto";
33206
33771
 
33207
33772
  // src/amaster-runtime-daemon/workspace-sensitive-path.mjs
33208
33773
  var SENSITIVE_PATH_SEGMENTS = /* @__PURE__ */ new Set([
@@ -33277,7 +33842,7 @@ function prepareRuntimeDocumentUploads(cwd, mcpToolResults) {
33277
33842
  maxByteSize: MAX_WORKSPACE_DOCUMENT_BYTES
33278
33843
  }
33279
33844
  );
33280
- const actualSha256 = createHash15("sha256").update(body).digest("hex");
33845
+ const actualSha256 = createHash16("sha256").update(body).digest("hex");
33281
33846
  if (body.length !== expectedByteSize || actualSha256 !== expectedSha256) {
33282
33847
  throw new Error(`Runtime Document ${callId} bytes do not match the governed ownership manifest`);
33283
33848
  }
@@ -33474,9 +34039,9 @@ function createRuntimeArtifactIngestQueue({ ingest, onError }) {
33474
34039
  }
33475
34040
 
33476
34041
  // src/amaster-runtime-daemon/workspace-guard.mjs
33477
- import { createHash as createHash16 } from "node:crypto";
34042
+ import { createHash as createHash17 } from "node:crypto";
33478
34043
  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";
34044
+ import { basename as basename6, join as join20, isAbsolute as isAbsolute9, relative as relative7, resolve as resolve13 } from "node:path";
33480
34045
  function pathWithin3(candidate, root) {
33481
34046
  const rel = relative7(root, candidate);
33482
34047
  return rel === "" || !rel.startsWith("..") && !isAbsolute9(rel);
@@ -33503,7 +34068,7 @@ function resolveWorkspaceCwd(config, command) {
33503
34068
  return cwd;
33504
34069
  }
33505
34070
  function shortHash(value, length = 12) {
33506
- return createHash16("sha256").update(String(value)).digest("hex").slice(0, length);
34071
+ return createHash17("sha256").update(String(value)).digest("hex").slice(0, length);
33507
34072
  }
33508
34073
  function safeSegment(value, fallback) {
33509
34074
  const raw = String(value ?? "").trim();
@@ -33545,9 +34110,9 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
33545
34110
  const workspaceKey = `${safeSegment(workspaceLabel(sourceWorkspacePath, payload), "workspace")}-${shortHash(sourceWorkspacePath)}`;
33546
34111
  const issueKey = `${safeSegment(issueLabel(command, payload), "issue")}-${shortHash(issueId, 8)}`;
33547
34112
  const runKey = `${safeSegment(runId, "run")}-${shortHash(runId, 8)}`;
33548
- const runDir = join19(root, workspaceKey, issueKey, runKey);
33549
- const cwd = join19(runDir, "workdir");
33550
- const executorHome = join19(runDir, "executors", safeSegment(executorKind, "executor"));
34113
+ const runDir = join20(root, workspaceKey, issueKey, runKey);
34114
+ const cwd = join20(runDir, "workdir");
34115
+ const executorHome = join20(runDir, "executors", safeSegment(executorKind, "executor"));
33551
34116
  mkdirSync11(cwd, { recursive: true });
33552
34117
  mkdirSync11(executorHome, { recursive: true });
33553
34118
  const workspace = {
@@ -33571,8 +34136,8 @@ function resolveExecutionWorkspace(config, command, opts = {}) {
33571
34136
  }
33572
34137
 
33573
34138
  // src/amaster-runtime-daemon/workspace-gc.mjs
33574
- import { existsSync as existsSync14, readdirSync as readdirSync8, statSync as statSync8 } from "node:fs";
33575
- import { join as join20, resolve as resolve14 } from "node:path";
34139
+ import { existsSync as existsSync14, readdirSync as readdirSync9, statSync as statSync8 } from "node:fs";
34140
+ import { join as join21, resolve as resolve14 } from "node:path";
33576
34141
  function readIsoTime(value) {
33577
34142
  if (typeof value !== "string" || !value.trim()) return null;
33578
34143
  const time2 = new Date(value).getTime();
@@ -33589,13 +34154,13 @@ function walkWorkdirs(root) {
33589
34154
  if (!current) continue;
33590
34155
  let entries = [];
33591
34156
  try {
33592
- entries = readdirSync8(current, { withFileTypes: true });
34157
+ entries = readdirSync9(current, { withFileTypes: true });
33593
34158
  } catch {
33594
34159
  continue;
33595
34160
  }
33596
34161
  for (const entry of entries) {
33597
34162
  if (!entry.isDirectory()) continue;
33598
- const fullPath = join20(current, entry.name);
34163
+ const fullPath = join21(current, entry.name);
33599
34164
  if (entry.name === "workdir" && existsSync14(workspaceManifestPath(fullPath))) {
33600
34165
  workdirs.push(fullPath);
33601
34166
  continue;
@@ -33622,12 +34187,12 @@ function directorySizeBytes(path) {
33622
34187
  if (stat.isDirectory()) {
33623
34188
  let entries = [];
33624
34189
  try {
33625
- entries = readdirSync8(current, { withFileTypes: true });
34190
+ entries = readdirSync9(current, { withFileTypes: true });
33626
34191
  } catch {
33627
34192
  continue;
33628
34193
  }
33629
34194
  for (const entry of entries) {
33630
- stack.push(join20(current, entry.name));
34195
+ stack.push(join21(current, entry.name));
33631
34196
  }
33632
34197
  continue;
33633
34198
  }
@@ -33699,35 +34264,35 @@ function planManagedWorkspaceGcDryRun(input) {
33699
34264
  }
33700
34265
 
33701
34266
  // src/amaster-runtime-daemon/preset-templates.mjs
33702
- import { createHash as createHash17 } from "node:crypto";
34267
+ import { createHash as createHash18 } from "node:crypto";
33703
34268
  import {
33704
34269
  accessSync,
33705
34270
  chmodSync as chmodSync7,
33706
34271
  constants as constants4,
33707
34272
  existsSync as existsSync15,
33708
- lstatSync as lstatSync11,
34273
+ lstatSync as lstatSync13,
33709
34274
  mkdirSync as mkdirSync12,
33710
34275
  mkdtempSync as mkdtempSync4,
33711
- readFileSync as readFileSync15,
33712
- readdirSync as readdirSync9,
34276
+ readFileSync as readFileSync16,
34277
+ readdirSync as readdirSync10,
33713
34278
  renameSync as renameSync10,
33714
34279
  rmSync as rmSync11,
33715
34280
  statSync as statSync9,
33716
34281
  unlinkSync as unlinkSync2,
33717
34282
  writeFileSync as writeFileSync13
33718
34283
  } from "node:fs";
33719
- import { dirname as dirname10, extname, isAbsolute as isAbsolute10, join as join21, parse as parse4, resolve as resolve15, sep as sep4 } from "node:path";
34284
+ import { dirname as dirname10, extname, isAbsolute as isAbsolute10, join as join22, parse as parse4, resolve as resolve15, sep as sep4 } from "node:path";
33720
34285
  import { fileURLToPath } from "node:url";
33721
34286
  var PRESET_TEMPLATE_MANIFEST_FILE = ".mirrorx-preset-templates.json";
33722
34287
  var MAX_PRESET_TEMPLATE_FILES = 256;
33723
34288
  var MAX_PRESET_TEMPLATE_FILE_BYTES = 20 * 1024 * 1024;
33724
34289
  var MAX_PRESET_TEMPLATE_TOTAL_BYTES = 50 * 1024 * 1024;
33725
34290
  function sha2562(value) {
33726
- return createHash17("sha256").update(value).digest("hex");
34291
+ return createHash18("sha256").update(value).digest("hex");
33727
34292
  }
33728
34293
  function lstatIfExists(path) {
33729
34294
  try {
33730
- return lstatSync11(path);
34295
+ return lstatSync13(path);
33731
34296
  } catch (error) {
33732
34297
  if (error?.code === "ENOENT") return null;
33733
34298
  throw error;
@@ -33742,7 +34307,7 @@ function modeAllows(stat, identity, ownerBit, groupBit, otherBit) {
33742
34307
  function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
33743
34308
  if (!identity) {
33744
34309
  accessSync(targetDir, constants4.R_OK | constants4.X_OK);
33745
- for (const name of fileNames) accessSync(join21(targetDir, name), constants4.R_OK);
34310
+ for (const name of fileNames) accessSync(join22(targetDir, name), constants4.R_OK);
33746
34311
  return;
33747
34312
  }
33748
34313
  let current = targetDir;
@@ -33760,7 +34325,7 @@ function assertCatalogReadableByExecutor(targetDir, fileNames, identity) {
33760
34325
  throw new Error(`preset_template_executor_catalog_unreadable: ${targetDir}`);
33761
34326
  }
33762
34327
  for (const name of fileNames) {
33763
- const path = join21(targetDir, name);
34328
+ const path = join22(targetDir, name);
33764
34329
  const stat = statSync9(path);
33765
34330
  if (!stat.isFile() || !modeAllows(stat, identity, 256, 32, 4)) {
33766
34331
  throw new Error(`preset_template_executor_file_unreadable: ${name}`);
@@ -33776,7 +34341,7 @@ function validTemplateName(value) {
33776
34341
  }
33777
34342
  function readManifest(manifestPath, { strict }) {
33778
34343
  try {
33779
- const parsed = JSON.parse(readFileSync15(manifestPath, "utf8"));
34344
+ const parsed = JSON.parse(readFileSync16(manifestPath, "utf8"));
33780
34345
  if (parsed?.schemaVersion !== 1 || !Array.isArray(parsed.files)) {
33781
34346
  throw new Error("preset_template_bundle_manifest_invalid");
33782
34347
  }
@@ -33804,12 +34369,12 @@ function readManifest(manifestPath, { strict }) {
33804
34369
  }
33805
34370
  function verifiedBundleFiles(sourceDir, manifest) {
33806
34371
  return manifest.files.map((entry) => {
33807
- const sourcePath = join21(sourceDir, entry.name);
33808
- const stat = lstatSync11(sourcePath);
34372
+ const sourcePath = join22(sourceDir, entry.name);
34373
+ const stat = lstatSync13(sourcePath);
33809
34374
  if (!stat.isFile() || stat.isSymbolicLink()) {
33810
34375
  throw new Error(`preset_template_bundle_file_unsafe: ${entry.name}`);
33811
34376
  }
33812
- const body = readFileSync15(sourcePath);
34377
+ const body = readFileSync16(sourcePath);
33813
34378
  if (body.byteLength !== entry.bytes || sha2562(body) !== entry.sha256) {
33814
34379
  throw new Error(`preset_template_bundle_digest_mismatch: ${entry.name}`);
33815
34380
  }
@@ -33819,9 +34384,9 @@ function verifiedBundleFiles(sourceDir, manifest) {
33819
34384
  function removeRetiredPresetFiles(targetDir, previousManifest, nextNames) {
33820
34385
  for (const entry of previousManifest.files) {
33821
34386
  if (nextNames.has(entry.name)) continue;
33822
- const targetPath = join21(targetDir, entry.name);
34387
+ const targetPath = join22(targetDir, entry.name);
33823
34388
  if (!existsSync15(targetPath)) continue;
33824
- const stat = lstatSync11(targetPath);
34389
+ const stat = lstatSync13(targetPath);
33825
34390
  if (stat.isDirectory()) {
33826
34391
  throw new Error(`preset_template_target_conflict: ${entry.name}`);
33827
34392
  }
@@ -33834,7 +34399,7 @@ function materializeBundledPresetTemplates(input) {
33834
34399
  if (sourceDir === targetDir || sourceDir.startsWith(`${targetDir}${sep4}`) || targetDir.startsWith(`${sourceDir}${sep4}`)) {
33835
34400
  throw new Error("preset_template_source_target_overlap");
33836
34401
  }
33837
- const manifest = readManifest(join21(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
34402
+ const manifest = readManifest(join22(sourceDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: true });
33838
34403
  const verifiedFiles = verifiedBundleFiles(sourceDir, manifest);
33839
34404
  mkdirSync12(dirname10(targetDir), { recursive: true, mode: 493 });
33840
34405
  const targetStat = lstatIfExists(targetDir);
@@ -33842,24 +34407,24 @@ function materializeBundledPresetTemplates(input) {
33842
34407
  throw new Error("preset_template_target_root_unsafe");
33843
34408
  }
33844
34409
  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-"));
34410
+ const previousManifest = readManifest(join22(targetDir, PRESET_TEMPLATE_MANIFEST_FILE), { strict: false });
34411
+ const stageDir = mkdtempSync4(join22(dirname10(targetDir), ".mirrorx-preset-templates-"));
33847
34412
  try {
33848
34413
  for (const file of verifiedFiles) {
33849
- const stagedPath = join21(stageDir, file.name);
34414
+ const stagedPath = join22(stageDir, file.name);
33850
34415
  writeFileSync13(stagedPath, file.body, { mode: 292 });
33851
34416
  chmodSync7(stagedPath, 292);
33852
- renameSync10(stagedPath, join21(targetDir, file.name));
34417
+ renameSync10(stagedPath, join22(targetDir, file.name));
33853
34418
  }
33854
34419
  removeRetiredPresetFiles(targetDir, previousManifest, new Set(manifest.files.map((file) => file.name)));
33855
- const stagedManifest = join21(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
34420
+ const stagedManifest = join22(stageDir, PRESET_TEMPLATE_MANIFEST_FILE);
33856
34421
  writeFileSync13(stagedManifest, `${JSON.stringify({
33857
34422
  schemaVersion: manifest.schemaVersion,
33858
34423
  files: manifest.files
33859
34424
  }, null, 2)}
33860
34425
  `, { mode: 292 });
33861
34426
  chmodSync7(stagedManifest, 292);
33862
- renameSync10(stagedManifest, join21(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
34427
+ renameSync10(stagedManifest, join22(targetDir, PRESET_TEMPLATE_MANIFEST_FILE));
33863
34428
  } finally {
33864
34429
  rmSync11(stageDir, { recursive: true, force: true });
33865
34430
  }
@@ -33876,12 +34441,12 @@ function materializeRuntimePresetTemplates(input) {
33876
34441
  sourceDir,
33877
34442
  targetDir: input.targetDir
33878
34443
  });
33879
- const manifestBody = readFileSync15(
33880
- join21(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
34444
+ const manifestBody = readFileSync16(
34445
+ join22(materialized.targetDir, PRESET_TEMPLATE_MANIFEST_FILE)
33881
34446
  );
33882
34447
  const manifest = JSON.parse(manifestBody.toString("utf8"));
33883
34448
  for (const file of manifest.files) {
33884
- const body = readFileSync15(join21(materialized.targetDir, file.name));
34449
+ const body = readFileSync16(join22(materialized.targetDir, file.name));
33885
34450
  if (sha2562(body) !== file.sha256) {
33886
34451
  throw new Error(`preset_template_materialized_digest_mismatch: ${file.name}`);
33887
34452
  }
@@ -33904,11 +34469,11 @@ function materializeRuntimePresetTemplates(input) {
33904
34469
  }
33905
34470
 
33906
34471
  // src/amaster-runtime-daemon/runtime-status-summary.mjs
33907
- import { existsSync as existsSync16, readdirSync as readdirSync10, statSync as statSync10 } from "node:fs";
33908
- import { dirname as dirname11, join as join22, resolve as resolve16 } from "node:path";
34472
+ import { existsSync as existsSync16, readdirSync as readdirSync11, statSync as statSync10 } from "node:fs";
34473
+ import { dirname as dirname11, join as join23, resolve as resolve16 } from "node:path";
33909
34474
  function runtimeStatusDirectoryEntries(path) {
33910
34475
  try {
33911
- return readdirSync10(path, { withFileTypes: true });
34476
+ return readdirSync11(path, { withFileTypes: true });
33912
34477
  } catch {
33913
34478
  return [];
33914
34479
  }
@@ -33928,7 +34493,7 @@ function runtimeStatusDirectorySizeBytes(path) {
33928
34493
  if (!stat || stat.isSymbolicLink()) continue;
33929
34494
  if (stat.isDirectory()) {
33930
34495
  for (const entry of runtimeStatusDirectoryEntries(current)) {
33931
- stack.push(join22(current, entry.name));
34496
+ stack.push(join23(current, entry.name));
33932
34497
  }
33933
34498
  continue;
33934
34499
  }
@@ -33945,7 +34510,7 @@ function walkRuntimeStatusManagedWorkdirs(root) {
33945
34510
  if (!current) continue;
33946
34511
  for (const entry of runtimeStatusDirectoryEntries(current)) {
33947
34512
  if (!entry.isDirectory()) continue;
33948
- const fullPath = join22(current, entry.name);
34513
+ const fullPath = join23(current, entry.name);
33949
34514
  if (entry.name === "workdir" && existsSync16(workspaceManifestPath(fullPath))) {
33950
34515
  workdirs.push(fullPath);
33951
34516
  continue;
@@ -33987,7 +34552,7 @@ function summarizeRuntimeStatusRecentRun(workdir, manifest) {
33987
34552
  }
33988
34553
  function runtimeStatusOutboxDir(config) {
33989
34554
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
33990
- return join22(dirname11(stateFilePath({
34555
+ return join23(dirname11(stateFilePath({
33991
34556
  AMASTER_DAEMON_STATE_FILE: statePath
33992
34557
  })), "result-outbox");
33993
34558
  }
@@ -33995,7 +34560,7 @@ function runtimeStatusRunCompletionDir(config) {
33995
34560
  const explicit = config.AMASTER_RUN_COMPLETION_STATE_DIR ?? config.runCompletionStateDir;
33996
34561
  if (typeof explicit === "string" && explicit.trim()) return resolve16(explicit);
33997
34562
  const statePath = config.AMASTER_DAEMON_STATE_FILE ?? config.daemonStateFile;
33998
- return join22(dirname11(stateFilePath({
34563
+ return join23(dirname11(stateFilePath({
33999
34564
  AMASTER_DAEMON_STATE_FILE: statePath
34000
34565
  })), "run-completion-state");
34001
34566
  }
@@ -34032,9 +34597,9 @@ function summarizeRuntimeLocalState(input) {
34032
34597
  }
34033
34598
  }
34034
34599
  const pendingOutboxDir = runtimeStatusOutboxDir(config);
34035
- const invalidOutboxDir = join22(pendingOutboxDir, "invalid");
34600
+ const invalidOutboxDir = join23(pendingOutboxDir, "invalid");
34036
34601
  const pendingRunCompletionDir = runtimeStatusRunCompletionDir(config);
34037
- const invalidRunCompletionDir = join22(pendingRunCompletionDir, "invalid");
34602
+ const invalidRunCompletionDir = join23(pendingRunCompletionDir, "invalid");
34038
34603
  return {
34039
34604
  managedWorkspacesRoot: root,
34040
34605
  managedWorkdirCount: workdirs.length,
@@ -34156,7 +34721,7 @@ function summarizeAmasterRuntimeVersionDrift(input = {}) {
34156
34721
  }
34157
34722
 
34158
34723
  // src/amaster-runtime-daemon/pi-context-budget.mjs
34159
- import { readFileSync as readFileSync16 } from "node:fs";
34724
+ import { readFileSync as readFileSync17 } from "node:fs";
34160
34725
  var CONTEXT_ERROR_CODES = /* @__PURE__ */ new Set([
34161
34726
  "context_effective_tool_schema_attestation_mismatch",
34162
34727
  "context_output_reserve_exceeds_model_limit",
@@ -34271,7 +34836,7 @@ function measureRestoredPiNativeHistory(managedMcpProfile) {
34271
34836
  if (!rolloutPath) {
34272
34837
  return { status: "fresh", tokens: 0, rolloutBytes: 0, usageTokens: 0 };
34273
34838
  }
34274
- const rollout = readFileSync16(rolloutPath);
34839
+ const rollout = readFileSync17(rolloutPath);
34275
34840
  const maximumRolloutBytes = 64 * 1024 * 1024;
34276
34841
  if (rollout.byteLength > maximumRolloutBytes) {
34277
34842
  throw stableContextError(
@@ -34365,7 +34930,7 @@ function resolvePiModelContextBudget({
34365
34930
  }
34366
34931
 
34367
34932
  // src/amaster-runtime-daemon/pi-project-instruction-extension.mjs
34368
- import { lstatSync as lstatSync12, readFileSync as readFileSync17 } from "node:fs";
34933
+ import { lstatSync as lstatSync14, readFileSync as readFileSync18 } from "node:fs";
34369
34934
  import { resolve as resolve17 } from "node:path";
34370
34935
  var MANAGED_PI_PROJECT_INSTRUCTION_FILENAME = "amaster-project-instructions.js";
34371
34936
  function requiredString4(value, name) {
@@ -34376,11 +34941,11 @@ function requiredString4(value, name) {
34376
34941
  }
34377
34942
  function managedPiProjectInstructionExtensionSource(input) {
34378
34943
  const projectInstructionPath = resolve17(requiredString4(input.projectInstructionPath, "projectInstructionPath"));
34379
- const stat = lstatSync12(projectInstructionPath);
34944
+ const stat = lstatSync14(projectInstructionPath);
34380
34945
  if (!stat.isFile() || stat.isSymbolicLink()) {
34381
34946
  throw new Error("pi_project_instruction_extension_invalid: unsafe projectInstructionPath");
34382
34947
  }
34383
- const projectInstructions = readFileSync17(projectInstructionPath, "utf8");
34948
+ const projectInstructions = readFileSync18(projectInstructionPath, "utf8");
34384
34949
  return String.raw`const PROJECT_INSTRUCTIONS = ${JSON.stringify(projectInstructions.trim())};
34385
34950
 
34386
34951
  export default function amasterProjectInstructions(pi) {
@@ -34394,9 +34959,9 @@ export default function amasterProjectInstructions(pi) {
34394
34959
 
34395
34960
  // src/amaster-runtime-daemon/workspace-status.mjs
34396
34961
  import { spawnSync as spawnSync4 } from "node:child_process";
34397
- import { createHash as createHash18 } from "node:crypto";
34398
- import { existsSync as existsSync17, readdirSync as readdirSync11, readFileSync as readFileSync18, statSync as statSync11 } from "node:fs";
34399
- import { basename as basename7, extname as extname2, isAbsolute as isAbsolute11, join as join23, relative as relative8, resolve as resolve18 } from "node:path";
34962
+ import { createHash as createHash19 } from "node:crypto";
34963
+ import { existsSync as existsSync17, readdirSync as readdirSync12, readFileSync as readFileSync19, statSync as statSync11 } from "node:fs";
34964
+ import { basename as basename7, extname as extname2, isAbsolute as isAbsolute11, join as join24, relative as relative8, resolve as resolve18 } from "node:path";
34400
34965
  var WORKSPACE_RUNTIME_SERVICES_FILENAME = ".amaster-runtime-services.json";
34401
34966
  var ARTIFACT_EXTENSIONS = /* @__PURE__ */ new Map([
34402
34967
  [".md", "markdown"],
@@ -34465,7 +35030,7 @@ function sanitizeTrackedChange(line) {
34465
35030
  return isSafeRelativePath(path) ? line : null;
34466
35031
  }
34467
35032
  function sha256File(filePath) {
34468
- return createHash18("sha256").update(readFileSync18(filePath)).digest("hex");
35033
+ return createHash19("sha256").update(readFileSync19(filePath)).digest("hex");
34469
35034
  }
34470
35035
  function artifactHashCacheKey(relativePath, stat) {
34471
35036
  return `${relativePath}\0${stat.size}\0${stat.mtimeMs}`;
@@ -34503,7 +35068,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
34503
35068
  const current = stack.pop();
34504
35069
  let entries;
34505
35070
  try {
34506
- entries = readdirSync11(current, { withFileTypes: true });
35071
+ entries = readdirSync12(current, { withFileTypes: true });
34507
35072
  } catch {
34508
35073
  continue;
34509
35074
  }
@@ -34514,7 +35079,7 @@ function scanArtifactCandidates(cwd, opts = {}) {
34514
35079
  if (entry.name.startsWith(".") && entry.name !== ".amaster-runtime.json") {
34515
35080
  if (entry.name === ".git") continue;
34516
35081
  }
34517
- const fullPath = join23(current, entry.name);
35082
+ const fullPath = join24(current, entry.name);
34518
35083
  const relativePath = normalizeRelativePath(root, fullPath);
34519
35084
  if (!isSafeRelativePath(relativePath)) continue;
34520
35085
  if (basename7(relativePath) === ".amaster-runtime.json") continue;
@@ -34592,10 +35157,10 @@ function sanitizeRuntimeService(entry) {
34592
35157
  };
34593
35158
  }
34594
35159
  function readRuntimeServicesSnapshot(cwd) {
34595
- const snapshotPath = join23(resolve18(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
35160
+ const snapshotPath = join24(resolve18(cwd), WORKSPACE_RUNTIME_SERVICES_FILENAME);
34596
35161
  if (!existsSync17(snapshotPath)) return [];
34597
35162
  try {
34598
- const parsed = JSON.parse(readFileSync18(snapshotPath, "utf8"));
35163
+ const parsed = JSON.parse(readFileSync19(snapshotPath, "utf8"));
34599
35164
  const rawServices = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.services) ? parsed.services : [];
34600
35165
  return rawServices.map((entry) => sanitizeRuntimeService(entry)).filter((entry) => entry !== null).slice(0, 50);
34601
35166
  } catch {
@@ -34697,7 +35262,7 @@ function assertRequiredTaskAttachmentMaterialized(input, materialized) {
34697
35262
  }
34698
35263
 
34699
35264
  // src/amaster-runtime-daemon.mjs
34700
- var CONNECTOR_VERSION = "0.1.9";
35265
+ var CONNECTOR_VERSION = "0.1.10";
34701
35266
  var CONNECTOR_CONTRACT_VERSION = "2026-06-04.v1";
34702
35267
  var SUPPORTED_TASK_CONTEXT_VERSIONS = Object.freeze([TASK_CONTEXT_MANIFEST_VERSION, TASK_CONTEXT_V2]);
34703
35268
  var daemonRequire = createRequire(import.meta.url);
@@ -34796,8 +35361,8 @@ function resultOutboxPendingCount(config) {
34796
35361
  if (!existsSync18(dir)) return 0;
34797
35362
  try {
34798
35363
  let pending = 0;
34799
- for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json"))) {
34800
- if (readValidResultOutboxEntryOrQuarantine(config, file, join24(dir, file))) {
35364
+ for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json"))) {
35365
+ if (readValidResultOutboxEntryOrQuarantine(config, file, join25(dir, file))) {
34801
35366
  pending += 1;
34802
35367
  }
34803
35368
  }
@@ -34809,15 +35374,15 @@ function resultOutboxPendingCount(config) {
34809
35374
  function runCompletionStateDir(config) {
34810
35375
  const explicit = readString(process.env.AMASTER_RUN_COMPLETION_STATE_DIR);
34811
35376
  if (explicit) return resolve19(expandHomePath(explicit));
34812
- return join24(dirname12(stateFilePath(process.env)), "run-completion-state");
35377
+ return join25(dirname12(stateFilePath(process.env)), "run-completion-state");
34813
35378
  }
34814
35379
  function runCompletionStateInvalidDir(config) {
34815
- return join24(runCompletionStateDir(config), "invalid");
35380
+ return join25(runCompletionStateDir(config), "invalid");
34816
35381
  }
34817
35382
  function quarantineInvalidRunCompletionState(config, filePath, reason) {
34818
35383
  const invalidDir = runCompletionStateInvalidDir(config);
34819
35384
  mkdirSync13(invalidDir, { recursive: true, mode: 448 });
34820
- const destination = join24(invalidDir, basename8(filePath));
35385
+ const destination = join25(invalidDir, basename8(filePath));
34821
35386
  try {
34822
35387
  renameSync11(filePath, destination);
34823
35388
  } catch {
@@ -34874,8 +35439,8 @@ function resultOutboxActiveRunCommands(config) {
34874
35439
  if (!existsSync18(dir)) return [];
34875
35440
  const outboxPending = resultOutboxPendingCount(config);
34876
35441
  const entries = [];
34877
- for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json")).sort()) {
34878
- const entry = readValidResultOutboxEntryOrQuarantine(config, file, join24(dir, file));
35442
+ for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json")).sort()) {
35443
+ const entry = readValidResultOutboxEntryOrQuarantine(config, file, join25(dir, file));
34879
35444
  if (!entry) continue;
34880
35445
  const activeRun = asRecord(entry.activeRun);
34881
35446
  const commandId = readString(activeRun.commandId) ?? readString(entry.commandId);
@@ -34908,10 +35473,10 @@ function resultOutboxFailedRunCommands(config) {
34908
35473
  const dir = resultOutboxInvalidDir(config);
34909
35474
  if (!existsSync18(dir)) return [];
34910
35475
  const entries = [];
34911
- for (const file of readdirSync12(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
35476
+ for (const file of readdirSync13(dir).filter((name) => name.endsWith(".json")).sort().slice(-100)) {
34912
35477
  let entry;
34913
35478
  try {
34914
- entry = asRecord(JSON.parse(readFileSync19(join24(dir, file), "utf8")));
35479
+ entry = asRecord(JSON.parse(readFileSync20(join25(dir, file), "utf8")));
34915
35480
  } catch {
34916
35481
  continue;
34917
35482
  }
@@ -34978,7 +35543,7 @@ function safeExpandPath(value) {
34978
35543
  }
34979
35544
  function safeJsonObjectFromFile(filePath) {
34980
35545
  try {
34981
- const parsed = JSON.parse(readFileSync19(filePath, "utf8"));
35546
+ const parsed = JSON.parse(readFileSync20(filePath, "utf8"));
34982
35547
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
34983
35548
  } catch {
34984
35549
  return null;
@@ -34995,7 +35560,7 @@ function safeDirectorySummary(pathValue) {
34995
35560
  }
34996
35561
  let entryCount = 0;
34997
35562
  let truncated = false;
34998
- for (const name of readdirSync12(pathValue)) {
35563
+ for (const name of readdirSync13(pathValue)) {
34999
35564
  if (name.startsWith(".")) continue;
35000
35565
  entryCount += 1;
35001
35566
  if (entryCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
@@ -35019,12 +35584,12 @@ function safeSkillRootSummary(kind, source, pathValue) {
35019
35584
  let truncated = false;
35020
35585
  if (directory.available && pathValue) {
35021
35586
  try {
35022
- for (const name of readdirSync12(pathValue)) {
35587
+ for (const name of readdirSync13(pathValue)) {
35023
35588
  if (name.startsWith(".")) continue;
35024
- const skillDir = join24(pathValue, name);
35589
+ const skillDir = join25(pathValue, name);
35025
35590
  try {
35026
35591
  if (!statSync12(skillDir).isDirectory()) continue;
35027
- if (!existsSync18(join24(skillDir, "SKILL.md"))) continue;
35592
+ if (!existsSync18(join25(skillDir, "SKILL.md"))) continue;
35028
35593
  skillCount += 1;
35029
35594
  if (skillCount >= MAX_PI_CAPABILITY_SOURCE_ENTRIES) {
35030
35595
  truncated = true;
@@ -35075,7 +35640,7 @@ function objectKeyCount(value) {
35075
35640
  return value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).length : 0;
35076
35641
  }
35077
35642
  function defaultPiCodingAgentDir() {
35078
- return join24(homedir6(), ".pi", "agent");
35643
+ return join25(homedir7(), ".pi", "agent");
35079
35644
  }
35080
35645
  function piCapabilitySourcesDiagnostics() {
35081
35646
  const configuredPiCodingAgentDir = safeExpandPath(process.env.PI_CODING_AGENT_DIR);
@@ -35084,14 +35649,14 @@ function piCapabilitySourcesDiagnostics() {
35084
35649
  const configuredPiAgentHome = safeExpandPath(process.env.PI_AGENT_HOME);
35085
35650
  const piAgentHome = configuredPiAgentHome ?? piCodingAgentDir;
35086
35651
  const piAgentHomeSource = configuredPiAgentHome ? "PI_AGENT_HOME" : piCodingAgentDirSource;
35087
- const userSkillsPath = piAgentHome ? join24(piAgentHome, "skills") : null;
35652
+ const userSkillsPath = piAgentHome ? join25(piAgentHome, "skills") : null;
35088
35653
  const configuredMarketplaceSkillsPath = safeExpandPath(
35089
35654
  process.env.PI_AGENT_MARKETPLACE_SKILLS_DIR
35090
35655
  );
35091
- const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join24(piAgentHome, "marketplace", "skills") : null);
35656
+ const marketplaceSkillsPath = configuredMarketplaceSkillsPath ?? (piAgentHome ? join25(piAgentHome, "marketplace", "skills") : null);
35092
35657
  const builtinSkillsPath = safeExpandPath(process.env.PI_AGENT_BUILTIN_SKILLS_DIR) ?? safeExpandPath(process.env.AMASTER_BUILTIN_SKILLS);
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;
35658
+ const mcpConfigPath = safeExpandPath(process.env.PI_AGENT_MCP_SERVERS_FILE) ?? (piAgentHome ? join25(piAgentHome, "mcp.json") : null);
35659
+ const settingsConfigPath = piCodingAgentDir ? join25(piCodingAgentDir, "settings.json") : null;
35095
35660
  const skillRoots = [
35096
35661
  safeSkillRootSummary("user", `${piAgentHomeSource}/skills`, userSkillsPath),
35097
35662
  safeSkillRootSummary(
@@ -35254,7 +35819,8 @@ function runtimeAdvertisedCapabilities(config) {
35254
35819
  checkpointUploadEnabled: config.checkpointUploadEnabled,
35255
35820
  executors: config.executors,
35256
35821
  browserCredentialAuth: inspectBrowserCredentialAuthReadiness(),
35257
- browserCredentialEnv: inspectBrowserCredentialEnvReadiness()
35822
+ browserCredentialEnv: inspectBrowserCredentialEnvReadiness(),
35823
+ piWebSearchReady: inspectPiWebSearchReadiness()
35258
35824
  });
35259
35825
  }
35260
35826
  function buildRegisterPayload(config) {
@@ -35386,16 +35952,16 @@ function handoffPiRunPathsToChild(config, paths) {
35386
35952
  function materializePiRuntimeSystemPrompt(config, promptRoot, commandId, contents) {
35387
35953
  const normalizedCommandId = readString(commandId);
35388
35954
  if (!normalizedCommandId) throw new Error("pi_runtime_system_prompt_command_id_missing");
35389
- const promptIdentity = createHash19("sha256").update(normalizedCommandId).digest("hex");
35390
- const promptDir = join24(promptRoot, "tmp");
35955
+ const promptIdentity = createHash20("sha256").update(normalizedCommandId).digest("hex");
35956
+ const promptDir = join25(promptRoot, "tmp");
35391
35957
  mkdirSync13(promptDir, { recursive: true, mode: 448 });
35392
- const promptDirStat = lstatSync13(promptDir);
35958
+ const promptDirStat = lstatSync15(promptDir);
35393
35959
  if (!promptDirStat.isDirectory() || promptDirStat.isSymbolicLink()) {
35394
35960
  throw new Error("pi_runtime_system_prompt_directory_invalid");
35395
35961
  }
35396
35962
  chmodSync8(promptDir, 448);
35397
- const promptPath = join24(promptDir, `runtime-system-${promptIdentity}.md`);
35398
- const temporaryPath = join24(promptDir, `.runtime-system.${process.pid}.${randomUUID2()}.tmp`);
35963
+ const promptPath = join25(promptDir, `runtime-system-${promptIdentity}.md`);
35964
+ const temporaryPath = join25(promptDir, `.runtime-system.${process.pid}.${randomUUID2()}.tmp`);
35399
35965
  try {
35400
35966
  writeFileSync14(temporaryPath, contents, { encoding: "utf8", mode: 384, flag: "wx" });
35401
35967
  renameSync11(temporaryPath, promptPath);
@@ -35571,7 +36137,7 @@ AMASTER_MACHINE_ID=${quoteShell(config.machineId)}
35571
36137
  AMASTER_WORKSPACE_ALLOWLIST=${quoteShell(config.workspaceBindings.join(","))}
35572
36138
  AMASTER_EXECUTORS=${quoteShell(executorEnv)}
35573
36139
  AMASTER_NETWORK_DOMAINS=${quoteShell(config.networkDomains.join(","))}
35574
- AMASTER_DAEMON_STATE_FILE=${quoteShell(join24(homedir6(), ".amaster-employee", "runtime-connector-state.json"))}
36140
+ AMASTER_DAEMON_STATE_FILE=${quoteShell(join25(homedir7(), ".amaster-employee", "runtime-connector-state.json"))}
35575
36141
  EOF
35576
36142
 
35577
36143
  set -a
@@ -36050,7 +36616,7 @@ function ensureBrowserSessionProfile(config, session) {
36050
36616
  const identity = browserSessionProfileIdentity(config, session);
36051
36617
  const profileRoot = resolve19(config.browserSessionStateRoot);
36052
36618
  mkdirSync13(profileRoot, { recursive: true, mode: 448 });
36053
- if (lstatSync13(profileRoot).isSymbolicLink() || !lstatSync13(profileRoot).isDirectory()) {
36619
+ if (lstatSync15(profileRoot).isSymbolicLink() || !lstatSync15(profileRoot).isDirectory()) {
36054
36620
  throw new Error("browser_session_profile_path_invalid");
36055
36621
  }
36056
36622
  chmodSync8(profileRoot, 448);
@@ -36059,13 +36625,13 @@ function ensureBrowserSessionProfile(config, session) {
36059
36625
  throw new Error("browser_session_profile_path_invalid");
36060
36626
  }
36061
36627
  mkdirSync13(userDataDir, { recursive: true, mode: 448 });
36062
- if (lstatSync13(userDataDir).isSymbolicLink() || !lstatSync13(userDataDir).isDirectory()) {
36628
+ if (lstatSync15(userDataDir).isSymbolicLink() || !lstatSync15(userDataDir).isDirectory()) {
36063
36629
  throw new Error("browser_session_profile_path_invalid");
36064
36630
  }
36065
36631
  chmodSync8(userDataDir, 448);
36066
- const markerPath = join24(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36632
+ const markerPath = join25(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36067
36633
  if (existsSync18(markerPath)) {
36068
- if (lstatSync13(markerPath).isSymbolicLink()) {
36634
+ if (lstatSync15(markerPath).isSymbolicLink()) {
36069
36635
  throw new Error("browser_session_profile_identity_invalid");
36070
36636
  }
36071
36637
  const existing = readJsonFile2(markerPath);
@@ -36073,9 +36639,9 @@ function ensureBrowserSessionProfile(config, session) {
36073
36639
  throw new Error("browser_session_profile_identity_invalid");
36074
36640
  }
36075
36641
  } else {
36076
- const temporaryPath = join24(
36642
+ const temporaryPath = join25(
36077
36643
  userDataDir,
36078
- `.${BROWSER_SESSION_PROFILE_OWNER_MARKER}.${process.pid}.${createHash19("sha256").update(randomUUID2()).digest("hex")}`
36644
+ `.${BROWSER_SESSION_PROFILE_OWNER_MARKER}.${process.pid}.${createHash20("sha256").update(randomUUID2()).digest("hex")}`
36079
36645
  );
36080
36646
  writeFileSync14(temporaryPath, `${JSON.stringify(identity)}
36081
36647
  `, { mode: 384, flag: "wx" });
@@ -36092,11 +36658,11 @@ function cleanupBrowserSessionProfile(config, value) {
36092
36658
  throw new Error("browser_session_profile_cleanup_invalid");
36093
36659
  }
36094
36660
  if (!existsSync18(userDataDir)) return { outcome: "absent", identity };
36095
- if (lstatSync13(userDataDir).isSymbolicLink() || !lstatSync13(userDataDir).isDirectory()) {
36661
+ if (lstatSync15(userDataDir).isSymbolicLink() || !lstatSync15(userDataDir).isDirectory()) {
36096
36662
  throw new Error("browser_session_profile_cleanup_invalid");
36097
36663
  }
36098
- const markerPath = join24(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36099
- if (!existsSync18(markerPath) || lstatSync13(markerPath).isSymbolicLink()) {
36664
+ const markerPath = join25(userDataDir, BROWSER_SESSION_PROFILE_OWNER_MARKER);
36665
+ if (!existsSync18(markerPath) || lstatSync15(markerPath).isSymbolicLink()) {
36100
36666
  throw new Error("browser_session_profile_cleanup_invalid");
36101
36667
  }
36102
36668
  if (JSON.stringify(readJsonFile2(markerPath)) !== JSON.stringify(identity)) {
@@ -36107,7 +36673,7 @@ function cleanupBrowserSessionProfile(config, value) {
36107
36673
  }
36108
36674
  function readJsonFile2(filePath) {
36109
36675
  try {
36110
- const parsed = JSON.parse(readFileSync19(filePath, "utf8"));
36676
+ const parsed = JSON.parse(readFileSync20(filePath, "utf8"));
36111
36677
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
36112
36678
  } catch {
36113
36679
  return {};
@@ -36118,8 +36684,8 @@ function syncPiExecutorProviderConfig(config, agentDir, providerConfig) {
36118
36684
  const { modelsSynced, settingsSynced } = syncAmasterProviderFiles(agentDir, providerConfig);
36119
36685
  if (!modelsSynced && !settingsSynced) return null;
36120
36686
  handoffPiRunPathsToChild(config, [
36121
- modelsSynced ? join24(agentDir, "models.json") : null,
36122
- settingsSynced ? join24(agentDir, "settings.json") : null
36687
+ modelsSynced ? join25(agentDir, "models.json") : null,
36688
+ settingsSynced ? join25(agentDir, "settings.json") : null
36123
36689
  ]);
36124
36690
  return { modelsSynced, settingsSynced };
36125
36691
  }
@@ -36156,7 +36722,7 @@ function safeAgentInstructionMaterializationTarget(workspace, filePath) {
36156
36722
  }
36157
36723
  function stableInstructionFilesHash(files) {
36158
36724
  const canonical = Object.entries(files).filter(([filePath, content]) => typeof filePath === "string" && typeof content === "string").sort(([left], [right]) => left.localeCompare(right)).map(([filePath, content]) => `${filePath.length}:${filePath}${content.length}:${content}`).join("");
36159
- return createHash19("sha256").update(canonical, "utf8").digest("hex");
36725
+ return createHash20("sha256").update(canonical, "utf8").digest("hex");
36160
36726
  }
36161
36727
  function requireCommandContextEnvelope(command) {
36162
36728
  const payload = asRecord(command.payload);
@@ -36200,7 +36766,7 @@ function requireCommandContextEnvelope(command) {
36200
36766
  if (instructions.effectiveChars !== files["AGENTS.md"].length) {
36201
36767
  throw new Error("context_envelope_instruction_size_mismatch");
36202
36768
  }
36203
- const entrySha256 = createHash19("sha256").update(files["AGENTS.md"], "utf8").digest("hex");
36769
+ const entrySha256 = createHash20("sha256").update(files["AGENTS.md"], "utf8").digest("hex");
36204
36770
  if (entrySha256 !== readString(instructions.contentSha256)) {
36205
36771
  throw new Error("context_envelope_instruction_content_hash_mismatch");
36206
36772
  }
@@ -36210,7 +36776,7 @@ function requireCommandContextEnvelope(command) {
36210
36776
  }
36211
36777
  const runDecisionContext = asRecord(envelope.runDecisionContext);
36212
36778
  const dynamicContext2 = asRecord(runDecisionContext.content);
36213
- const runDecisionHash = createHash19("sha256").update(canonicalGoalOutcomeValue(dynamicContext2), "utf8").digest("hex");
36779
+ const runDecisionHash = createHash20("sha256").update(canonicalGoalOutcomeValue(dynamicContext2), "utf8").digest("hex");
36214
36780
  if (!readString(runDecisionContext.revision) || !Number.isInteger(runDecisionContext.authorizationEpoch) || runDecisionContext.authorizationEpoch < 0 || runDecisionHash !== readString(runDecisionContext.contentSha256)) throw new Error("context_envelope_run_decision_invalid");
36215
36781
  if (!Array.isArray(envelope.selectedProcedures)) throw new Error("context_envelope_procedures_invalid");
36216
36782
  const toolProfile = asRecord(envelope.toolProfile);
@@ -36220,7 +36786,7 @@ function requireCommandContextEnvelope(command) {
36220
36786
  throw new Error("context_envelope_session_binding_invalid");
36221
36787
  }
36222
36788
  const envelopeHashInput = Object.fromEntries(Object.entries(envelope).filter(([key]) => key !== "envelopeSha256"));
36223
- const envelopeHash = createHash19("sha256").update(canonicalGoalOutcomeValue(envelopeHashInput), "utf8").digest("hex");
36789
+ const envelopeHash = createHash20("sha256").update(canonicalGoalOutcomeValue(envelopeHashInput), "utf8").digest("hex");
36224
36790
  if (envelopeHash !== readString(envelope.envelopeSha256)) {
36225
36791
  throw new Error("context_envelope_hash_mismatch");
36226
36792
  }
@@ -36240,7 +36806,7 @@ async function materializeEffectiveAgentInstructions(config, command, workspace,
36240
36806
  const temporaryPath = `${target.targetPath}.mirrorx-${command.commandId}.tmp`;
36241
36807
  try {
36242
36808
  writeFileSync14(temporaryPath, content, { encoding: "utf8", mode: 384 });
36243
- const readBack = readFileSync19(temporaryPath, "utf8");
36809
+ const readBack = readFileSync20(temporaryPath, "utf8");
36244
36810
  if (readBack !== content) {
36245
36811
  throw new Error(`context_envelope_instruction_readback_mismatch: ${filePath}`);
36246
36812
  }
@@ -36251,12 +36817,12 @@ async function materializeEffectiveAgentInstructions(config, command, workspace,
36251
36817
  materialized.push({
36252
36818
  path: target.relativePath,
36253
36819
  byteSize: Buffer.byteLength(content, "utf8"),
36254
- sha256: createHash19("sha256").update(content, "utf8").digest("hex")
36820
+ sha256: createHash20("sha256").update(content, "utf8").digest("hex")
36255
36821
  });
36256
36822
  }
36257
36823
  const readBackFiles = Object.fromEntries(materialized.map((entry) => [
36258
36824
  entry.path,
36259
- readFileSync19(resolve19(workspace.cwd, entry.path), "utf8")
36825
+ readFileSync20(resolve19(workspace.cwd, entry.path), "utf8")
36260
36826
  ]));
36261
36827
  if (stableInstructionFilesHash(readBackFiles) !== readString(instructionContract.contentHash)) {
36262
36828
  throw new Error("context_envelope_materialized_hash_mismatch");
@@ -36280,7 +36846,7 @@ function wikiTreePathForCommand(command, workspaceBindings) {
36280
36846
  const candidates = [];
36281
36847
  if (root.endsWith("paperclipai.plugin-llm-wiki")) candidates.push(root);
36282
36848
  if (basename8(root) === "plugin-data" && companyId) {
36283
- candidates.push(join24(root, companyId, "paperclipai.plugin-llm-wiki"));
36849
+ candidates.push(join25(root, companyId, "paperclipai.plugin-llm-wiki"));
36284
36850
  }
36285
36851
  for (const candidate of candidates) {
36286
36852
  try {
@@ -36519,7 +37085,7 @@ function attachPiProjectInstructionExtension(profile, input) {
36519
37085
  "managed Pi profile is missing"
36520
37086
  );
36521
37087
  }
36522
- const projectInstructionExtensionPath = join24(
37088
+ const projectInstructionExtensionPath = join25(
36523
37089
  profile.profileRoot,
36524
37090
  "extensions",
36525
37091
  MANAGED_PI_PROJECT_INSTRUCTION_FILENAME
@@ -36568,17 +37134,17 @@ function buildExecutorEnv(config, command, workspace) {
36568
37134
  };
36569
37135
  }
36570
37136
  function preparePiModelCallProfile(commandId, baseEnv, options = {}) {
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");
37137
+ const profileRoot = mkdtempSync5(join25(tmpdir(), "amaster-pi-model-call-"));
37138
+ const home = join25(profileRoot, "home");
37139
+ const sessionsDir = join25(profileRoot, "sessions");
37140
+ const tempDir = join25(profileRoot, "tmp");
36575
37141
  for (const directory of [home, sessionsDir, tempDir]) {
36576
37142
  mkdirSync13(directory, { recursive: true, mode: 448 });
36577
37143
  }
36578
37144
  try {
36579
37145
  const extensionArgs = [];
36580
37146
  if (options.responseContract) {
36581
- const extensionPath = join24(profileRoot, "model-call-output-contract.js");
37147
+ const extensionPath = join25(profileRoot, "model-call-output-contract.js");
36582
37148
  writeFileSync14(
36583
37149
  extensionPath,
36584
37150
  modelCallOutputContractExtensionSource(options.responseContract.maxOutputTokens),
@@ -36958,6 +37524,8 @@ function runtimeLogBatchBytes(command, entries) {
36958
37524
  return Buffer.byteLength(JSON.stringify({ entries: runtimeLogBatchEntries(command, entries) }));
36959
37525
  }
36960
37526
  function createLiveOutputLogger(config, command, executorKind, protectedValues = [], onMcpToolResults = null, options = {}) {
37527
+ const timing = executionTiming("runner.output", command);
37528
+ const observedTimingEvents = /* @__PURE__ */ new Set();
36961
37529
  const buffers = { stdout: "", stderr: "" };
36962
37530
  const displayCounts = { stdout: 0, stderr: 0, system: 0 };
36963
37531
  const sourceCounts = { stdout: 0, stderr: 0 };
@@ -37051,6 +37619,11 @@ function createLiveOutputLogger(config, command, executorKind, protectedValues =
37051
37619
  }
37052
37620
  jsonlEventCount += 1;
37053
37621
  const eventType = countEventType(event);
37622
+ const deltaType = asRecord(asRecord(event).assistantMessageEvent).type;
37623
+ if (eventType === "message_update" && ["text_delta", "thinking_delta"].includes(deltaType) && !observedTimingEvents.has(deltaType)) {
37624
+ observedTimingEvents.add(deltaType);
37625
+ timing(deltaType === "text_delta" ? "first_text_delta" : "first_thinking_delta");
37626
+ }
37054
37627
  const progressType = options2.suppressMeaningful === true ? null : meaningfulProgressType(event, entry);
37055
37628
  if (progressType) {
37056
37629
  meaningfulProgressEventCount += 1;
@@ -37499,7 +38072,7 @@ function allProcessCwdsByPid() {
37499
38072
  if (process.platform === "linux") {
37500
38073
  const procEntries = (() => {
37501
38074
  try {
37502
- return readdirSync12("/proc", { withFileTypes: true });
38075
+ return readdirSync13("/proc", { withFileTypes: true });
37503
38076
  } catch {
37504
38077
  return [];
37505
38078
  }
@@ -37592,13 +38165,13 @@ function walkManagedWorkdirs(root) {
37592
38165
  if (!current) continue;
37593
38166
  let entries = [];
37594
38167
  try {
37595
- entries = readdirSync12(current, { withFileTypes: true });
38168
+ entries = readdirSync13(current, { withFileTypes: true });
37596
38169
  } catch {
37597
38170
  continue;
37598
38171
  }
37599
38172
  for (const entry of entries) {
37600
38173
  if (!entry.isDirectory()) continue;
37601
- const fullPath = join24(current, entry.name);
38174
+ const fullPath = join25(current, entry.name);
37602
38175
  if (entry.name === "workdir" && existsSync18(workspaceManifestPath(fullPath))) {
37603
38176
  workdirs.push(fullPath);
37604
38177
  continue;
@@ -37789,7 +38362,7 @@ function runExecutor(command, args, options) {
37789
38362
  };
37790
38363
  const stdoutDecoder = createUtf8StreamDecoder(handleStdoutText);
37791
38364
  const stderrDecoder = createUtf8StreamDecoder(handleStderrText);
37792
- const finish = (result2) => {
38365
+ const finish = async (result2) => {
37793
38366
  if (settled) return;
37794
38367
  settled = true;
37795
38368
  stdoutDecoder.end();
@@ -37806,7 +38379,7 @@ function runExecutor(command, args, options) {
37806
38379
  if (stoppedResidentTimer) clearTimeout(stoppedResidentTimer);
37807
38380
  if (completionOutputDrainTimer) clearTimeout(completionOutputDrainTimer);
37808
38381
  if (stdinSettlementTimer) clearTimeout(stdinSettlementTimer);
37809
- const browserCredentialAuthReceipts = browserCredentialChannel?.receipts() ?? [];
38382
+ const browserCredentialAuthReceipts = await browserCredentialChannel?.receipts() ?? [];
37810
38383
  browserCredentialChannel?.close();
37811
38384
  options.signal?.removeEventListener?.("abort", abort);
37812
38385
  resolveRun({
@@ -37917,7 +38490,7 @@ function runExecutor(command, args, options) {
37917
38490
  child.stdout.destroy();
37918
38491
  child.stderr.destroy();
37919
38492
  }
37920
- finish({
38493
+ void finish({
37921
38494
  exitCode: closeCode,
37922
38495
  signal: closeSignal,
37923
38496
  timedOut: stopReason === "timeout",
@@ -38601,10 +39174,10 @@ async function completeCommand(config, command, status, result2, error) {
38601
39174
  function resultOutboxDir(config) {
38602
39175
  const explicit = readString(process.env.AMASTER_RESULT_OUTBOX_DIR);
38603
39176
  if (explicit) return resolve19(expandHomePath(explicit));
38604
- return join24(dirname12(stateFilePath(process.env)), "result-outbox");
39177
+ return join25(dirname12(stateFilePath(process.env)), "result-outbox");
38605
39178
  }
38606
39179
  function resultOutboxInvalidDir(config) {
38607
- return join24(resultOutboxDir(config), "invalid");
39180
+ return join25(resultOutboxDir(config), "invalid");
38608
39181
  }
38609
39182
  function writeResultOutboxEntry(config, entry) {
38610
39183
  const dir = resultOutboxDir(config);
@@ -38618,13 +39191,13 @@ function writeResultOutboxEntry(config, entry) {
38618
39191
  ...entry,
38619
39192
  ...pendingLogEntries.length > 0 ? { pendingLogEntries } : {}
38620
39193
  };
38621
- writeFileSync14(join24(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
39194
+ writeFileSync14(join25(dir, resultOutboxFileName(entry.commandId)), `${JSON.stringify(body, null, 2)}
38622
39195
  `, { mode: 384 });
38623
39196
  }
38624
39197
  function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail, original) {
38625
39198
  const invalidDir = resultOutboxInvalidDir(config);
38626
39199
  mkdirSync13(invalidDir, { recursive: true });
38627
- const invalidPath = join24(invalidDir, file);
39200
+ const invalidPath = join25(invalidDir, file);
38628
39201
  if (original === void 0) {
38629
39202
  try {
38630
39203
  renameSync11(fullPath, invalidPath);
@@ -38647,7 +39220,7 @@ function moveResultOutboxEntryToInvalid(config, file, fullPath, reason, detail,
38647
39220
  function readValidResultOutboxEntryOrQuarantine(config, file, fullPath) {
38648
39221
  let entry;
38649
39222
  try {
38650
- entry = JSON.parse(readFileSync19(fullPath, "utf8"));
39223
+ entry = JSON.parse(readFileSync20(fullPath, "utf8"));
38651
39224
  } catch (err) {
38652
39225
  const message = err instanceof Error ? err.message : String(err);
38653
39226
  moveResultOutboxEntryToInvalid(config, file, fullPath, "malformed_result_outbox_json", message);
@@ -38694,7 +39267,7 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
38694
39267
  ...typeof err?.httpStatus === "number" ? { httpStatus: err.httpStatus } : {},
38695
39268
  lastError: truncateText(err instanceof Error ? err.message : String(err), 1e3)
38696
39269
  };
38697
- const invalidPath = join24(invalidDir, file);
39270
+ const invalidPath = join25(invalidDir, file);
38698
39271
  writeFileSync14(invalidPath, `${JSON.stringify(body, null, 2)}
38699
39272
  `, { mode: 384 });
38700
39273
  try {
@@ -38710,10 +39283,10 @@ function quarantineResultOutboxEntry(config, fullPath, file, entry, reason, err)
38710
39283
  async function flushResultOutbox(config) {
38711
39284
  const dir = resultOutboxDir(config);
38712
39285
  if (!existsSync18(dir)) return { attempted: 0, completed: 0 };
38713
- const files = readdirSync12(dir).filter((name) => name.endsWith(".json")).sort();
39286
+ const files = readdirSync13(dir).filter((name) => name.endsWith(".json")).sort();
38714
39287
  let completed = 0;
38715
39288
  for (const file of files) {
38716
- const fullPath = join24(dir, file);
39289
+ const fullPath = join25(dir, file);
38717
39290
  let entry = readValidResultOutboxEntryOrQuarantine(config, file, fullPath);
38718
39291
  if (!entry) continue;
38719
39292
  const pendingLogEntries = Array.isArray(entry.pendingLogEntries) ? entry.pendingLogEntries.filter((logEntry) => typeof asRecord(logEntry).message === "string") : [];
@@ -38952,7 +39525,7 @@ async function materializeIssueAttachments(config, command, workspace) {
38952
39525
  runtimeAuth,
38953
39526
  issueId
38954
39527
  );
38955
- const targetDir = join24(workspace.cwd, "input-attachments");
39528
+ const targetDir = join25(workspace.cwd, "input-attachments");
38956
39529
  mkdirSync13(targetDir, { recursive: true });
38957
39530
  const usedFilenames = /* @__PURE__ */ new Set();
38958
39531
  const materialized = [];
@@ -38966,14 +39539,14 @@ async function materializeIssueAttachments(config, command, workspace) {
38966
39539
  let filename = safeMaterializedAttachmentFilename(attachment, index);
38967
39540
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
38968
39541
  usedFilenames.add(filename);
38969
- const targetPath = join24(targetDir, filename);
39542
+ const targetPath = join25(targetDir, filename);
38970
39543
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
38971
- if (attachment.initializationInput === true && (body.byteLength !== attachment.byteSize || createHash19("sha256").update(body).digest("hex") !== attachment.sha256)) {
39544
+ if (attachment.initializationInput === true && (body.byteLength !== attachment.byteSize || createHash20("sha256").update(body).digest("hex") !== attachment.sha256)) {
38972
39545
  throw new Error("Initialization input content does not match its preparation receipt");
38973
39546
  }
38974
39547
  writeFileSync14(targetPath, body);
38975
39548
  const attachmentId = readString(attachment.id);
38976
- const actualSha256 = createHash19("sha256").update(body).digest("hex");
39549
+ const actualSha256 = createHash20("sha256").update(body).digest("hex");
38977
39550
  const lineageCandidates = lineageCandidatesByAttachmentId.get(attachmentId) ?? [];
38978
39551
  const lineage = selectAttachmentLineage(lineageCandidates, actualSha256);
38979
39552
  if (lineageCandidates.length > 0 && !lineage) {
@@ -39038,7 +39611,7 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39038
39611
  if (manifest.version !== 1 || !Array.isArray(manifest.entries)) {
39039
39612
  throw new Error("artifact_input_manifest_invalid: expected version 1 entries array");
39040
39613
  }
39041
- const targetRoot = join24(workspace.cwd, "input-artifacts");
39614
+ const targetRoot = join25(workspace.cwd, "input-artifacts");
39042
39615
  rmSync12(targetRoot, { recursive: true, force: true });
39043
39616
  mkdirSync13(targetRoot, { recursive: true });
39044
39617
  const usedPaths = /* @__PURE__ */ new Set();
@@ -39058,7 +39631,7 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39058
39631
  throw new Error(`artifact_input_manifest_invalid: entry ${index} contentPath does not match attachmentId`);
39059
39632
  }
39060
39633
  const body = await runtimeApiBuffer(runtimeAuth, contentPath);
39061
- const actualSha256 = createHash19("sha256").update(body).digest("hex");
39634
+ const actualSha256 = createHash20("sha256").update(body).digest("hex");
39062
39635
  if (body.byteLength !== byteSize || actualSha256 !== sha2563) {
39063
39636
  throw new Error(
39064
39637
  `artifact_input_integrity_mismatch: workProductId=${workProductId} expectedBytes=${byteSize} actualBytes=${body.byteLength} expectedSha256=${sha2563} actualSha256=${actualSha256}`
@@ -39069,15 +39642,15 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39069
39642
  id: attachmentId,
39070
39643
  originalFilename: readString(entry.originalFilename)
39071
39644
  }, index);
39072
- let relativePath = join24("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39645
+ let relativePath = join25("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39073
39646
  if (usedPaths.has(relativePath)) {
39074
39647
  const ext = extname3(filename);
39075
39648
  const stem = ext ? filename.slice(0, -ext.length) : filename;
39076
39649
  filename = `${stem}-${index + 1}${ext}`;
39077
- relativePath = join24("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39650
+ relativePath = join25("input-artifacts", sourceDir, filename).split(/[\\/]+/).join("/");
39078
39651
  }
39079
39652
  usedPaths.add(relativePath);
39080
- const targetPath = join24(workspace.cwd, relativePath);
39653
+ const targetPath = join25(workspace.cwd, relativePath);
39081
39654
  mkdirSync13(dirname12(targetPath), { recursive: true });
39082
39655
  writeFileSync14(targetPath, body);
39083
39656
  chmodSync8(targetPath, 292);
@@ -39099,7 +39672,7 @@ async function materializeRequiredArtifactInputs(config, command, workspace) {
39099
39672
  version: 1,
39100
39673
  entries: materialized.map(({ path: _path, relativePath, ...entry }) => ({ ...entry, path: relativePath }))
39101
39674
  };
39102
- const manifestPath = join24(targetRoot, "artifact-input-manifest.json");
39675
+ const manifestPath = join25(targetRoot, "artifact-input-manifest.json");
39103
39676
  writeFileSync14(manifestPath, JSON.stringify(localManifest, null, 2) + "\n");
39104
39677
  chmodSync8(manifestPath, 292);
39105
39678
  updateWorkspaceManifest(workspaceManifestPath(workspace), { artifactInputManifest: localManifest });
@@ -39112,7 +39685,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39112
39685
  const runtimeAuth = commandRuntimeAuth(command);
39113
39686
  const files = Array.isArray(mention.files) ? mention.files : [];
39114
39687
  if (files.length === 0 || !readString(runtimeAuth.apiUrl) || !readString(runtimeAuth.apiKey)) return empty;
39115
- const targetDir = join24(workspace.cwd, "input-artifacts", "mentioned");
39688
+ const targetDir = join25(workspace.cwd, "input-artifacts", "mentioned");
39116
39689
  rmSync12(targetDir, { recursive: true, force: true });
39117
39690
  mkdirSync13(targetDir, { recursive: true });
39118
39691
  const usedFilenames = /* @__PURE__ */ new Set();
@@ -39137,7 +39710,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39137
39710
  });
39138
39711
  continue;
39139
39712
  }
39140
- const actualSha256 = createHash19("sha256").update(body).digest("hex");
39713
+ const actualSha256 = createHash20("sha256").update(body).digest("hex");
39141
39714
  const expectedSha256 = readString(entry.sha256)?.toLowerCase() ?? null;
39142
39715
  const expectedByteSize = readNumber(entry.byteSize, null);
39143
39716
  if (expectedByteSize !== null && body.byteLength !== expectedByteSize || expectedSha256 && actualSha256 !== expectedSha256) {
@@ -39158,7 +39731,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39158
39731
  }, index);
39159
39732
  filename = dedupeMaterializedFilename(filename, index, usedFilenames);
39160
39733
  usedFilenames.add(filename);
39161
- const targetPath = join24(targetDir, filename);
39734
+ const targetPath = join25(targetDir, filename);
39162
39735
  writeFileSync14(targetPath, body);
39163
39736
  chmodSync8(targetPath, 292);
39164
39737
  materialized.push({
@@ -39176,7 +39749,7 @@ async function materializeMentionedArtifactFiles(config, command, workspace) {
39176
39749
  return { materialized, skipped };
39177
39750
  }
39178
39751
  function issueCheckpointDir(workspace) {
39179
- return join24(dirname12(workspace.runDir), "checkpoint");
39752
+ return join25(dirname12(workspace.runDir), "checkpoint");
39180
39753
  }
39181
39754
  async function clearIssueCheckpoint(config, command, workspace, reason, consumedSource = null) {
39182
39755
  const checkpointDir = issueCheckpointDir(workspace);
@@ -39186,7 +39759,7 @@ async function clearIssueCheckpoint(config, command, workspace, reason, consumed
39186
39759
  if (!sourceRunId) return false;
39187
39760
  let manifest;
39188
39761
  try {
39189
- manifest = asRecord(JSON.parse(readFileSync19(join24(checkpointDir, "manifest.json"), "utf8")));
39762
+ manifest = asRecord(JSON.parse(readFileSync20(join25(checkpointDir, "manifest.json"), "utf8")));
39190
39763
  } catch {
39191
39764
  return false;
39192
39765
  }
@@ -39205,7 +39778,7 @@ function safeCheckpointRelativePath(rawPath) {
39205
39778
  return normalized;
39206
39779
  }
39207
39780
  function hashFileSha256(filePath) {
39208
- return createHash19("sha256").update(readFileSync19(filePath)).digest("hex");
39781
+ return createHash20("sha256").update(readFileSync20(filePath)).digest("hex");
39209
39782
  }
39210
39783
  function expectedContinuationCheckpoint(command) {
39211
39784
  const payload = asRecord(command.payload);
@@ -39231,7 +39804,7 @@ function expectedContinuationCheckpoint(command) {
39231
39804
  }
39232
39805
  async function materializeIssueCheckpoint(config, command, workspace) {
39233
39806
  const checkpointDir = issueCheckpointDir(workspace);
39234
- const manifestPath = join24(checkpointDir, "manifest.json");
39807
+ const manifestPath = join25(checkpointDir, "manifest.json");
39235
39808
  const expectedContinuation = expectedContinuationCheckpoint(command);
39236
39809
  const nativeRequest = asRecord(asRecord(command.payload).nativeSession);
39237
39810
  let portableNativeSession;
@@ -39261,7 +39834,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39261
39834
  }
39262
39835
  let manifest;
39263
39836
  try {
39264
- manifest = asRecord(JSON.parse(readFileSync19(manifestPath, "utf8")));
39837
+ manifest = asRecord(JSON.parse(readFileSync20(manifestPath, "utf8")));
39265
39838
  } catch (err) {
39266
39839
  rmSync12(checkpointDir, { recursive: true, force: true });
39267
39840
  throw new Error(`invalid issue checkpoint manifest: ${err instanceof Error ? err.message : String(err)}`);
@@ -39292,7 +39865,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39292
39865
  throw new Error("continuation_checkpoint_lineage_mismatch");
39293
39866
  }
39294
39867
  }
39295
- const filesRoot = files.length > 0 ? realpathSync12(join24(checkpointDir, "files")) : null;
39868
+ const filesRoot = files.length > 0 ? realpathSync12(join25(checkpointDir, "files")) : null;
39296
39869
  const workspaceRoot = realpathSync12(workspace.cwd);
39297
39870
  const validated = [];
39298
39871
  let totalBytes = 0;
@@ -39337,7 +39910,7 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39337
39910
  }
39338
39911
  let existingTarget = null;
39339
39912
  try {
39340
- existingTarget = lstatSync13(target);
39913
+ existingTarget = lstatSync15(target);
39341
39914
  } catch (err) {
39342
39915
  if (err?.code !== "ENOENT") throw err;
39343
39916
  }
@@ -39348,10 +39921,10 @@ async function materializeIssueCheckpoint(config, command, workspace) {
39348
39921
  materialized.push(relativePath);
39349
39922
  continue;
39350
39923
  }
39351
- const temporaryTarget = join24(targetParent, `.${basename8(target)}.checkpoint-${randomUUID2()}.tmp`);
39924
+ const temporaryTarget = join25(targetParent, `.${basename8(target)}.checkpoint-${randomUUID2()}.tmp`);
39352
39925
  try {
39353
39926
  copyFileSync2(source, temporaryTarget);
39354
- const temporaryStat = lstatSync13(temporaryTarget);
39927
+ const temporaryStat = lstatSync15(temporaryTarget);
39355
39928
  if (!temporaryStat.isFile() || temporaryStat.size !== expectedByteSize || hashFileSha256(temporaryTarget) !== expectedSha256) {
39356
39929
  throw new Error(`issue checkpoint target verification failed: ${relativePath}`);
39357
39930
  }
@@ -39384,7 +39957,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39384
39957
  const commandKey = readString(command.commandId)?.replace(/[^A-Za-z0-9_-]/g, "-") ?? randomUUID2();
39385
39958
  const stagingDir = `${checkpointDir}.tmp-${commandKey}`;
39386
39959
  const backupDir = `${checkpointDir}.previous-${commandKey}`;
39387
- const filesDir = join24(stagingDir, "files");
39960
+ const filesDir = join25(stagingDir, "files");
39388
39961
  rmSync12(stagingDir, { recursive: true, force: true });
39389
39962
  rmSync12(backupDir, { recursive: true, force: true });
39390
39963
  mkdirSync13(filesDir, { recursive: true });
@@ -39404,7 +39977,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39404
39977
  }
39405
39978
  let sourceStat;
39406
39979
  try {
39407
- sourceStat = lstatSync13(sourceCandidate);
39980
+ sourceStat = lstatSync15(sourceCandidate);
39408
39981
  } catch (err) {
39409
39982
  if (err?.code === "ENOENT") {
39410
39983
  throw new Error(`continuation_checkpoint_file_unavailable: ${requiredPath}`);
@@ -39440,7 +40013,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39440
40013
  if (!pathWithin3(target, filesDir)) continue;
39441
40014
  mkdirSync13(dirname12(target), { recursive: true });
39442
40015
  copyFileSync2(ownedSource, target);
39443
- const storedStat = lstatSync13(target);
40016
+ const storedStat = lstatSync15(target);
39444
40017
  if (!storedStat.isFile() || storedStat.size !== byteSize) {
39445
40018
  throw new Error(`issue checkpoint copy verification failed: ${relativePath}`);
39446
40019
  }
@@ -39474,7 +40047,7 @@ async function saveIssueCheckpoint(config, command, workspace, candidates, optio
39474
40047
  totalBytes,
39475
40048
  files
39476
40049
  };
39477
- writeFileSync14(join24(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
40050
+ writeFileSync14(join25(stagingDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
39478
40051
  `);
39479
40052
  const replacingExistingCheckpoint = existsSync18(checkpointDir);
39480
40053
  if (replacingExistingCheckpoint) renameSync11(checkpointDir, backupDir);
@@ -39529,6 +40102,28 @@ function piOutputValidationError(parsed, options = {}) {
39529
40102
  }
39530
40103
  return null;
39531
40104
  }
40105
+ function executionTiming(scope, command) {
40106
+ if (process.env.MIRRORX_EXECUTION_TIMING_ENABLED !== "true") return () => {
40107
+ };
40108
+ const started = performance.now();
40109
+ let previous = started;
40110
+ return (phase) => {
40111
+ const now = performance.now();
40112
+ process.stderr.write(`${JSON.stringify({ executionTiming: {
40113
+ version: 1,
40114
+ scope,
40115
+ commandId: command.commandId,
40116
+ issueId: commandIssueId(command),
40117
+ runId: commandRunId(command),
40118
+ phase,
40119
+ at: (/* @__PURE__ */ new Date()).toISOString(),
40120
+ elapsedMs: Number((now - started).toFixed(3)),
40121
+ segmentMs: Number((now - previous).toFixed(3))
40122
+ } })}
40123
+ `);
40124
+ previous = now;
40125
+ };
40126
+ }
39532
40127
  async function ackCommand(config, command, phase = "preparing") {
39533
40128
  const connectorId = requireConnectorId(config);
39534
40129
  return await postJsonWithRetry(config, `/api/amaster/runtime-connectors/${connectorId}/commands/${command.commandId}/ack`, {
@@ -39538,6 +40133,8 @@ async function ackCommand(config, command, phase = "preparing") {
39538
40133
  });
39539
40134
  }
39540
40135
  async function executeRunCommand(config, command) {
40136
+ const timing = executionTiming("runner.execution", command);
40137
+ timing("prepare_started");
39541
40138
  const preparationStartedAtMs = Date.now();
39542
40139
  let preparationLogChain = Promise.resolve();
39543
40140
  const enqueuePreparationLog = (stream, level, message, payload = {}) => {
@@ -39658,6 +40255,7 @@ async function executeRunCommand(config, command) {
39658
40255
  const browserSession = commandBrowserSession(command);
39659
40256
  const browserCredentialPresentationKind = browserCredentialPresentation(command);
39660
40257
  const browserCredentialPlan = browserCredentialEnvPlan(command, browserCredentialPresentationKind);
40258
+ const browserCredentialAuthority = browserCredentialPrivateAuthority(command, browserCredentialPresentationKind);
39661
40259
  if (browserCredentialPlan && executor.kind !== "pi") {
39662
40260
  throw new Error("browser_credential_env_pi_executor_required");
39663
40261
  }
@@ -39667,6 +40265,13 @@ async function executeRunCommand(config, command) {
39667
40265
  const nativeSessionRequest = asRecord(asRecord(command.payload).nativeSession);
39668
40266
  let invocation = null;
39669
40267
  let executorEnv = buildExecutorEnv(config, command, workspace);
40268
+ delete executorEnv[BROWSER_CREDENTIAL_AUTHORITY_ENV];
40269
+ if (browserCredentialAuthority) {
40270
+ executorEnv = {
40271
+ ...executorEnv,
40272
+ [BROWSER_CREDENTIAL_AUTHORITY_ENV]: JSON.stringify(browserCredentialAuthority)
40273
+ };
40274
+ }
39670
40275
  let managedMcpProfile = null;
39671
40276
  let managedMcpCleanup = null;
39672
40277
  let cleanupManagedMcpProfile = null;
@@ -39786,7 +40391,7 @@ async function executeRunCommand(config, command) {
39786
40391
  executorCommand: invocation.command,
39787
40392
  executorHome: workspace.executorHome,
39788
40393
  runDir: workspace.runDir,
39789
- runtimeCacheRoot: join24(dirname12(config.daemonStateFile), "cache"),
40394
+ runtimeCacheRoot: join25(dirname12(config.daemonStateFile), "cache"),
39790
40395
  cwd,
39791
40396
  runtimeAuth: commandRuntimeAuth(command),
39792
40397
  nativeSession: asRecord(asRecord(executionCommand.payload).nativeSession),
@@ -40049,7 +40654,9 @@ async function executeRunCommand(config, command) {
40049
40654
  runId: commandRunId(command),
40050
40655
  executorKind: executor.kind
40051
40656
  });
40657
+ timing("before_spawn_ack");
40052
40658
  await ackCommand(config, command, "spawned");
40659
+ timing("spawn_acknowledged");
40053
40660
  enqueuePreparationLog("system", "info", `Starting ${executor.kind} executor`, {
40054
40661
  executorKind: executor.kind,
40055
40662
  cwd,
@@ -40058,6 +40665,7 @@ async function executeRunCommand(config, command) {
40058
40665
  preparationStages
40059
40666
  });
40060
40667
  await preparationLogChain;
40668
+ timing("preparation_logs_delivered");
40061
40669
  const abortController = new AbortController();
40062
40670
  if (browserCredentialPlan) {
40063
40671
  browserCredentialEnvMaterialization = await runExecutionStage(
@@ -40157,7 +40765,9 @@ async function executeRunCommand(config, command) {
40157
40765
  { signal: abortController.signal }
40158
40766
  );
40159
40767
  } : null;
40768
+ let firstOutput = false;
40160
40769
  try {
40770
+ timing("before_executor_spawn");
40161
40771
  execution = await runExecutor(invocation.command, invocation.args, {
40162
40772
  cwd: executor.kind === "codebuddy" ? managedMcpProfile?.cwd ?? cwd : cwd,
40163
40773
  env: executorEnv,
@@ -40170,6 +40780,10 @@ async function executeRunCommand(config, command) {
40170
40780
  ...piExecutorIdentity ? { spawnIdentity: piExecutorIdentity } : {},
40171
40781
  ...browserCredentialConsumer ? { browserCredentialConsumer } : {},
40172
40782
  onOutput: (stream, chunk, rawBytes) => {
40783
+ if (!firstOutput) {
40784
+ firstOutput = true;
40785
+ timing("first_executor_output");
40786
+ }
40173
40787
  noteActiveRunOutput(command, stream, chunk, rawBytes);
40174
40788
  return liveOutputLogger.write(stream, chunk);
40175
40789
  }
@@ -40762,7 +41376,10 @@ async function executeRunCommand(config, command) {
40762
41376
  }
40763
41377
  }
40764
41378
  async function processCommand(config, command) {
41379
+ const timing = executionTiming("runner.dispatch", command);
41380
+ timing("received");
40765
41381
  await ackCommand(config, command);
41382
+ timing("preparing_acknowledged");
40766
41383
  try {
40767
41384
  if (command.commandType === "browser_session") {
40768
41385
  const error = new Error("legacy_browser_session_command_retired");