openmeld 0.3.246 → 0.3.248

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/{add-me-membership-C7dYkfPz.js → add-me-membership-zSJAa2ET.js} +2 -2
  2. package/dist/{add-me-membership-C7dYkfPz.js.map → add-me-membership-zSJAa2ET.js.map} +1 -1
  3. package/dist/{agents-QisYIlFS.js → agents-DLjDbkLV.js} +10 -10
  4. package/dist/{agents-QisYIlFS.js.map → agents-DLjDbkLV.js.map} +1 -1
  5. package/dist/{api-client-foundation-CYbEdm9o.js → api-client-foundation-BZvzqIeX.js} +3 -3
  6. package/dist/{api-client-foundation-CYbEdm9o.js.map → api-client-foundation-BZvzqIeX.js.map} +1 -1
  7. package/dist/{api-client-foundation-B1aTRrIy.js → api-client-foundation-DE_UqE2s.js} +1 -1
  8. package/dist/auth-session-BOi-tZ2y.js +4 -0
  9. package/dist/{auth-session-JhILeJRO.js → auth-session-DywRZLBr.js} +4 -4
  10. package/dist/{auth-session-JhILeJRO.js.map → auth-session-DywRZLBr.js.map} +1 -1
  11. package/dist/{channel-C6tm9T7P.js → channel-40SR2b5S.js} +3 -3
  12. package/dist/{channel-C6tm9T7P.js.map → channel-40SR2b5S.js.map} +1 -1
  13. package/dist/{cloud-computer-J2tdcTPm.js → cloud-computer-BqFhsHhC.js} +4 -4
  14. package/dist/{cloud-computer-J2tdcTPm.js.map → cloud-computer-BqFhsHhC.js.map} +1 -1
  15. package/dist/{command-BXJ-OwBD.js → command-DBfu-GeG.js} +15 -15
  16. package/dist/{command-BXJ-OwBD.js.map → command-DBfu-GeG.js.map} +1 -1
  17. package/dist/{computer-connection-BKtrn0d2.js → computer-connection-CVyM42a0.js} +2 -2
  18. package/dist/{computer-connection-BKtrn0d2.js.map → computer-connection-CVyM42a0.js.map} +1 -1
  19. package/dist/{computer-connection-review-bUqNKi6q.js → computer-connection-review-B5qKu2C9.js} +5 -5
  20. package/dist/{computer-connection-review-bUqNKi6q.js.map → computer-connection-review-B5qKu2C9.js.map} +1 -1
  21. package/dist/{computer-disconnect-D_Apsn9P.js → computer-disconnect-BxhAjQQx.js} +7 -7
  22. package/dist/{computer-disconnect-D_Apsn9P.js.map → computer-disconnect-BxhAjQQx.js.map} +1 -1
  23. package/dist/{computer-setup-continuation-occq0LmS.js → computer-setup-continuation-V40ov5FS.js} +3 -3
  24. package/dist/{computer-setup-continuation-occq0LmS.js.map → computer-setup-continuation-V40ov5FS.js.map} +1 -1
  25. package/dist/{context-M7dvalCp.js → context-BEgBhfbb.js} +4 -4
  26. package/dist/{context-M7dvalCp.js.map → context-BEgBhfbb.js.map} +1 -1
  27. package/dist/{daemon-device-id-C3gKch4E.js → daemon-device-id-CmykIapy.js} +4 -4
  28. package/dist/{daemon-device-id-C3gKch4E.js.map → daemon-device-id-CmykIapy.js.map} +1 -1
  29. package/dist/{daemon-lifecycle-journal-CGUuJshv.js → daemon-lifecycle-journal-2dzGUSWU.js} +3 -3
  30. package/dist/{daemon-lifecycle-journal-CGUuJshv.js.map → daemon-lifecycle-journal-2dzGUSWU.js.map} +1 -1
  31. package/dist/{daemon-service-runtime-CktU3ER4.js → daemon-service-runtime-pECs8jVc.js} +2 -2
  32. package/dist/{daemon-service-runtime-CktU3ER4.js.map → daemon-service-runtime-pECs8jVc.js.map} +1 -1
  33. package/dist/{daemon-service-update-coordinator-D0-15tZW.js → daemon-service-update-coordinator-DJKBTEjx.js} +14 -14
  34. package/dist/daemon-service-update-coordinator-DJKBTEjx.js.map +1 -0
  35. package/dist/{dispatch-owned-runtime-gOluDX5_.js → dispatch-owned-runtime-QhxDRdNr.js} +191 -52
  36. package/dist/dispatch-owned-runtime-QhxDRdNr.js.map +1 -0
  37. package/dist/{dist-KibLweLD.js → dist-BQcUIyf6.js} +747 -529
  38. package/dist/dist-BQcUIyf6.js.map +1 -0
  39. package/dist/dist-C8M8nzJ2.js +4 -0
  40. package/dist/{dual-view-guide-catalog-0kSizTFt.js → dual-view-guide-catalog-DDsnLpIT.js} +3 -3
  41. package/dist/{dual-view-guide-catalog-0kSizTFt.js.map → dual-view-guide-catalog-DDsnLpIT.js.map} +1 -1
  42. package/dist/{elapsed-time-Bo1CJczC.js → elapsed-time-DTb6L36x.js} +3 -3
  43. package/dist/{elapsed-time-Bo1CJczC.js.map → elapsed-time-DTb6L36x.js.map} +1 -1
  44. package/dist/{entry-B11DkH2I.js → entry-B3w4ZTC5.js} +7 -7
  45. package/dist/{entry-B11DkH2I.js.map → entry-B3w4ZTC5.js.map} +1 -1
  46. package/dist/{installation-inventory-BZgQmVup.js → installation-inventory-CCkKix8R.js} +3 -3
  47. package/dist/{installation-inventory-BZgQmVup.js.map → installation-inventory-CCkKix8R.js.map} +1 -1
  48. package/dist/{installer-k2gOOs58.js → installer-BiZM-o_y.js} +2 -2
  49. package/dist/{installer-k2gOOs58.js.map → installer-BiZM-o_y.js.map} +1 -1
  50. package/dist/{meta-api-DruuiAx-.js → meta-api-9iqkG_MP.js} +5 -5
  51. package/dist/{meta-api-DruuiAx-.js.map → meta-api-9iqkG_MP.js.map} +1 -1
  52. package/dist/{open-code-permission-DHFJYc_o.js → open-code-permission-B5f1e5an.js} +2 -31
  53. package/dist/open-code-permission-B5f1e5an.js.map +1 -0
  54. package/dist/{openmeld-DUdN78WD.js → openmeld-C70uo4ON.js} +215 -71
  55. package/dist/openmeld-C70uo4ON.js.map +1 -0
  56. package/dist/{openmeld-maintenance-worker-DwkvZD0q.js → openmeld-maintenance-worker-BFPEm1rE.js} +9 -9
  57. package/dist/{openmeld-maintenance-worker-DwkvZD0q.js.map → openmeld-maintenance-worker-BFPEm1rE.js.map} +1 -1
  58. package/dist/{openmeld-tools-update-join-BNUIw_Lo.js → openmeld-tools-update-join-Bki3ugUW.js} +4 -4
  59. package/dist/{openmeld-tools-update-join-BNUIw_Lo.js.map → openmeld-tools-update-join-Bki3ugUW.js.map} +1 -1
  60. package/dist/openmeld.js +4 -4
  61. package/dist/{prepare-provider-runtime-_XRIioDp.js → prepare-provider-runtime-CWZOcEF7.js} +85 -23
  62. package/dist/prepare-provider-runtime-CWZOcEF7.js.map +1 -0
  63. package/dist/{prepare-session-executor-B5AjN0qz.js → prepare-session-executor-B8XSTQdx.js} +18 -18
  64. package/dist/{prepare-session-executor-B5AjN0qz.js.map → prepare-session-executor-B8XSTQdx.js.map} +1 -1
  65. package/dist/{process-channel-CTXWjlBP.js → process-channel-DLXPiGRF.js} +2 -2
  66. package/dist/{process-channel-CTXWjlBP.js.map → process-channel-DLXPiGRF.js.map} +1 -1
  67. package/dist/{runtime-DCBc6YOq.js → runtime-DzToUfqW.js} +115 -32
  68. package/dist/{runtime-DCBc6YOq.js.map → runtime-DzToUfqW.js.map} +1 -1
  69. package/dist/{runtime-agent-controller-reporting-submission-CGa3GGL6.js → runtime-agent-controller-reporting-submission-BszHi0S1.js} +8 -8
  70. package/dist/{runtime-agent-controller-reporting-submission-CGa3GGL6.js.map → runtime-agent-controller-reporting-submission-BszHi0S1.js.map} +1 -1
  71. package/dist/{runtime-transport-BzCp9hM3.js → runtime-transport-DFBYm5Re.js} +214 -21
  72. package/dist/runtime-transport-DFBYm5Re.js.map +1 -0
  73. package/dist/{service-BEH6-P8U.js → service-8EozP77B.js} +546 -21
  74. package/dist/service-8EozP77B.js.map +1 -0
  75. package/dist/{service-account-authorization-CtvSn02O.js → service-account-authorization-CqUcNoD1.js} +2 -2
  76. package/dist/{service-account-authorization-CtvSn02O.js.map → service-account-authorization-CqUcNoD1.js.map} +1 -1
  77. package/dist/{service-account-control-BUPiFEGo.js → service-account-control-CzPgo-Iy.js} +9 -9
  78. package/dist/{service-account-control-BUPiFEGo.js.map → service-account-control-CzPgo-Iy.js.map} +1 -1
  79. package/dist/{service-control-capabilities-PMvSlaJj.js → service-control-capabilities-C5hd37o9.js} +3 -3
  80. package/dist/{service-control-capabilities-PMvSlaJj.js.map → service-control-capabilities-C5hd37o9.js.map} +1 -1
  81. package/dist/{service-control-capabilities-D-Nhqqgo.js → service-control-capabilities-CcwdbQf3.js} +1 -1
  82. package/dist/{state-C_iJAzKh.js → state-Fskb-utn.js} +2 -2
  83. package/dist/{state-C_iJAzKh.js.map → state-Fskb-utn.js.map} +1 -1
  84. package/dist/{updates-api-s2-QB929.js → updates-api-JM7f1ZDQ.js} +43 -146
  85. package/dist/updates-api-JM7f1ZDQ.js.map +1 -0
  86. package/dist/{upgrade-JmhCNmvs.js → upgrade-CDW-7zvb.js} +8 -8
  87. package/dist/{upgrade-JmhCNmvs.js.map → upgrade-CDW-7zvb.js.map} +1 -1
  88. package/dist/upgrade-r6W5TzOo.js +4 -0
  89. package/package.json +11 -11
  90. package/skills/openmeld-cli/SKILL.md +2 -0
  91. package/skills/openmeld-cli/playbooks/computer.md +55 -0
  92. package/skills/openmeld-cli/playbooks/plugins.md +37 -0
  93. package/dist/auth-session-DUYOBXO3.js +0 -4
  94. package/dist/daemon-service-update-coordinator-D0-15tZW.js.map +0 -1
  95. package/dist/dispatch-owned-runtime-gOluDX5_.js.map +0 -1
  96. package/dist/dist-DMlKqjUf.js +0 -4
  97. package/dist/dist-KibLweLD.js.map +0 -1
  98. package/dist/open-code-permission-DHFJYc_o.js.map +0 -1
  99. package/dist/openmeld-DUdN78WD.js.map +0 -1
  100. package/dist/prepare-provider-runtime-_XRIioDp.js.map +0 -1
  101. package/dist/runtime-transport-BzCp9hM3.js.map +0 -1
  102. package/dist/service-BEH6-P8U.js.map +0 -1
  103. package/dist/updates-api-s2-QB929.js.map +0 -1
  104. package/dist/upgrade-Dikfgr8z.js +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"context-M7dvalCp.js","names":["normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString"],"sources":["../src/config/account-context.ts","../src/config/profile-view.ts","../src/auth/auth-guidance.ts","../src/config/openmeld-profile-selection.ts","../src/local-service/state/catalog-sync-signal.ts","../src/config/profile-creation-capability.ts","../src/config/openmeld-profiles-api.ts","../src/config/resolve-openmeld-profile.ts","../src/config/view-profile-key.ts","../src/runtime/context.ts"],"sourcesContent":["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 { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { resolveCurrentOpenMeldAccountContext } from \"./account-context\";\nimport {\n accountProfileViewPath,\n normalizeOpenMeldProfileId,\n type OpenMeldProfileId,\n} from \"./paths\";\n\nexport type ProfileDefaultView = \"auto\" | \"human\" | \"agent\";\n\ntype ProfileViewV1 = {\n v: 1;\n openMeldProfileId: OpenMeldProfileId;\n defaultView: Exclude<ProfileDefaultView, \"auto\">;\n updatedAt: string;\n};\n\ntype StoredProfileViewInput = Partial<ProfileViewV1> & { profile?: string };\n\ntype NormalizedStoredProfileView = {\n needsRewrite: boolean;\n payload: ProfileViewV1;\n};\n\nexport async function getProfileDefaultView(\n openMeldProfileId: string\n): Promise<ProfileDefaultView> {\n const normalizedOpenMeldProfileId =\n normalizeOpenMeldProfileId(openMeldProfileId);\n const path = await resolveAccountProfileViewPath(normalizedOpenMeldProfileId);\n const raw = await readFile(path, \"utf8\").catch(() => null);\n if (!raw) {\n return \"auto\";\n }\n\n try {\n const parsed = JSON.parse(raw) as StoredProfileViewInput;\n if (parsed.v !== 1) {\n return \"auto\";\n }\n const normalizedStoredProfileView = normalizeStoredProfileView(parsed);\n if (!normalizedStoredProfileView) {\n return \"auto\";\n }\n if (\n normalizedStoredProfileView.payload.openMeldProfileId !==\n normalizedOpenMeldProfileId\n ) {\n await rm(path, { force: true });\n return \"auto\";\n }\n if (normalizedStoredProfileView.needsRewrite) {\n await writeProfileViewFile(path, normalizedStoredProfileView.payload);\n }\n return normalizedStoredProfileView.payload.defaultView;\n } catch {\n return \"auto\";\n }\n}\n\nexport async function setProfileDefaultView(input: {\n openMeldProfileId: string;\n view: ProfileDefaultView;\n}): Promise<void> {\n const openMeldProfileId = normalizeOpenMeldProfileId(input.openMeldProfileId);\n const path = await resolveAccountProfileViewPath(openMeldProfileId);\n\n if (input.view === \"auto\") {\n await rm(path, { force: true });\n return;\n }\n\n await writeProfileViewFile(path, {\n v: 1,\n openMeldProfileId,\n defaultView: input.view,\n updatedAt: new Date().toISOString(),\n });\n}\n\nasync function writeProfileViewFile(\n path: string,\n payload: ProfileViewV1\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n try {\n await rename(tempPath, path);\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nasync function resolveAccountProfileViewPath(\n openMeldProfileId: OpenMeldProfileId\n): Promise<string> {\n const accountContext = await resolveCurrentOpenMeldAccountContext();\n return accountProfileViewPath(accountContext.key, openMeldProfileId);\n}\n\nfunction normalizeStoredProfileView(\n input: StoredProfileViewInput\n): NormalizedStoredProfileView | null {\n const openMeldProfileId = normalizeOptionalOpenMeldProfileId(\n input.openMeldProfileId\n );\n const legacyProfile = normalizeOptionalOpenMeldProfileId(input.profile);\n const resolvedOpenMeldProfileId = openMeldProfileId ?? legacyProfile;\n if (!resolvedOpenMeldProfileId) {\n return null;\n }\n const defaultView = normalizeStoredDefaultView(input.defaultView);\n if (!defaultView) {\n return null;\n }\n const updatedAt = normalizeStoredUpdatedAt(input.updatedAt);\n return {\n needsRewrite:\n openMeldProfileId !== resolvedOpenMeldProfileId ||\n input.profile !== undefined ||\n input.updatedAt !== updatedAt,\n payload: {\n v: 1,\n openMeldProfileId: resolvedOpenMeldProfileId,\n defaultView,\n updatedAt,\n },\n };\n}\n\nfunction normalizeStoredDefaultView(\n value: unknown\n): Exclude<ProfileDefaultView, \"auto\"> | null {\n if (value === \"human\" || value === \"agent\") {\n return value;\n }\n return null;\n}\n\nfunction normalizeStoredUpdatedAt(value: unknown): string {\n if (typeof value === \"string\") {\n const trimmedValue = value.trim();\n if (trimmedValue.length > 0 && !Number.isNaN(Date.parse(trimmedValue))) {\n return trimmedValue;\n }\n }\n return new Date().toISOString();\n}\n\nfunction normalizeOptionalOpenMeldProfileId(\n value: unknown\n): OpenMeldProfileId | null {\n if (typeof value !== \"string\") {\n return null;\n }\n try {\n return normalizeOpenMeldProfileId(value);\n } catch {\n return null;\n }\n}\n","import 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 { createHash } from \"node:crypto\";\nimport {\n mkdir,\n readdir,\n readFile,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { openMeldRootDir, runtimeDir } from \"./paths\";\nimport {\n listCliContextStates,\n readCliContextState,\n resolveCliContext,\n writeCliContextState,\n} from \"./session-profile\";\n\ntype SelectedOpenMeldProfileV1 = {\n v: 1;\n sessionId: string;\n sessionSource: string;\n openMeldProfileId: string;\n updatedAt: string;\n};\n\nexport type SetSelectedOpenMeldProfileResult = {\n persistent: boolean;\n cliContextSource?: string;\n};\n\nexport type ClearAllSelectedOpenMeldProfileIdsResult = {\n clearedSessionSelections: number;\n failedSessionIds: string[];\n removedFallbackSelection: boolean;\n removedLegacySelectionFile: boolean;\n removedLegacySessionSelectionDirectory: boolean;\n};\n\nconst SESSION_FILE_HASH_LENGTH = 8;\nconst SESSION_FILE_MAX_LENGTH = 128;\nconst FALLBACK_SELECTION_SESSION_ID = \"global-default\";\nconst FALLBACK_SELECTION_SOURCE = \"fallback:no_runtime_session\";\n\nexport async function setSelectedOpenMeldProfileId(\n openMeldProfileId: string\n): Promise<SetSelectedOpenMeldProfileResult> {\n const normalized = normalizeRequiredString(\n openMeldProfileId,\n \"openMeldProfileId\"\n );\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n\n const cliContext = resolveCliContext();\n if (!cliContext) {\n await writeFallbackSelectionPayload(normalized);\n return {\n persistent: true,\n cliContextSource: FALLBACK_SELECTION_SOURCE,\n };\n }\n\n await writeCliContextState({\n selectedOpenMeldProfileId: normalized,\n });\n await rm(selectionPath(cliContext.cliContextId), {\n force: true,\n }).catch(() => undefined);\n return {\n persistent: true,\n cliContextSource: cliContext.source,\n };\n}\n\nexport async function getSelectedOpenMeldProfileId(): Promise<string | null> {\n const cliContext = resolveCliContext();\n if (!cliContext) {\n return await readFallbackSelectionPayload();\n }\n\n const sessionState = await readCliContextState();\n if (sessionState?.selectedOpenMeldProfileId) {\n return sessionState.selectedOpenMeldProfileId;\n }\n\n const legacySelection = await readLegacySelectionPayload(\n cliContext.cliContextId\n );\n if (!legacySelection?.openMeldProfileId) {\n return null;\n }\n await writeCliContextState({\n sessionId: legacySelection.sessionId,\n sessionSource: legacySelection.sessionSource,\n openMeldProfileId: legacySelection.openMeldProfileId,\n });\n await rm(selectionPath(cliContext.cliContextId), {\n force: true,\n }).catch(() => undefined);\n return legacySelection.openMeldProfileId;\n}\n\nexport async function clearSelectedOpenMeldProfileId(): Promise<void> {\n const cliContext = resolveCliContext();\n if (!cliContext) {\n await rm(fallbackSelectionPath(), { force: true }).catch(() => undefined);\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return;\n }\n\n await writeCliContextState({\n selectedOpenMeldProfileId: null,\n });\n await rm(selectionPath(cliContext.cliContextId), { force: true });\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n}\n\nexport async function clearAllSelectedOpenMeldProfileIds(): Promise<ClearAllSelectedOpenMeldProfileIdsResult> {\n const sessionStates = await listCliContextStates();\n let clearedSessionSelections = 0;\n const failedSessionIds: string[] = [];\n\n for (const sessionState of sessionStates) {\n if (!sessionState.selectedOpenMeldProfileId) {\n continue;\n }\n try {\n const written = await writeCliContextState({\n sessionId: sessionState.sessionId,\n sessionSource: sessionState.cliContextSource,\n selectedOpenMeldProfileId: null,\n });\n if (written) {\n clearedSessionSelections += 1;\n continue;\n }\n } catch {\n // Best-effort cleanup: skip unwritable session state and continue logout.\n }\n failedSessionIds.push(sessionState.sessionId);\n }\n\n const removedFallbackSelection = await removeFileIfPresent(\n fallbackSelectionPath()\n );\n const removedLegacySelectionFile = await removeFileIfPresent(\n legacySelectionPath()\n );\n const removedLegacySessionSelectionDirectory = await removeDirectoryIfPresent(\n sessionSelectionDir()\n );\n\n return {\n clearedSessionSelections,\n failedSessionIds,\n removedFallbackSelection,\n removedLegacySelectionFile,\n removedLegacySessionSelectionDirectory,\n };\n}\n\nexport async function alignSelectedOpenMeldProfileStorage(): Promise<{\n migratedSessionSelections: number;\n removedLegacyDirectory: boolean;\n removedLegacySelectionFile: boolean;\n}> {\n let migratedSessionSelections = 0;\n const entryNames = await readdir(sessionSelectionDir()).catch(() => []);\n for (const entryName of entryNames) {\n if (!entryName.endsWith(\".selected-profile.json\")) {\n continue;\n }\n const raw = await readFile(\n join(sessionSelectionDir(), entryName),\n \"utf8\"\n ).catch(() => null);\n if (!raw) {\n continue;\n }\n const parsed = parseLegacySelectionPayload(raw);\n if (!parsed) {\n continue;\n }\n const written = await writeCliContextState({\n sessionId: parsed.sessionId,\n sessionSource: parsed.sessionSource,\n selectedOpenMeldProfileId: parsed.openMeldProfileId,\n });\n if (written) {\n migratedSessionSelections += 1;\n }\n }\n\n const legacyDirectoryExists = entryNames.length > 0;\n if (legacyDirectoryExists) {\n await rm(sessionSelectionDir(), { recursive: true, force: true });\n }\n await migrateLegacyFallbackSelection();\n const removedLegacySelectionFile = await removeLegacySelectionFile();\n return {\n migratedSessionSelections,\n removedLegacyDirectory: legacyDirectoryExists,\n removedLegacySelectionFile,\n };\n}\n\nfunction selectionPath(sessionId: string): string {\n return join(\n sessionSelectionDir(),\n `${toSafeSessionFile(sessionId)}.selected-profile.json`\n );\n}\n\nfunction sessionSelectionDir(): string {\n return join(runtimeDir(), \"selected-openmeld-profiles\");\n}\n\nfunction legacySelectionPath(): string {\n return join(openMeldRootDir(), \"auth\", \"selected-profile.json\");\n}\n\nfunction fallbackSelectionPath(): string {\n return join(runtimeDir(), \"selected-profile-fallback.json\");\n}\n\nasync function readLegacySelectionPayload(\n sessionId: string\n): Promise<SelectedOpenMeldProfileV1 | null> {\n const raw = await readFile(selectionPath(sessionId), \"utf8\").catch(\n () => null\n );\n if (!raw) {\n return null;\n }\n return parseLegacySelectionPayload(raw);\n}\n\nasync function readFallbackSelectionPayload(): Promise<string | null> {\n const raw = await readFile(fallbackSelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n const legacyFallback = await readLegacyFallbackSelection();\n if (!legacyFallback) {\n return null;\n }\n await writeFallbackSelectionPayload(legacyFallback.openMeldProfileId);\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return legacyFallback.openMeldProfileId;\n }\n return parseLegacySelectionPayload(raw)?.openMeldProfileId ?? null;\n}\n\nasync function writeFallbackSelectionPayload(\n openMeldProfileId: string\n): Promise<void> {\n await mkdir(runtimeDir(), { recursive: true });\n const payload: SelectedOpenMeldProfileV1 = {\n v: 1,\n sessionId: FALLBACK_SELECTION_SESSION_ID,\n sessionSource: FALLBACK_SELECTION_SOURCE,\n openMeldProfileId,\n updatedAt: new Date().toISOString(),\n };\n await writeFile(\n fallbackSelectionPath(),\n `${JSON.stringify(payload, null, 2)}\\n`,\n \"utf8\"\n );\n}\n\nfunction parseLegacySelectionPayload(\n raw: string\n): SelectedOpenMeldProfileV1 | null {\n try {\n const payload = JSON.parse(raw) as Partial<SelectedOpenMeldProfileV1>;\n if (payload.v !== 1) {\n return null;\n }\n const sessionId = normalizeOptionalString(payload.sessionId);\n const openMeldProfileId = normalizeOptionalString(\n payload.openMeldProfileId\n );\n if (!(sessionId && openMeldProfileId)) {\n return null;\n }\n return {\n v: 1,\n sessionId,\n sessionSource: normalizeOptionalString(payload.sessionSource) ?? \"manual\",\n openMeldProfileId,\n updatedAt:\n normalizeOptionalString(payload.updatedAt) ?? new Date(0).toISOString(),\n };\n } catch {\n return null;\n }\n}\n\nasync function readLegacyFallbackSelection(): Promise<SelectedOpenMeldProfileV1 | null> {\n const raw = await readFile(legacySelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n return null;\n }\n const parsed = parseLegacySelectionPayload(raw);\n if (parsed?.sessionSource !== FALLBACK_SELECTION_SOURCE) {\n return null;\n }\n return parsed;\n}\n\nasync function migrateLegacyFallbackSelection(): Promise<void> {\n const legacyFallback = await readLegacyFallbackSelection();\n if (!legacyFallback) {\n return;\n }\n const existingFallback = await readFile(\n fallbackSelectionPath(),\n \"utf8\"\n ).catch(() => null);\n if (!existingFallback) {\n await writeFallbackSelectionPayload(legacyFallback.openMeldProfileId);\n }\n}\n\nasync function removeLegacySelectionFile(): Promise<boolean> {\n const raw = await readFile(legacySelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n return false;\n }\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return true;\n}\n\nfunction toSafeSessionFile(value: string): string {\n const hash = createHash(\"sha1\")\n .update(value, \"utf8\")\n .digest(\"hex\")\n .slice(0, SESSION_FILE_HASH_LENGTH);\n const safeBaseRaw = value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n const safeBase = safeBaseRaw.length > 0 ? safeBaseRaw : \"session\";\n const maxBaseLength = Math.max(\n 1,\n SESSION_FILE_MAX_LENGTH - SESSION_FILE_HASH_LENGTH - 1\n );\n const truncatedBase = safeBase.slice(0, maxBaseLength);\n return `${truncatedBase}-${hash}`;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeRequiredString(value: unknown, field: string): string {\n const normalized = normalizeOptionalString(value);\n if (!normalized) {\n throw new Error(`${field} is required`);\n }\n return normalized;\n}\n\nasync function removeFileIfPresent(path: string): Promise<boolean> {\n const raw = await readFile(path, \"utf8\").catch(() => null);\n if (raw === null) {\n return false;\n }\n await rm(path, { force: true }).catch(() => undefined);\n return true;\n}\n\nasync function removeDirectoryIfPresent(path: string): Promise<boolean> {\n const directory = await stat(path).catch(() => null);\n if (!directory?.isDirectory()) {\n return false;\n }\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n return true;\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 createAuthenticationError,\n resolveAuthenticationGuidanceFromError,\n resolveAuthenticationReasonFromState,\n} from \"../auth/auth-guidance\";\nimport { formatInlineOpenMeldCliCommands } from \"../runtime/cli-entry-command\";\nimport { getAuthSessionState } from \"./auth-session\";\nimport {\n clearSelectedOpenMeldProfileId,\n getSelectedOpenMeldProfileId,\n setSelectedOpenMeldProfileId,\n} from \"./openmeld-profile-selection\";\nimport {\n type OpenMeldProfile,\n type OpenMeldProfileKind,\n resolveOpenMeldProfile,\n resolveOpenMeldProfileByIdOrName,\n} from \"./openmeld-profiles-api\";\n\nexport type ResolveOpenMeldProfileInput = {\n openMeldProfileId?: string;\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated?: boolean;\n persistSelection?: boolean;\n allowDefaultFallback?: boolean;\n authAction?: string;\n};\n\nconst PROFILE_REQUIRED_ERROR_ROOT =\n \"no OpenMeld profile is selected for this terminal session yet\";\nconst PROFILE_REQUIRED_ERROR_MESSAGE = `${PROFILE_REQUIRED_ERROR_ROOT}; run \\`openmeld start\\` to choose one, or pass \\`--profile <id>\\`.`;\nconst SERVICE_TRACE_PROFILE_REQUIRED_ERROR_MESSAGE = `${PROFILE_REQUIRED_ERROR_ROOT}; dispatch trace needs an acting profile. Run \\`openmeld profile set <profile-id>\\` once, or pass \\`--profile <profile-id>\\` with this trace command. \\`--target-profile\\` only identifies the agent being traced.`;\nconst PROFILE_REQUIRED_ERROR_PREFIX =\n \"no OpenMeld profile is selected for this terminal session yet; run `\";\nconst PROFILE_REQUIRED_ERROR_SUFFIX =\n \" start` to choose one, or pass `--profile <id>`.\";\n\nexport function isSelectedOpenMeldProfileRequiredError(\n error: unknown\n): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n if (error.message === PROFILE_REQUIRED_ERROR_MESSAGE) {\n return true;\n }\n\n if (\n error.message.includes(PROFILE_REQUIRED_ERROR_ROOT) &&\n error.message.includes(\"--profile <\")\n ) {\n return true;\n }\n\n return (\n error.message.startsWith(PROFILE_REQUIRED_ERROR_PREFIX) &&\n error.message.endsWith(PROFILE_REQUIRED_ERROR_SUFFIX)\n );\n}\n\nexport async function resolveOpenMeldProfileOrNull(\n input: ResolveOpenMeldProfileInput = {}\n): Promise<OpenMeldProfile | null> {\n const explicitOpenMeldProfileId = normalizeOptionalString(\n input.openMeldProfileId\n );\n if (explicitOpenMeldProfileId) {\n return await resolveExplicitOpenMeldProfile(explicitOpenMeldProfileId, {\n profileKind: input.profileKind,\n allowUnauthenticated: input.allowUnauthenticated === true,\n persistSelection: input.persistSelection !== false,\n });\n }\n\n const selectedOpenMeldProfileId = await getSelectedOpenMeldProfileId();\n if (selectedOpenMeldProfileId) {\n const selectedProfile = await resolveSelectedOpenMeldProfile(\n selectedOpenMeldProfileId,\n {\n profileKind: input.profileKind,\n allowUnauthenticated: input.allowUnauthenticated === true,\n }\n );\n if (selectedProfile) {\n return selectedProfile;\n }\n }\n\n if (input.allowUnauthenticated === true) {\n const authState = await getAuthSessionState({\n validateRemote: false,\n });\n if (authState.state !== \"valid\") {\n return null;\n }\n }\n\n if (input.allowDefaultFallback !== true) {\n return null;\n }\n\n let fallbackProfile: OpenMeldProfile;\n try {\n fallbackProfile = await resolveOpenMeldProfile({\n profileKind: input.profileKind,\n });\n } catch (error) {\n if (input.allowUnauthenticated === true && isAuthRequiredError(error)) {\n return null;\n }\n throw error;\n }\n if (input.persistSelection !== false) {\n await setSelectedOpenMeldProfileId(fallbackProfile.openMeldProfileId);\n }\n return fallbackProfile;\n}\n\nasync function resolveExplicitOpenMeldProfile(\n openMeldProfileId: string,\n input: {\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated: boolean;\n persistSelection: boolean;\n }\n): Promise<OpenMeldProfile | null> {\n try {\n const profile = await resolveOpenMeldProfileByIdOrName({\n profileIdentifier: openMeldProfileId,\n profileKind: input.profileKind,\n });\n if (input.persistSelection) {\n await setSelectedOpenMeldProfileId(profile.openMeldProfileId);\n }\n return profile;\n } catch (error) {\n if (isAuthRequiredError(error) && input.allowUnauthenticated) {\n return null;\n }\n throw error;\n }\n}\n\nexport async function requireOpenMeldProfile(\n input: ResolveOpenMeldProfileInput = {}\n): Promise<OpenMeldProfile> {\n const profile = await resolveOpenMeldProfileOrNull(input);\n if (profile) {\n return profile;\n }\n\n const authState = await getAuthSessionState({\n validateRemote: false,\n });\n if (authState.state === \"valid\") {\n throw new Error(\n formatInlineOpenMeldCliCommands(\n resolveProfileRequiredErrorMessage(input.authAction)\n )\n );\n }\n const reason = resolveAuthenticationReasonFromState(authState.state);\n throw createAuthenticationError({\n reason: reason ?? \"required\",\n action: input.authAction,\n });\n}\n\nfunction resolveProfileRequiredErrorMessage(authAction?: string): string {\n if (authAction === \"reading a dispatch trace\") {\n return SERVICE_TRACE_PROFILE_REQUIRED_ERROR_MESSAGE;\n }\n\n return PROFILE_REQUIRED_ERROR_MESSAGE;\n}\n\nasync function resolveSelectedOpenMeldProfile(\n selectedOpenMeldProfileId: string,\n input: {\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated: boolean;\n }\n): Promise<OpenMeldProfile | null> {\n try {\n return await resolveOpenMeldProfile({\n openMeldProfileId: selectedOpenMeldProfileId,\n profileKind: input.profileKind,\n });\n } catch (error) {\n if (isAuthRequiredError(error)) {\n if (input.allowUnauthenticated) {\n return null;\n }\n throw error;\n }\n\n if (isProfileMissingError(error)) {\n await clearSelectedOpenMeldProfileId();\n return null;\n }\n\n throw error;\n }\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isAuthRequiredError(error: unknown): boolean {\n return resolveAuthenticationGuidanceFromError(error) !== null;\n}\n\nfunction isProfileMissingError(error: unknown): boolean {\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code ?? \"\")\n : \"\";\n if (code === \"profile.not_found\") {\n return true;\n }\n\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n return message.includes(\"profile not found\");\n}\n","import { openMeldProfileIdSchema } from \"@openmeld/schemas\";\nimport { getSelectedOpenMeldProfileId } from \"./openmeld-profile-selection\";\nimport { resolveOpenMeldProfileByIdOrName } from \"./openmeld-profiles-api\";\n\nexport async function resolveViewProfileKey(\n inputProfile?: string\n): Promise<string | null> {\n const explicit = normalizeOptionalString(inputProfile);\n if (explicit) {\n const profileId = openMeldProfileIdSchema.safeParse(explicit);\n if (profileId.success) {\n return profileId.data;\n }\n const profile = await resolveOpenMeldProfileByIdOrName({\n profileIdentifier: explicit,\n }).catch(() => null);\n return profile?.openMeldProfileId ?? explicit;\n }\n\n const selected = await getSelectedOpenMeldProfileId();\n if (selected) {\n return selected;\n }\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","import { getProfileDefaultView } from \"../config/profile-view\";\nimport { resolveOpenMeldProfileOrNull } from \"../config/resolve-openmeld-profile\";\nimport {\n getConfiguredViewCustomization,\n type RuntimeViewCustomization,\n} from \"../config/runtime-config\";\nimport { resolveViewProfileKey } from \"../config/view-profile-key\";\nimport type { CliViewMode, RuntimeContext } from \"./types\";\n\nexport type { CliViewMode, RuntimeContext } from \"./types\";\n\nexport async function resolveRuntimeContext(input?: {\n view?: string;\n profile?: string;\n interactive?: boolean;\n}): Promise<RuntimeContext> {\n const viewOpenMeldProfileId = await resolveViewProfileKey(input?.profile);\n const configuredViewMode = await readConfiguredDefaultView(\n viewOpenMeldProfileId\n );\n const viewMode = parseCliViewMode(input?.view ?? configuredViewMode);\n const interactive = input?.interactive ?? isInteractiveSession();\n const viewCustomization = await readViewCustomization();\n\n if (viewMode === \"human\" || viewMode === \"agent\") {\n return {\n viewMode,\n resolvedView: viewMode,\n interactive,\n ...(viewOpenMeldProfileId\n ? { openMeldProfileId: viewOpenMeldProfileId }\n : {}),\n ...(viewCustomization ? { viewCustomization } : {}),\n };\n }\n\n const openMeldProfile = await resolveOpenMeldProfileOrNull({\n openMeldProfileId: input?.profile,\n allowUnauthenticated: true,\n persistSelection: false,\n allowDefaultFallback: false,\n }).catch(() => null);\n const resolvedView =\n openMeldProfile?.profileKind === \"agent\" ? \"agent\" : \"human\";\n const resolvedOpenMeldProfileId = openMeldProfile\n ? openMeldProfile.openMeldProfileId\n : viewOpenMeldProfileId;\n\n return {\n viewMode,\n resolvedView,\n interactive,\n ...(resolvedOpenMeldProfileId\n ? { openMeldProfileId: resolvedOpenMeldProfileId }\n : {}),\n ...(openMeldProfile?.profileKind\n ? { profileKind: openMeldProfile.profileKind }\n : {}),\n ...(viewCustomization ? { viewCustomization } : {}),\n };\n}\n\nexport function parseCliViewMode(value?: string): CliViewMode {\n const normalized = String(value ?? \"auto\")\n .trim()\n .toLowerCase();\n if (\n normalized === \"auto\" ||\n normalized === \"human\" ||\n normalized === \"agent\"\n ) {\n return normalized;\n }\n\n throw new Error(`invalid --view value: ${normalized} (use auto|human|agent)`);\n}\n\nfunction readViewCustomization(): Promise<RuntimeViewCustomization | null> {\n return getConfiguredViewCustomization().catch(() => null);\n}\n\nfunction readConfiguredDefaultView(\n openMeldProfileId?: string | null\n): Promise<CliViewMode> {\n if (!openMeldProfileId) {\n return Promise.resolve(\"auto\");\n }\n return getProfileDefaultView(openMeldProfileId).catch(() => \"auto\");\n}\n\nfunction isInteractive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,gBAAgB,gCACd,qGACF;GACA,eAAe,gCACb,qGACF;GACA,qBAAqB,gCACnB,uIACF;GACA,mBAAmB,gCACjB,uIACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,uCACF;GACA,mBAAmB,gCACjB,uEACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,gDACF;GACA,mBAAmB,gCACjB,gFACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,2CACF;GACA,mBAAmB,gCACjB,2EACF;EACF;EACF,KAAK,YACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,mCACF;GACA,qBAAqB,gCACnB,wCACF;GACA,mBAAmB,gCACjB,wEACF;EACF;EACF,SACE,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,mCACF;GACA,qBAAqB,gCACnB,wCACF;GACA,mBAAmB,gCACjB,wEACF;EACF;CACJ;AACF;AAEA,SAAS,mCACP,UACQ;CACR,MAAM,aAAa,SAAS,SACxB,WAAW,SAAS,WACpB;CACJ,IAAI,SAAS,WAAW,YACtB,OAAO,4CAA4C,WAAW;CAEhE,IAAI,SAAS,WAAW,eACtB,OAAO,sDAAsD,WAAW;CAE1E,IACE,SAAS,WAAW,aACpB,SAAS,WAAW,aACpB,SAAS,WAAW,WAEpB,OAAO,gBAAgB,WAAW;CAEpC,OAAO,UAAU,WAAW;AAC9B;AAEA,SAAS,mCACP,UACU;CACV,MAAM,YAAY,SAAS,SACvB,sCAAsC,SAAS,OAAO,KACtD;CACJ,M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AAsB,IAC3C,CAAC;EACL,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;CACnD;CAGF,MAAM,kBAAkB,MAAM,6BAA6B;EACzD,mBAAmB,OAAO;EAC1B,sBAAsB;EACtB,kBAAkB;EAClB,sBAAsB;CACxB,CAAC,CAAC,CAAC,YAAY,IAAI;CACnB,MAAM,eACJ,iBAAiB,gBAAgB,UAAU,UAAU;CACvD,MAAM,4BAA4B,kBAC9B,gBAAgB,oBAChB;CAEJ,OAAO;EACL;EACA;EACA;EACA,GAAI,4BACA,EAAE,mBAAmB,0BAA0B,IAC/C,CAAC;EACL,GAAI,iBAAiB,cACjB,EAAE,aAAa,gBAAgB,YAAY,IAC3C,CAAC;EACL,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;CACnD;AACF;AAEA,SAAgB,iBAAiB,OAA6B;CAC5D,MAAM,aAAa,OAAO,SAAS,MAAM,CAAC,CACvC,KAAK,CAAC,CACN,YAAY;CACf,IACE,eAAe,UACf,eAAe,WACf,eAAe,SAEf,OAAO;CAGT,MAAM,IAAI,MAAM,yBAAyB,WAAW,wBAAwB;AAC9E;AAEA,SAAS,wBAAkE;CACzE,OAAO,+BAA+B,CAAC,CAAC,YAAY,IAAI;AAC1D;AAEA,SAAS,0BACP,mBACsB;CACtB,IAAI,CAAC,mBACH,OAAO,QAAQ,QAAQ,MAAM;CAE/B,OAAO,sBAAsB,iBAAiB,CAAC,CAAC,YAAY,MAAM;AACpE;AAEA,SAAS,uBAAgC;CACvC,OAAO,QAAQ,QAAQ,MAAM,SAAS,QAAQ,OAAO,KAAK;AAC5D"}
1
+ {"version":3,"file":"context-BEgBhfbb.js","names":["normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString"],"sources":["../src/config/account-context.ts","../src/config/profile-view.ts","../src/auth/auth-guidance.ts","../src/config/openmeld-profile-selection.ts","../src/local-service/state/catalog-sync-signal.ts","../src/config/profile-creation-capability.ts","../src/config/openmeld-profiles-api.ts","../src/config/resolve-openmeld-profile.ts","../src/config/view-profile-key.ts","../src/runtime/context.ts"],"sourcesContent":["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 { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { resolveCurrentOpenMeldAccountContext } from \"./account-context\";\nimport {\n accountProfileViewPath,\n normalizeOpenMeldProfileId,\n type OpenMeldProfileId,\n} from \"./paths\";\n\nexport type ProfileDefaultView = \"auto\" | \"human\" | \"agent\";\n\ntype ProfileViewV1 = {\n v: 1;\n openMeldProfileId: OpenMeldProfileId;\n defaultView: Exclude<ProfileDefaultView, \"auto\">;\n updatedAt: string;\n};\n\ntype StoredProfileViewInput = Partial<ProfileViewV1> & { profile?: string };\n\ntype NormalizedStoredProfileView = {\n needsRewrite: boolean;\n payload: ProfileViewV1;\n};\n\nexport async function getProfileDefaultView(\n openMeldProfileId: string\n): Promise<ProfileDefaultView> {\n const normalizedOpenMeldProfileId =\n normalizeOpenMeldProfileId(openMeldProfileId);\n const path = await resolveAccountProfileViewPath(normalizedOpenMeldProfileId);\n const raw = await readFile(path, \"utf8\").catch(() => null);\n if (!raw) {\n return \"auto\";\n }\n\n try {\n const parsed = JSON.parse(raw) as StoredProfileViewInput;\n if (parsed.v !== 1) {\n return \"auto\";\n }\n const normalizedStoredProfileView = normalizeStoredProfileView(parsed);\n if (!normalizedStoredProfileView) {\n return \"auto\";\n }\n if (\n normalizedStoredProfileView.payload.openMeldProfileId !==\n normalizedOpenMeldProfileId\n ) {\n await rm(path, { force: true });\n return \"auto\";\n }\n if (normalizedStoredProfileView.needsRewrite) {\n await writeProfileViewFile(path, normalizedStoredProfileView.payload);\n }\n return normalizedStoredProfileView.payload.defaultView;\n } catch {\n return \"auto\";\n }\n}\n\nexport async function setProfileDefaultView(input: {\n openMeldProfileId: string;\n view: ProfileDefaultView;\n}): Promise<void> {\n const openMeldProfileId = normalizeOpenMeldProfileId(input.openMeldProfileId);\n const path = await resolveAccountProfileViewPath(openMeldProfileId);\n\n if (input.view === \"auto\") {\n await rm(path, { force: true });\n return;\n }\n\n await writeProfileViewFile(path, {\n v: 1,\n openMeldProfileId,\n defaultView: input.view,\n updatedAt: new Date().toISOString(),\n });\n}\n\nasync function writeProfileViewFile(\n path: string,\n payload: ProfileViewV1\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;\n await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\\n`, \"utf8\");\n try {\n await rename(tempPath, path);\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nasync function resolveAccountProfileViewPath(\n openMeldProfileId: OpenMeldProfileId\n): Promise<string> {\n const accountContext = await resolveCurrentOpenMeldAccountContext();\n return accountProfileViewPath(accountContext.key, openMeldProfileId);\n}\n\nfunction normalizeStoredProfileView(\n input: StoredProfileViewInput\n): NormalizedStoredProfileView | null {\n const openMeldProfileId = normalizeOptionalOpenMeldProfileId(\n input.openMeldProfileId\n );\n const legacyProfile = normalizeOptionalOpenMeldProfileId(input.profile);\n const resolvedOpenMeldProfileId = openMeldProfileId ?? legacyProfile;\n if (!resolvedOpenMeldProfileId) {\n return null;\n }\n const defaultView = normalizeStoredDefaultView(input.defaultView);\n if (!defaultView) {\n return null;\n }\n const updatedAt = normalizeStoredUpdatedAt(input.updatedAt);\n return {\n needsRewrite:\n openMeldProfileId !== resolvedOpenMeldProfileId ||\n input.profile !== undefined ||\n input.updatedAt !== updatedAt,\n payload: {\n v: 1,\n openMeldProfileId: resolvedOpenMeldProfileId,\n defaultView,\n updatedAt,\n },\n };\n}\n\nfunction normalizeStoredDefaultView(\n value: unknown\n): Exclude<ProfileDefaultView, \"auto\"> | null {\n if (value === \"human\" || value === \"agent\") {\n return value;\n }\n return null;\n}\n\nfunction normalizeStoredUpdatedAt(value: unknown): string {\n if (typeof value === \"string\") {\n const trimmedValue = value.trim();\n if (trimmedValue.length > 0 && !Number.isNaN(Date.parse(trimmedValue))) {\n return trimmedValue;\n }\n }\n return new Date().toISOString();\n}\n\nfunction normalizeOptionalOpenMeldProfileId(\n value: unknown\n): OpenMeldProfileId | null {\n if (typeof value !== \"string\") {\n return null;\n }\n try {\n return normalizeOpenMeldProfileId(value);\n } catch {\n return null;\n }\n}\n","import 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 { createHash } from \"node:crypto\";\nimport {\n mkdir,\n readdir,\n readFile,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { openMeldRootDir, runtimeDir } from \"./paths\";\nimport {\n listCliContextStates,\n readCliContextState,\n resolveCliContext,\n writeCliContextState,\n} from \"./session-profile\";\n\ntype SelectedOpenMeldProfileV1 = {\n v: 1;\n sessionId: string;\n sessionSource: string;\n openMeldProfileId: string;\n updatedAt: string;\n};\n\nexport type SetSelectedOpenMeldProfileResult = {\n persistent: boolean;\n cliContextSource?: string;\n};\n\nexport type ClearAllSelectedOpenMeldProfileIdsResult = {\n clearedSessionSelections: number;\n failedSessionIds: string[];\n removedFallbackSelection: boolean;\n removedLegacySelectionFile: boolean;\n removedLegacySessionSelectionDirectory: boolean;\n};\n\nconst SESSION_FILE_HASH_LENGTH = 8;\nconst SESSION_FILE_MAX_LENGTH = 128;\nconst FALLBACK_SELECTION_SESSION_ID = \"global-default\";\nconst FALLBACK_SELECTION_SOURCE = \"fallback:no_runtime_session\";\n\nexport async function setSelectedOpenMeldProfileId(\n openMeldProfileId: string\n): Promise<SetSelectedOpenMeldProfileResult> {\n const normalized = normalizeRequiredString(\n openMeldProfileId,\n \"openMeldProfileId\"\n );\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n\n const cliContext = resolveCliContext();\n if (!cliContext) {\n await writeFallbackSelectionPayload(normalized);\n return {\n persistent: true,\n cliContextSource: FALLBACK_SELECTION_SOURCE,\n };\n }\n\n await writeCliContextState({\n selectedOpenMeldProfileId: normalized,\n });\n await rm(selectionPath(cliContext.cliContextId), {\n force: true,\n }).catch(() => undefined);\n return {\n persistent: true,\n cliContextSource: cliContext.source,\n };\n}\n\nexport async function getSelectedOpenMeldProfileId(): Promise<string | null> {\n const cliContext = resolveCliContext();\n if (!cliContext) {\n return await readFallbackSelectionPayload();\n }\n\n const sessionState = await readCliContextState();\n if (sessionState?.selectedOpenMeldProfileId) {\n return sessionState.selectedOpenMeldProfileId;\n }\n\n const legacySelection = await readLegacySelectionPayload(\n cliContext.cliContextId\n );\n if (!legacySelection?.openMeldProfileId) {\n return null;\n }\n await writeCliContextState({\n sessionId: legacySelection.sessionId,\n sessionSource: legacySelection.sessionSource,\n openMeldProfileId: legacySelection.openMeldProfileId,\n });\n await rm(selectionPath(cliContext.cliContextId), {\n force: true,\n }).catch(() => undefined);\n return legacySelection.openMeldProfileId;\n}\n\nexport async function clearSelectedOpenMeldProfileId(): Promise<void> {\n const cliContext = resolveCliContext();\n if (!cliContext) {\n await rm(fallbackSelectionPath(), { force: true }).catch(() => undefined);\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return;\n }\n\n await writeCliContextState({\n selectedOpenMeldProfileId: null,\n });\n await rm(selectionPath(cliContext.cliContextId), { force: true });\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n}\n\nexport async function clearAllSelectedOpenMeldProfileIds(): Promise<ClearAllSelectedOpenMeldProfileIdsResult> {\n const sessionStates = await listCliContextStates();\n let clearedSessionSelections = 0;\n const failedSessionIds: string[] = [];\n\n for (const sessionState of sessionStates) {\n if (!sessionState.selectedOpenMeldProfileId) {\n continue;\n }\n try {\n const written = await writeCliContextState({\n sessionId: sessionState.sessionId,\n sessionSource: sessionState.cliContextSource,\n selectedOpenMeldProfileId: null,\n });\n if (written) {\n clearedSessionSelections += 1;\n continue;\n }\n } catch {\n // Best-effort cleanup: skip unwritable session state and continue logout.\n }\n failedSessionIds.push(sessionState.sessionId);\n }\n\n const removedFallbackSelection = await removeFileIfPresent(\n fallbackSelectionPath()\n );\n const removedLegacySelectionFile = await removeFileIfPresent(\n legacySelectionPath()\n );\n const removedLegacySessionSelectionDirectory = await removeDirectoryIfPresent(\n sessionSelectionDir()\n );\n\n return {\n clearedSessionSelections,\n failedSessionIds,\n removedFallbackSelection,\n removedLegacySelectionFile,\n removedLegacySessionSelectionDirectory,\n };\n}\n\nexport async function alignSelectedOpenMeldProfileStorage(): Promise<{\n migratedSessionSelections: number;\n removedLegacyDirectory: boolean;\n removedLegacySelectionFile: boolean;\n}> {\n let migratedSessionSelections = 0;\n const entryNames = await readdir(sessionSelectionDir()).catch(() => []);\n for (const entryName of entryNames) {\n if (!entryName.endsWith(\".selected-profile.json\")) {\n continue;\n }\n const raw = await readFile(\n join(sessionSelectionDir(), entryName),\n \"utf8\"\n ).catch(() => null);\n if (!raw) {\n continue;\n }\n const parsed = parseLegacySelectionPayload(raw);\n if (!parsed) {\n continue;\n }\n const written = await writeCliContextState({\n sessionId: parsed.sessionId,\n sessionSource: parsed.sessionSource,\n selectedOpenMeldProfileId: parsed.openMeldProfileId,\n });\n if (written) {\n migratedSessionSelections += 1;\n }\n }\n\n const legacyDirectoryExists = entryNames.length > 0;\n if (legacyDirectoryExists) {\n await rm(sessionSelectionDir(), { recursive: true, force: true });\n }\n await migrateLegacyFallbackSelection();\n const removedLegacySelectionFile = await removeLegacySelectionFile();\n return {\n migratedSessionSelections,\n removedLegacyDirectory: legacyDirectoryExists,\n removedLegacySelectionFile,\n };\n}\n\nfunction selectionPath(sessionId: string): string {\n return join(\n sessionSelectionDir(),\n `${toSafeSessionFile(sessionId)}.selected-profile.json`\n );\n}\n\nfunction sessionSelectionDir(): string {\n return join(runtimeDir(), \"selected-openmeld-profiles\");\n}\n\nfunction legacySelectionPath(): string {\n return join(openMeldRootDir(), \"auth\", \"selected-profile.json\");\n}\n\nfunction fallbackSelectionPath(): string {\n return join(runtimeDir(), \"selected-profile-fallback.json\");\n}\n\nasync function readLegacySelectionPayload(\n sessionId: string\n): Promise<SelectedOpenMeldProfileV1 | null> {\n const raw = await readFile(selectionPath(sessionId), \"utf8\").catch(\n () => null\n );\n if (!raw) {\n return null;\n }\n return parseLegacySelectionPayload(raw);\n}\n\nasync function readFallbackSelectionPayload(): Promise<string | null> {\n const raw = await readFile(fallbackSelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n const legacyFallback = await readLegacyFallbackSelection();\n if (!legacyFallback) {\n return null;\n }\n await writeFallbackSelectionPayload(legacyFallback.openMeldProfileId);\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return legacyFallback.openMeldProfileId;\n }\n return parseLegacySelectionPayload(raw)?.openMeldProfileId ?? null;\n}\n\nasync function writeFallbackSelectionPayload(\n openMeldProfileId: string\n): Promise<void> {\n await mkdir(runtimeDir(), { recursive: true });\n const payload: SelectedOpenMeldProfileV1 = {\n v: 1,\n sessionId: FALLBACK_SELECTION_SESSION_ID,\n sessionSource: FALLBACK_SELECTION_SOURCE,\n openMeldProfileId,\n updatedAt: new Date().toISOString(),\n };\n await writeFile(\n fallbackSelectionPath(),\n `${JSON.stringify(payload, null, 2)}\\n`,\n \"utf8\"\n );\n}\n\nfunction parseLegacySelectionPayload(\n raw: string\n): SelectedOpenMeldProfileV1 | null {\n try {\n const payload = JSON.parse(raw) as Partial<SelectedOpenMeldProfileV1>;\n if (payload.v !== 1) {\n return null;\n }\n const sessionId = normalizeOptionalString(payload.sessionId);\n const openMeldProfileId = normalizeOptionalString(\n payload.openMeldProfileId\n );\n if (!(sessionId && openMeldProfileId)) {\n return null;\n }\n return {\n v: 1,\n sessionId,\n sessionSource: normalizeOptionalString(payload.sessionSource) ?? \"manual\",\n openMeldProfileId,\n updatedAt:\n normalizeOptionalString(payload.updatedAt) ?? new Date(0).toISOString(),\n };\n } catch {\n return null;\n }\n}\n\nasync function readLegacyFallbackSelection(): Promise<SelectedOpenMeldProfileV1 | null> {\n const raw = await readFile(legacySelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n return null;\n }\n const parsed = parseLegacySelectionPayload(raw);\n if (parsed?.sessionSource !== FALLBACK_SELECTION_SOURCE) {\n return null;\n }\n return parsed;\n}\n\nasync function migrateLegacyFallbackSelection(): Promise<void> {\n const legacyFallback = await readLegacyFallbackSelection();\n if (!legacyFallback) {\n return;\n }\n const existingFallback = await readFile(\n fallbackSelectionPath(),\n \"utf8\"\n ).catch(() => null);\n if (!existingFallback) {\n await writeFallbackSelectionPayload(legacyFallback.openMeldProfileId);\n }\n}\n\nasync function removeLegacySelectionFile(): Promise<boolean> {\n const raw = await readFile(legacySelectionPath(), \"utf8\").catch(() => null);\n if (!raw) {\n return false;\n }\n await rm(legacySelectionPath(), { force: true }).catch(() => undefined);\n return true;\n}\n\nfunction toSafeSessionFile(value: string): string {\n const hash = createHash(\"sha1\")\n .update(value, \"utf8\")\n .digest(\"hex\")\n .slice(0, SESSION_FILE_HASH_LENGTH);\n const safeBaseRaw = value.replace(/[^a-zA-Z0-9._-]+/g, \"_\");\n const safeBase = safeBaseRaw.length > 0 ? safeBaseRaw : \"session\";\n const maxBaseLength = Math.max(\n 1,\n SESSION_FILE_MAX_LENGTH - SESSION_FILE_HASH_LENGTH - 1\n );\n const truncatedBase = safeBase.slice(0, maxBaseLength);\n return `${truncatedBase}-${hash}`;\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeRequiredString(value: unknown, field: string): string {\n const normalized = normalizeOptionalString(value);\n if (!normalized) {\n throw new Error(`${field} is required`);\n }\n return normalized;\n}\n\nasync function removeFileIfPresent(path: string): Promise<boolean> {\n const raw = await readFile(path, \"utf8\").catch(() => null);\n if (raw === null) {\n return false;\n }\n await rm(path, { force: true }).catch(() => undefined);\n return true;\n}\n\nasync function removeDirectoryIfPresent(path: string): Promise<boolean> {\n const directory = await stat(path).catch(() => null);\n if (!directory?.isDirectory()) {\n return false;\n }\n await rm(path, { recursive: true, force: true }).catch(() => undefined);\n return true;\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 createAuthenticationError,\n resolveAuthenticationGuidanceFromError,\n resolveAuthenticationReasonFromState,\n} from \"../auth/auth-guidance\";\nimport { formatInlineOpenMeldCliCommands } from \"../runtime/cli-entry-command\";\nimport { getAuthSessionState } from \"./auth-session\";\nimport {\n clearSelectedOpenMeldProfileId,\n getSelectedOpenMeldProfileId,\n setSelectedOpenMeldProfileId,\n} from \"./openmeld-profile-selection\";\nimport {\n type OpenMeldProfile,\n type OpenMeldProfileKind,\n resolveOpenMeldProfile,\n resolveOpenMeldProfileByIdOrName,\n} from \"./openmeld-profiles-api\";\n\nexport type ResolveOpenMeldProfileInput = {\n openMeldProfileId?: string;\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated?: boolean;\n persistSelection?: boolean;\n allowDefaultFallback?: boolean;\n authAction?: string;\n};\n\nconst PROFILE_REQUIRED_ERROR_ROOT =\n \"no OpenMeld profile is selected for this terminal session yet\";\nconst PROFILE_REQUIRED_ERROR_MESSAGE = `${PROFILE_REQUIRED_ERROR_ROOT}; run \\`openmeld start\\` to choose one, or pass \\`--profile <id>\\`.`;\nconst SERVICE_TRACE_PROFILE_REQUIRED_ERROR_MESSAGE = `${PROFILE_REQUIRED_ERROR_ROOT}; dispatch trace needs an acting profile. Run \\`openmeld profile set <profile-id>\\` once, or pass \\`--profile <profile-id>\\` with this trace command. \\`--target-profile\\` only identifies the agent being traced.`;\nconst PROFILE_REQUIRED_ERROR_PREFIX =\n \"no OpenMeld profile is selected for this terminal session yet; run `\";\nconst PROFILE_REQUIRED_ERROR_SUFFIX =\n \" start` to choose one, or pass `--profile <id>`.\";\n\nexport function isSelectedOpenMeldProfileRequiredError(\n error: unknown\n): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n if (error.message === PROFILE_REQUIRED_ERROR_MESSAGE) {\n return true;\n }\n\n if (\n error.message.includes(PROFILE_REQUIRED_ERROR_ROOT) &&\n error.message.includes(\"--profile <\")\n ) {\n return true;\n }\n\n return (\n error.message.startsWith(PROFILE_REQUIRED_ERROR_PREFIX) &&\n error.message.endsWith(PROFILE_REQUIRED_ERROR_SUFFIX)\n );\n}\n\nexport async function resolveOpenMeldProfileOrNull(\n input: ResolveOpenMeldProfileInput = {}\n): Promise<OpenMeldProfile | null> {\n const explicitOpenMeldProfileId = normalizeOptionalString(\n input.openMeldProfileId\n );\n if (explicitOpenMeldProfileId) {\n return await resolveExplicitOpenMeldProfile(explicitOpenMeldProfileId, {\n profileKind: input.profileKind,\n allowUnauthenticated: input.allowUnauthenticated === true,\n persistSelection: input.persistSelection !== false,\n });\n }\n\n const selectedOpenMeldProfileId = await getSelectedOpenMeldProfileId();\n if (selectedOpenMeldProfileId) {\n const selectedProfile = await resolveSelectedOpenMeldProfile(\n selectedOpenMeldProfileId,\n {\n profileKind: input.profileKind,\n allowUnauthenticated: input.allowUnauthenticated === true,\n }\n );\n if (selectedProfile) {\n return selectedProfile;\n }\n }\n\n if (input.allowUnauthenticated === true) {\n const authState = await getAuthSessionState({\n validateRemote: false,\n });\n if (authState.state !== \"valid\") {\n return null;\n }\n }\n\n if (input.allowDefaultFallback !== true) {\n return null;\n }\n\n let fallbackProfile: OpenMeldProfile;\n try {\n fallbackProfile = await resolveOpenMeldProfile({\n profileKind: input.profileKind,\n });\n } catch (error) {\n if (input.allowUnauthenticated === true && isAuthRequiredError(error)) {\n return null;\n }\n throw error;\n }\n if (input.persistSelection !== false) {\n await setSelectedOpenMeldProfileId(fallbackProfile.openMeldProfileId);\n }\n return fallbackProfile;\n}\n\nasync function resolveExplicitOpenMeldProfile(\n openMeldProfileId: string,\n input: {\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated: boolean;\n persistSelection: boolean;\n }\n): Promise<OpenMeldProfile | null> {\n try {\n const profile = await resolveOpenMeldProfileByIdOrName({\n profileIdentifier: openMeldProfileId,\n profileKind: input.profileKind,\n });\n if (input.persistSelection) {\n await setSelectedOpenMeldProfileId(profile.openMeldProfileId);\n }\n return profile;\n } catch (error) {\n if (isAuthRequiredError(error) && input.allowUnauthenticated) {\n return null;\n }\n throw error;\n }\n}\n\nexport async function requireOpenMeldProfile(\n input: ResolveOpenMeldProfileInput = {}\n): Promise<OpenMeldProfile> {\n const profile = await resolveOpenMeldProfileOrNull(input);\n if (profile) {\n return profile;\n }\n\n const authState = await getAuthSessionState({\n validateRemote: false,\n });\n if (authState.state === \"valid\") {\n throw new Error(\n formatInlineOpenMeldCliCommands(\n resolveProfileRequiredErrorMessage(input.authAction)\n )\n );\n }\n const reason = resolveAuthenticationReasonFromState(authState.state);\n throw createAuthenticationError({\n reason: reason ?? \"required\",\n action: input.authAction,\n });\n}\n\nfunction resolveProfileRequiredErrorMessage(authAction?: string): string {\n if (authAction === \"reading a dispatch trace\") {\n return SERVICE_TRACE_PROFILE_REQUIRED_ERROR_MESSAGE;\n }\n\n return PROFILE_REQUIRED_ERROR_MESSAGE;\n}\n\nasync function resolveSelectedOpenMeldProfile(\n selectedOpenMeldProfileId: string,\n input: {\n profileKind?: OpenMeldProfileKind;\n allowUnauthenticated: boolean;\n }\n): Promise<OpenMeldProfile | null> {\n try {\n return await resolveOpenMeldProfile({\n openMeldProfileId: selectedOpenMeldProfileId,\n profileKind: input.profileKind,\n });\n } catch (error) {\n if (isAuthRequiredError(error)) {\n if (input.allowUnauthenticated) {\n return null;\n }\n throw error;\n }\n\n if (isProfileMissingError(error)) {\n await clearSelectedOpenMeldProfileId();\n return null;\n }\n\n throw error;\n }\n}\n\nfunction normalizeOptionalString(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isAuthRequiredError(error: unknown): boolean {\n return resolveAuthenticationGuidanceFromError(error) !== null;\n}\n\nfunction isProfileMissingError(error: unknown): boolean {\n const code =\n error && typeof error === \"object\" && \"code\" in error\n ? String((error as { code?: unknown }).code ?? \"\")\n : \"\";\n if (code === \"profile.not_found\") {\n return true;\n }\n\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n return message.includes(\"profile not found\");\n}\n","import { openMeldProfileIdSchema } from \"@openmeld/schemas\";\nimport { getSelectedOpenMeldProfileId } from \"./openmeld-profile-selection\";\nimport { resolveOpenMeldProfileByIdOrName } from \"./openmeld-profiles-api\";\n\nexport async function resolveViewProfileKey(\n inputProfile?: string\n): Promise<string | null> {\n const explicit = normalizeOptionalString(inputProfile);\n if (explicit) {\n const profileId = openMeldProfileIdSchema.safeParse(explicit);\n if (profileId.success) {\n return profileId.data;\n }\n const profile = await resolveOpenMeldProfileByIdOrName({\n profileIdentifier: explicit,\n }).catch(() => null);\n return profile?.openMeldProfileId ?? explicit;\n }\n\n const selected = await getSelectedOpenMeldProfileId();\n if (selected) {\n return selected;\n }\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","import { getProfileDefaultView } from \"../config/profile-view\";\nimport { resolveOpenMeldProfileOrNull } from \"../config/resolve-openmeld-profile\";\nimport {\n getConfiguredViewCustomization,\n type RuntimeViewCustomization,\n} from \"../config/runtime-config\";\nimport { resolveViewProfileKey } from \"../config/view-profile-key\";\nimport type { CliViewMode, RuntimeContext } from \"./types\";\n\nexport type { CliViewMode, RuntimeContext } from \"./types\";\n\nexport async function resolveRuntimeContext(input?: {\n view?: string;\n profile?: string;\n interactive?: boolean;\n}): Promise<RuntimeContext> {\n const viewOpenMeldProfileId = await resolveViewProfileKey(input?.profile);\n const configuredViewMode = await readConfiguredDefaultView(\n viewOpenMeldProfileId\n );\n const viewMode = parseCliViewMode(input?.view ?? configuredViewMode);\n const interactive = input?.interactive ?? isInteractiveSession();\n const viewCustomization = await readViewCustomization();\n\n if (viewMode === \"human\" || viewMode === \"agent\") {\n return {\n viewMode,\n resolvedView: viewMode,\n interactive,\n ...(viewOpenMeldProfileId\n ? { openMeldProfileId: viewOpenMeldProfileId }\n : {}),\n ...(viewCustomization ? { viewCustomization } : {}),\n };\n }\n\n const openMeldProfile = await resolveOpenMeldProfileOrNull({\n openMeldProfileId: input?.profile,\n allowUnauthenticated: true,\n persistSelection: false,\n allowDefaultFallback: false,\n }).catch(() => null);\n const resolvedView =\n openMeldProfile?.profileKind === \"agent\" ? \"agent\" : \"human\";\n const resolvedOpenMeldProfileId = openMeldProfile\n ? openMeldProfile.openMeldProfileId\n : viewOpenMeldProfileId;\n\n return {\n viewMode,\n resolvedView,\n interactive,\n ...(resolvedOpenMeldProfileId\n ? { openMeldProfileId: resolvedOpenMeldProfileId }\n : {}),\n ...(openMeldProfile?.profileKind\n ? { profileKind: openMeldProfile.profileKind }\n : {}),\n ...(viewCustomization ? { viewCustomization } : {}),\n };\n}\n\nexport function parseCliViewMode(value?: string): CliViewMode {\n const normalized = String(value ?? \"auto\")\n .trim()\n .toLowerCase();\n if (\n normalized === \"auto\" ||\n normalized === \"human\" ||\n normalized === \"agent\"\n ) {\n return normalized;\n }\n\n throw new Error(`invalid --view value: ${normalized} (use auto|human|agent)`);\n}\n\nfunction readViewCustomization(): Promise<RuntimeViewCustomization | null> {\n return getConfiguredViewCustomization().catch(() => null);\n}\n\nfunction readConfiguredDefaultView(\n openMeldProfileId?: string | null\n): Promise<CliViewMode> {\n if (!openMeldProfileId) {\n return Promise.resolve(\"auto\");\n }\n return getProfileDefaultView(openMeldProfileId).catch(() => \"auto\");\n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a;GACb,SAAS;GACT,gBAAgB,gCACd,qGACF;GACA,eAAe,gCACb,qGACF;GACA,qBAAqB,gCACnB,uIACF;GACA,mBAAmB,gCACjB,uIACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,uCACF;GACA,mBAAmB,gCACjB,uEACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,gDACF;GACA,mBAAmB,gCACjB,gFACF;EACF;EACF,KAAK,WACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,yCACF;GACA,qBAAqB,gCACnB,2CACF;GACA,mBAAmB,gCACjB,2EACF;EACF;EACF,KAAK,YACH,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,mCACF;GACA,qBAAqB,gCACnB,wCACF;GACA,mBAAmB,gCACjB,wEACF;EACF;EACF,SACE,OAAO;GACL,OAAO;GACP,aAAa;GACb,SAAS;GACT,gBAAgB;GAChB,eAAe,gCACb,mCACF;GACA,qBAAqB,gCACnB,wCACF;GACA,mBAAmB,gCACjB,wEACF;EACF;CACJ;AACF;AAEA,SAAS,mCACP,UACQ;CACR,MAAM,aAAa,SAAS,SACxB,WAAW,SAAS,WACpB;CACJ,IAAI,SAAS,WAAW,YACtB,OAAO,4CAA4C,WAAW;CAEhE,IAAI,SAAS,WAAW,eACtB,OAAO,sDAAsD,WAAW;CAE1E,IACE,SAAS,WAAW,aACpB,SAAS,WAAW,aACpB,SAAS,WAAW,WAEpB,OAAO,gBAAgB,WAAW;CAEpC,OAAO,UAAU,WAAW;AAC9B;AAEA,SAAS,mCACP,UACU;CACV,MAAM,YAAY,SAAS,SACvB,sCAAsC,SAAS,OA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EAAE,mBAAmB,sBAAsB,IAC3C,CAAC;EACL,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;CACnD;CAGF,MAAM,kBAAkB,MAAM,6BAA6B;EACzD,mBAAmB,OAAO;EAC1B,sBAAsB;EACtB,kBAAkB;EAClB,sBAAsB;CACxB,CAAC,CAAC,CAAC,YAAY,IAAI;CACnB,MAAM,eACJ,iBAAiB,gBAAgB,UAAU,UAAU;CACvD,MAAM,4BAA4B,kBAC9B,gBAAgB,oBAChB;CAEJ,OAAO;EACL;EACA;EACA;EACA,GAAI,4BACA,EAAE,mBAAmB,0BAA0B,IAC/C,CAAC;EACL,GAAI,iBAAiB,cACjB,EAAE,aAAa,gBAAgB,YAAY,IAC3C,CAAC;EACL,GAAI,oBAAoB,EAAE,kBAAkB,IAAI,CAAC;CACnD;AACF;AAEA,SAAgB,iBAAiB,OAA6B;CAC5D,MAAM,aAAa,OAAO,SAAS,MAAM,CAAC,CACvC,KAAK,CAAC,CACN,YAAY;CACf,IACE,eAAe,UACf,eAAe,WACf,eAAe,SAEf,OAAO;CAGT,MAAM,IAAI,MAAM,yBAAyB,WAAW,wBAAwB;AAC9E;AAEA,SAAS,wBAAkE;CACzE,OAAO,+BAA+B,CAAC,CAAC,YAAY,IAAI;AAC1D;AAEA,SAAS,0BACP,mBACsB;CACtB,IAAI,CAAC,mBACH,OAAO,QAAQ,QAAQ,MAAM;CAE/B,OAAO,sBAAsB,iBAAiB,CAAC,CAAC,YAAY,MAAM;AACpE;AAEA,SAAS,uBAAgC;CACvC,OAAO,QAAQ,QAAQ,MAAM,SAAS,QAAQ,OAAO,KAAK;AAC5D"}
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { U as systemDir } from "./paths-De9xdA2h.js";
4
- import { t as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH } from "./runtime-transport-BzCp9hM3.js";
4
+ import { Zn as agentControllerPermissionModeSchema, t as CURRENT_DAEMON_EXECUTION_CONTRACT_EPOCH } from "./runtime-transport-DFBYm5Re.js";
5
5
  import { E as agentProfileIdSchema, b as skippedDaemonProfileSchema } from "./control-plane-B93wmVS6.js";
6
6
  import { n as runtimeAgentControllerConversationIdMappingSpecSchema, o as runtimeStreamingModeSchema, r as runtimeAgentControllerLaunchContractSchema, s as runtimeTransportModeSchema, u as conversationPolicySchema } from "./controller-contract-DAOCaefz.js";
7
- import { $ as RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS$1, F as CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS$1, I as DAEMON_RUNTIME_CONTRACT_EPOCH$1, K as MIN_HEARTBEAT_INTERVAL_MS$1, L as DAEMON_STREAM_CONNECT_TIMEOUT_MS$1, P as CATALOG_SYNC_RETRY_INTERVAL_MS$1, R as DAEMON_STREAM_KEEPALIVE_INTERVAL_MS$1, U as HEARTBEAT_RESPONSE_TIMEOUT_MS$1, V as DEFAULT_HEARTBEAT_INTERVAL_MS$1, W as MAX_HEARTBEAT_INTERVAL_MS$1, X as PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS$1, Y as PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS$1, Z as REGISTER_RESPONSE_TIMEOUT_MS$1, et as RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS$1, tt as RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS$1, z as DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS$1 } from "./auth-session-JhILeJRO.js";
7
+ import { $ as RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS$1, F as CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS$1, I as DAEMON_RUNTIME_CONTRACT_EPOCH$1, K as MIN_HEARTBEAT_INTERVAL_MS$1, L as DAEMON_STREAM_CONNECT_TIMEOUT_MS$1, P as CATALOG_SYNC_RETRY_INTERVAL_MS$1, R as DAEMON_STREAM_KEEPALIVE_INTERVAL_MS$1, U as HEARTBEAT_RESPONSE_TIMEOUT_MS$1, V as DEFAULT_HEARTBEAT_INTERVAL_MS$1, W as MAX_HEARTBEAT_INTERVAL_MS$1, X as PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS$1, Y as PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS$1, Z as REGISTER_RESPONSE_TIMEOUT_MS$1, et as RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS$1, tt as RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS$1, z as DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS$1 } from "./auth-session-DywRZLBr.js";
8
8
  import { r as daemonServiceLaneSchema } from "./service-contract-CRyDcIIf.js";
9
- import { n as agentControllerPermissionModeSchema, r as agentControllerCollaborationModeSchema, t as openCodePermissionConfigSchema } from "./open-code-permission-DHFJYc_o.js";
9
+ import { n as agentControllerCollaborationModeSchema, t as openCodePermissionConfigSchema } from "./open-code-permission-B5f1e5an.js";
10
10
  import { n as toErrorMessage$1 } from "./dist-BLuEEVHh.js";
11
11
  import { h as daemonRuntimeRootPath } from "./daemon-state-Dte9re5V.js";
12
12
  import { randomUUID } from "node:crypto";
@@ -281,4 +281,4 @@ async function migrateLegacyDaemonDeviceId(input) {
281
281
  //#endregion
282
282
  export { DEFAULT_RECONNECT_DELAY_MS as A, cachedDaemonRouteConfigSchema as B, CONTROLLED_SHUTDOWN_SOCKET_CLOSE_TIMEOUT_MS as C, DAEMON_STREAM_CONNECT_TIMEOUT_MS as D, DAEMON_RUNTIME_CONTRACT_REPAIR_REPORT_FILE as E, REGISTER_RESPONSE_TIMEOUT_MS as F, agentExecutionSteerRequestSchema as H, RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_INTERVAL_MS as I, RUNTIME_AGENT_CONTROLLER_REPORT_SYNC_RETRY_INTERVAL_MS as L, MAX_RECONNECT_DELAY_MS as M, PROVIDER_CONVERSATION_PROOF_SYNC_INTERVAL_MS as N, DAEMON_STREAM_KEEPALIVE_INTERVAL_MS as O, PROVIDER_CONVERSATION_PROOF_SYNC_RETRY_INTERVAL_MS as P, RUNTIME_STATE_PERSIST_MIN_INTERVAL_MS as R, CONTROLLED_SHUTDOWN_RESULT_ACK_TIMEOUT_MS as S, DAEMON_RUNTIME_CONTRACT_META_FILE as T, agentExecutionSteerResponseSchema as U, daemonRouteCatalogCacheSchema as V, toErrorMessage as _, asRecord as a, CATALOG_SYNC_SIGNAL_POLL_INTERVAL_MS as b, normalizeHeartbeatIntervalMs as c, normalizeText as d, nowIsoString as f, parseTransportMode as g, parseStreamingMode as h, resolvePreferredDaemonDeviceId as i, HEARTBEAT_RESPONSE_TIMEOUT_MS as j, DAEMON_STREAM_KEEPALIVE_PONG_TIMEOUT_MS as k, normalizeNonNegativeInteger as l, parseRuntimeTransportMode as m, ensureDaemonRuntimePaths as n, dirnamePath as o, parseContextIdMappingSpec as p, resolveDaemonDeviceId as r, emitRunLine as s, buildLedgerPaths as t, normalizeOptionalText as u, warnDaemonEvent as v, DAEMON_RUNTIME_CONTRACT_EPOCH as w, CONTROLLED_SHUTDOWN_REQUEST_TIMEOUT_MS as x, CATALOG_SYNC_RETRY_INTERVAL_MS as y, DAEMON_ROUTE_CATALOG_CACHE_SCHEMA_NAME as z };
283
283
 
284
- //# sourceMappingURL=daemon-device-id-C3gKch4E.js.map
284
+ //# sourceMappingURL=daemon-device-id-CmykIapy.js.map