← Files DXIRARCHIVED FILE

scripts/project.mjs

16 KB · Nov 29, 2026 · 18:15 UTC

↓ Download file

See the change to this file →

import o from"node:fs/promises";import s from"node:path";import P from"node:os";import{createHash as D,randomUUID as b}from"node:crypto";import{pathToFileURL as U}from"node:url";import{isDeepStrictEqual as J}from"node:util";import{artifact as B,locked as F,uploadArtifact as R}from"./journal.mjs";const _=t=>{if(!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(t||""))throw new Error("invalid_id");return t},h=t=>D("sha256").update(t).digest("hex"),A=(t,e)=>{const i=s.relative(t,e);if(i===".."||i.startsWith(`..${s.sep}`)||s.isAbsolute(i))throw new Error("path_outside_project")};async function z(t,e=P.homedir()){if(typeof t!="string"||!t.trim()||t!==t.trim()||t.length>100||/^[.]/.test(t)||/[<>:"/\\|?*\x00-\x1f\x7f]/.test(t)||/[. ]$/.test(t)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(t))throw new Error("invalid_folder_name");if(!s.isAbsolute(e))throw new Error("absolute_parent_required");const i=await o.realpath(e);if(!(await o.stat(i)).isDirectory())throw new Error("invalid_parent_directory");const r=s.join(i,t);A(i,r);try{throw await o.lstat(r),new Error("folder_already_exists")}catch(n){if(n.code!=="ENOENT")throw n}return{status:"awaiting_folder_approval",folder_path:r,host_project_status:"not_verified"}}async function X(t,e,i){if(!i)throw new Error("folder_approval_required");const r=await z(t,e);if(i!==r.folder_path)throw new Error("folder_approval_path_mismatch");try{await o.mkdir(r.folder_path,{mode:448})}catch(c){throw c.code==="EEXIST"?new Error("folder_already_exists"):c}const n=await o.lstat(r.folder_path);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("unsafe_project_directory");if(await o.realpath(r.folder_path)!==r.folder_path)throw new Error("project_location_changed");return{...r,status:"folder_created"}}async function y(t,e){let i=t;for(const r of e){i=s.join(i,r);try{await o.mkdir(i)}catch(c){if(c.code!=="EEXIST")throw c}const n=await o.lstat(i);if(n.isSymbolicLink()||!n.isDirectory())throw new Error("unsafe_project_directory");if(A(t,await o.realpath(i)),i===s.join(t,".dxir"))try{await o.writeFile(s.join(i,".gitignore"),`*
`,{flag:"wx"})}catch(c){if(c.code!=="EEXIST")throw c}}return i}async function E(t,e){try{await o.writeFile(t,e,{flag:"wx",mode:384})}catch(i){if(i.code!=="EEXIST")throw i;if((await o.lstat(t)).isSymbolicLink()||!(await o.readFile(t)).equals(Buffer.from(e)))throw new Error("existing_file_differs")}}async function $(t,e,i,r){t=await o.realpath(t),_(e),_(i);const n=await y(t,[".dxir"]);await E(s.join(n,"location.json"),JSON.stringify({location_key:h(process.platform==="win32"?t.toLowerCase():t)})+`
`);const c=s.join(n,"project.json");try{if((await o.lstat(c)).isSymbolicLink())throw new Error("unsafe_project_mapping");const l=JSON.parse(await o.readFile(c,"utf8"));if(l.project_id!==e||l.account_id!==i)throw new Error("folder_already_connected");if(r&&l.folder_key!==r)throw new Error("folder_key_mismatch");return _(l.folder_key),l}catch(l){if(l.code!=="ENOENT")throw l}const a={version:1,project_id:e,account_id:i,folder_key:r?_(r):b()};return await E(c,JSON.stringify(a,null,2)+`
`),a}async function O(t,e){t=await o.realpath(t),_(e);const i=await y(t,[".dxir"]);await E(s.join(i,"location.json"),JSON.stringify({location_key:h(process.platform==="win32"?t.toLowerCase():t)})+`
`);for(const n of["project.json","app-context.json"])try{const c=s.join(i,n);if((await o.lstat(c)).isSymbolicLink())throw new Error("unsafe_project_mapping");const a=JSON.parse(await o.readFile(c,"utf8"));if(a.account_id!==e)throw new Error("folder_already_connected");return _(a.folder_key),a}catch(c){if(c.code!=="ENOENT")throw c}const r={version:1,account_id:e,folder_key:b()};return await E(s.join(i,"app-context.json"),JSON.stringify(r,null,2)+`
`),r}async function H(t,e){const i=await O(t,_(e.account_id));if(i.folder_key!==e.folder_key||e.status!=="active")throw new Error("context_mismatch");const r=await $(t,_(e.project_id),e.account_id,i.folder_key),n=await q(t,_(e.connection_id));return{...r,...n}}async function x(t){try{const e=await o.lstat(t);if(!e.isFile()||e.nlink!==1)throw new Error("unsafe_project_mapping");return await o.readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function N(t,e){const i=s.join(s.dirname(t),b()+".tmp");try{await o.writeFile(i,e,{mode:384,flag:"wx"}),await o.rename(i,t)}finally{await o.rm(i,{force:!0})}}async function W(t,e){t=await o.realpath(t);const i=await O(t,_(e.account_id));if(e.project_id!==i.project_id)throw new Error("context_mismatch");const r=_(e.mutation_id),n=e.input;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_input");const c={mutation_id:r,...e.selection_id?{selection_id:_(e.selection_id)}:{},service_key:e.service_key,input:n,input_evidence:e.input_evidence||{},source_ids:e.source_ids||[],ai_model:e.ai_model,ai_budget_usd:e.ai_budget_usd},a=await y(await o.realpath(t),[".dxir","analyses",r]);if(e.selection_id){const d=s.join(a,"selection.json");if((await o.lstat(d)).isSymbolicLink())throw new Error("unsafe_project_mapping");const w=JSON.parse(await o.readFile(d,"utf8"));if(w.selection_id!==e.selection_id||w.mutation_id!==r)throw new Error("selection_checkpoint_mismatch")}const l=s.join(a,"input.json"),p=JSON.stringify(c,null,2)+`
`,m=e.retry_after_needs_input;return await F(a,async()=>{const d=await x(l);if(!m){if(d===p)return;if(d!==null)throw new Error("existing_file_differs");return N(l,p)}const w=m.response;if(!c.selection_id||w?.status!=="needs_input"||w.service_key!==c.service_key||Object.hasOwn(w,"selection_id")&&w.selection_id!==c.selection_id||Object.hasOwn(w,"mutation_id")&&w.mutation_id!==r||w.analysis_id||w.input_sha256||!Array.isArray(w.input_errors)||!w.input_errors.length||!w.input_errors.every(g=>typeof g?.field=="string"&&g.field.length))throw new Error("analysis_correction_invalid");if(d===p)return;if(d===null)throw new Error("analysis_correction_stale");const j=h(d);if(j!==m.checkpoint_sha256)throw new Error("analysis_correction_stale");if(await x(s.join(a,"receipt.json"))!==null)throw new Error("analysis_already_prepared");const u=new Set(w.input_errors.map(g=>g.field)),k=JSON.parse(d),v=JSON.parse(p),f={...k,input_evidence:v.input_evidence,...u.has("source_ids")?{source_ids:v.source_ids}:{},input:{...k.input}};for(const g of u)Object.hasOwn(v.input,g)?f.input[g]=v.input[g]:delete f.input[g];const S=!J(k.input,v.input)||u.has("source_ids")&&!J(k.source_ids,v.source_ids)||(u.has("source_ids")||u.has("input_evidence"))&&!J(k.input_evidence,v.input_evidence);if(!J(f,v)||!S)throw new Error("analysis_correction_invalid");const C=s.join(a,"input-"+j+".json"),T=await x(C);if(T!==null&&T!==d)throw new Error("existing_file_differs");T===null&&await N(C,d),await N(l,p)}),{file:s.relative(t,l),mutation_id:r,checkpoint_sha256:h(p)}}async function Z(t,e){t=await o.realpath(t);const i=await O(t,_(e.account_id));if(e.project_id!==i.project_id)throw new Error("context_mismatch");const r=_(e.mutation_id),n=s.join(t,".dxir","connection.json");if((await o.lstat(n)).isSymbolicLink())throw new Error("unsafe_project_mapping");const c=JSON.parse(await o.readFile(n,"utf8"));if(_(e.connection_id)!==c.connection_id)throw new Error("context_mismatch");const a={mutation_id:r,connection_id:e.connection_id},l=await y(t,[".dxir","analyses",r]);if(await E(s.join(l,"selection-request.json"),JSON.stringify(a,null,2)+`
`),e.selection_id){const p={...a,selection_id:_(e.selection_id)};return await E(s.join(l,"selection.json"),JSON.stringify(p,null,2)+`
`),p}return a}async function G(t,e){t=await o.realpath(t);const i=await O(t,_(e.account_id));if(e.project_id!==i.project_id)throw new Error("context_mismatch");const r=_(e.mutation_id),n=await y(t,[".dxir","analyses",r]);if(!/^[a-f0-9]{64}$/.test(e.input_sha256))throw new Error("invalid_hash");const c={mutation_id:r,analysis_id:_(e.analysis_id),input_sha256:e.input_sha256};return await F(n,async()=>{const a=await x(s.join(n,"input.json")),l=a&&JSON.parse(a);if(!l||l.mutation_id!==r||l.service_key!==e.service_key||(l.selection_id||null)!==(e.selection_id||null)||e.checkpoint_sha256&&e.checkpoint_sha256!==h(a))throw new Error("analysis_checkpoint_mismatch");const p=s.join(n,"receipt.json"),m=await x(p),d=JSON.stringify(c,null,2)+`
`;if(m!==null&&m!==d)throw new Error("existing_file_differs");m===null&&await N(p,d)}),c}async function q(t,e){t=await o.realpath(t),_(e);const i=await y(t,[".dxir"]),r=s.join(i,"connection.json");return await E(r,JSON.stringify({connection_id:e},null,2)+`
`),{connection_id:e}}function L(t){return typeof t=="string"&&t.length<=200&&/^(?:[A-Za-z0-9_.:-]+[_:.])?dxir_strategy_automation(?:_read)?$/.test(t)}async function M(t,e={}){t=await o.realpath(t);const i=s.join(t,".dxir");try{if(!(await o.lstat(i)).isDirectory())throw new Error("unsafe_project_mapping")}catch(f){if(f.code==="ENOENT"&&!e.read_tool)return{status:"unbound"};throw f}const r=JSON.parse(await x(s.join(i,"project.json"))),n=JSON.parse(await x(s.join(i,"connection.json")));if((!r||!n)&&!e.read_tool)return{status:"unbound"};const c=JSON.parse(await x(s.join(i,"location.json")));if(!r||!n||c?.location_key!==h(process.platform==="win32"?t.toLowerCase():t))throw new Error("context_mismatch");const a={account_id:_(r.account_id),project_id:_(r.project_id),connection_id:_(n.connection_id),folder_key:_(r.folder_key)},l=s.join(i,"strategy-route.json");if(e.read_tool!==void 0){if(!L(e.read_tool)||e.account_id!==a.account_id||e.view?.project_id!==a.project_id||e.view?.connection_id!==a.connection_id||!["inactive","running","waiting","stopped"].includes(e.view?.status)||!Number.isSafeInteger(e.view.revision)||e.view.revision<0)throw new Error("verified_strategy_read_required");await F(i,async()=>{const f=JSON.stringify({...a,read_tool:e.read_tool})+`
`;await x(l)!==f&&await N(l,f)})}const p=JSON.parse(await x(l)),d=p&&Object.entries(a).every(([f,S])=>p[f]===S)&&L(p.read_tool)?p.read_tool:null,w={status:"bound",...a,preferred_read_tool:d};if(e.available_read_tools===void 0)return w;if(!Array.isArray(e.available_read_tools)||!e.available_read_tools.every(L))throw new Error("invalid_read_routes");const j=new Set(e.available_read_tools),u=e.attempts??[];if(!Array.isArray(u)||u.some(f=>!L(f?.tool)||typeof f.code!="string"))throw new Error("invalid_read_routes");const k=u.find(({code:f,confirmed_revocation:S})=>f==="dxir_project_approval_required"||f==="dxir_connection_revoked"&&S===!0);for(const{tool:f}of u)j.delete(f);const v=k||u.length>=2?null:j.has(d)?d:j.values().next().value??null;return{...w,next_read_tool:v,access_error:k?.code??null}}async function Q(t,e,i=t){if(t=await o.realpath(t),i=await o.realpath(i),!e||s.isAbsolute(e))throw new Error("select_relative_file");const r=s.resolve(t,e);A(t,r);const n=s.relative(t,r).split(s.sep);if(n.some(j=>[".git",".dxir","node_modules",".ssh"].includes(j))||/(^\.env(?:\.|$)|\.(?:pem|key|p12|pfx)$)/i.test(s.basename(r)))throw new Error("sensitive_or_generated_path");let c=t;for(const j of n)if(c=s.join(c,j),(await o.lstat(c)).isSymbolicLink())throw new Error("symlink_not_allowed");A(t,await o.realpath(r));const a=await o.stat(r);if(!a.isFile()||a.size<1||a.size>15*1024*1024)throw new Error("invalid_file_size");const l=await o.readFile(r),p=h(l),m=s.extname(r).toLowerCase(),d={".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}[m];if(!d)throw new Error("unsupported_file_type");const w=await y(i,[".dxir","sources",p]);return await E(s.join(w,"source"),l),{source_id:b(),file_name:s.basename(r),content_type:d,size_bytes:l.length,sha256:p,snapshot:s.relative(i,s.join(w,"source"))}}async function V(t,e){if(t=await o.realpath(t),!/^[a-f0-9]{64}$/.test(e.sha256))throw new Error("invalid_hash");const i=await y(t,[".dxir","sources",e.sha256]),r=s.join(i,"source");if((await o.lstat(r)).isSymbolicLink())throw new Error("symlink_not_allowed");const n=await o.readFile(r);if(h(n)!==e.sha256)throw new Error("snapshot_hash_mismatch");const c=new URL(e.upload_url);if(c.protocol!=="https:"||c.hostname!=="weufexgfzkdzqkfjxdpj.supabase.co"||c.port||c.username||c.password||!c.pathname.startsWith("/storage/v1/object/upload/sign/dxir-project-sources/"))throw new Error("invalid_upload_destination");if(!(await fetch(c,{method:"PUT",headers:{"Content-Type":e.content_type},body:n,redirect:"error"})).ok)throw new Error("upload_failed");return{uploaded:!0,sha256:e.sha256,size_bytes:n.length}}async function Y(t,e){if(t=await o.realpath(t),_(e.analysis_id),typeof e.html!="string"||!/^[a-f0-9]{64}$/.test(e.sha256)||h(Buffer.from(e.html))!==e.sha256)throw new Error("report_hash_mismatch");const i=await y(t,[".dxir","reports",e.analysis_id,e.sha256]),r=s.join(i,"report.html");return await F(i,async()=>{const n=await o.lstat(r).catch(a=>{if(a.code!=="ENOENT")throw a;return null});if(n){if(!n.isFile()||n.nlink!==1)throw new Error("unsafe_report_cache");if(h(await o.readFile(r))===e.sha256)return}const c=s.join(i,b()+".tmp");try{const a=await o.open(c,"wx",384);try{await a.writeFile(e.html),await a.sync()}finally{await a.close()}n&&await o.rename(r,s.join(i,"report-conflict-"+b()+".bin")),await o.rename(c,r)}finally{await o.rm(c,{force:!0})}}),{file:s.relative(t,r),sha256:e.sha256,verified:!0}}async function I(t,e){t=await o.realpath(t);const i=await y(t,[".dxir"]),r=JSON.parse(await o.readFile(s.join(i,"project.json"),"utf8")),n=JSON.parse(await o.readFile(s.join(i,"connection.json"),"utf8"));if(JSON.parse(await o.readFile(s.join(i,"location.json"),"utf8")).location_key!==h(process.platform==="win32"?t.toLowerCase():t))throw new Error("project_location_changed");if(e.account_id!==r.account_id||e.project_id!==r.project_id||e.connection_id!==n.connection_id)throw new Error("room_project_mismatch");if(e.binding_status!=="active"||e.decision!=="start")throw new Error("room_not_bound");const a={version:1,handoff_id:_(e.id),room_id:_(e.room_id),binding_id:_(e.binding_id),executor_key:_(e.executor_key),execution_context_id:_(e.execution_context_id),project_id:r.project_id,connection_id:n.connection_id,account_id:r.account_id},l=await y(t,[".dxir","rooms",a.room_id]);return await E(s.join(l,`${a.binding_id}.json`),JSON.stringify(a,null,2)+`
`),a}async function K(){const[t,...e]=process.argv.slice(2),i=Object.fromEntries(e.reduce((a,l,p)=>p%2===0?[...a,[l.replace(/^--/,""),e[p+1]]]:a,[])),r=i.root||process.cwd();if(t==="folder-plan"||t==="folder-create"){const a=t==="folder-plan"?await z(i.name,i.parent):await X(i.name,i.parent,i["approved-path"]);process.stdout.write(JSON.stringify(a)+`
`);return}let n;if(["upload","upload-artifact","save-report","room-bind","context-bind","strategy-route","checkpoint-input","save-selection","save-analysis"].includes(t)){const a=[];let l=0;for await(const p of process.stdin){if(l+=p.length,l>20*1024*1024)throw new Error("input_too_large");a.push(p)}n=JSON.parse(Buffer.concat(a).toString("utf8"))}if(t==="strategy-route"){process.stdout.write(JSON.stringify(await M(r,n))+`
`);return}const c=t==="artifact"?B(i.file,r):t==="upload-artifact"?await R({file:n.relative_path,cwd:r,sha256:n.sha256,contentType:n.content_type,uploadUrl:n.upload_url}):t==="context-init"?await O(r,i["account-id"]):t==="context-bind"?await H(r,n):t==="checkpoint-input"?await W(r,n):t==="save-selection"?await Z(r,n):t==="save-analysis"?await G(r,n):t==="init"?await $(r,i["project-id"],i["account-id"]):t==="bind"?await q(r,i["connection-id"]):t==="snapshot"?await Q(r,i.file,i["snapshot-root"]):t==="upload"?await V(r,n):t==="room-bind"?await I(r,n):t==="save-report"?await Y(r,n):(()=>{throw new Error("unknown_command")})();process.stdout.write(JSON.stringify(c)+`
`)}process.argv[1]&&import.meta.url===U(s.resolve(process.argv[1])).href&&K().catch(t=>{process.stderr.write(String(t.message).replace(/https?:\/\/\S+/g,"[url]")+`
`),process.exitCode=1});export{H as bindAppContext,q as bindProject,X as createProjectFolder,y as directory,O as initializeAppContext,$ as initializeProject,z as planProjectFolder,E as preserve,W as saveAnalysisCheckpoint,G as saveAnalysisReceipt,Y as saveProjectReport,I as saveRoomBinding,Z as saveSelectionCheckpoint,Q as snapshotProjectFile,M as strategyRoute,V as uploadProjectSnapshot};

SHA-256: 17b31fdbaf6831888e819d26b3dcb20faa92218fed716f0c74f52c81b2964e8e