@north-light/cli 0.3.704 → 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.
Files changed (43) hide show
  1. package/dist/clients/attach/render/chat-view.d.ts +7 -60
  2. package/dist/clients/attach/render/chat-view.js +2 -4
  3. package/dist/clients/attach/viewer.js +537 -539
  4. package/dist/core/canvas/schema-pg/024-conversation-cycle-offset.sql +4 -0
  5. package/dist/core/canvas/schema-version.d.ts +1 -1
  6. package/dist/core/canvas/schema-version.js +1 -1
  7. package/dist/core/config.js +1 -1
  8. package/dist/core/conversation-store/client.js +2 -2
  9. package/dist/core/conversation-store/index.d.ts +3 -3
  10. package/dist/core/conversation-store/patch.js +1 -1
  11. package/dist/core/conversation-store/row-store.js +13 -13
  12. package/dist/core/import/load/prepare.js +4 -4
  13. package/dist/core/runs/operations.js +6 -6
  14. package/dist/core/runtime/broker/tool-groups.js +1 -1
  15. package/dist/core/runtime/broker.js +1 -1
  16. package/dist/core/runtime/node-read.js +3 -3
  17. package/dist/core/runtime/session-cycles.d.ts +5 -22
  18. package/dist/core/runtime/session-cycles.js +1 -1
  19. package/dist/core/user-settings.d.ts +0 -30
  20. package/dist/core/user-settings.js +1 -1
  21. package/dist/daemon/api/handlers/conversations.js +3 -3
  22. package/dist/types.d.ts +0 -23
  23. package/dist/types.js +1 -1
  24. package/package.json +3 -3
  25. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +22 -261
  26. package/packages/crouter-api/dist/clients/attach/viewer.js +6 -5
  27. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  28. package/packages/crouter-api/dist/core/config.js +2 -6
  29. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  30. package/packages/crouter-api/dist/core/conversation-store/patch.js +8 -3
  31. package/packages/crouter-api/dist/core/conversation-store/row-store.js +46 -19
  32. package/packages/crouter-api/dist/core/import/load/prepare.js +1 -1
  33. package/packages/crouter-api/dist/core/runs/operations.js +2 -2
  34. package/packages/crouter-api/dist/core/runtime/session-cycles.js +27 -75
  35. package/packages/crouter-api/dist/core/user-settings.js +1 -43
  36. package/packages/crouter-api/dist/types.js +0 -7
  37. package/packages/crouter-api/package.json +1 -1
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/packages/crouter-plugin/package.json +3 -3
  40. package/runtime.lock.json +14 -14
  41. package/dist/clients/attach/render/condensed-history.d.ts +0 -21
  42. package/dist/clients/attach/render/condensed-history.js +0 -1
  43. package/packages/crouter-api/dist/clients/attach/render/condensed-history.js +0 -60
@@ -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 = 23;
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=23;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};
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};
@@ -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 E,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 H}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 W(e,n){return kn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(W,"withConfigPathLock");function J(e){return re(e,on)}s(J,"statePathFor");function St(e){const n=g(e);return n?h(n):null}s(St,"configPath");function jt(e){const n=g(e);return n?J(n):null}s(jt,"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 E(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 H(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"){W(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"?W(h(o.root),t=>{const r=n(E(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const T=globalThis,C=Symbol.for("crtr.broker.config-snapshot");function xt(e){T[C]=e}s(xt,"installBrokerConfigSnapshot");function Rt(){return T[C]}s(Rt,"brokerConfigSnapshot");function xn(e){const n=T[C];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 On(e){const n=E(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(On,"readProjectState");function En(e){const n=g(e);return n?e==="project"?Xe(n)?On(n):se():_n(S(n).key):se()}s(En,"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 Ot(e){return B(he(e))}s(Ot,"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 H(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 It(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(It,"updateRawConfigAtomically");async function Pt(e,n){await V(k(e),n)}s(Pt,"writeConfig");async function Tt(e,n){await V(k(e),n)}s(Tt,"writeRawConfig");function Pn(e,n){W(J(e),o=>q(o,n,{createParent:!1}))}s(Pn,"writeProjectState");async function Tn(e,n){const o=k(e);if(e==="project"){Pn(o,n);return}const t=S(o).key;await H(()=>[{op:"state.write",owner:t,state:n}])}s(Tn,"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}E(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Ct,"ensureScopeInitialized");function Cn(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(Cn,"normalizeKeybindings");const $n=new Set(ln.filter(mn).map(e=>e.id)),Mn=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 Nn(e){return e===void 0?[...Mn]:Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&pn.has(n)&&$n.has(n)))]:[]}s(Nn,"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 Ln(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(Ln,"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 Fn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Fn,"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(Fn(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}$/,Dn=new Set(["crtr","crtrd"]);function D(e,n){if(n==="bin"&&Dn.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 Un(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(Un,"binDeclarationIssues");function zn(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(zn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Kn(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(Kn,"humanActionDeclarationIssues");function Gn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Kn(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(Gn,"normalizeHumanActions");function $t(e){return Un(e).map(n=>n.message)}s($t,"invalidPluginBinReasons");function Mt(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(Mt,"normalizeRequires");function Nt(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(Nt,"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 U;function Lt(e){U=e}s(Lt,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&U!==void 0){let i=o;for(const c of Object.keys(U).sort((u,d)=>u.localeCompare(d)))i=b(U[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 Ft(){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(Ft,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Dt(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(Dt,"invalidPluginKindsReasons");function qn(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(qn,"normalizeRemoteCanvasTarget");function Bn(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=qn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(Bn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function O(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(O,"normalizePositiveInteger");function Hn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=O(o.warning,n.warning),r=O(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Hn,"mergeBrokerThresholds");function Wn(e,n){return{unattendedParkMs:O((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Wn,"mergeLifecycle");function Jn(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(Jn,"normalizeWhipMessages");function Vn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Vn,"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=O(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=Hn(e.brokerThresholds,n.brokerThresholds),y=Wn(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]:Sn(e.working_gerunds),Oe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Ee=ge(e.page_components),Ie=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Pe=Jn(e.whip_messages),Te=un.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ce=cn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=O(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,Ue=Cn(e.keybindings),ze=Nn(e.tmux_passthrough),Ke=$(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=Bn(e.remoteCanvas),He=Vn(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 We=L(e.spawnEnv,n.spawnEnv?.allow),Je=zn(e.bin),Ve=Gn(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:K,working_gerunds:m,whip_mode:Oe,page_components:Ee,page_surface:Ie,whip_messages:Pe,whip_message_mode:Te,mouse_mode_default:Ce,live_cycles:$e,condensed_history:Me,bash_tool_purpose:Ne,verbosity:Le,detailed_tool_recaps:Fe,document_port:De,keybindings:Ue,tmux_passthrough:ze,modelLadders:Ke,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:He,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:We}}s(z,"mergeConfig");function Yn(e){return P(e)}s(Yn,"readRawConfigAtRoot");function Zn(e){const n=g(e);return n?Yn(n):null}s(Zn,"readRawScopeConfig");function Xn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Xn,"readRawProfileConfig");function Qn(e,n){return[...bn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Qn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ze()||null){const o=T[C];if(o)return o.launch;const t=w(),r=Zn("user"),i=Xn(n),c=Qn(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:K,raw:m}of c)u=b(m?.kinds,Se("project",K,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 Ut(e){return Re().kinds[e]}s(Ut,"resolveKindConfig");function zt(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(zt,"subKindsAvailableTo");function et(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(et,"sparseModelLaddersToPersist");async function nt(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=et(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(nt,"mutateConfigAtRoot");async function Kt(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(Kt,"persistModelLadders");async function Gt(e,n,o){if(o!==void 0)Ln(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(Gt,"persistModelRoute");async function tt(e,n){return await nt(e,n)}s(tt,"updateConfigAtRoot");async function qt(e,n){return await tt(k(e),n)}s(qt,"updateConfig");async function Bt(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(Bt,"persistDefaultKindModel");async function Ht(e,n){const o=En(e);return n(o),await Tn(e,o),o}s(Ht,"updateState");export{Mn as DEFAULT_TMUX_PASSTHROUGH,In as InvalidRawSettingsError,Un as binDeclarationIssues,Rt as brokerConfigSnapshot,St as configPath,Ct as ensureScopeInitialized,Kn as humanActionDeclarationIssues,xt as installBrokerConfigSnapshot,$t as invalidPluginBinReasons,Dt as invalidPluginKindsReasons,Nt as invalidPluginRequiresReasons,zn as normalizeBin,Gn as normalizeHumanActions,Mt as normalizeRequires,Nn as normalizeTmuxPassthrough,Bt as persistDefaultKindModel,Kt as persistModelLadders,Gt as persistModelRoute,xn as readConfig,Rn as readConfigAtRoot,Re as readMergedLaunchConfig,Yn as readRawConfigAtRoot,Zn as readRawScopeConfig,Ot as readRawSettingsForTarget,En as readState,Et as replaceRawSettingsForTarget,Ut as resolveKindConfig,Ft as resolvePageComponents,Lt as setAppPluginKinds,jt as statePath,zt as subKindsAvailableTo,qt as updateConfig,tt as updateConfigAtRoot,It as updateRawConfigAtomically,Ht as updateState,Pt as writeConfig,Tt as writeRawConfig,Tn 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=(f,w)=>_(f,"name",{value:w,configurable:!0});import{MessageChannel as g,Worker as N,receiveMessageOnPort as q}from"node:worker_threads";import{ConversationNotFoundError as y}from"./index.js";let $;function D(f){$=f}n(D,"setConversationRequestMark");function x(f,w){const i=new N(new URL(import.meta.url.endsWith(".ts")?"./client-worker.ts":"./client-worker.js",import.meta.url),{workerData:{address:f,token:w}});i.unref();const k=Date.now();let b=0,s;i.on("error",e=>{s=e}),i.on("exit",e=>{s=new Error(`conversation store worker exited with ${e}`)});function m(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 y(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(m,"settle");function c(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{i.postMessage({method:e,path:r,data:t,signal:o,reply:d},[d]);const l=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}),l==="timed-out")throw a.postMessage("cancel"),new Error(`conversation store request timed out: ${e} ${r}`);return m(e,r,q(a)?.message)}finally{a.close()}}n(c,"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,l)=>{const M=setTimeout(()=>{o.postMessage("cancel"),o.close(),l(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(m(e,r,P))}catch(A){l(A)}}),i.postMessage({method:e,path:r,data:t,reply:a},[a])})}n(E,"callAsync");const u=n(e=>`/conversations/${encodeURIComponent(e)}`,"url");function T(e,r){if(s)throw s;i.postMessage({kind:"append",method:"POST",path:`${u(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{m("POST","/commit",a),t()}catch(d){o(d)}}),i.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?`${u(e)}?head=${r.head}&tail=${r.tail}`:u(e),"readPath");return{create(e,r,t,o){return JSON.parse(c("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){c("PUT",u(e),{header:r,entries:t})},read(e,r){return S(c("GET",v(e,r)))},async readAsync(e,r){return S(await E("GET",v(e,r)))},header(e){return JSON.parse(c("GET",`${u(e)}/header`).body)},fork(e,r,t,o){return JSON.parse(c("POST",`${u(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(c("GET",`/conversations${r}`).body).conversations},delete(e){c("DELETE",u(e))}}}n(x,"createStoreClient");export{x as createStoreClient,D as setConversationRequestMark};
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 interface ConversationWindow {
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 P=Object.defineProperty;var c=(l,i)=>P(l,"name",{value:i,configurable:!0});import{dirname as S,resolve as E}from"node:path";import{SessionManager as u}from"@earendil-works/pi-coding-agent";import{conversationClient as O,conversationIdFromPath as k}from"./index.js";import{findOrphanedParents as R}from"./repair.js";import{emitEvent as $}from"../events/emit.js";let x=!1;function H(l,i=O()){if(x)return;const d=u.prototype,a=u;for(const e of["_setSessionFile","_rewriteFile","_persist","createBranchedSession","newSession"])if(typeof d[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=d.createBranchedSession,y=d.newSession;function A(e,s){const t=R(s);t.length!==0&&$({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(A,"reportOrphans");function w(e,s){const{header:t,entries:n,path:o}=i.read(e);A(t.id,n);const r=u.inMemory(s??t.cwd);r.sessionFile=o,r.sessionDir=S(o),r._loadEntries([t,...n]),r.persist=!0,r.flushed=!0;const f=r.fileEntries[0];return f?.type==="session"&&f.version!==t.version&&r._rewriteFile(),r}c(w,"fromStore");function D(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(D,"newRecord");function I(e,s){e.sessionFile=s.path,e.sessionDir=S(e.sessionFile),e.flushed=!0}c(I,"adopt");function m(e){const{header:s,entries:t}=D(e);I(e,i.create(l,s,t))}c(m,"persistNew");function B(e,s){i.append(e.sessionId,[s])}c(B,"appendInOrder");function g(e){const s=k(e);if(!s)throw new Error(`invalid conversation path: ${e}`);return s}c(g,"idOf"),d._setSessionFile=function(e){const{header:s,entries:t}=i.read(g(e));this.sessionFile=i.header(s.id).path,this.sessionDir=S(this.sessionFile),A(s.id,t),this._loadEntries([s,...t]),this.flushed=!0},d._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)},d._persist=function(e){!this.persist||!this.sessionFile||(this.flushed?B(this,e):m(this))},d.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},d.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:o}=D(t);return I(t,await i.createAsync(l,n,o)),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),l,void 0,s)),a.findById=(e,s)=>i.list().find(t=>t.conversation_id===s&&t.header.cwd===E(e))?.path;function N(e){return i.list().filter(s=>e===void 0||s.header.cwd===E(e)).map(s=>{let t,n=0,o="",r;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)||(r=Math.max(r??0,b));const F=typeof h.content=="string"?h.content:Array.isArray(h.content)?h.content.filter(v=>v.type==="text").map(v=>v.text??"").join(" "):"";F&&(f.push(F),!o&&h.role==="user"&&(o=F))}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:r&&r>0?new Date(r):Number.isNaN(_.getTime())?new Date(s.mtime):_,messageCount:n,firstMessage:o||"(no messages)",allMessagesText:f.join(" ")}})}c(N,"sessionInfos"),a.list=async(e,s,t,n)=>{n?.throwIfAborted();const o=N(e);return t?.(o.length,o.length,o),o},a.listAll=async(...e)=>(e.find(t=>t instanceof AbortSignal)?.throwIfAborted(),N()),x=!0}c(H,"installSessionManagerStorePatch");export{H as installSessionManagerStorePatch};
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 W=Object.defineProperty;var _=(o,t)=>W(o,"name",{value:t,configurable:!0});import{randomUUID as m}from"node:crypto";import{existsSync as q,readFileSync as B,rmSync as j}from"node:fs";import{join as J}from"node:path";import{SessionManager as x}from"@earendil-works/pi-coding-agent";import{blobStore as l}from"../blobs/index.js";import{openDb as w,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as Y}from"../layout.js";import{timedSpan as T}from"../logged-step-timings.js";import{addStepTiming as V}from"../step-timings.js";import{appendConversationEvents as L,rootRepromptPending as D}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as O}from"./index.js";const N="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",M=_((o,t,a)=>`conversations/${o}/${t}/${a}.jsonl`,"keyFor"),H=_(o=>o.map(t=>JSON.stringify(t)+`
2
- `).join(""),"encode"),$=_(o=>o.split(`
3
- `).filter(Boolean).map(t=>JSON.parse(t)),"decode"),h=_(()=>new Date().toISOString(),"at");async function g(o,t,a=!1){const r=await o.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 ${N} LIMIT 1${a?" FOR UPDATE OF s":""}`).get(t);if(!r)throw new O(t);return r}_(g,"binding");async function b(o,t){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(t)}_(b,"parts");async function P(o,t){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(t)}_(P,"tail");async function I(o,t){const a=await o.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(t,t);return{parts:a.filter(r=>r.kind==="part").map(({seq:r,blob_key:n,bytes:s,entries:e,created:i})=>({seq:Number(r),blob_key:n,bytes:Number(s),entries:Number(e),created:i})),tail:a.filter(r=>r.kind==="tail").map(({seq:r,body:n,bytes:s,created:e})=>({seq:Number(r),body:n,bytes:Number(s),created:e}))}}_(I,"snapshot");const k=4*1024*1024,G=4,z=16;async function*A(o,t,a){const r=[];let n=0;const s=_(()=>{for(;n<o&&r.length<a;){const e=t(n++);e.catch(()=>{}),r.push(e)}},"fill");for(s();r.length>0;){const e=await r.shift();s(),yield e}}_(A,"readAhead");async function R(o,t,a){const r=[];let n=0;const s=await l(),e=[];for(const i of o.parts){const c=Math.max(t,n),d=Math.min(a,n+i.bytes);c<d&&e.push({key:i.blob_key,range:{start:c-n,length:d-c}}),n+=i.bytes}for await(const i of A(e.length,async c=>{const d=await s.get(e[c].key,e[c].range);if(!d)throw new Error(`missing conversation object: ${e[c].key}`);return d},z))r.push(i);for(const i of o.tail){const c=Math.max(t,n),d=Math.min(a,n+i.bytes);c<d&&r.push(Buffer.from(i.body+`
5
- `).subarray(c-n,d-n)),n+=i.bytes}return Buffer.concat(r)}_(R,"bytesOf");const C=new Map;async function F(o,t,a){const r=await w();if(await r.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!q(a))return;let n=B(a);const s=n.lastIndexOf(10);if(s<0)return;n=n.subarray(0,s+1);const e=await r.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 "+N+" LIMIT 1").get(o);let i=[];if(e?.run_id&&e.event_offset!==null){const p=Number(e.event_offset);if(n.length<p)throw new Error(`conversation shorter than indexed offset: ${o}`);i=$(n.subarray(p).toString("utf8")).filter(u=>u.type!=="session")}const c=e?.run_id?await D(e.run_id,e.node_id,i):!1,d=M(t,o,0);await(await l()).put(d,n),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(o,d,n.length,Math.max(0,n.toString("utf8").split(`
6
- `).filter(Boolean).length-1),h())||!e?.run_id||e.event_offset===null)return;const f=e.source_session_id?[]:await L(p,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(n.length,i.at(-1)?.id??null,JSON.stringify(f),e.binding_id)})}_(F,"importOne");async function S(o,t){const a=await t.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 ${N} LIMIT 1`).get(o),r=C.get(o);if(!a&&!r)throw new O(o);let n=(await b(t,o))[0];if(!n){const c=r?.path??a?.transcript_path??void 0;c&&await F(o,r?.node??a.node_id,c),n=(await b(t,o))[0]}if(!n||n.seq!==0)throw new O(o);const s=await(await l()).get(n.blob_key,{start:0,length:Math.min(n.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${n.blob_key}`);const e=s.indexOf(10);if(e<0)throw new Error(`invalid conversation header: ${o}`);const i=JSON.parse(s.subarray(0,e).toString("utf8"));if(i.type!=="session"||i.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:i,path:a?.transcript_path??r?.path??"",binding:a}}_(S,"initial");function dt(){const o={async create(t,a,r,n){const s=await w(),e=await T("owner_read",async()=>await s.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(t));if(!e)throw new Error(`missing conversation owner ${t}`);const i=a.id,c=J(Y(e.grantee).conversations,t,`${a.timestamp.replace(/[:.]/g,"-")}_${i}.jsonl`),d=H([a,...r]),p=M(t,i,0),u=e.run_id?await D(e.run_id,t,r):!1;return V("blob_bytes",Buffer.byteLength(d)),await T("blob_put",async()=>await(await l()).put(p,d)),await T("transaction",()=>y(async f=>{if(await f.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(i))throw new Error(`conversation already exists: ${i}`);const E=h(),v=a.parentSession?await f.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(a.parentSession):void 0;if(await f.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(m(),i,t,c,v?v.session_id:null,E,E,E),await f.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(i,p,Buffer.byteLength(d),r.length,E),e.run_id&&!v){const U=await L(f,e.run_id,t,r,[],u);await f.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(r.at(-1)?.id??null,JSON.stringify(U),i,t)}},{timingName:"create_tx"})),{conversation_id:i,path:c}},async append(t,a){if(!a.length)return;const r=await g(await w(),t),n=r.run_id?await D(r.run_id,r.node_id,a):!1;await y(async s=>{const e=await g(s,t,!0);if(!(await b(s,t)).length)throw new O(t);const i=[];for(const c of a){const d=JSON.stringify(c);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(t,c.id,d,Buffer.byteLength(d)+1,h())&&i.push(c)}if(e.run_id&&i.length){const c=await L(s,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json??"[]"),n);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(i.at(-1).id,JSON.stringify(c),e.binding_id)}})},async readLines(t){const a=await w(),{path:r}=await S(t,a),n=await I(a,t),s=n.parts.reduce((i,c)=>i+c.bytes,0)+n.tail.reduce((i,c)=>i+c.bytes,0);async function*e(){let i="";for await(const c of A(Math.ceil(s/k),d=>R(n,d*k,Math.min(s,(d+1)*k)),G)){const d=i+c.toString("latin1"),p=d.lastIndexOf(`
7
- `);i=d.slice(p+1);for(const u of d.slice(0,p+1).split(`
8
- `))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}i&&(yield Buffer.from(i,"latin1").toString("utf8"))}return _(e,"lines"),{path:r,lines:e()}},async read(t,a){const r=await w(),{header:n,path:s}=await S(t,r),e=await I(r,t),i=e.parts.reduce((f,E)=>f+E.bytes,0)+e.tail.reduce((f,E)=>f+E.bytes,0),c=_(f=>$(f).filter(E=>E.type!=="session"),"entriesOf");if(!a||i<=a.head+a.tail)return{header:n,entries:c((await R(e,0,i)).toString("utf8")),path:s};const d=(await R(e,0,Math.max(0,a.head))).toString("utf8").split(`
9
- `);d.pop();const p=Math.max(0,i-a.tail),u=(await R(e,p>0?p-1:0,i)).toString("utf8").split(`
10
- `);return p>0&&u.shift(),{header:n,entries:c(d.join(`
11
- `)),tail:c(u.join(`
12
- `)),path:s}},async header(t){const a=await w(),{header:r,path:n}=await S(t,a),s=await I(a,t);return{header:r,path:n,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((e,i)=>e+i.bytes,0)+s.tail.reduce((e,i)=>e+i.bytes,0)}},async list(t){const r=await(await w()).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, ${N}`).all(),n=[];for(const s of r){if(t&&s.node_id!==t)continue;const e=await o.header(s.session_id);n.push({conversation_id:s.session_id,node_id:s.node_id,...e})}return n.sort((s,e)=>e.mtime-s.mtime)},async replace(t,a,r){if(a.id!==t)throw new Error("replacement header id differs from conversation id");const n=await w(),s=await g(n,t);if(s.run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const e=`conversations/${s.node_id}/${t}/0-${m()}.jsonl`,i=H([a,...r]);await(await l()).put(e,i);const c=await y(async d=>{if((await g(d,t,!0)).run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const u=await b(d,t);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(t,e,Buffer.byteLength(i),r.length,h()),u});for(const d of c)await(await l()).delete(d.blob_key)},async fork(t,a,r,n){const s=await o.read(t);let e=s.entries;if(r!==void 0){const i=x.inMemory(s.header.cwd,void 0,[s.header,...e]);i.createBranchedSession(r),e=i.getEntries()}return(await o.create(a??(await S(t,await w())).binding?.node_id??C.get(t).node,{...s.header,id:m(),timestamp:h(),cwd:n??s.header.cwd,parentSession:s.path},e)).conversation_id},async delete(t,a){const r=await w(),n=await b(r,t);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(t)});for(const s of n)await(await l()).delete(s.blob_key);a&&j(a,{force:!0})},async commit(t){return await y(async a=>{const r=await g(a,t,!0),n=await P(a,t),s=await b(a,t);if(!n.length)return s.at(-1)?.seq??0;const e=(s.at(-1)?.seq??0)+1,i=M(r.node_id,t,e),c=n.map(d=>d.body+`
13
- `).join("");return await(await l()).put(i,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await a.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(t,e,i,Buffer.byteLength(c),n.length,h()),await a.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(t,n.at(-1).seq),e})},async importLegacy(t){const r=await(await w()).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 ${t?"AND n.run_id = ?":""} ORDER BY s.session_id, ${N}`).all(...t?[t]:[]);for(const n of r)await F(n.session_id,n.node_id,n.transcript_path)},recover(t){for(const a of t)a.transcript_path&&C.set(a.session_id,{node:a.node_id,path:a.transcript_path})}};return o}_(dt,"createRowStore");function K(o,t,a){const r=o.indexOf(10);if(r<0)throw new Error(`invalid conversation header: ${t}`);const n=JSON.parse(o.subarray(0,r).toString("utf8"));if(n.type!=="session"||n.id!==t)throw new Error(`invalid conversation header: ${t}`);const s=a(n.cwd);return s===n.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...n,cwd:s})),o.subarray(r)])}_(K,"withHeaderCwd");async function pt(o,t,a){const r=await w(),n=await g(r,o),s=(await b(r,o))[0];if(!s||s.seq!==0)return!1;const e=await(await l()).get(s.blob_key);if(!e)throw new Error(`missing conversation object: ${s.blob_key}`);const i=K(e,o,p=>p===t?a:p);if(i===null)return!1;const c=`conversations/${n.node_id}/${o}/0-${m()}.jsonl`;await(await l()).put(c,i);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ? WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,i.length,o,s.blob_key)!==void 0);if(await(await l()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(pt,"relocateConversationHeader");export{dt as createRowStore,A as readAhead,pt as relocateConversationHeader,K as withHeaderCwd};
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 = ? 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}
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 "),O=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();O.length>0&&t.push({table:r,key:d.name,values:O.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${l($)} IS DISTINCT FROM b.${l($)}`).join(" OR "),L=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();L.length>0&&t.push({table:r,key:d.name,values:L.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
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};
@@ -1,16 +1,16 @@
1
- var Ae=Object.defineProperty;var c=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as Z}from"node:crypto";import{ApiError as Te}from"../../api/errors.js";import{CrtrError as Le}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as K,relative as ke,resolve as xe,sep as We,join as Fe}from"node:path";import{SessionManager as qe}from"@earendil-works/pi-coding-agent";import{covers as j}from"@north-light/identity";import{openDb as Y,withCanvasWrite as U}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as ee}from"../canvas/sessions.js";import{getNode as v,nodeFiles as $e,removeNodeFiles as Pe,updateNode as Be}from"../canvas/canvas.js";import{fullName as Je}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{latestExecutionForNode as Ye,liveExecutionForNode as te}from"../canvas/executions.js";import{conversationStore as ne,isConversationNotFound as Ge}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Xe}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as ze}from"../canvas/deliveries.js";import{readNodeRecap as Qe}from"../canvas/node-recap.js";import{enqueueNodeMail as Ve}from"../feed/messages.js";import{recordInitialInput as Ze}from"./initial-input.js";import{newestReportBody as Ke}from"../feed/reports.js";import{ensureAppProfile as ae,loadExactProfileManifest as se}from"../profiles/manifest.js";import{stopNodeSandboxes as ie}from"../spaces/stop.js";import{deleteNodeSandboxes as et}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as tt}from"../runtime/broker-request.js";import{interruptLive as nt}from"../runtime/interactive-deliver.js";import{isBrokerLive as re}from"../runtime/model-swap.js";import{newNodeId as at}from"../runtime/nodes.js";import{reviveNode as G}from"../runtime/revive.js";import{spawnChildPrepared as st}from"../runtime/spawn.js";import{isPortableModelToken as it}from"../runtime/launch.js";import{parseDurationMs as rt}from"../wake.js";import{expandModelCandidates as ot,parseModelSpec as dt}from"../model-routes.js";import{payerOfGrant as X}from"../grants/mirror.js";import{runUsage as ct}from"../ledger/read.js";import{ZERO_RUN_USAGE as ut}from"../../api/dto/run-events.js";import{isolatedBrokerLauncherAvailable as mt}from"../runtime/host.js";import{blaxelEnvironmentOf as lt}from"../runtime/blaxel-environment.js";import{resolveRunKind as ft,resolveRunModel as pt}from"../runtime/launch-target.js";import{cycleAwareMessages as _t}from"../runtime/session-cycles.js";import{originFor as oe}from"../runtime/stamp/protocol.js";import{readOutputRequest as wt,readOutputResult as de}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as ce}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as gt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as Et}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as yt}from"../../daemon/runs/observer.js";import{closeNode as ue}from"../runtime/close.js";import{parseScope as ht}from"@north-light/identity";import{appendRunEvent as me,lockRunRoot as Rt,subscribeRunEvents as St}from"./events.js";import{runActivity as Nt}from"./activity.js";import{cancelOpenQuestions as le,openNoticeIds as bt,openQuestionIds as fe}from"./questions.js";import{appSpace as z}from"../layout.js";import{ensureAppSpace as vt}from"../spaces/space.js";import{assertUploadsUsable as pe,resolveStorageUrls as Ot}from"../storage/attachments.js";import{storageClient as Dt,storageConfig as Mt}from"../storage/client.js";import{deleteRunFiles as At,deleteUploadRow as It,insertUploadUses as _e,releaseRunUploads as Tt,runUsesPath as Lt}from"../storage/tables.js";import{abortProviderCalls as we}from"../providers/inflight.js";import{filterAsync as ge,mapAsync as q}from"../async-array.js";import{blobStore as Ct}from"../blobs/index.js";import{emitEvent as kt}from"../events/emit.js";const Ee=c((e,t,a,n,d)=>Ot(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),xt=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,f,r,i=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=f,this.scope=r,this.retryable=i}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),Q=c(()=>new R(404,"not_found","run not found"),"missing"),I=c(async()=>await Y(),"db");async function $(e,t,a=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw Q();return n}c($,"ownedRun");const ye=["waiting_on_user","idle","settled"];async function k(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await I()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
1
+ var Ae=Object.defineProperty;var c=(e,t)=>Ae(e,"name",{value:t,configurable:!0});import{coveredByAny as Ie}from"../../shared/env.js";import{createHash as Z}from"node:crypto";import{ApiError as Te}from"../../api/errors.js";import{CrtrError as Le}from"../errors.js";import{isCloudRole as Ce}from"../canvas/person.js";import{isAbsolute as K,relative as ke,resolve as xe,sep as We,join as Fe}from"node:path";import{SessionManager as qe}from"@earendil-works/pi-coding-agent";import{covers as j}from"@north-light/identity";import{openDb as Y,withCanvasWrite as U}from"../canvas/db.js";import{deleteNodeWithOwned as He}from"../graph/deletion.js";import{getById as Ue}from"../graph/objects.js";import{repairRunConversations as ee}from"../canvas/sessions.js";import{getNode as v,nodeFiles as $e,removeNodeFiles as Pe,updateNode as Be}from"../canvas/canvas.js";import{fullName as Je}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{latestExecutionForNode as Ye,liveExecutionForNode as te}from"../canvas/executions.js";import{conversationStore as ne,isConversationNotFound as Ge}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Xe}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as ze}from"../canvas/deliveries.js";import{readNodeRecap as Qe}from"../canvas/node-recap.js";import{enqueueNodeMail as Ve}from"../feed/messages.js";import{recordInitialInput as Ze}from"./initial-input.js";import{newestReportBody as Ke}from"../feed/reports.js";import{ensureAppProfile as ae,loadExactProfileManifest as se}from"../profiles/manifest.js";import{stopNodeSandboxes as ie}from"../spaces/stop.js";import{deleteNodeSandboxes as et}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as tt}from"../runtime/broker-request.js";import{interruptLive as nt}from"../runtime/interactive-deliver.js";import{isBrokerLive as re}from"../runtime/model-swap.js";import{newNodeId as at}from"../runtime/nodes.js";import{reviveNode as G}from"../runtime/revive.js";import{spawnChildPrepared as st}from"../runtime/spawn.js";import{isPortableModelToken as it}from"../runtime/launch.js";import{parseDurationMs as rt}from"../wake.js";import{expandModelCandidates as ot,parseModelSpec as dt}from"../model-routes.js";import{payerOfGrant as X}from"../grants/mirror.js";import{runUsage as ct}from"../ledger/read.js";import{ZERO_RUN_USAGE as ut}from"../../api/dto/run-events.js";import{isolatedBrokerLauncherAvailable as mt}from"../runtime/host.js";import{blaxelEnvironmentOf as lt}from"../runtime/blaxel-environment.js";import{resolveRunKind as ft,resolveRunModel as pt}from"../runtime/launch-target.js";import{transcriptMessages as _t}from"../runtime/session-cycles.js";import{originFor as oe}from"../runtime/stamp/protocol.js";import{readOutputRequest as wt,readOutputResult as de}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as ce}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as gt}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as Et}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as yt}from"../../daemon/runs/observer.js";import{closeNode as ue}from"../runtime/close.js";import{parseScope as ht}from"@north-light/identity";import{appendRunEvent as me,lockRunRoot as Rt,subscribeRunEvents as St}from"./events.js";import{runActivity as Nt}from"./activity.js";import{cancelOpenQuestions as le,openNoticeIds as bt,openQuestionIds as fe}from"./questions.js";import{appSpace as z}from"../layout.js";import{ensureAppSpace as vt}from"../spaces/space.js";import{assertUploadsUsable as pe,resolveStorageUrls as Ot}from"../storage/attachments.js";import{storageClient as Dt,storageConfig as Mt}from"../storage/client.js";import{deleteRunFiles as At,deleteUploadRow as It,insertUploadUses as _e,releaseRunUploads as Tt,runUsesPath as Lt}from"../storage/tables.js";import{abortProviderCalls as we}from"../providers/inflight.js";import{filterAsync as ge,mapAsync as q}from"../async-array.js";import{blobStore as Ct}from"../blobs/index.js";import{emitEvent as kt}from"../events/emit.js";const Ee=c((e,t,a,n,d)=>Ot(t,d,e,a,n?{taken:n}:{}),"defaultResolver"),xt=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,f,r,i=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=f,this.scope=r,this.retryable=i}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),Q=c(()=>new R(404,"not_found","run not found"),"missing"),I=c(async()=>await Y(),"db");async function $(e,t,a=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw Q();return n}c($,"ownedRun");const ye=["waiting_on_user","idle","settled"];async function k(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await I()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
2
2
  (n.last_settled_at IS NULL OR EXISTS (
3
3
  SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
4
4
  AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
5
5
  WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
6
6
  )) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await gt(e)?"running":(await fe(e.node_id)).length?"waiting_on_user":await(await I()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
7
7
  WHERE n.run_id = ? AND ${ze("d","'armed', 'pending', 'handed_off'")}
8
- AND (n.status IN ('active', 'idle') OR ${Xe("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(k,"runStatus");async function Zn(e){const t=await v(e);return t!==null&&await k(t)==="running"}c(Zn,"runIsRunning");async function H(e){await ee(e.node_id),e=await v(e.node_id)??e;const t=await k(e),a=t==="settled"?[]:await fe(e.node_id),n=await Ke(e.node_id)||void 0,d=t==="settled"?await Et(e):null,f=d?.kind==="result"?await de(e.node_id):void 0,r=Qe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...r?{recap:r}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await bt(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:await ct(e.node_id),payer:await X(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await Nt(e.node_id,t),worktree:await Wt(e.node_id)}}c(H,"runObject");async function Wt(e){const t=await Ye(e);if(t===null||t.runner!=="blaxel"||t.launchJson===null)return null;const a=JSON.parse(t.launchJson).worktree;return typeof a?.repository=="string"&&typeof a.branch=="string"?{repository:a.repository,branch:a.branch}:null}c(Wt,"runWorktree");const V=864e5,he=255;function Kn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>he)throw S(`Idempotency-Key must be 1-${he} characters`);return e}}c(Kn,"idempotencyKeyOf");function x(e){if(Ce()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(x,"cloudPersonScope");function W(e,t){const a=x(e);return a===void 0?t:`${a}:${t}`}c(W,"personKey");async function P(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await Y();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=V)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(P,"findIdempotent");async function Re(e,t,a,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-V).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(f),r)}c(Re,"recordIdempotent");async function ea(e=Date.now()){return Number((await(await Y()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-V).toISOString())).changes)}c(ea,"pruneExpiredIdempotencyKeys");async function Se(e,t,a,n,d,f,r=!1){const i=d.text;let u=0;return{messageId:(await Ve(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:f?{body:i,...r?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await pe(a,x(n),d.uses,h),await _e(d.uses.map(({upload_id:m,path:y,blob_key:s})=>({upload_id:m,path:y,blob_key:s,run_id:t})),h)),u=(await me(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Se,"acceptRunMessage");class Ne extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Ft=1440*60*1e3;function be(e){const t=typeof e=="string"?rt(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Ft)throw S("deadline must be at most 24h","deadline");return t}c(be,"parseRunDeadlineMs");async function ta(e,t,a,n=Ee){if(t.isolated&&!mt()&&await lt((t.profile===void 0?await ae(e.grantee):se(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&be(t.deadline);const{causedBy:d,...f}=t,r=Z("sha256").update(JSON.stringify(f)).digest("hex");if(a){const o=await P(e.grantee,W(e.sub,a),r);if(o){const m=await $(o.run_id,e.grantee);return!m.pi_pid&&await k(m)==="running"&&(t.output_schema!==void 0&&!m.outcome_at&&await wt(m.node_id)===null&&await de(m.node_id)===void 0&&await ce(m.node_id,"terminal",t.output_schema),await G(m.node_id,{resume:!0,capacity:"freeze"})),o.response}}await vt(e.grantee);const i=t.profile===void 0?await ae(e.grantee):se(t.profile),u=i.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${i.profileId}`;if(!e.resolved.some(m=>j(m,o))||t.scopes!==null&&!t.scopes.some(m=>j(m,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(it(o)){if(o.includes("/")&&await X(e.grant)!=="app"){const m=o.lastIndexOf("/"),y=o.slice(0,m),s=o.slice(m+1);if(["ultra","strong","medium","light"].includes(s)&&(await ot({kind:"logical",family:y,strength:s,spec:o},z(e.grantee).files,i.profileId)).every(E=>E.family!==y))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(dt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const _=await at(),h=Fe(z(e.grantee).nodes,_);if(t.isolated&&t.cwd!==void 0){const o=ke(h,xe(t.cwd));if(!K(t.cwd)||o===".."||o.startsWith(`..${We}`)||K(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(_,e.grantee,t.prompt,void 0,x(e.sub)),m=o.text,y=t.message===void 0?void 0:await n(_,e.grantee,t.message,o.uses.map(p=>p.path),x(e.sub)),s=await X(e.grant);let E;try{const p=pt(i,t.model);await st({kind:ft(i),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:z(e.grantee).files,profile:i.profileId,prompt:m,nodeId:_,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...p===void 0?{}:{model:p},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+be(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:_,event_cursor:1},withinCreate:c(async(g,D)=>{if(a){const N=await P(e.grantee,W(e.sub,a),r,g);if(N)throw new Ne(N)}const A=o.uses;if(A.length&&(await pe(e.grantee,x(e.sub),A,g),await _e(A.map(({upload_id:N,path:F,blob_key:T})=>({upload_id:N,path:F,blob_key:T,run_id:_})),g)),E={run_id:_,node_id:_,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:s,status:"running",created_at:D.created,metadata:t.metadata,sequence_number:0},await me(g,_,_,"run.started",{scopes:t.scopes,payer:s,usage:ut}),y){const N=await Se(g,_,e.grantee,e.sub,y,!1);E.message={run_id:_,message_id:N.messageId,sequence_number:N.sequence}}else await Ze(_,e.grantee,m);a&&await Re(g,e.grantee,W(e.sub,a),r,_,E,D.created)},"withinCreate")},t.output_schema===void 0?void 0:async g=>{await ce(g,"terminal",t.output_schema)})}catch(p){if(p instanceof Ne)return p.winner.response;if(t.model!==void 0&&p instanceof Le&&p.code==="usage")throw S(p.message,"model");if(p instanceof Te&&(p.code==="isolated_run"||p.code==="invalid_request")){const g=p.details&&typeof p.details=="object"&&"param"in p.details&&typeof p.details.param=="string"?p.details.param:void 0;throw new R(p.status,p.code,p.message,g)}throw p}if(!E)throw new Error("run creation did not commit");return E}finally{await qt(_)}}c(ta,"startRun");async function qt(e){try{if(await v(e)!==null)return;const t=await Ct();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){kt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(qt,"discardUncommittedAttachments");async function na(e,t){let a;if(t.after)try{const i=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!i||typeof i!="object"||!("activity"in i)||typeof i.activity!="string"||!("id"in i)||typeof i.id!="string")throw new Error("invalid cursor");a={activity:i.activity,id:i.id}}catch{throw S("invalid list cursor","after")}const n=await(await I()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
8
+ AND (n.status IN ('active', 'idle') OR ${Xe("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(k,"runStatus");async function Zn(e){const t=await v(e);return t!==null&&await k(t)==="running"}c(Zn,"runIsRunning");async function H(e){await ee(e.node_id),e=await v(e.node_id)??e;const t=await k(e),a=t==="settled"?[]:await fe(e.node_id),n=await Ke(e.node_id)||void 0,d=t==="settled"?await Et(e):null,f=d?.kind==="result"?await de(e.node_id):void 0,r=Qe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},...f===void 0?{}:{result:f},...n!==void 0?{last_report:n}:{},...r?{recap:r}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await bt(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:await ct(e.node_id),payer:await X(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await Nt(e.node_id,t),worktree:await Wt(e.node_id)}}c(H,"runObject");async function Wt(e){const t=await Ye(e);if(t===null||t.runner!=="blaxel"||t.launchJson===null)return null;const a=JSON.parse(t.launchJson).worktree;return typeof a?.repository=="string"&&typeof a.branch=="string"?{repository:a.repository,branch:a.branch}:null}c(Wt,"runWorktree");const V=864e5,he=255;function Kn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>he)throw S(`Idempotency-Key must be 1-${he} characters`);return e}}c(Kn,"idempotencyKeyOf");function x(e){if(Ce()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(x,"cloudPersonScope");function W(e,t){const a=x(e);return a===void 0?t:`${a}:${t}`}c(W,"personKey");async function P(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await Y();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=V)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(P,"findIdempotent");async function Re(e,t,a,n,d,f,r){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-V).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(f),r)}c(Re,"recordIdempotent");async function ea(e=Date.now()){return Number((await(await Y()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-V).toISOString())).changes)}c(ea,"pruneExpiredIdempotencyKeys");async function Se(e,t,a,n,d,f,r=!1){const i=d.text;let u=0;return{messageId:(await Ve(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:f?{body:i,...r?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:f?"normal":"deferred",wake:f?1:0,withinEnqueue:c(async(h,o)=>{d.uses.length&&(await pe(a,x(n),d.uses,h),await _e(d.uses.map(({upload_id:m,path:y,blob_key:s})=>({upload_id:m,path:y,blob_key:s,run_id:t})),h)),u=(await me(h,t,t,"node.message.accepted",{message_id:o,start_turn:f})).sequence_number},"withinEnqueue")})).messageId,sequence:u}}c(Se,"acceptRunMessage");class Ne extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Ft=1440*60*1e3;function be(e){const t=typeof e=="string"?rt(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Ft)throw S("deadline must be at most 24h","deadline");return t}c(be,"parseRunDeadlineMs");async function ta(e,t,a,n=Ee){if(t.isolated&&!mt()&&await lt((t.profile===void 0?await ae(e.grantee):se(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&be(t.deadline);const{causedBy:d,...f}=t,r=Z("sha256").update(JSON.stringify(f)).digest("hex");if(a){const o=await P(e.grantee,W(e.sub,a),r);if(o){const m=await $(o.run_id,e.grantee);return!m.pi_pid&&await k(m)==="running"&&(t.output_schema!==void 0&&!m.outcome_at&&await wt(m.node_id)===null&&await de(m.node_id)===void 0&&await ce(m.node_id,"terminal",t.output_schema),await G(m.node_id,{resume:!0,capacity:"freeze"})),o.response}}await vt(e.grantee);const i=t.profile===void 0?await ae(e.grantee):se(t.profile),u=i.manifest.grantee??"app:terminal";if(u!==e.grantee){const o=`crtr:memory:rw:${u}:profile:${i.profileId}`;if(!e.resolved.some(m=>j(m,o))||t.scopes!==null&&!t.scopes.some(m=>j(m,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(it(o)){if(o.includes("/")&&await X(e.grant)!=="app"){const m=o.lastIndexOf("/"),y=o.slice(0,m),s=o.slice(m+1);if(["ultra","strong","medium","light"].includes(s)&&(await ot({kind:"logical",family:y,strength:s,spec:o},z(e.grantee).files,i.profileId)).every(E=>E.family!==y))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(dt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const _=await at(),h=Fe(z(e.grantee).nodes,_);if(t.isolated&&t.cwd!==void 0){const o=ke(h,xe(t.cwd));if(!K(t.cwd)||o===".."||o.startsWith(`..${We}`)||K(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(_,e.grantee,t.prompt,void 0,x(e.sub)),m=o.text,y=t.message===void 0?void 0:await n(_,e.grantee,t.message,o.uses.map(p=>p.path),x(e.sub)),s=await X(e.grant);let E;try{const p=pt(i,t.model);await st({kind:ft(i),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:z(e.grantee).files,profile:i.profileId,prompt:m,nodeId:_,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...p===void 0?{}:{model:p},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+be(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:_,event_cursor:1},withinCreate:c(async(g,O)=>{if(a){const N=await P(e.grantee,W(e.sub,a),r,g);if(N)throw new Ne(N)}const A=o.uses;if(A.length&&(await pe(e.grantee,x(e.sub),A,g),await _e(A.map(({upload_id:N,path:F,blob_key:T})=>({upload_id:N,path:F,blob_key:T,run_id:_})),g)),E={run_id:_,node_id:_,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:s,status:"running",created_at:O.created,metadata:t.metadata,sequence_number:0},await me(g,_,_,"run.started",{scopes:t.scopes,payer:s,usage:ut}),y){const N=await Se(g,_,e.grantee,e.sub,y,!1);E.message={run_id:_,message_id:N.messageId,sequence_number:N.sequence}}else await Ze(_,e.grantee,m);a&&await Re(g,e.grantee,W(e.sub,a),r,_,E,O.created)},"withinCreate")},t.output_schema===void 0?void 0:async g=>{await ce(g,"terminal",t.output_schema)})}catch(p){if(p instanceof Ne)return p.winner.response;if(t.model!==void 0&&p instanceof Le&&p.code==="usage")throw S(p.message,"model");if(p instanceof Te&&(p.code==="isolated_run"||p.code==="invalid_request")){const g=p.details&&typeof p.details=="object"&&"param"in p.details&&typeof p.details.param=="string"?p.details.param:void 0;throw new R(p.status,p.code,p.message,g)}throw p}if(!E)throw new Error("run creation did not commit");return E}finally{await qt(_)}}c(ta,"startRun");async function qt(e){try{if(await v(e)!==null)return;const t=await Ct();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){kt({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(qt,"discardUncommittedAttachments");async function na(e,t){let a;if(t.after)try{const i=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!i||typeof i!="object"||!("activity"in i)||typeof i.activity!="string"||!("id"in i)||typeof i.id!="string")throw new Error("invalid cursor");a={activity:i.activity,id:i.id}}catch{throw S("invalid list cursor","after")}const n=await(await I()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
9
9
  WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}${t.sub===void 0?"":" AND sub = ?"}
10
- ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await ge(await q((await ge(n,async({node_id:i})=>!t.visible||await t.visible(i))).filter(({activity:i,node_id:u})=>!a||i<a.activity||i===a.activity&&u<a.id),async i=>({root:await v(i.node_id),activity:i.activity})),async({root:i})=>!t.status||await k(i)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await q(f,async({root:i})=>await H(i)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(na,"listRuns");async function aa(e,t,a){const n=await $(e,t),d=c(async()=>await H(await $(e,t)),"read");return!a||ye.includes(await k(n))?await d():new Promise((f,r)=>{let i=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(y),clearInterval(m),i()},"settle"),_=c(async()=>{u();try{f(await d())}catch(s){r(s)}},"finish"),h=c(async()=>{ye.includes(String((await d()).status))&&await _()},"check"),o=c(()=>{h().catch(s=>{u(),r(s)})},"run"),m=setInterval(o,250),y=setTimeout(()=>{_()},a*1e3);St(e,o).then(s=>{i=s},s=>{u(),r(s)})})}c(aa,"waitRun");const Ht=5;async function sa(e,t,a=Ee,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",i=e.grantee??"app:terminal",u=Z("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),_=c(async o=>{const m=await v(e.node_id),y=await(await I()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return m&&!r&&n&&!m.pi_pid&&y&&await G(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await P(i,W(e.sub,d),u);if(o)return _(o.response)}if(r)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const m=await a(e.node_id,i,t,void 0,x(e.sub)),y=await U(async s=>{if(d){const g=await P(i,W(e.sub,d),u,s);if(g)return{replayed:g.response}}if(m.uses.length){await Rt(s,e.node_id);for(const g of m.uses)if(await Lt(e.node_id,g.path,s))return"path_taken"}await h?.(e.node_id);const E=await Se(s,e.node_id,i,e.sub,m,n,n&&f),p={run_id:e.node_id,message_id:E.messageId,sequence_number:E.sequence};return d&&await Re(s,i,W(e.sub,d),u,e.node_id,p,new Date().toISOString()),{result:p}});if(y==="path_taken"){if(o>=Ht)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in y?_(y.replayed):(n&&!e.pi_pid&&await G(e.node_id,{resume:!0,capacity:"freeze"}),y.result)}}c(sa,"messageRun");async function Ut(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await v(e);if(!n)throw Q();if(!re(n)){if(n.streaming)throw t();return}const d=(await te(e))?.executionId;try{await nt(e)==="turn"&&we({nodes:[e]});return}catch(f){if(!(f instanceof tt))throw f;const r=await v(e);if(!r)throw Q();if(!r.streaming)return;if(a===0&&re(r)&&(await te(e))?.executionId!==d)continue;throw t()}}throw t()}c(Ut,"interruptNode");async function ia(e,t="stop"){const a=t==="stop"?(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>Ut(n))),await H(await v(e.node_id)??e)}c(ia,"interruptRun");async function ra(e,t={}){const a=(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);we({run:e.node_id});const n=[];if(await k(e)!=="settled")n.push(...(await ue(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of a){if(r===e.node_id)continue;const i=await v(r);i&&i.status!=="done"&&i.status!=="canceled"&&i.status!=="dead"&&n.push(...(await ue(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await le({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>ie(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await v(e.node_id);return await H(f??e)}c(ra,"cancelRun");const ve=200;async function oa(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>ve)throw S(`name exceeds ${ve} characters`,"name");const n=await Be(e.node_id,{name:a});return n.window&&je(n.window,Je(n)),await H(n)}c(oa,"renameRun");async function da(e,t={config:Mt,client:Dt}){await le({run_id:e.node_id},"the run was deleted");const a=await U(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(_=>_.node_id)));if((await Promise.all(a.map(u=>ie(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await et(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await q(a,async u=>{const _=await $e(u);if(_.app===null)throw new Error(`run node missing during deletion: ${u}`);return _}),f=await(await I()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of f)try{await ne().delete(u)}catch(_){if(!Ge(_))throw _}const r=await U(async u=>{for(const m of a){const y=await Ue(u,m);y!==null&&y.deleted_at===null&&await He(u,y)}const _=await Tt([e.node_id],u);await At([e.node_id],u),await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:m}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(m,m);return _});for(const u of d)await Pe(u);const{notifyRunDeleted:i}=await import("./events.js");return i(e.node_id),{uploads_pending:await $t(r,t)}}c(da,"deleteRun");async function $t(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(r=>a.deleteUpload(r).then(async()=>{await It(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??xt),f.unref?.()})]),clearTimeout(f),e.length-n.size}c($t,"deleteReleasedUploads");async function ca(e,t,a){await $(e,t),await ee(e);const n=await U(async s=>{const E=await s.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),p=new Map;for(const b of E)p.set(b.node_id,(await s.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(b.node_id)).map(l=>l.session_id));const D=(await s.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await s.prepare(`SELECT node_id, sequence_number FROM run_events
10
+ ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await ge(await q((await ge(n,async({node_id:i})=>!t.visible||await t.visible(i))).filter(({activity:i,node_id:u})=>!a||i<a.activity||i===a.activity&&u<a.id),async i=>({root:await v(i.node_id),activity:i.activity})),async({root:i})=>!t.status||await k(i)===t.status),f=d.slice(0,t.limit),r=f.at(-1);return{runs:await q(f,async({root:i})=>await H(i)),next:d.length>t.limit&&r?Buffer.from(JSON.stringify({activity:r.activity,id:r.root.node_id})).toString("base64url"):null}}c(na,"listRuns");async function aa(e,t,a){const n=await $(e,t),d=c(async()=>await H(await $(e,t)),"read");return!a||ye.includes(await k(n))?await d():new Promise((f,r)=>{let i=c(()=>{},"unsubscribe");const u=c(()=>{clearTimeout(y),clearInterval(m),i()},"settle"),_=c(async()=>{u();try{f(await d())}catch(s){r(s)}},"finish"),h=c(async()=>{ye.includes(String((await d()).status))&&await _()},"check"),o=c(()=>{h().catch(s=>{u(),r(s)})},"run"),m=setInterval(o,250),y=setTimeout(()=>{_()},a*1e3);St(e,o).then(s=>{i=s},s=>{u(),r(s)})})}c(aa,"waitRun");const Ht=5;async function sa(e,t,a=Ee,n=!0,d,f=!0){const r=e.status==="canceled"||e.outcome_reason==="closed",i=e.grantee??"app:terminal",u=Z("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!f?["steer:false"]:[]])).digest("hex"),_=c(async o=>{const m=await v(e.node_id),y=await(await I()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return m&&!r&&n&&!m.pi_pid&&y&&await G(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await P(i,W(e.sub,d),u);if(o)return _(o.response)}if(r)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const m=await a(e.node_id,i,t,void 0,x(e.sub)),y=await U(async s=>{if(d){const g=await P(i,W(e.sub,d),u,s);if(g)return{replayed:g.response}}if(m.uses.length){await Rt(s,e.node_id);for(const g of m.uses)if(await Lt(e.node_id,g.path,s))return"path_taken"}await h?.(e.node_id);const E=await Se(s,e.node_id,i,e.sub,m,n,n&&f),p={run_id:e.node_id,message_id:E.messageId,sequence_number:E.sequence};return d&&await Re(s,i,W(e.sub,d),u,e.node_id,p,new Date().toISOString()),{result:p}});if(y==="path_taken"){if(o>=Ht)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in y?_(y.replayed):(n&&!e.pi_pid&&await G(e.node_id,{resume:!0,capacity:"freeze"}),y.result)}}c(sa,"messageRun");async function Ut(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await v(e);if(!n)throw Q();if(!re(n)){if(n.streaming)throw t();return}const d=(await te(e))?.executionId;try{await nt(e)==="turn"&&we({nodes:[e]});return}catch(f){if(!(f instanceof tt))throw f;const r=await v(e);if(!r)throw Q();if(!r.streaming)return;if(a===0&&re(r)&&(await te(e))?.executionId!==d)continue;throw t()}}throw t()}c(Ut,"interruptNode");async function ia(e,t="stop"){const a=t==="stop"?(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>Ut(n))),await H(await v(e.node_id)??e)}c(ia,"interruptRun");async function ra(e,t={}){const a=(await(await I()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(r=>r.node_id);we({run:e.node_id});const n=[];if(await k(e)!=="settled")n.push(...(await ue(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const r of a){if(r===e.node_id)continue;const i=await v(r);i&&i.status!=="done"&&i.status!=="canceled"&&i.status!=="dead"&&n.push(...(await ue(r,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await le({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(r=>ie(r,"run_canceled")))).some(r=>!r.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const f=await v(e.node_id);return await H(f??e)}c(ra,"cancelRun");const ve=200;async function oa(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>ve)throw S(`name exceeds ${ve} characters`,"name");const n=await Be(e.node_id,{name:a});return n.window&&je(n.window,Je(n)),await H(n)}c(oa,"renameRun");async function da(e,t={config:Mt,client:Dt}){await le({run_id:e.node_id},"the run was deleted");const a=await U(async u=>(await u.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await u.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(_=>_.node_id)));if((await Promise.all(a.map(u=>ie(u,"run_deleted",{deleting:!0})))).some(u=>!u.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await et(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await q(a,async u=>{const _=await $e(u);if(_.app===null)throw new Error(`run node missing during deletion: ${u}`);return _}),f=await(await I()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:u}of f)try{await ne().delete(u)}catch(_){if(!Ge(_))throw _}const r=await U(async u=>{for(const m of a){const y=await Ue(u,m);y!==null&&y.deleted_at===null&&await He(u,y)}const _=await Tt([e.node_id],u);await At([e.node_id],u),await u.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await u.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await u.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await u.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:m}of o)await u.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(m,m);return _});for(const u of d)await Pe(u);const{notifyRunDeleted:i}=await import("./events.js");return i(e.node_id),{uploads_pending:await $t(r,t)}}c(da,"deleteRun");async function $t(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(r=>a.deleteUpload(r).then(async()=>{await It(r),n.add(r)},()=>{}));let f;return await Promise.race([Promise.all(d),new Promise(r=>{f=setTimeout(r,t.budgetMs??xt),f.unref?.()})]),clearTimeout(f),e.length-n.size}c($t,"deleteReleasedUploads");async function ca(e,t,a){await $(e,t),await ee(e);const n=await U(async s=>{const E=await s.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),p=new Map;for(const b of E)p.set(b.node_id,(await s.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(b.node_id)).map(l=>l.session_id));const O=(await s.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await s.prepare(`SELECT node_id, sequence_number FROM run_events
11
11
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
12
- ORDER BY sequence_number`).all(e,D),N=await s.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
12
+ ORDER BY sequence_number`).all(e,O),N=await s.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
13
13
  WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
14
- ORDER BY sequence_number`).all(e,D),F=await s.prepare(`SELECT node_id, sequence_number, ts, body_json FROM run_events
14
+ ORDER BY sequence_number`).all(e,O),F=await s.prepare(`SELECT node_id, sequence_number, ts, body_json FROM run_events
15
15
  WHERE run_id = ? AND sequence_number <= ? AND type = 'file.sent'
16
- ORDER BY sequence_number`).all(e,D),T=new Set((await s.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=F.flatMap(b=>{const l=JSON.parse(b.body_json);return T.has(l.file_id)?[{file_id:l.file_id,node_id:b.node_id,name:l.name,media_type:l.media_type,size:l.size,sequence_number:Number(b.sequence_number),ts:b.ts}]:[]});return{nodes:E,sessionIds:p,latestSequence:D,completed:A,deltas:N,files:B}}),{nodes:d,sessionIds:f,latestSequence:r,completed:i,deltas:u,files:_}=n,h=await q(d,async s=>({node_id:s.node_id,parent_node_id:s.parent,conversations:await q(f.get(s.node_id)??[],async E=>{const{header:p,entries:g}=await ne().read(E);if(a==="entries")return{conversation_id:E,header:p,entries:g};const D=qe.inMemory(p.cwd,void 0,[p,...g]),A=_t(D)??[],N=new Map(g.map((l,O)=>[l.id,O])),F=g.filter(l=>l.type==="custom"&&l.customType==="crtr-system-prompt").map(l=>({id:l.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in l?l.data:void 0,timestamp:l.timestamp}})),T=g.filter(l=>l.type==="custom_message"&&l.customType==="app_message").map(l=>({id:l.id,message:{role:"custom",customType:"app_message",content:"content"in l?l.content:"",timestamp:l.timestamp}})),B=s.node_id===e?g.find(l=>{if(l.type!=="message"||l.message.role!=="user")return!1;const O=oe(g,l.message.timestamp);return O?.type==="runtime"&&O.kind==="kickoff"})?.id:void 0,b=[...A.filter(({id:l})=>!T.some(O=>O.id===l)),...F,...T].sort((l,O)=>(N.get(l.id)??Number.MAX_SAFE_INTEGER)-(N.get(O.id)??Number.MAX_SAFE_INTEGER)).map(({id:l,message:O})=>{const w=O,L=w.usage,J=w.role==="user"?oe(g,Number(w.timestamp)):null,Oe=J?.type==="human"||l===B,C=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?Oe?"user":"custom":w.role,De=C==="custom"?w.role==="custom"?w.customType:J?.type==="runtime"?J.kind:"unknown":void 0,Me=C==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(M=>M.type==="toolCall"?{type:"tool_call",tool_call_id:M.id,name:M.name,arguments:M.arguments}:M.type==="image"?{type:"image",mime_type:M.mimeType}:M.type==="thinking"?{type:"thinking",text:M.thinking}:M):[];return{entry_id:l,role:C,...C==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...C==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...L?{usage:{input_tokens:L.input??0,output_tokens:L.output??0,cache_read_tokens:L.cacheRead??0,cache_write_tokens:L.cacheWrite??0,cost_usd:L.cost?.total??0}}:{}}:{},...C==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:E,messages:b}})})),o=new Map(await Promise.all(h.map(async s=>[s.node_id,await yt(s.node_id)])));for(const s of i){const E=o.get(s.node_id);E!=null&&s.sequence_number>=E&&o.set(s.node_id,null)}const m=new Map;for(const s of u){const E=o.get(s.node_id);if(E==null||s.sequence_number<E)continue;const p=JSON.parse(s.body_json),g=m.get(s.node_id)??{thinking:"",text:""};s.type==="node.thinking.delta"?g.thinking+=p.delta:g.text+=p.delta,m.set(s.node_id,g)}const y=h.map(s=>({...s,in_progress_message:o.get(s.node_id)==null?null:m.get(s.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:y,files:_}}c(ca,"traceRun");function ua(e,t,a){if(t===void 0){if(!e.some(n=>j(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{ht(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ie(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(ua,"requestedScopes");export{V as IDEMPOTENCY_WINDOW_MS,Ft as RUN_DEADLINE_MAX_MS,xt as RUN_DELETE_STORAGE_BUDGET_MS,ve as RUN_NAME_MAX,R as RunError,ra as cancelRun,x as cloudPersonScope,da as deleteRun,Kn as idempotencyKeyOf,ia as interruptRun,na as listRuns,sa as messageRun,$ as ownedRun,be as parseRunDeadlineMs,ea as pruneExpiredIdempotencyKeys,oa as renameRun,ua as requestedScopes,Zn as runIsRunning,H as runObject,ta as startRun,ca as traceRun,aa as waitRun};
16
+ ORDER BY sequence_number`).all(e,O),T=new Set((await s.prepare("SELECT file_id FROM files WHERE run_id = ? AND completed_at IS NOT NULL").all(e)).map(b=>b.file_id)),B=F.flatMap(b=>{const l=JSON.parse(b.body_json);return T.has(l.file_id)?[{file_id:l.file_id,node_id:b.node_id,name:l.name,media_type:l.media_type,size:l.size,sequence_number:Number(b.sequence_number),ts:b.ts}]:[]});return{nodes:E,sessionIds:p,latestSequence:O,completed:A,deltas:N,files:B}}),{nodes:d,sessionIds:f,latestSequence:r,completed:i,deltas:u,files:_}=n,h=await q(d,async s=>({node_id:s.node_id,parent_node_id:s.parent,conversations:await q(f.get(s.node_id)??[],async E=>{const{header:p,entries:g}=await ne().read(E);if(a==="entries")return{conversation_id:E,header:p,entries:g};const O=qe.inMemory(p.cwd,void 0,[p,...g]),A=_t(O.getEntries(),O.getLeafId()),N=new Map(g.map((l,D)=>[l.id,D])),F=g.filter(l=>l.type==="custom"&&l.customType==="crtr-system-prompt").map(l=>({id:l.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in l?l.data:void 0,timestamp:l.timestamp}})),T=g.filter(l=>l.type==="custom_message"&&l.customType==="app_message").map(l=>({id:l.id,message:{role:"custom",customType:"app_message",content:"content"in l?l.content:"",timestamp:l.timestamp}})),B=s.node_id===e?g.find(l=>{if(l.type!=="message"||l.message.role!=="user")return!1;const D=oe(g,l.message.timestamp);return D?.type==="runtime"&&D.kind==="kickoff"})?.id:void 0,b=[...A.filter(({id:l})=>!T.some(D=>D.id===l)),...F,...T].sort((l,D)=>(N.get(l.id)??Number.MAX_SAFE_INTEGER)-(N.get(D.id)??Number.MAX_SAFE_INTEGER)).map(({id:l,message:D})=>{const w=D,L=w.usage,J=w.role==="user"?oe(g,Number(w.timestamp)):null,Oe=J?.type==="human"||l===B,C=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?Oe?"user":"custom":w.role,De=C==="custom"?w.role==="custom"?w.customType:J?.type==="runtime"?J.kind:"unknown":void 0,Me=C==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(M=>M.type==="toolCall"?{type:"tool_call",tool_call_id:M.id,name:M.name,arguments:M.arguments}:M.type==="image"?{type:"image",mime_type:M.mimeType}:M.type==="thinking"?{type:"thinking",text:M.thinking}:M):[];return{entry_id:l,role:C,...C==="custom"?{custom_type:De}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:Me,...C==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...L?{usage:{input_tokens:L.input??0,output_tokens:L.output??0,cache_read_tokens:L.cacheRead??0,cache_write_tokens:L.cacheWrite??0,cost_usd:L.cost?.total??0}}:{}}:{},...C==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:E,messages:b}})})),o=new Map(await Promise.all(h.map(async s=>[s.node_id,await yt(s.node_id)])));for(const s of i){const E=o.get(s.node_id);E!=null&&s.sequence_number>=E&&o.set(s.node_id,null)}const m=new Map;for(const s of u){const E=o.get(s.node_id);if(E==null||s.sequence_number<E)continue;const p=JSON.parse(s.body_json),g=m.get(s.node_id)??{thinking:"",text:""};s.type==="node.thinking.delta"?g.thinking+=p.delta:g.text+=p.delta,m.set(s.node_id,g)}const y=h.map(s=>({...s,in_progress_message:o.get(s.node_id)==null?null:m.get(s.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:r,nodes:y,files:_}}c(ca,"traceRun");function ua(e,t,a){if(t===void 0){if(!e.some(n=>j(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{ht(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ie(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(ua,"requestedScopes");export{V as IDEMPOTENCY_WINDOW_MS,Ft as RUN_DEADLINE_MAX_MS,xt as RUN_DELETE_STORAGE_BUDGET_MS,ve as RUN_NAME_MAX,R as RunError,ra as cancelRun,x as cloudPersonScope,da as deleteRun,Kn as idempotencyKeyOf,ia as interruptRun,na as listRuns,sa as messageRun,$ as ownedRun,be as parseRunDeadlineMs,ea as pruneExpiredIdempotencyKeys,oa as renameRun,ua as requestedScopes,Zn as runIsRunning,H as runObject,ta as startRun,ca as traceRun,aa as waitRun};