@yuandc/aica 0.1.24 → 0.1.25
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Agent as
|
|
1
|
+
import{Agent as S}from"undici";import $ from"node:crypto";import E from"node:fs";import{Readable as p,Transform as v}from"node:stream";import{pipeline as U}from"node:stream/promises";import{loadAcaConfig as g}from"./aca-config.js";const _=new S({connect:{rejectUnauthorized:!1}}),b=15e3,y=12e4,x=12e4;async function C(e,t,r,n={}){const i=g(),a=(n.serverUrl||i.serverUrl).replace(/\/$/,""),o=n.token??i.token,l={...r===void 0?{}:{"content-type":"application/json"},...o?{authorization:`Bearer ${o}`}:{}},u=h(n,b);try{const s=await fetch(`${a}${t}`,{method:e,headers:l,signal:u.signal,...r===void 0?{}:{body:JSON.stringify(r)},...d(a)}),f=await s.text(),c=f?JSON.parse(f):null;if(!s.ok){const m=c&&typeof c=="object"&&"message"in c?String(c.message):`HTTP ${s.status}`;throw new Error(m)}return c}catch(s){throw w(s,e,t,u)}finally{u.dispose()}}async function q(e,t={}){const r=g(),n=(t.serverUrl||r.serverUrl).replace(/\/$/,""),i=t.token??r.token,a=h(t,y);try{const o=await fetch(`${n}${e}`,{method:"GET",headers:i?{authorization:`Bearer ${i}`}:{},signal:a.signal,...d(n)});if(!o.ok)throw new Error(`附件下载失败 HTTP ${o.status}`);return Buffer.from(await o.arrayBuffer())}catch(o){throw w(o,"GET",e,a)}finally{a.dispose()}}async function z(e,t,r={}){const n=g(),i=(r.serverUrl||n.serverUrl).replace(/\/$/,""),a=r.token??n.token,o=h(r,y);let l=0;const u=$.createHash("sha256");try{const s=await fetch(`${i}${e}`,{method:"GET",headers:a?{authorization:`Bearer ${a}`}:{},signal:o.signal,...d(i)});if(!s.ok)throw new Error(`项目文件下载失败 HTTP ${s.status}`);if(!s.body)throw new Error("项目文件下载响应为空");const f=new v({transform(c,m,T){if(l+=c.byteLength,Number.isFinite(r.maxBytes)&&l>Number(r.maxBytes)){T(new Error("project_upload_too_large"));return}u.update(c),T(null,c)}});return await U(p.fromWeb(s.body),f,E.createWriteStream(t,{flags:"wx",mode:384})),{sizeBytes:l,sha256:u.digest("hex")}}catch(s){throw u.digest(),E.rmSync(t,{force:!0}),w(s,"GET",e,o)}finally{o.dispose()}}async function D(e,t,r,n={},i={}){const a=g(),o=(i.serverUrl||a.serverUrl).replace(/\/$/,""),l=i.token??a.token,u=h(i,x);try{const s=await fetch(`${o}${t}`,{method:e,headers:{...n,...l?{authorization:`Bearer ${l}`}:{}},body:r,duplex:"half",signal:u.signal,...d(o)}),f=await s.text(),c=f?JSON.parse(f):null;if(!s.ok){const m=c&&typeof c=="object"&&"message"in c?String(c.message):`HTTP ${s.status}`;throw new Error(m)}return c}catch(s){throw w(s,e,t,u)}finally{u.dispose()}}function h(e,t){const r=A(e.timeoutMs,t),n=new AbortController;let i=!1;const a=()=>n.abort(e.signal?.reason);e.signal?.aborted?a():e.signal?.addEventListener("abort",a,{once:!0});const o=setTimeout(()=>{i=!0,n.abort(new Error(`ACA Server request timed out after ${r}ms`))},r);return o.unref(),{signal:n.signal,timeoutMs:r,timedOut:()=>i,dispose:()=>{clearTimeout(o),e.signal?.removeEventListener("abort",a)}}}function w(e,t,r,n){return n.timedOut()?new Error(`ACA Server 请求超时(${n.timeoutMs}ms):${t} ${r}`,{cause:e}):e instanceof Error?e:new Error(String(e))}function A(e,t){return!Number.isFinite(e)||Number(e)<=0?t:Math.max(250,Math.min(Number(e),30*6e4))}function d(e){return!/^https:/i.test(e)||!k(process.env.ACA_SERVER_INSECURE_TLS)?{}:{dispatcher:_}}function k(e){return e==="1"||e?.toLowerCase()==="true"||e?.toLowerCase()==="yes"}export{q as acaServerDownload,z as acaServerDownloadToFile,C as acaServerRequest,D as acaServerStreamRequest};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{execFileSync as h}from"node:child_process";import{randomUUID as H}from"node:crypto";import l from"node:fs";import k from"node:os";import c from"node:path";import{acaServerRequest as y}from"./aca-server-client.js";import{loadAcaConfig as W,upsertLocalProject as B}from"./aca-config.js";import{startLongPollWorker as U}from"./long-poll-worker.js";import{expandWorkerRuntimePath as z}from"./worker-runtime-paths.js";const D=25e3,K=D+1e4,S=300,J=3e4;let b=null;function Nt(t){return U({run:async()=>{const e=W();if(!e.token)throw new Error("Worker 尚未配置认证令牌");const r=await y("GET",`/api/client/machine-operations/claim?machineId=${encodeURIComponent(e.machineId)}&waitMs=${D}`,void 0,{timeoutMs:K});if(r.item)try{const o=await V(r.item);await y("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/complete`,{result:o})}catch(o){const n=o instanceof Error?o.message:String(o);t.warn(`machine filesystem request failed request=${r.item.requestId}: ${n}`),await y("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/fail`,{message:n}).catch(()=>{})}},onError:(e,r)=>t.warn(`machine filesystem worker failed, retry in ${r}ms: ${e instanceof Error?e.message:String(e)}`)})}async function V(t){if(t.operation==="filesystem_roots")return ut();if(t.operation==="list_directory")return lt({directoryPath:String(t.payload.path||""),includeHidden:t.payload.includeHidden===!0});if(t.operation==="register_project")return wt(t.payload);if(t.operation==="list_project_directory")return Q(t.payload);if(t.operation==="get_project_git_status")return $(t.payload);if(t.operation==="get_project_git_diff")return Z(t.payload);if(t.operation==="get_project_git_log")return q(t.payload);if(t.operation==="get_project_git_commit")return tt(t.payload);if(t.operation==="get_worktree_status")return P(t.payload);if(t.operation==="commit_worktree")return X(t.payload);if(t.operation==="cleanup_worktree")return Y(t.payload);throw new Error("不支持的 Machine 文件系统操作。 ")}function P(t){const e=j(String(t.worktreePath||""));if(!l.existsSync(e))return{exists:!1,isRepository:!1,dirty:!1,changedFiles:0,ahead:0};const r=m(e);if(!p(r))return{exists:!0,isRepository:!1,dirty:nt(r),changedFiles:null,ahead:0};const o=$({rootPath:r}),n=String(t.baseCommit||"").trim(),s=n&&/^[0-9a-f]{7,64}$/i.test(n)?ot(r,n):0;return{exists:!0,isRepository:!0,dirty:Array.isArray(o.files)&&o.files.length>0,changedFiles:Array.isArray(o.files)?o.files.length:0,branch:o.branch,ahead:s,files:Array.isArray(o.files)?o.files.slice(0,50):[],truncated:o.truncated===!0}}function X(t){const e=m(String(t.worktreePath||"")),r=String(t.message||"").trim();if(!r)throw new Error("提交说明不能为空。");if(!p(e))throw new Error("当前 Worktree 不是 Git 仓库,无法提交。");h("git",["-C",e,"add","-A"],{stdio:"pipe",timeout:3e4});try{return h("git",["-C",e,"diff","--cached","--quiet"],{stdio:"pipe",timeout:1e4}),{committed:!1,reason:"no_changes",...P(t)}}catch(o){if(Number(o.status)!==1)throw o}return h("git",["-C",e,"commit","-m",r],{stdio:"pipe",timeout:6e4}),{committed:!0,commit:f(e,["rev-parse","HEAD"],8*1024).trim(),...P(t)}}function Y(t){const e=j(String(t.worktreePath||"")),r=m(String(t.projectRoot||""));if(d(e)===d(r))throw new Error("不能清理项目主目录。");if(!l.existsSync(e))return{removed:!1,reason:"not_found"};const o=m(e),n=String(t.branchName||"").trim(),s=p(o)&&p(r);if(s){if(h("git",["-C",r,"worktree","remove","--force",o],{stdio:"pipe",timeout:6e4}),t.deleteBranch===!0&&n)try{h("git",["-C",r,"branch","-D",n],{stdio:"pipe",timeout:3e4})}catch(i){const a=String(i.stderr||i);if(!/not found|not exist/i.test(a))throw i}}else l.rmSync(o,{recursive:!0,force:!0,maxRetries:2,retryDelay:200});return{removed:!0,branchDeleted:!!(s&&t.deleteBranch===!0&&n)}}function Q(t){const e=m(String(t.rootPath||"")),r=x(String(t.relativePath||"")),o=yt(e,r,!0),n=Math.max(0,Number(t.offset||0)),s=Math.min(300,Math.max(20,Number(t.limit||200))),i=l.readdirSync(o,{withFileTypes:!0}).filter(u=>!u.isSymbolicLink()).map(u=>({name:u.name,path:St(e,c.join(o,u.name)),type:u.isDirectory()?"directory":u.isFile()?"file":"other",hidden:u.name.startsWith("."),extension:u.isFile()?c.extname(u.name).slice(1).toLowerCase():""})).filter(u=>u.type!=="other").sort((u,g)=>u.type!==g.type?u.type==="directory"?-1:1:u.name.localeCompare(g.name,void 0,{numeric:!0,sensitivity:"base"})),a=i.slice(n,n+s);return{path:r,rootKind:t.rootKind==="worktree"?"worktree":"project",items:a,total:i.length,nextOffset:n+a.length<i.length?n+a.length:null}}const R=500,_=2*1024*1024,w=2*1024*1024;function $(t){const e=m(String(t.rootPath||""));if(!p(e))return{isRepository:!1,branch:null,files:[],ahead:0,behind:0};const o=f(e,["status","--porcelain=v1","-z","--untracked-files=all","--no-renames"],_).split("\0").filter(Boolean).slice(0,R),n=o.map(a=>rt(a)).filter(a=>!!a),s=v(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--","."],_));for(const a of n){const u=s.get(a.path);if(u)a.additions=u.additions,a.deletions=u.deletions;else if(a.status==="untracked"){const g=C(e,a.path);a.additions=g.additions,a.deletions=g.deletions}}const i=ct(e);return{isRepository:!0,branch:at(e),files:n,ahead:i.ahead,behind:i.behind,truncated:o.length>=R}}function Z(t){const e=m(String(t.rootPath||"")),r=x(String(t.relativePath||""));if(!r)throw new Error("Diff 文件路径不能为空。");if(!p(e))return{isRepository:!1,path:r,diff:"",additions:0,deletions:0};const o=T(e,r),n=it(e,r),s=n?f(e,["diff","--no-ext-diff","--unified=80","HEAD","--",r],w):I(e,["diff","--no-ext-diff","--no-index","--unified=80",process.platform==="win32"?"NUL":"/dev/null",o],w),i=n?v(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--",r],32*1024)).get(r):C(e,r);return{isRepository:!0,path:r,diff:F(s),additions:i?.additions??0,deletions:i?.deletions??0,truncated:s.length>w}}function q(t){const e=m(String(t.rootPath||""));if(!p(e))return{isRepository:!1,items:[]};if(!st(e))return{isRepository:!0,items:[]};const r=Math.min(200,Math.max(20,Number(t.limit||100)));return{isRepository:!0,items:f(e,["log",`--max-count=${r}`,"--date=iso-strict","--pretty=format:%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%D%x1f%s%x1f%b%x1e"],_).split("").map(i=>et(i)).filter(i=>!!i),limit:r}}function tt(t){const e=m(String(t.rootPath||"")),r=String(t.commit||"").trim();if(!/^[0-9a-f]{7,64}$/i.test(r))throw new Error("Git 提交标识无效。");if(!p(e))return{isRepository:!1,commit:r,diff:"",additions:0,deletions:0};f(e,["cat-file","-e",`${r}^{commit}`],8*1024);const o=f(e,["show","--no-ext-diff","--no-color","--format=","--stat","--patch","--unified=40",r],w),n=[...v(f(e,["show","--no-ext-diff","--numstat","-z","--no-renames","--format=",r],_)).values()];return{isRepository:!0,commit:r,diff:F(o),additions:n.reduce((s,i)=>s+(i.additions||0),0),deletions:n.reduce((s,i)=>s+(i.deletions||0),0),changedFiles:n.length,truncated:o.length>w}}function et(t){const e=t.replace(/^\s+|\s+$/g,"");if(!e)return null;const r=e.split(""),o=String(r[0]||"").trim();return o?{hash:o,shortHash:String(r[1]||o.slice(0,8)).trim(),authorName:String(r[2]||"").trim(),authorEmail:String(r[3]||"").trim(),authoredAt:String(r[4]||"").trim(),refs:String(r[5]||"").trim(),subject:String(r[6]||"").trim(),body:r.slice(7).join("").trim()}:null}function rt(t){if(t.length<4)return null;const e=t[0]||" ",r=t[1]||" ",o=x(t.slice(3));return o?{path:o,status:e==="?"&&r==="?"?"untracked":e==="U"||r==="U"?"conflicted":e==="D"||r==="D"?"deleted":e==="A"||r==="A"?"added":e==="R"||r==="R"?"renamed":"modified",indexStatus:e,worktreeStatus:r,staged:e!==" "&&e!=="?",additions:null,deletions:null}:null}function v(t){const e=new Map;for(const r of t.split("\0")){if(!r)continue;const o=N(r);if(!o||!o.path)continue;const n=x(o.path);n&&e.set(n,{additions:o.additions,deletions:o.deletions})}return e}function C(t,e){const r=T(t,e),n=I(t,["diff","--no-ext-diff","--no-index","--numstat","-z","--",process.platform==="win32"?"NUL":"/dev/null",r],32*1024).split("\0",1)[0]||"",s=N(n);return s?{additions:s.additions,deletions:s.deletions}:{additions:null,deletions:null}}function N(t){const e=t.indexOf(" "),r=e<0?-1:t.indexOf(" ",e+1);if(e<0||r<0)return null;const o=t.slice(0,e),n=t.slice(e+1,r);return{additions:/^\d+$/.test(o)?Number(o):null,deletions:/^\d+$/.test(n)?Number(n):null,path:t.slice(r+1)}}function p(t){try{return f(t,["rev-parse","--is-inside-work-tree"],8*1024).trim()==="true"}catch(e){if(String(e.code||"")==="ENOENT")throw new Error("设备未安装 Git。");return!1}}function ot(t,e){try{const r=f(t,["rev-list","--count",`${e}..HEAD`],8192).trim(),o=Number(r);return Number.isSafeInteger(o)&&o>0?o:0}catch{return 0}}function nt(t){try{return l.readdirSync(t).length>0}catch{return!1}}function it(t,e){try{return f(t,["ls-files","--error-unmatch","--",e],8*1024),!0}catch{return!1}}function st(t){try{return f(t,["rev-parse","--verify","HEAD"],8*1024),!0}catch{return!1}}function at(t){try{return f(t,["symbolic-ref","--quiet","--short","HEAD"],8*1024).trim()||null}catch{try{return`HEAD (${f(t,["rev-parse","--short","HEAD"],8*1024).trim()})`}catch{return null}}}function ct(t){try{const e=f(t,["rev-list","--left-right","--count","HEAD...@{upstream}"],8192).trim().split(/\s+/).map(Number);return{ahead:Number.isFinite(e[0])?e[0]:0,behind:Number.isFinite(e[1])?e[1]:0}}catch{return{ahead:0,behind:0}}}function T(t,e){const r=c.resolve(t,...e.split("/")),o=c.relative(t,r);if(o.startsWith("..")||c.isAbsolute(o))throw new Error("Diff 路径超出项目范围。");return r}function f(t,e,r){return h("git",["-C",t,...e],{encoding:"utf8",timeout:2e4,maxBuffer:r,stdio:["ignore","pipe","pipe"]})}function I(t,e,r){try{return f(t,e,r)}catch(o){const n=String(o.stdout||"");if(n)return n;if(Number(o.status)===1)return"";throw o}}function F(t){return t.length<=w?t:`${t.slice(0,w)}
|
|
1
|
+
import{execFileSync as g}from"node:child_process";import{randomUUID as R}from"node:crypto";import l from"node:fs";import T from"node:os";import c from"node:path";import{acaServerDownloadToFile as Q,acaServerRequest as b}from"./aca-server-client.js";import{loadAcaConfig as Z,upsertLocalProject as q}from"./aca-config.js";import{startLongPollWorker as tt}from"./long-poll-worker.js";import{expandWorkerRuntimePath as et}from"./worker-runtime-paths.js";const F=25e3,rt=F+1e4,x=300,ot=3e4;let E=null;function zt(t){return tt({run:async()=>{const e=Z();if(!e.token)throw new Error("Worker 尚未配置认证令牌");const r=await b("GET",`/api/client/machine-operations/claim?machineId=${encodeURIComponent(e.machineId)}&waitMs=${F}`,void 0,{timeoutMs:rt});if(r.item)try{const o=await nt(r.item);await b("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/complete`,{result:o})}catch(o){const n=o instanceof Error?o.message:String(o);t.warn(`machine filesystem request failed request=${r.item.requestId}: ${n}`),await b("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/fail`,{message:n}).catch(()=>{})}},onError:(e,r)=>t.warn(`machine filesystem worker failed, retry in ${r}ms: ${e instanceof Error?e.message:String(e)}`)})}async function nt(t){if(t.operation==="filesystem_roots")return Et();if(t.operation==="list_directory")return _t({directoryPath:String(t.payload.path||""),includeHidden:t.payload.includeHidden===!0});if(t.operation==="register_project")return Dt(t.payload);if(t.operation==="list_project_directory")return at(t.payload);if(t.operation==="upload_project_file")return ct(t.payload);if(t.operation==="get_project_git_status")return O(t.payload);if(t.operation==="get_project_git_diff")return dt(t.payload);if(t.operation==="get_project_git_log")return mt(t.payload);if(t.operation==="get_project_git_commit")return pt(t.payload);if(t.operation==="get_worktree_status")return j(t.payload);if(t.operation==="commit_worktree")return it(t.payload);if(t.operation==="cleanup_worktree")return st(t.payload);throw new Error("不支持的 Machine 文件系统操作。 ")}function j(t){const e=D(String(t.worktreePath||""));if(!l.existsSync(e))return{exists:!1,isRepository:!1,dirty:!1,changedFiles:0,ahead:0};const r=m(e);if(!w(r))return{exists:!0,isRepository:!1,dirty:yt(r),changedFiles:null,ahead:0};const o=O({rootPath:r}),n=String(t.baseCommit||"").trim(),s=n&&/^[0-9a-f]{7,64}$/i.test(n)?gt(r,n):0;return{exists:!0,isRepository:!0,dirty:Array.isArray(o.files)&&o.files.length>0,changedFiles:Array.isArray(o.files)?o.files.length:0,branch:o.branch,ahead:s,files:Array.isArray(o.files)?o.files.slice(0,50):[],truncated:o.truncated===!0}}function it(t){const e=m(String(t.worktreePath||"")),r=String(t.message||"").trim();if(!r)throw new Error("提交说明不能为空。");if(!w(e))throw new Error("当前 Worktree 不是 Git 仓库,无法提交。");g("git",["-C",e,"add","-A"],{stdio:"pipe",timeout:3e4});try{return g("git",["-C",e,"diff","--cached","--quiet"],{stdio:"pipe",timeout:1e4}),{committed:!1,reason:"no_changes",...j(t)}}catch(o){if(Number(o.status)!==1)throw o}return g("git",["-C",e,"commit","-m",r],{stdio:"pipe",timeout:6e4}),{committed:!0,commit:f(e,["rev-parse","HEAD"],8*1024).trim(),...j(t)}}function st(t){const e=D(String(t.worktreePath||"")),r=m(String(t.projectRoot||""));if(p(e)===p(r))throw new Error("不能清理项目主目录。");if(!l.existsSync(e))return{removed:!1,reason:"not_found"};const o=m(e),n=String(t.branchName||"").trim(),s=w(o)&&w(r);if(s){if(g("git",["-C",r,"worktree","remove","--force",o],{stdio:"pipe",timeout:6e4}),t.deleteBranch===!0&&n)try{g("git",["-C",r,"branch","-D",n],{stdio:"pipe",timeout:3e4})}catch(i){const a=String(i.stderr||i);if(!/not found|not exist/i.test(a))throw i}}else l.rmSync(o,{recursive:!0,force:!0,maxRetries:2,retryDelay:200});return{removed:!0,branchDeleted:!!(s&&t.deleteBranch===!0&&n)}}function at(t){const e=m(String(t.rootPath||"")),r=P(String(t.relativePath||"")),o=N(e,r,!0),n=Math.max(0,Number(t.offset||0)),s=Math.min(300,Math.max(20,Number(t.limit||200))),i=l.readdirSync(o,{withFileTypes:!0}).filter(u=>!u.isSymbolicLink()).map(u=>({name:u.name,path:K(e,c.join(o,u.name)),type:u.isDirectory()?"directory":u.isFile()?"file":"other",hidden:u.name.startsWith("."),extension:u.isFile()?c.extname(u.name).slice(1).toLowerCase():""})).filter(u=>u.type!=="other").sort((u,d)=>u.type!==d.type?u.type==="directory"?-1:1:u.name.localeCompare(d.name,void 0,{numeric:!0,sensitivity:"base"})),a=i.slice(n,n+s);return{path:r,rootKind:t.rootKind==="worktree"?"worktree":"project",items:a,total:i.length,nextOffset:n+a.length<i.length?n+a.length:null}}async function ct(t){const e=String(t.uploadId||"").trim();if(!e)throw new Error("项目上传任务缺少 uploadId。");const r=m(String(t.rootPath||"")),o=P(String(t.relativeDirectory||"")),n=N(r,o,!0),s=I(String(t.fileName||"")),i=Number(t.sizeBytes),a=String(t.sha256||"").trim().toLowerCase();if(!Number.isSafeInteger(i)||i<0)throw new Error("项目上传文件大小无效。");if(!/^[0-9a-f]{64}$/.test(a))throw new Error("项目上传文件摘要无效。");const u=c.join(n,`.aca-upload-${R()}.tmp`);try{const d=await Q(`/api/client/project-uploads/${encodeURIComponent(e)}`,u,{maxBytes:i,timeoutMs:3e5});if(d.sizeBytes!==i)throw new Error("项目上传文件大小校验失败。");if(d.sha256.toLowerCase()!==a)throw new Error("项目上传文件完整性校验失败。");const h=lt(r,o,s,u);return{name:c.basename(h),path:K(r,h),directory:o,size:d.sizeBytes,sha256:d.sha256,renamed:c.basename(h)!==s,rootKind:t.rootKind==="worktree"?"worktree":"project"}}finally{l.rmSync(u,{force:!0})}}function lt(t,e,r,o){const n=m(t),s=P(e),i=N(n,s,!0),a=I(r);if(l.realpathSync.native(c.dirname(o))!==i)throw new Error("项目上传临时文件不在目标目录中。");const d=l.lstatSync(o);if(!d.isFile()||d.isSymbolicLink())throw new Error("项目上传临时文件无效。");for(let h=1;h<=1e4;h+=1){const J=h===1?a:ut(a,h),S=c.join(i,J);try{return l.linkSync(o,S),l.chmodSync(S,420),l.rmSync(o,{force:!0}),S}catch(v){if(L(v))continue;if(!ft(v))throw v;try{return l.copyFileSync(o,S,l.constants.COPYFILE_EXCL),l.chmodSync(S,420),l.rmSync(o,{force:!0}),S}catch(C){if(L(C))continue;throw C}}}throw new Error("同名文件过多,无法生成可用文件名。")}function I(t){const e=t.trim();if(!e||e==="."||e===".."||/[\\/\x00-\x1F]/.test(e))throw new Error("项目上传文件名无效。");if(process.platform==="win32"&&(/[<>:"|?*]/.test(e)||/[. ]$/.test(e)))throw new Error("项目上传文件名在 Windows 上无效。");return e.slice(0,180)}function ut(t,e){const r=c.extname(t);return`${r?t.slice(0,-r.length):t} (${e})${r}`}function L(t){return!!(t&&typeof t=="object"&&t.code==="EEXIST")}function ft(t){const e=t&&typeof t=="object"?t.code:"";return["EPERM","EACCES","EXDEV","ENOTSUP","EOPNOTSUPP"].includes(String(e||""))}const M=500,_=2*1024*1024,y=2*1024*1024;function O(t){const e=m(String(t.rootPath||""));if(!w(e))return{isRepository:!1,branch:null,files:[],ahead:0,behind:0};const o=f(e,["status","--porcelain=v1","-z","--untracked-files=all","--no-renames"],_).split("\0").filter(Boolean).slice(0,M),n=o.map(a=>wt(a)).filter(a=>!!a),s=A(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--","."],_));for(const a of n){const u=s.get(a.path);if(u)a.additions=u.additions,a.deletions=u.deletions;else if(a.status==="untracked"){const d=G(e,a.path);a.additions=d.additions,a.deletions=d.deletions}}const i=xt(e);return{isRepository:!0,branch:bt(e),files:n,ahead:i.ahead,behind:i.behind,truncated:o.length>=M}}function dt(t){const e=m(String(t.rootPath||"")),r=P(String(t.relativePath||""));if(!r)throw new Error("Diff 文件路径不能为空。");if(!w(e))return{isRepository:!1,path:r,diff:"",additions:0,deletions:0};const o=W(e,r),n=St(e,r),s=n?f(e,["diff","--no-ext-diff","--unified=80","HEAD","--",r],y):B(e,["diff","--no-ext-diff","--no-index","--unified=80",process.platform==="win32"?"NUL":"/dev/null",o],y),i=n?A(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--",r],32*1024)).get(r):G(e,r);return{isRepository:!0,path:r,diff:U(s),additions:i?.additions??0,deletions:i?.deletions??0,truncated:s.length>y}}function mt(t){const e=m(String(t.rootPath||""));if(!w(e))return{isRepository:!1,items:[]};if(!Pt(e))return{isRepository:!0,items:[]};const r=Math.min(200,Math.max(20,Number(t.limit||100)));return{isRepository:!0,items:f(e,["log",`--max-count=${r}`,"--date=iso-strict","--pretty=format:%H%x1f%h%x1f%an%x1f%ae%x1f%aI%x1f%D%x1f%s%x1f%b%x1e"],_).split("").map(i=>ht(i)).filter(i=>!!i),limit:r}}function pt(t){const e=m(String(t.rootPath||"")),r=String(t.commit||"").trim();if(!/^[0-9a-f]{7,64}$/i.test(r))throw new Error("Git 提交标识无效。");if(!w(e))return{isRepository:!1,commit:r,diff:"",additions:0,deletions:0};f(e,["cat-file","-e",`${r}^{commit}`],8*1024);const o=f(e,["show","--no-ext-diff","--no-color","--format=","--stat","--patch","--unified=40",r],y),n=[...A(f(e,["show","--no-ext-diff","--numstat","-z","--no-renames","--format=",r],_)).values()];return{isRepository:!0,commit:r,diff:U(o),additions:n.reduce((s,i)=>s+(i.additions||0),0),deletions:n.reduce((s,i)=>s+(i.deletions||0),0),changedFiles:n.length,truncated:o.length>y}}function ht(t){const e=t.replace(/^\s+|\s+$/g,"");if(!e)return null;const r=e.split(""),o=String(r[0]||"").trim();return o?{hash:o,shortHash:String(r[1]||o.slice(0,8)).trim(),authorName:String(r[2]||"").trim(),authorEmail:String(r[3]||"").trim(),authoredAt:String(r[4]||"").trim(),refs:String(r[5]||"").trim(),subject:String(r[6]||"").trim(),body:r.slice(7).join("").trim()}:null}function wt(t){if(t.length<4)return null;const e=t[0]||" ",r=t[1]||" ",o=P(t.slice(3));return o?{path:o,status:e==="?"&&r==="?"?"untracked":e==="U"||r==="U"?"conflicted":e==="D"||r==="D"?"deleted":e==="A"||r==="A"?"added":e==="R"||r==="R"?"renamed":"modified",indexStatus:e,worktreeStatus:r,staged:e!==" "&&e!=="?",additions:null,deletions:null}:null}function A(t){const e=new Map;for(const r of t.split("\0")){if(!r)continue;const o=H(r);if(!o||!o.path)continue;const n=P(o.path);n&&e.set(n,{additions:o.additions,deletions:o.deletions})}return e}function G(t,e){const r=W(t,e),n=B(t,["diff","--no-ext-diff","--no-index","--numstat","-z","--",process.platform==="win32"?"NUL":"/dev/null",r],32*1024).split("\0",1)[0]||"",s=H(n);return s?{additions:s.additions,deletions:s.deletions}:{additions:null,deletions:null}}function H(t){const e=t.indexOf(" "),r=e<0?-1:t.indexOf(" ",e+1);if(e<0||r<0)return null;const o=t.slice(0,e),n=t.slice(e+1,r);return{additions:/^\d+$/.test(o)?Number(o):null,deletions:/^\d+$/.test(n)?Number(n):null,path:t.slice(r+1)}}function w(t){try{return f(t,["rev-parse","--is-inside-work-tree"],8*1024).trim()==="true"}catch(e){if(String(e.code||"")==="ENOENT")throw new Error("设备未安装 Git。");return!1}}function gt(t,e){try{const r=f(t,["rev-list","--count",`${e}..HEAD`],8192).trim(),o=Number(r);return Number.isSafeInteger(o)&&o>0?o:0}catch{return 0}}function yt(t){try{return l.readdirSync(t).length>0}catch{return!1}}function St(t,e){try{return f(t,["ls-files","--error-unmatch","--",e],8*1024),!0}catch{return!1}}function Pt(t){try{return f(t,["rev-parse","--verify","HEAD"],8*1024),!0}catch{return!1}}function bt(t){try{return f(t,["symbolic-ref","--quiet","--short","HEAD"],8*1024).trim()||null}catch{try{return`HEAD (${f(t,["rev-parse","--short","HEAD"],8*1024).trim()})`}catch{return null}}}function xt(t){try{const e=f(t,["rev-list","--left-right","--count","HEAD...@{upstream}"],8192).trim().split(/\s+/).map(Number);return{ahead:Number.isFinite(e[0])?e[0]:0,behind:Number.isFinite(e[1])?e[1]:0}}catch{return{ahead:0,behind:0}}}function W(t,e){const r=c.resolve(t,...e.split("/")),o=c.relative(t,r);if(o.startsWith("..")||c.isAbsolute(o))throw new Error("Diff 路径超出项目范围。");return r}function f(t,e,r){return g("git",["-C",t,...e],{encoding:"utf8",timeout:2e4,maxBuffer:r,stdio:["ignore","pipe","pipe"]})}function B(t,e,r){try{return f(t,e,r)}catch(o){const n=String(o.stdout||"");if(n)return n;if(Number(o.status)===1)return"";throw o}}function U(t){return t.length<=y?t:`${t.slice(0,y)}
|
|
2
2
|
|
|
3
|
-
[Diff 内容过大,已截断]`}function
|
|
4
|
-
`),o=
|
|
5
|
-
`),n=
|
|
3
|
+
[Diff 内容过大,已截断]`}function Et(){const t=process.platform,e=k(t);return{platform:t,roots:e}}function _t(t){if(!t.directoryPath.trim())throw new Error("目录路径不能为空。");return process.platform==="win32"?kt(t.directoryPath,!!t.includeHidden):At(t.directoryPath,!!t.includeHidden)}function p(t,e=process.platform){const r=e==="win32"?c.win32:c.posix,o=r.normalize(t),n=r.parse(o).root,s=o.length>n.length?o.replace(/[\\/]+$/,""):o;return e==="win32"?s.toLocaleLowerCase("en-US"):s}function vt(){const t=l.realpathSync(T.homedir()),e=[{id:"home",label:"用户目录",path:t,kind:"home",available:!0}];return t!==c.parse(t).root&&e.push({id:"root",label:"文件系统",path:"/",kind:"root",available:!0}),e}function k(t){if(E?.platform===t&&E.expiresAtMs>Date.now())return E.roots;const e=t==="win32"?jt():vt();return E={platform:t,roots:e,expiresAtMs:Date.now()+ot},e}function jt(){const t=l.realpathSync.native(T.homedir()),e=new Map;e.set(p(t,"win32"),{id:"home",label:"用户目录",path:t,kind:"home",available:!0});try{const r=["$items = Get-CimInstance Win32_LogicalDisk | ForEach-Object {"," [PSCustomObject]@{ Name = $_.DeviceID; Root = ($_.DeviceID + '\\\\'); DriveType = $_.DriveType; VolumeName = $_.VolumeName }","}","@($items) | ConvertTo-Json -Compress"].join(`
|
|
4
|
+
`),o=Y(V(r));for(const n of o){const s=String(n.Root||"");if(!s)continue;const i=Number(n.DriveType||0),a=String(n.Name||s.replace(/[\\/]+$/,"")),u=String(n.VolumeName||"").trim();e.set(p(s,"win32"),{id:`drive-${a.replace(/[^a-z0-9]+/gi,"").toLowerCase()}`,label:u?`${u} (${a})`:Ft(a,i),path:s,kind:Tt(i),available:!0})}}catch{const r=c.win32.parse(t).root;e.set(p(r,"win32"),{id:"drive-system",label:`系统盘 (${r.replace(/\\$/,"")})`,path:r,kind:"fixed",available:!0})}return[...e.values()]}function At(t,e){const r=$(t),n=l.readdirSync(r,{withFileTypes:!0}).filter(i=>i.isDirectory()&&!i.isSymbolicLink()&&(e||!i.name.startsWith("."))),s=n.slice(0,x).map(i=>({name:i.name,path:c.join(r,i.name),kind:"directory",hidden:i.name.startsWith("."),hasChildren:!0}));return s.sort((i,a)=>i.name.localeCompare(a.name,void 0,{numeric:!0,sensitivity:"base"})),z(r,s,n.length>x,"linux")}function kt(t,e){const r=$(t),o=["$items = Get-ChildItem -LiteralPath $env:ACA_MACHINE_FS_PATH -Directory -Force -ErrorAction Stop | ForEach-Object {"," [PSCustomObject]@{ Name = $_.Name; FullName = $_.FullName; Attributes = $_.Attributes.ToString() }","}","@($items) | ConvertTo-Json -Compress"].join(`
|
|
5
|
+
`),n=Y(V(o,{ACA_MACHINE_FS_PATH:r})),s=n.map(i=>{const a=String(i.Attributes||"");return{name:String(i.Name||""),path:String(i.FullName||""),kind:"directory",hidden:/Hidden|System/i.test(a),hasChildren:!0,reparsePoint:/ReparsePoint/i.test(a)}}).filter(i=>i.name&&i.path&&!i.reparsePoint&&(e||!i.hidden)).slice(0,x).sort((i,a)=>i.name.localeCompare(a.name,void 0,{numeric:!0,sensitivity:"base"}));return z(r,s,n.length>x,"win32")}function z(t,e,r,o){const n=o==="win32"?c.win32:c.posix,s=n.parse(t).root,i=p(t,o)===p(s,o)?null:n.dirname(t);return{platform:o,path:t,parentPath:i,breadcrumbs:$t(t,o),readable:X(t,l.constants.R_OK),writable:X(t,l.constants.W_OK),items:e,truncated:r}}function $t(t,e){const r=e==="win32"?c.win32:c.posix,o=r.parse(t),n=t.slice(o.root.length).split(/[\\/]+/).filter(Boolean),s=[{label:o.root.replace(/[\\/]+$/,"")||o.root,path:o.root}];let i=o.root;for(const a of n)i=r.join(i,a),s.push({label:a,path:i});return s}async function Dt(t){const e=String(t.workspaceId||"").trim(),r=String(t.name||"").trim(),o=t.projectType==="chat_room"?"chat_room":"project";if(!e||!r)throw new Error("项目名称和工作区不能为空。");const n=$(String(t.path||""));l.accessSync(n,l.constants.R_OK|l.constants.W_OK);const i=(await b("GET",`/api/projects?workspaceId=${encodeURIComponent(e)}`)).items.find(u=>p(u.root_path)===p(n)),a=i||(await b("POST","/api/projects",{projectId:R(),workspaceId:e,name:r,rootPath:n,source:"aica",projectType:o})).item;return q(Nt(a)),{project:a,duplicate:!!i}}function Nt(t){return{projectId:t.project_id,workspaceId:t.workspace_id,name:t.name,rootPath:t.root_path}}function $(t){if(!t.trim()||!c.isAbsolute(t))throw new Error("必须选择绝对目录路径。");if(Ct(t),!l.statSync(t).isDirectory())throw new Error("选择的路径不是目录。");const r=l.realpathSync.native(t);return Rt(r),r}function m(t){const e=D(t),r=l.realpathSync.native(e);if(!l.statSync(r).isDirectory())throw new Error("项目根目录不存在。");return r}function D(t){const e=et(t);if(!e||!c.isAbsolute(e))throw new Error("项目根目录无效。");return c.resolve(e)}function P(t){const e=t.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"");if(!e)return"";if(e.includes("\0")||e.split("/").some(r=>!r||r==="."||r===".."))throw new Error("项目相对路径无效。");return e}function N(t,e,r){const o=e?c.join(t,...e.split("/")):t,n=l.realpathSync.native(o),s=c.relative(t,n);if(s.startsWith("..")||c.isAbsolute(s))throw new Error("目录超出项目范围。");const i=l.statSync(n);if(r&&!i.isDirectory())throw new Error("请求路径不是目录。");return n}function K(t,e){return c.relative(t,e).split(c.sep).join("/")}function Ct(t){const e=process.platform==="win32"?c.win32:c.posix;if(!k(process.platform).some(o=>{const n=String(o.path||"");if(!n)return!1;const s=e.relative(n,t);return s===""||!s.startsWith("..")&&!e.isAbsolute(s)}))throw new Error("目录不在允许浏览的位置内。")}function Rt(t){const e=process.platform==="win32"?c.win32:c.posix;if(!k(process.platform).some(o=>{const n=String(o.path||"");if(!n)return!1;const s=e.relative(n,t);return s===""||!s.startsWith("..")&&!e.isAbsolute(s)}))throw new Error("目录不在允许浏览的位置内。")}function X(t,e){try{return l.accessSync(t,e),!0}catch{return!1}}function V(t,e={}){return g("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",t],{encoding:"utf8",windowsHide:!0,timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,...e}}).replace(/^\uFEFF/,"").trim()}function Y(t){if(!t)return[];const e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>!!(r&&typeof r=="object")):e&&typeof e=="object"?[e]:[]}function Tt(t){return t===2?"removable":t===3?"fixed":t===4?"network":t===5?"optical":"drive"}function Ft(t,e){return e===2?`移动磁盘 (${t})`:e===4?`网络驱动器 (${t})`:e===5?`光驱 (${t})`:`本地磁盘 (${t})`}export{st as cleanupWorktree,lt as commitProjectUploadTempFile,it as commitWorktree,p as comparableMachinePath,pt as getProjectGitCommit,dt as getProjectGitDiff,mt as getProjectGitLog,O as getProjectGitStatus,j as getWorktreeStatus,_t as listMachineDirectory,Et as listMachineFilesystemRoots,at as listProjectDirectory,zt as startMachineFilesystemWorkerLoop,ct as uploadProjectFile};
|
package/dist/worker-cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as a}from"commander";import m from"node:path";import{createStartCommand as n}from"./commands/start.js";import{createDaemonCommand as t}from"./commands/daemon.js";import{createWorkerAuthCommand as s}from"./commands/worker-auth.js";import{createWorkerCodexCommand as c}from"./commands/worker-codex.js";import{createWorkerProjectCommand as i}from"./commands/worker-project.js";import{DEFAULT_ACA_SERVER_URL as d}from"./core/aca-config.js";process.env.ACA_DEFAULT_SERVER_URL||=d;async function p(r=process.argv){const o=new a;o.name("aica").description("AICA remote Agent worker").version("0.1.
|
|
2
|
+
import{Command as a}from"commander";import m from"node:path";import{createStartCommand as n}from"./commands/start.js";import{createDaemonCommand as t}from"./commands/daemon.js";import{createWorkerAuthCommand as s}from"./commands/worker-auth.js";import{createWorkerCodexCommand as c}from"./commands/worker-codex.js";import{createWorkerProjectCommand as i}from"./commands/worker-project.js";import{DEFAULT_ACA_SERVER_URL as d}from"./core/aca-config.js";process.env.ACA_DEFAULT_SERVER_URL||=d;async function p(r=process.argv){const o=new a;o.name("aica").description("AICA remote Agent worker").version("0.1.25").enablePositionalOptions(),o.addCommand(n()),o.addCommand(t()),o.addCommand(s()),o.addCommand(i()),o.addCommand(c()),await o.parseAsync(r)}const C=process.argv[1]||"",e=m.basename(C).replace(/\.(?:js|ts|cjs|mjs)$/i,"");(e==="worker-cli"||e==="aica"||e==="aca")&&p().catch(r=>{const o=r instanceof Error?r.message:String(r);console.error(o),process.exitCode=1});export{p as runWorkerCli};
|