openpond 0.2.37 → 0.2.38

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 (158) hide show
  1. package/dist/app-server.js +1 -1
  2. package/dist/chunks/actions-command-MHWHPQ66.js +2 -0
  3. package/dist/chunks/{app-layer-BDAKS3DG.js → app-layer-JZTMHORT.js} +1 -1
  4. package/dist/chunks/app-server-runtime-PDT6BJD2.js +2 -0
  5. package/dist/chunks/apps-U5GIOD6W.js +2 -0
  6. package/dist/chunks/{chunk-DXOOJFFU.js → chunk-25OT6IYM.js} +2 -2
  7. package/dist/chunks/chunk-3HQEEZPO.js +2 -0
  8. package/dist/chunks/{chunk-YQPECTJ2.js → chunk-562Q5UVS.js} +2 -2
  9. package/dist/chunks/chunk-7BGT6Q2D.js +8 -0
  10. package/dist/chunks/{chunk-6EAQL7YX.js → chunk-AOBTILU5.js} +1 -1
  11. package/dist/chunks/{chunk-3YA2CD22.js → chunk-DDHUSA3I.js} +1 -1
  12. package/dist/chunks/{chunk-XLVFY2BA.js → chunk-FKVP26MC.js} +1 -1
  13. package/dist/chunks/{chunk-5YUITAUN.js → chunk-FUFIZ37W.js} +2 -2
  14. package/dist/chunks/chunk-GIPSOLAY.js +2 -0
  15. package/dist/chunks/{chunk-I6DQSOSF.js → chunk-GKRTXVNT.js} +1 -1
  16. package/dist/chunks/{chunk-SL7XLTIT.js → chunk-GOHJHZVA.js} +204 -204
  17. package/dist/chunks/{chunk-3I5BMVJI.js → chunk-IKM6ICPY.js} +1 -1
  18. package/dist/chunks/{chunk-4R4KM6LL.js → chunk-J4S7AVGF.js} +1 -1
  19. package/dist/chunks/chunk-JUX77H6K.js +13 -0
  20. package/dist/chunks/chunk-KNEMKYHY.js +2 -0
  21. package/dist/chunks/chunk-MRGA6BKG.js +19 -0
  22. package/dist/chunks/{chunk-FQOVC2GR.js → chunk-OCWH4BV7.js} +135 -141
  23. package/dist/chunks/chunk-P5CFBE6Z.js +3 -0
  24. package/dist/chunks/chunk-Q3X5WOVH.js +4 -0
  25. package/dist/chunks/{chunk-L6NNQUAT.js → chunk-QK2GLRCY.js} +1 -1
  26. package/dist/chunks/chunk-RELOOVWW.js +2 -0
  27. package/dist/chunks/chunk-SBBXUZWL.js +5 -0
  28. package/dist/chunks/{chunk-UJLZRM2M.js → chunk-SHCKK3SU.js} +1 -1
  29. package/dist/chunks/chunk-SHCRE7B2.js +2 -0
  30. package/dist/chunks/{chunk-3N4GQL6I.js → chunk-T7Y5OYO2.js} +1 -1
  31. package/dist/chunks/chunk-TZNKOKQJ.js +5 -0
  32. package/dist/chunks/{chunk-Z3RBK6LN.js → chunk-V5BC6QT2.js} +1 -1
  33. package/dist/chunks/{chunk-DG4DIFF4.js → chunk-WCZRDULE.js} +7 -7
  34. package/dist/chunks/chunk-XHJUP7M4.js +23 -0
  35. package/dist/chunks/{chunk-OO7JG7KM.js → chunk-ZCDOE3EO.js} +3 -3
  36. package/dist/chunks/{chunk-S4RSY6CR.js → chunk-ZCFX6HQO.js} +1 -1
  37. package/dist/chunks/{chunk-KCFVJDIV.js → chunk-ZPGTGQJT.js} +1 -1
  38. package/dist/chunks/cli-OP4EDGZN.js +2 -0
  39. package/dist/chunks/{configuration-command-URDRLDNY.js → configuration-command-RPNYWBKK.js} +1 -1
  40. package/dist/chunks/{continual-6EW2SLGL.js → continual-MHMPLLUZ.js} +3 -3
  41. package/dist/chunks/core-commands-WFTASSGL.js +2 -0
  42. package/dist/chunks/datasets-V7E4I5N3.js +13 -0
  43. package/dist/chunks/desktop-test-NZAZVXLK.js +3 -0
  44. package/dist/chunks/dist-4OUZANXR.js +2 -0
  45. package/dist/chunks/experiments-7UBJCQAQ.js +2 -0
  46. package/dist/chunks/{extension-DG2XISC6.js → extension-OQ7CFD4Q.js} +1 -1
  47. package/dist/chunks/{help-ZLJV3ZVW.js → help-4BB2A5JC.js} +1 -1
  48. package/dist/chunks/hosted-harness-runtime-6TE37GBH.js +2 -0
  49. package/dist/chunks/hosted-profile-compiler-7ZWCIHPA.js +3 -0
  50. package/dist/chunks/opchat-QVB4UIZR.js +3 -0
  51. package/dist/chunks/organizations-MUKXB6MX.js +2 -0
  52. package/dist/chunks/{profile-LMRN5QMQ.js → profile-LZYR4CMX.js} +1 -1
  53. package/dist/chunks/project-agent-FHNWIH2D.js +2 -0
  54. package/dist/chunks/sandbox-command-GJN3HSJQ.js +2 -0
  55. package/dist/chunks/{sandbox-template-LN5OQ55F.js → sandbox-template-6RLQYNTY.js} +1 -1
  56. package/dist/chunks/{src-LRJO4THC.js → src-2NVS6PNZ.js} +112 -112
  57. package/dist/chunks/{src-A5KEQW52.js → src-PASASTIA.js} +5 -5
  58. package/dist/chunks/{taskset-YPKY3HUM.js → taskset-BZYQT65N.js} +1 -1
  59. package/dist/chunks/{teams-bot-RY5M6AOW.js → teams-bot-UQB636V3.js} +1 -1
  60. package/dist/chunks/training-7PST5HZU.js +1 -1
  61. package/dist/chunks/{workspaces-KZ6ZJXXY.js → workspaces-2KYAFRX4.js} +1 -1
  62. package/dist/cli.js +1 -1
  63. package/dist/index.js +1 -1
  64. package/dist/web/assets/{App-BRZg56AC.js → App-BL1D_PLh.js} +9 -9
  65. package/dist/web/assets/{AppDialog-BR9UjEFe.js → AppDialog-CmPsGOzE.js} +1 -1
  66. package/dist/web/assets/{AppTerminalPanel-DNXVV6S_.js → AppTerminalPanel-0_Ewf4wJ.js} +2 -2
  67. package/dist/web/assets/{AppsView-DhaB7uT7.js → AppsView-Ddn9R2I-.js} +1 -1
  68. package/dist/web/assets/{BrowserSidebar-zecj1P2T.js → BrowserSidebar-j2Yyiaz-.js} +1 -1
  69. package/dist/web/assets/{CartesianChart-DRhWC0XA.js → CartesianChart-BWAkc0mY.js} +1 -1
  70. package/dist/web/assets/{CollaborationTabs-BzNNwOcD.js → CollaborationTabs-SVc7oX8N.js} +1 -1
  71. package/dist/web/assets/{CommandMenu-C7HuXmgN.js → CommandMenu-CcX5ypdX.js} +1 -1
  72. package/dist/web/assets/{CommunityView-C4HfU5ky.js → CommunityView-B7W1C8KG.js} +1 -1
  73. package/dist/web/assets/{ComposerCreateImproveStrip-CG8YZxWB.js → ComposerCreateImproveStrip-BBKdrbNP.js} +1 -1
  74. package/dist/web/assets/{GetStartedView-ZxtcgU5X.js → GetStartedView-BXuTBT4U.js} +1 -1
  75. package/dist/web/assets/HostedModelLearningReview-C3oAdyoF.js +1 -0
  76. package/dist/web/assets/{HostedModelLearningSettings-BKM_1-LZ.js → HostedModelLearningSettings-9e5z5eRf.js} +1 -1
  77. package/dist/web/assets/{LabModelVersionDetailPage-CklKwV_e.js → LabModelVersionDetailPage-CctGBUae.js} +1 -1
  78. package/dist/web/assets/{LabSkillSidebar-Cq_axOXr.js → LabSkillSidebar-Cl8Sdiqc.js} +1 -1
  79. package/dist/web/assets/{LabsRoute-BPGkQnKq.js → LabsRoute-di9O0XV1.js} +4 -4
  80. package/dist/web/assets/{MainChatThread-DvllW6Ej.js → MainChatThread-BaEeNsrh.js} +2 -2
  81. package/dist/web/assets/{MainPane-BaUIvio6.js → MainPane-Dw90VsN-.js} +4 -4
  82. package/dist/web/assets/{MarkdownText-DP7Hjp4L.js → MarkdownText-CGGUFrZe.js} +1 -1
  83. package/dist/web/assets/{NativeSkillSidebar-BSSKKH-y.js → NativeSkillSidebar-2mgh6WV4.js} +1 -1
  84. package/dist/web/assets/{NewExperienceSwitcher-cWw4m_pU.js → NewExperienceSwitcher-DMTe3jS9.js} +1 -1
  85. package/dist/web/assets/{NewProjectDialog-BMzXEHsC.js → NewProjectDialog-D6pvuCoo.js} +1 -1
  86. package/dist/web/assets/{OutputsPage-CGWtgJ_j.js → OutputsPage-DMeIKxzN.js} +1 -1
  87. package/dist/web/assets/{ProjectsPage-C00Wt3oR.js → ProjectsPage-V5oXwB-5.js} +1 -1
  88. package/dist/web/assets/{RightChatPanelStack-0D_jpeAm.js → RightChatPanelStack-B0y2XNdm.js} +1 -1
  89. package/dist/web/assets/{RightSidebarHomePanel-BgHpI97K.js → RightSidebarHomePanel-BksZR71F.js} +1 -1
  90. package/dist/web/assets/{ScheduledWorkPage-C-P_Jv04.js → ScheduledWorkPage-BRcVebWV.js} +1 -1
  91. package/dist/web/assets/{SettingsView-BJDvzvtZ.js → SettingsView-CtI170q1.js} +3 -3
  92. package/dist/web/assets/{TeamChatView-BdUQNXvx.js → TeamChatView-DWGM8eXj.js} +1 -1
  93. package/dist/web/assets/{TerminalOverlay-85H1eqcg.js → TerminalOverlay-DLSmAkbQ.js} +1 -1
  94. package/dist/web/assets/{TrainingCreationPanel-Bdx2BJzb.js → TrainingCreationPanel-C6e6zhC8.js} +1 -1
  95. package/dist/web/assets/{TrainingDraftPanel-TcvqZfYS.js → TrainingDraftPanel-Q1GXOAlQ.js} +1 -1
  96. package/dist/web/assets/{UsageSettingsSection-Dm8bsNIT.js → UsageSettingsSection-UET2vS1c.js} +1 -1
  97. package/dist/web/assets/{WorkSidebarPanel-C9bKi4NH.js → WorkSidebarPanel-DMsXId2s.js} +1 -1
  98. package/dist/web/assets/{WorkspaceDiffPanel-CFzHklbv.js → WorkspaceDiffPanel-B_eZE-bq.js} +3 -3
  99. package/dist/web/assets/{WorkspaceEnvironmentMenu-_e6IkhGw.js → WorkspaceEnvironmentMenu-C848cDBP.js} +1 -1
  100. package/dist/web/assets/{WorkspaceGitDialogs-BglcR8S9.js → WorkspaceGitDialogs-CSnIC26s.js} +1 -1
  101. package/dist/web/assets/{WorkspaceMonacoEditor-BuipCT-i.js → WorkspaceMonacoEditor-C5dvv9s_.js} +3 -3
  102. package/dist/web/assets/{arrow-up-right-jN0p0koy.js → arrow-up-right-CsvQameJ.js} +1 -1
  103. package/dist/web/assets/{clipboard-Bat4as9H.js → clipboard-fZsv7_ot.js} +1 -1
  104. package/dist/web/assets/{cloud-upload-CFs0F_2n.js → cloud-upload-CUXNsLn2.js} +1 -1
  105. package/dist/web/assets/{cssMode-Cg4Jey3B.js → cssMode-1tbsSShK.js} +1 -1
  106. package/dist/web/assets/{folder-open-BqInWH_9.js → folder-open-Da8t5AtB.js} +1 -1
  107. package/dist/web/assets/{folder-plus-BSA6I7ld.js → folder-plus-X7B8dzc3.js} +1 -1
  108. package/dist/web/assets/{git-commit-horizontal-CLDqrpDQ.js → git-commit-horizontal-CajQIfK5.js} +1 -1
  109. package/dist/web/assets/{htmlMode-DHHN3vwk.js → htmlMode-qapgENKW.js} +1 -1
  110. package/dist/web/assets/{index-VtbQYCWA.js → index-DUQK09vA.js} +2 -2
  111. package/dist/web/assets/{info-BSebzpyp.js → info-BYfs9_PT.js} +1 -1
  112. package/dist/web/assets/{jsonMode-mvqMGlEK.js → jsonMode-DYPkWxLK.js} +1 -1
  113. package/dist/web/assets/{lspLanguageFeatures-Bw_QMGcP.js → lspLanguageFeatures-Cbcp__rz.js} +1 -1
  114. package/dist/web/assets/{minimize-2-CaHjbHpF.js → minimize-2-Dp7tWjno.js} +1 -1
  115. package/dist/web/assets/{monaco.contribution-DubQum0F.js → monaco.contribution-COP3_DCK.js} +2 -2
  116. package/dist/web/assets/{monaco.contribution-KrPDFXc4.js → monaco.contribution-CcL6YtdZ.js} +2 -2
  117. package/dist/web/assets/{monaco.contribution-CBkwYqsg.js → monaco.contribution-DApKEq_e.js} +2 -2
  118. package/dist/web/assets/{monaco.contribution-CiXEi4Ka.js → monaco.contribution-cIq6c5M4.js} +2 -2
  119. package/dist/web/assets/{monitor-DwOfVMY6.js → monitor-nP1D5S_1.js} +1 -1
  120. package/dist/web/assets/{python-BPnA89YS.js → python-DXYfRGSs.js} +1 -1
  121. package/dist/web/assets/{refresh-cw-DO-hUyTn.js → refresh-cw-D_9Q01ox.js} +1 -1
  122. package/dist/web/assets/{save-C7WFI7Mn.js → save-BxG7d5Nm.js} +1 -1
  123. package/dist/web/assets/{square-DiLQ59tw.js → square--Ua9DQPL.js} +1 -1
  124. package/dist/web/assets/{toggleHighContrast-BWFPIQBM.js → toggleHighContrast-CqAtkn5E.js} +1 -1
  125. package/dist/web/assets/{tsMode-CWxqU0x6.js → tsMode-BCdfa4wT.js} +1 -1
  126. package/dist/web/assets/{upload-vUnuWYGk.js → upload-BkYSJcbc.js} +1 -1
  127. package/dist/web/assets/{useLocalAgentSchedules-BFbGmflA.js → useLocalAgentSchedules-CGlPbPZr.js} +1 -1
  128. package/dist/web/assets/{useSessionTurnCache-C0zgYrCB.js → useSessionTurnCache-DtNQyWXl.js} +1 -1
  129. package/dist/web/assets/{wifi-off-DbNO6u3Z.js → wifi-off-DF8YmlRa.js} +1 -1
  130. package/dist/web/assets/{workers-4I09fePv.js → workers-BUHY0ojx.js} +1 -1
  131. package/dist/web/assets/{yaml-DpHYonDY.js → yaml-CtBzXx8s.js} +1 -1
  132. package/dist/web/index.html +1 -1
  133. package/docs/command-reference.md +35 -0
  134. package/package.json +3 -1
  135. package/dist/chunks/actions-command-GNQREIDD.js +0 -2
  136. package/dist/chunks/app-server-runtime-D74FFS27.js +0 -2
  137. package/dist/chunks/apps-2SUP5JZE.js +0 -2
  138. package/dist/chunks/chunk-2O5UZOYL.js +0 -13
  139. package/dist/chunks/chunk-3LG4G5JR.js +0 -3
  140. package/dist/chunks/chunk-BLXEK5F7.js +0 -26
  141. package/dist/chunks/chunk-DAOLQUAK.js +0 -19
  142. package/dist/chunks/chunk-EIB7GHIQ.js +0 -4
  143. package/dist/chunks/chunk-FFEI7IRU.js +0 -2
  144. package/dist/chunks/chunk-FOW3LI6G.js +0 -2
  145. package/dist/chunks/chunk-IYROEHYB.js +0 -2
  146. package/dist/chunks/chunk-TZ6N7WFI.js +0 -5
  147. package/dist/chunks/chunk-XISNUB62.js +0 -2
  148. package/dist/chunks/cli-A2P56J7R.js +0 -2
  149. package/dist/chunks/core-commands-CMAAUKPQ.js +0 -2
  150. package/dist/chunks/desktop-test-5PKGG6H6.js +0 -3
  151. package/dist/chunks/dist-CEKBK32A.js +0 -2
  152. package/dist/chunks/hosted-harness-runtime-ABEMAABI.js +0 -2
  153. package/dist/chunks/hosted-profile-compiler-CSLJT75T.js +0 -3
  154. package/dist/chunks/opchat-IMGIFM4W.js +0 -3
  155. package/dist/chunks/organizations-G3UOHURO.js +0 -2
  156. package/dist/chunks/project-agent-DTAVYEB6.js +0 -2
  157. package/dist/chunks/sandbox-command-YO6RR5SD.js +0 -2
  158. package/dist/web/assets/HostedModelLearningReview-BhGIhvoc.js +0 -1
@@ -50,4 +50,4 @@ CREATE TABLE IF NOT EXISTS managed_artifact_pins (id TEXT PRIMARY KEY, sha256 TE
50
50
  `).some(i=>/^p\d+$/.test(i)&&Number(i.slice(1))!==process.pid))throw n()}catch(o){if(o instanceof _)throw o;if(o.code!==1)throw new _({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"OpenPond could not verify that the previous installation is stopped.",action:"Ensure lsof is available, close the previous app and retry."})}return}if(process.platform==="win32"){let o="Get-CimInstance Win32_Process | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress";try{let{stdout:i}=await ro("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBuffer:4e6,env:Ur()}),s=JSON.parse(i),c=Array.isArray(s)?s:[s];for(let d of c)if(!(!d.CommandLine||d.ProcessId===process.pid)&&/(?:openpond|apps[\\/]server).*(?:serve|server|desktop)/i.test(d.CommandLine)&&(r.some(f=>d.CommandLine.includes(f))||e&&d.CommandLine.includes(e)))throw n()}catch(i){throw i instanceof _?i:new _({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"OpenPond could not inspect previous runtime ownership.",action:"Close the previous app and enable local process inspection before retrying."})}return}throw new _({code:"MIGRATION_OWNERSHIP_UNVERIFIED",path:e??t,message:"Automatic migration ownership checks are unavailable on this platform.",action:"Migrate this installation on a supported desktop platform."})}l(ot,"assertMigrationSourcesStopped");import{randomUUID as Ii}from"node:crypto";import{promises as q}from"node:fs";import X from"node:path";var oo=a.string().min(1).refine(e=>!X.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).some(t=>!t||t==="."||t==="..")),xi=a.strictObject({path:oo,sha256:a.string().regex(/^[a-f0-9]{64}$/),executable:a.boolean().optional()}),ao=a.strictObject({schemaVersion:a.literal("openpond.migration.v1"),id:a.string().regex(/^migration-[A-Za-z0-9-]+$/),status:a.enum(["preparing","prepared","installing","committed","verified","failed"]),home:a.string(),stage:a.string(),backup:a.string(),files:a.array(xi),installed:a.array(oo),sourceAppHome:a.string().optional(),sourceConfig:a.string().optional(),sourceBrowserState:a.string().optional(),resolutions:Ut.optional(),snapshotComplete:a.boolean().optional(),error:a.string().optional(),createdAt:a.string()}),Ft={schemaVersion:"openpond.storage.v1",version:1};async function Me(e){let t=X.join(y(e).runtime,"migration.json"),r=await M(t,()=>null);if(r===null)return null;let n=ao.safeParse(r);if(!n.success)throw Or(t);let o=n.data,i=X.resolve(e);if(o.home!==i||o.stage!==X.join(X.dirname(i),`.${X.basename(i)}-${o.id}`)||o.backup!==X.join(i,"backups",o.id))throw Or(t);let s=new Set(o.files.map(c=>c.path));if(s.size!==o.files.length||o.installed.some(c=>!s.has(c))||o.files.some(c=>/^(runtime|backups)([\\/]|$)/.test(c.path)||c.path==="storage.json"))throw Or(t);return o}l(Me,"readMigrationJournal");function Or(e){return new _({code:"INVALID_MIGRATION_JOURNAL",path:e,message:"The migration journal could not be verified.",action:"Preserve the journal and backups. Restore a verified backup into a separate home."})}l(Or,"invalidJournal");async function le(e){ao.parse(e),await I(X.join(y(e.home).runtime,"migration.json"),`${JSON.stringify(e,null,2)}
51
51
  `)}l(le,"saveMigrationJournal");async function at(e,t=e){let r=[];for(let n of await q.readdir(t,{withFileTypes:!0})){let o=X.join(t,n.name);n.isDirectory()?r.push(...await at(e,o)):r.push({path:X.relative(e,o),sha256:await G(o),executable:!!((await q.lstat(o)).mode&64)})}return r.sort((n,o)=>n.path.localeCompare(o.path))}l(at,"fileReceipts");async function Y(e,t){let r=await q.lstat(e),n=await q.lstat(t).catch(o=>{if(R(o))return null;throw o});if(r.isDirectory()){if(n&&!n.isDirectory())throw new Error(`Backup path is not a directory: ${t}`);await U(t);for(let o of await q.readdir(e))await Y(X.join(e,o),X.join(t,o));return}if(n){if(await G(e)!==await G(t))throw new _({code:"SOURCE_CHANGED_DURING_MIGRATION",path:e,message:"A source file changed after its migration backup was created.",action:"Stop the old installation and review the preserved backup before retrying."});return}if(await U(X.dirname(t)),r.isSymbolicLink())await q.symlink(await q.readlink(e),t);else{let o=`${t}.${Ii()}.snapshot`;try{await q.copyFile(e,o,q.constants.COPYFILE_EXCL),await q.chmod(o,r.mode&64?448:384);let i=await q.open(o,"r+");try{await i.sync()}finally{await i.close()}if(await q.link(o,t),process.platform!=="win32"){let s=await q.open(X.dirname(t),"r");try{await s.sync()}finally{await s.close()}}}finally{await q.rm(o,{force:!0})}}}l(Y,"snapshotCopy");import{existsSync as io}from"node:fs";import De from"node:path";var Li="CREATE TABLE IF NOT EXISTS storage_path_relocations (source TEXT PRIMARY KEY, destination TEXT NOT NULL)";function Bt(e,t){let r=y(e).database;if(!io(r))return;let n=[...t].sort((d,f)=>f.from.length-d.from.length);function o(d){if(!De.isAbsolute(d))return d;let f=n.find(p=>kt(d,p.from));return f?De.join(f.to,De.relative(f.from,d)):d}l(o,"rebase");function i(d,f=""){return typeof d=="string"&&/(?:path|directory|root|cwd)$/i.test(f)?o(d):Array.isArray(d)?d.map(p=>i(p,f)):d&&typeof d=="object"?Object.fromEntries(Object.entries(d).map(([p,g])=>[p,["messages","events","turns","metadata","input","output","result","credential","manifest"].includes(p)?g:i(g,p)])):d}l(i,"visit");let s=l(d=>`"${d.replaceAll('"','""')}"`,"quote"),c=D(r);try{c.exec("BEGIN IMMEDIATE"),c.exec(Li);for(let d of c.prepare("SELECT source, destination FROM storage_path_relocations").all())c.prepare("UPDATE storage_path_relocations SET destination=? WHERE source=?").run(o(d.destination),d.source);for(let d of n)d.from!==d.to&&c.prepare("INSERT INTO storage_path_relocations VALUES (?, ?) ON CONFLICT(source) DO UPDATE SET destination=excluded.destination").run(d.from,d.to);for(let{name:d}of c.prepare("SELECT name FROM sqlite_master WHERE type='table'").all())if(Sr.has(d)){let f=c.prepare(`PRAGMA table_info(${s(d)})`).all(),p=f.filter(h=>h.pk).sort((h,b)=>h.pk-b.pk);if(!p.length)continue;let g=f.filter(h=>h.name==="payload"||/(?:_path|_directory|_root)$/.test(h.name)||h.name==="cwd"),m=p.map(h=>`${s(h.name)}=?`).join(" AND ");for(let h of c.prepare(`SELECT * FROM ${s(d)}`).all())for(let b of g){let w=h[b.name];if(typeof w!="string")continue;let O=b.name==="payload"?JSON.stringify(i(JSON.parse(w))):o(w);w!==O&&c.prepare(`UPDATE ${s(d)} SET ${s(b.name)}=? WHERE ${m}`).run(O,...p.map(S=>h[S.name]))}}c.exec("COMMIT; PRAGMA wal_checkpoint(TRUNCATE)")}finally{c.close()}}l(Bt,"rebaseStoragePointers");function Ci(e,t){let r=y(e).database;if(!De.isAbsolute(t)||!io(r))return t;let n=D(r,!0);try{if(!n.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='storage_path_relocations'").get())return t;let i=n.prepare("SELECT source, destination FROM storage_path_relocations").all().sort((s,c)=>c.source.length-s.source.length).find(s=>kt(t,s.source));return i?De.join(i.destination,De.relative(i.source,t)):t}finally{n.close()}}l(Ci,"resolveStoredPath");import{existsSync as Ue,promises as it}from"node:fs";import A from"node:path";async function so(e){let t=A.join(e.backup,"app"),r=A.join(t,"refiners");if(Ue(A.join(r,"binding.json"))){let c=await M(A.join(r,"binding.json"),()=>({}));if(c.schemaVersion!=="openpond.refinerBinding.v1")throw C(r,"Unsupported Refiner binding schema.");B(e.stage,"refiner_bindings","active",c);let d=A.join(r,"transitions");if(Ue(d))for(let f of await it.readdir(d)){if(!f.endsWith(".json"))continue;let p=await M(A.join(d,f),()=>({}));if(p.schemaVersion!=="openpond.refinerTransitionReceipt.v1"||typeof p.contentHash!="string")throw C(d,"Unsupported Refiner transition schema.");B(e.stage,"refiner_transitions",p.contentHash,p)}await it.rm(A.join(e.stage,"library","refiners","binding.json"),{force:!0}),await it.rm(A.join(e.stage,"library","refiners","transitions"),{recursive:!0,force:!0})}let n=A.join(e.backup,"global","extensions");if(Ue(n)&&(await Y(n,A.join(e.stage,"library","extensions")),Ue(A.join(n,"registry.json")))){let c=await M(A.join(n,"registry.json"),()=>({}));if(c.schemaVersion!==1||!Array.isArray(c.extensions))throw C(n,"Unsupported extension registry schema.");B(e.stage,"extension_installations","registry",c),await it.rm(A.join(e.stage,"library","extensions","registry.json"),{force:!0})}let o=A.join(e.backup,"global","profiles");if(Ue(o)){await Y(o,A.join(e.stage,"library","profiles"));let c=K(e.stage,"profile_installations","library"),d=e.sourceConfig?A.join(A.dirname(e.sourceConfig),"profiles"):null;if(c&&d){let f=l(g=>({...g,...typeof g.repoPath=="string"&&Oi(g.repoPath,d)?{repoPath:A.join(e.home,"library","profiles",A.relative(d,g.repoPath))}:{}}),"rebase"),p=f(c.value);Array.isArray(p.profiles)&&(p.profiles=p.profiles.map(g=>f(g))),B(e.stage,"profile_installations","library",p)}}if(e.sourceBrowserState){let c=A.join(e.backup,"browser-sidebar-state.json"),d=vr.safeParse(await M(c,()=>null));if(!d.success)throw C(c,"Unsupported browser tab metadata.");let f=d.data;for(let[p,g]of Object.entries(f.conversations))B(e.stage,"browser_tab_state",p,g)}let i=[];if(e.sourceAppHome){for(let c of["harnesses","refiners"])i.push({from:A.join(e.sourceAppHome,c),to:A.join(e.home,"library",c)});i.push({from:e.sourceAppHome,to:e.home})}if(e.sourceConfig)for(let c of["profiles","extensions"])i.push({from:A.join(A.dirname(e.sourceConfig),c),to:A.join(e.home,"library",c)});Bt(e.stage,i);let s=A.join(e.stage,"attachments");Ue(s)&&await co(e.stage,s,[])}l(so,"importAdditionalDomains");function Oi(e,t){let r=A.relative(t,e);return r===""||!r.startsWith(`..${A.sep}`)&&r!==".."&&!A.isAbsolute(r)}l(Oi,"within");async function co(e,t,r){for(let n of await it.readdir(t,{withFileTypes:!0})){let o=A.join(t,n.name),i=[...r,n.name];if(n.isDirectory())await co(e,o,i);else if(n.isFile()&&i.length>=3){let s=i.slice(2).join("/");await Bn(e,{owner:{domain:"chat_attachment",id:JSON.stringify([i[0],i[1],s])},displayName:n.name,mediaType:"application/octet-stream",sourceFile:o})}else throw C(o,"Attachment storage contains an unsupported file or symbolic link.")}}l(co,"importAttachments");var ki=new Set(["config.json","providers.json","provider-secrets.json","provider-secrets.key","personalization.json","SOUL.md","token","state.sqlite","state.sqlite-wal","state.sqlite-shm"]),Pi=new Set(["cache","logs","diagnostics","backups","runtime"]);async function uo(e,t={}){e=T.resolve(e),Oe(e);let r=await M(y(e).marker,()=>null),n=await Me(e);if(r&&(lo(r,e),!n||n.status==="verified"))return t.sourceBrowserState&&!t.dryRun&&await Gn(e,t.sourceBrowserState),je(e,"current",n);if(n&&!t.dryRun)return Di(e);let o=await no(e,t),{issues:i,sourceCandidates:s,...c}=o;if(t.dryRun)return{...je(e,"planned",null),sourceAppHome:c.sourceAppHome??null,sourceConfig:c.sourceConfig??null,issues:i,sourceCandidates:s,...i.length?{}:{preview:await Mn(e,c,po)}};if(i.length)throw C(e,i.map(d=>d.message).join(" "));return x(T.join(y(e).runtime,"migration-owner"),async()=>{let d=await M(y(e).marker,()=>null);if(d)return lo(d,e),je(e,"current",null);let f=await Me(e);if(f)return Nr(f);if(!c.sourceAppHome&&!c.sourceConfig&&!c.sourceBrowserState)return await U(e),await L(e),await I(y(e).marker,`${JSON.stringify({...Ft,migrationId:null},null,2)}
52
52
  `),je(e,"new",null);for(let m of[y(e).database,y(e).credentials])if(m&&de(m))throw C(m,"The destination already contains authoritative state. Import the previous installation into a fresh home; existing history and credentials have been preserved.");await ot(c.sourceAppHome,c.sourceConfig);let p=`migration-${new Date().toISOString().replace(/[:.]/g,"-")}-${kr().slice(0,8)}`,g={schemaVersion:"openpond.migration.v1",id:p,status:"preparing",home:e,stage:T.join(T.dirname(e),`.${T.basename(e)}-${p}`),backup:T.join(e,"backups",p),files:[],installed:[],...c,resolutions:t.resolutions,createdAt:new Date().toISOString()};return await le(g),Nr(g)})}l(uo,"initializeHome");function lo(e,t){if(e.version!==1||e.schemaVersion!==Ft.schemaVersion)throw new _({code:"UNSUPPORTED_STORAGE_VERSION",path:y(t).marker,message:"This OpenPond home requires a different application version.",action:"Update OpenPond, or restore a compatible backup into a separate home."})}l(lo,"assertLayout");async function Ri(e){if(!e.snapshotComplete){if(await ot(e.sourceAppHome,e.sourceConfig),await U(e.backup),e.sourceConfig){await Y(e.sourceConfig,T.join(e.backup,"config.json"));for(let t of["extensions","profiles"]){let r=T.join(T.dirname(e.sourceConfig),t);de(r)&&await Y(r,T.join(e.backup,"global",t))}}if(e.sourceBrowserState&&await Y(e.sourceBrowserState,T.join(e.backup,"browser-sidebar-state.json")),e.sourceAppHome){for(let n of await P.readdir(e.sourceAppHome,{withFileTypes:!0}))["openpond-app","openpond-app-nightly","storage.json","config.toml","state","browser"].includes(n.name)||Pi.has(n.name)||n.name.startsWith("state.sqlite")||await Y(T.join(e.sourceAppHome,n.name),T.join(e.backup,"app",n.name));let t=T.join(e.sourceAppHome,"state.sqlite"),r=T.join(e.backup,"state.sqlite");if(de(t)&&!de(r)){let n=`${r}.${kr()}.tmp`,o=D(t,!0);try{await Ni(o,n);let i=await P.open(n,"r+");try{await i.sync()}finally{await i.close()}if(await P.rename(n,r),process.platform!=="win32"){let s=await P.open(T.dirname(r),"r");try{await s.sync()}finally{await s.close()}}}finally{o.close(),await P.rm(n,{force:!0})}}}await ot(e.sourceAppHome,e.sourceConfig),e.snapshotComplete=!0,await le(e)}}l(Ri,"captureSources");async function po(e){await Ri(e),await U(e.stage);let t=T.join(e.backup,"app");if(de(t))for(let n of await P.readdir(t)){if(ki.has(n)||n==="souls"||/^soul-.+\.md$/i.test(n))continue;let o=["harnesses","refiners"].includes(n)?T.join("library",n):n;await Y(T.join(t,n),T.join(e.stage,o))}de(T.join(e.backup,"state.sqlite"))&&await Y(T.join(e.backup,"state.sqlite"),y(e.stage).database),await Xn(e.stage,e.sourceConfig?T.join(e.backup,"config.json"):void 0),await Yn(e.stage,e.sourceAppHome),await Qn(e.stage,e.sourceAppHome?t:void 0),await Zn(e.stage,e.sourceAppHome?t:void 0),await eo(e.stage,e.sourceAppHome?t:void 0);let r=await E(T.join(t,"token"));r&&await I(y(e.stage).token,r),await so(e),de(y(e.home).config)&&await Vn(e.home,e.stage,e.resolutions),await xe(e.stage),await P.rm(T.join(e.stage,"runtime"),{recursive:!0,force:!0}),await P.rm(T.join(e.stage,"backups"),{recursive:!0,force:!0}),await P.rm(T.join(e.stage,"datasets","settings.json"),{force:!0}),e.files=(await at(e.stage)).filter(n=>!n.path.endsWith("-wal")&&!n.path.endsWith("-shm")),e.status="prepared",await le(e)}l(po,"prepare");async function xe(e){let{document:t}=await L(e);await Nn(e);for(let r of Object.values(t.providers??{}))if(r.credential?.source==="secret"&&!await Ot(e,r.credential.id))throw C(y(e).config,"An imported provider credential is missing.");if(de(y(e).database)){let r=D(y(e).database);try{let n=r.prepare("PRAGMA integrity_check").all();if(n.length!==1||Object.values(n[0])[0]!=="ok"||r.prepare("PRAGMA foreign_key_check").all().length)throw C(y(e).database,"The imported database failed integrity checks.");r.exec("PRAGMA wal_checkpoint(TRUNCATE)")}finally{r.close()}await Fn(e)}}l(xe,"validateMigratedHome");async function Mi(e){e.status="installing",await le(e);for(let t of e.files){let r=T.join(e.home,t.path),n=T.join(e.stage,t.path),o=de(r)?await G(r):null;if(e.installed.includes(t.path)&&o!==t.sha256)throw C(r,"An installed file changed before migration recovery completed.");if(o!==t.sha256){if(await G(n)!==t.sha256)throw C(n,"A staged file failed its checksum check.");if(o!==null&&await Y(r,T.join(e.backup,"destination",t.path)),await U(T.dirname(r)),(await P.lstat(n)).isSymbolicLink())de(r)&&await P.unlink(r),await P.symlink(await P.readlink(n),r);else{let s=`${r}.${kr()}.migration`;try{await P.copyFile(n,s),await P.chmod(s,t.executable?448:384);let c=await P.open(s,"r+");try{await c.sync()}finally{await c.close()}await P.rename(s,r)}finally{await P.rm(s,{force:!0})}}}if(process.platform!=="win32"){let i=await P.open(T.dirname(r),"r");try{await i.sync()}finally{await i.close()}}e.installed.includes(t.path)||e.installed.push(t.path),await le(e)}await xe(e.home),await I(y(e.home).marker,`${JSON.stringify({...Ft,migrationId:e.id},null,2)}
53
- `),e.status="committed",await le(e),e.status="verified",delete e.error,await le(e),await P.rm(e.stage,{recursive:!0,force:!0})}l(Mi,"install");async function Di(e){return x(T.join(y(e).runtime,"migration-owner"),async()=>{let t=await Me(e);if(!t)throw C(e,"No migration journal is available.");return Nr(t)})}l(Di,"recoverMigration");async function Nr(e){if(e.status==="verified")return je(e.home,"current",e);try{return(e.status==="preparing"||e.status==="failed")&&(await P.rm(e.stage,{recursive:!0,force:!0}),e.status="preparing",await po(e)),e.status!=="committed"?await Mi(e):(await xe(e.home),e.status="verified",await le(e),await P.rm(e.stage,{recursive:!0,force:!0})),je(e.home,"verified",e)}catch(t){throw e.error=t instanceof _?t.issue.code:"MIGRATION_FAILED",e.status==="preparing"&&(e.status="failed"),await le(e),t instanceof _?t:new _({code:"MIGRATION_FAILED",path:T.join(y(e.home).runtime,"migration.json"),message:"OpenPond could not finish updating its storage.",action:"Open migration details or run openpond config recover. Original data and snapshots have been preserved."},{cause:t})}}l(Nr,"recoverUnlocked");function je(e,t,r){return{id:r?.id??null,status:t,home:e,sourceAppHome:r?.sourceAppHome??null,sourceConfig:r?.sourceConfig??null,backup:r?.backup??null}}l(je,"report");async function Xu(e){return x(T.join(y(e).runtime,"migration-owner"),async()=>{let t=await Me(e);if(!t)return{restarted:!1,backup:null};if(!["preparing","failed"].includes(t.status)||t.installed.length||t.files.length)throw C(e,"Installation has already begun. Resume recovery or restore into a fresh home; preparation cannot be restarted.");return await ot(t.sourceAppHome,t.sourceConfig),await I(T.join(t.backup,"abandoned-preparation.json"),JSON.stringify(t,null,2)),await P.rm(t.stage,{recursive:!0,force:!0}),await P.rm(T.join(y(e).runtime,"migration.json")),{restarted:!0,backup:t.backup}})}l(Xu,"restartMigration");async function Ui(e){let t=await L(e),r=K(e,"client_preferences","global");return{preferences:Ze(t.document,r?.value),config:t}}l(Ui,"readPreferences");async function sp(e,t,r){return x(`${y(e).runtime}/preferences`,async()=>{let n=K(e,"client_preferences","global"),o=n?.value;return await W(e,i=>{let s=Ze(i,n?.value),c=Z.parse({...s,...t,...t.defaultChatModelRef===void 0&&(t.defaultChatModel!==void 0||t.defaultChatProvider!==void 0)?{defaultChatModelRef:{providerId:t.defaultChatProvider??s.defaultChatProvider,modelId:t.defaultChatModel??s.defaultChatModel}}:{}});o=xt(c);let d=structuredClone(i);for(let f of ie(Ae(s),Ae(c))){let p=d;for(let m of f.path.slice(0,-1))p[m]??={},p=p[m];let g=f.path.at(-1);f.op==="set"?p[g]=f.value:delete p[g]}return d},r),o&&JSON.stringify(o)!==JSON.stringify(n?.value)&&B(e,"client_preferences","global",o,n?.revision??null),Ui(e)})}l(sp,"updatePreferences");import{createHash as ji}from"node:crypto";import{promises as Le}from"node:fs";import mo from"node:path";var me=l(e=>ji("sha256").update(JSON.stringify(e)??"null").digest("hex"),"hash"),ho=l((e,t="local")=>me([e,t]),"trustKey");async function Ep(e,t,r,n){let o=await Le.realpath(t);B(e,"project_trust",ho(o,r),{root:o,accountId:r,trusted:n,updatedAt:new Date().toISOString()})}l(Ep,"setProjectTrust");async function go(e,t={}){let r=Ae(Z.parse({})),n=[],o={},i=[];function s(h,b,w,O=me(b)){let S={layer:h,path:w,revision:O};r=vt(r,b),n.push(S);function v(F,ue){if(F&&typeof F=="object"&&!Array.isArray(F)&&!("mode"in F)&&!("source"in F)&&!("provider_id"in F))for(let[Be,ct]of Object.entries(F))v(ct,[...ue,Be]);else o[JSON.stringify(ue)]=S}l(v,"visit"),v(b,[])}l(s,"apply"),s("defaults",r,"shipped"),t.profile&&(fo(t.profile.defaults,"profile"),s("profile",t.profile.defaults,t.profile.id,t.profile.revision));let c=await L(e);s("user",c.document,c.path,c.rawRevision);let d=structuredClone(r.permissions),f=null,p=null;if(t.projectRoot){f=await Le.realpath(t.projectRoot);let h=mo.join(f,".openpond","config.toml");if(await Le.lstat(h).catch(w=>{if(R(w))return null;throw w})){if(await Le.realpath(h)!==h)throw new _({code:"UNSAFE_PROJECT_CONFIG",path:h,message:"Project configuration must be a regular file inside its canonical project root.",action:"Replace symbolic links in the project configuration path with a regular local file."});let O=K(e,"project_trust",ho(f,t.accountId));if(!O?.value.trusted)i.push({code:"PROJECT_CONFIG_UNTRUSTED",path:h,message:"Project settings are ignored until this project is trusted.",action:"Review the project configuration, then trust it in configuration settings."});else{p=O.revision;let S=await L(e,{path:h,scope:"project"});s("project",S.document,S.path,S.rawRevision),d?.command_access==="disabled"&&(r.permissions={...r.permissions,command_access:"disabled"}),d?.codex_mode==="default"&&(r.permissions={...r.permissions,codex_mode:"default"}),d=structuredClone(r.permissions)}}}for(let h of["task","turn"])t[h]&&(fo(t[h],h),s(h,t[h],h));(d?.command_access==="disabled"||d?.command_access==="ask"&&r.permissions?.command_access==="full-access")&&(r.permissions={...r.permissions,command_access:d.command_access}),d?.codex_mode&&d.codex_mode!=="full-access"&&r.permissions?.codex_mode!=="default"&&(r.permissions={...r.permissions,codex_mode:d.codex_mode}),oe(r),await Fi(e,r);let g=[...Object.values(r.accounts??{}),...Object.values(r.providers??{})].flatMap(h=>h.credential?.source==="secret"?[h.credential.id]:[]),m=await Ln(e,g);return{document:r,effectiveRevision:me({document:r,sources:n,projectTrustRevision:p,versions:m}),sources:n,provenance:o,diagnostics:i,projectRoot:f,projectTrustRevision:p,credentialVersions:m}}l(go,"resolveEffectiveConfig");function fo(e,t){oe(e);let r=t==="profile"?["schema_version","chat","codex","context_compaction","subagents","runtime"]:["schema_version","chat","codex","context_compaction","subagents","permissions"];for(let n of Object.keys(e))if(!r.includes(n))throw new _({code:"CONFIG_SCOPE_VIOLATION",path:`${t}.${n}`,message:`This setting is not allowed in ${t} configuration.`,action:"Move host settings to the user configuration file."})}l(fo,"checkScope");async function Fi(e,t){let r=t.defaults;if(r?.account_id&&(!t.accounts?.[r.account_id]||t.accounts[r.account_id].enabled===!1))throw new _({code:"INVALID_ACCOUNT_DEFAULT",path:"defaults.account_id",message:"The default account is missing or disabled.",action:"Choose an enabled account or remove the explicit default."});let n=t.personalization?.active;if(n&&t.personalization?.mode!=="disabled"){let i=n.startsWith("custom:")?mo.join(e,"instructions","personalities",`${n.slice(7)}.md`):n,s=n.startsWith("custom:")?await E(i):He.find(c=>c.id===n.slice(8))?.content;if(s==null||s.trim().length>8e3)throw new _({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The selected personality is missing or exceeds its supported size.",action:"Restore its Markdown file or select an available personality in Settings."})}let o=t.personalization?.user_instructions;if(o){let i=Ve(o,e);try{if(!(await Le.stat(i)).isFile())throw new Error("Not a file");await Le.access(i,Le.constants.R_OK)}catch(s){throw new _({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The configured user instruction file cannot be read.",action:"Restore the file or remove its configuration reference."},{cause:s})}}}l(Fi,"validateRequiredSources");async function Sp(e,t,r={}){let n=await go(e,r);return B(e,"config_run_snapshots",t,{...n,capturedAt:new Date().toISOString()},null),n}l(Sp,"captureConfigRun");async function Ap(e,t,r={}){let n=await go(e,r);if(t.projectTrustRevision!==null&&n.projectTrustRevision!==t.projectTrustRevision)throw new _({code:"PROJECT_TRUST_CHANGED",path:t.projectRoot??e,message:"Project trust changed during this turn.",action:"Review project trust before starting a new turn."});let o=t.document.permissions,i=n.document.permissions;if(i?.command_access!==o?.command_access||i?.codex_mode!==o?.codex_mode||me(n.credentialVersions)!==me(t.credentialVersions)||me(n.document.accounts)!==me(t.document.accounts)||me(n.document.providers)!==me(t.document.providers))throw new _({code:"EXECUTION_POLICY_CHANGED",path:e,message:"Permissions or credential configuration changed during this turn.",action:"Start a new turn with the current settings."})}l(Ap,"assertConfigRunCurrent");function vp(e){return Ze(e.document)}l(vp,"effectivePreferences");import{createHash as Bi}from"node:crypto";var Vt=a.strictObject({chatMode:a.enum(["chat","work"]).optional(),notificationMode:a.enum(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:a.boolean().optional(),sidebarVisibility:a.strictObject({showCodexChats:a.boolean(),onlyRunningTasks:a.boolean()}).optional(),scheduledWorkView:a.enum(["calendar","list"]).optional(),editorControlsVisible:a.boolean().optional(),voiceNoticeAcknowledged:a.boolean().optional(),lessonProgress:a.record(a.string().min(1).max(200),a.strictObject({completed:a.boolean(),currentTime:a.number().finite().nonnegative(),duration:a.number().finite().positive(),updatedAt:a.number().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Cp={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"};import Vi from"node:path";async function yo(e){let r=(await L(e)).document.defaults?.account_id??K(e,"account_selection","last_used")?.value??"local";return`choices:${Bi("sha256").update(JSON.stringify(r)).digest("hex")}`}l(yo,"scope");async function $i(e){let t=await yo(e),r=K(e,"client_preferences",t),n=await L(e);return{owner:t,revision:r?.revision??null,value:Vt.parse({...r?.value,notificationMode:n.document.notifications?.team_chat??"all"})}}l($i,"readClientChoices");async function Fp(e,t,r,n=!1){return x(Vi.join(y(e).runtime,"accounts"),async()=>{let o=Vt.parse(r);if(await yo(e)!==t)throw new _({code:"CLIENT_OWNER_CHANGED",path:"client_preferences",message:"The active account changed before this preference was saved.",action:"Reload preferences for the current account."});let{notificationMode:i,...s}=o;return i!==void 0&&await W(e,c=>n&&c.notifications?.team_chat!==void 0?c:{...c,notifications:{...c.notifications,team_chat:i}}),ge(e,c=>{c.exec("BEGIN IMMEDIATE");try{let d=c.prepare("SELECT payload, revision FROM client_preferences WHERE id=?").get(t),f=d?JSON.parse(d.payload):{};delete f.notificationMode;let p=Vt.parse(n?{...s,...f}:{...f,...s});c.prepare("INSERT INTO client_preferences VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(t,JSON.stringify(p)),c.exec("COMMIT")}catch(d){throw c.exec("ROLLBACK"),d}}),$i(e)})}l(Fp,"updateClientChoices");import{randomUUID as Pr}from"node:crypto";import{promises as Q}from"node:fs";import k from"node:path";import{backup as Qi}from"node:sqlite";import{createCipheriv as Gi,createDecipheriv as Ki,randomBytes as Hi}from"node:crypto";import{createReadStream as _o,createWriteStream as zi,promises as Fe}from"node:fs";import ne from"node:path";import{Readable as Wi}from"node:stream";import{pipeline as bo}from"node:stream/promises";import{createGzip as Ji,createGunzip as qi}from"node:zlib";var Ce=Buffer.from("OPBK1\0"),Xi=a.string().min(1).refine(e=>!ne.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).some(t=>!t||t==="."||t==="..")),Yi=a.strictObject({path:Xi,sizeBytes:a.number().safe().int().nonnegative(),sha256:a.string().regex(/^[a-f0-9]{64}$/),executable:a.boolean(),link:a.string().optional()}),wo=a.strictObject({schemaVersion:a.literal("openpond.recoveryBackup.v1"),originalHome:a.string(),createdAt:a.string().datetime(),entries:a.array(Yi).max(5e5),externalRoots:a.array(a.strictObject({path:a.string(),available:a.boolean(),included:a.literal(!1)})),browserIncluded:a.boolean()});async function To(e,t,r,n){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let o=Buffer.from(JSON.stringify(wo.parse(n)));if(o.length>32*1024*1024)throw new Error("Backup manifest exceeds the supported size.");let i=Buffer.alloc(4);i.writeUInt32BE(o.length);let s=Hi(12),c=Gi("aes-256-gcm",r,s);c.setAAD(Ce);let d=await Fe.open(t,"wx",384);try{await d.write(Buffer.concat([Ce,s])),await d.sync()}finally{await d.close()}async function*f(){yield i,yield o;for(let g of n.entries)if(g.link===void 0)for await(let m of _o(ne.join(e,g.path)))yield m}l(f,"archive"),await bo(Wi.from(f()),Ji(),c,zi(t,{flags:"a"}));let p=await Fe.open(t,"a");try{await p.write(c.getAuthTag()),await p.sync()}finally{await p.close()}}l(To,"encryptBackup");async function Eo(e,t,r){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let n=(await Fe.stat(e)).size,o=Ce.length+12;if(n<o+16)throw new Error("Truncated recovery backup.");let i=await Fe.open(e,"r"),s=Buffer.alloc(o),c=Buffer.alloc(16);try{await i.read(s,0,s.length,0),await i.read(c,0,16,n-16)}finally{await i.close()}if(!s.subarray(0,Ce.length).equals(Ce))throw new Error("Unsupported recovery backup format.");let d=Ki("aes-256-gcm",r,s.subarray(Ce.length));d.setAAD(Ce),d.setAuthTag(c);let f=_o(e,{start:o,end:n-17}),p=qi(),g=bo(f,d,p);g.catch(()=>{});let m=p[Symbol.asyncIterator](),h=Buffer.alloc(0),b=0;async function w(O){let S=Buffer.alloc(O),v=0;for(;v<O;){if(b>=h.length){let ue=await m.next();if(ue.done)throw new Error("Truncated recovery object.");h=Buffer.from(ue.value),b=0}let F=Math.min(O-v,h.length-b);h.copy(S,v,b,b+F),b+=F,v+=F}return S}l(w,"take");try{let O=(await w(4)).readUInt32BE();if(O>32*1024*1024)throw new Error("Invalid recovery manifest size.");let S=wo.parse(JSON.parse((await w(O)).toString("utf8")));if(new Set(S.entries.map(v=>v.path)).size!==S.entries.length)throw new Error("Duplicate recovery object paths.");for(let v of S.entries){let F=ne.join(t,v.path);if(/^(runtime|backups)([\\/]|$)/.test(v.path)||v.path.endsWith("-wal")||v.path.endsWith("-shm"))throw new Error("Recovery manifest contains an unsupported runtime object.");if(await U(ne.dirname(F)),v.link!==void 0){if(ne.isAbsolute(v.link)||!st(ne.resolve(ne.dirname(F),v.link),t))throw new Error("Recovery symlink leaves the backup root.");await Fe.symlink(v.link,F)}else{let ue=await Fe.open(F,"wx",v.executable?448:384);try{for(let Be=v.sizeBytes;Be>0;){let ct=await w(Math.min(1048576,Be));await ue.writeFile(ct),Be-=ct.length}await ue.sync()}finally{await ue.close()}}if(await G(F)!==v.sha256)throw new Error("Recovery object failed its checksum.")}if(b<h.length||!(await m.next()).done)throw new Error("Unexpected trailing recovery data.");return await g,S}catch(O){throw f.destroy(),d.destroy(),p.destroy(),await g.catch(()=>{}),O}}l(Eo,"decryptBackup");function st(e,t){let r=ne.relative(ne.resolve(t),ne.resolve(e));return r===""||r!==".."&&!r.startsWith(`..${ne.sep}`)&&!ne.isAbsolute(r)}l(st,"within");var Zi=new Set(["backups","runtime","cache","logs","diagnostics","browser","tmp","openpond-app","openpond-app-nightly","config.json","state.sqlite","state.sqlite-wal","state.sqlite-shm","providers.json","provider-secrets.json","provider-secrets.key","personalization.json","SOUL.md","token"]);async function mf(e,t,r){if(e=k.resolve(e),t=k.resolve(t),st(t,e))throw new Error("Export recovery backups outside the active home.");let n=[],o=k.join(k.dirname(e),`.${k.basename(e)}-backup-${Pr()}`),i=`${t}.${Pr()}.tmp`;try{n.push(await we(k.join(y(e).runtime,"server-owner"),100)),await uo(e);for(let f of["accounts","providers","preferences","personalization","artifacts"])n.push(await we(k.join(y(e).runtime,f)));n.push(await we(y(e).config)),n.push(await we(y(e).credentials)),await U(o);for(let f of await Q.readdir(e))Zi.has(f)||f==="state"||await Y(k.join(e,f),k.join(o,f));let s=y(e).database;if(await Q.stat(s).catch(f=>{if(R(f))return null;throw f})){await U(k.dirname(y(o).database));let f=D(s,!0);try{await Qi(f,y(o).database)}finally{f.close()}}await xe(o);let c=await Pt(e),d=[];for(let f of await at(o)){if(f.path.endsWith("-wal")||f.path.endsWith("-shm")||/^(config\.toml|secrets[\\/](?:credentials\.json|server-token))\.lock(?:\.|$)/.test(f.path))continue;let p=k.join(o,f.path),g=await Q.lstat(p),m=g.isSymbolicLink()?await Q.readlink(p):void 0;if(m!==void 0&&(k.isAbsolute(m)||!st(k.resolve(k.dirname(p),m),o)))throw new Error(`Source symlink requires rebinding before export: ${f.path}`);d.push({path:f.path,sha256:f.sha256,sizeBytes:m===void 0?g.size:0,executable:f.executable??!1,...m===void 0?{}:{link:m}})}return await Q.mkdir(k.dirname(t),{recursive:!0,mode:448}),await To(o,i,r,{schemaVersion:"openpond.recoveryBackup.v1",originalHome:e,createdAt:new Date().toISOString(),entries:d,externalRoots:c,browserIncluded:!1}),await Q.link(i,t),{path:t,files:d.length,externalRoots:c}}catch(s){throw s instanceof _?s:new _({code:"BACKUP_FAILED",path:t,message:"The recovery backup could not be completed.",action:"Keep the application stopped, check the destination and supplied encryption key, then retry. Existing backups are never overwritten."},{cause:s})}finally{await Q.rm(o,{recursive:!0,force:!0}),await Q.rm(i,{force:!0});for(let s of n.reverse())await s()}}l(mf,"exportRecoveryBackup");async function hf(e,t,r){t=k.resolve(t);let n=await Q.lstat(t).catch(i=>{if(R(i))return null;throw i});if(n&&(!n.isDirectory()||(await Q.readdir(t)).length))throw new Error("Restore requires a fresh, empty home. Existing homes are never overwritten.");let o=k.join(k.dirname(t),`.${k.basename(t)}-restore-${Pr()}`);await U(o);try{let i=await Eo(e,o,r);return await xe(o),await es(o,i.originalHome,t),await I(y(o).marker,JSON.stringify({schemaVersion:"openpond.storage.v1",version:1,migrationId:null,restoredAt:new Date().toISOString()})),await I(k.join(o,"restore-receipt.json"),JSON.stringify({schemaVersion:"openpond.restoreReceipt.v1",originalHome:i.originalHome,restoredAt:new Date().toISOString(),externalRoots:i.externalRoots})),await xe(o),n&&await Q.rmdir(t),await Q.rename(o,t),{home:t,files:i.entries.length,externalRoots:await Promise.all(i.externalRoots.map(async s=>({...s,available:!!await Q.stat(s.path).catch(()=>null)})))}}catch(i){throw new _({code:"RESTORE_FAILED",path:t,message:"The backup could not be authenticated and validated for restoration.",action:"Check the backup and its separately stored key. The existing home has not been replaced."},{cause:i})}finally{await Q.rm(o,{recursive:!0,force:!0})}}l(hf,"restoreRecoveryBackup");async function es(e,t,r){let n=l(o=>st(o,t)?k.join(r,k.relative(t,o)):o,"rebase");await W(e,o=>({...o,...o.storage?.datasets_dir&&k.isAbsolute(o.storage.datasets_dir)?{storage:{...o.storage,datasets_dir:n(o.storage.datasets_dir)}}:{},...o.personalization?.user_instructions&&k.isAbsolute(o.personalization.user_instructions)?{personalization:{...o.personalization,user_instructions:n(o.personalization.user_instructions)}}:{},...o.projects?.new_project_directory&&k.isAbsolute(o.projects.new_project_directory)?{projects:{...o.projects,new_project_directory:n(o.projects.new_project_directory)}}:{}})),Bt(e,[{from:t,to:r}])}l(es,"rebaseRestoredPointers");async function bf(e){let t=structuredClone((await L(e)).document),r=[];function n(o,i,s,c){o&&Object.hasOwn(o,i)&&(delete o[i],r.push({path:[...s,i],reason:c}))}l(n,"omit");for(let o of["accounts","providers"])for(let[i,s]of Object.entries(t[o]??{}))n(s,"credential",[o,i],"Reconnect or bind a credential on the destination device.");for(let o of["accounts","providers"])for(let[i,s]of Object.entries(t[o]??{}))for(let c of["base_url","api_base_url","chat_api_base_url"]){let d=s[c];if(typeof d=="string")try{let f=new URL(d);(f.username||f.password||[...f.searchParams.keys()].some(p=>/token|key|secret|password|credential|signature/i.test(p))||f.hash)&&n(s,c,[o,i],"Rebind this endpoint without embedded authentication data.")}catch{n(s,c,[o,i],"Validate and bind this endpoint on the destination device.")}}n(t.storage,"datasets_dir",["storage"],"Choose the dataset storage root on the destination device."),n(t.projects,"new_project_directory",["projects"],"Choose the local projects directory."),n(t.personalization,"user_instructions",["personalization"],"Transfer the instruction source and bind its destination path."),t.personalization?.active?.startsWith("custom:")&&n(t.personalization,"active",["personalization"],"Transfer the selected custom personality Markdown before selecting it."),n(t.defaults,"profile_ref",["defaults"],"Install and select the Profile on the destination device.");for(let[o,i]of Object.entries(t.editor?.languages??{}))i.custom_command&&(n(i,"custom_command",["editor","languages",o],"Configure the local language-server command."),i.mode==="custom"&&delete i.mode);return{schemaVersion:"openpond.settingsExport.v1",config:t,requiresRebinding:r}}l(bf,"exportSettings");async function ts(e){let t=y(e).marker,r=await M(t,()=>null);if(r&&(r.schemaVersion!=="openpond.storage.v1"||r.version!==1))throw new _({code:"UNSUPPORTED_STORAGE_VERSION",path:t,message:"This OpenPond home requires a different application version.",action:"Update OpenPond, or restore a compatible backup into a separate home."})}l(ts,"assertHomeCompatible");export{Ao as a,$ as b,E as c,U as d,I as e,x as f,we as g,Io as h,M as i,cs as j,Fr as k,zt as l,Oo as m,No as n,ko as o,Mo as p,ms as q,Do as r,Jt as s,hs as t,gs as u,ys as v,_s as w,bs as x,ws as y,Ke as z,qt as A,Fo as B,Bo as C,Yt as D,Ko as E,zo as F,xs as G,qo as H,Cs as I,zr as J,Yo as K,Ms as L,Qo as M,ta as N,Wr as O,er as P,tr as Q,rr as R,Ds as S,js as T,Gr as U,Qt as V,Fs as W,Bs as X,Kr as Y,Hr as Z,Z as _,sa as $,He as aa,qr as ba,Vs as ca,$s as da,Qr as ea,ar as fa,oe as ga,ie as ha,Ya as ia,gr as ja,St as ka,Qa as la,Za as ma,xc as na,Lc as oa,L as pa,Bc as qa,W as ra,vt as sa,Vc as ta,Hc as ua,Ae as va,Ze as wa,xt as xa,Zc as ya,br as za,el as Aa,tl as Ba,Ot as Ca,ll as Da,Nt as Ea,In as Fa,xn as Ga,Ln as Ha,Pe as Ia,Nn as Ja,Pn as Ka,Fn as La,Bn as Ma,_i as Na,Zl as Oa,ed as Pa,td as Qa,Ut as Ra,Me as Sa,Ci as Ta,uo as Ua,xe as Va,Di as Wa,Xu as Xa,Ui as Ya,sp as Za,Ep as _a,go as $a,Sp as ab,Ap as bb,vp as cb,Vt as db,Cp as eb,$i as fb,Fp as gb,mf as hb,hf as ib,bf as jb,ts as kb};
53
+ `),e.status="committed",await le(e),e.status="verified",delete e.error,await le(e),await P.rm(e.stage,{recursive:!0,force:!0})}l(Mi,"install");async function Di(e){return x(T.join(y(e).runtime,"migration-owner"),async()=>{let t=await Me(e);if(!t)throw C(e,"No migration journal is available.");return Nr(t)})}l(Di,"recoverMigration");async function Nr(e){if(e.status==="verified")return je(e.home,"current",e);try{return(e.status==="preparing"||e.status==="failed")&&(await P.rm(e.stage,{recursive:!0,force:!0}),e.status="preparing",await po(e)),e.status!=="committed"?await Mi(e):(await xe(e.home),e.status="verified",await le(e),await P.rm(e.stage,{recursive:!0,force:!0})),je(e.home,"verified",e)}catch(t){throw e.error=t instanceof _?t.issue.code:"MIGRATION_FAILED",e.status==="preparing"&&(e.status="failed"),await le(e),t instanceof _?t:new _({code:"MIGRATION_FAILED",path:T.join(y(e.home).runtime,"migration.json"),message:"OpenPond could not finish updating its storage.",action:"Open migration details or run openpond config recover. Original data and snapshots have been preserved."},{cause:t})}}l(Nr,"recoverUnlocked");function je(e,t,r){return{id:r?.id??null,status:t,home:e,sourceAppHome:r?.sourceAppHome??null,sourceConfig:r?.sourceConfig??null,backup:r?.backup??null}}l(je,"report");async function Xu(e){return x(T.join(y(e).runtime,"migration-owner"),async()=>{let t=await Me(e);if(!t)return{restarted:!1,backup:null};if(!["preparing","failed"].includes(t.status)||t.installed.length||t.files.length)throw C(e,"Installation has already begun. Resume recovery or restore into a fresh home; preparation cannot be restarted.");return await ot(t.sourceAppHome,t.sourceConfig),await I(T.join(t.backup,"abandoned-preparation.json"),JSON.stringify(t,null,2)),await P.rm(t.stage,{recursive:!0,force:!0}),await P.rm(T.join(y(e).runtime,"migration.json")),{restarted:!0,backup:t.backup}})}l(Xu,"restartMigration");async function Ui(e){let t=await L(e),r=K(e,"client_preferences","global");return{preferences:Ze(t.document,r?.value),config:t}}l(Ui,"readPreferences");async function sp(e,t,r){return x(`${y(e).runtime}/preferences`,async()=>{let n=K(e,"client_preferences","global"),o=n?.value;return await W(e,i=>{let s=Ze(i,n?.value),c=Z.parse({...s,...t,...t.defaultChatModelRef===void 0&&(t.defaultChatModel!==void 0||t.defaultChatProvider!==void 0)?{defaultChatModelRef:{providerId:t.defaultChatProvider??s.defaultChatProvider,modelId:t.defaultChatModel??s.defaultChatModel}}:{}});o=xt(c);let d=structuredClone(i);for(let f of ie(Ae(s),Ae(c))){let p=d;for(let m of f.path.slice(0,-1))p[m]??={},p=p[m];let g=f.path.at(-1);f.op==="set"?p[g]=f.value:delete p[g]}return d},r),o&&JSON.stringify(o)!==JSON.stringify(n?.value)&&B(e,"client_preferences","global",o,n?.revision??null),Ui(e)})}l(sp,"updatePreferences");import{createHash as ji}from"node:crypto";import{promises as Le}from"node:fs";import mo from"node:path";var me=l(e=>ji("sha256").update(JSON.stringify(e)??"null").digest("hex"),"hash"),ho=l((e,t="local")=>me([e,t]),"trustKey");async function Ep(e,t,r,n){let o=await Le.realpath(t);B(e,"project_trust",ho(o,r),{root:o,accountId:r,trusted:n,updatedAt:new Date().toISOString()})}l(Ep,"setProjectTrust");async function go(e,t={}){let r=Ae(Z.parse({})),n=[],o={},i=[];function s(h,b,w,O=me(b)){let S={layer:h,path:w,revision:O};r=vt(r,b),n.push(S);function v(F,ue){if(F&&typeof F=="object"&&!Array.isArray(F)&&!("mode"in F)&&!("source"in F)&&!("provider_id"in F))for(let[Be,ct]of Object.entries(F))v(ct,[...ue,Be]);else o[JSON.stringify(ue)]=S}l(v,"visit"),v(b,[])}l(s,"apply"),s("defaults",r,"shipped"),t.profile&&(fo(t.profile.defaults,"profile"),s("profile",t.profile.defaults,t.profile.id,t.profile.revision));let c=await L(e);s("user",c.document,c.path,c.rawRevision);let d=structuredClone(r.permissions),f=null,p=null;if(t.projectRoot){f=await Le.realpath(t.projectRoot);let h=mo.join(f,".openpond","config.toml");if(await Le.lstat(h).catch(w=>{if(R(w))return null;throw w})){if(await Le.realpath(h)!==h)throw new _({code:"UNSAFE_PROJECT_CONFIG",path:h,message:"Project configuration must be a regular file inside its canonical project root.",action:"Replace symbolic links in the project configuration path with a regular local file."});let O=K(e,"project_trust",ho(f,t.accountId));if(!O?.value.trusted)i.push({code:"PROJECT_CONFIG_UNTRUSTED",path:h,message:"Project settings are ignored until this project is trusted.",action:"Review the project configuration, then trust it in configuration settings."});else{p=O.revision;let S=await L(e,{path:h,scope:"project"});s("project",S.document,S.path,S.rawRevision),d?.command_access==="disabled"&&(r.permissions={...r.permissions,command_access:"disabled"}),d?.codex_mode==="default"&&(r.permissions={...r.permissions,codex_mode:"default"}),d=structuredClone(r.permissions)}}}for(let h of["task","turn"])t[h]&&(fo(t[h],h),s(h,t[h],h));(d?.command_access==="disabled"||d?.command_access==="ask"&&r.permissions?.command_access==="full-access")&&(r.permissions={...r.permissions,command_access:d.command_access}),d?.codex_mode&&d.codex_mode!=="full-access"&&r.permissions?.codex_mode!=="default"&&(r.permissions={...r.permissions,codex_mode:d.codex_mode}),oe(r),await Fi(e,r);let g=[...Object.values(r.accounts??{}),...Object.values(r.providers??{})].flatMap(h=>h.credential?.source==="secret"?[h.credential.id]:[]),m=await Ln(e,g);return{document:r,effectiveRevision:me({document:r,sources:n,projectTrustRevision:p,versions:m}),sources:n,provenance:o,diagnostics:i,projectRoot:f,projectTrustRevision:p,credentialVersions:m}}l(go,"resolveEffectiveConfig");function fo(e,t){oe(e);let r=t==="profile"?["schema_version","chat","codex","context_compaction","subagents","runtime"]:["schema_version","chat","codex","context_compaction","subagents","permissions"];for(let n of Object.keys(e))if(!r.includes(n))throw new _({code:"CONFIG_SCOPE_VIOLATION",path:`${t}.${n}`,message:`This setting is not allowed in ${t} configuration.`,action:"Move host settings to the user configuration file."})}l(fo,"checkScope");async function Fi(e,t){let r=t.defaults;if(r?.account_id&&(!t.accounts?.[r.account_id]||t.accounts[r.account_id].enabled===!1))throw new _({code:"INVALID_ACCOUNT_DEFAULT",path:"defaults.account_id",message:"The default account is missing or disabled.",action:"Choose an enabled account or remove the explicit default."});let n=t.personalization?.active;if(n&&t.personalization?.mode!=="disabled"){let i=n.startsWith("custom:")?mo.join(e,"instructions","personalities",`${n.slice(7)}.md`):n,s=n.startsWith("custom:")?await E(i):He.find(c=>c.id===n.slice(8))?.content;if(s==null||s.trim().length>8e3)throw new _({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The selected personality is missing or exceeds its supported size.",action:"Restore its Markdown file or select an available personality in Settings."})}let o=t.personalization?.user_instructions;if(o){let i=Ve(o,e);try{if(!(await Le.stat(i)).isFile())throw new Error("Not a file");await Le.access(i,Le.constants.R_OK)}catch(s){throw new _({code:"MISSING_INSTRUCTION_SOURCE",path:i,message:"The configured user instruction file cannot be read.",action:"Restore the file or remove its configuration reference."},{cause:s})}}}l(Fi,"validateRequiredSources");async function Sp(e,t,r={}){let n=await go(e,r);return B(e,"config_run_snapshots",t,{...n,capturedAt:new Date().toISOString()},null),n}l(Sp,"captureConfigRun");async function Ap(e,t,r={}){let n=await go(e,r);if(t.projectTrustRevision!==null&&n.projectTrustRevision!==t.projectTrustRevision)throw new _({code:"PROJECT_TRUST_CHANGED",path:t.projectRoot??e,message:"Project trust changed during this turn.",action:"Review project trust before starting a new turn."});let o=t.document.permissions,i=n.document.permissions;if(i?.command_access!==o?.command_access||i?.codex_mode!==o?.codex_mode||me(n.credentialVersions)!==me(t.credentialVersions)||me(n.document.accounts)!==me(t.document.accounts)||me(n.document.providers)!==me(t.document.providers))throw new _({code:"EXECUTION_POLICY_CHANGED",path:e,message:"Permissions or credential configuration changed during this turn.",action:"Start a new turn with the current settings."})}l(Ap,"assertConfigRunCurrent");function vp(e){return Ze(e.document)}l(vp,"effectivePreferences");import{createHash as Bi}from"node:crypto";var Vt=a.strictObject({chatMode:a.enum(["chat","work"]).optional(),notificationMode:a.enum(["all","direct_mentions","none"]).optional(),learningNoticeDismissed:a.boolean().optional(),sidebarVisibility:a.strictObject({showCodexChats:a.boolean(),onlyRunningTasks:a.boolean()}).optional(),scheduledWorkView:a.enum(["calendar","list"]).optional(),editorControlsVisible:a.boolean().optional(),voiceNoticeAcknowledged:a.boolean().optional(),lessonProgress:a.record(a.string().min(1).max(200),a.strictObject({completed:a.boolean(),currentTime:a.number().finite().nonnegative(),duration:a.number().finite().positive(),updatedAt:a.number().finite().nonnegative()})).refine(e=>Object.keys(e).length<=200,"Too many lessons").optional()}),Cp={"openpond:last-chat-task-mode":"chatMode","openpond.team-chat.notification-mode":"notificationMode","openpond.sidebar.continuous-learning.dismissed.v1":"learningNoticeDismissed","openpond.sidebar-task-visibility.v1":"sidebarVisibility","openpond.scheduled-work.view.v1":"scheduledWorkView","openpond.workspace.editorControlsVisible":"editorControlsVisible","openpond.voice.setupNoticeAcknowledged":"voiceNoticeAcknowledged","openpond.post-training-progress.v1":"lessonProgress"};import Vi from"node:path";async function yo(e){let r=(await L(e)).document.defaults?.account_id??K(e,"account_selection","last_used")?.value??"local";return`choices:${Bi("sha256").update(JSON.stringify(r)).digest("hex")}`}l(yo,"scope");async function $i(e){let t=await yo(e),r=K(e,"client_preferences",t),n=await L(e);return{owner:t,revision:r?.revision??null,value:Vt.parse({...r?.value,notificationMode:n.document.notifications?.team_chat??"all"})}}l($i,"readClientChoices");async function Fp(e,t,r,n=!1){return x(Vi.join(y(e).runtime,"accounts"),async()=>{let o=Vt.parse(r);if(await yo(e)!==t)throw new _({code:"CLIENT_OWNER_CHANGED",path:"client_preferences",message:"The active account changed before this preference was saved.",action:"Reload preferences for the current account."});let{notificationMode:i,...s}=o;return i!==void 0&&await W(e,c=>n&&c.notifications?.team_chat!==void 0?c:{...c,notifications:{...c.notifications,team_chat:i}}),ge(e,c=>{c.exec("BEGIN IMMEDIATE");try{let d=c.prepare("SELECT payload, revision FROM client_preferences WHERE id=?").get(t),f=d?JSON.parse(d.payload):{};delete f.notificationMode;let p=Vt.parse(n?{...s,...f}:{...f,...s});c.prepare("INSERT INTO client_preferences VALUES (?, ?, 1) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload, revision=revision+1").run(t,JSON.stringify(p)),c.exec("COMMIT")}catch(d){throw c.exec("ROLLBACK"),d}}),$i(e)})}l(Fp,"updateClientChoices");import{randomUUID as Pr}from"node:crypto";import{promises as Q}from"node:fs";import k from"node:path";import{backup as Qi}from"node:sqlite";import{createCipheriv as Gi,createDecipheriv as Ki,randomBytes as Hi}from"node:crypto";import{createReadStream as _o,createWriteStream as zi,promises as Fe}from"node:fs";import ne from"node:path";import{Readable as Wi}from"node:stream";import{pipeline as bo}from"node:stream/promises";import{createGzip as Ji,createGunzip as qi}from"node:zlib";var Ce=Buffer.from("OPBK1\0"),Xi=a.string().min(1).refine(e=>!ne.isAbsolute(e)&&!/^[A-Za-z]:/.test(e)&&!e.split(/[\\/]/).some(t=>!t||t==="."||t==="..")),Yi=a.strictObject({path:Xi,sizeBytes:a.number().safe().int().nonnegative(),sha256:a.string().regex(/^[a-f0-9]{64}$/),executable:a.boolean(),link:a.string().optional()}),wo=a.strictObject({schemaVersion:a.literal("openpond.recoveryBackup.v1"),originalHome:a.string(),createdAt:a.string().datetime(),entries:a.array(Yi).max(5e5),externalRoots:a.array(a.strictObject({path:a.string(),available:a.boolean(),included:a.literal(!1)})),browserIncluded:a.boolean()});async function To(e,t,r,n){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let o=Buffer.from(JSON.stringify(wo.parse(n)));if(o.length>32*1024*1024)throw new Error("Backup manifest exceeds the supported size.");let i=Buffer.alloc(4);i.writeUInt32BE(o.length);let s=Hi(12),c=Gi("aes-256-gcm",r,s);c.setAAD(Ce);let d=await Fe.open(t,"wx",384);try{await d.write(Buffer.concat([Ce,s])),await d.sync()}finally{await d.close()}async function*f(){yield i,yield o;for(let g of n.entries)if(g.link===void 0)for await(let m of _o(ne.join(e,g.path)))yield m}l(f,"archive"),await bo(Wi.from(f()),Ji(),c,zi(t,{flags:"a"}));let p=await Fe.open(t,"a");try{await p.write(c.getAuthTag()),await p.sync()}finally{await p.close()}}l(To,"encryptBackup");async function Eo(e,t,r){if(r.byteLength!==32)throw new Error("A backup encryption key must contain exactly 32 bytes.");let n=(await Fe.stat(e)).size,o=Ce.length+12;if(n<o+16)throw new Error("Truncated recovery backup.");let i=await Fe.open(e,"r"),s=Buffer.alloc(o),c=Buffer.alloc(16);try{await i.read(s,0,s.length,0),await i.read(c,0,16,n-16)}finally{await i.close()}if(!s.subarray(0,Ce.length).equals(Ce))throw new Error("Unsupported recovery backup format.");let d=Ki("aes-256-gcm",r,s.subarray(Ce.length));d.setAAD(Ce),d.setAuthTag(c);let f=_o(e,{start:o,end:n-17}),p=qi(),g=bo(f,d,p);g.catch(()=>{});let m=p[Symbol.asyncIterator](),h=Buffer.alloc(0),b=0;async function w(O){let S=Buffer.alloc(O),v=0;for(;v<O;){if(b>=h.length){let ue=await m.next();if(ue.done)throw new Error("Truncated recovery object.");h=Buffer.from(ue.value),b=0}let F=Math.min(O-v,h.length-b);h.copy(S,v,b,b+F),b+=F,v+=F}return S}l(w,"take");try{let O=(await w(4)).readUInt32BE();if(O>32*1024*1024)throw new Error("Invalid recovery manifest size.");let S=wo.parse(JSON.parse((await w(O)).toString("utf8")));if(new Set(S.entries.map(v=>v.path)).size!==S.entries.length)throw new Error("Duplicate recovery object paths.");for(let v of S.entries){let F=ne.join(t,v.path);if(/^(runtime|backups)([\\/]|$)/.test(v.path)||v.path.endsWith("-wal")||v.path.endsWith("-shm"))throw new Error("Recovery manifest contains an unsupported runtime object.");if(await U(ne.dirname(F)),v.link!==void 0){if(ne.isAbsolute(v.link)||!st(ne.resolve(ne.dirname(F),v.link),t))throw new Error("Recovery symlink leaves the backup root.");await Fe.symlink(v.link,F)}else{let ue=await Fe.open(F,"wx",v.executable?448:384);try{for(let Be=v.sizeBytes;Be>0;){let ct=await w(Math.min(1048576,Be));await ue.writeFile(ct),Be-=ct.length}await ue.sync()}finally{await ue.close()}}if(await G(F)!==v.sha256)throw new Error("Recovery object failed its checksum.")}if(b<h.length||!(await m.next()).done)throw new Error("Unexpected trailing recovery data.");return await g,S}catch(O){throw f.destroy(),d.destroy(),p.destroy(),await g.catch(()=>{}),O}}l(Eo,"decryptBackup");function st(e,t){let r=ne.relative(ne.resolve(t),ne.resolve(e));return r===""||r!==".."&&!r.startsWith(`..${ne.sep}`)&&!ne.isAbsolute(r)}l(st,"within");var Zi=new Set(["backups","runtime","cache","logs","diagnostics","browser","tmp","openpond-app","openpond-app-nightly","config.json","state.sqlite","state.sqlite-wal","state.sqlite-shm","providers.json","provider-secrets.json","provider-secrets.key","personalization.json","SOUL.md","token"]);async function mf(e,t,r){if(e=k.resolve(e),t=k.resolve(t),st(t,e))throw new Error("Export recovery backups outside the active home.");let n=[],o=k.join(k.dirname(e),`.${k.basename(e)}-backup-${Pr()}`),i=`${t}.${Pr()}.tmp`;try{n.push(await we(k.join(y(e).runtime,"server-owner"),100)),await uo(e);for(let f of["accounts","providers","preferences","personalization","artifacts"])n.push(await we(k.join(y(e).runtime,f)));n.push(await we(y(e).config)),n.push(await we(y(e).credentials)),await U(o);for(let f of await Q.readdir(e))Zi.has(f)||f==="state"||await Y(k.join(e,f),k.join(o,f));let s=y(e).database;if(await Q.stat(s).catch(f=>{if(R(f))return null;throw f})){await U(k.dirname(y(o).database));let f=D(s,!0);try{await Qi(f,y(o).database)}finally{f.close()}}await xe(o);let c=await Pt(e),d=[];for(let f of await at(o)){if(f.path.endsWith("-wal")||f.path.endsWith("-shm")||/^(config\.toml|secrets[\\/](?:credentials\.json|server-token))\.lock(?:\.|$)/.test(f.path))continue;let p=k.join(o,f.path),g=await Q.lstat(p),m=g.isSymbolicLink()?await Q.readlink(p):void 0;if(m!==void 0&&(k.isAbsolute(m)||!st(k.resolve(k.dirname(p),m),o)))throw new Error(`Source symlink requires rebinding before export: ${f.path}`);d.push({path:f.path,sha256:f.sha256,sizeBytes:m===void 0?g.size:0,executable:f.executable??!1,...m===void 0?{}:{link:m}})}return await Q.mkdir(k.dirname(t),{recursive:!0,mode:448}),await To(o,i,r,{schemaVersion:"openpond.recoveryBackup.v1",originalHome:e,createdAt:new Date().toISOString(),entries:d,externalRoots:c,browserIncluded:!1}),await Q.link(i,t),{path:t,files:d.length,externalRoots:c}}catch(s){throw s instanceof _?s:new _({code:"BACKUP_FAILED",path:t,message:"The recovery backup could not be completed.",action:"Keep the application stopped, check the destination and supplied encryption key, then retry. Existing backups are never overwritten."},{cause:s})}finally{await Q.rm(o,{recursive:!0,force:!0}),await Q.rm(i,{force:!0});for(let s of n.reverse())await s()}}l(mf,"exportRecoveryBackup");async function hf(e,t,r){t=k.resolve(t);let n=await Q.lstat(t).catch(i=>{if(R(i))return null;throw i});if(n&&(!n.isDirectory()||(await Q.readdir(t)).length))throw new Error("Restore requires a fresh, empty home. Existing homes are never overwritten.");let o=k.join(k.dirname(t),`.${k.basename(t)}-restore-${Pr()}`);await U(o);try{let i=await Eo(e,o,r);return await xe(o),await es(o,i.originalHome,t),await I(y(o).marker,JSON.stringify({schemaVersion:"openpond.storage.v1",version:1,migrationId:null,restoredAt:new Date().toISOString()})),await I(k.join(o,"restore-receipt.json"),JSON.stringify({schemaVersion:"openpond.restoreReceipt.v1",originalHome:i.originalHome,restoredAt:new Date().toISOString(),externalRoots:i.externalRoots})),await xe(o),n&&await Q.rmdir(t),await Q.rename(o,t),{home:t,files:i.entries.length,externalRoots:await Promise.all(i.externalRoots.map(async s=>({...s,available:!!await Q.stat(s.path).catch(()=>null)})))}}catch(i){throw new _({code:"RESTORE_FAILED",path:t,message:"The backup could not be authenticated and validated for restoration.",action:"Check the backup and its separately stored key. The existing home has not been replaced."},{cause:i})}finally{await Q.rm(o,{recursive:!0,force:!0})}}l(hf,"restoreRecoveryBackup");async function es(e,t,r){let n=l(o=>st(o,t)?k.join(r,k.relative(t,o)):o,"rebase");await W(e,o=>({...o,...o.storage?.datasets_dir&&k.isAbsolute(o.storage.datasets_dir)?{storage:{...o.storage,datasets_dir:n(o.storage.datasets_dir)}}:{},...o.personalization?.user_instructions&&k.isAbsolute(o.personalization.user_instructions)?{personalization:{...o.personalization,user_instructions:n(o.personalization.user_instructions)}}:{},...o.projects?.new_project_directory&&k.isAbsolute(o.projects.new_project_directory)?{projects:{...o.projects,new_project_directory:n(o.projects.new_project_directory)}}:{}})),Bt(e,[{from:t,to:r}])}l(es,"rebaseRestoredPointers");async function bf(e){let t=structuredClone((await L(e)).document),r=[];function n(o,i,s,c){o&&Object.hasOwn(o,i)&&(delete o[i],r.push({path:[...s,i],reason:c}))}l(n,"omit");for(let o of["accounts","providers"])for(let[i,s]of Object.entries(t[o]??{}))n(s,"credential",[o,i],"Reconnect or bind a credential on the destination device.");for(let o of["accounts","providers"])for(let[i,s]of Object.entries(t[o]??{}))for(let c of["base_url","api_base_url","chat_api_base_url"]){let d=s[c];if(typeof d=="string")try{let f=new URL(d);(f.username||f.password||[...f.searchParams.keys()].some(p=>/token|key|secret|password|credential|signature/i.test(p))||f.hash)&&n(s,c,[o,i],"Rebind this endpoint without embedded authentication data.")}catch{n(s,c,[o,i],"Validate and bind this endpoint on the destination device.")}}n(t.storage,"datasets_dir",["storage"],"Choose the dataset storage root on the destination device."),n(t.projects,"new_project_directory",["projects"],"Choose the local projects directory."),n(t.personalization,"user_instructions",["personalization"],"Transfer the instruction source and bind its destination path."),t.personalization?.active?.startsWith("custom:")&&n(t.personalization,"active",["personalization"],"Transfer the selected custom personality Markdown before selecting it."),n(t.defaults,"profile_ref",["defaults"],"Install and select the Profile on the destination device.");for(let[o,i]of Object.entries(t.editor?.languages??{}))i.custom_command&&(n(i,"custom_command",["editor","languages",o],"Configure the local language-server command."),i.mode==="custom"&&delete i.mode);return{schemaVersion:"openpond.settingsExport.v1",config:t,requiresRebinding:r}}l(bf,"exportSettings");async function ts(e){let t=y(e).marker,r=await M(t,()=>null);if(r&&(r.schemaVersion!=="openpond.storage.v1"||r.version!==1))throw new _({code:"UNSUPPORTED_STORAGE_VERSION",path:t,message:"This OpenPond home requires a different application version.",action:"Update OpenPond, or restore a compatible backup into a separate home."})}l(ts,"assertHomeCompatible");export{Fr as a,zt as b,Oo as c,No as d,ko as e,Mo as f,ms as g,Do as h,Jt as i,hs as j,gs as k,ys as l,_s as m,bs as n,ws as o,Ke as p,qt as q,Fo as r,Bo as s,Yt as t,Ko as u,zo as v,xs as w,qo as x,Cs as y,zr as z,Yo as A,Ms as B,Qo as C,ta as D,Wr as E,er as F,tr as G,rr as H,Ds as I,js as J,Gr as K,Qt as L,Fs as M,Bs as N,Kr as O,Hr as P,Z as Q,sa as R,He as S,qr as T,Vs as U,$s as V,Ao as W,$ as X,E as Y,U as Z,I as _,x as $,we as aa,Io as ba,M as ca,cs as da,Qr as ea,ar as fa,oe as ga,ie as ha,Ya as ia,gr as ja,St as ka,Qa as la,Za as ma,xc as na,Lc as oa,L as pa,Bc as qa,W as ra,vt as sa,Vc as ta,Hc as ua,Ae as va,Ze as wa,xt as xa,Zc as ya,br as za,el as Aa,tl as Ba,Ot as Ca,ll as Da,Nt as Ea,In as Fa,xn as Ga,Ln as Ha,Pe as Ia,Nn as Ja,Pn as Ka,Fn as La,Bn as Ma,_i as Na,Zl as Oa,ed as Pa,td as Qa,Ut as Ra,Me as Sa,Ci as Ta,uo as Ua,xe as Va,Di as Wa,Xu as Xa,Ui as Ya,sp as Za,Ep as _a,go as $a,Sp as ab,Ap as bb,vp as cb,Vt as db,Cp as eb,$i as fb,Fp as gb,mf as hb,hf as ib,bf as jb,ts as kb};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __openpondCreateRequire } from "node:module"; var require = __openpondCreateRequire(import.meta.url);
2
+ import{Wa as A,v as C}from"./chunk-JUX77H6K.js";import{a as f,b,c as R,e as H,h as j,l as h,m as z}from"./chunk-HZP5U2AA.js";import{b as e}from"./chunk-ES2ISFJC.js";import{a as d}from"./chunk-FTQLQJQV.js";var F=e.number().finite().nonnegative(),V=e.discriminatedUnion("kind",[e.object({kind:e.literal("model"),modelId:f,configurationHash:b}).strict(),e.object({kind:e.literal("harness"),source:A}).strict(),e.object({kind:e.literal("fixture"),configurationHash:b}).strict()]),U=e.object({release:H.extend({revision:e.union([e.number().int().positive(),e.string().trim().min(1).max(200)])}).strict(),feedbackKey:C,configurationHash:b.optional(),output:e.enum(["boolean","score","category"]),categories:e.array(e.string().trim().min(1).max(120)).max(50)}).strict().superRefine((t,n)=>{t.output==="category"!=t.categories.length>0&&n.addIssue({code:"custom",path:["categories"],message:"Only category feedback declares categories."}),new Set(t.categories).size!==t.categories.length&&n.addIssue({code:"custom",path:["categories"],message:"Feedback categories must be unique."})}),M=e.object({caseId:f,seed:e.string().trim().min(1).max(500),fixtureId:f.nullable()}).strict();function K(t){let n=M.parse(t);return JSON.stringify([n.caseId,n.seed,n.fixtureId])}d(K,"experimentCaseKey");var D=e.object({schemaVersion:e.literal("openpond.experimentManifest.v1"),id:f,name:e.string().trim().min(1).max(500),teamId:f,operationId:f,maximumCostUsd:F.nullable(),dataset:H.extend({revision:e.number().int().positive()}).strict(),target:V,execution:e.object({packageHash:b,runtimeTargetHash:b,metricPolicyHash:b}).strict().optional(),lineage:e.object({definition:H.extend({revision:e.number().int().positive()}).strict().nullable(),execution:H,scoringPassId:f.nullable()}).strict().optional(),evaluators:e.array(U).max(100),population:e.array(M).min(1).max(1e4),createdAt:R}).strict().superRefine((t,n)=>{t.lineage&&t.id!==(t.lineage.scoringPassId??t.lineage.execution.id)&&n.addIssue({code:"custom",path:["lineage"],message:"Experiment identity must match its execution or independent scoring pass."}),new Set(t.population.map(K)).size!==t.population.length&&n.addIssue({code:"custom",path:["population"],message:"Experiment cases must be unique."}),new Set(t.evaluators.map(s=>s.feedbackKey)).size!==t.evaluators.length&&n.addIssue({code:"custom",path:["evaluators"],message:"Experiment feedback keys must be unique."})}),q=D.extend({contentHash:b}).strict(),J=e.object({feedbackKey:C,evaluator:U.shape.release,status:e.enum(["scored","unavailable","failed","pending"]),value:e.union([e.boolean(),e.number().finite(),e.string().max(120)]).nullable(),passed:e.boolean().nullable().optional(),reasoning:e.string().max(2e4).nullable(),evidenceRefs:e.array(j).max(1e3)}).strict(),B=e.object({inputTokens:e.number().int().nonnegative().nullable(),outputTokens:e.number().int().nonnegative().nullable(),totalTokens:e.number().int().nonnegative().nullable(),costUsd:F.nullable(),latencyMs:e.number().finite().nonnegative().nullable()}).strict().superRefine((t,n)=>{t.inputTokens!==null&&t.outputTokens!==null&&t.totalTokens!==null&&t.totalTokens<t.inputTokens+t.outputTokens&&n.addIssue({code:"custom",path:["totalTokens"],message:"Total tokens cannot be less than input plus output."})}),G=e.object({identity:M,status:e.enum(["completed","failed","cancelled","unavailable"]),output:e.unknown().nullable(),error:e.object({code:f,message:e.string().max(2e3)}).strict().nullable(),feedback:e.array(J).max(100),usage:B,traceRef:j.nullable(),startedAt:R.nullable(),completedAt:R.nullable()}).strict(),N=e.object({schemaVersion:e.literal("openpond.experimentResult.v1"),manifest:H,status:e.enum(["completed","failed","cancelled"]),cases:e.array(G).min(1).max(1e4),completedAt:R}).strict(),O=N.extend({contentHash:b}).strict();function L(t,n){q.parse(n),z(n,"Experiment manifest");let s=N.parse(t);if(s.manifest.id!==n.id||s.manifest.contentHash!==n.contentHash)throw new Error("Experiment result differs from its manifest.");let v=new Set(n.population.map(K)),l=new Set,w=new Map(n.evaluators.map(g=>[g.feedbackKey,g]));for(let g of s.cases){let S=K(g.identity);if(!v.has(S)||l.has(S))throw new Error("Experiment result has an unexpected or repeated case.");l.add(S);let I=new Set;for(let i of g.feedback){let a=w.get(i.feedbackKey);if(!a||I.has(i.feedbackKey)||i.evaluator.id!==a.release.id||i.evaluator.contentHash!==a.release.contentHash||i.evaluator.revision!==a.release.revision)throw new Error("Experiment feedback differs from its pinned evaluator.");if(I.add(i.feedbackKey),i.status==="scored"){if(i.value===null||typeof i.value!=={boolean:"boolean",score:"number",category:"string"}[a.output]||a.output==="category"&&!a.categories.includes(i.value)||a.output==="score"&&(i.value<0||i.value>1))throw new Error("Experiment feedback value violates its output contract.")}else if(i.value!==null||i.passed!==null&&i.passed!==void 0)throw new Error("Unscored experiment feedback cannot claim a value or pass decision.")}}if(l.size!==v.size)throw new Error("Experiment result omits admitted cases.");return O.parse({...s,contentHash:h(s)})}d(L,"createExperimentResult");function Q(t){let n=q.parse(t.manifest),s=O.parse(t.result),{contentHash:v,...l}=s;if(h(l)!==v)throw new Error("Experiment result integrity failed.");return L(l,n),{manifest:n,result:s}}d(Q,"verifyExperimentEvidence");function $(t,n){for(let a of[t,n])Q(a);let s=[];if(t.manifest.teamId!==n.manifest.teamId&&s.push("different_workspace"),(t.manifest.dataset.id!==n.manifest.dataset.id||t.manifest.dataset.contentHash!==n.manifest.dataset.contentHash||t.manifest.dataset.revision!==n.manifest.dataset.revision)&&s.push("different_dataset_version"),t.manifest.target.kind!==n.manifest.target.kind&&s.push("different_target_kind"),h(t.manifest.execution??null)!==h(n.manifest.execution??null)&&s.push("different_execution_contract"),t.manifest.target.kind==="harness"&&n.manifest.target.kind==="harness"){let a=t.manifest.target.source,r=n.manifest.target.source;(a.profileId!==r.profileId||h(a.target)!==h(r.target))&&s.push("different_component"),a.environmentHash!==r.environmentHash&&s.push("different_environment"),(a.definitionId!==r.definitionId||a.definitionHash!==r.definitionHash)&&s.push("different_evaluation_definition")}let v=d(a=>[...a.evaluators].sort((r,o)=>r.feedbackKey.localeCompare(o.feedbackKey)),"orderedEvaluators");h(v(t.manifest))!==h(v(n.manifest))&&s.push("different_evaluators");let l=new Map(t.result.cases.map(a=>[K(a.identity),a])),w=new Map(n.result.cases.map(a=>[K(a.identity),a])),g=[...new Set([...l.keys(),...w.keys()])].sort();(l.size!==w.size||g.some(a=>!l.has(a)||!w.has(a)))&&s.push("different_population");let S=s.length===0,I=g.map(a=>{let r=l.get(a)??null,o=w.get(a)??null,T=new Map(r?.feedback.map(c=>[c.feedbackKey,c])??[]),_=new Map(o?.feedback.map(c=>[c.feedbackKey,c])??[]);return{identity:(r??o).identity,baseline:r,candidate:o,feedback:t.manifest.evaluators.map(c=>{let y=T.get(c.feedbackKey),x=_.get(c.feedbackKey),m=S?!r||!o?"missing_case":r.status!=="completed"||o.status!=="completed"||r.error||o.error?"case_not_completed":!y||!x||y.status!=="scored"||x.status!=="scored"?"feedback_unavailable":c.output==="category"?"categorical_feedback":null:"incompatible_experiments",u=d(k=>typeof k?.value=="boolean"?Number(k.value):typeof k?.value=="number"?k.value:null,"numeric"),p=m?null:u(y),E=m?null:u(x),P=d(k=>m?null:typeof k?.value=="boolean"?k.value:k?.passed??null,"pass");return{feedbackKey:c.feedbackKey,eligible:m===null,reason:m,baseline:p,candidate:E,delta:p===null||E===null?null:E-p,baselinePassed:P(y),candidatePassed:P(x)}})}}),i=t.manifest.evaluators.map((a,r)=>{let o=I.map(u=>u.feedback[r]).filter(u=>u.eligible),T=d(u=>o.length?o.reduce((p,E)=>p+E[u],0)/o.length:null,"mean"),_=T("baseline"),c=T("candidate"),y=d(u=>o.length&&o.every(p=>p[u]!==null)?o.reduce((p,E)=>p+Number(E[u]),0)/o.length:null,"passRate"),x=y("baselinePassed"),m=y("candidatePassed");return{feedbackKey:a.feedbackKey,eligibleCount:o.length,excludedCount:I.length-o.length,baseline:_,candidate:c,delta:_===null||c===null?null:c-_,baselinePassRate:x,candidatePassRate:m,passRateDelta:x===null||m===null?null:m-x}});return{comparable:S,reasons:s,cases:I,metrics:i}}d($,"compareExperiments");export{Q as a,$ as b};