@yuandc/aica 0.1.16 → 0.1.17

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 s from"node:fs";import d from"node:os";import i from"node:path";import{Readable as w}from"node:stream";import{acaServerRequest as f,acaServerStreamRequest as h}from"./aca-server-client.js";import{loadAcaConfig as x}from"./aca-config.js";import{getAcaHome as p}from"./paths.js";import{startLongPollWorker as y}from"./long-poll-worker.js";const b=25e3;function P(e){return y({run:async()=>{const t=x();if(!t.token)throw new Error("Worker 尚未配置认证令牌");const a=await f("GET",`/api/client/file-requests/claim?machineId=${encodeURIComponent(t.machineId)}&waitMs=${b}`);if(a.item)try{await S(a.item,t,e)}catch(n){const o=n instanceof Error?n.message:String(n);e.warn(`file request failed request=${a.item.requestId}: ${o}`);try{await j(a.item.requestId,o)}catch(r){e.warn(`file request fail callback failed request=${a.item.requestId}: ${r instanceof Error?r.message:String(r)}`)}}},onError:(t,a)=>e.warn(`file transfer worker failed, retry in ${a}ms: ${t instanceof Error?t.message:String(t)}`)})}async function j(e,t){await f("POST",`/api/client/file-requests/${encodeURIComponent(e)}/fail`,{message:t})}async function S(e,t,a){const n=t.projects.find(g=>g.projectId===e.projectId),o=u(e.projectRoot||n?.rootPath||"");if(!o)throw new Error(`file request ${e.requestId} project root is unknown`);const r=e.purpose==="temp-image"?"temp-image":e.purpose==="project-preview"?"project-preview":"project-file",c=r==="temp-image"?v(e.path):I(o,e.path),m=s.statSync(c);if(!m.isFile())throw new Error(`file request ${e.requestId} target is not a file`);if(m.size>e.maxBytes)throw new Error(`file request ${e.requestId} target is too large (${m.size} bytes)`);const l=r==="temp-image"?E(c):$(c);a.info(`streaming file request=${e.requestId} path=${c}`),await h("POST",`/api/client/file-requests/${encodeURIComponent(e.requestId)}/stream`,w.toWeb(s.createReadStream(c)),{"content-type":"application/octet-stream","x-aca-file-name":encodeURIComponent(i.basename(c)),"x-aca-file-size":String(m.size),"x-aca-file-mime":l})}function I(e,t){const a=s.realpathSync(u(e)),n=i.isAbsolute(t)?t:i.join(a,t),o=s.realpathSync(n),r=i.relative(a,o);if(r===""||r.startsWith("..")||i.isAbsolute(r))throw new Error("requested file is outside project root");return o}function v(e){const t=R(e);if(!i.isAbsolute(t))throw new Error("temporary image path must be absolute");const a=s.lstatSync(t);if(a.isSymbolicLink())throw new Error("temporary image cannot be a symbolic link");if(!a.isFile())throw new Error("temporary image target is not a regular file");const n=s.realpathSync(d.tmpdir()),o=s.realpathSync(t),r=i.relative(n,o);if(r===""||r.startsWith("..")||i.isAbsolute(r))throw new Error("temporary image is outside the system temp directory");return o}function E(e){const t=i.extname(e).toLowerCase(),a=Buffer.alloc(16),n=s.openSync(e,"r");let o=0;try{o=s.readSync(n,a,0,a.length,0)}finally{s.closeSync(n)}const r=a.subarray(0,o);if(t===".png"&&r.length>=8&&r.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if([".jpg",".jpeg"].includes(t)&&r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(t===".gif"&&r.length>=6&&["GIF87a","GIF89a"].includes(r.subarray(0,6).toString("ascii")))return"image/gif";if(t===".webp"&&r.length>=12&&r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP")return"image/webp";throw new Error("temporary file is not a supported raster image")}function R(e){const t=String(e||"").trim();if(!t.startsWith("file://"))return t;try{return decodeURIComponent(new URL(t).pathname)}catch{throw new Error("temporary image path is invalid")}}function u(e){return e?e==="~"?i.dirname(p()):e.startsWith("~/")?i.join(i.dirname(p()),e.slice(2)):e:""}function $(e){switch(i.extname(e).toLowerCase()){case".pdf":return"application/pdf";case".md":case".markdown":return"text/markdown; charset=utf-8";case".txt":case".log":return"text/plain; charset=utf-8";case".html":case".htm":return"text/html; charset=utf-8";case".css":return"text/css; charset=utf-8";case".js":case".mjs":return"text/javascript; charset=utf-8";case".json":case".map":return"application/json; charset=utf-8";case".xml":return"application/xml; charset=utf-8";case".svg":return"image/svg+xml; charset=utf-8";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".avif":return"image/avif";case".ico":return"image/x-icon";case".bmp":return"image/bmp";case".woff":return"font/woff";case".woff2":return"font/woff2";case".ttf":return"font/ttf";case".otf":return"font/otf";case".eot":return"application/vnd.ms-fontobject";case".mp4":return"video/mp4";case".webm":return"video/webm";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".ogg":return"audio/ogg";case".webmanifest":return"application/manifest+json; charset=utf-8";case".zip":return"application/zip";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";default:return"application/octet-stream"}}export{E as detectSafeTempImageMime,$ as mimeForPath,I as resolveProjectFile,v as resolveTempImageFile,P as startFileTransferWorkerLoop};
1
+ import i from"node:fs";import g from"node:os";import s from"node:path";import{Readable as d}from"node:stream";import{acaServerRequest as p,acaServerStreamRequest as w}from"./aca-server-client.js";import{loadAcaConfig as h}from"./aca-config.js";import{expandWorkerRuntimePath as x}from"./worker-runtime-paths.js";import{startLongPollWorker as y}from"./long-poll-worker.js";const b=25e3;function U(e){return y({run:async()=>{const t=h();if(!t.token)throw new Error("Worker 尚未配置认证令牌");const a=await p("GET",`/api/client/file-requests/claim?machineId=${encodeURIComponent(t.machineId)}&waitMs=${b}`);if(a.item)try{await S(a.item,t,e)}catch(n){const o=n instanceof Error?n.message:String(n);e.warn(`file request failed request=${a.item.requestId}: ${o}`);try{await j(a.item.requestId,o)}catch(r){e.warn(`file request fail callback failed request=${a.item.requestId}: ${r instanceof Error?r.message:String(r)}`)}}},onError:(t,a)=>e.warn(`file transfer worker failed, retry in ${a}ms: ${t instanceof Error?t.message:String(t)}`)})}async function j(e,t){await p("POST",`/api/client/file-requests/${encodeURIComponent(e)}/fail`,{message:t})}async function S(e,t,a){const n=t.projects.find(l=>l.projectId===e.projectId),o=f(e.projectRoot||n?.rootPath||"");if(!o)throw new Error(`file request ${e.requestId} project root is unknown`);const r=e.purpose==="temp-image"?"temp-image":e.purpose==="project-preview"?"project-preview":"project-file",c=r==="temp-image"?I(e.path):v(o,e.path),m=i.statSync(c);if(!m.isFile())throw new Error(`file request ${e.requestId} target is not a file`);if(m.size>e.maxBytes)throw new Error(`file request ${e.requestId} target is too large (${m.size} bytes)`);const u=r==="temp-image"?R(c):$(c);a.info(`streaming file request=${e.requestId} path=${c}`),await w("POST",`/api/client/file-requests/${encodeURIComponent(e.requestId)}/stream`,d.toWeb(i.createReadStream(c)),{"content-type":"application/octet-stream","x-aca-file-name":encodeURIComponent(s.basename(c)),"x-aca-file-size":String(m.size),"x-aca-file-mime":u})}function v(e,t){const a=i.realpathSync(f(e)),n=s.isAbsolute(t)?t:s.join(a,t),o=i.realpathSync(n),r=s.relative(a,o);if(r===""||r.startsWith("..")||s.isAbsolute(r))throw new Error("requested file is outside project root");return o}function I(e){const t=E(e);if(!s.isAbsolute(t))throw new Error("temporary image path must be absolute");const a=i.lstatSync(t);if(a.isSymbolicLink())throw new Error("temporary image cannot be a symbolic link");if(!a.isFile())throw new Error("temporary image target is not a regular file");const n=i.realpathSync(g.tmpdir()),o=i.realpathSync(t),r=s.relative(n,o);if(r===""||r.startsWith("..")||s.isAbsolute(r))throw new Error("temporary image is outside the system temp directory");return o}function R(e){const t=s.extname(e).toLowerCase(),a=Buffer.alloc(16),n=i.openSync(e,"r");let o=0;try{o=i.readSync(n,a,0,a.length,0)}finally{i.closeSync(n)}const r=a.subarray(0,o);if(t===".png"&&r.length>=8&&r.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if([".jpg",".jpeg"].includes(t)&&r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255)return"image/jpeg";if(t===".gif"&&r.length>=6&&["GIF87a","GIF89a"].includes(r.subarray(0,6).toString("ascii")))return"image/gif";if(t===".webp"&&r.length>=12&&r.subarray(0,4).toString("ascii")==="RIFF"&&r.subarray(8,12).toString("ascii")==="WEBP")return"image/webp";throw new Error("temporary file is not a supported raster image")}function E(e){const t=String(e||"").trim();if(!t.startsWith("file://"))return t;try{return decodeURIComponent(new URL(t).pathname)}catch{throw new Error("temporary image path is invalid")}}function f(e){return x(e)}function $(e){switch(s.extname(e).toLowerCase()){case".pdf":return"application/pdf";case".md":case".markdown":return"text/markdown; charset=utf-8";case".txt":case".log":return"text/plain; charset=utf-8";case".html":case".htm":return"text/html; charset=utf-8";case".css":return"text/css; charset=utf-8";case".js":case".mjs":return"text/javascript; charset=utf-8";case".json":case".map":return"application/json; charset=utf-8";case".xml":return"application/xml; charset=utf-8";case".svg":return"image/svg+xml; charset=utf-8";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".avif":return"image/avif";case".ico":return"image/x-icon";case".bmp":return"image/bmp";case".woff":return"font/woff";case".woff2":return"font/woff2";case".ttf":return"font/ttf";case".otf":return"font/otf";case".eot":return"application/vnd.ms-fontobject";case".mp4":return"video/mp4";case".webm":return"video/webm";case".mp3":return"audio/mpeg";case".wav":return"audio/wav";case".ogg":return"audio/ogg";case".webmanifest":return"application/manifest+json; charset=utf-8";case".zip":return"application/zip";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";default:return"application/octet-stream"}}export{R as detectSafeTempImageMime,$ as mimeForPath,v as resolveProjectFile,I as resolveTempImageFile,U as startFileTransferWorkerLoop};
@@ -1,6 +1,6 @@
1
- import W from"node:crypto";import E from"node:fs";import A from"node:path";import{compactAgentContext as V,forkAgentSession as q,sendAgentPrompt as D}from"../acp/agent.js";import{acaServerDownload as H,acaServerRequest as y}from"./aca-server-client.js";import{loadAcaConfig as G}from"./aca-config.js";import{prepareLocalWorktree as K}from"./worktree.js";import{getAcaHome as M}from"./paths.js";import{collectAffectedFiles as N,extractAffectedFilePathsFromAcpRaw as X}from"./affected-files.js";import{resolveJobPermissionPolicy as Z}from"./job-permission-policy.js";import{appendCoalescedAcpEvent as Q}from"./acp-event-coalescer.js";import{shouldUploadAcpEvent as Y}from"./acp-event-upload-filter.js";const ee=1500,te=5e3,O=1e3,ne=200,oe=64,U=900,ie=1e4,ae=0,re=12e3;function se(e){return e?e==="~"?A.dirname(M()):e.startsWith("~/")?A.join(A.dirname(M()),e.slice(2)):e:""}function ce(e){const t=e.project_metadata;return t&&typeof t=="object"&&!Array.isArray(t)&&t.kind==="chat"?!0:typeof e.project_root_path=="string"&&(e.project_root_path.startsWith("~/.aca/chats/")||/(^|\/)\.aca\/chats\//.test(e.project_root_path))}function He(e,t={}){let n=!1,i=null,o=null;const r=new Set,l=new Set,u=new Map,a=async()=>{if(n)return;const s=le();if(B(r.size,s))try{const p=t.loadConfig?.()??G();if(!p.token)return;for(;!n&&B(r.size,s);){const C=t.claimNextJob?await t.claimNextJob(p):await y("POST","/api/client/jobs/claim",{machineId:p.machineId,workspaceId:p.defaultWorkspaceId});if(!C.item)break;const f=C.item;if(n){await(t.cancelClaimedJob?t.cancelClaimedJob(f,p):R(f.job_id,p.machineId,"cancelled")).catch(()=>{});break}const m=f.session_id;l.has(m)&&e.warn(`claimed job=${f.job_id} for already active session=${m}; running anyway to avoid leaving it stuck`),r.add(f.job_id),l.add(m);const T=new AbortController,k=(t.runJob??pe)(f,p,e,T).catch(d=>{e.warn(`job ${f.job_id} failed outside handler: ${d instanceof Error?d.message:String(d)}`)}).finally(()=>{r.delete(f.job_id),l.delete(m),u.delete(f.job_id)});u.set(f.job_id,{controller:T,promise:k})}}catch(p){n||e.warn(`job worker failed: ${p instanceof Error?p.message:String(p)}`)}},h=()=>{if(n||i)return;const s=a();i=s,s.finally(()=>{i===s&&(i=null)})};h();const S=setInterval(()=>{h()},t.claimIntervalMs??ee);return{timer:S,stop:()=>o||(o=(async()=>{if(n)return;n=!0,clearInterval(S);for(const p of u.values())p.controller.abort();await i?.catch(()=>{});for(const p of u.values())p.controller.abort();const s=[...u.values()].map(p=>p.promise);s.length!==0&&await Promise.race([Promise.allSettled(s).then(()=>{}),j(re)])})(),o)}}function le(){const e=process.env.ACA_MAX_CONCURRENT_JOBS||process.env.ACA_MAX_CONCURRENT_PROJECT_JOBS||"",t=Number.parseInt(e,10);return!e.trim()||!Number.isFinite(t)||t<0?ae:t===0?0:Math.max(1,Math.min(t,8))}function B(e,t){return t===0||e<t}function ue(){const e=Number.parseInt(process.env.ACA_ACP_EVENT_BATCH_INTERVAL_MS||"",10);return Number.isFinite(e)?Math.max(40,Math.min(e,2e3)):ne}async function pe(e,t,n,i){const o=e.job_id,r=e.session_id,l=e.workspace_id,u=e.project_id??null,a=e.input??{},h=String(a.control?.type||"").toLowerCase();if(!h&&!a.message?.trim()&&(a.attachments??[]).length===0){await R(o,t.machineId,"job input missing message");return}const S=t.projects.find(d=>d.projectId===u),s=se(S?.rootPath||e.project_root_path||"");if(!s){await R(o,t.machineId,"job project root is unknown");return}ce(e)&&E.mkdirSync(s,{recursive:!0}),n.info(`claimed job=${o} session=${r} project=${S?.name??u??"unknown"}`);const p=setInterval(()=>{y("POST",`/api/client/jobs/${encodeURIComponent(o)}/heartbeat`,{machineId:t.machineId}).catch(()=>{}),je(o,i).catch(()=>{})},te);let C=0;const f=ye(o,t.machineId),m=Te(o,t.machineId),T=new Set;let k=null;try{await m.sendNow({phase:"initializing",label:"准备工作区",detail:e.worktree_id?"worktree":"project root"}).catch(()=>{});const d=K({projectId:u,sessionId:r,projectRoot:s,worktree:e});k=d,await Re(o,t.machineId,d);const I=fe(a.acpRun);if(h==="compact"){if(!e.acp_session_id)throw new Error("Current session does not have an ACP context to compact");const c=await V({agentType:P(I.agentType,"codex"),cliType:P(I.cliType,"builtin"),acpSessionId:e.acp_session_id,cwd:d.cwd,model:a.model,mode:a.mode,configOptionValues:a.configOptionValues,timeoutMs:a.timeoutMs,allowRollover:a.control?.allowRollover===!0,signal:i.signal,onStatus:b=>{m.report({phase:b.phase,label:b.label,detail:b.detail,updateType:b.updateType,raw:b})}});await m.flush(),await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:c.acpSessionId,suppressTurn:!0,result:{ok:!0,control:{type:"compact",allowRollover:a.control?.allowRollover===!0},acpSessionId:c.acpSessionId,durationMs:c.durationMs,usage:c.contextUsage,maintenance:c.maintenance,worktree:v(d)}}),n.info(`completed context compact job=${o}`);return}if(h==="fork"){const c=String(a.control?.sourceAcpSessionId||"").trim();if(!c)throw new Error("Source session does not have a Codex ACP context to fork");await m.sendNow({phase:"forking",label:"正在分叉 Codex 会话",detail:a.control?.sourceSessionId?`源会话 ${a.control.sourceSessionId}`:void 0}).catch(()=>{});const b=await q({agentType:P(I.agentType,"codex"),cliType:P(I.cliType,"builtin"),sourceProviderSessionId:c,cwd:d.cwd,model:a.model,mode:a.mode,configOptionValues:a.configOptionValues,timeoutMs:a.timeoutMs,signal:i.signal,onStatus:_=>{m.report({phase:_.phase,label:_.label,detail:_.detail,updateType:_.updateType,raw:_})}});await m.flush(),await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:b.acpSessionId,suppressTurn:!0,result:{ok:!0,control:{type:"fork",sourceSessionId:a.control?.sourceSessionId||null},acpSessionId:b.acpSessionId,worktree:v(d)}}),n.info(`completed Codex session fork job=${o}`);return}const g=await Ae({cwd:d.cwd,sessionId:r,jobId:o,attachments:a.attachments??[]});g.length>0&&(n.info(`materialized ${g.length} attachment(s) for job=${o}`),await m.sendNow({phase:"initializing",label:"附件已写入本机",detail:g.map(c=>c.relativePath).join(", "),raw:{attachments:F(g)}}).catch(()=>{}));const $=Se(a,g),J=_e($,g),w=await D({agentType:P(I.agentType,"codex"),cliType:P(I.cliType,"builtin"),acpSessionId:e.acp_session_id??null,requireSessionResume:de(e.session_raw),prompt:$,promptBlocks:J,cwd:d.cwd,model:a.model,mode:a.mode,configOptionValues:a.configOptionValues,canExecuteTools:a.canExecuteTools,timeoutMs:a.timeoutMs,contextWindow:he(I.contextWindow),signal:i.signal,onStatus:c=>{m.report({phase:c.phase,label:c.label,detail:c.detail,updateType:c.updateType,raw:c})},onUpdate:c=>{C+=1;for(const _ of X(c.raw))T.add(_);const b={turnId:e.user_turn_id??null,eventType:c.type,label:c.label,text:c.text,status:c.status,toolCallId:c.toolCallId,raw:ge(c.raw,C)};Y(b)&&f.push(b)},onPermissionRequest:c=>{const b=Z(a,c);return b?Promise.resolve(b):xe(o,t.machineId,c,i.signal)},onUserInputRequest:c=>Ee(o,t.machineId,c,i.signal)});await f.flush(),await m.flush();const L=N({cwd:d.cwd,evidencePaths:T}),x=we(w.promptResponse);if(!(be(x)||!!w.content)){await R(o,t.machineId,`${w.agentType} stopped: ${x??"unknown"}`,{acpSessionId:w.acpSessionId,stopReason:x,exitCode:w.exitCode,stderr:$e(w.stderr,4e3),worktree:v(d)});return}await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:w.acpSessionId,assistantText:w.content,result:{ok:!0,acpSessionId:w.acpSessionId,stopReason:x,durationMs:w.durationMs,acpRun:a.acpRun??null,effectiveConfig:w.effectiveConfig??null,performance:w.performance??null,usage:w.contextUsage??null,updateCount:w.updates.length,statusTimeline:w.statusTimeline,worktree:v(d),attachments:F(g),files:L}}),n.info(`completed job=${o}`)}catch(d){await f.flush(),await m.flush();const I=i.signal.aborted?"cancelled":d instanceof Error?d.message:String(d),g=k?N({cwd:k.cwd,evidencePaths:T}):[];await R(o,t.machineId,me(I),{rawError:I,files:g})}finally{await f.flush(),await m.flush(),clearInterval(p)}}function de(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e.importedProviderSession;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.strictResume===!0)}function me(e){return/ACP request timed out/i.test(e)?"ACP 长时间没有完成,请稍后重试,或点击停止后重新发送。":/MimoCode request timed out/i.test(e)?"MimoCode 长时间没有完成,请稍后重试,或点击停止后重新发送。":e.replace(/\bsession\/prompt\b/g,"ACP 请求")}function fe(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function P(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function we(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(typeof t.stopReason=="string")return t.stopReason;if(typeof t.reason=="string")return t.reason;const n=t.part;if(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.reason=="string")return n.reason}function be(e){return e?["end_turn","stop","completed","complete"].includes(e):!1}function ye(e,t){let n=[],i=null,o=Promise.resolve();const r=async a=>{a.length!==0&&await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/events/batch`,{machineId:t,events:a})},l=()=>{i&&(clearTimeout(i),i=null);const a=n;return n=[],o=o.then(()=>r(a)).catch(()=>{}),o},u=()=>{i||(i=setTimeout(()=>{l()},ue()),i.unref())};return{push(a){if(Q(n,a),Ie(a)||n.length>=oe){l();return}u()},flush:l}}function Ie(e){return e.eventType==="tool_call"?!0:e.eventType!=="tool_call_update"?!1:["completed","failed","cancelled"].includes(String(e.status||"").toLowerCase())}function Te(e,t){let n=null,i=0,o="",r=null,l=Promise.resolve();const u=s=>JSON.stringify({phase:s.phase??"",label:s.label??"",detail:s.detail??"",updateType:s.updateType??""}),a=async s=>{await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/presence`,{machineId:t,phase:s.phase,label:s.label,detail:s.detail,updateType:s.updateType,raw:s.raw}),i=Date.now(),o=u(s)},h=()=>{if(r&&(clearTimeout(r),r=null),!n)return l;const s=n;return n=null,l=l.then(()=>a(s)).catch(()=>{}),l},S=s=>{r||(r=setTimeout(()=>{h()},s),r.unref())};return{report(s){const p=Date.now(),f=u(s)!==o,m=p-i>=ie;if(!f&&!m)return;n=s;const T=p-i;if(T>=U||i===0){h();return}S(U-T)},sendNow(s){return n=s,h()},flush:h}}function ge(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,acaSequence:t}:{value:e,acaSequence:t}}function Se(e,t=[]){const n=e?.message?.trim()??"";if(t.length===0)return n;const o=["用户随消息上传了以下附件,aca 已将附件写入本机工作区。需要读取附件时请直接使用下面的 localPath;图片附件也已作为 ACP image block 随本轮请求传入。",...t.map((r,l)=>`${l+1}. ${r.name} (${r.kind}, ${r.mimeType}, ${ve(r.size)})
1
+ import L from"node:crypto";import E from"node:fs";import x from"node:path";import{compactAgentContext as W,forkAgentSession as V,sendAgentPrompt as q}from"../acp/agent.js";import{acaServerDownload as D,acaServerRequest as y}from"./aca-server-client.js";import{loadAcaConfig as H}from"./aca-config.js";import{prepareLocalWorktree as G}from"./worktree.js";import{expandWorkerRuntimePath as K}from"./worker-runtime-paths.js";import{collectAffectedFiles as M,extractAffectedFilePathsFromAcpRaw as X}from"./affected-files.js";import{resolveJobPermissionPolicy as Z}from"./job-permission-policy.js";import{appendCoalescedAcpEvent as Q}from"./acp-event-coalescer.js";import{shouldUploadAcpEvent as Y}from"./acp-event-upload-filter.js";const ee=1500,te=5e3,N=1e3,ne=200,oe=64,O=900,ae=1e4,ie=0,re=12e3;function se(e){return K(e)}function ce(e){const t=e.project_metadata;return t&&typeof t=="object"&&!Array.isArray(t)&&t.kind==="chat"?!0:typeof e.project_root_path=="string"&&(e.project_root_path.startsWith("~/.aica/chats/")||e.project_root_path.startsWith("~/.aca/chats/")||/(^|\/)\.aica\/chats\//.test(e.project_root_path)||/(^|\/)\.aca\/chats\//.test(e.project_root_path))}function He(e,t={}){let n=!1,a=null,o=null;const r=new Set,l=new Set,u=new Map,i=async()=>{if(n)return;const s=le();if(U(r.size,s))try{const p=t.loadConfig?.()??H();if(!p.token)return;for(;!n&&U(r.size,s);){const A=t.claimNextJob?await t.claimNextJob(p):await y("POST","/api/client/jobs/claim",{machineId:p.machineId,workspaceId:p.defaultWorkspaceId});if(!A.item)break;const f=A.item;if(n){await(t.cancelClaimedJob?t.cancelClaimedJob(f,p):k(f.job_id,p.machineId,"cancelled")).catch(()=>{});break}const m=f.session_id;l.has(m)&&e.warn(`claimed job=${f.job_id} for already active session=${m}; running anyway to avoid leaving it stuck`),r.add(f.job_id),l.add(m);const _=new AbortController,P=(t.runJob??pe)(f,p,e,_).catch(d=>{e.warn(`job ${f.job_id} failed outside handler: ${d instanceof Error?d.message:String(d)}`)}).finally(()=>{r.delete(f.job_id),l.delete(m),u.delete(f.job_id)});u.set(f.job_id,{controller:_,promise:P})}}catch(p){n||e.warn(`job worker failed: ${p instanceof Error?p.message:String(p)}`)}},h=()=>{if(n||a)return;const s=i();a=s,s.finally(()=>{a===s&&(a=null)})};h();const S=setInterval(()=>{h()},t.claimIntervalMs??ee);return{timer:S,stop:()=>o||(o=(async()=>{if(n)return;n=!0,clearInterval(S);for(const p of u.values())p.controller.abort();await a?.catch(()=>{});for(const p of u.values())p.controller.abort();const s=[...u.values()].map(p=>p.promise);s.length!==0&&await Promise.race([Promise.allSettled(s).then(()=>{}),j(re)])})(),o)}}function le(){const e=process.env.ACA_MAX_CONCURRENT_JOBS||process.env.ACA_MAX_CONCURRENT_PROJECT_JOBS||"",t=Number.parseInt(e,10);return!e.trim()||!Number.isFinite(t)||t<0?ie:t===0?0:Math.max(1,Math.min(t,8))}function U(e,t){return t===0||e<t}function ue(){const e=Number.parseInt(process.env.ACA_ACP_EVENT_BATCH_INTERVAL_MS||"",10);return Number.isFinite(e)?Math.max(40,Math.min(e,2e3)):ne}async function pe(e,t,n,a){const o=e.job_id,r=e.session_id,l=e.workspace_id,u=e.project_id??null,i=e.input??{},h=String(i.control?.type||"").toLowerCase();if(!h&&!i.message?.trim()&&(i.attachments??[]).length===0){await k(o,t.machineId,"job input missing message");return}const S=t.projects.find(d=>d.projectId===u),s=se(S?.rootPath||e.project_root_path||"");if(!s){await k(o,t.machineId,"job project root is unknown");return}ce(e)&&E.mkdirSync(s,{recursive:!0}),n.info(`claimed job=${o} session=${r} project=${S?.name??u??"unknown"}`);const p=setInterval(()=>{y("POST",`/api/client/jobs/${encodeURIComponent(o)}/heartbeat`,{machineId:t.machineId}).catch(()=>{}),je(o,a).catch(()=>{})},te);let A=0;const f=ye(o,t.machineId),m=_e(o,t.machineId),_=new Set;let P=null;try{await m.sendNow({phase:"initializing",label:"准备工作区",detail:e.worktree_id?"worktree":"project root"}).catch(()=>{});const d=G({projectId:u,sessionId:r,projectRoot:s,worktree:e});P=d,await Re(o,t.machineId,d);const I=fe(i.acpRun);if(h==="compact"){if(!e.acp_session_id)throw new Error("Current session does not have an ACP context to compact");const c=await W({agentType:C(I.agentType,"codex"),cliType:C(I.cliType,"builtin"),acpSessionId:e.acp_session_id,cwd:d.cwd,model:i.model,mode:i.mode,configOptionValues:i.configOptionValues,timeoutMs:i.timeoutMs,allowRollover:i.control?.allowRollover===!0,signal:a.signal,onStatus:b=>{m.report({phase:b.phase,label:b.label,detail:b.detail,updateType:b.updateType,raw:b})}});await m.flush(),await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:c.acpSessionId,suppressTurn:!0,result:{ok:!0,control:{type:"compact",allowRollover:i.control?.allowRollover===!0},acpSessionId:c.acpSessionId,durationMs:c.durationMs,usage:c.contextUsage,maintenance:c.maintenance,worktree:v(d)}}),n.info(`completed context compact job=${o}`);return}if(h==="fork"){const c=String(i.control?.sourceAcpSessionId||"").trim();if(!c)throw new Error("Source session does not have a Codex ACP context to fork");await m.sendNow({phase:"forking",label:"正在分叉 Codex 会话",detail:i.control?.sourceSessionId?`源会话 ${i.control.sourceSessionId}`:void 0}).catch(()=>{});const b=await V({agentType:C(I.agentType,"codex"),cliType:C(I.cliType,"builtin"),sourceProviderSessionId:c,cwd:d.cwd,model:i.model,mode:i.mode,configOptionValues:i.configOptionValues,timeoutMs:i.timeoutMs,signal:a.signal,onStatus:g=>{m.report({phase:g.phase,label:g.label,detail:g.detail,updateType:g.updateType,raw:g})}});await m.flush(),await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:b.acpSessionId,suppressTurn:!0,result:{ok:!0,control:{type:"fork",sourceSessionId:i.control?.sourceSessionId||null},acpSessionId:b.acpSessionId,worktree:v(d)}}),n.info(`completed Codex session fork job=${o}`);return}const T=await Ae({cwd:d.cwd,sessionId:r,jobId:o,attachments:i.attachments??[]});T.length>0&&(n.info(`materialized ${T.length} attachment(s) for job=${o}`),await m.sendNow({phase:"initializing",label:"附件已写入本机",detail:T.map(c=>c.relativePath).join(", "),raw:{attachments:z(T)}}).catch(()=>{}));const $=Se(i,T),F=ge($,T),w=await q({agentType:C(I.agentType,"codex"),cliType:C(I.cliType,"builtin"),acpSessionId:e.acp_session_id??null,requireSessionResume:de(e.session_raw),prompt:$,promptBlocks:F,cwd:d.cwd,model:i.model,mode:i.mode,configOptionValues:i.configOptionValues,canExecuteTools:i.canExecuteTools,timeoutMs:i.timeoutMs,contextWindow:he(I.contextWindow),signal:a.signal,onStatus:c=>{m.report({phase:c.phase,label:c.label,detail:c.detail,updateType:c.updateType,raw:c})},onUpdate:c=>{A+=1;for(const g of X(c.raw))_.add(g);const b={turnId:e.user_turn_id??null,eventType:c.type,label:c.label,text:c.text,status:c.status,toolCallId:c.toolCallId,raw:Te(c.raw,A)};Y(b)&&f.push(b)},onPermissionRequest:c=>{const b=Z(i,c);return b?Promise.resolve(b):xe(o,t.machineId,c,a.signal)},onUserInputRequest:c=>Ee(o,t.machineId,c,a.signal)});await f.flush(),await m.flush();const J=M({cwd:d.cwd,evidencePaths:_}),R=we(w.promptResponse);if(!(be(R)||!!w.content)){await k(o,t.machineId,`${w.agentType} stopped: ${R??"unknown"}`,{acpSessionId:w.acpSessionId,stopReason:R,exitCode:w.exitCode,stderr:$e(w.stderr,4e3),worktree:v(d)});return}await y("POST",`/api/client/jobs/${encodeURIComponent(o)}/complete`,{machineId:t.machineId,acpSessionId:w.acpSessionId,assistantText:w.content,result:{ok:!0,acpSessionId:w.acpSessionId,stopReason:R,durationMs:w.durationMs,acpRun:i.acpRun??null,effectiveConfig:w.effectiveConfig??null,performance:w.performance??null,usage:w.contextUsage??null,updateCount:w.updates.length,statusTimeline:w.statusTimeline,worktree:v(d),attachments:z(T),files:J}}),n.info(`completed job=${o}`)}catch(d){await f.flush(),await m.flush();const I=a.signal.aborted?"cancelled":d instanceof Error?d.message:String(d),T=P?M({cwd:P.cwd,evidencePaths:_}):[];await k(o,t.machineId,me(I),{rawError:I,files:T})}finally{await f.flush(),await m.flush(),clearInterval(p)}}function de(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e.importedProviderSession;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.strictResume===!0)}function me(e){return/ACP request timed out/i.test(e)?"ACP 长时间没有完成,请稍后重试,或点击停止后重新发送。":/MimoCode request timed out/i.test(e)?"MimoCode 长时间没有完成,请稍后重试,或点击停止后重新发送。":e.replace(/\bsession\/prompt\b/g,"ACP 请求")}function fe(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function he(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function C(...e){for(const t of e)if(typeof t=="string"&&t.trim())return t.trim();return""}function we(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(typeof t.stopReason=="string")return t.stopReason;if(typeof t.reason=="string")return t.reason;const n=t.part;if(n&&typeof n=="object"&&!Array.isArray(n)&&typeof n.reason=="string")return n.reason}function be(e){return e?["end_turn","stop","completed","complete"].includes(e):!1}function ye(e,t){let n=[],a=null,o=Promise.resolve();const r=async i=>{i.length!==0&&await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/events/batch`,{machineId:t,events:i})},l=()=>{a&&(clearTimeout(a),a=null);const i=n;return n=[],o=o.then(()=>r(i)).catch(()=>{}),o},u=()=>{a||(a=setTimeout(()=>{l()},ue()),a.unref())};return{push(i){if(Q(n,i),Ie(i)||n.length>=oe){l();return}u()},flush:l}}function Ie(e){return e.eventType==="tool_call"?!0:e.eventType!=="tool_call_update"?!1:["completed","failed","cancelled"].includes(String(e.status||"").toLowerCase())}function _e(e,t){let n=null,a=0,o="",r=null,l=Promise.resolve();const u=s=>JSON.stringify({phase:s.phase??"",label:s.label??"",detail:s.detail??"",updateType:s.updateType??""}),i=async s=>{await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/presence`,{machineId:t,phase:s.phase,label:s.label,detail:s.detail,updateType:s.updateType,raw:s.raw}),a=Date.now(),o=u(s)},h=()=>{if(r&&(clearTimeout(r),r=null),!n)return l;const s=n;return n=null,l=l.then(()=>i(s)).catch(()=>{}),l},S=s=>{r||(r=setTimeout(()=>{h()},s),r.unref())};return{report(s){const p=Date.now(),f=u(s)!==o,m=p-a>=ae;if(!f&&!m)return;n=s;const _=p-a;if(_>=O||a===0){h();return}S(O-_)},sendNow(s){return n=s,h()},flush:h}}function Te(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,acaSequence:t}:{value:e,acaSequence:t}}function Se(e,t=[]){const n=e?.message?.trim()??"";if(t.length===0)return n;const o=["用户随消息上传了以下附件,aca 已将附件写入本机工作区。需要读取附件时请直接使用下面的 localPath;图片附件也已作为 ACP image block 随本轮请求传入。",...t.map((r,l)=>`${l+1}. ${r.name} (${r.kind}, ${r.mimeType}, ${ke(r.size)})
2
2
  localPath: ${r.path}
3
3
  workspacePath: ${r.relativePath}`)].join(`
4
4
  `);return n?`${n}
5
5
 
6
- ${o}`:o}function _e(e,t){const n=[{type:"text",text:e}];for(const i of t)i.kind!=="image"||!i.mimeType.startsWith("image/")||n.push({type:"image",data:i.base64,mimeType:i.mimeType,uri:i.path});return n}async function Ae(e){if(e.attachments.length===0)return[];const t=A.join(e.cwd,".aca","attachments",z(e.sessionId),z(e.jobId));E.mkdirSync(t,{recursive:!0});const n=[];for(const[i,o]of e.attachments.entries()){const r=o.attachmentId?{mimeType:o.mimeType||"application/octet-stream",bytes:await H(`/api/client/attachments/${encodeURIComponent(o.attachmentId)}`)}:Ce(o.dataUrl??""),l=o.mimeType||r.mimeType||"application/octet-stream",u=o.kind==="image"||l.startsWith("image/")?"image":"file",a=Pe(o.name||`attachment-${i+1}`,l),h=A.join(t,`${String(i+1).padStart(2,"0")}-${a}`);E.writeFileSync(h,r.bytes),n.push({name:o.name||a,mimeType:l,size:r.bytes.byteLength,kind:u,path:h,relativePath:A.relative(e.cwd,h),base64:r.bytes.toString("base64"),sha256:W.createHash("sha256").update(r.bytes).digest("hex")})}return n}function Ce(e){const t=e.indexOf(",");if(!e.startsWith("data:")||t<0)throw new Error("attachment dataUrl is not a data URL");const n=e.slice(5,t),i=e.slice(t+1),o=n.split(";").filter(Boolean),r=o[0]?.includes("/")?o[0]:"application/octet-stream";if(!o.includes("base64"))throw new Error("attachment dataUrl is not base64 encoded");return{mimeType:r,bytes:Buffer.from(i,"base64")}}function Pe(e,t){const n=A.basename(e).replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").trim(),i=`attachment${ke(t)}`;return(!n||n==="."||n===".."?i:n).slice(0,180)}function ke(e){switch(e.toLowerCase()){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";case"text/plain":return".txt";case"application/json":return".json";case"text/markdown":case"text/x-markdown":return".md";case"application/pdf":return".pdf";case"application/msword":return".doc";case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return".docx";case"application/vnd.ms-excel":return".xls";case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return".xlsx";case"application/vnd.ms-powerpoint":return".ppt";case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return".pptx";case"application/zip":return".zip";case"application/x-7z-compressed":return".7z";case"application/x-rar-compressed":case"application/vnd.rar":return".rar";case"application/gzip":return".gz";case"application/x-tar":return".tar";default:return""}}function z(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"item"}function F(e){return e.map(t=>({name:t.name,kind:t.kind,mimeType:t.mimeType,size:t.size,path:t.path,relativePath:t.relativePath,sha256:t.sha256}))}function ve(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB"];let n=e,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i+=1;return`${n>=10||i===0?n.toFixed(0):n.toFixed(1)} ${t[i]}`}async function Re(e,t,n){!n.usedWorktree||!n.worktreeId||await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/worktree`,{machineId:t,baseCommit:n.baseCommit??null,worktreePath:n.cwd,status:n.status??"active",raw:n.raw??v(n)})}function v(e){return{usedWorktree:e.usedWorktree,worktreeId:e.worktreeId??null,cwd:e.cwd,status:e.status??null,baseCommit:e.baseCommit??null,branchName:e.branchName??null,baseBranch:e.baseBranch??null}}async function xe(e,t,n,i){const r=(await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/permissions`,{machineId:t,request:n})).item.permission_id;for(;!i.aborted;){await j(O);const l=await y("GET",`/api/client/permissions/${encodeURIComponent(r)}`);if(l.item.status==="resolved"&&l.item.response){const u=l.item.response.outcome;return u.outcome==="selected"?{outcome:u}:{outcome:{outcome:"cancelled"}}}}return{outcome:{outcome:"cancelled"}}}async function Ee(e,t,n,i){const r=(await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/permissions`,{machineId:t,request:{kind:"elicitation",...n}})).item.permission_id;for(;!i.aborted;){await j(O);const l=await y("GET",`/api/client/permissions/${encodeURIComponent(r)}`);if(l.item.status==="resolved"&&l.item.response){const u=l.item.response.outcome;return u.outcome==="submitted"?{outcome:u}:{outcome:{outcome:"cancelled"}}}}return{outcome:{outcome:"cancelled"}}}async function je(e,t){if(t.signal.aborted)return;const n=await y("GET",`/api/client/jobs/${encodeURIComponent(e)}`);Number(n.item.cancel_requested??0)===1&&t.abort()}async function R(e,t,n,i){await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/fail`,{machineId:t,error:n,result:i})}function j(e){return new Promise(t=>setTimeout(t,e))}function $e(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}export{He as startJobWorkerLoop};
6
+ ${o}`:o}function ge(e,t){const n=[{type:"text",text:e}];for(const a of t)a.kind!=="image"||!a.mimeType.startsWith("image/")||n.push({type:"image",data:a.base64,mimeType:a.mimeType,uri:a.path});return n}async function Ae(e){if(e.attachments.length===0)return[];const t=x.join(e.cwd,".aca","attachments",B(e.sessionId),B(e.jobId));E.mkdirSync(t,{recursive:!0});const n=[];for(const[a,o]of e.attachments.entries()){const r=o.attachmentId?{mimeType:o.mimeType||"application/octet-stream",bytes:await D(`/api/client/attachments/${encodeURIComponent(o.attachmentId)}`)}:Ce(o.dataUrl??""),l=o.mimeType||r.mimeType||"application/octet-stream",u=o.kind==="image"||l.startsWith("image/")?"image":"file",i=Pe(o.name||`attachment-${a+1}`,l),h=x.join(t,`${String(a+1).padStart(2,"0")}-${i}`);E.writeFileSync(h,r.bytes),n.push({name:o.name||i,mimeType:l,size:r.bytes.byteLength,kind:u,path:h,relativePath:x.relative(e.cwd,h),base64:r.bytes.toString("base64"),sha256:L.createHash("sha256").update(r.bytes).digest("hex")})}return n}function Ce(e){const t=e.indexOf(",");if(!e.startsWith("data:")||t<0)throw new Error("attachment dataUrl is not a data URL");const n=e.slice(5,t),a=e.slice(t+1),o=n.split(";").filter(Boolean),r=o[0]?.includes("/")?o[0]:"application/octet-stream";if(!o.includes("base64"))throw new Error("attachment dataUrl is not base64 encoded");return{mimeType:r,bytes:Buffer.from(a,"base64")}}function Pe(e,t){const n=x.basename(e).replace(/[<>:"/\\|?*\x00-\x1F]/g,"_").trim(),a=`attachment${ve(t)}`;return(!n||n==="."||n===".."?a:n).slice(0,180)}function ve(e){switch(e.toLowerCase()){case"image/png":return".png";case"image/jpeg":return".jpg";case"image/webp":return".webp";case"image/gif":return".gif";case"text/plain":return".txt";case"application/json":return".json";case"text/markdown":case"text/x-markdown":return".md";case"application/pdf":return".pdf";case"application/msword":return".doc";case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return".docx";case"application/vnd.ms-excel":return".xls";case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return".xlsx";case"application/vnd.ms-powerpoint":return".ppt";case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return".pptx";case"application/zip":return".zip";case"application/x-7z-compressed":return".7z";case"application/x-rar-compressed":case"application/vnd.rar":return".rar";case"application/gzip":return".gz";case"application/x-tar":return".tar";default:return""}}function B(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"item"}function z(e){return e.map(t=>({name:t.name,kind:t.kind,mimeType:t.mimeType,size:t.size,path:t.path,relativePath:t.relativePath,sha256:t.sha256}))}function ke(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB"];let n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;return`${n>=10||a===0?n.toFixed(0):n.toFixed(1)} ${t[a]}`}async function Re(e,t,n){!n.usedWorktree||!n.worktreeId||await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/worktree`,{machineId:t,baseCommit:n.baseCommit??null,worktreePath:n.cwd,status:n.status??"active",raw:n.raw??v(n)})}function v(e){return{usedWorktree:e.usedWorktree,worktreeId:e.worktreeId??null,cwd:e.cwd,status:e.status??null,baseCommit:e.baseCommit??null,branchName:e.branchName??null,baseBranch:e.baseBranch??null}}async function xe(e,t,n,a){const r=(await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/permissions`,{machineId:t,request:n})).item.permission_id;for(;!a.aborted;){await j(N);const l=await y("GET",`/api/client/permissions/${encodeURIComponent(r)}`);if(l.item.status==="resolved"&&l.item.response){const u=l.item.response.outcome;return u.outcome==="selected"?{outcome:u}:{outcome:{outcome:"cancelled"}}}}return{outcome:{outcome:"cancelled"}}}async function Ee(e,t,n,a){const r=(await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/permissions`,{machineId:t,request:{kind:"elicitation",...n}})).item.permission_id;for(;!a.aborted;){await j(N);const l=await y("GET",`/api/client/permissions/${encodeURIComponent(r)}`);if(l.item.status==="resolved"&&l.item.response){const u=l.item.response.outcome;return u.outcome==="submitted"?{outcome:u}:{outcome:{outcome:"cancelled"}}}}return{outcome:{outcome:"cancelled"}}}async function je(e,t){if(t.signal.aborted)return;const n=await y("GET",`/api/client/jobs/${encodeURIComponent(e)}`);Number(n.item.cancel_requested??0)===1&&t.abort()}async function k(e,t,n,a){await y("POST",`/api/client/jobs/${encodeURIComponent(e)}/fail`,{machineId:t,error:n,result:a})}function j(e){return new Promise(t=>setTimeout(t,e))}function $e(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}export{He as startJobWorkerLoop};
@@ -1,5 +1,5 @@
1
- import{execFileSync as h}from"node:child_process";import{randomUUID as L}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 O,upsertLocalProject as W}from"./aca-config.js";import{startLongPollWorker as B}from"./long-poll-worker.js";const U=25e3,S=300,z=3e4;let b=null;function $t(t){return B({run:async()=>{const e=O();if(!e.token)throw new Error("Worker 尚未配置认证令牌");const r=await y("GET",`/api/client/machine-operations/claim?machineId=${encodeURIComponent(e.machineId)}&waitMs=${U}`);if(r.item)try{const o=await K(r.item);await y("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/complete`,{result:o})}catch(o){const i=o instanceof Error?o.message:String(o);t.warn(`machine filesystem request failed request=${r.item.requestId}: ${i}`),await y("POST",`/api/client/machine-operations/${encodeURIComponent(r.item.requestId)}/fail`,{message:i}).catch(()=>{})}},onError:(e,r)=>t.warn(`machine filesystem worker failed, retry in ${r}ms: ${e instanceof Error?e.message:String(e)}`)})}async function K(t){if(t.operation==="filesystem_roots")return at();if(t.operation==="list_directory")return ct({directoryPath:String(t.payload.path||""),includeHidden:t.payload.includeHidden===!0});if(t.operation==="register_project")return pt(t.payload);if(t.operation==="list_project_directory")return X(t.payload);if(t.operation==="get_project_git_status")return $(t.payload);if(t.operation==="get_project_git_diff")return Y(t.payload);if(t.operation==="get_project_git_log")return Q(t.payload);if(t.operation==="get_project_git_commit")return Z(t.payload);if(t.operation==="get_worktree_status")return P(t.payload);if(t.operation==="commit_worktree")return J(t.payload);if(t.operation==="cleanup_worktree")return V(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:rt(r),changedFiles:null,ahead:0};const o=$({rootPath:r}),i=String(t.baseCommit||"").trim(),s=i&&/^[0-9a-f]{7,64}$/i.test(i)?et(r,i):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 J(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 V(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),i=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&&i)try{h("git",["-C",r,"branch","-D",i],{stdio:"pipe",timeout:3e4})}catch(n){const a=String(n.stderr||n);if(!/not found|not exist/i.test(a))throw n}}else l.rmSync(o,{recursive:!0,force:!0,maxRetries:2,retryDelay:200});return{removed:!0,branchDeleted:!!(s&&t.deleteBranch===!0&&i)}}function X(t){const e=m(String(t.rootPath||"")),r=x(String(t.relativePath||"")),o=wt(e,r,!0),i=Math.max(0,Number(t.offset||0)),s=Math.min(300,Math.max(20,Number(t.limit||200))),n=l.readdirSync(o,{withFileTypes:!0}).filter(u=>!u.isSymbolicLink()).map(u=>({name:u.name,path:gt(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=n.slice(i,i+s);return{path:r,rootKind:t.rootKind==="worktree"?"worktree":"project",items:a,total:n.length,nextOffset:i+a.length<n.length?i+a.length:null}}const D=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,D),i=o.map(a=>tt(a)).filter(a=>!!a),s=v(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--","."],_));for(const a of i){const u=s.get(a.path);if(u)a.additions=u.additions,a.deletions=u.deletions;else if(a.status==="untracked"){const g=R(e,a.path);a.additions=g.additions,a.deletions=g.deletions}}const n=st(e);return{isRepository:!0,branch:nt(e),files:i,ahead:n.ahead,behind:n.behind,truncated:o.length>=D}}function Y(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=N(e,r),i=ot(e,r),s=i?f(e,["diff","--no-ext-diff","--unified=80","HEAD","--",r],w):T(e,["diff","--no-ext-diff","--no-index","--unified=80",process.platform==="win32"?"NUL":"/dev/null",o],w),n=i?v(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--",r],32*1024)).get(r):R(e,r);return{isRepository:!0,path:r,diff:I(s),additions:n?.additions??0,deletions:n?.deletions??0,truncated:s.length>w}}function Q(t){const e=m(String(t.rootPath||""));if(!p(e))return{isRepository:!1,items:[]};if(!it(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(n=>q(n)).filter(n=>!!n),limit:r}}function Z(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),i=[...v(f(e,["show","--no-ext-diff","--numstat","-z","--no-renames","--format=",r],_)).values()];return{isRepository:!0,commit:r,diff:I(o),additions:i.reduce((s,n)=>s+(n.additions||0),0),deletions:i.reduce((s,n)=>s+(n.deletions||0),0),changedFiles:i.length,truncated:o.length>w}}function q(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 tt(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=C(r);if(!o||!o.path)continue;const i=x(o.path);i&&e.set(i,{additions:o.additions,deletions:o.deletions})}return e}function R(t,e){const r=N(t,e),i=T(t,["diff","--no-ext-diff","--no-index","--numstat","-z","--",process.platform==="win32"?"NUL":"/dev/null",r],32*1024).split("\0",1)[0]||"",s=C(i);return s?{additions:s.additions,deletions:s.deletions}:{additions:null,deletions:null}}function C(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),i=t.slice(e+1,r);return{additions:/^\d+$/.test(o)?Number(o):null,deletions:/^\d+$/.test(i)?Number(i):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 et(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 rt(t){try{return l.readdirSync(t).length>0}catch{return!1}}function ot(t,e){try{return f(t,["ls-files","--error-unmatch","--",e],8*1024),!0}catch{return!1}}function it(t){try{return f(t,["rev-parse","--verify","HEAD"],8*1024),!0}catch{return!1}}function nt(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 st(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 N(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 T(t,e,r){try{return f(t,e,r)}catch(o){const i=String(o.stdout||"");if(i)return i;if(Number(o.status)===1)return"";throw o}}function I(t){return t.length<=w?t:`${t.slice(0,w)}
1
+ import{execFileSync as h}from"node:child_process";import{randomUUID as L}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 O,upsertLocalProject as W}from"./aca-config.js";import{startLongPollWorker as B}from"./long-poll-worker.js";import{expandWorkerRuntimePath as U}from"./worker-runtime-paths.js";const z=25e3,S=300,K=3e4;let b=null;function Ct(t){return B({run:async()=>{const e=O();if(!e.token)throw new Error("Worker 尚未配置认证令牌");const r=await y("GET",`/api/client/machine-operations/claim?machineId=${encodeURIComponent(e.machineId)}&waitMs=${z}`);if(r.item)try{const o=await J(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 J(t){if(t.operation==="filesystem_roots")return ct();if(t.operation==="list_directory")return ut({directoryPath:String(t.payload.path||""),includeHidden:t.payload.includeHidden===!0});if(t.operation==="register_project")return ht(t.payload);if(t.operation==="list_project_directory")return Y(t.payload);if(t.operation==="get_project_git_status")return $(t.payload);if(t.operation==="get_project_git_diff")return Q(t.payload);if(t.operation==="get_project_git_log")return Z(t.payload);if(t.operation==="get_project_git_commit")return q(t.payload);if(t.operation==="get_worktree_status")return P(t.payload);if(t.operation==="commit_worktree")return V(t.payload);if(t.operation==="cleanup_worktree")return X(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:ot(r),changedFiles:null,ahead:0};const o=$({rootPath:r}),n=String(t.baseCommit||"").trim(),s=n&&/^[0-9a-f]{7,64}$/i.test(n)?rt(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 V(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 X(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 Y(t){const e=m(String(t.rootPath||"")),r=_(String(t.relativePath||"")),o=gt(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:yt(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 D=500,x=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"],x).split("\0").filter(Boolean).slice(0,D),n=o.map(a=>et(a)).filter(a=>!!a),s=v(f(e,["diff","--no-ext-diff","--numstat","-z","--no-renames","HEAD","--","."],x));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=R(e,a.path);a.additions=g.additions,a.deletions=g.deletions}}const i=at(e);return{isRepository:!0,branch:st(e),files:n,ahead:i.ahead,behind:i.behind,truncated:o.length>=D}}function Q(t){const e=m(String(t.rootPath||"")),r=_(String(t.relativePath||""));if(!r)throw new Error("Diff 文件路径不能为空。");if(!p(e))return{isRepository:!1,path:r,diff:"",additions:0,deletions:0};const o=N(e,r),n=nt(e,r),s=n?f(e,["diff","--no-ext-diff","--unified=80","HEAD","--",r],w):T(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):R(e,r);return{isRepository:!0,path:r,diff:I(s),additions:i?.additions??0,deletions:i?.deletions??0,truncated:s.length>w}}function Z(t){const e=m(String(t.rootPath||""));if(!p(e))return{isRepository:!1,items:[]};if(!it(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"],x).split("").map(i=>tt(i)).filter(i=>!!i),limit:r}}function q(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],x)).values()];return{isRepository:!0,commit:r,diff:I(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 tt(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 et(t){if(t.length<4)return null;const e=t[0]||" ",r=t[1]||" ",o=_(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=C(r);if(!o||!o.path)continue;const n=_(o.path);n&&e.set(n,{additions:o.additions,deletions:o.deletions})}return e}function R(t,e){const r=N(t,e),n=T(t,["diff","--no-ext-diff","--no-index","--numstat","-z","--",process.platform==="win32"?"NUL":"/dev/null",r],32*1024).split("\0",1)[0]||"",s=C(n);return s?{additions:s.additions,deletions:s.deletions}:{additions:null,deletions:null}}function C(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 rt(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 ot(t){try{return l.readdirSync(t).length>0}catch{return!1}}function nt(t,e){try{return f(t,["ls-files","--error-unmatch","--",e],8*1024),!0}catch{return!1}}function it(t){try{return f(t,["rev-parse","--verify","HEAD"],8*1024),!0}catch{return!1}}function st(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 at(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 N(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 T(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 I(t){return t.length<=w?t:`${t.slice(0,w)}
2
2
 
3
- [Diff 内容过大,已截断]`}function at(){const t=process.platform,e=A(t);return{platform:t,roots:e}}function ct(t){if(!t.directoryPath.trim())throw new Error("目录路径不能为空。");return process.platform==="win32"?dt(t.directoryPath,!!t.includeHidden):ft(t.directoryPath,!!t.includeHidden)}function d(t,e=process.platform){const r=e==="win32"?c.win32:c.posix,o=r.normalize(t),i=r.parse(o).root,s=o.length>i.length?o.replace(/[\\/]+$/,""):o;return e==="win32"?s.toLocaleLowerCase("en-US"):s}function ut(){const t=l.realpathSync(k.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 A(t){if(b?.platform===t&&b.expiresAtMs>Date.now())return b.roots;const e=t==="win32"?lt():ut();return b={platform:t,roots:e,expiresAtMs:Date.now()+z},e}function lt(){const t=l.realpathSync.native(k.homedir()),e=new Map;e.set(d(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=H(M(r));for(const i of o){const s=String(i.Root||"");if(!s)continue;const n=Number(i.DriveType||0),a=String(i.Name||s.replace(/[\\/]+$/,"")),u=String(i.VolumeName||"").trim();e.set(d(s,"win32"),{id:`drive-${a.replace(/[^a-z0-9]+/gi,"").toLowerCase()}`,label:u?`${u} (${a})`:_t(a,n),path:s,kind:bt(n),available:!0})}}catch{const r=c.win32.parse(t).root;e.set(d(r,"win32"),{id:"drive-system",label:`系统盘 (${r.replace(/\\$/,"")})`,path:r,kind:"fixed",available:!0})}return[...e.values()]}function ft(t,e){const r=E(t),i=l.readdirSync(r,{withFileTypes:!0}).filter(n=>n.isDirectory()&&!n.isSymbolicLink()&&(e||!n.name.startsWith("."))),s=i.slice(0,S).map(n=>({name:n.name,path:c.join(r,n.name),kind:"directory",hidden:n.name.startsWith("."),hasChildren:!0}));return s.sort((n,a)=>n.name.localeCompare(a.name,void 0,{numeric:!0,sensitivity:"base"})),F(r,s,i.length>S,"linux")}function dt(t,e){const r=E(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
- `),i=H(M(o,{ACA_MACHINE_FS_PATH:r})),s=i.map(n=>{const a=String(n.Attributes||"");return{name:String(n.Name||""),path:String(n.FullName||""),kind:"directory",hidden:/Hidden|System/i.test(a),hasChildren:!0,reparsePoint:/ReparsePoint/i.test(a)}}).filter(n=>n.name&&n.path&&!n.reparsePoint&&(e||!n.hidden)).slice(0,S).sort((n,a)=>n.name.localeCompare(a.name,void 0,{numeric:!0,sensitivity:"base"}));return F(r,s,i.length>S,"win32")}function F(t,e,r,o){const i=o==="win32"?c.win32:c.posix,s=i.parse(t).root,n=d(t,o)===d(s,o)?null:i.dirname(t);return{platform:o,path:t,parentPath:n,breadcrumbs:mt(t,o),readable:G(t,l.constants.R_OK),writable:G(t,l.constants.W_OK),items:e,truncated:r}}function mt(t,e){const r=e==="win32"?c.win32:c.posix,o=r.parse(t),i=t.slice(o.root.length).split(/[\\/]+/).filter(Boolean),s=[{label:o.root.replace(/[\\/]+$/,"")||o.root,path:o.root}];let n=o.root;for(const a of i)n=r.join(n,a),s.push({label:a,path:n});return s}async function pt(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 i=E(String(t.path||""));l.accessSync(i,l.constants.R_OK|l.constants.W_OK);const n=(await y("GET",`/api/projects?workspaceId=${encodeURIComponent(e)}`)).items.find(u=>d(u.root_path)===d(i)),a=n||(await y("POST","/api/projects",{projectId:L(),workspaceId:e,name:r,rootPath:i,source:"aica",projectType:o})).item;return W(ht(a)),{project:a,duplicate:!!n}}function ht(t){return{projectId:t.project_id,workspaceId:t.workspace_id,name:t.name,rootPath:t.root_path}}function E(t){if(!t.trim()||!c.isAbsolute(t))throw new Error("必须选择绝对目录路径。");if(yt(t),!l.statSync(t).isDirectory())throw new Error("选择的路径不是目录。");const r=l.realpathSync.native(t);return St(r),r}function m(t){const e=j(t),r=l.realpathSync.native(e);if(!l.statSync(r).isDirectory())throw new Error("项目根目录不存在。");return r}function j(t){if(!t.trim()||!c.isAbsolute(t))throw new Error("项目根目录无效。");return c.resolve(t)}function x(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 wt(t,e,r){const o=e?c.join(t,...e.split("/")):t,i=l.realpathSync.native(o),s=c.relative(t,i);if(s.startsWith("..")||c.isAbsolute(s))throw new Error("目录超出项目范围。");const n=l.statSync(i);if(r&&!n.isDirectory())throw new Error("请求路径不是目录。");return i}function gt(t,e){return c.relative(t,e).split(c.sep).join("/")}function yt(t){const e=process.platform==="win32"?c.win32:c.posix;if(!A(process.platform).some(o=>{const i=String(o.path||"");if(!i)return!1;const s=e.relative(i,t);return s===""||!s.startsWith("..")&&!e.isAbsolute(s)}))throw new Error("目录不在允许浏览的位置内。")}function St(t){const e=process.platform==="win32"?c.win32:c.posix;if(!A(process.platform).some(o=>{const i=String(o.path||"");if(!i)return!1;const s=e.relative(i,t);return s===""||!s.startsWith("..")&&!e.isAbsolute(s)}))throw new Error("目录不在允许浏览的位置内。")}function G(t,e){try{return l.accessSync(t,e),!0}catch{return!1}}function M(t,e={}){return h("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 H(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 bt(t){return t===2?"removable":t===3?"fixed":t===4?"network":t===5?"optical":"drive"}function _t(t,e){return e===2?`移动磁盘 (${t})`:e===4?`网络驱动器 (${t})`:e===5?`光驱 (${t})`:`本地磁盘 (${t})`}export{V as cleanupWorktree,J as commitWorktree,d as comparableMachinePath,Z as getProjectGitCommit,Y as getProjectGitDiff,Q as getProjectGitLog,$ as getProjectGitStatus,P as getWorktreeStatus,ct as listMachineDirectory,at as listMachineFilesystemRoots,X as listProjectDirectory,$t as startMachineFilesystemWorkerLoop};
3
+ [Diff 内容过大,已截断]`}function ct(){const t=process.platform,e=A(t);return{platform:t,roots:e}}function ut(t){if(!t.directoryPath.trim())throw new Error("目录路径不能为空。");return process.platform==="win32"?mt(t.directoryPath,!!t.includeHidden):dt(t.directoryPath,!!t.includeHidden)}function d(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 lt(){const t=l.realpathSync(k.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 A(t){if(b?.platform===t&&b.expiresAtMs>Date.now())return b.roots;const e=t==="win32"?ft():lt();return b={platform:t,roots:e,expiresAtMs:Date.now()+K},e}function ft(){const t=l.realpathSync.native(k.homedir()),e=new Map;e.set(d(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=H(M(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(d(s,"win32"),{id:`drive-${a.replace(/[^a-z0-9]+/gi,"").toLowerCase()}`,label:u?`${u} (${a})`:_t(a,i),path:s,kind:xt(i),available:!0})}}catch{const r=c.win32.parse(t).root;e.set(d(r,"win32"),{id:"drive-system",label:`系统盘 (${r.replace(/\\$/,"")})`,path:r,kind:"fixed",available:!0})}return[...e.values()]}function dt(t,e){const r=E(t),n=l.readdirSync(r,{withFileTypes:!0}).filter(i=>i.isDirectory()&&!i.isSymbolicLink()&&(e||!i.name.startsWith("."))),s=n.slice(0,S).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"})),F(r,s,n.length>S,"linux")}function mt(t,e){const r=E(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=H(M(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,S).sort((i,a)=>i.name.localeCompare(a.name,void 0,{numeric:!0,sensitivity:"base"}));return F(r,s,n.length>S,"win32")}function F(t,e,r,o){const n=o==="win32"?c.win32:c.posix,s=n.parse(t).root,i=d(t,o)===d(s,o)?null:n.dirname(t);return{platform:o,path:t,parentPath:i,breadcrumbs:pt(t,o),readable:G(t,l.constants.R_OK),writable:G(t,l.constants.W_OK),items:e,truncated:r}}function pt(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 ht(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=E(String(t.path||""));l.accessSync(n,l.constants.R_OK|l.constants.W_OK);const i=(await y("GET",`/api/projects?workspaceId=${encodeURIComponent(e)}`)).items.find(u=>d(u.root_path)===d(n)),a=i||(await y("POST","/api/projects",{projectId:L(),workspaceId:e,name:r,rootPath:n,source:"aica",projectType:o})).item;return W(wt(a)),{project:a,duplicate:!!i}}function wt(t){return{projectId:t.project_id,workspaceId:t.workspace_id,name:t.name,rootPath:t.root_path}}function E(t){if(!t.trim()||!c.isAbsolute(t))throw new Error("必须选择绝对目录路径。");if(St(t),!l.statSync(t).isDirectory())throw new Error("选择的路径不是目录。");const r=l.realpathSync.native(t);return bt(r),r}function m(t){const e=j(t),r=l.realpathSync.native(e);if(!l.statSync(r).isDirectory())throw new Error("项目根目录不存在。");return r}function j(t){const e=U(t);if(!e||!c.isAbsolute(e))throw new Error("项目根目录无效。");return c.resolve(e)}function _(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 gt(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 yt(t,e){return c.relative(t,e).split(c.sep).join("/")}function St(t){const e=process.platform==="win32"?c.win32:c.posix;if(!A(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 bt(t){const e=process.platform==="win32"?c.win32:c.posix;if(!A(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 G(t,e){try{return l.accessSync(t,e),!0}catch{return!1}}function M(t,e={}){return h("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 H(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 xt(t){return t===2?"removable":t===3?"fixed":t===4?"network":t===5?"optical":"drive"}function _t(t,e){return e===2?`移动磁盘 (${t})`:e===4?`网络驱动器 (${t})`:e===5?`光驱 (${t})`:`本地磁盘 (${t})`}export{X as cleanupWorktree,V as commitWorktree,d as comparableMachinePath,q as getProjectGitCommit,Q as getProjectGitDiff,Z as getProjectGitLog,$ as getProjectGitStatus,P as getWorktreeStatus,ut as listMachineDirectory,ct as listMachineFilesystemRoots,Y as listProjectDirectory,Ct as startMachineFilesystemWorkerLoop};
@@ -1 +1 @@
1
- import i from"node:fs";import c from"node:os";import o from"node:path";import{getAcaConfigPath as t,getAcaHome as a,getCredentialsPath as m}from"./paths.js";function l(e){const n=e.aicaHome||e.acaHome;n&&(process.env.AICA_HOME=o.resolve(n));const s=e.aicaConfig||e.acaConfig;s&&(process.env.AICA_CONFIG=o.resolve(s)),f()}function f(){const e=o.resolve(process.env.AICA_LEGACY_HOME||o.join(c.homedir(),".aca")),n=o.resolve(a()),s=o.resolve(o.join(c.homedir(),".aica"));e===n||n!==s||(!process.env.AICA_CONFIG&&!process.env.ACA_CONFIG&&r(o.join(e,"config.json"),t()),!process.env.AICA_CREDENTIALS&&!process.env.ACA_CREDENTIALS&&r(o.join(e,"credentials.json"),m()))}function r(e,n){i.existsSync(n)||!i.existsSync(e)||(i.mkdirSync(o.dirname(n),{recursive:!0}),i.copyFileSync(e,n,i.constants.COPYFILE_EXCL))}export{l as applyRuntimePathOptions};
1
+ import i from"node:fs";import c from"node:os";import n from"node:path";import{getAcaConfigPath as y,getAcaHome as A,getCredentialsPath as v}from"./paths.js";function p(e){const r=e.aicaHome||e.acaHome;r&&(process.env.AICA_HOME=n.resolve(r));const o=e.aicaConfig||e.acaConfig;o&&(process.env.AICA_CONFIG=n.resolve(o)),C()}function C(){const e=n.resolve(process.env.AICA_LEGACY_HOME||n.join(c.homedir(),".aca")),r=n.resolve(A()),o=n.resolve(n.join(c.homedir(),".aica"));e===r||r!==o||(!process.env.AICA_CONFIG&&!process.env.ACA_CONFIG&&s(n.join(e,"config.json"),y()),!process.env.AICA_CREDENTIALS&&!process.env.ACA_CREDENTIALS&&s(n.join(e,"credentials.json"),v()),a(n.join(e,"chats"),n.join(r,"chats")),a(n.join(e,"worktrees"),n.join(r,"worktrees")))}function s(e,r){i.existsSync(r)||!i.existsSync(e)||(i.mkdirSync(n.dirname(r),{recursive:!0}),m(e,r))}function a(e,r){if(!(!i.existsSync(e)||!i.statSync(e).isDirectory())){i.mkdirSync(r,{recursive:!0});for(const o of i.readdirSync(e)){const f=n.join(e,o),t=n.join(r,o);i.existsSync(t)||m(f,t)}try{i.readdirSync(e).length===0&&i.rmdirSync(e)}catch{}}}function m(e,r){try{i.renameSync(e,r)}catch(o){if(o.code!=="EXDEV")throw o;i.cpSync(e,r,{recursive:!0,errorOnExist:!0}),i.rmSync(e,{recursive:!0,force:!0})}}export{p as applyRuntimePathOptions};
@@ -0,0 +1 @@
1
+ import e from"node:os";import i from"node:path";import{getAcaHome as a}from"./paths.js";const o="~/.aica/chats";function h(r){const t=r.trim();return t?t==="~"?e.homedir():t==="~/.aica"||t==="~/.aca"?a():t.startsWith("~/.aica/")?i.join(a(),t.slice(8)):t.startsWith("~/.aca/")?i.join(a(),t.slice(7)):t.startsWith("~/")||t.startsWith("~\\")?i.join(e.homedir(),t.slice(2)):t:""}function u(r){return`${o}/${r}`}export{o as WORKER_CHAT_ROOT_TEMPLATE,h as expandWorkerRuntimePath,u as workerChatRootPath};
@@ -1 +1 @@
1
- import{execFileSync as m}from"node:child_process";import w from"node:crypto";import a from"node:fs";import s from"node:path";import{getAcaHome as f}from"./paths.js";function S(e){const t=e.worktree.worktree_id;if(!t||e.worktree.worktree_status==="disabled")return{cwd:e.projectRoot,usedWorktree:!1};const c=e.worktree.worktree_path?s.resolve(e.worktree.worktree_path):null;if(e.worktree.worktree_status==="active"&&c&&a.existsSync(c))return{cwd:c,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:e.worktree.worktree_base_commit??null,branchName:e.worktree.worktree_branch_name??null,baseBranch:e.worktree.worktree_base_branch??null};const r=s.resolve(e.projectRoot),l=k(e.projectId??"project"),d=k(e.sessionId),o=s.join(f(),"worktrees",l,d),i=e.worktree.worktree_base_branch||"HEAD",n=e.worktree.worktree_branch_name||`aca/session-${d}`,u=b(r);return a.mkdirSync(s.dirname(o),{recursive:!0}),a.existsSync(o)?{cwd:o,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:u,branchName:n,baseBranch:i,raw:{source:"aca-client",reusedExistingPath:!0,projectRoot:r}}:u?(m("git",["worktree","add","-B",n,o,i],{cwd:r,stdio:"pipe"}),{cwd:o,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:u,branchName:n,baseBranch:i,raw:{source:"aca-client",mode:"git-worktree",projectRoot:r}}):(a.mkdirSync(o,{recursive:!0}),h(r,o),{cwd:o,usedWorktree:!0,worktreeId:t,status:"fallback-directory",baseCommit:null,branchName:n,baseBranch:i,raw:{source:"aca-client",mode:"fallback-directory",projectRoot:r,fallbackReason:"git repository has no commits"}})}function b(e){try{return m("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",stdio:"pipe"}).trim()||null}catch{return null}}function h(e,t){a.cpSync(e,t,{recursive:!0,filter:c=>{const r=s.relative(e,c);if(!r)return!0;const l=r.split(s.sep)[0];return![".git","node_modules","dist",".aca",".aica"].includes(l)}})}function k(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,80)||w.randomUUID()}export{S as prepareLocalWorktree};
1
+ import{execFileSync as d}from"node:child_process";import w from"node:crypto";import c from"node:fs";import a from"node:path";import{getAcaHome as f}from"./paths.js";import{expandWorkerRuntimePath as h}from"./worker-runtime-paths.js";function x(e){const t=e.worktree.worktree_id;if(!t||e.worktree.worktree_status==="disabled")return{cwd:e.projectRoot,usedWorktree:!1};const s=e.worktree.worktree_path?a.resolve(h(e.worktree.worktree_path)):null;if(e.worktree.worktree_status==="active"&&s&&c.existsSync(s))return{cwd:s,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:e.worktree.worktree_base_commit??null,branchName:e.worktree.worktree_branch_name??null,baseBranch:e.worktree.worktree_base_branch??null};const r=a.resolve(e.projectRoot),l=k(e.projectId??"project"),u=k(e.sessionId),o=a.join(f(),"worktrees",l,u),i=e.worktree.worktree_base_branch||"HEAD",n=e.worktree.worktree_branch_name||`aca/session-${u}`,m=b(r);return c.mkdirSync(a.dirname(o),{recursive:!0}),c.existsSync(o)?{cwd:o,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:m,branchName:n,baseBranch:i,raw:{source:"aca-client",reusedExistingPath:!0,projectRoot:r}}:m?(d("git",["worktree","add","-B",n,o,i],{cwd:r,stdio:"pipe"}),{cwd:o,usedWorktree:!0,worktreeId:t,status:"active",baseCommit:m,branchName:n,baseBranch:i,raw:{source:"aca-client",mode:"git-worktree",projectRoot:r}}):(c.mkdirSync(o,{recursive:!0}),p(r,o),{cwd:o,usedWorktree:!0,worktreeId:t,status:"fallback-directory",baseCommit:null,branchName:n,baseBranch:i,raw:{source:"aca-client",mode:"fallback-directory",projectRoot:r,fallbackReason:"git repository has no commits"}})}function b(e){try{return d("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",stdio:"pipe"}).trim()||null}catch{return null}}function p(e,t){c.cpSync(e,t,{recursive:!0,filter:s=>{const r=a.relative(e,s);if(!r)return!0;const l=r.split(a.sep)[0];return![".git","node_modules","dist",".aca",".aica"].includes(l)}})}function k(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,80)||w.randomUUID()}export{x as prepareLocalWorktree};
@@ -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.16").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};
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.17").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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuandc/aica",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "AICA remote Agent worker",
5
5
  "author": "yuandc",
6
6
  "type": "module",