openmeld 0.3.225 → 0.3.227
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.
- package/dist/{add-me-membership-BUuys3IZ.js → add-me-membership-pkREbEJG.js} +2 -2
- package/dist/{add-me-membership-BUuys3IZ.js.map → add-me-membership-pkREbEJG.js.map} +1 -1
- package/dist/{agents-Blvf8wC0.js → agents-D_RojMEE.js} +11 -11
- package/dist/{agents-Blvf8wC0.js.map → agents-D_RojMEE.js.map} +1 -1
- package/dist/{api-client-foundation-CqbIn_de.js → api-client-foundation-CEScBsM7.js} +1 -1
- package/dist/{api-client-foundation-DpVwrgh-.js → api-client-foundation-Czb9hJvA.js} +3 -3
- package/dist/{api-client-foundation-DpVwrgh-.js.map → api-client-foundation-Czb9hJvA.js.map} +1 -1
- package/dist/{auth-session-uEk_Tx6T.js → auth-session-Q0B3Nfae.js} +5 -4
- package/dist/{auth-session-uEk_Tx6T.js.map → auth-session-Q0B3Nfae.js.map} +1 -1
- package/dist/auth-session-ga82_Wa9.js +4 -0
- package/dist/{base-url-DXrUiSMI.js → base-url-B8eWb2md.js} +1 -1
- package/dist/{base-url-DvjOkKPs.js → base-url-eck31vC8.js} +3 -2
- package/dist/{base-url-DvjOkKPs.js.map → base-url-eck31vC8.js.map} +1 -1
- package/dist/{channel-B2fD2_be.js → channel-B1gMWx__.js} +3 -3
- package/dist/{channel-B2fD2_be.js.map → channel-B1gMWx__.js.map} +1 -1
- package/dist/{cli-binary-manifest-CT5X05lk.js → cli-binary-manifest-Bjf6T7Ef.js} +2 -2
- package/dist/{cli-binary-manifest-CT5X05lk.js.map → cli-binary-manifest-Bjf6T7Ef.js.map} +1 -1
- package/dist/{command-Cjxx-f4g.js → command-B5E_YSAY.js} +18 -17
- package/dist/{command-Cjxx-f4g.js.map → command-B5E_YSAY.js.map} +1 -1
- package/dist/{computer-connection-Dm7iTnRK.js → computer-connection-BbDdF_MD.js} +2 -2
- package/dist/{computer-connection-Dm7iTnRK.js.map → computer-connection-BbDdF_MD.js.map} +1 -1
- package/dist/{computer-connection-review-De0X_5c4.js → computer-connection-review-Dop02mby.js} +6 -6
- package/dist/{computer-connection-review-De0X_5c4.js.map → computer-connection-review-Dop02mby.js.map} +1 -1
- package/dist/{computer-disconnect-CvBzCJF9.js → computer-disconnect-pH6HaHQq.js} +9 -9
- package/dist/{computer-disconnect-CvBzCJF9.js.map → computer-disconnect-pH6HaHQq.js.map} +1 -1
- package/dist/{computer-setup-continuation-CaUPhhdb.js → computer-setup-continuation-BhM3HsRI.js} +3 -3
- package/dist/{computer-setup-continuation-CaUPhhdb.js.map → computer-setup-continuation-BhM3HsRI.js.map} +1 -1
- package/dist/{context-Bdh3nAzw.js → context-D3kAC8RG.js} +5 -5
- package/dist/{context-Bdh3nAzw.js.map → context-D3kAC8RG.js.map} +1 -1
- package/dist/{daemon-device-id-B1Af2Zmn.js → daemon-device-id-DEGf1fm6.js} +7 -6
- package/dist/{daemon-device-id-B1Af2Zmn.js.map → daemon-device-id-DEGf1fm6.js.map} +1 -1
- package/dist/{daemon-frame-transport-CSvV88PL.js → daemon-frame-transport-BMZP90f0.js} +10 -9
- package/dist/{daemon-frame-transport-CSvV88PL.js.map → daemon-frame-transport-BMZP90f0.js.map} +1 -1
- package/dist/{daemon-lifecycle-journal-ChhAF8yX.js → daemon-lifecycle-journal-NeBAn_SY.js} +27 -12
- package/dist/daemon-lifecycle-journal-NeBAn_SY.js.map +1 -0
- package/dist/{daemon-runtime-lease-1LMeZ6IS.js → daemon-runtime-lease-C1wkT4Bi.js} +2 -2
- package/dist/{daemon-runtime-lease-1LMeZ6IS.js.map → daemon-runtime-lease-C1wkT4Bi.js.map} +1 -1
- package/dist/{daemon-runtime-lease-Bz0ucJj3.js → daemon-runtime-lease-DAQyRUc5.js} +1 -1
- package/dist/{daemon-service-contract-GLmAxsq-.js → daemon-service-contract-DhEfbzHt.js} +4 -4
- package/dist/{daemon-service-contract-GLmAxsq-.js.map → daemon-service-contract-DhEfbzHt.js.map} +1 -1
- package/dist/{daemon-service-manager-C8RUCMDo.js → daemon-service-manager-CRnFxPKA.js} +6 -5
- package/dist/{daemon-service-manager-C8RUCMDo.js.map → daemon-service-manager-CRnFxPKA.js.map} +1 -1
- package/dist/{daemon-service-manager-CU-79a4z.js → daemon-service-manager-l0unaDGa.js} +1 -1
- package/dist/{daemon-service-runtime-BtqJMt8J.js → daemon-service-runtime-nIBQreis.js} +27 -153
- package/dist/daemon-service-runtime-nIBQreis.js.map +1 -0
- package/dist/{daemon-service-update-coordinator-BczvSdXA.js → daemon-service-update-coordinator-BdcEl-QC.js} +22 -20
- package/dist/daemon-service-update-coordinator-BdcEl-QC.js.map +1 -0
- package/dist/{daemon-state-Ca0WK5x0.js → daemon-state-B6G5xe7f.js} +4 -3
- package/dist/{daemon-state-Ca0WK5x0.js.map → daemon-state-B6G5xe7f.js.map} +1 -1
- package/dist/{dist-C32frPV2.js → dist-C5emSnFG.js} +1 -1
- package/dist/{dist-BeJcIdCZ.js → dist-DkN9tKMX.js} +127 -284
- package/dist/dist-DkN9tKMX.js.map +1 -0
- package/dist/{dist-YbTZ-Y-2.js → dist-vpxgF6Lp.js} +2 -2
- package/dist/{dist-YbTZ-Y-2.js.map → dist-vpxgF6Lp.js.map} +1 -1
- package/dist/{elapsed-time-Dvn2LxSm.js → elapsed-time-BxMWSsxC.js} +5 -5
- package/dist/{elapsed-time-Dvn2LxSm.js.map → elapsed-time-BxMWSsxC.js.map} +1 -1
- package/dist/{entry-B19Dcymp.js → entry-jvTvDBr-.js} +12 -11
- package/dist/{entry-B19Dcymp.js.map → entry-jvTvDBr-.js.map} +1 -1
- package/dist/{installation-inventory-BmZVMUzJ.js → installation-inventory-Bf1SvGVh.js} +5 -5
- package/dist/{installation-inventory-BmZVMUzJ.js.map → installation-inventory-Bf1SvGVh.js.map} +1 -1
- package/dist/{installer-DAZpeNXo.js → installer-IVAr1ZD-.js} +2 -2
- package/dist/{installer-DAZpeNXo.js.map → installer-IVAr1ZD-.js.map} +1 -1
- package/dist/{lock-iue1J2xy.js → lock-CMH9eoS7.js} +5 -270
- package/dist/lock-CMH9eoS7.js.map +1 -0
- package/dist/{meta-api-eV9exiaO.js → meta-api-BYB9vhya.js} +8 -8
- package/dist/{meta-api-eV9exiaO.js.map → meta-api-BYB9vhya.js.map} +1 -1
- package/dist/{openmeld-DEbL_TIZ.js → openmeld-0pnb6g3R.js} +63 -38
- package/dist/{openmeld-DEbL_TIZ.js.map → openmeld-0pnb6g3R.js.map} +1 -1
- package/dist/openmeld-dev.js +1 -1
- package/dist/{openmeld-environment-target-BBn5Ko6p.js → openmeld-environment-target-Cw3V0WnE.js} +3 -3
- package/dist/{openmeld-environment-target-BBn5Ko6p.js.map → openmeld-environment-target-Cw3V0WnE.js.map} +1 -1
- package/dist/{openmeld-maintenance-worker-Ds8LpQ1c.js → openmeld-maintenance-worker-CSes51Vp.js} +14 -14
- package/dist/{openmeld-maintenance-worker-Ds8LpQ1c.js.map → openmeld-maintenance-worker-CSes51Vp.js.map} +1 -1
- package/dist/{openmeld-tools-update-join-DV_THLes.js → openmeld-tools-update-join-BlPynw_v.js} +4 -4
- package/dist/{openmeld-tools-update-join-DV_THLes.js.map → openmeld-tools-update-join-BlPynw_v.js.map} +1 -1
- package/dist/openmeld.js +8 -4
- package/dist/openmeld.js.map +1 -1
- package/dist/paths-DSkUuEu3.js +273 -0
- package/dist/paths-DSkUuEu3.js.map +1 -0
- package/dist/{prepare-provider-runtime-CP88BnLy.js → prepare-provider-runtime-DSKQFj-R.js} +94 -28
- package/dist/prepare-provider-runtime-DSKQFj-R.js.map +1 -0
- package/dist/{prepare-session-executor-Dt5hHfsR.js → prepare-session-executor-DEJ9OaJh.js} +25 -24
- package/dist/{prepare-session-executor-Dt5hHfsR.js.map → prepare-session-executor-DEJ9OaJh.js.map} +1 -1
- package/dist/{process-channel-CgbduFCz.js → process-channel-BIumgluJ.js} +2 -2
- package/dist/{process-channel-CgbduFCz.js.map → process-channel-BIumgluJ.js.map} +1 -1
- package/dist/{process-identity-BQLdaZdB.js → process-identity-BRbhGGTM.js} +2 -2
- package/dist/{process-identity-BQLdaZdB.js.map → process-identity-BRbhGGTM.js.map} +1 -1
- package/dist/{published-production-safety-C40hKrBA.js → published-production-safety-CgXxtdMK.js} +2 -2
- package/dist/{published-production-safety-C40hKrBA.js.map → published-production-safety-CgXxtdMK.js.map} +1 -1
- package/dist/{runtime-4_VPSImW.js → runtime-Du3Az4wt.js} +18 -18
- package/dist/{runtime-4_VPSImW.js.map → runtime-Du3Az4wt.js.map} +1 -1
- package/dist/{runtime-agent-controller-reporting-submission-OpySJXCT.js → runtime-agent-controller-reporting-submission-Bl2CWQ96.js} +12 -10
- package/dist/runtime-agent-controller-reporting-submission-Bl2CWQ96.js.map +1 -0
- package/dist/{runtime-reporting-health-state-B14XCJQF.js → runtime-reporting-health-state-CKmph14R.js} +14 -13
- package/dist/{runtime-reporting-health-state-B14XCJQF.js.map → runtime-reporting-health-state-CKmph14R.js.map} +1 -1
- package/dist/{runtime-transport-YIYHSJPn.js → runtime-transport-DUR91mKK.js} +205 -5
- package/dist/runtime-transport-DUR91mKK.js.map +1 -0
- package/dist/{service-v9KNVG7t.js → service-Bh1iD84k.js} +30 -29
- package/dist/service-Bh1iD84k.js.map +1 -0
- package/dist/{service-account-authorization-DZbUOD29.js → service-account-authorization-CyV8YFAw.js} +6 -6
- package/dist/{service-account-authorization-DZbUOD29.js.map → service-account-authorization-CyV8YFAw.js.map} +1 -1
- package/dist/{service-account-control-DguBlRfW.js → service-account-control-Cc6qVa0m.js} +14 -14
- package/dist/{service-account-control-DguBlRfW.js.map → service-account-control-Cc6qVa0m.js.map} +1 -1
- package/dist/{service-control-capabilities-fFuX3GbE.js → service-control-capabilities-CdVTTNRK.js} +1 -1
- package/dist/{service-control-capabilities-CQb9zWvz.js → service-control-capabilities-D4W3WTHS.js} +5 -5
- package/dist/{service-control-capabilities-CQb9zWvz.js.map → service-control-capabilities-D4W3WTHS.js.map} +1 -1
- package/dist/{service-control-carrier-capability-gMk5gMKU.js → service-control-carrier-capability-SuKbNKaR.js} +2 -2
- package/dist/{service-control-carrier-capability-gMk5gMKU.js.map → service-control-carrier-capability-SuKbNKaR.js.map} +1 -1
- package/dist/{state-B7JOni3p.js → state-ClTXLNB3.js} +3 -3
- package/dist/{state-B7JOni3p.js.map → state-ClTXLNB3.js.map} +1 -1
- package/dist/{upgrade-DnWyXA1G.js → upgrade-B07Dh83M.js} +8 -8
- package/dist/{upgrade-DnWyXA1G.js.map → upgrade-B07Dh83M.js.map} +1 -1
- package/dist/upgrade-DgTfV7-m.js +4 -0
- package/dist/windows/openmeld-windows-process.exe +0 -0
- package/dist/{windows-artifact-DJ9DKjfc.js → windows-artifact-D99JU1ll.js} +3 -2
- package/dist/{windows-artifact-DJ9DKjfc.js.map → windows-artifact-D99JU1ll.js.map} +1 -1
- package/dist/windows-managed-install-BVlswqjA.js +146 -0
- package/dist/windows-managed-install-BVlswqjA.js.map +1 -0
- package/dist/windows-preview-channel-DPrYuLyY.js +32 -0
- package/dist/windows-preview-channel-DPrYuLyY.js.map +1 -0
- package/dist/{windows-user-task-Io5QuEVR.js → windows-user-task-BR-WB7hr.js} +5 -5
- package/dist/{windows-user-task-Io5QuEVR.js.map → windows-user-task-BR-WB7hr.js.map} +1 -1
- package/dist/{windows-user-task-B8NcRg_u.js → windows-user-task-m9eMEUEq.js} +1 -1
- package/package.json +11 -11
- package/skills/openmeld-cli/playbooks/plugins.md +12 -0
- package/dist/auth-session-BJfKu74u.js +0 -4
- package/dist/daemon-lifecycle-journal-ChhAF8yX.js.map +0 -1
- package/dist/daemon-service-runtime-BtqJMt8J.js.map +0 -1
- package/dist/daemon-service-update-coordinator-BczvSdXA.js.map +0 -1
- package/dist/dist-BeJcIdCZ.js.map +0 -1
- package/dist/lock-iue1J2xy.js.map +0 -1
- package/dist/prepare-provider-runtime-CP88BnLy.js.map +0 -1
- package/dist/runtime-agent-controller-reporting-submission-OpySJXCT.js.map +0 -1
- package/dist/runtime-transport-YIYHSJPn.js.map +0 -1
- package/dist/service-v9KNVG7t.js.map +0 -1
- package/dist/upgrade-Cy4bMox8.js +0 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lock-CMH9eoS7.js","names":["resolveLocksDir","process","resolveRuntimeDir"],"sources":["../../../packages/schemas/dist/schemas/local-machine/recovery.js","../src/system/local-machine-recovery/index.ts","../src/config/openmeld-lane-descriptor.ts","../src/config/session-profile.ts","../src/config/lock.ts"],"sourcesContent":["import * as z$1 from \"zod/v4\";\n//#region src/schemas/local-machine/recovery.ts\nconst LOCAL_MACHINE_RECOVERY_SCHEMA_VERSION = 1;\nconst localMachineIssueCodeSchema = z$1.enum([\n\t\"local_machine.storage.exhausted\",\n\t\"local_machine.storage.not_writable\",\n\t\"local_machine.permission.denied\",\n\t\"local_machine.resources.exhausted\",\n\t\"local_machine.background_execution.blocked\",\n\t\"local_machine.concurrency.active\",\n\t\"local_machine.concurrency.orphaned\",\n\t\"local_machine.failure.unknown\"\n]);\nconst localMachineOperationSchema = z$1.enum([\n\t\"create_lock\",\n\t\"read_local_state\",\n\t\"write_local_state\",\n\t\"start_background_service\",\n\t\"start_process\",\n\t\"unknown\"\n]);\nconst localMachineRecoveryPolicySchema = z$1.enum([\n\t\"automatic\",\n\t\"retry_with_backoff\",\n\t\"user_action\",\n\t\"diagnostics\"\n]);\nconst LOCAL_MACHINE_RECOVERY_POLICY_BY_CODE = {\n\t\"local_machine.storage.exhausted\": \"user_action\",\n\t\"local_machine.storage.not_writable\": \"user_action\",\n\t\"local_machine.permission.denied\": \"user_action\",\n\t\"local_machine.resources.exhausted\": \"user_action\",\n\t\"local_machine.background_execution.blocked\": \"user_action\",\n\t\"local_machine.concurrency.active\": \"user_action\",\n\t\"local_machine.concurrency.orphaned\": \"user_action\",\n\t\"local_machine.failure.unknown\": \"diagnostics\"\n};\nfunction resolveLocalMachineRecoveryPolicy(code) {\n\tif (!Object.hasOwn(LOCAL_MACHINE_RECOVERY_POLICY_BY_CODE, code)) return null;\n\treturn LOCAL_MACHINE_RECOVERY_POLICY_BY_CODE[code];\n}\nconst localMachineUserMessageSchema = z$1.string().trim().min(1).max(512);\nconst localMachineDiagnosticTextSchema = z$1.string().trim().min(1).max(2048);\nconst localMachineAgentMessageSchema = z$1.string().trim().min(1).max(1025);\nfunction formatLocalMachineIssueMessage(issue) {\n\treturn issue.primaryAction ? `${issue.summary} ${issue.primaryAction}` : issue.summary;\n}\nconst localMachineIssueSchema = z$1.strictObject({\n\tschemaVersion: z$1.literal(1),\n\tcode: localMachineIssueCodeSchema,\n\toperation: localMachineOperationSchema,\n\trecoveryPolicy: localMachineRecoveryPolicySchema,\n\tsummary: localMachineUserMessageSchema,\n\tprimaryAction: z$1.union([localMachineUserMessageSchema, z$1.null()]),\n\tdiagnostics: z$1.strictObject({\n\t\tsystemCode: z$1.union([z$1.string().trim().min(1).max(64), z$1.null()]),\n\t\tdetail: z$1.union([localMachineDiagnosticTextSchema, z$1.null()])\n\t})\n}).superRefine((value, context) => {\n\tconst expectedPolicy = resolveLocalMachineRecoveryPolicy(value.code);\n\tif (value.recoveryPolicy !== expectedPolicy) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: `recovery policy must be ${expectedPolicy} for ${value.code}`,\n\t\tpath: [\"recoveryPolicy\"]\n\t});\n});\nconst localMachineIssueAgentEventSchema = z$1.strictObject({\n\ttype: z$1.literal(\"error\"),\n\tcode: localMachineIssueCodeSchema,\n\tmessage: localMachineAgentMessageSchema,\n\trequestId: z$1.string().trim().min(1).max(256).optional(),\n\tpayload: z$1.strictObject({ localMachineIssue: localMachineIssueSchema })\n}).superRefine((value, context) => {\n\tif (value.code !== value.payload.localMachineIssue.code) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"agent event code must match local machine issue code\",\n\t\tpath: [\"code\"]\n\t});\n\tconst expectedMessage = formatLocalMachineIssueMessage(value.payload.localMachineIssue);\n\tif (value.message !== expectedMessage) context.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"agent event message must match local machine issue copy\",\n\t\tpath: [\"message\"]\n\t});\n});\n//#endregion\nexport { LOCAL_MACHINE_RECOVERY_POLICY_BY_CODE, LOCAL_MACHINE_RECOVERY_SCHEMA_VERSION, formatLocalMachineIssueMessage, localMachineIssueAgentEventSchema, localMachineIssueCodeSchema, localMachineIssueSchema, localMachineOperationSchema, localMachineRecoveryPolicySchema, resolveLocalMachineRecoveryPolicy };\n\n//# sourceMappingURL=recovery.js.map","import {\n formatLocalMachineIssueMessage,\n type LocalMachineIssue,\n type LocalMachineOperation,\n} from \"@openmeld/schemas\";\n\ntype LocalMachineFailureInput = {\n operation: LocalMachineOperation;\n error: unknown;\n};\n\nexport class LocalMachineFailureError extends Error {\n readonly code: LocalMachineIssue[\"code\"];\n readonly issue: LocalMachineIssue;\n\n constructor(input: { issue: LocalMachineIssue; cause?: unknown }) {\n super(formatLocalMachineIssueMessage(input.issue), {\n cause: input.cause,\n });\n this.name = \"LocalMachineFailureError\";\n this.code = input.issue.code;\n this.issue = input.issue;\n }\n}\n\nexport function isLocalMachineFailureError(\n error: unknown\n): error is LocalMachineFailureError {\n return error instanceof LocalMachineFailureError;\n}\n\nexport function toLocalMachineFailureError(\n input: LocalMachineFailureInput\n): LocalMachineFailureError {\n if (isLocalMachineFailureError(input.error)) {\n return input.error;\n }\n return new LocalMachineFailureError({\n issue: assessLocalMachineFailure(input),\n cause: input.error,\n });\n}\n\nexport function toRecognizedLocalMachineFailureError(\n input: LocalMachineFailureInput\n): LocalMachineFailureError | null {\n if (isLocalMachineFailureError(input.error)) {\n return input.error;\n }\n const issue = assessLocalMachineFailure(input);\n return issue.code === \"local_machine.failure.unknown\"\n ? null\n : new LocalMachineFailureError({\n issue,\n cause: input.error,\n });\n}\n\nexport function assessLocalMachineFailure(\n input: LocalMachineFailureInput\n): LocalMachineIssue {\n const systemCode = readSystemErrorCode(input.error);\n const detail = readErrorMessage(input.error);\n\n if (systemCode === \"ENOSPC\" || systemCode === \"EDQUOT\") {\n return {\n schemaVersion: 1,\n code: \"local_machine.storage.exhausted\",\n operation: input.operation,\n recoveryPolicy: \"user_action\",\n summary:\n \"Your computer is out of storage space. OpenMeld can't save the local files it needs.\",\n primaryAction: \"Free up storage, then try again.\",\n diagnostics: {\n systemCode,\n detail,\n },\n };\n }\n\n if (\n systemCode === \"EROFS\" ||\n ((input.operation === \"create_lock\" ||\n input.operation === \"write_local_state\") &&\n (systemCode === \"EACCES\" || systemCode === \"EPERM\"))\n ) {\n return {\n schemaVersion: 1,\n code: \"local_machine.storage.not_writable\",\n operation: input.operation,\n recoveryPolicy: \"user_action\",\n summary: \"OpenMeld can't write to its local data folder.\",\n primaryAction: \"Make sure the folder is writable, then try again.\",\n diagnostics: {\n systemCode,\n detail,\n },\n };\n }\n\n if (\n systemCode === \"EACCES\" ||\n systemCode === \"EPERM\" ||\n systemCode === \"EROFS\"\n ) {\n return {\n schemaVersion: 1,\n code: \"local_machine.permission.denied\",\n operation: input.operation,\n recoveryPolicy: \"user_action\",\n summary:\n \"OpenMeld doesn't have permission to complete local setup on this computer.\",\n primaryAction:\n \"Allow OpenMeld to access its local files and background services, then try again.\",\n diagnostics: {\n systemCode,\n detail,\n },\n };\n }\n\n if (\n systemCode === \"EMFILE\" ||\n systemCode === \"ENFILE\" ||\n systemCode === \"ENOMEM\"\n ) {\n return {\n schemaVersion: 1,\n code: \"local_machine.resources.exhausted\",\n operation: input.operation,\n recoveryPolicy: \"user_action\",\n summary:\n \"Your computer doesn't have enough available system resources for OpenMeld to continue.\",\n primaryAction: \"Restart your computer, then try again.\",\n diagnostics: {\n systemCode,\n detail,\n },\n };\n }\n\n return {\n schemaVersion: 1,\n code: \"local_machine.failure.unknown\",\n operation: input.operation,\n recoveryPolicy: \"diagnostics\",\n summary: \"OpenMeld couldn't complete a required action on this computer.\",\n primaryAction: \"Try again. If it still fails, open diagnostics.\",\n diagnostics: {\n systemCode,\n detail,\n },\n };\n}\n\nexport function createServiceSpawnPendingIssue(input: {\n detail?: string | null;\n}): LocalMachineIssue {\n return {\n schemaVersion: 1,\n code: \"local_machine.failure.unknown\",\n operation: \"start_background_service\",\n recoveryPolicy: \"diagnostics\",\n summary: \"macOS registered OpenMeld Service but hasn't started it.\",\n primaryAction:\n \"Run `openmeld service snapshot --view agent` to collect startup diagnostics.\",\n diagnostics: {\n systemCode: \"SERVICE_SPAWN_PENDING\",\n detail: input.detail?.trim().slice(0, 2048) || null,\n },\n };\n}\n\nexport function createActiveSetupConcurrencyIssue(input: {\n detail?: string | null;\n primaryAction: string;\n}): LocalMachineIssue {\n return {\n schemaVersion: 1,\n code: \"local_machine.concurrency.active\",\n operation: \"create_lock\",\n recoveryPolicy: \"user_action\",\n summary: \"Another OpenMeld setup is already running on this computer.\",\n primaryAction: input.primaryAction,\n diagnostics: {\n systemCode: \"OPENMELD_LOCK_ACTIVE\",\n detail: input.detail?.trim().slice(0, 2048) || null,\n },\n };\n}\n\nexport function createOrphanedSetupConcurrencyIssue(input: {\n detail?: string | null;\n primaryAction: string;\n}): LocalMachineIssue {\n return createOrphanedLocalConcurrencyIssue({\n ...input,\n summary: \"OpenMeld found a setup lock left by an older version.\",\n });\n}\n\nexport function createOrphanedLocalConcurrencyIssue(input: {\n detail?: string | null;\n primaryAction: string;\n summary: string;\n}): LocalMachineIssue {\n return {\n schemaVersion: 1,\n code: \"local_machine.concurrency.orphaned\",\n operation: \"create_lock\",\n recoveryPolicy: \"user_action\",\n summary: input.summary,\n primaryAction: input.primaryAction,\n diagnostics: {\n systemCode: \"OPENMELD_LOCK_ORPHANED\",\n detail: input.detail?.trim().slice(0, 2048) || null,\n },\n };\n}\n\nfunction readSystemErrorCode(error: unknown): string | null {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" && code.trim().length > 0 ? code : null;\n}\n\nfunction readErrorMessage(error: unknown): string | null {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message.trim().slice(0, 2048);\n }\n if (typeof error === \"string\" && error.trim().length > 0) {\n return error.trim().slice(0, 2048);\n }\n return null;\n}\n","import {\n type OpenMeldEnvPreset,\n resolveOpenMeldEnvPreset,\n resolveOpenMeldRootDir,\n} from \"./paths\";\n\nexport type OpenMeldLaneDescriptor = {\n command: \"openmeld\" | \"openmeld-dev\" | \"openmeld-canary\";\n preset: OpenMeldEnvPreset;\n openMeldHome: string;\n destructiveResetAllowed: boolean;\n repairCommand: string;\n removeCommand: string | null;\n resetCommand: string;\n};\n\nexport function resolveOpenMeldLaneDescriptor(input?: {\n env?: NodeJS.ProcessEnv;\n argv?: string[];\n homeDir?: string;\n}): OpenMeldLaneDescriptor {\n const env = input?.env ?? process.env;\n const preset = resolveOpenMeldEnvPreset({\n argv: input?.argv,\n env,\n homeDir: input?.homeDir,\n });\n const command = resolveLaneCommand(preset);\n return {\n command,\n preset,\n openMeldHome: resolveOpenMeldRootDir({\n argv: input?.argv,\n env,\n homeDir: input?.homeDir,\n }),\n destructiveResetAllowed: true,\n repairCommand: `${command} repair local-state`,\n removeCommand: preset === \"canary\" ? \"pnpm openmeld:canary:remove\" : null,\n resetCommand: `${command} reset --yes`,\n };\n}\n\nexport function formatLaneScopeSentence(\n lane: Pick<OpenMeldLaneDescriptor, \"openMeldHome\" | \"command\">\n): string {\n return `This only affects the ${lane.command} lane at ${lane.openMeldHome}.`;\n}\n\nexport function buildLaneScopedCleanupGuidance(\n lane: Pick<\n OpenMeldLaneDescriptor,\n \"command\" | \"repairCommand\" | \"removeCommand\"\n >\n): string {\n const commands = [`\\`${lane.repairCommand}\\``];\n if (lane.removeCommand) {\n commands.unshift(`\\`${lane.removeCommand}\\``);\n }\n return `Optional cleanup for this lane: run ${commands.join(\" or \")}.`;\n}\n\nfunction resolveLaneCommand(\n preset: OpenMeldEnvPreset\n): OpenMeldLaneDescriptor[\"command\"] {\n if (preset === \"dev-local\") {\n return \"openmeld-dev\";\n }\n if (preset === \"canary\") {\n return \"openmeld-canary\";\n }\n return \"openmeld\";\n}\n","import { createHash } from \"node:crypto\";\nimport { mkdir, open, readdir, readFile, rename, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n normalizeOpenMeldProfileId,\n type OpenMeldProfileId,\n sessionsDir,\n} from \"./paths\";\n\nexport const OPENMELD_CLI_CONTEXT_ENV_KEY = \"OPENMELD_CLI_CONTEXT_ID\";\nexport const LEGACY_OPENMELD_AGENT_SESSION_ENV_KEY =\n \"OPENMELD_AGENT_SESSION_ID\";\n\nexport const CLI_CONTEXT_ENV_KEYS = [\n OPENMELD_CLI_CONTEXT_ENV_KEY,\n LEGACY_OPENMELD_AGENT_SESSION_ENV_KEY,\n] as const;\n\nconst SESSION_FILE_MAX_LENGTH = 128;\nconst SESSION_FILE_HASH_LENGTH = 8;\n\nexport type CliContextResolution = {\n cliContextId: string;\n source: string;\n};\n\nexport type CliContextStateV1 = {\n v: 1;\n sessionId: string;\n updatedAt: string;\n cliContextSource?: string;\n openMeldProfileId?: string;\n selectedOpenMeldProfileId?: string;\n};\n\nexport function resolveCliContext(\n profileIdInput?: string\n): CliContextResolution | null {\n const explicit = normalizeSessionId(profileIdInput);\n if (explicit) {\n return {\n cliContextId: explicit,\n source: \"manual\",\n };\n }\n\n for (const key of CLI_CONTEXT_ENV_KEYS) {\n const sessionId = normalizeSessionId(process.env[key]);\n if (sessionId) {\n return {\n cliContextId: sessionId,\n source: `environment:${key}`,\n };\n }\n }\n\n return resolveTerminalSessionId();\n}\n\nexport function resolveCliContextId(profileIdInput?: string): string | null {\n return resolveCliContext(profileIdInput)?.cliContextId ?? null;\n}\n\nexport function buildSessionProfilePayload(\n session: CliContextResolution,\n openMeldProfileId: OpenMeldProfileId\n): CliContextStateV1 {\n return {\n v: 1,\n sessionId: session.cliContextId,\n cliContextSource: session.source,\n openMeldProfileId: normalizeOpenMeldProfileId(openMeldProfileId),\n updatedAt: new Date().toISOString(),\n };\n}\n\nexport function formatCliContextSource(source: string): string {\n if (source === \"manual\") {\n return \"manual\";\n }\n if (source.startsWith(\"environment:\")) {\n return `environment:${source.slice(\"environment:\".length)}`;\n }\n if (source.startsWith(\"terminal:\")) {\n return \"terminal-fingerprint\";\n }\n return source;\n}\n\nexport function normalizeCliContextResolution(\n value: unknown\n): CliContextResolution | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const maybe = value as {\n cliContextId?: unknown;\n source?: unknown;\n };\n const cliContextId = normalizeSessionId(maybe.cliContextId);\n const source = normalizeSessionSource(maybe.source);\n if (!(cliContextId && source)) {\n return null;\n }\n\n return { cliContextId, source };\n}\n\nfunction normalizeSessionSource(raw: unknown): string | null {\n const value = String(raw ?? \"\").trim();\n if (!value) {\n return null;\n }\n return value;\n}\n\nexport async function setSessionOpenMeldProfileId(\n openMeldProfileId: OpenMeldProfileId\n): Promise<boolean> {\n return await writeCliContextState({\n openMeldProfileId,\n });\n}\n\nexport async function getSessionOpenMeldProfileId(): Promise<OpenMeldProfileId | null> {\n return (await readCliContextState())?.openMeldProfileId ?? null;\n}\n\nexport async function clearSessionOpenMeldProfileId(): Promise<boolean> {\n return await writeCliContextState({\n openMeldProfileId: null,\n });\n}\n\nexport async function readCliContextState(input?: {\n sessionId?: string;\n}): Promise<CliContextStateV1 | null> {\n const cliContextId = resolveSessionStateId(input?.sessionId);\n if (!cliContextId) {\n return null;\n }\n\n const raw = await readFile(cliContextStatePath(cliContextId), \"utf8\").catch(\n () => null\n );\n if (!raw) {\n return null;\n }\n\n return parseCliContextState(raw);\n}\n\nexport async function listCliContextStates(): Promise<CliContextStateV1[]> {\n const entryNames = await readdir(sessionsDir()).catch(() => []);\n const states: CliContextStateV1[] = [];\n for (const entryName of entryNames) {\n if (!entryName.endsWith(\".json\")) {\n continue;\n }\n const raw = await readFile(join(sessionsDir(), entryName), \"utf8\").catch(\n () => null\n );\n if (!raw) {\n continue;\n }\n const parsed = parseCliContextState(raw);\n if (!parsed) {\n continue;\n }\n states.push(parsed);\n }\n return states.sort((left, right) =>\n left.sessionId.localeCompare(right.sessionId)\n );\n}\n\nexport async function writeCliContextState(input: {\n sessionId?: string;\n sessionSource?: string;\n openMeldProfileId?: string | null;\n selectedOpenMeldProfileId?: string | null;\n}): Promise<boolean> {\n const cliContext = resolveCliContextStateInput(input) ?? resolveCliContext();\n if (!cliContext) {\n return false;\n }\n\n await mkdir(sessionsDir(), { recursive: true });\n const existing = await readCliContextState({\n sessionId: cliContext.cliContextId,\n });\n const nextOpenMeldProfileId = resolveNextSessionOpenMeldProfileId(\n existing,\n input\n );\n const nextSelectedOpenMeldProfileId = resolveNextSelectedOpenMeldProfileId(\n existing,\n input\n );\n const outputPath = cliContextStatePath(cliContext.cliContextId);\n\n if (!(nextOpenMeldProfileId || nextSelectedOpenMeldProfileId)) {\n await rm(outputPath, { force: true });\n return true;\n }\n\n const payload: CliContextStateV1 = {\n v: 1,\n sessionId: cliContext.cliContextId,\n cliContextSource:\n cliContext.source ?? existing?.cliContextSource ?? \"manual\",\n ...(nextOpenMeldProfileId\n ? { openMeldProfileId: nextOpenMeldProfileId }\n : {}),\n ...(nextSelectedOpenMeldProfileId\n ? { selectedOpenMeldProfileId: nextSelectedOpenMeldProfileId }\n : {}),\n updatedAt: new Date().toISOString(),\n };\n\n await writeCliContextStateFile(outputPath, payload);\n return true;\n}\n\nexport function cliContextStatePath(sessionId: string): string {\n return join(sessionsDir(), `${toSafeSessionFile(sessionId)}.json`);\n}\n\nfunction toSafeSessionFile(value: string): string {\n const hash = createHash(\"sha1\")\n .update(value, \"utf8\")\n .digest(\"hex\")\n .slice(0, SESSION_FILE_HASH_LENGTH);\n const safeBaseRaw = value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n const safeBase = safeBaseRaw.length > 0 ? safeBaseRaw : \"session\";\n const maxBaseLength = Math.max(\n 1,\n SESSION_FILE_MAX_LENGTH - SESSION_FILE_HASH_LENGTH - 1\n );\n const truncatedBase = safeBase.slice(0, maxBaseLength);\n return `${truncatedBase}-${hash}`;\n}\n\nfunction resolveCliContextStateInput(input: {\n sessionId?: string;\n sessionSource?: string;\n}): CliContextResolution | null {\n const sessionId = normalizeSessionId(input.sessionId);\n if (!sessionId) {\n return null;\n }\n return {\n cliContextId: sessionId,\n source: normalizeSessionSource(input.sessionSource) ?? \"manual\",\n };\n}\n\nfunction resolveSessionStateId(sessionId?: string): string | null {\n const explicit = normalizeSessionId(sessionId);\n if (explicit) {\n return explicit;\n }\n return resolveCliContext()?.cliContextId ?? null;\n}\n\nfunction parseCliContextState(raw: string): CliContextStateV1 | null {\n let parsed: Partial<CliContextStateV1> & {\n profile?: unknown;\n };\n try {\n parsed = JSON.parse(raw) as Partial<CliContextStateV1> & {\n profile?: unknown;\n };\n } catch {\n return null;\n }\n\n if (parsed.v !== 1) {\n return null;\n }\n const sessionId = normalizeSessionId(parsed.sessionId);\n if (!sessionId) {\n return null;\n }\n const openMeldProfileId = resolveStoredSessionOpenMeldProfileId(parsed);\n const selectedOpenMeldProfileId =\n resolveStoredSelectedOpenMeldProfileId(parsed);\n if (!(openMeldProfileId || selectedOpenMeldProfileId)) {\n return null;\n }\n const cliContextSource = normalizeSessionSource(parsed.cliContextSource);\n return {\n v: 1,\n sessionId,\n ...(cliContextSource ? { cliContextSource } : {}),\n ...(openMeldProfileId ? { openMeldProfileId } : {}),\n ...(selectedOpenMeldProfileId ? { selectedOpenMeldProfileId } : {}),\n updatedAt:\n typeof parsed.updatedAt === \"string\" && parsed.updatedAt.trim().length > 0\n ? parsed.updatedAt\n : new Date(0).toISOString(),\n };\n}\n\nfunction resolveNextSessionOpenMeldProfileId(\n existing: CliContextStateV1 | null,\n input: {\n openMeldProfileId?: string | null;\n selectedOpenMeldProfileId?: string | null;\n }\n): string | undefined {\n if (!(\"openMeldProfileId\" in input)) {\n return existing?.openMeldProfileId;\n }\n return (\n normalizeOptionalOpenMeldProfileId(input.openMeldProfileId) ?? undefined\n );\n}\n\nfunction resolveNextSelectedOpenMeldProfileId(\n existing: CliContextStateV1 | null,\n input: {\n openMeldProfileId?: string | null;\n selectedOpenMeldProfileId?: string | null;\n }\n): string | undefined {\n if (!(\"selectedOpenMeldProfileId\" in input)) {\n return existing?.selectedOpenMeldProfileId;\n }\n return (\n normalizeOptionalOpenMeldProfileId(input.selectedOpenMeldProfileId) ??\n undefined\n );\n}\n\nasync function writeCliContextStateFile(\n outputPath: string,\n payload: CliContextStateV1\n): Promise<void> {\n const tempPath = `${outputPath}.tmp-${process.pid}-${Date.now()}`;\n const file = await open(tempPath, \"w\");\n let writeFailure: unknown = null;\n try {\n await file.writeFile(`${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n await file.sync();\n } catch (error) {\n writeFailure = error;\n }\n try {\n await file.close();\n } catch (error) {\n if (!writeFailure) {\n writeFailure = error;\n }\n }\n if (writeFailure) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw writeFailure;\n }\n\n try {\n await rename(tempPath, outputPath);\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nfunction normalizeSessionId(value: unknown): string | null {\n const raw = String(value ?? \"\").trim();\n if (!raw) {\n return null;\n }\n return raw.slice(0, 256);\n}\n\nfunction resolveTerminalSessionId(): CliContextResolution | null {\n if (!(process.stdin.isTTY || process.stdout.isTTY)) {\n return null;\n }\n\n const parentPid = Number(process.ppid);\n if (!Number.isInteger(parentPid) || parentPid <= 1) {\n return null;\n }\n\n return {\n cliContextId: `terminal-ppid-${parentPid}`,\n source: `terminal:ppid-${parentPid}`,\n };\n}\n\nfunction resolveStoredSessionOpenMeldProfileId(input: {\n openMeldProfileId?: unknown;\n profile?: unknown;\n}): OpenMeldProfileId | null {\n const openMeldProfileId = normalizeOptionalOpenMeldProfileId(\n input.openMeldProfileId\n );\n const legacyProfile = normalizeOptionalOpenMeldProfileId(input.profile);\n if (\n openMeldProfileId &&\n legacyProfile &&\n openMeldProfileId !== legacyProfile\n ) {\n throw new Error(\n `conflicting stored OpenMeld profile identity: openMeldProfileId=${openMeldProfileId}, profile=${legacyProfile}. Remove or reconcile the legacy profile field so it matches openMeldProfileId.`\n );\n }\n return openMeldProfileId ?? legacyProfile;\n}\n\nfunction resolveStoredSelectedOpenMeldProfileId(input: {\n selectedOpenMeldProfileId?: unknown;\n}): OpenMeldProfileId | null {\n return normalizeOptionalOpenMeldProfileId(input.selectedOpenMeldProfileId);\n}\n\nfunction normalizeOptionalOpenMeldProfileId(\n value: unknown\n): OpenMeldProfileId | null {\n if (typeof value !== \"string\") {\n return null;\n }\n try {\n return normalizeOpenMeldProfileId(value);\n } catch {\n return null;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport { rmdirSync, unlinkSync } from \"node:fs\";\nimport {\n lstat,\n mkdir,\n open,\n readdir,\n rmdir,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport process from \"node:process\";\nimport type { LocalMachineIssue } from \"@openmeld/schemas\";\nimport {\n createOrphanedLocalConcurrencyIssue,\n toRecognizedLocalMachineFailureError,\n} from \"../system/local-machine-recovery\";\nimport {\n CURRENT_PROCESS_START_IDENTITY,\n isPreciseProcessStartIdentity,\n isProcessIdentityAlive,\n readProcessStartIdentity,\n} from \"../system/process-identity\";\nimport { resolveOpenMeldLaneDescriptor } from \"./openmeld-lane-descriptor\";\nimport {\n normalizeOpenMeldProfileId,\n type OpenMeldPathResolutionInput,\n locksDir as resolveLocksDir,\n runtimeDir as resolveRuntimeDir,\n} from \"./paths\";\nimport { resolveCliContextId } from \"./session-profile\";\n\nexport type OpenMeldLock = {\n ownerId: string;\n path: string;\n};\n\nexport type OpenMeldLockMeta = Record<string, unknown>;\nexport type OpenMeldLockContentionState = \"active\" | \"orphaned\" | \"unknown\";\nexport type OpenMeldLegacyLockRepairReport = {\n removedOrphanedLegacyLocks: number;\n};\ntype HeldLockReleaseContext = Record<string, unknown>;\nconst MALFORMED_LOCK_RECOVERY_GRACE_MS = 30_000;\nconst OPENMELD_ORPHANED_LOCK_SUMMARY =\n \"OpenMeld found a local command lock left by an older version.\";\n\nexport class OpenMeldLockError extends Error {\n readonly code = \"openmeld.locked\";\n readonly lockPath: string;\n readonly lockKey: string;\n readonly metaRaw: string | null;\n readonly meta: OpenMeldLockMeta | null;\n readonly contentionState: OpenMeldLockContentionState;\n\n constructor(input: {\n path: string;\n key: string;\n metaRaw?: string;\n contentionState?: OpenMeldLockContentionState;\n }) {\n const normalizedMetaRaw = normalizeMetaRaw(input.metaRaw);\n const contentionState = input.contentionState ?? \"unknown\";\n super(\n buildOpenMeldLockErrorMessage(\n input.path,\n normalizedMetaRaw,\n contentionState\n )\n );\n this.name = \"OpenMeldLockError\";\n this.lockPath = input.path;\n this.lockKey = input.key;\n this.metaRaw = normalizedMetaRaw;\n this.meta = parseOpenMeldLockMeta(normalizedMetaRaw);\n this.contentionState = contentionState;\n }\n}\n\nexport function isOpenMeldLockError(\n error: unknown\n): error is OpenMeldLockError {\n return error instanceof OpenMeldLockError;\n}\n\nexport function isOpenMeldOrphanedLockError(\n error: unknown\n): error is OpenMeldLockError {\n return isOpenMeldLockError(error) && error.contentionState === \"orphaned\";\n}\n\nexport function resolveOpenMeldOrphanedLockIssue(\n error: unknown\n): LocalMachineIssue | null {\n if (!isOpenMeldOrphanedLockError(error)) {\n return null;\n }\n return createOrphanedLocalConcurrencyIssue({\n summary: OPENMELD_ORPHANED_LOCK_SUMMARY,\n primaryAction: buildOpenMeldOrphanedLockAction(),\n detail: error.message,\n });\n}\n\nexport function buildOpenMeldOrphanedLockAction(): string {\n const repairCommand = resolveOpenMeldLaneDescriptor().repairCommand;\n return `Close any other OpenMeld commands, then run \\`${repairCommand}\\` and try again.`;\n}\n\nexport async function acquireLock(input: {\n openMeldProfileId: string;\n key: string;\n meta?: OpenMeldLockMeta;\n pathResolution?: OpenMeldPathResolutionInput;\n}): Promise<OpenMeldLock> {\n const openMeldProfileId = normalizeOpenMeldProfileId(input.openMeldProfileId);\n const sessionId = resolveCliContextId();\n const dir = resolveLocksDir(openMeldProfileId, input.pathResolution);\n const path = resolveLockPath({\n openMeldProfileId,\n key: input.key,\n pathResolution: input.pathResolution,\n });\n const ownerId = randomUUID();\n try {\n await mkdir(dir, { recursive: true });\n } catch (error) {\n throwRecognizedLocalMachineFailure({\n operation: \"create_lock\",\n error,\n });\n }\n\n // A directory is the atomic ownership boundary. Its owner-specific entry\n // lets release remove only the lock it acquired, even if another process\n // publishes a replacement at the same canonical path.\n for (let attempt = 0; attempt < 2; attempt++) {\n const contents = `${JSON.stringify({\n ...(input.meta ? { ...input.meta } : {}),\n pid: process.pid,\n ownerProcessStartedAt: CURRENT_PROCESS_START_IDENTITY,\n openMeldProfileId,\n ...(sessionId ? { sessionId } : {}),\n at: new Date().toISOString(),\n ownerId,\n })}\\n`;\n let published: boolean;\n try {\n published = await tryPublishLock(path, ownerId, contents);\n } catch (error) {\n throwRecognizedLocalMachineFailure({\n operation: \"create_lock\",\n error,\n });\n }\n if (published) {\n return { ownerId, path };\n }\n\n try {\n const existingLock = await readLockSnapshot(path);\n if (\n !existingLock.exists ||\n (await tryCleanupStaleLockPath(path, existingLock))\n ) {\n continue;\n }\n\n throw new OpenMeldLockError({\n path,\n key: input.key,\n metaRaw: existingLock.metaRaw ?? undefined,\n contentionState: resolveLockContentionState(existingLock),\n });\n } catch (error) {\n if (isOpenMeldLockError(error)) {\n throw error;\n }\n throwRecognizedLocalMachineFailure({\n operation: \"create_lock\",\n error,\n });\n }\n }\n\n throw new OpenMeldLockError({\n path,\n key: input.key,\n });\n}\n\nexport async function releaseLock(lock: OpenMeldLock): Promise<void> {\n const removedOwnerEntry = await unlinkOwnedDirectoryEntry(lock);\n if (!removedOwnerEntry) {\n return;\n }\n await rmdir(lock.path).catch((error) => {\n if (![\"ENOENT\", \"ENOTEMPTY\"].includes(getErrorCode(error) ?? \"\")) {\n throw error;\n }\n });\n}\n\n/** Attach a waiting native process before granting it permission to exec. */\nexport async function attachLockProcess(\n lock: OpenMeldLock,\n pid: number\n): Promise<OpenMeldLock> {\n const ownerProcessStartedAt = readProcessStartIdentity(pid);\n if (!isPreciseProcessStartIdentity(ownerProcessStartedAt)) {\n throw new Error(\"Cannot establish native command process identity.\");\n }\n const parent = await open(\n resolveOwnerEntryPath(lock.path, lock.ownerId),\n \"r\"\n );\n try {\n const meta = parseOpenMeldLockMeta(await parent.readFile(\"utf8\"));\n if (\n meta?.ownerId !== lock.ownerId ||\n meta.pid !== process.pid ||\n meta.ownerProcessStartedAt !== CURRENT_PROCESS_START_IDENTITY\n ) {\n throw new Error(\"Native command does not own the lifecycle lock.\");\n }\n const participant = { path: lock.path, ownerId: randomUUID() };\n const contents = `${JSON.stringify({\n ownerId: participant.ownerId,\n parentOwnerId: lock.ownerId,\n pid,\n ownerProcessStartedAt,\n at: new Date().toISOString(),\n })}\\n`;\n await writeFile(\n resolveOwnerEntryPath(lock.path, participant.ownerId),\n contents,\n {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n }\n );\n // A failed attachment must never grant execution. Keep its entry until\n // the waiting process exits; subsequent recovery proves that identity dead.\n const snapshot = await readLockSnapshot(lock.path);\n if (\n readProcessStartIdentity(pid) !== ownerProcessStartedAt ||\n !(snapshot.ownerEntryNames ?? [snapshot.ownerEntryName]).includes(\n `${encodeURIComponent(participant.ownerId)}.owner.json`\n )\n ) {\n throw new Error(\n \"Native command lifecycle attachment could not be verified.\"\n );\n }\n return participant;\n } finally {\n await parent.close();\n }\n}\n\nexport function releaseLockSync(lock: OpenMeldLock): void {\n try {\n unlinkSync(resolveOwnerEntryPath(lock.path, lock.ownerId));\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\" || getErrorCode(error) === \"ENOTDIR\") {\n return;\n }\n throw error;\n }\n\n try {\n rmdirSync(lock.path);\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\") {\n return;\n }\n throw error;\n }\n}\n\nexport async function runWithCleanupPreservingRunError<T>(input: {\n run: () => Promise<T>;\n cleanup: () => Promise<void>;\n onCleanupErrorAfterRunFailure?: (cleanupError: unknown) => void;\n}): Promise<T> {\n let runResult: T | undefined;\n let runSucceeded = false;\n let runError: unknown;\n\n try {\n runResult = await input.run();\n runSucceeded = true;\n } catch (error) {\n runError = error;\n }\n\n try {\n await input.cleanup();\n } catch (cleanupError) {\n if (!runSucceeded) {\n input.onCleanupErrorAfterRunFailure?.(cleanupError);\n throw runError;\n }\n throw cleanupError;\n }\n\n if (!runSucceeded) {\n throw runError;\n }\n\n return runResult as T;\n}\n\nexport async function runWithHeldLock<T>(input: {\n lock: OpenMeldLock;\n run: () => Promise<T>;\n releaseContext?: HeldLockReleaseContext;\n}): Promise<T> {\n return await runWithCleanupPreservingRunError({\n run: input.run,\n cleanup: () => releaseLock(input.lock),\n onCleanupErrorAfterRunFailure: (releaseError) => {\n warnLockReleaseFailure({\n error: releaseError,\n lock: input.lock,\n releaseContext: input.releaseContext,\n });\n },\n });\n}\n\nexport async function readLockMeta(input: {\n openMeldProfileId: string;\n key: string;\n pathResolution?: OpenMeldPathResolutionInput;\n}): Promise<OpenMeldLockMeta | null> {\n const existingLock = await readLockSnapshot(\n resolveLockPath({\n openMeldProfileId: input.openMeldProfileId,\n key: input.key,\n pathResolution: input.pathResolution,\n })\n );\n return existingLock.meta;\n}\n\nexport async function tryCleanupStaleLock(input: {\n openMeldProfileId: string;\n key: string;\n pathResolution?: OpenMeldPathResolutionInput;\n}): Promise<boolean> {\n return await tryCleanupStaleLockPath(\n resolveLockPath({\n openMeldProfileId: input.openMeldProfileId,\n key: input.key,\n pathResolution: input.pathResolution,\n })\n );\n}\n\nexport async function repairOrphanedLegacyLock(input: {\n openMeldProfileId: string;\n key: string;\n}): Promise<boolean> {\n const path = resolveLockPath({\n openMeldProfileId: input.openMeldProfileId,\n key: input.key,\n });\n return await repairOrphanedLegacyLockPath(path);\n}\n\nexport async function repairOrphanedLegacyLocks(): Promise<OpenMeldLegacyLockRepairReport> {\n const locksRootPath = join(resolveRuntimeDir(), \"locks\");\n const profileEntries = await readDirectoryEntries(locksRootPath);\n let removedOrphanedLegacyLocks = 0;\n\n for (const profileEntry of profileEntries.sort((left, right) =>\n left.name.localeCompare(right.name)\n )) {\n if (!profileEntry.isDirectory()) {\n continue;\n }\n const profileLocksPath = join(locksRootPath, profileEntry.name);\n const lockEntries = await readDirectoryEntries(profileLocksPath);\n for (const lockEntry of lockEntries.sort((left, right) =>\n left.name.localeCompare(right.name)\n )) {\n if (!(lockEntry.isFile() && lockEntry.name.endsWith(\".lock\"))) {\n continue;\n }\n if (\n await repairOrphanedLegacyLockPath(\n join(profileLocksPath, lockEntry.name)\n )\n ) {\n removedOrphanedLegacyLocks += 1;\n }\n }\n }\n\n return { removedOrphanedLegacyLocks };\n}\n\nasync function repairOrphanedLegacyLockPath(path: string): Promise<boolean> {\n const firstSnapshot = await readLockSnapshot(path);\n if (\n firstSnapshot.storageKind !== \"legacy_file\" ||\n !isRecoverableStaleLock(firstSnapshot)\n ) {\n return false;\n }\n\n const confirmedSnapshot = await readLockSnapshot(path);\n if (!isSameRecoverableLockSnapshot(firstSnapshot, confirmedSnapshot)) {\n return false;\n }\n\n try {\n // Ordinary lock acquisition never unlinks legacy files because an older\n // client may replace one concurrently. This path is reserved for the\n // explicit local-state repair action after the user has closed other\n // OpenMeld commands that could publish a legacy lock at this path.\n await unlink(path);\n return true;\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\" || getErrorCode(error) === \"EISDIR\") {\n return false;\n }\n throw error;\n }\n}\n\nasync function readDirectoryEntries(path: string) {\n return await readdir(path, { withFileTypes: true }).catch((error) => {\n if (getErrorCode(error) === \"ENOENT\") {\n return [];\n }\n throw error;\n });\n}\n\ntype LockSnapshot = {\n exists: boolean;\n fileIdentity: string | null;\n ownerEntryName: string | null;\n ownerEntryNames?: string[];\n modifiedAtMs: number | null;\n metaRaw: string | null;\n meta: OpenMeldLockMeta | null;\n pid: number | null;\n hasStaleOwner: boolean;\n storageKind: \"directory\" | \"legacy_file\" | null;\n};\n\nfunction resolveLockPath(input: {\n openMeldProfileId: string;\n key: string;\n pathResolution?: OpenMeldPathResolutionInput;\n}): string {\n const openMeldProfileId = normalizeOpenMeldProfileId(input.openMeldProfileId);\n return join(\n resolveLocksDir(openMeldProfileId, input.pathResolution),\n `${sanitizeFilename(input.key)}.lock`\n );\n}\n\nfunction sanitizeFilename(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n}\n\nfunction safeParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\nfunction normalizeMetaRaw(metaRaw: string | undefined): string | null {\n if (typeof metaRaw !== \"string\") {\n return null;\n }\n const normalized = metaRaw.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction parseOpenMeldLockMeta(\n metaRaw: string | null\n): OpenMeldLockMeta | null {\n if (!metaRaw) {\n return null;\n }\n const parsed = safeParse(metaRaw);\n if (!parsed || typeof parsed !== \"object\") {\n return null;\n }\n return parsed as OpenMeldLockMeta;\n}\n\nfunction buildOpenMeldLockErrorMessage(\n path: string,\n metaRaw: string | null,\n contentionState: OpenMeldLockContentionState\n): string {\n const lockDetail = metaRaw\n ? `space is locked (${path}). Meta: ${metaRaw}`\n : `space is locked (${path})`;\n if (contentionState !== \"orphaned\") {\n return lockDetail;\n }\n return `${lockDetail}. ${OPENMELD_ORPHANED_LOCK_SUMMARY} ${buildOpenMeldOrphanedLockAction()}`;\n}\n\nfunction getPidFromMeta(meta: unknown): number | null {\n if (!meta || typeof meta !== \"object\") {\n return null;\n }\n const pid = (meta as Record<string, unknown>).pid;\n return typeof pid === \"number\" ? pid : null;\n}\n\nfunction missingLockSnapshot(): LockSnapshot {\n return {\n exists: false,\n fileIdentity: null,\n ownerEntryName: null,\n modifiedAtMs: null,\n metaRaw: null,\n meta: null,\n pid: null,\n hasStaleOwner: false,\n storageKind: null,\n };\n}\n\nasync function readLockSnapshot(\n path: string,\n remainingRaceRetries = 2\n): Promise<LockSnapshot> {\n const pathStats = await lstat(path).catch((error) => {\n if (getErrorCode(error) === \"ENOENT\") {\n return null;\n }\n throw error;\n });\n if (!pathStats) {\n return missingLockSnapshot();\n }\n\n if (pathStats.isDirectory()) {\n try {\n return await readDirectoryLockSnapshot(path, pathStats);\n } catch (error) {\n if (\n remainingRaceRetries > 0 &&\n (getErrorCode(error) === \"ENOENT\" || getErrorCode(error) === \"ENOTDIR\")\n ) {\n return await readLockSnapshot(path, remainingRaceRetries - 1);\n }\n throw error;\n }\n }\n\n const handle = await open(path, \"r\").catch((error) => {\n if (getErrorCode(error) === \"ENOENT\") {\n return null;\n }\n if (remainingRaceRetries > 0 && getErrorCode(error) === \"EISDIR\") {\n return \"retry\" as const;\n }\n throw error;\n });\n if (handle === \"retry\") {\n return await readLockSnapshot(path, remainingRaceRetries - 1);\n }\n if (!handle) {\n return missingLockSnapshot();\n }\n\n try {\n const [metaRaw, stats] = await Promise.all([\n handle.readFile(\"utf8\"),\n handle.stat(),\n ]);\n const normalizedMetaRaw = normalizeMetaRaw(metaRaw);\n const meta = parseOpenMeldLockMeta(normalizedMetaRaw);\n const pid = getPidFromMeta(meta);\n return {\n exists: true,\n fileIdentity: `${stats.dev}:${stats.ino}:${stats.mtimeMs}:${stats.size}`,\n ownerEntryName: null,\n modifiedAtMs: stats.mtimeMs,\n metaRaw: normalizedMetaRaw,\n meta,\n pid,\n hasStaleOwner: isLockOwnerStale({ meta, pid }),\n storageKind: \"legacy_file\",\n };\n } finally {\n await handle.close();\n }\n}\n\nasync function readDirectoryLockSnapshot(\n path: string,\n pathStats: Awaited<ReturnType<typeof lstat>>,\n selectedEntry?: string\n): Promise<LockSnapshot> {\n const ownerEntries = (await readdir(path, { withFileTypes: true }))\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".owner.json\"))\n .map((entry) => entry.name)\n .sort();\n const ownerEntryName =\n selectedEntry ?? (ownerEntries.length === 1 ? ownerEntries[0] : null);\n const directoryIdentity = `${pathStats.dev}:${pathStats.ino}:${pathStats.mtimeMs}`;\n\n if (!selectedEntry && ownerEntries.length > 1) {\n const snapshots = await Promise.all(\n ownerEntries.map((entry) =>\n readDirectoryLockSnapshot(path, pathStats, entry)\n )\n );\n const recognized = snapshots.every(\n (snapshot) =>\n typeof snapshot.meta?.ownerId === \"string\" &&\n snapshot.ownerEntryName ===\n `${encodeURIComponent(snapshot.meta.ownerId)}.owner.json` &&\n isPreciseProcessStartIdentity(snapshot.meta.ownerProcessStartedAt) &&\n snapshot.pid !== null\n );\n return {\n exists: true,\n fileIdentity: snapshots\n .map((snapshot) => snapshot.fileIdentity)\n .join(\"|\"),\n ownerEntryName: null,\n ownerEntryNames: recognized ? ownerEntries : undefined,\n modifiedAtMs: Number(pathStats.mtimeMs),\n metaRaw: null,\n meta: null,\n pid: recognized ? (snapshots[0]?.pid ?? null) : null,\n hasStaleOwner:\n recognized && snapshots.every((snapshot) => snapshot.hasStaleOwner),\n storageKind: \"directory\",\n };\n }\n\n if (!ownerEntryName) {\n return {\n exists: true,\n fileIdentity: `${directoryIdentity}:empty-or-malformed`,\n ownerEntryName: null,\n modifiedAtMs: Number(pathStats.mtimeMs),\n metaRaw: null,\n meta: null,\n pid: null,\n hasStaleOwner: false,\n storageKind: \"directory\",\n };\n }\n\n const ownerEntryPath = join(path, ownerEntryName);\n const handle = await open(ownerEntryPath, \"r\");\n try {\n const [metaRaw, stats] = await Promise.all([\n handle.readFile(\"utf8\"),\n handle.stat(),\n ]);\n const normalizedMetaRaw = normalizeMetaRaw(metaRaw);\n const meta = parseOpenMeldLockMeta(normalizedMetaRaw);\n const pid = getPidFromMeta(meta);\n return {\n exists: true,\n fileIdentity: `${directoryIdentity}:${ownerEntryName}:${stats.dev}:${stats.ino}:${stats.mtimeMs}:${stats.size}`,\n ownerEntryName,\n modifiedAtMs: stats.mtimeMs,\n metaRaw: normalizedMetaRaw,\n meta,\n pid,\n hasStaleOwner: isLockOwnerStale({ meta, pid }),\n storageKind: \"directory\",\n };\n } finally {\n await handle.close();\n }\n}\n\nasync function tryCleanupStaleLockPath(\n path: string,\n initialSnapshot?: LockSnapshot\n): Promise<boolean> {\n const firstSnapshot = initialSnapshot ?? (await readLockSnapshot(path));\n\n if (!isRecoverableStaleLock(firstSnapshot)) {\n return false;\n }\n\n // A legacy client can replace a stale file lock with a live file lock at the\n // same path between inspection and unlink. Without owner-scoped storage,\n // cleanup cannot prove that it is removing the same owner, so fail closed\n // throughout the mixed-version rollout.\n if (firstSnapshot.storageKind === \"legacy_file\") {\n return false;\n }\n\n const confirmedSnapshot = await readLockSnapshot(path);\n if (!isSameRecoverableLockSnapshot(firstSnapshot, confirmedSnapshot)) {\n return false;\n }\n\n if (confirmedSnapshot.storageKind === \"directory\") {\n return await cleanupStaleDirectoryLock(path, confirmedSnapshot);\n }\n\n return false;\n}\n\nfunction isSameRecoverableLockSnapshot(\n firstSnapshot: LockSnapshot,\n confirmedSnapshot: LockSnapshot\n): boolean {\n return (\n confirmedSnapshot.exists &&\n confirmedSnapshot.fileIdentity === firstSnapshot.fileIdentity &&\n confirmedSnapshot.ownerEntryName === firstSnapshot.ownerEntryName &&\n confirmedSnapshot.metaRaw === firstSnapshot.metaRaw &&\n confirmedSnapshot.pid === firstSnapshot.pid &&\n confirmedSnapshot.storageKind === firstSnapshot.storageKind &&\n isRecoverableStaleLock(confirmedSnapshot)\n );\n}\n\nfunction resolveLockContentionState(\n snapshot: LockSnapshot\n): OpenMeldLockContentionState {\n if (\n snapshot.storageKind === \"legacy_file\" &&\n isRecoverableStaleLock(snapshot)\n ) {\n return \"orphaned\";\n }\n if (\n snapshot.storageKind !== null &&\n (snapshot.pid === null || !snapshot.hasStaleOwner)\n ) {\n return \"active\";\n }\n return \"unknown\";\n}\n\nasync function cleanupStaleDirectoryLock(\n path: string,\n snapshot: LockSnapshot\n): Promise<boolean> {\n for (const entry of snapshot.ownerEntryNames ??\n (snapshot.ownerEntryName ? [snapshot.ownerEntryName] : [])) {\n try {\n await unlink(join(path, entry));\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n }\n try {\n await rmdir(path);\n return true;\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\") {\n return true;\n }\n if (getErrorCode(error) === \"ENOTEMPTY\") {\n return false;\n }\n throw error;\n }\n}\n\nasync function tryPublishLock(\n path: string,\n ownerId: string,\n contents: string\n): Promise<boolean> {\n try {\n await mkdir(path);\n } catch (error) {\n if (getErrorCode(error) === \"EEXIST\") {\n return false;\n }\n throw error;\n }\n\n const ownerEntryPath = resolveOwnerEntryPath(path, ownerId);\n try {\n await writeFile(ownerEntryPath, contents, {\n encoding: \"utf8\",\n flag: \"wx\",\n });\n return true;\n } catch (error) {\n await unlink(ownerEntryPath).catch((cleanupError) => {\n if (getErrorCode(cleanupError) !== \"ENOENT\") {\n console.warn(\"[openmeld.lock.owner_entry_cleanup_warning]\", {\n ownerEntryPath,\n cleanupError: toErrorMessage(cleanupError),\n });\n }\n });\n await rmdir(path).catch((cleanupError) => {\n if (getErrorCode(cleanupError) !== \"ENOENT\") {\n console.warn(\"[openmeld.lock.directory_cleanup_warning]\", {\n lockPath: path,\n cleanupError: toErrorMessage(cleanupError),\n });\n }\n });\n throw error;\n }\n}\n\nasync function unlinkOwnedDirectoryEntry(lock: OpenMeldLock): Promise<boolean> {\n try {\n await unlink(resolveOwnerEntryPath(lock.path, lock.ownerId));\n return true;\n } catch (error) {\n if (getErrorCode(error) === \"ENOENT\" || getErrorCode(error) === \"ENOTDIR\") {\n return false;\n }\n throw error;\n }\n}\n\nfunction resolveOwnerEntryPath(path: string, ownerId: string): string {\n return join(path, `${encodeURIComponent(ownerId)}.owner.json`);\n}\n\nfunction isRecoverableStaleLock(snapshot: LockSnapshot): boolean {\n if (!snapshot.exists) {\n return false;\n }\n if (snapshot.pid !== null) {\n return snapshot.hasStaleOwner;\n }\n return (\n snapshot.modifiedAtMs !== null &&\n Date.now() - snapshot.modifiedAtMs >= MALFORMED_LOCK_RECOVERY_GRACE_MS\n );\n}\n\nfunction isLockOwnerStale(input: {\n meta: OpenMeldLockMeta | null;\n pid: number | null;\n}): boolean {\n if (input.pid === null) {\n return false;\n }\n const ownerProcessStartedAt = getProcessStartIdentityFromMeta(input.meta);\n if (!ownerProcessStartedAt) {\n // Locks from older clients do not carry process-start identity. Keep them\n // while their PID is live, but preserve the existing dead-PID recovery.\n return !isPidAlive(input.pid);\n }\n return !isProcessIdentityAlive({\n ownerPid: input.pid,\n ownerProcessStartedAt,\n });\n}\n\nfunction getProcessStartIdentityFromMeta(meta: unknown): string | null {\n if (!(meta && typeof meta === \"object\")) {\n return null;\n }\n const value = (meta as Record<string, unknown>).ownerProcessStartedAt;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n if (getErrorCode(err) === \"ESRCH\") {\n return false;\n }\n return true;\n }\n}\n\nfunction getErrorCode(err: unknown): string | undefined {\n if (!err || typeof err !== \"object\") {\n return undefined;\n }\n const code = (err as { code?: unknown }).code;\n return typeof code === \"string\" ? code : undefined;\n}\n\nfunction throwRecognizedLocalMachineFailure(input: {\n operation: \"create_lock\";\n error: unknown;\n}): never {\n const recognizedFailure = toRecognizedLocalMachineFailureError(input);\n throw recognizedFailure ?? input.error;\n}\n\nfunction warnLockReleaseFailure(input: {\n error: unknown;\n lock: OpenMeldLock;\n releaseContext?: HeldLockReleaseContext;\n}): void {\n console.warn(\"[openmeld.lock.release.warning]\", {\n lockPath: input.lock.path,\n releaseError: toErrorMessage(input.error),\n releaseContext: input.releaseContext ?? {},\n });\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":";;;;;;;;;;;AAGA,MAAM,8BAA8B,IAAI,KAAK;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,8BAA8B,IAAI,KAAK;CAC5C;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,mCAAmC,IAA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AAO,CAAC,uBAAuB;EAC7B,UAAU,MAAM;EAChB;CACF,CAAC;AACH;AAEA,SAAS,gCAAgC,MAA8B;CACrE,IAAI,EAAE,QAAQ,OAAO,SAAS,WAC5B,OAAO;CAET,MAAM,QAAS,KAAiC;CAChD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAEA,SAAS,WAAW,KAAsB;CACxC,IAAI;EACF,UAAQ,KAAK,KAAK,CAAC;EACnB,OAAO;CACT,SAAS,KAAK;EACZ,IAAI,aAAa,GAAG,MAAM,SACxB,OAAO;EAET,OAAO;CACT;AACF;AAEA,SAAS,aAAa,KAAkC;CACtD,IAAI,CAAC,OAAO,OAAO,QAAQ,UACzB;CAEF,MAAM,OAAQ,IAA2B;CACzC,OAAO,OAAO,SAAS,WAAW,OAAO,KAAA;AAC3C;AAEA,SAAS,mCAAmC,OAGlC;CAER,MAD0B,qCAAqC,KACzC,KAAK,MAAM;AACnC;AAEA,SAAS,uBAAuB,OAIvB;CACP,QAAQ,KAAK,mCAAmC;EAC9C,UAAU,MAAM,KAAK;EACrB,cAAc,eAAe,MAAM,KAAK;EACxC,gBAAgB,MAAM,kBAAkB,CAAC;CAC3C,CAAC;AACH;AAEA,SAAS,eAAe,OAAwB;CAC9C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { f as toSpaceMetaUrl } from "./urls-CY2uzH2-.js";
|
|
4
|
-
import {
|
|
5
|
-
import { Pn as toStructuredApiClientFailure, Wr as spaceMemberDirectoryEntrySchema, Xn as OPENMELD_HEADER_REQUEST_ID, cn as createSpaceApi, oi as spaceMetaSchema, pr as gatewayErrorEnvelopeSchema, t as OpenMeldApiClientHttpError } from "./dist-
|
|
6
|
-
import { Jt as SPACE_FILE_MAX_SIZE_BYTES, Q as openMeldSpaceEgressActionSchema,
|
|
7
|
-
import { _n as OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV, gn as OPENMELD_DISPATCH_RUNTIME_MODE_ENV, hn as OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV, pn as DISPATCH_OWNED_RUNTIME_MODE, vn as OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV, yn as OPENMELD_USER_FACING_CLI_COMMAND_ENV } from "./daemon-frame-transport-
|
|
8
|
-
import { h as isSelfWakeSpaceAction } from "./dist-
|
|
4
|
+
import { F as resolveOpenMeldEnvPreset, w as openMeldManagedBinaryPath } from "./paths-DSkUuEu3.js";
|
|
5
|
+
import { Pn as toStructuredApiClientFailure, Wr as spaceMemberDirectoryEntrySchema, Xn as OPENMELD_HEADER_REQUEST_ID, cn as createSpaceApi, oi as spaceMetaSchema, pr as gatewayErrorEnvelopeSchema, t as OpenMeldApiClientHttpError } from "./dist-DkN9tKMX.js";
|
|
6
|
+
import { Jt as SPACE_FILE_MAX_SIZE_BYTES, Q as openMeldSpaceEgressActionSchema, Qn as executionContextAssignmentSchema, in as resolveSpaceFileMimeType, mn as spaceFileNameSchema } from "./runtime-transport-DUR91mKK.js";
|
|
7
|
+
import { _n as OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV, gn as OPENMELD_DISPATCH_RUNTIME_MODE_ENV, hn as OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV, pn as DISPATCH_OWNED_RUNTIME_MODE, vn as OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV, yn as OPENMELD_USER_FACING_CLI_COMMAND_ENV } from "./daemon-frame-transport-BMZP90f0.js";
|
|
8
|
+
import { h as isSelfWakeSpaceAction } from "./dist-vpxgF6Lp.js";
|
|
9
9
|
import { n as resolveOpenMeldDistribution } from "./distribution-BDQT2ilb.js";
|
|
10
|
-
import { h as daemonRuntimeRootPath } from "./daemon-state-
|
|
11
|
-
import { n as fetchSpaceRequestWithTimeout, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-
|
|
10
|
+
import { h as daemonRuntimeRootPath } from "./daemon-state-B6G5xe7f.js";
|
|
11
|
+
import { n as fetchSpaceRequestWithTimeout, s as buildOpenMeldRequestContextHeadersWithAuth, t as createCliApiClientFoundation } from "./api-client-foundation-Czb9hJvA.js";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
13
|
import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
14
14
|
import { access } from "node:fs/promises";
|
|
@@ -839,4 +839,4 @@ async function updateSpaceMeta(input) {
|
|
|
839
839
|
//#endregion
|
|
840
840
|
export { supersedeDispatchSpaceActionRecordForReconsideration as C, readDispatchSpaceActionRecord as S, DispatchSpaceActionRejectedError as _, GatewayHttpError as a, readDispatchSpaceActionContextForReceiptFromEnv as b, toStructuredGatewayFailure as c, uploadPreparedSpaceFiles as d, createCliSpaceApi as f, DispatchSpaceActionClosedError as g, readDispatchOwnedRuntimeGuard as h, parseSpaceMetaResponse as i, parseJsonResponse as l, buildDispatchOwnedRuntimeEnv as m, updateSpaceMeta as n, readGatewayJsonResponse as o, assertDispatchOwnedRuntimePublicWriteAllowed as p, parseSpaceMetaPayload as r, readGatewayTextResponse as s, fetchSpaceMeta as t, prepareRequestedSpaceSendFiles as u, OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV as v, writeDispatchSpaceActionRecord as w, readDispatchSpaceActionContextFromEnv as x, createDispatchSpaceActionContext as y };
|
|
841
841
|
|
|
842
|
-
//# sourceMappingURL=meta-api-
|
|
842
|
+
//# sourceMappingURL=meta-api-BYB9vhya.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"meta-api-eV9exiaO.js","names":["normalizeOptionalText","normalizeOptionalText","record"],"sources":["../src/runtime/dispatch-space-action-context.ts","../src/runtime/dispatch-owned-runtime.ts","../src/space/cli-space-api.ts","../src/space/send-files.ts","../src/space/api-json.ts","../src/space/gateway-response.ts","../src/space/space-meta-response.ts","../src/space/meta-api.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n executionContextAssignmentSchema,\n openMeldSpaceEgressActionSchema,\n spaceMemberDirectoryEntrySchema,\n} from \"@openmeld/schemas\";\nimport type {\n DispatchSpaceActionClosedReasonCode,\n DispatchSpaceActionReceipt,\n OpenMeldSpaceEgressAction,\n SpaceContract,\n SpaceMemberDirectoryEntry,\n} from \"@openmeld/schemas/types\";\nimport { isSelfWakeSpaceAction } from \"@openmeld/space-mesh\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n} from \"./dispatch-runtime-env\";\n\nexport const OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV =\n \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\n\n/** The local action context is known expired/closed/mismatched: a new ordinary action must be rejected, never recorded. */\nexport class DispatchSpaceActionClosedError extends Error {\n readonly receipt = \"rejected_closed\" as const;\n readonly reasonCode: DispatchSpaceActionClosedReasonCode;\n constructor(\n reasonCode: DispatchSpaceActionClosedReasonCode,\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionClosedError\";\n this.reasonCode = reasonCode;\n }\n}\n\n/** Use only at a boundary that has positively rejected this call before recording. */\nexport class DispatchSpaceActionRejectedError extends Error {\n readonly reasonCode: Extract<\n DispatchSpaceActionReceipt,\n { status: \"rejected_before_recording\" }\n >[\"reasonCode\"];\n\n constructor(\n reasonCode: DispatchSpaceActionRejectedError[\"reasonCode\"],\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionRejectedError\";\n this.reasonCode = reasonCode;\n }\n}\n\nconst DISPATCH_SPACE_ACTION_CONTEXT_VERSION = 1 as const;\nconst DISPATCH_SPACE_ACTION_RECORD_VERSION = 1 as const;\nconst DEFAULT_CONTEXT_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport type DispatchSpaceActionSendTargetReference =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectoryEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport type DispatchSpaceActionContext = {\n projectShell?: {\n boundaryRoot: string;\n executionContextId: string;\n ledgerRootPath: string;\n workspacePath: string;\n runtime: {\n binary: string;\n engineIdentity: string;\n kind: \"docker\" | \"podman\";\n };\n };\n workingCopyId?: string;\n version: typeof DISPATCH_SPACE_ACTION_CONTEXT_VERSION;\n actionRecordPath: string;\n attemptId: string;\n contextId: string;\n dispatchId: string;\n expiresAtMs: number;\n nonce: string;\n replyToSignalId: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot: Pick<\n SpaceContract,\n \"allowedActions\" | \"publicationMode\"\n > | null;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n};\n\nexport type DispatchSpaceActionRecord = {\n version: typeof DISPATCH_SPACE_ACTION_RECORD_VERSION;\n action: OpenMeldSpaceEgressAction;\n command: string;\n contextId: string;\n createdAtMs: number;\n nonce: string;\n};\n\nexport type DispatchSpaceActionRecordReadResult =\n | {\n status: \"missing\";\n }\n | {\n errorMessage: string;\n status: \"invalid\";\n }\n | {\n record: DispatchSpaceActionRecord;\n status: \"loaded\";\n };\n\nexport function createDispatchSpaceActionContext(input: {\n projectShell?: DispatchSpaceActionContext[\"projectShell\"];\n workingCopyId?: string;\n attemptId: string;\n dispatchId: string;\n env?: Record<string, string | undefined>;\n pathInput?: OpenMeldPathResolutionInput;\n replyToSignalId?: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot:\n | Pick<SpaceContract, \"allowedActions\" | \"publicationMode\">\n | null\n | undefined;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n ttlMs?: number;\n}): {\n context: DispatchSpaceActionContext;\n contextPath: string;\n} {\n const contextId = randomUUID();\n const nonce = randomUUID();\n const contextDir = join(\n daemonRuntimeRootPath(input.pathInput ?? { env: input.env }),\n \"dispatch-space-actions\",\n `${Date.now().toString(36)}-${contextId}`\n );\n mkdirSync(contextDir, { recursive: true, mode: 0o700 });\n chmodSync(contextDir, 0o700);\n\n const contextPath = join(contextDir, \"context.json\");\n const actionRecordPath = join(contextDir, \"action.json\");\n const context: DispatchSpaceActionContext = {\n ...(input.projectShell ? { projectShell: input.projectShell } : {}),\n ...(input.workingCopyId ? { workingCopyId: input.workingCopyId } : {}),\n version: DISPATCH_SPACE_ACTION_CONTEXT_VERSION,\n actionRecordPath,\n attemptId: input.attemptId,\n contextId,\n dispatchId: input.dispatchId,\n expiresAtMs: Date.now() + (input.ttlMs ?? DEFAULT_CONTEXT_TTL_MS),\n nonce,\n replyToSignalId: normalizeOptionalText(input.replyToSignalId),\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.sourceEventId,\n spaceContractSnapshot: input.spaceContractSnapshot\n ? {\n allowedActions: input.spaceContractSnapshot.allowedActions,\n publicationMode: input.spaceContractSnapshot.publicationMode,\n }\n : null,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n writeJsonFileExclusive(contextPath, context);\n return { context, contextPath };\n}\n\nexport function readDispatchSpaceActionContextFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const context = readDispatchSpaceActionContextForReceiptFromEnv(env);\n assertContextActive(context, Date.now());\n return context;\n}\n\n// Expiry does not erase a prior receipt. Callers may use this context to compare\n// an exact existing action; writeDispatchSpaceActionRecord still rejects new\n// actions after expiry. File reads/uploads and target listing use the active\n// context reader instead.\nexport function readDispatchSpaceActionContextForReceiptFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const contextPath = normalizeOptionalText(\n env[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]\n );\n if (!contextPath) {\n throw new Error(\n \"No active OpenMeld Space Action dispatch context was found. Use this command inside an OpenMeld Space Wake dispatch.\"\n );\n }\n const context = readDispatchSpaceActionContext(contextPath);\n assertDispatchRuntimeEnvMatchesContext({ context, env });\n return context;\n}\n\nexport function readDispatchSpaceActionContext(\n contextPath: string\n): DispatchSpaceActionContext {\n return parseDispatchSpaceActionContext(readJsonFile(contextPath));\n}\n\nexport function writeDispatchSpaceActionRecord(input: {\n action: OpenMeldSpaceEgressAction;\n command: string;\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecord {\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(input.action);\n if (!parsedAction.success) {\n throw new DispatchSpaceActionRejectedError(\n \"space_action.invalid_input\",\n parsedAction.error.message\n );\n }\n if (isSelfWakeSpaceAction(parsedAction.data, input.context.targetProfileId)) {\n throw new DispatchSpaceActionRejectedError(\n \"space_action.invalid_input\",\n \"An Agent cannot Wake itself. To reply to the current message, omit wakeTargets (CLI: --wake) and submit the reply again. No action was recorded.\"\n );\n }\n\n const existing = readDispatchSpaceActionRecord({ context: input.context });\n if (existing.status === \"invalid\") {\n throw new Error(existing.errorMessage);\n }\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n assertContextActive(input.context, input.nowMs ?? Date.now());\n\n const record: DispatchSpaceActionRecord = {\n version: DISPATCH_SPACE_ACTION_RECORD_VERSION,\n action: parsedAction.data,\n command: input.command,\n contextId: input.context.contextId,\n createdAtMs: input.nowMs ?? Date.now(),\n nonce: input.context.nonce,\n };\n try {\n writeJsonFileExclusive(input.context.actionRecordPath, record);\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const existing = readDispatchSpaceActionRecord({\n context: input.context,\n });\n // A lost acknowledgement may cause the same proposal to be submitted\n // again. Acknowledge that record, never replace it or accept a new action.\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n throw new DispatchSpaceActionRejectedError(\n \"space_action.already_recorded\",\n \"An OpenMeld Space Action has already been recorded for this dispatch. A Wake can only have one final Space action. Recover its receipt with the exact original arguments; do not replace it with a different action.\"\n );\n }\n throw error;\n }\n return record;\n}\n\nexport function readDispatchSpaceActionRecord(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecordReadResult {\n if (!existsSync(input.context.actionRecordPath)) {\n return { status: \"missing\" };\n }\n try {\n const record = parseDispatchSpaceActionRecord(\n readJsonFile(input.context.actionRecordPath)\n );\n if (\n record.contextId !== input.context.contextId ||\n record.nonce !== input.context.nonce\n ) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record does not match the active dispatch context.\",\n };\n }\n if (record.createdAtMs > input.context.expiresAtMs) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record was created after the active dispatch context expired.\",\n };\n }\n return { status: \"loaded\", record };\n } catch (error) {\n return {\n status: \"invalid\",\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function supersedeDispatchSpaceActionRecordForReconsideration(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): { archivedPath: string; record: DispatchSpaceActionRecord } | null {\n const readResult = readDispatchSpaceActionRecord(input);\n if (readResult.status === \"missing\") {\n return null;\n }\n if (readResult.status === \"invalid\") {\n throw new Error(readResult.errorMessage);\n }\n const archivedPath = `${input.context.actionRecordPath}.superseded-${String(input.nowMs ?? Date.now())}-${randomUUID()}`;\n renameSync(input.context.actionRecordPath, archivedPath);\n return { archivedPath, record: readResult.record };\n}\n\nfunction parseDispatchSpaceActionContext(\n value: unknown\n): DispatchSpaceActionContext {\n const record = toRecord(value, \"OpenMeld Space Action context\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_CONTEXT_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action context version.\");\n }\n const sendTargetReference = parseSendTargetReference(\n record.sendTargetReference\n );\n return {\n ...(record.projectShell\n ? { projectShell: parseProjectShell(record.projectShell) }\n : {}),\n version,\n actionRecordPath: requiredString(\n record.actionRecordPath,\n \"actionRecordPath\"\n ),\n attemptId: requiredString(record.attemptId, \"attemptId\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n dispatchId: requiredString(record.dispatchId, \"dispatchId\"),\n expiresAtMs: requiredFiniteNumber(record.expiresAtMs, \"expiresAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n replyToSignalId: optionalString(record.replyToSignalId),\n sendTargetReference,\n sourceEventId: requiredString(record.sourceEventId, \"sourceEventId\"),\n spaceContractSnapshot: parseSpaceContractSnapshot(\n record.spaceContractSnapshot\n ),\n spaceId: requiredString(record.spaceId, \"spaceId\"),\n targetProfileId: requiredString(record.targetProfileId, \"targetProfileId\"),\n taskId: requiredString(record.taskId, \"taskId\"),\n ...(record.workingCopyId\n ? { workingCopyId: requiredString(record.workingCopyId, \"workingCopyId\") }\n : {}),\n };\n}\n\nfunction parseProjectShell(\n value: unknown\n): NonNullable<DispatchSpaceActionContext[\"projectShell\"]> {\n const record = toRecord(value, \"OpenMeld project shell context\");\n const runtime = toRecord(record.runtime, \"OpenMeld project shell runtime\");\n const kind = runtime.kind;\n if (kind !== \"docker\" && kind !== \"podman\") {\n throw new Error(\"OpenMeld project shell runtime is invalid.\");\n }\n const executionContextId = requiredString(\n record.executionContextId,\n \"executionContextId\"\n );\n const workspacePath = requiredString(record.workspacePath, \"workspacePath\");\n const boundaryRoot = requiredString(record.boundaryRoot, \"boundaryRoot\");\n const ledgerRootPath = requiredString(\n record.ledgerRootPath,\n \"ledgerRootPath\"\n );\n const binary = requiredString(runtime.binary, \"binary\");\n const validContextId =\n executionContextAssignmentSchema.shape.id.safeParse(\n executionContextId\n ).success;\n const validPaths = [\n workspacePath,\n boundaryRoot,\n ledgerRootPath,\n binary,\n ].every(isAbsolute);\n if (!(validContextId && validPaths)) {\n throw new Error(\"OpenMeld project shell context is invalid.\");\n }\n return {\n boundaryRoot,\n executionContextId,\n ledgerRootPath,\n workspacePath,\n runtime: {\n binary,\n engineIdentity: requiredString(runtime.engineIdentity, \"engineIdentity\"),\n kind,\n },\n };\n}\n\nfunction assertDispatchRuntimeEnvMatchesContext(input: {\n context: DispatchSpaceActionContext;\n env: NodeJS.ProcessEnv;\n}): void {\n const mode = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]\n );\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return;\n }\n\n const envDispatchId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n );\n if (!envDispatchId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active dispatch ID.\"\n );\n }\n if (envDispatchId !== input.context.dispatchId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action dispatch context does not match the active dispatch runtime.\"\n );\n }\n\n const envTargetProfileId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n );\n if (!envTargetProfileId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active target profile ID.\"\n );\n }\n if (envTargetProfileId !== input.context.targetProfileId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action target profile does not match the active dispatch runtime.\"\n );\n }\n}\n\nfunction parseDispatchSpaceActionRecord(\n value: unknown\n): DispatchSpaceActionRecord {\n const record = toRecord(value, \"OpenMeld Space Action record\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_RECORD_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action record version.\");\n }\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(record.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n return {\n version,\n action: parsedAction.data,\n command: requiredString(record.command, \"command\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n createdAtMs: requiredFiniteNumber(record.createdAtMs, \"createdAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n };\n}\n\nfunction parseSendTargetReference(\n value: unknown\n): DispatchSpaceActionSendTargetReference {\n const record = toRecord(value, \"sendTargetReference\");\n if (record.status === \"loaded\") {\n if (!Array.isArray(record.projection)) {\n throw new Error(\n \"OpenMeld Space Action send target projection must be an array.\"\n );\n }\n return {\n status: \"loaded\",\n projection: record.projection.map(parseSendTargetProjectionEntry),\n referenceLines: parseStringArray(record.referenceLines),\n };\n }\n if (record.status === \"failed\") {\n return {\n status: \"failed\",\n errorMessage: requiredString(record.errorMessage, \"errorMessage\"),\n projection: null,\n referenceLines: [],\n };\n }\n throw new Error(\n \"Invalid OpenMeld Space Action send target reference status.\"\n );\n}\n\nfunction parseSendTargetProjectionEntry(\n value: unknown,\n index: number\n): SpaceMemberDirectoryEntry {\n const parsed = spaceMemberDirectoryEntrySchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `OpenMeld Space Action target projection entry ${index} is not a valid Space member directory entry.`\n );\n }\n return parsed.data;\n}\n\nfunction parseSpaceContractSnapshot(\n value: unknown\n): Pick<SpaceContract, \"allowedActions\" | \"publicationMode\"> | null {\n if (value === null || value === undefined) {\n return null;\n }\n const record = toRecord(value, \"spaceContractSnapshot\");\n return {\n allowedActions: Array.isArray(record.allowedActions)\n ? (record.allowedActions as SpaceContract[\"allowedActions\"])\n : [],\n publicationMode:\n record.publicationMode === \"raw_context_sharing\"\n ? \"raw_context_sharing\"\n : \"collaboration\",\n };\n}\n\nfunction assertContextActive(\n context: DispatchSpaceActionContext,\n nowMs: number\n): void {\n if (nowMs > context.expiresAtMs) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_expired\",\n \"The OpenMeld Space Action dispatch context has expired.\"\n );\n }\n}\n\nfunction readJsonFile(path: string): unknown {\n return JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction writeJsonFileExclusive(path: string, value: unknown): void {\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n });\n chmodSync(path, 0o600);\n}\n\nfunction toRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredString(value: unknown, fieldName: string): string {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return normalized;\n}\n\nfunction requiredFiniteNumber(value: unknown, fieldName: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(`${fieldName} must be a finite number.`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return normalizeOptionalText(value);\n}\n\nfunction parseStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map((item) => normalizeOptionalText(item))\n .filter((item): item is string => Boolean(item));\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { delimiter, dirname, join, resolve } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport {\n type OpenMeldPathResolutionInput,\n openMeldManagedBinaryPath,\n resolveOpenMeldEnvPreset,\n} from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n OPENMELD_USER_FACING_CLI_COMMAND_ENV,\n} from \"./dispatch-runtime-env\";\nimport { OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV } from \"./dispatch-space-action-context\";\nimport {\n type OpenMeldDistribution,\n resolveOpenMeldDistribution,\n} from \"./distribution\";\n\nconst DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME = \"dispatch-owned-cli\";\nconst DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME = \"bin\";\nconst OPENMELD_ENV_PRESET_ENV = \"OPENMELD_ENV_PRESET\";\nconst DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES = [\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n] as const;\n\nexport type DispatchOwnedRuntimeGuard = {\n active: boolean;\n dispatchId: string | null;\n targetProfileId: string | null;\n};\n\nexport function buildDispatchOwnedRuntimeEnv(input: {\n dispatchId: string;\n targetProfileId: string;\n distribution?: OpenMeldDistribution;\n env?: Record<string, string | undefined>;\n cliEntryPath?: string;\n spaceActionContextPath?: string | null;\n}): Record<string, string | undefined> {\n // Provider overrides are not a replacement for the carrier's lane. Keep\n // these non-secret installation selectors without copying unrelated Service\n // credentials into the provider environment.\n const env = {\n OPENMELD_HOME: process.env.OPENMELD_HOME,\n OPENMELD_ENV_PRESET: process.env.OPENMELD_ENV_PRESET,\n ...(input.env ?? {}),\n };\n const currentPath = normalizeOptionalText(\n input.env?.PATH ?? process.env.PATH\n );\n const shimDir = ensureDispatchOwnedRuntimeCliShims({\n cliEntryPath: input.cliEntryPath,\n dispatchId: input.dispatchId,\n distribution: input.distribution,\n env,\n spaceActionContextPath: input.spaceActionContextPath,\n targetProfileId: input.targetProfileId,\n });\n const actionCommand = resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env,\n });\n return {\n ...env,\n PATH: prependPathEntry({\n currentPath,\n nextEntry: shimDir,\n }),\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: input.dispatchId,\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]: input.targetProfileId,\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: actionCommand,\n [OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV]: join(shimDir, actionCommand),\n [OPENMELD_ENV_PRESET_ENV]: resolveDispatchOwnedRuntimeEnvPreset({\n env,\n }),\n ...(input.spaceActionContextPath\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]:\n input.spaceActionContextPath,\n }\n : {}),\n };\n}\n\nexport function resolveDispatchOwnedRuntimeActionCliEntryCommand(\n input: OpenMeldPathResolutionInput = {}\n): \"openmeld\" | \"openmeld-dev\" | \"openmeld-canary\" {\n const preset = resolveOpenMeldEnvPreset(input);\n if (preset === \"dev-local\") {\n return \"openmeld-dev\";\n }\n if (preset === \"canary\") {\n return \"openmeld-canary\";\n }\n return \"openmeld\";\n}\n\nexport function resolveDispatchOwnedRuntimeCliShimDir(\n input: OpenMeldPathResolutionInput & {\n spaceActionContextPath?: string | null;\n } = {}\n): string {\n const spaceActionContextPath = normalizeOptionalText(\n input.spaceActionContextPath\n );\n if (spaceActionContextPath) {\n return join(\n dirname(spaceActionContextPath),\n DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME\n );\n }\n return join(\n daemonRuntimeRootPath(input),\n \"bin\",\n DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME\n );\n}\n\nexport function ensureDispatchOwnedRuntimeCliShims(input?: {\n cliEntryPath?: string;\n distribution?: OpenMeldDistribution;\n dispatchId?: string;\n env?: Record<string, string | undefined>;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const distribution = input?.distribution ?? resolveOpenMeldDistribution();\n const cliEntryPath =\n distribution === \"binary\"\n ? resolveDispatchOwnedRuntimeBinaryCliEntryPath({\n cliEntryPath: input?.cliEntryPath,\n env: input?.env,\n })\n : resolveDispatchOwnedRuntimeCliEntryPath(input?.cliEntryPath);\n const shimDir = resolveDispatchOwnedRuntimeCliShimDir({\n env: input?.env,\n spaceActionContextPath: input?.spaceActionContextPath,\n });\n mkdirSync(shimDir, { recursive: true });\n\n for (const commandName of DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES) {\n const shimPath = join(shimDir, commandName);\n const shimSource = buildDispatchOwnedRuntimeCliShimSource({\n cliEntryPath,\n commandName,\n dispatchId: input?.dispatchId,\n distribution,\n nodePath: process.execPath,\n spaceActionContextPath: input?.spaceActionContextPath,\n targetProfileId: input?.targetProfileId,\n });\n if (existsSync(shimPath)) {\n const currentSource = safeReadTextFile(shimPath);\n if (currentSource === shimSource) {\n chmodSync(shimPath, 0o755);\n continue;\n }\n }\n writeFileSync(shimPath, shimSource, {\n encoding: \"utf8\",\n mode: 0o755,\n });\n chmodSync(shimPath, 0o755);\n }\n\n return shimDir;\n}\n\nexport function readDispatchOwnedRuntimeGuard(\n env: NodeJS.ProcessEnv = process.env\n): DispatchOwnedRuntimeGuard {\n const mode = normalizeOptionalText(env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]);\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return {\n active: false,\n dispatchId: null,\n targetProfileId: null,\n };\n }\n\n return {\n active: true,\n dispatchId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n ),\n targetProfileId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n ),\n };\n}\n\nexport function assertDispatchOwnedRuntimePublicWriteAllowed(input: {\n commandLabel: string;\n env?: NodeJS.ProcessEnv;\n}): void {\n const guard = readDispatchOwnedRuntimeGuard(input.env);\n if (!guard.active) {\n return;\n }\n\n const dispatchIdSuffix = guard.dispatchId\n ? ` (dispatch ${guard.dispatchId})`\n : \"\";\n throw new Error(\n `${input.commandLabel} is blocked inside a dispatch-owned runtime${dispatchIdSuffix}. Public space writes must be returned through OpenMeld Space structured actions: post_message, post_status, or stay_silent.`\n );\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveDispatchOwnedRuntimeCliEntryPath(\n cliEntryPath?: string\n): string {\n const normalizedCliEntryPath =\n normalizeOptionalText(cliEntryPath) ??\n normalizeOptionalText(process.argv[1]) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current CLI entry path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction resolveDispatchOwnedRuntimeBinaryCliEntryPath(input: {\n cliEntryPath?: string;\n env?: Record<string, string | undefined>;\n}): string {\n // A background Service may keep running from an executable path that an\n // upgrade later replaces with a launcher. The lane-owned managed CLI is the\n // stable command authority for new Space Action subprocesses.\n const normalizedCliEntryPath =\n normalizeOptionalText(input.cliEntryPath) ??\n normalizeOptionalText(openMeldManagedBinaryPath({ env: input.env })) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current binary CLI path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction buildDispatchOwnedRuntimeCliShimSource(input: {\n cliEntryPath: string;\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number];\n distribution: OpenMeldDistribution;\n dispatchId?: string;\n nodePath: string;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const embeddedEnv = {\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_ENV_PRESET_ENV]: resolveEnvPresetForCommandName(\n input.commandName\n ),\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: input.commandName,\n ...(normalizeOptionalText(input.dispatchId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: normalizeOptionalText(\n input.dispatchId\n ) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.targetProfileId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]:\n normalizeOptionalText(input.targetProfileId) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.spaceActionContextPath)\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: normalizeOptionalText(\n input.spaceActionContextPath\n ) as string,\n }\n : {}),\n };\n if (input.distribution === \"binary\") {\n const exportRows = Object.entries(embeddedEnv).map(\n ([key, value]) => `export ${key}=${quoteShellValue(value)}`\n );\n return `#!/bin/sh\n${exportRows.join(\"\\n\")}\nexec ${quoteShellValue(input.cliEntryPath)} \"$@\"\n`;\n }\n return `#!/usr/bin/env node\nimport { spawnSync } from \"node:child_process\";\n\nconst result = spawnSync(${JSON.stringify(input.nodePath)}, [${JSON.stringify(\n input.cliEntryPath\n )}, ...process.argv.slice(2)], {\n env: { ...process.env, ...${JSON.stringify(embeddedEnv)} },\n stdio: \"inherit\",\n});\n\nif (result.error) {\n throw result.error;\n}\n\nprocess.exit(result.status ?? 1);\n`;\n}\n\nfunction resolveDispatchOwnedRuntimeEnvPreset(input: {\n env?: Record<string, string | undefined>;\n}): \"prod\" | \"dev-local\" | \"canary\" {\n return resolveEnvPresetForCommandName(\n resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env: input.env,\n })\n );\n}\n\nfunction resolveEnvPresetForCommandName(\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number]\n): \"prod\" | \"dev-local\" | \"canary\" {\n if (commandName === \"openmeld-dev\") {\n return \"dev-local\";\n }\n if (commandName === \"openmeld-canary\") {\n return \"canary\";\n }\n return \"prod\";\n}\n\nfunction quoteShellValue(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction safeReadTextFile(path: string): string | null {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction prependPathEntry(input: {\n currentPath: string | null;\n nextEntry: string;\n}): string {\n const currentEntries = (input.currentPath ?? \"\")\n .split(delimiter)\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n const dedupedEntries = currentEntries.filter(\n (entry) => entry !== input.nextEntry\n );\n return [input.nextEntry, ...dedupedEntries].join(delimiter);\n}\n","import { createSpaceApi, type SpaceApi } from \"@openmeld/api-client\";\nimport { createCliApiClientFoundation } from \"./api-client-foundation\";\n\nexport type {\n SpaceApi,\n SpaceSignalsReadQuery,\n} from \"@openmeld/api-client\";\n\nexport function createCliSpaceApi(\n baseUrl: string,\n options: Parameters<typeof createCliApiClientFoundation>[1] = {}\n): SpaceApi {\n return createSpaceApi(createCliApiClientFoundation(baseUrl, options));\n}\n","import { openAsBlob } from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport {\n type StructuredApiClientFailure,\n toStructuredApiClientFailure,\n} from \"@openmeld/api-client\";\nimport {\n resolveSpaceFileMimeType,\n SPACE_FILE_MAX_SIZE_BYTES,\n SPACE_MESSAGE_FILE_MAX_COUNT,\n spaceFileNameSchema,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldRequestContext,\n SpaceMessageFileReference,\n} from \"@openmeld/schemas/types\";\nimport type { SpaceApi } from \"./cli-space-api\";\n\ntype PreparedSpaceFile = {\n bytes: Blob;\n name: string;\n mimeType: string;\n};\n\ntype SpaceFileCleanupFailure = {\n failure: StructuredApiClientFailure;\n fileId: string;\n};\n\nexport class SpaceSendFileError extends Error {\n readonly code: string;\n readonly requestId?: string;\n readonly status?: number;\n readonly upstreamCode?: string;\n\n constructor(input: {\n code: string;\n message: string;\n cause?: unknown;\n requestId?: string | null;\n status?: number | null;\n upstreamCode?: string | null;\n }) {\n super(input.message, { cause: input.cause });\n this.name = \"SpaceSendFileError\";\n this.code = input.code;\n if (input.requestId) {\n this.requestId = input.requestId;\n }\n if (input.status !== null && input.status !== undefined) {\n this.status = input.status;\n }\n if (input.upstreamCode) {\n this.upstreamCode = input.upstreamCode;\n }\n }\n}\n\nexport async function prepareRequestedSpaceSendFiles(input: {\n filePaths: readonly string[];\n}): Promise<readonly PreparedSpaceFile[]> {\n if (input.filePaths.length > SPACE_MESSAGE_FILE_MAX_COUNT) {\n throw new SpaceSendFileError({\n code: \"space.file.too_many\",\n message: `A Space message can include at most ${SPACE_MESSAGE_FILE_MAX_COUNT} files. The message was not sent.`,\n });\n }\n\n const prepared: PreparedSpaceFile[] = [];\n for (const rawPath of input.filePaths) {\n if (!rawPath.trim()) {\n throw new SpaceSendFileError({\n code: \"space.file.invalid_path\",\n message: \"File paths cannot be empty. The message was not sent.\",\n });\n }\n prepared.push(await prepareSpaceSendFile(rawPath));\n }\n return prepared;\n}\n\nexport async function uploadPreparedSpaceFiles(input: {\n files: readonly PreparedSpaceFile[];\n password?: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n}): Promise<readonly SpaceMessageFileReference[]> {\n const uploaded: SpaceMessageFileReference[] = [];\n for (const file of input.files) {\n try {\n const descriptor = await input.spaceApi.uploadFile({\n bytes: file.bytes,\n clientMutationId: crypto.randomUUID(),\n mimeType: file.mimeType,\n name: file.name,\n origin: \"chat_upload\",\n parentId: null,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n uploaded.push({\n fileId: descriptor.id,\n revision: descriptor.latestRevision.revision,\n name: descriptor.name,\n mimeType: descriptor.latestRevision.mimeType,\n sizeBytes: descriptor.latestRevision.sizeBytes,\n });\n } catch (error) {\n const failure = toStructuredApiClientFailure(error);\n const cleanupFailures = await moveUploadedFilesToTrash({\n files: uploaded,\n password: input.password,\n requestContext: input.requestContext,\n spaceApi: input.spaceApi,\n spaceId: input.spaceId,\n });\n let cleanupMessage = \"\";\n if (uploaded.length > 0) {\n cleanupMessage =\n cleanupFailures.length === 0\n ? \" Files added earlier in this send were moved to Trash.\"\n : ` ${formatCleanupFailures({\n failures: cleanupFailures,\n passwordProtected: input.password !== undefined,\n profileId: input.requestContext.actorContext.openMeldProfileId,\n spaceId: input.spaceId,\n })}`;\n }\n throw new SpaceSendFileError({\n code: failure.code ?? \"space.file.upload_failed\",\n message: `Could not add file \"${file.name}\" to this Space. The message was not sent. ${failure.message}${cleanupMessage}`,\n cause: error,\n requestId: failure.requestId,\n status: failure.status,\n upstreamCode: failure.upstreamCode,\n });\n }\n }\n return uploaded;\n}\n\nasync function moveUploadedFilesToTrash(input: {\n files: readonly SpaceMessageFileReference[];\n password?: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n}): Promise<readonly SpaceFileCleanupFailure[]> {\n const failures: SpaceFileCleanupFailure[] = [];\n for (const file of input.files) {\n try {\n await input.spaceApi.trashFileEntry({\n clientMutationId: crypto.randomUUID(),\n entryId: file.fileId,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n } catch (error) {\n failures.push({\n failure: toStructuredApiClientFailure(error),\n fileId: file.fileId,\n });\n }\n }\n return failures;\n}\n\nfunction formatCleanupFailures(input: {\n failures: readonly SpaceFileCleanupFailure[];\n passwordProtected: boolean;\n profileId: string;\n spaceId: string;\n}): string {\n const failureMessages = input.failures\n .map(({ failure, fileId }) => {\n const evidence = [\n failure.code ? `code ${failure.code}` : null,\n failure.requestId ? `request ${failure.requestId}` : null,\n ]\n .filter((value): value is string => value !== null)\n .join(\", \");\n const evidenceText = evidence ? ` (${evidence})` : \"\";\n return `Could not move file ${fileId} to Trash${evidenceText}: ${failure.message} Run \\`openmeld space files trash ${input.spaceId} ${fileId} --profile ${input.profileId}\\` to finish cleanup.`;\n })\n .join(\" \");\n const passwordGuidance = input.passwordProtected\n ? \" This Space is password protected. Add `--password` with the same Space password you used for this send; OpenMeld does not include the password in this message.\"\n : \"\";\n return `${failureMessages}${passwordGuidance}`;\n}\n\nasync function prepareSpaceSendFile(\n sourcePath: string\n): Promise<PreparedSpaceFile> {\n let bytes: Blob;\n try {\n // openAsBlob collapses missing paths into ERR_INVALID_ARG_VALUE on Node 24.\n // Preserve the filesystem error code for the user-facing failure category.\n await access(sourcePath);\n bytes = await openAsBlob(sourcePath);\n } catch (error) {\n const code = readNodeErrorCode(error);\n if (code === \"ENOENT\") {\n throw new SpaceSendFileError({\n code: \"space.file.file_not_found\",\n message: `File not found: ${sourcePath}. The message was not sent.`,\n cause: error,\n });\n }\n throw new SpaceSendFileError({\n code: \"space.file.file_unreadable\",\n message: `Could not read file: ${sourcePath}. The message was not sent.`,\n cause: error,\n });\n }\n\n if (bytes.size > SPACE_FILE_MAX_SIZE_BYTES) {\n throw new SpaceSendFileError({\n code: \"space.file.too_large\",\n message: `File exceeds the ${formatFileSizeLimit()} limit: ${sourcePath}. The message was not sent.`,\n });\n }\n\n const parsedName = spaceFileNameSchema.safeParse(basename(sourcePath));\n if (!parsedName.success) {\n throw new SpaceSendFileError({\n code: \"space.file.invalid_file_name\",\n message: `File name is invalid: ${sourcePath}. The message was not sent.`,\n });\n }\n\n return {\n bytes,\n name: parsedName.data,\n mimeType: resolveSpaceFileMimeType({ fileName: parsedName.data }),\n };\n}\n\nfunction readNodeErrorCode(error: unknown): string | null {\n if (!(error && typeof error === \"object\" && \"code\" in error)) {\n return null;\n }\n return typeof error.code === \"string\" ? error.code : null;\n}\n\nfunction formatFileSizeLimit(): string {\n return `${SPACE_FILE_MAX_SIZE_BYTES / (1024 * 1024)} MiB`;\n}\n","export function parseJsonResponse(raw: string): unknown {\n if (!raw.trim()) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { OpenMeldApiClientHttpError } from \"@openmeld/api-client\";\nimport { OPENMELD_HEADER_REQUEST_ID } from \"@openmeld/gateway-contract\";\nimport { gatewayErrorEnvelopeSchema } from \"@openmeld/schemas\";\nimport type { GatewayErrorCode } from \"@openmeld/schemas/types\";\nimport { parseJsonResponse } from \"./api-json\";\n\nconst FALLBACK_GATEWAY_HTTP_ERROR_CODE = \"gateway.http_error\" as const;\nconst GENERIC_NETWORK_ERROR_CODES = [\n \"network.timeout\",\n \"network.request_failed\",\n] as const;\n\ntype SafeParseResult<T> = { success: true; data: T } | { success: false };\n\ntype GatewayResponseSchema<T> = {\n safeParse: (value: unknown) => SafeParseResult<T>;\n};\n\nexport type GatewayResponseErrorCode =\n | GatewayErrorCode\n | typeof FALLBACK_GATEWAY_HTTP_ERROR_CODE\n | (typeof GENERIC_NETWORK_ERROR_CODES)[number]\n | string;\n\nexport type StructuredGatewayFailure = {\n code: GatewayResponseErrorCode | null;\n message: string;\n requestId: string | null;\n status: number | null;\n upstreamCode: string | null;\n};\n\nexport class GatewayHttpError extends Error {\n readonly code: GatewayResponseErrorCode;\n readonly requestId: string | null;\n readonly status: number;\n readonly rawBody: string;\n readonly upstreamCode: string | null;\n\n constructor(input: {\n code: GatewayResponseErrorCode;\n message: string;\n requestId?: string | null;\n status: number;\n rawBody: string;\n upstreamCode?: string | null;\n }) {\n super(input.message);\n this.name = \"GatewayHttpError\";\n this.code = input.code;\n this.requestId = normalizeOptionalText(input.requestId);\n this.status = input.status;\n this.rawBody = input.rawBody;\n this.upstreamCode = normalizeOptionalText(input.upstreamCode);\n }\n}\n\nexport async function readGatewayJsonResponse<T>(input: {\n response: Response;\n schema: GatewayResponseSchema<T>;\n invalidMessage: string;\n}): Promise<T> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n\n const parsed = input.schema.safeParse(parseJsonResponse(raw));\n if (!parsed.success) {\n throw new Error(input.invalidMessage);\n }\n return parsed.data;\n}\n\nexport async function readGatewayTextResponse(input: {\n response: Response;\n}): Promise<string> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n return raw;\n}\n\nexport function assertGatewayResponseOk(input: {\n response: Response;\n raw: string;\n}): void {\n if (input.response.ok) {\n return;\n }\n throw parseGatewayErrorResponse(input);\n}\n\nexport function parseGatewayErrorResponse(input: {\n response: Pick<Response, \"headers\" | \"status\">;\n raw: string;\n}): GatewayHttpError {\n const payload = parseJsonResponse(input.raw);\n const parsed = gatewayErrorEnvelopeSchema.safeParse(payload);\n const headerRequestId = normalizeOptionalText(\n input.response.headers.get(OPENMELD_HEADER_REQUEST_ID)\n );\n\n if (parsed.success) {\n return new GatewayHttpError({\n code: parsed.data.error.code,\n message: parsed.data.error.message,\n requestId: parsed.data.error.requestId || headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: parsed.data.error.upstreamCode ?? null,\n });\n }\n\n const looseEnvelope = readLooseGatewayErrorEnvelope(payload);\n if (looseEnvelope) {\n return new GatewayHttpError({\n code: looseEnvelope.code ?? FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n looseEnvelope.message ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: looseEnvelope.requestId ?? headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: looseEnvelope.upstreamCode,\n });\n }\n\n return new GatewayHttpError({\n code: FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n normalizeOptionalText(input.raw) ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: null,\n });\n}\n\nexport function toStructuredGatewayFailure(\n error: unknown\n): StructuredGatewayFailure {\n if (error instanceof OpenMeldApiClientHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n if (error instanceof GatewayHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n const genericErrorCode = readGenericErrorCode(error);\n if (genericErrorCode) {\n return {\n code: genericErrorCode,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n }\n\n return {\n code: null,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFailureMessage(value: unknown): string {\n return normalizeOptionalText(value) ?? \"Unknown error.\";\n}\n\nfunction readGenericErrorCode(value: unknown): GatewayResponseErrorCode | null {\n if (!value || typeof value !== \"object\" || !(\"code\" in value)) {\n return null;\n }\n\n const normalized = normalizeOptionalText(\n (value as { code?: unknown }).code ?? null\n );\n return normalized as GatewayResponseErrorCode | null;\n}\n\nfunction readLooseGatewayErrorEnvelope(value: unknown): {\n code: string | null;\n message: string | null;\n requestId: string | null;\n upstreamCode: string | null;\n} | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const record = value as {\n error?: {\n code?: unknown;\n message?: unknown;\n requestId?: unknown;\n upstreamCode?: unknown;\n } | null;\n };\n const error = record.error;\n if (!error || typeof error !== \"object\") {\n return null;\n }\n\n const code = normalizeOptionalText(error.code);\n const message = normalizeOptionalText(error.message);\n const requestId = normalizeOptionalText(error.requestId);\n const upstreamCode = normalizeOptionalText(error.upstreamCode);\n if (!(code || message || requestId || upstreamCode)) {\n return null;\n }\n\n return {\n code,\n message,\n requestId,\n upstreamCode,\n };\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { spaceMetaSchema } from \"@openmeld/schemas\";\n\ntype SpaceMetaParseOperation =\n | \"createSpaceMeta\"\n | \"fetchSpaceMeta\"\n | \"updateSpaceMeta\";\n\nexport function parseSpaceMetaPayload(input: {\n data: unknown;\n endpoint: string;\n operation: SpaceMetaParseOperation;\n}): SpaceMeta {\n try {\n const validation = spaceMetaSchema.safeParse(input.data);\n if (!validation.success) {\n const reason =\n validation.error.issues[0]?.message ??\n \"space meta payload does not match schema\";\n throw new Error(reason);\n }\n return validation.data;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${JSON.stringify(input.data)}`\n );\n }\n}\n\nexport function parseSpaceMetaResponse(input: {\n raw: string;\n endpoint: string;\n operation: Extract<\n SpaceMetaParseOperation,\n \"fetchSpaceMeta\" | \"updateSpaceMeta\"\n >;\n}): SpaceMeta {\n try {\n return parseSpaceMetaPayload({\n data: JSON.parse(input.raw) as unknown,\n endpoint: input.endpoint,\n operation: input.operation,\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${input.raw}`\n );\n }\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { toSpaceMetaUrl } from \"../protocol/urls\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { readGatewayTextResponse } from \"./gateway-response\";\nimport { parseSpaceMetaResponse } from \"./space-meta-response\";\n\ntype SpaceMetaApiInput = {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n};\n\nexport async function fetchSpaceMeta(\n input: SpaceMetaApiInput\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.fetch_meta\",\n init: {\n method: \"GET\",\n headers: await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceMeta\",\n });\n}\n\nexport async function updateSpaceMeta(\n input: SpaceMetaApiInput & {\n purpose?: string;\n guide?: string;\n }\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.update_meta\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({\n ...(input.purpose === undefined ? {} : { purpose: input.purpose }),\n ...(input.guide === undefined ? {} : { guide: input.guide }),\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"updateSpaceMeta\",\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,MAAa,yCACX;;AAGF,IAAa,iCAAb,cAAoD,MAAM;CACxD,UAAmB;CACnB;CACA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;AAGA,IAAa,mCAAb,cAAsD,MAAM;CAC1D;CAKA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,uCAAuC;AAC7C,MAAM,yBAAyB,MAAU,KAAK;AAqE9C,SAAgB,iCAAiC,OAqB/C;CACA,MAAM,YAAY,WAAW;CAC7B,MAAM,QAAQ,WAAW;CACzB,M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AAM,SAAS,MAAM,KAAK;CAC1D,MAAM,UAAU,MAAM,2CAA2C;EAC/D,YAAY;EACZ,gBAAgB,MAAM;EACtB,eAAe,MAAM;CACvB,CAAC;CACD,QAAQ,kBAAkB;CAgB1B,OAAO,uBAAuB;EAC5B,KAAA,MAHgB,wBAAwB,EAAE,UAAA,MAZrB,6BAA6B;GAClD,KAAK;GACL,WAAW;GACX,MAAM;IACJ,QAAQ;IACR;IACA,MAAM,KAAK,UAAU;KACnB,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,MAAM,QAAQ;KAChE,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;IAC5D,CAAC;GACH;EACF,CAAC,EACoD,CAAC;EAIpD;EACA,WAAW;CACb,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"meta-api-BYB9vhya.js","names":["normalizeOptionalText","normalizeOptionalText","record"],"sources":["../src/runtime/dispatch-space-action-context.ts","../src/runtime/dispatch-owned-runtime.ts","../src/space/cli-space-api.ts","../src/space/send-files.ts","../src/space/api-json.ts","../src/space/gateway-response.ts","../src/space/space-meta-response.ts","../src/space/meta-api.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n writeFileSync,\n} from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport {\n executionContextAssignmentSchema,\n openMeldSpaceEgressActionSchema,\n spaceMemberDirectoryEntrySchema,\n} from \"@openmeld/schemas\";\nimport type {\n DispatchSpaceActionClosedReasonCode,\n DispatchSpaceActionReceipt,\n OpenMeldSpaceEgressAction,\n SpaceContract,\n SpaceMemberDirectoryEntry,\n} from \"@openmeld/schemas/types\";\nimport { isSelfWakeSpaceAction } from \"@openmeld/space-mesh\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport type { OpenMeldPathResolutionInput } from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n} from \"./dispatch-runtime-env\";\n\nexport const OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV =\n \"OPENMELD_SPACE_ACTION_CONTEXT_PATH\";\n\n/** The local action context is known expired/closed/mismatched: a new ordinary action must be rejected, never recorded. */\nexport class DispatchSpaceActionClosedError extends Error {\n readonly receipt = \"rejected_closed\" as const;\n readonly reasonCode: DispatchSpaceActionClosedReasonCode;\n constructor(\n reasonCode: DispatchSpaceActionClosedReasonCode,\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionClosedError\";\n this.reasonCode = reasonCode;\n }\n}\n\n/** Use only at a boundary that has positively rejected this call before recording. */\nexport class DispatchSpaceActionRejectedError extends Error {\n readonly reasonCode: Extract<\n DispatchSpaceActionReceipt,\n { status: \"rejected_before_recording\" }\n >[\"reasonCode\"];\n\n constructor(\n reasonCode: DispatchSpaceActionRejectedError[\"reasonCode\"],\n message: string\n ) {\n super(message);\n this.name = \"DispatchSpaceActionRejectedError\";\n this.reasonCode = reasonCode;\n }\n}\n\nconst DISPATCH_SPACE_ACTION_CONTEXT_VERSION = 1 as const;\nconst DISPATCH_SPACE_ACTION_RECORD_VERSION = 1 as const;\nconst DEFAULT_CONTEXT_TTL_MS = 12 * 60 * 60 * 1000;\n\nexport type DispatchSpaceActionSendTargetReference =\n | {\n status: \"loaded\";\n projection: SpaceMemberDirectoryEntry[];\n referenceLines: string[];\n }\n | {\n status: \"failed\";\n errorMessage: string;\n projection: null;\n referenceLines: [];\n };\n\nexport type DispatchSpaceActionContext = {\n projectShell?: {\n boundaryRoot: string;\n executionContextId: string;\n ledgerRootPath: string;\n workspacePath: string;\n runtime: {\n binary: string;\n engineIdentity: string;\n kind: \"docker\" | \"podman\";\n };\n };\n workingCopyId?: string;\n version: typeof DISPATCH_SPACE_ACTION_CONTEXT_VERSION;\n actionRecordPath: string;\n attemptId: string;\n contextId: string;\n dispatchId: string;\n expiresAtMs: number;\n nonce: string;\n replyToSignalId: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot: Pick<\n SpaceContract,\n \"allowedActions\" | \"publicationMode\"\n > | null;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n};\n\nexport type DispatchSpaceActionRecord = {\n version: typeof DISPATCH_SPACE_ACTION_RECORD_VERSION;\n action: OpenMeldSpaceEgressAction;\n command: string;\n contextId: string;\n createdAtMs: number;\n nonce: string;\n};\n\nexport type DispatchSpaceActionRecordReadResult =\n | {\n status: \"missing\";\n }\n | {\n errorMessage: string;\n status: \"invalid\";\n }\n | {\n record: DispatchSpaceActionRecord;\n status: \"loaded\";\n };\n\nexport function createDispatchSpaceActionContext(input: {\n projectShell?: DispatchSpaceActionContext[\"projectShell\"];\n workingCopyId?: string;\n attemptId: string;\n dispatchId: string;\n env?: Record<string, string | undefined>;\n pathInput?: OpenMeldPathResolutionInput;\n replyToSignalId?: string | null;\n sendTargetReference: DispatchSpaceActionSendTargetReference;\n sourceEventId: string;\n spaceContractSnapshot:\n | Pick<SpaceContract, \"allowedActions\" | \"publicationMode\">\n | null\n | undefined;\n spaceId: string;\n targetProfileId: string;\n taskId: string;\n ttlMs?: number;\n}): {\n context: DispatchSpaceActionContext;\n contextPath: string;\n} {\n const contextId = randomUUID();\n const nonce = randomUUID();\n const contextDir = join(\n daemonRuntimeRootPath(input.pathInput ?? { env: input.env }),\n \"dispatch-space-actions\",\n `${Date.now().toString(36)}-${contextId}`\n );\n mkdirSync(contextDir, { recursive: true, mode: 0o700 });\n chmodSync(contextDir, 0o700);\n\n const contextPath = join(contextDir, \"context.json\");\n const actionRecordPath = join(contextDir, \"action.json\");\n const context: DispatchSpaceActionContext = {\n ...(input.projectShell ? { projectShell: input.projectShell } : {}),\n ...(input.workingCopyId ? { workingCopyId: input.workingCopyId } : {}),\n version: DISPATCH_SPACE_ACTION_CONTEXT_VERSION,\n actionRecordPath,\n attemptId: input.attemptId,\n contextId,\n dispatchId: input.dispatchId,\n expiresAtMs: Date.now() + (input.ttlMs ?? DEFAULT_CONTEXT_TTL_MS),\n nonce,\n replyToSignalId: normalizeOptionalText(input.replyToSignalId),\n sendTargetReference: input.sendTargetReference,\n sourceEventId: input.sourceEventId,\n spaceContractSnapshot: input.spaceContractSnapshot\n ? {\n allowedActions: input.spaceContractSnapshot.allowedActions,\n publicationMode: input.spaceContractSnapshot.publicationMode,\n }\n : null,\n spaceId: input.spaceId,\n targetProfileId: input.targetProfileId,\n taskId: input.taskId,\n };\n\n writeJsonFileExclusive(contextPath, context);\n return { context, contextPath };\n}\n\nexport function readDispatchSpaceActionContextFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const context = readDispatchSpaceActionContextForReceiptFromEnv(env);\n assertContextActive(context, Date.now());\n return context;\n}\n\n// Expiry does not erase a prior receipt. Callers may use this context to compare\n// an exact existing action; writeDispatchSpaceActionRecord still rejects new\n// actions after expiry. File reads/uploads and target listing use the active\n// context reader instead.\nexport function readDispatchSpaceActionContextForReceiptFromEnv(\n env: NodeJS.ProcessEnv = process.env\n): DispatchSpaceActionContext {\n const contextPath = normalizeOptionalText(\n env[OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]\n );\n if (!contextPath) {\n throw new Error(\n \"No active OpenMeld Space Action dispatch context was found. Use this command inside an OpenMeld Space Wake dispatch.\"\n );\n }\n const context = readDispatchSpaceActionContext(contextPath);\n assertDispatchRuntimeEnvMatchesContext({ context, env });\n return context;\n}\n\nexport function readDispatchSpaceActionContext(\n contextPath: string\n): DispatchSpaceActionContext {\n return parseDispatchSpaceActionContext(readJsonFile(contextPath));\n}\n\nexport function writeDispatchSpaceActionRecord(input: {\n action: OpenMeldSpaceEgressAction;\n command: string;\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecord {\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(input.action);\n if (!parsedAction.success) {\n throw new DispatchSpaceActionRejectedError(\n \"space_action.invalid_input\",\n parsedAction.error.message\n );\n }\n if (isSelfWakeSpaceAction(parsedAction.data, input.context.targetProfileId)) {\n throw new DispatchSpaceActionRejectedError(\n \"space_action.invalid_input\",\n \"An Agent cannot Wake itself. To reply to the current message, omit wakeTargets (CLI: --wake) and submit the reply again. No action was recorded.\"\n );\n }\n\n const existing = readDispatchSpaceActionRecord({ context: input.context });\n if (existing.status === \"invalid\") {\n throw new Error(existing.errorMessage);\n }\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n assertContextActive(input.context, input.nowMs ?? Date.now());\n\n const record: DispatchSpaceActionRecord = {\n version: DISPATCH_SPACE_ACTION_RECORD_VERSION,\n action: parsedAction.data,\n command: input.command,\n contextId: input.context.contextId,\n createdAtMs: input.nowMs ?? Date.now(),\n nonce: input.context.nonce,\n };\n try {\n writeJsonFileExclusive(input.context.actionRecordPath, record);\n } catch (error) {\n if (isNodeErrorCode(error, \"EEXIST\")) {\n const existing = readDispatchSpaceActionRecord({\n context: input.context,\n });\n // A lost acknowledgement may cause the same proposal to be submitted\n // again. Acknowledge that record, never replace it or accept a new action.\n if (\n existing.status === \"loaded\" &&\n isDeepStrictEqual(existing.record.action, parsedAction.data)\n ) {\n return existing.record;\n }\n throw new DispatchSpaceActionRejectedError(\n \"space_action.already_recorded\",\n \"An OpenMeld Space Action has already been recorded for this dispatch. A Wake can only have one final Space action. Recover its receipt with the exact original arguments; do not replace it with a different action.\"\n );\n }\n throw error;\n }\n return record;\n}\n\nexport function readDispatchSpaceActionRecord(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): DispatchSpaceActionRecordReadResult {\n if (!existsSync(input.context.actionRecordPath)) {\n return { status: \"missing\" };\n }\n try {\n const record = parseDispatchSpaceActionRecord(\n readJsonFile(input.context.actionRecordPath)\n );\n if (\n record.contextId !== input.context.contextId ||\n record.nonce !== input.context.nonce\n ) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record does not match the active dispatch context.\",\n };\n }\n if (record.createdAtMs > input.context.expiresAtMs) {\n return {\n status: \"invalid\",\n errorMessage:\n \"OpenMeld Space Action record was created after the active dispatch context expired.\",\n };\n }\n return { status: \"loaded\", record };\n } catch (error) {\n return {\n status: \"invalid\",\n errorMessage: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function supersedeDispatchSpaceActionRecordForReconsideration(input: {\n context: DispatchSpaceActionContext;\n nowMs?: number;\n}): { archivedPath: string; record: DispatchSpaceActionRecord } | null {\n const readResult = readDispatchSpaceActionRecord(input);\n if (readResult.status === \"missing\") {\n return null;\n }\n if (readResult.status === \"invalid\") {\n throw new Error(readResult.errorMessage);\n }\n const archivedPath = `${input.context.actionRecordPath}.superseded-${String(input.nowMs ?? Date.now())}-${randomUUID()}`;\n renameSync(input.context.actionRecordPath, archivedPath);\n return { archivedPath, record: readResult.record };\n}\n\nfunction parseDispatchSpaceActionContext(\n value: unknown\n): DispatchSpaceActionContext {\n const record = toRecord(value, \"OpenMeld Space Action context\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_CONTEXT_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action context version.\");\n }\n const sendTargetReference = parseSendTargetReference(\n record.sendTargetReference\n );\n return {\n ...(record.projectShell\n ? { projectShell: parseProjectShell(record.projectShell) }\n : {}),\n version,\n actionRecordPath: requiredString(\n record.actionRecordPath,\n \"actionRecordPath\"\n ),\n attemptId: requiredString(record.attemptId, \"attemptId\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n dispatchId: requiredString(record.dispatchId, \"dispatchId\"),\n expiresAtMs: requiredFiniteNumber(record.expiresAtMs, \"expiresAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n replyToSignalId: optionalString(record.replyToSignalId),\n sendTargetReference,\n sourceEventId: requiredString(record.sourceEventId, \"sourceEventId\"),\n spaceContractSnapshot: parseSpaceContractSnapshot(\n record.spaceContractSnapshot\n ),\n spaceId: requiredString(record.spaceId, \"spaceId\"),\n targetProfileId: requiredString(record.targetProfileId, \"targetProfileId\"),\n taskId: requiredString(record.taskId, \"taskId\"),\n ...(record.workingCopyId\n ? { workingCopyId: requiredString(record.workingCopyId, \"workingCopyId\") }\n : {}),\n };\n}\n\nfunction parseProjectShell(\n value: unknown\n): NonNullable<DispatchSpaceActionContext[\"projectShell\"]> {\n const record = toRecord(value, \"OpenMeld project shell context\");\n const runtime = toRecord(record.runtime, \"OpenMeld project shell runtime\");\n const kind = runtime.kind;\n if (kind !== \"docker\" && kind !== \"podman\") {\n throw new Error(\"OpenMeld project shell runtime is invalid.\");\n }\n const executionContextId = requiredString(\n record.executionContextId,\n \"executionContextId\"\n );\n const workspacePath = requiredString(record.workspacePath, \"workspacePath\");\n const boundaryRoot = requiredString(record.boundaryRoot, \"boundaryRoot\");\n const ledgerRootPath = requiredString(\n record.ledgerRootPath,\n \"ledgerRootPath\"\n );\n const binary = requiredString(runtime.binary, \"binary\");\n const validContextId =\n executionContextAssignmentSchema.shape.id.safeParse(\n executionContextId\n ).success;\n const validPaths = [\n workspacePath,\n boundaryRoot,\n ledgerRootPath,\n binary,\n ].every(isAbsolute);\n if (!(validContextId && validPaths)) {\n throw new Error(\"OpenMeld project shell context is invalid.\");\n }\n return {\n boundaryRoot,\n executionContextId,\n ledgerRootPath,\n workspacePath,\n runtime: {\n binary,\n engineIdentity: requiredString(runtime.engineIdentity, \"engineIdentity\"),\n kind,\n },\n };\n}\n\nfunction assertDispatchRuntimeEnvMatchesContext(input: {\n context: DispatchSpaceActionContext;\n env: NodeJS.ProcessEnv;\n}): void {\n const mode = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]\n );\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return;\n }\n\n const envDispatchId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n );\n if (!envDispatchId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active dispatch ID.\"\n );\n }\n if (envDispatchId !== input.context.dispatchId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action dispatch context does not match the active dispatch runtime.\"\n );\n }\n\n const envTargetProfileId = normalizeOptionalText(\n input.env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n );\n if (!envTargetProfileId) {\n throw new Error(\n \"OpenMeld Space Action dispatch runtime is missing the active target profile ID.\"\n );\n }\n if (envTargetProfileId !== input.context.targetProfileId) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_mismatch\",\n \"OpenMeld Space Action target profile does not match the active dispatch runtime.\"\n );\n }\n}\n\nfunction parseDispatchSpaceActionRecord(\n value: unknown\n): DispatchSpaceActionRecord {\n const record = toRecord(value, \"OpenMeld Space Action record\");\n const version = record.version;\n if (version !== DISPATCH_SPACE_ACTION_RECORD_VERSION) {\n throw new Error(\"Unsupported OpenMeld Space Action record version.\");\n }\n const parsedAction = openMeldSpaceEgressActionSchema.safeParse(record.action);\n if (!parsedAction.success) {\n throw parsedAction.error;\n }\n return {\n version,\n action: parsedAction.data,\n command: requiredString(record.command, \"command\"),\n contextId: requiredString(record.contextId, \"contextId\"),\n createdAtMs: requiredFiniteNumber(record.createdAtMs, \"createdAtMs\"),\n nonce: requiredString(record.nonce, \"nonce\"),\n };\n}\n\nfunction parseSendTargetReference(\n value: unknown\n): DispatchSpaceActionSendTargetReference {\n const record = toRecord(value, \"sendTargetReference\");\n if (record.status === \"loaded\") {\n if (!Array.isArray(record.projection)) {\n throw new Error(\n \"OpenMeld Space Action send target projection must be an array.\"\n );\n }\n return {\n status: \"loaded\",\n projection: record.projection.map(parseSendTargetProjectionEntry),\n referenceLines: parseStringArray(record.referenceLines),\n };\n }\n if (record.status === \"failed\") {\n return {\n status: \"failed\",\n errorMessage: requiredString(record.errorMessage, \"errorMessage\"),\n projection: null,\n referenceLines: [],\n };\n }\n throw new Error(\n \"Invalid OpenMeld Space Action send target reference status.\"\n );\n}\n\nfunction parseSendTargetProjectionEntry(\n value: unknown,\n index: number\n): SpaceMemberDirectoryEntry {\n const parsed = spaceMemberDirectoryEntrySchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n `OpenMeld Space Action target projection entry ${index} is not a valid Space member directory entry.`\n );\n }\n return parsed.data;\n}\n\nfunction parseSpaceContractSnapshot(\n value: unknown\n): Pick<SpaceContract, \"allowedActions\" | \"publicationMode\"> | null {\n if (value === null || value === undefined) {\n return null;\n }\n const record = toRecord(value, \"spaceContractSnapshot\");\n return {\n allowedActions: Array.isArray(record.allowedActions)\n ? (record.allowedActions as SpaceContract[\"allowedActions\"])\n : [],\n publicationMode:\n record.publicationMode === \"raw_context_sharing\"\n ? \"raw_context_sharing\"\n : \"collaboration\",\n };\n}\n\nfunction assertContextActive(\n context: DispatchSpaceActionContext,\n nowMs: number\n): void {\n if (nowMs > context.expiresAtMs) {\n throw new DispatchSpaceActionClosedError(\n \"space_action.context_expired\",\n \"The OpenMeld Space Action dispatch context has expired.\"\n );\n }\n}\n\nfunction readJsonFile(path: string): unknown {\n return JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n}\n\nfunction writeJsonFileExclusive(path: string, value: unknown): void {\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n mode: 0o600,\n });\n chmodSync(path, 0o600);\n}\n\nfunction toRecord(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${label} must be a JSON object.`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction requiredString(value: unknown, fieldName: string): string {\n const normalized = normalizeOptionalText(value);\n if (!normalized) {\n throw new Error(`${fieldName} must be a non-empty string.`);\n }\n return normalized;\n}\n\nfunction requiredFiniteNumber(value: unknown, fieldName: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(`${fieldName} must be a finite number.`);\n }\n return value;\n}\n\nfunction optionalString(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return normalizeOptionalText(value);\n}\n\nfunction parseStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n return value\n .map((item) => normalizeOptionalText(item))\n .filter((item): item is string => Boolean(item));\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isNodeErrorCode(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code === code\n );\n}\n","import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { delimiter, dirname, join, resolve } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../config/daemon-state\";\nimport {\n type OpenMeldPathResolutionInput,\n openMeldManagedBinaryPath,\n resolveOpenMeldEnvPreset,\n} from \"../config/paths\";\nimport {\n DISPATCH_OWNED_RUNTIME_MODE,\n OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV,\n OPENMELD_DISPATCH_RUNTIME_MODE_ENV,\n OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV,\n OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV,\n OPENMELD_USER_FACING_CLI_COMMAND_ENV,\n} from \"./dispatch-runtime-env\";\nimport { OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV } from \"./dispatch-space-action-context\";\nimport {\n type OpenMeldDistribution,\n resolveOpenMeldDistribution,\n} from \"./distribution\";\n\nconst DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME = \"dispatch-owned-cli\";\nconst DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME = \"bin\";\nconst OPENMELD_ENV_PRESET_ENV = \"OPENMELD_ENV_PRESET\";\nconst DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES = [\n \"openmeld\",\n \"openmeld-dev\",\n \"openmeld-canary\",\n] as const;\n\nexport type DispatchOwnedRuntimeGuard = {\n active: boolean;\n dispatchId: string | null;\n targetProfileId: string | null;\n};\n\nexport function buildDispatchOwnedRuntimeEnv(input: {\n dispatchId: string;\n targetProfileId: string;\n distribution?: OpenMeldDistribution;\n env?: Record<string, string | undefined>;\n cliEntryPath?: string;\n spaceActionContextPath?: string | null;\n}): Record<string, string | undefined> {\n // Provider overrides are not a replacement for the carrier's lane. Keep\n // these non-secret installation selectors without copying unrelated Service\n // credentials into the provider environment.\n const env = {\n OPENMELD_HOME: process.env.OPENMELD_HOME,\n OPENMELD_ENV_PRESET: process.env.OPENMELD_ENV_PRESET,\n ...(input.env ?? {}),\n };\n const currentPath = normalizeOptionalText(\n input.env?.PATH ?? process.env.PATH\n );\n const shimDir = ensureDispatchOwnedRuntimeCliShims({\n cliEntryPath: input.cliEntryPath,\n dispatchId: input.dispatchId,\n distribution: input.distribution,\n env,\n spaceActionContextPath: input.spaceActionContextPath,\n targetProfileId: input.targetProfileId,\n });\n const actionCommand = resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env,\n });\n return {\n ...env,\n PATH: prependPathEntry({\n currentPath,\n nextEntry: shimDir,\n }),\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: input.dispatchId,\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]: input.targetProfileId,\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: actionCommand,\n [OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV]: join(shimDir, actionCommand),\n [OPENMELD_ENV_PRESET_ENV]: resolveDispatchOwnedRuntimeEnvPreset({\n env,\n }),\n ...(input.spaceActionContextPath\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]:\n input.spaceActionContextPath,\n }\n : {}),\n };\n}\n\nexport function resolveDispatchOwnedRuntimeActionCliEntryCommand(\n input: OpenMeldPathResolutionInput = {}\n): \"openmeld\" | \"openmeld-dev\" | \"openmeld-canary\" {\n const preset = resolveOpenMeldEnvPreset(input);\n if (preset === \"dev-local\") {\n return \"openmeld-dev\";\n }\n if (preset === \"canary\") {\n return \"openmeld-canary\";\n }\n return \"openmeld\";\n}\n\nexport function resolveDispatchOwnedRuntimeCliShimDir(\n input: OpenMeldPathResolutionInput & {\n spaceActionContextPath?: string | null;\n } = {}\n): string {\n const spaceActionContextPath = normalizeOptionalText(\n input.spaceActionContextPath\n );\n if (spaceActionContextPath) {\n return join(\n dirname(spaceActionContextPath),\n DISPATCH_SPACE_ACTION_CLI_SHIM_DIRNAME\n );\n }\n return join(\n daemonRuntimeRootPath(input),\n \"bin\",\n DISPATCH_OWNED_RUNTIME_CLI_SHIM_DIRNAME\n );\n}\n\nexport function ensureDispatchOwnedRuntimeCliShims(input?: {\n cliEntryPath?: string;\n distribution?: OpenMeldDistribution;\n dispatchId?: string;\n env?: Record<string, string | undefined>;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const distribution = input?.distribution ?? resolveOpenMeldDistribution();\n const cliEntryPath =\n distribution === \"binary\"\n ? resolveDispatchOwnedRuntimeBinaryCliEntryPath({\n cliEntryPath: input?.cliEntryPath,\n env: input?.env,\n })\n : resolveDispatchOwnedRuntimeCliEntryPath(input?.cliEntryPath);\n const shimDir = resolveDispatchOwnedRuntimeCliShimDir({\n env: input?.env,\n spaceActionContextPath: input?.spaceActionContextPath,\n });\n mkdirSync(shimDir, { recursive: true });\n\n for (const commandName of DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES) {\n const shimPath = join(shimDir, commandName);\n const shimSource = buildDispatchOwnedRuntimeCliShimSource({\n cliEntryPath,\n commandName,\n dispatchId: input?.dispatchId,\n distribution,\n nodePath: process.execPath,\n spaceActionContextPath: input?.spaceActionContextPath,\n targetProfileId: input?.targetProfileId,\n });\n if (existsSync(shimPath)) {\n const currentSource = safeReadTextFile(shimPath);\n if (currentSource === shimSource) {\n chmodSync(shimPath, 0o755);\n continue;\n }\n }\n writeFileSync(shimPath, shimSource, {\n encoding: \"utf8\",\n mode: 0o755,\n });\n chmodSync(shimPath, 0o755);\n }\n\n return shimDir;\n}\n\nexport function readDispatchOwnedRuntimeGuard(\n env: NodeJS.ProcessEnv = process.env\n): DispatchOwnedRuntimeGuard {\n const mode = normalizeOptionalText(env[OPENMELD_DISPATCH_RUNTIME_MODE_ENV]);\n if (mode !== DISPATCH_OWNED_RUNTIME_MODE) {\n return {\n active: false,\n dispatchId: null,\n targetProfileId: null,\n };\n }\n\n return {\n active: true,\n dispatchId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]\n ),\n targetProfileId: normalizeOptionalText(\n env[OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]\n ),\n };\n}\n\nexport function assertDispatchOwnedRuntimePublicWriteAllowed(input: {\n commandLabel: string;\n env?: NodeJS.ProcessEnv;\n}): void {\n const guard = readDispatchOwnedRuntimeGuard(input.env);\n if (!guard.active) {\n return;\n }\n\n const dispatchIdSuffix = guard.dispatchId\n ? ` (dispatch ${guard.dispatchId})`\n : \"\";\n throw new Error(\n `${input.commandLabel} is blocked inside a dispatch-owned runtime${dispatchIdSuffix}. Public space writes must be returned through OpenMeld Space structured actions: post_message, post_status, or stay_silent.`\n );\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveDispatchOwnedRuntimeCliEntryPath(\n cliEntryPath?: string\n): string {\n const normalizedCliEntryPath =\n normalizeOptionalText(cliEntryPath) ??\n normalizeOptionalText(process.argv[1]) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current CLI entry path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction resolveDispatchOwnedRuntimeBinaryCliEntryPath(input: {\n cliEntryPath?: string;\n env?: Record<string, string | undefined>;\n}): string {\n // A background Service may keep running from an executable path that an\n // upgrade later replaces with a launcher. The lane-owned managed CLI is the\n // stable command authority for new Space Action subprocesses.\n const normalizedCliEntryPath =\n normalizeOptionalText(input.cliEntryPath) ??\n normalizeOptionalText(openMeldManagedBinaryPath({ env: input.env })) ??\n null;\n if (!normalizedCliEntryPath) {\n throw new Error(\n \"dispatch-owned runtime CLI shim requires a current binary CLI path\"\n );\n }\n return resolve(normalizedCliEntryPath);\n}\n\nfunction buildDispatchOwnedRuntimeCliShimSource(input: {\n cliEntryPath: string;\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number];\n distribution: OpenMeldDistribution;\n dispatchId?: string;\n nodePath: string;\n spaceActionContextPath?: string | null;\n targetProfileId?: string;\n}): string {\n const embeddedEnv = {\n [OPENMELD_DISPATCH_RUNTIME_MODE_ENV]: DISPATCH_OWNED_RUNTIME_MODE,\n [OPENMELD_ENV_PRESET_ENV]: resolveEnvPresetForCommandName(\n input.commandName\n ),\n [OPENMELD_USER_FACING_CLI_COMMAND_ENV]: input.commandName,\n ...(normalizeOptionalText(input.dispatchId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV]: normalizeOptionalText(\n input.dispatchId\n ) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.targetProfileId)\n ? {\n [OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV]:\n normalizeOptionalText(input.targetProfileId) as string,\n }\n : {}),\n ...(normalizeOptionalText(input.spaceActionContextPath)\n ? {\n [OPENMELD_SPACE_ACTION_CONTEXT_PATH_ENV]: normalizeOptionalText(\n input.spaceActionContextPath\n ) as string,\n }\n : {}),\n };\n if (input.distribution === \"binary\") {\n const exportRows = Object.entries(embeddedEnv).map(\n ([key, value]) => `export ${key}=${quoteShellValue(value)}`\n );\n return `#!/bin/sh\n${exportRows.join(\"\\n\")}\nexec ${quoteShellValue(input.cliEntryPath)} \"$@\"\n`;\n }\n return `#!/usr/bin/env node\nimport { spawnSync } from \"node:child_process\";\n\nconst result = spawnSync(${JSON.stringify(input.nodePath)}, [${JSON.stringify(\n input.cliEntryPath\n )}, ...process.argv.slice(2)], {\n env: { ...process.env, ...${JSON.stringify(embeddedEnv)} },\n stdio: \"inherit\",\n});\n\nif (result.error) {\n throw result.error;\n}\n\nprocess.exit(result.status ?? 1);\n`;\n}\n\nfunction resolveDispatchOwnedRuntimeEnvPreset(input: {\n env?: Record<string, string | undefined>;\n}): \"prod\" | \"dev-local\" | \"canary\" {\n return resolveEnvPresetForCommandName(\n resolveDispatchOwnedRuntimeActionCliEntryCommand({\n env: input.env,\n })\n );\n}\n\nfunction resolveEnvPresetForCommandName(\n commandName: (typeof DISPATCH_OWNED_RUNTIME_CLI_COMMAND_NAMES)[number]\n): \"prod\" | \"dev-local\" | \"canary\" {\n if (commandName === \"openmeld-dev\") {\n return \"dev-local\";\n }\n if (commandName === \"openmeld-canary\") {\n return \"canary\";\n }\n return \"prod\";\n}\n\nfunction quoteShellValue(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction safeReadTextFile(path: string): string | null {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n}\n\nfunction prependPathEntry(input: {\n currentPath: string | null;\n nextEntry: string;\n}): string {\n const currentEntries = (input.currentPath ?? \"\")\n .split(delimiter)\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n const dedupedEntries = currentEntries.filter(\n (entry) => entry !== input.nextEntry\n );\n return [input.nextEntry, ...dedupedEntries].join(delimiter);\n}\n","import { createSpaceApi, type SpaceApi } from \"@openmeld/api-client\";\nimport { createCliApiClientFoundation } from \"./api-client-foundation\";\n\nexport type {\n SpaceApi,\n SpaceSignalsReadQuery,\n} from \"@openmeld/api-client\";\n\nexport function createCliSpaceApi(\n baseUrl: string,\n options: Parameters<typeof createCliApiClientFoundation>[1] = {}\n): SpaceApi {\n return createSpaceApi(createCliApiClientFoundation(baseUrl, options));\n}\n","import { openAsBlob } from \"node:fs\";\nimport { access } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport {\n type StructuredApiClientFailure,\n toStructuredApiClientFailure,\n} from \"@openmeld/api-client\";\nimport {\n resolveSpaceFileMimeType,\n SPACE_FILE_MAX_SIZE_BYTES,\n SPACE_MESSAGE_FILE_MAX_COUNT,\n spaceFileNameSchema,\n} from \"@openmeld/schemas\";\nimport type {\n OpenMeldRequestContext,\n SpaceMessageFileReference,\n} from \"@openmeld/schemas/types\";\nimport type { SpaceApi } from \"./cli-space-api\";\n\ntype PreparedSpaceFile = {\n bytes: Blob;\n name: string;\n mimeType: string;\n};\n\ntype SpaceFileCleanupFailure = {\n failure: StructuredApiClientFailure;\n fileId: string;\n};\n\nexport class SpaceSendFileError extends Error {\n readonly code: string;\n readonly requestId?: string;\n readonly status?: number;\n readonly upstreamCode?: string;\n\n constructor(input: {\n code: string;\n message: string;\n cause?: unknown;\n requestId?: string | null;\n status?: number | null;\n upstreamCode?: string | null;\n }) {\n super(input.message, { cause: input.cause });\n this.name = \"SpaceSendFileError\";\n this.code = input.code;\n if (input.requestId) {\n this.requestId = input.requestId;\n }\n if (input.status !== null && input.status !== undefined) {\n this.status = input.status;\n }\n if (input.upstreamCode) {\n this.upstreamCode = input.upstreamCode;\n }\n }\n}\n\nexport async function prepareRequestedSpaceSendFiles(input: {\n filePaths: readonly string[];\n}): Promise<readonly PreparedSpaceFile[]> {\n if (input.filePaths.length > SPACE_MESSAGE_FILE_MAX_COUNT) {\n throw new SpaceSendFileError({\n code: \"space.file.too_many\",\n message: `A Space message can include at most ${SPACE_MESSAGE_FILE_MAX_COUNT} files. The message was not sent.`,\n });\n }\n\n const prepared: PreparedSpaceFile[] = [];\n for (const rawPath of input.filePaths) {\n if (!rawPath.trim()) {\n throw new SpaceSendFileError({\n code: \"space.file.invalid_path\",\n message: \"File paths cannot be empty. The message was not sent.\",\n });\n }\n prepared.push(await prepareSpaceSendFile(rawPath));\n }\n return prepared;\n}\n\nexport async function uploadPreparedSpaceFiles(input: {\n files: readonly PreparedSpaceFile[];\n password?: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n}): Promise<readonly SpaceMessageFileReference[]> {\n const uploaded: SpaceMessageFileReference[] = [];\n for (const file of input.files) {\n try {\n const descriptor = await input.spaceApi.uploadFile({\n bytes: file.bytes,\n clientMutationId: crypto.randomUUID(),\n mimeType: file.mimeType,\n name: file.name,\n origin: \"chat_upload\",\n parentId: null,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n uploaded.push({\n fileId: descriptor.id,\n revision: descriptor.latestRevision.revision,\n name: descriptor.name,\n mimeType: descriptor.latestRevision.mimeType,\n sizeBytes: descriptor.latestRevision.sizeBytes,\n });\n } catch (error) {\n const failure = toStructuredApiClientFailure(error);\n const cleanupFailures = await moveUploadedFilesToTrash({\n files: uploaded,\n password: input.password,\n requestContext: input.requestContext,\n spaceApi: input.spaceApi,\n spaceId: input.spaceId,\n });\n let cleanupMessage = \"\";\n if (uploaded.length > 0) {\n cleanupMessage =\n cleanupFailures.length === 0\n ? \" Files added earlier in this send were moved to Trash.\"\n : ` ${formatCleanupFailures({\n failures: cleanupFailures,\n passwordProtected: input.password !== undefined,\n profileId: input.requestContext.actorContext.openMeldProfileId,\n spaceId: input.spaceId,\n })}`;\n }\n throw new SpaceSendFileError({\n code: failure.code ?? \"space.file.upload_failed\",\n message: `Could not add file \"${file.name}\" to this Space. The message was not sent. ${failure.message}${cleanupMessage}`,\n cause: error,\n requestId: failure.requestId,\n status: failure.status,\n upstreamCode: failure.upstreamCode,\n });\n }\n }\n return uploaded;\n}\n\nasync function moveUploadedFilesToTrash(input: {\n files: readonly SpaceMessageFileReference[];\n password?: string;\n requestContext: OpenMeldRequestContext;\n spaceApi: SpaceApi;\n spaceId: string;\n}): Promise<readonly SpaceFileCleanupFailure[]> {\n const failures: SpaceFileCleanupFailure[] = [];\n for (const file of input.files) {\n try {\n await input.spaceApi.trashFileEntry({\n clientMutationId: crypto.randomUUID(),\n entryId: file.fileId,\n requestContext: input.requestContext,\n spaceId: input.spaceId,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n } catch (error) {\n failures.push({\n failure: toStructuredApiClientFailure(error),\n fileId: file.fileId,\n });\n }\n }\n return failures;\n}\n\nfunction formatCleanupFailures(input: {\n failures: readonly SpaceFileCleanupFailure[];\n passwordProtected: boolean;\n profileId: string;\n spaceId: string;\n}): string {\n const failureMessages = input.failures\n .map(({ failure, fileId }) => {\n const evidence = [\n failure.code ? `code ${failure.code}` : null,\n failure.requestId ? `request ${failure.requestId}` : null,\n ]\n .filter((value): value is string => value !== null)\n .join(\", \");\n const evidenceText = evidence ? ` (${evidence})` : \"\";\n return `Could not move file ${fileId} to Trash${evidenceText}: ${failure.message} Run \\`openmeld space files trash ${input.spaceId} ${fileId} --profile ${input.profileId}\\` to finish cleanup.`;\n })\n .join(\" \");\n const passwordGuidance = input.passwordProtected\n ? \" This Space is password protected. Add `--password` with the same Space password you used for this send; OpenMeld does not include the password in this message.\"\n : \"\";\n return `${failureMessages}${passwordGuidance}`;\n}\n\nasync function prepareSpaceSendFile(\n sourcePath: string\n): Promise<PreparedSpaceFile> {\n let bytes: Blob;\n try {\n // openAsBlob collapses missing paths into ERR_INVALID_ARG_VALUE on Node 24.\n // Preserve the filesystem error code for the user-facing failure category.\n await access(sourcePath);\n bytes = await openAsBlob(sourcePath);\n } catch (error) {\n const code = readNodeErrorCode(error);\n if (code === \"ENOENT\") {\n throw new SpaceSendFileError({\n code: \"space.file.file_not_found\",\n message: `File not found: ${sourcePath}. The message was not sent.`,\n cause: error,\n });\n }\n throw new SpaceSendFileError({\n code: \"space.file.file_unreadable\",\n message: `Could not read file: ${sourcePath}. The message was not sent.`,\n cause: error,\n });\n }\n\n if (bytes.size > SPACE_FILE_MAX_SIZE_BYTES) {\n throw new SpaceSendFileError({\n code: \"space.file.too_large\",\n message: `File exceeds the ${formatFileSizeLimit()} limit: ${sourcePath}. The message was not sent.`,\n });\n }\n\n const parsedName = spaceFileNameSchema.safeParse(basename(sourcePath));\n if (!parsedName.success) {\n throw new SpaceSendFileError({\n code: \"space.file.invalid_file_name\",\n message: `File name is invalid: ${sourcePath}. The message was not sent.`,\n });\n }\n\n return {\n bytes,\n name: parsedName.data,\n mimeType: resolveSpaceFileMimeType({ fileName: parsedName.data }),\n };\n}\n\nfunction readNodeErrorCode(error: unknown): string | null {\n if (!(error && typeof error === \"object\" && \"code\" in error)) {\n return null;\n }\n return typeof error.code === \"string\" ? error.code : null;\n}\n\nfunction formatFileSizeLimit(): string {\n return `${SPACE_FILE_MAX_SIZE_BYTES / (1024 * 1024)} MiB`;\n}\n","export function parseJsonResponse(raw: string): unknown {\n if (!raw.trim()) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n","import { OpenMeldApiClientHttpError } from \"@openmeld/api-client\";\nimport { OPENMELD_HEADER_REQUEST_ID } from \"@openmeld/gateway-contract\";\nimport { gatewayErrorEnvelopeSchema } from \"@openmeld/schemas\";\nimport type { GatewayErrorCode } from \"@openmeld/schemas/types\";\nimport { parseJsonResponse } from \"./api-json\";\n\nconst FALLBACK_GATEWAY_HTTP_ERROR_CODE = \"gateway.http_error\" as const;\nconst GENERIC_NETWORK_ERROR_CODES = [\n \"network.timeout\",\n \"network.request_failed\",\n] as const;\n\ntype SafeParseResult<T> = { success: true; data: T } | { success: false };\n\ntype GatewayResponseSchema<T> = {\n safeParse: (value: unknown) => SafeParseResult<T>;\n};\n\nexport type GatewayResponseErrorCode =\n | GatewayErrorCode\n | typeof FALLBACK_GATEWAY_HTTP_ERROR_CODE\n | (typeof GENERIC_NETWORK_ERROR_CODES)[number]\n | string;\n\nexport type StructuredGatewayFailure = {\n code: GatewayResponseErrorCode | null;\n message: string;\n requestId: string | null;\n status: number | null;\n upstreamCode: string | null;\n};\n\nexport class GatewayHttpError extends Error {\n readonly code: GatewayResponseErrorCode;\n readonly requestId: string | null;\n readonly status: number;\n readonly rawBody: string;\n readonly upstreamCode: string | null;\n\n constructor(input: {\n code: GatewayResponseErrorCode;\n message: string;\n requestId?: string | null;\n status: number;\n rawBody: string;\n upstreamCode?: string | null;\n }) {\n super(input.message);\n this.name = \"GatewayHttpError\";\n this.code = input.code;\n this.requestId = normalizeOptionalText(input.requestId);\n this.status = input.status;\n this.rawBody = input.rawBody;\n this.upstreamCode = normalizeOptionalText(input.upstreamCode);\n }\n}\n\nexport async function readGatewayJsonResponse<T>(input: {\n response: Response;\n schema: GatewayResponseSchema<T>;\n invalidMessage: string;\n}): Promise<T> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n\n const parsed = input.schema.safeParse(parseJsonResponse(raw));\n if (!parsed.success) {\n throw new Error(input.invalidMessage);\n }\n return parsed.data;\n}\n\nexport async function readGatewayTextResponse(input: {\n response: Response;\n}): Promise<string> {\n const raw = await input.response.text();\n assertGatewayResponseOk({\n response: input.response,\n raw,\n });\n return raw;\n}\n\nexport function assertGatewayResponseOk(input: {\n response: Response;\n raw: string;\n}): void {\n if (input.response.ok) {\n return;\n }\n throw parseGatewayErrorResponse(input);\n}\n\nexport function parseGatewayErrorResponse(input: {\n response: Pick<Response, \"headers\" | \"status\">;\n raw: string;\n}): GatewayHttpError {\n const payload = parseJsonResponse(input.raw);\n const parsed = gatewayErrorEnvelopeSchema.safeParse(payload);\n const headerRequestId = normalizeOptionalText(\n input.response.headers.get(OPENMELD_HEADER_REQUEST_ID)\n );\n\n if (parsed.success) {\n return new GatewayHttpError({\n code: parsed.data.error.code,\n message: parsed.data.error.message,\n requestId: parsed.data.error.requestId || headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: parsed.data.error.upstreamCode ?? null,\n });\n }\n\n const looseEnvelope = readLooseGatewayErrorEnvelope(payload);\n if (looseEnvelope) {\n return new GatewayHttpError({\n code: looseEnvelope.code ?? FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n looseEnvelope.message ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: looseEnvelope.requestId ?? headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: looseEnvelope.upstreamCode,\n });\n }\n\n return new GatewayHttpError({\n code: FALLBACK_GATEWAY_HTTP_ERROR_CODE,\n message:\n normalizeOptionalText(input.raw) ??\n `Gateway request failed with HTTP ${input.response.status}.`,\n requestId: headerRequestId,\n status: input.response.status,\n rawBody: input.raw,\n upstreamCode: null,\n });\n}\n\nexport function toStructuredGatewayFailure(\n error: unknown\n): StructuredGatewayFailure {\n if (error instanceof OpenMeldApiClientHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n if (error instanceof GatewayHttpError) {\n return {\n code: error.code,\n message: normalizeFailureMessage(error.message),\n requestId: error.requestId,\n status: error.status,\n upstreamCode: error.upstreamCode,\n };\n }\n\n const genericErrorCode = readGenericErrorCode(error);\n if (genericErrorCode) {\n return {\n code: genericErrorCode,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n }\n\n return {\n code: null,\n message: normalizeFailureMessage(\n error instanceof Error ? error.message : String(error)\n ),\n requestId: null,\n status: null,\n upstreamCode: null,\n };\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFailureMessage(value: unknown): string {\n return normalizeOptionalText(value) ?? \"Unknown error.\";\n}\n\nfunction readGenericErrorCode(value: unknown): GatewayResponseErrorCode | null {\n if (!value || typeof value !== \"object\" || !(\"code\" in value)) {\n return null;\n }\n\n const normalized = normalizeOptionalText(\n (value as { code?: unknown }).code ?? null\n );\n return normalized as GatewayResponseErrorCode | null;\n}\n\nfunction readLooseGatewayErrorEnvelope(value: unknown): {\n code: string | null;\n message: string | null;\n requestId: string | null;\n upstreamCode: string | null;\n} | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const record = value as {\n error?: {\n code?: unknown;\n message?: unknown;\n requestId?: unknown;\n upstreamCode?: unknown;\n } | null;\n };\n const error = record.error;\n if (!error || typeof error !== \"object\") {\n return null;\n }\n\n const code = normalizeOptionalText(error.code);\n const message = normalizeOptionalText(error.message);\n const requestId = normalizeOptionalText(error.requestId);\n const upstreamCode = normalizeOptionalText(error.upstreamCode);\n if (!(code || message || requestId || upstreamCode)) {\n return null;\n }\n\n return {\n code,\n message,\n requestId,\n upstreamCode,\n };\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { spaceMetaSchema } from \"@openmeld/schemas\";\n\ntype SpaceMetaParseOperation =\n | \"createSpaceMeta\"\n | \"fetchSpaceMeta\"\n | \"updateSpaceMeta\";\n\nexport function parseSpaceMetaPayload(input: {\n data: unknown;\n endpoint: string;\n operation: SpaceMetaParseOperation;\n}): SpaceMeta {\n try {\n const validation = spaceMetaSchema.safeParse(input.data);\n if (!validation.success) {\n const reason =\n validation.error.issues[0]?.message ??\n \"space meta payload does not match schema\";\n throw new Error(reason);\n }\n return validation.data;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${JSON.stringify(input.data)}`\n );\n }\n}\n\nexport function parseSpaceMetaResponse(input: {\n raw: string;\n endpoint: string;\n operation: Extract<\n SpaceMetaParseOperation,\n \"fetchSpaceMeta\" | \"updateSpaceMeta\"\n >;\n}): SpaceMeta {\n try {\n return parseSpaceMetaPayload({\n data: JSON.parse(input.raw) as unknown,\n endpoint: input.endpoint,\n operation: input.operation,\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `${input.operation} received invalid response payload from ${input.endpoint}: ${reason}; raw=${input.raw}`\n );\n }\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport type { OpenMeldRequestContext } from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { toSpaceMetaUrl } from \"../protocol/urls\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { readGatewayTextResponse } from \"./gateway-response\";\nimport { parseSpaceMetaResponse } from \"./space-meta-response\";\n\ntype SpaceMetaApiInput = {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n};\n\nexport async function fetchSpaceMeta(\n input: SpaceMetaApiInput\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.fetch_meta\",\n init: {\n method: \"GET\",\n headers: await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceMeta\",\n });\n}\n\nexport async function updateSpaceMeta(\n input: SpaceMetaApiInput & {\n purpose?: string;\n guide?: string;\n }\n): Promise<SpaceMeta> {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.update_meta\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({\n ...(input.purpose === undefined ? {} : { purpose: input.purpose }),\n ...(input.guide === undefined ? {} : { guide: input.guide }),\n }),\n },\n });\n const raw = await readGatewayTextResponse({ response });\n\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"updateSpaceMeta\",\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,MAAa,yCACX;;AAGF,IAAa,iCAAb,cAAoD,MAAM;CACxD,UAAmB;CACnB;CACA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;;AAGA,IAAa,mCAAb,cAAsD,MAAM;CAC1D;CAKA,YACE,YACA,SACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF;AAEA,MAAM,wCAAwC;AAC9C,MAAM,uCAAuC;AAC7C,MAAM,yBAAyB,MAAU,KAAK;AAqE9C,SAAgB,iCAAiC,OAqB/C;CACA,MAAM,YAAY,WAAW;CAC7B,MAAM,QAAQ,WAAW;CACzB,MAAM,aAAa,KACjB,sBAAsB,MAAM,aAAa,EAAE,KAAK,MAAM,IAAI,CAAC,GAC3D,0BACA,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,GAAG,WAChC;CACA,UAAU,YAAY;EAAE,WAAW;EAAM,MAAM;CAAM,CAAC;CACtD,UAAU,YAAY,GAAK;CAE3B,MAAM,cAAc,KAAK,YAAY,cAAc;CACnD,MAAM,mBAAmB,KAAK,YAAY,aAAa;CACvD,MAAM,UAAsC;EAC1C,GAAI,MAAM,eAAe,EAAE,cAAc,MAAM,aAAa,IAAI,CAAC;EACjE,GAAI,MAAM,gBAAgB,EAAE,eAAe,MAAM,cAAc,IAAI,CAAC;EACpE,SAAS;EACT;EACA,WAAW,MAAM;EACjB;EACA,YAAY,MAAM;EAClB,aAAa,KAAK,IAAI,KAAK,MAAM,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