openmeld 0.3.227 → 0.3.229

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.
Files changed (93) hide show
  1. package/dist/{add-me-membership-pkREbEJG.js → add-me-membership-25sIYCId.js} +2 -2
  2. package/dist/{add-me-membership-pkREbEJG.js.map → add-me-membership-25sIYCId.js.map} +1 -1
  3. package/dist/{agents-D_RojMEE.js → agents-DqhKdgat.js} +9 -9
  4. package/dist/{agents-D_RojMEE.js.map → agents-DqhKdgat.js.map} +1 -1
  5. package/dist/{api-client-foundation-Czb9hJvA.js → api-client-foundation-DgTXf3Gb.js} +3 -3
  6. package/dist/{api-client-foundation-Czb9hJvA.js.map → api-client-foundation-DgTXf3Gb.js.map} +1 -1
  7. package/dist/{api-client-foundation-CEScBsM7.js → api-client-foundation-d4E5XWdJ.js} +1 -1
  8. package/dist/auth-session-DExyUwLo.js +4 -0
  9. package/dist/{auth-session-Q0B3Nfae.js → auth-session-pLaN5cnC.js} +2 -2
  10. package/dist/{auth-session-Q0B3Nfae.js.map → auth-session-pLaN5cnC.js.map} +1 -1
  11. package/dist/{channel-B1gMWx__.js → channel-DppbHxHw.js} +3 -3
  12. package/dist/{channel-B1gMWx__.js.map → channel-DppbHxHw.js.map} +1 -1
  13. package/dist/{command-B5E_YSAY.js → command-BFIRSLTj.js} +15 -15
  14. package/dist/{command-B5E_YSAY.js.map → command-BFIRSLTj.js.map} +1 -1
  15. package/dist/{computer-connection-BbDdF_MD.js → computer-connection-DMkamVpB.js} +2 -2
  16. package/dist/{computer-connection-BbDdF_MD.js.map → computer-connection-DMkamVpB.js.map} +1 -1
  17. package/dist/{computer-connection-review-Dop02mby.js → computer-connection-review-C9CKzIdH.js} +5 -5
  18. package/dist/{computer-connection-review-Dop02mby.js.map → computer-connection-review-C9CKzIdH.js.map} +1 -1
  19. package/dist/{computer-disconnect-pH6HaHQq.js → computer-disconnect-Cvl_ia32.js} +7 -7
  20. package/dist/{computer-disconnect-pH6HaHQq.js.map → computer-disconnect-Cvl_ia32.js.map} +1 -1
  21. package/dist/{computer-setup-continuation-BhM3HsRI.js → computer-setup-continuation-uFrI9ZaE.js} +3 -3
  22. package/dist/{computer-setup-continuation-BhM3HsRI.js.map → computer-setup-continuation-uFrI9ZaE.js.map} +1 -1
  23. package/dist/{context-D3kAC8RG.js → context-qbQXVLF5.js} +3 -3
  24. package/dist/{context-D3kAC8RG.js.map → context-qbQXVLF5.js.map} +1 -1
  25. package/dist/{daemon-device-id-DEGf1fm6.js → daemon-device-id-B6iDyQEs.js} +4 -4
  26. package/dist/{daemon-device-id-DEGf1fm6.js.map → daemon-device-id-B6iDyQEs.js.map} +1 -1
  27. package/dist/{daemon-frame-transport-BMZP90f0.js → daemon-frame-transport-BQR5LfG2.js} +52 -8
  28. package/dist/{daemon-frame-transport-BMZP90f0.js.map → daemon-frame-transport-BQR5LfG2.js.map} +1 -1
  29. package/dist/{daemon-lifecycle-journal-NeBAn_SY.js → daemon-lifecycle-journal-G_C_pRtu.js} +3 -3
  30. package/dist/{daemon-lifecycle-journal-NeBAn_SY.js.map → daemon-lifecycle-journal-G_C_pRtu.js.map} +1 -1
  31. package/dist/{daemon-service-runtime-nIBQreis.js → daemon-service-runtime-BkVvz7bG.js} +2 -2
  32. package/dist/{daemon-service-runtime-nIBQreis.js.map → daemon-service-runtime-BkVvz7bG.js.map} +1 -1
  33. package/dist/{daemon-service-update-coordinator-BdcEl-QC.js → daemon-service-update-coordinator-UajkUU66.js} +43 -34
  34. package/dist/daemon-service-update-coordinator-UajkUU66.js.map +1 -0
  35. package/dist/{dist-DkN9tKMX.js → dist-CAypwFRu.js} +693 -63
  36. package/dist/dist-CAypwFRu.js.map +1 -0
  37. package/dist/{dist-vpxgF6Lp.js → dist-DFhd6JmQ.js} +2 -2
  38. package/dist/{dist-vpxgF6Lp.js.map → dist-DFhd6JmQ.js.map} +1 -1
  39. package/dist/dist-olOaAWkl.js +4 -0
  40. package/dist/{elapsed-time-BxMWSsxC.js → elapsed-time-UlhDiZjv.js} +5 -5
  41. package/dist/{elapsed-time-BxMWSsxC.js.map → elapsed-time-UlhDiZjv.js.map} +1 -1
  42. package/dist/{entry-jvTvDBr-.js → entry-BotSzkFU.js} +7 -7
  43. package/dist/{entry-jvTvDBr-.js.map → entry-BotSzkFU.js.map} +1 -1
  44. package/dist/{installation-inventory-Bf1SvGVh.js → installation-inventory-BgZq7fWv.js} +3 -3
  45. package/dist/{installation-inventory-Bf1SvGVh.js.map → installation-inventory-BgZq7fWv.js.map} +1 -1
  46. package/dist/{installer-IVAr1ZD-.js → installer-DxU4S_WH.js} +2 -2
  47. package/dist/{installer-IVAr1ZD-.js.map → installer-DxU4S_WH.js.map} +1 -1
  48. package/dist/{meta-api-BYB9vhya.js → meta-api-D0nhhSY7.js} +6 -6
  49. package/dist/{meta-api-BYB9vhya.js.map → meta-api-D0nhhSY7.js.map} +1 -1
  50. package/dist/{openmeld-0pnb6g3R.js → openmeld-BWAL_LKY.js} +822 -36
  51. package/dist/openmeld-BWAL_LKY.js.map +1 -0
  52. package/dist/{openmeld-maintenance-worker-CSes51Vp.js → openmeld-maintenance-worker-DOTHTGQt.js} +9 -9
  53. package/dist/{openmeld-maintenance-worker-CSes51Vp.js.map → openmeld-maintenance-worker-DOTHTGQt.js.map} +1 -1
  54. package/dist/{openmeld-tools-update-join-BlPynw_v.js → openmeld-tools-update-join-DQd7kyjX.js} +4 -4
  55. package/dist/{openmeld-tools-update-join-BlPynw_v.js.map → openmeld-tools-update-join-DQd7kyjX.js.map} +1 -1
  56. package/dist/openmeld.js +4 -4
  57. package/dist/{prepare-provider-runtime-DSKQFj-R.js → prepare-provider-runtime-DDYaeyRp.js} +9 -9
  58. package/dist/{prepare-provider-runtime-DSKQFj-R.js.map → prepare-provider-runtime-DDYaeyRp.js.map} +1 -1
  59. package/dist/{prepare-session-executor-DEJ9OaJh.js → prepare-session-executor-C7n9tbr-.js} +18 -18
  60. package/dist/{prepare-session-executor-DEJ9OaJh.js.map → prepare-session-executor-C7n9tbr-.js.map} +1 -1
  61. package/dist/{process-channel-BIumgluJ.js → process-channel-DmTb_kO4.js} +2 -2
  62. package/dist/{process-channel-BIumgluJ.js.map → process-channel-DmTb_kO4.js.map} +1 -1
  63. package/dist/{runtime-Du3Az4wt.js → runtime-Cxz_FMWn.js} +16 -16
  64. package/dist/{runtime-Du3Az4wt.js.map → runtime-Cxz_FMWn.js.map} +1 -1
  65. package/dist/{runtime-agent-controller-reporting-submission-Bl2CWQ96.js → runtime-agent-controller-reporting-submission-Ba_cI1hv.js} +8 -8
  66. package/dist/{runtime-agent-controller-reporting-submission-Bl2CWQ96.js.map → runtime-agent-controller-reporting-submission-Ba_cI1hv.js.map} +1 -1
  67. package/dist/{runtime-reporting-health-state-CKmph14R.js → runtime-reporting-health-state-BUX4e4x7.js} +9 -9
  68. package/dist/{runtime-reporting-health-state-CKmph14R.js.map → runtime-reporting-health-state-BUX4e4x7.js.map} +1 -1
  69. package/dist/{runtime-transport-DUR91mKK.js → runtime-transport-D4x8_AmR.js} +19 -2
  70. package/dist/runtime-transport-D4x8_AmR.js.map +1 -0
  71. package/dist/{service-Bh1iD84k.js → service-BHNAamFv.js} +18 -18
  72. package/dist/{service-Bh1iD84k.js.map → service-BHNAamFv.js.map} +1 -1
  73. package/dist/{service-account-authorization-CyV8YFAw.js → service-account-authorization-Di59Cjth.js} +2 -2
  74. package/dist/{service-account-authorization-CyV8YFAw.js.map → service-account-authorization-Di59Cjth.js.map} +1 -1
  75. package/dist/{service-account-control-Cc6qVa0m.js → service-account-control-s0OXYGgp.js} +9 -9
  76. package/dist/{service-account-control-Cc6qVa0m.js.map → service-account-control-s0OXYGgp.js.map} +1 -1
  77. package/dist/{service-control-capabilities-D4W3WTHS.js → service-control-capabilities-DrFu2peO.js} +3 -3
  78. package/dist/{service-control-capabilities-D4W3WTHS.js.map → service-control-capabilities-DrFu2peO.js.map} +1 -1
  79. package/dist/{service-control-capabilities-CdVTTNRK.js → service-control-capabilities-LZc_90-g.js} +1 -1
  80. package/dist/{state-ClTXLNB3.js → state-mQWCO2uD.js} +2 -2
  81. package/dist/{state-ClTXLNB3.js.map → state-mQWCO2uD.js.map} +1 -1
  82. package/dist/upgrade-BFwP5HXC.js +4 -0
  83. package/dist/{upgrade-B07Dh83M.js → upgrade-CJn4nMKH.js} +7 -7
  84. package/dist/{upgrade-B07Dh83M.js.map → upgrade-CJn4nMKH.js.map} +1 -1
  85. package/dist/windows/openmeld-windows-process.exe +0 -0
  86. package/package.json +13 -13
  87. package/dist/auth-session-ga82_Wa9.js +0 -4
  88. package/dist/daemon-service-update-coordinator-BdcEl-QC.js.map +0 -1
  89. package/dist/dist-C5emSnFG.js +0 -4
  90. package/dist/dist-DkN9tKMX.js.map +0 -1
  91. package/dist/openmeld-0pnb6g3R.js.map +0 -1
  92. package/dist/runtime-transport-DUR91mKK.js.map +0 -1
  93. package/dist/upgrade-DgTfV7-m.js +0 -4
@@ -1 +1 @@
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;EAC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C;GACH;EACF,CAAC,EACoD,CAAC;EAIpD;EACA,WAAW;CACb,CAAC;AACH"}
1
+ {"version":3,"file":"meta-api-D0nhhSY7.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;CA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