@north-light/cli 0.3.703 → 0.3.705
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +7 -60
- package/dist/clients/attach/render/chat-view.js +2 -4
- package/dist/clients/attach/session/bindings.d.ts +1 -1
- package/dist/clients/attach/viewer.d.ts +1 -1
- package/dist/clients/attach/viewer.js +537 -539
- package/dist/commands/sys/setup-core.js +1 -1
- package/dist/core/canvas/schema-pg/024-conversation-cycle-offset.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/config.d.ts +4 -1
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +3 -3
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/conversation-store/row-store.js +13 -13
- package/dist/core/import/load/prepare.js +4 -4
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/keybindings/persistence.js +1 -1
- package/dist/core/runs/operations.js +6 -6
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/node-read.js +3 -3
- package/dist/core/runtime/session-cycles.d.ts +5 -22
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/user-settings.d.ts +0 -30
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/types.d.ts +0 -23
- package/dist/types.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/config.js +6 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +22 -261
- package/packages/crouter-api/dist/clients/attach/session/bindings.js +1 -1
- package/packages/crouter-api/dist/clients/attach/viewer.js +8 -7
- package/packages/crouter-api/dist/commands/sys/setup-core.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/config.js +10 -7
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/patch.js +8 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +46 -19
- package/packages/crouter-api/dist/core/import/load/prepare.js +1 -1
- package/packages/crouter-api/dist/core/keybindings/catalog.js +6 -6
- package/packages/crouter-api/dist/core/keybindings/persistence.js +2 -4
- package/packages/crouter-api/dist/core/runs/operations.js +2 -2
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +27 -75
- package/packages/crouter-api/dist/core/user-settings.js +1 -43
- package/packages/crouter-api/dist/types.js +0 -7
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/clients/attach/render/condensed-history.d.ts +0 -21
- package/dist/clients/attach/render/condensed-history.js +0 -1
- package/packages/crouter-api/dist/clients/attach/render/condensed-history.js +0 -60
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as x,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as P}from"../../core/runtime/package-health.js";import{basename as le,dirname as _,join as m,relative as ue,resolve as de}from"node:path";import{isDeepStrictEqual as w}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as he,inboxShortcut as me,resolveKeybindings as S}from"../../core/keybindings/index.js";import{runtimeManifest as ge}from"./shared.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as we}from"../../core/runtime/pi-cli.js";import{crtrVersion as xe}from"../../shared/crtr-version.js";import{installTmuxBindings as be}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as ye}from"../../core/config.js";import{detectNerdFont as Ie,nerdFontInstallCommand as Pe,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as Ae}from"../../core/runtime/progress-bar.js";import{ensureRenderer as $e,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Me}from"../../core/plugin-env.js";import{readPluginManifest as Ne}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Te}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",A="https://github.com/crouton-labs/crouter-official-marketplace.git",$="main";function It(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[l,c]=o.installSource.split("/");if(!l||!c)continue;const u=F(c,"user")?.manifest;let d=C(l,"user");if(!d&&!u&&l===E)try{let i=r.get(l);i||(i=oe(m(ae(),"crtr-setup-market-")),r.set(l,i),Te(A,m(i,"checkout"),{ref:$,depth:1}));const p=m(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const h=d?.manifest.plugins.find(i=>i.name===c)?.source,f=h&&De(h)?Ne(m(d.root,h))??u:u;if(f)for(const i of Me(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(It,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class Pt{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=ye(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!w(this.current,this.baseline)||!w(this.invalidRoot,this.baselineInvalidRoot)||!w(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:he(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const l=[...new Set(o)],c={...this.current};delete c[t];const u=[...S(c).gestures(t)],s=w(l,u)?c:{...this.current,[t]:l},d=S(s),h=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=n.length===0?void 0:[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"exa-search-plugin":{name:"exa-search",shortDescription:"crtr plugin mounting `crtr exa-search` \u2014 public-web discovery, grounded answers, and content extraction.",longDescription:"Installs the `exa-search` plugin from the official crtr marketplace. It mounts `crtr exa-search` and calls Exa directly with EXA_API_KEY, collected during install or set through `crtr sys env set --name EXA_API_KEY` in the app env store. Uncheck it on a machine whose agents get web search from somewhere else, such as a Northlight home where the platform serves `crtr search` from its own plugin."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:A},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"exa-search-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/exa-search"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"exa-search-plugin":[],"dev-plugin":[]};function U(e){return m(ge.runtimeHome(),"selected","dist","builtin-pi-packages",e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","exa-search-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function b(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(b,"normalizePackageIdentity");function y(e){return`package:${e}`}a(y,"packageNameIdentity");function Y(e){return e.startsWith("npm:")?[]:[y(le(e))]}a(Y,"localPackageNameIdentities");function Ge(e,t,n){const r=[b(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(y(e.name));for(const o of je[e.id])r.push(y(o))}return r}a(Ge,"manifestIdentities");function z(e,t=D(),n=m(P(),"settings.json"),r=x()){const o=_(n),l=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const u=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(u))return l;for(const s of u){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const h=[b(d,o,r),...Y(d)];for(const f of h){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(b(d,o,r)!==b(p.installSource,o,r)||!s||typeof s!="object"||!w(s.extensions,B))continue}i!==void 0&&l.add(i)}}return l}a(z,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Ie().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const l=Pe(t);return{tool:e,installed:!1,command:l.command,hint:`${l.hint} \u2014 ${Ee}`,autoInstall:l.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function M(e=x()){return m(e===x()?P():m(e,".pi","agent"),"settings.json")}a(M,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??x(),n=e.settingsPath??M(t),r=e.manifest??D(),o=ve(n),l=z(o,r,n,t);for(const d of V(r))l.add(d);const c=e.commandExists??k,u=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,u,c));return{manifest:r,installedPackageIds:l,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${me()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
1
|
+
var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as x,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as P}from"../../core/runtime/package-health.js";import{basename as le,dirname as _,join as m,relative as ue,resolve as de}from"node:path";import{isDeepStrictEqual as w}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as he,inboxShortcut as me,resolveKeybindings as S}from"../../core/keybindings/index.js";import{runtimeManifest as ge}from"./shared.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as we}from"../../core/runtime/pi-cli.js";import{crtrVersion as xe}from"../../shared/crtr-version.js";import{installTmuxBindings as be}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as ye}from"../../core/config.js";import{detectNerdFont as Ie,nerdFontInstallCommand as Pe,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as Ae}from"../../core/runtime/progress-bar.js";import{ensureRenderer as $e,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Me}from"../../core/plugin-env.js";import{readPluginManifest as Ne}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Te}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",A="https://github.com/crouton-labs/crouter-official-marketplace.git",$="main";function It(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[l,c]=o.installSource.split("/");if(!l||!c)continue;const u=F(c,"user")?.manifest;let d=C(l,"user");if(!d&&!u&&l===E)try{let i=r.get(l);i||(i=oe(m(ae(),"crtr-setup-market-")),r.set(l,i),Te(A,m(i,"checkout"),{ref:$,depth:1}));const p=m(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const h=d?.manifest.plugins.find(i=>i.name===c)?.source,f=h&&De(h)?Ne(m(d.root,h))??u:u;if(f)for(const i of Me(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(It,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class Pt{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=ye(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!w(this.current,this.baseline)||!w(this.invalidRoot,this.baselineInvalidRoot)||!w(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:he(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const l=[...new Set(o)],c={...this.current};delete c[t];const u=[...S(c).gestures(t)],s=w(l,u)?c:{...this.current,[t]:l},d=S(s),h=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"exa-search-plugin":{name:"exa-search",shortDescription:"crtr plugin mounting `crtr exa-search` \u2014 public-web discovery, grounded answers, and content extraction.",longDescription:"Installs the `exa-search` plugin from the official crtr marketplace. It mounts `crtr exa-search` and calls Exa directly with EXA_API_KEY, collected during install or set through `crtr sys env set --name EXA_API_KEY` in the app env store. Uncheck it on a machine whose agents get web search from somewhere else, such as a Northlight home where the platform serves `crtr search` from its own plugin."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:A},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"exa-search-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/exa-search"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"exa-search-plugin":[],"dev-plugin":[]};function U(e){return m(ge.runtimeHome(),"selected","dist","builtin-pi-packages",e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","exa-search-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function b(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(b,"normalizePackageIdentity");function y(e){return`package:${e}`}a(y,"packageNameIdentity");function Y(e){return e.startsWith("npm:")?[]:[y(le(e))]}a(Y,"localPackageNameIdentities");function Ge(e,t,n){const r=[b(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(y(e.name));for(const o of je[e.id])r.push(y(o))}return r}a(Ge,"manifestIdentities");function z(e,t=D(),n=m(P(),"settings.json"),r=x()){const o=_(n),l=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const u=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(u))return l;for(const s of u){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const h=[b(d,o,r),...Y(d)];for(const f of h){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(b(d,o,r)!==b(p.installSource,o,r)||!s||typeof s!="object"||!w(s.extensions,B))continue}i!==void 0&&l.add(i)}}return l}a(z,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Ie().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const l=Pe(t);return{tool:e,installed:!1,command:l.command,hint:`${l.hint} \u2014 ${Ee}`,autoInstall:l.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function M(e=x()){return m(e===x()?P():m(e,".pi","agent"),"settings.json")}a(M,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??x(),n=e.settingsPath??M(t),r=e.manifest??D(),o=ve(n),l=z(o,r,n,t);for(const d of V(r))l.add(d);const c=e.commandExists??k,u=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,u,c));return{manifest:r,installedPackageIds:l,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${me()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`}a(Et,"renderSetupStaticInstructions");class I extends Error{static{a(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function At(e){return`${e.stdout?.toString()??""}${e.stderr?.toString()??""}`}a(At,"commandOutput");function q(e,t,n,r=process.env){return new Promise((o,l)=>{const c=ie(e,t,{stdio:["ignore","pipe","pipe"],env:r});let u="";c.stdout.setEncoding("utf8"),c.stderr.setEncoding("utf8"),c.stdout.on("data",s=>{u+=s}),c.stderr.on("data",s=>{u+=s,n?.(s)}),c.on("error",s=>l(new I(`${e} failed: ${s.message}`,u))),c.on("close",s=>{s===0?o():l(new I(`${e} failed with status ${s??"unknown"}`,u))})})}a(q,"runCapturedCommand");function N(e,t){return q("sh",["-lc",e],t)}a(N,"runShellCommand");function Ye(e,t=we()){return q(process.execPath,[t,"install",e],void 0,{...process.env,PI_CODING_AGENT_DIR:P()})}a(Ye,"installPiPackage");async function W(){k("capture")||await N("npm install -g @crouton-kit/capture")}a(W,"installCaptureCliIfMissing");function H(e){return e instanceof I?e.output:void 0}a(H,"capturedFailureOutput");function ze(e){const n=H(e)?.split(/\r?\n/).find(r=>r.trim()!=="");return n!==void 0?n.trim():e instanceof Error?e.message:String(e)}a(ze,"firstFailureLine");function qe(e){const t=H(e);t===void 0||t.length===0||process.stderr.write(t.endsWith(`
|
|
4
4
|
`)?t:`${t}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
-- 024-conversation-cycle-offset.sql — `conversation_parts.cycle_offset`: the byte offset of the conversation's last `crtr-cycle` entry, on its
|
|
2
|
+
-- part 0 row, so a broker start reads only the current cycle. NULL until recorded (at the next cycle start, or by the first `from=cycle`
|
|
3
|
+
-- read's scan). An added column: `schema_min_reader` is not touched, so the previous release (version 23) still opens the result.
|
|
4
|
+
ALTER TABLE conversation_parts ADD COLUMN IF NOT EXISTS cycle_offset bigint;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 24;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=24;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
package/dist/core/config.d.ts
CHANGED
|
@@ -37,8 +37,11 @@ export declare function writeRawConfig(scope: Scope, config: Partial<ScopeConfig
|
|
|
37
37
|
export declare function writeState(scope: Scope, state: ScopeState): Promise<void>;
|
|
38
38
|
/** A project scope is a directory holding `config.json`; the user and profile scopes are the person's rows and need no directory setup. */
|
|
39
39
|
export declare function ensureScopeInitialized(scope: Scope, root: string): Promise<void>;
|
|
40
|
+
/** Attach scroll keys tmux wraps by default, so the Ctrl scroll keys keep each user's own tmux binding in every non-viewer pane. An explicit list, including an empty one, replaces this. */
|
|
41
|
+
export declare const DEFAULT_TMUX_PASSTHROUGH: readonly BindingId[];
|
|
40
42
|
/** Normalize the user-owned list of attach actions allowed to bridge through an
|
|
41
|
-
* occupied tmux root binding. Unknown and non-attach ids have no effect.
|
|
43
|
+
* occupied tmux root binding. Unknown and non-attach ids have no effect.
|
|
44
|
+
* `undefined` (no saved setting) yields the default list; any other non-array yields an empty list. */
|
|
42
45
|
export declare function normalizeTmuxPassthrough(raw: unknown): BindingId[];
|
|
43
46
|
type LegacyModelRouteConfig = Omit<ModelRouteConfig, 'models'> & {
|
|
44
47
|
models: Partial<Record<ModelStrength, string>>;
|
package/dist/core/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ye=Object.defineProperty;var s=(e,n)=>Ye(e,"name",{value:n,configurable:!0});import{envProfileId as Ze}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Xe,mkdirSync as Qe,statSync as en}from"node:fs";import{isDeepStrictEqual as nn}from"node:util";import{CONFIG_FILE as tn,STATE_FILE as on,CONDENSED_HISTORY_MODES as rn,VERBOSITY_LEVELS as sn,MOUSE_MODE_DEFAULTS as cn,WHIP_MESSAGE_MODES as un,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as dn,defaultKindsConfig as an,defaultRemoteCanvasConfig as fn}from"../types.js";import{BINDING_CATALOG as ln,BINDING_IDS as pn,isAttachPaneBinding as mn}from"./keybindings/catalog.js";import{notFound as gn}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as yn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as hn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as bn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as ae,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as vn,readCachedSettings as B,readCachedState as _n,revisionOf as I,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as pe,splitUserSettingsWrite as wn,withAppInstalls as me}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as kn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as An}from"./user-settings.js";import{normalizeWorkingGerunds as Sn}from"../shared/working-activity.js";import{mergePageComponentLayers as jn,normalizePageComponents as ge}from"./human/page-catalog.js";function h(e){return re(e,tn)}s(h,"configPathFor");function H(e,n){return kn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,on)}s(J,"statePathFor");function At(e){const n=g(e);return n?h(n):null}s(At,"configPath");function St(e){const n=g(e);return n?J(n):null}s(St,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(ae(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ue()))return O(h(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&pe()?me(vn(),o):o}s(P,"readRawAtRoot");async function ye(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&pe(),c=n(structuredClone((i?me(t,r??null):r)??{}));return o=c.value,i?wn(t,c.next,I(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:I(r)}]}),o}s(ye,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>q(t,n,{createParent:!1}));return}await ye(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const C=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function jt(e){C[T]=e}s(jt,"installBrokerConfigSnapshot");function xt(){return C[T]}s(xt,"brokerConfigSnapshot");function xn(e){const n=C[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?Rn(o):w()}s(xn,"readConfig");function Rn(e){const n=P(e);return n?z(n):w()}s(Rn,"readConfigAtRoot");function En(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(En,"readProjectState");function On(e){const n=g(e);return n?e==="project"?Xe(n)?En(n):se():_n(S(n).key):se()}s(On,"readState");class In extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function he(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw gn(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(he,"rawSettingsKeyForTarget");function Rt(e){return B(he(e))}s(Rt,"readRawSettingsForTarget");async function Et(e,n,o){const t=he(e);try{z(n)}catch(u){throw new In(u)}if(B(t).revision!==o)throw new le;const i=await W(u=>I(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=I(i.settings[t]);return{revision:c,changed:c!==o}}s(Et,"replaceRawSettingsForTarget");async function Ot(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Ot,"updateRawConfigAtomically");async function It(e,n){await V(k(e),n)}s(It,"writeConfig");async function Pt(e,n){await V(k(e),n)}s(Pt,"writeRawConfig");function Pn(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(Pn,"writeProjectState");async function Cn(e,n){const o=k(e);if(e==="project"){Pn(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(Cn,"writeState");async function Ct(e,n){if(e!=="project"){hn(n);return}try{Qe(n)}catch(o){if(o.code!=="EEXIST"||!en(n).isDirectory())throw o}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Ct,"ensureScopeInitialized");function Tn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(Tn,"normalizeKeybindings");const $n=new Set(ln.filter(mn).map(e=>e.id));function Mn(e){return Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&pn.has(n)&&$n.has(n)))]:[]}s(Mn,"normalizeTmuxPassthrough");function $(e,n=dn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,d]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof d=="string"&&(r[i][u]=d)}return r}s($,"mergeModelLadders");function be(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(be,"validStrength");const Y=["ultra","strong","medium","light"];function Z(){return Object.create(null)}s(Z,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function ve(e){const n=Z();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(ve,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function M(e,n={}){const o=ve(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let d;for(const f of["family","credentialSource","providerId"]){const a=i[f];if(a!==void 0){if(typeof a!="string"||a.trim()===""){d=`${f} must be a non-empty string`;break}u[f]=a}}if(d===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))d="models must be an object";else{const f={...c?.models};for(const[a,l]of Object.entries(i.models)){if(!be(a)){d=`models.${a} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){d=`models.${a} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){d=`models.${a} must be provider/id`;break}f[a]=l}u.models=f}if(d===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,a]of Object.entries(u.models))if(a.slice(0,a.indexOf("/"))!==u.providerId){d=`models.${f} provider prefix must equal providerId`;break}}if(d!==void 0){R(t,d);continue}x(o,t,u)}return o}s(M,"mergeModelRoutePatches");function _e(e){const n=Z(),o=Z();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Y.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(_e,"resolveModelRoutes");function Nn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Y.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Y){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s(Nn,"assertCompleteModelRoute");function N(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>be(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(N,"mergeModelRouting");function Ln(e){return e!==""&&e.replace(/\*/g,"")===""}s(Ln,"isInheritAllGlob");function L(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Ln(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(L,"mergeSpawnEnv");function F(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(F,"mergeProviderOptions");const we=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Fn=new Set(["crtr","crtrd"]);function D(e,n){if(n==="bin"&&Fn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!we.test(e))return`${n}.${e} is not a safe bare command name (expected ${we.source})`}s(D,"bareCommandNameIssue");function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=D(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Dn,"binDeclarationIssues");function Kn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))D(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Kn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function zn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(ke.test(o)||r.push(`action name must match ${ke.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(zn,"humanActionDeclarationIssues");function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(zn(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(Un,"normalizeHumanActions");function Tt(e){return Dn(e).map(n=>n.message)}s(Tt,"invalidPluginBinReasons");function $t(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))D(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s($t,"normalizeRequires");function Mt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=D(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Mt,"invalidPluginRequiresReasons");function Ae(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Ae,"normalizeKindFields");function b(e,n=an()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Ae(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(b,"mergeKinds");let K;function Nt(e){K=e}s(Nt,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&K!==void 0){let i=o;for(const c of Object.keys(K).sort((u,d)=>u.localeCompare(d)))i=b(K[c],i);return i}if(n===null)return o;const t=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=b(i.manifest.kinds,r);return r}s(Se,"layerPluginKinds");function Lt(){const e=[{origin:"config.json",components:xn("user").page_components}],n=g("user");if(n!==null){const o=de("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ge(t.manifest.page_components,r)})}}return jn(e)}s(Lt,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Ft(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Ae(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Ft,"invalidPluginKindsReasons");function Gn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(Gn,"normalizeRemoteCanvasTarget");function qn(e,n=fn()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=Gn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(qn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function E(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(E,"normalizePositiveInteger");function Bn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=E(o.warning,n.warning),r=E(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Bn,"mergeBrokerThresholds");function Wn(e,n){return{unattendedParkMs:E((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Wn,"mergeLifecycle");function Hn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...ie]}s(Hn,"normalizeWhipMessages");function Jn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Jn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(yn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,d={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,a=E(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=Bn(e.brokerThresholds,n.brokerThresholds),y=Wn(e.lifecycle,n.lifecycle),U=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:Sn(e.working_gerunds),Ee=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Oe=ge(e.page_components),Ie=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Pe=Hn(e.whip_messages),Ce=un.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Te=cn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=E(e.live_cycles,n.live_cycles),Me=rn.includes(e.condensed_history)?e.condensed_history:n.condensed_history,Ne=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Le=sn.includes(e.verbosity)?e.verbosity:n.verbosity,Fe=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,De=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Ke=Tn(e.keybindings),ze=Mn(e.tmux_passthrough),Ue=$(e.modelLadders),Ge=F(e.providerOptions,n.providerOptions),G=_e(M(e.modelRoutes)),Q=G.complete,ee=N(e.modelRouting,void 0),qe=b(e.kinds),Be=qn(e.remoteCanvas),We=Jn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const He=L(e.spawnEnv,n.spawnEnv?.allow),Je=Kn(e.bin),Ve=Un(e.humanActions);return{bin:Je,humanActions:Ve,schema_version:o,marketplaces:t,plugins:r,auto_update:d,max_panes_per_window:a,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:U,working_gerunds:m,whip_mode:Ee,page_components:Oe,page_surface:Ie,whip_messages:Pe,whip_message_mode:Ce,mouse_mode_default:Te,live_cycles:$e,condensed_history:Me,bash_tool_purpose:Ne,verbosity:Le,detailed_tool_recaps:Fe,document_port:De,keybindings:Ke,tmux_passthrough:ze,modelLadders:Ue,providerOptions:Ge,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:qe,remoteCanvas:Be,api:We,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:He}}s(z,"mergeConfig");function Vn(e){return P(e)}s(Vn,"readRawConfigAtRoot");function Yn(e){const n=g(e);return n?Vn(n):null}s(Yn,"readRawScopeConfig");function Zn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Zn,"readRawProfileConfig");function Xn(e,n){return[...bn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Xn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ze()||null){const o=C[T];if(o)return o.launch;const t=w(),r=Yn("user"),i=Zn(n),c=Xn(e,n);let u=b(r?.kinds,Se("user",g("user"),t.kinds)),d=$(r?.modelLadders,t.modelLadders),f=F(r?.providerOptions,t.providerOptions),a=M(r?.modelRoutes),l=N(r?.modelRouting,void 0),p=L(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),d=$(i.modelLadders,d),f=F(i.providerOptions,f),a=M(i.modelRoutes,a),l=N(i.modelRouting,l),p=L(i.spawnEnv,p.allow));for(const{root:U,raw:m}of c)u=b(m?.kinds,Se("project",U,u)),m!==null&&(d=$(m.modelLadders,d),f=F(m.providerOptions,f),a=M(m.modelRoutes,a),l=N(m.modelRouting,l),p=L(m.spawnEnv,p.allow));const y=_e(a);return{kinds:u,modelLadders:d,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Re,"readMergedLaunchConfig");function Dt(e){return Re().kinds[e]}s(Dt,"resolveKindConfig");function Kt(e){const n=Re().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Kt,"subKindsAvailableTo");function Qn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Qn,"sparseModelLaddersToPersist");async function et(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of An)u!=="modelLadders"&&!nn(r[u],t[u])&&(i[u]=r[u]);const c=Qn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(et,"mutateConfigAtRoot");async function zt(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(zt,"persistModelLadders");async function Ut(e,n,o){if(o!==void 0)Nn(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=ve(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Ut,"persistModelRoute");async function nt(e,n){return await et(e,n)}s(nt,"updateConfigAtRoot");async function Gt(e,n){return await nt(k(e),n)}s(Gt,"updateConfig");async function qt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:h(e.root),field:n}}s(qt,"persistDefaultKindModel");async function Bt(e,n){const o=On(e);return n(o),await Cn(e,o),o}s(Bt,"updateState");export{In as InvalidRawSettingsError,Dn as binDeclarationIssues,xt as brokerConfigSnapshot,At as configPath,Ct as ensureScopeInitialized,zn as humanActionDeclarationIssues,jt as installBrokerConfigSnapshot,Tt as invalidPluginBinReasons,Ft as invalidPluginKindsReasons,Mt as invalidPluginRequiresReasons,Kn as normalizeBin,Un as normalizeHumanActions,$t as normalizeRequires,Mn as normalizeTmuxPassthrough,qt as persistDefaultKindModel,zt as persistModelLadders,Ut as persistModelRoute,xn as readConfig,Rn as readConfigAtRoot,Re as readMergedLaunchConfig,Vn as readRawConfigAtRoot,Yn as readRawScopeConfig,Rt as readRawSettingsForTarget,On as readState,Et as replaceRawSettingsForTarget,Dt as resolveKindConfig,Lt as resolvePageComponents,Nt as setAppPluginKinds,St as statePath,Kt as subKindsAvailableTo,Gt as updateConfig,nt as updateConfigAtRoot,Ot as updateRawConfigAtomically,Bt as updateState,It as writeConfig,Pt as writeRawConfig,Cn as writeState};
|
|
1
|
+
var Je=Object.defineProperty;var s=(e,n)=>Je(e,"name",{value:n,configurable:!0});import{envProfileId as Ve}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Ze,mkdirSync as Ye,statSync as Xe}from"node:fs";import{isDeepStrictEqual as Qe}from"node:util";import{CONFIG_FILE as en,STATE_FILE as nn,VERBOSITY_LEVELS as tn,MOUSE_MODE_DEFAULTS as on,WHIP_MESSAGE_MODES as rn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as sn,defaultKindsConfig as cn,defaultRemoteCanvasConfig as un}from"../types.js";import{BINDING_CATALOG as an,BINDING_IDS as dn,isAttachPaneBinding as fn}from"./keybindings/catalog.js";import{notFound as ln}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as pn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as mn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as gn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as ae}from"./installed-plugins.js";import{profileDir as de,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as yn,readCachedSettings as B,readCachedState as hn,revisionOf as E,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as pe,splitUserSettingsWrite as bn,withAppInstalls as me}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as vn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as _n}from"./user-settings.js";import{normalizeWorkingGerunds as wn}from"../shared/working-activity.js";import{mergePageComponentLayers as kn,normalizePageComponents as ge}from"./human/page-catalog.js";function h(e){return re(e,en)}s(h,"configPathFor");function H(e,n){return vn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,nn)}s(J,"statePathFor");function wt(e){const n=g(e);return n?h(n):null}s(wt,"configPath");function kt(e){const n=g(e);return n?J(n):null}s(kt,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(de(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ue()))return O(h(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&pe()?me(yn(),o):o}s(P,"readRawAtRoot");async function ye(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&pe(),c=n(structuredClone((i?me(t,r??null):r)??{}));return o=c.value,i?bn(t,c.next,E(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:E(r)}]}),o}s(ye,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>q(t,n,{createParent:!1}));return}await ye(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function At(e){I[T]=e}s(At,"installBrokerConfigSnapshot");function St(){return I[T]}s(St,"brokerConfigSnapshot");function An(e){const n=I[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?Sn(o):w()}s(An,"readConfig");function Sn(e){const n=P(e);return n?z(n):w()}s(Sn,"readConfigAtRoot");function jn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(jn,"readProjectState");function xn(e){const n=g(e);return n?e==="project"?Ze(n)?jn(n):se():hn(S(n).key):se()}s(xn,"readState");class Rn extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function he(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw ln(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(he,"rawSettingsKeyForTarget");function jt(e){return B(he(e))}s(jt,"readRawSettingsForTarget");async function xt(e,n,o){const t=he(e);try{z(n)}catch(u){throw new Rn(u)}if(B(t).revision!==o)throw new le;const i=await W(u=>E(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=E(i.settings[t]);return{revision:c,changed:c!==o}}s(xt,"replaceRawSettingsForTarget");async function Rt(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Rt,"updateRawConfigAtomically");async function Ot(e,n){await V(k(e),n)}s(Ot,"writeConfig");async function Et(e,n){await V(k(e),n)}s(Et,"writeRawConfig");function On(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(On,"writeProjectState");async function En(e,n){const o=k(e);if(e==="project"){On(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(En,"writeState");async function Pt(e,n){if(e!=="project"){mn(n);return}try{Ye(n)}catch(o){if(o.code!=="EEXIST"||!Xe(n).isDirectory())throw o}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Pt,"ensureScopeInitialized");function Pn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(Pn,"normalizeKeybindings");const In=new Set(an.filter(fn).map(e=>e.id)),Tn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);function Cn(e){return e===void 0?[...Tn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&dn.has(n)&&In.has(n)))]:[]}s(Cn,"normalizeTmuxPassthrough");function C(e,n=sn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,a]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof a=="string"&&(r[i][u]=a)}return r}s(C,"mergeModelLadders");function be(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(be,"validStrength");const Z=["ultra","strong","medium","light"];function Y(){return Object.create(null)}s(Y,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function ve(e){const n=Y();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(ve,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const o=ve(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let a;for(const f of["family","credentialSource","providerId"]){const d=i[f];if(d!==void 0){if(typeof d!="string"||d.trim()===""){a=`${f} must be a non-empty string`;break}u[f]=d}}if(a===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))a="models must be an object";else{const f={...c?.models};for(const[d,l]of Object.entries(i.models)){if(!be(d)){a=`models.${d} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){a=`models.${d} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){a=`models.${d} must be provider/id`;break}f[d]=l}u.models=f}if(a===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,d]of Object.entries(u.models))if(d.slice(0,d.indexOf("/"))!==u.providerId){a=`models.${f} provider prefix must equal providerId`;break}}if(a!==void 0){R(t,a);continue}x(o,t,u)}return o}s($,"mergeModelRoutePatches");function _e(e){const n=Y(),o=Y();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Z.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(_e,"resolveModelRoutes");function $n(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Z.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Z){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s($n,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>be(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Mn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Mn,"isInheritAllGlob");function N(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Mn(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(N,"mergeSpawnEnv");function L(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(L,"mergeProviderOptions");const we=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Nn=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&Nn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!we.test(e))return`${n}.${e} is not a safe bare command name (expected ${we.source})`}s(F,"bareCommandNameIssue");function Ln(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Ln,"binDeclarationIssues");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Fn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(ke.test(o)||r.push(`action name must match ${ke.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(Dn,"humanActionDeclarationIssues");function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Dn(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(Un,"normalizeHumanActions");function It(e){return Ln(e).map(n=>n.message)}s(It,"invalidPluginBinReasons");function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))F(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s(Tt,"normalizeRequires");function Ct(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=F(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Ct,"invalidPluginRequiresReasons");function Ae(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Ae,"normalizeKindFields");function b(e,n=cn()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Ae(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(b,"mergeKinds");let D;function $t(e){D=e}s($t,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&D!==void 0){let i=o;for(const c of Object.keys(D).sort((u,a)=>u.localeCompare(a)))i=b(D[c],i);return i}if(n===null)return o;const t=ae(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=b(i.manifest.kinds,r);return r}s(Se,"layerPluginKinds");function Mt(){const e=[{origin:"config.json",components:An("user").page_components}],n=g("user");if(n!==null){const o=ae("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ge(t.manifest.page_components,r)})}}return kn(e)}s(Mt,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Ae(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Nt,"invalidPluginKindsReasons");function zn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(zn,"normalizeRemoteCanvasTarget");function Kn(e,n=un()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=zn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Kn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function U(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(U,"normalizePositiveInteger");function Gn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=U(o.warning,n.warning),r=U(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Gn,"mergeBrokerThresholds");function qn(e,n){return{unattendedParkMs:U((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(qn,"mergeLifecycle");function Bn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...ie]}s(Bn,"normalizeWhipMessages");function Wn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Wn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(pn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,a={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,d=U(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=Gn(e.brokerThresholds,n.brokerThresholds),y=qn(e.lifecycle,n.lifecycle),K=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:wn(e.working_gerunds),Oe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Ee=ge(e.page_components),Pe=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Ie=Bn(e.whip_messages),Te=rn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ce=on.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=tn.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Le=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Fe=Pn(e.keybindings),De=Cn(e.tmux_passthrough),Ue=C(e.modelLadders),ze=L(e.providerOptions,n.providerOptions),G=_e($(e.modelRoutes)),Q=G.complete,ee=M(e.modelRouting,void 0),Ke=b(e.kinds),Ge=Kn(e.remoteCanvas),qe=Wn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const Be=N(e.spawnEnv,n.spawnEnv?.allow),We=Fn(e.bin),He=Un(e.humanActions);return{bin:We,humanActions:He,schema_version:o,marketplaces:t,plugins:r,auto_update:a,max_panes_per_window:d,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:K,working_gerunds:m,whip_mode:Oe,page_components:Ee,page_surface:Pe,whip_messages:Ie,whip_message_mode:Te,mouse_mode_default:Ce,bash_tool_purpose:$e,verbosity:Me,detailed_tool_recaps:Ne,document_port:Le,keybindings:Fe,tmux_passthrough:De,modelLadders:Ue,providerOptions:ze,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ke,remoteCanvas:Ge,api:qe,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:Be}}s(z,"mergeConfig");function Hn(e){return P(e)}s(Hn,"readRawConfigAtRoot");function Jn(e){const n=g(e);return n?Hn(n):null}s(Jn,"readRawScopeConfig");function Vn(e){if(e===null||e==="")return null;try{return P(de(e))}catch{return null}}s(Vn,"readRawProfileConfig");function Zn(e,n){return[...gn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Zn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ve()||null){const o=I[T];if(o)return o.launch;const t=w(),r=Jn("user"),i=Vn(n),c=Zn(e,n);let u=b(r?.kinds,Se("user",g("user"),t.kinds)),a=C(r?.modelLadders,t.modelLadders),f=L(r?.providerOptions,t.providerOptions),d=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=N(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),a=C(i.modelLadders,a),f=L(i.providerOptions,f),d=$(i.modelRoutes,d),l=M(i.modelRouting,l),p=N(i.spawnEnv,p.allow));for(const{root:K,raw:m}of c)u=b(m?.kinds,Se("project",K,u)),m!==null&&(a=C(m.modelLadders,a),f=L(m.providerOptions,f),d=$(m.modelRoutes,d),l=M(m.modelRouting,l),p=N(m.spawnEnv,p.allow));const y=_e(d);return{kinds:u,modelLadders:a,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Re,"readMergedLaunchConfig");function Lt(e){return Re().kinds[e]}s(Lt,"resolveKindConfig");function Ft(e){const n=Re().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Ft,"subKindsAvailableTo");function Yn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Yn,"sparseModelLaddersToPersist");async function Xn(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of _n)u!=="modelLadders"&&!Qe(r[u],t[u])&&(i[u]=r[u]);const c=Yn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Xn,"mutateConfigAtRoot");async function Dt(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(Dt,"persistModelLadders");async function Ut(e,n,o){if(o!==void 0)$n(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=ve(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Ut,"persistModelRoute");async function Qn(e,n){return await Xn(e,n)}s(Qn,"updateConfigAtRoot");async function zt(e,n){return await Qn(k(e),n)}s(zt,"updateConfig");async function Kt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:h(e.root),field:n}}s(Kt,"persistDefaultKindModel");async function Gt(e,n){const o=xn(e);return n(o),await En(e,o),o}s(Gt,"updateState");export{Tn as DEFAULT_TMUX_PASSTHROUGH,Rn as InvalidRawSettingsError,Ln as binDeclarationIssues,St as brokerConfigSnapshot,wt as configPath,Pt as ensureScopeInitialized,Dn as humanActionDeclarationIssues,At as installBrokerConfigSnapshot,It as invalidPluginBinReasons,Nt as invalidPluginKindsReasons,Ct as invalidPluginRequiresReasons,Fn as normalizeBin,Un as normalizeHumanActions,Tt as normalizeRequires,Cn as normalizeTmuxPassthrough,Kt as persistDefaultKindModel,Dt as persistModelLadders,Ut as persistModelRoute,An as readConfig,Sn as readConfigAtRoot,Re as readMergedLaunchConfig,Hn as readRawConfigAtRoot,Jn as readRawScopeConfig,jt as readRawSettingsForTarget,xn as readState,xt as replaceRawSettingsForTarget,Lt as resolveKindConfig,Mt as resolvePageComponents,$t as setAppPluginKinds,kt as statePath,Ft as subKindsAvailableTo,zt as updateConfig,Qn as updateConfigAtRoot,Rt as updateRawConfigAtomically,Gt as updateState,Ot as writeConfig,Et as writeRawConfig,En as writeState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _=Object.defineProperty;var n=(
|
|
2
|
-
`).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead"),v=n((e,r)=>r?`${
|
|
1
|
+
var _=Object.defineProperty;var n=(l,m)=>_(l,"name",{value:m,configurable:!0});import{MessageChannel as g,Worker as y,receiveMessageOnPort as N}from"node:worker_threads";import{ConversationNotFoundError as q}from"./index.js";let $;function D(l){$=l}n(D,"setConversationRequestMark");function x(l,m){const c=new y(new URL(import.meta.url.endsWith(".ts")?"./client-worker.ts":"./client-worker.js",import.meta.url),{workerData:{address:l,token:m}});c.unref();const k=Date.now();let b=0,s;c.on("error",e=>{s=e}),c.on("exit",e=>{s=new Error(`conversation store worker exited with ${e}`)});function w(e,r,t){if(!t)throw new Error("conversation store worker returned no reply");if(t.error)throw new Error(t.error);if(t.status===404)throw new q(r.split("/")[2]??r);if(!t.status||t.status>=400)throw new Error(`conversation store ${e} ${r} failed (${t.status}): ${t.body}`);return{body:t.body??"",...t.path?{path:t.path}:{},...t.tail?{tail:Number(t.tail)}:{}}}n(w,"settle");function u(e,r,t){if(s)throw s;const o=new SharedArrayBuffer(4),{port1:a,port2:d}=new g,p=process.hrtime.bigint(),h=b++===0;try{c.postMessage({method:e,path:r,data:t,signal:o,reply:d},[d]);const f=Atomics.wait(new Int32Array(o),0,0,3e4);if($?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-p)/1e6,firstRequest:h,workerAgeMs:Date.now()-k}),f==="timed-out")throw a.postMessage("cancel"),new Error(`conversation store request timed out: ${e} ${r}`);return w(e,r,N(a)?.message)}finally{a.close()}}n(u,"call");function E(e,r,t){if(s)return Promise.reject(s);const{port1:o,port2:a}=new g,d=process.hrtime.bigint(),p=b++===0;return new Promise((h,f)=>{const M=setTimeout(()=>{o.postMessage("cancel"),o.close(),f(new Error(`conversation store request timed out: ${e} ${r}`))},3e4);M.unref(),o.once("message",P=>{clearTimeout(M),o.close(),$?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-d)/1e6,firstRequest:p,workerAgeMs:Date.now()-k});try{h(w(e,r,P))}catch(A){f(A)}}),c.postMessage({method:e,path:r,data:t,reply:a},[a])})}n(E,"callAsync");const i=n(e=>`/conversations/${encodeURIComponent(e)}`,"url");function T(e,r){if(s)throw s;c.postMessage({kind:"append",method:"POST",path:`${i(e)}/entries`,data:{entries:r}})}n(T,"enqueueAppend");function O(){if(s)return Promise.reject(s);const{port1:e,port2:r}=new g;return new Promise((t,o)=>{e.once("message",a=>{e.close();try{w("POST","/commit",a),t()}catch(d){o(d)}}),c.postMessage({kind:"flush",method:"POST",path:"/commit",reply:r},[r])})}n(O,"flush");const S=n(e=>{const[r,...t]=e.body.trimEnd().split(`
|
|
2
|
+
`).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead"),v=n((e,r)=>r==="cycle"?`${i(e)}?from=cycle`:r?`${i(e)}?head=${r.head}&tail=${r.tail}`:i(e),"readPath");return{create(e,r,t,o){return JSON.parse(u("POST","/conversations",{node_id:e,header:r,entries:t,path:o}).body)},async createAsync(e,r,t,o){return JSON.parse((await E("POST","/conversations",{node_id:e,header:r,entries:t,path:o})).body)},append(e,r){T(e,r)},flush:O,replace(e,r,t){u("PUT",i(e),{header:r,entries:t})},read(e,r){return S(u("GET",v(e,r)))},async readAsync(e,r){return S(await E("GET",v(e,r)))},header(e){return JSON.parse(u("GET",`${i(e)}/header`).body)},fork(e,r,t,o){return JSON.parse(u("POST",`${i(e)}/fork`,{node_id:r,leaf_id:t,cwd:o}).body).conversation_id},list(e){const r=e===void 0?"":`?node_id=${encodeURIComponent(e)}`;return JSON.parse(u("GET",`/conversations${r}`).body).conversations},delete(e){u("DELETE",i(e))}}}n(x,"createStoreClient");export{x as createStoreClient,D as setConversationRequestMark};
|
|
@@ -14,11 +14,11 @@ export interface ConversationInfo {
|
|
|
14
14
|
size: number;
|
|
15
15
|
path: string;
|
|
16
16
|
}
|
|
17
|
-
/** Byte budgets for a bounded read of a conversation's two ends. */
|
|
18
|
-
export
|
|
17
|
+
/** Byte budgets for a bounded read of a conversation's two ends, or `'cycle'`: the entries from the last `crtr-cycle` entry on. */
|
|
18
|
+
export type ConversationWindow = {
|
|
19
19
|
head: number;
|
|
20
20
|
tail: number;
|
|
21
|
-
}
|
|
21
|
+
} | 'cycle';
|
|
22
22
|
/** The synchronous shape pi's `SessionManager` statics need (`patch.ts`). The broker's client
|
|
23
23
|
* (`client.ts`: an `Atomics.wait` worker, no db) implements it. It is declared apart from
|
|
24
24
|
* `ConversationStore` so a change to the daemon's store never changes pi's contract. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var R=Object.defineProperty;var c=(d,i)=>R(d,"name",{value:i,configurable:!0});import{dirname as F,resolve as E}from"node:path";import{CURRENT_SESSION_VERSION as x,SessionManager as u}from"@earendil-works/pi-coding-agent";import{conversationClient as P,conversationIdFromPath as k}from"./index.js";import{findOrphanedParents as C}from"./repair.js";import{emitEvent as T}from"../events/emit.js";let B=!1;function G(d,i=P()){if(B)return;const l=u.prototype,a=u;for(const e of["_setSessionFile","_rewriteFile","_persist","createBranchedSession","newSession"])if(typeof l[e]!="function")throw new Error(`pi SessionManager.${e} changed; store patch cannot start`);for(const e of["create","open","continueRecent","forkFrom","findById","list","listAll"])if(typeof a[e]!="function")throw new Error(`pi SessionManager.${e} changed; store patch cannot start`);const M=l.createBranchedSession,y=l.newSession;function N(e,s){const t=C(s);t.length!==0&&T({level:"error",event:"conversation.orphaned_parent",fields:{conversation_id:e,orphan_count:t.length,orphans:t.slice(0,20).map(n=>({entry_id:n.entryId,missing_parent_id:n.missingParentId}))}})}c(N,"reportOrphans");function w(e,s){let{header:t,entries:n,path:r}=i.read(e,"cycle");t.version!==x&&({header:t,entries:n,path:r}=i.read(e)),N(t.id,n);const o=u.inMemory(s??t.cwd);o.sessionFile=r,o.sessionDir=F(r),o._loadEntries([t,...n]),o.persist=!0,o.flushed=!0;const f=o.fileEntries[0];return f?.type==="session"&&f.version!==t.version&&o._rewriteFile(),o}c(w,"fromStore");function A(e){const[s,...t]=e.fileEntries;if(!s||s.type!=="session")throw new Error("conversation has no session header");return{header:s,entries:t}}c(A,"newRecord");function D(e,s){e.sessionFile=s.path,e.sessionDir=F(e.sessionFile),e.flushed=!0}c(D,"adopt");function m(e){const{header:s,entries:t}=A(e);D(e,i.create(d,s,t))}c(m,"persistNew");function O(e,s){i.append(e.sessionId,[s])}c(O,"appendInOrder");function g(e){const s=k(e);if(!s)throw new Error(`invalid conversation path: ${e}`);return s}c(g,"idOf"),l._setSessionFile=function(e){let{header:s,entries:t}=i.read(g(e),"cycle");s.version!==x&&({header:s,entries:t}=i.read(s.id)),this.sessionFile=i.header(s.id).path,this.sessionDir=F(this.sessionFile),N(s.id,t),this._loadEntries([s,...t]),this.flushed=!0},l._rewriteFile=function(){if(!this.persist||!this.sessionFile)return;const[e,...s]=this.fileEntries;if(!e||e.type!=="session")throw new Error("conversation has no session header");i.replace(e.id,e,s)},l._persist=function(e){!this.persist||!this.sessionFile||(this.flushed?O(this,e):m(this))},l.newSession=function(e){if(!this.persist)return y.call(this,e);const s=this.flushed&&this.fileEntries.length===1&&this.sessionFile!==void 0?this.sessionId:void 0;if(s!==void 0&&(e?.id===void 0||e.id===s)){const t=this.sessionFile;y.call(this,{...e,id:s});const n=this.fileEntries[0];if(!n||n.type!=="session")throw new Error("conversation has no session header");return i.replace(s,n,[]),this.sessionFile=t,this.flushed=!0,t}return y.call(this,e),m(this),this.sessionFile},l.createBranchedSession=function(e){if(!this.persist)return M.call(this,e);const s=this.sessionFile;this.persist=!1;try{M.call(this,e)}finally{this.persist=!0}const t=this.fileEntries[0];if(!t||t.type!=="session")throw new Error("branch has no header");return this.fileEntries[0]={...t,parentSession:s},m(this),this.sessionFile},a.create=(e,s,t)=>{const n=u.inMemory(e,t);return n.persist=!0,m(n),n},a.createAsync=async(e,s)=>{const t=u.inMemory(e,s);t.persist=!0;const{header:n,entries:r}=A(t);return D(t,await i.createAsync(d,n,r)),t},a.open=(e,s,t)=>w(g(e),t),a.continueRecent=e=>{const s=i.list().find(t=>t.header.cwd===E(e));return s?w(s.conversation_id,e):a.create(e)},a.forkFrom=(e,s)=>w(i.fork(g(e),d,void 0,s)),a.findById=(e,s)=>i.list().find(t=>t.conversation_id===s&&t.header.cwd===E(e))?.path;function I(e){return i.list().filter(s=>e===void 0||s.header.cwd===E(e)).map(s=>{let t,n=0,r="",o;const f=[];for(const p of i.read(s.conversation_id).entries){if(p.type==="session_info"&&(t=p.name?.trim()||void 0),p.type!=="message")continue;n++;const h=p.message;if(h.role!=="user"&&h.role!=="assistant")continue;const b=typeof h.timestamp=="number"?h.timestamp:Date.parse(p.timestamp);Number.isNaN(b)||(o=Math.max(o??0,b));const S=typeof h.content=="string"?h.content:Array.isArray(h.content)?h.content.filter(v=>v.type==="text").map(v=>v.text??"").join(" "):"";S&&(f.push(S),!r&&h.role==="user"&&(r=S))}const _=new Date(s.header.timestamp);return{path:s.path,id:s.conversation_id,cwd:s.header.cwd,...t?{name:t}:{},...s.header.parentSession?{parentSessionPath:s.header.parentSession}:{},created:_,modified:o&&o>0?new Date(o):Number.isNaN(_.getTime())?new Date(s.mtime):_,messageCount:n,firstMessage:r||"(no messages)",allMessagesText:f.join(" ")}})}c(I,"sessionInfos"),a.list=async(e,s,t,n)=>{n?.throwIfAborted();const r=I(e);return t?.(r.length,r.length,r),r},a.listAll=async(...e)=>(e.find(t=>t instanceof AbortSignal)?.throwIfAborted(),I()),B=!0}c(G,"installSessionManagerStorePatch");export{G as installSessionManagerStorePatch};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).join(""),"encode")
|
|
3
|
-
`).filter(Boolean).map(
|
|
4
|
-
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(
|
|
5
|
-
`).subarray(c-
|
|
6
|
-
`)
|
|
7
|
-
`);i=
|
|
8
|
-
`))
|
|
9
|
-
`);d.pop();const p=Math.max(0,
|
|
10
|
-
`);return p>0&&
|
|
11
|
-
`)),tail:c(
|
|
12
|
-
`)),path:s}},async header(
|
|
13
|
-
`).join("");return await(await
|
|
1
|
+
var j=Object.defineProperty;var f=(i,e)=>j(i,"name",{value:e,configurable:!0});import{randomUUID as S}from"node:crypto";import{existsSync as J,readFileSync as x,rmSync as P}from"node:fs";import{join as Y}from"node:path";import{SessionManager as V}from"@earendil-works/pi-coding-agent";import{blobStore as E}from"../blobs/index.js";import{openDb as l,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as G}from"../layout.js";import{timedSpan as L}from"../logged-step-timings.js";import{addStepTiming as z}from"../step-timings.js";import{appendConversationEvents as D,rootRepromptPending as M}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as v}from"./index.js";const R="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",A=f((i,e,r)=>`conversations/${i}/${e}/${r}.jsonl`,"keyFor"),U=f(i=>i.map(e=>JSON.stringify(e)+`
|
|
2
|
+
`).join(""),"encode"),F=f(i=>i.split(`
|
|
3
|
+
`).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=f(()=>new Date().toISOString(),"at");async function m(i,e,r=!1){const a=await i.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1${r?" FOR UPDATE OF s":""}`).get(e);if(!a)throw new v(e);return a}f(m,"binding");async function b(i,e){return await i.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(e)}f(b,"parts");async function W(i,e){return await i.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(e)}f(W,"tail");async function H(i,e){const r=await i.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
|
|
4
|
+
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:r.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:s,entries:n,created:o})=>({seq:Number(a),blob_key:t,bytes:Number(s),entries:Number(n),created:o})),tail:r.filter(a=>a.kind==="tail").map(({seq:a,body:t,bytes:s,created:n})=>({seq:Number(a),body:t,bytes:Number(s),created:n}))}}f(H,"snapshot");const I=4*1024*1024,K=4,Q=16;async function*$(i,e,r){const a=[];let t=0;const s=f(()=>{for(;t<i&&a.length<r;){const n=e(t++);n.catch(()=>{}),a.push(n)}},"fill");for(s();a.length>0;){const n=await a.shift();s(),yield n}}f($,"readAhead");async function O(i,e,r){const a=[];let t=0;const s=await E(),n=[];for(const o of i.parts){const c=Math.max(e,t),d=Math.min(r,t+o.bytes);c<d&&n.push({key:o.blob_key,range:{start:c-t,length:d-c}}),t+=o.bytes}for await(const o of $(n.length,async c=>{const d=await s.get(n[c].key,n[c].range);if(!d)throw new Error(`missing conversation object: ${n[c].key}`);return d},Q))a.push(o);for(const o of i.tail){const c=Math.max(e,t),d=Math.min(r,t+o.bytes);c<d&&a.push(Buffer.from(o.body+`
|
|
5
|
+
`).subarray(c-t,d-t)),t+=o.bytes}return Buffer.concat(a)}f(O,"bytesOf");async function*q(i){const e=i.parts.reduce((a,t)=>a+t.bytes,0)+i.tail.reduce((a,t)=>a+t.bytes,0);let r="";for await(const a of $(Math.ceil(e/I),t=>O(i,t*I,Math.min(e,(t+1)*I)),K)){const t=r+a.toString("latin1"),s=t.lastIndexOf(`
|
|
6
|
+
`);r=t.slice(s+1);for(const n of t.slice(0,s+1).split(`
|
|
7
|
+
`))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}r&&(yield Buffer.from(r,"latin1").toString("utf8"))}f(q,"linesOf");const C=new Map;async function B(i,e,r){const a=await l();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(i)||!J(r))return;let t=x(r);const s=t.lastIndexOf(10);if(s<0)return;t=t.subarray(0,s+1);const n=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+R+" LIMIT 1").get(i);let o=[];if(n?.run_id&&n.event_offset!==null){const p=Number(n.event_offset);if(t.length<p)throw new Error(`conversation shorter than indexed offset: ${i}`);o=F(t.subarray(p).toString("utf8")).filter(w=>w.type!=="session")}const c=n?.run_id?await M(n.run_id,n.node_id,o):!1,d=A(e,i,0);await(await E()).put(d,t),await y(async p=>{if(!await p.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(i,d,t.length,Math.max(0,t.toString("utf8").split(`
|
|
8
|
+
`).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const _=n.source_session_id?[]:await D(p,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(t.length,o.at(-1)?.id??null,JSON.stringify(_),n.binding_id)})}f(B,"importOne");async function T(i,e){const r=await e.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1`).get(i),a=C.get(i);if(!r&&!a)throw new v(i);let t=(await b(e,i))[0];if(!t){const c=a?.path??r?.transcript_path??void 0;c&&await B(i,a?.node??r.node_id,c),t=(await b(e,i))[0]}if(!t||t.seq!==0)throw new v(i);const s=await(await E()).get(t.blob_key,{start:0,length:Math.min(t.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${t.blob_key}`);const n=s.indexOf(10);if(n<0)throw new Error(`invalid conversation header: ${i}`);const o=JSON.parse(s.subarray(0,n).toString("utf8"));if(o.type!=="session"||o.id!==i)throw new Error(`invalid conversation header: ${i}`);return{header:o,path:r?.transcript_path??a?.path??"",binding:r}}f(T,"initial");function _e(){const i={async create(e,r,a,t){const s=await l(),n=await L("owner_read",async()=>await s.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(e));if(!n)throw new Error(`missing conversation owner ${e}`);const o=r.id,c=Y(G(n.grantee).conversations,e,`${r.timestamp.replace(/[:.]/g,"-")}_${o}.jsonl`),d=U([r,...a]),p=A(e,o,0),w=n.run_id?await M(n.run_id,e,a):!1;return z("blob_bytes",Buffer.byteLength(d)),await L("blob_put",async()=>await(await E()).put(p,d)),await L("transaction",()=>y(async _=>{if(await _.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(o))throw new Error(`conversation already exists: ${o}`);const u=N(),g=r.parentSession?await _.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(r.parentSession):void 0;if(await _.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(S(),o,e,c,g?g.session_id:null,u,u,u),await _.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(o,p,Buffer.byteLength(d),a.length,u),n.run_id&&!g){const h=await D(_,n.run_id,e,a,[],w);await _.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(h),o,e)}},{timingName:"create_tx"})),{conversation_id:o,path:c}},async append(e,r){if(!r.length)return;const a=await m(await l(),e),t=a.run_id?await M(a.run_id,a.node_id,r):!1;await y(async s=>{const n=await m(s,e,!0);if(!(await b(s,e)).length)throw new v(e);const o=[];for(const c of r){const d=JSON.stringify(c);if(await s.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(e,c.id,d,Buffer.byteLength(d)+1,N())&&(o.push(c),c.type==="custom"&&c.customType==="crtr-cycle")){await s.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0 FOR UPDATE").get(e);const w=[...await b(s,e),...await W(s,e)].reduce((_,u)=>_+Number(u.bytes),0)-Buffer.byteLength(d)-1;await s.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0").run(w,e)}}if(n.run_id&&o.length){const c=await D(s,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json??"[]"),t);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(o.at(-1).id,JSON.stringify(c),n.binding_id)}})},async readLines(e){const r=await l(),{path:a}=await T(e,r);return{path:a,lines:q(await H(r,e))}},async read(e,r){const a=await l(),{header:t,path:s}=await T(e,a),n=await H(a,e),o=n.parts.reduce((_,u)=>_+u.bytes,0)+n.tail.reduce((_,u)=>_+u.bytes,0),c=f(_=>F(_).filter(u=>u.type!=="session"),"entriesOf");if(r==="cycle"){const _=await a.prepare("SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(e);let u=_?.cycle_offset==null?null:Number(_.cycle_offset);if(u===null){u=0;let g=0;for await(const h of q(n)){if(h.includes('"crtr-cycle"')){const k=JSON.parse(h);k.type==="custom"&&k.customType==="crtr-cycle"&&(u=g)}g+=Buffer.byteLength(h)+1}await y(async h=>{await h.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL").run(u,e)})}return{header:t,entries:c((await O(n,u,o)).toString("utf8")),path:s}}if(!r||o<=r.head+r.tail)return{header:t,entries:c((await O(n,0,o)).toString("utf8")),path:s};const d=(await O(n,0,Math.max(0,r.head))).toString("utf8").split(`
|
|
9
|
+
`);d.pop();const p=Math.max(0,o-r.tail),w=(await O(n,p>0?p-1:0,o)).toString("utf8").split(`
|
|
10
|
+
`);return p>0&&w.shift(),{header:t,entries:c(d.join(`
|
|
11
|
+
`)),tail:c(w.join(`
|
|
12
|
+
`)),path:s}},async header(e){const r=await l(),{header:a,path:t}=await T(e,r),s=await H(r,e);return{header:a,path:t,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((n,o)=>n+o.bytes,0)+s.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await l()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${R}`).all(),t=[];for(const s of a){if(e&&s.node_id!==e)continue;const n=await i.header(s.session_id);t.push({conversation_id:s.session_id,node_id:s.node_id,...n})}return t.sort((s,n)=>n.mtime-s.mtime)},async replace(e,r,a){if(r.id!==e)throw new Error("replacement header id differs from conversation id");const t=await l(),s=await m(t,e);if(s.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${s.node_id}/${e}/0-${S()}.jsonl`,o=U([r,...a]);await(await E()).put(n,o);const c=await y(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const w=await b(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),w});for(const d of c)await(await E()).delete(d.blob_key)},async fork(e,r,a,t){const s=await i.read(e);let n=s.entries;if(a!==void 0){const o=V.inMemory(s.header.cwd,void 0,[s.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(r??(await T(e,await l())).binding?.node_id??C.get(e).node,{...s.header,id:S(),timestamp:N(),cwd:t??s.header.cwd,parentSession:s.path},n)).conversation_id},async delete(e,r){const a=await l(),t=await b(a,e);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(e)});for(const s of t)await(await E()).delete(s.blob_key);r&&P(r,{force:!0})},async commit(e){return await y(async r=>{const a=await m(r,e,!0),t=await W(r,e),s=await b(r,e);if(!t.length)return s.at(-1)?.seq??0;const n=(s.at(-1)?.seq??0)+1,o=A(a.node_id,e,n),c=t.map(d=>d.body+`
|
|
13
|
+
`).join("");return await(await E()).put(o,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await r.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,o,Buffer.byteLength(c),t.length,N()),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await l()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${R}`).all(...e?[e]:[]);for(const t of a)await B(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const r of e)r.transcript_path&&C.set(r.session_id,{node:r.node_id,path:r.transcript_path})}};return i}f(_e,"createRowStore");function X(i,e,r){const a=i.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(i.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const s=r(t.cwd);return s===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:s})),i.subarray(a)])}f(X,"withHeaderCwd");async function fe(i,e,r){const a=await l(),t=await m(a,i),s=(await b(a,i))[0];if(!s||s.seq!==0)return!1;const n=await(await E()).get(s.blob_key);if(!n)throw new Error(`missing conversation object: ${s.blob_key}`);const o=X(n,i,p=>p===e?r:p);if(o===null)return!1;const c=`conversations/${t.node_id}/${i}/0-${S()}.jsonl`;await(await E()).put(c,o);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,o.length,o.length,i,s.blob_key)!==void 0);if(await(await E()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${i}`);return!0}f(fe,"relocateConversationHeader");export{_e as createRowStore,$ as readAhead,fe as relocateConversationHeader,X as withHeaderCwd};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
var A=Object.defineProperty;var p=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const f=p((n,s)=>`${l(n)}.${l(s)}`,"sq");async function B(n,s,c){if(c.length===0)return 0;const e=p(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=p(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${l(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${l(t)} = ? WHERE ${l(t)}::text = ? AND ${r}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}p(B,"rewritePaths");async function K(n,s,c,e,i){if(c.length===0)return 0;const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
|
|
2
|
-
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes =
|
|
2
|
+
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}p(K,"rewriteConversationHeaders");async function J(n,s){const c=f(s,"human_requests"),e=p(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
|
|
3
3
|
WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
|
|
4
4
|
WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
|
|
5
5
|
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.prepareUncached(`UPDATE ${c} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
|
|
6
6
|
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}p(J,"rewriteRequestPaths");function D(n,s){const c=p(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return S(s,n)}}p(D,"rewriteJsonPaths");async function Y(n,s,c,e,i){const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}p(Y,"renameClashingProfiles");async function X(n,s,c,e,i){const a=p(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}p(X,"fillEnvironments");async function z(n,s,c,e){const i=p(o=>f(s,o),"S"),a={},E=p(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${l(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}p(z,"pruneStaged");async function G(n,s,c){const e=p(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
|
|
7
7
|
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
|
|
8
8
|
COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
|
|
9
|
-
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}p(G,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function Q(n,s,c,e,i,a,E){const o=p(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(d=>u.identity.includes(d)),h=R.map(d=>`s.${l(d)} = t.${l(d)}`).join(" AND "),I=m?"TRUE":R.map(d=>`s.${l(d)} IS DISTINCT FROM t.${l(d)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const d of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=d.predicate===null?"":` WHERE ${d.predicate}`,T=d.columns.map($=>`s.${l($)} = t.${l($)}`).join(" AND "),
|
|
10
|
-
FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();
|
|
11
|
-
FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${d.columns.map($=>`a.${l($)} = b.${l($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();
|
|
9
|
+
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}p(G,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function Q(n,s,c,e,i,a,E){const o=p(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(d=>u.identity.includes(d)),h=R.map(d=>`s.${l(d)} = t.${l(d)}`).join(" AND "),I=m?"TRUE":R.map(d=>`s.${l(d)} IS DISTINCT FROM t.${l(d)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const d of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=d.predicate===null?"":` WHERE ${d.predicate}`,T=d.columns.map($=>`s.${l($)} = t.${l($)}`).join(" AND "),L=await n.prepareUncached(`SELECT ${d.columns.map($=>`s.${l($)}::text`).join(" || ',' || ")} AS value
|
|
10
|
+
FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:d.name,values:L.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${l($)} IS DISTINCT FROM b.${l($)}`).join(" OR "),O=await n.prepareUncached(`SELECT DISTINCT ${d.columns.map($=>`a.${l($)}::text`).join(" || ',' || ")} AS value
|
|
11
|
+
FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${d.columns.map($=>`a.${l($)} = b.${l($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:d.name,values:O.map($=>$.value),staged:!0})}const w=u.columns.filter(d=>!u.identity.includes(d)&&!o(r).includes(d)&&(W[r]?.includes(d)??!0));if(w.length>0&&!m){const d=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
|
|
12
12
|
FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${d} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}p(Q,"precheck");export{X as fillEnvironments,Q as precheck,z as pruneStaged,Y as renameClashingProfiles,K as rewriteConversationHeaders,B as rewritePaths,J as rewriteRequestPaths,G as takeRepoSyncedDocuments};
|