@agimon-ai/po-config 0.0.0-alpha.2 → 0.0.0-alpha.21

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 (221) hide show
  1. package/LICENSE +149 -21
  2. package/README.md +11 -11
  3. package/dist/agentPluginMcp.cjs +313 -134
  4. package/dist/agentPluginMcp.cjs.map +1 -1
  5. package/dist/agentPluginMcp.d.mts +22 -4
  6. package/dist/agentPluginMcp.d.mts.map +1 -1
  7. package/dist/agentPluginMcp.mjs +312 -134
  8. package/dist/agentPluginMcp.mjs.map +1 -1
  9. package/dist/apiContracts.cjs.map +1 -1
  10. package/dist/apiContracts.mjs.map +1 -1
  11. package/dist/atomicJson-D3MHqnLW.cjs +59 -0
  12. package/dist/atomicJson-D3MHqnLW.cjs.map +1 -0
  13. package/dist/atomicJson-Dj3rlZbD.mjs +40 -0
  14. package/dist/atomicJson-Dj3rlZbD.mjs.map +1 -0
  15. package/dist/atomicJson.cjs +4 -2
  16. package/dist/atomicJson.d.mts +2 -2
  17. package/dist/atomicJson.mjs +3 -2
  18. package/dist/{index-BT29GZx5.d.mts → completion-Ba0TiBHa.d.mts} +58 -27
  19. package/dist/completion-Ba0TiBHa.d.mts.map +1 -0
  20. package/dist/config-BBvn_ZLP.mjs +1 -0
  21. package/dist/config-Cdybp9rT.cjs +155 -0
  22. package/dist/config-Cdybp9rT.cjs.map +1 -0
  23. package/dist/config-Cxc2xw54.mjs +112 -0
  24. package/dist/config-Cxc2xw54.mjs.map +1 -0
  25. package/dist/{config-D2HbBLzo.d.mts → config-pxC7FyUJ.d.mts} +33 -33
  26. package/dist/config-pxC7FyUJ.d.mts.map +1 -0
  27. package/dist/config.cjs +21 -17
  28. package/dist/config.d.mts +3 -3
  29. package/dist/config.mjs +4 -3
  30. package/dist/{configPolicy-Ce1QKDxa.cjs → configPolicy-CowlLhK1.cjs} +99 -99
  31. package/dist/configPolicy-CowlLhK1.cjs.map +1 -0
  32. package/dist/{configPolicy-DCQgF5-f.mjs → configPolicy-DueX0k6i.mjs} +84 -84
  33. package/dist/configPolicy-DueX0k6i.mjs.map +1 -0
  34. package/dist/configSchema.d.mts +2 -2
  35. package/dist/configWriter-DCASRzr-.mjs +180 -0
  36. package/dist/configWriter-DCASRzr-.mjs.map +1 -0
  37. package/dist/configWriter-DGO0gmXo.cjs +218 -0
  38. package/dist/configWriter-DGO0gmXo.cjs.map +1 -0
  39. package/dist/configWriter.cjs +7 -4
  40. package/dist/configWriter.d.mts +2 -2
  41. package/dist/configWriter.mjs +1 -2
  42. package/dist/core-B0Qg0Qq2.cjs +224 -0
  43. package/dist/core-B0Qg0Qq2.cjs.map +1 -0
  44. package/dist/core-DKWW9gkh.mjs +139 -0
  45. package/dist/core-DKWW9gkh.mjs.map +1 -0
  46. package/dist/{domains-DGCb7uMC.cjs → domains-CiDUsRiX.cjs} +473 -171
  47. package/dist/domains-CiDUsRiX.cjs.map +1 -0
  48. package/dist/{domains-BroCVHrS.mjs → domains-IlieGHaY.mjs} +437 -170
  49. package/dist/domains-IlieGHaY.mjs.map +1 -0
  50. package/dist/domains.cjs +9 -3
  51. package/dist/domains.d.mts +3 -3
  52. package/dist/domains.mjs +3 -3
  53. package/dist/extensions/mcp-ui.mjs +1 -1
  54. package/dist/extensions/mcp-ui.mjs.map +1 -1
  55. package/dist/extensions/mcp.cjs +3 -3
  56. package/dist/extensions/mcp.cjs.map +1 -1
  57. package/dist/extensions/mcp.d.mts +1 -1
  58. package/dist/extensions/mcp.mjs +2 -2
  59. package/dist/extensions/mcp.mjs.map +1 -1
  60. package/dist/extensions/server.cjs +55 -47
  61. package/dist/extensions/server.cjs.map +1 -1
  62. package/dist/extensions/server.d.mts +2 -2
  63. package/dist/extensions/server.d.mts.map +1 -1
  64. package/dist/extensions/server.mjs +56 -48
  65. package/dist/extensions/server.mjs.map +1 -1
  66. package/dist/{harnessState-Dn_S7fB9.mjs → harnessState-8lZda_8r.mjs} +2 -2
  67. package/dist/{harnessState-Dn_S7fB9.mjs.map → harnessState-8lZda_8r.mjs.map} +1 -1
  68. package/dist/{harnessState-CCyBeutB.cjs → harnessState-BrmH0lG5.cjs} +2 -2
  69. package/dist/{harnessState-CCyBeutB.cjs.map → harnessState-BrmH0lG5.cjs.map} +1 -1
  70. package/dist/harnessState.cjs +1 -1
  71. package/dist/harnessState.d.mts +1 -1
  72. package/dist/harnessState.mjs +1 -2
  73. package/dist/{harnessStore-CJSxdSkV.cjs → harnessStore-BinxGITh.cjs} +189 -81
  74. package/dist/harnessStore-BinxGITh.cjs.map +1 -0
  75. package/dist/{harnessStore-CltwLB7M.mjs → harnessStore-w8zHmJ_H.mjs} +160 -82
  76. package/dist/harnessStore-w8zHmJ_H.mjs.map +1 -0
  77. package/dist/harnessStore.cjs +6 -1
  78. package/dist/harnessStore.d.mts +2 -2
  79. package/dist/harnessStore.mjs +1 -2
  80. package/dist/index-7RuIAWX1.d.mts +63 -0
  81. package/dist/index-7RuIAWX1.d.mts.map +1 -0
  82. package/dist/{index-CkDDvVQt.d.mts → index-BNcG0voG.d.mts} +61 -16
  83. package/dist/index-BNcG0voG.d.mts.map +1 -0
  84. package/dist/{index-Dy_-m7gx.d.mts → index-BTOU4XiI.d.mts} +3 -3
  85. package/dist/{index-Dy_-m7gx.d.mts.map → index-BTOU4XiI.d.mts.map} +1 -1
  86. package/dist/index-COokUToB.d.mts +83 -0
  87. package/dist/index-COokUToB.d.mts.map +1 -0
  88. package/dist/index-D3vGEYup.d.mts +135 -0
  89. package/dist/index-D3vGEYup.d.mts.map +1 -0
  90. package/dist/{index-Ch7ptOkW.d.mts → index-DNEK9W6n.d.mts} +26 -16
  91. package/dist/index-DNEK9W6n.d.mts.map +1 -0
  92. package/dist/index-D_OtYtsl.d.mts +37 -0
  93. package/dist/index-D_OtYtsl.d.mts.map +1 -0
  94. package/dist/{index-DNk4q0Qm.d.mts → index-Nbj2iQWw.d.mts} +19 -25
  95. package/dist/index-Nbj2iQWw.d.mts.map +1 -0
  96. package/dist/{index-CEUc7m16.d.mts → index-dYgF03lE.d.mts} +82 -32
  97. package/dist/index-dYgF03lE.d.mts.map +1 -0
  98. package/dist/index-fTuf8tVH.d.mts +34 -0
  99. package/dist/index-fTuf8tVH.d.mts.map +1 -0
  100. package/dist/index-nVcEC1jO.d.mts +62 -0
  101. package/dist/index-nVcEC1jO.d.mts.map +1 -0
  102. package/dist/index.cjs +81 -59
  103. package/dist/index.d.mts +16 -15
  104. package/dist/index.mjs +17 -15
  105. package/dist/{init-Cd3Ki6Ub.cjs → init-BdZ-gqqk.cjs} +209 -59
  106. package/dist/init-BdZ-gqqk.cjs.map +1 -0
  107. package/dist/{init-DVzhiCUE.mjs → init-DG7MxGxC.mjs} +187 -48
  108. package/dist/init-DG7MxGxC.mjs.map +1 -0
  109. package/dist/init.cjs +8 -6
  110. package/dist/init.d.mts +2 -2
  111. package/dist/init.mjs +1 -2
  112. package/dist/layeredConfig-BbkoIEfM.mjs +95 -0
  113. package/dist/layeredConfig-BbkoIEfM.mjs.map +1 -0
  114. package/dist/layeredConfig-Bs18dXQG.cjs +127 -0
  115. package/dist/layeredConfig-Bs18dXQG.cjs.map +1 -0
  116. package/dist/layeredConfig.cjs +5 -4
  117. package/dist/layeredConfig.d.mts +7 -2
  118. package/dist/layeredConfig.d.mts.map +1 -0
  119. package/dist/layeredConfig.mjs +1 -2
  120. package/dist/{majorModes-D1Itd8SN.mjs → majorModes-B8Km83e1.mjs} +130 -23
  121. package/dist/majorModes-B8Km83e1.mjs.map +1 -0
  122. package/dist/{majorModes-DnNSH9ZK.cjs → majorModes-CLccNMZt.cjs} +147 -22
  123. package/dist/majorModes-CLccNMZt.cjs.map +1 -0
  124. package/dist/majorModes.cjs +4 -1
  125. package/dist/majorModes.d.mts +2 -2
  126. package/dist/majorModes.mjs +1 -2
  127. package/dist/{piConfig-qGyCbcVj.mjs → piConfig-Bq36PQFF.mjs} +104 -69
  128. package/dist/piConfig-Bq36PQFF.mjs.map +1 -0
  129. package/dist/{piConfig-Bx26HMb_.d.mts → piConfig-C9rGUqPe.d.mts} +3 -3
  130. package/dist/{piConfig-Bx26HMb_.d.mts.map → piConfig-C9rGUqPe.d.mts.map} +1 -1
  131. package/dist/{piConfig-CCBdZXQr.cjs → piConfig-cluCie5i.cjs} +122 -70
  132. package/dist/piConfig-cluCie5i.cjs.map +1 -0
  133. package/dist/piConfig.cjs +4 -1
  134. package/dist/piConfig.d.mts +2 -2
  135. package/dist/piConfig.mjs +1 -2
  136. package/dist/piContext.cjs +27 -16
  137. package/dist/piContext.d.mts +3 -3
  138. package/dist/piContext.mjs +1 -2
  139. package/dist/{profiles-DBcYg5nA.mjs → profiles-CHict0x-.mjs} +322 -101
  140. package/dist/profiles-CHict0x-.mjs.map +1 -0
  141. package/dist/{profiles-tpplXY4r.cjs → profiles-t2EUj0aB.cjs} +359 -102
  142. package/dist/profiles-t2EUj0aB.cjs.map +1 -0
  143. package/dist/profiles.cjs +7 -1
  144. package/dist/profiles.d.mts +27 -3
  145. package/dist/profiles.d.mts.map +1 -1
  146. package/dist/profiles.mjs +1 -2
  147. package/dist/selectionSwitch.cjs +88 -22
  148. package/dist/selectionSwitch.cjs.map +1 -1
  149. package/dist/selectionSwitch.d.mts +40 -18
  150. package/dist/selectionSwitch.d.mts.map +1 -1
  151. package/dist/selectionSwitch.mjs +85 -22
  152. package/dist/selectionSwitch.mjs.map +1 -1
  153. package/dist/{sessionConfig-DV5xTRRw.mjs → sessionConfig-DFQF618G.mjs} +48 -47
  154. package/dist/sessionConfig-DFQF618G.mjs.map +1 -0
  155. package/dist/{sessionConfig-Bf6xHWLd.cjs → sessionConfig-DeP6pplT.cjs} +74 -85
  156. package/dist/sessionConfig-DeP6pplT.cjs.map +1 -0
  157. package/dist/sync-BJ8gCP9s.mjs +29 -0
  158. package/dist/sync-BJ8gCP9s.mjs.map +1 -0
  159. package/dist/sync-CC_15kkB.d.mts +46 -0
  160. package/dist/sync-CC_15kkB.d.mts.map +1 -0
  161. package/dist/sync-Dlxz2msM.cjs +37 -0
  162. package/dist/sync-Dlxz2msM.cjs.map +1 -0
  163. package/dist/types.cjs +2 -2
  164. package/dist/types.d.mts +2 -2
  165. package/dist/types.mjs +1 -2
  166. package/llms.txt +1 -1
  167. package/package.json +16 -16
  168. package/src/prompts/po-author-config/SKILL.md +4 -4
  169. package/src/prompts/po-author-config/agents/openai.yaml +1 -1
  170. package/src/prompts/po-author-config/references/config-contract.md +5 -5
  171. package/dist/atomicJson-1W0WhuFF.mjs +0 -44
  172. package/dist/atomicJson-1W0WhuFF.mjs.map +0 -1
  173. package/dist/atomicJson-Dt2z_DXl.cjs +0 -52
  174. package/dist/atomicJson-Dt2z_DXl.cjs.map +0 -1
  175. package/dist/config-CfTb0_9G.cjs +0 -219
  176. package/dist/config-CfTb0_9G.cjs.map +0 -1
  177. package/dist/config-D2HbBLzo.d.mts.map +0 -1
  178. package/dist/config-DoQWSt1V.mjs +0 -162
  179. package/dist/config-DoQWSt1V.mjs.map +0 -1
  180. package/dist/config-NSHRd6na.mjs +0 -2
  181. package/dist/configPolicy-Ce1QKDxa.cjs.map +0 -1
  182. package/dist/configPolicy-DCQgF5-f.mjs.map +0 -1
  183. package/dist/configWriter-B7uO8MuN.cjs +0 -150
  184. package/dist/configWriter-B7uO8MuN.cjs.map +0 -1
  185. package/dist/configWriter-DUtLgOlD.mjs +0 -130
  186. package/dist/configWriter-DUtLgOlD.mjs.map +0 -1
  187. package/dist/domains-BroCVHrS.mjs.map +0 -1
  188. package/dist/domains-DGCb7uMC.cjs.map +0 -1
  189. package/dist/harnessStore-CJSxdSkV.cjs.map +0 -1
  190. package/dist/harnessStore-CltwLB7M.mjs.map +0 -1
  191. package/dist/index-78zvoS9s.d.mts +0 -35
  192. package/dist/index-78zvoS9s.d.mts.map +0 -1
  193. package/dist/index-BT29GZx5.d.mts.map +0 -1
  194. package/dist/index-C6GaYjq-.d.mts +0 -6
  195. package/dist/index-C6GaYjq-.d.mts.map +0 -1
  196. package/dist/index-CEUc7m16.d.mts.map +0 -1
  197. package/dist/index-CRcoVYXz.d.mts +0 -39
  198. package/dist/index-CRcoVYXz.d.mts.map +0 -1
  199. package/dist/index-CVlciCJF.d.mts +0 -40
  200. package/dist/index-CVlciCJF.d.mts.map +0 -1
  201. package/dist/index-Ch7ptOkW.d.mts.map +0 -1
  202. package/dist/index-CkDDvVQt.d.mts.map +0 -1
  203. package/dist/index-Cvdt-Y-i.d.mts +0 -66
  204. package/dist/index-Cvdt-Y-i.d.mts.map +0 -1
  205. package/dist/index-DNk4q0Qm.d.mts.map +0 -1
  206. package/dist/index-DdH0w56b.d.mts +0 -116
  207. package/dist/index-DdH0w56b.d.mts.map +0 -1
  208. package/dist/init-Cd3Ki6Ub.cjs.map +0 -1
  209. package/dist/init-DVzhiCUE.mjs.map +0 -1
  210. package/dist/layeredConfig-fukqN2EA.mjs +0 -67
  211. package/dist/layeredConfig-fukqN2EA.mjs.map +0 -1
  212. package/dist/layeredConfig-ol0274TN.cjs +0 -94
  213. package/dist/layeredConfig-ol0274TN.cjs.map +0 -1
  214. package/dist/majorModes-D1Itd8SN.mjs.map +0 -1
  215. package/dist/majorModes-DnNSH9ZK.cjs.map +0 -1
  216. package/dist/piConfig-CCBdZXQr.cjs.map +0 -1
  217. package/dist/piConfig-qGyCbcVj.mjs.map +0 -1
  218. package/dist/profiles-DBcYg5nA.mjs.map +0 -1
  219. package/dist/profiles-tpplXY4r.cjs.map +0 -1
  220. package/dist/sessionConfig-Bf6xHWLd.cjs.map +0 -1
  221. package/dist/sessionConfig-DV5xTRRw.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"piConfig-qGyCbcVj.mjs","names":[],"sources":["../src/services/imageSettings/index.ts","../src/services/piConfig/index.ts"],"sourcesContent":["/**\n * The image limits every Po surface applies before an image reaches a model.\n *\n * Pi already owns half of this: `images.autoResize` lives in its settings.json\n * and its resize core hardcodes a 2000px cap. What Pi has no place for is a\n * smaller cap, so `images.maxDimension` is Doom's key written into the same\n * file, because a machine should describe how images reach a model in one\n * place rather than two.\n *\n * A cap above Pi's own is not offered. Pi normalizes every tool result image at\n * 2000px as it enters session history, so a larger number would hold on a\n * pasted image and be silently undone on a read. Clamping says so instead of\n * letting the two surfaces disagree.\n *\n * AVOID:\n * - Reading these keys straight off a config record; a hand-written file holds\n * strings, nulls and negative numbers, and only this parser answers for them.\n */\n\nimport type { PiConfig } from '../../types/piConfig';\n\nexport const IMAGE_SETTINGS_KEY = 'images';\nexport const IMAGE_AUTO_RESIZE_KEY = 'autoResize';\nexport const IMAGE_MAX_DIMENSION_KEY = 'maxDimension';\n\n/** Pi's own cap, from its resize core; also the largest value worth writing. */\nexport const DEFAULT_IMAGE_MAX_DIMENSION = 2000;\n/** Below this a screenshot stops being readable, which is what reads are for. */\nexport const MIN_IMAGE_MAX_DIMENSION = 256;\n\nexport interface PiImageSettings {\n /** Pi's own toggle. Unset is on, matching Pi's default. */\n autoResize: boolean;\n /** The longest edge an image keeps once resizing is on. */\n maxDimension: number;\n}\n\n/** The written form of a change; an absent field leaves that key alone. */\nexport interface PiImageSettingsUpdate {\n autoResize?: boolean;\n maxDimension?: number;\n}\n\nexport function clampImageMaxDimension(value: number): number {\n const rounded = Math.round(value);\n if (rounded < MIN_IMAGE_MAX_DIMENSION) return MIN_IMAGE_MAX_DIMENSION;\n if (rounded > DEFAULT_IMAGE_MAX_DIMENSION) return DEFAULT_IMAGE_MAX_DIMENSION;\n return rounded;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Resolves the effective limits, defaulting anything absent or unusable. */\nexport function parsePiImageSettings(config: PiConfig): PiImageSettings {\n const images = config[IMAGE_SETTINGS_KEY];\n if (!isRecord(images)) return { autoResize: true, maxDimension: DEFAULT_IMAGE_MAX_DIMENSION };\n const autoResize = images[IMAGE_AUTO_RESIZE_KEY];\n const maxDimension = images[IMAGE_MAX_DIMENSION_KEY];\n return {\n autoResize: typeof autoResize === 'boolean' ? autoResize : true,\n maxDimension:\n typeof maxDimension === 'number' && Number.isFinite(maxDimension)\n ? clampImageMaxDimension(maxDimension)\n : DEFAULT_IMAGE_MAX_DIMENSION,\n };\n}\n\n/**\n * Folds a change into the `images` object of a settings document, leaving every\n * other key of that document, and of `images` itself, as it was.\n */\nexport function applyPiImageSettings(config: PiConfig, update: PiImageSettingsUpdate): PiConfig {\n const existing = config[IMAGE_SETTINGS_KEY];\n const images: Record<string, unknown> = isRecord(existing) ? { ...existing } : {};\n if (update.autoResize !== undefined) images[IMAGE_AUTO_RESIZE_KEY] = update.autoResize;\n if (update.maxDimension !== undefined) images[IMAGE_MAX_DIMENSION_KEY] = clampImageMaxDimension(update.maxDimension);\n return { ...config, [IMAGE_SETTINGS_KEY]: images };\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { piAgentDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport type { PiConfig, PiConfigLoadOptions, PiConfigPaths } from '../../types/piConfig';\nimport { writePrivateAtomicJson } from '../atomicJson';\nimport {\n applyPiImageSettings,\n parsePiImageSettings,\n type PiImageSettings,\n type PiImageSettingsUpdate,\n} from '../imageSettings';\n\nconst SETTINGS_FILE_NAME = 'settings.json';\nconst CONFIG_DIR_NAME = '.pi';\nconst LEGACY_CONFIG_DIR_NAME = 'pi';\n\n/** An explicit home other than the real one is isolated from the process environment. */\nfunction defaultAgentDirectory(homeDirectory: string): string {\n return piAgentDirectory(homeDirectory === os.homedir() ? process.env : {}, homeDirectory);\n}\nfunction isObject(value: unknown): value is PiConfig {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction mergeConfig(base: PiConfig, override: PiConfig): PiConfig {\n const result: PiConfig = { ...base };\n for (const [key, value] of Object.entries(override)) {\n const current = result[key];\n result[key] = isObject(current) && isObject(value) ? mergeConfig(current, value) : value;\n }\n return result;\n}\n\nfunction readConfig(filePath: string): PiConfig {\n if (!fs.existsSync(filePath)) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`Could not parse Pi settings at ${filePath}`, { cause: error });\n }\n if (!isObject(parsed)) throw new Error(`Pi settings at ${filePath} must be a JSON object`);\n return parsed;\n}\n\nasync function readConfigAsync(filePath: string): Promise<PiConfig> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fs.promises.readFile(filePath, 'utf8'));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw new Error(`Could not parse Pi settings at ${filePath}`, { cause: error });\n }\n if (!isObject(parsed)) throw new Error(`Pi settings at ${filePath} must be a JSON object`);\n return parsed;\n}\n\nfunction readConfigPaths(paths: readonly string[]): PiConfig {\n return paths.reduce<PiConfig>((config, filePath) => mergeConfig(config, readConfig(filePath)), {});\n}\n\nasync function readConfigPathsAsync(paths: readonly string[]): Promise<PiConfig> {\n const layers = await Promise.all(paths.map(readConfigAsync));\n return layers.reduce<PiConfig>(mergeConfig, {});\n}\n\nfunction projectIsTrusted(value: PiConfigLoadOptions['isProjectTrusted']): boolean {\n return typeof value === 'function' ? value() : value;\n}\n\nexport function piConfigPaths(\n repoRoot: string,\n homeDirectory = os.homedir(),\n agentDirectory = defaultAgentDirectory(homeDirectory),\n): PiConfigPaths {\n return {\n canonicalUser: path.join(agentDirectory, SETTINGS_FILE_NAME),\n canonicalProject: path.join(repoRoot, CONFIG_DIR_NAME, SETTINGS_FILE_NAME),\n legacyUser: [path.join(homeDirectory, CONFIG_DIR_NAME, SETTINGS_FILE_NAME)],\n legacyProject: [path.join(repoRoot, LEGACY_CONFIG_DIR_NAME, SETTINGS_FILE_NAME)],\n };\n}\n\nexport function loadPiConfig(options: PiConfigLoadOptions): PiConfig {\n const paths = piConfigPaths(options.repoRoot, options.homeDirectory);\n const userPaths = [...paths.legacyUser, ...(options.userConfigPaths ?? []), paths.canonicalUser];\n const projectPaths = [...paths.legacyProject, ...(options.projectConfigPaths ?? []), paths.canonicalProject];\n const defaults = options.defaults ?? {};\n const user = readConfigPaths(userPaths);\n const trustedProject = projectIsTrusted(options.isProjectTrusted) ? readConfigPaths(projectPaths) : {};\n return [\n defaults,\n user,\n options.overlay ?? {},\n trustedProject,\n options.environment ?? {},\n options.cli ?? {},\n options.programmatic ?? {},\n ].reduce(mergeConfig, {});\n}\n\nexport async function loadPiConfigAsync(options: PiConfigLoadOptions): Promise<PiConfig> {\n const paths = piConfigPaths(options.repoRoot, options.homeDirectory);\n const userPaths = [...paths.legacyUser, ...(options.userConfigPaths ?? []), paths.canonicalUser];\n const projectPaths = [...paths.legacyProject, ...(options.projectConfigPaths ?? []), paths.canonicalProject];\n const [user, trustedProject] = await Promise.all([\n readConfigPathsAsync(userPaths),\n projectIsTrusted(options.isProjectTrusted) ? readConfigPathsAsync(projectPaths) : Promise.resolve({}),\n ]);\n return [\n options.defaults ?? {},\n user,\n options.overlay ?? {},\n trustedProject,\n options.environment ?? {},\n options.cli ?? {},\n options.programmatic ?? {},\n ].reduce(mergeConfig, {});\n}\n\n/**\n * Where the image limits are read from and written to.\n *\n * The user layer only. Pi merges a trusted project settings.json over it, but\n * these limits describe one machine's tolerance for image payloads rather than\n * one repository's, and the cockpit page that writes them has no repository\n * scope to offer. The legacy user path is still read, because a machine that\n * has not been migrated still answers from it.\n */\nfunction userSettingsPaths(homeDirectory: string): { legacy: string; canonical: string } {\n return {\n legacy: path.join(homeDirectory, CONFIG_DIR_NAME, SETTINGS_FILE_NAME),\n canonical: path.join(defaultAgentDirectory(homeDirectory), SETTINGS_FILE_NAME),\n };\n}\n\n/** The file a change lands in; Pi's own settings toggle writes the same one. */\nexport function piImageSettingsPath(homeDirectory = os.homedir()): string {\n return userSettingsPaths(homeDirectory).canonical;\n}\n\nexport function loadPiImageSettings(homeDirectory = os.homedir()): PiImageSettings {\n const paths = userSettingsPaths(homeDirectory);\n return parsePiImageSettings(readConfigPaths([paths.legacy, paths.canonical]));\n}\n\n/**\n * Writes the changed keys back and reports the limits that now apply.\n *\n * Read-modify-write on Pi's own file, so a save races a concurrent Pi settings\n * save rather than merging with it. Pi writes only the fields its UI touched,\n * as this does, which keeps the window to the one setting being changed on\n * both sides at once.\n */\nexport function savePiImageSettings(update: PiImageSettingsUpdate, homeDirectory = os.homedir()): PiImageSettings {\n const paths = userSettingsPaths(homeDirectory);\n writePrivateAtomicJson(paths.canonical, applyPiImageSettings(readConfig(paths.canonical), update));\n return loadPiImageSettings(homeDirectory);\n}\n"],"mappings":";;;;;;AAqBA,MAAa,qBAAqB;AAClC,MAAa,wBAAwB;AACrC,MAAa,0BAA0B;;AAGvC,MAAa,8BAA8B;;AAE3C,MAAa,0BAA0B;AAevC,SAAgB,uBAAuB,OAAuB;CAC5D,MAAM,UAAU,KAAK,MAAM,KAAK;CAChC,IAAI,UAAA,KAAmC,OAAA;CACvC,IAAI,UAAA,KAAuC,OAAO;CAClD,OAAO;AACT;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;AAGA,SAAgB,qBAAqB,QAAmC;CACtE,MAAM,SAAS,OAAO;CACtB,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;EAAE,YAAY;EAAM,cAAc;CAA4B;CAC5F,MAAM,aAAa,OAAO;CAC1B,MAAM,eAAe,OAAO;CAC5B,OAAO;EACL,YAAY,OAAO,eAAe,YAAY,aAAa;EAC3D,cACE,OAAO,iBAAiB,YAAY,OAAO,SAAS,YAAY,IAC5D,uBAAuB,YAAY,IACnC;CACR;AACF;;;;;AAMA,SAAgB,qBAAqB,QAAkB,QAAyC;CAC9F,MAAM,WAAW,OAAO;CACxB,MAAM,SAAkC,SAAS,QAAQ,IAAI,EAAE,GAAG,SAAS,IAAI,CAAC;CAChF,IAAI,OAAO,eAAe,KAAA,GAAW,OAAO,yBAAyB,OAAO;CAC5E,IAAI,OAAO,iBAAiB,KAAA,GAAW,OAAO,2BA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AqB,WAAW,MAAM,SAAS,GAAG,MAAM,CAAC;CACjG,OAAO,oBAAoB,aAAa;AAC1C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiles-DBcYg5nA.mjs","names":["isRecord","parseYaml","PARENT_DIRECTORY"],"sources":["../src/services/personaFrontMatter/index.ts","../src/services/personaIcon/index.ts","../src/services/profileBinding/index.ts","../src/services/profiles/index.ts"],"sourcesContent":["import { parse as parseYaml } from 'yaml';\n\nimport type { PersonaDocument, PersonaFrontMatter, PersonaVoiceOverride } from '../../types/profiles';\n\n/**\n * Optional identity a persona declares at the top of its `profile.md`.\n *\n * A profile used to be prompt text only, so there was nowhere to say who the\n * persona is or how it should sound. Front-matter puts that beside the persona\n * text it describes, which is the only place that works for both explicit\n * `profiles.yaml` entries and folders found by root discovery.\n *\n * Recognition is deliberately narrow. Personas that exist today were written\n * without any of this, and one of them may legitimately open with a horizontal\n * rule, so a leading fence alone is not enough to claim the block. A block is\n * only treated as identity when it is fenced at the very first line, closed,\n * parses as a mapping, and declares at least one field this contract owns.\n * Anything else is passed through byte for byte.\n */\n\nconst FENCE = '---';\nconst OWNED_KEYS = ['name', 'icon', 'voice'] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readVoice(value: unknown): PersonaVoiceOverride | undefined {\n if (!isRecord(value)) return undefined;\n const voice = typeof value.voice === 'string' && value.voice.trim().length > 0 ? value.voice.trim() : undefined;\n const rate = typeof value.rate === 'number' && Number.isFinite(value.rate) ? value.rate : undefined;\n if (voice === undefined && rate === undefined) return undefined;\n return { ...(voice === undefined ? {} : { voice }), ...(rate === undefined ? {} : { rate }) };\n}\n\nfunction readFrontMatter(parsed: Record<string, unknown>): PersonaFrontMatter | undefined {\n const name = typeof parsed.name === 'string' && parsed.name.trim().length > 0 ? parsed.name.trim() : undefined;\n const icon = typeof parsed.icon === 'string' && parsed.icon.trim().length > 0 ? parsed.icon.trim() : undefined;\n const voice = readVoice(parsed.voice);\n if (name === undefined && icon === undefined && voice === undefined) return undefined;\n return {\n ...(name === undefined ? {} : { name }),\n ...(icon === undefined ? {} : { icon }),\n ...(voice === undefined ? {} : { voice }),\n };\n}\n\n/**\n * Splits a recognised identity block off a persona document.\n *\n * Never throws: a malformed avatar must not make a persona unloadable, so an\n * unparseable or unrecognised block leaves the document exactly as it arrived.\n */\nexport function parsePersonaFrontMatter(content: string): PersonaDocument {\n const lines = content.split('\\n');\n if (lines[0]?.trimEnd() !== FENCE) return { body: content };\n\n const closingIndex = lines.findIndex((line, index) => index > 0 && line.trimEnd() === FENCE);\n if (closingIndex === -1) return { body: content };\n\n let parsed: unknown;\n try {\n parsed = parseYaml(lines.slice(1, closingIndex).join('\\n'));\n } catch {\n return { body: content };\n }\n if (!isRecord(parsed)) return { body: content };\n if (!OWNED_KEYS.some((key) => Object.hasOwn(parsed, key))) return { body: content };\n\n const frontMatter = readFrontMatter(parsed);\n if (!frontMatter) return { body: content };\n return { frontMatter, body: lines.slice(closingIndex + 1).join('\\n') };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { PROFILE_ICON_MAX_DATA_URL_LENGTH, type ProfileIconMimeType } from '@agimon-ai/po-core/profileIdentity';\n\n/**\n * Reads a persona icon into a bounded `data:` URL.\n *\n * The icon travels inside the journalled identity entry rather than through an\n * HTTP route. A route would leave a request-time filesystem resolution reachable\n * from the browser for the life of a session, defended on every request forever;\n * this resolves the path once, server side, at the moment the profile loads.\n *\n * The path comes from user-authored front-matter, so it is confined the same way\n * `buildPersonaPrompt` confines persona files: a symlink must not read outside\n * the persona directory.\n *\n * Every failure is silent and returns undefined. An avatar is decoration, and a\n * broken one must never stop a persona from loading.\n */\nconst PARENT_DIRECTORY = '..';\n\n/**\n * Magic-byte signatures, checked instead of trusting the filename.\n *\n * `image/svg+xml` is absent on purpose: an SVG rendered same-origin executes\n * script, and the author of this path is whoever wrote the persona. Do not add\n * it to match the cockpit's broader media catalog.\n */\nconst SIGNATURES: readonly { readonly mime: ProfileIconMimeType; readonly test: (bytes: Buffer) => boolean }[] = [\n {\n mime: 'image/png',\n test: (b) => b.length > 8 && b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),\n },\n { mime: 'image/jpeg', test: (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },\n { mime: 'image/gif', test: (b) => b.length > 6 && b.subarray(0, 6).toString('latin1').startsWith('GIF8') },\n {\n mime: 'image/webp',\n test: (b) =>\n b.length > 12 &&\n b.subarray(0, 4).toString('latin1') === 'RIFF' &&\n b.subarray(8, 12).toString('latin1') === 'WEBP',\n },\n];\n\nfunction sniff(bytes: Buffer): ProfileIconMimeType | undefined {\n return SIGNATURES.find((signature) => signature.test(bytes))?.mime;\n}\n\n/**\n * Resolves an icon declared in persona front-matter, or undefined when it is\n * missing, unreadable, not an allowed image, escapes the persona directory, or\n * exceeds the data-URL ceiling.\n */\nexport function readPersonaIcon(personaPath: string, iconRelative: string): string | undefined {\n if (path.isAbsolute(iconRelative)) return undefined;\n\n try {\n const realPersonaPath = fs.realpathSync(personaPath);\n const iconPath = path.resolve(realPersonaPath, iconRelative);\n if (!fs.existsSync(iconPath)) return undefined;\n\n const realIconPath = fs.realpathSync(iconPath);\n const relative = path.relative(realPersonaPath, realIconPath);\n if (\n relative === PARENT_DIRECTORY ||\n relative.startsWith(`${PARENT_DIRECTORY}${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n return undefined;\n }\n if (!fs.statSync(realIconPath).isFile()) return undefined;\n\n const bytes = fs.readFileSync(realIconPath);\n const mime = sniff(bytes);\n if (!mime) return undefined;\n\n const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;\n return dataUrl.length > PROFILE_ICON_MAX_DATA_URL_LENGTH ? undefined : dataUrl;\n } catch {\n return undefined;\n }\n}\n","import type { ProfileBrowserBinding, ProfileIntegrationBinding, ProfileSecretReference } from './type';\n\nconst BINDING_KEYS = new Set(['provider', 'organizationId', 'mailboxId', 'credentialRef', 'secrets', 'browser']);\nconst SECRET_KEYS = new Set(['credentialId', 'field', 'allowedOrigins']);\nconst BROWSER_KEYS = new Set(['profileName', 'allowedOrigins']);\nconst ALIAS_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;\nconst FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;\nconst BROWSER_PROFILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;\n\nfunction record(value: unknown, location: string, keys?: ReadonlySet<string>): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`${location} must be a mapping`);\n }\n if (keys && Object.keys(value).some((key) => !keys.has(key))) {\n // Never echo an unknown key or value, either of which might contain a misplaced secret.\n throw new Error(`${location} contains unsupported metadata`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction reference(value: unknown, location: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256 || /\\s/.test(value)) {\n throw new Error(`${location} must be a non-empty reference without whitespace`);\n }\n return value;\n}\n\nfunction origins(value: unknown, location: string): readonly string[] {\n if (!Array.isArray(value) || value.length === 0) throw new Error(`${location} must contain exact HTTP(S) origins`);\n const result = value.map((entry: unknown) => {\n if (typeof entry !== 'string') throw new Error(`${location} must contain exact HTTP(S) origins`);\n let url: URL;\n try {\n url = new URL(entry);\n } catch {\n throw new Error(`${location} must contain exact HTTP(S) origins`);\n }\n if (\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.origin !== entry ||\n url.username ||\n url.password\n ) {\n throw new Error(`${location} must contain exact HTTP(S) origins`);\n }\n return entry;\n });\n return Object.freeze([...new Set(result)]);\n}\n\nfunction browser(value: unknown, location: string): ProfileBrowserBinding {\n const entry = record(value, location, BROWSER_KEYS);\n if (typeof entry.profileName !== 'string' || !BROWSER_PROFILE_PATTERN.test(entry.profileName)) {\n throw new Error(`${location}.profileName must be a safe browser profile name`);\n }\n return Object.freeze({\n profileName: entry.profileName,\n allowedOrigins: origins(entry.allowedOrigins, `${location}.allowedOrigins`),\n });\n}\n\n/** Validates and deeply freezes a detached metadata snapshot. No provider SDK or secret is loaded. */\nexport function parseProfileBinding(value: unknown, location = 'Profile integration'): ProfileIntegrationBinding {\n const entry = record(value, location, BINDING_KEYS);\n const sourceSecrets = record(entry.secrets, `${location}.secrets`);\n const secrets: Record<string, ProfileSecretReference> = {};\n for (const [alias, value] of Object.entries(sourceSecrets)) {\n if (!ALIAS_PATTERN.test(alias)) throw new Error(`${location}.secrets requires uppercase alias names`);\n const secret = record(value, `${location}.secrets.${alias}`, SECRET_KEYS);\n if (typeof secret.field !== 'string' || !FIELD_PATTERN.test(secret.field)) {\n throw new Error(`${location}.secrets.${alias}.field must be a credential field name`);\n }\n secrets[alias] = Object.freeze({\n credentialId: reference(secret.credentialId, `${location}.secrets.${alias}.credentialId`),\n field: secret.field,\n allowedOrigins: origins(secret.allowedOrigins, `${location}.secrets.${alias}.allowedOrigins`),\n });\n }\n const browserBinding = entry.browser === undefined ? undefined : browser(entry.browser, `${location}.browser`);\n if (\n browserBinding &&\n Object.values(secrets).some((secret) =>\n secret.allowedOrigins.some((origin) => !browserBinding.allowedOrigins.includes(origin)),\n )\n ) {\n throw new Error(`${location} secret origins must be included in browser.allowedOrigins`);\n }\n return Object.freeze({\n provider: reference(entry.provider, `${location}.provider`),\n organizationId: reference(entry.organizationId, `${location}.organizationId`),\n mailboxId: reference(entry.mailboxId, `${location}.mailboxId`),\n credentialRef: reference(entry.credentialRef, `${location}.credentialRef`),\n secrets: Object.freeze(secrets),\n ...(browserBinding === undefined ? {} : { browser: browserBinding }),\n });\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport type { PersonaIdentity } from '../../types/profiles';\nimport { type PersonaFrontMatter, type PersonaVoiceOverride } from '../../types/profiles';\nimport { readDoomConfigSources } from '../layeredConfig';\nimport { parsePersonaFrontMatter } from '../personaFrontMatter';\nimport { readPersonaIcon } from '../personaIcon';\nimport { parseProfileBinding } from '../profileBinding';\nimport type { ProfileIntegrationBinding } from '../profileBinding/type';\n\n/** Files that make up one repository persona, concatenated in this order. */\nexport const PERSONA_FILES = ['profile.md', 'SOUL.md', 'AGENTS.md'];\n\n/** The persona file that may carry an identity block; the others are prose only. */\nconst PERSONA_IDENTITY_FILE = 'profile.md';\n\n/** A persona's resolved presentation: display name, and an icon already read into a data URL. */\n\nexport interface AgentProfile {\n name: string;\n /** Directory relative to personaRoot, which remains the persona source. */\n persona: string;\n /**\n * Root the persona path resolves against: the repository root for a\n * repository profile, the global `.po` directory for a global one.\n */\n personaRoot: string;\n /** Environment defaults. Values already exported by the caller win. */\n env: Record<string, string>;\n /** Nonsecret integration metadata. Resolved secrets never enter profile environment. */\n integration?: ProfileIntegrationBinding;\n /** Display name and avatar declared in the persona's own front-matter. */\n identity?: PersonaIdentity;\n /** Narrowly scoped TTS override declared alongside the identity. */\n voice?: PersonaVoiceOverride;\n}\n\ninterface ProfileConfigLayer {\n filePath: string;\n baseDirectory: string;\n roots: string[];\n entries: Record<string, unknown>;\n defaultProfile?: string;\n}\n\nconst PROFILE_KEYS = new Set(['persona', 'env', 'integration']);\nconst PROFILE_CATALOG_KEYS = new Set(['roots', 'entries', 'defaultProfile']);\nconst PROFILES_FILE = 'profiles.yaml';\nconst PROFILES_ROOT_KEY = 'profiles';\nconst AGENTS_DIRECTORY = 'agents';\nconst PARENT_DIRECTORY = '..';\nconst TEXT_ENCODING = 'utf8';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return (\n relative === '' ||\n (!path.isAbsolute(relative) &&\n relative !== PARENT_DIRECTORY &&\n !relative.startsWith(`${PARENT_DIRECTORY}${path.sep}`))\n );\n}\n\nfunction parseEnvironment(name: string, value: unknown): Record<string, string> {\n if (value === undefined) return {};\n if (!isRecord(value)) throw new Error(`Profile \"${name}\" env must be a string mapping`);\n\n const environment: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (typeof entry !== 'string') throw new Error(`Profile \"${name}\" env.${key} must be a string`);\n if (entry.includes('${secrets.')) throw new Error(`Profile \"${name}\" env cannot contain secret aliases`);\n environment[key] = entry;\n }\n return environment;\n}\n\nfunction parseProfileRoots(value: unknown, filePath: string, baseDirectory: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new Error(`profiles.roots in ${filePath} must be an array`);\n return value.map((entry, index) => {\n if (typeof entry !== 'string' || entry.trim().length === 0) {\n throw new Error(`profiles.roots[${index}] in ${filePath} must be a non-empty string`);\n }\n return path.resolve(baseDirectory, entry.trim());\n });\n}\n\nfunction parseProfileLayer(source: { filePath: string; baseDirectory: string; document: unknown }): ProfileConfigLayer {\n if (!isRecord(source.document) || !isRecord(source.document[PROFILES_ROOT_KEY])) {\n throw new Error(`${source.filePath} must contain a profiles mapping`);\n }\n const unsupportedDocumentKeys = Object.keys(source.document).filter((key) => key !== PROFILES_ROOT_KEY);\n if (unsupportedDocumentKeys.length > 0) {\n throw new Error(`${source.filePath} may only contain profiles; unsupported: ${unsupportedDocumentKeys.join(', ')}`);\n }\n\n const profiles = source.document[PROFILES_ROOT_KEY];\n const usesCatalogShape = Object.hasOwn(profiles, 'roots') || Object.hasOwn(profiles, 'entries');\n if (!usesCatalogShape) {\n return { filePath: source.filePath, baseDirectory: source.baseDirectory, roots: [], entries: profiles };\n }\n\n const unsupportedCatalogKeys = Object.keys(profiles).filter((key) => !PROFILE_CATALOG_KEYS.has(key));\n if (unsupportedCatalogKeys.length > 0) {\n throw new Error(\n `profiles in ${source.filePath} may only contain roots, entries and defaultProfile; unsupported: ${unsupportedCatalogKeys.join(', ')}`,\n );\n }\n if (\n profiles.defaultProfile !== undefined &&\n (typeof profiles.defaultProfile !== 'string' || profiles.defaultProfile.trim().length === 0)\n ) {\n throw new Error(`profiles.defaultProfile in ${source.filePath} must be a non-empty string`);\n }\n if (profiles.entries !== undefined && !isRecord(profiles.entries)) {\n throw new Error(`profiles.entries in ${source.filePath} must be a mapping`);\n }\n return {\n filePath: source.filePath,\n baseDirectory: source.baseDirectory,\n roots: parseProfileRoots(profiles.roots, source.filePath, source.baseDirectory),\n entries: profiles.entries ?? {},\n ...(profiles.defaultProfile === undefined ? {} : { defaultProfile: String(profiles.defaultProfile).trim() }),\n };\n}\n\nfunction assertProfileInsideAllowedRoot(name: string, personaPath: string, lexicalRoots: readonly string[]): void {\n const realPersonaPath = fs.realpathSync(personaPath);\n if (!lexicalRoots.some((root) => isPathInside(fs.realpathSync(root), realPersonaPath))) {\n throw new Error(`Profile \"${name}\" persona must stay inside agents/ or a configured profile root`);\n }\n}\n\nfunction parseProfile(\n personaRoot: string,\n configuredRoots: readonly string[],\n name: string,\n value: unknown,\n): AgentProfile {\n if (!isRecord(value)) throw new Error(`Profile \"${name}\" must be a mapping`);\n\n const unsupported = Object.keys(value).filter((key) => !PROFILE_KEYS.has(key));\n if (unsupported.length > 0) {\n throw new Error(\n `Profile \"${name}\" may only set persona, env and integration; unsupported: ${unsupported.join(', ')}`,\n );\n }\n if (typeof value.persona !== 'string' || value.persona.trim().length === 0) {\n throw new Error(`Profile \"${name}\" must set a persona`);\n }\n if (path.isAbsolute(value.persona)) {\n throw new Error(`Profile \"${name}\" persona must be relative to the config that declares it`);\n }\n\n const persona = value.persona;\n const personaPath = path.resolve(personaRoot, persona);\n const lexicalRoots = [path.resolve(personaRoot, AGENTS_DIRECTORY), ...configuredRoots].filter((root) =>\n isPathInside(root, personaPath),\n );\n if (lexicalRoots.length === 0) {\n throw new Error(`Profile \"${name}\" persona must stay inside agents/ or a configured profile root`);\n }\n if (!fs.existsSync(personaPath) || !fs.statSync(personaPath).isDirectory()) {\n throw new Error(`Profile \"${name}\" references a missing persona: ${persona}`);\n }\n assertProfileInsideAllowedRoot(name, personaPath, lexicalRoots);\n if (!buildPersonaPrompt(personaRoot, persona)) {\n // An identity block is not persona text, so a profile.md holding nothing else\n // leaves the persona empty. Say that, rather than claiming the file is unreadable.\n const declaresIdentity = readPersonaFrontMatter(personaRoot, persona) !== undefined;\n throw new Error(\n declaresIdentity\n ? `Profile \"${name}\" persona declares identity front-matter but no persona text: ${persona}`\n : `Profile \"${name}\" persona has no readable persona files: ${persona}`,\n );\n }\n\n return {\n name,\n persona,\n personaRoot,\n env: parseEnvironment(name, value.env),\n ...(value.integration === undefined\n ? {}\n : { integration: parseProfileBinding(value.integration, `Profile \"${name}\" integration`) }),\n ...readPersonaPresentation(personaRoot, persona),\n };\n}\n\nfunction containsPersonaFile(directory: string): boolean {\n return PERSONA_FILES.some((file) => {\n try {\n return fs.lstatSync(path.join(directory, file)).isFile();\n } catch {\n return false;\n }\n });\n}\n\nfunction discoverProfile(directory: string, configuredRoot: string, personaRoot: string): AgentProfile | undefined {\n if (!containsPersonaFile(directory)) return undefined;\n try {\n const realConfiguredRoot = fs.realpathSync(configuredRoot);\n const realDirectory = fs.realpathSync(directory);\n if (!isPathInside(realConfiguredRoot, realDirectory)) return undefined;\n const persona = path.relative(personaRoot, directory) || '.';\n if (!buildPersonaPrompt(personaRoot, persona)) return undefined;\n return {\n name: path.basename(directory),\n persona,\n personaRoot,\n env: {},\n ...readPersonaPresentation(personaRoot, persona),\n };\n } catch {\n // Automatic discovery ignores unreadable or unsafe candidates; explicit entries remain fatal.\n return undefined;\n }\n}\n\nfunction discoverProfileRoot(root: string, personaRoot: string): AgentProfile[] {\n if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {\n throw new Error(`Configured profile root is not a directory: ${root}`);\n }\n\n const rootProfile = discoverProfile(root, root, personaRoot);\n if (rootProfile) return [rootProfile];\n\n return fs\n .readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .sort((left, right) => left.name.localeCompare(right.name))\n .flatMap((entry) => {\n const profile = discoverProfile(path.join(root, entry.name), root, personaRoot);\n return profile ? [profile] : [];\n });\n}\n\n/**\n * Loads profiles from the global and repository configs, repository last.\n *\n * Configured roots accumulate and inspect themselves or their direct-child\n * directories for persona files. Later discoveries replace earlier names, and\n * explicit entries replace discoveries. Legacy flat profile mappings remain\n * accepted as explicit entries.\n */\nexport function loadProfiles(repoRoot: string, homeDirectory: string = os.homedir()): AgentProfile[] {\n const layers = readDoomConfigSources<unknown>(PROFILES_FILE, repoRoot, homeDirectory).map(parseProfileLayer);\n const byName = new Map<string, AgentProfile>();\n\n for (const layer of layers) {\n for (const root of layer.roots) {\n for (const profile of discoverProfileRoot(root, layer.baseDirectory)) byName.set(profile.name, profile);\n }\n }\n\n for (const layer of layers) {\n for (const [name, value] of Object.entries(layer.entries)) {\n byName.set(name, parseProfile(layer.baseDirectory, layer.roots, name, value));\n }\n }\n\n return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));\n}\n\n/**\n * The profile catalog: every resolved profile, plus the name a launch starts on\n * when the caller names none.\n *\n * `defaultProfile` mirrors `defaultMajorMode` in modes.yaml and `defaultDomains`\n * in domains.yaml, so each selection axis declares its default in its own\n * catalog. A repository declaration replaces a personal one. An unknown name is\n * an error rather than a silent fallback: a typo that quietly starts the session\n * with no persona is worse than a refused launch.\n */\nexport function loadProfileCatalog(\n repoRoot: string,\n homeDirectory: string = os.homedir(),\n): { profiles: AgentProfile[]; defaultProfile?: string } {\n const layers = readDoomConfigSources<unknown>(PROFILES_FILE, repoRoot, homeDirectory).map(parseProfileLayer);\n const profiles = loadProfiles(repoRoot, homeDirectory);\n let defaultProfile: string | undefined;\n for (const layer of layers) {\n if (layer.defaultProfile !== undefined) defaultProfile = layer.defaultProfile;\n }\n if (defaultProfile !== undefined && !profiles.some((profile) => profile.name === defaultProfile)) {\n throw new Error(`profiles.defaultProfile names an unknown profile: ${defaultProfile}`);\n }\n return { profiles, ...(defaultProfile === undefined ? {} : { defaultProfile }) };\n}\n\n/** Resolves one selected profile and fails clearly when its name is unknown. */\nexport function resolveProfile(repoRoot: string, name: string, homeDirectory?: string): AgentProfile {\n const profile = loadProfiles(repoRoot, homeDirectory).find((candidate) => candidate.name === name);\n if (!profile) throw new Error(`Unknown profile: ${name}`);\n return profile;\n}\n\nexport function listProfileNames(repoRoot: string, homeDirectory?: string): string[] {\n return loadProfiles(repoRoot, homeDirectory).map((profile) => profile.name);\n}\n\n/**\n * Reads the identity block from a persona's `profile.md`.\n *\n * Separate from `buildPersonaPrompt` because the prompt is assembled on several\n * paths that do not want the icon bytes, and because a persona that declares\n * nothing must stay exactly as cheap as it is today.\n */\nfunction readPersonaPresentation(\n personaRoot: string,\n personaDirectory: string,\n): { identity?: PersonaIdentity; voice?: PersonaVoiceOverride } {\n const frontMatter = readPersonaFrontMatter(personaRoot, personaDirectory);\n if (!frontMatter) return {};\n\n const icon =\n frontMatter.icon === undefined\n ? undefined\n : readPersonaIcon(path.join(personaRoot, personaDirectory), frontMatter.icon);\n const identity: PersonaIdentity = {\n ...(frontMatter.name === undefined ? {} : { name: frontMatter.name }),\n ...(icon === undefined ? {} : { icon }),\n };\n return {\n ...(identity.name === undefined && identity.icon === undefined ? {} : { identity }),\n ...(frontMatter.voice === undefined ? {} : { voice: frontMatter.voice }),\n };\n}\n\nfunction readPersonaFrontMatter(personaRoot: string, personaDirectory: string): PersonaFrontMatter | undefined {\n try {\n const personaPath = fs.realpathSync(path.join(personaRoot, personaDirectory));\n const filePath = path.join(personaPath, PERSONA_IDENTITY_FILE);\n if (!fs.existsSync(filePath)) return undefined;\n return parsePersonaFrontMatter(fs.readFileSync(fs.realpathSync(filePath), TEXT_ENCODING)).frontMatter;\n } catch {\n return undefined;\n }\n}\n/** Builds the persona system-prompt block, or undefined when nothing is readable. */\nexport function buildPersonaPrompt(personaRoot: string, personaDirectory: string): string | undefined {\n const sections: string[] = [];\n const personaPath = fs.realpathSync(path.join(personaRoot, personaDirectory));\n for (const file of PERSONA_FILES) {\n const filePath = path.join(personaPath, file);\n if (!fs.existsSync(filePath)) continue;\n const realFilePath = fs.realpathSync(filePath);\n const relativeFilePath = path.relative(personaPath, realFilePath);\n if (relativeFilePath === PARENT_DIRECTORY || relativeFilePath.startsWith(`${PARENT_DIRECTORY}${path.sep}`)) {\n throw new Error(`Persona file must stay inside ${personaDirectory}: ${file}`);\n }\n const raw = fs.readFileSync(realFilePath, TEXT_ENCODING);\n // Only profile.md may declare identity, so only profile.md is stripped.\n const content = (file === PERSONA_IDENTITY_FILE ? parsePersonaFrontMatter(raw).body : raw).trim();\n if (content) sections.push(content);\n }\n if (sections.length === 0) return undefined;\n return [`[PERSONA] You are operating as the person described below (source: ${personaDirectory}).`, ...sections].join(\n '\\n\\n',\n );\n}\n\n/** Applies profile environment defaults and returns only the values it contributed. */\nexport function applyProfileEnvironment(\n environment: NodeJS.ProcessEnv,\n defaults: Record<string, string>,\n): Record<string, string> {\n const applied: Record<string, string> = {};\n for (const [key, value] of Object.entries(defaults)) {\n if (environment[key] !== undefined) continue;\n environment[key] = value;\n applied[key] = value;\n }\n return applied;\n}\n\n/** Replaces environment defaults previously contributed by another profile. */\nexport function replaceProfileEnvironment(\n environment: NodeJS.ProcessEnv,\n previous: Record<string, string>,\n next: Record<string, string>,\n): Record<string, string> {\n for (const [key, value] of Object.entries(previous)) {\n if (environment[key] === value) delete environment[key];\n }\n return applyProfileEnvironment(environment, next);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,QAAQ;AACd,MAAM,aAAa;CAAC;CAAQ;CAAQ;AAAO;AAE3C,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,UAAU,OAAkD;CACnE,IAAI,CAACA,WAAS,KAAK,GAAG,OAAO,KAAA;CAC7B,MAAM,QAAQ,OAAO,MAAM,UAAU,YAAY,MAAM,MAAM,KAAK,CAAC,CAAC,SAAS,IAAI,MAAM,MAAM,KAAK,IAAI,KAAA;CACtG,MAAM,OAAO,OAAO,MAA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,OAAO,wBAAwB,aAAa,IAAI;AAClD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"profiles-tpplXY4r.cjs","names":["isRecord","parseYaml","PARENT_DIRECTORY","path","fs","PROFILE_ICON_MAX_DATA_URL_LENGTH","path","fs","os","readDoomConfigSources"],"sources":["../src/services/personaFrontMatter/index.ts","../src/services/personaIcon/index.ts","../src/services/profileBinding/index.ts","../src/services/profiles/index.ts"],"sourcesContent":["import { parse as parseYaml } from 'yaml';\n\nimport type { PersonaDocument, PersonaFrontMatter, PersonaVoiceOverride } from '../../types/profiles';\n\n/**\n * Optional identity a persona declares at the top of its `profile.md`.\n *\n * A profile used to be prompt text only, so there was nowhere to say who the\n * persona is or how it should sound. Front-matter puts that beside the persona\n * text it describes, which is the only place that works for both explicit\n * `profiles.yaml` entries and folders found by root discovery.\n *\n * Recognition is deliberately narrow. Personas that exist today were written\n * without any of this, and one of them may legitimately open with a horizontal\n * rule, so a leading fence alone is not enough to claim the block. A block is\n * only treated as identity when it is fenced at the very first line, closed,\n * parses as a mapping, and declares at least one field this contract owns.\n * Anything else is passed through byte for byte.\n */\n\nconst FENCE = '---';\nconst OWNED_KEYS = ['name', 'icon', 'voice'] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction readVoice(value: unknown): PersonaVoiceOverride | undefined {\n if (!isRecord(value)) return undefined;\n const voice = typeof value.voice === 'string' && value.voice.trim().length > 0 ? value.voice.trim() : undefined;\n const rate = typeof value.rate === 'number' && Number.isFinite(value.rate) ? value.rate : undefined;\n if (voice === undefined && rate === undefined) return undefined;\n return { ...(voice === undefined ? {} : { voice }), ...(rate === undefined ? {} : { rate }) };\n}\n\nfunction readFrontMatter(parsed: Record<string, unknown>): PersonaFrontMatter | undefined {\n const name = typeof parsed.name === 'string' && parsed.name.trim().length > 0 ? parsed.name.trim() : undefined;\n const icon = typeof parsed.icon === 'string' && parsed.icon.trim().length > 0 ? parsed.icon.trim() : undefined;\n const voice = readVoice(parsed.voice);\n if (name === undefined && icon === undefined && voice === undefined) return undefined;\n return {\n ...(name === undefined ? {} : { name }),\n ...(icon === undefined ? {} : { icon }),\n ...(voice === undefined ? {} : { voice }),\n };\n}\n\n/**\n * Splits a recognised identity block off a persona document.\n *\n * Never throws: a malformed avatar must not make a persona unloadable, so an\n * unparseable or unrecognised block leaves the document exactly as it arrived.\n */\nexport function parsePersonaFrontMatter(content: string): PersonaDocument {\n const lines = content.split('\\n');\n if (lines[0]?.trimEnd() !== FENCE) return { body: content };\n\n const closingIndex = lines.findIndex((line, index) => index > 0 && line.trimEnd() === FENCE);\n if (closingIndex === -1) return { body: content };\n\n let parsed: unknown;\n try {\n parsed = parseYaml(lines.slice(1, closingIndex).join('\\n'));\n } catch {\n return { body: content };\n }\n if (!isRecord(parsed)) return { body: content };\n if (!OWNED_KEYS.some((key) => Object.hasOwn(parsed, key))) return { body: content };\n\n const frontMatter = readFrontMatter(parsed);\n if (!frontMatter) return { body: content };\n return { frontMatter, body: lines.slice(closingIndex + 1).join('\\n') };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { PROFILE_ICON_MAX_DATA_URL_LENGTH, type ProfileIconMimeType } from '@agimon-ai/po-core/profileIdentity';\n\n/**\n * Reads a persona icon into a bounded `data:` URL.\n *\n * The icon travels inside the journalled identity entry rather than through an\n * HTTP route. A route would leave a request-time filesystem resolution reachable\n * from the browser for the life of a session, defended on every request forever;\n * this resolves the path once, server side, at the moment the profile loads.\n *\n * The path comes from user-authored front-matter, so it is confined the same way\n * `buildPersonaPrompt` confines persona files: a symlink must not read outside\n * the persona directory.\n *\n * Every failure is silent and returns undefined. An avatar is decoration, and a\n * broken one must never stop a persona from loading.\n */\nconst PARENT_DIRECTORY = '..';\n\n/**\n * Magic-byte signatures, checked instead of trusting the filename.\n *\n * `image/svg+xml` is absent on purpose: an SVG rendered same-origin executes\n * script, and the author of this path is whoever wrote the persona. Do not add\n * it to match the cockpit's broader media catalog.\n */\nconst SIGNATURES: readonly { readonly mime: ProfileIconMimeType; readonly test: (bytes: Buffer) => boolean }[] = [\n {\n mime: 'image/png',\n test: (b) => b.length > 8 && b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),\n },\n { mime: 'image/jpeg', test: (b) => b.length > 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },\n { mime: 'image/gif', test: (b) => b.length > 6 && b.subarray(0, 6).toString('latin1').startsWith('GIF8') },\n {\n mime: 'image/webp',\n test: (b) =>\n b.length > 12 &&\n b.subarray(0, 4).toString('latin1') === 'RIFF' &&\n b.subarray(8, 12).toString('latin1') === 'WEBP',\n },\n];\n\nfunction sniff(bytes: Buffer): ProfileIconMimeType | undefined {\n return SIGNATURES.find((signature) => signature.test(bytes))?.mime;\n}\n\n/**\n * Resolves an icon declared in persona front-matter, or undefined when it is\n * missing, unreadable, not an allowed image, escapes the persona directory, or\n * exceeds the data-URL ceiling.\n */\nexport function readPersonaIcon(personaPath: string, iconRelative: string): string | undefined {\n if (path.isAbsolute(iconRelative)) return undefined;\n\n try {\n const realPersonaPath = fs.realpathSync(personaPath);\n const iconPath = path.resolve(realPersonaPath, iconRelative);\n if (!fs.existsSync(iconPath)) return undefined;\n\n const realIconPath = fs.realpathSync(iconPath);\n const relative = path.relative(realPersonaPath, realIconPath);\n if (\n relative === PARENT_DIRECTORY ||\n relative.startsWith(`${PARENT_DIRECTORY}${path.sep}`) ||\n path.isAbsolute(relative)\n ) {\n return undefined;\n }\n if (!fs.statSync(realIconPath).isFile()) return undefined;\n\n const bytes = fs.readFileSync(realIconPath);\n const mime = sniff(bytes);\n if (!mime) return undefined;\n\n const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;\n return dataUrl.length > PROFILE_ICON_MAX_DATA_URL_LENGTH ? undefined : dataUrl;\n } catch {\n return undefined;\n }\n}\n","import type { ProfileBrowserBinding, ProfileIntegrationBinding, ProfileSecretReference } from './type';\n\nconst BINDING_KEYS = new Set(['provider', 'organizationId', 'mailboxId', 'credentialRef', 'secrets', 'browser']);\nconst SECRET_KEYS = new Set(['credentialId', 'field', 'allowedOrigins']);\nconst BROWSER_KEYS = new Set(['profileName', 'allowedOrigins']);\nconst ALIAS_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;\nconst FIELD_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;\nconst BROWSER_PROFILE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;\n\nfunction record(value: unknown, location: string, keys?: ReadonlySet<string>): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error(`${location} must be a mapping`);\n }\n if (keys && Object.keys(value).some((key) => !keys.has(key))) {\n // Never echo an unknown key or value, either of which might contain a misplaced secret.\n throw new Error(`${location} contains unsupported metadata`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction reference(value: unknown, location: string): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > 256 || /\\s/.test(value)) {\n throw new Error(`${location} must be a non-empty reference without whitespace`);\n }\n return value;\n}\n\nfunction origins(value: unknown, location: string): readonly string[] {\n if (!Array.isArray(value) || value.length === 0) throw new Error(`${location} must contain exact HTTP(S) origins`);\n const result = value.map((entry: unknown) => {\n if (typeof entry !== 'string') throw new Error(`${location} must contain exact HTTP(S) origins`);\n let url: URL;\n try {\n url = new URL(entry);\n } catch {\n throw new Error(`${location} must contain exact HTTP(S) origins`);\n }\n if (\n (url.protocol !== 'https:' && url.protocol !== 'http:') ||\n url.origin !== entry ||\n url.username ||\n url.password\n ) {\n throw new Error(`${location} must contain exact HTTP(S) origins`);\n }\n return entry;\n });\n return Object.freeze([...new Set(result)]);\n}\n\nfunction browser(value: unknown, location: string): ProfileBrowserBinding {\n const entry = record(value, location, BROWSER_KEYS);\n if (typeof entry.profileName !== 'string' || !BROWSER_PROFILE_PATTERN.test(entry.profileName)) {\n throw new Error(`${location}.profileName must be a safe browser profile name`);\n }\n return Object.freeze({\n profileName: entry.profileName,\n allowedOrigins: origins(entry.allowedOrigins, `${location}.allowedOrigins`),\n });\n}\n\n/** Validates and deeply freezes a detached metadata snapshot. No provider SDK or secret is loaded. */\nexport function parseProfileBinding(value: unknown, location = 'Profile integration'): ProfileIntegrationBinding {\n const entry = record(value, location, BINDING_KEYS);\n const sourceSecrets = record(entry.secrets, `${location}.secrets`);\n const secrets: Record<string, ProfileSecretReference> = {};\n for (const [alias, value] of Object.entries(sourceSecrets)) {\n if (!ALIAS_PATTERN.test(alias)) throw new Error(`${location}.secrets requires uppercase alias names`);\n const secret = record(value, `${location}.secrets.${alias}`, SECRET_KEYS);\n if (typeof secret.field !== 'string' || !FIELD_PATTERN.test(secret.field)) {\n throw new Error(`${location}.secrets.${alias}.field must be a credential field name`);\n }\n secrets[alias] = Object.freeze({\n credentialId: reference(secret.credentialId, `${location}.secrets.${alias}.credentialId`),\n field: secret.field,\n allowedOrigins: origins(secret.allowedOrigins, `${location}.secrets.${alias}.allowedOrigins`),\n });\n }\n const browserBinding = entry.browser === undefined ? undefined : browser(entry.browser, `${location}.browser`);\n if (\n browserBinding &&\n Object.values(secrets).some((secret) =>\n secret.allowedOrigins.some((origin) => !browserBinding.allowedOrigins.includes(origin)),\n )\n ) {\n throw new Error(`${location} secret origins must be included in browser.allowedOrigins`);\n }\n return Object.freeze({\n provider: reference(entry.provider, `${location}.provider`),\n organizationId: reference(entry.organizationId, `${location}.organizationId`),\n mailboxId: reference(entry.mailboxId, `${location}.mailboxId`),\n credentialRef: reference(entry.credentialRef, `${location}.credentialRef`),\n secrets: Object.freeze(secrets),\n ...(browserBinding === undefined ? {} : { browser: browserBinding }),\n });\n}\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport type { PersonaIdentity } from '../../types/profiles';\nimport { type PersonaFrontMatter, type PersonaVoiceOverride } from '../../types/profiles';\nimport { readDoomConfigSources } from '../layeredConfig';\nimport { parsePersonaFrontMatter } from '../personaFrontMatter';\nimport { readPersonaIcon } from '../personaIcon';\nimport { parseProfileBinding } from '../profileBinding';\nimport type { ProfileIntegrationBinding } from '../profileBinding/type';\n\n/** Files that make up one repository persona, concatenated in this order. */\nexport const PERSONA_FILES = ['profile.md', 'SOUL.md', 'AGENTS.md'];\n\n/** The persona file that may carry an identity block; the others are prose only. */\nconst PERSONA_IDENTITY_FILE = 'profile.md';\n\n/** A persona's resolved presentation: display name, and an icon already read into a data URL. */\n\nexport interface AgentProfile {\n name: string;\n /** Directory relative to personaRoot, which remains the persona source. */\n persona: string;\n /**\n * Root the persona path resolves against: the repository root for a\n * repository profile, the global `.po` directory for a global one.\n */\n personaRoot: string;\n /** Environment defaults. Values already exported by the caller win. */\n env: Record<string, string>;\n /** Nonsecret integration metadata. Resolved secrets never enter profile environment. */\n integration?: ProfileIntegrationBinding;\n /** Display name and avatar declared in the persona's own front-matter. */\n identity?: PersonaIdentity;\n /** Narrowly scoped TTS override declared alongside the identity. */\n voice?: PersonaVoiceOverride;\n}\n\ninterface ProfileConfigLayer {\n filePath: string;\n baseDirectory: string;\n roots: string[];\n entries: Record<string, unknown>;\n defaultProfile?: string;\n}\n\nconst PROFILE_KEYS = new Set(['persona', 'env', 'integration']);\nconst PROFILE_CATALOG_KEYS = new Set(['roots', 'entries', 'defaultProfile']);\nconst PROFILES_FILE = 'profiles.yaml';\nconst PROFILES_ROOT_KEY = 'profiles';\nconst AGENTS_DIRECTORY = 'agents';\nconst PARENT_DIRECTORY = '..';\nconst TEXT_ENCODING = 'utf8';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return (\n relative === '' ||\n (!path.isAbsolute(relative) &&\n relative !== PARENT_DIRECTORY &&\n !relative.startsWith(`${PARENT_DIRECTORY}${path.sep}`))\n );\n}\n\nfunction parseEnvironment(name: string, value: unknown): Record<string, string> {\n if (value === undefined) return {};\n if (!isRecord(value)) throw new Error(`Profile \"${name}\" env must be a string mapping`);\n\n const environment: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (typeof entry !== 'string') throw new Error(`Profile \"${name}\" env.${key} must be a string`);\n if (entry.includes('${secrets.')) throw new Error(`Profile \"${name}\" env cannot contain secret aliases`);\n environment[key] = entry;\n }\n return environment;\n}\n\nfunction parseProfileRoots(value: unknown, filePath: string, baseDirectory: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) throw new Error(`profiles.roots in ${filePath} must be an array`);\n return value.map((entry, index) => {\n if (typeof entry !== 'string' || entry.trim().length === 0) {\n throw new Error(`profiles.roots[${index}] in ${filePath} must be a non-empty string`);\n }\n return path.resolve(baseDirectory, entry.trim());\n });\n}\n\nfunction parseProfileLayer(source: { filePath: string; baseDirectory: string; document: unknown }): ProfileConfigLayer {\n if (!isRecord(source.document) || !isRecord(source.document[PROFILES_ROOT_KEY])) {\n throw new Error(`${source.filePath} must contain a profiles mapping`);\n }\n const unsupportedDocumentKeys = Object.keys(source.document).filter((key) => key !== PROFILES_ROOT_KEY);\n if (unsupportedDocumentKeys.length > 0) {\n throw new Error(`${source.filePath} may only contain profiles; unsupported: ${unsupportedDocumentKeys.join(', ')}`);\n }\n\n const profiles = source.document[PROFILES_ROOT_KEY];\n const usesCatalogShape = Object.hasOwn(profiles, 'roots') || Object.hasOwn(profiles, 'entries');\n if (!usesCatalogShape) {\n return { filePath: source.filePath, baseDirectory: source.baseDirectory, roots: [], entries: profiles };\n }\n\n const unsupportedCatalogKeys = Object.keys(profiles).filter((key) => !PROFILE_CATALOG_KEYS.has(key));\n if (unsupportedCatalogKeys.length > 0) {\n throw new Error(\n `profiles in ${source.filePath} may only contain roots, entries and defaultProfile; unsupported: ${unsupportedCatalogKeys.join(', ')}`,\n );\n }\n if (\n profiles.defaultProfile !== undefined &&\n (typeof profiles.defaultProfile !== 'string' || profiles.defaultProfile.trim().length === 0)\n ) {\n throw new Error(`profiles.defaultProfile in ${source.filePath} must be a non-empty string`);\n }\n if (profiles.entries !== undefined && !isRecord(profiles.entries)) {\n throw new Error(`profiles.entries in ${source.filePath} must be a mapping`);\n }\n return {\n filePath: source.filePath,\n baseDirectory: source.baseDirectory,\n roots: parseProfileRoots(profiles.roots, source.filePath, source.baseDirectory),\n entries: profiles.entries ?? {},\n ...(profiles.defaultProfile === undefined ? {} : { defaultProfile: String(profiles.defaultProfile).trim() }),\n };\n}\n\nfunction assertProfileInsideAllowedRoot(name: string, personaPath: string, lexicalRoots: readonly string[]): void {\n const realPersonaPath = fs.realpathSync(personaPath);\n if (!lexicalRoots.some((root) => isPathInside(fs.realpathSync(root), realPersonaPath))) {\n throw new Error(`Profile \"${name}\" persona must stay inside agents/ or a configured profile root`);\n }\n}\n\nfunction parseProfile(\n personaRoot: string,\n configuredRoots: readonly string[],\n name: string,\n value: unknown,\n): AgentProfile {\n if (!isRecord(value)) throw new Error(`Profile \"${name}\" must be a mapping`);\n\n const unsupported = Object.keys(value).filter((key) => !PROFILE_KEYS.has(key));\n if (unsupported.length > 0) {\n throw new Error(\n `Profile \"${name}\" may only set persona, env and integration; unsupported: ${unsupported.join(', ')}`,\n );\n }\n if (typeof value.persona !== 'string' || value.persona.trim().length === 0) {\n throw new Error(`Profile \"${name}\" must set a persona`);\n }\n if (path.isAbsolute(value.persona)) {\n throw new Error(`Profile \"${name}\" persona must be relative to the config that declares it`);\n }\n\n const persona = value.persona;\n const personaPath = path.resolve(personaRoot, persona);\n const lexicalRoots = [path.resolve(personaRoot, AGENTS_DIRECTORY), ...configuredRoots].filter((root) =>\n isPathInside(root, personaPath),\n );\n if (lexicalRoots.length === 0) {\n throw new Error(`Profile \"${name}\" persona must stay inside agents/ or a configured profile root`);\n }\n if (!fs.existsSync(personaPath) || !fs.statSync(personaPath).isDirectory()) {\n throw new Error(`Profile \"${name}\" references a missing persona: ${persona}`);\n }\n assertProfileInsideAllowedRoot(name, personaPath, lexicalRoots);\n if (!buildPersonaPrompt(personaRoot, persona)) {\n // An identity block is not persona text, so a profile.md holding nothing else\n // leaves the persona empty. Say that, rather than claiming the file is unreadable.\n const declaresIdentity = readPersonaFrontMatter(personaRoot, persona) !== undefined;\n throw new Error(\n declaresIdentity\n ? `Profile \"${name}\" persona declares identity front-matter but no persona text: ${persona}`\n : `Profile \"${name}\" persona has no readable persona files: ${persona}`,\n );\n }\n\n return {\n name,\n persona,\n personaRoot,\n env: parseEnvironment(name, value.env),\n ...(value.integration === undefined\n ? {}\n : { integration: parseProfileBinding(value.integration, `Profile \"${name}\" integration`) }),\n ...readPersonaPresentation(personaRoot, persona),\n };\n}\n\nfunction containsPersonaFile(directory: string): boolean {\n return PERSONA_FILES.some((file) => {\n try {\n return fs.lstatSync(path.join(directory, file)).isFile();\n } catch {\n return false;\n }\n });\n}\n\nfunction discoverProfile(directory: string, configuredRoot: string, personaRoot: string): AgentProfile | undefined {\n if (!containsPersonaFile(directory)) return undefined;\n try {\n const realConfiguredRoot = fs.realpathSync(configuredRoot);\n const realDirectory = fs.realpathSync(directory);\n if (!isPathInside(realConfiguredRoot, realDirectory)) return undefined;\n const persona = path.relative(personaRoot, directory) || '.';\n if (!buildPersonaPrompt(personaRoot, persona)) return undefined;\n return {\n name: path.basename(directory),\n persona,\n personaRoot,\n env: {},\n ...readPersonaPresentation(personaRoot, persona),\n };\n } catch {\n // Automatic discovery ignores unreadable or unsafe candidates; explicit entries remain fatal.\n return undefined;\n }\n}\n\nfunction discoverProfileRoot(root: string, personaRoot: string): AgentProfile[] {\n if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {\n throw new Error(`Configured profile root is not a directory: ${root}`);\n }\n\n const rootProfile = discoverProfile(root, root, personaRoot);\n if (rootProfile) return [rootProfile];\n\n return fs\n .readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .sort((left, right) => left.name.localeCompare(right.name))\n .flatMap((entry) => {\n const profile = discoverProfile(path.join(root, entry.name), root, personaRoot);\n return profile ? [profile] : [];\n });\n}\n\n/**\n * Loads profiles from the global and repository configs, repository last.\n *\n * Configured roots accumulate and inspect themselves or their direct-child\n * directories for persona files. Later discoveries replace earlier names, and\n * explicit entries replace discoveries. Legacy flat profile mappings remain\n * accepted as explicit entries.\n */\nexport function loadProfiles(repoRoot: string, homeDirectory: string = os.homedir()): AgentProfile[] {\n const layers = readDoomConfigSources<unknown>(PROFILES_FILE, repoRoot, homeDirectory).map(parseProfileLayer);\n const byName = new Map<string, AgentProfile>();\n\n for (const layer of layers) {\n for (const root of layer.roots) {\n for (const profile of discoverProfileRoot(root, layer.baseDirectory)) byName.set(profile.name, profile);\n }\n }\n\n for (const layer of layers) {\n for (const [name, value] of Object.entries(layer.entries)) {\n byName.set(name, parseProfile(layer.baseDirectory, layer.roots, name, value));\n }\n }\n\n return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));\n}\n\n/**\n * The profile catalog: every resolved profile, plus the name a launch starts on\n * when the caller names none.\n *\n * `defaultProfile` mirrors `defaultMajorMode` in modes.yaml and `defaultDomains`\n * in domains.yaml, so each selection axis declares its default in its own\n * catalog. A repository declaration replaces a personal one. An unknown name is\n * an error rather than a silent fallback: a typo that quietly starts the session\n * with no persona is worse than a refused launch.\n */\nexport function loadProfileCatalog(\n repoRoot: string,\n homeDirectory: string = os.homedir(),\n): { profiles: AgentProfile[]; defaultProfile?: string } {\n const layers = readDoomConfigSources<unknown>(PROFILES_FILE, repoRoot, homeDirectory).map(parseProfileLayer);\n const profiles = loadProfiles(repoRoot, homeDirectory);\n let defaultProfile: string | undefined;\n for (const layer of layers) {\n if (layer.defaultProfile !== undefined) defaultProfile = layer.defaultProfile;\n }\n if (defaultProfile !== undefined && !profiles.some((profile) => profile.name === defaultProfile)) {\n throw new Error(`profiles.defaultProfile names an unknown profile: ${defaultProfile}`);\n }\n return { profiles, ...(defaultProfile === undefined ? {} : { defaultProfile }) };\n}\n\n/** Resolves one selected profile and fails clearly when its name is unknown. */\nexport function resolveProfile(repoRoot: string, name: string, homeDirectory?: string): AgentProfile {\n const profile = loadProfiles(repoRoot, homeDirectory).find((candidate) => candidate.name === name);\n if (!profile) throw new Error(`Unknown profile: ${name}`);\n return profile;\n}\n\nexport function listProfileNames(repoRoot: string, homeDirectory?: string): string[] {\n return loadProfiles(repoRoot, homeDirectory).map((profile) => profile.name);\n}\n\n/**\n * Reads the identity block from a persona's `profile.md`.\n *\n * Separate from `buildPersonaPrompt` because the prompt is assembled on several\n * paths that do not want the icon bytes, and because a persona that declares\n * nothing must stay exactly as cheap as it is today.\n */\nfunction readPersonaPresentation(\n personaRoot: string,\n personaDirectory: string,\n): { identity?: PersonaIdentity; voice?: PersonaVoiceOverride } {\n const frontMatter = readPersonaFrontMatter(personaRoot, personaDirectory);\n if (!frontMatter) return {};\n\n const icon =\n frontMatter.icon === undefined\n ? undefined\n : readPersonaIcon(path.join(personaRoot, personaDirectory), frontMatter.icon);\n const identity: PersonaIdentity = {\n ...(frontMatter.name === undefined ? {} : { name: frontMatter.name }),\n ...(icon === undefined ? {} : { icon }),\n };\n return {\n ...(identity.name === undefined && identity.icon === undefined ? {} : { identity }),\n ...(frontMatter.voice === undefined ? {} : { voice: frontMatter.voice }),\n };\n}\n\nfunction readPersonaFrontMatter(personaRoot: string, personaDirectory: string): PersonaFrontMatter | undefined {\n try {\n const personaPath = fs.realpathSync(path.join(personaRoot, personaDirectory));\n const filePath = path.join(personaPath, PERSONA_IDENTITY_FILE);\n if (!fs.existsSync(filePath)) return undefined;\n return parsePersonaFrontMatter(fs.readFileSync(fs.realpathSync(filePath), TEXT_ENCODING)).frontMatter;\n } catch {\n return undefined;\n }\n}\n/** Builds the persona system-prompt block, or undefined when nothing is readable. */\nexport function buildPersonaPrompt(personaRoot: string, personaDirectory: string): string | undefined {\n const sections: string[] = [];\n const personaPath = fs.realpathSync(path.join(personaRoot, personaDirectory));\n for (const file of PERSONA_FILES) {\n const filePath = path.join(personaPath, file);\n if (!fs.existsSync(filePath)) continue;\n const realFilePath = fs.realpathSync(filePath);\n const relativeFilePath = path.relative(personaPath, realFilePath);\n if (relativeFilePath === PARENT_DIRECTORY || relativeFilePath.startsWith(`${PARENT_DIRECTORY}${path.sep}`)) {\n throw new Error(`Persona file must stay inside ${personaDirectory}: ${file}`);\n }\n const raw = fs.readFileSync(realFilePath, TEXT_ENCODING);\n // Only profile.md may declare identity, so only profile.md is stripped.\n const content = (file === PERSONA_IDENTITY_FILE ? parsePersonaFrontMatter(raw).body : raw).trim();\n if (content) sections.push(content);\n }\n if (sections.length === 0) return undefined;\n return [`[PERSONA] You are operating as the person described below (source: ${personaDirectory}).`, ...sections].join(\n '\\n\\n',\n );\n}\n\n/** Applies profile environment defaults and returns only the values it contributed. */\nexport function applyProfileEnvironment(\n environment: NodeJS.ProcessEnv,\n defaults: Record<string, string>,\n): Record<string, string> {\n const applied: Record<string, string> = {};\n for (const [key, value] of Object.entries(defaults)) {\n if (environment[key] !== undefined) continue;\n environment[key] = value;\n applied[key] = value;\n }\n return applied;\n}\n\n/** Replaces environment defaults previously contributed by another profile. */\nexport function replaceProfileEnvironment(\n environment: NodeJS.ProcessEnv,\n previous: Record<string, string>,\n next: Record<string, string>,\n): Record<string, string> {\n for (const [key, value] of Object.entries(previous)) {\n if (environment[key] === value) delete environment[key];\n }\n return applyProfileEnvironment(environment, next);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,QAAQ;AACd,MAAM,aAAa;CAAC;CAAQ;CAAQ;AAAO;AAE3C,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,UAAU,OAAkD;CACnE,IAAI,CAACA,WAAS,KAAK,GAAG,OAAO,KAAA;CAC7B,MAAM,QAAQ,OAAO,MAAM,UAAU,YAAY,MAAM,MAAM,KAAK,CAAC,CAAC,SAAS,IAAI,MAAM,MAAM,KAAK,IAAI,KAAA;CACtG,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W,GAAG,OAAO,KAAA;CAClC,OAAO,CAAC,sEAAsE,iBAAiB,KAAK,GAAG,QAAQ,CAAC,CAAC,KAC/G,MACF;AACF;;AAGA,SAAgB,wBACd,aACA,UACwB;CACxB,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAAG;EACnD,IAAI,YAAY,SAAS,KAAA,GAAW;EACpC,YAAY,OAAO;EACnB,QAAQ,OAAO;CACjB;CACA,OAAO;AACT;;AAGA,SAAgB,0BACd,aACA,UACA,MACwB;CACxB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAChD,IAAI,YAAY,SAAS,OAAO,OAAO,YAAY;CAErD,OAAO,wBAAwB,aAAa,IAAI;AAClD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sessionConfig-Bf6xHWLd.cjs","names":["deepFreeze","Service","DOOM_CONFIG_SERVICE","getSessionHarnessState","loadDoomConfig","loadDoomConfigAsync","getHarnessState","DOOM_CONFIG_SERVICE"],"sources":["../src/services/doomConfigService/index.ts","../src/services/sessionConfig/index.ts"],"sourcesContent":["import { type Context, Service } from '@deepseek-ai/cordis';\n\nimport {\n DOOM_CONFIG_SERVICE,\n type DeepReadonly,\n type DoomConfig,\n type DoomConfigContext,\n type DoomConfigLoader,\n type IDoomConfigService,\n} from '../../types/config';\n\nfunction deepFreeze<TValue>(value: TValue): DeepReadonly<TValue> {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {\n return value as DeepReadonly<TValue>;\n }\n for (const child of Object.values(value)) deepFreeze(child);\n return Object.freeze(value) as DeepReadonly<TValue>;\n}\n\n/**\n * Doom configuration published on the shared cordis Context.\n *\n * Every extension resolves the same instance by name, so configuration stays\n * one read per session instead of one per consumer, and the registration is\n * removed with the fiber that created it. The loader is injected so this stays\n * free of filesystem access.\n */\nexport class DoomConfigService extends Service implements IDoomConfigService {\n readonly generation: string;\n private snapshot: DoomConfigContext;\n\n constructor(\n ctx: Context,\n snapshot: DoomConfigContext,\n private readonly loadConfig: DoomConfigLoader,\n generation = `doom-config:${crypto.randomUUID()}`,\n ) {\n super(ctx, DOOM_CONFIG_SERVICE);\n this.snapshot = deepFreeze(snapshot) as DoomConfigContext;\n this.generation = generation;\n }\n\n getSnapshot(): DoomConfigContext {\n return this.snapshot;\n }\n\n replaceSnapshot(context: DoomConfigContext): DoomConfigContext {\n this.snapshot = deepFreeze(context) as DoomConfigContext;\n return this.snapshot;\n }\n\n load(repoRoot: string, homeDirectory?: string): DoomConfig {\n return this.loadConfig(repoRoot, homeDirectory);\n }\n}\n","import type { DoomHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport type {\n DoomConfigSelection as ConfigSelection,\n DeepReadonly,\n DoomConfigContext,\n DoomConfigPendingSelection,\n DoomConfigTransitionRecord,\n DoomConfigTransitionStrategy,\n HarnessState,\n IDoomConfigService,\n} from '../../types/config';\nimport { DOOM_CONFIG_SERVICE } from '../../types/config';\nimport { loadDoomConfig, loadDoomConfigAsync } from '../config';\nimport { DoomConfigService } from '../doomConfigService';\nimport { getHarnessState, getSessionHarnessState } from '../harnessStore';\n\nexport const DOOM_CONFIG_ENTRY_TYPE = 'po:config:v1';\nexport const DOOM_CONFIG_TRANSITION_ENTRY_TYPE = 'po:transition:v1';\n\nexport type DoomConfigSelection = ConfigSelection;\n\ntype DoomConfigTransitionEntry = DoomConfigTransitionRecord;\n\nfunction isSelection(value: unknown): value is DoomConfigSelection {\n if (typeof value !== 'object' || value === null) return false;\n const selection = value as Partial<DoomConfigSelection>;\n return (\n selection.version === 1 &&\n typeof selection.majorMode === 'string' &&\n Array.isArray(selection.domains) &&\n selection.domains.every((domain) => typeof domain === 'string') &&\n (selection.profile === undefined || typeof selection.profile === 'string') &&\n (selection.compositionFingerprint === undefined || typeof selection.compositionFingerprint === 'string')\n );\n}\n\nfunction branchSelection(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n): DoomConfigSelection | undefined {\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index];\n if (entry?.type === 'custom' && entry.customType === DOOM_CONFIG_ENTRY_TYPE && isSelection(entry.data)) {\n return entry.data;\n }\n }\n return undefined;\n}\n\nfunction isTransitionStrategy(value: unknown): value is DoomConfigTransitionStrategy {\n return value === 'pi-reload' || value === 'process-relaunch';\n}\n\nfunction isTransition(value: unknown): value is DoomConfigTransitionEntry {\n if (typeof value !== 'object' || value === null) return false;\n const transition = value as Partial<DoomConfigTransitionEntry>;\n return (\n transition.version === 1 &&\n typeof transition.operationId === 'string' &&\n isSelection(transition.active) &&\n isSelection(transition.target) &&\n isTransitionStrategy(transition.strategy) &&\n (transition.phase === 'pending' ||\n transition.phase === 'applied' ||\n transition.phase === 'aborted' ||\n transition.phase === 'superseded')\n );\n}\n\nfunction branchTransition(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n): DoomConfigTransitionEntry | undefined {\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index];\n if (\n entry?.type === 'custom' &&\n entry.customType === DOOM_CONFIG_TRANSITION_ENTRY_TYPE &&\n isTransition(entry.data)\n ) {\n return entry.data;\n }\n }\n return undefined;\n}\n\nfunction sameSelection(left: DoomConfigSelection, state: HarnessState): boolean {\n return (\n left.majorMode === state.majorMode &&\n left.profile === state.profile &&\n (left.compositionFingerprint === undefined || left.compositionFingerprint === state.compositionFingerprint) &&\n left.domains.length === state.domains.length &&\n left.domains.every((domain, index) => domain === state.domains[index])\n );\n}\n\nfunction isActiveTransitionTarget(target: DoomConfigSelection, state: HarnessState): boolean {\n return (\n target.compositionFingerprint !== undefined &&\n target.compositionFingerprint === state.compositionFingerprint &&\n sameSelection(target, state)\n );\n}\n\nfunction pendingFromTransition(transition: DoomConfigTransitionEntry): DoomConfigPendingSelection | undefined {\n if (transition.phase !== 'pending') return undefined;\n return { ...transition, phase: 'pending' };\n}\n\nfunction pendingFromLegacySelection(\n selection: DoomConfigSelection,\n bootstrap: HarnessState,\n): DoomConfigPendingSelection | undefined {\n if (sameSelection(selection, bootstrap)) return undefined;\n const active: DoomConfigSelection = {\n version: 1,\n majorMode: bootstrap.majorMode,\n domains: [...bootstrap.domains],\n profile: bootstrap.profile,\n compositionFingerprint: bootstrap.compositionFingerprint,\n };\n return {\n version: 1,\n operationId: 'legacy-config-selection',\n active,\n target: selection,\n strategy: 'process-relaunch',\n phase: 'pending',\n };\n}\n\nfunction deepFreeze<TValue>(value: TValue): DeepReadonly<TValue> {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {\n return value as DeepReadonly<TValue>;\n }\n for (const child of Object.values(value)) deepFreeze(child);\n return Object.freeze(value) as DeepReadonly<TValue>;\n}\n\nexport function readDoomConfigSelection(\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n): DoomConfigSelection | undefined {\n return branchSelection(ctx.sessionManager.getBranch());\n}\n\nfunction resolveContextState(ctx: Pick<ExtensionContext, 'sessionManager'>): {\n harness: HarnessState;\n pendingSelection: DoomConfigPendingSelection | undefined;\n requiresRelaunch: boolean;\n root: string | undefined;\n} {\n const bootstrap = getSessionHarnessState(ctx.sessionManager.getSessionId());\n return resolveBranchState(ctx.sessionManager.getBranch(), bootstrap);\n}\n\nfunction resolveBranchState(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n bootstrap: HarnessState,\n): {\n harness: HarnessState;\n pendingSelection: DoomConfigPendingSelection | undefined;\n requiresRelaunch: boolean;\n root: string | undefined;\n} {\n const selection = branchSelection(entries);\n const transition = branchTransition(entries);\n const transitionPending = transition ? pendingFromTransition(transition) : undefined;\n const pendingSelection = transition\n ? transitionPending\n : selection\n ? pendingFromLegacySelection(selection, bootstrap)\n : undefined;\n return {\n harness: bootstrap,\n pendingSelection,\n requiresRelaunch:\n pendingSelection !== undefined &&\n (transitionPending === undefined || !isActiveTransitionTarget(pendingSelection.target, bootstrap)),\n root: bootstrap.root,\n };\n}\n\nexport function createDoomConfigContext(ctx: Pick<ExtensionContext, 'cwd' | 'sessionManager'>): DoomConfigContext {\n const { harness, pendingSelection, requiresRelaunch, root } = resolveContextState(ctx);\n return deepFreeze({ settings: loadDoomConfig(root ?? ctx.cwd), harness, pendingSelection, requiresRelaunch });\n}\n\nexport async function createDoomConfigContextAsync(\n ctx: Pick<ExtensionContext, 'cwd' | 'sessionManager'>,\n): Promise<DoomConfigContext> {\n const { harness, pendingSelection, requiresRelaunch, root } = resolveContextState(ctx);\n const settings = await loadDoomConfigAsync(root ?? ctx.cwd);\n return deepFreeze({ settings, harness, pendingSelection, requiresRelaunch });\n}\n\n/** Initializes from this native session's branch, awaiting durable transition acknowledgement. */\nexport async function createNativeDoomConfigContext(\n execution: DoomHeadlessExecutionContext,\n): Promise<DoomConfigContext> {\n const bootstrap = getSessionHarnessState(execution.sessionId);\n const entries = await execution.session.entries({ type: 'custom' });\n const branch = entries.map((entry) => ({\n type: String(entry.type),\n customType: typeof entry.customType === 'string' ? entry.customType : undefined,\n data: entry.data,\n }));\n const transition = branchTransition(branch);\n if (transition?.phase === 'pending' && isActiveTransitionTarget(transition.target, bootstrap)) {\n const data = { ...transition, phase: 'applied' as const };\n await execution.session.appendCustomEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, data);\n branch.push({ type: 'custom', customType: DOOM_CONFIG_TRANSITION_ENTRY_TYPE, data });\n }\n const { harness, pendingSelection, requiresRelaunch, root } = resolveBranchState(branch, bootstrap);\n const settings = await loadDoomConfigAsync(root ?? execution.cwd, undefined, execution.environment);\n return deepFreeze({ settings, harness, pendingSelection, requiresRelaunch });\n}\n\nexport function appendDoomConfigSelection(pi: Pick<ExtensionAPI, 'appendEntry'>, selection: DoomConfigSelection): void {\n pi.appendEntry(DOOM_CONFIG_ENTRY_TYPE, selection);\n}\n\n/** Journals the live selection, defaulting to whatever the harness store holds. */\nexport function persistHarnessSelection(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n state: {\n readonly majorMode: string;\n readonly domains: readonly string[];\n readonly profile?: string;\n readonly compositionFingerprint?: string;\n } = getHarnessState(),\n): void {\n appendDoomConfigSelection(pi, {\n version: 1,\n majorMode: state.majorMode,\n domains: state.domains,\n profile: state.profile,\n compositionFingerprint: state.compositionFingerprint,\n });\n}\n\nexport function appendDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n transition: DoomConfigTransitionRecord,\n): void {\n pi.appendEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, transition);\n}\n\nexport function supersedeDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n transition: DoomConfigPendingSelection,\n): void {\n pi.appendEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, { ...transition, phase: 'superseded' });\n}\n\n/** Acknowledges the latest pending transition from a fresh session that owns its exact target composition. */\nexport function acknowledgeDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n harness: HarnessState,\n): boolean {\n const transition = branchTransition(ctx.sessionManager.getBranch());\n if (!transition || transition.phase !== 'pending' || !isActiveTransitionTarget(transition.target, harness)) {\n return false;\n }\n appendDoomConfigTransition(pi, { ...transition, phase: 'applied' });\n return true;\n}\n\nexport function readDoomConfigPendingSelection(\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n): DoomConfigPendingSelection | undefined {\n const bootstrap = getSessionHarnessState(ctx.sessionManager.getSessionId());\n const transition = branchTransition(ctx.sessionManager.getBranch());\n const transitionPending = transition ? pendingFromTransition(transition) : undefined;\n if (transition) return transitionPending;\n const selection = branchSelection(ctx.sessionManager.getBranch());\n return selection ? pendingFromLegacySelection(selection, bootstrap) : undefined;\n}\n\nexport function provideDoomConfigContext(\n ctx: Context,\n context: DoomConfigContext,\n generation = `doom-config:${crypto.randomUUID()}`,\n): IDoomConfigService {\n return new DoomConfigService(ctx, deepFreeze(context) as DoomConfigContext, loadDoomConfig, generation);\n}\n\n/** Returns the binding identity used to fence in-flight transitions. */\nexport function readDoomConfigContextGeneration(ctx: Context): string | undefined {\n return readDoomConfigService(ctx)?.generation;\n}\n\n/** Precomputes an immutable context before a transaction reaches publication. */\nexport function freezeDoomConfigContext(context: DoomConfigContext): DoomConfigContext {\n return deepFreeze(context);\n}\n\n/** Replaces a live binding with a deeply frozen context after publication. */\nexport function replaceDoomConfigContext(ctx: Context, context: DoomConfigContext): DoomConfigContext {\n const next = deepFreeze(context);\n return requireDoomConfigService(ctx).replaceSnapshot(next as DoomConfigContext);\n}\n\nexport function readDoomConfigService(ctx: Context): IDoomConfigService | undefined {\n return ctx.get(DOOM_CONFIG_SERVICE) as IDoomConfigService | undefined;\n}\n\nexport function requireDoomConfigService(ctx: Context): IDoomConfigService {\n const service = readDoomConfigService(ctx);\n if (!service) throw new Error('Doom config service is unavailable. Load @agimon-ai/po-config/extensions/server.');\n return service;\n}\n\nexport function requireDoomConfigContext(ctx: Context): DoomConfigContext {\n return requireDoomConfigService(ctx).getSnapshot();\n}\n"],"mappings":";;;;;;AAWA,SAASA,aAAmB,OAAqC;CAC/D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,SAAS,KAAK,GACtE,OAAO;CAET,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,aAAW,KAAK;CAC1D,OAAO,OAAO,OAAO,KAAK;AAC5B;;;;;;;;;AAUA,IAAa,oBAAb,cAAuCC,oBAAAA,QAAsC;CAOxD;CANnB;CACA;CAEA,YACE,KACA,UACA,YACA,aAAa,eAAe,OAAO,WAAW,KAC9C;EACA,MAAM,KAAKC,0BAAAA,mBAAmB;EAHb,KAAA,aAAA;EAIjB,KAAK,WAAWF,aAAW,QAAQ;EACnC,KAAK,aAAa;CACpB;CAEA,cAAiC;EAC/B,OAAO,KAAK;CACd;CAEA,gBAAgB,SAA+C;EAC7D,KAAK,WAAWA,aAAW,OAAO;EAClC,OAAO,KAAK;CACd;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;AACxE;AAEA,SAAgB,yBACd,KACA,SACA,aAAa,eAAe,OAAO,WAAW,KAC1B;CACpB,OAAO,IAAI,kBAAkB,KAAK,WAAW,OAAO,GAAwBC,eAAAA,gBAAgB,UAAU;AACxG;;AAGA,SAAgB,gCAAgC,KAAkC;CAChF,OAAO,sBAAsB,GAAG,CAAC,EAAE;AACrC;;AAGA,SAAgB,wBAAwB,SAA+C;CACrF,OAAO,WAAW,OAAO;AAC3B;;AAGA,SAAgB,yBAAyB,KAAc,SAA+C;CACpG,MAAM,OAAO,WAAW,OAAO;CAC/B,OAAO,yBAAyB,GAAG,CAAC,CAAC,gBAAgB,IAAyB;AAChF;AAEA,SAAgB,sBAAsB,KAA8C;CAClF,OAAO,IAAI,IAAIG,0BAAAA,mBAAmB;AACpC;AAEA,SAAgB,yBAAyB,KAAkC;CACzE,MAAM,UAAU,sBAAsB,GAAG;CACzC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,kFAAkF;CAChH,OAAO;AACT;AAEA,SAAgB,yBAAyB,KAAiC;CACxE,OAAO,yBAAyB,GAAG,CAAC,CAAC,YAAY;AACnD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"sessionConfig-DV5xTRRw.mjs","names":["deepFreeze"],"sources":["../src/services/doomConfigService/index.ts","../src/services/sessionConfig/index.ts"],"sourcesContent":["import { type Context, Service } from '@deepseek-ai/cordis';\n\nimport {\n DOOM_CONFIG_SERVICE,\n type DeepReadonly,\n type DoomConfig,\n type DoomConfigContext,\n type DoomConfigLoader,\n type IDoomConfigService,\n} from '../../types/config';\n\nfunction deepFreeze<TValue>(value: TValue): DeepReadonly<TValue> {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {\n return value as DeepReadonly<TValue>;\n }\n for (const child of Object.values(value)) deepFreeze(child);\n return Object.freeze(value) as DeepReadonly<TValue>;\n}\n\n/**\n * Doom configuration published on the shared cordis Context.\n *\n * Every extension resolves the same instance by name, so configuration stays\n * one read per session instead of one per consumer, and the registration is\n * removed with the fiber that created it. The loader is injected so this stays\n * free of filesystem access.\n */\nexport class DoomConfigService extends Service implements IDoomConfigService {\n readonly generation: string;\n private snapshot: DoomConfigContext;\n\n constructor(\n ctx: Context,\n snapshot: DoomConfigContext,\n private readonly loadConfig: DoomConfigLoader,\n generation = `doom-config:${crypto.randomUUID()}`,\n ) {\n super(ctx, DOOM_CONFIG_SERVICE);\n this.snapshot = deepFreeze(snapshot) as DoomConfigContext;\n this.generation = generation;\n }\n\n getSnapshot(): DoomConfigContext {\n return this.snapshot;\n }\n\n replaceSnapshot(context: DoomConfigContext): DoomConfigContext {\n this.snapshot = deepFreeze(context) as DoomConfigContext;\n return this.snapshot;\n }\n\n load(repoRoot: string, homeDirectory?: string): DoomConfig {\n return this.loadConfig(repoRoot, homeDirectory);\n }\n}\n","import type { DoomHeadlessExecutionContext } from '@agimon-ai/po-core/headless';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport type {\n DoomConfigSelection as ConfigSelection,\n DeepReadonly,\n DoomConfigContext,\n DoomConfigPendingSelection,\n DoomConfigTransitionRecord,\n DoomConfigTransitionStrategy,\n HarnessState,\n IDoomConfigService,\n} from '../../types/config';\nimport { DOOM_CONFIG_SERVICE } from '../../types/config';\nimport { loadDoomConfig, loadDoomConfigAsync } from '../config';\nimport { DoomConfigService } from '../doomConfigService';\nimport { getHarnessState, getSessionHarnessState } from '../harnessStore';\n\nexport const DOOM_CONFIG_ENTRY_TYPE = 'po:config:v1';\nexport const DOOM_CONFIG_TRANSITION_ENTRY_TYPE = 'po:transition:v1';\n\nexport type DoomConfigSelection = ConfigSelection;\n\ntype DoomConfigTransitionEntry = DoomConfigTransitionRecord;\n\nfunction isSelection(value: unknown): value is DoomConfigSelection {\n if (typeof value !== 'object' || value === null) return false;\n const selection = value as Partial<DoomConfigSelection>;\n return (\n selection.version === 1 &&\n typeof selection.majorMode === 'string' &&\n Array.isArray(selection.domains) &&\n selection.domains.every((domain) => typeof domain === 'string') &&\n (selection.profile === undefined || typeof selection.profile === 'string') &&\n (selection.compositionFingerprint === undefined || typeof selection.compositionFingerprint === 'string')\n );\n}\n\nfunction branchSelection(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n): DoomConfigSelection | undefined {\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index];\n if (entry?.type === 'custom' && entry.customType === DOOM_CONFIG_ENTRY_TYPE && isSelection(entry.data)) {\n return entry.data;\n }\n }\n return undefined;\n}\n\nfunction isTransitionStrategy(value: unknown): value is DoomConfigTransitionStrategy {\n return value === 'pi-reload' || value === 'process-relaunch';\n}\n\nfunction isTransition(value: unknown): value is DoomConfigTransitionEntry {\n if (typeof value !== 'object' || value === null) return false;\n const transition = value as Partial<DoomConfigTransitionEntry>;\n return (\n transition.version === 1 &&\n typeof transition.operationId === 'string' &&\n isSelection(transition.active) &&\n isSelection(transition.target) &&\n isTransitionStrategy(transition.strategy) &&\n (transition.phase === 'pending' ||\n transition.phase === 'applied' ||\n transition.phase === 'aborted' ||\n transition.phase === 'superseded')\n );\n}\n\nfunction branchTransition(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n): DoomConfigTransitionEntry | undefined {\n for (let index = entries.length - 1; index >= 0; index -= 1) {\n const entry = entries[index];\n if (\n entry?.type === 'custom' &&\n entry.customType === DOOM_CONFIG_TRANSITION_ENTRY_TYPE &&\n isTransition(entry.data)\n ) {\n return entry.data;\n }\n }\n return undefined;\n}\n\nfunction sameSelection(left: DoomConfigSelection, state: HarnessState): boolean {\n return (\n left.majorMode === state.majorMode &&\n left.profile === state.profile &&\n (left.compositionFingerprint === undefined || left.compositionFingerprint === state.compositionFingerprint) &&\n left.domains.length === state.domains.length &&\n left.domains.every((domain, index) => domain === state.domains[index])\n );\n}\n\nfunction isActiveTransitionTarget(target: DoomConfigSelection, state: HarnessState): boolean {\n return (\n target.compositionFingerprint !== undefined &&\n target.compositionFingerprint === state.compositionFingerprint &&\n sameSelection(target, state)\n );\n}\n\nfunction pendingFromTransition(transition: DoomConfigTransitionEntry): DoomConfigPendingSelection | undefined {\n if (transition.phase !== 'pending') return undefined;\n return { ...transition, phase: 'pending' };\n}\n\nfunction pendingFromLegacySelection(\n selection: DoomConfigSelection,\n bootstrap: HarnessState,\n): DoomConfigPendingSelection | undefined {\n if (sameSelection(selection, bootstrap)) return undefined;\n const active: DoomConfigSelection = {\n version: 1,\n majorMode: bootstrap.majorMode,\n domains: [...bootstrap.domains],\n profile: bootstrap.profile,\n compositionFingerprint: bootstrap.compositionFingerprint,\n };\n return {\n version: 1,\n operationId: 'legacy-config-selection',\n active,\n target: selection,\n strategy: 'process-relaunch',\n phase: 'pending',\n };\n}\n\nfunction deepFreeze<TValue>(value: TValue): DeepReadonly<TValue> {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {\n return value as DeepReadonly<TValue>;\n }\n for (const child of Object.values(value)) deepFreeze(child);\n return Object.freeze(value) as DeepReadonly<TValue>;\n}\n\nexport function readDoomConfigSelection(\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n): DoomConfigSelection | undefined {\n return branchSelection(ctx.sessionManager.getBranch());\n}\n\nfunction resolveContextState(ctx: Pick<ExtensionContext, 'sessionManager'>): {\n harness: HarnessState;\n pendingSelection: DoomConfigPendingSelection | undefined;\n requiresRelaunch: boolean;\n root: string | undefined;\n} {\n const bootstrap = getSessionHarnessState(ctx.sessionManager.getSessionId());\n return resolveBranchState(ctx.sessionManager.getBranch(), bootstrap);\n}\n\nfunction resolveBranchState(\n entries: readonly { type: string; customType?: string; data?: unknown }[],\n bootstrap: HarnessState,\n): {\n harness: HarnessState;\n pendingSelection: DoomConfigPendingSelection | undefined;\n requiresRelaunch: boolean;\n root: string | undefined;\n} {\n const selection = branchSelection(entries);\n const transition = branchTransition(entries);\n const transitionPending = transition ? pendingFromTransition(transition) : undefined;\n const pendingSelection = transition\n ? transitionPending\n : selection\n ? pendingFromLegacySelection(selection, bootstrap)\n : undefined;\n return {\n harness: bootstrap,\n pendingSelection,\n requiresRelaunch:\n pendingSelection !== undefined &&\n (transitionPending === undefined || !isActiveTransitionTarget(pendingSelection.target, bootstrap)),\n root: bootstrap.root,\n };\n}\n\nexport function createDoomConfigContext(ctx: Pick<ExtensionContext, 'cwd' | 'sessionManager'>): DoomConfigContext {\n const { harness, pendingSelection, requiresRelaunch, root } = resolveContextState(ctx);\n return deepFreeze({ settings: loadDoomConfig(root ?? ctx.cwd), harness, pendingSelection, requiresRelaunch });\n}\n\nexport async function createDoomConfigContextAsync(\n ctx: Pick<ExtensionContext, 'cwd' | 'sessionManager'>,\n): Promise<DoomConfigContext> {\n const { harness, pendingSelection, requiresRelaunch, root } = resolveContextState(ctx);\n const settings = await loadDoomConfigAsync(root ?? ctx.cwd);\n return deepFreeze({ settings, harness, pendingSelection, requiresRelaunch });\n}\n\n/** Initializes from this native session's branch, awaiting durable transition acknowledgement. */\nexport async function createNativeDoomConfigContext(\n execution: DoomHeadlessExecutionContext,\n): Promise<DoomConfigContext> {\n const bootstrap = getSessionHarnessState(execution.sessionId);\n const entries = await execution.session.entries({ type: 'custom' });\n const branch = entries.map((entry) => ({\n type: String(entry.type),\n customType: typeof entry.customType === 'string' ? entry.customType : undefined,\n data: entry.data,\n }));\n const transition = branchTransition(branch);\n if (transition?.phase === 'pending' && isActiveTransitionTarget(transition.target, bootstrap)) {\n const data = { ...transition, phase: 'applied' as const };\n await execution.session.appendCustomEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, data);\n branch.push({ type: 'custom', customType: DOOM_CONFIG_TRANSITION_ENTRY_TYPE, data });\n }\n const { harness, pendingSelection, requiresRelaunch, root } = resolveBranchState(branch, bootstrap);\n const settings = await loadDoomConfigAsync(root ?? execution.cwd, undefined, execution.environment);\n return deepFreeze({ settings, harness, pendingSelection, requiresRelaunch });\n}\n\nexport function appendDoomConfigSelection(pi: Pick<ExtensionAPI, 'appendEntry'>, selection: DoomConfigSelection): void {\n pi.appendEntry(DOOM_CONFIG_ENTRY_TYPE, selection);\n}\n\n/** Journals the live selection, defaulting to whatever the harness store holds. */\nexport function persistHarnessSelection(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n state: {\n readonly majorMode: string;\n readonly domains: readonly string[];\n readonly profile?: string;\n readonly compositionFingerprint?: string;\n } = getHarnessState(),\n): void {\n appendDoomConfigSelection(pi, {\n version: 1,\n majorMode: state.majorMode,\n domains: state.domains,\n profile: state.profile,\n compositionFingerprint: state.compositionFingerprint,\n });\n}\n\nexport function appendDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n transition: DoomConfigTransitionRecord,\n): void {\n pi.appendEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, transition);\n}\n\nexport function supersedeDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n transition: DoomConfigPendingSelection,\n): void {\n pi.appendEntry(DOOM_CONFIG_TRANSITION_ENTRY_TYPE, { ...transition, phase: 'superseded' });\n}\n\n/** Acknowledges the latest pending transition from a fresh session that owns its exact target composition. */\nexport function acknowledgeDoomConfigTransition(\n pi: Pick<ExtensionAPI, 'appendEntry'>,\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n harness: HarnessState,\n): boolean {\n const transition = branchTransition(ctx.sessionManager.getBranch());\n if (!transition || transition.phase !== 'pending' || !isActiveTransitionTarget(transition.target, harness)) {\n return false;\n }\n appendDoomConfigTransition(pi, { ...transition, phase: 'applied' });\n return true;\n}\n\nexport function readDoomConfigPendingSelection(\n ctx: Pick<ExtensionContext, 'sessionManager'>,\n): DoomConfigPendingSelection | undefined {\n const bootstrap = getSessionHarnessState(ctx.sessionManager.getSessionId());\n const transition = branchTransition(ctx.sessionManager.getBranch());\n const transitionPending = transition ? pendingFromTransition(transition) : undefined;\n if (transition) return transitionPending;\n const selection = branchSelection(ctx.sessionManager.getBranch());\n return selection ? pendingFromLegacySelection(selection, bootstrap) : undefined;\n}\n\nexport function provideDoomConfigContext(\n ctx: Context,\n context: DoomConfigContext,\n generation = `doom-config:${crypto.randomUUID()}`,\n): IDoomConfigService {\n return new DoomConfigService(ctx, deepFreeze(context) as DoomConfigContext, loadDoomConfig, generation);\n}\n\n/** Returns the binding identity used to fence in-flight transitions. */\nexport function readDoomConfigContextGeneration(ctx: Context): string | undefined {\n return readDoomConfigService(ctx)?.generation;\n}\n\n/** Precomputes an immutable context before a transaction reaches publication. */\nexport function freezeDoomConfigContext(context: DoomConfigContext): DoomConfigContext {\n return deepFreeze(context);\n}\n\n/** Replaces a live binding with a deeply frozen context after publication. */\nexport function replaceDoomConfigContext(ctx: Context, context: DoomConfigContext): DoomConfigContext {\n const next = deepFreeze(context);\n return requireDoomConfigService(ctx).replaceSnapshot(next as DoomConfigContext);\n}\n\nexport function readDoomConfigService(ctx: Context): IDoomConfigService | undefined {\n return ctx.get(DOOM_CONFIG_SERVICE) as IDoomConfigService | undefined;\n}\n\nexport function requireDoomConfigService(ctx: Context): IDoomConfigService {\n const service = readDoomConfigService(ctx);\n if (!service) throw new Error('Doom config service is unavailable. Load @agimon-ai/po-config/extensions/server.');\n return service;\n}\n\nexport function requireDoomConfigContext(ctx: Context): DoomConfigContext {\n return requireDoomConfigService(ctx).getSnapshot();\n}\n"],"mappings":";;;;;AAWA,SAASA,aAAmB,OAAqC;CAC/D,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,SAAS,KAAK,GACtE,OAAO;CAET,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,aAAW,KAAK;CAC1D,OAAO,OAAO,OAAO,KAAK;AAC5B;;;;;;;;;AAUA,IAAa,oBAAb,cAAuC,QAAsC;CAOxD;CANnB;CACA;CAEA,YACE,KACA,UACA,YACA,aAAa,eAAe,OAAO,WAAW,KAC9C;EACA,MAAM,KAAK,mBAAmB;EAHb,KAAA,aAAA;EAIjB,KAAK,WAAWA,aAAW,QAAQ;EACnC,KAAK,aAAa;CACpB;CAEA,cAAiC;EAC/B,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