@north-light/cli 0.3.458 → 0.3.460
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/profiles.d.ts +3 -1
- package/dist/builtin-memory/crouter-sdk/guides/apps-on-northlight.md +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +12 -0
- package/dist/clients/attach/session/profile-files.js +1 -1
- package/dist/clients/attach/viewer.js +178 -178
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile/show.js +1 -1
- package/dist/commands/sys/join.js +1 -1
- package/dist/commands/sys/panels/models-panel.js +1 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/directory/join.d.ts +4 -2
- package/dist/core/directory/join.js +1 -1
- package/dist/core/io.d.ts +12 -2
- package/dist/core/io.js +7 -7
- package/dist/core/layout-migrate/stored-paths.js +3 -3
- package/dist/core/layout-migrate/stores.js +1 -1
- package/dist/core/layout.d.ts +2 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/profiles/manifest.d.ts +1 -1
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/profiles/relocate.d.ts +8 -0
- package/dist/core/profiles/relocate.js +1 -0
- package/dist/core/providers/device.js +1 -1
- package/dist/core/render.d.ts +1 -1
- package/dist/core/render.js +6 -6
- package/dist/core/scoped-state/migrate.js +1 -1
- package/dist/core/scoped-state/profiles.js +1 -1
- package/dist/core/scoped-state/settings.js +1 -1
- package/dist/core/spaces/space.js +2 -2
- package/dist/core/storage/download.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/crtrd.js +8 -7
- package/dist/migrations/004-canvas-documents/index.js +2 -2
- package/dist/migrations/004-canvas-documents/legacy/types.d.ts +1 -1
- package/docs/sdk/guides/apps-on-northlight.md +1 -1
- package/docs/sdk/release-notes.md +12 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
var P=Object.defineProperty;var y=(e,c)=>P(e,"name",{value:c,configurable:!0});import{DatabaseSync as S}from"node:sqlite";import{closeSync as F,existsSync as m,fsyncSync as C,lstatSync as D,openSync as B,readFileSync as $,readdirSync as g,renameSync as J,unlinkSync as x,writeFileSync as q}from"node:fs";import{basename as L,dirname as N,join as a,relative as v,resolve as H,sep as A}from"node:path";import{homedir as G}from"node:os";function M(e,c){return typeof e=="string"?c.map.mapPath(e):Array.isArray(e)?e.map(r=>M(r,c)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,M(i,c)])):e}y(M,"mappedJson");function b(e,c){const r=JSON.parse(e),i=M(r,c);return JSON.stringify(i)===JSON.stringify(r)?e:JSON.stringify(i)}y(b,"rewriteJson");function O(e,c){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(c)!==void 0}y(O,"tableExists");function T(e,c,r){if(!m(e))return;const i=new S(e);try{i.exec("BEGIN IMMEDIATE");try{for(const[f,p]of Object.entries(c)){if(!O(i,f))continue;const u=new Set(i.prepare(`PRAGMA table_info("${f}")`).all().map(o=>o.name)),d=[...(p.paths??[]).filter(o=>u.has(o)),...(p.json??[]).filter(o=>u.has(o))];if(d.length===0)continue;const s=i.prepare(`SELECT rowid AS migration_rowid, ${d.map(o=>`"${o}"`).join(", ")} FROM "${f}"`).all();for(const o of s){const l=[];for(const n of d){const t=o[n];if(typeof t!="string")continue;const h=(p.json??[]).includes(n)?b(t,r):r.map.mapPath(t);h!==t&&l.push([n,h])}l.length&&(i.prepare(`UPDATE "${f}" SET ${l.map(([n])=>`"${n}" = ?`).join(", ")} WHERE rowid = ?`).run(...l.map(([,n])=>n),o.migration_rowid),r.moved+=l.length,r.changes.push(`${e}:${f}:${String(o.migration_rowid)} (${l.map(([n])=>n).join(", ")})`))}}i.exec("COMMIT")}catch(f){throw i.exec("ROLLBACK"),f}}finally{i.close()}}y(T,"rewriteDb");const k={nodes:{paths:["cwd","fork_source_file","pi_session_file"],json:["launch_config_json","review_binding_json","metadata_json","outcome_detail_json"]},sessions:{paths:["transcript_path","fork_source_path"]},worktrees:{paths:["path","repo_root"],json:["sweep_observed_json","abandoned_json","land_intent_json","disposal_json"]},crons:{paths:["cwd"],json:["env_json","sink"]},human_action_deliveries:{paths:["cwd"],json:["argv_json","completion_json","last_failure_json"]},deliveries:{json:["adapter_json"]},reviews:{paths:["origin_session_file","review_dir","branch_file","output_path","file","presentation_dir"],json:["result_json","specification_json"]},human_requests:{paths:["request_dir","file","presentation_dir"],json:["specification_json","action_json","progress_json","feedback_json","result_json"]},run_events:{json:["body_json"]},webhook_deliveries:{json:["payload_json","document_json","last_failure_json","argv_json"]}},W={scope_owners:{paths:["root"]},profiles:{paths:["home"]},profile_projects:{paths:["path"]},profile_defaults:{paths:["directory"]},scope_bookkeeping:{paths:["active_canvas"]},scope_settings:{json:["raw_json"]}};function E(e,c,r){if(!m(e))return;const i=$(e,"utf8"),f=r(i);if(f===i)return;const p=D(e);if(!p.isFile())throw new Error(`migration path is not a regular file: ${e}`);const u=`${e}.migration-tmp`;if(m(u))throw new Error(`migration temporary file already exists: ${u}`);try{q(u,f,{flag:"wx",mode:p.mode});const d=B(u,"r");try{C(d)}finally{F(d)}J(u,e)}finally{m(u)&&x(u)}c.moved++,c.changes.push(`${e} (stored paths)`)}y(E,"rewriteFile");function _(e,c){if(m(e))for(const r of g(e,{withFileTypes:!0})){const i=a(e,r.name);r.isDirectory()?_(i,c):r.isFile()&&c(i)}}y(_,"walk");function U(e,c,r){const{map:i}=e,{old:f}=i,p=new Map,u=new Set,d=new Set;_(c,n=>{if(!n.includes("/conversations/")||!n.endsWith(".jsonl"))return;const t=L(n);p.has(t)?u.add(t):p.set(t,a(f.targetRoot,v(f.root,n)))});const s=y(n=>{if(typeof n=="string"){if(!n.startsWith(f.storedAgent+A+"sessions"+A)||d.has(n)||i.mapPath(n)!==n)return;const t=L(n);if(u.has(t)||!p.has(t)){d.has(n)||e.resolutions.push(`lost-transcript: ${n} is referenced but ${u.has(t)?"matches more than one moved transcript":"exists nowhere"}; left the reference unchanged`),d.add(n);return}i.add(n,p.get(t))}else if(Array.isArray(n))for(const t of n)s(t);else if(n!==null&&typeof n=="object")for(const t of Object.values(n))s(t)},"reference"),o=y(n=>{if(n.endsWith("/meta.json")||n.endsWith(".json")&&(n.includes("/tickets/")||n.includes("/requests/")))s(JSON.parse($(n,"utf8")));else if(n.endsWith(".jsonl")&&n.includes("/conversations/")){const t=$(n,"utf8");s(JSON.parse(t.slice(0,t.indexOf(`
|
|
2
2
|
`)<0?void 0:t.indexOf(`
|
|
3
|
-
`))))}else if(n.endsWith(".md")&&n.includes("/memory/")){const t=$(n,"utf8");if(!t.startsWith(`---
|
|
3
|
+
`))))}else if(n.endsWith(".md")&&(n.includes("/memory/")||n.includes("/profiles/"))){const t=$(n,"utf8");if(!t.startsWith(`---
|
|
4
4
|
`))return;const h=t.indexOf(`
|
|
5
5
|
---`,4);if(h<0)return;for(const j of t.slice(0,h).split(`
|
|
6
|
-
`)){const w=j.match(/^\s*session_file:\s*["']?([^"'\n]+)["']?$/);w&&s(w[1])}}},"inspect");_(c,o),_(a(f.root,"user","memory"),o),_(a(r,"nodes"),o),_(a(r,"tickets"),o),_(a(r,"requests"),o);const l=a(r,"canvas.db");if(m(l)){const n=new S(l,{readOnly:!0});try{for(const[t,h]of Object.entries(k)){if(!O(n,t))continue;const j=new Set(n.prepare(`PRAGMA table_info("${t}")`).all().map(w=>w.name));for(const w of[...h.paths??[],...h.json??[]].filter(R=>j.has(R)))for(const R of n.prepare(`SELECT "${w}" AS value FROM "${t}" WHERE "${w}" LIKE ?`).all(`%${f.storedAgent}/sessions/%`))(h.json??[]).includes(w)?s(JSON.parse(R.value)):s(R.value)}}finally{n.close()}}}y(U,"recoverSessionMappings");function se(e){const{root:c}=e.map.old,r=a(c,"runtime"),i=a(c,"apps");U(e,i,r),T(a(r,"canvas.db"),k,e),T(a(r,"scope","operations.db"),W,e);const f=new Set,p=a(r,"canvas.db");if(m(p)){const s=new S(p,{readOnly:!0});try{if(O(s,"nodes")&&s.prepare("PRAGMA table_info(nodes)").all().some(o=>o.name==="cwd"))for(const o of s.prepare("SELECT cwd FROM nodes").all())f.add(o.cwd)}finally{s.close()}}const u=a(r,"scope","operations.db");if(m(u)){const s=new S(u,{readOnly:!0});try{if(O(s,"profile_projects"))for(const o of s.prepare("SELECT path FROM profile_projects").all())f.add(o.path)}finally{s.close()}}for(const s of f){const o=e.map.old.targetRoot;let l=s.startsWith(o+"/")?H(c,v(o,s)):s;for(;l!==N(l);)T(a(l,".crouter","operations.db"),W,e),l=N(l)}_(a(i),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e),s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith(".md")&&s.includes("/memory/")&&I(s,e),s.endsWith(".jsonl")&&s.includes("/conversations/")&&X(s,e)}),_(a(c,"user","memory"),s=>{s.endsWith(".md")&&I(s,e)}),Y(e);for(const s of e.map.dangling)e.resolutions.push(`dangling-path: ${s} names a file the new layout drops; left the stored path unchanged`);_(a(c,"user","files"),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e)}),_(a(r,"nodes"),s=>{s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith("/session.ptr")&&x(s)}),_(a(r,"tickets"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))}),_(a(r,"requests"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))});const d=a(r,"canvas.db");if(m(d)){const s=new S(d);try{s.exec("DROP TABLE IF EXISTS layout_header_rewrites")}finally{s.close()}}}y(se,"storedPaths");function I(e,c){E(e,c,r=>{if(!r.startsWith(`---
|
|
6
|
+
`)){const w=j.match(/^\s*session_file:\s*["']?([^"'\n]+)["']?$/);w&&s(w[1])}}},"inspect");_(c,o),_(a(f.root,"user","memory"),o),_(a(r,"nodes"),o),_(a(r,"tickets"),o),_(a(r,"requests"),o);const l=a(r,"canvas.db");if(m(l)){const n=new S(l,{readOnly:!0});try{for(const[t,h]of Object.entries(k)){if(!O(n,t))continue;const j=new Set(n.prepare(`PRAGMA table_info("${t}")`).all().map(w=>w.name));for(const w of[...h.paths??[],...h.json??[]].filter(R=>j.has(R)))for(const R of n.prepare(`SELECT "${w}" AS value FROM "${t}" WHERE "${w}" LIKE ?`).all(`%${f.storedAgent}/sessions/%`))(h.json??[]).includes(w)?s(JSON.parse(R.value)):s(R.value)}}finally{n.close()}}}y(U,"recoverSessionMappings");function se(e){const{root:c}=e.map.old,r=a(c,"runtime"),i=a(c,"apps");U(e,i,r),T(a(r,"canvas.db"),k,e),T(a(r,"scope","operations.db"),W,e);const f=new Set,p=a(r,"canvas.db");if(m(p)){const s=new S(p,{readOnly:!0});try{if(O(s,"nodes")&&s.prepare("PRAGMA table_info(nodes)").all().some(o=>o.name==="cwd"))for(const o of s.prepare("SELECT cwd FROM nodes").all())f.add(o.cwd)}finally{s.close()}}const u=a(r,"scope","operations.db");if(m(u)){const s=new S(u,{readOnly:!0});try{if(O(s,"profile_projects"))for(const o of s.prepare("SELECT path FROM profile_projects").all())f.add(o.path)}finally{s.close()}}for(const s of f){const o=e.map.old.targetRoot;let l=s.startsWith(o+"/")?H(c,v(o,s)):s;for(;l!==N(l);)T(a(l,".crouter","operations.db"),W,e),l=N(l)}_(a(i),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e),s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith(".md")&&(s.includes("/memory/")||s.includes("/profiles/"))&&I(s,e),s.endsWith(".jsonl")&&s.includes("/conversations/")&&X(s,e)}),_(a(c,"user","memory"),s=>{s.endsWith(".md")&&I(s,e)}),Y(e);for(const s of e.map.dangling)e.resolutions.push(`dangling-path: ${s} names a file the new layout drops; left the stored path unchanged`);_(a(c,"user","files"),s=>{s.endsWith("/.crouter/operations.db")&&T(s,W,e)}),_(a(r,"nodes"),s=>{s.endsWith("/meta.json")&&E(s,e,o=>b(o,e)),s.endsWith("/session.ptr")&&x(s)}),_(a(r,"tickets"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))}),_(a(r,"requests"),s=>{s.endsWith(".json")&&E(s,e,o=>b(o,e))});const d=a(r,"canvas.db");if(m(d)){const s=new S(d);try{s.exec("DROP TABLE IF EXISTS layout_header_rewrites")}finally{s.close()}}}y(se,"storedPaths");function I(e,c){E(e,c,r=>{if(!r.startsWith(`---
|
|
7
7
|
`))return r;const i=r.indexOf(`
|
|
8
8
|
---`,4);return i<0?r:r.slice(0,i).replace(/^(\s*session_file:\s*)([^\n]+)$/gm,(p,u,d)=>{const s=d.match(/^(["'])(.*)\1$/),o=s?s[2]:d.trim(),l=c.map.mapPath(o);return l===o?p:`${u}${s?s[1]:""}${l}${s?s[1]:""}`})+r.slice(i)})}y(I,"rewriteMemory");function X(e,c){const r=a(c.map.old.root,"runtime","canvas.db");if(!m(r)){E(e,c,f=>{const p=f.indexOf(`
|
|
9
9
|
`),u=p<0?f:f.slice(0,p);return b(u,c)+(p<0?"":f.slice(p))});return}const i=new S(r);try{i.exec("CREATE TABLE IF NOT EXISTS layout_header_rewrites (path TEXT PRIMARY KEY, old_header TEXT NOT NULL, new_header TEXT NOT NULL)");const f=i.prepare("SELECT old_header, new_header FROM layout_header_rewrites WHERE path = ?").get(e),p=$(e,"utf8"),u=p.indexOf(`
|
|
10
10
|
`),d=u<0?p:p.slice(0,u),s=f?.new_header??b(d,c);if(f&&d!==f.old_header&&d!==s)throw new Error(`conversation header changed during migration: ${e}`);if(!f&&s!==d){const o=a(c.map.old.targetRoot,v(c.map.old.root,e)),l=Buffer.byteLength(s)-Buffer.byteLength(d);i.exec("BEGIN IMMEDIATE");try{i.prepare("INSERT INTO layout_header_rewrites (path, old_header, new_header) VALUES (?, ?, ?)").run(e,d,s),l!==0&&O(i,"sessions")&&i.prepare("UPDATE sessions SET event_offset = event_offset + ? WHERE transcript_path = ? AND event_offset > 0").run(l,o),i.exec("COMMIT")}catch(n){throw i.exec("ROLLBACK"),n}}d!==s&&E(e,c,o=>{const l=o.indexOf(`
|
|
11
|
-
`);if((l<0?o:o.slice(0,l))!==d)throw new Error(`conversation header changed during migration: ${e}`);return s+(l<0?"":o.slice(l))}),(f||s!==d)&&i.prepare("DELETE FROM layout_header_rewrites WHERE path = ?").run(e)}finally{i.close()}}y(X,"rewriteHeader");function K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}y(K,"escape");function Y(e){const c=e.bodyPaths;if(c.length===0)return;const r=G(),i=[];for(const[t,h]of c)i.push([t,h]),t.startsWith(r+A)&&i.push([`~${t.slice(r.length)}`,h.startsWith(r+A)?`~${h.slice(r.length)}`:h]);i.sort((t,h)=>h[0].length-t[0].length);const f=new RegExp(`(${i.map(([t])=>K(t)).join("|")})(?![A-Za-z0-9_-])`,"g"),p=new Map(i),{root:u,scope:d,canvas:s}=e.map.old,o=y(t=>{if(!t.endsWith(".md"))return;if(e.dryRun){const j=$(t,"utf8").match(f)?.length??0;j&&e.resolutions.push(`profile-extra-link: rewrote ${j} link(s) to moved profile files in ${t}`);return}let h=0;E(t,e,j=>j.replace(f,w=>(h++,p.get(w)))),h&&e.resolutions.push(`profile-extra-link: rewrote ${h} link(s) to moved profile files in ${t}`)},"visit"),l=y(t=>{if(m(t))for(const h of g(t))_(a(t,h,"context"),o)},"nodeContexts");if(e.dryRun){_(a(d,"memory"),o),_(a(d,"profiles"),o),l(a(s,"nodes"));return}_(a(u,"user","memory"),o);const n=a(u,"apps");if(m(n))for(const t of g(n))_(a(n,t,"memory"),o),_(a(n,t,"files","profiles"),o),l(a(n,t,"nodes"))}y(Y,"rewriteBodyPaths");export{Y as rewriteBodyPaths,se as storedPaths};
|
|
11
|
+
`);if((l<0?o:o.slice(0,l))!==d)throw new Error(`conversation header changed during migration: ${e}`);return s+(l<0?"":o.slice(l))}),(f||s!==d)&&i.prepare("DELETE FROM layout_header_rewrites WHERE path = ?").run(e)}finally{i.close()}}y(X,"rewriteHeader");function K(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}y(K,"escape");function Y(e){const c=e.bodyPaths;if(c.length===0)return;const r=G(),i=[];for(const[t,h]of c)i.push([t,h]),t.startsWith(r+A)&&i.push([`~${t.slice(r.length)}`,h.startsWith(r+A)?`~${h.slice(r.length)}`:h]);i.sort((t,h)=>h[0].length-t[0].length);const f=new RegExp(`(${i.map(([t])=>K(t)).join("|")})(?![A-Za-z0-9_-])`,"g"),p=new Map(i),{root:u,scope:d,canvas:s}=e.map.old,o=y(t=>{if(!t.endsWith(".md"))return;if(e.dryRun){const j=$(t,"utf8").match(f)?.length??0;j&&e.resolutions.push(`profile-extra-link: rewrote ${j} link(s) to moved profile files in ${t}`);return}let h=0;E(t,e,j=>j.replace(f,w=>(h++,p.get(w)))),h&&e.resolutions.push(`profile-extra-link: rewrote ${h} link(s) to moved profile files in ${t}`)},"visit"),l=y(t=>{if(m(t))for(const h of g(t))_(a(t,h,"context"),o)},"nodeContexts");if(e.dryRun){_(a(d,"memory"),o),_(a(d,"profiles"),o),l(a(s,"nodes"));return}_(a(u,"user","memory"),o);const n=a(u,"apps");if(m(n))for(const t of g(n))_(a(n,t,"memory"),o),_(a(n,t,"profiles"),o),_(a(n,t,"files","profiles"),o),l(a(n,t,"nodes"))}y(Y,"rewriteBodyPaths");export{Y as rewriteBodyPaths,se as storedPaths};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var oe=Object.defineProperty;var h=(e,t)=>oe(e,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{closeSync as se,copyFileSync as re,existsSync as u,realpathSync as ne,fsyncSync as pe,lstatSync as $,mkdirSync as B,openSync as ce,readFileSync as T,readdirSync as E,renameSync as M,rmdirSync as F,unlinkSync as D,writeFileSync as J}from"node:fs";import{execFileSync as Z}from"node:child_process";import{basename as x,dirname as R,isAbsolute as q,join as n,relative as k,resolve as C,sep as P}from"node:path";import{profileSpace as ae}from"../layout.js";import{isJunkFile as j,movePath as S,sameFile as A,setAside as O,setAsidePath as H}from"./index.js";import{rewriteBodyPaths as ie}from"./stored-paths.js";function L(e,t){Z("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe"})}h(L,"gitInRepo");function _(e,t){const{root:s,targetRoot:p}=t.map.old;return C(s,k(p,e))}h(_,"physical");function N(e,t=!1){const{old:s}=e.map,p=n(s.canvas,"canvas.db"),o=n(s.root,"runtime","canvas.db"),r=u(p)?p:o;return u(r)&&$(r).size>0?new z(r,{readOnly:!t||e.dryRun}):null}h(N,"canvasDb");function W(e){return new Map(e.prepare("SELECT node_id, grantee FROM nodes").all().map(({node_id:t,grantee:s})=>{const p=s==="user:local"?"terminal":s.startsWith("app:")?s.slice(4):"";if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(p))throw new Error(`node ${t} has no valid app`);return[t,p]}))}h(W,"nodeApps");function Y(e,t,s){return n(s.map.old.targetRoot,"apps",e,"files","profiles",t)}h(Y,"profileFiles");function G(e,t,s,p){if(!u(e))return;if(!u(t)){S(e,t,p);return}const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const d of E(e))G(n(e,d),n(t,d),n(s,d),p);F(e);return}if(o.isFile()&&r.isFile()&&A(e,t)){D(e);return}const a=_(s,p);p.dryRun||S(e,a,p),p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${a}`)}h(G,"mergeHome");function K(e,t,s,p){if(!u(e)||!u(t))return;const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const a of E(e))K(n(e,a),n(t,a),n(s,a),p);return}o.isFile()&&r.isFile()&&A(e,t)||p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${_(s,p)}`)}h(K,"previewHome");function Q(e,t,s){e.bodyPaths.some(([p])=>p===t)||e.bodyPaths.push([t,s])}h(Q,"bodyPath");function V(e){const{map:t}=e,s=[n(t.old.scope,"operations.db"),n(t.old.root,"runtime","scope","operations.db")].find(u),p=s?new z(s,{readOnly:!0}):null,o=new Map;try{if(p&&p.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='profiles'").get())for(const i of p.prepare("SELECT id, grantee FROM profiles").all())o.set(i.id,i.grantee)}finally{p?.close()}const r=new Map;for(const[i,c]of o){const w=c==null||c==="user:local"?"terminal":c.startsWith("app:")?c.slice(4):"",f=ae(w,i),y=n(t.old.storedScope,"profiles",i);t.retire(y,f.
|
|
1
|
+
var oe=Object.defineProperty;var h=(e,t)=>oe(e,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{closeSync as se,copyFileSync as re,existsSync as u,realpathSync as ne,fsyncSync as pe,lstatSync as $,mkdirSync as B,openSync as ce,readFileSync as T,readdirSync as E,renameSync as M,rmdirSync as F,unlinkSync as D,writeFileSync as J}from"node:fs";import{execFileSync as Z}from"node:child_process";import{basename as x,dirname as R,isAbsolute as q,join as n,relative as k,resolve as C,sep as P}from"node:path";import{profileSpace as ae}from"../layout.js";import{isJunkFile as j,movePath as S,sameFile as A,setAside as O,setAsidePath as H}from"./index.js";import{rewriteBodyPaths as ie}from"./stored-paths.js";function L(e,t){Z("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe"})}h(L,"gitInRepo");function _(e,t){const{root:s,targetRoot:p}=t.map.old;return C(s,k(p,e))}h(_,"physical");function N(e,t=!1){const{old:s}=e.map,p=n(s.canvas,"canvas.db"),o=n(s.root,"runtime","canvas.db"),r=u(p)?p:o;return u(r)&&$(r).size>0?new z(r,{readOnly:!t||e.dryRun}):null}h(N,"canvasDb");function W(e){return new Map(e.prepare("SELECT node_id, grantee FROM nodes").all().map(({node_id:t,grantee:s})=>{const p=s==="user:local"?"terminal":s.startsWith("app:")?s.slice(4):"";if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(p))throw new Error(`node ${t} has no valid app`);return[t,p]}))}h(W,"nodeApps");function Y(e,t,s){return n(s.map.old.targetRoot,"apps",e,"files","profiles",t)}h(Y,"profileFiles");function G(e,t,s,p){if(!u(e))return;if(!u(t)){S(e,t,p);return}const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const d of E(e))G(n(e,d),n(t,d),n(s,d),p);F(e);return}if(o.isFile()&&r.isFile()&&A(e,t)){D(e);return}const a=_(s,p);p.dryRun||S(e,a,p),p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${a}`)}h(G,"mergeHome");function K(e,t,s,p){if(!u(e)||!u(t))return;const o=$(e),r=$(t);if(o.isDirectory()&&r.isDirectory()){for(const a of E(e))K(n(e,a),n(t,a),n(s,a),p);return}o.isFile()&&r.isFile()&&A(e,t)||p.resolutions.push(`profile-home: ${t} differs from the profile's ${e}; kept the app home's copy, moved the profile's to ${_(s,p)}`)}h(K,"previewHome");function Q(e,t,s){e.bodyPaths.some(([p])=>p===t)||e.bodyPaths.push([t,s])}h(Q,"bodyPath");function V(e){const{map:t}=e,s=[n(t.old.scope,"operations.db"),n(t.old.root,"runtime","scope","operations.db")].find(u),p=s?new z(s,{readOnly:!0}):null,o=new Map;try{if(p&&p.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='profiles'").get())for(const i of p.prepare("SELECT id, grantee FROM profiles").all())o.set(i.id,i.grantee)}finally{p?.close()}const r=new Map;for(const[i,c]of o){const w=c==null||c==="user:local"?"terminal":c.startsWith("app:")?c.slice(4):"",f=ae(w,i),y=n(t.old.storedScope,"profiles",i);t.retire(y,f.dir),t.add(n(y,"memory"),f.dir),t.add(n(y,"env.json"),f.env),t.add(n(y,"home"),f.home),r.set(i,{target:f,app:w})}const a=n(t.old.scope,"profiles"),d={folders:[],junk:[],aside:[]};if(!u(a))return d;for(const i of E(a)){const c=n(a,i);if(!$(c).isDirectory()){(j(i)?d.junk:d.aside).push(c);continue}if(i===".locks"){for(const l of E(c)){const v=n(c,l);!(l.endsWith(".lock")&&$(v).isFile())&&!j(l)&&d.aside.push(v)}continue}const w=n(t.old.storedScope,"profiles",i),f=r.get(i);if(!f){const l=Y("terminal",i,e);t.add(w,l),Q(e,w,l),d.folders.push({id:i,source:c,target:null,files:l,extras:[]});continue}const y=Y(f.app,i,e),b=[];for(const l of E(c)){const v=$(n(c,l));(l==="memory"||l==="home"?v.isDirectory():l==="env.json"||l==="profile.json"||l.endsWith(".lock")?v.isFile():j(l))||(b.push(l),t.add(n(w,l),n(y,l)),Q(e,n(w,l),n(y,l)))}d.folders.push({id:i,source:c,target:f.target,files:y,extras:b})}return d}h(V,"profileFolders");function X(e,t){for(const s of e.folders){s.target||t.resolutions.push(`profile-folder: ${s.source} has no profile row; moved whole to ${_(s.files,t)}`);for(const p of s.extras)t.resolutions.push(`profile-extra: ${n(s.source,p)} moved to ${_(n(s.files,p),t)}`)}for(const s of e.junk)t.resolutions.push(`profile-leftover: deleted ${s} (not profile data)`);for(const s of e.aside)t.resolutions.push(`profile-leftover: ${s} is not a profile; moved to ${H(t,"profiles",x(s))}`)}h(X,"profileLines");function Fe(e){const{map:t}=e;S(n(t.old.scope,"memory"),n(t.old.root,"user","memory"),e);const s=N(e);if(s)try{for(const[r,a]of W(s)){const d=n(t.old.root,"apps",a,"memory","nodes",r);S(n(t.old.root,"apps",a,"nodes",r,"context","memory"),d,e),S(n(t.old.canvas,"nodes",r,"context","memory"),d,e)}}finally{s.close()}const p=V(e);X(p,e);for(const{source:r,target:a,files:d,extras:i}of p.folders){if(!a){S(r,_(d,e),e,!0);continue}for(const c of i)S(n(r,c),_(n(d,c),e),e);S(n(r,"memory"),_(a.dir,e),e),S(n(r,"env.json"),_(a.env,e),e),G(n(r,"home"),_(a.home,e),n(d,"home"),e);for(const c of E(r))D(n(r,c));F(r),e.moved++,e.changes.push(`${r} (removed)`)}for(const r of p.junk)D(r);for(const r of p.aside)O(r,"profiles",e);const o=n(t.old.scope,"profiles");if(u(o)){const r=n(o,".locks");if(u(r)){for(const a of E(r))D(n(r,a));F(r)}F(o)}}h(Fe,"memoryAndProfiles");function de(e,t,s,p){if(u(e)){if(!$(e).isFile())throw new Error(`session path is not a file: ${e}`);if(B(R(t),{recursive:!0}),u(t)){if($(t).isFile()&&A(e,t))return;const o=O(t,"replaced",s,k(s.map.old.root,t));s.resolutions.push(`stray-destination: ${t} predates the migration; moved it to ${o} and put ${e} in its place`)}if(p){const o=n(R(t),`.${x(t)}.migrating`);u(o)&&D(o),re(e,o);const r=ce(o,"r");try{pe(r)}finally{se(r)}if(!A(e,o))throw new Error(`session copy verification failed: ${e}`);M(o,t),s.moved++,s.changes.push(`${e} -> ${t} (source retained)`);return}M(e,t),s.moved++,s.changes.push(`${e} -> ${t}`)}}h(de,"moveSession");function le(e,t,s){const p=new Set(t.prepare("SELECT s.transcript_path AS path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.unbound_at IS NULL AND n.status IN ('active', 'idle') AND s.transcript_path IS NOT NULL").all().map(r=>r.path)),o=e.dryRun?null:t.prepare("UPDATE sessions SET transcript_path = NULL WHERE transcript_path = ?");for(const r of s)if(!(u(r.source)||u(_(r.destination,e)))){if(p.has(r.transcript_path)){e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing but is a live node's current session; kept its path`);continue}o?.run(r.transcript_path),e.resolutions.push(`lost-transcript: ${r.transcript_path} is missing from both paths; cleared the session's transcript path`)}}h(le,"lostTranscripts");function fe(e){const t=N(e,!0);if(t)try{const s=W(t),p=t.prepare("SELECT session_id, node_id, transcript_path FROM sessions WHERE transcript_path IS NOT NULL ORDER BY session_id, (unbound_at IS NULL) DESC, created_at DESC, rowid DESC").all(),o=new Map,r=new Map,a=new Map;for(const c of p){o.has(c.session_id)||o.set(c.session_id,c.node_id),a.set(c.transcript_path,(a.get(c.transcript_path)??0)+1);const w=r.get(c.transcript_path)??new Set;w.add(c.session_id),r.set(c.transcript_path,w)}const d=new Set,i=[];for(const{session_id:c,node_id:w,transcript_path:f}of p){if(d.has(f))continue;if(d.add(f),r.get(f).size!==1)throw new Error(`two conversations share a transcript: ${f}`);const y=a.get(f)>1?o.get(c):w,b=s.get(y);if(!b)throw new Error(`session belongs to unknown node: ${y}`);if(!q(f))throw new Error(`session path is not absolute: ${f}`);const l=n(e.map.old.targetRoot,"apps",b,"conversations",y,x(f));if(f===l)continue;const v=f===e.map.old.storedAgent||f.startsWith(e.map.old.storedAgent+P),m=v?n(e.map.old.agent,k(e.map.old.storedAgent,f)):f;i.push({transcript_path:f,destination:l,source:m,retain:process.platform==="linux"&&v})}le(e,t,i);for(const{transcript_path:c,destination:w}of i)e.map.add(c,w);if(e.dryRun)return;for(const{destination:c,source:w,retain:f}of i)de(w,_(c,e),e,f)}finally{t.close()}}h(fe,"conversations");function De(e){if(process.platform!=="linux")return;const t=N(e);if(t)try{const s=t.prepare("SELECT node_id, path, repo_root FROM worktrees").all(),p=W(t);for(const o of s){const r=e.map.mapPath(o.repo_root);if(r===o.repo_root)continue;const a=p.get(o.node_id);if(!a)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);const d=_(n(e.map.old.targetRoot,"apps",a,"nodes",o.node_id,"worktree"),e);if(!u(d))continue;L(_(r,e),["worktree","repair",d]);const i=o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path;I(i,d,e)}}finally{t.close()}}h(De,"repairMovedRepositories");function I(e,t,s){const p=h(o=>{for(const r of E(o)){const a=n(o,r);if(r===".git"&&a!==n(t,".git")&&$(a).isFile()){const d=T(a,"utf8");if(!d.startsWith("gitdir: "))throw new Error(`invalid submodule git link: ${a}`);const i=d.slice(8).trim(),c=C(R(a),i),w=n(e,k(t,a)),f=C(R(w),i),y=u(c)?c:f;if(!u(y))throw new Error(`submodule git directory missing: ${w}`);const b=s?.map.mapPath(y)??y,l=s&&b!==y?_(b,s):y;if(!u(l))throw new Error(`moved submodule git directory missing: ${l}`);c!==l&&J(a,`gitdir: ${k(R(a),l)}
|
|
2
2
|
`);const v=n(l,"config"),m=T(v,"utf8");if(!/^\s*worktree\s*=.*$/m.test(m))throw new Error(`submodule has no worktree setting: ${v}`);const te=JSON.stringify(k(l,R(a))),U=m.replace(/^(\s*worktree\s*=).*$/m,`$1 ${te}`);U!==m&&J(v,U)}else r!==".git"&&$(a).isDirectory()&&p(a)}},"visit");p(t)}h(I,"repairSubmoduleLinks");function ue(e,t){return Z("git",["-c",`safe.directory=${e}`,"-C",e,...t],{stdio:"pipe",encoding:"utf8"})}h(ue,"gitOut");function g(e){try{return ne(e)}catch{return C(e)}}h(g,"real");function he(e,t){try{const s=g(t);return ue(e,["worktree","list","--porcelain"]).split(`
|
|
3
3
|
`).some(p=>p.startsWith("worktree ")&&g(p.slice(9))===s)}catch{return!1}}h(he,"registered");function we(e,t){if(!u(e))return!1;try{const s=T(n(t,".git"),"utf8");return s.startsWith("gitdir: ")?u(C(t,s.slice(8).trim())):!1}catch{return!1}}h(we,"repairable");function ee(e,t,s){s.dryRun||t.state!=="open"&&t.cleanup_state==="complete"||e.prepare("UPDATE worktrees SET state = CASE WHEN state = 'open' THEN 'closed' ELSE state END, cleanup_state = 'complete', closed_at = COALESCE(closed_at, ?) WHERE node_id = ?").run(new Date().toISOString(),t.node_id)}h(ee,"closeRow");function ye(e){const t=N(e,!0);if(t){try{const s=W(t),p=t.prepare("SELECT node_id, state, cleanup_state, path, repo_root FROM worktrees").all();for(const o of p){const r=s.get(o.node_id);if(!r)throw new Error(`worktree belongs to unknown node: ${o.node_id}`);if(!q(o.path))throw new Error(`worktree path is not absolute: ${o.path}`);const a=n(e.map.old.targetRoot,"apps",r,"nodes",o.node_id,"worktree");if(o.path===a)continue;const d=o.path===e.map.old.storedCanvas||o.path.startsWith(e.map.old.storedCanvas+P)?n(e.map.old.canvas,k(e.map.old.storedCanvas,o.path)):o.path,i=_(a,e);if(!u(d)){e.map.add(o.path,a),u(i)?!e.dryRun&&u(o.repo_root)&&(L(o.repo_root,["worktree","repair",i]),I(d,i)):o.state!=="open"&&o.cleanup_state==="complete"||(ee(t,o,e),e.resolutions.push(`missing-worktree: ${o.path} (node ${o.node_id}) is gone; closed its row`));continue}if(!he(o.repo_root,d))if(o.state==="open"&&we(o.repo_root,d))e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}) is not registered in ${o.repo_root}; relinked it with git worktree repair`),e.dryRun||L(o.repo_root,["worktree","repair",d]);else{const c=H(e,"worktrees",x(d));e.resolutions.push(`unregistered-worktree: ${o.path} (node ${o.node_id}${o.state==="open"?"":`, ${o.state}`}) is not a worktree of ${u(o.repo_root)?o.repo_root:`the missing repository ${o.repo_root}`}; ${o.state==="open"?"closed its row and ":""}moved the folder to ${c}`),e.map.redirect(o.path,n(e.map.old.targetRoot,k(e.map.old.root,c))),e.dryRun||(O(d,"worktrees",e),ee(t,o,e));continue}if(e.map.add(o.path,a),u(i)){const c=H(e,"replaced",k(e.map.old.root,i));e.resolutions.push(`stray-destination: ${i} predates the migration; moved it to ${c} and put the worktree ${d} in its place`),e.dryRun||O(i,"replaced",e,k(e.map.old.root,i))}if(!e.dryRun){B(R(i),{recursive:!0});try{L(o.repo_root,["worktree","move",d,i])}catch(c){if(!String(c.stderr??"").includes("submodule"))throw c;M(d,i),L(o.repo_root,["worktree","repair",i])}I(d,i),e.moved++,e.changes.push(`${d} -> ${i} (git worktree move)`)}}}finally{t.close()}e.dryRun||_e(e)}}h(ye,"worktrees");function _e(e){const t=n(e.map.old.canvas,"nodes");if(u(t)){for(const s of E(t)){const p=n(t,s);$(p).isDirectory()&&E(p).length===0&&F(p)}E(t).length===0&&F(t)}}h(_e,"pruneOldNodeFolders");function Ce(e){ye(e);const t=V(e);X(t,e);for(const{source:s,target:p,files:o}of t.folders)p&&K(n(s,"home"),_(p.home,e),n(o,"home"),e);fe(e),ie(e)}h(Ce,"previewStores");export{fe as conversations,Fe as memoryAndProfiles,Ce as previewStores,V as profileFolders,De as repairMovedRepositories,ye as worktrees};
|
package/dist/core/layout.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export declare function userRoot(): string;
|
|
|
6
6
|
export declare function appsRoot(): string;
|
|
7
7
|
export declare function secretsDir(): string;
|
|
8
8
|
export declare function profileSpace(app: string, id: string): {
|
|
9
|
-
|
|
9
|
+
dir: string;
|
|
10
10
|
env: string;
|
|
11
11
|
home: string;
|
|
12
12
|
};
|
|
@@ -15,7 +15,7 @@ export declare function layoutVersionFile(): string;
|
|
|
15
15
|
export declare function userFilesRoot(): string;
|
|
16
16
|
export declare function appSpace(app: string): {
|
|
17
17
|
root: string;
|
|
18
|
-
|
|
18
|
+
profiles: string;
|
|
19
19
|
conversations: string;
|
|
20
20
|
nodes: string;
|
|
21
21
|
files: string;
|
package/dist/core/layout.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var $=Object.defineProperty;var n=(r,o)=>$(r,"name",{value:o,configurable:!0});import{existsSync as i,mkdirSync as d,readFileSync as S,statSync as R}from"node:fs";import{homedir as _,userInfo as g}from"node:os";import{basename as x,dirname as f,isAbsolute as A,join as t,resolve as p}from"node:path";import{envHomeOverride as T}from"../shared/env.js";import{readConfig as O}from"./config.js";import{publishFileExclusive as z,syncDirectory as h}from"./fs-utils.js";const
|
|
2
|
-
`,384)}n(W,"initializeEmptyLayout");export{
|
|
1
|
+
var $=Object.defineProperty;var n=(r,o)=>$(r,"name",{value:o,configurable:!0});import{existsSync as i,mkdirSync as d,readFileSync as S,statSync as R}from"node:fs";import{homedir as _,userInfo as g}from"node:os";import{basename as x,dirname as f,isAbsolute as A,join as t,resolve as p}from"node:path";import{envHomeOverride as T}from"../shared/env.js";import{readConfig as O}from"./config.js";import{publishFileExclusive as z,syncDirectory as h}from"./fs-utils.js";const l="1";function s(){const r=p(T()||(process.platform==="linux"?"/":t(_(),".crouter")));if(C()&&r===L())throw new Error(`refusing to use the account's real crouter root ${r} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return r}n(s,"layoutRoot");function C(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}n(C,"runningUnderNodeTest");let c;function L(){if(c===void 0)try{c=p(g().homedir,".crouter")}catch{c=null}return c}n(L,"accountLayoutRoot");function u(){return t(s(),"runtime")}n(u,"runtimeRoot");function v(){return t(s(),"user")}n(v,"userRoot");function w(){return t(s(),"apps")}n(w,"appsRoot");function y(){return t(u(),"secrets")}n(y,"secretsDir");function Y(r,o){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(o))throw new Error(`invalid profile id: ${o}`);const e=m(r);return{dir:t(e.profiles,o),env:t(y(),"env",x(e.root),o),home:e.home}}n(Y,"profileSpace");function E(){return process.platform==="linux"?"/run/crtr":u()}n(E,"socketDir");function a(){return t(u(),"layout")}n(a,"layoutVersionFile");function k(){const r=O("user").paths?.user_files??(process.platform==="linux"?t(v(),"files"):f(s()));if(!A(r))throw new Error("paths.user_files must be absolute");return p(r)}n(k,"userFilesRoot");function m(r){const o=r.startsWith("app:")?r.slice(4):r;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o)||o==="."||o==="..")throw new Error(`invalid app id: ${r}`);const e=t(w(),o);return{root:e,profiles:t(e,"profiles"),conversations:t(e,"conversations"),nodes:t(e,"nodes"),files:t(e,"files"),home:t(e,"home"),cache:t(e,"cache")}}n(m,"appSpace");function q(r,o){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o))throw new Error(`invalid cron id: ${o}`);return t(m(r).root,"crons",o)}n(q,"cronFolder");function P(r){const o=m(r);return process.platform==="linux"?o.home:x(o.root)==="terminal"?k():o.home}n(P,"appProcessHome");function F(r){const o=Array.from(r.subarray(0,32),e=>e===92?"\\\\":e===34?'\\"':e===10?"\\n":e===13?"\\r":e===9?"\\t":e>=32&&e<127?String.fromCharCode(e):`\\x${e.toString(16).padStart(2,"0")}`).join("");return`${r.length} bytes, preview "${o}"${r.length>32?"\u2026":""}`}n(F,"describeLayoutMarker");function M(r){const o=S(r);if(o.toString("utf8").trim()!==l)throw new Error(`unsupported runtime layout version: ${r} holds ${F(o)}; expected "${l}"`)}n(M,"assertSupportedLayoutMarker");function N(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(i(a()))return M(a()),!1;const r=s(),o=process.platform==="linux"&&r==="/"&&i("/volume")?"/volume":r;return i(t(o,"canvas"))||i(t(o,"canvas.db"))?!0:i(t(u(),"canvas.db"))}n(N,"layoutNeedsMigration");function W(){if(N())throw new Error("layout_migration_required");for(const r of[u(),v(),w(),y()]){const o=d(r,{recursive:!0,mode:448});if(o!==void 0){for(let e=r;h(e),e!==o;e=f(e));h(f(o))}}if(d(E(),{recursive:!0,mode:493}),process.platform==="linux"&&(R(E()).mode&511)!==493)throw new Error("launcher socket directory must be mode 0755");i(a())||z(a(),`${l}
|
|
2
|
+
`,384)}n(W,"initializeEmptyLayout");export{l as LAYOUT_VERSION,P as appProcessHome,m as appSpace,w as appsRoot,M as assertSupportedLayoutMarker,q as cronFolder,F as describeLayoutMarker,W as initializeEmptyLayout,N as layoutNeedsMigration,s as layoutRoot,a as layoutVersionFile,Y as profileSpace,u as runtimeRoot,y as secretsDir,E as socketDir,k as userFilesRoot,v as userRoot};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ProfileManifest } from '../../types.js';
|
|
2
2
|
import type { DeliveryLimits, ProfileProject, ProfileProjectMemory } from '../../api/dto/profiles.js';
|
|
3
3
|
export declare const ROOT_PROFILE_ID = "root-00000000";
|
|
4
|
-
export declare function
|
|
4
|
+
export declare function profileDir(profileId: string): string;
|
|
5
5
|
export declare function assertProfileProjects(entries: unknown): asserts entries is ProfileProject[];
|
|
6
6
|
export declare function assertDeliveryLimits(value: unknown): asserts value is DeliveryLimits;
|
|
7
7
|
export interface ProfileEntry {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var o=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{randomUUID as G}from"node:crypto";import{existsSync as W,realpathSync as b,rmSync as S,statSync as B}from"node:fs";import{join as A,resolve as E}from"node:path";import{SCHEMA_VERSION as R}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as O}from"../../api/dto/profiles.js";import{userScopeRoot as c}from"../scope.js";import{ensureDir as k,nowIso as m}from"../fs-utils.js";import{deleteStoredProfile as Q,getStoredProfile as h,insertStoredProfile as M,listStoredProfiles as X,pausedProfileIds as I,profilePaused as ee,updateStoredProfile as te}from"../scoped-state/profiles.js";import{usage as f,notFound as d,ambiguous as D,general as L}from"../errors.js";import{withExclusiveDirectoryLock as re}from"../exclusive-lock.js";import{fuzzyMatchProfile as ne}from"./fuzzy-match.js";const N=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,p="root-00000000",oe="root";function P(e){return e.grantee??"app:terminal"}o(P,"profileApp");function w(e,t){k(g(P(t),e).memory)}o(w,"scaffoldProfile");function y(e){if(!N.test(e))throw f(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}o(y,"assertSafeProfileId");function Ee(e){y(e);const t=h(c(),e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return g(P(t.manifest),e).memory}o(Ee,"profileMemoryDir");function z(e){if(!Array.isArray(e))throw f("projects must be an array of {path} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw f(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"}.'});const{path:r}=t;if(typeof r!="string"||r.trim()==="")throw f(`project entry has no path: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a non-empty directory path."})}}o(z,"assertProfileProjects");function ie(e){const t=O.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw f("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[r,n]of Object.entries(e)){if(r.trim()==="")throw f("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof n!="string"||!O.includes(n))throw f(`invalid delivery limit for ${r}: ${JSON.stringify(n)}`,{received:String(n),field:"delivery_limits",next:`Set ${r} to one of: ${t}.`})}}o(ie,"assertDeliveryLimits");function ae(){return{entries:X(c()),unreadableIds:[]}}o(ae,"enumerateProfiles");function x(){return ae().entries}o(x,"listProfiles");function se(e){const t=x(),r=J(t,e,$);return r?{kind:"resolved",entry:r}:{kind:"absent"}}o(se,"lookupProfile");function C(e){y(e);const t=h(c(),e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(C,"loadExactProfileManifest");const $=o(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function J(e,t,r){if(N.test(t)){const i=e.find(a=>r(a).profileId===t);if(i!==void 0)return i}const n=e.filter(i=>r(i).name===t);if(n.length===1)return n[0];if(n.length>1){const i=n.map(a=>r(a).profileId);throw D(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}o(J,"findExactProfile");function T(e,t,r){const n=e.map(i=>`${r(i).profileId} (${r(i).name})`);return d(`profile not found: ${t}`,{received:t,available:n,next:n.length>0?`Re-run with one of the profiles on this host: ${n.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}o(T,"profileNotFound");function fe(e){const t=se(e);if(t.kind==="resolved")return t.entry;throw T(x(),e,$)}o(fe,"loadProfileManifest");function Re(e){return le(x(),e,$)}o(Re,"resolveProfileOperand");function le(e,t,r){const n=J(e,t,r);if(n!==null)return n;const{match:i,tied:a}=ne(t,e.map(r));if(i!==null){const s=e.find(l=>r(l).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${r(s).name} (${r(s).profileId})`),s}if(a.length>1){const s=a.map(l=>`${l.profileId} (${l.name})`);throw D(`"${t}" is equally close to ${a.length} profiles: ${s.join(", ")}`,{received:t,candidates:a.map(l=>l.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw T(e,t,r)}o(le,"matchProfileOperand");function U(){return A(c(),"profile-locks")}o(U,"locksDir");function v(e,t){return y(e),k(U()),re(A(U(),`${e}.lock`),t,{timeoutError:o(()=>L(`timed out waiting for the profile lock: ${e}`,{next:"Retry \u2014 another `crtr profile` command may be running concurrently on this profile."}),"timeoutError")})}o(v,"withProfileManifestLock");function F(e){const t=E(e);if(!W(t)||!B(t).isDirectory())throw f(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return b(t)}catch{return t}}o(F,"resolveExistingProjectDir");function K(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}o(K,"dedupeProjects");function ce(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}o(ce,"slugify");function ue(e){const t=ce(e);for(let r=0;r<20;r++){const n=G().replace(/-/g,"").slice(0,8),i=`${t}-${n}`;if(h(c(),i)===null)return i}throw L(`failed to generate a unique profile id for "${e}" after 20 attempts`)}o(ue,"generateProfileId");function Oe(){return v(p,()=>{const e=h(c(),p);if(e!==null)return w(p,e.manifest),e;const t={schema_version:R,name:oe,projects:[],grantee:"app:terminal",paused_at:null,created_at:m(),last_used_at:m()};return w(p,t),M(c(),{profileId:p,manifest:t}),{profileId:p,manifest:t}})}o(Oe,"ensureRootProfile");const q=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function H(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}o(H,"metadataEnvName");function _(e){if(typeof e!="object"||e===null||Array.isArray(e))throw f("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[r,n]of Object.entries(e)){if(!q.test(r))throw f(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw f(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw f(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=H(r),a=t.get(i);if(a!==void 0)throw f(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,r)}}o(_,"assertProfileMetadata");function Z(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,i]of Object.entries(e)){if(typeof i!="string"||!q.test(n)||i.includes("\0"))continue;const a=H(n);r.has(a)||(r.add(a),t[n]=i)}return t}o(Z,"sanitizeProfileMetadata");function de(e,t=[],r={}){const n=e.trim();if(n==="")throw f("profile name must not be empty");r.metadata!==void 0&&_(r.metadata),z(t);const i=K(t.map(s=>({path:F(s.path)}))),a=ue(n);return v(a,()=>{const s={schema_version:R,name:n,projects:i,paused_at:null,...r.grantee===void 0?{}:{grantee:r.grantee},...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:m(),last_used_at:null};return w(a,s),M(c(),{profileId:a,manifest:s}),{profileId:a,manifest:s}})}o(de,"createProfile");function ke(e){if(!e.startsWith("app:")||e.length<=4)throw f("an app grantee is required");const t=`app-${e.slice(4)}`,r=x().filter(n=>n.manifest.name===t&&n.manifest.grantee===e);if(r.length>1)throw new Error(`duplicate default profile for ${e}`);return r[0]?r[0]:de(t,[],{grantee:e})}o(ke,"ensureAppProfile");function V(e){if(y(e),h(c(),e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(V,"requireExistingProfile");function u(e,t){return V(e),v(e,()=>{const r=te(c(),e,t);if(r===null)throw d(`profile not found: ${e}`,{received:e});return r})}o(u,"mutateManifest");function Me(e){return u(e,t=>({...t,last_used_at:m()}))}o(Me,"updateProfileLastUsed");function pe(e){if(e==null||e==="")return null;try{return fe(e)}catch{return null}}o(pe,"loadProfileManifestOrNull");function De(e){if(e==null||e==="")return!1;try{return y(e),ee(c(),e)}catch{return!1}}o(De,"isProfilePaused");function Le(){return I(c())}o(Le,"pausedCanvasProfiles");function me(e){if(e.manifest.paused_at!==null)throw f(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}o(me,"assertProfileEntryActive");function Ne(e){const t=pe(e);return t===null?null:(me(t),t)}o(Ne,"assertProfileActive");function ze(e){return u(e,t=>({...t,paused_at:t.paused_at??m()}))}o(ze,"pauseProfile");function Ce(e){let t=null;return{...u(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}o(Ce,"resumeProfile");function Je(e,t){return u(e,r=>({...r,default_kind:t}))}o(Je,"setProfileDefaultKind");function Te(e,t,r=[]){return _(t),u(e,n=>{const i={...Z(n.metadata),...t};for(const l of r)delete i[l];_(i);const{metadata:a,...s}=n;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}o(Te,"updateProfileMetadata");function Ue(e){if(e===null||e==="")return{};try{return Z(C(e).manifest.metadata)}catch{return{}}}o(Ue,"readProfileMetadata");function Fe(e,t){const r=t.trim();if(r==="")throw f("profile name must not be empty");return u(e,i=>({...i,name:r}))}o(Fe,"renameProfile");function Ke(e,t){z([{path:t}]);const r=F(t);return u(e,i=>({...i,projects:K([...i.projects,{path:r}])}))}o(Ke,"addProfileProject");function qe(e,t,r){return ie({[t]:r}),u(e,n=>{const{[t]:i,...a}=n.delivery_limits??{},s=r==="content"?a:{...a,[t]:r},{delivery_limits:l,...j}=n;return Object.keys(s).length===0?j:{...j,delivery_limits:s}})}o(qe,"setProfileDeliveryLimit");function He(e,t){const r=E(t);let n=r;try{n=b(r)}catch{}return u(e,a=>{const s=a.projects.filter(l=>l.path!==n&&l.path!==r);if(s.length===a.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(l=>l.path).join(", "):"(none)"}.`});return{...a,projects:s}})}o(He,"removeProfileProject");function Ze(e){V(e),v(e,()=>{const t=g(P(C(e).manifest),e);if(!Q(c(),e))throw d(`profile not found: ${e}`,{received:e});S(t.memory,{recursive:!0,force:!0}),S(t.env,{force:!0})})}o(Ze,"deleteProfile");export{p as ROOT_PROFILE_ID,Ke as addProfileProject,ie as assertDeliveryLimits,Ne as assertProfileActive,me as assertProfileEntryActive,_ as assertProfileMetadata,z as assertProfileProjects,de as createProfile,Ze as deleteProfile,ke as ensureAppProfile,Oe as ensureRootProfile,De as isProfilePaused,x as listProfiles,C as loadExactProfileManifest,fe as loadProfileManifest,se as lookupProfile,le as matchProfileOperand,H as metadataEnvName,ze as pauseProfile,Le as pausedCanvasProfiles,Ee as profileMemoryDir,Ue as readProfileMetadata,He as removeProfileProject,Fe as renameProfile,Re as resolveProfileOperand,Ce as resumeProfile,Z as sanitizeProfileMetadata,Je as setProfileDefaultKind,qe as setProfileDeliveryLimit,Me as updateProfileLastUsed,Te as updateProfileMetadata,v as withProfileManifestLock};
|
|
1
|
+
var Y=Object.defineProperty;var o=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{randomUUID as G}from"node:crypto";import{existsSync as W,realpathSync as b,rmSync as S,statSync as B}from"node:fs";import{join as A,resolve as E}from"node:path";import{SCHEMA_VERSION as R}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as O}from"../../api/dto/profiles.js";import{userScopeRoot as c}from"../scope.js";import{ensureDir as k,nowIso as m}from"../fs-utils.js";import{deleteStoredProfile as Q,getStoredProfile as h,insertStoredProfile as M,listStoredProfiles as X,pausedProfileIds as I,profilePaused as ee,updateStoredProfile as te}from"../scoped-state/profiles.js";import{usage as f,notFound as d,ambiguous as D,general as L}from"../errors.js";import{withExclusiveDirectoryLock as re}from"../exclusive-lock.js";import{fuzzyMatchProfile as ne}from"./fuzzy-match.js";const N=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,p="root-00000000",oe="root";function P(e){return e.grantee??"app:terminal"}o(P,"profileApp");function w(e,t){k(g(P(t),e).dir)}o(w,"scaffoldProfile");function y(e){if(!N.test(e))throw f(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}o(y,"assertSafeProfileId");function Ee(e){y(e);const t=h(c(),e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return g(P(t.manifest),e).dir}o(Ee,"profileDir");function z(e){if(!Array.isArray(e))throw f("projects must be an array of {path} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw f(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"}.'});const{path:r}=t;if(typeof r!="string"||r.trim()==="")throw f(`project entry has no path: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a non-empty directory path."})}}o(z,"assertProfileProjects");function ie(e){const t=O.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw f("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[r,n]of Object.entries(e)){if(r.trim()==="")throw f("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof n!="string"||!O.includes(n))throw f(`invalid delivery limit for ${r}: ${JSON.stringify(n)}`,{received:String(n),field:"delivery_limits",next:`Set ${r} to one of: ${t}.`})}}o(ie,"assertDeliveryLimits");function ae(){return{entries:X(c()),unreadableIds:[]}}o(ae,"enumerateProfiles");function x(){return ae().entries}o(x,"listProfiles");function se(e){const t=x(),r=J(t,e,$);return r?{kind:"resolved",entry:r}:{kind:"absent"}}o(se,"lookupProfile");function C(e){y(e);const t=h(c(),e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(C,"loadExactProfileManifest");const $=o(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function J(e,t,r){if(N.test(t)){const i=e.find(a=>r(a).profileId===t);if(i!==void 0)return i}const n=e.filter(i=>r(i).name===t);if(n.length===1)return n[0];if(n.length>1){const i=n.map(a=>r(a).profileId);throw D(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}o(J,"findExactProfile");function T(e,t,r){const n=e.map(i=>`${r(i).profileId} (${r(i).name})`);return d(`profile not found: ${t}`,{received:t,available:n,next:n.length>0?`Re-run with one of the profiles on this host: ${n.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}o(T,"profileNotFound");function fe(e){const t=se(e);if(t.kind==="resolved")return t.entry;throw T(x(),e,$)}o(fe,"loadProfileManifest");function Re(e){return le(x(),e,$)}o(Re,"resolveProfileOperand");function le(e,t,r){const n=J(e,t,r);if(n!==null)return n;const{match:i,tied:a}=ne(t,e.map(r));if(i!==null){const s=e.find(l=>r(l).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${r(s).name} (${r(s).profileId})`),s}if(a.length>1){const s=a.map(l=>`${l.profileId} (${l.name})`);throw D(`"${t}" is equally close to ${a.length} profiles: ${s.join(", ")}`,{received:t,candidates:a.map(l=>l.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw T(e,t,r)}o(le,"matchProfileOperand");function U(){return A(c(),"profile-locks")}o(U,"locksDir");function v(e,t){return y(e),k(U()),re(A(U(),`${e}.lock`),t,{timeoutError:o(()=>L(`timed out waiting for the profile lock: ${e}`,{next:"Retry \u2014 another `crtr profile` command may be running concurrently on this profile."}),"timeoutError")})}o(v,"withProfileManifestLock");function F(e){const t=E(e);if(!W(t)||!B(t).isDirectory())throw f(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return b(t)}catch{return t}}o(F,"resolveExistingProjectDir");function K(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}o(K,"dedupeProjects");function ce(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}o(ce,"slugify");function ue(e){const t=ce(e);for(let r=0;r<20;r++){const n=G().replace(/-/g,"").slice(0,8),i=`${t}-${n}`;if(h(c(),i)===null)return i}throw L(`failed to generate a unique profile id for "${e}" after 20 attempts`)}o(ue,"generateProfileId");function Oe(){return v(p,()=>{const e=h(c(),p);if(e!==null)return w(p,e.manifest),e;const t={schema_version:R,name:oe,projects:[],grantee:"app:terminal",paused_at:null,created_at:m(),last_used_at:m()};return w(p,t),M(c(),{profileId:p,manifest:t}),{profileId:p,manifest:t}})}o(Oe,"ensureRootProfile");const q=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function H(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}o(H,"metadataEnvName");function _(e){if(typeof e!="object"||e===null||Array.isArray(e))throw f("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[r,n]of Object.entries(e)){if(!q.test(r))throw f(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw f(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw f(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=H(r),a=t.get(i);if(a!==void 0)throw f(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,r)}}o(_,"assertProfileMetadata");function Z(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,i]of Object.entries(e)){if(typeof i!="string"||!q.test(n)||i.includes("\0"))continue;const a=H(n);r.has(a)||(r.add(a),t[n]=i)}return t}o(Z,"sanitizeProfileMetadata");function de(e,t=[],r={}){const n=e.trim();if(n==="")throw f("profile name must not be empty");r.metadata!==void 0&&_(r.metadata),z(t);const i=K(t.map(s=>({path:F(s.path)}))),a=ue(n);return v(a,()=>{const s={schema_version:R,name:n,projects:i,paused_at:null,...r.grantee===void 0?{}:{grantee:r.grantee},...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:m(),last_used_at:null};return w(a,s),M(c(),{profileId:a,manifest:s}),{profileId:a,manifest:s}})}o(de,"createProfile");function ke(e){if(!e.startsWith("app:")||e.length<=4)throw f("an app grantee is required");const t=`app-${e.slice(4)}`,r=x().filter(n=>n.manifest.name===t&&n.manifest.grantee===e);if(r.length>1)throw new Error(`duplicate default profile for ${e}`);return r[0]?r[0]:de(t,[],{grantee:e})}o(ke,"ensureAppProfile");function V(e){if(y(e),h(c(),e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(V,"requireExistingProfile");function u(e,t){return V(e),v(e,()=>{const r=te(c(),e,t);if(r===null)throw d(`profile not found: ${e}`,{received:e});return r})}o(u,"mutateManifest");function Me(e){return u(e,t=>({...t,last_used_at:m()}))}o(Me,"updateProfileLastUsed");function pe(e){if(e==null||e==="")return null;try{return fe(e)}catch{return null}}o(pe,"loadProfileManifestOrNull");function De(e){if(e==null||e==="")return!1;try{return y(e),ee(c(),e)}catch{return!1}}o(De,"isProfilePaused");function Le(){return I(c())}o(Le,"pausedCanvasProfiles");function me(e){if(e.manifest.paused_at!==null)throw f(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}o(me,"assertProfileEntryActive");function Ne(e){const t=pe(e);return t===null?null:(me(t),t)}o(Ne,"assertProfileActive");function ze(e){return u(e,t=>({...t,paused_at:t.paused_at??m()}))}o(ze,"pauseProfile");function Ce(e){let t=null;return{...u(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}o(Ce,"resumeProfile");function Je(e,t){return u(e,r=>({...r,default_kind:t}))}o(Je,"setProfileDefaultKind");function Te(e,t,r=[]){return _(t),u(e,n=>{const i={...Z(n.metadata),...t};for(const l of r)delete i[l];_(i);const{metadata:a,...s}=n;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}o(Te,"updateProfileMetadata");function Ue(e){if(e===null||e==="")return{};try{return Z(C(e).manifest.metadata)}catch{return{}}}o(Ue,"readProfileMetadata");function Fe(e,t){const r=t.trim();if(r==="")throw f("profile name must not be empty");return u(e,i=>({...i,name:r}))}o(Fe,"renameProfile");function Ke(e,t){z([{path:t}]);const r=F(t);return u(e,i=>({...i,projects:K([...i.projects,{path:r}])}))}o(Ke,"addProfileProject");function qe(e,t,r){return ie({[t]:r}),u(e,n=>{const{[t]:i,...a}=n.delivery_limits??{},s=r==="content"?a:{...a,[t]:r},{delivery_limits:l,...j}=n;return Object.keys(s).length===0?j:{...j,delivery_limits:s}})}o(qe,"setProfileDeliveryLimit");function He(e,t){const r=E(t);let n=r;try{n=b(r)}catch{}return u(e,a=>{const s=a.projects.filter(l=>l.path!==n&&l.path!==r);if(s.length===a.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(l=>l.path).join(", "):"(none)"}.`});return{...a,projects:s}})}o(He,"removeProfileProject");function Ze(e){V(e),v(e,()=>{const t=g(P(C(e).manifest),e);if(!Q(c(),e))throw d(`profile not found: ${e}`,{received:e});S(t.dir,{recursive:!0,force:!0}),S(t.env,{force:!0})})}o(Ze,"deleteProfile");export{p as ROOT_PROFILE_ID,Ke as addProfileProject,ie as assertDeliveryLimits,Ne as assertProfileActive,me as assertProfileEntryActive,_ as assertProfileMetadata,z as assertProfileProjects,de as createProfile,Ze as deleteProfile,ke as ensureAppProfile,Oe as ensureRootProfile,De as isProfilePaused,x as listProfiles,C as loadExactProfileManifest,fe as loadProfileManifest,se as lookupProfile,le as matchProfileOperand,H as metadataEnvName,ze as pauseProfile,Le as pausedCanvasProfiles,Ee as profileDir,Ue as readProfileMetadata,He as removeProfileProject,Fe as renameProfile,Re as resolveProfileOperand,Ce as resumeProfile,Z as sanitizeProfileMetadata,Je as setProfileDefaultKind,qe as setProfileDeliveryLimit,Me as updateProfileLastUsed,Te as updateProfileMetadata,v as withProfileManifestLock};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Profile folders used to live at `<app space>/memory/profiles/<id>`; they are
|
|
3
|
+
* `<app space>/profiles/<id>` now, because documents live in the canvas and the
|
|
4
|
+
* folder only anchors the profile's settings row. Idempotent: it moves what is
|
|
5
|
+
* still in the old place, then points every stored profile's settings-owner root
|
|
6
|
+
* at its current folder. Returns one line per thing it did or could not do.
|
|
7
|
+
*/
|
|
8
|
+
export declare function relocateProfileFolders(): string[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var p=(e,s)=>g(e,"name",{value:s,configurable:!0});import{existsSync as f,mkdirSync as w,readdirSync as m,renameSync as d,rmdirSync as l,statSync as u}from"node:fs";import{join as c}from"node:path";import{appSpace as y,appsRoot as h}from"../layout.js";import{userScopeRoot as S}from"../scope.js";import{prepared as $}from"../sqlite-statements.js";import{withScopedWrite as R}from"../scoped-state/db.js";import{canonicalRoot as D,userStore as _}from"../scoped-state/paths.js";import{listStoredProfiles as T}from"../scoped-state/profiles.js";function E(e,s,t){for(const o of m(e)){const r=c(e,o),i=c(s,o);if(!f(i)){d(r,i);continue}if(u(r).isDirectory()&&u(i).isDirectory()){E(r,i,t);try{l(r)}catch{t.push(r)}}else t.push(r)}}p(E,"mergeInto");function I(){const e=[];if(f(h()))for(const t of m(h(),{withFileTypes:!0})){if(!t.isDirectory()||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(t.name))continue;const o=y(t.name),r=c(o.root,"memory","profiles");if(f(r)){if(!f(o.profiles))d(r,o.profiles),e.push(`profile folders: moved ${r} to ${o.profiles}`);else{const i=[];E(r,o.profiles,i);try{l(r)}catch{}e.push(`profile folders: merged ${r} into ${o.profiles}`);for(const n of i)e.push(`profile folders: left ${n} in place; ${o.profiles} already holds that name`)}try{l(c(o.root,"memory"))}catch{}}}const s=T(S());return s.length>0&&R(_(S()),t=>{for(const{profileId:o,manifest:r}of s){const i=c(y(r.grantee??"app:terminal").profiles,o);w(i,{recursive:!0});const n=D(i),a=$(t,"SELECT root FROM scope_owners WHERE owner_key=?").get(`profile:${o}`);a!==void 0&&a.root!==n&&($(t,"UPDATE scope_owners SET root=? WHERE owner_key=?").run(n,`profile:${o}`),e.push(`profile folders: settings root of ${o} is now ${n}`))}}),e}p(I,"relocateProfileFolders");export{I as relocateProfileFolders};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _=Object.defineProperty;var a=(e,
|
|
1
|
+
var _=Object.defineProperty;var a=(e,n)=>_(e,"name",{value:n,configurable:!0});import{directory as c,normalizeMachineId as h}from"../peer/directory.js";import{peerCall as m}from"../peer/client.js";import{ProviderError as t}from"./errors.js";const l={current:{list:a(()=>c.list(),"list"),lastList:a(()=>c.lastList(),"lastList"),call:a((e,n,i)=>m(e,n,i),"call")}},p="/v1/device/call",D=6e4,f=a(e=>({machine_id:e.machine_id,name:e.name,last_seen:e.last_seen}),"candidateView");function s(e,n){const i=e.map(r=>`${r.name} (${r.machine_id})`).join(", ");return new t("machine_required",n===void 0?`This account has ${e.length} devices: ${i}. Pick one with --machine <machine_id>.`:`${n} is not one of this account's devices. Devices: ${i}. Pick one with --machine <machine_id>.`,{param:"machine",details:{candidates:e.map(f)}})}a(s,"machineRequired");async function x(e,n=l.current){let i;try{i=await n.list()}catch(o){const d=n.lastList();if(d===null)throw new t("provider_unavailable",`The directory could not be reached to find your devices: ${o instanceof Error?o.message:String(o)}`,{origin:"directory"});i=d}const r=i.filter(o=>o.kind==="device");if(r.length===0)throw new t("provider_not_connected","No device is connected to this account. Install Northlight Desktop on your Mac and sign in.",{origin:"directory"});if(e!==void 0){const o=h(e),d=r.find(u=>u.machine_id===o);if(!d)throw s(r,e);return d}if(r.length>1)throw s(r,void 0);return r[0]}a(x,"selectDevice");function v(e){return{tool:e.tool,arguments:e.arguments,version:e.version,request_id:e.requestId,...e.runId===null?{}:{run_id:e.runId},deadline_at:e.deadlineAt,...e.upload===null?{}:{upload:e.upload}}}a(v,"deviceBody");async function A(e,n,i,r,o=l.current){const d=Math.max(1,n.deadlineAt-Date.now());return o.call(e.machine_id,{method:"POST",path:p,body:v(n)},{envelope:i,device:!0,signal:AbortSignal.any([r,AbortSignal.timeout(d)])})}a(A,"sendDeviceCall");function E(e,n,i){switch(n){case"timeout":return new t("device_timeout",`${e.name} did not answer in time.`,{origin:"runtime",details:{machine_id:e.machine_id}});case"directory_unreachable":case"no_directory":return new t("provider_unavailable",i,{origin:"directory"});case"unknown_machine":return new t("provider_not_connected",`${e.name} is no longer on this account.`,{origin:"directory"});case"not_a_crtr_peer":return new t("server_error",i);default:return new t("device_offline",i.trim()===""?`${e.name} is offline.`:i,{origin:"runtime",details:{machine_id:e.machine_id}})}}a(E,"deviceUnreachable");function b(e,n,i,r,o){if(n===401)return new t("device_offline",`${e.name}: Desktop is signed out. Sign in to Northlight Desktop again.`,{origin:"runtime",details:{machine_id:e.machine_id}});if(n===426){const d=o?.error?.details?.supported;return new t("peer_version_too_old",r??`${e.name} does not serve this device major. Update Northlight Desktop.`,{origin:"runtime",details:{machine_id:e.machine_id,...Array.isArray(d)?{supported:d}:{}}})}return n===502&&i==="machine_disconnected"?new t("device_disconnected",`${e.name} disconnected during the call; the action may have run.`,{origin:"runtime",details:{machine_id:e.machine_id}}):i==="payload_too_large"||i==="response_too_large"?new t("provider_error",r??"The call or its answer was too large for the relay (16 MiB).",{origin:"runtime",status:413,details:{code:i,message:r??null,status:n}}):null}a(b,"deviceFailure");export{D as DEFAULT_DEVICE_REQUEST_MS,p as DEVICE_CALL_PATH,v as deviceBody,l as deviceDeps,b as deviceFailure,E as deviceUnreachable,x as selectDevice,A as sendDeviceCall};
|
package/dist/core/render.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { ErrorPayload } from './io.js';
|
|
|
5
5
|
* after. Scalars (and nested objects) list as `- name: value` bullets, prose
|
|
6
6
|
* fields render as paragraphs, and arrays become a count lead-in plus a table
|
|
7
7
|
* or bullets. No root tag — the result is read as a continuation of the prompt. */
|
|
8
|
-
export declare function renderResult(result: Record<string, unknown>, help: LeafHelp): string;
|
|
8
|
+
export declare function renderResult(result: Record<string, unknown>, help: Pick<LeafHelp, 'output'>): string;
|
|
9
9
|
/** Render a structured failure as an instruction-shaped block: what broke, what
|
|
10
10
|
* was received, and the recovery road sign — the same recovery info the JSON
|
|
11
11
|
* payload carries, shaped for the model to act on. */
|
package/dist/core/render.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var h=Object.defineProperty;var u=(e,n)=>h(e,"name",{value:n,configurable:!0});const
|
|
1
|
+
var h=Object.defineProperty;var u=(e,n)=>h(e,"name",{value:n,configurable:!0});const y=new Set(["follow_up","digest","message","next","result","content","body","guide","summary","note","reason","detail","details","hint","instruction","instructions","prompt","roadmap","report","answer","response","text"]);function $(e){return String(e).replace(/"/g,"'").replace(/\n/g," ")}u($,"attrEsc");function f(e){return e==null?"":Array.isArray(e)?e.map(f).join(", "):typeof e=="object"?JSON.stringify(e):String(e)}u(f,"scalarStr");function m(e){const n=JSON.stringify(e,null,2);let s="```";for(;n.includes(s);)s+="`";return`${s}json
|
|
2
2
|
${n}
|
|
3
|
-
${s}`}u(m,"fencedJson");function g(e,n){return typeof n!="string"?!1
|
|
3
|
+
${s}`}u(m,"fencedJson");function g(e,n){return typeof n!="string"?!1:y.has(e)?!0:n.includes(`
|
|
4
4
|
`)||n.length>80}u(g,"isProse");function j(e){return f(e).replace(/\|/g,"\\|").replace(/\n/g," ")}u(j,"cellEsc");function b(e,n){if(n.length===0)return`0 ${e}.`;const s=`${n.length} ${e}:`;if(n.every(o=>o!==null&&typeof o=="object"&&!Array.isArray(o))){const o=n,i=[];for(const p of o)for(const a of Object.keys(p))i.includes(a)||i.push(a);const d=`| ${i.join(" | ")} |`,t=`| ${i.map(()=>"---").join(" | ")} |`,r=o.map(p=>`| ${i.map(a=>j(p[a])).join(" | ")} |`).join(`
|
|
5
5
|
`);return`${s}
|
|
6
6
|
|
|
@@ -8,11 +8,11 @@ ${d}
|
|
|
8
8
|
${t}
|
|
9
9
|
${r}`}const c=n.map(o=>`- ${f(o)}`).join(`
|
|
10
10
|
`);return`${s}
|
|
11
|
-
${c}`}u(b,"renderArray");function
|
|
11
|
+
${c}`}u(b,"renderArray");function O(e,n){const s=n.output.map(t=>t.name);for(const t of Object.keys(e))s.includes(t)||s.push(t);const l=[],c=[],o=[];for(const t of s){const r=e[t];if(r!=null){if(Array.isArray(r)){o.push(b(t,r));continue}if(g(t,r)){c.push({name:t,text:r});continue}l.push(`- ${t}: ${f(r)}`)}}const i=[];l.length>0&&i.push(l.join(`
|
|
12
12
|
`));const d=c.length>1;for(const{name:t,text:r}of c)i.push(d?`**${t}:** ${r}`:r);for(const t of o)i.push(t);return i.join(`
|
|
13
13
|
|
|
14
|
-
`)}u(
|
|
15
|
-
${m(e.result)}`)),n.push(`Next: ${e.next}`),`<error code="${
|
|
14
|
+
`)}u(O,"renderResult");function _(e){const n=[e.message];return e.received!==void 0&&e.received!==null&&e.received!==""&&n.push(`received: ${f(e.received)}`),e.field!==void 0&&n.push(`field: ${e.field}`),e.http_status!==void 0&&n.push(`http status: ${e.http_status}`),e.retry_after_s!==void 0&&n.push(`retry after: ${e.retry_after_s}s`),e.details!==void 0&&Object.keys(e.details).length>0&&n.push(O(e.details,{output:[]})),"primaryCompleted"in e&&e.primaryCompleted===!0&&(n.push("primaryCompleted: true"),n.push(`Primary result (the command already completed):
|
|
15
|
+
${m(e.result)}`)),n.push(`Next: ${e.next}`),`<error code="${$(e.error)}">
|
|
16
16
|
${n.join(`
|
|
17
17
|
`)}
|
|
18
|
-
</error>`}u(
|
|
18
|
+
</error>`}u(_,"renderError");export{_ as renderError,O as renderResult};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
var U=Object.defineProperty;var f=(e,r)=>U(e,"name",{value:r,configurable:!0});import{prepared as p}from"../sqlite-statements.js";import{randomUUID as x}from"node:crypto";import{chmodSync as I,copyFileSync as P,existsSync as m,mkdirSync as w,readFileSync as _,readdirSync as V,statSync as N}from"node:fs";import{dirname as L,join as u,relative as J}from"node:path";import W from"proper-lockfile";import{CONFIG_FILE as b,PROFILE_DIR as D,STATE_FILE as v}from"../../types.js";import{LockedJsonFile as C}from"../locked-file.js";import{assertScopedStoreReady as q,createScopedStore as j,discardIncompleteScopedStore as z,legacyScopedStorePaths as O,PROFILE_ID_SHAPE as G,scopedStoreExists as g,withProjectStateLock as H,writeOwnerRoot as K}from"./db.js";import{canonicalRoot as M,providerStore as T,projectStore as X,userStore as B}from"./paths.js";import{profileSpace as Q}from"../layout.js";import{createScopedSchema as F}from"./schema.js";function h(e){return JSON.parse(_(e,"utf8"))}f(h,"json");function R(e){return e.some(m)}f(R,"existsLegacy");function E(e,r){const o=u(e,".legacy-scoped-state");try{w(o,{mode:448})}catch(a){if(a.code!=="EEXIST"||!N(o).isDirectory())throw a}I(o,448);for(const a of r)if(m(a)&&N(a).isFile()){const n=J(e,a);if(n===""||n.startsWith(".."))throw new Error(`legacy state is outside its owning root: ${a}`);const t=u(o,n);L(t)!==o&&w(L(t),{recursive:!0,mode:448}),P(a,t),I(t,384)}}f(E,"preserve");import{initializeFreshScopedStore as ge}from"./db.js";function me(e){const r=e.kind==="user"?B(e.root):e.kind==="project"?X(e.root):T(e.root);if(e.kind!=="project"&&g(r))return;if(e.kind==="provider")throw new Error("provider conversion requires convertLegacyProviderStore() under coordinated shared-agent-dir activation");const o=O(r),a=f(()=>{e.kind==="project"&&z(r),!g(r)&&(e.kind==="project"&&R(o)&&E(r.root,o),j(r,n=>{F(n,e.kind);const t=e.kind==="user"?"user":"project";K(n,t,r.root),e.kind==="user"?re(n,r.root):k(n,t,u(r.root,v))}),e.kind==="user"&&R(o)&&E(r.root,o))},"convert");e.kind==="project"?H(r.root,()=>{a(),q(r)}):a()}f(me,"convertLegacyScopedStore");function Y(e){if(!m(e))return[];const r=JSON.parse(_(e,"utf8"));if(!Array.isArray(r))throw new Error(`legacy subscription pool is malformed: ${e}`);const o=new Set;return r.map((a,n)=>{if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy subscription pool entry ${n+1} is malformed: ${e}`);const t=a,s=typeof t.label=="string"?t.label.trim():"",c=typeof t.refresh=="string"?t.refresh.trim():"",i=typeof t.access=="string"?t.access.trim():"",d=Number(t.expires);if(!s||!c||!i||!Number.isFinite(d))throw new Error(`legacy subscription pool entry ${n+1} is incomplete: ${e}`);const y=s.toLowerCase();if(o.has(y))throw new Error(`legacy subscription pool has duplicate label "${s}": ${e}`);o.add(y);const l=f(A=>Number.isFinite(Number(t[A]))?Number(t[A]):0,"timing"),S=typeof t.accountId=="string"&&t.accountId.trim()!==""?t.accountId.trim():void 0;return{label:s,refresh:c,access:i,expires:d,rateLimitedUntil:l("rateLimitedUntil"),lastAttemptAt:l("lastAttemptAt"),lastRateLimitedAt:l("lastRateLimitedAt"),...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...S?{accountId:S}:{}}})}f(Y,"parseLegacyProviderPool");function Z(e){if(!m(e))return{};const r=JSON.parse(_(e,"utf8"));if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`legacy provider rotation settings are malformed: ${e}`);const o=r;return{...o.defaultFallbackStrength==="ultra"||o.defaultFallbackStrength==="strong"||o.defaultFallbackStrength==="medium"||o.defaultFallbackStrength==="light"?{defaultFallbackStrength:o.defaultFallbackStrength}:{},...typeof o.revertWhenAvailable=="boolean"?{revertWhenAvailable:o.revertWhenAvailable}:{}}}f(Z,"parseLegacyRotation");async function ee(e,r){const o=[];try{for(const a of e)m(a)&&o.push(await W.lock(a,{realpath:!1,retries:0,stale:3e4,update:1e4}));return await r()}finally{await Promise.allSettled(o.reverse().map(a=>a()))}}f(ee,"withLegacyProviderLocks");async function ye(e){const r=T(e);if(g(r))return;const o=O(r);await ee(o,async()=>{if(g(r))return;const a=new Map(o.slice(0,2).map((t,s)=>[s===0?"anthropic":"openai-codex",Y(t)])),n=Z(o[2]);w(r.root,{recursive:!0,mode:448}),E(r.root,o);for(const[t,s]of a){const c=Object.fromEntries(s.map(d=>[x(),{refresh:d.refresh,access:d.access,expires:d.expires,...d.accountId?{accountId:d.accountId}:{}}]));await new C(u(r.root,`${t}-credentials.json`),!0,`{"version":1,"accounts":{}}
|
|
2
2
|
`).withLockAsync(async(d,y,l)=>(l(`${JSON.stringify({version:1,accounts:c})}
|
|
3
|
-
`),{result:void 0}))}j(r,t=>{F(t,"provider");for(const[s,c]of a){const i=JSON.parse(_(u(r.root,`${s}-credentials.json`),"utf8")),d=Object.keys(i.accounts),y=p(t,"INSERT INTO managed_accounts(provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure) VALUES(?,?,?,?,?,?,?,?,?)");c.forEach((l,S)=>y.run(s,d[S],l.label,l.label.toLowerCase(),S,l.lastAttemptAt,l.lastRateLimitedAt,l.rateLimitedUntil,l.authFailure??null))}(n.defaultFallbackStrength!==void 0||n.revertWhenAvailable!==void 0)&&p(t,"INSERT INTO rotation_settings(singleton,default_fallback_strength,revert_when_available) VALUES(1,?,?)").run(n.defaultFallbackStrength??null,n.revertWhenAvailable===void 0?null:n.revertWhenAvailable?1:0)})})}f(ye,"convertLegacyProviderStore");function $(e,r,o){if(!m(o))return;const a=h(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy config is malformed: ${o}`);p(e,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(r,JSON.stringify(a))}f($,"importSettings");function k(e,r,o){if(!m(o))return;const a=h(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy state is malformed: ${o}`);const n=a;p(e,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(r,n.last_self_check??null,n.activeCanvas??null);const t=p(e,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(const[c,i]of Object.entries(n.marketplaces??{}))t.run(r,c,i.last_updated??null);const s=p(e,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(const[c,i]of Object.entries(n.plugins??{}))s.run(r,c,i.last_updated??null,i.etag??null,i.checked_at??null)}f(k,"importState");function re(e,r){$(e,"user",u(r,b)),k(e,"user",u(r,v));const o=u(r,D);if(m(o))for(const n of V(o,{withFileTypes:!0})){if(!n.isDirectory()||!G.test(n.name))continue;const t=n.name,s=u(o,t),c=u(s,"profile.json");if(!m(c))throw new Error(`legacy profile manifest is missing: ${c}`);const i=h(c);if(!i||typeof i!="object"||!Array.isArray(i.projects)||typeof i.name!="string"||typeof i.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${c}`);p(e,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(t,i.name,i.created_at,i.last_used_at??null,i.paused_at??null,i.default_kind??null,i.grantee??null,JSON.stringify(i.metadata??{})),p(e,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${t}`,"profile",M(Q(i.grantee??"app:terminal",t).
|
|
3
|
+
`),{result:void 0}))}j(r,t=>{F(t,"provider");for(const[s,c]of a){const i=JSON.parse(_(u(r.root,`${s}-credentials.json`),"utf8")),d=Object.keys(i.accounts),y=p(t,"INSERT INTO managed_accounts(provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure) VALUES(?,?,?,?,?,?,?,?,?)");c.forEach((l,S)=>y.run(s,d[S],l.label,l.label.toLowerCase(),S,l.lastAttemptAt,l.lastRateLimitedAt,l.rateLimitedUntil,l.authFailure??null))}(n.defaultFallbackStrength!==void 0||n.revertWhenAvailable!==void 0)&&p(t,"INSERT INTO rotation_settings(singleton,default_fallback_strength,revert_when_available) VALUES(1,?,?)").run(n.defaultFallbackStrength??null,n.revertWhenAvailable===void 0?null:n.revertWhenAvailable?1:0)})})}f(ye,"convertLegacyProviderStore");function $(e,r,o){if(!m(o))return;const a=h(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy config is malformed: ${o}`);p(e,"INSERT INTO scope_settings(owner_key,raw_json) VALUES(?,?)").run(r,JSON.stringify(a))}f($,"importSettings");function k(e,r,o){if(!m(o))return;const a=h(o);if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`legacy state is malformed: ${o}`);const n=a;p(e,"INSERT INTO scope_bookkeeping(owner_key,last_self_check,active_canvas) VALUES(?,?,?)").run(r,n.last_self_check??null,n.activeCanvas??null);const t=p(e,"INSERT INTO scope_marketplaces(owner_key,name,last_updated) VALUES(?,?,?)");for(const[c,i]of Object.entries(n.marketplaces??{}))t.run(r,c,i.last_updated??null);const s=p(e,"INSERT INTO scope_plugins(owner_key,name,last_updated,etag,checked_at) VALUES(?,?,?,?,?)");for(const[c,i]of Object.entries(n.plugins??{}))s.run(r,c,i.last_updated??null,i.etag??null,i.checked_at??null)}f(k,"importState");function re(e,r){$(e,"user",u(r,b)),k(e,"user",u(r,v));const o=u(r,D);if(m(o))for(const n of V(o,{withFileTypes:!0})){if(!n.isDirectory()||!G.test(n.name))continue;const t=n.name,s=u(o,t),c=u(s,"profile.json");if(!m(c))throw new Error(`legacy profile manifest is missing: ${c}`);const i=h(c);if(!i||typeof i!="object"||!Array.isArray(i.projects)||typeof i.name!="string"||typeof i.created_at!="string")throw new Error(`legacy profile manifest is malformed: ${c}`);p(e,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json) VALUES(?,?,?,?,?,?,?,?)").run(t,i.name,i.created_at,i.last_used_at??null,i.paused_at??null,i.default_kind??null,i.grantee??null,JSON.stringify(i.metadata??{})),p(e,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${t}`,"profile",M(Q(i.grantee??"app:terminal",t).dir),t);const d=p(e,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)"),y=p(e,"INSERT INTO legacy_project_caps(profile_id,path,memory) VALUES(?,?,?)");i.projects.forEach((l,S)=>{d.run(t,l.path,S),l.memory!==void 0&&l.memory!=="content"&&y.run(t,l.path,l.memory)}),$(e,`profile:${t}`,u(s,b)),k(e,`profile:${t}`,u(s,v))}const a=u(r,"profile-defaults.json");if(m(a)){const n=h(a);if(n===null||typeof n!="object"||Array.isArray(n))throw new Error(`legacy profile defaults are malformed: ${a}`);const t=p(e,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(const[s,c]of Object.entries(n)){if(typeof c!="string")throw new Error(`legacy profile default is malformed: ${a}`);t.run(s,c)}}}f(re,"importUser");export{ye as convertLegacyProviderStore,me as convertLegacyScopedStore,ge as initializeFreshScopedStore};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});import{prepared as n}from"../sqlite-statements.js";import{canonicalRoot as m,userStore as S}from"./paths.js";import{profileSpace as R}from"../layout.js";import{openScopedStore as
|
|
1
|
+
var c=Object.defineProperty;var o=(t,e)=>c(t,"name",{value:e,configurable:!0});import{prepared as n}from"../sqlite-statements.js";import{canonicalRoot as m,userStore as S}from"./paths.js";import{profileSpace as R}from"../layout.js";import{openScopedStore as d,withScopedWrite as f}from"./db.js";function s(t){return S(t)}o(s,"store");function O(t,e){return{profileId:t.id,manifest:{schema_version:1,name:t.name,projects:e,paused_at:t.paused_at,...t.default_kind===null?{}:{default_kind:t.default_kind},...t.grantee===null?{}:{grantee:t.grantee},...t.delivery_limits_json==="{}"?{}:{delivery_limits:JSON.parse(t.delivery_limits_json)},...Object.keys(JSON.parse(t.metadata_json)).length===0?{}:{metadata:JSON.parse(t.metadata_json)},created_at:t.created_at,last_used_at:t.last_used_at}}}o(O,"rowToProfile");function u(t,e){const r=n(t,"SELECT id, name, created_at, last_used_at, paused_at, default_kind, grantee, metadata_json, delivery_limits_json FROM profiles WHERE id=?").get(e);if(!r)return null;const i=n(t,"SELECT path FROM profile_projects WHERE profile_id=? ORDER BY position").all(e);return O(r,i)}o(u,"get");function I(t){const e=d(s(t));return n(e,"SELECT id FROM profiles ORDER BY rowid").all().map(({id:i})=>u(e,i)).filter(Boolean)}o(I,"listStoredProfiles");function N(t,e){return u(d(s(t)),e)}o(N,"getStoredProfile");function k(t,e){return n(d(s(t)),"SELECT paused_at FROM profiles WHERE id=?").get(e)?.paused_at!=null}o(k,"profilePaused");function h(t){const e=n(d(s(t)),"SELECT id FROM profiles WHERE paused_at IS NOT NULL").all();return new Set(e.map(r=>r.id))}o(h,"pausedProfileIds");function D(t,e){f(s(t),r=>{n(r,"INSERT INTO profiles(id,name,created_at,last_used_at,paused_at,default_kind,grantee,metadata_json,delivery_limits_json) VALUES(?,?,?,?,?,?,?,?,?)").run(e.profileId,e.manifest.name,e.manifest.created_at,e.manifest.last_used_at,e.manifest.paused_at,e.manifest.default_kind??null,e.manifest.grantee??null,JSON.stringify(e.manifest.metadata??{}),JSON.stringify(e.manifest.delivery_limits??{})),n(r,"INSERT INTO scope_owners(owner_key,kind,root,profile_id) VALUES(?,?,?,?)").run(`profile:${e.profileId}`,"profile",m(R(e.manifest.grantee??"app:terminal",e.profileId).dir),e.profileId);const i=n(r,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)");e.manifest.projects.forEach((l,a)=>i.run(e.profileId,l.path,a))})}o(D,"insertStoredProfile");function F(t,e,r){return f(s(t),i=>{const l=u(i,e);if(!l)return null;const a=r(l.manifest);n(i,"UPDATE profiles SET name=?, last_used_at=?, paused_at=?, default_kind=?, grantee=?, metadata_json=?, delivery_limits_json=? WHERE id=?").run(a.name,a.last_used_at,a.paused_at,a.default_kind??null,a.grantee??null,JSON.stringify(a.metadata??{}),JSON.stringify(a.delivery_limits??{}),e),n(i,"DELETE FROM profile_projects WHERE profile_id=?").run(e);const p=n(i,"INSERT INTO profile_projects(profile_id,path,position) VALUES(?,?,?)");return a.projects.forEach((E,_)=>p.run(e,E.path,_)),{profileId:e,manifest:a}})}o(F,"updateStoredProfile");function M(t,e){return f(s(t),r=>{if(!u(r,e))return!1;const i=`profile:${e}`;return n(r,"DELETE FROM scope_settings WHERE owner_key=?").run(i),n(r,"DELETE FROM scope_bookkeeping WHERE owner_key=?").run(i),n(r,"DELETE FROM scope_marketplaces WHERE owner_key=?").run(i),n(r,"DELETE FROM scope_plugins WHERE owner_key=?").run(i),n(r,"DELETE FROM scope_owners WHERE owner_key=?").run(i),n(r,"DELETE FROM profiles WHERE id=?").run(e),!0})}o(M,"deleteStoredProfile");function W(t){f(s(t),e=>{n(e,"UPDATE profiles SET grantee = 'app:terminal' WHERE grantee = 'user:local'").run()})}o(W,"rewriteLocalProfileGrantees");function x(t){const e=d(s(t));return Object.fromEntries(n(e,"SELECT directory,profile_id FROM profile_defaults").all().map(r=>[r.directory,r.profile_id]))}o(x,"readStoredDefaults");function H(t,e){return f(s(t),r=>{const i=Object.fromEntries(n(r,"SELECT directory,profile_id FROM profile_defaults").all().map(p=>[p.directory,p.profile_id])),l=e(i);n(r,"DELETE FROM profile_defaults").run();const a=n(r,"INSERT INTO profile_defaults(directory,profile_id) VALUES(?,?)");for(const[p,E]of Object.entries(l))a.run(p,E);return l})}o(H,"mutateStoredDefaults");function P(t){return n(d(s(t)),"SELECT profile_id, path, memory FROM legacy_project_caps ORDER BY profile_id, path").all().map(e=>({profileId:e.profile_id,path:e.path,memory:e.memory}))}o(P,"listLegacyProjectCaps");function v(t,e){f(s(t),r=>{const i=n(r,"UPDATE profiles SET delivery_limits_json=? WHERE id=?");for(const l of e)if(i.run(JSON.stringify(l.deliveryLimits),l.profileId).changes!==1)throw new Error(`no stored profile ${l.profileId}`);n(r,"DELETE FROM legacy_project_caps").run()})}o(v,"commitConvertedProjectCaps");export{v as commitConvertedProjectCaps,M as deleteStoredProfile,N as getStoredProfile,D as insertStoredProfile,P as listLegacyProjectCaps,I as listStoredProfiles,H as mutateStoredDefaults,h as pausedProfileIds,k as profilePaused,x as readStoredDefaults,W as rewriteLocalProfileGrantees,F as updateStoredProfile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var a=(e,t)=>k(e,"name",{value:t,configurable:!0});import{prepared as r}from"../sqlite-statements.js";import{createHash as E}from"node:crypto";import{openScopedStore as p,withScopedWrite as _}from"./db.js";function l(e,t,n){const o=r(e,"SELECT kind, root, profile_id FROM scope_owners WHERE owner_key = ?").get(t.key);if(!o)throw new Error(`scoped SQL owner is missing: ${t.key}`);if(o.kind!==t.kind||(t.profileId??null)!==o.profile_id)throw new Error(`scoped SQL owner does not match its root: ${t.key}`);if(o.root===t.root)return;if(!(t.kind==="profile"&&t.profileId!==void 0)&&(t.kind!=="project"||t.store.kind!=="project"||t.store.root!==t.root))throw new Error(`scoped SQL owner does not match its root: ${t.key}`);n==="write"&&r(e,"UPDATE scope_owners SET root = ? WHERE owner_key = ?").run(t.root,t.key)}a(l,"ensureOwner");function u(e){return e===void 0?"absent":E("sha256").update(e.raw_json).digest("hex")}a(u,"revisionFor");function d(e,t){return r(e,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(t.key)}a(d,"readRawSettingsRow");class f extends Error{static{a(this,"SettingsRevisionConflictError")}constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}}function g(e){const t=p(e.store);l(t,e,"read");const n=d(t,e);return{revision:u(n),settings:n===void 0?null:JSON.parse(n.raw_json)}}a(g,"readRawSettingsWithRevision");function R(e){return g(e).settings}a(R,"readRawSettings");function h(e,t,n,o){return _(e.store,i=>{l(i,e,"write");const s=d(i,e);if(n!==u(s))throw new f;o(t);const c=JSON.stringify(t);return s?.raw_json===c?{revision:u(s),changed:!1}:(r(i,"INSERT INTO scope_settings(owner_key, raw_json) VALUES (?, ?) ON CONFLICT(owner_key) DO UPDATE SET raw_json=excluded.raw_json").run(e.key,c),{revision:u({raw_json:c}),changed:!0})})}a(h,"replaceRawSettings");function m(e,t){_(e.store,n=>{l(n,e,"write"),r(n,"INSERT INTO scope_settings(owner_key, raw_json) VALUES (?, ?) ON CONFLICT(owner_key) DO UPDATE SET raw_json=excluded.raw_json").run(e.key,JSON.stringify(t))})}a(m,"writeRawSettings");function v(e,t){return _(e.store,n=>{l(n,e,"write");const o=r(n,"SELECT raw_json FROM scope_settings WHERE owner_key = ?").get(e.key),i=t(o?JSON.parse(o.raw_json):{});return r(n,"INSERT INTO scope_settings(owner_key, raw_json) VALUES (?, ?) ON CONFLICT(owner_key) DO UPDATE SET raw_json=excluded.raw_json").run(e.key,JSON.stringify(i.next)),i.value})}a(v,"mutateRawSettings");function w(e){const t=p(e.store);l(t,e,"read");const n=r(t,"SELECT last_self_check, active_canvas FROM scope_bookkeeping WHERE owner_key = ?").get(e.key),o=Object.fromEntries(r(t,"SELECT name, last_updated FROM scope_marketplaces WHERE owner_key = ?").all(e.key).map(s=>[s.name,s.last_updated===null?{}:{last_updated:s.last_updated}])),i=Object.fromEntries(r(t,"SELECT name, last_updated, etag, checked_at FROM scope_plugins WHERE owner_key = ?").all(e.key).map(s=>[s.name,{...s.last_updated===null?{}:{last_updated:s.last_updated},...s.etag===null?{}:{etag:s.etag},...s.checked_at===null?{}:{checked_at:s.checked_at}}]));return{marketplaces:o,plugins:i,...n?.last_self_check===null||n===void 0?{}:{last_self_check:n.last_self_check},activeCanvas:n?.active_canvas??null}}a(w,"readBookkeeping");function N(e,t){_(e.store,n=>{l(n,e,"write"),r(n,"INSERT INTO scope_bookkeeping(owner_key, last_self_check, active_canvas) VALUES (?, ?, ?) ON CONFLICT(owner_key) DO UPDATE SET last_self_check=excluded.last_self_check, active_canvas=excluded.active_canvas").run(e.key,t.last_self_check??null,t.activeCanvas??null),r(n,"DELETE FROM scope_marketplaces WHERE owner_key = ?").run(e.key),r(n,"DELETE FROM scope_plugins WHERE owner_key = ?").run(e.key);const o=r(n,"INSERT INTO scope_marketplaces(owner_key, name, last_updated) VALUES (?, ?, ?)");for(const[s,c]of Object.entries(t.marketplaces))o.run(e.key,s,c.last_updated??null);const i=r(n,"INSERT INTO scope_plugins(owner_key, name, last_updated, etag, checked_at) VALUES (?, ?, ?, ?, ?)");for(const[s,c]of Object.entries(t.plugins))i.run(e.key,s,c.last_updated??null,c.etag??null,c.checked_at??null)})}a(N,"writeBookkeeping");export{f as SettingsRevisionConflictError,v as mutateRawSettings,w as readBookkeeping,R as readRawSettings,g as readRawSettingsWithRevision,h as replaceRawSettings,N as writeBookkeeping,m as writeRawSettings};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var f=Object.defineProperty;var n=(o,r)=>f(o,"name",{value:r,configurable:!0});import{chownSync as a,chmodSync as d,existsSync as
|
|
2
|
-
`).find(e=>e.startsWith("crtr-data:"));if(!o)throw new Error("crtr-data group is required on sandboxed Linux");const r=Number(o.split(":")[2]);if(!Number.isInteger(r))throw new Error("invalid crtr-data group id");return r}n(p,"dataGroup");function L(){const o=y(),r=p();c(o,{recursive:!0,mode:1528});const e=
|
|
1
|
+
var f=Object.defineProperty;var n=(o,r)=>f(o,"name",{value:r,configurable:!0});import{chownSync as a,chmodSync as d,existsSync as l,mkdirSync as c,readFileSync as h,statSync as m}from"node:fs";import{appSpace as g,appsRoot as w,userFilesRoot as y}from"../layout.js";import{launcherRequest as S}from"../../launcher/client.js";import{LAUNCHER_SOCKET as x}from"../../launcher/spec.js";import{allocateAppUser as E,uidForApp as v}from"./users.js";function p(){const o=h("/etc/group","utf8").split(`
|
|
2
|
+
`).find(e=>e.startsWith("crtr-data:"));if(!o)throw new Error("crtr-data group is required on sandboxed Linux");const r=Number(o.split(":")[2]);if(!Number.isInteger(r))throw new Error("invalid crtr-data group id");return r}n(p,"dataGroup");function L(){const o=y(),r=p();c(o,{recursive:!0,mode:1528});const e=m(o),t=e.mode&4095;if(!e.isDirectory()||e.gid!==r||t!==1528){if(!e.isDirectory()||e.uid!==process.getuid())throw new Error(`${o} has owner ${e.uid}, group ${e.gid}, mode ${t.toString(8).padStart(4,"0")}; requires an crtr-data (${r}) directory with mode 2770; only its owner can repair it`);e.gid!==r&&a(o,e.uid,r),t!==1528&&d(o,1528)}}n(L,"ensureUserFiles");async function N(o){const r=g(o);if(!(process.platform==="linux"&&l(x))){if(process.platform==="linux")throw new Error("app space requires the root launcher on Linux");for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0});return{uid:v(o),gid:process.getgid(),root:r.root}}const t=p(),s=E(o),u=await S({operation:"user.create",app:r.root.slice(w().length+1),uid:s.uid});if(!("uid"in u)||u.uid!==s.uid)throw new Error(`launcher did not create OS user for ${o}`);for(const i of[r.root,r.profiles,r.conversations,r.nodes,r.files,r.home,r.cache])c(i,{recursive:!0,mode:1528}),a(i,process.getuid(),t),d(i,1528);return{uid:s.uid,gid:t,root:r.root}}n(N,"ensureAppSpace");export{N as ensureAppSpace,L as ensureUserFiles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var y=Object.defineProperty;var c=(i,
|
|
1
|
+
var y=Object.defineProperty;var c=(i,e)=>y(i,"name",{value:e,configurable:!0});import{closeSync as m,constants as h,createReadStream as v,fstatSync as b,realpathSync as g}from"node:fs";import{extname as C,isAbsolute as N,join as w,relative as l,resolve as R,sep as d}from"node:path";import{pipeline as S}from"node:stream/promises";import{appsRoot as E,runtimeRoot as _,userRoot as $}from"../layout.js";import{RunError as f}from"../runs/operations.js";import{isBeneathRefusal as O,openBeneath as I}from"../spaces/open-beneath.js";import{fileRoot as T}from"../spaces/permissions.js";const j={".txt":"text/plain; charset=utf-8",".log":"text/plain; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".tsv":"text/tab-separated-values; charset=utf-8",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".heic":"image/heic",".heif":"image/heif",".avif":"image/avif",".bmp":"image/bmp",".tif":"image/tiff",".tiff":"image/tiff",".mp3":"audio/mpeg",".m4a":"audio/mp4",".wav":"audio/wav",".ogg":"audio/ogg",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"},L=new Set(["text/html","image/svg+xml","application/xhtml+xml"]);function A(i){const e=j[C(i).toLowerCase()]??"application/octet-stream";return L.has(e.split(";")[0].trim().toLowerCase())?"application/octet-stream":e}c(A,"contentTypeFor");function u(i,e){const o=l(i,e);return o===""||o!==".."&&!o.startsWith(`..${d}`)&&!o.startsWith(d)}c(u,"contains");function D(i){const e=c(n=>process.platform==="darwin"?n.toLowerCase():n,"fold"),o=e(i),r=e(E());if(u(e(_()),o)||u(e(w($(),"memory")),o))return!0;if(!u(r,o))return!1;const t=l(r,o).split(d)[1];return t==="memory"||t==="profiles"||t==="conversations"}c(D,"withheld");function z(i,e){if(typeof e!="string"||!e)throw new f(400,"invalid_request","path is required","path");if(!N(e)||e.includes("\0"))throw new f(400,"invalid_request","path must be absolute","path");const o=R(e),r=c(()=>new f(404,"not_found",`no such file: ${o}`),"notFound");if(D(o))throw r();const t=T(i,o,"read");if("hidden"in t)throw r();if(!("root"in t))throw new f(403,"scope_missing",t.missing?`missing scope ${t.missing}`:`no permission names ${o}`,void 0,void 0,t.missing??void 0);const n=c(()=>new f(400,"invalid_request",`${o} meets a symlink, leaves its permitted root, or is not a regular file`,"path"),"symlink");let p;try{p=I(t.root,o,h.O_RDONLY|h.O_NONBLOCK)}catch(a){if(O(a))throw n();const s=a.code;throw s==="ENOENT"||s==="ENOTDIR"||s==="EISDIR"||s==="ENXIO"||s==="EACCES"||s==="EPERM"?r():a}try{if(process.platform!=="linux"){let s;try{s=g(o)}catch{throw r()}if(s!==w(g(t.root),l(t.root,o)))throw n()}const a=b(p);if(!a.isFile())throw r();return{fd:p,path:o,size:a.size}}catch(a){throw m(p),a}}c(z,"openCallerFile");function M(i,e){if(i===void 0)return null;const o=c(()=>new f(416,"range_not_satisfiable","range not satisfiable","range",{size:e}),"refuse"),r=/^bytes=(.+)$/i.exec(i.trim());if(!r)throw o();if(r[1].includes(","))return null;const t=/^\s*(\d*)\s*-\s*(\d*)\s*$/.exec(r[1]);if(!t||t[1]===""&&t[2]==="")throw o();let n,p;if(t[1]===""){const a=Number(t[2]);if(!Number.isSafeInteger(a)||a===0||e===0)throw o();n=Math.max(0,e-a),p=e-1}else if(n=Number(t[1]),p=t[2]===""?e-1:Math.min(Number(t[2]),e-1),!Number.isSafeInteger(n)||!Number.isSafeInteger(p)||n>=e||t[2]!==""&&Number(t[2])<n)throw o();return{start:n,end:p}}c(M,"parseRange");async function X(i,e,o,r){const t=z(o,r);let n;try{const s=i.headers.range;try{n=M(Array.isArray(s)?s[0]:s,t.size)}catch(x){throw e.setHeader("Content-Range",`bytes */${t.size}`),x}}catch(s){throw m(t.fd),s}const p={"Content-Type":A(t.path),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"sandbox; default-src 'none'","Accept-Ranges":"bytes","Cache-Control":"no-store"};if(i.destroyed||e.destroyed){m(t.fd);return}if(n?e.writeHead(206,{...p,"Content-Length":String(n.end-n.start+1),"Content-Range":`bytes ${n.start}-${n.end}/${t.size}`}):e.writeHead(200,{...p,"Content-Length":String(t.size)}),t.size===0||n&&n.end<n.start){m(t.fd),e.end();return}const a=v("",{fd:t.fd,autoClose:!0,...n?{start:n.start,end:n.end}:{start:0}});try{await S(a,e)}catch{a.destroy(),e.destroy()}}c(X,"serveDownload");export{A as contentTypeFor,z as openCallerFile,M as parseRange,X as serveDownload};
|
package/dist/daemon/api/map.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var h=Object.defineProperty;var r=(e,t)=>h(e,"name",{value:t,configurable:!0});import{join as g}from"node:path";import{readOutputResult as b}from"../../core/runtime/structured-output.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as y}from"../../core/canvas/crons.js";import{isProfilePaused as c,profileMemoryDir as x,sanitizeProfileMetadata as O}from"../../core/profiles/manifest.js";import{nodeMetaPath as D,transcriptPath as T,viewSocketPath as E}from"../../core/canvas/paths.js";import{appForNode as f,contextDir as S,nodeAgentDir as A}from"../../core/canvas/node-agent-paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as z}from"../../core/runtime/nodes.js";import{ScopeDeniedError as N}from"../../core/scopes.js";import{isBeneathRefusal as C}from"../../core/spaces/open-beneath.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as j}from"../../core/worktree.js";import{ApiError as q}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ce(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}r(ce,"toMigrateStateDTO");function F(e,t){try{return b(e,t)??null}catch{return null}}r(F,"readStructuredResult");function I(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}r(I,"toNodeOutcomeSummaryDTO");function p(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?F(e.node_id,e.grantee):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}r(p,"toNodeOutcomeDTO");function fe(e){const t=p(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}r(fe,"toRunOutcomeDTO");function pe(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}r(pe,"toOutcomeDeliveryDTO");function me(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}r(me,"toGraphNodeDTO");function ve(e,t=c(e.profile_id)){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??f(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:I(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}r(ve,"toNodeSummaryDTO");function P(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}r(P,"toNodeEdgesDTO");function M(e,t){return{node_dir:A(e,t),context_dir:S(e,t),meta_path:D(e),transcript_path:T(e),view_socket:E(e)}}r(M,"toNodePathsDTO");function U(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}r(U,"toNodeWorktreeDTO");function ke(e,t){const n=f(e.node_id),i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:c(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:p(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:P(e,t),paths:M(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=U(e.managed_worktree)),i}r(ke,"toNodeDetailDTO");function he(e,t,n){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome}}r(he,"toReviveResultDTO");function ge(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}r(ge,"toCloseResultDTO");function be(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}r(be,"toReportResultDTO");function ye(e){return{node_id:e.node_id,active:e.active,created:e.created}}r(ye,"toSubscriptionDTO");function G(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}r(G,"envKeys");function xe(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:G(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:y(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}r(xe,"toCronDTO");function Oe(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}r(Oe,"toCronRunDTO");function De(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:O(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,memory_path:x(e.profileId)}}r(De,"toProfileDTO");function m(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}r(m,"toReviewDTO");function Te(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}r(Te,"toReviewCommentDTO");function B(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}r(B,"toPageFeedbackCommentDTO");function Ee(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(B)}}r(Ee,"toPageFeedbackDTO");function Se(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}r(Se,"toReviewCommentEventDTO");function Ae(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}r(Ae,"toFeedbackResultDTO");const L=!0,W=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function $(e){const t=v(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof z)return{status:409,code:"node_id_exists"};if(t instanceof N)return{status:403,code:"scope_denied"};if(C(t))return{status:400,code:"invalid_request"};if(t instanceof _)return W[t.code];if(t instanceof s)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"?{status:403,code:t.code}:{status:H(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}r($,"errorToStatus");function v(e){if(!(e instanceof j))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new s(e.code,e.message,t,n)}r(v,"normalizeThrow");function K(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:V(t)}}r(K,"reviewErrorDetails");function V(e){return e.state!=="approved"?m(e):m(e,{result_path:g(e.review_dir,"result.json")})}r(V,"terminalConflictReviewDTO");function H(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}r(H,"statusForExitCode");function J(e){const n=(e instanceof Error?e.message:String(e)).split(`
|
|
2
|
-
`,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}r(J,"boundedCause");function Re(e){const t=
|
|
1
|
+
var g=Object.defineProperty;var r=(e,t)=>g(e,"name",{value:t,configurable:!0});import{join as b}from"node:path";import{readOutputResult as y}from"../../core/runtime/structured-output.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as x}from"../../core/canvas/crons.js";import{isProfilePaused as c,profileDir as f,sanitizeProfileMetadata as O}from"../../core/profiles/manifest.js";import{nodeMetaPath as D,transcriptPath as T,viewSocketPath as E}from"../../core/canvas/paths.js";import{appForNode as p,contextDir as S,nodeAgentDir as A}from"../../core/canvas/node-agent-paths.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as z}from"../../core/runtime/nodes.js";import{ScopeDeniedError as N}from"../../core/scopes.js";import{isBeneathRefusal as C}from"../../core/spaces/open-beneath.js";import{CrtrError as s}from"../../core/errors.js";import{WorktreeError as j}from"../../core/worktree.js";import{ApiError as q}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ce(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}r(ce,"toMigrateStateDTO");function F(e,t){try{return y(e,t)??null}catch{return null}}r(F,"readStructuredResult");function I(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}r(I,"toNodeOutcomeSummaryDTO");function m(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?F(e.node_id,e.grantee):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}r(m,"toNodeOutcomeDTO");function fe(e){const t=m(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}r(fe,"toRunOutcomeDTO");function pe(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}r(pe,"toOutcomeDeliveryDTO");function me(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}r(me,"toGraphNodeDTO");function ve(e,t=c(e.profile_id)){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??p(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:e.waiting_for,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:I(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}r(ve,"toNodeSummaryDTO");function P(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}r(P,"toNodeEdgesDTO");function U(e,t){return{node_dir:A(e,t),context_dir:S(e,t),meta_path:D(e),transcript_path:T(e),view_socket:E(e)}}r(U,"toNodePathsDTO");function G(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}r(G,"toNodeWorktreeDTO");function he(e,t){const n=p(e.node_id),i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:c(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:e.waiting_for??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,outcome:m(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:P(e,t),paths:U(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=G(e.managed_worktree)),i}r(he,"toNodeDetailDTO");function ke(e,t,n){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome}}r(ke,"toReviveResultDTO");function ge(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}r(ge,"toCloseResultDTO");function be(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}r(be,"toReportResultDTO");function ye(e){return{node_id:e.node_id,active:e.active,created:e.created}}r(ye,"toSubscriptionDTO");function M(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}r(M,"envKeys");function xe(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:M(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:x(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}r(xe,"toCronDTO");function Oe(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}r(Oe,"toCronRunDTO");function De(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:O(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,profile_path:f(e.profileId),memory_path:f(e.profileId)}}r(De,"toProfileDTO");function v(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}r(v,"toReviewDTO");function Te(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},anchor_state:e.anchor_state,anchor_line_text:e.anchor_line_text,anchor_doc_hash:e.anchor_doc_hash,author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}r(Te,"toReviewCommentDTO");function B(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}r(B,"toPageFeedbackCommentDTO");function Ee(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(B)}}r(Ee,"toPageFeedbackDTO");function Se(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}r(Se,"toReviewCommentEventDTO");function Ae(e){return{file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}r(Ae,"toFeedbackResultDTO");const L=!0,W=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},anchor_out_of_range:{status:400,code:"anchor_out_of_range"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"},range_batch_incomplete:{status:409,code:"range_batch_incomplete"},range_batch_stale:{status:409,code:"range_batch_stale"}});function $(e){const t=h(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof z)return{status:409,code:"node_id_exists"};if(t instanceof N)return{status:403,code:"scope_denied"};if(C(t))return{status:400,code:"invalid_request"};if(t instanceof _)return W[t.code];if(t instanceof s)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"?{status:403,code:t.code}:{status:H(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}r($,"errorToStatus");function h(e){if(!(e instanceof j))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new s(e.code,e.message,t,n)}r(h,"normalizeThrow");function K(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:V(t)}}r(K,"reviewErrorDetails");function V(e){return e.state!=="approved"?v(e):v(e,{result_path:b(e.review_dir,"result.json")})}r(V,"terminalConflictReviewDTO");function H(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}r(H,"statusForExitCode");function J(e){const n=(e instanceof Error?e.message:String(e)).split(`
|
|
2
|
+
`,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}r(J,"boundedCause");function Re(e){const t=h(e),{status:n,code:i}=$(t);if(n>=500){const a={error:{code:i,message:J(t)}};return t instanceof l&&(a.error.origin="runtime",a.error.retryable=t.retryable),{status:n,body:a}}const k=t instanceof Error?t.message:String(t),u=t instanceof _?K(t):(t instanceof s||t instanceof q||t instanceof l)&&t.details!==void 0?t.details:void 0,d={error:{code:i,message:k}};return u!==void 0&&(d.error.details=u),t instanceof l&&(t.param&&(d.error.param=t.param),t.scope&&(d.error.scope=t.scope),d.error.origin="runtime",d.error.retryable=t.retryable),{status:n,body:d}}r(Re,"toErrorBody");export{W as REVIEW_ERROR_MAP,$ as errorToStatus,ge as toCloseResultDTO,xe as toCronDTO,Oe as toCronRunDTO,Re as toErrorBody,Ae as toFeedbackResultDTO,me as toGraphNodeDTO,ce as toMigrateStateDTO,he as toNodeDetailDTO,P as toNodeEdgesDTO,m as toNodeOutcomeDTO,I as toNodeOutcomeSummaryDTO,U as toNodePathsDTO,ve as toNodeSummaryDTO,G as toNodeWorktreeDTO,pe as toOutcomeDeliveryDTO,B as toPageFeedbackCommentDTO,Ee as toPageFeedbackDTO,De as toProfileDTO,be as toReportResultDTO,Te as toReviewCommentDTO,Se as toReviewCommentEventDTO,v as toReviewDTO,ke as toReviveResultDTO,fe as toRunOutcomeDTO,ye as toSubscriptionDTO};
|