openmeld 0.3.218 → 0.3.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{add-me-membership-CY6oMdtz.js → add-me-membership-GzOoooxS.js} +2 -2
- package/dist/{add-me-membership-CY6oMdtz.js.map → add-me-membership-GzOoooxS.js.map} +1 -1
- package/dist/{agents-CzSR8rmW.js → agents-C8ATowD6.js} +9 -9
- package/dist/{agents-CzSR8rmW.js.map → agents-C8ATowD6.js.map} +1 -1
- package/dist/{api-client-foundation-BOBrz3Lx.js → api-client-foundation-CDlVc0zT.js} +3 -3
- package/dist/{api-client-foundation-BOBrz3Lx.js.map → api-client-foundation-CDlVc0zT.js.map} +1 -1
- package/dist/{api-client-foundation-D1M0bkwm.js → api-client-foundation-Dv2OE-Pi.js} +1 -1
- package/dist/{auth-session-BAq7KkIa.js → auth-session-CDhQANWx.js} +2 -2
- package/dist/{auth-session-BAq7KkIa.js.map → auth-session-CDhQANWx.js.map} +1 -1
- package/dist/auth-session-DsBkEFct.js +4 -0
- package/dist/{channel-DAZr7cKE.js → channel-D5ABuavH.js} +3 -3
- package/dist/{channel-DAZr7cKE.js.map → channel-D5ABuavH.js.map} +1 -1
- package/dist/{cli-space-api-Ccr8COpr.js → cli-space-api-skevaFSC.js} +6 -6
- package/dist/{cli-space-api-Ccr8COpr.js.map → cli-space-api-skevaFSC.js.map} +1 -1
- package/dist/{command-tsXWNPpM.js → command-CmlgCUU2.js} +15 -15
- package/dist/{command-tsXWNPpM.js.map → command-CmlgCUU2.js.map} +1 -1
- package/dist/{computer-connection-BK9TsQjc.js → computer-connection-DYnof5Xw.js} +2 -2
- package/dist/{computer-connection-BK9TsQjc.js.map → computer-connection-DYnof5Xw.js.map} +1 -1
- package/dist/{computer-connection-review-jPtrO484.js → computer-connection-review-Bjyn3UbU.js} +5 -5
- package/dist/{computer-connection-review-jPtrO484.js.map → computer-connection-review-Bjyn3UbU.js.map} +1 -1
- package/dist/{computer-disconnect-DzvN_Cbv.js → computer-disconnect-CRWsoihu.js} +7 -7
- package/dist/{computer-disconnect-DzvN_Cbv.js.map → computer-disconnect-CRWsoihu.js.map} +1 -1
- package/dist/{computer-setup-continuation-bJzZPnNU.js → computer-setup-continuation-D0kC6-l2.js} +3 -3
- package/dist/{computer-setup-continuation-bJzZPnNU.js.map → computer-setup-continuation-D0kC6-l2.js.map} +1 -1
- package/dist/{context-DN_LvdgC.js → context-D9Ebb5wl.js} +4 -4
- package/dist/{context-DN_LvdgC.js.map → context-D9Ebb5wl.js.map} +1 -1
- package/dist/{daemon-device-id-bP58j3NL.js → daemon-device-id-YnLMx1kN.js} +4 -4
- package/dist/{daemon-device-id-bP58j3NL.js.map → daemon-device-id-YnLMx1kN.js.map} +1 -1
- package/dist/{daemon-frame-transport-DFfxVRi2.js → daemon-frame-transport-E-H3DjWA.js} +27 -7
- package/dist/daemon-frame-transport-E-H3DjWA.js.map +1 -0
- package/dist/{daemon-lifecycle-journal-57QR_a3_.js → daemon-lifecycle-journal-DDrWgEzN.js} +4 -4
- package/dist/{daemon-lifecycle-journal-57QR_a3_.js.map → daemon-lifecycle-journal-DDrWgEzN.js.map} +1 -1
- package/dist/{daemon-service-manager-ReGjcyjq.js → daemon-service-manager-B-QrDe5p.js} +1 -1
- package/dist/{daemon-service-manager-rNRRVrj1.js → daemon-service-manager-HL4VKbIU.js} +2 -2
- package/dist/{daemon-service-manager-rNRRVrj1.js.map → daemon-service-manager-HL4VKbIU.js.map} +1 -1
- package/dist/{daemon-service-runtime-686fUcq9.js → daemon-service-runtime-M-kfrWro.js} +5 -5
- package/dist/{daemon-service-runtime-686fUcq9.js.map → daemon-service-runtime-M-kfrWro.js.map} +1 -1
- package/dist/{daemon-service-update-coordinator-DaoVYK6k.js → daemon-service-update-coordinator-Clqxj3A1.js} +12 -12
- package/dist/{daemon-service-update-coordinator-DaoVYK6k.js.map → daemon-service-update-coordinator-Clqxj3A1.js.map} +1 -1
- package/dist/{dist-CBWePGgY.js → dist-ChS52b_E.js} +2 -2
- package/dist/{dist-CBWePGgY.js.map → dist-ChS52b_E.js.map} +1 -1
- package/dist/{dist-CiLvbjZA.js → dist-YPzkhLLp.js} +74 -6
- package/dist/dist-YPzkhLLp.js.map +1 -0
- package/dist/{dist-C1fbc-VK.js → dist-kTVDInkZ.js} +1 -1
- package/dist/{elapsed-time-DslUBczL.js → elapsed-time-4PuBjDUi.js} +5 -5
- package/dist/{elapsed-time-DslUBczL.js.map → elapsed-time-4PuBjDUi.js.map} +1 -1
- package/dist/{entry-B3x5OX3x.js → entry-q_QHht2-.js} +7 -7
- package/dist/{entry-B3x5OX3x.js.map → entry-q_QHht2-.js.map} +1 -1
- package/dist/{installation-inventory-BZJmaCVr.js → installation-inventory-CuPmLaLZ.js} +3 -3
- package/dist/{installation-inventory-BZJmaCVr.js.map → installation-inventory-CuPmLaLZ.js.map} +1 -1
- package/dist/{installer-BRcaSYgu.js → installer-mSB-Oiwx.js} +2 -2
- package/dist/{installer-BRcaSYgu.js.map → installer-mSB-Oiwx.js.map} +1 -1
- package/dist/{openmeld-Bbffsx9Y.js → openmeld-CFXnmBH6.js} +36 -34
- package/dist/{openmeld-Bbffsx9Y.js.map → openmeld-CFXnmBH6.js.map} +1 -1
- package/dist/{openmeld-maintenance-worker-CDd4d01O.js → openmeld-maintenance-worker-K-nEox6k.js} +10 -10
- package/dist/{openmeld-maintenance-worker-CDd4d01O.js.map → openmeld-maintenance-worker-K-nEox6k.js.map} +1 -1
- package/dist/{openmeld-tools-update-join-htb9JVUN.js → openmeld-tools-update-join-CN4mjp4-.js} +4 -4
- package/dist/{openmeld-tools-update-join-htb9JVUN.js.map → openmeld-tools-update-join-CN4mjp4-.js.map} +1 -1
- package/dist/openmeld.js +4 -4
- package/dist/{prepare-provider-runtime-3eIWxGgM.js → prepare-provider-runtime-iA3g-8MS.js} +16 -11
- package/dist/prepare-provider-runtime-iA3g-8MS.js.map +1 -0
- package/dist/{prepare-session-executor-DO2p7uLE.js → prepare-session-executor-DbewUeyQ.js} +19 -19
- package/dist/{prepare-session-executor-DO2p7uLE.js.map → prepare-session-executor-DbewUeyQ.js.map} +1 -1
- package/dist/{process-channel-48ZNmEF6.js → process-channel-B2BU2X7x.js} +2 -2
- package/dist/{process-channel-48ZNmEF6.js.map → process-channel-B2BU2X7x.js.map} +1 -1
- package/dist/{runtime-C49hR7fG.js → runtime-D_AGEH9G.js} +16 -16
- package/dist/{runtime-C49hR7fG.js.map → runtime-D_AGEH9G.js.map} +1 -1
- package/dist/{runtime-agent-controller-reporting-submission-BJuVnZqs.js → runtime-agent-controller-reporting-submission-CB25cpq0.js} +8 -8
- package/dist/{runtime-agent-controller-reporting-submission-BJuVnZqs.js.map → runtime-agent-controller-reporting-submission-CB25cpq0.js.map} +1 -1
- package/dist/{runtime-reporting-health-state-4Y-fo13l.js → runtime-reporting-health-state-205lHdBE.js} +9 -9
- package/dist/{runtime-reporting-health-state-4Y-fo13l.js.map → runtime-reporting-health-state-205lHdBE.js.map} +1 -1
- package/dist/{runtime-transport-KEwcSZ89.js → runtime-transport-0F5E6So6.js} +11 -1
- package/dist/{runtime-transport-KEwcSZ89.js.map → runtime-transport-0F5E6So6.js.map} +1 -1
- package/dist/{service-account-authorization-A5Ly0UFD.js → service-account-authorization-DAPQy2yP.js} +2 -2
- package/dist/{service-account-authorization-A5Ly0UFD.js.map → service-account-authorization-DAPQy2yP.js.map} +1 -1
- package/dist/{service-account-control-DCz_pwrV.js → service-account-control-BQ1e5Y1X.js} +10 -10
- package/dist/{service-account-control-DCz_pwrV.js.map → service-account-control-BQ1e5Y1X.js.map} +1 -1
- package/dist/{service-control-capabilities-plI5rUzP.js → service-control-capabilities-C4520NIi.js} +4 -4
- package/dist/{service-control-capabilities-plI5rUzP.js.map → service-control-capabilities-C4520NIi.js.map} +1 -1
- package/dist/{service-control-capabilities-BPL-T8xI.js → service-control-capabilities-DPYmrWgX.js} +1 -1
- package/dist/{service-BlcIfxYE.js → service-yziCG6lR.js} +20 -20
- package/dist/service-yziCG6lR.js.map +1 -0
- package/dist/{state-Dj3YS3aV.js → state-DLMkZqd8.js} +2 -2
- package/dist/{state-Dj3YS3aV.js.map → state-DLMkZqd8.js.map} +1 -1
- package/dist/{upgrade-CRKSer_1.js → upgrade-BmM1hEB3.js} +7 -7
- package/dist/{upgrade-CRKSer_1.js.map → upgrade-BmM1hEB3.js.map} +1 -1
- package/dist/upgrade-neqPXWyw.js +4 -0
- package/dist/{windows-user-task-hNE24Gqr.js → windows-user-task-Bx2yYnOM.js} +1 -1
- package/dist/{windows-user-task-D4uMvea3.js → windows-user-task-CRGbKggi.js} +18 -3
- package/dist/windows-user-task-CRGbKggi.js.map +1 -0
- package/package.json +12 -12
- package/dist/auth-session-D-HTJNKZ.js +0 -4
- package/dist/daemon-frame-transport-DFfxVRi2.js.map +0 -1
- package/dist/dist-CiLvbjZA.js.map +0 -1
- package/dist/prepare-provider-runtime-3eIWxGgM.js.map +0 -1
- package/dist/service-BlcIfxYE.js.map +0 -1
- package/dist/upgrade-DdetA0-U.js +0 -4
- package/dist/windows-user-task-D4uMvea3.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"daemon-device-id-bP58j3NL.js","names":["normalizeOptionalString","normalizeOptionalString","STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS","STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS","STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH","STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS","STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS","STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS","STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS","STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS","STRATEGY_MAX_HEARTBEAT_INTERVAL_MS","STRATEGY_MIN_HEARTBEAT_INTERVAL_MS","STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS","STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS","STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS","STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS","STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS","STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS","sharedToErrorMessage"],"sources":["../../../packages/schemas/dist/schemas/daemon/route-catalog-cache.js","../src/config/account-context.ts","../src/auth/auth-guidance.ts","../src/local-service/state/catalog-sync-signal.ts","../src/config/profile-creation-capability.ts","../src/config/openmeld-profiles-api.ts","../src/local-service/core/constants.ts","../src/local-service/core/logger.ts","../src/local-service/state/daemon-device-id.ts"],"sourcesContent":["import { agentProfileIdSchema } from \"../protocol/profile.js\";\nimport { daemonServiceLaneSchema } from \"./service-contract.js\";\nimport { conversationPolicySchema } from \"./conversation-contract.js\";\nimport { runtimeAgentControllerConversationIdMappingSpecSchema, runtimeAgentControllerLaunchContractSchema, runtimeStreamingModeSchema, runtimeTransportModeSchema } from \"./controller-contract.js\";\nimport { skippedDaemonProfileSchema } from \"./control-plane.js\";\nimport { CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH } from \"./runtime-transport.js\";\nimport { agentControllerCollaborationModeSchema } from \"../agent-controller-collaboration-mode.js\";\nimport { agentControllerPermissionModeSchema } from \"../agent-controller-permission-mode.js\";\nimport { openCodePermissionConfigSchema } from \"../open-code-permission.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/schemas/daemon/route-catalog-cache.ts\nconst DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION = 4;\nconst DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME = \"openmeld-daemon-route-catalog-cache-v4\";\nconst cachedDaemonRouteConfigSchema = z$1.strictObject({\n\tagentControllerRef: z$1.string().trim().min(1),\n\tbindingId: z$1.string().trim().min(1).optional(),\n\tagentControllerCollaborationMode: agentControllerCollaborationModeSchema.optional(),\n\tagentControllerPermissionMode: agentControllerPermissionModeSchema.optional(),\n\tconfigurationRevision: z$1.number().int().positive().optional(),\n\tcontextIdMappingSpec: runtimeAgentControllerConversationIdMappingSpecSchema,\n\tconversationPolicy: conversationPolicySchema.optional(),\n\topenCodePermission: openCodePermissionConfigSchema.optional(),\n\tlaunchContract: runtimeAgentControllerLaunchContractSchema.nullable().optional(),\n\tprofileId: agentProfileIdSchema,\n\tstreamingMode: runtimeStreamingModeSchema,\n\ttransportMode: runtimeTransportModeSchema,\n\topenMeldServiceRuntimeId: z$1.string().trim().min(1).optional()\n});\nconst daemonRouteCatalogCacheBodySchema = z$1.strictObject({\n\tcachedAt: z$1.iso.datetime({ offset: true }),\n\truntimeContractEpoch: z$1.literal(CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH),\n\townerUserId: z$1.string().trim().min(1),\n\tlane: daemonServiceLaneSchema,\n\tserviceBundleId: z$1.string().trim().min(1),\n\tprofileIds: z$1.array(agentProfileIdSchema),\n\troutes: z$1.array(cachedDaemonRouteConfigSchema),\n\tskippedProfiles: z$1.array(skippedDaemonProfileSchema)\n});\nconst daemonRouteCatalogCacheSchema = z$1.discriminatedUnion(\"v\", [\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(2),\n\t\tschema: z$1.literal(\"openmeld-daemon-route-catalog-cache-v2\")\n\t}),\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(3),\n\t\tschema: z$1.literal(\"openmeld-daemon-route-catalog-cache-v3\")\n\t}),\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(4),\n\t\tschema: z$1.literal(DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME)\n\t})\n]).superRefine((value, ctx) => {\n\tconst routeIds = new Set(value.routes.map((route) => route.profileId));\n\tfor (const profileId of value.profileIds) if (!routeIds.has(profileId)) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"route catalog cache profileIds must match routes\",\n\t\tpath: [\"profileIds\"]\n\t});\n});\n//#endregion\nexport { DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME, DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION, cachedDaemonRouteConfigSchema, daemonRouteCatalogCacheSchema };\n\n//# sourceMappingURL=route-catalog-cache.js.map","import { createHash } from \"node:crypto\";\nimport type { StoredAuthSession } from \"./auth-session\";\nimport { normalizeAccountKey, type OpenMeldAccountKey } from \"./paths\";\n\ntype AuthSessionLike = Pick<\n StoredAuthSession,\n \"authBaseUrl\" | \"clientId\" | \"createdAt\" | \"user\"\n>;\n\nexport type OpenMeldAccountContext = {\n key: OpenMeldAccountKey;\n source: \"session\" | \"fallback\";\n authBaseUrl?: string;\n user?: {\n id?: string;\n email?: string;\n name?: string;\n };\n};\n\nexport function resolveOpenMeldAccountContext(input?: {\n session?: AuthSessionLike | null;\n}): OpenMeldAccountContext {\n const session = input?.session ?? null;\n if (!session) {\n return {\n key: normalizeAccountKey({}),\n source: \"fallback\",\n };\n }\n\n const normalizedBaseUrl = normalizeOptionalString(session.authBaseUrl);\n const hostKey = resolveHostKey(normalizedBaseUrl);\n const user = normalizeUser(session.user);\n const userKey =\n user?.id ??\n user?.email ??\n buildSessionScopedUserKey({\n authBaseUrl: normalizedBaseUrl,\n clientId: normalizeOptionalString(session.clientId),\n createdAt: normalizeOptionalString(session.createdAt),\n });\n const key = normalizeAccountKey({\n hostKey: hostKey ?? undefined,\n userKey,\n });\n\n return {\n key,\n source: \"session\",\n ...(normalizedBaseUrl ? { authBaseUrl: normalizedBaseUrl } : {}),\n ...(user ? { user } : {}),\n };\n}\n\nexport async function resolveCurrentOpenMeldAccountContext(): Promise<OpenMeldAccountContext> {\n const { getAuthSessionMetadata } = await import(\"./auth-session\");\n const session = await getAuthSessionMetadata().catch(() => null);\n return resolveOpenMeldAccountContext({ session });\n}\n\nfunction resolveHostKey(baseUrl: string | null): string | null {\n if (!baseUrl) {\n return null;\n }\n try {\n return new URL(baseUrl).host;\n } catch {\n return null;\n }\n}\n\nfunction buildSessionScopedUserKey(input: {\n authBaseUrl: string | null;\n clientId: string | null;\n createdAt: string | null;\n}): string | undefined {\n const seed = [input.authBaseUrl, input.clientId, input.createdAt]\n .filter((value) => typeof value === \"string\" && value.length > 0)\n .join(\"|\");\n if (!seed) {\n return undefined;\n }\n const digest = createHash(\"sha256\").update(seed, \"utf8\").digest(\"hex\");\n return `session-${digest.slice(0, 16)}`;\n}\n\nfunction normalizeUser(value: unknown): OpenMeldAccountContext[\"user\"] | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const id = normalizeOptionalString(record.id);\n const email = normalizeOptionalString(record.email);\n const name = normalizeOptionalString(record.name);\n if (!(id || email || name)) {\n return null;\n }\n return {\n ...(id ? { id } : {}),\n ...(email ? { email } : {}),\n ...(name ? { name } : {}),\n };\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import type { AuthSessionState } from \"../config/auth-session\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommands,\n} from \"../runtime/cli-entry-command\";\nimport type { DualViewGuideInput } from \"../runtime/dual-view-guide\";\n\nconst AUTH_MISMATCH_ERROR_RE =\n /session auth:\\s*(.+?),\\s*gateway:\\s*(.+?)\\);?\\s*run/u;\nconst AUTH_MISMATCH_SUMMARY_RE =\n /Current session is for\\s+(.+?),\\s+but.+?\\s+is\\s+(.+?)\\./u;\nconst AUTH_PROMPT_ACTION_RE =\n /^Sign in is required before (?<action>.+?)\\. What do you want to do\\?$/u;\n\nexport type AuthenticationGuidanceReason =\n | \"required\"\n | \"expired\"\n | \"invalid\"\n | \"revoked\"\n | \"unavailable\"\n | \"mismatch\";\n\nexport type AuthenticationGuidance = {\n reason: AuthenticationGuidanceReason;\n action: string | null;\n authBaseUrl: string | null;\n gatewayUrl: string | null;\n title: string;\n statusLabel: string;\n summary: string;\n promptNextStep: string;\n errorNextStep: string;\n commandErrorMessage: string;\n agentErrorMessage: string;\n};\n\nexport class OpenMeldAuthenticationError extends Error {\n readonly code = \"auth.authentication_required\";\n readonly guidance: AuthenticationGuidance;\n\n constructor(guidance: AuthenticationGuidance) {\n super(guidance.commandErrorMessage);\n this.name = \"OpenMeldAuthenticationError\";\n this.guidance = guidance;\n }\n}\n\nexport function createAuthenticationError(input: {\n reason: AuthenticationGuidanceReason;\n action?: string | null;\n authBaseUrl?: string | null;\n gatewayUrl?: string | null;\n}): OpenMeldAuthenticationError {\n return new OpenMeldAuthenticationError(resolveAuthenticationGuidance(input));\n}\n\nexport function resolveAuthenticationGuidance(input: {\n reason: AuthenticationGuidanceReason;\n action?: string | null;\n authBaseUrl?: string | null;\n gatewayUrl?: string | null;\n}): AuthenticationGuidance {\n const action = normalizeOptionalString(input.action);\n const authBaseUrl = normalizeOptionalString(input.authBaseUrl);\n const gatewayUrl = normalizeOptionalString(input.gatewayUrl);\n if (input.reason === \"mismatch\") {\n return {\n reason: input.reason,\n action,\n authBaseUrl,\n gatewayUrl,\n title: \"Wrong OpenMeld Environment\",\n statusLabel: \"wrong OpenMeld environment\",\n summary: \"This command is using a different OpenMeld environment.\",\n promptNextStep: \"Choose Sign in now to switch and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` for this OpenMeld environment, then retry.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n `authentication does not match current gateway (session auth: ${\n authBaseUrl ?? \"another OpenMeld environment\"\n }, gateway: ${gatewayUrl ?? \"the current OpenMeld gateway\"}); run \\`openmeld login\\` and retry`\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in is for a different OpenMeld environment; run `openmeld login` for this OpenMeld environment, then retry\"\n ),\n };\n }\n\n const requiredGuidance = resolveRequiredAuthenticationGuidance(input.reason);\n return {\n reason: input.reason,\n action,\n authBaseUrl,\n gatewayUrl,\n ...requiredGuidance,\n };\n}\n\nexport function buildCommandAuthenticationPromptMessage(\n action?: string\n): string {\n const normalizedAction = normalizeOptionalString(action);\n if (!normalizedAction) {\n return \"Sign in is required to continue. What do you want to do?\";\n }\n return `Sign in is required before ${normalizedAction}. What do you want to do?`;\n}\n\nexport function buildHumanAuthenticationCard(input: {\n guidance: AuthenticationGuidance;\n mode: \"prompt\" | \"error\";\n}): {\n title: string;\n rows: Array<{ label: string; value: string }>;\n} {\n const rows: Array<{ label: string; value: string }> = [];\n rows.push({\n label: \"What happened\",\n value: buildHumanAuthenticationStatusText(input.guidance),\n });\n\n rows.push({\n label: \"Next\",\n value:\n input.mode === \"prompt\"\n ? input.guidance.promptNextStep\n : input.guidance.errorNextStep,\n });\n\n return {\n title: input.guidance.title,\n rows,\n };\n}\n\nexport function buildAgentAuthenticationGuide(\n guidance: AuthenticationGuidance\n): DualViewGuideInput {\n if (guidance.reason === \"unavailable\") {\n return {\n summary: guidance.agentErrorMessage,\n humanSteps: [\n \"Retry the same command from a fresh CLI process.\",\n ...formatOpenMeldCliCommands([\n \"If it still fails, run `openmeld auth status --view agent` and share the diagnostics with the operator.\",\n ]),\n ],\n agentCommands: [\n \"Retry the same command once from a fresh CLI process.\",\n ...formatOpenMeldCliCommands([\n \"If it still fails, run `openmeld auth status --view agent` for diagnostics.\",\n ]),\n ],\n notes: buildAgentAuthenticationNotes(guidance),\n };\n }\n return {\n summary: guidance.agentErrorMessage,\n humanSteps: buildAgentAuthenticationHumanSteps(guidance),\n agentCommands: [\n \"Ask the operator to complete sign-in in a human terminal, then retry the same command.\",\n ],\n notes: buildAgentAuthenticationNotes(guidance),\n };\n}\n\nexport function buildAuthenticationStatusLabel(\n state: AuthSessionState | AuthenticationGuidanceReason\n): string {\n switch (state) {\n case \"valid\":\n return \"signed in\";\n case \"missing\":\n case \"required\":\n return \"sign in needed\";\n case \"expired\":\n return \"sign in expired\";\n case \"invalid\":\n return \"sign in needs refresh\";\n case \"revoked\":\n return \"sign in removed\";\n case \"mismatch\":\n return \"wrong OpenMeld environment\";\n case \"unavailable\":\n return \"saved sign-in unavailable\";\n default:\n return \"sign in needed\";\n }\n}\n\nexport function resolveAuthenticationReasonFromState(\n state: AuthSessionState\n): AuthenticationGuidanceReason | null {\n switch (state) {\n case \"missing\":\n return \"required\";\n case \"expired\":\n case \"invalid\":\n case \"revoked\":\n return state;\n default:\n return null;\n }\n}\n\nexport function isAuthenticationError(\n error: unknown\n): error is OpenMeldAuthenticationError {\n return error instanceof OpenMeldAuthenticationError;\n}\n\nexport function resolveAuthenticationGuidanceFromError(\n error: unknown\n): AuthenticationGuidance | null {\n if (error instanceof OpenMeldAuthenticationError) {\n return error.guidance;\n }\n\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n return resolveAuthenticationGuidanceFromMessage(message);\n}\n\nexport function resolveAuthenticationGuidanceFromMessage(\n message: string\n): AuthenticationGuidance | null {\n const normalizedMessage = String(message ?? \"\").trim();\n if (normalizedMessage.length === 0) {\n return null;\n }\n const loweredMessage = normalizedMessage.toLowerCase();\n\n const mismatch = AUTH_MISMATCH_ERROR_RE.exec(normalizedMessage);\n if (mismatch?.[1] && mismatch[2]) {\n return resolveAuthenticationGuidance({\n reason: \"mismatch\",\n authBaseUrl: mismatch[1],\n gatewayUrl: mismatch[2],\n });\n }\n\n if (normalizedMessage.includes(\"Current session is for\")) {\n const parsed = AUTH_MISMATCH_SUMMARY_RE.exec(normalizedMessage);\n return resolveAuthenticationGuidance({\n reason: \"mismatch\",\n authBaseUrl: parsed?.[1] ?? null,\n gatewayUrl: parsed?.[2] ?? null,\n });\n }\n\n if (loweredMessage.includes(\"auth session expired\")) {\n return resolveAuthenticationGuidance({\n reason: \"expired\",\n });\n }\n if (loweredMessage.includes(\"invalid local auth session\")) {\n return resolveAuthenticationGuidance({\n reason: \"invalid\",\n });\n }\n if (loweredMessage.includes(\"auth session revoked\")) {\n return resolveAuthenticationGuidance({\n reason: \"revoked\",\n });\n }\n if (\n loweredMessage.includes(\"saved sign-in is unavailable\") ||\n loweredMessage.includes(\"saved sign-in is temporarily unavailable\")\n ) {\n return resolveAuthenticationGuidance({\n reason: \"unavailable\",\n });\n }\n if (\n loweredMessage.includes(\"authentication required\") ||\n loweredMessage.includes(\"auth.unauthenticated\") ||\n loweredMessage.includes(\"auth.authentication_required\") ||\n loweredMessage.includes(\"sign-in required\")\n ) {\n return resolveAuthenticationGuidance({\n reason: \"required\",\n });\n }\n\n return null;\n}\n\nexport function extractAuthenticationPromptAction(\n promptMessage: string\n): string | null {\n const normalizedMessage = String(promptMessage ?? \"\").trim();\n if (normalizedMessage.length === 0) {\n return null;\n }\n const match = AUTH_PROMPT_ACTION_RE.exec(normalizedMessage);\n return normalizeOptionalString(match?.groups?.action);\n}\n\nfunction resolveRequiredAuthenticationGuidance(\n reason: Exclude<AuthenticationGuidanceReason, \"mismatch\">\n): Omit<\n AuthenticationGuidance,\n \"reason\" | \"action\" | \"authBaseUrl\" | \"gatewayUrl\"\n> {\n switch (reason) {\n case \"unavailable\":\n return {\n title: \"OpenMeld Sign-In Unavailable\",\n statusLabel: \"saved sign-in unavailable\",\n summary: \"OpenMeld could not read this device's saved sign-in.\",\n promptNextStep: formatInlineOpenMeldCliCommands(\n \"Retry the same command. If it still fails, run `openmeld auth status --view agent` for diagnostics.\"\n ),\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Retry the same command. If it still fails, run `openmeld auth status --view agent` for diagnostics.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"saved sign-in is unavailable; retry the same command once; if it still fails, run `openmeld auth status --view agent` for diagnostics\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"saved sign-in is unavailable; retry the same command once; if it still fails, run `openmeld auth status --view agent` for diagnostics\"\n ),\n };\n case \"expired\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in expired\",\n summary: \"Your OpenMeld sign-in has expired.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in expired; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in expired; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"invalid\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needs refresh\",\n summary: \"This device's OpenMeld sign-in is no longer valid.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"local sign-in is invalid; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"local sign-in is invalid; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"revoked\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in removed\",\n summary: \"Your OpenMeld sign-in was revoked.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in was revoked; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in was revoked; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"required\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needed\",\n summary: \"You're not signed in to OpenMeld yet.\",\n promptNextStep: \"Choose Sign in now to continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n default:\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needed\",\n summary: \"You're not signed in to OpenMeld yet.\",\n promptNextStep: \"Choose Sign in now to continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n }\n}\n\nfunction buildHumanAuthenticationStatusText(\n guidance: AuthenticationGuidance\n): string {\n const actionText = guidance.action\n ? ` before ${guidance.action}`\n : \" to continue\";\n if (guidance.reason === \"mismatch\") {\n return `Sign in to the right OpenMeld environment${actionText}.`;\n }\n if (guidance.reason === \"unavailable\") {\n return `OpenMeld could not read this device's saved sign-in${actionText}.`;\n }\n if (\n guidance.reason === \"expired\" ||\n guidance.reason === \"invalid\" ||\n guidance.reason === \"revoked\"\n ) {\n return `Sign in again${actionText}.`;\n }\n return `Sign in${actionText}.`;\n}\n\nfunction buildAgentAuthenticationHumanSteps(\n guidance: AuthenticationGuidance\n): string[] {\n const retryStep = guidance.action\n ? `Retry after sign-in, then continue ${guidance.action}.`\n : \"Retry the same command after sign-in finishes.\";\n const steps = [...formatOpenMeldCliCommands([\"openmeld login\"]), retryStep];\n if (guidance.reason === \"mismatch\" && guidance.gatewayUrl) {\n steps.splice(\n 1,\n 0,\n `Use the OpenMeld environment for ${guidance.gatewayUrl}.`\n );\n }\n return steps;\n}\n\nfunction buildAgentAuthenticationNotes(\n guidance: AuthenticationGuidance\n): string[] {\n const notes: string[] = [];\n if (guidance.action) {\n notes.push(`Blocked action: ${guidance.action}`);\n }\n if (guidance.authBaseUrl) {\n notes.push(`Current sign-in: ${guidance.authBaseUrl}`);\n }\n if (guidance.gatewayUrl) {\n notes.push(`Current gateway: ${guidance.gatewayUrl}`);\n }\n return notes;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { daemonRuntimeDataPath } from \"../../config/daemon-state\";\nimport { OPENMELD_HOME_ENV_KEY } from \"../../config/paths\";\n\nconst CATALOG_SYNC_SIGNAL_FILE = \"catalog-sync-signal.json\";\nconst CATALOG_SYNC_SIGNAL_SCHEMA = \"openmeld-daemon-catalog-sync-signal-v1\";\n\nexport type DaemonCatalogSyncSignal = {\n signalId?: string;\n updatedAt: string;\n updatedAtMs: number;\n reason: string;\n};\n\ntype DaemonCatalogSyncSignalFile = {\n signalId?: string;\n v: 1;\n schema: string;\n updatedAt: string;\n reason: string;\n};\n\nexport async function touchDaemonCatalogSyncSignal(input: {\n reason: string;\n rootDir?: string;\n}): Promise<void> {\n const now = new Date().toISOString();\n const runtimeDataPath = resolveDaemonRuntimeDataPath(input.rootDir);\n const signalPath = daemonCatalogSyncSignalPath(runtimeDataPath);\n await mkdir(runtimeDataPath, { recursive: true });\n const next: DaemonCatalogSyncSignalFile = {\n signalId: randomUUID(),\n v: 1,\n schema: CATALOG_SYNC_SIGNAL_SCHEMA,\n updatedAt: now,\n reason: normalizeReason(input.reason),\n };\n\n const tempPath = `${signalPath}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n try {\n await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, signalPath);\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nexport async function readDaemonCatalogSyncSignal(\n input: { rootDir?: string } = {}\n): Promise<DaemonCatalogSyncSignal | null> {\n const raw = await readFile(\n daemonCatalogSyncSignalPath(resolveDaemonRuntimeDataPath(input.rootDir)),\n \"utf8\"\n ).catch(() => null);\n if (!raw) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as Partial<DaemonCatalogSyncSignalFile>;\n if (parsed.v !== 1) {\n return null;\n }\n if (\n parsed.schema !== CATALOG_SYNC_SIGNAL_SCHEMA ||\n typeof parsed.updatedAt !== \"string\" ||\n parsed.updatedAt.trim().length === 0 ||\n typeof parsed.reason !== \"string\"\n ) {\n return null;\n }\n const updatedAt = parsed.updatedAt.trim();\n const updatedAtMs = Date.parse(updatedAt);\n if (!Number.isFinite(updatedAtMs) || updatedAtMs <= 0) {\n return null;\n }\n return {\n ...(typeof parsed.signalId === \"string\" && parsed.signalId.trim()\n ? { signalId: parsed.signalId.trim() }\n : {}),\n updatedAt,\n updatedAtMs,\n reason: normalizeReason(parsed.reason),\n };\n } catch {\n return null;\n }\n}\n\nfunction daemonCatalogSyncSignalPath(runtimeDataPath: string): string {\n return join(runtimeDataPath, CATALOG_SYNC_SIGNAL_FILE);\n}\n\nfunction resolveDaemonRuntimeDataPath(rootDir: string | undefined): string {\n if (!rootDir) {\n return daemonRuntimeDataPath();\n }\n return daemonRuntimeDataPath({\n env: { ...process.env, [OPENMELD_HOME_ENV_KEY]: rootDir },\n });\n}\n\nfunction normalizeReason(value: string): string {\n const normalized = value.trim();\n if (normalized.length > 0) {\n return normalized;\n }\n return \"local_state_changed\";\n}\n","import {\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_MESSAGE,\n} from \"@openmeld/schemas\";\n\nexport function assertAdditionalHumanProfileCreationEnabled(input: {\n additionalHumanProfileCreationEnabled: boolean;\n cause?: unknown;\n}): void {\n if (input.additionalHumanProfileCreationEnabled) {\n return;\n }\n throw Object.assign(\n new Error(ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_MESSAGE, {\n cause: input.cause,\n }),\n {\n code: ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n }\n );\n}\n","import {\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n authProfileManagedRoleSchema,\n profileCapabilitiesResponseSchema,\n profileErrorResponseSchema,\n} from \"@openmeld/schemas\";\nimport type { z } from \"zod/v4\";\nimport {\n createAuthenticationError,\n resolveAuthenticationReasonFromState,\n} from \"../auth/auth-guidance\";\nimport { touchDaemonCatalogSyncSignal } from \"../local-service/state/catalog-sync-signal\";\nimport { getAuthSessionState, type StoredAuthSession } from \"./auth-session\";\nimport { isLoopbackHostname } from \"./loopback-hostname\";\nimport { assertAdditionalHumanProfileCreationEnabled } from \"./profile-creation-capability\";\n\nexport type OpenMeldProfileKind = \"human\" | \"agent\" | \"system\";\nexport type OpenMeldProfileStatus = \"active\" | \"disabled\";\nexport type OpenMeldProfileManagedRole = z.infer<\n typeof authProfileManagedRoleSchema\n>;\nexport type OpenMeldProfileCapabilities = z.infer<\n typeof profileCapabilitiesResponseSchema\n>;\n\nexport type OpenMeldProfile = {\n openMeldProfileId: string;\n profileName: string;\n profileHandle: string;\n profileKind: OpenMeldProfileKind;\n isDefault?: boolean;\n status: OpenMeldProfileStatus;\n ownerUserId: string;\n ownerName?: string;\n source: string;\n managedRole?: OpenMeldProfileManagedRole | null;\n createdByUserId: string | null;\n defaultProjectId?: string | null;\n creationActorProfileId?: string | null;\n creatorProfileId?: string | null;\n lastUsedAt: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nconst VALIDATED_SESSION_CACHE_TTL_MS = 5000;\nconst DEFAULT_OPENMELD_PROFILES_API_TIMEOUT_MS = 10_000;\nconst LOOPBACK_OPENMELD_PROFILES_API_TIMEOUT_MS = 2500;\nconst PROFILE_HANDLE_PREFIX_RE = /^@+/;\n\nlet validatedSessionCache: {\n session: StoredAuthSession;\n validatedAtMs: number;\n} | null = null;\n\nexport function resetOpenMeldProfilesSessionCacheForTests(): void {\n validatedSessionCache = null;\n}\n\nexport function primeOpenMeldProfilesSessionCache(\n session: StoredAuthSession\n): void {\n validatedSessionCache = {\n session,\n validatedAtMs: Date.now(),\n };\n}\n\nclass AuthProfilesApiError extends Error {\n readonly status: number;\n readonly endpoint: string;\n readonly code: string | null;\n\n constructor(input: {\n message: string;\n status: number;\n endpoint: string;\n code?: string | null;\n }) {\n super(input.message);\n this.name = \"AuthProfilesApiError\";\n this.status = input.status;\n this.endpoint = input.endpoint;\n this.code = normalizeOptionalString(input.code);\n }\n}\n\nfunction isAuthProfilesApiError(error: unknown): error is AuthProfilesApiError {\n return error instanceof AuthProfilesApiError;\n}\n\nexport async function listOpenMeldProfiles(): Promise<OpenMeldProfile[]> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"GET\",\n path: \"/v1/profiles\",\n });\n\n const profiles = readArrayField(payload, \"profiles\");\n return profiles.map(parseOpenMeldProfileItem);\n}\n\nexport async function getOpenMeldProfileCapabilities(): Promise<OpenMeldProfileCapabilities> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"GET\",\n path: \"/v1/profiles/capabilities\",\n });\n const parsed = profileCapabilitiesResponseSchema.safeParse(payload);\n if (!parsed.success) {\n throw new Error(\"invalid profile capabilities payload\", {\n cause: parsed.error,\n });\n }\n return parsed.data;\n}\n\nexport async function resolveOpenMeldProfile(input: {\n openMeldProfileId?: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/resolve\",\n body: {\n ...(normalizeOptionalString(input.openMeldProfileId)\n ? {\n openMeldProfileId: normalizeOptionalString(input.openMeldProfileId),\n }\n : {}),\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n },\n });\n\n return parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n}\n\nexport async function resolveOpenMeldProfileByIdOrName(input: {\n profileIdentifier: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<OpenMeldProfile> {\n const profileIdentifier = normalizeOptionalString(input.profileIdentifier);\n if (!profileIdentifier) {\n throw new Error(\"profile identifier is required\");\n }\n\n try {\n return await resolveOpenMeldProfile({\n openMeldProfileId: profileIdentifier,\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n });\n } catch (idError) {\n const matched = await findOpenMeldProfileByNameOrHandle({\n profileIdentifier,\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n });\n if (matched.status === \"found\") {\n return matched.profile;\n }\n if (matched.status === \"ambiguous\") {\n throw new Error(\n `OpenMeld profile name is ambiguous: ${profileIdentifier}. Pass the profile ID instead.`\n );\n }\n if (isAuthProfilesApiError(idError)) {\n throw new Error(`OpenMeld profile not found: ${profileIdentifier}`);\n }\n throw idError;\n }\n}\n\nexport function createOpenMeldAgentProfile(input: {\n profileName: string;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n return createOpenMeldAgentProfileRequest({\n profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n}\n\nexport function ensureOpenMeldManagedAgentProfile(input: {\n profileName: string;\n managedRole: OpenMeldProfileManagedRole;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n return ensureOpenMeldManagedAgentProfileRequest({\n profileName,\n managedRole: input.managedRole,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n}\n\nexport async function createOpenMeldHumanProfile(input: {\n profileName: string;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n\n try {\n const capabilities = await getOpenMeldProfileCapabilities();\n assertAdditionalHumanProfileCreationEnabled(capabilities);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n error.code === ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE\n ) {\n throw error;\n }\n assertAdditionalHumanProfileCreationEnabled({\n additionalHumanProfileCreationEnabled: false,\n cause: error,\n });\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/humans\",\n body: {\n profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n },\n });\n\n const created = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_created\");\n return created;\n}\n\nexport async function updateOpenMeldProfile(input: {\n openMeldProfileId: string;\n profileName?: string;\n}): Promise<OpenMeldProfile> {\n const openMeldProfileId = normalizeOptionalString(input.openMeldProfileId);\n if (!openMeldProfileId) {\n throw new Error(\"openMeldProfileId is required\");\n }\n\n const profileName = normalizeOptionalString(input.profileName);\n const hasProfileName = Boolean(profileName);\n\n if (!hasProfileName) {\n throw new Error(\"profileName is required\");\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"PATCH\",\n path: `/v1/profiles/${encodeURIComponent(openMeldProfileId)}`,\n body: {\n ...(profileName ? { profileName } : {}),\n },\n });\n\n const updated = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_updated\");\n return updated;\n}\n\nexport async function deleteOpenMeldProfile(input: {\n openMeldProfileId: string;\n}): Promise<OpenMeldProfile> {\n const openMeldProfileId = normalizeOptionalString(input.openMeldProfileId);\n if (!openMeldProfileId) {\n throw new Error(\"openMeldProfileId is required\");\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"DELETE\",\n path: `/v1/profiles/${encodeURIComponent(openMeldProfileId)}`,\n });\n\n const deleted = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_deleted\");\n return deleted;\n}\n\nasync function requestOpenMeldProfilesApi(input: {\n method: \"GET\" | \"POST\" | \"DELETE\" | \"PATCH\";\n path: string;\n body?: Record<string, unknown>;\n}): Promise<Record<string, unknown>> {\n const session = await requireOpenMeldProfilesSession();\n const endpoint = toAuthEndpoint(session.authBaseUrl, input.path);\n const response = await fetch(endpoint, {\n method: input.method,\n headers: {\n Authorization: `${normalizeTokenType(session.tokenType)} ${session.accessToken}`,\n ...(input.body ? { \"content-type\": \"application/json\" } : {}),\n },\n ...(input.body ? { body: JSON.stringify(input.body) } : {}),\n signal: AbortSignal.timeout(resolveOpenMeldProfilesApiTimeoutMs(endpoint)),\n });\n\n const payload = await parseResponseJson(response);\n\n if (!response.ok) {\n const parsedError = profileErrorResponseSchema.safeParse(payload);\n const status = response.status;\n const code = parsedError.success ? parsedError.data.code : null;\n if (status === 401 || status === 403 || code === \"auth.unauthenticated\") {\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n }\n\n const message = resolveProfilesApiErrorMessage({\n payload: parsedError.success ? parsedError.data : payload,\n status,\n code,\n endpoint,\n });\n throw new AuthProfilesApiError({\n status,\n endpoint,\n code,\n message,\n });\n }\n\n const record = isRecord(payload) ? payload : {};\n const ok = readBooleanField(record, \"ok\");\n if (!ok) {\n const parsedError = profileErrorResponseSchema.safeParse(payload);\n const code = parsedError.success ? parsedError.data.code : null;\n throw new AuthProfilesApiError({\n status: response.status,\n endpoint,\n code,\n message: resolveProfilesApiErrorMessage({\n payload: parsedError.success ? parsedError.data : payload,\n status: response.status,\n code,\n endpoint,\n }),\n });\n }\n\n return record;\n}\n\nasync function createOpenMeldAgentProfileRequest(input: {\n profileName: string;\n creatorProfileId?: string;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/agents\",\n body: {\n profileName: input.profileName,\n ...(input.creatorProfileId\n ? { creatorProfileId: input.creatorProfileId }\n : {}),\n },\n });\n\n const created = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_created\");\n return created;\n}\n\nasync function ensureOpenMeldManagedAgentProfileRequest(input: {\n profileName: string;\n managedRole: OpenMeldProfileManagedRole;\n creatorProfileId?: string;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/agents/managed/ensure\",\n body: {\n profileName: input.profileName,\n managedRole: input.managedRole,\n ...(input.creatorProfileId\n ? { creatorProfileId: input.creatorProfileId }\n : {}),\n },\n });\n\n const ensured = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_ensured\");\n return ensured;\n}\n\nasync function requireOpenMeldProfilesSession(): Promise<StoredAuthSession> {\n const now = Date.now();\n if (\n validatedSessionCache &&\n now - validatedSessionCache.validatedAtMs <= VALIDATED_SESSION_CACHE_TTL_MS\n ) {\n const localState = await getAuthSessionState({\n validateRemote: false,\n });\n if (\n localState.state === \"valid\" &&\n localState.session &&\n isSameStoredAuthSession(localState.session, validatedSessionCache.session)\n ) {\n return validatedSessionCache.session;\n }\n validatedSessionCache = null;\n }\n\n const state = await getAuthSessionState({\n validateRemote: true,\n });\n\n switch (state.state) {\n case \"valid\": {\n if (!state.session) {\n throw new Error(\"auth session unavailable\");\n }\n validatedSessionCache = {\n session: state.session,\n validatedAtMs: now,\n };\n return state.session;\n }\n case \"missing\":\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n case \"expired\":\n case \"invalid\":\n case \"revoked\":\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: resolveAuthenticationReasonFromState(state.state) ?? \"required\",\n });\n default:\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n }\n}\n\nfunction resolveOpenMeldProfilesApiTimeoutMs(endpoint: string): number {\n const url = parseUrlOrNull(endpoint);\n if (url && isLoopbackHostname(url.hostname)) {\n return LOOPBACK_OPENMELD_PROFILES_API_TIMEOUT_MS;\n }\n return DEFAULT_OPENMELD_PROFILES_API_TIMEOUT_MS;\n}\n\nfunction parseUrlOrNull(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction isSameStoredAuthSession(\n a: StoredAuthSession,\n b: StoredAuthSession\n): boolean {\n return (\n a.authBaseUrl === b.authBaseUrl &&\n a.clientId === b.clientId &&\n a.tokenType === b.tokenType &&\n a.accessToken === b.accessToken &&\n (a.expiresAt ?? null) === (b.expiresAt ?? null)\n );\n}\n\nasync function emitRouteCatalogSync(reason: string): Promise<void> {\n await touchDaemonCatalogSyncSignal({ reason }).catch(() => undefined);\n}\n\nfunction parseOpenMeldProfileItem(value: unknown): OpenMeldProfile {\n const record = isRecord(value) ? value : {};\n\n const openMeldProfileId = readOptionalStringField(\n record,\n \"openMeldProfileId\"\n );\n if (!openMeldProfileId) {\n throw new Error(\"invalid profile payload: missing openMeldProfileId\");\n }\n\n const profileName = readRequiredStringField(record, \"profileName\");\n const profileHandle = readRequiredStringField(record, \"profileHandle\");\n const profileKind = readProfileKind(record, \"profileKind\");\n const isDefault = readOptionalBooleanField(record, \"isDefault\") ?? false;\n const status = readProfileStatus(record, \"status\");\n const ownerUserId = readRequiredStringField(record, \"ownerUserId\");\n const ownerName = readOptionalStringField(record, \"ownerName\") ?? undefined;\n const source = readRequiredStringField(record, \"source\");\n const managedRole = readOptionalManagedRoleField(record, \"managedRole\");\n const createdByUserId =\n readOptionalStringField(record, \"createdByUserId\") ?? null;\n const defaultProjectId = readOptionalStringField(record, \"defaultProjectId\");\n const creationActorProfileId =\n readOptionalStringField(record, \"creationActorProfileId\") ?? null;\n const creatorProfileId =\n readOptionalStringField(record, \"creatorProfileId\") ?? null;\n const lastUsedAt = readOptionalStringField(record, \"lastUsedAt\");\n const createdAt = readRequiredStringField(record, \"createdAt\");\n const updatedAt = readRequiredStringField(record, \"updatedAt\");\n\n return {\n openMeldProfileId,\n profileName,\n profileHandle,\n profileKind,\n isDefault,\n status,\n ownerUserId,\n ...(ownerName ? { ownerName } : {}),\n source,\n managedRole,\n createdByUserId,\n defaultProjectId,\n creationActorProfileId,\n creatorProfileId,\n lastUsedAt,\n createdAt,\n updatedAt,\n };\n}\n\nfunction readProfileKind(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileKind {\n const value = readRequiredStringField(input, field);\n if (value === \"human\" || value === \"agent\" || value === \"system\") {\n return value;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readProfileStatus(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileStatus {\n const value = readRequiredStringField(input, field);\n if (value === \"active\" || value === \"disabled\") {\n return value;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readOptionalManagedRoleField(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileManagedRole | null {\n const value = readOptionalStringField(input, field);\n if (!value) {\n return null;\n }\n const parsed = authProfileManagedRoleSchema.safeParse(value);\n if (parsed.success) {\n return parsed.data;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readRecordField(\n input: Record<string, unknown>,\n field: string\n): Record<string, unknown> {\n const value = input[field];\n if (isRecord(value)) {\n return value;\n }\n throw new Error(`invalid api payload: missing ${field}`);\n}\n\nfunction readArrayField(\n input: Record<string, unknown>,\n field: string\n): Record<string, unknown>[] {\n const value = input[field];\n if (!Array.isArray(value)) {\n throw new Error(`invalid api payload: missing ${field}`);\n }\n\n return value.filter(isRecord);\n}\n\nfunction readRequiredStringField(\n input: Record<string, unknown>,\n field: string\n): string {\n const value = normalizeOptionalString(input[field]);\n if (!value) {\n throw new Error(`invalid profile payload: missing ${field}`);\n }\n return value;\n}\n\nfunction readOptionalStringField(\n input: Record<string, unknown>,\n field: string\n): string | null {\n return normalizeOptionalString(input[field]);\n}\n\nfunction readBooleanField(\n input: Record<string, unknown>,\n field: string\n): boolean {\n return input[field] === true;\n}\n\nfunction readOptionalBooleanField(\n input: Record<string, unknown>,\n field: string\n): boolean | null {\n const value = input[field];\n if (typeof value === \"boolean\") {\n return value;\n }\n return null;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeTokenType(tokenType: string): string {\n const normalized = tokenType.trim();\n return normalized.length > 0 ? normalized : \"Bearer\";\n}\n\nfunction toAuthEndpoint(baseUrl: string, pathname: string): string {\n const url = new URL(baseUrl);\n url.pathname = pathname;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nasync function parseResponseJson(response: Response): Promise<unknown> {\n const raw = await response.text();\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return { message: raw };\n }\n}\n\nfunction extractApiErrorMessage(payload: unknown, status: number): string {\n const record = isRecord(payload) ? payload : {};\n const message =\n normalizeOptionalString(record.message) ??\n normalizeOptionalString(record.error_description) ??\n normalizeOptionalString(record.error);\n\n if (message) {\n return message;\n }\n\n return `request failed with status ${status}`;\n}\n\nfunction resolveProfilesApiErrorMessage(input: {\n payload: unknown;\n status: number;\n code: string | null;\n endpoint: string;\n}): string {\n const message = extractApiErrorMessage(input.payload, input.status);\n if (\n input.status === 500 &&\n input.code === \"profile.internal_error\" &&\n isLoopbackProfileEndpoint(input.endpoint)\n ) {\n return (\n \"internal error from local auth service; if profile schema changed, run \" +\n \"`pnpm db:migrate:dev` and retry.\"\n );\n }\n if (\n input.status === 500 &&\n input.code === \"profile.internal_error\" &&\n isHostedProfilesEndpoint(input.endpoint)\n ) {\n return (\n \"internal error from OpenMeld auth service while handling profile state. \" +\n \"If this works in `openmeld-dev` but fails in `openmeld`, the hosted auth deployment \" +\n \"is likely out of sync with the latest profile flow. Retry after the \" +\n \"production auth deploy/migration is updated.\"\n );\n }\n\n return message;\n}\n\nfunction normalizeProfileLookupKey(value: string): string {\n return value.trim().replace(PROFILE_HANDLE_PREFIX_RE, \"\").toLowerCase();\n}\n\nasync function findOpenMeldProfileByNameOrHandle(input: {\n profileIdentifier: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<\n | { status: \"found\"; profile: OpenMeldProfile }\n | { status: \"ambiguous\" }\n | { status: \"not_found\" }\n> {\n const lookupKey = normalizeProfileLookupKey(input.profileIdentifier);\n const matches = (await listOpenMeldProfiles()).filter((profile) => {\n if (input.profileKind && profile.profileKind !== input.profileKind) {\n return false;\n }\n return (\n normalizeProfileLookupKey(profile.profileName) === lookupKey ||\n normalizeProfileLookupKey(profile.profileHandle) === lookupKey\n );\n });\n\n if (matches.length === 1) {\n const profile = matches[0];\n if (profile) {\n return { status: \"found\", profile };\n }\n }\n if (matches.length > 1) {\n return { status: \"ambiguous\" };\n }\n return { status: \"not_found\" };\n}\n\nfunction isLoopbackProfileEndpoint(endpoint: string): boolean {\n const url = parseUrlOrNull(endpoint);\n return Boolean(\n url &&\n isLoopbackHostname(url.hostname) &&\n url.pathname.startsWith(\"/v1/profiles\")\n );\n}\n\nfunction isHostedProfilesEndpoint(endpoint: string): boolean {\n const url = parseUrlOrNull(endpoint);\n return Boolean(\n url &&\n !isLoopbackHostname(url.hostname) &&\n url.pathname.startsWith(\"/v1/profiles\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n CATALOG_SYNC_INTERVAL_MULTIPLIER as STRATEGY_CATALOG_SYNC_INTERVAL_MULTIPLIER,\n CATALOG_SYNC_RETRY_INTERVAL_MS as STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS,\n CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS as STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS,\n DAEMON_RUNTIME_CONTRACT_EPOCH as STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH,\n DAEMON_STREAM_CONNECT_TIMEOUT_MS as STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS,\n DAEMON_STREAM_KEEPALIVE_INTERVAL_MS as STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS,\n DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS as STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS,\n DEFAULT_HEARTBEAT_INTERVAL_MS as STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS,\n HEARTBEAT_RESPONSE_TIMEOUT_MS as STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS,\n MAX_CATALOG_SYNC_INTERVAL_MS as STRATEGY_MAX_CATALOG_SYNC_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS as STRATEGY_MAX_HEARTBEAT_INTERVAL_MS,\n MIN_CATALOG_SYNC_INTERVAL_MS as STRATEGY_MIN_CATALOG_SYNC_INTERVAL_MS,\n MIN_HEARTBEAT_INTERVAL_MS as STRATEGY_MIN_HEARTBEAT_INTERVAL_MS,\n PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS as STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS,\n PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS as STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS,\n REGISTER_RESPONSE_TIMEOUT_MS as STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS,\n RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS as STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS,\n RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS as STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS,\n RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS as STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS,\n} from \"../../strategy-constants\";\n\nexport const ADAPTIVE_HEARTBEAT_GROWTH_FACTOR = 1.35;\nexport const ADAPTIVE_HEARTBEAT_JITTER_RATIO = 0.1;\nexport const CATALOG_SYNC_INTERVAL_MULTIPLIER =\n STRATEGY_CATALOG_SYNC_INTERVAL_MULTIPLIER;\nexport const CATALOG_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS;\nexport const CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS =\n STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS;\nexport const DAEMON_RUNTIME_CONTRACT_EPOCH =\n STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH;\nexport const DAEMON_STREAM_CONNECT_TIMEOUT_MS =\n STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS;\nexport const DAEMON_STREAM_KEEPALIVE_INTERVAL_MS =\n STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS;\nexport const DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS =\n STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS;\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS =\n STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS;\nexport const HEARTBEAT_RESPONSE_TIMEOUT_MS =\n STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS;\nexport const MAX_CATALOG_SYNC_INTERVAL_MS =\n STRATEGY_MAX_CATALOG_SYNC_INTERVAL_MS;\nexport const MAX_HEARTBEAT_INTERVAL_MS = STRATEGY_MAX_HEARTBEAT_INTERVAL_MS;\nexport const MIN_CATALOG_SYNC_INTERVAL_MS =\n STRATEGY_MIN_CATALOG_SYNC_INTERVAL_MS;\nexport const MIN_HEARTBEAT_INTERVAL_MS = STRATEGY_MIN_HEARTBEAT_INTERVAL_MS;\nexport const PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS =\n STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS;\nexport const PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS;\nexport const REGISTER_RESPONSE_TIMEOUT_MS =\n STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS;\nexport const RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS =\n STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS;\nexport const RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS;\nexport const RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS =\n STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS;\nexport const DEFAULT_RECONNECT_DELAY_MS = 1000;\nexport const MAX_RECONNECT_DELAY_MS = 10_000;\nexport const HEARTBEAT_CONSECUTIVE_FAILURES_BEFORE_CLOSE = 3;\nexport const CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS = 5000;\nexport const CONTROLLED_SHUTDOWN_SOCKET_CLOSE_TIMEOUT_MS = 5000;\nexport const CONTROLLED_SHUTDOWN_REQUEST_TIMEOUT_MS = 15_000;\nexport const DAEMON_DEVICE_ID_FILE = \"daemon-device-id.txt\";\nexport const CONTEXT_STORE_FILE = \"daemon-context-map.json\";\nexport const LEDGER_DIR_NAME = \"openMeldDaemon-ledger\";\nexport const DAEMON_RUNTIME_CONTRACT_META_FILE = \"runtime-contract-meta.json\";\nexport const DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE =\n \"runtime-contract-repair-report.json\";\nexport const OPENMELD_CLI_NPX_COMMAND = \"npx -y openmeld@latest\";\nexport const SPACE_HISTORY_BOOTSTRAP_LIMIT = 200;\nexport const BOOTSTRAP_INJECTION_KEY_SEPARATOR = \"::\";\n","import { runtimeTransportModeSchema } from \"@openmeld/schemas\";\nimport type { RuntimeTransportMode } from \"@openmeld/schemas/types\";\nimport {\n sleep as sharedSleep,\n toErrorMessage as sharedToErrorMessage,\n} from \"@openmeld/utils\";\n\nimport type {\n RuntimeAgentControllerConversationIdMappingSpec,\n RuntimeAgentStreamingMode,\n RuntimeAgentTransportMode,\n} from \"../../config/runtime-config\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS,\n MIN_HEARTBEAT_INTERVAL_MS,\n} from \"./constants\";\n\nexport function emitRunLine(input: {\n code: string;\n payload?: unknown;\n presenter: Presenter;\n text: string;\n}): void {\n if (input.presenter.view === \"agent\") {\n input.presenter.data({\n code: input.code,\n payload: {\n message: input.text,\n ...(input.payload === undefined ? {} : { payload: input.payload }),\n },\n });\n return;\n }\n input.presenter.line({\n code: input.code,\n text: input.text,\n });\n}\n\nexport function clampInteger(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\nexport function normalizeHeartbeatIntervalMs(\n value: number | undefined\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return DEFAULT_HEARTBEAT_INTERVAL_MS;\n }\n return clampInteger(\n value,\n MIN_HEARTBEAT_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS\n );\n}\n\nexport function parseTransportMode(\n value: unknown\n): RuntimeAgentTransportMode | null {\n const parsed = runtimeTransportModeSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n}\n\nexport function parseStreamingMode(\n value: unknown\n): RuntimeAgentStreamingMode | null {\n if (value === \"final\" || value === \"stream\") {\n return value;\n }\n return null;\n}\n\nexport function parseRuntimeTransportMode(\n value: unknown\n): RuntimeTransportMode | null {\n return parseTransportMode(value);\n}\n\nexport function parseDispatchSourceProfileKind(\n value: unknown\n): \"agent\" | \"human\" | \"system\" | null {\n const normalized = normalizeText(value).toLowerCase();\n if (\n normalized === \"agent\" ||\n normalized === \"human\" ||\n normalized === \"system\"\n ) {\n return normalized;\n }\n return null;\n}\n\nexport function parseContextIdMappingSpec(\n value: unknown\n): RuntimeAgentControllerConversationIdMappingSpec | null {\n const record = asRecord(value);\n if (!record) {\n return null;\n }\n const sourceField = normalizeOptionalText(record.sourceField);\n const mappingVersion = normalizePositiveInteger(record.mappingVersion);\n if (!(sourceField && mappingVersion)) {\n return null;\n }\n return {\n sourceField,\n mappingVersion,\n };\n}\n\nexport function parsePositiveInteger(value: unknown): number | null {\n if (!(typeof value === \"number\" && Number.isInteger(value) && value > 0)) {\n return null;\n }\n return value;\n}\n\nexport function normalizeNonNegativeInteger(value: unknown): number | null {\n if (!(typeof value === \"number\" && Number.isInteger(value) && value >= 0)) {\n return null;\n }\n return value;\n}\n\nexport function normalizePositiveInteger(value: unknown): number | null {\n return parsePositiveInteger(value);\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\nexport function normalizeText(value: unknown): string {\n return String(value ?? \"\").trim();\n}\n\nexport function normalizeOptionalText(value: unknown): string | null {\n const normalized = normalizeText(value);\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function nowIsoString(): string {\n return new Date().toISOString();\n}\n\ntype DaemonLogField =\n | string\n | number\n | boolean\n | null\n | readonly (string | number | boolean | null)[];\n\nexport function warnDaemonEvent(\n eventName: string,\n fields: Record<string, DaemonLogField | undefined>\n): void {\n const definedFields = Object.fromEntries(\n Object.entries(fields).filter((entry) => entry[1] !== undefined)\n );\n console.warn(\n `${nowIsoString()} ${eventName} ${JSON.stringify(definedFields)}`\n );\n}\n\nexport const toErrorMessage: (error: unknown) => string = sharedToErrorMessage;\n\nexport const sleep: (delayMs: number) => Promise<void> = sharedSleep;\n\nexport function dirnamePath(path: string): string {\n const lastSlash = Math.max(path.lastIndexOf(\"/\"), path.lastIndexOf(\"\\\\\"));\n if (lastSlash <= 0) {\n return \".\";\n }\n return path.slice(0, lastSlash);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../../config/daemon-state\";\nimport { systemDir } from \"../../config/paths\";\nimport {\n CONTEXT_STORE_FILE,\n DAEMON_DEVICE_ID_FILE,\n DAEMON_RUNTIME_CONTRACT_META_FILE,\n DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE,\n LEDGER_DIR_NAME,\n} from \"../core/constants\";\nimport { dirnamePath, normalizeOptionalText } from \"../core/logger\";\nimport type { DaemonRuntimePaths, LedgerPaths } from \"../core/types\";\n\nexport function resolvePreferredDaemonDeviceId(input: {\n explicitDeviceId?: string;\n contractDeviceId?: string | null;\n}): string | undefined {\n return (\n normalizeOptionalText(input.explicitDeviceId) ??\n normalizeOptionalText(input.contractDeviceId) ??\n undefined\n );\n}\n\nexport async function resolveDaemonDeviceId(input: {\n deviceId?: string;\n deviceIdPath: string;\n shouldDiscardPersistedDeviceId?: (deviceId: string) => boolean;\n}): Promise<string> {\n const explicit = normalizeOptionalText(input.deviceId);\n if (explicit) {\n await persistDaemonDeviceIdIfNeeded({\n deviceId: explicit,\n deviceIdPath: input.deviceIdPath,\n });\n return explicit;\n }\n\n const persisted = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (\n persisted &&\n !(input.shouldDiscardPersistedDeviceId?.(persisted) ?? false)\n ) {\n return persisted;\n }\n\n const generated = randomUUID();\n await writeDaemonDeviceId({\n deviceId: generated,\n deviceIdPath: input.deviceIdPath,\n });\n return generated;\n}\n\nexport async function ensureDaemonRuntimePaths(): Promise<DaemonRuntimePaths> {\n const dataRootPath = join(daemonRuntimeRootPath(), \"data\");\n const contextStorePath = join(dataRootPath, CONTEXT_STORE_FILE);\n const deviceIdPath = daemonDeviceIdPath();\n const legacyDeviceIdPath = join(dataRootPath, DAEMON_DEVICE_ID_FILE);\n const ledgerRootPath = join(dataRootPath, LEDGER_DIR_NAME);\n await mkdir(dataRootPath, {\n recursive: true,\n });\n await mkdir(ledgerRootPath, {\n recursive: true,\n });\n await mkdir(dirnamePath(deviceIdPath), { recursive: true });\n await migrateLegacyDaemonDeviceId({ deviceIdPath, legacyDeviceIdPath });\n return {\n contractMetaPath: join(dataRootPath, DAEMON_RUNTIME_CONTRACT_META_FILE),\n contractRepairReportPath: join(\n dataRootPath,\n DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE\n ),\n contextStorePath,\n dataRootPath,\n deviceIdPath,\n ledgerRootPath,\n };\n}\n\nexport function daemonDeviceIdPath(): string {\n return join(systemDir(), DAEMON_DEVICE_ID_FILE);\n}\n\nexport function buildLedgerPaths(ledgerRootPath: string): LedgerPaths {\n return {\n backupStateFilePath: join(ledgerRootPath, \"state.backup.json\"),\n historyFilePath: join(ledgerRootPath, \"history.ndjson\"),\n historyTempFilePath: join(ledgerRootPath, \"history.tmp\"),\n rootDirPath: ledgerRootPath,\n stateFilePath: join(ledgerRootPath, \"state.json\"),\n stateTempFilePath: join(ledgerRootPath, \"state.tmp\"),\n };\n}\n\nasync function persistDaemonDeviceIdIfNeeded(input: {\n deviceId: string;\n deviceIdPath: string;\n}): Promise<void> {\n const persisted = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (persisted === input.deviceId) {\n return;\n }\n await writeDaemonDeviceId(input);\n}\n\nasync function writeDaemonDeviceId(input: {\n deviceId: string;\n deviceIdPath: string;\n}): Promise<void> {\n await mkdir(dirnamePath(input.deviceIdPath), { recursive: true });\n await writeFile(input.deviceIdPath, `${input.deviceId}\\n`, \"utf8\");\n}\n\nasync function migrateLegacyDaemonDeviceId(input: {\n deviceIdPath: string;\n legacyDeviceIdPath: string;\n}): Promise<void> {\n const current = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (current) {\n return;\n }\n const legacy = normalizeOptionalText(\n await readFile(input.legacyDeviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (!legacy) {\n return;\n }\n await writeDaemonDeviceId({\n deviceId: legac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AAiB,KAAK,gBAAgB,gBAAgB;EACtD,qBAAqB,KAAK,gBAAgB,aAAa;EACvD,aAAa;EACb,eAAe,KAAK,gBAAgB,YAAY;EAChD,mBAAmB,KAAK,gBAAgB,WAAW;CACrD;AACF;AAEA,eAAe,8BAA8B,OAG3B;CAIhB,IAHkB,sBAChB,MAAM,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,YAAY,EAAE,CAE/C,MAAM,MAAM,UACtB;CAEF,MAAM,oBAAoB,KAAK;AACjC;AAEA,eAAe,oBAAoB,OAGjB;CAChB,MAAM,MAAM,YAAY,MAAM,YAAY,GAAG,EAAE,WAAW,KAAK,CAAC;CAChE,MAAM,UAAU,MAAM,cAAc,GAAG,MAAM,SAAS,KAAK,MAAM;AACnE;AAEA,eAAe,4BAA4B,OAGzB;CAIhB,IAHgB,sBACd,MAAM,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,YAAY,EAAE,CAEjD,GACR;CAEF,MAAM,SAAS,sBACb,MAAM,SAAS,MAAM,oBAAoB,MAAM,CAAC,CAAC,YAAY,EAAE,CACjE;CACA,IAAI,CAAC,QACH;CAEF,MAAM,oBAAoB;EACxB,UAAU;EACV,cAAc,MAAM;CACtB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"daemon-device-id-YnLMx1kN.js","names":["normalizeOptionalString","normalizeOptionalString","STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS","STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS","STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH","STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS","STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS","STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS","STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS","STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS","STRATEGY_MAX_HEARTBEAT_INTERVAL_MS","STRATEGY_MIN_HEARTBEAT_INTERVAL_MS","STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS","STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS","STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS","STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS","STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS","STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS","sharedToErrorMessage"],"sources":["../../../packages/schemas/dist/schemas/daemon/route-catalog-cache.js","../src/config/account-context.ts","../src/auth/auth-guidance.ts","../src/local-service/state/catalog-sync-signal.ts","../src/config/profile-creation-capability.ts","../src/config/openmeld-profiles-api.ts","../src/local-service/core/constants.ts","../src/local-service/core/logger.ts","../src/local-service/state/daemon-device-id.ts"],"sourcesContent":["import { agentProfileIdSchema } from \"../protocol/profile.js\";\nimport { daemonServiceLaneSchema } from \"./service-contract.js\";\nimport { conversationPolicySchema } from \"./conversation-contract.js\";\nimport { runtimeAgentControllerConversationIdMappingSpecSchema, runtimeAgentControllerLaunchContractSchema, runtimeStreamingModeSchema, runtimeTransportModeSchema } from \"./controller-contract.js\";\nimport { skippedDaemonProfileSchema } from \"./control-plane.js\";\nimport { CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH } from \"./runtime-transport.js\";\nimport { agentControllerCollaborationModeSchema } from \"../agent-controller-collaboration-mode.js\";\nimport { agentControllerPermissionModeSchema } from \"../agent-controller-permission-mode.js\";\nimport { openCodePermissionConfigSchema } from \"../open-code-permission.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/schemas/daemon/route-catalog-cache.ts\nconst DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION = 4;\nconst DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME = \"openmeld-daemon-route-catalog-cache-v4\";\nconst cachedDaemonRouteConfigSchema = z$1.strictObject({\n\tagentControllerRef: z$1.string().trim().min(1),\n\tbindingId: z$1.string().trim().min(1).optional(),\n\tagentControllerCollaborationMode: agentControllerCollaborationModeSchema.optional(),\n\tagentControllerPermissionMode: agentControllerPermissionModeSchema.optional(),\n\tconfigurationRevision: z$1.number().int().positive().optional(),\n\tcontextIdMappingSpec: runtimeAgentControllerConversationIdMappingSpecSchema,\n\tconversationPolicy: conversationPolicySchema.optional(),\n\topenCodePermission: openCodePermissionConfigSchema.optional(),\n\tlaunchContract: runtimeAgentControllerLaunchContractSchema.nullable().optional(),\n\tprofileId: agentProfileIdSchema,\n\tstreamingMode: runtimeStreamingModeSchema,\n\ttransportMode: runtimeTransportModeSchema,\n\topenMeldServiceRuntimeId: z$1.string().trim().min(1).optional()\n});\nconst daemonRouteCatalogCacheBodySchema = z$1.strictObject({\n\tcachedAt: z$1.iso.datetime({ offset: true }),\n\truntimeContractEpoch: z$1.literal(CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH),\n\townerUserId: z$1.string().trim().min(1),\n\tlane: daemonServiceLaneSchema,\n\tserviceBundleId: z$1.string().trim().min(1),\n\tprofileIds: z$1.array(agentProfileIdSchema),\n\troutes: z$1.array(cachedDaemonRouteConfigSchema),\n\tskippedProfiles: z$1.array(skippedDaemonProfileSchema)\n});\nconst daemonRouteCatalogCacheSchema = z$1.discriminatedUnion(\"v\", [\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(2),\n\t\tschema: z$1.literal(\"openmeld-daemon-route-catalog-cache-v2\")\n\t}),\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(3),\n\t\tschema: z$1.literal(\"openmeld-daemon-route-catalog-cache-v3\")\n\t}),\n\tdaemonRouteCatalogCacheBodySchema.extend({\n\t\tv: z$1.literal(4),\n\t\tschema: z$1.literal(DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME)\n\t})\n]).superRefine((value, ctx) => {\n\tconst routeIds = new Set(value.routes.map((route) => route.profileId));\n\tfor (const profileId of value.profileIds) if (!routeIds.has(profileId)) ctx.addIssue({\n\t\tcode: \"custom\",\n\t\tmessage: \"route catalog cache profileIds must match routes\",\n\t\tpath: [\"profileIds\"]\n\t});\n});\n//#endregion\nexport { DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME, DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_VERSION, cachedDaemonRouteConfigSchema, daemonRouteCatalogCacheSchema };\n\n//# sourceMappingURL=route-catalog-cache.js.map","import { createHash } from \"node:crypto\";\nimport type { StoredAuthSession } from \"./auth-session\";\nimport { normalizeAccountKey, type OpenMeldAccountKey } from \"./paths\";\n\ntype AuthSessionLike = Pick<\n StoredAuthSession,\n \"authBaseUrl\" | \"clientId\" | \"createdAt\" | \"user\"\n>;\n\nexport type OpenMeldAccountContext = {\n key: OpenMeldAccountKey;\n source: \"session\" | \"fallback\";\n authBaseUrl?: string;\n user?: {\n id?: string;\n email?: string;\n name?: string;\n };\n};\n\nexport function resolveOpenMeldAccountContext(input?: {\n session?: AuthSessionLike | null;\n}): OpenMeldAccountContext {\n const session = input?.session ?? null;\n if (!session) {\n return {\n key: normalizeAccountKey({}),\n source: \"fallback\",\n };\n }\n\n const normalizedBaseUrl = normalizeOptionalString(session.authBaseUrl);\n const hostKey = resolveHostKey(normalizedBaseUrl);\n const user = normalizeUser(session.user);\n const userKey =\n user?.id ??\n user?.email ??\n buildSessionScopedUserKey({\n authBaseUrl: normalizedBaseUrl,\n clientId: normalizeOptionalString(session.clientId),\n createdAt: normalizeOptionalString(session.createdAt),\n });\n const key = normalizeAccountKey({\n hostKey: hostKey ?? undefined,\n userKey,\n });\n\n return {\n key,\n source: \"session\",\n ...(normalizedBaseUrl ? { authBaseUrl: normalizedBaseUrl } : {}),\n ...(user ? { user } : {}),\n };\n}\n\nexport async function resolveCurrentOpenMeldAccountContext(): Promise<OpenMeldAccountContext> {\n const { getAuthSessionMetadata } = await import(\"./auth-session\");\n const session = await getAuthSessionMetadata().catch(() => null);\n return resolveOpenMeldAccountContext({ session });\n}\n\nfunction resolveHostKey(baseUrl: string | null): string | null {\n if (!baseUrl) {\n return null;\n }\n try {\n return new URL(baseUrl).host;\n } catch {\n return null;\n }\n}\n\nfunction buildSessionScopedUserKey(input: {\n authBaseUrl: string | null;\n clientId: string | null;\n createdAt: string | null;\n}): string | undefined {\n const seed = [input.authBaseUrl, input.clientId, input.createdAt]\n .filter((value) => typeof value === \"string\" && value.length > 0)\n .join(\"|\");\n if (!seed) {\n return undefined;\n }\n const digest = createHash(\"sha256\").update(seed, \"utf8\").digest(\"hex\");\n return `session-${digest.slice(0, 16)}`;\n}\n\nfunction normalizeUser(value: unknown): OpenMeldAccountContext[\"user\"] | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const id = normalizeOptionalString(record.id);\n const email = normalizeOptionalString(record.email);\n const name = normalizeOptionalString(record.name);\n if (!(id || email || name)) {\n return null;\n }\n return {\n ...(id ? { id } : {}),\n ...(email ? { email } : {}),\n ...(name ? { name } : {}),\n };\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import type { AuthSessionState } from \"../config/auth-session\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommands,\n} from \"../runtime/cli-entry-command\";\nimport type { DualViewGuideInput } from \"../runtime/dual-view-guide\";\n\nconst AUTH_MISMATCH_ERROR_RE =\n /session auth:\\s*(.+?),\\s*gateway:\\s*(.+?)\\);?\\s*run/u;\nconst AUTH_MISMATCH_SUMMARY_RE =\n /Current session is for\\s+(.+?),\\s+but.+?\\s+is\\s+(.+?)\\./u;\nconst AUTH_PROMPT_ACTION_RE =\n /^Sign in is required before (?<action>.+?)\\. What do you want to do\\?$/u;\n\nexport type AuthenticationGuidanceReason =\n | \"required\"\n | \"expired\"\n | \"invalid\"\n | \"revoked\"\n | \"unavailable\"\n | \"mismatch\";\n\nexport type AuthenticationGuidance = {\n reason: AuthenticationGuidanceReason;\n action: string | null;\n authBaseUrl: string | null;\n gatewayUrl: string | null;\n title: string;\n statusLabel: string;\n summary: string;\n promptNextStep: string;\n errorNextStep: string;\n commandErrorMessage: string;\n agentErrorMessage: string;\n};\n\nexport class OpenMeldAuthenticationError extends Error {\n readonly code = \"auth.authentication_required\";\n readonly guidance: AuthenticationGuidance;\n\n constructor(guidance: AuthenticationGuidance) {\n super(guidance.commandErrorMessage);\n this.name = \"OpenMeldAuthenticationError\";\n this.guidance = guidance;\n }\n}\n\nexport function createAuthenticationError(input: {\n reason: AuthenticationGuidanceReason;\n action?: string | null;\n authBaseUrl?: string | null;\n gatewayUrl?: string | null;\n}): OpenMeldAuthenticationError {\n return new OpenMeldAuthenticationError(resolveAuthenticationGuidance(input));\n}\n\nexport function resolveAuthenticationGuidance(input: {\n reason: AuthenticationGuidanceReason;\n action?: string | null;\n authBaseUrl?: string | null;\n gatewayUrl?: string | null;\n}): AuthenticationGuidance {\n const action = normalizeOptionalString(input.action);\n const authBaseUrl = normalizeOptionalString(input.authBaseUrl);\n const gatewayUrl = normalizeOptionalString(input.gatewayUrl);\n if (input.reason === \"mismatch\") {\n return {\n reason: input.reason,\n action,\n authBaseUrl,\n gatewayUrl,\n title: \"Wrong OpenMeld Environment\",\n statusLabel: \"wrong OpenMeld environment\",\n summary: \"This command is using a different OpenMeld environment.\",\n promptNextStep: \"Choose Sign in now to switch and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` for this OpenMeld environment, then retry.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n `authentication does not match current gateway (session auth: ${\n authBaseUrl ?? \"another OpenMeld environment\"\n }, gateway: ${gatewayUrl ?? \"the current OpenMeld gateway\"}); run \\`openmeld login\\` and retry`\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in is for a different OpenMeld environment; run `openmeld login` for this OpenMeld environment, then retry\"\n ),\n };\n }\n\n const requiredGuidance = resolveRequiredAuthenticationGuidance(input.reason);\n return {\n reason: input.reason,\n action,\n authBaseUrl,\n gatewayUrl,\n ...requiredGuidance,\n };\n}\n\nexport function buildCommandAuthenticationPromptMessage(\n action?: string\n): string {\n const normalizedAction = normalizeOptionalString(action);\n if (!normalizedAction) {\n return \"Sign in is required to continue. What do you want to do?\";\n }\n return `Sign in is required before ${normalizedAction}. What do you want to do?`;\n}\n\nexport function buildHumanAuthenticationCard(input: {\n guidance: AuthenticationGuidance;\n mode: \"prompt\" | \"error\";\n}): {\n title: string;\n rows: Array<{ label: string; value: string }>;\n} {\n const rows: Array<{ label: string; value: string }> = [];\n rows.push({\n label: \"What happened\",\n value: buildHumanAuthenticationStatusText(input.guidance),\n });\n\n rows.push({\n label: \"Next\",\n value:\n input.mode === \"prompt\"\n ? input.guidance.promptNextStep\n : input.guidance.errorNextStep,\n });\n\n return {\n title: input.guidance.title,\n rows,\n };\n}\n\nexport function buildAgentAuthenticationGuide(\n guidance: AuthenticationGuidance\n): DualViewGuideInput {\n if (guidance.reason === \"unavailable\") {\n return {\n summary: guidance.agentErrorMessage,\n humanSteps: [\n \"Retry the same command from a fresh CLI process.\",\n ...formatOpenMeldCliCommands([\n \"If it still fails, run `openmeld auth status --view agent` and share the diagnostics with the operator.\",\n ]),\n ],\n agentCommands: [\n \"Retry the same command once from a fresh CLI process.\",\n ...formatOpenMeldCliCommands([\n \"If it still fails, run `openmeld auth status --view agent` for diagnostics.\",\n ]),\n ],\n notes: buildAgentAuthenticationNotes(guidance),\n };\n }\n return {\n summary: guidance.agentErrorMessage,\n humanSteps: buildAgentAuthenticationHumanSteps(guidance),\n agentCommands: [\n \"Ask the operator to complete sign-in in a human terminal, then retry the same command.\",\n ],\n notes: buildAgentAuthenticationNotes(guidance),\n };\n}\n\nexport function buildAuthenticationStatusLabel(\n state: AuthSessionState | AuthenticationGuidanceReason\n): string {\n switch (state) {\n case \"valid\":\n return \"signed in\";\n case \"missing\":\n case \"required\":\n return \"sign in needed\";\n case \"expired\":\n return \"sign in expired\";\n case \"invalid\":\n return \"sign in needs refresh\";\n case \"revoked\":\n return \"sign in removed\";\n case \"mismatch\":\n return \"wrong OpenMeld environment\";\n case \"unavailable\":\n return \"saved sign-in unavailable\";\n default:\n return \"sign in needed\";\n }\n}\n\nexport function resolveAuthenticationReasonFromState(\n state: AuthSessionState\n): AuthenticationGuidanceReason | null {\n switch (state) {\n case \"missing\":\n return \"required\";\n case \"expired\":\n case \"invalid\":\n case \"revoked\":\n return state;\n default:\n return null;\n }\n}\n\nexport function isAuthenticationError(\n error: unknown\n): error is OpenMeldAuthenticationError {\n return error instanceof OpenMeldAuthenticationError;\n}\n\nexport function resolveAuthenticationGuidanceFromError(\n error: unknown\n): AuthenticationGuidance | null {\n if (error instanceof OpenMeldAuthenticationError) {\n return error.guidance;\n }\n\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n return resolveAuthenticationGuidanceFromMessage(message);\n}\n\nexport function resolveAuthenticationGuidanceFromMessage(\n message: string\n): AuthenticationGuidance | null {\n const normalizedMessage = String(message ?? \"\").trim();\n if (normalizedMessage.length === 0) {\n return null;\n }\n const loweredMessage = normalizedMessage.toLowerCase();\n\n const mismatch = AUTH_MISMATCH_ERROR_RE.exec(normalizedMessage);\n if (mismatch?.[1] && mismatch[2]) {\n return resolveAuthenticationGuidance({\n reason: \"mismatch\",\n authBaseUrl: mismatch[1],\n gatewayUrl: mismatch[2],\n });\n }\n\n if (normalizedMessage.includes(\"Current session is for\")) {\n const parsed = AUTH_MISMATCH_SUMMARY_RE.exec(normalizedMessage);\n return resolveAuthenticationGuidance({\n reason: \"mismatch\",\n authBaseUrl: parsed?.[1] ?? null,\n gatewayUrl: parsed?.[2] ?? null,\n });\n }\n\n if (loweredMessage.includes(\"auth session expired\")) {\n return resolveAuthenticationGuidance({\n reason: \"expired\",\n });\n }\n if (loweredMessage.includes(\"invalid local auth session\")) {\n return resolveAuthenticationGuidance({\n reason: \"invalid\",\n });\n }\n if (loweredMessage.includes(\"auth session revoked\")) {\n return resolveAuthenticationGuidance({\n reason: \"revoked\",\n });\n }\n if (\n loweredMessage.includes(\"saved sign-in is unavailable\") ||\n loweredMessage.includes(\"saved sign-in is temporarily unavailable\")\n ) {\n return resolveAuthenticationGuidance({\n reason: \"unavailable\",\n });\n }\n if (\n loweredMessage.includes(\"authentication required\") ||\n loweredMessage.includes(\"auth.unauthenticated\") ||\n loweredMessage.includes(\"auth.authentication_required\") ||\n loweredMessage.includes(\"sign-in required\")\n ) {\n return resolveAuthenticationGuidance({\n reason: \"required\",\n });\n }\n\n return null;\n}\n\nexport function extractAuthenticationPromptAction(\n promptMessage: string\n): string | null {\n const normalizedMessage = String(promptMessage ?? \"\").trim();\n if (normalizedMessage.length === 0) {\n return null;\n }\n const match = AUTH_PROMPT_ACTION_RE.exec(normalizedMessage);\n return normalizeOptionalString(match?.groups?.action);\n}\n\nfunction resolveRequiredAuthenticationGuidance(\n reason: Exclude<AuthenticationGuidanceReason, \"mismatch\">\n): Omit<\n AuthenticationGuidance,\n \"reason\" | \"action\" | \"authBaseUrl\" | \"gatewayUrl\"\n> {\n switch (reason) {\n case \"unavailable\":\n return {\n title: \"OpenMeld Sign-In Unavailable\",\n statusLabel: \"saved sign-in unavailable\",\n summary: \"OpenMeld could not read this device's saved sign-in.\",\n promptNextStep: formatInlineOpenMeldCliCommands(\n \"Retry the same command. If it still fails, run `openmeld auth status --view agent` for diagnostics.\"\n ),\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Retry the same command. If it still fails, run `openmeld auth status --view agent` for diagnostics.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"saved sign-in is unavailable; retry the same command once; if it still fails, run `openmeld auth status --view agent` for diagnostics\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"saved sign-in is unavailable; retry the same command once; if it still fails, run `openmeld auth status --view agent` for diagnostics\"\n ),\n };\n case \"expired\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in expired\",\n summary: \"Your OpenMeld sign-in has expired.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in expired; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in expired; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"invalid\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needs refresh\",\n summary: \"This device's OpenMeld sign-in is no longer valid.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"local sign-in is invalid; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"local sign-in is invalid; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"revoked\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in removed\",\n summary: \"Your OpenMeld sign-in was revoked.\",\n promptNextStep: \"Choose Sign in now to refresh and continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` again to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in was revoked; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in was revoked; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n case \"required\":\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needed\",\n summary: \"You're not signed in to OpenMeld yet.\",\n promptNextStep: \"Choose Sign in now to continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n default:\n return {\n title: \"Sign In Needed\",\n statusLabel: \"sign in needed\",\n summary: \"You're not signed in to OpenMeld yet.\",\n promptNextStep: \"Choose Sign in now to continue.\",\n errorNextStep: formatInlineOpenMeldCliCommands(\n \"Run `openmeld login` to continue.\"\n ),\n commandErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login`\"\n ),\n agentErrorMessage: formatInlineOpenMeldCliCommands(\n \"sign-in required; run `openmeld login` in a human terminal, then retry\"\n ),\n };\n }\n}\n\nfunction buildHumanAuthenticationStatusText(\n guidance: AuthenticationGuidance\n): string {\n const actionText = guidance.action\n ? ` before ${guidance.action}`\n : \" to continue\";\n if (guidance.reason === \"mismatch\") {\n return `Sign in to the right OpenMeld environment${actionText}.`;\n }\n if (guidance.reason === \"unavailable\") {\n return `OpenMeld could not read this device's saved sign-in${actionText}.`;\n }\n if (\n guidance.reason === \"expired\" ||\n guidance.reason === \"invalid\" ||\n guidance.reason === \"revoked\"\n ) {\n return `Sign in again${actionText}.`;\n }\n return `Sign in${actionText}.`;\n}\n\nfunction buildAgentAuthenticationHumanSteps(\n guidance: AuthenticationGuidance\n): string[] {\n const retryStep = guidance.action\n ? `Retry after sign-in, then continue ${guidance.action}.`\n : \"Retry the same command after sign-in finishes.\";\n const steps = [...formatOpenMeldCliCommands([\"openmeld login\"]), retryStep];\n if (guidance.reason === \"mismatch\" && guidance.gatewayUrl) {\n steps.splice(\n 1,\n 0,\n `Use the OpenMeld environment for ${guidance.gatewayUrl}.`\n );\n }\n return steps;\n}\n\nfunction buildAgentAuthenticationNotes(\n guidance: AuthenticationGuidance\n): string[] {\n const notes: string[] = [];\n if (guidance.action) {\n notes.push(`Blocked action: ${guidance.action}`);\n }\n if (guidance.authBaseUrl) {\n notes.push(`Current sign-in: ${guidance.authBaseUrl}`);\n }\n if (guidance.gatewayUrl) {\n notes.push(`Current gateway: ${guidance.gatewayUrl}`);\n }\n return notes;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { daemonRuntimeDataPath } from \"../../config/daemon-state\";\nimport { OPENMELD_HOME_ENV_KEY } from \"../../config/paths\";\n\nconst CATALOG_SYNC_SIGNAL_FILE = \"catalog-sync-signal.json\";\nconst CATALOG_SYNC_SIGNAL_SCHEMA = \"openmeld-daemon-catalog-sync-signal-v1\";\n\nexport type DaemonCatalogSyncSignal = {\n signalId?: string;\n updatedAt: string;\n updatedAtMs: number;\n reason: string;\n};\n\ntype DaemonCatalogSyncSignalFile = {\n signalId?: string;\n v: 1;\n schema: string;\n updatedAt: string;\n reason: string;\n};\n\nexport async function touchDaemonCatalogSyncSignal(input: {\n reason: string;\n rootDir?: string;\n}): Promise<void> {\n const now = new Date().toISOString();\n const runtimeDataPath = resolveDaemonRuntimeDataPath(input.rootDir);\n const signalPath = daemonCatalogSyncSignalPath(runtimeDataPath);\n await mkdir(runtimeDataPath, { recursive: true });\n const next: DaemonCatalogSyncSignalFile = {\n signalId: randomUUID(),\n v: 1,\n schema: CATALOG_SYNC_SIGNAL_SCHEMA,\n updatedAt: now,\n reason: normalizeReason(input.reason),\n };\n\n const tempPath = `${signalPath}.tmp-${process.pid}-${Date.now()}`;\n let shouldCleanupTemp = true;\n try {\n await writeFile(tempPath, `${JSON.stringify(next, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, signalPath);\n shouldCleanupTemp = false;\n } finally {\n if (shouldCleanupTemp) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n }\n }\n}\n\nexport async function readDaemonCatalogSyncSignal(\n input: { rootDir?: string } = {}\n): Promise<DaemonCatalogSyncSignal | null> {\n const raw = await readFile(\n daemonCatalogSyncSignalPath(resolveDaemonRuntimeDataPath(input.rootDir)),\n \"utf8\"\n ).catch(() => null);\n if (!raw) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(raw) as Partial<DaemonCatalogSyncSignalFile>;\n if (parsed.v !== 1) {\n return null;\n }\n if (\n parsed.schema !== CATALOG_SYNC_SIGNAL_SCHEMA ||\n typeof parsed.updatedAt !== \"string\" ||\n parsed.updatedAt.trim().length === 0 ||\n typeof parsed.reason !== \"string\"\n ) {\n return null;\n }\n const updatedAt = parsed.updatedAt.trim();\n const updatedAtMs = Date.parse(updatedAt);\n if (!Number.isFinite(updatedAtMs) || updatedAtMs <= 0) {\n return null;\n }\n return {\n ...(typeof parsed.signalId === \"string\" && parsed.signalId.trim()\n ? { signalId: parsed.signalId.trim() }\n : {}),\n updatedAt,\n updatedAtMs,\n reason: normalizeReason(parsed.reason),\n };\n } catch {\n return null;\n }\n}\n\nfunction daemonCatalogSyncSignalPath(runtimeDataPath: string): string {\n return join(runtimeDataPath, CATALOG_SYNC_SIGNAL_FILE);\n}\n\nfunction resolveDaemonRuntimeDataPath(rootDir: string | undefined): string {\n if (!rootDir) {\n return daemonRuntimeDataPath();\n }\n return daemonRuntimeDataPath({\n env: { ...process.env, [OPENMELD_HOME_ENV_KEY]: rootDir },\n });\n}\n\nfunction normalizeReason(value: string): string {\n const normalized = value.trim();\n if (normalized.length > 0) {\n return normalized;\n }\n return \"local_state_changed\";\n}\n","import {\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_MESSAGE,\n} from \"@openmeld/schemas\";\n\nexport function assertAdditionalHumanProfileCreationEnabled(input: {\n additionalHumanProfileCreationEnabled: boolean;\n cause?: unknown;\n}): void {\n if (input.additionalHumanProfileCreationEnabled) {\n return;\n }\n throw Object.assign(\n new Error(ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_MESSAGE, {\n cause: input.cause,\n }),\n {\n code: ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n }\n );\n}\n","import {\n ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE,\n authProfileManagedRoleSchema,\n profileCapabilitiesResponseSchema,\n profileErrorResponseSchema,\n} from \"@openmeld/schemas\";\nimport type { z } from \"zod/v4\";\nimport {\n createAuthenticationError,\n resolveAuthenticationReasonFromState,\n} from \"../auth/auth-guidance\";\nimport { touchDaemonCatalogSyncSignal } from \"../local-service/state/catalog-sync-signal\";\nimport { getAuthSessionState, type StoredAuthSession } from \"./auth-session\";\nimport { isLoopbackHostname } from \"./loopback-hostname\";\nimport { assertAdditionalHumanProfileCreationEnabled } from \"./profile-creation-capability\";\n\nexport type OpenMeldProfileKind = \"human\" | \"agent\" | \"system\";\nexport type OpenMeldProfileStatus = \"active\" | \"disabled\";\nexport type OpenMeldProfileManagedRole = z.infer<\n typeof authProfileManagedRoleSchema\n>;\nexport type OpenMeldProfileCapabilities = z.infer<\n typeof profileCapabilitiesResponseSchema\n>;\n\nexport type OpenMeldProfile = {\n openMeldProfileId: string;\n profileName: string;\n profileHandle: string;\n profileKind: OpenMeldProfileKind;\n isDefault?: boolean;\n status: OpenMeldProfileStatus;\n ownerUserId: string;\n ownerName?: string;\n source: string;\n managedRole?: OpenMeldProfileManagedRole | null;\n createdByUserId: string | null;\n defaultProjectId?: string | null;\n creationActorProfileId?: string | null;\n creatorProfileId?: string | null;\n lastUsedAt: string | null;\n createdAt: string;\n updatedAt: string;\n};\n\nconst VALIDATED_SESSION_CACHE_TTL_MS = 5000;\nconst DEFAULT_OPENMELD_PROFILES_API_TIMEOUT_MS = 10_000;\nconst LOOPBACK_OPENMELD_PROFILES_API_TIMEOUT_MS = 2500;\nconst PROFILE_HANDLE_PREFIX_RE = /^@+/;\n\nlet validatedSessionCache: {\n session: StoredAuthSession;\n validatedAtMs: number;\n} | null = null;\n\nexport function resetOpenMeldProfilesSessionCacheForTests(): void {\n validatedSessionCache = null;\n}\n\nexport function primeOpenMeldProfilesSessionCache(\n session: StoredAuthSession\n): void {\n validatedSessionCache = {\n session,\n validatedAtMs: Date.now(),\n };\n}\n\nclass AuthProfilesApiError extends Error {\n readonly status: number;\n readonly endpoint: string;\n readonly code: string | null;\n\n constructor(input: {\n message: string;\n status: number;\n endpoint: string;\n code?: string | null;\n }) {\n super(input.message);\n this.name = \"AuthProfilesApiError\";\n this.status = input.status;\n this.endpoint = input.endpoint;\n this.code = normalizeOptionalString(input.code);\n }\n}\n\nfunction isAuthProfilesApiError(error: unknown): error is AuthProfilesApiError {\n return error instanceof AuthProfilesApiError;\n}\n\nexport async function listOpenMeldProfiles(): Promise<OpenMeldProfile[]> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"GET\",\n path: \"/v1/profiles\",\n });\n\n const profiles = readArrayField(payload, \"profiles\");\n return profiles.map(parseOpenMeldProfileItem);\n}\n\nexport async function getOpenMeldProfileCapabilities(): Promise<OpenMeldProfileCapabilities> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"GET\",\n path: \"/v1/profiles/capabilities\",\n });\n const parsed = profileCapabilitiesResponseSchema.safeParse(payload);\n if (!parsed.success) {\n throw new Error(\"invalid profile capabilities payload\", {\n cause: parsed.error,\n });\n }\n return parsed.data;\n}\n\nexport async function resolveOpenMeldProfile(input: {\n openMeldProfileId?: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/resolve\",\n body: {\n ...(normalizeOptionalString(input.openMeldProfileId)\n ? {\n openMeldProfileId: normalizeOptionalString(input.openMeldProfileId),\n }\n : {}),\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n },\n });\n\n return parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n}\n\nexport async function resolveOpenMeldProfileByIdOrName(input: {\n profileIdentifier: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<OpenMeldProfile> {\n const profileIdentifier = normalizeOptionalString(input.profileIdentifier);\n if (!profileIdentifier) {\n throw new Error(\"profile identifier is required\");\n }\n\n try {\n return await resolveOpenMeldProfile({\n openMeldProfileId: profileIdentifier,\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n });\n } catch (idError) {\n const matched = await findOpenMeldProfileByNameOrHandle({\n profileIdentifier,\n ...(input.profileKind ? { profileKind: input.profileKind } : {}),\n });\n if (matched.status === \"found\") {\n return matched.profile;\n }\n if (matched.status === \"ambiguous\") {\n throw new Error(\n `OpenMeld profile name is ambiguous: ${profileIdentifier}. Pass the profile ID instead.`\n );\n }\n if (isAuthProfilesApiError(idError)) {\n throw new Error(`OpenMeld profile not found: ${profileIdentifier}`);\n }\n throw idError;\n }\n}\n\nexport function createOpenMeldAgentProfile(input: {\n profileName: string;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n return createOpenMeldAgentProfileRequest({\n profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n}\n\nexport function ensureOpenMeldManagedAgentProfile(input: {\n profileName: string;\n managedRole: OpenMeldProfileManagedRole;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n return ensureOpenMeldManagedAgentProfileRequest({\n profileName,\n managedRole: input.managedRole,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n}\n\nexport async function createOpenMeldHumanProfile(input: {\n profileName: string;\n creatorProfileId?: string | null;\n}): Promise<OpenMeldProfile> {\n const profileName = normalizeOptionalString(input.profileName);\n const creatorProfileId =\n normalizeOptionalString(input.creatorProfileId) ?? undefined;\n if (!profileName) {\n throw new Error(\"profile name is required\");\n }\n\n try {\n const capabilities = await getOpenMeldProfileCapabilities();\n assertAdditionalHumanProfileCreationEnabled(capabilities);\n } catch (error) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n error.code === ADDITIONAL_HUMAN_PROFILE_CREATION_DISABLED_CODE\n ) {\n throw error;\n }\n assertAdditionalHumanProfileCreationEnabled({\n additionalHumanProfileCreationEnabled: false,\n cause: error,\n });\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/humans\",\n body: {\n profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n },\n });\n\n const created = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_created\");\n return created;\n}\n\nexport async function updateOpenMeldProfile(input: {\n openMeldProfileId: string;\n profileName?: string;\n}): Promise<OpenMeldProfile> {\n const openMeldProfileId = normalizeOptionalString(input.openMeldProfileId);\n if (!openMeldProfileId) {\n throw new Error(\"openMeldProfileId is required\");\n }\n\n const profileName = normalizeOptionalString(input.profileName);\n const hasProfileName = Boolean(profileName);\n\n if (!hasProfileName) {\n throw new Error(\"profileName is required\");\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"PATCH\",\n path: `/v1/profiles/${encodeURIComponent(openMeldProfileId)}`,\n body: {\n ...(profileName ? { profileName } : {}),\n },\n });\n\n const updated = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_updated\");\n return updated;\n}\n\nexport async function deleteOpenMeldProfile(input: {\n openMeldProfileId: string;\n}): Promise<OpenMeldProfile> {\n const openMeldProfileId = normalizeOptionalString(input.openMeldProfileId);\n if (!openMeldProfileId) {\n throw new Error(\"openMeldProfileId is required\");\n }\n\n const payload = await requestOpenMeldProfilesApi({\n method: \"DELETE\",\n path: `/v1/profiles/${encodeURIComponent(openMeldProfileId)}`,\n });\n\n const deleted = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_deleted\");\n return deleted;\n}\n\nasync function requestOpenMeldProfilesApi(input: {\n method: \"GET\" | \"POST\" | \"DELETE\" | \"PATCH\";\n path: string;\n body?: Record<string, unknown>;\n}): Promise<Record<string, unknown>> {\n const session = await requireOpenMeldProfilesSession();\n const endpoint = toAuthEndpoint(session.authBaseUrl, input.path);\n const response = await fetch(endpoint, {\n method: input.method,\n headers: {\n Authorization: `${normalizeTokenType(session.tokenType)} ${session.accessToken}`,\n ...(input.body ? { \"content-type\": \"application/json\" } : {}),\n },\n ...(input.body ? { body: JSON.stringify(input.body) } : {}),\n signal: AbortSignal.timeout(resolveOpenMeldProfilesApiTimeoutMs(endpoint)),\n });\n\n const payload = await parseResponseJson(response);\n\n if (!response.ok) {\n const parsedError = profileErrorResponseSchema.safeParse(payload);\n const status = response.status;\n const code = parsedError.success ? parsedError.data.code : null;\n if (status === 401 || status === 403 || code === \"auth.unauthenticated\") {\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n }\n\n const message = resolveProfilesApiErrorMessage({\n payload: parsedError.success ? parsedError.data : payload,\n status,\n code,\n endpoint,\n });\n throw new AuthProfilesApiError({\n status,\n endpoint,\n code,\n message,\n });\n }\n\n const record = isRecord(payload) ? payload : {};\n const ok = readBooleanField(record, \"ok\");\n if (!ok) {\n const parsedError = profileErrorResponseSchema.safeParse(payload);\n const code = parsedError.success ? parsedError.data.code : null;\n throw new AuthProfilesApiError({\n status: response.status,\n endpoint,\n code,\n message: resolveProfilesApiErrorMessage({\n payload: parsedError.success ? parsedError.data : payload,\n status: response.status,\n code,\n endpoint,\n }),\n });\n }\n\n return record;\n}\n\nasync function createOpenMeldAgentProfileRequest(input: {\n profileName: string;\n creatorProfileId?: string;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/agents\",\n body: {\n profileName: input.profileName,\n ...(input.creatorProfileId\n ? { creatorProfileId: input.creatorProfileId }\n : {}),\n },\n });\n\n const created = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_created\");\n return created;\n}\n\nasync function ensureOpenMeldManagedAgentProfileRequest(input: {\n profileName: string;\n managedRole: OpenMeldProfileManagedRole;\n creatorProfileId?: string;\n}): Promise<OpenMeldProfile> {\n const payload = await requestOpenMeldProfilesApi({\n method: \"POST\",\n path: \"/v1/profiles/agents/managed/ensure\",\n body: {\n profileName: input.profileName,\n managedRole: input.managedRole,\n ...(input.creatorProfileId\n ? { creatorProfileId: input.creatorProfileId }\n : {}),\n },\n });\n\n const ensured = parseOpenMeldProfileItem(readRecordField(payload, \"profile\"));\n await emitRouteCatalogSync(\"profile_ensured\");\n return ensured;\n}\n\nasync function requireOpenMeldProfilesSession(): Promise<StoredAuthSession> {\n const now = Date.now();\n if (\n validatedSessionCache &&\n now - validatedSessionCache.validatedAtMs <= VALIDATED_SESSION_CACHE_TTL_MS\n ) {\n const localState = await getAuthSessionState({\n validateRemote: false,\n });\n if (\n localState.state === \"valid\" &&\n localState.session &&\n isSameStoredAuthSession(localState.session, validatedSessionCache.session)\n ) {\n return validatedSessionCache.session;\n }\n validatedSessionCache = null;\n }\n\n const state = await getAuthSessionState({\n validateRemote: true,\n });\n\n switch (state.state) {\n case \"valid\": {\n if (!state.session) {\n throw new Error(\"auth session unavailable\");\n }\n validatedSessionCache = {\n session: state.session,\n validatedAtMs: now,\n };\n return state.session;\n }\n case \"missing\":\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n case \"expired\":\n case \"invalid\":\n case \"revoked\":\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: resolveAuthenticationReasonFromState(state.state) ?? \"required\",\n });\n default:\n validatedSessionCache = null;\n throw createAuthenticationError({\n reason: \"required\",\n });\n }\n}\n\nfunction resolveOpenMeldProfilesApiTimeoutMs(endpoint: string): number {\n const url = parseUrlOrNull(endpoint);\n if (url && isLoopbackHostname(url.hostname)) {\n return LOOPBACK_OPENMELD_PROFILES_API_TIMEOUT_MS;\n }\n return DEFAULT_OPENMELD_PROFILES_API_TIMEOUT_MS;\n}\n\nfunction parseUrlOrNull(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction isSameStoredAuthSession(\n a: StoredAuthSession,\n b: StoredAuthSession\n): boolean {\n return (\n a.authBaseUrl === b.authBaseUrl &&\n a.clientId === b.clientId &&\n a.tokenType === b.tokenType &&\n a.accessToken === b.accessToken &&\n (a.expiresAt ?? null) === (b.expiresAt ?? null)\n );\n}\n\nasync function emitRouteCatalogSync(reason: string): Promise<void> {\n await touchDaemonCatalogSyncSignal({ reason }).catch(() => undefined);\n}\n\nfunction parseOpenMeldProfileItem(value: unknown): OpenMeldProfile {\n const record = isRecord(value) ? value : {};\n\n const openMeldProfileId = readOptionalStringField(\n record,\n \"openMeldProfileId\"\n );\n if (!openMeldProfileId) {\n throw new Error(\"invalid profile payload: missing openMeldProfileId\");\n }\n\n const profileName = readRequiredStringField(record, \"profileName\");\n const profileHandle = readRequiredStringField(record, \"profileHandle\");\n const profileKind = readProfileKind(record, \"profileKind\");\n const isDefault = readOptionalBooleanField(record, \"isDefault\") ?? false;\n const status = readProfileStatus(record, \"status\");\n const ownerUserId = readRequiredStringField(record, \"ownerUserId\");\n const ownerName = readOptionalStringField(record, \"ownerName\") ?? undefined;\n const source = readRequiredStringField(record, \"source\");\n const managedRole = readOptionalManagedRoleField(record, \"managedRole\");\n const createdByUserId =\n readOptionalStringField(record, \"createdByUserId\") ?? null;\n const defaultProjectId = readOptionalStringField(record, \"defaultProjectId\");\n const creationActorProfileId =\n readOptionalStringField(record, \"creationActorProfileId\") ?? null;\n const creatorProfileId =\n readOptionalStringField(record, \"creatorProfileId\") ?? null;\n const lastUsedAt = readOptionalStringField(record, \"lastUsedAt\");\n const createdAt = readRequiredStringField(record, \"createdAt\");\n const updatedAt = readRequiredStringField(record, \"updatedAt\");\n\n return {\n openMeldProfileId,\n profileName,\n profileHandle,\n profileKind,\n isDefault,\n status,\n ownerUserId,\n ...(ownerName ? { ownerName } : {}),\n source,\n managedRole,\n createdByUserId,\n defaultProjectId,\n creationActorProfileId,\n creatorProfileId,\n lastUsedAt,\n createdAt,\n updatedAt,\n };\n}\n\nfunction readProfileKind(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileKind {\n const value = readRequiredStringField(input, field);\n if (value === \"human\" || value === \"agent\" || value === \"system\") {\n return value;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readProfileStatus(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileStatus {\n const value = readRequiredStringField(input, field);\n if (value === \"active\" || value === \"disabled\") {\n return value;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readOptionalManagedRoleField(\n input: Record<string, unknown>,\n field: string\n): OpenMeldProfileManagedRole | null {\n const value = readOptionalStringField(input, field);\n if (!value) {\n return null;\n }\n const parsed = authProfileManagedRoleSchema.safeParse(value);\n if (parsed.success) {\n return parsed.data;\n }\n throw new Error(`invalid profile payload: unsupported ${field}`);\n}\n\nfunction readRecordField(\n input: Record<string, unknown>,\n field: string\n): Record<string, unknown> {\n const value = input[field];\n if (isRecord(value)) {\n return value;\n }\n throw new Error(`invalid api payload: missing ${field}`);\n}\n\nfunction readArrayField(\n input: Record<string, unknown>,\n field: string\n): Record<string, unknown>[] {\n const value = input[field];\n if (!Array.isArray(value)) {\n throw new Error(`invalid api payload: missing ${field}`);\n }\n\n return value.filter(isRecord);\n}\n\nfunction readRequiredStringField(\n input: Record<string, unknown>,\n field: string\n): string {\n const value = normalizeOptionalString(input[field]);\n if (!value) {\n throw new Error(`invalid profile payload: missing ${field}`);\n }\n return value;\n}\n\nfunction readOptionalStringField(\n input: Record<string, unknown>,\n field: string\n): string | null {\n return normalizeOptionalString(input[field]);\n}\n\nfunction readBooleanField(\n input: Record<string, unknown>,\n field: string\n): boolean {\n return input[field] === true;\n}\n\nfunction readOptionalBooleanField(\n input: Record<string, unknown>,\n field: string\n): boolean | null {\n const value = input[field];\n if (typeof value === \"boolean\") {\n return value;\n }\n return null;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeTokenType(tokenType: string): string {\n const normalized = tokenType.trim();\n return normalized.length > 0 ? normalized : \"Bearer\";\n}\n\nfunction toAuthEndpoint(baseUrl: string, pathname: string): string {\n const url = new URL(baseUrl);\n url.pathname = pathname;\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nasync function parseResponseJson(response: Response): Promise<unknown> {\n const raw = await response.text();\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw);\n } catch {\n return { message: raw };\n }\n}\n\nfunction extractApiErrorMessage(payload: unknown, status: number): string {\n const record = isRecord(payload) ? payload : {};\n const message =\n normalizeOptionalString(record.message) ??\n normalizeOptionalString(record.error_description) ??\n normalizeOptionalString(record.error);\n\n if (message) {\n return message;\n }\n\n return `request failed with status ${status}`;\n}\n\nfunction resolveProfilesApiErrorMessage(input: {\n payload: unknown;\n status: number;\n code: string | null;\n endpoint: string;\n}): string {\n const message = extractApiErrorMessage(input.payload, input.status);\n if (\n input.status === 500 &&\n input.code === \"profile.internal_error\" &&\n isLoopbackProfileEndpoint(input.endpoint)\n ) {\n return (\n \"internal error from local auth service; if profile schema changed, run \" +\n \"`pnpm db:migrate:dev` and retry.\"\n );\n }\n if (\n input.status === 500 &&\n input.code === \"profile.internal_error\" &&\n isHostedProfilesEndpoint(input.endpoint)\n ) {\n return (\n \"internal error from OpenMeld auth service while handling profile state. \" +\n \"If this works in `openmeld-dev` but fails in `openmeld`, the hosted auth deployment \" +\n \"is likely out of sync with the latest profile flow. Retry after the \" +\n \"production auth deploy/migration is updated.\"\n );\n }\n\n return message;\n}\n\nfunction normalizeProfileLookupKey(value: string): string {\n return value.trim().replace(PROFILE_HANDLE_PREFIX_RE, \"\").toLowerCase();\n}\n\nasync function findOpenMeldProfileByNameOrHandle(input: {\n profileIdentifier: string;\n profileKind?: OpenMeldProfileKind;\n}): Promise<\n | { status: \"found\"; profile: OpenMeldProfile }\n | { status: \"ambiguous\" }\n | { status: \"not_found\" }\n> {\n const lookupKey = normalizeProfileLookupKey(input.profileIdentifier);\n const matches = (await listOpenMeldProfiles()).filter((profile) => {\n if (input.profileKind && profile.profileKind !== input.profileKind) {\n return false;\n }\n return (\n normalizeProfileLookupKey(profile.profileName) === lookupKey ||\n normalizeProfileLookupKey(profile.profileHandle) === lookupKey\n );\n });\n\n if (matches.length === 1) {\n const profile = matches[0];\n if (profile) {\n return { status: \"found\", profile };\n }\n }\n if (matches.length > 1) {\n return { status: \"ambiguous\" };\n }\n return { status: \"not_found\" };\n}\n\nfunction isLoopbackProfileEndpoint(endpoint: string): boolean {\n const url = parseUrlOrNull(endpoint);\n return Boolean(\n url &&\n isLoopbackHostname(url.hostname) &&\n url.pathname.startsWith(\"/v1/profiles\")\n );\n}\n\nfunction isHostedProfilesEndpoint(endpoint: string): boolean {\n const url = parseUrlOrNull(endpoint);\n return Boolean(\n url &&\n !isLoopbackHostname(url.hostname) &&\n url.pathname.startsWith(\"/v1/profiles\")\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n","import {\n CATALOG_SYNC_INTERVAL_MULTIPLIER as STRATEGY_CATALOG_SYNC_INTERVAL_MULTIPLIER,\n CATALOG_SYNC_RETRY_INTERVAL_MS as STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS,\n CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS as STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS,\n DAEMON_RUNTIME_CONTRACT_EPOCH as STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH,\n DAEMON_STREAM_CONNECT_TIMEOUT_MS as STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS,\n DAEMON_STREAM_KEEPALIVE_INTERVAL_MS as STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS,\n DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS as STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS,\n DEFAULT_HEARTBEAT_INTERVAL_MS as STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS,\n HEARTBEAT_RESPONSE_TIMEOUT_MS as STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS,\n MAX_CATALOG_SYNC_INTERVAL_MS as STRATEGY_MAX_CATALOG_SYNC_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS as STRATEGY_MAX_HEARTBEAT_INTERVAL_MS,\n MIN_CATALOG_SYNC_INTERVAL_MS as STRATEGY_MIN_CATALOG_SYNC_INTERVAL_MS,\n MIN_HEARTBEAT_INTERVAL_MS as STRATEGY_MIN_HEARTBEAT_INTERVAL_MS,\n PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS as STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS,\n PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS as STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS,\n REGISTER_RESPONSE_TIMEOUT_MS as STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS,\n RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS as STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS,\n RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS as STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS,\n RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS as STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS,\n} from \"../../strategy-constants\";\n\nexport const ADAPTIVE_HEARTBEAT_GROWTH_FACTOR = 1.35;\nexport const ADAPTIVE_HEARTBEAT_JITTER_RATIO = 0.1;\nexport const CATALOG_SYNC_INTERVAL_MULTIPLIER =\n STRATEGY_CATALOG_SYNC_INTERVAL_MULTIPLIER;\nexport const CATALOG_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_CATALOG_SYNC_RETRY_INTERVAL_MS;\nexport const CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS =\n STRATEGY_CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS;\nexport const DAEMON_RUNTIME_CONTRACT_EPOCH =\n STRATEGY_DAEMON_RUNTIME_CONTRACT_EPOCH;\nexport const DAEMON_STREAM_CONNECT_TIMEOUT_MS =\n STRATEGY_DAEMON_STREAM_CONNECT_TIMEOUT_MS;\nexport const DAEMON_STREAM_KEEPALIVE_INTERVAL_MS =\n STRATEGY_DAEMON_STREAM_KEEPALIVE_INTERVAL_MS;\nexport const DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS =\n STRATEGY_DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS;\nexport const DEFAULT_HEARTBEAT_INTERVAL_MS =\n STRATEGY_DEFAULT_HEARTBEAT_INTERVAL_MS;\nexport const HEARTBEAT_RESPONSE_TIMEOUT_MS =\n STRATEGY_HEARTBEAT_RESPONSE_TIMEOUT_MS;\nexport const MAX_CATALOG_SYNC_INTERVAL_MS =\n STRATEGY_MAX_CATALOG_SYNC_INTERVAL_MS;\nexport const MAX_HEARTBEAT_INTERVAL_MS = STRATEGY_MAX_HEARTBEAT_INTERVAL_MS;\nexport const MIN_CATALOG_SYNC_INTERVAL_MS =\n STRATEGY_MIN_CATALOG_SYNC_INTERVAL_MS;\nexport const MIN_HEARTBEAT_INTERVAL_MS = STRATEGY_MIN_HEARTBEAT_INTERVAL_MS;\nexport const PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS =\n STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS;\nexport const PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS;\nexport const REGISTER_RESPONSE_TIMEOUT_MS =\n STRATEGY_REGISTER_RESPONSE_TIMEOUT_MS;\nexport const RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS =\n STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS;\nexport const RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS =\n STRATEGY_RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS;\nexport const RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS =\n STRATEGY_RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS;\nexport const DEFAULT_RECONNECT_DELAY_MS = 1000;\nexport const MAX_RECONNECT_DELAY_MS = 10_000;\nexport const HEARTBEAT_CONSECUTIVE_FAILURES_BEFORE_CLOSE = 3;\nexport const CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS = 5000;\nexport const CONTROLLED_SHUTDOWN_SOCKET_CLOSE_TIMEOUT_MS = 5000;\nexport const CONTROLLED_SHUTDOWN_REQUEST_TIMEOUT_MS = 15_000;\nexport const DAEMON_DEVICE_ID_FILE = \"daemon-device-id.txt\";\nexport const CONTEXT_STORE_FILE = \"daemon-context-map.json\";\nexport const LEDGER_DIR_NAME = \"openMeldDaemon-ledger\";\nexport const DAEMON_RUNTIME_CONTRACT_META_FILE = \"runtime-contract-meta.json\";\nexport const DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE =\n \"runtime-contract-repair-report.json\";\nexport const OPENMELD_CLI_NPX_COMMAND = \"npx -y openmeld@latest\";\nexport const SPACE_HISTORY_BOOTSTRAP_LIMIT = 200;\nexport const BOOTSTRAP_INJECTION_KEY_SEPARATOR = \"::\";\n","import { runtimeTransportModeSchema } from \"@openmeld/schemas\";\nimport type { RuntimeTransportMode } from \"@openmeld/schemas/types\";\nimport {\n sleep as sharedSleep,\n toErrorMessage as sharedToErrorMessage,\n} from \"@openmeld/utils\";\n\nimport type {\n RuntimeAgentControllerConversationIdMappingSpec,\n RuntimeAgentStreamingMode,\n RuntimeAgentTransportMode,\n} from \"../../config/runtime-config\";\nimport type { Presenter } from \"../../runtime/presenter/types\";\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS,\n MIN_HEARTBEAT_INTERVAL_MS,\n} from \"./constants\";\n\nexport function emitRunLine(input: {\n code: string;\n payload?: unknown;\n presenter: Presenter;\n text: string;\n}): void {\n if (input.presenter.view === \"agent\") {\n input.presenter.data({\n code: input.code,\n payload: {\n message: input.text,\n ...(input.payload === undefined ? {} : { payload: input.payload }),\n },\n });\n return;\n }\n input.presenter.line({\n code: input.code,\n text: input.text,\n });\n}\n\nexport function clampInteger(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\nexport function normalizeHeartbeatIntervalMs(\n value: number | undefined\n): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n return DEFAULT_HEARTBEAT_INTERVAL_MS;\n }\n return clampInteger(\n value,\n MIN_HEARTBEAT_INTERVAL_MS,\n MAX_HEARTBEAT_INTERVAL_MS\n );\n}\n\nexport function parseTransportMode(\n value: unknown\n): RuntimeAgentTransportMode | null {\n const parsed = runtimeTransportModeSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n}\n\nexport function parseStreamingMode(\n value: unknown\n): RuntimeAgentStreamingMode | null {\n if (value === \"final\" || value === \"stream\") {\n return value;\n }\n return null;\n}\n\nexport function parseRuntimeTransportMode(\n value: unknown\n): RuntimeTransportMode | null {\n return parseTransportMode(value);\n}\n\nexport function parseDispatchSourceProfileKind(\n value: unknown\n): \"agent\" | \"human\" | \"system\" | null {\n const normalized = normalizeText(value).toLowerCase();\n if (\n normalized === \"agent\" ||\n normalized === \"human\" ||\n normalized === \"system\"\n ) {\n return normalized;\n }\n return null;\n}\n\nexport function parseContextIdMappingSpec(\n value: unknown\n): RuntimeAgentControllerConversationIdMappingSpec | null {\n const record = asRecord(value);\n if (!record) {\n return null;\n }\n const sourceField = normalizeOptionalText(record.sourceField);\n const mappingVersion = normalizePositiveInteger(record.mappingVersion);\n if (!(sourceField && mappingVersion)) {\n return null;\n }\n return {\n sourceField,\n mappingVersion,\n };\n}\n\nexport function parsePositiveInteger(value: unknown): number | null {\n if (!(typeof value === \"number\" && Number.isInteger(value) && value > 0)) {\n return null;\n }\n return value;\n}\n\nexport function normalizeNonNegativeInteger(value: unknown): number | null {\n if (!(typeof value === \"number\" && Number.isInteger(value) && value >= 0)) {\n return null;\n }\n return value;\n}\n\nexport function normalizePositiveInteger(value: unknown): number | null {\n return parsePositiveInteger(value);\n}\n\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\nexport function normalizeText(value: unknown): string {\n return String(value ?? \"\").trim();\n}\n\nexport function normalizeOptionalText(value: unknown): string | null {\n const normalized = normalizeText(value);\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function nowIsoString(): string {\n return new Date().toISOString();\n}\n\ntype DaemonLogField =\n | string\n | number\n | boolean\n | null\n | readonly (string | number | boolean | null)[];\n\nexport function warnDaemonEvent(\n eventName: string,\n fields: Record<string, DaemonLogField | undefined>\n): void {\n const definedFields = Object.fromEntries(\n Object.entries(fields).filter((entry) => entry[1] !== undefined)\n );\n console.warn(\n `${nowIsoString()} ${eventName} ${JSON.stringify(definedFields)}`\n );\n}\n\nexport const toErrorMessage: (error: unknown) => string = sharedToErrorMessage;\n\nexport const sleep: (delayMs: number) => Promise<void> = sharedSleep;\n\nexport function dirnamePath(path: string): string {\n const lastSlash = Math.max(path.lastIndexOf(\"/\"), path.lastIndexOf(\"\\\\\"));\n if (lastSlash <= 0) {\n return \".\";\n }\n return path.slice(0, lastSlash);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { daemonRuntimeRootPath } from \"../../config/daemon-state\";\nimport { systemDir } from \"../../config/paths\";\nimport {\n CONTEXT_STORE_FILE,\n DAEMON_DEVICE_ID_FILE,\n DAEMON_RUNTIME_CONTRACT_META_FILE,\n DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE,\n LEDGER_DIR_NAME,\n} from \"../core/constants\";\nimport { dirnamePath, normalizeOptionalText } from \"../core/logger\";\nimport type { DaemonRuntimePaths, LedgerPaths } from \"../core/types\";\n\nexport function resolvePreferredDaemonDeviceId(input: {\n explicitDeviceId?: string;\n contractDeviceId?: string | null;\n}): string | undefined {\n return (\n normalizeOptionalText(input.explicitDeviceId) ??\n normalizeOptionalText(input.contractDeviceId) ??\n undefined\n );\n}\n\nexport async function resolveDaemonDeviceId(input: {\n deviceId?: string;\n deviceIdPath: string;\n shouldDiscardPersistedDeviceId?: (deviceId: string) => boolean;\n}): Promise<string> {\n const explicit = normalizeOptionalText(input.deviceId);\n if (explicit) {\n await persistDaemonDeviceIdIfNeeded({\n deviceId: explicit,\n deviceIdPath: input.deviceIdPath,\n });\n return explicit;\n }\n\n const persisted = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (\n persisted &&\n !(input.shouldDiscardPersistedDeviceId?.(persisted) ?? false)\n ) {\n return persisted;\n }\n\n const generated = randomUUID();\n await writeDaemonDeviceId({\n deviceId: generated,\n deviceIdPath: input.deviceIdPath,\n });\n return generated;\n}\n\nexport async function ensureDaemonRuntimePaths(): Promise<DaemonRuntimePaths> {\n const dataRootPath = join(daemonRuntimeRootPath(), \"data\");\n const contextStorePath = join(dataRootPath, CONTEXT_STORE_FILE);\n const deviceIdPath = daemonDeviceIdPath();\n const legacyDeviceIdPath = join(dataRootPath, DAEMON_DEVICE_ID_FILE);\n const ledgerRootPath = join(dataRootPath, LEDGER_DIR_NAME);\n await mkdir(dataRootPath, {\n recursive: true,\n });\n await mkdir(ledgerRootPath, {\n recursive: true,\n });\n await mkdir(dirnamePath(deviceIdPath), { recursive: true });\n await migrateLegacyDaemonDeviceId({ deviceIdPath, legacyDeviceIdPath });\n return {\n contractMetaPath: join(dataRootPath, DAEMON_RUNTIME_CONTRACT_META_FILE),\n contractRepairReportPath: join(\n dataRootPath,\n DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE\n ),\n contextStorePath,\n dataRootPath,\n deviceIdPath,\n ledgerRootPath,\n };\n}\n\nexport function daemonDeviceIdPath(): string {\n return join(systemDir(), DAEMON_DEVICE_ID_FILE);\n}\n\nexport function buildLedgerPaths(ledgerRootPath: string): LedgerPaths {\n return {\n backupStateFilePath: join(ledgerRootPath, \"state.backup.json\"),\n historyFilePath: join(ledgerRootPath, \"history.ndjson\"),\n historyTempFilePath: join(ledgerRootPath, \"history.tmp\"),\n rootDirPath: ledgerRootPath,\n stateFilePath: join(ledgerRootPath, \"state.json\"),\n stateTempFilePath: join(ledgerRootPath, \"state.tmp\"),\n };\n}\n\nasync function persistDaemonDeviceIdIfNeeded(input: {\n deviceId: string;\n deviceIdPath: string;\n}): Promise<void> {\n const persisted = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (persisted === input.deviceId) {\n return;\n }\n await writeDaemonDeviceId(input);\n}\n\nasync function writeDaemonDeviceId(input: {\n deviceId: string;\n deviceIdPath: string;\n}): Promise<void> {\n await mkdir(dirnamePath(input.deviceIdPath), { recursive: true });\n await writeFile(input.deviceIdPath, `${input.deviceId}\\n`, \"utf8\");\n}\n\nasync function migrateLegacyDaemonDeviceId(input: {\n deviceIdPath: string;\n legacyDeviceIdPath: string;\n}): Promise<void> {\n const current = normalizeOptionalText(\n await readFile(input.deviceIdPath, \"utf8\").catch(() => \"\")\n );\n if (current) {\n return;\n }\n const legacy = normalizeOptionalText(\n await readFile(input.legacyDeviceIdPath, \"utf8\").catch(() => \"\")\n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AAO;EACL,qBAAqB,KAAK,gBAAgB,mBAAmB;EAC7D,iBAAiB,KAAK,gBAAgB,gBAAgB;EACtD,qBAAqB,KAAK,gBAAgB,aAAa;EACvD,aAAa;EACb,eAAe,KAAK,gBAAgB,YAAY;EAChD,mBAAmB,KAAK,gBAAgB,WAAW;CACrD;AACF;AAEA,eAAe,8BAA8B,OAG3B;CAIhB,IAHkB,sBAChB,MAAM,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,YAAY,EAAE,CAE/C,MAAM,MAAM,UACtB;CAEF,MAAM,oBAAoB,KAAK;AACjC;AAEA,eAAe,oBAAoB,OAGjB;CAChB,MAAM,MAAM,YAAY,MAAM,YAAY,GAAG,EAAE,WAAW,KAAK,CAAC;CAChE,MAAM,UAAU,MAAM,cAAc,GAAG,MAAM,SAAS,KAAK,MAAM;AACnE;AAEA,eAAe,4BAA4B,OAGzB;CAIhB,IAHgB,sBACd,MAAM,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,YAAY,EAAE,CAEjD,GACR;CAEF,MAAM,SAAS,sBACb,MAAM,SAAS,MAAM,oBAAoB,MAAM,CAAC,CAAC,YAAY,EAAE,CACjE;CACA,IAAI,CAAC,QACH;CAEF,MAAM,oBAAoB;EACxB,UAAU;EACV,cAAc,MAAM;CACtB,CAAC;AACH"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { G as legacyAccountProfileSpacesDir, J as normalizeOpenMeldProfileId, M as accountProfileSpaceCacheDir, ct as resolveOpenMeldEnvPreset, lt as resolveOpenMeldRootDir, v as resolveCliContextId } from "./lock-Bsl_ElWy.js";
|
|
4
|
-
import { Ri as computerFileAccessPolicyInputSchema, Vi as toCompatibleSpaceAddressingRequestWireValue, _i as agentActivityEventSchema, ai as spaceCreatorSchema, er as spaceEntryTargetSchema, gi as AGENT_ACTIVITY_PRESENCE_TTL_MAX_MS, zi as computerFileAccessPolicySchema } from "./dist-
|
|
5
|
-
import { $n as areAgentControllerInterfaceAccountsSame, Ct as resolveLocalProjectConnectionForPath, Kt as SPACE_ACTION_CONTEXT_GUIDANCE_LINES, Mn as buildTaskResultEnvelope, Tt as withAgentActivityLocalStateLock, Xt as buildDispatchReplyContextSummary, dt as isProjectBound, ft as listProjectBindings, jn as buildRuntimeWorkspaceFingerprint, kn as DaemonServiceRunError, mr as renderWorkingLanguagePrompt, nr as buildWorkingLanguagePromptPlan, pr as renderInformationProtectionPrompt, tr as buildInformationProtectionPromptPlan, ur as parseAgentControllerRef } from "./prepare-provider-runtime-
|
|
6
|
-
import { Cr as resolveSpaceMentionLabels, F as runtimeTransportRegisterSessionResponseSchema, Rn as MESSAGE_MENTION_TYPE_VALUES, S as runtimeTransportHeartbeatResponseSchema, Sr as resolveSingleSpaceMentionLabels, Un as normalizeMessageEnvelope, V as runtimeTransportSubmitTaskResultRequestSchema, Vn as getSpaceMessageAddressingRelationSupportForTargetKind, Wn as resolveMessageEnvelopeTargetField, Y as openMeldDaemonTaskResultPayloadSchema, _ as runtimeTransportDispatchRuntimeEvidenceRequestSchema, br as normalizeSpacePasswordText, g as runtimeTransportDispatchReasoningRequestSchema, h as runtimeTransportDispatchPreviewRequestSchema, i as daemonStreamFrameSchema, m as runtimeTransportDispatchPreviewEndRequestSchema, p as runtimeTransportDispatchLifecycleRequestSchema, u as runtimeTransportDispatchInteractionRequestSchema, v as runtimeTransportDispatchToolActivityRequestSchema, wt as sanitizeSignalTextPreview, zn as collectCanonicalMentionTextFragments } from "./runtime-transport-
|
|
4
|
+
import { Ri as computerFileAccessPolicyInputSchema, Vi as toCompatibleSpaceAddressingRequestWireValue, _i as agentActivityEventSchema, ai as spaceCreatorSchema, er as spaceEntryTargetSchema, gi as AGENT_ACTIVITY_PRESENCE_TTL_MAX_MS, zi as computerFileAccessPolicySchema } from "./dist-YPzkhLLp.js";
|
|
5
|
+
import { $n as areAgentControllerInterfaceAccountsSame, Ct as resolveLocalProjectConnectionForPath, Kt as SPACE_ACTION_CONTEXT_GUIDANCE_LINES, Mn as buildTaskResultEnvelope, Tt as withAgentActivityLocalStateLock, Xt as buildDispatchReplyContextSummary, dt as isProjectBound, ft as listProjectBindings, jn as buildRuntimeWorkspaceFingerprint, kn as DaemonServiceRunError, mr as renderWorkingLanguagePrompt, nr as buildWorkingLanguagePromptPlan, pr as renderInformationProtectionPrompt, tr as buildInformationProtectionPromptPlan, ur as parseAgentControllerRef } from "./prepare-provider-runtime-iA3g-8MS.js";
|
|
6
|
+
import { Cr as resolveSpaceMentionLabels, F as runtimeTransportRegisterSessionResponseSchema, Rn as MESSAGE_MENTION_TYPE_VALUES, S as runtimeTransportHeartbeatResponseSchema, Sr as resolveSingleSpaceMentionLabels, Un as normalizeMessageEnvelope, V as runtimeTransportSubmitTaskResultRequestSchema, Vn as getSpaceMessageAddressingRelationSupportForTargetKind, Wn as resolveMessageEnvelopeTargetField, Y as openMeldDaemonTaskResultPayloadSchema, _ as runtimeTransportDispatchRuntimeEvidenceRequestSchema, br as normalizeSpacePasswordText, g as runtimeTransportDispatchReasoningRequestSchema, h as runtimeTransportDispatchPreviewRequestSchema, i as daemonStreamFrameSchema, m as runtimeTransportDispatchPreviewEndRequestSchema, p as runtimeTransportDispatchLifecycleRequestSchema, u as runtimeTransportDispatchInteractionRequestSchema, v as runtimeTransportDispatchToolActivityRequestSchema, wt as sanitizeSignalTextPreview, zn as collectCanonicalMentionTextFragments } from "./runtime-transport-0F5E6So6.js";
|
|
7
7
|
import { D as normalizeOptionalWorkingDirectory, O as openMeldRuntimeProfileIdSchema } from "./control-plane-BDS63N7Y.js";
|
|
8
|
-
import { _ as toErrorMessage, a as asRecord, d as normalizeText, l as normalizeNonNegativeInteger$1, s as emitRunLine, st as resolveCurrentOpenMeldAccountContext, u as normalizeOptionalText$8 } from "./daemon-device-id-
|
|
9
|
-
import { _ as renderSpaceEntryBrief, c as buildCenterAgentRoleTemplateText, d as buildSpaceEntryBriefNeedMoreLine, f as buildSpaceWakeParticipantLines, h as deriveContinuity, l as buildCompactDispatchActionGuidanceLines, m as composeDispatchBrief, n as SPACE_COLLABORATION_CONTEXT_RULE, o as buildAgentFacingMentalModelLines, u as buildSpaceAgentIdentityLine, y as resolveSpacePublicationRequirement } from "./dist-
|
|
8
|
+
import { _ as toErrorMessage, a as asRecord, d as normalizeText, l as normalizeNonNegativeInteger$1, s as emitRunLine, st as resolveCurrentOpenMeldAccountContext, u as normalizeOptionalText$8 } from "./daemon-device-id-YnLMx1kN.js";
|
|
9
|
+
import { _ as renderSpaceEntryBrief, c as buildCenterAgentRoleTemplateText, d as buildSpaceEntryBriefNeedMoreLine, f as buildSpaceWakeParticipantLines, h as deriveContinuity, l as buildCompactDispatchActionGuidanceLines, m as composeDispatchBrief, n as SPACE_COLLABORATION_CONTEXT_RULE, o as buildAgentFacingMentalModelLines, u as buildSpaceAgentIdentityLine, y as resolveSpacePublicationRequirement } from "./dist-ChS52b_E.js";
|
|
10
10
|
import { d as createDefaultRuntimeAgentControllerSettings } from "./base-url-D7uE_xTo.js";
|
|
11
11
|
import { d as daemonDispatchJournalPath } from "./daemon-state-B44aq2nm.js";
|
|
12
12
|
import { a as formatOpenMeldCliTextBlock } from "./cli-entry-command-CR_9QU1i.js";
|
|
@@ -511,26 +511,46 @@ function prepareSpaceFileOnlySubmission(input) {
|
|
|
511
511
|
function normalizeAuthoredMentionsInTextOrder(input) {
|
|
512
512
|
const normalizedMentions = [];
|
|
513
513
|
let searchStart = 0;
|
|
514
|
+
let sharedAudienceRange = null;
|
|
514
515
|
for (const mention of input.mentions ?? []) {
|
|
515
516
|
const profileId = normalizeOptionalText$5(mention.profileId);
|
|
516
517
|
const text = normalizeOptionalText$5(mention.text);
|
|
517
518
|
if (!(profileId && text)) throw createSubmissionError("addressing.invalid_message_envelope", "Authored mention target must include a profile and visible mention text.");
|
|
518
519
|
if (!CANONICAL_MENTION_TYPES.has(mention.relation)) throw createSubmissionError("addressing.invalid_message_envelope", INVALID_MENTION_ACTION_GUIDANCE);
|
|
519
520
|
const declaredStart = mention.start;
|
|
520
|
-
const hasValidDeclaredStart =
|
|
521
|
+
const hasValidDeclaredStart = isDeclaredMentionStartValid({
|
|
522
|
+
declaredStart,
|
|
523
|
+
audience: mention.audience,
|
|
524
|
+
searchStart,
|
|
525
|
+
sharedAudienceRange,
|
|
526
|
+
text,
|
|
527
|
+
sourceText: input.text
|
|
528
|
+
});
|
|
521
529
|
if (declaredStart !== void 0 && !hasValidDeclaredStart) continue;
|
|
522
530
|
const start = hasValidDeclaredStart ? declaredStart : input.text.indexOf(text, searchStart);
|
|
523
531
|
if (start < 0) continue;
|
|
524
532
|
normalizedMentions.push({
|
|
533
|
+
...mention.audience ? { audience: mention.audience } : {},
|
|
525
534
|
profileId,
|
|
526
535
|
relation: mention.relation,
|
|
527
536
|
start,
|
|
528
537
|
text
|
|
529
538
|
});
|
|
530
539
|
searchStart = start + text.length;
|
|
540
|
+
sharedAudienceRange = mention.audience ? {
|
|
541
|
+
audience: mention.audience,
|
|
542
|
+
start,
|
|
543
|
+
text
|
|
544
|
+
} : null;
|
|
531
545
|
}
|
|
532
546
|
return normalizedMentions;
|
|
533
547
|
}
|
|
548
|
+
function isDeclaredMentionStartValid(input) {
|
|
549
|
+
const start = input.declaredStart;
|
|
550
|
+
if (!Number.isInteger(start)) return false;
|
|
551
|
+
const sharesAudienceRange = input.audience !== void 0 && input.sharedAudienceRange?.audience === input.audience && input.sharedAudienceRange.start === start && input.sharedAudienceRange.text === input.text;
|
|
552
|
+
return (start ?? -1) >= 0 && ((start ?? -1) >= input.searchStart || sharesAudienceRange) && input.sourceText.slice(start, (start ?? 0) + input.text.length) === input.text;
|
|
553
|
+
}
|
|
534
554
|
function emptyResolvedStructuredTargets() {
|
|
535
555
|
return {
|
|
536
556
|
mentionsInTextOrder: [],
|
|
@@ -6096,4 +6116,4 @@ function sendDaemonFrame(sink, input) {
|
|
|
6096
6116
|
//#endregion
|
|
6097
6117
|
export { emitDaemonDispatchJournalEvent as $, getSpaceAccessRequestContext as $t, readLastKnownAgentControllerAuthSnapshot as A, SpaceComposerSubmissionError as At, enqueueDispatchResultOutboxRecord as B, buildSpaceProfileAddPlan as Bt, readAgentActivityOutboxHealth as C, removeSpaceConfig as Ct, buildAgentControllerInterfaceKeeperKey as D, upsertSpaceConfig as Dt, readRecentAgentActivityHookStatus as E, updateSpaceLastSeenTs as Et, recordAgentControllerInterfaceProbeSuccess as F, buildSignalMessageReadProjection as Ft, resolveDispatchResultPayload as G, collectResolvedSpaceMentions as Gt, listDispatchResultOutboxPendingAcknowledgementKeys as H, buildSpaceRoundSignalPublication as Ht, recordAgentControllerUsageLimitsObservation as I, buildSignalReplyWorkflowProjection as It, sendDispatchPreviewEndFrame as J, createSpaceTargetCatalog as Jt, sendDispatchInteractionRequestFrame as K, createDispatchContinuationSpaceAccessContext as Kt, resolveAgentControllerCommandFingerprint as L, buildSpaceMemberAgentPresencePresentation as Lt, readLastSuccessfulAgentControllerInterfaceCheckAt as M, buildDispatchResultReplyWorkflowProjection as Mt, readReusableAgentControllerInterfaceSnapshot as N, buildPublicSpaceEntryUrl as Nt, consumeArmedAgentControllerInterfaceReprobe as O, writeSpaceCacheDeletionNoticeState as Ot, recordAgentControllerInterfaceProbeFailure as P, buildSignalIndex as Pt, sendDispatchToolActivityFrame as Q, getSpaceAccessPassword as Qt, resolveNextRuntimeAgentControllerReportSyncAtMs as R, buildSpaceMentionProfileIndex as Rt, deferAgentActivityOutbox as S, readSpaceRecentMentionProfileIds as St, removeProjectOutbox as T, toSpaceConfigListIntegrityError as Tt, waitForDispatchResultOutboxAcknowledgement as U, buildUpdatesReplyWorkflowProjection as Ut, flushDispatchResultOutbox as V, buildSpaceRoundReadProjection as Vt, buildFailedTaskResultPayload as W, closeMentionPickerState as Wt, sendDispatchReasoningFrame as X, extractMentionAuthoringPrefix as Xt, sendDispatchPreviewFrame as Y, enterRelationPickerState as Yt, sendDispatchRuntimeEvidenceFrame as Z, formatRemovedCcRelationMessage as Zt, drainAgentActivityHookInbox as _, OPENMELD_DISPATCH_RUNTIME_TARGET_PROFILE_ID_ENV as _n, isLocalSpaceStateCorruptResult as _t, resolveRegisterResponseFrame as a, listSpaceMentionSuggestions as an, isSameOrDescendantPath as at, AgentActivitySubmissionResultsMismatchError as b, readSpaceConfig as bt, scanLocalAgentActivity as c, prepareSpaceFileOnlySubmission as cn, buildDispatchPromptPlan as ct, resolveOpenCodeAuthPath as d, returnToTargetPickerState as dn, resolveBootstrapSpaceOwnerProfileId as dt, isRelationPickerState as en, readRecentDaemonDispatchJournalEvents as et, resolveOpenCodeDatabasePath as f, updateAuthoredMentionRanges as fn, resolveBootstrapTargetProfileContext as ft, readCodexSessionTitles as g, OPENMELD_DISPATCH_RUNTIME_MODE_ENV as gn, inspectSpaceCacheFile as gt, normalizeSharedSessionTitle as h, OPENMELD_DISPATCH_RUNTIME_DISPATCH_ID_ENV as hn, LocalSpaceStateIntegrityError as ht, resolveHeartbeatResponseFrame as i, listSpaceMentionRelationChoices as in, updateComputerFileAccessPolicy as it, readLastKnownAgentControllerUsageLimits as j, buildDispatchResultMessageReadProjection as jt, didAgentControllerCommandFingerprintRemainStable as k, writeSpaceRecentMentionProfileIds as kt, startAgentActivityTranscriptWatchers as l, resolveNextRecentMentionProfileIdsForQueuedText as ln, buildDispatchSessionTitle as lt, resolveObservedAgentActivityBinding as m, DISPATCH_SPACE_ACTION_CLI_FALLBACK_COMMAND as mn, projectSpaceProfileCache as mt, handleDaemonTransportFrame as n, isWakeClosingSystemNoticeType as nn, readComputerFileAccessPolicy as nt, sendDaemonFrame as o, openTargetPickerState as on, buildDispatchBootstrapTemplateFacts as ot, buildAgentActivityEvent as p, DISPATCH_OWNED_RUNTIME_MODE as pn, resolveDispatchMentionSourceContext as pt, sendDispatchLifecycleFrame as q, createSpaceMemberIdentityIndex as qt, parseDaemonFrame as r, listSpaceMemberDirectorySendTargets as rn, resolveComputerFileAccessStorePath as rt, collectObservedSessionWorkingDirectories as s, prepareSpaceComposerSubmission as sn, buildDispatchCorrelation as st, emitDaemonErrorFrame as t, isTargetPickerState as tn, ComputerFileAccessStoreError as tt, readOpenCodeSessionRows as u, resolveSpaceMemberAgentOwnerWakeDiagnosticsView as un, parseDispatchTask as ut, enqueueAgentActivityHookEvent as v, OPENMELD_SPACE_ACTION_TOOL_COMMAND_PATH_ENV as vn, listSpaceConfigs as vt, readDueAgentActivityOutbox as w, toLocalSpaceStateIntegrityError as wt, applyAgentActivitySubmissionResults as x, readSpaceLastSeenTs as xt, removeProjectInbox as y, OPENMELD_USER_FACING_CLI_COMMAND_ENV as yn, readSpaceCacheDeletionNoticeState as yt, acknowledgeDispatchResultOutboxRecord as z, buildSpaceMessageReadRelationSummary as zt };
|
|
6098
6118
|
|
|
6099
|
-
//# sourceMappingURL=daemon-frame-transport-
|
|
6119
|
+
//# sourceMappingURL=daemon-frame-transport-E-H3DjWA.js.map
|