needle-cloud 3.6.0-rc.1793897293.dc2cab1 → 3.6.0
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.
|
@@ -60,4 +60,4 @@ try {
|
|
|
60
60
|
} catch {
|
|
61
61
|
@{status='unavailable'; pid=$ownerPid; reason=$_.Exception.Message} | ConvertTo-Json -Compress
|
|
62
62
|
}
|
|
63
|
-
`;function Of(e,t,n,o){Im(e,async(e,n)=>{try{const o=await t(e,n);return"string"==typeof o?Dm(o):{...o,content:o.content.map(e=>"text"===e.type?{...e,text:Dm(e.text)}:e)}}catch(e){throw new Error(Dm(e instanceof Error?e.message:String(e)))}},n,o)}const Af=function(e,t=Xm,n=Date.now){let o,i=0;const r=Object.assign(async(r={})=>{var a,s,c,l;const p={status:"error",message:"Use mode check, results or error; file/code filters, nonnegative integer offset/index. No paths or commands can be selected."};if(!r||"object"!=typeof r||Array.isArray(r))return p;if(Object.keys(r).some(e=>!["mode","file","code","offset","index"].includes(e)))return p;const u=null!=(a=r.mode)?a:"check";if(!["check","results","error"].includes(u))return p;for(const e of[r.file,r.code])if(void 0!==e&&("string"!=typeof e||e.length>250))return p;for(const e of[r.offset,r.index])if(void 0!==e&&(!Number.isSafeInteger(e)||e<0))return p;const d=e();if(o&&o.project!==d&&(o=void 0),"check"===u){var m;const e=i,r=ef(d),a=await t(d);o={project:d,result:{...a,...a.message?{message:Dm(a.message)}:{},...a.output?{output:Dm(a.output)}:{},diagnostics:(null!=(m=a.diagnostics)?m:[]).map(e=>({...e,message:Dm(e.message)}))},time:n(),revision:e,snapshot:r}}if(!o)return{status:"unavailable",message:"No saved check for this local project. Run local_files_check_project with mode check first."};const f=ef(d),h=null===o.snapshot||null===f,g=o.result,v=null!=(s=g.diagnostics)?s:[],b=v.map((e,t)=>({...e,index:t})),y=b.filter(e=>{var t;return(!r.file||(null!=(t=e.file)?t:"").toLowerCase().includes(r.file.toLowerCase()))&&(!r.code||e.code===r.code)}),x=null!=(c=r.offset)?c:0,w="error"===u?y.filter(e=>{var t,n;return e.index===(null!=(t=r.index)?t:null==(n=y.at(-1))?void 0:n.index)}):y.slice(x,x+5);if("error"===u&&!w.length)return{status:"unavailable",message:"No matching error in the latest check. Use mode results to list available error indexes."};const _="error"===u?2e3:300;return{status:g.status,check:"typescript",checkedAt:new Date(o.time).toISOString(),cached:"check"!==u,stale:o.revision!==i||h||o.snapshot!==f,project:tf(d,300),totalDiagnostics:null!=(l=g.totalDiagnostics)?l:v.length,retainedDiagnostics:v.length,matchingDiagnostics:y.length,truncated:Boolean(g.truncated),diagnostics:w.map(e=>({...e,...e.file?{file:tf(e.file,300)}:{},message:tf(e.message,_),messageTruncated:e.message.length>_})),..."error"!==u&&x+w.length<y.length?{nextOffset:x+w.length}:{},...g.message||h?{message:tf([g.message,h?"Could not scan project files for changes; this check is marked stale.":null].filter(Boolean).join(" "),500)}:{},...g.output?{output:tf(g.output,"error"===u?2e3:500),outputTruncated:g.output.length>("error"===u?2e3:500)}:{}}},{markStale(){i++}});return r}(()=>{var e;return null==(e=Ff())?void 0:e.web_location}),Nf=function(e,t=ce(oe(),".needle","cli","ai-checkpoints"),n=(()=>{})){let o=0n,r=!1;function a(t){if(!(t&&t.chatId&&t.sessionId&&t.turnId&&t.project))throw new Error("Local file edit approval is required.");const n=e();if(!n||le(n)!==le(t.project))throw new Error("The approved local project has changed.");return{root:A(n),grant:t}}function s(e,t,n){if("string"!=typeof t||!t||t.includes("\0")||de(t)||fe.isAbsolute(t)||he.isAbsolute(t)||t.split(/[\\/]/).some(e=>!e||"."===e||".."===e||e.includes(":")))throw new Error("Path must be a file inside the selected local project.");if(Bm(e)||Bm(t))throw new Error("Sensitive files cannot be accessed by local AI tools.");if(t.split(/[\\/]/).some(e=>/[ .]$/.test(e)))throw new Error("Invalid file path.");const o=le(e,t);if(!o.startsWith(e+me))throw new Error("Path escapes the selected local project.");let i=e;const r=pe(e,o).split(me);for(let e=0;e<r.length;e++){if(i=ce(i,r[e]),!I(i)){if(e!==r.length-1||!n)throw new Error("The file or its parent directory does not exist.");continue}const t=M(i);if(t.isSymbolicLink()||t.nlink>1)throw new Error("Symbolic links and hard links cannot be edited.");if(e<r.length-1&&!t.isDirectory())throw new Error("Parent path is not a directory.");if(e===r.length-1&&!t.isFile())throw new Error("Target is not a regular file.")}return o}function c(e,t){const n=`${e}.needle-ai-${i()}.tmp`;try{H(n,t,{flag:"wx",mode:384}),O(n,e)}finally{I(n)&&G(n)}}function l(){return I(t)?B(t).filter(e=>e.endsWith(".json")).reduce((e,n)=>e+N(ce(t,n)).size,0):0}function p(e){if(!r){if(I(t))for(const e of B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e))){const n=JSON.parse(W(ce(t,e),"utf8"));if(n.order&&/^\d+$/.test(n.order)){const e=BigInt(n.order);e>o&&(o=e)}}r=!0}const n=1000000n*BigInt(Date.now());o=n>o?n:o+1n,e.order=o.toString();const a=JSON.stringify(e);if(l()+Buffer.byteLength(a)>of)throw new Error("Checkpoint storage is full; no file was changed.");C(t,{recursive:!0,mode:448});const s=i(),c=ce(t,`${s}.json`);return H(c,a,{flag:"wx",mode:384}),{id:s,file:c}}function u(e,t){if(e.byteLength>nf)throw new Error("File exceeds the 1 MiB edit limit.");if(!t||!/^[a-f0-9]{64}$/.test(t))throw new Error("Expected file SHA-256 hash is required before changing a file.");if(rf(e)!==t)throw new Error("The supplied expectedSha256 does not match this file. The file may have changed, or the hash may be incorrect. Run local_files_stat again and use its sha256 value.")}function d(e,t){try{const n=t=>{const n=s(e,t,!0);return I(n)?W(n):null},o=n(t.path),i=null===t.before?null:rf(Buffer.from(t.before,"base64"));if("rename"===t.operation){if(!t.newPath)return"conflicted";const e=n(t.newPath);if(null===o&&e&&rf(e)===t.afterSha256)return"applied";if(null===e&&o&&rf(o)===i)return"undone"}else if("delete"===t.operation){if(null===o)return"applied";if(o&&rf(o)===i)return"undone"}else{if(o&&rf(o)===t.afterSha256)return"applied";if(null===o&&null===t.before||o&&rf(o)===i)return"undone"}return"conflicted"}catch{return"conflicted"}}return{list(e){const{root:n,grant:o}=a(e);if(!I(t))return{changes:[],total:0};const i=B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({...JSON.parse(W(ce(t,e),"utf8")),checkpointId:e.slice(0,-5)})).filter(e=>e.project===n&&e.chatId===o.chatId).sort((e,t)=>e.order&&t.order?BigInt(t.order)>BigInt(e.order)?1:BigInt(t.order)<BigInt(e.order)?-1:0:t.createdAt.localeCompare(e.createdAt));return{changes:i.slice(0,100).map(({path:e,checkpointId:t,turnId:o,createdAt:i,operation:r,newPath:a,...s})=>({path:e,checkpointId:t,turnId:o,createdAt:i,operation:null!=r?r:"write",...a?{newPath:a}:{},state:d(n,{...s,path:e,turnId:o,createdAt:i,operation:r,newPath:a})})),total:i.length}},stat(t){const n=e();if(!n)throw new Error("No connected local web project.");const o=A(n),i=s(o,t,!0);if(!I(i))return{path:t,exists:!1};const r=N(i).size;if(r>nf)throw new Error("File exceeds the 1 MiB edit limit.");const a=Gm(o,t,{maxBytes:nf});return Hm(a),{path:t,exists:!0,sha256:rf(a),size:r}},write(e,t){var o;const{root:i,grant:r}=a(t);if(!e||"string"!=typeof e.content)throw new Error("Text content is required.");const l=Buffer.from(e.content,"utf8");if(l.byteLength>nf||e.content.includes("\0"))throw new Error("Text file exceeds the 1 MiB limit or contains NUL.");const d=s(i,e.path,!0===e.create),m=I(d);if(!0===e.create&&m)throw new Error("File already exists.");if(!0!==e.create&&!m)throw new Error("File does not exist; use create.");const f=m?W(d):null;if(f&&u(f,e.expectedSha256),f&&rf(f)===rf(l))throw new Error("File already has this content; no edit was saved.");const h={project:i,path:pe(i,d),chatId:r.chatId,sessionId:r.sessionId,turnId:r.turnId,before:null!=(o=null==f?void 0:f.toString("base64"))?o:null,after:l.toString("base64"),afterSha256:rf(l),createdAt:(new Date).toISOString(),operation:"write"},g=p(h);try{if(s(i,e.path,!0===e.create),!0===e.create){if(I(d))throw new Error("The file was created since it was checked; check it again.")}else if(!I(d)||rf(W(d))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");c(d,l)}catch(e){throw G(g.file),e}return n(),{path:e.path,checkpointId:g.id,turnId:r.turnId,afterSha256:h.afterSha256}},delete(e,t){const{root:o,grant:i}=a(t),r=s(o,null==e?void 0:e.path,!1),c=W(r);u(c,e.expectedSha256);const l=p({project:o,path:pe(o,r),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:c.toString("base64"),after:null,afterSha256:null,createdAt:(new Date).toISOString(),operation:"delete"});try{if(s(o,e.path,!1),rf(W(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");G(r)}catch(e){throw G(l.file),e}return n(),{path:e.path,checkpointId:l.id,turnId:i.turnId,afterSha256:null}},rename(e,t){const{root:o,grant:i}=a(t),r=s(o,null==e?void 0:e.path,!1),c=s(o,null==e?void 0:e.newPath,!0);if(I(c))throw new Error("Destination file already exists.");const l=W(r);u(l,e.expectedSha256);const d={project:o,path:pe(o,r),newPath:pe(o,c),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:l.toString("base64"),after:l.toString("base64"),afterSha256:rf(l),createdAt:(new Date).toISOString(),operation:"rename"},m=p(d);try{if(s(o,e.path,!1),s(o,e.newPath,!0),I(c))throw new Error("Destination file already exists.");if(rf(W(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");O(r,c)}catch(e){throw G(m.file),e}return n(),{path:e.newPath,checkpointId:m.id,turnId:i.turnId,afterSha256:d.afterSha256}},undo(e,o){const{root:i,grant:r}=a(o);if(!e||"string"!=typeof e.checkpointId||!/^[a-f0-9-]{36}$/.test(e.checkpointId))throw new Error("Invalid checkpoint ID.");const p=ce(t,`${e.checkpointId}.json`),u=JSON.parse(W(p,"utf8"));if(u.project!==i||u.chatId!==r.chatId)throw new Error("Checkpoint belongs to another project or chat.");const d=s(i,u.path,!0);if("delete"===u.operation){var m;if(I(d))throw new Error("File changed after the AI edit; Undo would overwrite later work.");c(d,Buffer.from(null!=(m=u.before)?m:"","base64"))}else if("rename"===u.operation){if(!u.newPath)throw new Error("Invalid rename checkpoint.");const e=s(i,u.newPath,!1);if(I(d)||rf(W(e))!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");O(e,d)}else{const e=W(d);if(rf(e)!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");void 0===u.after&&(u.after=e.toString("base64"),function(e,t){const n=JSON.stringify(t);if(l()-N(e).size+Buffer.byteLength(n)>of)throw new Error("Checkpoint storage is full; no file was changed.");c(e,Buffer.from(n))}(p,u)),null===u.before?G(d):c(d,Buffer.from(u.before,"base64"))}return n(),{path:u.path,checkpointId:e.checkpointId,undone:!0}},redo(e,o){const{root:i,grant:r}=a(o);if(!e||"string"!=typeof e.checkpointId||!/^[a-f0-9-]{36}$/.test(e.checkpointId))throw new Error("Invalid checkpoint ID.");const l=ce(t,`${e.checkpointId}.json`),p=JSON.parse(W(l,"utf8"));if(p.project!==i||p.chatId!==r.chatId)throw new Error("Checkpoint belongs to another project or chat.");const u=s(i,p.path,!0);if("delete"===p.operation){var d;if(!I(u)||rf(W(u))!==rf(Buffer.from(null!=(d=p.before)?d:"","base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,!1),G(u)}else if("rename"===p.operation){var m;if(!p.newPath)throw new Error("Invalid rename checkpoint.");const e=s(i,p.newPath,!0);if(!I(u)||I(e)||rf(W(u))!==rf(Buffer.from(null!=(m=p.before)?m:"","base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,!1),s(i,p.newPath,!0),O(u,e)}else{if("string"!=typeof p.after||null===p.afterSha256)throw new Error("This checkpoint cannot be redone.");const e=Buffer.from(p.after,"base64");if(rf(e)!==p.afterSha256)throw new Error("Checkpoint content is damaged; Redo was refused.");if(null===p.before?I(u):!I(u)||rf(W(u))!==rf(Buffer.from(p.before,"base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,null===p.before),c(u,e)}return n(),{path:"rename"===p.operation?p.newPath:p.path,checkpointId:e.checkpointId,redone:!0}},undoTurn(e,n){const{root:o,grant:i}=a(n);if(!e||"string"!=typeof e.turnId||!e.turnId||e.turnId.length>255)throw new Error("Valid turn ID is required.");if(!I(t))throw new Error("No checkpoints found for this turn.");const r=B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({checkpoint:JSON.parse(W(ce(t,e),"utf8")),checkpointId:e.slice(0,-5)})).filter(t=>t.checkpoint.project===o&&t.checkpoint.chatId===i.chatId&&t.checkpoint.turnId===e.turnId);if(!r.length)throw new Error("No checkpoints found for this turn.");if(r.some(e=>!e.checkpoint.order||!/^\d+$/.test(e.checkpoint.order)))throw new Error("Older checkpoints cannot be undone as a turn; use local_files_undo for each file.");r.sort((e,t)=>{const n=BigInt(e.checkpoint.order),o=BigInt(t.checkpoint.order);return n<o?1:n>o?-1:0});const c=new Map,l=e=>{const t=s(o,e,!0);return"win32"===process.platform?t.toLowerCase():t},p=e=>{var t;const n=s(o,e,!0),i=l(e);if(c.has(i))return null!=(t=c.get(i))?t:null;const r=I(n)?W(n):null;return c.set(i,r),r};for(const{checkpoint:e}of r){const t=null===e.before?null:Buffer.from(e.before,"base64");if("rename"===e.operation){if(!e.newPath)throw new Error("Invalid rename checkpoint.");const n=p(e.path),o=p(e.newPath);if(null!==n||null===o||rf(o)!==e.afterSha256)throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t),c.set(l(e.newPath),null)}else if("delete"===e.operation){if(null!==p(e.path))throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t)}else{const n=p(e.path);if(null===n||rf(n)!==e.afterSha256)throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t)}}const u=[];try{for(const{checkpointId:e}of r)this.undo({checkpointId:e},n),u.push(e)}catch(e){const t=[];for(const e of[...u].reverse())try{this.redo({checkpointId:e},n)}catch(e){t.push(e)}if(t.length)throw new AggregateError([e,...t],"Turn Undo stopped and rollback failed; inspect the listed checkpoints before editing again.");throw new Error("Turn Undo stopped; earlier changes were rolled back.",{cause:e})}return{turnId:e.turnId,checkpointIds:u,undone:!0}}}}(()=>{var e;return null==(e=Ff())?void 0:e.web_location},void 0,()=>Af.markStale()),Rf=function(e=ce(oe(),".needle","cli","ai-observations")){function t(t){if(!t||"string"!=typeof t.root||!t.root||"string"!=typeof t.path||!t.path||"string"!=typeof t.chatId||!t.chatId||t.path.includes("\0")||de(t.path)||fe.isAbsolute(t.path)||he.isAbsolute(t.path))throw new Error("A project-relative file path and chat are required.");const n=A(t.root),o=le(n,t.path);if(Wm(n,t.path,{allowMissing:!0}),!o.startsWith(n+me))throw new Error("File path escapes the project.");const i=pe(n,o).split(me).join("/");return{project:n,target:o,path:i,file:ce(e,sf(n),sf(t.chatId),`${sf(i)}.json`)}}function n(e){if(!I(e.target))return null;if(N(Wm(e.project,e.target).path).size>af)return{unsupported:"File exceeds the 1 MiB observation limit."};const t=Gm(e.project,e.target,{maxBytes:af}),n=t.toString("utf8");if(n.includes("\0")||!Buffer.from(n,"utf8").every((e,n)=>t[n]===e)||Buffer.byteLength(n,"utf8")!==t.length)return{unsupported:"Only UTF-8 text files can be observed."};const o=n.split("\n");return o.length>5e3?{unsupported:"File exceeds the 5,000-line observation limit."}:{content:t,lines:Jm(t).split("\n"),hashes:o.map(sf),fileSha256:sf(t)}}function o(e){if(!I(e.file))return null;const t=JSON.parse(W(e.file,"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Stored file observation is damaged.");const n=t;if(1!==n.version||n.project!==e.project||n.path!==e.path||!Array.isArray(n.lineHashes)||!n.lineHashes.every(e=>"string"==typeof e&&/^[a-f0-9]{64}$/.test(e))||"string"!=typeof n.fileSha256||!/^[a-f0-9]{64}$/.test(n.fileSha256)||"string"!=typeof n.chatId||"string"!=typeof n.observedAt)throw new Error("Stored file observation is damaged.");return n}function r(t,n,o){if("unsupported"in n)return{status:"unsupported",reason:n.unsupported};const r={version:1,project:t.project,path:t.path,chatId:o,observedAt:(new Date).toISOString(),fileSha256:n.fileSha256,lineHashes:n.hashes};C(ce(e,sf(t.project),sf(o)),{recursive:!0,mode:448});const a=`${t.file}.${i()}.tmp`;try{H(a,JSON.stringify(r),{flag:"wx",mode:384}),O(a,t.file)}finally{I(a)&&G(a)}return{status:"saved",observedAt:r.observedAt,sha256:r.fileSha256}}return{observe(e){const i=t(e),a=n(i);if(!a)throw new Error("File does not exist.");if("unsupported"in a)return{status:"unsupported",reason:a.unsupported};const s=o(i);return s?{status:"existing",observedAt:s.observedAt,sha256:s.fileSha256}:r(i,a,e.chatId)},snapshot(e){const o=t(e),i=n(o);if(!i)throw new Error("File does not exist.");return r(o,i,e.chatId)},diff(e){const i=t(e),r=o(i);if(!r)return{status:"no_baseline",path:i.path};const a=n(i);if(!a)return{status:"deleted",path:i.path,observedAt:r.observedAt};if("unsupported"in a)return{status:"unsupported",path:i.path,reason:a.unsupported};if(r.fileSha256===a.fileSha256)return{status:"unchanged",path:i.path,observedAt:r.observedAt,sha256:a.fileSha256};const s=function(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let o=e.length,i=t.length;for(;o>n&&i>n&&e[o-1]===t[i-1];)o--,i--;if(n===o&&n===i)return[];const r=new Map;for(let t=n;t<o;t++){const n=r.get(e[t]);n?n.count++:r.set(e[t],{index:t,count:1})}const a=new Map;for(let e=n;e<i;e++){var s;a.set(t[e],(null!=(s=a.get(t[e]))?s:0)+1)}const c=[];for(let e=n;e<i;e++){const n=r.get(t[e]);1===(null==n?void 0:n.count)&&1===a.get(t[e])&&c.push({old:n.index,current:e})}const l=[],p=[];for(let e=0;e<c.length;e++){let t=0,n=l.length;for(;t<n;){const o=t+n>>1;c[l[o]].old<c[e].old?t=o+1:n=o}p[e]=t?l[t-1]:-1,l[t]=e}const u=[];for(let e=l.length?l[l.length-1]:-1;e>=0;e=p[e])u.push(c[e]);u.reverse();const d=[];let m=n,f=n;for(const n of[...u,{old:o,current:i}]){let o=n.old,i=n.current;for(;m<o&&f<i&&e[m]===t[f];)m++,f++;for(;o>m&&i>f&&e[o-1]===t[i-1];)o--,i--;m===o&&f===i||d.push({oldStart:m,oldEnd:o,newStart:f,newEnd:i}),m=n.old+1,f=n.current+1}return d}(r.lineHashes,a.hashes);let c=80;const l=s.slice(0,20).map(e=>{const t=Math.min(e.newEnd-e.newStart,c);return c-=t,{before:{start:e.oldStart+1,count:e.oldEnd-e.oldStart},after:{start:e.newStart+1,count:e.newEnd-e.newStart},lines:a.lines.slice(e.newStart,e.newStart+t).map(e=>e.slice(0,300)),omittedLines:e.newEnd-e.newStart-t}});return{status:"changed",path:i.path,observedAt:r.observedAt,beforeSha256:r.fileSha256,afterSha256:a.fileSha256,beforeLineCount:r.lineHashes.length,afterLineCount:a.hashes.length,hunks:l,totalHunks:s.length,truncated:s.length>l.length,detail:s.length?void 0:"File bytes changed without a text-line change (for example line endings)."}}}}(),Pf=function(e,t=x){return async function(n){const o=e(),i="web"===n.project?null==o?void 0:o.web_location:"editor"===n.project?null==o?void 0:o.project_location:null;if(!i)throw new Error("The selected local project is unavailable.");if("string"!=typeof n.path||!n.path.trim()||de(n.path)||n.path.includes("\0"))throw new Error("Use a nonempty project-relative path.");const r=A.native(i),a=le(r,n.path),s=pe(r,a);if(".."===s||s.startsWith(`..${me}`)||de(s))throw new Error("File path is outside the selected project.");const c=A.native(a),l=pe(r,c);if(".."===l||l.startsWith(`..${me}`)||de(l))throw new Error("File path is outside the selected project.");const p=N(c);if(!p.isFile()&&!p.isDirectory())throw new Error("The selected path is not a file or directory.");if(cf.has(ae(c).toLowerCase()))throw new Error("Opening executable file types is not supported.");return await t(c),{opened:!0,project:n.project,path:pe(r,c)||"."}}}(Ff),Uf=function(e){const{getProject:t,getHome:n=oe,run:o=Tf,commandsEnabled:r=(()=>!hf()),onFailure:a,onCreated:s,onApprovedProject:c,now:l=Date.now,getProcessIdentity:p=yf}=e,u=function(e=ce(oe(),".needle","cli","ai-jobs"),t=Date.now){const n=t=>{if(!bf.test(t))throw new Error("Invalid project job ID.");return ce(e,`${t}.json`)};return{runtimeFile:t=>(n(t),ce(e,`${t}.runtime.json`)),runtime(e){const t=this.runtimeFile(e);if(!I(t))return;const n=JSON.parse(W(t,"utf8"));if(!n||"object"!=typeof n||Array.isArray(n))throw new Error("Invalid local dev runtime state.");const o=n;if(!["running","completed","failed","canceled"].includes(String(o.status))||void 0!==o.url&&"string"!=typeof o.url||void 0!==o.exitCode&&!Number.isSafeInteger(o.exitCode)||void 0!==o.error&&"string"!=typeof o.error)throw new Error("Invalid local dev runtime state.");return o},save(t){const o=n(t.jobId);C(e,{recursive:!0,mode:448});const r=ce(e,`${t.jobId}.${i()}.tmp`);try{H(r,JSON.stringify(t),{flag:"wx",mode:384}),O(r,o)}finally{I(r)&&G(r)}},get(e){const o=n(e);if(!I(o))return;const i=JSON.parse(W(o,"utf8"));if(!i||"object"!=typeof i||Array.isArray(i))throw new Error("Invalid stored project job.");const r=i;if(r.jobId!==e||"string"!=typeof r.chatId||"string"!=typeof r.operation||void 0!==r.project&&"string"!=typeof r.project||void 0!==r.workingDirectory&&"string"!=typeof r.workingDirectory||void 0!==r.startedAt&&!Number.isFinite(r.startedAt)||void 0!==r.pid&&(!Number.isSafeInteger(r.pid)||Number(r.pid)<1)||void 0!==r.processIdentity&&"string"!=typeof r.processIdentity||!Number.isFinite(r.createdAt)||!Number.isFinite(r.updatedAt)||"string"!=typeof r.output||r.output.length>8e3||!["running","completed","failed","canceled"].includes(String(r.status)))throw new Error("Invalid stored project job.");const a=r;if(!("running"!==a.status&&t()-a.updatedAt>1728e5))return a;{G(o);const t=this.runtimeFile(e);I(t)&&G(t)}},list(){return I(e)?B(e).filter(e=>bf.test(e.slice(0,-5))&&e.endsWith(".json")).map(e=>{try{return this.get(e.slice(0,-5))}catch(t){return void console.warn(`Could not read local project job ${e}: ${t instanceof Error?t.message:String(t)}`)}}).filter(e=>!!e):[]},remove(e){const t=n(e);I(t)&&G(t);const o=this.runtimeFile(e);I(o)&&G(o)}}}(ce(n(),".needle","cli","ai-jobs"),l),d=new Map,m=new Map;function f(e){const{controller:t,...n}=e;u.save(n)}function h(e){if("failed"!==e.status||!a)return;const{controller:t,...n}=e;try{a(n)}catch(e){console.error(`Could not record local project job failure: ${e instanceof Error?e.message:String(e)}`)}}function g(){for(const[e,t]of d)l()-t.createdAt>3e5&&d.delete(e);for(const[e,t]of m)"running"!==t.status&&l()-t.updatedAt>36e5&&m.delete(e)}function v(e){const o=kf(e.request,t(),n());if(JSON.stringify({...o,request:null})!==JSON.stringify({...e,request:null,planId:void 0,chatId:void 0,createdAt:void 0}))throw new Error("The project command or its inputs changed since approval. Plan it again.")}function b(e){if("running"!==e.status)return e;const t="dev"===e.operation?u.runtime(e.jobId):void 0;return null!=t&&t.url&&(e.url=t.url),t&&"running"!==t.status?(e.status=t.status,e.exitCode=t.exitCode,t.error&&(e.output=Dm(t.error).slice(-8e3))):"dev"===e.operation&&e.pid&&e.processIdentity&&p(e.pid)===e.processIdentity||(e.status="failed",e.output=`${e.output}\nThe CLI restarted and the original project process is no longer running or cannot be verified.`.trim().slice(-8e3)),"running"!==e.status&&(e.updatedAt=l(),u.save(e)),e}function y(e){if(e)return[...m.values()].find(t=>"dev"===t.operation&&t.project===e&&"running"===t.status)||u.list().map(b).find(t=>"dev"===t.operation&&t.project===e&&"running"===t.status)}function x(){for(const e of u.list())b(e)}x();const w=setInterval(x,36e5);return w.unref(),{plan(e,o){if(g(),!o)throw new Error("A Cloud chat is required to plan an AI project command.");const r={...kf(e,t(),n()),planId:i(),chatId:o,createdAt:l()},a="dev"===r.operation?y(r.project):void 0;if(a)throw new Error(`A dev server for this project is already running (job ID ${a.jobId}). Check its status or cancel it before starting another.`);return d.set(r.planId,r),r},getPlan(e,t){g();const n=d.get(e);if(!n||n.chatId!==t)throw new Error("This project command plan does not belong to this chat or expired.");return v(n),n},async start(e,t){g();const n=d.get(e);if(!n)throw new Error("This project command plan expired or was already used.");if(!t||t.chatId!==n.chatId||t.planId!==e)throw new Error("Exact Cloud approval is required for this project command.");if(!r())throw new Error("AI project commands are disabled in local Needle CLI settings.");v(n);const a="dev"===n.operation?y(n.project):void 0;if(a)throw new Error(`A dev server for this project is already running (job ID ${a.jobId}). Check its status or cancel it before starting another.`);n.customProject&&n.project&&(null==c||c(n.project)),d.delete(e);const p={jobId:i(),chatId:n.chatId,operation:n.operation,project:n.project||n.destination,workingDirectory:n.project||ue(n.destination),startedAt:l(),createdAt:l(),updatedAt:l(),status:"running",output:"",controller:new AbortController};return m.set(p.jobId,p),f(p),"dev"===n.operation&&(n.runtimeFile=u.runtimeFile(p.jobId)),Promise.resolve().then(()=>o(n,p.controller.signal,e=>{"running"===p.status&&(void 0!==e.output&&(p.output=Dm(e.output).slice(-8e3)),void 0!==e.url&&(p.url=e.url),void 0!==e.browserOpened&&(p.browserOpened=e.browserOpened),void 0!==e.browserError&&(p.browserError=e.browserError),"dev"===n.operation&&void 0!==e.pid&&e.processIdentity&&(p.pid=e.pid,p.processIdentity=e.processIdentity,void 0!==e.startedAt&&(p.startedAt=e.startedAt)),p.updatedAt=l(),f(p))})).then(e=>{p.exitCode=e.exitCode,p.output=Dm(String(e.output||"")).slice(-8e3),"canceled"!==p.status&&0===e.exitCode&&"create"===n.operation&&n.destination&&(null==s||s(n.destination)),"canceled"!==p.status&&(p.status=0===e.exitCode?"completed":"failed"),p.updatedAt=l(),f(p),h(p)}).catch(e=>{const t=p.controller.signal.aborted;p.controller.abort(),p.output=Dm(e instanceof Error?e.message:String(e)).slice(-8e3),p.status=t?"canceled":"failed",p.updatedAt=l(),f(p),h(p)}),{jobId:p.jobId,status:"running"}},status(e,t){g();const n=m.get(e)||u.get(e);if(!n||n.chatId!==t)throw new Error("This project job does not belong to this chat.");const o=m.get(e);if(o){const{controller:e,...t}=o;return t}return b(n)},async cancel(e,t){const n=m.get(e),o=n?void 0:u.get(e),i=n||o&&b(o);if(!i||i.chatId!==t)throw new Error("This project job does not belong to this chat.");if("running"!==i.status)return{jobId:e,canceled:!1};if(!n){if("dev"!==i.operation)throw new Error("Only supervised dev jobs can be stopped after a CLI restart.");H(`${u.runtimeFile(e)}.cancel`,"",{flag:"w",mode:384});const t=Date.now()+1e4;for(;Date.now()<t;){const t=b(i);if("running"!==t.status)return{jobId:e,canceled:"canceled"===t.status};await new Promise(e=>setTimeout(e,100))}throw new Error("The dev server stop was requested, but the supervisor did not confirm it within 10 seconds. Check the job status.")}return n.controller.abort(),i.status="canceled",i.updatedAt=l(),f(n),{jobId:e,canceled:!0}},dispose(){clearInterval(w);for(const e of m.values())"running"===e.status&&"dev"!==e.operation&&(e.controller.abort(),e.status="canceled",e.updatedAt=l(),f(e))}}}({getProject:()=>{var e;return null==(e=Ff())?void 0:e.web_location},onCreated:gm,onApprovedProject:gm,onFailure:e=>{var t;return du(`[AI project] ${e.operation} failed job=${e.jobId} exit=${null!=(t=e.exitCode)?t:"error"} output=${e.output.replace(/\s+/g," ").slice(0,700)}`)}});function Lf(e){if(null==e||!e.editGrant)throw new Error("Local file edit approval is required.");if(ff())throw new Error("AI file edits are disabled in local Needle CLI settings.");return e.editGrant}function zf(e={}){Of({name:"local_files_editor_log_path",description:"Get the filepath to the editor log file on disk (this may be Unity or Blender)",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];if(null!=e&&e.log_location){const n=p(e.log_location).mtime;t.content.push({type:"text",text:`${e.log_location} (last modified: ${n.toLocaleString()})`})}else{let n="No recent project with known log location known.";e&&(n+=" Recent project is "+(null==e?void 0:e.project_location)),t.content.push({type:"text",text:n})}}return t},{source:"cli"},()=>{}),Of({name:"local_files_editor_project_path",description:"Get the filepath to the currently opened project in the editor (this may be Unity or Blender)",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];t.content.push(null!=e&&e.project_location?{type:"text",text:e.project_location}:{type:"text",text:"No recent project with known project location known."})}return t},{source:"cli"},()=>{}),Of({name:"local_files_editor_scene_path",description:"Get the filepath to the currently opened scene in the editor (Unity or Blender). Use this to find out which scene the user is working on.",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];t.content.push(null!=e&&e.scene_location?{type:"text",text:e.scene_location}:{type:"text",text:"No recent project with known scene location known."})}return t},{source:"cli"},()=>{}),Of({name:"local_files_web_project_path",description:"Get the filepath to the selected Needle Engine web project. Unity-generated web projects may validly live inside the Unity project's Library/Needle directory; do not treat that location alone as a misconfiguration. Use this directory as the web-project root.",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=Ff();return t.content.push(null!=n&&n.web_location?{type:"text",text:_(n.web_location)}:{type:"text",text:"No selected web project is known."}),t},{source:"cli"},()=>{}),Of({name:"local_files_diff",description:"Compare a local project text file with the first version observed by this chat. local_files_read saves a hash-only baseline on the first read; later reads do not replace it. Returns changed line ranges and bounded current lines, never removed text or who changed it. If no baseline exists, read the file first. Use mode=reset only after reviewing changes to start a new baseline. Works for web and editor project files.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path relative to the connected web or editor project, or an absolute path within it."},mode:{type:"string",enum:["compare","reset"],description:"Compare with the first observed version (default), or replace that version with the current file."}},required:["path"],additionalProperties:!1}},async(e,t)=>{var n;const o=Bf(e.path);if(!o)throw new Error("Path is outside the connected project.");const i={root:o.root,path:j(o.root,o.resolved),chatId:null!=(n=null==t?void 0:t.chatId)?n:"local-mcp"},r="reset"===e.mode?Rf.snapshot(i):Rf.diff(i);return{content:[{type:"text",text:JSON.stringify(r)}]}},{source:"cli"},()=>{}),Of({name:"local_files_open",description:'Open an existing file or directory in the connected local web or editor project using the operating system default app. Directories open in the file manager; use path="." for the project root. Use a project-relative path and select project="web" or "editor". This affects the user desktop. It does not read or edit files. Executable file types and paths outside the selected project are refused.',inputSchema:{type:"object",properties:{project:{type:"string",enum:["web","editor"]},path:{type:"string"}},required:["project","path"],additionalProperties:!1}},async e=>({content:[{type:"text",text:JSON.stringify(await Pf(e))}]}),{source:"cli"},()=>{}),Of({name:"local_files_read",description:"Read a file from the user's local project on disk (editor project or web project). The path must be relative to the project root or an absolute path inside the project. Sensitive files, including .env variants and private keys, are refused. Recognizable secrets are redacted before filtering or selecting lines. UTF-8 files are limited to 8 MiB. Returns the file contents (or a portion if offset/limit are specified). Use 'filter' to search for specific terms within the file.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path (relative to project root, or absolute within the project)"},offset:{type:"number",description:"Line number to start reading from (1-based, default: 1). In filter mode: number of matches to skip."},limit:{type:"number",description:"Maximum number of lines to return (default: 200, max: 1000). In filter mode: max matches to return."},filter:{type:"string",description:'Regex to search for in the file (case-insensitive, e.g. "error|warning"). Falls back to a literal substring match if the pattern isn\'t valid regex. Returns matching lines with line numbers instead of sequential content.'}},additionalProperties:!1,required:["path"]}},async(e,t)=>{const n=Bf(e.path);if(!n)return{content:[{type:"text",text:"Error: path is outside the project directory."}]};try{const i=p(n.resolved).mtime.toISOString(),r=Vm(n.root,n.resolved).text.split("\n");let a="";try{var o;const e=Rf.observe({root:n.root,path:j(n.root,n.resolved),chatId:null!=(o=null==t?void 0:t.chatId)?o:"local-mcp"});a="unsupported"===e.status?`\nChange baseline unavailable: ${e.reason}`:`\nChange baseline: ${"saved"===e.status?"saved":"kept from first read"}. Use local_files_diff to compare later changes.`}catch(e){console.error("[MCP] Could not observe local file changes",e),a=`\nChange baseline unavailable: ${e instanceof Error?e.message:"unknown error"}`}if(e.filter){const t=$f(e.filter),o=[];for(let e=0;e<r.length;e++)t.test(r[e])&&o.push(`${e+1}: ${r[e]}`);const s=o.length,c=Math.max(0,e.offset||0),l=Math.min(Math.max(e.limit||200,1),1e3),p=o.slice(c,c+l);return{content:[{type:"text",text:`File: ${n.resolved} (modified: ${i}) — filter="${e.filter}" (${t.mode}) → ${s} matches (showing ${c+1}-${c+p.length}) in ${r.length} lines`+a+"\n"+p.join("\n")}]}}const s=Math.max(1,e.offset||1),c=Math.min(e.limit||200,1e3),l=r.slice(s-1,s-1+c),u=l.map((e,t)=>`${s+t}: ${e}`).join("\n");return{content:[{type:"text",text:`File: ${n.resolved} (${r.length} lines, modified: ${i}, showing ${s}-${s+l.length-1})`+a+"\n"+u}]}}catch(e){return{content:[{type:"text",text:`Error reading file: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),Of({name:"local_files_grep",description:"Search for a pattern in the user's local project files on disk (editor project and web project) using grep. Searches sanitized UTF-8 text; sensitive files, links, hidden directories and node_modules are skipped. Reports omitted entries and search limits. Returns matching lines with file paths and line numbers. Note: runtime-only things (e.g. node-material shaders) have no source files — read those with the inspector_* tools instead.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regular expression)"},glob:{type:"string",description:"File glob filter, e.g. '*.ts' or '*.cs' (optional)"},max_results:{type:"number",description:"Maximum number of matching lines to return (default: 50)"}},additionalProperties:!1,required:["pattern"]}},async e=>{const t=qf();if(0===t.length)return{content:[{type:"text",text:"Error: no active project found."}]};const n=Math.min(Math.max(Math.floor(e.max_results||50),1),200),o=t.map(t=>Ym(t,{pattern:e.pattern,glob:e.glob,maxResults:n})),i=o.flatMap(e=>e.lines),r=`\nOmitted ${o.reduce((e,t)=>e+t.omitted,0)} sensitive, unsupported or excluded entries.${o.some(e=>e.limited)?" Search stopped at the file, byte, depth or time limit.":""}`;return{content:[{type:"text",text:(i.length?`Found ${i.length} matches:\n`+i.slice(0,n).join("\n"):"No matches found.")+r}]}},{source:"cli"},()=>{}),Of({name:"local_files_list",description:"List files in the user's local project directories on disk matching an optional glob pattern. A list is shallow by default: files in subdirectories are NOT included. When checking whether a file exists anywhere below a folder, use recursive=true or provide its exact subdirectory in path. By default searches both the editor project (Unity/Blender) and the web project. Use the 'project' parameter to target a specific one. Results are prefixed with <web_project>/..., <unity>/..., or <blender>/... so you know which root each file belongs to. Do not conclude that a file is absent from a project based on a shallow listing.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Project-relative subdirectory to list (default: root). Absolute paths, including paths to a different project, are not accepted."},pattern:{type:"string",description:"Glob pattern to filter files, e.g. '*.ts' or '*.glb'. Supports multiple patterns separated by '|', e.g. '*.gltf|*.glb' (optional)"},recursive:{type:"boolean",description:"Set true to include files in all subdirectories. Default false lists only files directly in path; use true before claiming a nested file is absent."},project:{type:"string",enum:["web","editor"],description:"Which project root to search: 'web' for the Needle Engine web project (use this for exported assets, source files, node_modules), 'editor' for the Unity/Blender project. Omit to search both."}},additionalProperties:!1,required:[]}},async e=>{if(void 0!==e.path&&("string"!=typeof e.path||k(e.path)))return{content:[{type:"text",text:"Error: local_files_list requires a project-relative path. It cannot list an absolute path outside the connected project."}]};const t=Ff();if(!t)return{content:[{type:"text",text:"Error: no active project found."}]};const n="blender"===t.editor?"<blender>":"unity"===t.editor?"<unity>":"<editor_project>",o=[];if(e.project&&"editor"!==e.project||!t.project_location||o.push({root:_(t.project_location),label:n}),e.project&&"web"!==e.project||!t.web_location||o.push({root:_(t.web_location),label:"<web_project>"}),0===o.length)return{content:[{type:"text",text:"Error: no active project found."}]};const i=[],r=[];for(const{root:t,label:n}of o){const o=Df(e.path||".",t);if(o)try{var a;e.recursive||r.push(...d(o,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"node_modules"!==e.name).map(e=>`${n}/${j(t,S(o,e.name))}`));const s=Wf(o,t,null!=(a=e.recursive)&&a,e.pattern,0);i.push(...s.map(e=>({file:e,root:t,label:n})))}catch(e){throw new Error(`Could not list project files: ${e instanceof Error?e.message:String(e)}`)}}const s=r.length>0?`\nShallow listing: subdirectories were not searched (${r.slice(0,12).join(", ")}${r.length>12?", ...":""}). To search nested files, call local_files_list with recursive=true or set path to the subdirectory.`:"";if(0===i.length)return{content:[{type:"text",text:`No files found directly in the selected path.${o.length>0?`\nSearched in:\n${o.map(e=>`${e.label} → ${e.root}`).join("\n")}`:"\nNo project directories available to search."}${s}`}]};const c=i.slice(0,500).map(e=>`${e.label}/${j(e.root,e.file)}`);return{content:[{type:"text",text:`Found ${i.length} files${i.length>500?" (showing first 500)":""}:\n`+c.join("\n")+s}]}},{source:"cli"},()=>{}),Of({name:"local_files_read_editor_log",description:"Read or search the Unity or Blender editor log file. By default reads the last N lines. Use the 'filter' parameter to search for specific terms (e.g. error messages, warnings, component names) across the entire log.",inputSchema:{type:"object",properties:{lines:{type:"number",description:"Number of lines to read from the end of the log (default: 100, max: 500). Ignored when filter is set."},filter:{type:"string",description:'Regex to search for in the log (case-insensitive, e.g. "error|exception|warning"). Falls back to a literal substring match if the pattern isn\'t valid regex. Returns all matching lines from the entire log instead of just the tail.'},offset:{type:"number",description:"Number of matching results to skip from the start (default: 0). Only used with filter."},limit:{type:"number",description:"Maximum number of matching results to return (default: 200, max: 500). Only used with filter."}},additionalProperties:!1,required:[]}},async e=>{const t=Ff();var n;if(null==t||!t.log_location)return mu(`read_editor_log: no editor log file known (project: ${null!=(n=null==t?void 0:t.project_location)?n:"none"})`),{content:[{type:"text",text:"Error: no editor log file known. Is a Unity or Blender project open?"}]};try{if(!t.log_location.toLowerCase().endsWith(".log"))throw new Error("Only the connected editor log can be read.");const n=Vm(ue(t.log_location),se(t.log_location),{maxBytes:67108864,allowPrivateKeys:!0}).text.split("\n");let o,i;if(e.filter){const t=$f(e.filter);o=[];for(let e=0;e<n.length;e++)t.test(n[e])&&o.push(`L${e+1}: ${n[e]}`);const r=o.length,a=Math.max(0,e.offset||0),s=Math.min(Math.max(e.limit||200,1),500);o=o.slice(a,a+s),i=`filter="${e.filter}" (${t.mode}) → ${r} matches (showing ${a+1}-${a+o.length}) in ${n.length} total lines`}else{const t=Math.min(Math.max(e.lines||100,1),500);o=n.slice(-t),i=`last ${t} of ${n.length} lines`}const r="unity"===t.editor?function(e){const t=[],n=new Map;let o=!1,i=0;for(const r of e){if(/^\s+at\s/.test(r)||/^\s*(UnityEngine\.|System\.|Unity\.)/.test(r)||/^\s+\w+[\w.<>]+\s*\(/.test(r)){o||(o=!0,i=0),i++,i<=3?t.push(r):4===i&&t.push(" ... (stack trace truncated)");continue}if(o=!1,i=0,!r.trim())continue;const e=n.get(r)||0;if(n.set(r,e+1),0===e)t.push(r);else if(1===e)t.push(` [repeated ${e+1}x] ${r}`);else{const n=t.length-1;n>=0&&t[n].startsWith(" [repeated")&&(t[n]=` [repeated ${e+1}x] ${r}`)}}return t}(o):o,a=5e4;let s=r.join("\n"),c="";if(s.length>a){s=s.substring(s.length-a);const e=s.indexOf("\n");e>0&&(s=s.substring(e+1)),c=" (output truncated to last ~50KB)"}return{content:[{type:"text",text:`Editor log: ${t.log_location} (${i}, ${r.length} after processing, editor: ${t.editor})${c}:\n`+s}]}}catch(e){return{content:[{type:"text",text:`Error reading log: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),Of({name:"local_files_read_gltf",description:"Read and summarize a glTF or GLB file from the user's local project on disk. Without a query, returns a structured summary including nodes, meshes, materials, animations, extensions, and compression/optimization hints. Use 'query' to drill into specific parts using JSON pointer paths. Use '*' as a wildcard for array indices or object keys. For GLB files, extracts the JSON chunk and skips binary data.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to a .gltf or .glb file (relative to project root, or absolute path)"},query:{type:"string",description:"JSON pointer path to extract a specific part of the glTF, e.g. '/nodes/0', '/materials', '/extensions/NEEDLE_progressive', '/materials/*/extensions'. Use '*' as a wildcard for array indices or object keys."}},additionalProperties:!1,required:["path"]}},async e=>{let t=Bf(e.path);if(!t)return{content:[{type:"text",text:"Error: path is outside the project directory."}]};if(!l(t.resolved))return{content:[{type:"text",text:`Error: file not found: ${t.resolved}`}]};try{const n=function(e,t){const n=e.toLowerCase();if(n.endsWith(".gltf")){const n=Vm(t,e).text;return JSON.parse(n)}if(n.endsWith(".glb")){const n=Gm(t,e,{maxBytes:20,range:{offset:0,length:20}});if(n.length<20)return null;if(1179937895!==n.readUInt32LE(0))return null;const o=n.readUInt32LE(12);if(1313821514!==n.readUInt32LE(16))return null;const i=Gm(t,e,{maxBytes:67108864,range:{offset:20,length:o}}).toString("utf-8"),r=Lm(JSON.parse(i));if(!r||"object"!=typeof r||Array.isArray(r))throw new Error("glTF JSON must be an object.");return r}return null}(t.resolved,t.root);if(!n)return{content:[{type:"text",text:"Error: could not parse glTF/GLB file."}]};const o=5e4;if(e.query){const i=Mf(n,e.query.replace(/^\//,"").split("/"));if(void 0===i)return{content:[{type:"text",text:`No data found at pointer: ${e.query}`}]};let r=JSON.stringify(i),a=!1;return r.length>o&&(r=r.substring(0,o),a=!0),{content:[{type:"text",text:`${e.query} in ${t.resolved}`+(a?` (truncated to ${o} chars)`:"")+"\n"+r}]}}let i=function(e,t){var n,o,i,r,a,s,c,l,p,u,d,m,f;const h=[`glTF: ${t}`];if(e.asset){const t=[];e.asset.version&&t.push(`v${e.asset.version}`),e.asset.generator&&t.push(e.asset.generator),h.push(`Asset: ${t.join(", ")}`)}if(null!=(n=e.extensionsUsed)&&n.length&&h.push(`Extensions used: ${e.extensionsUsed.join(", ")}`),null!=(o=e.extensionsRequired)&&o.length&&h.push(`Extensions required: ${e.extensionsRequired.join(", ")}`),null!=(i=e.scenes)&&i.length&&h.push(`Scenes: ${e.scenes.length}${void 0!==e.scene?` (default: ${e.scene})`:""}`),null!=(r=e.nodes)&&r.length){var g,v,b;h.push(`\nNodes (${e.nodes.length}):`);const t=null!=(g=null==(v=e.scenes)||null==(v=v[null!=(b=e.scene)?b:0])?void 0:v.nodes)?g:[],n=new Set,o=(t,i)=>{if(i>6||n.has(t))return;n.add(t);const r=e.nodes[t];if(!r)return;const a=" ".repeat(i),s=[];if(void 0!==r.mesh&&s.push(`mesh:${r.mesh}`),void 0!==r.camera&&s.push(`camera:${r.camera}`),void 0!==r.skin&&s.push(`skin:${r.skin}`),r.extensions&&s.push(`ext:[${Object.keys(r.extensions).join(",")}]`),h.push(`${a}- ${r.name||`node_${t}`}${s.length?` (${s.join(", ")})`:""}`),r.children)for(const e of r.children)o(e,i+1)};for(const e of t)o(e,1);n.size<e.nodes.length&&n.size>0&&h.push(` ... and ${e.nodes.length-n.size} more nodes`)}if(null!=(a=e.meshes)&&a.length){h.push(`\nMeshes (${e.meshes.length}):`);for(const t of e.meshes.slice(0,30)){var y,x;const e=null!=(y=null==(x=t.primitives)?void 0:x.length)?y:0;h.push(` - ${t.name||"(unnamed)"} (${e} primitive${1!==e?"s":""})`)}e.meshes.length>30&&h.push(` ... and ${e.meshes.length-30} more`)}if(null!=(s=e.materials)&&s.length){h.push(`\nMaterials (${e.materials.length}):`);for(const t of e.materials.slice(0,30)){const e=t.name||"(unnamed)",n=[];t.pbrMetallicRoughness&&n.push("PBR"),t.alphaMode&&"OPAQUE"!==t.alphaMode&&n.push(t.alphaMode),t.doubleSided&&n.push("doubleSided"),t.extensions&&n.push(`ext:[${Object.keys(t.extensions).join(",")}]`),h.push(` - ${e}${n.length?` (${n.join(", ")})`:""}`)}e.materials.length>30&&h.push(` ... and ${e.materials.length-30} more`)}if(null!=(c=e.textures)&&c.length&&h.push(`Textures: ${e.textures.length}`),null!=(l=e.images)&&l.length&&h.push(`Images: ${e.images.length}`),null!=(p=e.animations)&&p.length){h.push(`\nAnimations (${e.animations.length}):`);for(const t of e.animations.slice(0,20)){var w,_;const e=null!=(w=null==(_=t.channels)?void 0:_.length)?w:0;h.push(` - ${t.name||"(unnamed)"} (${e} channel${1!==e?"s":""})`)}e.animations.length>20&&h.push(` ... and ${e.animations.length-20} more`)}if(null!=(u=e.skins)&&u.length){h.push(`\nSkins (${e.skins.length}):`);for(const t of e.skins.slice(0,10)){var S,j;h.push(` - ${t.name||"(unnamed)"} (${null!=(S=null==(j=t.joints)?void 0:j.length)?S:0} joints)`)}}if(null!=(d=e.cameras)&&d.length){h.push(`\nCameras (${e.cameras.length}):`);for(const t of e.cameras)h.push(` - ${t.name||"(unnamed)"} (${t.type})`)}if(null!=(m=e.buffers)&&m.length){const t=e.buffers.reduce((e,t)=>e+(t.byteLength||0),0);h.push(`\nBuffers: ${e.buffers.length} (${(t/1024/1024).toFixed(1)} MB total)`)}return null!=(f=e.accessors)&&f.length&&h.push(`Accessors: ${e.accessors.length}`),h.join("\n")}(n,t.resolved);return i.length>o&&(i=i.substring(0,o)+"\n... (truncated)"),{content:[{type:"text",text:i}]}}catch(e){return{content:[{type:"text",text:`Error reading glTF: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),function(){const e=e=>({content:[{type:"text",text:JSON.stringify(e)}]});Of({name:"local_files_resolve_url",description:"Find the working directory of the process serving a localhost URL, including a server started by another app or by the user. Returns the listening PID and working directory, or an explicit reason when unavailable. The URL path is not assumed to be a file path. Works only for a server running on the same machine as the Needle CLI.",inputSchema:{type:"object",properties:{url:{type:"string",description:"HTTP localhost URL or loopback host:port, for example http://127.0.0.1:8765/preview.html."}},required:["url"],additionalProperties:!1}},async t=>e(await async function(e){const t=function(e){if("string"!=typeof e||!e.trim())throw new Error("A localhost URL or host:port is required.");const t=e.trim(),n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`http://${t}`);if("http:"!==n.protocol&&"https:"!==n.protocol)throw new Error("Only HTTP and HTTPS localhost URLs are supported.");const o=n.hostname.toLowerCase();if(!["localhost","127.0.0.1","[::1]"].includes(o))throw new Error("Only localhost or loopback IP addresses are supported.");const i=n.port?Number(n.port):"https:"===n.protocol?443:80;if(!Number.isInteger(i)||i<1||i>65535)throw new Error("A valid TCP port is required.");return{host:o,port:i,path:n.pathname+n.search}}(e);if("win32"===process.platform){const e=await async function(e,t){const n=Cf.replace("__PORT__",String(e)).replace("__HOST__",t),o=Buffer.from(n,"utf16le").toString("base64"),{stdout:i}=await If("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",o],{timeout:1e4,maxBuffer:1048576});return JSON.parse(i.trim())}(t.port,t.host);return{...t,...e}}if("linux"===process.platform||"darwin"===process.platform){const e="linux"===process.platform?await async function(e){const t=new Set;for(const o of["/proc/net/tcp","/proc/net/tcp6"]){let i;try{i=await K(o,"utf8")}catch(e){if("ENOENT"===e.code)continue;throw e}for(const o of i.split("\n").slice(1)){var n;const i=o.trim().split(/\s+/);i.length<10||Number.parseInt(null!=(n=i[1].split(":").at(-1))?n:"",16)===e&&"0A"===i[3]&&t.add(i[9])}}if(!t.size)return null;const o=await Z("/proc",{withFileTypes:!0});for(const e of o){if(!e.isDirectory()||!/^\d+$/.test(e.name))continue;let n;try{n=await Z(`/proc/${e.name}/fd`)}catch{continue}for(const o of n)try{const n=await Y(`/proc/${e.name}/fd/${o}`),i=/^socket:\[(\d+)\]$/.exec(n);if(i&&t.has(i[1]))return Number(e.name)}catch{}}throw new Error("A process is listening, but its PID is not visible to this CLI.")}(t.port):await async function(e){try{const{stdout:t}=await If("lsof",["-nP","-t",`-iTCP:${e}`,"-sTCP:LISTEN"],{timeout:5e3}),n=Number(t.trim().split(/\s+/)[0]);return Number.isInteger(n)&&n>0?n:null}catch(e){if(1===e.code)return null;throw e}}(t.port);if(null===e)return{...t,status:"not-listening"};try{const n="linux"===process.platform?await Y(`/proc/${e}/cwd`):await async function(e){const{stdout:t}=await If("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeout:5e3}),n=t.split(/\r?\n/).find(e=>e.startsWith("n"));if(!n)throw new Error("The process working directory is not available.");return n.slice(1)}(e);return{...t,status:"found",pid:e,workingDirectory:n}}catch(n){return{...t,status:"unavailable",pid:e,reason:n instanceof Error?n.message:String(n)}}}return{...t,status:"unavailable",reason:`Unsupported platform: ${process.platform}`}}(null==t?void 0:t.url)),{source:"cli"},()=>{}),Of({name:"local_project_list",description:"List web projects registered with the local Needle CLI, including projects created by AI after a successful create job. Each path may be selected with local_project_select. File tools access only the currently selected project.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1}},async()=>e(dm().entries.filter(e=>e.web_location).map(e=>({path:e.web_location,selected:e===Ff(),editor:e.editor}))),{source:"cli"},()=>{}),Of({name:"local_project_select",description:"Select a registered local web project by its exact path from local_project_list. Subsequent local_files_* tools use this project. Selecting a project does not approve edits; Cloud chat must obtain a separate file-edit grant for the selected project.",inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1}},async t=>e({selected:vm(t.path).web_location}),{source:"cli"},()=>{}),Of({name:"local_project_action",description:"Prepare a local Needle project action without executing it. Operations: create (name, template, optional absolute parent or destination), install, add_package (packages, optional dev), build, dev (start the dev server and open its local URL in the default browser), deploy (target team ID required; optional name and relative build directory). For dev, hot reload may be disabled in vite.config.js/ts by hmr: false or Needle allowHotReload: false; if edits do not appear, inspect the config and use the normal file-edit approval to enable it if appropriate. For create, parent is an existing folder to create the named project INSIDE, even if the parent has spaces or parentheses; destination is the full path of the new project and must end with name. If the user provides an existing folder path, use parent and do not treat its basename as the project name. If only the name is missing, ask only for a name. For install/add_package/build/dev/deploy, omit project to use the selected web project, or pass an explicit absolute path to another local project; that target needs fresh Cloud approval. An approved action for another project registers and selects it for local file tools, even if the command fails. A successful create job also registers and selects its new project. Use local_project_list and local_project_select to return to another registered project. Never put a project path in directory; that is only the deploy build output. Cloud chat fills the current team if omitted. For a prepared action, pass planId alone to retrieve its exact command and project. Then call request_local_project_command with planId for approval. Local CLI settings can still disable execution.",inputSchema:{type:"object",properties:{operation:{type:"string",enum:["create","install","add_package","build","dev","deploy"]},name:{type:"string"},template:{type:"string",enum:xf},parent:{type:"string",description:"Existing absolute folder in which to create the new project. Its name may contain spaces or parentheses; the new child folder uses name."},destination:{type:"string",description:"Full absolute path to the new project folder; its last segment must equal name. Use parent instead when the user supplies an existing containing folder."},project:{type:"string",description:"Absolute local project path. Use the path returned by a completed create job for a new project; omit for the connected web project. A different path requires fresh approval."},packages:{type:"array",items:{type:"string"}},dev:{type:"boolean"},directory:{type:"string"},team:{type:"string",description:"Target Needle Cloud team ID for deploy. Use the org_... identifier, which Cloud data may call orgId. In Cloud chat, omit this to use the current team."},planId:{type:"string"}},required:[],additionalProperties:!1}},async(t,n)=>{if(null==n||!n.chatId)throw new Error("A Cloud chat is required to plan an AI project command.");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Project command arguments must be an object.");return e(t.planId?Uf.getPlan(t.planId,n.chatId):Uf.plan(t,n.chatId))},{source:"cli"},()=>{}),Of({name:"local_project_start",description:"Internal Cloud approval handoff for a previously planned project command. A model tool call cannot grant approval.",inputSchema:{type:"object",properties:{planId:{type:"string"}},required:["planId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.planId)throw new Error("A project plan ID is required.");if(null==n||!n.commandGrant||n.chatId!==n.commandGrant.chatId||t.planId!==n.commandGrant.planId)throw new Error("Exact Cloud approval is required for this project command.");if(hf())throw new Error("AI project commands are disabled in local Needle CLI settings.");return e(await Uf.start(t.planId,n.commandGrant))},{source:"cli"},()=>{}),Of({name:"local_project_status",description:"Read the status and bounded output of a local project command job in this chat. Poll this after local_project_start; the job may take several minutes.",inputSchema:{type:"object",properties:{jobId:{type:"string"}},required:["jobId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.jobId)throw new Error("A project job ID is required.");if(null==n||!n.chatId)throw new Error("A Cloud chat is required to inspect this project job.");return e(Uf.status(t.jobId,n.chatId))},{source:"cli"},()=>{}),Of({name:"local_project_cancel",description:"Cancel a running local project command job in this chat.",inputSchema:{type:"object",properties:{jobId:{type:"string"}},required:["jobId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.jobId)throw new Error("A project job ID is required.");if(null==n||!n.chatId)throw new Error("A Cloud chat is required to cancel this project job.");return e(await Uf.cancel(t.jobId,n.chatId))},{source:"cli"},()=>{})}(),Of(jp.schema,async e=>{const t=await jp.execute(e);return"error"in t?{content:[{type:"text",text:t.error}]}:{content:[{type:"text",text:t.content}]}},{source:"cli"},()=>{}),Of({name:"local_files_stat",description:'Check one exact relative path in the connected local web project and read its SHA-256 hash and size. This does not search by basename or recurse: exists=false only means that exact path was not found. First locate a nested file with local_files_list(path="src", recursive=true), then pass the full relative path such as src/scripts/MyComponent.ts. Use the returned hash as expectedSha256 before replacing or deleting that file.',inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1}},async e=>({content:[{type:"text",text:JSON.stringify(Nf.stat(e.path))}]}),{source:"cli"},()=>{}),Of({name:"local_files_write",description:"Create or replace a UTF-8 text file in the approved local web project. For an existing file, first call local_files_stat and pass its SHA-256 hash as expectedSha256. Creating a new file requires create=true. Automatically saves an undo checkpoint. Requires user approval for this project and chat session. A successful write only confirms that bytes were saved; run local_files_check_project with mode=check afterward before saying TypeScript errors are fixed.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"},create:{type:"boolean"},expectedSha256:{type:"string"}},required:["path","content"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.write(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_delete",description:"Delete a file in the approved local web project. First call local_files_stat and pass its SHA-256 hash as expectedSha256. Saves an undo checkpoint and refuses changed files.",inputSchema:{type:"object",properties:{path:{type:"string"},expectedSha256:{type:"string"}},required:["path","expectedSha256"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.delete(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_rename",description:"Rename a file within the approved local web project. First call local_files_stat and pass its SHA-256 hash as expectedSha256. The destination must not exist. Saves an undo checkpoint.",inputSchema:{type:"object",properties:{path:{type:"string"},newPath:{type:"string"},expectedSha256:{type:"string"}},required:["path","newPath","expectedSha256"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.rename(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_undo",description:"Undo one saved AI file edit in the approved local web project. Refuses to overwrite changes made after the edit. The checkpoint remains available for Redo.",inputSchema:{type:"object",properties:{checkpointId:{type:"string"}},required:["checkpointId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.undo(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_redo",description:"Reapply one previously undone AI file edit from its checkpoint. Refuses to overwrite changes made after Undo. Requires active file-edit approval.",inputSchema:{type:"object",properties:{checkpointId:{type:"string"}},required:["checkpointId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.redo(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_undo_turn",description:"Undo all AI file edits from one turn in reverse order. Use a turnId from local_files_list_changes. Checks every file for conflicts before changing anything; refuses changed files. Older checkpoints without turn ordering must be undone individually.",inputSchema:{type:"object",properties:{turnId:{type:"string"}},required:["turnId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.undoTurn(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_list_changes",description:"List recent undo checkpoints for this chat and connected local web project. Requires active user approval. Returns filenames and checkpoint IDs, not file contents.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.list(Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_check_project",description:"Check the connected local web project for TypeScript errors without emitting files or applying fixes. Default mode check runs its installed compiler (10 second limit) and returns up to 5 short diagnostics. Use mode results with file/code filters and offset to browse the latest check without rerunning. Use mode error with an index for details; omit index for the last matching error. Results are timestamped snapshots, retained until another check or project change, or CLI exit. Local AI writes and changes to tracked local project files mark saved results stale; dependency files inside node_modules are excluded from the change scan. Retains at most 100 diagnostics. Reports current errors, not whether they predate edits. Not a linter or Unity/Blender compiler.",inputSchema:{type:"object",properties:{mode:{type:"string",enum:["check","results","error"],description:"Run a new check, browse cached results, or inspect one cached error."},file:{type:"string",maxLength:250,description:"Filter diagnostic filenames by case-insensitive substring; does not select a project or restrict compiler inputs."},code:{type:"string",maxLength:250,description:"Exact diagnostic code, e.g. TS2322."},offset:{type:"integer",minimum:0,description:"Offset within filtered results; 5 errors per page."},index:{type:"integer",minimum:0,description:"Diagnostic index from the latest check for mode error; defaults to the last matching error."}},additionalProperties:!1,required:[]}},async e=>{const t=await Af(e);return{content:[{type:"text",text:JSON.stringify(t)}],isError:"error"===t.status||"unavailable"===t.status}},{source:"cli"},()=>{}),null!=e&&e.logToolCount&&mu(`[MCP] registered ${jm.length} built-in tools: ${jm.map(e=>e.name).join(", ")}`)}function Ff(){return hm()}function Df(e,t){const n=_(t,e),o=_(t),i=j(o,n);return k(i)||".."===i||i.startsWith(".."+E)?null:Wm(o,n,{allowMissing:!0}).path}function qf(){const e=Ff();if(!e)return[];const t=[];return e.project_location&&t.push(_(e.project_location)),e.web_location&&t.push(_(e.web_location)),t}function Bf(e){const t=qf();for(const n of t){const t=Df(e,n);if(t&&l(t))return{resolved:t,root:n}}for(const n of t){const t=Df(e,n);if(t)return{resolved:t,root:n}}const n=_(e);for(const e of t)if(n.startsWith(e+E)||n===e)return{resolved:n,root:e};return null}function Mf(e,t){if(0===t.length||null==e)return e;const[n,...o]=t;if("*"!==n)return Mf(e[/^\d+$/.test(n)?Number(n):n],o);if(Array.isArray(e)){const t=e.map(e=>Mf(e,o)).filter(e=>void 0!==e);return t.length>0?t:void 0}if("object"==typeof e){const t={};for(const n of Object.keys(e)){const i=Mf(e[n],o);void 0!==i&&(t[n]=i)}return Object.keys(t).length>0?t:void 0}}function Wf(e,t,n,o,i){if(i>10)return[];const r=[],a=d(e,{withFileTypes:!0}),s="node_modules"===(e.split("/").pop()||e.split("\\").pop()||"");for(const c of a){if(s){if(".needle"!==c.name&&".vite"!==c.name)continue}else{if("Library"===c.name)continue;if(c.name.startsWith(".")||"node_modules"===c.name){if(!n)continue;if(c.name.startsWith("."))continue}}const a=S(e,c.name);if(!Bm(j(t,a))&&!c.isSymbolicLink())if(Wm(t,a),c.isDirectory())n&&r.push(...Wf(a,t,!0,o,i+1));else{if(o&&!o.split("|").map(e=>(e=e.trim()).startsWith(".")&&!e.startsWith("*.")?"*"+e:e).filter(Boolean).some(e=>Ze(c.name,e,{nocase:!0})))continue;r.push(a)}}return r}process.once("exit",()=>Uf.dispose());const Gf="cli-installation-id",Hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Jf="2025-06-18";function Vf(e){return{jsonrpc:"2.0",id:e,result:{protocolVersion:Jf,capabilities:{tools:{listChanged:!0}},serverInfo:Kf}}}const Kf={name:"Needle Cloud MCP",version:"1.0.0"};function Yf(e){if(null!==e&&"object"==typeof e&&"name"in e&&"version"in e&&"string"==typeof e.name&&"string"==typeof e.version&&e.name.trim()&&e.version.trim())return{name:e.name,version:e.version}}function Zf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}let Xf=!1;const Qf=We(),eh=new Map,th=new Map;let nh=0;function oh(){const e=[];for(const[t,{connectedAt:n,userAgent:o}]of th)e.push({id:t,connectedAt:n,userAgent:o});return e}function ih(e,t,n,o){if((t.headers.accept||"").includes("text/event-stream")){var i,r;n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id"),n.flushHeaders(),n.write(": connected\n\n");const a=t.headers["mcp-session-id"],s=null!=(i=null!=(r=null!=o?o:"string"==typeof a?eh.get(a):void 0)?r:t.headers["user-agent"])?i:"",c=()=>{clearInterval(l),th.delete(e)&&(console.log(`[MCP] SSE client disconnected (ID: ${e}): ${s}`),mu(`MCP SSE client disconnected (ID: ${e}): ${s}`))},l=setInterval(()=>{try{n.write(": keepalive\n\n")}catch(t){console.error(`[MCP] SSE heartbeat failed (${e}):`,t),c(),n.destroy()}},15e3);return l.unref(),n.once("close",c),n.once("error",t=>{console.error(`[MCP] SSE stream failed (${e}):`,t),c()}),th.set(e,{id:e,client:n,connectedAt:Date.now(),userAgent:s,dispose:c}),console.log(`[MCP] SSE client connected (ID: ${e}) ${s}. Total clients: ${th.size}`),mu(`MCP SSE client connected (ID: ${e}) ${s}. Total clients: ${th.size}`),!0}return!1}function rh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}async function ah(e=ce(oe(),".needle")){let t,n;try{t=await K(ce(e,"local-server-token"),"utf8")}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;throw new Error("Cannot read local Needle server credentials. Check the credential file permissions.")}try{n=JSON.parse(t)}catch{throw new Error("Invalid local Needle server credentials. Restart the local server to repair them.")}if(null===n||"object"!=typeof n||!("token"in n)||"string"!=typeof n.token||!/^[\x21-\x7e]+$/.test(n.token))throw new Error("Invalid local Needle server credentials. Restart the local server to repair them.");return n.token}async function sh(){const e=await ah();try{const t=await fetch(`${nd}/mcp`,{method:"POST",headers:{...e?{Authorization:`Bearer ${e}`}:{},"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"needle-startup-probe",method:"ping"}),signal:AbortSignal.timeout(1e3),redirect:"error"});if(!t.ok)return!1;const n=await t.json();return null!==n&&"object"==typeof n&&"jsonrpc"in n&&"2.0"===n.jsonrpc&&"id"in n&&"needle-startup-probe"===n.id&&"result"in n}catch(e){if(e instanceof TypeError||e instanceof Error&&["TimeoutError","AbortError"].includes(e.name))return!1;throw e}}async function ch(e,t=process.argv[1]){await new Promise((n,o)=>{const i=Ye(process.execPath,[t,"start","--integration","mcp","--silent"],{detached:!0,windowsHide:!0,stdio:"ignore",env:process.env});i.once("error",t=>{e(`MCP local server launch failed: ${t.message}`),o(t)}),i.once("spawn",()=>{i.unref(),n(void 0)}),i.once("exit",(t,n)=>{0!==t&&e(`MCP local server process exited (${null!=n?n:t}); see the CLI log for details.`)})})}Qf.get("/mcp",async(e,t)=>{if(ih(nh++,e,t))return;const n=function(e){const t=[...jm].sort((e,t)=>e.name.localeCompare(t.name)),n=t.map(e=>`\n <div class="tool">\n <span class="tool-name">${Zf(e.name)}</span>\n <span class="tool-desc">${Zf(function(e){const t=e.indexOf("\n");return-1===t?e:e.slice(0,t)}(e.description))}</span>\n </div>`).join("\n");return`<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>Needle MCP Server</title>\n <style>\n * { box-sizing: border-box; }\n body {\n background: #f0f4ef;\n font-family: system-ui, -apple-system, sans-serif;\n line-height: 1.6;\n padding: 20px 24px;\n max-width: 960px;\n margin: 0 auto;\n color: #1a1a1a;\n }\n header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n }\n h2 {\n margin-top: 1.2em;\n margin-bottom: 0.4em;\n }\n a { color: inherit; }\n img.logo {\n height: 2em;\n width: auto;\n }\n .badge {\n font-size: 0.75em;\n background: #d0d4cf;\n padding: 2px 8px;\n border-radius: 10px;\n vertical-align: middle;\n font-weight: normal;\n }\n .tools-info {\n color: #555;\n font-size: 0.9rem;\n margin-top: 0;\n margin-bottom: 10px;\n }\n\n /* Tool items */\n .tool {\n background: #fff;\n border: 1px solid #d8dcd7;\n border-radius: 6px;\n margin-bottom: 6px;\n padding: 10px 14px;\n display: flex;\n align-items: baseline;\n gap: 10px;\n }\n .tool-name {\n font-weight: 600;\n white-space: nowrap;\n }\n .tool-desc {\n color: #555;\n font-size: 0.9rem;\n }\n</style>\n</head>\n<body>\n <header>\n <img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" />\n <strong>Needle MCP Server</strong>\n </header>\n\n <p>The Needle MCP server is alive and running.</p>\n\n <h2>Usage</h2>\n <p><a href="https://fwd.needle.tools/mcp">Open Documentation</a></p>\n\n <h2>Available Tools <span class="badge">${t.length}</span></h2>\n <p class="tools-info">These tools are available to AI agents connected via the Model Context Protocol (MCP).</p>\n ${n}\n</body>\n</html>`}();t.status(200).header("Content-Type","text/html; charset=utf-8").send(n)}),Qf.post("/mcp",async(e,t)=>{const n=e.headers.accept||"",o=e.headers["user-agent"]||"",{method:i,id:r}=e.body;console.log(`[MCP] Received request from ${o} (${i}) (ID: ${r})`),t.setHeader("Content-Type","application/json"),t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Mcp-Session-Id"),t.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id");try{if("initialize"===i&&n.includes("text/event-stream")){var a;const n=nh++,o=Yf(null==(a=e.body.params)?void 0:a.clientInfo);if(ih(n,e,t,o?`${o.name}/${o.version}`:void 0)){Xf=!0;const e=Vf(null!=r?r:0);return void t.write(`data: ${JSON.stringify(e)}\n\n`)}}const l=await async function(e,t){const{method:n,params:o,id:i}=e;if("initialize"===n)return Vf(null!=i?i:0);if("ping"===n)return{jsonrpc:"2.0",id:i,result:{}};if("notifications/initialized"===n||"notifications/cancelled"===n)return null;if("tools/list"===n){try{zf()}catch{}return{jsonrpc:"2.0",id:i,result:{tools:jm}}}if("tools/call"===n){const e=null==o?void 0:o.name;try{zf()}catch{}try{return{jsonrpc:"2.0",id:i,result:await Om(e,(null==o?void 0:o.arguments)||{})}}catch(e){return{jsonrpc:"2.0",id:i,error:{code:-32603,message:`Tool execution failed: ${e.message}`}}}}return{jsonrpc:"2.0",id:null!=i?i:null,error:{code:-32601,message:`Method '${n}' not found`}}}(e.body);if("initialize"===i){var s;Xf=!0;const n=Se(),i=Yf(null==(s=e.body.params)?void 0:s.clientInfo);eh.set(n,i?`${i.name}/${i.version}`:void 0),t.setHeader("Mcp-Session-Id",n),console.log(`[MCP] New session created: ${n} for ${o}`),mu(`MCP New session: ${n} for ${o}`)}if(null===l)return t.status(204).end();if(mu(`MCP Request: ${i}`),"tools/list"===i){var c;const e=(null==(c=l.result)||null==(c=c.tools)?void 0:c.map(e=>e.name))||[];console.log(`[MCP] Sending tools/list: ${e.length} tools [${e.join(", ")}]`)}else{const e=JSON.stringify(l);console.log(`[MCP] Sending response for ${i}:`,e.length>500?e.substring(0,500)+" [...]":e)}t.json(l)}catch(e){console.error("[MCP] Error processing request:",e);const n={jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:"development"===process.env.NODE_ENV?e.stack:void 0},id:r||null};t.json(n)}}),Qf.options("/mcp",(e,t)=>{t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS, DELETE"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Mcp-Session-Id"),t.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id"),t.status(204).end()});let lh=!1;function ph(e,t={}){lh&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n")}var uh={__proto__:null,sendStdioNotification:ph,startStdio:function(){lh=!0,console.log=console.info=console.debug=console.error.bind(console);const e=e=>{console.error(e),mu(e)},t=function({endpoint:e,ensureServer:t,notify:n,log:o,getToken:i,retryMs:r=250,streamTimeoutMs:a=45e3}){const s=new AbortController;let c,l,p,u,d=!1,m=!1,f={name:"Needle stdio bridge",version:"1.0.0"};const h=async()=>i?{Authorization:`Bearer ${await i()}`}:{},g=()=>`${encodeURIComponent(f.name)}/${encodeURIComponent(f.version)}`;function v(e){d!==e&&(d=e,m&&n("notifications/tools/list_changed"))}async function b(t){s.signal.throwIfAborted();const n=new AbortController,o=()=>n.abort();s.signal.addEventListener("abort",o,{once:!0});const i=setTimeout(o,"tools/call"===t.method?35e3:5e3);try{var r,a;const o=await h(),i=await fetch(e,{method:"POST",headers:{...o,"User-Agent":g(),"Content-Type":"application/json",Accept:"application/json","MCP-Protocol-Version":Jf,...u?{"Mcp-Session-Id":u}:{}},body:JSON.stringify(t),signal:n.signal,redirect:"error"});if(!i.ok)throw new Error(`MCP server returned HTTP ${i.status}`);if(204===i.status)return null;const s=await i.json();if(!rh(s)||"2.0"!==s.jsonrpc||s.id!==t.id||!rh(s.result)&&!rh(s.error))throw new Error("Invalid response from local MCP server");if(rh(s.error)){var c;if("number"!=typeof s.error.code||"string"!=typeof s.error.message)throw new Error("Invalid MCP error response");return{jsonrpc:"2.0",id:null!=(c=t.id)?c:null,error:{code:s.error.code,message:s.error.message}}}return"initialize"===t.method&&(u=null!=(r=i.headers.get("Mcp-Session-Id"))?r:void 0),{jsonrpc:"2.0",id:null!=(a=t.id)?a:null,result:s.result}}finally{clearTimeout(i),s.signal.removeEventListener("abort",o)}}return{start:()=>(l||(l=new Promise(e=>{p=e}),c=async function(){let i=r;for(;!s.signal.aborted;){let d;const y=new AbortController,x=()=>y.abort();let w;s.signal.addEventListener("abort",x,{once:!0});const _=(e,t=!0)=>{clearTimeout(w),w=setTimeout(()=>{t?S():y.abort(new Error("MCP notification stream connection timed out"))},e)},S=async()=>{try{var e,t;const n=await b({jsonrpc:"2.0",id:"needle-bridge-liveness",method:"ping"});if(null==n||!n.result||n.error)throw new Error(null!=(e=null==n||null==(t=n.error)?void 0:t.message)?e:"Invalid MCP ping response");s.signal.aborted||y.signal.aborted||_(a)}catch(e){s.signal.aborted||y.signal.aborted||y.abort(e)}};try{var c;await t(s.signal);const o=await b({jsonrpc:"2.0",id:"needle-bridge-initialize",method:"initialize",params:{protocolVersion:Jf,capabilities:{},clientInfo:f}});if(null!=o&&o.error)throw new Error(o.error.message);await b({jsonrpc:"2.0",method:"notifications/initialized"}),_(5e3,!1);const x=await h(),w=await fetch(e,{headers:{...x,"User-Agent":g(),Accept:"text/event-stream","MCP-Protocol-Version":Jf,...u?{"Mcp-Session-Id":u}:{}},signal:y.signal,redirect:"error"});var l;if(!w.ok||null==(c=w.headers.get("content-type"))||!c.includes("text/event-stream")||!w.body)throw await(null==(l=w.body)?void 0:l.cancel()),new Error(`MCP notification stream unavailable (HTTP ${w.status})`);_(a),d=w.body.getReader(),v(!0),null==p||p(),i=r;const S=new TextDecoder;let j="";for(;!s.signal.aborted;){const{value:e,done:t}=await d.read();if(t)throw new Error("MCP notification stream closed");let o;for(_(a),j+=S.decode(e,{stream:!0});o=/\r?\n\r?\n/.exec(j);){const e=j.slice(0,o.index);j=j.slice(o.index+o[0].length);const t=e.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).replace(/^ /,"")).join("\n");if(!t)continue;const i=JSON.parse(t);rh(i)&&"2.0"===i.jsonrpc&&"notifications/tools/list_changed"===i.method&&m&&n("notifications/tools/list_changed")}if(j.length>1048576)throw new Error("MCP notification exceeds size limit")}}catch(e){s.signal.aborted||(o(`MCP bridge disconnected: ${e instanceof Error?e.message:String(e)}; retrying.`),v(!1))}finally{if(clearTimeout(w),s.signal.removeEventListener("abort",x),d){if(!y.signal.aborted)try{await d.cancel()}catch(e){s.signal.aborted||o(`MCP stream cleanup failed: ${String(e)}`)}d.releaseLock()}u=void 0,null==p||p()}if(!s.signal.aborted){try{await Qe(i,void 0,{signal:s.signal})}catch(e){if(!s.signal.aborted)throw e}i=Math.min(2*i,1e4)}}}()),l),async stop(){s.abort(),await c},async handle(e){var t,i;if("initialize"===e.method)return f=null!=(t=Yf(null==(i=e.params)?void 0:i.clientInfo))?t:f,null;if("notifications/initialized"===e.method)return m=!0,d&&n("notifications/tools/list_changed"),null;if(void 0===e.id)return null;if(!d)return"tools/list"===e.method?{jsonrpc:"2.0",id:e.id,result:{tools:[]}}:{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"The local Needle server is unavailable. Reconnecting; try again shortly."}};try{return await b(e)}catch(t){const n=t instanceof Error?t.message:String(t);return o(`MCP bridge ${e.method} failed: ${n}`),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:`Local Needle server request failed: ${n}`}}}}}}({endpoint:`${nd}/mcp`,ensureServer:t=>async function(e={}){const{signal:t,lockPath:n=ce(oe(),".needle","mcp-server-start.lock"),probe:o=sh,log:i=(e=>console.error(e)),launch:r=(()=>ch(i)),timeoutMs:a=2e4,pollMs:s=100}=e;if(null==t||t.throwIfAborted(),await o())return;await X(ue(n),{recursive:!0});const c=Date.now()+a;let l;try{for(;Date.now()<c;){if(null==t||t.throwIfAborted(),await o())return;if(!l){try{l=await Q(n,"wx",384)}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e;try{const e=await ee(n);Date.now()-e.mtimeMs>12e4&&(i("Removing an expired MCP server startup lock."),await te(n))}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e}}if(l){if(await o())return;i("Starting the shared Needle local server."),await r()}}await Qe(s,void 0,{signal:t})}throw new Error("The local Needle server did not become ready in time. See the CLI log for startup errors.")}finally{l&&(await l.close(),await te(n))}}({signal:t,log:e}),notify:ph,log:e,getToken:()=>async function(e){const t=await ah(void 0);if(void 0===t)throw new Error("Local Needle server credentials are missing. Restart the local server to create them.");return t}()}),n=qe({input:process.stdin,terminal:!1}),o=e=>{lh&&process.stdout.write(JSON.stringify(e)+"\n")};n.on("line",i=>{(async function(n){if(!n.trim())return;let i;try{i=JSON.parse(n)}catch{return void o({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}if(!rh(r=i)||"2.0"!==r.jsonrpc||"string"!=typeof r.method||null!=r.id&&"string"!=typeof r.id&&"number"!=typeof r.id||void 0!==r.params&&!rh(r.params))return void o({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Invalid request"}});var r,a;if("initialize"===i.method)return o(Vf(null!=(a=i.id)?a:0)),await t.handle(i),void t.start().catch(t=>e(`MCP bridge startup failed: ${String(t)}`));if("ping"===i.method)return void(void 0!==i.id&&o({jsonrpc:"2.0",id:i.id,result:{}}));const s=await t.handle(i);s&&o(s)})(i).catch(t=>{e(`MCP stdio request failed: ${String(t)}`),process.exitCode=1,n.close()})}),n.once("close",()=>{lh=!1,t.stop().then(()=>{var e;return process.exit(null!=(e=process.exitCode)?e:0)},t=>{e(`MCP bridge shutdown failed: ${String(t)}`),process.exit(1)})})}};let dh=null;function mh(){dh&&clearTimeout(dh),dh=setTimeout(()=>{!function(e,t={}){if(0===th.size)return;const n=`data: ${JSON.stringify({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:t})}\n\n`;for(const[e,{client:t,dispose:o}]of th)try{t.write(n)}catch(n){console.error(`[MCP] Error sending notification to client (${e}):`,n),o(),t.destroy()}}(),ph("notifications/tools/list_changed"),Ih(),dh=null},10)}const fh=function({send:e,register:t,clear:n,onError:o}){const r=new Map,a=new Set;let s=null,c=null,l=!1;const p=()=>{l=!1,s=null,c&&clearTimeout(c),c=null,a.size&&n(),a.clear();for(const e of r.values())clearTimeout(e.timer),e.reject(new Error("Needle Cloud disconnected."));r.clear()},u=(t,n)=>new Promise((o,a)=>{if(!l)return void a(new Error("Needle Cloud disconnected."));if(r.size>=4)return void a(new Error("Too many concurrent cloud tool requests."));const s=i(),c=setTimeout(()=>{r.delete(s),a(new Error("Cloud tool request timed out."))},3e4);r.set(s,{resolve:o,reject:a,timer:c});try{e({type:"cloud_tool_call",requestId:s,name:t,args:n})}catch(e){clearTimeout(c),r.delete(s),a(e instanceof Error?e:new Error(String(e)))}});return{connect(){p(),l=!0,s=i(),c=setTimeout(()=>{s=null,o("Cloud tool discovery timed out. Update the Cloud API if it does not support MCP tools.")},15e3);try{e({type:"cloud_tools_list",requestId:s})}catch(e){p(),o(e instanceof Error?e.message:String(e))}},disconnect:p,isCloudTool:e=>a.has(e),receive(e){if(!e||"object"!=typeof e||!("type"in e)||!("requestId"in e)||"string"!=typeof e.requestId)return!1;if("cloud_tools_result"===e.type){if(!l||e.requestId!==s)return!0;if(s=null,c&&clearTimeout(c),c=null,"error"in e&&"string"==typeof e.error)return o(e.error),!0;if(!("tools"in e)||!Array.isArray(e.tools))return o("Invalid cloud tool catalog."),!0;try{for(const n of e.tools){if(!n||"object"!=typeof n||"string"!=typeof n.name||!/^[a-zA-Z0-9_]{1,45}$/.test(n.name)||"string"!=typeof n.description||!n.inputSchema||"object"!=typeof n.inputSchema||Array.isArray(n.inputSchema))throw new Error("Invalid cloud tool schema.");const e=`needle_cloud_${n.name}`;t({name:e,description:n.description,inputSchema:n.inputSchema},e=>u(n.name,e)),a.add(e)}}catch(e){p(),o(e instanceof Error?e.message:String(e))}return!0}if("cloud_tool_result"===e.type){const t=r.get(e.requestId);return!t||(r.delete(e.requestId),clearTimeout(t.timer),"error"in e&&"string"==typeof e.error?t.reject(new Error(e.error)):"result"in e&&"string"==typeof e.result?t.resolve(e.result):t.reject(new Error("Invalid cloud tool result.")),!0)}return!1}}}({send:e=>{if(!xh||xh.readyState!==Ge.OPEN)throw new Error("Needle Cloud disconnected.");xh.send(JSON.stringify(e))},register:(e,t)=>Im(e,t,{source:"cloud"},mh),clear:()=>Tm("cloud",mh),onError:e=>mu(`[Cloud MCP] ${e}`)}),hh=2e3,gh=6e4,vh=25e3,bh=1e4,yh=i();let xh=null,wh=null,_h=null,Sh=null,jh=hh,kh=!1,Eh=!1;function Th(){xh||(df()?mu("Needle Cloud connection: skipped (remote_ai_tools disabled in settings)"):(kh=!1,wh&&(clearTimeout(wh),wh=null),jh=hh,Ch()))}function $h(e){fh.disconnect(),kh=!0,Oh(),wh&&(clearTimeout(wh),wh=null),xh?(mu(`Needle Cloud connection: closing (reason: ${null!=e?e:"shutdown"})`),xh.close(1e3,null!=e?e:"shutdown"),xh=null):e&&mu(`Needle Cloud connection: disconnect requested (reason: ${e}) — no active connection`)}function Ih(){if(!xh||xh.readyState!==Ge.OPEN)return;try{zf()}catch(e){mu(`Needle Cloud connection: registerServerTools failed: ${e}`)}const e=jm.filter(e=>!fh.isCloudTool(e.name)),t=e.map(e=>e.name);var n;mu(`Needle Cloud connection: sending ${t.length} tools: ${t.join(", ")}`),xh.send(JSON.stringify({type:"tools",tools:(n=e,n.map(e=>{var t;return{name:e.name,description:e.description,inputSchema:e.inputSchema,capability:null!=(t=e.capability)?t:"local"}}))}))}async function Ch(){let e,t,n=await Gd();if(n||(n=function(){const e=Pd("accessToken");if(c.existsSync(e)){const t=c.readFileSync(e,"utf8");if(t){const e=JSON.parse(t),n=null==e?void 0:e["@https://cloud.needle.tools/api"];return null==n?void 0:n.token}}return null}(),n&&mu("Needle Cloud connection: using cached token (refresh failed)")),!n)return Eh||(mu("Needle Cloud connection: skipped (not logged in)"),Eh=!0),void Ah(!0);Eh=!1;try{e=function(e=pf()){C(e,{recursive:!0,mode:448});const t=ce(e,Gf);try{H(t,i(),{flag:"wx",mode:384})}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw e}const n=W(t,"utf8").trim();if(!Hf.test(n))throw new Error("Invalid local CLI installation ID.");return n}()}catch(e){return mu(`Needle Cloud connection: could not read local CLI installation identity: ${e instanceof Error?e.message:String(e)}`),void Ah(!0)}try{t=await async function(e,t={getUser:Hd,getDefaultOrg:Jd,authHeaders:Xd}){var n;const o=await t.getUser();if(null==o||!o.isAuthenticated)return{authToken:e,org:null};const i=await t.getDefaultOrg(o);if(i&&"object"==typeof i)throw new Error(i.error);if(!i)return{authToken:e,org:null};const r=await t.authHeaders(o,i);if("error"in r)throw new Error(r.error);if(!r.authToken)throw new Error("No access token for the default team.");return{authToken:r.authToken,org:null!=(n=r.org)?n:null}}(n)}catch(e){return mu(`Needle Cloud connection: team authentication failed: ${e instanceof Error?e.message:String(e)}`),void Ah()}const o="https://cloud.needle.tools/api".replace(/^http/,"ws")+"/v1/cli/ws?token="+encodeURIComponent(t.authToken)+(t.org?"&org="+encodeURIComponent(t.org):"")+"&instance="+encodeURIComponent(yh)+"&installation="+encodeURIComponent(e);mu("Needle Cloud connection: connecting...");const r=`needle-cloud/${wm()} Node/${process.versions.node}`;xh=new Ge(o,{headers:{"User-Agent":r,Origin:"cli://needle-cloud"}}),xh.on("open",()=>{jh=hh,mu("Needle Cloud connection: established"),Nh(),Ih(),Oh(),_h=setInterval(()=>{xh&&xh.readyState===Ge.OPEN&&(xh.ping(),Sh=setTimeout(()=>{mu("Needle Cloud connection: pong timeout, terminating"),xh&&xh.terminate()},bh))},vh),fh.connect()}),xh.on("pong",()=>{Sh&&(clearTimeout(Sh),Sh=null)}),xh.on("message",e=>{try{const n=JSON.parse(e.toString());if(fh.receive(n))return;var t;"execute_tool"===n.type&&n.requestId&&n.toolName&&async function(e,t,n,o,i,r){mu(function(e,t,n){const o=Object.entries(t).slice(0,12).map(([e,t])=>`${e.slice(0,40)}:${"string"==typeof t?t.length+" chars":typeof t}`);return`Cloud tool request: ${e.slice(0,64)}(${o.join(", ")}) [${n.slice(0,64)}]`}(t,n,e));const a=Date.now();try{var s,c;if(fh.isCloudTool(t))throw new Error("Cloud tools cannot be executed as local tools.");"local_project_action"===t&&Nh();const l=await Om(t,n,{chatId:o,editGrant:i,commandGrant:r});"local_project_select"!==t&&"local_project_start"!==t&&"local_project_status"!==t||Nh(),mu(`Cloud tool result: ${t} → ${null!=(s=null==l||null==(c=l.content)?void 0:c.reduce((e,t)=>{var n;return e+((null==(n=t.text)?void 0:n.length)||0)},0))?s:0} chars in ${Date.now()-a}ms [${e}]`),xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify({type:"tool_result",requestId:e,result:l}))}catch(n){const o=n instanceof Error?n.message:String(n);mu(`Cloud tool error: ${t} → ${o} in ${Date.now()-a}ms [${e}]`),xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify({type:"tool_result",requestId:e,error:o}))}}(n.requestId,n.toolName,null!=(t=n.args)?t:{},n.chatId,n.editGrant,n.commandGrant)}catch{}}),xh.on("close",(e,t)=>{const n=(null==t?void 0:t.toString())||"";mu(`Needle Cloud connection: closed (code=${e}${n?" "+n:""})`),Oh(),fh.disconnect(),xh=null,kh||Ah()}),xh.on("error",e=>{mu(`Needle Cloud connection: error - ${e.message||"connection refused"} (is https://cloud.needle.tools/api reachable?)`)})}function Oh(){_h&&(clearInterval(_h),_h=null),Sh&&(clearTimeout(Sh),Sh=null)}function Ah(e=!1){kh||wh||(e||mu(`Needle Cloud connection: reconnecting in ${jh/1e3}s`),wh=setTimeout(()=>{wh=null,Ch()},jh),jh=Math.min(2*jh,gh))}function Nh(){xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify(function(){var e,t,n;const o=hm();return{type:"presence",editor:null!=(e=null==o?void 0:o.editor)?e:"unknown",project:null!=(t=null==o?void 0:o.project_location)?t:null,scene:null!=(n=null==o?void 0:o.scene_location)?n:null,web_project:null!=o&&o.web_location?le(o.web_location):null,cli_version:wm()}}()))}const Rh=e=>{const t=We();return t.use("/:action",async(t,n,o)=>{const{action:i}=t.params,r=Vd({navigate:e=>{n.redirect(e)}});switch(i){case"sign-in":e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,mu("Sign in..."),await r.clearAllTokens(),Fd();try{await r.signIn(`${nd}/auth-callback`)}catch(e){const t=null==e?void 0:e.cause,o=`Sign-in failed: ${null!=t&&t.code?`${t.code}${t.address?` (${t.address}:${t.port})`:""}`:(null==e?void 0:e.message)||"unknown error"}`;return mu(o),console.error(o),n.status(502).send(o)}break;case"sign-out":{var a,s;const t=await Hd(),n=(null==t||null==(a=t.userInfo)?void 0:a.sub)||(null==t||null==(s=t.claims)?void 0:s.sub),o=null==t?void 0:t.accessToken;mu(`Sign out... (${n})`),n&&o&&await async function(e){return!e.accessToken||import("node-machine-id").then(async t=>{const n=await cm();return im=n,await fetch("https://cloud.needle.tools/api"+vt.account.post_machine,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({action:"logout",machine_id:n,machine_name:lm()})}).catch(e=>{mu(`Failed to validate logout: ${e.message} - Make sure https://cloud.needle.tools/api is reachable`),console.error(`Failed to validate logout: ${e.message} - Make sure https://cloud.needle.tools/api is reachable`)}),!0})}({userId:n,accessToken:o}).catch(e=>{console.error(e),mu(`Failed to validate logout: ${e}`)}),e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,console.log("User signed out"+(n?`: ${n}`:"")),await r.signOut(kd()),Fd();break}case"auth-callback":if(t.url){const o=await r.handleSignInCallback(`${nd}${t.originalUrl}`).catch(e=>({error:e}));if(Fd(),o&&"error"in o){mu(`Error during sign in: ${o.error}`);const e=o.error instanceof Error?o.error.message:String(o.error);n.redirect(nd+"?cancelled&message="+encodeURIComponent(e))}else{var c,l,p,u;const t=await Hd();if(null!=t&&t.isAuthenticated){var d,m;e.invalid_login=!1,e.user_email=(null==(d=t.claims)?void 0:d.email)||(null==(m=t.userInfo)?void 0:m.email)||null,e.logged_in_machine_names=[...rm(t)];const o=await pm(t,{signout:!0});if(!o)return e.invalid_login=!0,e.invalid_login_type="too-many-logins",n.redirect(kd("too-many-logins"));if("object"==typeof o&&"error"in o)return e.invalid_login=!0,e.invalid_login_type="error",e.error=o.error,n.redirect(kd("error"));Fd()}console.log(`User logged in: ${(null==t||null==(c=t.userInfo)?void 0:c.sub)||(null==t||null==(l=t.claims)?void 0:l.sub)}`),mu(`User logged in: ${(null==t||null==(p=t.userInfo)?void 0:p.sub)||(null==t||null==(u=t.claims)?void 0:u.sub)}`),Th(),n.redirect(nd)}}break;default:o()}}),t};function Ph(e,t,n){return!!n||e===Vp||"string"==typeof t&&t===e}function Uh(e){if(!Array.isArray(e))return console.error("Invalid input: paths should be an array of strings."),null;for(const t of e)if(!1!==l(t))try{const e=Lh(t);if(e)return e}catch(e){}}function Lh(e){const t=S(e,".git");if(l(t)){const e=function(e){const t=v(e);if(t.isDirectory())return S(e,"config");if(t.isFile()){const t=u(e,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(t){let n=t[1].trim();k(n)||(n=_(T(e),n));const o=S(n,"config");if(l(o))return o;const i=S(n,"commondir");if(l(i)){let e=u(i,"utf-8").trim();return k(e)||(e=_(n,e)),S(e,"config")}}}return null}(t);if(e&&l(e)){const t=function(e){const t=u(e,"utf-8"),n=/\[remote\s+"(?<name>.+?)"\].+?url\s*=\s*(?<url>.+?)$/gms,o=[];let i;for(;null!==(i=n.exec(t));)if(i.groups){const e=i.groups.name,t=i.groups.url.trim();t.length&&o.push({name:e,url:t})}const r=o.find(e=>"origin"===e.name)||o.find(e=>"upstream"===e.name)||o[0];return r?r.url:null}(e);if(t)return t}}const n=S(e,".plastic");if(l(n)){const e=S(n,"replicas.db");if(l(e)){const t=u(e,"utf-8").split("\n");for(const e of t){const t=e.split("=");if(2===t.length&&"repo"===t[0].trim()){const e=t[1].trim();if(e.length)return e}}}}const o=S(e,"..");return o===e?null:Lh(o)}function zh(e){if("string"!=typeof e)return!1;const t=/^(localhost|127\.0\.0\.1|\[::1\])(?::([0-9]{1,5}))?$/i.exec(e);return!!t&&(void 0===t[2]||Number(t[2])>0&&Number(t[2])<=65535)}const Fh=new Set(["https://cloud.needle.tools","https://needle.tools","https://engine.needle.tools","https://docs.needle.tools","chrome-extension://kjcepmifiddcepiocokclhibpkgcdomk","chrome-extension://jonplpbnhmanoekkgcepnedhghflblmo"]),Dh=new Set(["localhost","127.0.0.1","[::1]","::1"]);function qh(e){if("string"!=typeof e||0===e.length)return!1;if(Fh.has(e))return!0;let t;try{t=new URL(e)}catch{return!1}if("/"!==t.pathname&&""!==t.pathname)return!1;if(""!==t.search||""!==t.hash)return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const n=t.hostname.toLowerCase();return!!Dh.has(n)||"::1"===n}const Bh="[MCP]",Mh=new Array;function Wh(e){return"string"==typeof e&&/^[a-zA-Z0-9_.-]{1,80}$/.test(e)?e:void 0}function Gh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Hh(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>0}async function Jh(){try{return JSON.parse(await K(ce(oe(),".needle","local-server-token"),"utf8"))}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return null;if(e instanceof SyntaxError)throw new Error("The local server record is invalid.");throw e}}function Vh(e){try{return process.kill(e,0),!0}catch(e){if(e instanceof Error&&"code"in e){if("ESRCH"===e.code)return!1;if("EPERM"===e.code)return!0}throw e}}function Kh(e,t){return{api_endpoint:e,version:t,pid:process.pid}}var Yh={__proto__:null,getLocalServerInfo:Kh,getLocalServerStatus:async function(e={}){var t,n,o;const i=null!=(t=e.fetch)?t:globalThis.fetch;let r,a;try{r=await i(`${nd}/api/info`,{signal:AbortSignal.timeout(3e3)})}catch(e){if(e instanceof Error&&Gh(e.cause)&&"ECONNREFUSED"===e.cause.code)return{running:!1,url:nd};throw e}if(!r.ok)throw new Error(`Local server status request failed (HTTP ${r.status}).`);try{a=await r.json()}catch(e){if(e instanceof SyntaxError)throw new Error("Invalid local server info response.");throw e}if(!Gh(a)||"string"!=typeof a.version||!a.version.trim()||"string"!=typeof a.api_endpoint||!a.api_endpoint.trim())throw new Error("Invalid local server info response.");if(void 0!==a.pid&&!Hh(a.pid))throw new Error("Invalid local server PID.");if(Hh(a.pid))return{running:!0,url:nd,version:a.version,pid:a.pid,pidSource:"server"};const s=await(null!=(n=e.readServerRecord)?n:Jh)();return Gh(s)&&s.port===td&&Hh(s.pid)&&(null!=(o=e.isProcessAlive)?o:Vh)(s.pid)?{running:!0,url:nd,version:a.version,pid:s.pid,pidSource:"record"}:{running:!0,url:nd,version:a.version,pid:null,pidSource:"unavailable"}},formatLocalServerStatus:function(e){return e.running?`Needle local server: running\nURL: ${e.url}\nVersion: ${e.version}\nPID: ${null===e.pid?"unavailable":`${e.pid}${"record"===e.pidSource?" (recorded)":""}`}`:`Needle local server: not running\nURL: ${e.url}`}};const Zh="2026-11-05T16:47:37.091Z";var Xh={__proto__:null,BUILD_TIME:Zh};const{json:Qh}=et;function eg(e){const t=null==e?void 0:e.cause;return null!=t&&t.code?`${t.code}${t.address?` (${t.address}:${t.port})`:""}`:null!=t&&t.message?t.message:null!=e&&e.code?e.code:null!=e&&e.message&&"fetch failed"!==e.message?e.message:"connection refused or network unreachable"}async function tg(t={restart:!1}){const n=!0===t.restart,o=await e(nd).catch(e=>({ok:!1})),a="/sign-in",s="/api/authenticated",c="/api/projects",p="/api/content",u={baseUrl:nd,port:td,isHost:!1,auth_endpoints:{"sign-in":`${nd}${a}`,"sign-out":`${nd}/sign-out`,"is-authenticated":`${nd}${s}`}};let d=o.ok;if(d){var m;const x=await e(`${nd}/api/info`).catch(()=>null);if(null!=x&&x.ok){const w=await x.json().catch(()=>null);if(null!=w&&w.api_endpoint&&"https://cloud.needle.tools/api"!==w.api_endpoint){if(!Ph(w.api_endpoint,"https://cloud.needle.tools/api",n))return mu(`Keeping CLI server for ${w.api_endpoint}; https://cloud.needle.tools/api did not request an explicit restart.`),u;mu(`Running server uses different API endpoint (${w.api_endpoint} vs https://cloud.needle.tools/api), restarting...`),t||(t={}),t.restart=!0}}if(!0===(null==(m=t)?void 0:m.restart)){var f;mu("Restarting auth server...");const _=`${nd}/restart`;t.ora&&(t.ora.text="Sending restart request to server");const j=new AbortController;setTimeout(()=>j.abort(),1e4);let k={};try{const T=S(Ie(),".needle","local-server-token"),$=JSON.parse((await import("fs")).readFileSync(T,"utf-8"));$.token&&(k={Authorization:`Bearer ${$.token}`})}catch{}const E=await e(_,{method:"post",signal:j.signal,headers:{...k,"x-needle-client-integration":null!=(f=t.integration)?f:"cli","x-needle-client-version":wm(),"x-needle-client-pid":String(process.pid),"x-needle-api-endpoint":"https://cloud.needle.tools/api",...n?{"x-needle-explicit-restart":"true"}:{}}}).catch(e=>({ok:!1,status:400,error:e}));if(E.ok)return await $l(300),tg({restart:!1,integration:t.integration});409!==E.status&&console.error("Failed to restart server",E.status),mu(`Failed to restart server: ${E.status}`)}}if(!d){process.title="Needle CLI server";const O=await import("express").catch(e=>{throw console.error("Error starting the auth server (express not found)",e),mu("Error starting the auth server"),new Error("Failed to load express module")});if(!O)throw mu("Error loading auth server module"),new Error("Failed to load express module");let A;mu(`Starting Needle CLI server ${wm()} (built ${Zh})... (Using api at https://cloud.needle.tools/api)`,{emptyLineBefore:!0}),u.isHost=!0;let N=null;const R={invalid_login:!1,invalid_login_type:null,user_email:null,logged_in_machine_names:[]};let P=O.default();const U=S(Ie(),".needle"),L=function(e,t){var n;const o=ce(e,"local-server-token"),r=null!=(n=function(e){if(!I(e))return null;try{const t=W(e,"utf-8");if(0===t.length)return null;const n=JSON.parse(t);if(n&&"string"==typeof n.token&&n.token.length>0)return n.token}catch{}return null}(o))?n:i();C(e,{recursive:!0});const a=JSON.stringify({token:r,pid:process.pid,port:t},null,2);if(H(o,a,{encoding:"utf-8",mode:384}),"win32"===process.platform)try{const e=process.env.USERNAME||process.env.USER||"";e&&Je("icacls",[o,"/inheritance:r","/grant:r",`${e}:(F)`],{stdio:"ignore",timeout:5e3})}catch{}return r}(U,td);mu(`Local token written to ${S(U,"local-server-token")}`);const z=function(e,t=5e3){const n=new Map,o=Math.max(1,Math.round(t/1e3));return(i,r)=>{const a=Date.now(),s=n.get(i);if(!s||a-s.lastLog>t){var c;const t=null!=(c=null==s?void 0:s.suppressed)?c:0;e(t>0?`${r} [+${t} similar in last ${o}s]`:r),n.set(i,{lastLog:a,suppressed:0})}else s.suppressed++}}(e=>mu(`Denied: ${e}`),5e3);P.use((y={onDenied:z},(e,t,n)=>{var o;return zh(e.headers.host)?n():(null==y||null==y.onDenied||y.onDenied(`host|${null!=(o=e.headers.host)?o:"missing"}`,"HTTP Host is not a loopback authority"),t.status(403).send("Forbidden: host not allowed"))})),P.use(function(e){const t=null==e?void 0:e.onDenied;return(e,n,o)=>{var i,r;if("OPTIONS"===e.method)return o();const a=null==(i=e.headers)?void 0:i.origin,s=null==(r=e.headers)?void 0:r["sec-fetch-site"];if(void 0!==a){if(qh(a))return o();if(t)try{var c,l,p,u;const n=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown",o=null!=(p=null!=(u=e.path)?u:e.url)?p:"?";t(`origin|${a}|${o}`,`denied origin=${a} path=${o} ua="${n}"`)}catch{}return n.status(403).send("Forbidden: origin not allowed")}var d,m;if(s&&"none"!==s&&"same-origin"!==s&&("GET"!==e.method||"navigate"!==(null==(d=e.headers)?void 0:d["sec-fetch-mode"])||"document"!==(null==(m=e.headers)?void 0:m["sec-fetch-dest"]))){if(t)try{var f,h;const n=null!=(f=null!=(h=e.path)?h:e.url)?f:"?";t(`fetch-site|${s}|${n}`,`denied fetch-site=${s} path=${n}`)}catch{}return n.status(403).send("Forbidden: origin not allowed")}return o()}}({onDenied:z})),P.use(Qh({limit:"10mb"}));const F=new Set(["/","/sign-in","/sign-out","/auth-callback","/api/info","/api/authenticated","/api/public_key","/mcp","/register"]),D="needle_local";P.use((e,t,n)=>{var o,i,r;if("OPTIONS"===e.method)return n();if(F.has(e.path))return n();if(e.path.startsWith("/mcp/"))return n();if(e.path.startsWith("/.well-known/"))return n();const a=null==(o=e.headers)?void 0:o.authorization;if(a){const e=a.split(" ");if(2===e.length&&"Bearer"===e[0]&&e[1]===L)return n()}if((null==(i=e.query)?void 0:i.token)===L)return n();const s=((null==(r=e.headers)?void 0:r.cookie)||"").split(";").map(e=>e.trim()).find(e=>e.startsWith(D+"="));if(s&&s.split("=")[1]===L)return n();try{var c,l;const t=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown";z(`token|${t}|${e.path}`,`path=${e.path} ua="${t}" — no valid token or cookie`)}catch{}return t.status(401).send("Unauthorized: token required")}),P.use(Rh(R)),t.ora?(t.ora.start("Starting MCP server..."),t.ora.succeed(`MCP server available at ${nd}/mcp`)):console.log(`\nMCP server available at ${nd}/mcp .`),P.use(Qf);const q="\n <title>Needle Cloud</title>\n <link rel=\"icon\" href=\"https://cdn.needle.tools/static/branding/favicon.ico\" type=\"image/x-icon\">\n <style>\n body { \n font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\n font-size: 18px;\n padding: 2rem;\n background: #f0f4ef;\n }\n a {\n color: rgb(120, 76, 223);\n }\n .main_panel {\n display: flex;\n flex-direction: column;\n gap: .5rem;\n justify-content: flex-start;\n align-items: center;\n width: min(80ch, 90vw);\n margin: 0 auto;\n\n height: 100%;\n\n & img.logo {\n height: 3rem;\n margin-bottom: 1rem;\n }\n }\n .secondary {\n color: rgba(0, 0, 0, .5);\n }\n .error-details {\n font-size: 12px;\n color: rgba(0, 0, 0, .5);\n }\n .error-details a {\n color: inherit;\n }\n </style>",B=`<div class="main_panel"><img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" title="Needle Logo (${wm()})"/>`,M="</div>";let G="";P.get("/",Qd(),async(e,t)=>{var n,o;if(null!=(n=e.user)&&n.isAuthenticated?t.cookie(D,L,{httpOnly:!0,sameSite:"strict",path:"/"}):t.clearCookie(D,{path:"/"}),t.set({"Content-Type":"text/html; charset=utf-8"}),t.write(q),null!=e.query.cancelled)return t.end("Login cancelled. You can close this window now."),void mu("Login cancelled by user");if(null!=e.query["too-many-logins"]&&R.logged_in_machine_names.length){var i;const e=Kp();let n="<div>";return n+="<strong>You have reached the maximum number of allowed device logins!</strong><br/><br/>",n+=(null==(i=R.logged_in_machine_names)?void 0:i.map(e=>`• ${e}`).join("<br/>"))+"<br/><br/>",n+=`1) Go to <a href="${e}#device-logins" target="_blank">Needle Cloud device logins</a> and logout one of your devices.<br/>\n 2) Then <a href="${a}">sign-in on this machine</a>.<br/><br/>`,n+="</div>",t.status(406),t.end(B+n+M),void mu(`Login failed: Too many logins from different machines: [${R.logged_in_machine_names.join(", ")}]`)}if(null!=e.query.error)return t.status(500),void t.end(`${B}\n <div>\n <strong>An error occurred</strong>: Please make sure <i>https://cloud.needle.tools/api</i> and <i>https://auth.needle.tools</i> are reachable and not blocked by your firewall or network. After that please try to <a href="${a}">sign-in</a> again.\n <br/><span class="error-details">If the issue persists, please contact support and include the log file: <a title="Link to local log file. Please copy this url and open it in your file explorer or terminal" href="file://${pu()}" target="_blank">${pu()}</a></span>\n </div>\n ${M}`);if(null!=(o=e.user)&&o.isAuthenticated){var r;if(!await sm(e.user)){if(R.invalid_login=!0,R.logged_in_machine_names=[...rm(e.user)],Td(),mu("Cleared stored auth data"),"client"in e.user){const t=e.user;await t.client.clearAccessToken(),await t.client.clearAllTokens(),mu("Cleared all tokens")}return t.end(`${B}<div>You have been logged out from this machine. You can close this window now or try to <a href="${a}">sign in</a> again</div>${M}`)}R.invalid_login=!1,t.end(`${B}\n <div>\n Hi ${Zd(e.user)} — you logged in successfully. You can close this window now.\n </div>\n ${M}`);const n=`Logged in successfully as ${Zd(e.user)} (${null==(r=e.user.userInfo)?void 0:r.sub})`;return void(G!==n&&(G=n,mu(G)))}let s=`<span><a href="${a}">Sign in</a> to your Needle account</span>`;"1"===e.query["signed-out"]&&(s=`<span class="secondary">You have been signed out successfully.</span>${s}`),t.write(B+s+M),t.end()}),P.post("/restart",(e,n)=>{var o,i;if(!Ph("https://cloud.needle.tools/api",e.headers["x-needle-api-endpoint"],"true"===e.headers["x-needle-explicit-restart"]))return mu("Rejected restart from a CLI targeting another API endpoint"),void n.status(409).end("A Needle CLI connected to a different environment is already running.");null==(o=A)||o.shutdownRequested("restart",{integration:e.headers["x-needle-client-integration"],version:e.headers["x-needle-client-version"],pid:Number(e.headers["x-needle-client-pid"])}),t.ora&&(t.ora.text="Received restart event. This instance will close"),null==(i=N)||i.close(e=>{e&&console.error(e)}),setTimeout(()=>{process.exit(0)},100),n.status(200).end("Server is restarting"),mu("Server is restarting\n")}),P.get("/api/logs",async(e,t)=>{const n=pu();l(n)?b(n,"utf-8",(e,o)=>{if(e)return console.error(e),void t.status(500).end("Failed to read log file");t.set({"Content-Type":"text/plain; charset=utf-8"});const i=o.split("\n").filter(e=>e.length>0).reverse().join("\n");let r=`--- Needle CLI v${wm()} (built ${Zh}) Log File (newest first) ---\n${n}\n\n`;r+=i,t.status(200).end(r)}):t.status(404).end("Log file not found")}),P.get("/api/info",(e,t)=>{var n;t.json({...Kh("https://cloud.needle.tools/api",wm()),...null==(n=A)?void 0:n.info})}),P.get(s,Qd(),async(e,t)=>{var n;if(!0===R.invalid_login){const e=ng(R);return t.status(e.status).json(e)}R.invalid_login=!1,t.status(null!=(n=e.user)&&n.isAuthenticated?200:400).send()}),P.get("/api/user",Qd(),async(e,t)=>{var n;const o=e.user;if(null==o||!o.isAuthenticated){if(!0===R.invalid_login){const e=ng(R);return t.status(e.status).json(e)}return t.status(401).json({error:"Not authenticated"})}if(R.invalid_login=!1,!await sm(o))return Td(),t.status(403).json({error:"You have been logged out from this machine"});if(null==o||!o.claims)return t.status(400).json({error:"User claims not found"});if(null==o||!o.userInfo)return t.status(400).json({error:"User info not found"});const i=null==o||null==(n=o.claims)?void 0:n.organization_roles,r=null==o?void 0:o.userInfo.custom_data,a={authenticated:o.isAuthenticated,id:o.userInfo.sub,name:Zd(o),email:o.claims.email||o.userInfo.email||"",profile_picture:o.userInfo.picture||"",default_org_id:(null==r?void 0:r.default_org)||"none",orgs:[]},s=["manage","owner","member","developer"];o.userInfo.organization_data&&(a.orgs=o.userInfo.organization_data.map(e=>{var t;const n={id:e.id,name:e.name,roles:(null==i?void 0:i.filter(t=>t.startsWith(e.id)).map(e=>e.split(":")[1]))||[],canWrite:!1};return n.canWrite=null==(t=n.roles)?void 0:t.some(e=>s.includes(e)),n}).sort((e,t)=>e.id===a.default_org_id?-1:t.id===a.default_org_id?1:e.name.localeCompare(t.name))),t.json(a)}),P.get("/api/license",Qd(),async(t,n)=>{var o,i,r;const a=null==(o=t.query.token)?void 0:o.toString(),s=null==(i=t.query.org)?void 0:i.toString();let c=null;if(a)c={authToken:a};else{const e=await Hd();if(!e||!e.isAuthenticated)return n.status(401).json({error:"Not authenticated",code:"not_authenticated"});if(!await sm(e))return Td(),n.status(403).json({error:"Invalid login"});c=await Xd(e,s||null).catch(e=>({status:500,error:e.message}))}if(!c)return n.status(500).json({error:"Failed to fetch licenses (Missing auth)"});if("error"in c)return n.status(c.status).json({error:c.error});const l=bt(c),p=null==(r=t.query.integration)?void 0:r.toLocaleString(),u={...l,"x-needle":"cli","x-needle-integration":null!=p&&p.length?p:"unknown"},d=await e(`https://cloud.needle.tools/api${vt.account.get_licenses}`,{method:"GET",headers:u}).catch(e=>{const t=eg(e);return console.error("Failed to fetch licenses:",t),mu(`Failed to fetch licenses: "${t}" - is https://cloud.needle.tools/api reachable?`),null});if(!d)return n.status(502).json({error:"Failed to fetch licenses: upstream API unreachable"});if(d.ok){const e=await d.json();return void 0===e.can_use_editor&&(e.can_use_editor=!0),n.json(e)}return n.status(d.status).json({error:d.statusText})}),P.get("/api/deployments",Qd(),async(e,t)=>{var n;const o=await Hd();if(!o||!o.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const i=null==(n=e.query.org)?void 0:n.toString(),r=await Xd(o,i).catch(e=>({status:500,error:e.message}));if("error"in r)return t.status(r.status).json({error:r.error});if(i&&!r.org)return t.status(400).json({error:"Organization not found"});const a=await Zu({endpoint:"https://cloud.needle.tools/api",authToken:r.authToken,org:r.org||void 0,limit:20,offset:0,names:void 0}).catch(e=>(console.error("List Deployments error: "+e.message),{status:502,error:"Failed to list deployments: upstream API unreachable"}));if("error"in a)return t.status(a.status).json({error:a.error});for(const e of a.deployments)e.editUrl=`${Yp()}/${e.id}`;const s={...a};return t.json(s)}),P.get(p,Qd(),async(e,t)=>{var n,o,i,r,a,s,c,l;const p=await Hd();if(!p||!p.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const u=(null==(n=e.query.org)?void 0:n.toString())||(null==(o=p.userInfo)||null==(o=o.custom_data)?void 0:o.default_org)||void 0,d=await Xd(p,u).catch(e=>({status:500,error:e.message}));if("error"in d)return t.status(d.status).json({error:d.error});const m={content_type:(null==(i=e.query.content_type)?void 0:i.toString())||void 0,content_format:(null==(r=e.query.content_format)?void 0:r.toString())||void 0,search:(null==(a=e.query.search)?void 0:a.toString())||void 0,tags:(null==(s=e.query.tags)?void 0:s.toString())||void 0,types:(null==(c=e.query.types)?void 0:c.toString())||void 0,trash:"true"===e.query.trash||void 0,collection_id:(null==(l=e.query.collection_id)?void 0:l.toString())||void 0,limit:e.query.limit?parseInt(e.query.limit.toString()):void 0,page:e.query.page?parseInt(e.query.page.toString()):void 0,offset:e.query.offset?parseInt(e.query.offset.toString()):void 0},f=await sp({baseUrl:"https://cloud.needle.tools/api",authToken:d.authToken,org:d.org||void 0},m).catch(e=>(console.error("List content error: "+e.message),{status:502,error:"Failed to list content: upstream API unreachable"}));return"error"in f?t.status(f.status).json({error:f.error}):t.json(f)}),P.get(p+"/:identifier",Qd(),async(e,t)=>{var n,o;const i=await Hd();if(!i||!i.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const r=(null==(n=e.query.org)?void 0:n.toString())||(null==(o=i.userInfo)||null==(o=o.custom_data)?void 0:o.default_org)||void 0,a=await Xd(i,r).catch(e=>({status:500,error:e.message}));if("error"in a)return t.status(a.status).json({error:a.error});const s=await cp({baseUrl:"https://cloud.needle.tools/api",authToken:a.authToken,org:a.org||void 0},e.params.identifier).catch(e=>(console.error("Get content error: "+e.message),{status:502,error:"Failed to get content: upstream API unreachable"}));return"error"in s?t.status(s.status).json({error:s.error}):t.json(s)}),P.get(c,Qd(),async(t,n)=>{const o=await Hd();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i=`https://cloud.needle.tools/api${vt.local_projects.get.user}`,r=await e(i,{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}}).catch(e=>(console.error("Failed to fetch projects:",eg(e)),null));if(!r)return n.status(502).json({error:"Failed to fetch projects: upstream API unreachable"});if(!r.ok)return n.status(r.status).json({error:r.statusText});const a=await r.json().catch(e=>console.error(e));return n.json(a)}),P.get(c+"/:id",Qd(),async(t,n)=>{var o;const i=await Hd();if(!i||!i.isAuthenticated)return n.status(401).json({error:"Not authenticated"});let r=null==(o=t.query.org)?void 0:o.toString();const a=await Xd(i,r).catch(e=>({status:500,error:e.message}));if(!a)return n.status(500).json({error:"Failed to fetch projects"});if("error"in a)return n.status(a.status).json({error:a.error});const s=bt(a),c=`https://cloud.needle.tools/api${vt.local_projects.get.by_id}${encodeURIComponent(t.params.id)}`,l=await e(c,{method:"GET",headers:{...s}}).catch(e=>(console.error("Failed to fetch project:",eg(e)),null));if(!l)return n.status(502).json({error:"Failed to fetch project: upstream API unreachable. Please try again later or contact hi@needle.tools"});if(!l.ok)return n.status(l.status).json({error:l.statusText});const p=await l.json().catch(e=>(console.error(e),null));return p?n.json(p):n.status(500).json({error:"Failed to parse data. Please try again later or contact hi@needle.tools"})}),P.post("/api/projects",Qd(),async(t,n)=>{const o=await Hd();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i="string"==typeof t.body?JSON.parse(t.body):t.body,r={machine_id:await cm(),project_id:i.project_id,project_name:i.project_name,scene_name:i.scene_name,web_project_path:i.web_project_path,editor_name:i.editor_name,editor_version:i.editor_version};if(!r.project_id||!r.project_name)return n.status(400).json({error:"Invalid request"});const a=`https://cloud.needle.tools/api${vt.local_projects.post}`,s=await e(a,{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(r)}).catch(e=>(console.error("Failed to upsert project:",eg(e)),null));return s?s.ok?n.send("OK"):n.status(s.status).json({error:s.statusText}):n.status(502).json({error:"Failed to upsert project: upstream API unreachable"})}),P.get("/api/public_key",Qd(),async(t,n)=>{var o,i;const r=await Hd();if(!r||!r.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const a=null==(o=t.query.org)?void 0:o.toString(),s=await Xd(r,a).catch(e=>({error:e.message,status:500}));if(!s)return n.status(500).json({error:"Failed to fetch public key"});if("error"in s)return n.status(s.status).json({error:s.error});const c={project_id:(null==(i=t.query.project_id)?void 0:i.toString())||void 0,machine_id:await cm()},l=await e(`https://cloud.needle.tools/api${vt.account.public_key}`,{method:"POST",headers:{...bt(s),"Content-Type":"application/json"},body:JSON.stringify(c)}).catch(e=>(console.error("Failed to fetch public key:",eg(e)),null));if(!l)return n.status(502).json({error:"Failed to fetch public key: upstream API unreachable"});if(l.ok){const e=await l.json().catch(console.error);return null!=e&&e.public_key?n.json(e):n.status(500).json({error:"Failed to fetch public key"})}return n.status(l.status).json({error:l.statusText})}),P.get("/api/local_project_id",async(e,t)=>{const n=e.query.paths;if(!n)return t.status(400).json({error:"Missing paths"});let o=[];"string"==typeof n?o=n.split(",").map(e=>e.trim()).filter(e=>e.length>0):Array.isArray(n)&&(o=n.map(e=>e.toString().trim()).filter(e=>e.length>0));const i=Uh(o);return i?t.json({project_id:i}):t.status(404).json({error:"Project ID not found"})}),P.post("/api/project/info",Qd(),async(e,t)=>{(function(e){try{!function(e){var t,n,o,i;const r={last_accessed:Date.now(),editor:null!=(t=e.scene_path)&&t.endsWith(".unity")?"unity":null!=(n=e.scene_path)&&n.endsWith(".blend")?"blender":"unknown",editor_version:e.editor_version,editor_installation_path:e.editor_installation_path,log_location:e.editor_log_path,project_location:e.unity_project_path||e.blender_project_path||e.scene_path,scene_location:e.scene_path,web_location:e.web_project_path,needle_engine_integration_location:e.needle_sourcecode_location},a=bm();let s=ym();const c=s.entries.findIndex(e=>e.project_location===r.project_location),l=null==(o=s.entries[0])?void 0:o.project_location;-1!==c?s.entries[c]=r:s.entries.push(r),s.entries.sort((e,t)=>t.last_accessed-e.last_accessed);let p=0;s.entries=s.entries.filter(e=>"cli"===e.source||++p<=30);const u=null==(i=s.entries[0])?void 0:i.project_location;u&&u!==l&&mu(`Active project changed: ${l||"(none)"} → ${u}`);try{um=s;const e=JSON.stringify(s);h(a,e,"utf-8")}catch(e){console.error("Failed to save project info:",e)}}(e)}catch(e){mu("Error saving project info: "+e)}})("string"==typeof e.body?JSON.parse(e.body):e.body),t.send("OK")});let J=null;const V=new Promise(e=>J=e);let K=!1;if(N=(v=P,tt({maxHeaderSize:131072},v)).listen(td,()=>{null==J||J()}),N.on("error",e=>{if("EADDRINUSE"===(null==e?void 0:e.code))return mu(`License server port ${td} already in use — a server is already running; not starting a second one.`),K=!0,u.isHost=!1,void(null==J||J());console.error("[needle] License server failed to start:",(null==e?void 0:e.message)||e),mu(`License server failed to start: ${(null==e?void 0:e.message)||e}`),process.exit(1)}),function(e,t){e.on("connection",e=>{const n=e.remoteAddress;if(!function(e){if(!e)return!1;const t=e.includes("%")?e.slice(0,e.indexOf("%")):e;return"127.0.0.1"===t||"::1"===t||"::ffff:127.0.0.1"===t}(n)){try{null==t||t(`Local server: rejected non-loopback connection from ${n||"unknown"}`)}catch{}e.destroy()}})}(N,mu),N.on("close",g),process.on("exit",g),process.on("SIGINT",()=>{var e;null==(e=A)||e.shutdownRequested("SIGINT"),g(),process.exit(0)}),await V.catch(e=>{console.error(e),mu(`Error starting the auth server (promise failed): ${e.message}`)}),K)return u;function g(){mu("Cleaning up auth server...")}A=function(e){var t,n;const o=null!=(t=e.proc)?t:process,i=null!=(n=e.log)?n:du,a={instance_id:r(16).toString("hex"),started_at:(new Date).toISOString(),pid:o.pid,parent_pid:o.ppid,version:Wh(e.version),integration:Wh(e.integration)};let s;const c=(e,t={})=>i(`[local-server] ${JSON.stringify({...a,event:e,...t})}`),l=(e,t={})=>{null!=s||(s=e),c("shutdown_requested",{reason:e,requester:{integration:Wh(t.integration),version:Wh(t.version),pid:"number"==typeof t.pid&&Number.isSafeInteger(t.pid)&&t.pid>0?t.pid:void 0}})};return o.on("exit",e=>{var t;return c("exit",{exit_code:e,reason:null!=(t=s)?t:"unexpected_exit"})}),o.on("uncaughtExceptionMonitor",(e,t)=>c("crash",{error_name:Wh(null==e?void 0:e.name),error_code:Wh(e&&"code"in e?e.code:void 0),origin:Wh(t)})),o.on("SIGTERM",()=>{l("SIGTERM"),o.exit(143)}),{info:a,started:()=>c("started"),shutdownRequested:l}}({version:wm(),integration:t.integration}),A.started();const Y=function(e,t){const n=new He({server:e,path:"/mcp/ws",verifyClient:({req:e},t)=>{var n;if(!zh(e.headers.host))return mu(`${Bh} rejected WS upgrade: host not allowed`),void t(!1,403,"Forbidden: host not allowed");const o=null==(n=e.headers)?void 0:n.origin;if(o&&!qh(o))return mu(`${Bh} rejected WS upgrade: disallowed origin ${o}`),void t(!1,403,"Forbidden: origin not allowed");t(!0)}});mu("MCP websocket server created.");let o=0,i=new Map;return n.on("connection",e=>{const t=++o;Mh.push(e),console.log(`${Bh} client connected (#${t})`),mu(`${Bh} client connected (#${t})`),e.on("close",()=>{const n=Mh.indexOf(e);-1!==n&&Mh.splice(n,1);const o=i.get(t);if(o){for(const e of o)$m(e,mh);i.delete(t)}console.log(`${Bh} client disconnected (#${t})`),mu(`${Bh} client disconnected (#${t})`)});const n=new Map;e.on("message",o=>{try{const r=o.toString(),a=JSON.parse(r);switch(a.command){default:console.log(`${Bh} Unknown command: ${a.command}`),mu(`Unknown MCP websocket command received: ${a.command}`);break;case"get_connected_clients":!function(t,n){const o={clients:[...oh()],command:"mcp_server_response",messageId:"messageId"in t?t.messageId:void 0};e.send(JSON.stringify(o))}(a);break;case"register_tools":{const o=a.tools,r=a.source;if("cli"===r||"cloud"===r)throw new Error("The CLI and cloud tool sources are reserved for built-in tools.");r&&Tm(r,mh);const s=r||"unknown";console.log(`${Bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`),mu(`${Bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`);const c=i.get(t)||new Set;i.set(t,c);for(const t of o)Im(t,async o=>{console.log(`Tool ${t.name} executed via WebSocket with args:`,o);const i=`${t.name}-${Date.now()}-${Math.random()}`;return await new Promise((r,a)=>{const s=setTimeout(()=>{n.has(i)&&(console.error(`${Bh} Tool execution timed out for tool: ${t.name}`),n.delete(i),a(new Error(`Tool execution timed out for tool: ${t.name}`)))},3e4);n.set(i,{resolve:e=>{r(e),clearTimeout(s)},reject:a}),e.send(JSON.stringify({command:"execute_tool",toolName:t.name,args:o,requestId:i}))})},{source:r},mh),c.add(t.name);break}case"tool_result":{const e=a.requestId,t=a.result;if(console.log(`${Bh} Received tool result for requestId: ${e}`,t),n.has(e)){const o=n.get(e);null==o||o.resolve(t),n.delete(e)}else console.error(`${Bh} No pending tool execution found for requestId: ${e}`);break}}}catch(e){console.error(`${Bh} Error processing WebSocket message:`,e)}})}),n}(N);zf({logToolCount:!0}),Th();const Z=gf(U,()=>{df()?(mu("Settings changed: remote_ai_tools disabled — closing cloud connection"),$h("remote_ai_tools setting disabled")):(mu("Settings changed: remote_ai_tools enabled — opening cloud connection"),Th())});tm(P,L,()=>{mu("Authenticated stop requested; shutting down the local Needle server."),N&&nm(N,Y,()=>{Z(),$h("stop requested")})},e=>{var t;return null==(t=A)?void 0:t.shutdownRequested("stop",e)}),process.on("exit",()=>{Z(),$h("process exit")})}var v,y;return u}function ng(e){let t="";return t=e.error?e.error:e.logged_in_machine_names.length>0?`You're already authenticated on ${e.logged_in_machine_names.length} other machine(s)${e.user_email?` with ${e.user_email}`:""}. Please logout from other machines first on ${Kp()}. You're currently logged in on: ${e.logged_in_machine_names.join(", ")}`:"An unknown error occured.",{status:403,error:t}}async function og(e={headless:!1,silent:!1,clearAuthData:!1}){return!0===e.clearAuthData&&await Td(),rg("sign-in",{...e})}function ig(e={}){return rg("sign-out",{...e})}function rg(t,n){return new Promise(async(o,i)=>{let r=!1;if("sign-in"==t){const e=await Hd();if(null!=e&&e.isAuthenticated&&e.accessToken)return await pm(e)?(r=!0,n.ora&&(n.ora.text=`Authorized as ${Zd(e)}`),"gotoAccountPage"in n&&!0===n.gotoAccountPage&&(n.ora&&(n.ora.text="Opening account page in the browser"),Zp(Kp()),await new Promise(e=>setTimeout(e,2e3))),o(e)):o(null);if(!0===n.headless)return o(null)}else if("sign-out"==t&&!0===n.headless){r=!0,Td();const t=await tg(),n=await e(t.auth_endpoints["sign-out"],{follow:2});return o(n.ok)}const a=await tg();switch(n.timeout||(n.timeout=6e5),"number"==typeof n.timeout&&n.timeout>0&&setTimeout(()=>{r||(n.ora&&n.ora.fail('Timeout "'+t+'"'),o(null))},n.timeout),t){case"sign-in":const e=a.auth_endpoints["sign-in"];setTimeout(()=>Zp(e),300),n.ora&&(n.ora.text=`Please authenticate in the browser: ${e}`),setTimeout(l,2e3);break;case"sign-out":Td(),Zp(a.auth_endpoints["sign-out"]),setTimeout(l,2e3)}let s=0;const c=10;function l(){e(a.auth_endpoints["is-authenticated"]).then(async e=>{if(200===e.status||400===e.status||403===e.status)switch(t){case"sign-in":if(200===e.status){const e=await Hd();return e&&!await pm(e)?o(null):(r=!0,n.ora&&e&&(n.ora.text="User is authenticated"),o(e))}if(403===e.status){n.ora&&n.ora.fail("Authentication failed");const t=await e.text();if(t.startsWith("{")){const e=JSON.parse(t);if("logged_in_machine_names"in e&&Array.isArray(e.logged_in_machine_names)){const t=e.logged_in_machine_names;$().fail(`You're already authenticated on ${t.length} other machine(s). Please logout from other machines first. You're currently logged in on: ${t.join(", ")}`)}}return o(null)}break;case"sign-out":if(400===e.status)return r=!0,Td(),n.ora&&(n.ora.text="User is signed-out"),o(!0)}else if(s++,s>c)return n.ora?n.ora.fail(`Failed to complete auth flow. Please try again. Make sure that port ${a.port} is not blocked`):n.silent||console.error(`Failed to complete auth flow. Please try again. Make sure that port ${a.port} is not blocked`),o(null);setTimeout(l,1e3)}).catch(e=>{s>=10&&console.debug("Error polling auth status: "+e.message)})}})}globalThis.fetch||(globalThis.fetch=e),globalThis.File||(globalThis.File=t),globalThis.crypto||(globalThis.crypto=n.webcrypto),function(e={}){var t,n,o;const i=null!=(t=e.proc)?t:process,r=null!=(n=e.log)?n:du,a=null!=(o=e.error)?o:e=>console.error(e),s=(e,t)=>{const n=t instanceof Error&&t.message||String(t);try{const o=t instanceof Error&&t.stack?`\n${t.stack}`:"";r(`CLI crashed (${e}): ${n}${o}`)}catch{}try{a(`error: ${n}`)}catch{}try{i.exit(1)}catch{}};i.on("unhandledRejection",e=>s("unhandled rejection",e)),i.on("uncaughtException",e=>s("uncaught exception",e))}();const ag=process.argv.includes("--silent"),sg=JSON.parse(u(new URL("../package.json",import.meta.url),"utf-8")),cg="The access token to use. Use the login command or get a token from https://cloud.needle.tools. You can pass the access token with your command or set the environment variable NEEDLE_CLOUD_TOKEN";async function lg(e,t=null,n=!0){let o,i=null==e?void 0:e.toString();var r;if(i||(Fe.config(),process.env.NEEDLE_CLOUD_TOKEN&&(i=process.env.NEEDLE_CLOUD_TOKEN,null!=(r=i)&&r.length&&console.error("Using NEEDLE_CLOUD_TOKEN token from env"))),""===i||"true"===i){if(!n)throw new Error("--token requires a value in non-interactive mode.");const e=(await import("node:readline")).createInterface({input:process.stdin}),t=10;let i,r="",a=!1;return new Promise(n=>{const s="Paste your https://cloud.needle.tools/team#token access token here:",c=$({text:s,interval:200,spinner:"moon"}).start();process.stdin.setRawMode(!0),process.stdin.on("data",l=>{const p=l.toString();""===p&&process.exit();const u="\n"===p||"\r"===p;if(!u&&"\n"!==p&&"\r"!==p){""===p||"\b"===p?r=r.slice(0,-1):r+=p;const e=r.replace(/./g,"*");c.text=`${s} ${e}`}clearTimeout(i),i=setTimeout(()=>{if(!a&&(u||r.trim().length>t)){process.stdin.setRawMode(!1),e.close(),a=!0;const t=r.trim();if(t.length>0){const e=t.slice(3,-3).replace(/./g,"*");c.succeed("Access token received: "+e)}else c.fail("No access token provided");n({accessToken:t,org_id:o})}},150)})})}if(!i){let e;n&&!await async function(){const e=await Hd();return null==e?void 0:e.isAuthenticated}()&&(e=ag?void 0:$("No access token found. Please sign in to authenticate...").start()),mu("No access token provided, attempting login. Org: "+t);const r=og({headless:!n,ora:e,timeout:12e4}),d=await r;if(d&&!await sm(d)){var a;if(!n)throw new Error("Saved authentication is invalid. Provide --token or NEEDLE_CLOUD_TOKEN.");null==(a=e)||a.fail("You are not logged in from this machine. Please login again."),await ig({headless:!0}),process.exit(1)}else e&&(mu("User logged in via getAccessToken "+(null==d?void 0:d.isAuthenticated)),d?e.succeed("Logged in"):e.fail("Login failed"));if(null!=d&&d.isAuthenticated){var s;if(null==t){const e=await Jd(d);"string"==typeof e&&(t=e)}else t===(null==(s=d.userInfo)?void 0:s.sub)&&(t=null);if(t){var c,l,p;if(o=null==(c=d.userInfo)||null==(c=c.organization_data)||null==(c=c.find(e=>e.id===t))?void 0:c.id,o||(t=null==(l=t.toString())?void 0:l.toLowerCase(),null!=o||(o=null==(p=d.userInfo)||null==(p=p.organization_data)||null==(p=p.find(e=>e.name.toLowerCase()===t))?void 0:p.id)),!o)throw new Error(`ERR: You (${Zd(d)}) are not a member of the team "${t}" or the team does not exist. Please check the team name/id and try again.`);i=await(null==d?void 0:d.client.getOrganizationToken(o)),mu("Getting access token for org "+o+", "+i.substring(0,8)+"...")}else{var u;mu("Getting access token for user "+(null==(u=d.userInfo)?void 0:u.sub)),i=null==d?void 0:d.accessToken}}}if(!i)throw mu("ERR: Missing NEEDLE_CLOUD_TOKEN token. Org: "+o),new Error("Missing authentication. Provide --token, set NEEDLE_CLOUD_TOKEN, or run needle-cloud login.");return{accessToken:i,org_id:o}}function pg(e){return null!=e.org&&console.warn("Warning: --org is deprecated. Use --team instead."),e.team||e.org}const ug=ht.program;async function dg(){const{spawn:e}=await import("node:child_process");e(process.execPath,[process.argv[1],"start","--integration","cli-login"],{stdio:"inherit",env:{...process.env,NEEDLE_CLOUD_TOKEN:process.env.NEEDLE_CLOUD_TOKEN||""}}),await new Promise(e=>setTimeout(e,1e3))}ug.version(sg.version).description("Command-line interface (CLI) for Needle Cloud"),ug.command("version","Print the CLI version").configure({visible:!1}).action(()=>{ag||console.log(`☁ Needle CLI — ${sg.version}, Node ${process.version}`)}),ug.command("start","Starts the Needle Auth server").alias("start-server").configure({visible:!1,strictOptions:!1}).help("Start the local server for Needle Cloud. This is required to authenticate with Needle Cloud and access your account and data.").option("--restart <restart>","Restarts the server",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--integration <integration>","Hint for the process which integration triggered this command",{required:!1,validator:ug.STRING}).action(async({options:e})=>{const t=e.integration,n=ag?void 0:$("Starting Needle License server "+(t?`(from ${t})`:"")).start();tg({ora:n,restart:e.restart,integration:t}).catch(e=>{console.error("Failed to start server:",e),null==n||n.fail("Failed to start server: "+e.message),process.exit(1)}).then(e=>{null!=e&&e.baseUrl&&e.isHost?null==n||n.succeed(`Server started on ${e.baseUrl} (v${wm()}, built ${function(e){if("string"!=typeof Zh||0===Zh.length)return"unknown";const t=new Date(Zh);if(Number.isNaN(t.getTime()))return"unknown";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}()})`):!1===(null==e?void 0:e.isHost)?(t||null==n||n.warn(`Server is running on ${e.baseUrl||e.port}`),process.exit(0)):(null==n||n.fail("Failed to start server"),process.exit(1))})}),ug.command("stop","Stop the local Needle license server").alias("quit").help("Request an authenticated shutdown of the local Needle server, then exit. Does not sign out or stop Unity. Older servers without stop support must be closed manually.").action(async()=>{try{const{stopLocalServer:e}=await Promise.resolve().then(function(){return om}),t=await e({version:wm()});ag||console.log("not-running"===t?"Needle server is not running.":"Needle server shutdown requested."),process.exit(0)}catch(e){console.error(`Could not stop the Needle server: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),ug.command("settings","Show current Needle CLI settings").action(async()=>{const{readSettings:e,KNOWN_SETTINGS:t}=await Promise.resolve().then(function(){return vf}),n=e();for(const[e,o]of Object.entries(t)){const t=n[e],i=void 0!==t?String(t):o.default;console.log(`\n ${"enabled"===i?"[x]":"[ ]"} ${o.displayName}: ${i}${void 0===t?" (default)":""}`),console.log(` ${o.description}`),console.log(` Change: ${o.command}`)}console.log("")}),ug.command("settings remote-ai-tools","Enable or disable cloud AI tool dispatch to this machine").help("When disabled, the CLI does NOT connect to the Needle Cloud AI tool dispatcher (wss://cloud.needle.tools/v1/cli/ws), so cloud-side AI chats cannot invoke tools (file reads, grep, etc.) on this machine. The local /mcp/ws endpoint used by Unity/Blender stays available. Setting persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings remote-ai-tools",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled,i=n();o?(t(i,"remote_ai_tools",null),console.log("Remote AI tools enabled (default)."),mu("Settings: remote_ai_tools set to enabled (default) via CLI command")):(t(i,"remote_ai_tools","disabled"),console.log("Remote AI tools disabled. The cloud AI chat will not be able to dispatch tools to this machine."),mu("Settings: remote_ai_tools set to disabled via CLI command"))})),ug.command("settings local-file-edits","Enable or disable AI file changes on this machine").help("This local setting is checked for every AI write, delete, rename, Undo, and Redo. Cloud chat approval cannot override it. Persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings local-file-edits",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled;t(n(),"local_file_edits",o?null:"disabled"),console.log(`Local AI file edits ${o?"enabled":"disabled"}.`)})),ug.command("settings local-project-commands","Enable or disable approved AI project commands on this machine").help("Allows separately approved AI package installs, project creation, builds, and deploys. Enabled by default; Cloud chat approval cannot override this setting. Persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings local-project-commands",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled;t(n(),"local_project_commands",o?null:"disabled"),console.log(`Local AI project commands ${o?"enabled":"disabled"}.`)})),ug.command("status","Show the local Needle server status and process ID").action(yu("status",async()=>{const{getLocalServerStatus:e,formatLocalServerStatus:t}=await Promise.resolve().then(function(){return Yh});console.log(t(await e()))})),ug.command("mcp","Start MCP server for AI agents (stdio transport)").help('Start the Needle Cloud MCP server using stdio transport.\nReuses or starts the shared local server for Inspector/Unity tools and cloud connections.\nThis is the standard way to connect AI agents (Claude Desktop, Cursor, VS Code, etc.).\n\nAdd to your MCP client config:\n{\n "mcpServers": {\n "needle": {\n "command": "npx",\n "args": ["-y", "needle-cloud", "mcp"]\n }\n }\n}').action(yu("mcp",async()=>{const{startStdio:e}=await Promise.resolve().then(function(){return uh});e()})),ug.command("get-project-id","Gets the project id for a local project").configure({visible:!1,strictOptions:!1}).argument("<paths...>","The path to the local project (web project directory)").action(async({args:e})=>{const t=Uh(e.paths);t?console.log(`Found project ID: "${t}"`):console.log("No project ID found.")}),ug.command("send-logs","Upload CLI, editor, and optimization-pipeline logs to Needle (secrets and sensitive info redacted)").help("Stream the current and previous CLI log, the most recent editor log (Unity or Blender), and the optimization-pipeline log to Needle for support diagnosis. Before upload, tokens, Bearer/Authorization values, UUIDs, home-directory paths, email addresses, Username/User fields, and *_KEY / *_TOKEN / *_SECRET / *_PASSWORD env-var values are redacted (replaced with <redacted:Nch> so the length is preserved for debugging). Returns a reference ID to paste into your bug report. Requires sign-in; the upload is tagged with your Needle account.").option("--crash <crash>","Mark this upload as a crash report (uses the crash-mode daily quota)",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--note <note>","One-line note attached to the upload",{required:!1}).option("--dry-run <dryRun>","Print the redacted payload without uploading",{required:!1,validator:ug.BOOLEAN,default:!1}).action(yu("send-logs",async({options:e})=>{var t,n,o,i,r,a,s;const{runSendLogs:c,HAYSTACK_RESOURCE:l}=await Promise.resolve().then(function(){return _d}),{tryGetFreshAccessTokenForResource:p}=await Promise.resolve().then(function(){return Yd}),{findActiveEditorLog:u}=await import("./cli.send-logs.discovery-552e1cfc.js"),{getLogFilePath:d,getPrevLogsFilePath:m,getPipelineLogFilePath:f}=await Promise.resolve().then(function(){return fu}),{homedir:h,platform:g}=await import("os"),{existsSync:v}=await import("fs"),{BUILD_TIME:b}=await Promise.resolve().then(function(){return Xh}),{getNodeVersion:y,getNpmVersion:x,getArch:w,getOsRelease:_,getCpuCount:S,getTotalMemoryMb:j,getTzOffsetMinutes:k,isCi:E,isTty:T}=await import("./cli.runtime-465aa7a3.js"),I=null!=(t=null!=(n=null==(o=e.crash)||null==o.valueOf?void 0:o.valueOf())?n:e.crash)&&t?"crash":"normal",C=e.note,O=null!=(i=null!=(r=null==(a=e.dryRun)||null==a.valueOf?void 0:a.valueOf())?r:e.dryRun)&&i,A=d(),N=m(),R=f(),P={getAccessToken:()=>p(l),fetch:globalThis.fetch,paths:{cliLogPath:v(A)?A:null,prevLogPath:v(N)?N:null,pipelineLogPath:v(R)?R:null,homeDir:h()},meta:{cli_version:wm(),build_time:b,os:g(),os_release:_(),arch:w(),node_version:y(),npm_version:null!=(s=x())?s:"unknown",cpu_count:S(),total_memory_mb:j(),tz_offset_minutes:k(),is_ci:E(),is_tty:T()},findActiveEditorLog:u,stdout:process.stdout,stderr:process.stderr},U=O?"Building payload (dry-run)":"Uploading logs",L=ag?void 0:$(U).start();P.recoverAuth=async()=>{null==L||L.stop();try{await dg();const e=await og({clearAuthData:!0,silent:ag,ora:void 0});if(null==e||!e.isAuthenticated)return null}catch(e){return mu(`send-logs: auto-recovery login failed: ${e instanceof Error?e.message:e}`),null}finally{null==L||L.start(U)}return await p(l)};const z=await c({mode:I,note:C,dryRun:O},P);z.ok?O?null==L||L.succeed("Dry-run payload printed above. Nothing was uploaded."):z.truncated?(null==L||L.warn(`Uploaded (truncated at server cap). Reference: ${z.refId}`),console.log(`Share ${z.refId} in your bug report.`)):(null==L||L.succeed(`Uploaded. Reference: ${z.refId}`),console.log(`Share ${z.refId} in your bug report.`)):(null==L||L.fail(z.error||"Upload failed"),process.exitCode=1)})),ug.command("login","Login to Needle Cloud").help("Login to Needle Cloud. If you are already logged in, this will refresh the access token.").option("--headless <headless>","The headless process will not open a browser window to login. If the user is not authorized then no auth flow can be started. Use this if you only want to **check** if the user is authenticated",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--clear <clear>","Refresh the access token",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({options:e})=>{const t=_u(e),n=!0===e.nonInteractive||!0===e.headless;n||await dg();const o=!0===e.clear,i=ag?void 0:$("Login").start();await og({headless:n,silent:ag,clearAuthData:o,ora:i}).then(async e=>{"json"===t&&ku({authenticated:!0===(null==e?void 0:e.isAuthenticated)}),null!=e&&e.isAuthenticated?null==i||i.succeed("Successfully logged in as "+Zd(e)):0==n?null!=e&&e.claims||null!=e&&e.userInfo?null==i||i.warn(`You (${Zd(e)}) are not authenticated...`):null==i||i.fail("Login failed"):ag||null==i||i.warn("Not logged in"),await Eu(null!=e&&e.isAuthenticated?0:1)})})),ug.command("logout","Logout of Needle Cloud").help("Logout of Needle Cloud (if you have logged in before).").option("--headless <headless>","Headless will not open a browser window to logout",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({options:e})=>{const t=_u(e),n=!0===e.nonInteractive||!0===e.headless;n||await dg(),await ig({headless:n}).then(async e=>{"json"===t&&ku({success:e}),e?$("Logged out").succeed():$("Logout failed").fail(),await Eu(e?0:1)})})),ug.command("me","Prints your user information").help("Prints basic informaton about the logged in Needle Cloud account (your account)").action(ju(async({options:e})=>{const t=_u(e),n=ag?void 0:$("Query user data").start(),o=await Hd(),i=Boolean((null==o?void 0:o.isAuthenticated)&&await sm(o));if("json"!==t)if(o&&i){const e=o.userInfo||o.claims;var r,a,s;e?(null==n||n.succeed(`You are logged in as ${Zd(o)}`),console.log(`- Name: ${Zd(o)}`),console.log(`- ID: ${e.sub}`),e.email&&console.log(`- Email: ${e.email}`),e.phone_number&&console.log(`- Phone: ${e.phone_number}`),null!=(r=o.userInfo)&&r.organization_data&&console.log(`- Teams [${null==(a=o.userInfo)?void 0:a.organization_data.length}]: ${null==(s=o.userInfo)?void 0:s.organization_data.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.name).join(", ")}`)):null==n||n.fail("Failed to get user data")}else null==n||n.warn("You are not logged in");else{null==n||n.stop();const e=(null==o?void 0:o.userInfo)||(null==o?void 0:o.claims);var c,l;o&&i&&e?ku({authenticated:!0,id:e.sub,name:Zd(o),email:e.email,teams:(null!=(c=null==(l=o.userInfo)?void 0:l.organization_data)?c:[]).map(e=>({id:e.id,name:e.name}))}):(ku({authenticated:!1}),process.exitCode=1)}})),ug.command("get-pro","Start license flow for Needle Engine PRO").configure({visible:!1,strictArgsCount:!1,strictOptions:!1}).option("--team <team>","The team to purchase the license for",{validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{validator:ug.STRING,hidden:!0}).action(yu("get-pro",async({options:e})=>{var t;let n=(null==(t=pg(e))?void 0:t.toString())||null;const o=$().start("Start Needle Engine PRO purchase flow"),i=function(e){e=e||{};const t="undefined"!=typeof window?window.location:null;"current_page"===e.baseUrl&&(e.baseUrl=null==t?void 0:t.href);let n=e.pathname||(null==t?void 0:t.pathname),o=e.baseUrl||(null==t?void 0:t.href);if(!n||!o)return null;const i=new URL(n,o);return t&&(i.search=t.search),e.license||(e.license="needle-engine:pro"),i.searchParams.set("purchase_intent",e.license),e.account_id&&i.searchParams.set("account_id",e.account_id),e.return_url&&i.searchParams.set("return_url",e.return_url),e.checkout_if_possible&&i.searchParams.set("checkout_if_possible","true"),e.show_all_cards&&i.searchParams.set("show_all_cards","true"),e.affiliate_id&&i.searchParams.set("affiliate_id",e.affiliate_id),e.tracking_id&&i.searchParams.set("tracking_id",e.tracking_id),i}({baseUrl:"https://cloud.needle.tools",pathname:n?`/team/${n}`:"/account",account_id:n,license:"needle-engine:pro",return_url:null});if(!i)return void o.fail("Failed to get purchase url - please visit https://cloud.needle.tools");const r=i.toString();o.succeed(`Started Needle Engine PRO purchase flow: opening browser at ${r}`),Zp(r)}));const mg={account:{url:Kp}},fg=`"${Object.keys(mg).join('", "')}"`;ug.command("open",`Open a page in the default browser. Options are: ${fg}`).argument("<page>",`The page to open. Options are: ${fg}`,{validator:ug.STRING}).configure({strictOptions:!1,strictArgsCount:!1,visible:!1}).help("").action(async({args:e,logger:t})=>{const n=e.page.toString(),o=mg[n];o?"url"in o?Zp(o.url()):t.error(`Unknown argument: ${n}`):t.error(`Unknown argument: ${n}. Options are: ${fg}`)}),ug.command("list-deployments","Get a list of deployed websites").configure({visible:!1}).help("").option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--limit <limit>","Limit the number of deployments to show (min: 0, max: 100)",{validator:ug.NUMBER,default:10}).option("--offset <offset>","The offset for deployments (default: 0, min: 0)",{validator:ug.NUMBER,default:0}).option("--format <format>","Legacy output option: cli or json",{validator:ug.STRING,hidden:!0}).option("--name","Filter by one or multiple deployment names (separated by ;)",{validator:ug.STRING}).action(ju(async({options:e,logger:t})=>{var n,o,i,r;const a=_u(e,{legacyFormat:!0}),{accessToken:s,org_id:c}=await lg(e.token,pg(e),!0!==e.nonInteractive),l=(null==(n=e.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",p=Number(null!=(o=e.limit)?o:10),u=Number(null!=(i=e.offset)?i:0),d=(null==(r=e.name)?void 0:r.toString())||void 0;if(p<0)throw new Error("The limit cannot be negative.");if(p>100)throw new Error("The limit cannot exceed 100.");const m=$("Query deployments").start(),f=await Zu({endpoint:l,authToken:s,org:c,limit:p,offset:u,names:null==d?void 0:d.split(";")});if(f&&"error"in f)throw new Error(f.error+" (status: "+f.status+")");if(!f)throw new Error("Failed to query deployments.");if("json"===a)return m.succeed(`Found ${f.deployments.length} deployments`),void ku(f.deployments);f.deployments.length>0?(m.succeed(`Found ${f.deployments.length} deployments`),f.deployments.forEach((e,n)=>{t.info(`${n+p*u}: ${e.name} – ${e.url}`)})):m.warn("No deployments found")}));for(const e of["list","search"]){const t=ug.command(e,"search"===e?"Search content items by name, title or description":"List content items (3d assets, deployments, materials, etc.)");"list"===e?t.alias("list-content"):t.argument("<query>","Search by name, title or description",{validator:ug.STRING}),t.help(("search"===e?"Search":"List")+' content items stored in Needle Cloud.\n\nUse --type to filter by content type (e.g. "material", "3d-asset", "deployment").\nUse --format to filter by output format (e.g. "glb", "textures").\nUse --include-projects to include saved web projects; --type editor-project selects only projects.').option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--include-projects","Include saved web projects (default: uploaded content only)",{validator:ug.BOOLEAN,default:!1}).option("--trash","List deleted items instead of active content",{validator:ug.BOOLEAN,default:!1}).option("--interactive","Override automatic terminal browsing: true or false",{validator:ug.BOOLEAN}).option("--type <type>","Filter by content type (e.g. material, 3d-asset, deployment, editor-project)",{required:!1,validator:ug.STRING}).option("--format <format>","Filter by output format (e.g. glb, textures)",{required:!1,validator:ug.STRING}).option("--search <search>","Search by name, title or description",{required:!1,validator:ug.STRING}).option("--limit <limit>","Max number of items to show (default: 20, max: 100)",{validator:ug.NUMBER,default:20}).option("--offset <offset>","Offset for pagination (default: 0)",{validator:ug.NUMBER,default:0}).option("--output <output>","Output style: cli (default), json",{validator:ug.STRING,default:"cli"}).action(ju(async({args:t,options:n,logger:o})=>{var i,r,a,s,c,l,p;const u="search"===e?String(null!=(i=t.query)?i:"").trim():void 0;if("search"===e&&!u)throw new Error("Search query must not be empty.");if(u&&void 0!==n.search&&n.search.toString()!==u)throw new Error("Conflicting query and --search. Supply one search value.");const d=_u(n),m=Uu(n),f=Number(null!=(r=n.limit)?r:20),h=Number(null!=(a=n.offset)?a:0);if(!Number.isInteger(f)||f<1)throw new Error("--limit must be a positive integer.");if(!Number.isInteger(h)||h<0)throw new Error("--offset must be a nonnegative integer.");const g=null==(s=n.type)?void 0:s.toString(),v=null==(c=n.format)?void 0:c.toString();if(g&&"editor-project"!==g&&!rp.some(e=>e===g))throw new Error("Invalid --type. Use "+[...rp,"editor-project"].join(", ")+".");if(v&&!ap.some(e=>e===v))throw new Error("Invalid --format. Use "+ap.join(", ")+".");const{accessToken:b,org_id:y}=await lg(n.token,pg(n),!0!==n.nonInteractive),x=(null==(l=n.endpoint)?void 0:l.toString())||"https://cloud.needle.tools/api",w=Math.min(f,100),_=g||void 0,S=v||void 0,j=null!=u?u:(null==(p=n.search)?void 0:p.toString())||void 0,k={content_type:_,include_projects:!0===n.includeProjects,trash:!0===n.trash,content_format:S,search:j,limit:w,offset:h},E=$("Querying content...").start();try{const e=await sp({baseUrl:x,authToken:b,org:y},k);if(m)return E.stop(),await Wu({auth:{baseUrl:x,authToken:b,org:y},query:k,initial:e}),void await Eu(0);if("json"===d)return E.succeed(`Found ${e.items.length} of ${e.total} items`),void ku(e.items);0===e.items.length&&(E.warn("No content found"+(_?` (type: ${_})`:"")+(S?` (format: ${S})`:"")),process.exit(0)),E.succeed(`Found ${e.items.length} of ${e.total} items`);const t=e.items.map(e=>{var t;const n=e.title||"(untitled)";return{id:e.identifier,type:e.content_type||"?",formats:null!=(t=e.content_formats)&&t.length?e.content_formats.join(", "):"",name:n.length>20?n.slice(0,17)+"...":n,versions:String(e.version_count||0),date:e.created_at?Il(new Date(e.created_at),new Date,{allowSimple:!0,limitInDays:2}):""}}),n={id:Math.max(2,...t.map(e=>e.id.length)),type:Math.max(4,...t.map(e=>e.type.length)),formats:Math.max(7,...t.map(e=>e.formats.length)),name:Math.max(4,...t.map(e=>e.name.length))},i=ed(` ${"ID".padEnd(n.id)} ${"TYPE".padEnd(n.type)} ${"FORMATS".padEnd(n.formats)} ${"NAME".padEnd(n.name)} ${"#".padStart(3)} AGE`);o.info(i);for(const e of t){const t=Qu(e.type).padEnd(n.type+11),i=(e.formats?e.formats.split(", "):[]).map(e=>Qu(e)).join(", ")+" ".repeat(Math.max(0,n.formats-e.formats.length));o.info(` ${ed(e.id.padEnd(n.id))} ${t} ${i} ${e.name.padEnd(n.name)} ${e.versions.padStart(3)} ${ed(e.date)}`)}e.total>h+w&&o.info(` ... ${e.total-h-w} more (use --offset ${h+w})`),process.exit(0)}catch(e){E.fail(e.message),process.exit(1)}}))}ug.command("delete","Move a content item to the trash").help("Move a content item to the trash. This immediately frees total storage capacity but does not refund monthly usage. The item can be restored for 31 days if enough total storage is available.\n\nUsage:\n needle-cloud delete <identifier>").argument("<identifier>","Content item identifier",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The Needle Cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).action(ju(async({args:e,options:t})=>{var n;const o=_u(t),{accessToken:i,org_id:r}=await lg(t.token,pg(t),!0!==t.nonInteractive),a=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",s=String(e.identifier),c=$(`Deleting content "${s}"...`).start();try{const e=await Yu({identifier:s,endpoint:a,authToken:i,org:r});c.succeed(e.message||`Moved content "${s}" to the trash`),"json"===o&&ku(e)}catch(e){c.fail(e.message),process.exitCode=1}})),ug.command("download","Download a content item by identifier").help('Download files from a content item.\n\nUse --format to select which output format to download (e.g. "glb", "textures").\n\nUsage:\n needle-cloud download <identifier> [directory]\n needle-cloud download abc123 --format glb').argument("<identifier>","Content item identifier",{validator:ug.STRING}).argument("[directory]","Output directory (default: current directory)",{default:"."}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--format <format>","Output format to download (e.g. glb, textures)",{required:!1,validator:ug.STRING}).option("--version <version>","Download this source version or derived output ID",{validator:ug.STRING}).option("--label <label>","Download the version served by this label",{validator:ug.STRING}).option("--name <name>","Output filename (without extension)",{required:!1,validator:ug.STRING}).option("--verbose","Show detailed download info",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({args:e,options:t})=>{var n,o,i,r,a,s;const c=_u(t),{accessToken:l,org_id:p}=await lg(t.token,pg(t),!0!==t.nonInteractive),u=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",d=String(e.identifier),m=(null==(o=e.directory)?void 0:o.toString())||".",f=(null==(i=t.name)?void 0:i.toString())||void 0,h=null!=(r=null==(a=t.verbose)?void 0:a.valueOf())&&r,g=(null==(s=t.format)?void 0:s.toString())||void 0,v=$("Looking up content...").start();try{var b,y;const e={baseUrl:u,authToken:l,org:p},n=await cp(e,d);if(!n)throw new Error(`Content not found: "${d}". Use the exact content identifier (see list).`);const o=function(e,t){if(void 0!==t.version&&!t.version.trim())throw new Error("--version requires a version ID.");if(void 0!==t.label&&!t.label.trim())throw new Error("--label requires a label name.");if(t.version&&t.label)throw new Error("Use either --version or --label, not both.");const n=e.versions[0];if(!n)throw new Error(`Content "${e.title||e.name}" has no upload versions.`);let o;if(t.version){const n=e.versions.find(e=>e.identifier===t.version);if(o=n?[n,...n.variants]:e.versions.flatMap(e=>e.variants).filter(e=>e.identifier===t.version),!o.length)throw new Error(`Version "${t.version}" does not belong to this content item.`)}else if(t.label){if(o=e.versions.flatMap(e=>[e,...e.variants]).filter(e=>e.labels.some(e=>e.label===t.label)),!o.length)throw new Error(`Label "${t.label}" was not found on this content item.`)}else o=t.format?e.versions.flatMap(e=>[e,...e.variants]):[n];const i=t.format?o.find(e=>e.content_format===t.format):o[0];if(!i)throw new Error(`No output with format "${t.format}" found for the requested content selection.`);if((t.version||t.label)&&i.status&&"completed"!==i.status)throw new Error(`Version "${i.identifier}" is ${i.status}; select a completed version.`);return i.identifier}(n,{version:null==(b=t.version)?void 0:b.toString(),label:null==(y=t.label)?void 0:y.toString(),format:g});v.text=`Downloading "${n.title||n.name}"${g?` (format: ${g})`:""}...`,v.stop();const i=await Gu({baseUrl:u,authToken:l,org:p,identifier:o,outDir:m,filename:f,verbose:h,content_format:g});if("error"in i)throw new Error(i.error);"json"===c&&ku(i)}catch(e){v.fail(e instanceof Error?e.message:String(e)),process.exitCode=1}})),ug.command("deploy","Deploy a website to Needle").help("").argument("<directory>","The directory to deploy",{validator:ug.STRING}).option("--label <label>","Create or move a label to the deployed version (latest is automatic; requires read/write access)",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to deploy to (not needed when using token/accesstoken)",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id to deloy to (not needed when using token/accesstoken)",{required:!1,validator:ug.STRING,hidden:!0}).option("--name <name>","The project name. This name will also be used in your website URL",{required:!1,validator:ug.STRING}).option("--entrypoint <entrypoint>",'The entrypoint file to use (e.g. "index.html"). This is useful if you want to deploy a folder with multiple HTML files and you want to configure which file to load initially or if you have multiple model files in one folder',{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING,hidden:!0}).option("--open","Open the deployment in the default browser",{default:!0,validator:ug.BOOLEAN}).option("--verbose <verbose>","Enables verbose output logs",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--experimental","Use the experimental upload API. Mostly used for debugging (default: false)",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--raw","Use raw to disallow modifications like gzip compression on upload",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--no-provenance","Do not record which commit and CI run this deployment came from",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(yu("deploy",async({args:e,options:t,logger:n})=>{var o,i,r,a,s;const c=null==(o=t.label)?void 0:o.toString();void 0!==c&&qp(c);const l=_u(t),p=!0!==t.nonInteractive&&t.open,{accessToken:u,org_id:d}=await lg(t.token,pg(t),!0!==t.nonInteractive),m=!0===t.verbose,f=!0===t.experimental,h=!0===t.raw,g=(null==(i=t.noProvenance)?void 0:i.valueOf())||!1,v=await gu({label:c,logger:n,endpoint:(null==(r=t.endpoint)?void 0:r.toString())||void 0,token:u,org_id:d,directory:String(e.directory),name:(null==(a=t.name)?void 0:a.toString())||void 0,entrypoint:(null==(s=t.entrypoint)?void 0:s.toString())||void 0,open:p,verbose:m||!1,experimental:f||!1,raw:h||!1,noProvenance:g});"json"===l&&null!=v&&v.success&&ku(v)}))),function(e,t){for(const n of["upload","optimize"]){const o="optimize"===n,i=e.command(n,o?"Upload and wait for optimized assets (shorthand for upload --wait)":"Upload source assets to Needle Cloud").help("Upload returns source file identities and links after the transfer completes. Optimization continues in the background. Use upload --wait or optimize to wait for the selected optimized variant. Public glTF/GLB URLs are imported by Cloud with their referenced files. URL imports return a queued job; --wait waits for import and optimization. URL source-url output requires --wait. Folders are collected recursively into one grouped upload. Use --format json for its file list. Original links always identify the uploaded source version.").argument("<path>","File, folder, or public glTF/GLB URL to upload",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Organization name or ID (deprecated; use --team)",{validator:e.STRING,hidden:!0}).option("--name <name>","Upload name or identifier of an existing asset",{validator:e.STRING}).option("--content-id <id>","Append to an existing 3D asset",{validator:e.STRING}).option("--format <format>","Legacy output option: cli, json, source-url or edit-url",{validator:e.STRING}).option("--outdir <outdir>","Download optimized files to this directory (requires waiting)",{validator:e.STRING}).option("--progressive","Use progressive loading when waiting for optimization",{validator:e.BOOLEAN,default:!!o||void 0}).option("--usecase <usecase>","Optimization variant: product or world (requires waiting)",{validator:e.STRING,default:o?"product":void 0}).option("--verbose <verbose>","Print detailed diagnostics to stderr",{validator:e.BOOLEAN,default:!1});o||i.alias("import"),o||i.option("--wait","Wait for the selected optimized result",{validator:e.BOOLEAN,default:!1}).option("--no-optimize","Store source files without requesting processing",{validator:e.BOOLEAN,default:!1}),i.action(yu(n,async({args:e,options:n})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Pe({stdout:a,stderr:a});try{var s,c;const i=_u(n,{legacyFormat:!0,links:!0}),r=o||!0===n.wait;if(r&&!0===n.noOptimize)throw new Error("--wait cannot be combined with --no-optimize.");if(!r&&(void 0!==n.outdir||void 0!==n.progressive||void 0!==n.usecase))throw new Error("--wait is required for --outdir, --progressive and --usecase.");const a=n.usecase;if(void 0!==a&&"product"!==a&&"world"!==a)throw new Error("Use case must be product or world.");void 0!==n.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await wu(t.getAccessToken,n);if(p!==n.token&&p!==process.env.NEEDLE_CLOUD_TOKEN){const e=await t.getUser();if(null==e||!e.isAuthenticated)throw new Error("Please login to upload files.");if(!u)throw new Error("Please provide a team to upload files.");if(r){var l;const e=await(null!=(l=t.getLicenses)?l:xt)({baseUrl:"https://cloud.needle.tools/api",authToken:p,org:u},{type:"org",org_id:u});if(null==e||!e.some(e=>"Needle Engine"===e.type&&("pro"===e.license||"enterprise"===e.license)))throw new Error("Update to Needle PRO or Enterprise required to optimize files via CLI. Visit https://cloud.needle.tools/get-pro")}}Vu(await(null!=(s=t.upload)?s:Hu)({token:p,org_id:u,fileOrDirectory:String(e.path),contentId:void 0===n.contentId?void 0:String(n.contentId),name:void 0===n.name?void 0:String(n.name),wait:r,noOptimize:!0===n.noOptimize,progressive:void 0===n.progressive?void 0:!0===n.progressive,usecase:a,outDir:void 0===n.outdir?void 0:String(n.outdir),verbose:!0===n.verbose,format:i}),i,null!=(c=t.write)?c:e=>{process.stdout.write(e)})}finally{globalThis.console=r}}))}$u(e)}(ug,{getAccessToken:lg,getUser:Hd}),function(e,t){e.command("label","List, create or move content labels");for(const n of["list","set"]){const o=e.command(`label ${n}`,"list"===n?"List content labels and their source/derived URLs":"Create or move a label to a completed content version").argument("<content-id>","Content item identifier",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Organization name or ID (deprecated; use --team)",{validator:e.STRING,hidden:!0}).option("--format <format>","Legacy output option: cli or json",{validator:e.STRING});"set"===n&&o.argument("<label>","Destination label; latest is managed automatically",{validator:e.STRING}).option("--version <version>","Completed version ID from this content item",{validator:e.STRING}).option("--from <label>","Select the version currently targeted by this label (for example latest)",{validator:e.STRING}).help("Provide exactly one of --version or --from. Moving a label also updates its related completed outputs. Both read and write access are required."),o.action(yu(`label ${n}`,async({args:e,options:o})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Pe({stdout:a,stderr:a});try{var s;const i=_u(o,{legacyFormat:!0}),r=String(e.contentId);Bp(r);const a={contentId:r,label:String(e.label),versionId:void 0===o.version?void 0:String(o.version),from:void 0===o.from?void 0:String(o.from)};"set"===n&&Mp(a),void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await wu(t.getAccessToken,o),d={baseUrl:"https://cloud.needle.tools/api",authToken:p,org:u},m=null!=(s=t.write)?s:e=>{process.stdout.write(e)};if("list"===n){var c;const e=await(null!=(c=t.listContentLabels)?c:Hp)(d,r);if("json"===i)m(JSON.stringify(e)+"\n");else if(e.labels.length)for(const t of e.labels)m(`${t.label}: ${t.sourceVersionIds.join(", ")}\n`),Iu(t.targets,m);else m(`No labels for ${r}.\n`)}else{var l;const e=await(null!=(l=t.setContentLabel)?l:Jp)(d,a);"json"===i?m(JSON.stringify(e)+"\n"):(m(`${e.label}: ${e.previousVersionIds.join(", ")||"(new label)"} -> ${e.versionId}\n`),Iu(e.targets,m))}}finally{globalThis.console=r}}))}$u(e)}(ug,{getAccessToken:lg}),function(e,t){const n={getContent:cp,updateContent:lp,restoreContent:up,...t},o={info:"Inspect content metadata, versions and processing state",versions:"List source versions and their derived outputs, newest first",update:"Update content metadata or its thumbnail",restore:"Restore a content item from Trash"};for(const i of["info","versions","update","restore"]){const r=e.command(i,o[i]).argument("<identifier>","Content identifier",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Legacy alias for --team",{validator:e.STRING,hidden:!0}).option("--endpoint <endpoint>","Needle Cloud API endpoint",{validator:e.STRING}).option("--output <output>","Output style: cli (default) or json",{validator:e.STRING,default:"cli"});"update"===i&&r.option("--title <title>","Set the title; an empty string clears it",{validator:e.STRING}).option("--description <description>","Set the description; an empty string clears it",{validator:e.STRING}).option("--tags <tags>","Replace tags with a comma-separated list",{validator:e.STRING}).option("--thumbnail <path>","Set a JPEG, PNG or WebP thumbnail (up to 5 MiB)",{validator:e.STRING}),"restore"===i&&r.help("Restore an item within 31 days of deletion. Requires enough available storage. Use list --trash to find deleted items."),r.action(yu(i,async({args:e,options:o})=>{var r,a,s;const c=String(e.identifier);if(!c.trim()||/[/\\?#\s]/.test(c))throw new Error("Pass an exact content identifier from list.");const l=String(null!=(r=o.output)?r:"cli");if("cli"!==l&&"json"!==l)throw new Error("Invalid --output. Use cli or json.");const p="update"===i?await Ou(o):void 0,u=globalThis.console,d=null!=(a=t.stderr)?a:process.stderr,m=null!=(s=t.write)?s:e=>{process.stdout.write(e)};globalThis.console=new Pe({stdout:d,stderr:d});try{var f;void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:e,org_id:r}=await wu(t.getAccessToken,o),a={baseUrl:String(null!=(f=o.endpoint)?f:"https://cloud.needle.tools/api"),authToken:e,org:r};if("update"===i&&p){const e=await n.updateContent(a,c,p);if("error"in e)throw new Error(e.error);if(!e.success)throw new Error("Content update was not confirmed.");m("json"===l?JSON.stringify(e)+"\n":`Updated ${c}\n`)}else if("restore"===i){const e=await n.restoreContent(a,c);if(!e.restored)throw new Error("Content restore was not confirmed.");m("json"===l?JSON.stringify(e)+"\n":`Restored ${c}\n`)}else{const e=await n.getContent(a,c);var h,g;"json"===l?m(JSON.stringify("versions"===i?e.versions:e,null,2)+"\n"):("info"===i&&m(`${e.title||e.name} (${e.identifier})\n${null!=(h=e.description)?h:""}\nTags: ${(null!=(g=e.tags)?g:[]).join(", ")}\n`),m(e.versions.length?e.versions.map(Au).join(""):"No upload versions.\n"))}}finally{globalThis.console=u}}))}$u(e)}(ug,{getAccessToken:lg}),function(e,t){const n={queryCollections:bp,getCollectionMetadata:yp,listCollectionItems:xp,createCollection:fp,updateCollection:hp,deleteCollection:gp,addCollectionEntry:Sp,removeCollectionEntry:wp,reorderCollectionEntries:_p,...t},o={list:"List collections in the authenticated team",info:"Read collection metadata and membership IDs",items:"List collection items and their membership IDs",create:"Create a collection",update:"Edit collection metadata or thumbnail",delete:"Delete a collection; source content remains intact",add:"Add uploaded content to a collection",remove:"Remove a membership; source content remains intact",reorder:"Set the complete manual order using membership IDs"};e.command("collection","Manage collections and their items");for(const i of["list","info","items","create","update","delete","add","remove","reorder"]){const r=e.command(`collection ${i}`,o[i]).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Legacy alias for --team",{validator:e.STRING,hidden:!0}).option("--endpoint <endpoint>","Needle Cloud API endpoint",{validator:e.STRING});"create"===i?r.argument("<name>","Collection name",{validator:e.STRING}):"list"!==i&&r.argument("<identifier>","Collection identifier",{validator:e.STRING}),"add"===i&&r.argument("<content-id>","Uploaded content identifier",{validator:e.STRING}),"remove"===i&&r.argument("<entry-id>","Membership ID from collection items",{validator:e.STRING}),"reorder"===i&&r.argument("<entry-ids>","Complete comma-separated membership IDs in desired order",{validator:e.STRING}).help("Use collection info for all membership IDs, including unavailable items. Supply every ID exactly once."),"info"!==i&&"list"!==i||r.option("--diagnostics","Include collection eligibility counts and exclusion guidance",{validator:e.BOOLEAN,default:!1}),"items"===i&&r.option("--include-unavailable","Include excluded memberships and API guidance (team read access required)",{validator:e.BOOLEAN,default:!1}),"delete"===i&&r.option("--yes","Confirm collection deletion",{validator:e.BOOLEAN,default:!1}),"create"!==i&&"update"!==i||("update"===i&&r.option("--name <name>","Set the collection name",{validator:e.STRING}),r.option("--description <description>","Set description; an empty string clears it",{validator:e.STRING}).option("--tags <tags>","Replace comma-separated tags; an empty string clears them",{validator:e.STRING}).option("--visibility <visibility>","private, unlisted or public (subject to server availability)",{validator:e.STRING}),"update"===i&&r.option("--thumbnail <path>","JPEG, PNG or WebP thumbnail, up to 5 MiB",{validator:e.STRING}).option("--remove-thumbnail","Remove the collection thumbnail",{validator:e.BOOLEAN,default:!1})),"list"!==i&&"items"!==i||(r.option("--limit <limit>","Page size, 1..100 (default 20)",{validator:e.NUMBER}).option("--offset <offset>","Page offset (default 0)",{validator:e.NUMBER}),"list"===i?r.option("--search <search>","Filter collection names and descriptions",{validator:e.STRING}).option("--tags <tags>","Require all comma-separated collection tags",{validator:e.STRING}).option("--visibility <visibility>","Filter by private, unlisted or public",{validator:e.STRING}):r.option("--sort-by <sort>","manual (default), name, created_at or updated_at",{validator:e.STRING}).option("--sort-direction <direction>","asc (default) or desc",{validator:e.STRING})),r.action(yu(`collection ${i}`,async({args:e,options:o})=>{var r,a,s,c,l,p,u,d;const m=_u(o),f="list"!==i&&"create"!==i?String(e.identifier):"";"list"!==i&&"create"!==i&&Bp(f);const h="create"===i||"update"===i?await Pu(o,"create"===i?e.name:o.name):{};if("create"===i&&!h.name)throw new Error("Pass a collection name.");if("update"===i&&!Object.keys(h).length)throw new Error("Nothing to update. Pass --name, --description, --tags, --visibility, --thumbnail or --remove-thumbnail.");if("delete"===i&&!0!==o.yes)throw new Error("Pass --yes to confirm collection deletion.");const g=String(null!=(r=e.contentId)?r:"");"add"===i&&Bp(g);const v="remove"===i?Ru(e.entryId,"Membership ID",1):0,b="reorder"===i?String(e.entryIds).split(",").map(e=>Ru(e,"Membership ID",1)):[];if("reorder"===i&&new Set(b).size!==b.length)throw new Error("Membership IDs must not repeat.");const y="list"===i||"items"===i?Ru(null!=(a=o.limit)?a:20,"Limit",1,100):20,x="list"===i||"items"===i?Ru(null!=(s=o.offset)?s:0,"Offset",0):0,w=Nu(o.visibility),_=void 0===o.tags?void 0:mp(String(o.tags).split(",")),S=null!=(c=o.sortBy)?c:"manual";if("manual"!==S&&"name"!==S&&"created_at"!==S&&"updated_at"!==S)throw new Error("Invalid --sort-by. Use manual, name, created_at or updated_at.");const j=null!=(l=o.sortDirection)?l:"asc";if("asc"!==j&&"desc"!==j)throw new Error("Invalid --sort-direction. Use asc or desc.");const k=globalThis.console;globalThis.console=new Pe({stdout:null!=(p=t.stderr)?p:process.stderr,stderr:null!=(u=t.stderr)?u:process.stderr});const E=null!=(d=t.write)?d:e=>{process.stdout.write(e)};try{var T;void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:e,org_id:r}=await wu(t.getAccessToken,o),a={baseUrl:String(null!=(T=o.endpoint)?T:"https://cloud.needle.tools/api"),authToken:e,org:r};let s,c="";if("list"===i){if(!r)throw new Error("Select a team with --team to list its collections.");const e=await n.queryCollections(a,{org:r,limit:y,offset:x,...void 0!==o.search?{search:String(o.search)}:{},...void 0!==_?{tags:_}:{},...w?{visibility:w}:{},...o.diagnostics?{include_diagnostics:!0}:{}});s=e,c=e.collections.map(e=>`${e.identifier} ${e.name} (${e.item_count} items)\n`).join("")||"No collections.\n",c+=`Showing ${e.collections.length} of ${e.total}; offset ${e.offset}.\n`}else if("info"===i)s=await n.getCollectionMetadata(a,f,{include_memberships:!0,...o.diagnostics?{include_diagnostics:!0}:{}}),c=JSON.stringify(s,null,2)+"\n";else if("items"===i){const e=await n.listCollectionItems(a,f,{limit:y,offset:x,sort_by:S,sort_direction:j,...o.includeUnavailable?{include_unavailable:!0}:{}});s=e,c=e.items.map(e=>`${e.id} ${e.content_item_id} ${e.title||e.name||"(unavailable)"}${e.diagnostics?` — ${e.diagnostics.message}`:""}\n`).join("")||"No items.\n",c+=`Showing ${e.items.length} of ${e.total}; offset ${e.offset}.\n`}else if("create"===i){const e=await n.createCollection(a,{...h,name:h.name||""});if(!e.identifier)throw new Error("Collection creation was not confirmed.");s=e,c=`Created ${e.identifier}\n`}else if("update"===i||"delete"===i){const e="update"===i?await n.updateCollection(a,f,h):await n.deleteCollection(a,f);if(e.identifier!==f)throw new Error("Collection change was not confirmed.");s=e,c=`${"update"===i?"Updated":"Deleted"} ${f}\n`}else if("add"===i){const e=await n.addCollectionEntry(a,f,g);if(!Number.isSafeInteger(e.id)||e.id<1)throw new Error("Collection addition was not confirmed.");s=e,c=`Added ${g} to ${f}; membership ${e.id}\n`}else{const e="remove"===i?await n.removeCollectionEntry(a,f,v):await n.reorderCollectionEntries(a,f,b);if(!0!==e.success)throw new Error("Collection change was not confirmed.");s=e,c=`${"remove"===i?"Removed membership "+v+" from":"Reordered"} ${f}\n`}E("json"===m?JSON.stringify(s)+"\n":c)}finally{globalThis.console=k}}))}$u(e)}(ug,{getAccessToken:lg}),ug.command("generate-material","Generate a PBR material from a text prompt").help("").argument("<prompt>","The text prompt describing the material to generate",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:ug.STRING,hidden:!0}).option("--resolution <resolution>","The material texture resolution (256, 512, 1k, 2k, 4k)",{default:"512",required:!1,validator:ug.STRING}).option("--name <name>","Output filename",{required:!1,validator:ug.STRING}).option("--outdir <outdir>","Output directory to download the generated file(s) to. If not set, the job ID is printed instead.",{required:!1,validator:ug.STRING}).action(ju(yu("generate-material",async({args:e,options:t,logger:n})=>{var o,i,r;const a=_u(t),{accessToken:s,org_id:c}=await lg(t.token,pg(t),!0!==t.nonInteractive),l=String(e.prompt),p=null==(o=t.resolution)?void 0:o.toString(),u=null==(i=t.outdir)?void 0:i.toString(),d=null==(r=t.name)?void 0:r.toString(),m=await async function(e){if(!e.token||e.token.length<=1||"string"!=typeof e.token||"true"===e.token)return{error:`Missing access token. Create a token at ${Kp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";mu(`[generate-material] Starting request to ${t}, prompt="${e.prompt}", resolution=${e.resolution||512}`,{emptyLineBefore:!0});const n=$("Requesting material generation...").start(),o=await Promise.race([op({baseUrl:t,authToken:e.token,org:e.org_id,trigger_type:"cli"},{prompt:e.prompt,resolution:e.resolution||512}).catch(e=>({error:e.message||"Request failed"})),new Promise(e=>setTimeout(()=>e({error:"Request timed out after 30s. Please try again."}),3e4))]);if("error"in o)return mu(`[generate-material] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(mu(`[generate-material] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return mu(`[generate-material] Job canceled: ${i.status_message||"quota exceeded"}`),n.fail(i.status_message||"Material generation was canceled (quota exceeded)"),{error:i.status_message||"Quota exceeded"};n.succeed(`Material generation requested: ${i.identifier}`);const r=$("Waiting for material generation...").start();r.color="gray";const a=Tc();for(;;){if("completed"===i.status){r.succeed("Material generation completed");break}let n=2e3;const o=await Ec(i.identifier,{baseUrl:t,authToken:e.token,org:i.org}),s=a.record(o);if(s)return r.fail(s.reason),{error:s.reason};if("new"===(null==o?void 0:o.status)||"pending"===(null==o?void 0:o.status))r.text="Your material is queued - waiting for generation to start",r.color="yellow",n=2e3;else if("running"===(null==o?void 0:o.status))r.text=`Generating material: ${o.progress?`${o.progress}%`:""} ${o.status_message?`— ${o.status_message}`:""}`,r.color="cyan",n=1e3;else{if("completed"===(null==o?void 0:o.status)){mu(`[generate-material] Job completed: ${i.identifier}`),r.succeed(`Material generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return mu(`[generate-material] Job canceled: ${i.identifier}, error=${o.error}`),r.fail(`Material generation canceled: ${o.error||""}`),{error:o.error||"Material generation canceled"};if("failed"===(null==o?void 0:o.status))return mu(`[generate-material] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`Material generation failed: ${o.error||""}`),{error:o.error||"Material generation failed"}}await $l(n)}if(e.outDir){const n=await Gu({baseUrl:t,authToken:e.token,org:e.org_id,identifier:i.identifier,outDir:e.outDir,filename:e.outputName});if("error"in n)return{error:n.error}}return{success:!0,identifier:i.identifier}}({logger:n,token:s,org_id:c,prompt:l,resolution:p,outputName:d,outDir:u});"error"in m&&(m.error&&n.error(m.error),process.exit(1)),"json"===a?ku(m):!u&&"identifier"in m&&console.log(m.identifier),await Eu(0)}))),ug.command("generate-3d","Generate a 3D model from a text prompt").help("").argument("<prompt>",'A description of the object to generate, e.g. "a weathered wooden crate with iron bands"',{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:ug.STRING,hidden:!0}).option("--quality <quality>","Quality tier: standard (default, includes physically based material maps) or draft (faster and cheaper, base color only)",{default:"standard",required:!1,validator:ug.STRING}).option("--face-count <faceCount>","Target polygon count (40000-1500000). Leave unset to let the generator choose.",{required:!1,validator:ug.NUMBER}).option("--name <name>","Output filename",{required:!1,validator:ug.STRING}).option("--outdir <outdir>","Output directory to download the generated file(s) to. If not set, the job ID is printed instead.",{required:!1,validator:ug.STRING}).action(ju(yu("generate-3d",async({args:e,options:t,logger:n})=>{var o,i,r;const a=_u(t),s=null==(o=t.quality)?void 0:o.toString();if(void 0!==s&&"draft"!==s&&"standard"!==s)throw new Error("Quality must be draft or standard.");const c=null!=t.faceCount?Number(t.faceCount):void 0;if(void 0!==c&&(!Number.isInteger(c)||c<4e4||c>15e5))throw new Error("--face-count must be an integer from 40000 to 1500000.");const{accessToken:l,org_id:p}=await lg(t.token,pg(t),!0!==t.nonInteractive),u=String(e.prompt),d=null==(i=t.outdir)?void 0:i.toString(),m=null==(r=t.name)?void 0:r.toString(),f=await async function(e){if(!e.token||e.token.length<=1||"string"!=typeof e.token||"true"===e.token)return{error:`Missing access token. Create a token at ${Kp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";mu(`[generate-3d] Starting request to ${t}, prompt="${e.prompt}", quality=${e.quality||"draft"}`,{emptyLineBefore:!0});const n=$("Requesting 3D generation...").start(),o=await async function(e,t){var n;if(null!=(n=e.signal)&&n.aborted)return{error:"The 3D generation request was cancelled"};const o=e.baseUrl+vt.jobs.create,i={...bt(e),"content-type":"application/json"},r={type:"ai-3d-asset",triggered_by:e.trigger_type,parameters:{...t}},a=await fetch(o,{...yt,method:"POST",headers:i,body:JSON.stringify(r),signal:e.signal}).catch(e=>function(e){return"AbortError"===(null==e?void 0:e.name)||"TimeoutError"===(null==e?void 0:e.name)}(e)?{__aborted:!0}:(console.error(`Failed to request 3D asset generation: ${null==e?void 0:e.message}`),{__failed:(null==e?void 0:e.message)||"Request failed"}));if("__aborted"in a)return{error:"The 3D generation request was cancelled"};if("__failed"in a)return{error:a.__failed};if(!a.ok){const e=await a.text();return console.error(`Failed to request 3D asset generation (${a.status}): ${e}`),{error:e||`Request failed (${a.status})`}}const s=await a.json().catch(e=>(console.error(e),null));return null!=s&&s.job?s:{error:"The server did not return a job"}}({baseUrl:t,authToken:e.token,org:e.org_id,trigger_type:"cli",signal:AbortSignal.timeout(3e4)},{prompt:e.prompt,...e.quality?{quality:e.quality}:{},...e.face_count?{face_count:e.face_count}:{}});if("error"in o)return mu(`[generate-3d] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(mu(`[generate-3d] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return mu(`[generate-3d] Job canceled: ${i.status_message||"quota exceeded"}`),n.fail(i.status_message||"3D generation was canceled (quota exceeded)"),{error:i.status_message||"Quota exceeded"};n.succeed(`3D generation requested: ${i.identifier}`);const r=$("Waiting for the 3D model...").start();r.color="gray";const a=Tc();for(;;){if("completed"===i.status){r.succeed("3D generation completed");break}let n=2e3;const o=await Ec(i.identifier,{baseUrl:t,authToken:e.token,org:i.org}),s=a.record(o);if(s)return r.fail(s.reason),{error:s.reason};if("new"===(null==o?void 0:o.status)||"pending"===(null==o?void 0:o.status))r.text="Your model is queued - waiting for generation to start",r.color="yellow",n=2e3;else if("running"===(null==o?void 0:o.status))r.text=`Generating 3D model: ${o.progress?`${o.progress}%`:""} ${o.status_message?`— ${o.status_message}`:""}`,r.color="cyan",n=1e3;else{if("completed"===(null==o?void 0:o.status)){mu(`[generate-3d] Job completed: ${i.identifier}`),r.succeed(`3D generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return mu(`[generate-3d] Job canceled: ${i.identifier}, error=${o.error}`),r.fail(`3D generation canceled: ${o.error||""}`),{error:o.error||"3D generation canceled"};if("failed"===(null==o?void 0:o.status))return mu(`[generate-3d] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`3D generation failed: ${o.error||""}`),{error:o.error||"3D generation failed"}}await $l(n)}if(e.outDir){const n=await Gu({baseUrl:t,authToken:e.token,org:e.org_id,identifier:i.identifier,outDir:e.outDir,filename:e.outputName});if("error"in n)return{error:n.error}}return{success:!0,identifier:i.identifier}}({logger:n,token:l,org_id:p,prompt:u,quality:s,face_count:c,outputName:m,outDir:d});"error"in f&&(f.error&&n.error(f.error),process.exit(1)),"json"===a?ku(f):!d&&"identifier"in f&&console.log(f.identifier),await Eu(0)}))),ug.command("ask","Send a message to the Needle Cloud AI").help("Send a message to Needle Cloud AI. By default, starts an interactive conversation, optionally with an initial message. Use --once to send one message and exit, or --non-interactive to also prohibit authentication prompts and browser launches. Both require a message. --output json returns one complete response and exits. --no-stream prints the full answer as text. Use --slug to continue a conversation.").argument("[message...]","The message to send (omit for interactive mode)").option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--slug <slug>","Chat slug to continue an existing conversation",{required:!1,validator:ug.STRING}).option("--no-stream","Disable streaming (returns full response at once)",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--once","Send one message and exit",{validator:ug.BOOLEAN,default:!1}).action(yu("ask",async({args:e,options:t})=>{var n,o;const i=_u(t),r=Array.isArray(e.message)?e.message:e.message?[e.message]:[],a=r.length?r.join(" "):void 0;if(!(!0!==t.nonInteractive&&!0!==t.once&&"json"!==i||null!=a&&a.trim()))throw new Error("A message is required for one-shot or non-interactive chat.");const{accessToken:s,org_id:c}=await lg(t.token,pg(t),!0!==t.nonInteractive),l=(null==(n=t.slug)?void 0:n.toString())||void 0,p=(null==(o=t.noStream)?void 0:o.valueOf())||!1;await async function(e){const{token:t,org_id:n,message:o,slug:i,stream:r}=e,a=i||function(e){try{const t=e.split(".")[1],n=JSON.parse(Buffer.from(t,"base64url").toString());if(n.sub)return n.sub+"-cli"}catch{}return"cli-"+Math.random().toString(36).slice(2,10)}(t);if(!0===e.nonInteractive||!0===e.once||"json"===e.output){if(null==o||!o.trim())throw new Error("A message is required for one-shot or non-interactive chat.");await Su("json"===e.output,()=>Ku({token:t,org_id:n,slug:a,message:o,stream:"json"!==e.output&&r,output:e.output}))}else await async function(e){const{token:t,org_id:n,slug:o,stream:i,initialMessage:r}=e,a=Ue({input:process.stdin,output:process.stdout});console.log(`Needle Cloud AI (chat: ${o})`),console.log('Type your message. Press Ctrl+C or type "exit" to quit.\n');try{for(r&&(console.log(`> ${r}`),await Ku({token:t,org_id:n,slug:o,message:r,stream:i}),console.log(""));;){const e=(await a.question("> ")).trim();if(e){if("exit"===e||"quit"===e)break;await Ku({token:t,org_id:n,slug:o,message:e,stream:i}),console.log("")}}}finally{a.close()}}({token:t,org_id:n,slug:a,stream:r,initialMessage:o})}({token:s,org_id:c,message:a,slug:l,stream:!p,nonInteractive:!0===t.nonInteractive,once:!0===t.once,output:"json"===i?"json":"cli"}),await Eu(0)})),$u(ug);export{dm as g,ug as p};
|
|
63
|
+
`;function Of(e,t,n,o){Im(e,async(e,n)=>{try{const o=await t(e,n);return"string"==typeof o?Dm(o):{...o,content:o.content.map(e=>"text"===e.type?{...e,text:Dm(e.text)}:e)}}catch(e){throw new Error(Dm(e instanceof Error?e.message:String(e)))}},n,o)}const Af=function(e,t=Xm,n=Date.now){let o,i=0;const r=Object.assign(async(r={})=>{var a,s,c,l;const p={status:"error",message:"Use mode check, results or error; file/code filters, nonnegative integer offset/index. No paths or commands can be selected."};if(!r||"object"!=typeof r||Array.isArray(r))return p;if(Object.keys(r).some(e=>!["mode","file","code","offset","index"].includes(e)))return p;const u=null!=(a=r.mode)?a:"check";if(!["check","results","error"].includes(u))return p;for(const e of[r.file,r.code])if(void 0!==e&&("string"!=typeof e||e.length>250))return p;for(const e of[r.offset,r.index])if(void 0!==e&&(!Number.isSafeInteger(e)||e<0))return p;const d=e();if(o&&o.project!==d&&(o=void 0),"check"===u){var m;const e=i,r=ef(d),a=await t(d);o={project:d,result:{...a,...a.message?{message:Dm(a.message)}:{},...a.output?{output:Dm(a.output)}:{},diagnostics:(null!=(m=a.diagnostics)?m:[]).map(e=>({...e,message:Dm(e.message)}))},time:n(),revision:e,snapshot:r}}if(!o)return{status:"unavailable",message:"No saved check for this local project. Run local_files_check_project with mode check first."};const f=ef(d),h=null===o.snapshot||null===f,g=o.result,v=null!=(s=g.diagnostics)?s:[],b=v.map((e,t)=>({...e,index:t})),y=b.filter(e=>{var t;return(!r.file||(null!=(t=e.file)?t:"").toLowerCase().includes(r.file.toLowerCase()))&&(!r.code||e.code===r.code)}),x=null!=(c=r.offset)?c:0,w="error"===u?y.filter(e=>{var t,n;return e.index===(null!=(t=r.index)?t:null==(n=y.at(-1))?void 0:n.index)}):y.slice(x,x+5);if("error"===u&&!w.length)return{status:"unavailable",message:"No matching error in the latest check. Use mode results to list available error indexes."};const _="error"===u?2e3:300;return{status:g.status,check:"typescript",checkedAt:new Date(o.time).toISOString(),cached:"check"!==u,stale:o.revision!==i||h||o.snapshot!==f,project:tf(d,300),totalDiagnostics:null!=(l=g.totalDiagnostics)?l:v.length,retainedDiagnostics:v.length,matchingDiagnostics:y.length,truncated:Boolean(g.truncated),diagnostics:w.map(e=>({...e,...e.file?{file:tf(e.file,300)}:{},message:tf(e.message,_),messageTruncated:e.message.length>_})),..."error"!==u&&x+w.length<y.length?{nextOffset:x+w.length}:{},...g.message||h?{message:tf([g.message,h?"Could not scan project files for changes; this check is marked stale.":null].filter(Boolean).join(" "),500)}:{},...g.output?{output:tf(g.output,"error"===u?2e3:500),outputTruncated:g.output.length>("error"===u?2e3:500)}:{}}},{markStale(){i++}});return r}(()=>{var e;return null==(e=Ff())?void 0:e.web_location}),Nf=function(e,t=ce(oe(),".needle","cli","ai-checkpoints"),n=(()=>{})){let o=0n,r=!1;function a(t){if(!(t&&t.chatId&&t.sessionId&&t.turnId&&t.project))throw new Error("Local file edit approval is required.");const n=e();if(!n||le(n)!==le(t.project))throw new Error("The approved local project has changed.");return{root:A(n),grant:t}}function s(e,t,n){if("string"!=typeof t||!t||t.includes("\0")||de(t)||fe.isAbsolute(t)||he.isAbsolute(t)||t.split(/[\\/]/).some(e=>!e||"."===e||".."===e||e.includes(":")))throw new Error("Path must be a file inside the selected local project.");if(Bm(e)||Bm(t))throw new Error("Sensitive files cannot be accessed by local AI tools.");if(t.split(/[\\/]/).some(e=>/[ .]$/.test(e)))throw new Error("Invalid file path.");const o=le(e,t);if(!o.startsWith(e+me))throw new Error("Path escapes the selected local project.");let i=e;const r=pe(e,o).split(me);for(let e=0;e<r.length;e++){if(i=ce(i,r[e]),!I(i)){if(e!==r.length-1||!n)throw new Error("The file or its parent directory does not exist.");continue}const t=M(i);if(t.isSymbolicLink()||t.nlink>1)throw new Error("Symbolic links and hard links cannot be edited.");if(e<r.length-1&&!t.isDirectory())throw new Error("Parent path is not a directory.");if(e===r.length-1&&!t.isFile())throw new Error("Target is not a regular file.")}return o}function c(e,t){const n=`${e}.needle-ai-${i()}.tmp`;try{H(n,t,{flag:"wx",mode:384}),O(n,e)}finally{I(n)&&G(n)}}function l(){return I(t)?B(t).filter(e=>e.endsWith(".json")).reduce((e,n)=>e+N(ce(t,n)).size,0):0}function p(e){if(!r){if(I(t))for(const e of B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e))){const n=JSON.parse(W(ce(t,e),"utf8"));if(n.order&&/^\d+$/.test(n.order)){const e=BigInt(n.order);e>o&&(o=e)}}r=!0}const n=1000000n*BigInt(Date.now());o=n>o?n:o+1n,e.order=o.toString();const a=JSON.stringify(e);if(l()+Buffer.byteLength(a)>of)throw new Error("Checkpoint storage is full; no file was changed.");C(t,{recursive:!0,mode:448});const s=i(),c=ce(t,`${s}.json`);return H(c,a,{flag:"wx",mode:384}),{id:s,file:c}}function u(e,t){if(e.byteLength>nf)throw new Error("File exceeds the 1 MiB edit limit.");if(!t||!/^[a-f0-9]{64}$/.test(t))throw new Error("Expected file SHA-256 hash is required before changing a file.");if(rf(e)!==t)throw new Error("The supplied expectedSha256 does not match this file. The file may have changed, or the hash may be incorrect. Run local_files_stat again and use its sha256 value.")}function d(e,t){try{const n=t=>{const n=s(e,t,!0);return I(n)?W(n):null},o=n(t.path),i=null===t.before?null:rf(Buffer.from(t.before,"base64"));if("rename"===t.operation){if(!t.newPath)return"conflicted";const e=n(t.newPath);if(null===o&&e&&rf(e)===t.afterSha256)return"applied";if(null===e&&o&&rf(o)===i)return"undone"}else if("delete"===t.operation){if(null===o)return"applied";if(o&&rf(o)===i)return"undone"}else{if(o&&rf(o)===t.afterSha256)return"applied";if(null===o&&null===t.before||o&&rf(o)===i)return"undone"}return"conflicted"}catch{return"conflicted"}}return{list(e){const{root:n,grant:o}=a(e);if(!I(t))return{changes:[],total:0};const i=B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({...JSON.parse(W(ce(t,e),"utf8")),checkpointId:e.slice(0,-5)})).filter(e=>e.project===n&&e.chatId===o.chatId).sort((e,t)=>e.order&&t.order?BigInt(t.order)>BigInt(e.order)?1:BigInt(t.order)<BigInt(e.order)?-1:0:t.createdAt.localeCompare(e.createdAt));return{changes:i.slice(0,100).map(({path:e,checkpointId:t,turnId:o,createdAt:i,operation:r,newPath:a,...s})=>({path:e,checkpointId:t,turnId:o,createdAt:i,operation:null!=r?r:"write",...a?{newPath:a}:{},state:d(n,{...s,path:e,turnId:o,createdAt:i,operation:r,newPath:a})})),total:i.length}},stat(t){const n=e();if(!n)throw new Error("No connected local web project.");const o=A(n),i=s(o,t,!0);if(!I(i))return{path:t,exists:!1};const r=N(i).size;if(r>nf)throw new Error("File exceeds the 1 MiB edit limit.");const a=Gm(o,t,{maxBytes:nf});return Hm(a),{path:t,exists:!0,sha256:rf(a),size:r}},write(e,t){var o;const{root:i,grant:r}=a(t);if(!e||"string"!=typeof e.content)throw new Error("Text content is required.");const l=Buffer.from(e.content,"utf8");if(l.byteLength>nf||e.content.includes("\0"))throw new Error("Text file exceeds the 1 MiB limit or contains NUL.");const d=s(i,e.path,!0===e.create),m=I(d);if(!0===e.create&&m)throw new Error("File already exists.");if(!0!==e.create&&!m)throw new Error("File does not exist; use create.");const f=m?W(d):null;if(f&&u(f,e.expectedSha256),f&&rf(f)===rf(l))throw new Error("File already has this content; no edit was saved.");const h={project:i,path:pe(i,d),chatId:r.chatId,sessionId:r.sessionId,turnId:r.turnId,before:null!=(o=null==f?void 0:f.toString("base64"))?o:null,after:l.toString("base64"),afterSha256:rf(l),createdAt:(new Date).toISOString(),operation:"write"},g=p(h);try{if(s(i,e.path,!0===e.create),!0===e.create){if(I(d))throw new Error("The file was created since it was checked; check it again.")}else if(!I(d)||rf(W(d))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");c(d,l)}catch(e){throw G(g.file),e}return n(),{path:e.path,checkpointId:g.id,turnId:r.turnId,afterSha256:h.afterSha256}},delete(e,t){const{root:o,grant:i}=a(t),r=s(o,null==e?void 0:e.path,!1),c=W(r);u(c,e.expectedSha256);const l=p({project:o,path:pe(o,r),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:c.toString("base64"),after:null,afterSha256:null,createdAt:(new Date).toISOString(),operation:"delete"});try{if(s(o,e.path,!1),rf(W(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");G(r)}catch(e){throw G(l.file),e}return n(),{path:e.path,checkpointId:l.id,turnId:i.turnId,afterSha256:null}},rename(e,t){const{root:o,grant:i}=a(t),r=s(o,null==e?void 0:e.path,!1),c=s(o,null==e?void 0:e.newPath,!0);if(I(c))throw new Error("Destination file already exists.");const l=W(r);u(l,e.expectedSha256);const d={project:o,path:pe(o,r),newPath:pe(o,c),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:l.toString("base64"),after:l.toString("base64"),afterSha256:rf(l),createdAt:(new Date).toISOString(),operation:"rename"},m=p(d);try{if(s(o,e.path,!1),s(o,e.newPath,!0),I(c))throw new Error("Destination file already exists.");if(rf(W(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");O(r,c)}catch(e){throw G(m.file),e}return n(),{path:e.newPath,checkpointId:m.id,turnId:i.turnId,afterSha256:d.afterSha256}},undo(e,o){const{root:i,grant:r}=a(o);if(!e||"string"!=typeof e.checkpointId||!/^[a-f0-9-]{36}$/.test(e.checkpointId))throw new Error("Invalid checkpoint ID.");const p=ce(t,`${e.checkpointId}.json`),u=JSON.parse(W(p,"utf8"));if(u.project!==i||u.chatId!==r.chatId)throw new Error("Checkpoint belongs to another project or chat.");const d=s(i,u.path,!0);if("delete"===u.operation){var m;if(I(d))throw new Error("File changed after the AI edit; Undo would overwrite later work.");c(d,Buffer.from(null!=(m=u.before)?m:"","base64"))}else if("rename"===u.operation){if(!u.newPath)throw new Error("Invalid rename checkpoint.");const e=s(i,u.newPath,!1);if(I(d)||rf(W(e))!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");O(e,d)}else{const e=W(d);if(rf(e)!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");void 0===u.after&&(u.after=e.toString("base64"),function(e,t){const n=JSON.stringify(t);if(l()-N(e).size+Buffer.byteLength(n)>of)throw new Error("Checkpoint storage is full; no file was changed.");c(e,Buffer.from(n))}(p,u)),null===u.before?G(d):c(d,Buffer.from(u.before,"base64"))}return n(),{path:u.path,checkpointId:e.checkpointId,undone:!0}},redo(e,o){const{root:i,grant:r}=a(o);if(!e||"string"!=typeof e.checkpointId||!/^[a-f0-9-]{36}$/.test(e.checkpointId))throw new Error("Invalid checkpoint ID.");const l=ce(t,`${e.checkpointId}.json`),p=JSON.parse(W(l,"utf8"));if(p.project!==i||p.chatId!==r.chatId)throw new Error("Checkpoint belongs to another project or chat.");const u=s(i,p.path,!0);if("delete"===p.operation){var d;if(!I(u)||rf(W(u))!==rf(Buffer.from(null!=(d=p.before)?d:"","base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,!1),G(u)}else if("rename"===p.operation){var m;if(!p.newPath)throw new Error("Invalid rename checkpoint.");const e=s(i,p.newPath,!0);if(!I(u)||I(e)||rf(W(u))!==rf(Buffer.from(null!=(m=p.before)?m:"","base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,!1),s(i,p.newPath,!0),O(u,e)}else{if("string"!=typeof p.after||null===p.afterSha256)throw new Error("This checkpoint cannot be redone.");const e=Buffer.from(p.after,"base64");if(rf(e)!==p.afterSha256)throw new Error("Checkpoint content is damaged; Redo was refused.");if(null===p.before?I(u):!I(u)||rf(W(u))!==rf(Buffer.from(p.before,"base64")))throw new Error("File changed after Undo; Redo would overwrite later work.");s(i,p.path,null===p.before),c(u,e)}return n(),{path:"rename"===p.operation?p.newPath:p.path,checkpointId:e.checkpointId,redone:!0}},undoTurn(e,n){const{root:o,grant:i}=a(n);if(!e||"string"!=typeof e.turnId||!e.turnId||e.turnId.length>255)throw new Error("Valid turn ID is required.");if(!I(t))throw new Error("No checkpoints found for this turn.");const r=B(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({checkpoint:JSON.parse(W(ce(t,e),"utf8")),checkpointId:e.slice(0,-5)})).filter(t=>t.checkpoint.project===o&&t.checkpoint.chatId===i.chatId&&t.checkpoint.turnId===e.turnId);if(!r.length)throw new Error("No checkpoints found for this turn.");if(r.some(e=>!e.checkpoint.order||!/^\d+$/.test(e.checkpoint.order)))throw new Error("Older checkpoints cannot be undone as a turn; use local_files_undo for each file.");r.sort((e,t)=>{const n=BigInt(e.checkpoint.order),o=BigInt(t.checkpoint.order);return n<o?1:n>o?-1:0});const c=new Map,l=e=>{const t=s(o,e,!0);return"win32"===process.platform?t.toLowerCase():t},p=e=>{var t;const n=s(o,e,!0),i=l(e);if(c.has(i))return null!=(t=c.get(i))?t:null;const r=I(n)?W(n):null;return c.set(i,r),r};for(const{checkpoint:e}of r){const t=null===e.before?null:Buffer.from(e.before,"base64");if("rename"===e.operation){if(!e.newPath)throw new Error("Invalid rename checkpoint.");const n=p(e.path),o=p(e.newPath);if(null!==n||null===o||rf(o)!==e.afterSha256)throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t),c.set(l(e.newPath),null)}else if("delete"===e.operation){if(null!==p(e.path))throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t)}else{const n=p(e.path);if(null===n||rf(n)!==e.afterSha256)throw new Error("File changed after this turn; no file was undone.");c.set(l(e.path),t)}}const u=[];try{for(const{checkpointId:e}of r)this.undo({checkpointId:e},n),u.push(e)}catch(e){const t=[];for(const e of[...u].reverse())try{this.redo({checkpointId:e},n)}catch(e){t.push(e)}if(t.length)throw new AggregateError([e,...t],"Turn Undo stopped and rollback failed; inspect the listed checkpoints before editing again.");throw new Error("Turn Undo stopped; earlier changes were rolled back.",{cause:e})}return{turnId:e.turnId,checkpointIds:u,undone:!0}}}}(()=>{var e;return null==(e=Ff())?void 0:e.web_location},void 0,()=>Af.markStale()),Rf=function(e=ce(oe(),".needle","cli","ai-observations")){function t(t){if(!t||"string"!=typeof t.root||!t.root||"string"!=typeof t.path||!t.path||"string"!=typeof t.chatId||!t.chatId||t.path.includes("\0")||de(t.path)||fe.isAbsolute(t.path)||he.isAbsolute(t.path))throw new Error("A project-relative file path and chat are required.");const n=A(t.root),o=le(n,t.path);if(Wm(n,t.path,{allowMissing:!0}),!o.startsWith(n+me))throw new Error("File path escapes the project.");const i=pe(n,o).split(me).join("/");return{project:n,target:o,path:i,file:ce(e,sf(n),sf(t.chatId),`${sf(i)}.json`)}}function n(e){if(!I(e.target))return null;if(N(Wm(e.project,e.target).path).size>af)return{unsupported:"File exceeds the 1 MiB observation limit."};const t=Gm(e.project,e.target,{maxBytes:af}),n=t.toString("utf8");if(n.includes("\0")||!Buffer.from(n,"utf8").every((e,n)=>t[n]===e)||Buffer.byteLength(n,"utf8")!==t.length)return{unsupported:"Only UTF-8 text files can be observed."};const o=n.split("\n");return o.length>5e3?{unsupported:"File exceeds the 5,000-line observation limit."}:{content:t,lines:Jm(t).split("\n"),hashes:o.map(sf),fileSha256:sf(t)}}function o(e){if(!I(e.file))return null;const t=JSON.parse(W(e.file,"utf8"));if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Stored file observation is damaged.");const n=t;if(1!==n.version||n.project!==e.project||n.path!==e.path||!Array.isArray(n.lineHashes)||!n.lineHashes.every(e=>"string"==typeof e&&/^[a-f0-9]{64}$/.test(e))||"string"!=typeof n.fileSha256||!/^[a-f0-9]{64}$/.test(n.fileSha256)||"string"!=typeof n.chatId||"string"!=typeof n.observedAt)throw new Error("Stored file observation is damaged.");return n}function r(t,n,o){if("unsupported"in n)return{status:"unsupported",reason:n.unsupported};const r={version:1,project:t.project,path:t.path,chatId:o,observedAt:(new Date).toISOString(),fileSha256:n.fileSha256,lineHashes:n.hashes};C(ce(e,sf(t.project),sf(o)),{recursive:!0,mode:448});const a=`${t.file}.${i()}.tmp`;try{H(a,JSON.stringify(r),{flag:"wx",mode:384}),O(a,t.file)}finally{I(a)&&G(a)}return{status:"saved",observedAt:r.observedAt,sha256:r.fileSha256}}return{observe(e){const i=t(e),a=n(i);if(!a)throw new Error("File does not exist.");if("unsupported"in a)return{status:"unsupported",reason:a.unsupported};const s=o(i);return s?{status:"existing",observedAt:s.observedAt,sha256:s.fileSha256}:r(i,a,e.chatId)},snapshot(e){const o=t(e),i=n(o);if(!i)throw new Error("File does not exist.");return r(o,i,e.chatId)},diff(e){const i=t(e),r=o(i);if(!r)return{status:"no_baseline",path:i.path};const a=n(i);if(!a)return{status:"deleted",path:i.path,observedAt:r.observedAt};if("unsupported"in a)return{status:"unsupported",path:i.path,reason:a.unsupported};if(r.fileSha256===a.fileSha256)return{status:"unchanged",path:i.path,observedAt:r.observedAt,sha256:a.fileSha256};const s=function(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;let o=e.length,i=t.length;for(;o>n&&i>n&&e[o-1]===t[i-1];)o--,i--;if(n===o&&n===i)return[];const r=new Map;for(let t=n;t<o;t++){const n=r.get(e[t]);n?n.count++:r.set(e[t],{index:t,count:1})}const a=new Map;for(let e=n;e<i;e++){var s;a.set(t[e],(null!=(s=a.get(t[e]))?s:0)+1)}const c=[];for(let e=n;e<i;e++){const n=r.get(t[e]);1===(null==n?void 0:n.count)&&1===a.get(t[e])&&c.push({old:n.index,current:e})}const l=[],p=[];for(let e=0;e<c.length;e++){let t=0,n=l.length;for(;t<n;){const o=t+n>>1;c[l[o]].old<c[e].old?t=o+1:n=o}p[e]=t?l[t-1]:-1,l[t]=e}const u=[];for(let e=l.length?l[l.length-1]:-1;e>=0;e=p[e])u.push(c[e]);u.reverse();const d=[];let m=n,f=n;for(const n of[...u,{old:o,current:i}]){let o=n.old,i=n.current;for(;m<o&&f<i&&e[m]===t[f];)m++,f++;for(;o>m&&i>f&&e[o-1]===t[i-1];)o--,i--;m===o&&f===i||d.push({oldStart:m,oldEnd:o,newStart:f,newEnd:i}),m=n.old+1,f=n.current+1}return d}(r.lineHashes,a.hashes);let c=80;const l=s.slice(0,20).map(e=>{const t=Math.min(e.newEnd-e.newStart,c);return c-=t,{before:{start:e.oldStart+1,count:e.oldEnd-e.oldStart},after:{start:e.newStart+1,count:e.newEnd-e.newStart},lines:a.lines.slice(e.newStart,e.newStart+t).map(e=>e.slice(0,300)),omittedLines:e.newEnd-e.newStart-t}});return{status:"changed",path:i.path,observedAt:r.observedAt,beforeSha256:r.fileSha256,afterSha256:a.fileSha256,beforeLineCount:r.lineHashes.length,afterLineCount:a.hashes.length,hunks:l,totalHunks:s.length,truncated:s.length>l.length,detail:s.length?void 0:"File bytes changed without a text-line change (for example line endings)."}}}}(),Pf=function(e,t=x){return async function(n){const o=e(),i="web"===n.project?null==o?void 0:o.web_location:"editor"===n.project?null==o?void 0:o.project_location:null;if(!i)throw new Error("The selected local project is unavailable.");if("string"!=typeof n.path||!n.path.trim()||de(n.path)||n.path.includes("\0"))throw new Error("Use a nonempty project-relative path.");const r=A.native(i),a=le(r,n.path),s=pe(r,a);if(".."===s||s.startsWith(`..${me}`)||de(s))throw new Error("File path is outside the selected project.");const c=A.native(a),l=pe(r,c);if(".."===l||l.startsWith(`..${me}`)||de(l))throw new Error("File path is outside the selected project.");const p=N(c);if(!p.isFile()&&!p.isDirectory())throw new Error("The selected path is not a file or directory.");if(cf.has(ae(c).toLowerCase()))throw new Error("Opening executable file types is not supported.");return await t(c),{opened:!0,project:n.project,path:pe(r,c)||"."}}}(Ff),Uf=function(e){const{getProject:t,getHome:n=oe,run:o=Tf,commandsEnabled:r=(()=>!hf()),onFailure:a,onCreated:s,onApprovedProject:c,now:l=Date.now,getProcessIdentity:p=yf}=e,u=function(e=ce(oe(),".needle","cli","ai-jobs"),t=Date.now){const n=t=>{if(!bf.test(t))throw new Error("Invalid project job ID.");return ce(e,`${t}.json`)};return{runtimeFile:t=>(n(t),ce(e,`${t}.runtime.json`)),runtime(e){const t=this.runtimeFile(e);if(!I(t))return;const n=JSON.parse(W(t,"utf8"));if(!n||"object"!=typeof n||Array.isArray(n))throw new Error("Invalid local dev runtime state.");const o=n;if(!["running","completed","failed","canceled"].includes(String(o.status))||void 0!==o.url&&"string"!=typeof o.url||void 0!==o.exitCode&&!Number.isSafeInteger(o.exitCode)||void 0!==o.error&&"string"!=typeof o.error)throw new Error("Invalid local dev runtime state.");return o},save(t){const o=n(t.jobId);C(e,{recursive:!0,mode:448});const r=ce(e,`${t.jobId}.${i()}.tmp`);try{H(r,JSON.stringify(t),{flag:"wx",mode:384}),O(r,o)}finally{I(r)&&G(r)}},get(e){const o=n(e);if(!I(o))return;const i=JSON.parse(W(o,"utf8"));if(!i||"object"!=typeof i||Array.isArray(i))throw new Error("Invalid stored project job.");const r=i;if(r.jobId!==e||"string"!=typeof r.chatId||"string"!=typeof r.operation||void 0!==r.project&&"string"!=typeof r.project||void 0!==r.workingDirectory&&"string"!=typeof r.workingDirectory||void 0!==r.startedAt&&!Number.isFinite(r.startedAt)||void 0!==r.pid&&(!Number.isSafeInteger(r.pid)||Number(r.pid)<1)||void 0!==r.processIdentity&&"string"!=typeof r.processIdentity||!Number.isFinite(r.createdAt)||!Number.isFinite(r.updatedAt)||"string"!=typeof r.output||r.output.length>8e3||!["running","completed","failed","canceled"].includes(String(r.status)))throw new Error("Invalid stored project job.");const a=r;if(!("running"!==a.status&&t()-a.updatedAt>1728e5))return a;{G(o);const t=this.runtimeFile(e);I(t)&&G(t)}},list(){return I(e)?B(e).filter(e=>bf.test(e.slice(0,-5))&&e.endsWith(".json")).map(e=>{try{return this.get(e.slice(0,-5))}catch(t){return void console.warn(`Could not read local project job ${e}: ${t instanceof Error?t.message:String(t)}`)}}).filter(e=>!!e):[]},remove(e){const t=n(e);I(t)&&G(t);const o=this.runtimeFile(e);I(o)&&G(o)}}}(ce(n(),".needle","cli","ai-jobs"),l),d=new Map,m=new Map;function f(e){const{controller:t,...n}=e;u.save(n)}function h(e){if("failed"!==e.status||!a)return;const{controller:t,...n}=e;try{a(n)}catch(e){console.error(`Could not record local project job failure: ${e instanceof Error?e.message:String(e)}`)}}function g(){for(const[e,t]of d)l()-t.createdAt>3e5&&d.delete(e);for(const[e,t]of m)"running"!==t.status&&l()-t.updatedAt>36e5&&m.delete(e)}function v(e){const o=kf(e.request,t(),n());if(JSON.stringify({...o,request:null})!==JSON.stringify({...e,request:null,planId:void 0,chatId:void 0,createdAt:void 0}))throw new Error("The project command or its inputs changed since approval. Plan it again.")}function b(e){if("running"!==e.status)return e;const t="dev"===e.operation?u.runtime(e.jobId):void 0;return null!=t&&t.url&&(e.url=t.url),t&&"running"!==t.status?(e.status=t.status,e.exitCode=t.exitCode,t.error&&(e.output=Dm(t.error).slice(-8e3))):"dev"===e.operation&&e.pid&&e.processIdentity&&p(e.pid)===e.processIdentity||(e.status="failed",e.output=`${e.output}\nThe CLI restarted and the original project process is no longer running or cannot be verified.`.trim().slice(-8e3)),"running"!==e.status&&(e.updatedAt=l(),u.save(e)),e}function y(e){if(e)return[...m.values()].find(t=>"dev"===t.operation&&t.project===e&&"running"===t.status)||u.list().map(b).find(t=>"dev"===t.operation&&t.project===e&&"running"===t.status)}function x(){for(const e of u.list())b(e)}x();const w=setInterval(x,36e5);return w.unref(),{plan(e,o){if(g(),!o)throw new Error("A Cloud chat is required to plan an AI project command.");const r={...kf(e,t(),n()),planId:i(),chatId:o,createdAt:l()},a="dev"===r.operation?y(r.project):void 0;if(a)throw new Error(`A dev server for this project is already running (job ID ${a.jobId}). Check its status or cancel it before starting another.`);return d.set(r.planId,r),r},getPlan(e,t){g();const n=d.get(e);if(!n||n.chatId!==t)throw new Error("This project command plan does not belong to this chat or expired.");return v(n),n},async start(e,t){g();const n=d.get(e);if(!n)throw new Error("This project command plan expired or was already used.");if(!t||t.chatId!==n.chatId||t.planId!==e)throw new Error("Exact Cloud approval is required for this project command.");if(!r())throw new Error("AI project commands are disabled in local Needle CLI settings.");v(n);const a="dev"===n.operation?y(n.project):void 0;if(a)throw new Error(`A dev server for this project is already running (job ID ${a.jobId}). Check its status or cancel it before starting another.`);n.customProject&&n.project&&(null==c||c(n.project)),d.delete(e);const p={jobId:i(),chatId:n.chatId,operation:n.operation,project:n.project||n.destination,workingDirectory:n.project||ue(n.destination),startedAt:l(),createdAt:l(),updatedAt:l(),status:"running",output:"",controller:new AbortController};return m.set(p.jobId,p),f(p),"dev"===n.operation&&(n.runtimeFile=u.runtimeFile(p.jobId)),Promise.resolve().then(()=>o(n,p.controller.signal,e=>{"running"===p.status&&(void 0!==e.output&&(p.output=Dm(e.output).slice(-8e3)),void 0!==e.url&&(p.url=e.url),void 0!==e.browserOpened&&(p.browserOpened=e.browserOpened),void 0!==e.browserError&&(p.browserError=e.browserError),"dev"===n.operation&&void 0!==e.pid&&e.processIdentity&&(p.pid=e.pid,p.processIdentity=e.processIdentity,void 0!==e.startedAt&&(p.startedAt=e.startedAt)),p.updatedAt=l(),f(p))})).then(e=>{p.exitCode=e.exitCode,p.output=Dm(String(e.output||"")).slice(-8e3),"canceled"!==p.status&&0===e.exitCode&&"create"===n.operation&&n.destination&&(null==s||s(n.destination)),"canceled"!==p.status&&(p.status=0===e.exitCode?"completed":"failed"),p.updatedAt=l(),f(p),h(p)}).catch(e=>{const t=p.controller.signal.aborted;p.controller.abort(),p.output=Dm(e instanceof Error?e.message:String(e)).slice(-8e3),p.status=t?"canceled":"failed",p.updatedAt=l(),f(p),h(p)}),{jobId:p.jobId,status:"running"}},status(e,t){g();const n=m.get(e)||u.get(e);if(!n||n.chatId!==t)throw new Error("This project job does not belong to this chat.");const o=m.get(e);if(o){const{controller:e,...t}=o;return t}return b(n)},async cancel(e,t){const n=m.get(e),o=n?void 0:u.get(e),i=n||o&&b(o);if(!i||i.chatId!==t)throw new Error("This project job does not belong to this chat.");if("running"!==i.status)return{jobId:e,canceled:!1};if(!n){if("dev"!==i.operation)throw new Error("Only supervised dev jobs can be stopped after a CLI restart.");H(`${u.runtimeFile(e)}.cancel`,"",{flag:"w",mode:384});const t=Date.now()+1e4;for(;Date.now()<t;){const t=b(i);if("running"!==t.status)return{jobId:e,canceled:"canceled"===t.status};await new Promise(e=>setTimeout(e,100))}throw new Error("The dev server stop was requested, but the supervisor did not confirm it within 10 seconds. Check the job status.")}return n.controller.abort(),i.status="canceled",i.updatedAt=l(),f(n),{jobId:e,canceled:!0}},dispose(){clearInterval(w);for(const e of m.values())"running"===e.status&&"dev"!==e.operation&&(e.controller.abort(),e.status="canceled",e.updatedAt=l(),f(e))}}}({getProject:()=>{var e;return null==(e=Ff())?void 0:e.web_location},onCreated:gm,onApprovedProject:gm,onFailure:e=>{var t;return du(`[AI project] ${e.operation} failed job=${e.jobId} exit=${null!=(t=e.exitCode)?t:"error"} output=${e.output.replace(/\s+/g," ").slice(0,700)}`)}});function Lf(e){if(null==e||!e.editGrant)throw new Error("Local file edit approval is required.");if(ff())throw new Error("AI file edits are disabled in local Needle CLI settings.");return e.editGrant}function zf(e={}){Of({name:"local_files_editor_log_path",description:"Get the filepath to the editor log file on disk (this may be Unity or Blender)",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];if(null!=e&&e.log_location){const n=p(e.log_location).mtime;t.content.push({type:"text",text:`${e.log_location} (last modified: ${n.toLocaleString()})`})}else{let n="No recent project with known log location known.";e&&(n+=" Recent project is "+(null==e?void 0:e.project_location)),t.content.push({type:"text",text:n})}}return t},{source:"cli"},()=>{}),Of({name:"local_files_editor_project_path",description:"Get the filepath to the currently opened project in the editor (this may be Unity or Blender)",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];t.content.push(null!=e&&e.project_location?{type:"text",text:e.project_location}:{type:"text",text:"No recent project with known project location known."})}return t},{source:"cli"},()=>{}),Of({name:"local_files_editor_scene_path",description:"Get the filepath to the currently opened scene in the editor (Unity or Blender). Use this to find out which scene the user is working on.",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=dm();if(n){const e=null==n?void 0:n.entries.sort((e,t)=>t.last_accessed-e.last_accessed)[0];t.content.push(null!=e&&e.scene_location?{type:"text",text:e.scene_location}:{type:"text",text:"No recent project with known scene location known."})}return t},{source:"cli"},()=>{}),Of({name:"local_files_web_project_path",description:"Get the filepath to the selected Needle Engine web project. Unity-generated web projects may validly live inside the Unity project's Library/Needle directory; do not treat that location alone as a misconfiguration. Use this directory as the web-project root.",inputSchema:{type:"object",properties:{},additionalProperties:!1,required:[]}},async e=>{const t={content:[]},n=Ff();return t.content.push(null!=n&&n.web_location?{type:"text",text:_(n.web_location)}:{type:"text",text:"No selected web project is known."}),t},{source:"cli"},()=>{}),Of({name:"local_files_diff",description:"Compare a local project text file with the first version observed by this chat. local_files_read saves a hash-only baseline on the first read; later reads do not replace it. Returns changed line ranges and bounded current lines, never removed text or who changed it. If no baseline exists, read the file first. Use mode=reset only after reviewing changes to start a new baseline. Works for web and editor project files.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path relative to the connected web or editor project, or an absolute path within it."},mode:{type:"string",enum:["compare","reset"],description:"Compare with the first observed version (default), or replace that version with the current file."}},required:["path"],additionalProperties:!1}},async(e,t)=>{var n;const o=Bf(e.path);if(!o)throw new Error("Path is outside the connected project.");const i={root:o.root,path:j(o.root,o.resolved),chatId:null!=(n=null==t?void 0:t.chatId)?n:"local-mcp"},r="reset"===e.mode?Rf.snapshot(i):Rf.diff(i);return{content:[{type:"text",text:JSON.stringify(r)}]}},{source:"cli"},()=>{}),Of({name:"local_files_open",description:'Open an existing file or directory in the connected local web or editor project using the operating system default app. Directories open in the file manager; use path="." for the project root. Use a project-relative path and select project="web" or "editor". This affects the user desktop. It does not read or edit files. Executable file types and paths outside the selected project are refused.',inputSchema:{type:"object",properties:{project:{type:"string",enum:["web","editor"]},path:{type:"string"}},required:["project","path"],additionalProperties:!1}},async e=>({content:[{type:"text",text:JSON.stringify(await Pf(e))}]}),{source:"cli"},()=>{}),Of({name:"local_files_read",description:"Read a file from the user's local project on disk (editor project or web project). The path must be relative to the project root or an absolute path inside the project. Sensitive files, including .env variants and private keys, are refused. Recognizable secrets are redacted before filtering or selecting lines. UTF-8 files are limited to 8 MiB. Returns the file contents (or a portion if offset/limit are specified). Use 'filter' to search for specific terms within the file.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path (relative to project root, or absolute within the project)"},offset:{type:"number",description:"Line number to start reading from (1-based, default: 1). In filter mode: number of matches to skip."},limit:{type:"number",description:"Maximum number of lines to return (default: 200, max: 1000). In filter mode: max matches to return."},filter:{type:"string",description:'Regex to search for in the file (case-insensitive, e.g. "error|warning"). Falls back to a literal substring match if the pattern isn\'t valid regex. Returns matching lines with line numbers instead of sequential content.'}},additionalProperties:!1,required:["path"]}},async(e,t)=>{const n=Bf(e.path);if(!n)return{content:[{type:"text",text:"Error: path is outside the project directory."}]};try{const i=p(n.resolved).mtime.toISOString(),r=Vm(n.root,n.resolved).text.split("\n");let a="";try{var o;const e=Rf.observe({root:n.root,path:j(n.root,n.resolved),chatId:null!=(o=null==t?void 0:t.chatId)?o:"local-mcp"});a="unsupported"===e.status?`\nChange baseline unavailable: ${e.reason}`:`\nChange baseline: ${"saved"===e.status?"saved":"kept from first read"}. Use local_files_diff to compare later changes.`}catch(e){console.error("[MCP] Could not observe local file changes",e),a=`\nChange baseline unavailable: ${e instanceof Error?e.message:"unknown error"}`}if(e.filter){const t=$f(e.filter),o=[];for(let e=0;e<r.length;e++)t.test(r[e])&&o.push(`${e+1}: ${r[e]}`);const s=o.length,c=Math.max(0,e.offset||0),l=Math.min(Math.max(e.limit||200,1),1e3),p=o.slice(c,c+l);return{content:[{type:"text",text:`File: ${n.resolved} (modified: ${i}) — filter="${e.filter}" (${t.mode}) → ${s} matches (showing ${c+1}-${c+p.length}) in ${r.length} lines`+a+"\n"+p.join("\n")}]}}const s=Math.max(1,e.offset||1),c=Math.min(e.limit||200,1e3),l=r.slice(s-1,s-1+c),u=l.map((e,t)=>`${s+t}: ${e}`).join("\n");return{content:[{type:"text",text:`File: ${n.resolved} (${r.length} lines, modified: ${i}, showing ${s}-${s+l.length-1})`+a+"\n"+u}]}}catch(e){return{content:[{type:"text",text:`Error reading file: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),Of({name:"local_files_grep",description:"Search for a pattern in the user's local project files on disk (editor project and web project) using grep. Searches sanitized UTF-8 text; sensitive files, links, hidden directories and node_modules are skipped. Reports omitted entries and search limits. Returns matching lines with file paths and line numbers. Note: runtime-only things (e.g. node-material shaders) have no source files — read those with the inspector_* tools instead.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regular expression)"},glob:{type:"string",description:"File glob filter, e.g. '*.ts' or '*.cs' (optional)"},max_results:{type:"number",description:"Maximum number of matching lines to return (default: 50)"}},additionalProperties:!1,required:["pattern"]}},async e=>{const t=qf();if(0===t.length)return{content:[{type:"text",text:"Error: no active project found."}]};const n=Math.min(Math.max(Math.floor(e.max_results||50),1),200),o=t.map(t=>Ym(t,{pattern:e.pattern,glob:e.glob,maxResults:n})),i=o.flatMap(e=>e.lines),r=`\nOmitted ${o.reduce((e,t)=>e+t.omitted,0)} sensitive, unsupported or excluded entries.${o.some(e=>e.limited)?" Search stopped at the file, byte, depth or time limit.":""}`;return{content:[{type:"text",text:(i.length?`Found ${i.length} matches:\n`+i.slice(0,n).join("\n"):"No matches found.")+r}]}},{source:"cli"},()=>{}),Of({name:"local_files_list",description:"List files in the user's local project directories on disk matching an optional glob pattern. A list is shallow by default: files in subdirectories are NOT included. When checking whether a file exists anywhere below a folder, use recursive=true or provide its exact subdirectory in path. By default searches both the editor project (Unity/Blender) and the web project. Use the 'project' parameter to target a specific one. Results are prefixed with <web_project>/..., <unity>/..., or <blender>/... so you know which root each file belongs to. Do not conclude that a file is absent from a project based on a shallow listing.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Project-relative subdirectory to list (default: root). Absolute paths, including paths to a different project, are not accepted."},pattern:{type:"string",description:"Glob pattern to filter files, e.g. '*.ts' or '*.glb'. Supports multiple patterns separated by '|', e.g. '*.gltf|*.glb' (optional)"},recursive:{type:"boolean",description:"Set true to include files in all subdirectories. Default false lists only files directly in path; use true before claiming a nested file is absent."},project:{type:"string",enum:["web","editor"],description:"Which project root to search: 'web' for the Needle Engine web project (use this for exported assets, source files, node_modules), 'editor' for the Unity/Blender project. Omit to search both."}},additionalProperties:!1,required:[]}},async e=>{if(void 0!==e.path&&("string"!=typeof e.path||k(e.path)))return{content:[{type:"text",text:"Error: local_files_list requires a project-relative path. It cannot list an absolute path outside the connected project."}]};const t=Ff();if(!t)return{content:[{type:"text",text:"Error: no active project found."}]};const n="blender"===t.editor?"<blender>":"unity"===t.editor?"<unity>":"<editor_project>",o=[];if(e.project&&"editor"!==e.project||!t.project_location||o.push({root:_(t.project_location),label:n}),e.project&&"web"!==e.project||!t.web_location||o.push({root:_(t.web_location),label:"<web_project>"}),0===o.length)return{content:[{type:"text",text:"Error: no active project found."}]};const i=[],r=[];for(const{root:t,label:n}of o){const o=Df(e.path||".",t);if(o)try{var a;e.recursive||r.push(...d(o,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"node_modules"!==e.name).map(e=>`${n}/${j(t,S(o,e.name))}`));const s=Wf(o,t,null!=(a=e.recursive)&&a,e.pattern,0);i.push(...s.map(e=>({file:e,root:t,label:n})))}catch(e){throw new Error(`Could not list project files: ${e instanceof Error?e.message:String(e)}`)}}const s=r.length>0?`\nShallow listing: subdirectories were not searched (${r.slice(0,12).join(", ")}${r.length>12?", ...":""}). To search nested files, call local_files_list with recursive=true or set path to the subdirectory.`:"";if(0===i.length)return{content:[{type:"text",text:`No files found directly in the selected path.${o.length>0?`\nSearched in:\n${o.map(e=>`${e.label} → ${e.root}`).join("\n")}`:"\nNo project directories available to search."}${s}`}]};const c=i.slice(0,500).map(e=>`${e.label}/${j(e.root,e.file)}`);return{content:[{type:"text",text:`Found ${i.length} files${i.length>500?" (showing first 500)":""}:\n`+c.join("\n")+s}]}},{source:"cli"},()=>{}),Of({name:"local_files_read_editor_log",description:"Read or search the Unity or Blender editor log file. By default reads the last N lines. Use the 'filter' parameter to search for specific terms (e.g. error messages, warnings, component names) across the entire log.",inputSchema:{type:"object",properties:{lines:{type:"number",description:"Number of lines to read from the end of the log (default: 100, max: 500). Ignored when filter is set."},filter:{type:"string",description:'Regex to search for in the log (case-insensitive, e.g. "error|exception|warning"). Falls back to a literal substring match if the pattern isn\'t valid regex. Returns all matching lines from the entire log instead of just the tail.'},offset:{type:"number",description:"Number of matching results to skip from the start (default: 0). Only used with filter."},limit:{type:"number",description:"Maximum number of matching results to return (default: 200, max: 500). Only used with filter."}},additionalProperties:!1,required:[]}},async e=>{const t=Ff();var n;if(null==t||!t.log_location)return mu(`read_editor_log: no editor log file known (project: ${null!=(n=null==t?void 0:t.project_location)?n:"none"})`),{content:[{type:"text",text:"Error: no editor log file known. Is a Unity or Blender project open?"}]};try{if(!t.log_location.toLowerCase().endsWith(".log"))throw new Error("Only the connected editor log can be read.");const n=Vm(ue(t.log_location),se(t.log_location),{maxBytes:67108864,allowPrivateKeys:!0}).text.split("\n");let o,i;if(e.filter){const t=$f(e.filter);o=[];for(let e=0;e<n.length;e++)t.test(n[e])&&o.push(`L${e+1}: ${n[e]}`);const r=o.length,a=Math.max(0,e.offset||0),s=Math.min(Math.max(e.limit||200,1),500);o=o.slice(a,a+s),i=`filter="${e.filter}" (${t.mode}) → ${r} matches (showing ${a+1}-${a+o.length}) in ${n.length} total lines`}else{const t=Math.min(Math.max(e.lines||100,1),500);o=n.slice(-t),i=`last ${t} of ${n.length} lines`}const r="unity"===t.editor?function(e){const t=[],n=new Map;let o=!1,i=0;for(const r of e){if(/^\s+at\s/.test(r)||/^\s*(UnityEngine\.|System\.|Unity\.)/.test(r)||/^\s+\w+[\w.<>]+\s*\(/.test(r)){o||(o=!0,i=0),i++,i<=3?t.push(r):4===i&&t.push(" ... (stack trace truncated)");continue}if(o=!1,i=0,!r.trim())continue;const e=n.get(r)||0;if(n.set(r,e+1),0===e)t.push(r);else if(1===e)t.push(` [repeated ${e+1}x] ${r}`);else{const n=t.length-1;n>=0&&t[n].startsWith(" [repeated")&&(t[n]=` [repeated ${e+1}x] ${r}`)}}return t}(o):o,a=5e4;let s=r.join("\n"),c="";if(s.length>a){s=s.substring(s.length-a);const e=s.indexOf("\n");e>0&&(s=s.substring(e+1)),c=" (output truncated to last ~50KB)"}return{content:[{type:"text",text:`Editor log: ${t.log_location} (${i}, ${r.length} after processing, editor: ${t.editor})${c}:\n`+s}]}}catch(e){return{content:[{type:"text",text:`Error reading log: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),Of({name:"local_files_read_gltf",description:"Read and summarize a glTF or GLB file from the user's local project on disk. Without a query, returns a structured summary including nodes, meshes, materials, animations, extensions, and compression/optimization hints. Use 'query' to drill into specific parts using JSON pointer paths. Use '*' as a wildcard for array indices or object keys. For GLB files, extracts the JSON chunk and skips binary data.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to a .gltf or .glb file (relative to project root, or absolute path)"},query:{type:"string",description:"JSON pointer path to extract a specific part of the glTF, e.g. '/nodes/0', '/materials', '/extensions/NEEDLE_progressive', '/materials/*/extensions'. Use '*' as a wildcard for array indices or object keys."}},additionalProperties:!1,required:["path"]}},async e=>{let t=Bf(e.path);if(!t)return{content:[{type:"text",text:"Error: path is outside the project directory."}]};if(!l(t.resolved))return{content:[{type:"text",text:`Error: file not found: ${t.resolved}`}]};try{const n=function(e,t){const n=e.toLowerCase();if(n.endsWith(".gltf")){const n=Vm(t,e).text;return JSON.parse(n)}if(n.endsWith(".glb")){const n=Gm(t,e,{maxBytes:20,range:{offset:0,length:20}});if(n.length<20)return null;if(1179937895!==n.readUInt32LE(0))return null;const o=n.readUInt32LE(12);if(1313821514!==n.readUInt32LE(16))return null;const i=Gm(t,e,{maxBytes:67108864,range:{offset:20,length:o}}).toString("utf-8"),r=Lm(JSON.parse(i));if(!r||"object"!=typeof r||Array.isArray(r))throw new Error("glTF JSON must be an object.");return r}return null}(t.resolved,t.root);if(!n)return{content:[{type:"text",text:"Error: could not parse glTF/GLB file."}]};const o=5e4;if(e.query){const i=Mf(n,e.query.replace(/^\//,"").split("/"));if(void 0===i)return{content:[{type:"text",text:`No data found at pointer: ${e.query}`}]};let r=JSON.stringify(i),a=!1;return r.length>o&&(r=r.substring(0,o),a=!0),{content:[{type:"text",text:`${e.query} in ${t.resolved}`+(a?` (truncated to ${o} chars)`:"")+"\n"+r}]}}let i=function(e,t){var n,o,i,r,a,s,c,l,p,u,d,m,f;const h=[`glTF: ${t}`];if(e.asset){const t=[];e.asset.version&&t.push(`v${e.asset.version}`),e.asset.generator&&t.push(e.asset.generator),h.push(`Asset: ${t.join(", ")}`)}if(null!=(n=e.extensionsUsed)&&n.length&&h.push(`Extensions used: ${e.extensionsUsed.join(", ")}`),null!=(o=e.extensionsRequired)&&o.length&&h.push(`Extensions required: ${e.extensionsRequired.join(", ")}`),null!=(i=e.scenes)&&i.length&&h.push(`Scenes: ${e.scenes.length}${void 0!==e.scene?` (default: ${e.scene})`:""}`),null!=(r=e.nodes)&&r.length){var g,v,b;h.push(`\nNodes (${e.nodes.length}):`);const t=null!=(g=null==(v=e.scenes)||null==(v=v[null!=(b=e.scene)?b:0])?void 0:v.nodes)?g:[],n=new Set,o=(t,i)=>{if(i>6||n.has(t))return;n.add(t);const r=e.nodes[t];if(!r)return;const a=" ".repeat(i),s=[];if(void 0!==r.mesh&&s.push(`mesh:${r.mesh}`),void 0!==r.camera&&s.push(`camera:${r.camera}`),void 0!==r.skin&&s.push(`skin:${r.skin}`),r.extensions&&s.push(`ext:[${Object.keys(r.extensions).join(",")}]`),h.push(`${a}- ${r.name||`node_${t}`}${s.length?` (${s.join(", ")})`:""}`),r.children)for(const e of r.children)o(e,i+1)};for(const e of t)o(e,1);n.size<e.nodes.length&&n.size>0&&h.push(` ... and ${e.nodes.length-n.size} more nodes`)}if(null!=(a=e.meshes)&&a.length){h.push(`\nMeshes (${e.meshes.length}):`);for(const t of e.meshes.slice(0,30)){var y,x;const e=null!=(y=null==(x=t.primitives)?void 0:x.length)?y:0;h.push(` - ${t.name||"(unnamed)"} (${e} primitive${1!==e?"s":""})`)}e.meshes.length>30&&h.push(` ... and ${e.meshes.length-30} more`)}if(null!=(s=e.materials)&&s.length){h.push(`\nMaterials (${e.materials.length}):`);for(const t of e.materials.slice(0,30)){const e=t.name||"(unnamed)",n=[];t.pbrMetallicRoughness&&n.push("PBR"),t.alphaMode&&"OPAQUE"!==t.alphaMode&&n.push(t.alphaMode),t.doubleSided&&n.push("doubleSided"),t.extensions&&n.push(`ext:[${Object.keys(t.extensions).join(",")}]`),h.push(` - ${e}${n.length?` (${n.join(", ")})`:""}`)}e.materials.length>30&&h.push(` ... and ${e.materials.length-30} more`)}if(null!=(c=e.textures)&&c.length&&h.push(`Textures: ${e.textures.length}`),null!=(l=e.images)&&l.length&&h.push(`Images: ${e.images.length}`),null!=(p=e.animations)&&p.length){h.push(`\nAnimations (${e.animations.length}):`);for(const t of e.animations.slice(0,20)){var w,_;const e=null!=(w=null==(_=t.channels)?void 0:_.length)?w:0;h.push(` - ${t.name||"(unnamed)"} (${e} channel${1!==e?"s":""})`)}e.animations.length>20&&h.push(` ... and ${e.animations.length-20} more`)}if(null!=(u=e.skins)&&u.length){h.push(`\nSkins (${e.skins.length}):`);for(const t of e.skins.slice(0,10)){var S,j;h.push(` - ${t.name||"(unnamed)"} (${null!=(S=null==(j=t.joints)?void 0:j.length)?S:0} joints)`)}}if(null!=(d=e.cameras)&&d.length){h.push(`\nCameras (${e.cameras.length}):`);for(const t of e.cameras)h.push(` - ${t.name||"(unnamed)"} (${t.type})`)}if(null!=(m=e.buffers)&&m.length){const t=e.buffers.reduce((e,t)=>e+(t.byteLength||0),0);h.push(`\nBuffers: ${e.buffers.length} (${(t/1024/1024).toFixed(1)} MB total)`)}return null!=(f=e.accessors)&&f.length&&h.push(`Accessors: ${e.accessors.length}`),h.join("\n")}(n,t.resolved);return i.length>o&&(i=i.substring(0,o)+"\n... (truncated)"),{content:[{type:"text",text:i}]}}catch(e){return{content:[{type:"text",text:`Error reading glTF: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),function(){const e=e=>({content:[{type:"text",text:JSON.stringify(e)}]});Of({name:"local_files_resolve_url",description:"Find the working directory of the process serving a localhost URL, including a server started by another app or by the user. Returns the listening PID and working directory, or an explicit reason when unavailable. The URL path is not assumed to be a file path. Works only for a server running on the same machine as the Needle CLI.",inputSchema:{type:"object",properties:{url:{type:"string",description:"HTTP localhost URL or loopback host:port, for example http://127.0.0.1:8765/preview.html."}},required:["url"],additionalProperties:!1}},async t=>e(await async function(e){const t=function(e){if("string"!=typeof e||!e.trim())throw new Error("A localhost URL or host:port is required.");const t=e.trim(),n=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(t)?t:`http://${t}`);if("http:"!==n.protocol&&"https:"!==n.protocol)throw new Error("Only HTTP and HTTPS localhost URLs are supported.");const o=n.hostname.toLowerCase();if(!["localhost","127.0.0.1","[::1]"].includes(o))throw new Error("Only localhost or loopback IP addresses are supported.");const i=n.port?Number(n.port):"https:"===n.protocol?443:80;if(!Number.isInteger(i)||i<1||i>65535)throw new Error("A valid TCP port is required.");return{host:o,port:i,path:n.pathname+n.search}}(e);if("win32"===process.platform){const e=await async function(e,t){const n=Cf.replace("__PORT__",String(e)).replace("__HOST__",t),o=Buffer.from(n,"utf16le").toString("base64"),{stdout:i}=await If("powershell.exe",["-NoProfile","-NonInteractive","-EncodedCommand",o],{timeout:1e4,maxBuffer:1048576});return JSON.parse(i.trim())}(t.port,t.host);return{...t,...e}}if("linux"===process.platform||"darwin"===process.platform){const e="linux"===process.platform?await async function(e){const t=new Set;for(const o of["/proc/net/tcp","/proc/net/tcp6"]){let i;try{i=await K(o,"utf8")}catch(e){if("ENOENT"===e.code)continue;throw e}for(const o of i.split("\n").slice(1)){var n;const i=o.trim().split(/\s+/);i.length<10||Number.parseInt(null!=(n=i[1].split(":").at(-1))?n:"",16)===e&&"0A"===i[3]&&t.add(i[9])}}if(!t.size)return null;const o=await Z("/proc",{withFileTypes:!0});for(const e of o){if(!e.isDirectory()||!/^\d+$/.test(e.name))continue;let n;try{n=await Z(`/proc/${e.name}/fd`)}catch{continue}for(const o of n)try{const n=await Y(`/proc/${e.name}/fd/${o}`),i=/^socket:\[(\d+)\]$/.exec(n);if(i&&t.has(i[1]))return Number(e.name)}catch{}}throw new Error("A process is listening, but its PID is not visible to this CLI.")}(t.port):await async function(e){try{const{stdout:t}=await If("lsof",["-nP","-t",`-iTCP:${e}`,"-sTCP:LISTEN"],{timeout:5e3}),n=Number(t.trim().split(/\s+/)[0]);return Number.isInteger(n)&&n>0?n:null}catch(e){if(1===e.code)return null;throw e}}(t.port);if(null===e)return{...t,status:"not-listening"};try{const n="linux"===process.platform?await Y(`/proc/${e}/cwd`):await async function(e){const{stdout:t}=await If("lsof",["-a","-p",String(e),"-d","cwd","-Fn"],{timeout:5e3}),n=t.split(/\r?\n/).find(e=>e.startsWith("n"));if(!n)throw new Error("The process working directory is not available.");return n.slice(1)}(e);return{...t,status:"found",pid:e,workingDirectory:n}}catch(n){return{...t,status:"unavailable",pid:e,reason:n instanceof Error?n.message:String(n)}}}return{...t,status:"unavailable",reason:`Unsupported platform: ${process.platform}`}}(null==t?void 0:t.url)),{source:"cli"},()=>{}),Of({name:"local_project_list",description:"List web projects registered with the local Needle CLI, including projects created by AI after a successful create job. Each path may be selected with local_project_select. File tools access only the currently selected project.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1}},async()=>e(dm().entries.filter(e=>e.web_location).map(e=>({path:e.web_location,selected:e===Ff(),editor:e.editor}))),{source:"cli"},()=>{}),Of({name:"local_project_select",description:"Select a registered local web project by its exact path from local_project_list. Subsequent local_files_* tools use this project. Selecting a project does not approve edits; Cloud chat must obtain a separate file-edit grant for the selected project.",inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1}},async t=>e({selected:vm(t.path).web_location}),{source:"cli"},()=>{}),Of({name:"local_project_action",description:"Prepare a local Needle project action without executing it. Operations: create (name, template, optional absolute parent or destination), install, add_package (packages, optional dev), build, dev (start the dev server and open its local URL in the default browser), deploy (target team ID required; optional name and relative build directory). For dev, hot reload may be disabled in vite.config.js/ts by hmr: false or Needle allowHotReload: false; if edits do not appear, inspect the config and use the normal file-edit approval to enable it if appropriate. For create, parent is an existing folder to create the named project INSIDE, even if the parent has spaces or parentheses; destination is the full path of the new project and must end with name. If the user provides an existing folder path, use parent and do not treat its basename as the project name. If only the name is missing, ask only for a name. For install/add_package/build/dev/deploy, omit project to use the selected web project, or pass an explicit absolute path to another local project; that target needs fresh Cloud approval. An approved action for another project registers and selects it for local file tools, even if the command fails. A successful create job also registers and selects its new project. Use local_project_list and local_project_select to return to another registered project. Never put a project path in directory; that is only the deploy build output. Cloud chat fills the current team if omitted. For a prepared action, pass planId alone to retrieve its exact command and project. Then call request_local_project_command with planId for approval. Local CLI settings can still disable execution.",inputSchema:{type:"object",properties:{operation:{type:"string",enum:["create","install","add_package","build","dev","deploy"]},name:{type:"string"},template:{type:"string",enum:xf},parent:{type:"string",description:"Existing absolute folder in which to create the new project. Its name may contain spaces or parentheses; the new child folder uses name."},destination:{type:"string",description:"Full absolute path to the new project folder; its last segment must equal name. Use parent instead when the user supplies an existing containing folder."},project:{type:"string",description:"Absolute local project path. Use the path returned by a completed create job for a new project; omit for the connected web project. A different path requires fresh approval."},packages:{type:"array",items:{type:"string"}},dev:{type:"boolean"},directory:{type:"string"},team:{type:"string",description:"Target Needle Cloud team ID for deploy. Use the org_... identifier, which Cloud data may call orgId. In Cloud chat, omit this to use the current team."},planId:{type:"string"}},required:[],additionalProperties:!1}},async(t,n)=>{if(null==n||!n.chatId)throw new Error("A Cloud chat is required to plan an AI project command.");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("Project command arguments must be an object.");return e(t.planId?Uf.getPlan(t.planId,n.chatId):Uf.plan(t,n.chatId))},{source:"cli"},()=>{}),Of({name:"local_project_start",description:"Internal Cloud approval handoff for a previously planned project command. A model tool call cannot grant approval.",inputSchema:{type:"object",properties:{planId:{type:"string"}},required:["planId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.planId)throw new Error("A project plan ID is required.");if(null==n||!n.commandGrant||n.chatId!==n.commandGrant.chatId||t.planId!==n.commandGrant.planId)throw new Error("Exact Cloud approval is required for this project command.");if(hf())throw new Error("AI project commands are disabled in local Needle CLI settings.");return e(await Uf.start(t.planId,n.commandGrant))},{source:"cli"},()=>{}),Of({name:"local_project_status",description:"Read the status and bounded output of a local project command job in this chat. Poll this after local_project_start; the job may take several minutes.",inputSchema:{type:"object",properties:{jobId:{type:"string"}},required:["jobId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.jobId)throw new Error("A project job ID is required.");if(null==n||!n.chatId)throw new Error("A Cloud chat is required to inspect this project job.");return e(Uf.status(t.jobId,n.chatId))},{source:"cli"},()=>{}),Of({name:"local_project_cancel",description:"Cancel a running local project command job in this chat.",inputSchema:{type:"object",properties:{jobId:{type:"string"}},required:["jobId"],additionalProperties:!1}},async(t,n)=>{if(!t||"string"!=typeof t.jobId)throw new Error("A project job ID is required.");if(null==n||!n.chatId)throw new Error("A Cloud chat is required to cancel this project job.");return e(await Uf.cancel(t.jobId,n.chatId))},{source:"cli"},()=>{})}(),Of(jp.schema,async e=>{const t=await jp.execute(e);return"error"in t?{content:[{type:"text",text:t.error}]}:{content:[{type:"text",text:t.content}]}},{source:"cli"},()=>{}),Of({name:"local_files_stat",description:'Check one exact relative path in the connected local web project and read its SHA-256 hash and size. This does not search by basename or recurse: exists=false only means that exact path was not found. First locate a nested file with local_files_list(path="src", recursive=true), then pass the full relative path such as src/scripts/MyComponent.ts. Use the returned hash as expectedSha256 before replacing or deleting that file.',inputSchema:{type:"object",properties:{path:{type:"string"}},required:["path"],additionalProperties:!1}},async e=>({content:[{type:"text",text:JSON.stringify(Nf.stat(e.path))}]}),{source:"cli"},()=>{}),Of({name:"local_files_write",description:"Create or replace a UTF-8 text file in the approved local web project. For an existing file, first call local_files_stat and pass its SHA-256 hash as expectedSha256. Creating a new file requires create=true. Automatically saves an undo checkpoint. Requires user approval for this project and chat session. A successful write only confirms that bytes were saved; run local_files_check_project with mode=check afterward before saying TypeScript errors are fixed.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"},create:{type:"boolean"},expectedSha256:{type:"string"}},required:["path","content"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.write(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_delete",description:"Delete a file in the approved local web project. First call local_files_stat and pass its SHA-256 hash as expectedSha256. Saves an undo checkpoint and refuses changed files.",inputSchema:{type:"object",properties:{path:{type:"string"},expectedSha256:{type:"string"}},required:["path","expectedSha256"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.delete(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_rename",description:"Rename a file within the approved local web project. First call local_files_stat and pass its SHA-256 hash as expectedSha256. The destination must not exist. Saves an undo checkpoint.",inputSchema:{type:"object",properties:{path:{type:"string"},newPath:{type:"string"},expectedSha256:{type:"string"}},required:["path","newPath","expectedSha256"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.rename(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_undo",description:"Undo one saved AI file edit in the approved local web project. Refuses to overwrite changes made after the edit. The checkpoint remains available for Redo.",inputSchema:{type:"object",properties:{checkpointId:{type:"string"}},required:["checkpointId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.undo(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_redo",description:"Reapply one previously undone AI file edit from its checkpoint. Refuses to overwrite changes made after Undo. Requires active file-edit approval.",inputSchema:{type:"object",properties:{checkpointId:{type:"string"}},required:["checkpointId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.redo(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_undo_turn",description:"Undo all AI file edits from one turn in reverse order. Use a turnId from local_files_list_changes. Checks every file for conflicts before changing anything; refuses changed files. Older checkpoints without turn ordering must be undone individually.",inputSchema:{type:"object",properties:{turnId:{type:"string"}},required:["turnId"],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.undoTurn(e,Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_list_changes",description:"List recent undo checkpoints for this chat and connected local web project. Requires active user approval. Returns filenames and checkpoint IDs, not file contents.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1}},async(e,t)=>({content:[{type:"text",text:JSON.stringify(Nf.list(Lf(t)))}]}),{source:"cli"},()=>{}),Of({name:"local_files_check_project",description:"Check the connected local web project for TypeScript errors without emitting files or applying fixes. Default mode check runs its installed compiler (10 second limit) and returns up to 5 short diagnostics. Use mode results with file/code filters and offset to browse the latest check without rerunning. Use mode error with an index for details; omit index for the last matching error. Results are timestamped snapshots, retained until another check or project change, or CLI exit. Local AI writes and changes to tracked local project files mark saved results stale; dependency files inside node_modules are excluded from the change scan. Retains at most 100 diagnostics. Reports current errors, not whether they predate edits. Not a linter or Unity/Blender compiler.",inputSchema:{type:"object",properties:{mode:{type:"string",enum:["check","results","error"],description:"Run a new check, browse cached results, or inspect one cached error."},file:{type:"string",maxLength:250,description:"Filter diagnostic filenames by case-insensitive substring; does not select a project or restrict compiler inputs."},code:{type:"string",maxLength:250,description:"Exact diagnostic code, e.g. TS2322."},offset:{type:"integer",minimum:0,description:"Offset within filtered results; 5 errors per page."},index:{type:"integer",minimum:0,description:"Diagnostic index from the latest check for mode error; defaults to the last matching error."}},additionalProperties:!1,required:[]}},async e=>{const t=await Af(e);return{content:[{type:"text",text:JSON.stringify(t)}],isError:"error"===t.status||"unavailable"===t.status}},{source:"cli"},()=>{}),null!=e&&e.logToolCount&&mu(`[MCP] registered ${jm.length} built-in tools: ${jm.map(e=>e.name).join(", ")}`)}function Ff(){return hm()}function Df(e,t){const n=_(t,e),o=_(t),i=j(o,n);return k(i)||".."===i||i.startsWith(".."+E)?null:Wm(o,n,{allowMissing:!0}).path}function qf(){const e=Ff();if(!e)return[];const t=[];return e.project_location&&t.push(_(e.project_location)),e.web_location&&t.push(_(e.web_location)),t}function Bf(e){const t=qf();for(const n of t){const t=Df(e,n);if(t&&l(t))return{resolved:t,root:n}}for(const n of t){const t=Df(e,n);if(t)return{resolved:t,root:n}}const n=_(e);for(const e of t)if(n.startsWith(e+E)||n===e)return{resolved:n,root:e};return null}function Mf(e,t){if(0===t.length||null==e)return e;const[n,...o]=t;if("*"!==n)return Mf(e[/^\d+$/.test(n)?Number(n):n],o);if(Array.isArray(e)){const t=e.map(e=>Mf(e,o)).filter(e=>void 0!==e);return t.length>0?t:void 0}if("object"==typeof e){const t={};for(const n of Object.keys(e)){const i=Mf(e[n],o);void 0!==i&&(t[n]=i)}return Object.keys(t).length>0?t:void 0}}function Wf(e,t,n,o,i){if(i>10)return[];const r=[],a=d(e,{withFileTypes:!0}),s="node_modules"===(e.split("/").pop()||e.split("\\").pop()||"");for(const c of a){if(s){if(".needle"!==c.name&&".vite"!==c.name)continue}else{if("Library"===c.name)continue;if(c.name.startsWith(".")||"node_modules"===c.name){if(!n)continue;if(c.name.startsWith("."))continue}}const a=S(e,c.name);if(!Bm(j(t,a))&&!c.isSymbolicLink())if(Wm(t,a),c.isDirectory())n&&r.push(...Wf(a,t,!0,o,i+1));else{if(o&&!o.split("|").map(e=>(e=e.trim()).startsWith(".")&&!e.startsWith("*.")?"*"+e:e).filter(Boolean).some(e=>Ze(c.name,e,{nocase:!0})))continue;r.push(a)}}return r}process.once("exit",()=>Uf.dispose());const Gf="cli-installation-id",Hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Jf="2025-06-18";function Vf(e){return{jsonrpc:"2.0",id:e,result:{protocolVersion:Jf,capabilities:{tools:{listChanged:!0}},serverInfo:Kf}}}const Kf={name:"Needle Cloud MCP",version:"1.0.0"};function Yf(e){if(null!==e&&"object"==typeof e&&"name"in e&&"version"in e&&"string"==typeof e.name&&"string"==typeof e.version&&e.name.trim()&&e.version.trim())return{name:e.name,version:e.version}}function Zf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}let Xf=!1;const Qf=We(),eh=new Map,th=new Map;let nh=0;function oh(){const e=[];for(const[t,{connectedAt:n,userAgent:o}]of th)e.push({id:t,connectedAt:n,userAgent:o});return e}function ih(e,t,n,o){if((t.headers.accept||"").includes("text/event-stream")){var i,r;n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),n.setHeader("Access-Control-Allow-Origin","*"),n.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id"),n.flushHeaders(),n.write(": connected\n\n");const a=t.headers["mcp-session-id"],s=null!=(i=null!=(r=null!=o?o:"string"==typeof a?eh.get(a):void 0)?r:t.headers["user-agent"])?i:"",c=()=>{clearInterval(l),th.delete(e)&&(console.log(`[MCP] SSE client disconnected (ID: ${e}): ${s}`),mu(`MCP SSE client disconnected (ID: ${e}): ${s}`))},l=setInterval(()=>{try{n.write(": keepalive\n\n")}catch(t){console.error(`[MCP] SSE heartbeat failed (${e}):`,t),c(),n.destroy()}},15e3);return l.unref(),n.once("close",c),n.once("error",t=>{console.error(`[MCP] SSE stream failed (${e}):`,t),c()}),th.set(e,{id:e,client:n,connectedAt:Date.now(),userAgent:s,dispose:c}),console.log(`[MCP] SSE client connected (ID: ${e}) ${s}. Total clients: ${th.size}`),mu(`MCP SSE client connected (ID: ${e}) ${s}. Total clients: ${th.size}`),!0}return!1}function rh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}async function ah(e=ce(oe(),".needle")){let t,n;try{t=await K(ce(e,"local-server-token"),"utf8")}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return;throw new Error("Cannot read local Needle server credentials. Check the credential file permissions.")}try{n=JSON.parse(t)}catch{throw new Error("Invalid local Needle server credentials. Restart the local server to repair them.")}if(null===n||"object"!=typeof n||!("token"in n)||"string"!=typeof n.token||!/^[\x21-\x7e]+$/.test(n.token))throw new Error("Invalid local Needle server credentials. Restart the local server to repair them.");return n.token}async function sh(){const e=await ah();try{const t=await fetch(`${nd}/mcp`,{method:"POST",headers:{...e?{Authorization:`Bearer ${e}`}:{},"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"needle-startup-probe",method:"ping"}),signal:AbortSignal.timeout(1e3),redirect:"error"});if(!t.ok)return!1;const n=await t.json();return null!==n&&"object"==typeof n&&"jsonrpc"in n&&"2.0"===n.jsonrpc&&"id"in n&&"needle-startup-probe"===n.id&&"result"in n}catch(e){if(e instanceof TypeError||e instanceof Error&&["TimeoutError","AbortError"].includes(e.name))return!1;throw e}}async function ch(e,t=process.argv[1]){await new Promise((n,o)=>{const i=Ye(process.execPath,[t,"start","--integration","mcp","--silent"],{detached:!0,windowsHide:!0,stdio:"ignore",env:process.env});i.once("error",t=>{e(`MCP local server launch failed: ${t.message}`),o(t)}),i.once("spawn",()=>{i.unref(),n(void 0)}),i.once("exit",(t,n)=>{0!==t&&e(`MCP local server process exited (${null!=n?n:t}); see the CLI log for details.`)})})}Qf.get("/mcp",async(e,t)=>{if(ih(nh++,e,t))return;const n=function(e){const t=[...jm].sort((e,t)=>e.name.localeCompare(t.name)),n=t.map(e=>`\n <div class="tool">\n <span class="tool-name">${Zf(e.name)}</span>\n <span class="tool-desc">${Zf(function(e){const t=e.indexOf("\n");return-1===t?e:e.slice(0,t)}(e.description))}</span>\n </div>`).join("\n");return`<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1">\n <title>Needle MCP Server</title>\n <style>\n * { box-sizing: border-box; }\n body {\n background: #f0f4ef;\n font-family: system-ui, -apple-system, sans-serif;\n line-height: 1.6;\n padding: 20px 24px;\n max-width: 960px;\n margin: 0 auto;\n color: #1a1a1a;\n }\n header {\n display: flex;\n align-items: center;\n gap: 8px;\n margin-bottom: 8px;\n }\n h2 {\n margin-top: 1.2em;\n margin-bottom: 0.4em;\n }\n a { color: inherit; }\n img.logo {\n height: 2em;\n width: auto;\n }\n .badge {\n font-size: 0.75em;\n background: #d0d4cf;\n padding: 2px 8px;\n border-radius: 10px;\n vertical-align: middle;\n font-weight: normal;\n }\n .tools-info {\n color: #555;\n font-size: 0.9rem;\n margin-top: 0;\n margin-bottom: 10px;\n }\n\n /* Tool items */\n .tool {\n background: #fff;\n border: 1px solid #d8dcd7;\n border-radius: 6px;\n margin-bottom: 6px;\n padding: 10px 14px;\n display: flex;\n align-items: baseline;\n gap: 10px;\n }\n .tool-name {\n font-weight: 600;\n white-space: nowrap;\n }\n .tool-desc {\n color: #555;\n font-size: 0.9rem;\n }\n</style>\n</head>\n<body>\n <header>\n <img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" />\n <strong>Needle MCP Server</strong>\n </header>\n\n <p>The Needle MCP server is alive and running.</p>\n\n <h2>Usage</h2>\n <p><a href="https://fwd.needle.tools/mcp">Open Documentation</a></p>\n\n <h2>Available Tools <span class="badge">${t.length}</span></h2>\n <p class="tools-info">These tools are available to AI agents connected via the Model Context Protocol (MCP).</p>\n ${n}\n</body>\n</html>`}();t.status(200).header("Content-Type","text/html; charset=utf-8").send(n)}),Qf.post("/mcp",async(e,t)=>{const n=e.headers.accept||"",o=e.headers["user-agent"]||"",{method:i,id:r}=e.body;console.log(`[MCP] Received request from ${o} (${i}) (ID: ${r})`),t.setHeader("Content-Type","application/json"),t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Mcp-Session-Id"),t.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id");try{if("initialize"===i&&n.includes("text/event-stream")){var a;const n=nh++,o=Yf(null==(a=e.body.params)?void 0:a.clientInfo);if(ih(n,e,t,o?`${o.name}/${o.version}`:void 0)){Xf=!0;const e=Vf(null!=r?r:0);return void t.write(`data: ${JSON.stringify(e)}\n\n`)}}const l=await async function(e,t){const{method:n,params:o,id:i}=e;if("initialize"===n)return Vf(null!=i?i:0);if("ping"===n)return{jsonrpc:"2.0",id:i,result:{}};if("notifications/initialized"===n||"notifications/cancelled"===n)return null;if("tools/list"===n){try{zf()}catch{}return{jsonrpc:"2.0",id:i,result:{tools:jm}}}if("tools/call"===n){const e=null==o?void 0:o.name;try{zf()}catch{}try{return{jsonrpc:"2.0",id:i,result:await Om(e,(null==o?void 0:o.arguments)||{})}}catch(e){return{jsonrpc:"2.0",id:i,error:{code:-32603,message:`Tool execution failed: ${e.message}`}}}}return{jsonrpc:"2.0",id:null!=i?i:null,error:{code:-32601,message:`Method '${n}' not found`}}}(e.body);if("initialize"===i){var s;Xf=!0;const n=Se(),i=Yf(null==(s=e.body.params)?void 0:s.clientInfo);eh.set(n,i?`${i.name}/${i.version}`:void 0),t.setHeader("Mcp-Session-Id",n),console.log(`[MCP] New session created: ${n} for ${o}`),mu(`MCP New session: ${n} for ${o}`)}if(null===l)return t.status(204).end();if(mu(`MCP Request: ${i}`),"tools/list"===i){var c;const e=(null==(c=l.result)||null==(c=c.tools)?void 0:c.map(e=>e.name))||[];console.log(`[MCP] Sending tools/list: ${e.length} tools [${e.join(", ")}]`)}else{const e=JSON.stringify(l);console.log(`[MCP] Sending response for ${i}:`,e.length>500?e.substring(0,500)+" [...]":e)}t.json(l)}catch(e){console.error("[MCP] Error processing request:",e);const n={jsonrpc:"2.0",error:{code:-32603,message:"Internal server error",data:"development"===process.env.NODE_ENV?e.stack:void 0},id:r||null};t.json(n)}}),Qf.options("/mcp",(e,t)=>{t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS, DELETE"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, Mcp-Session-Id"),t.setHeader("Access-Control-Expose-Headers","Mcp-Session-Id"),t.status(204).end()});let lh=!1;function ph(e,t={}){lh&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n")}var uh={__proto__:null,sendStdioNotification:ph,startStdio:function(){lh=!0,console.log=console.info=console.debug=console.error.bind(console);const e=e=>{console.error(e),mu(e)},t=function({endpoint:e,ensureServer:t,notify:n,log:o,getToken:i,retryMs:r=250,streamTimeoutMs:a=45e3}){const s=new AbortController;let c,l,p,u,d=!1,m=!1,f={name:"Needle stdio bridge",version:"1.0.0"};const h=async()=>i?{Authorization:`Bearer ${await i()}`}:{},g=()=>`${encodeURIComponent(f.name)}/${encodeURIComponent(f.version)}`;function v(e){d!==e&&(d=e,m&&n("notifications/tools/list_changed"))}async function b(t){s.signal.throwIfAborted();const n=new AbortController,o=()=>n.abort();s.signal.addEventListener("abort",o,{once:!0});const i=setTimeout(o,"tools/call"===t.method?35e3:5e3);try{var r,a;const o=await h(),i=await fetch(e,{method:"POST",headers:{...o,"User-Agent":g(),"Content-Type":"application/json",Accept:"application/json","MCP-Protocol-Version":Jf,...u?{"Mcp-Session-Id":u}:{}},body:JSON.stringify(t),signal:n.signal,redirect:"error"});if(!i.ok)throw new Error(`MCP server returned HTTP ${i.status}`);if(204===i.status)return null;const s=await i.json();if(!rh(s)||"2.0"!==s.jsonrpc||s.id!==t.id||!rh(s.result)&&!rh(s.error))throw new Error("Invalid response from local MCP server");if(rh(s.error)){var c;if("number"!=typeof s.error.code||"string"!=typeof s.error.message)throw new Error("Invalid MCP error response");return{jsonrpc:"2.0",id:null!=(c=t.id)?c:null,error:{code:s.error.code,message:s.error.message}}}return"initialize"===t.method&&(u=null!=(r=i.headers.get("Mcp-Session-Id"))?r:void 0),{jsonrpc:"2.0",id:null!=(a=t.id)?a:null,result:s.result}}finally{clearTimeout(i),s.signal.removeEventListener("abort",o)}}return{start:()=>(l||(l=new Promise(e=>{p=e}),c=async function(){let i=r;for(;!s.signal.aborted;){let d;const y=new AbortController,x=()=>y.abort();let w;s.signal.addEventListener("abort",x,{once:!0});const _=(e,t=!0)=>{clearTimeout(w),w=setTimeout(()=>{t?S():y.abort(new Error("MCP notification stream connection timed out"))},e)},S=async()=>{try{var e,t;const n=await b({jsonrpc:"2.0",id:"needle-bridge-liveness",method:"ping"});if(null==n||!n.result||n.error)throw new Error(null!=(e=null==n||null==(t=n.error)?void 0:t.message)?e:"Invalid MCP ping response");s.signal.aborted||y.signal.aborted||_(a)}catch(e){s.signal.aborted||y.signal.aborted||y.abort(e)}};try{var c;await t(s.signal);const o=await b({jsonrpc:"2.0",id:"needle-bridge-initialize",method:"initialize",params:{protocolVersion:Jf,capabilities:{},clientInfo:f}});if(null!=o&&o.error)throw new Error(o.error.message);await b({jsonrpc:"2.0",method:"notifications/initialized"}),_(5e3,!1);const x=await h(),w=await fetch(e,{headers:{...x,"User-Agent":g(),Accept:"text/event-stream","MCP-Protocol-Version":Jf,...u?{"Mcp-Session-Id":u}:{}},signal:y.signal,redirect:"error"});var l;if(!w.ok||null==(c=w.headers.get("content-type"))||!c.includes("text/event-stream")||!w.body)throw await(null==(l=w.body)?void 0:l.cancel()),new Error(`MCP notification stream unavailable (HTTP ${w.status})`);_(a),d=w.body.getReader(),v(!0),null==p||p(),i=r;const S=new TextDecoder;let j="";for(;!s.signal.aborted;){const{value:e,done:t}=await d.read();if(t)throw new Error("MCP notification stream closed");let o;for(_(a),j+=S.decode(e,{stream:!0});o=/\r?\n\r?\n/.exec(j);){const e=j.slice(0,o.index);j=j.slice(o.index+o[0].length);const t=e.split(/\r?\n/).filter(e=>e.startsWith("data:")).map(e=>e.slice(5).replace(/^ /,"")).join("\n");if(!t)continue;const i=JSON.parse(t);rh(i)&&"2.0"===i.jsonrpc&&"notifications/tools/list_changed"===i.method&&m&&n("notifications/tools/list_changed")}if(j.length>1048576)throw new Error("MCP notification exceeds size limit")}}catch(e){s.signal.aborted||(o(`MCP bridge disconnected: ${e instanceof Error?e.message:String(e)}; retrying.`),v(!1))}finally{if(clearTimeout(w),s.signal.removeEventListener("abort",x),d){if(!y.signal.aborted)try{await d.cancel()}catch(e){s.signal.aborted||o(`MCP stream cleanup failed: ${String(e)}`)}d.releaseLock()}u=void 0,null==p||p()}if(!s.signal.aborted){try{await Qe(i,void 0,{signal:s.signal})}catch(e){if(!s.signal.aborted)throw e}i=Math.min(2*i,1e4)}}}()),l),async stop(){s.abort(),await c},async handle(e){var t,i;if("initialize"===e.method)return f=null!=(t=Yf(null==(i=e.params)?void 0:i.clientInfo))?t:f,null;if("notifications/initialized"===e.method)return m=!0,d&&n("notifications/tools/list_changed"),null;if(void 0===e.id)return null;if(!d)return"tools/list"===e.method?{jsonrpc:"2.0",id:e.id,result:{tools:[]}}:{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"The local Needle server is unavailable. Reconnecting; try again shortly."}};try{return await b(e)}catch(t){const n=t instanceof Error?t.message:String(t);return o(`MCP bridge ${e.method} failed: ${n}`),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:`Local Needle server request failed: ${n}`}}}}}}({endpoint:`${nd}/mcp`,ensureServer:t=>async function(e={}){const{signal:t,lockPath:n=ce(oe(),".needle","mcp-server-start.lock"),probe:o=sh,log:i=(e=>console.error(e)),launch:r=(()=>ch(i)),timeoutMs:a=2e4,pollMs:s=100}=e;if(null==t||t.throwIfAborted(),await o())return;await X(ue(n),{recursive:!0});const c=Date.now()+a;let l;try{for(;Date.now()<c;){if(null==t||t.throwIfAborted(),await o())return;if(!l){try{l=await Q(n,"wx",384)}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e;try{const e=await ee(n);Date.now()-e.mtimeMs>12e4&&(i("Removing an expired MCP server startup lock."),await te(n))}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e}}if(l){if(await o())return;i("Starting the shared Needle local server."),await r()}}await Qe(s,void 0,{signal:t})}throw new Error("The local Needle server did not become ready in time. See the CLI log for startup errors.")}finally{l&&(await l.close(),await te(n))}}({signal:t,log:e}),notify:ph,log:e,getToken:()=>async function(e){const t=await ah(void 0);if(void 0===t)throw new Error("Local Needle server credentials are missing. Restart the local server to create them.");return t}()}),n=qe({input:process.stdin,terminal:!1}),o=e=>{lh&&process.stdout.write(JSON.stringify(e)+"\n")};n.on("line",i=>{(async function(n){if(!n.trim())return;let i;try{i=JSON.parse(n)}catch{return void o({jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}if(!rh(r=i)||"2.0"!==r.jsonrpc||"string"!=typeof r.method||null!=r.id&&"string"!=typeof r.id&&"number"!=typeof r.id||void 0!==r.params&&!rh(r.params))return void o({jsonrpc:"2.0",id:null,error:{code:-32600,message:"Invalid request"}});var r,a;if("initialize"===i.method)return o(Vf(null!=(a=i.id)?a:0)),await t.handle(i),void t.start().catch(t=>e(`MCP bridge startup failed: ${String(t)}`));if("ping"===i.method)return void(void 0!==i.id&&o({jsonrpc:"2.0",id:i.id,result:{}}));const s=await t.handle(i);s&&o(s)})(i).catch(t=>{e(`MCP stdio request failed: ${String(t)}`),process.exitCode=1,n.close()})}),n.once("close",()=>{lh=!1,t.stop().then(()=>{var e;return process.exit(null!=(e=process.exitCode)?e:0)},t=>{e(`MCP bridge shutdown failed: ${String(t)}`),process.exit(1)})})}};let dh=null;function mh(){dh&&clearTimeout(dh),dh=setTimeout(()=>{!function(e,t={}){if(0===th.size)return;const n=`data: ${JSON.stringify({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:t})}\n\n`;for(const[e,{client:t,dispose:o}]of th)try{t.write(n)}catch(n){console.error(`[MCP] Error sending notification to client (${e}):`,n),o(),t.destroy()}}(),ph("notifications/tools/list_changed"),Ih(),dh=null},10)}const fh=function({send:e,register:t,clear:n,onError:o}){const r=new Map,a=new Set;let s=null,c=null,l=!1;const p=()=>{l=!1,s=null,c&&clearTimeout(c),c=null,a.size&&n(),a.clear();for(const e of r.values())clearTimeout(e.timer),e.reject(new Error("Needle Cloud disconnected."));r.clear()},u=(t,n)=>new Promise((o,a)=>{if(!l)return void a(new Error("Needle Cloud disconnected."));if(r.size>=4)return void a(new Error("Too many concurrent cloud tool requests."));const s=i(),c=setTimeout(()=>{r.delete(s),a(new Error("Cloud tool request timed out."))},3e4);r.set(s,{resolve:o,reject:a,timer:c});try{e({type:"cloud_tool_call",requestId:s,name:t,args:n})}catch(e){clearTimeout(c),r.delete(s),a(e instanceof Error?e:new Error(String(e)))}});return{connect(){p(),l=!0,s=i(),c=setTimeout(()=>{s=null,o("Cloud tool discovery timed out. Update the Cloud API if it does not support MCP tools.")},15e3);try{e({type:"cloud_tools_list",requestId:s})}catch(e){p(),o(e instanceof Error?e.message:String(e))}},disconnect:p,isCloudTool:e=>a.has(e),receive(e){if(!e||"object"!=typeof e||!("type"in e)||!("requestId"in e)||"string"!=typeof e.requestId)return!1;if("cloud_tools_result"===e.type){if(!l||e.requestId!==s)return!0;if(s=null,c&&clearTimeout(c),c=null,"error"in e&&"string"==typeof e.error)return o(e.error),!0;if(!("tools"in e)||!Array.isArray(e.tools))return o("Invalid cloud tool catalog."),!0;try{for(const n of e.tools){if(!n||"object"!=typeof n||"string"!=typeof n.name||!/^[a-zA-Z0-9_]{1,45}$/.test(n.name)||"string"!=typeof n.description||!n.inputSchema||"object"!=typeof n.inputSchema||Array.isArray(n.inputSchema))throw new Error("Invalid cloud tool schema.");const e=`needle_cloud_${n.name}`;t({name:e,description:n.description,inputSchema:n.inputSchema},e=>u(n.name,e)),a.add(e)}}catch(e){p(),o(e instanceof Error?e.message:String(e))}return!0}if("cloud_tool_result"===e.type){const t=r.get(e.requestId);return!t||(r.delete(e.requestId),clearTimeout(t.timer),"error"in e&&"string"==typeof e.error?t.reject(new Error(e.error)):"result"in e&&"string"==typeof e.result?t.resolve(e.result):t.reject(new Error("Invalid cloud tool result.")),!0)}return!1}}}({send:e=>{if(!xh||xh.readyState!==Ge.OPEN)throw new Error("Needle Cloud disconnected.");xh.send(JSON.stringify(e))},register:(e,t)=>Im(e,t,{source:"cloud"},mh),clear:()=>Tm("cloud",mh),onError:e=>mu(`[Cloud MCP] ${e}`)}),hh=2e3,gh=6e4,vh=25e3,bh=1e4,yh=i();let xh=null,wh=null,_h=null,Sh=null,jh=hh,kh=!1,Eh=!1;function Th(){xh||(df()?mu("Needle Cloud connection: skipped (remote_ai_tools disabled in settings)"):(kh=!1,wh&&(clearTimeout(wh),wh=null),jh=hh,Ch()))}function $h(e){fh.disconnect(),kh=!0,Oh(),wh&&(clearTimeout(wh),wh=null),xh?(mu(`Needle Cloud connection: closing (reason: ${null!=e?e:"shutdown"})`),xh.close(1e3,null!=e?e:"shutdown"),xh=null):e&&mu(`Needle Cloud connection: disconnect requested (reason: ${e}) — no active connection`)}function Ih(){if(!xh||xh.readyState!==Ge.OPEN)return;try{zf()}catch(e){mu(`Needle Cloud connection: registerServerTools failed: ${e}`)}const e=jm.filter(e=>!fh.isCloudTool(e.name)),t=e.map(e=>e.name);var n;mu(`Needle Cloud connection: sending ${t.length} tools: ${t.join(", ")}`),xh.send(JSON.stringify({type:"tools",tools:(n=e,n.map(e=>{var t;return{name:e.name,description:e.description,inputSchema:e.inputSchema,capability:null!=(t=e.capability)?t:"local"}}))}))}async function Ch(){let e,t,n=await Gd();if(n||(n=function(){const e=Pd("accessToken");if(c.existsSync(e)){const t=c.readFileSync(e,"utf8");if(t){const e=JSON.parse(t),n=null==e?void 0:e["@https://cloud.needle.tools/api"];return null==n?void 0:n.token}}return null}(),n&&mu("Needle Cloud connection: using cached token (refresh failed)")),!n)return Eh||(mu("Needle Cloud connection: skipped (not logged in)"),Eh=!0),void Ah(!0);Eh=!1;try{e=function(e=pf()){C(e,{recursive:!0,mode:448});const t=ce(e,Gf);try{H(t,i(),{flag:"wx",mode:384})}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw e}const n=W(t,"utf8").trim();if(!Hf.test(n))throw new Error("Invalid local CLI installation ID.");return n}()}catch(e){return mu(`Needle Cloud connection: could not read local CLI installation identity: ${e instanceof Error?e.message:String(e)}`),void Ah(!0)}try{t=await async function(e,t={getUser:Hd,getDefaultOrg:Jd,authHeaders:Xd}){var n;const o=await t.getUser();if(null==o||!o.isAuthenticated)return{authToken:e,org:null};const i=await t.getDefaultOrg(o);if(i&&"object"==typeof i)throw new Error(i.error);if(!i)return{authToken:e,org:null};const r=await t.authHeaders(o,i);if("error"in r)throw new Error(r.error);if(!r.authToken)throw new Error("No access token for the default team.");return{authToken:r.authToken,org:null!=(n=r.org)?n:null}}(n)}catch(e){return mu(`Needle Cloud connection: team authentication failed: ${e instanceof Error?e.message:String(e)}`),void Ah()}const o="https://cloud.needle.tools/api".replace(/^http/,"ws")+"/v1/cli/ws?token="+encodeURIComponent(t.authToken)+(t.org?"&org="+encodeURIComponent(t.org):"")+"&instance="+encodeURIComponent(yh)+"&installation="+encodeURIComponent(e);mu("Needle Cloud connection: connecting...");const r=`needle-cloud/${wm()} Node/${process.versions.node}`;xh=new Ge(o,{headers:{"User-Agent":r,Origin:"cli://needle-cloud"}}),xh.on("open",()=>{jh=hh,mu("Needle Cloud connection: established"),Nh(),Ih(),Oh(),_h=setInterval(()=>{xh&&xh.readyState===Ge.OPEN&&(xh.ping(),Sh=setTimeout(()=>{mu("Needle Cloud connection: pong timeout, terminating"),xh&&xh.terminate()},bh))},vh),fh.connect()}),xh.on("pong",()=>{Sh&&(clearTimeout(Sh),Sh=null)}),xh.on("message",e=>{try{const n=JSON.parse(e.toString());if(fh.receive(n))return;var t;"execute_tool"===n.type&&n.requestId&&n.toolName&&async function(e,t,n,o,i,r){mu(function(e,t,n){const o=Object.entries(t).slice(0,12).map(([e,t])=>`${e.slice(0,40)}:${"string"==typeof t?t.length+" chars":typeof t}`);return`Cloud tool request: ${e.slice(0,64)}(${o.join(", ")}) [${n.slice(0,64)}]`}(t,n,e));const a=Date.now();try{var s,c;if(fh.isCloudTool(t))throw new Error("Cloud tools cannot be executed as local tools.");"local_project_action"===t&&Nh();const l=await Om(t,n,{chatId:o,editGrant:i,commandGrant:r});"local_project_select"!==t&&"local_project_start"!==t&&"local_project_status"!==t||Nh(),mu(`Cloud tool result: ${t} → ${null!=(s=null==l||null==(c=l.content)?void 0:c.reduce((e,t)=>{var n;return e+((null==(n=t.text)?void 0:n.length)||0)},0))?s:0} chars in ${Date.now()-a}ms [${e}]`),xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify({type:"tool_result",requestId:e,result:l}))}catch(n){const o=n instanceof Error?n.message:String(n);mu(`Cloud tool error: ${t} → ${o} in ${Date.now()-a}ms [${e}]`),xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify({type:"tool_result",requestId:e,error:o}))}}(n.requestId,n.toolName,null!=(t=n.args)?t:{},n.chatId,n.editGrant,n.commandGrant)}catch{}}),xh.on("close",(e,t)=>{const n=(null==t?void 0:t.toString())||"";mu(`Needle Cloud connection: closed (code=${e}${n?" "+n:""})`),Oh(),fh.disconnect(),xh=null,kh||Ah()}),xh.on("error",e=>{mu(`Needle Cloud connection: error - ${e.message||"connection refused"} (is https://cloud.needle.tools/api reachable?)`)})}function Oh(){_h&&(clearInterval(_h),_h=null),Sh&&(clearTimeout(Sh),Sh=null)}function Ah(e=!1){kh||wh||(e||mu(`Needle Cloud connection: reconnecting in ${jh/1e3}s`),wh=setTimeout(()=>{wh=null,Ch()},jh),jh=Math.min(2*jh,gh))}function Nh(){xh&&xh.readyState===Ge.OPEN&&xh.send(JSON.stringify(function(){var e,t,n;const o=hm();return{type:"presence",editor:null!=(e=null==o?void 0:o.editor)?e:"unknown",project:null!=(t=null==o?void 0:o.project_location)?t:null,scene:null!=(n=null==o?void 0:o.scene_location)?n:null,web_project:null!=o&&o.web_location?le(o.web_location):null,cli_version:wm()}}()))}const Rh=e=>{const t=We();return t.use("/:action",async(t,n,o)=>{const{action:i}=t.params,r=Vd({navigate:e=>{n.redirect(e)}});switch(i){case"sign-in":e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,mu("Sign in..."),await r.clearAllTokens(),Fd();try{await r.signIn(`${nd}/auth-callback`)}catch(e){const t=null==e?void 0:e.cause,o=`Sign-in failed: ${null!=t&&t.code?`${t.code}${t.address?` (${t.address}:${t.port})`:""}`:(null==e?void 0:e.message)||"unknown error"}`;return mu(o),console.error(o),n.status(502).send(o)}break;case"sign-out":{var a,s;const t=await Hd(),n=(null==t||null==(a=t.userInfo)?void 0:a.sub)||(null==t||null==(s=t.claims)?void 0:s.sub),o=null==t?void 0:t.accessToken;mu(`Sign out... (${n})`),n&&o&&await async function(e){return!e.accessToken||import("node-machine-id").then(async t=>{const n=await cm();return im=n,await fetch("https://cloud.needle.tools/api"+vt.account.post_machine,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({action:"logout",machine_id:n,machine_name:lm()})}).catch(e=>{mu(`Failed to validate logout: ${e.message} - Make sure https://cloud.needle.tools/api is reachable`),console.error(`Failed to validate logout: ${e.message} - Make sure https://cloud.needle.tools/api is reachable`)}),!0})}({userId:n,accessToken:o}).catch(e=>{console.error(e),mu(`Failed to validate logout: ${e}`)}),e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,console.log("User signed out"+(n?`: ${n}`:"")),await r.signOut(kd()),Fd();break}case"auth-callback":if(t.url){const o=await r.handleSignInCallback(`${nd}${t.originalUrl}`).catch(e=>({error:e}));if(Fd(),o&&"error"in o){mu(`Error during sign in: ${o.error}`);const e=o.error instanceof Error?o.error.message:String(o.error);n.redirect(nd+"?cancelled&message="+encodeURIComponent(e))}else{var c,l,p,u;const t=await Hd();if(null!=t&&t.isAuthenticated){var d,m;e.invalid_login=!1,e.user_email=(null==(d=t.claims)?void 0:d.email)||(null==(m=t.userInfo)?void 0:m.email)||null,e.logged_in_machine_names=[...rm(t)];const o=await pm(t,{signout:!0});if(!o)return e.invalid_login=!0,e.invalid_login_type="too-many-logins",n.redirect(kd("too-many-logins"));if("object"==typeof o&&"error"in o)return e.invalid_login=!0,e.invalid_login_type="error",e.error=o.error,n.redirect(kd("error"));Fd()}console.log(`User logged in: ${(null==t||null==(c=t.userInfo)?void 0:c.sub)||(null==t||null==(l=t.claims)?void 0:l.sub)}`),mu(`User logged in: ${(null==t||null==(p=t.userInfo)?void 0:p.sub)||(null==t||null==(u=t.claims)?void 0:u.sub)}`),Th(),n.redirect(nd)}}break;default:o()}}),t};function Ph(e,t,n){return!!n||e===Vp||"string"==typeof t&&t===e}function Uh(e){if(!Array.isArray(e))return console.error("Invalid input: paths should be an array of strings."),null;for(const t of e)if(!1!==l(t))try{const e=Lh(t);if(e)return e}catch(e){}}function Lh(e){const t=S(e,".git");if(l(t)){const e=function(e){const t=v(e);if(t.isDirectory())return S(e,"config");if(t.isFile()){const t=u(e,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(t){let n=t[1].trim();k(n)||(n=_(T(e),n));const o=S(n,"config");if(l(o))return o;const i=S(n,"commondir");if(l(i)){let e=u(i,"utf-8").trim();return k(e)||(e=_(n,e)),S(e,"config")}}}return null}(t);if(e&&l(e)){const t=function(e){const t=u(e,"utf-8"),n=/\[remote\s+"(?<name>.+?)"\].+?url\s*=\s*(?<url>.+?)$/gms,o=[];let i;for(;null!==(i=n.exec(t));)if(i.groups){const e=i.groups.name,t=i.groups.url.trim();t.length&&o.push({name:e,url:t})}const r=o.find(e=>"origin"===e.name)||o.find(e=>"upstream"===e.name)||o[0];return r?r.url:null}(e);if(t)return t}}const n=S(e,".plastic");if(l(n)){const e=S(n,"replicas.db");if(l(e)){const t=u(e,"utf-8").split("\n");for(const e of t){const t=e.split("=");if(2===t.length&&"repo"===t[0].trim()){const e=t[1].trim();if(e.length)return e}}}}const o=S(e,"..");return o===e?null:Lh(o)}function zh(e){if("string"!=typeof e)return!1;const t=/^(localhost|127\.0\.0\.1|\[::1\])(?::([0-9]{1,5}))?$/i.exec(e);return!!t&&(void 0===t[2]||Number(t[2])>0&&Number(t[2])<=65535)}const Fh=new Set(["https://cloud.needle.tools","https://needle.tools","https://engine.needle.tools","https://docs.needle.tools","chrome-extension://kjcepmifiddcepiocokclhibpkgcdomk","chrome-extension://jonplpbnhmanoekkgcepnedhghflblmo"]),Dh=new Set(["localhost","127.0.0.1","[::1]","::1"]);function qh(e){if("string"!=typeof e||0===e.length)return!1;if(Fh.has(e))return!0;let t;try{t=new URL(e)}catch{return!1}if("/"!==t.pathname&&""!==t.pathname)return!1;if(""!==t.search||""!==t.hash)return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const n=t.hostname.toLowerCase();return!!Dh.has(n)||"::1"===n}const Bh="[MCP]",Mh=new Array;function Wh(e){return"string"==typeof e&&/^[a-zA-Z0-9_.-]{1,80}$/.test(e)?e:void 0}function Gh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Hh(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>0}async function Jh(){try{return JSON.parse(await K(ce(oe(),".needle","local-server-token"),"utf8"))}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return null;if(e instanceof SyntaxError)throw new Error("The local server record is invalid.");throw e}}function Vh(e){try{return process.kill(e,0),!0}catch(e){if(e instanceof Error&&"code"in e){if("ESRCH"===e.code)return!1;if("EPERM"===e.code)return!0}throw e}}function Kh(e,t){return{api_endpoint:e,version:t,pid:process.pid}}var Yh={__proto__:null,getLocalServerInfo:Kh,getLocalServerStatus:async function(e={}){var t,n,o;const i=null!=(t=e.fetch)?t:globalThis.fetch;let r,a;try{r=await i(`${nd}/api/info`,{signal:AbortSignal.timeout(3e3)})}catch(e){if(e instanceof Error&&Gh(e.cause)&&"ECONNREFUSED"===e.cause.code)return{running:!1,url:nd};throw e}if(!r.ok)throw new Error(`Local server status request failed (HTTP ${r.status}).`);try{a=await r.json()}catch(e){if(e instanceof SyntaxError)throw new Error("Invalid local server info response.");throw e}if(!Gh(a)||"string"!=typeof a.version||!a.version.trim()||"string"!=typeof a.api_endpoint||!a.api_endpoint.trim())throw new Error("Invalid local server info response.");if(void 0!==a.pid&&!Hh(a.pid))throw new Error("Invalid local server PID.");if(Hh(a.pid))return{running:!0,url:nd,version:a.version,pid:a.pid,pidSource:"server"};const s=await(null!=(n=e.readServerRecord)?n:Jh)();return Gh(s)&&s.port===td&&Hh(s.pid)&&(null!=(o=e.isProcessAlive)?o:Vh)(s.pid)?{running:!0,url:nd,version:a.version,pid:s.pid,pidSource:"record"}:{running:!0,url:nd,version:a.version,pid:null,pidSource:"unavailable"}},formatLocalServerStatus:function(e){return e.running?`Needle local server: running\nURL: ${e.url}\nVersion: ${e.version}\nPID: ${null===e.pid?"unavailable":`${e.pid}${"record"===e.pidSource?" (recorded)":""}`}`:`Needle local server: not running\nURL: ${e.url}`}};const Zh="2026-11-05T18:22:19.955Z";var Xh={__proto__:null,BUILD_TIME:Zh};const{json:Qh}=et;function eg(e){const t=null==e?void 0:e.cause;return null!=t&&t.code?`${t.code}${t.address?` (${t.address}:${t.port})`:""}`:null!=t&&t.message?t.message:null!=e&&e.code?e.code:null!=e&&e.message&&"fetch failed"!==e.message?e.message:"connection refused or network unreachable"}async function tg(t={restart:!1}){const n=!0===t.restart,o=await e(nd).catch(e=>({ok:!1})),a="/sign-in",s="/api/authenticated",c="/api/projects",p="/api/content",u={baseUrl:nd,port:td,isHost:!1,auth_endpoints:{"sign-in":`${nd}${a}`,"sign-out":`${nd}/sign-out`,"is-authenticated":`${nd}${s}`}};let d=o.ok;if(d){var m;const x=await e(`${nd}/api/info`).catch(()=>null);if(null!=x&&x.ok){const w=await x.json().catch(()=>null);if(null!=w&&w.api_endpoint&&"https://cloud.needle.tools/api"!==w.api_endpoint){if(!Ph(w.api_endpoint,"https://cloud.needle.tools/api",n))return mu(`Keeping CLI server for ${w.api_endpoint}; https://cloud.needle.tools/api did not request an explicit restart.`),u;mu(`Running server uses different API endpoint (${w.api_endpoint} vs https://cloud.needle.tools/api), restarting...`),t||(t={}),t.restart=!0}}if(!0===(null==(m=t)?void 0:m.restart)){var f;mu("Restarting auth server...");const _=`${nd}/restart`;t.ora&&(t.ora.text="Sending restart request to server");const j=new AbortController;setTimeout(()=>j.abort(),1e4);let k={};try{const T=S(Ie(),".needle","local-server-token"),$=JSON.parse((await import("fs")).readFileSync(T,"utf-8"));$.token&&(k={Authorization:`Bearer ${$.token}`})}catch{}const E=await e(_,{method:"post",signal:j.signal,headers:{...k,"x-needle-client-integration":null!=(f=t.integration)?f:"cli","x-needle-client-version":wm(),"x-needle-client-pid":String(process.pid),"x-needle-api-endpoint":"https://cloud.needle.tools/api",...n?{"x-needle-explicit-restart":"true"}:{}}}).catch(e=>({ok:!1,status:400,error:e}));if(E.ok)return await $l(300),tg({restart:!1,integration:t.integration});409!==E.status&&console.error("Failed to restart server",E.status),mu(`Failed to restart server: ${E.status}`)}}if(!d){process.title="Needle CLI server";const O=await import("express").catch(e=>{throw console.error("Error starting the auth server (express not found)",e),mu("Error starting the auth server"),new Error("Failed to load express module")});if(!O)throw mu("Error loading auth server module"),new Error("Failed to load express module");let A;mu(`Starting Needle CLI server ${wm()} (built ${Zh})... (Using api at https://cloud.needle.tools/api)`,{emptyLineBefore:!0}),u.isHost=!0;let N=null;const R={invalid_login:!1,invalid_login_type:null,user_email:null,logged_in_machine_names:[]};let P=O.default();const U=S(Ie(),".needle"),L=function(e,t){var n;const o=ce(e,"local-server-token"),r=null!=(n=function(e){if(!I(e))return null;try{const t=W(e,"utf-8");if(0===t.length)return null;const n=JSON.parse(t);if(n&&"string"==typeof n.token&&n.token.length>0)return n.token}catch{}return null}(o))?n:i();C(e,{recursive:!0});const a=JSON.stringify({token:r,pid:process.pid,port:t},null,2);if(H(o,a,{encoding:"utf-8",mode:384}),"win32"===process.platform)try{const e=process.env.USERNAME||process.env.USER||"";e&&Je("icacls",[o,"/inheritance:r","/grant:r",`${e}:(F)`],{stdio:"ignore",timeout:5e3})}catch{}return r}(U,td);mu(`Local token written to ${S(U,"local-server-token")}`);const z=function(e,t=5e3){const n=new Map,o=Math.max(1,Math.round(t/1e3));return(i,r)=>{const a=Date.now(),s=n.get(i);if(!s||a-s.lastLog>t){var c;const t=null!=(c=null==s?void 0:s.suppressed)?c:0;e(t>0?`${r} [+${t} similar in last ${o}s]`:r),n.set(i,{lastLog:a,suppressed:0})}else s.suppressed++}}(e=>mu(`Denied: ${e}`),5e3);P.use((y={onDenied:z},(e,t,n)=>{var o;return zh(e.headers.host)?n():(null==y||null==y.onDenied||y.onDenied(`host|${null!=(o=e.headers.host)?o:"missing"}`,"HTTP Host is not a loopback authority"),t.status(403).send("Forbidden: host not allowed"))})),P.use(function(e){const t=null==e?void 0:e.onDenied;return(e,n,o)=>{var i,r;if("OPTIONS"===e.method)return o();const a=null==(i=e.headers)?void 0:i.origin,s=null==(r=e.headers)?void 0:r["sec-fetch-site"];if(void 0!==a){if(qh(a))return o();if(t)try{var c,l,p,u;const n=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown",o=null!=(p=null!=(u=e.path)?u:e.url)?p:"?";t(`origin|${a}|${o}`,`denied origin=${a} path=${o} ua="${n}"`)}catch{}return n.status(403).send("Forbidden: origin not allowed")}var d,m;if(s&&"none"!==s&&"same-origin"!==s&&("GET"!==e.method||"navigate"!==(null==(d=e.headers)?void 0:d["sec-fetch-mode"])||"document"!==(null==(m=e.headers)?void 0:m["sec-fetch-dest"]))){if(t)try{var f,h;const n=null!=(f=null!=(h=e.path)?h:e.url)?f:"?";t(`fetch-site|${s}|${n}`,`denied fetch-site=${s} path=${n}`)}catch{}return n.status(403).send("Forbidden: origin not allowed")}return o()}}({onDenied:z})),P.use(Qh({limit:"10mb"}));const F=new Set(["/","/sign-in","/sign-out","/auth-callback","/api/info","/api/authenticated","/api/public_key","/mcp","/register"]),D="needle_local";P.use((e,t,n)=>{var o,i,r;if("OPTIONS"===e.method)return n();if(F.has(e.path))return n();if(e.path.startsWith("/mcp/"))return n();if(e.path.startsWith("/.well-known/"))return n();const a=null==(o=e.headers)?void 0:o.authorization;if(a){const e=a.split(" ");if(2===e.length&&"Bearer"===e[0]&&e[1]===L)return n()}if((null==(i=e.query)?void 0:i.token)===L)return n();const s=((null==(r=e.headers)?void 0:r.cookie)||"").split(";").map(e=>e.trim()).find(e=>e.startsWith(D+"="));if(s&&s.split("=")[1]===L)return n();try{var c,l;const t=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown";z(`token|${t}|${e.path}`,`path=${e.path} ua="${t}" — no valid token or cookie`)}catch{}return t.status(401).send("Unauthorized: token required")}),P.use(Rh(R)),t.ora?(t.ora.start("Starting MCP server..."),t.ora.succeed(`MCP server available at ${nd}/mcp`)):console.log(`\nMCP server available at ${nd}/mcp .`),P.use(Qf);const q="\n <title>Needle Cloud</title>\n <link rel=\"icon\" href=\"https://cdn.needle.tools/static/branding/favicon.ico\" type=\"image/x-icon\">\n <style>\n body { \n font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;\n font-size: 18px;\n padding: 2rem;\n background: #f0f4ef;\n }\n a {\n color: rgb(120, 76, 223);\n }\n .main_panel {\n display: flex;\n flex-direction: column;\n gap: .5rem;\n justify-content: flex-start;\n align-items: center;\n width: min(80ch, 90vw);\n margin: 0 auto;\n\n height: 100%;\n\n & img.logo {\n height: 3rem;\n margin-bottom: 1rem;\n }\n }\n .secondary {\n color: rgba(0, 0, 0, .5);\n }\n .error-details {\n font-size: 12px;\n color: rgba(0, 0, 0, .5);\n }\n .error-details a {\n color: inherit;\n }\n </style>",B=`<div class="main_panel"><img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" title="Needle Logo (${wm()})"/>`,M="</div>";let G="";P.get("/",Qd(),async(e,t)=>{var n,o;if(null!=(n=e.user)&&n.isAuthenticated?t.cookie(D,L,{httpOnly:!0,sameSite:"strict",path:"/"}):t.clearCookie(D,{path:"/"}),t.set({"Content-Type":"text/html; charset=utf-8"}),t.write(q),null!=e.query.cancelled)return t.end("Login cancelled. You can close this window now."),void mu("Login cancelled by user");if(null!=e.query["too-many-logins"]&&R.logged_in_machine_names.length){var i;const e=Kp();let n="<div>";return n+="<strong>You have reached the maximum number of allowed device logins!</strong><br/><br/>",n+=(null==(i=R.logged_in_machine_names)?void 0:i.map(e=>`• ${e}`).join("<br/>"))+"<br/><br/>",n+=`1) Go to <a href="${e}#device-logins" target="_blank">Needle Cloud device logins</a> and logout one of your devices.<br/>\n 2) Then <a href="${a}">sign-in on this machine</a>.<br/><br/>`,n+="</div>",t.status(406),t.end(B+n+M),void mu(`Login failed: Too many logins from different machines: [${R.logged_in_machine_names.join(", ")}]`)}if(null!=e.query.error)return t.status(500),void t.end(`${B}\n <div>\n <strong>An error occurred</strong>: Please make sure <i>https://cloud.needle.tools/api</i> and <i>https://auth.needle.tools</i> are reachable and not blocked by your firewall or network. After that please try to <a href="${a}">sign-in</a> again.\n <br/><span class="error-details">If the issue persists, please contact support and include the log file: <a title="Link to local log file. Please copy this url and open it in your file explorer or terminal" href="file://${pu()}" target="_blank">${pu()}</a></span>\n </div>\n ${M}`);if(null!=(o=e.user)&&o.isAuthenticated){var r;if(!await sm(e.user)){if(R.invalid_login=!0,R.logged_in_machine_names=[...rm(e.user)],Td(),mu("Cleared stored auth data"),"client"in e.user){const t=e.user;await t.client.clearAccessToken(),await t.client.clearAllTokens(),mu("Cleared all tokens")}return t.end(`${B}<div>You have been logged out from this machine. You can close this window now or try to <a href="${a}">sign in</a> again</div>${M}`)}R.invalid_login=!1,t.end(`${B}\n <div>\n Hi ${Zd(e.user)} — you logged in successfully. You can close this window now.\n </div>\n ${M}`);const n=`Logged in successfully as ${Zd(e.user)} (${null==(r=e.user.userInfo)?void 0:r.sub})`;return void(G!==n&&(G=n,mu(G)))}let s=`<span><a href="${a}">Sign in</a> to your Needle account</span>`;"1"===e.query["signed-out"]&&(s=`<span class="secondary">You have been signed out successfully.</span>${s}`),t.write(B+s+M),t.end()}),P.post("/restart",(e,n)=>{var o,i;if(!Ph("https://cloud.needle.tools/api",e.headers["x-needle-api-endpoint"],"true"===e.headers["x-needle-explicit-restart"]))return mu("Rejected restart from a CLI targeting another API endpoint"),void n.status(409).end("A Needle CLI connected to a different environment is already running.");null==(o=A)||o.shutdownRequested("restart",{integration:e.headers["x-needle-client-integration"],version:e.headers["x-needle-client-version"],pid:Number(e.headers["x-needle-client-pid"])}),t.ora&&(t.ora.text="Received restart event. This instance will close"),null==(i=N)||i.close(e=>{e&&console.error(e)}),setTimeout(()=>{process.exit(0)},100),n.status(200).end("Server is restarting"),mu("Server is restarting\n")}),P.get("/api/logs",async(e,t)=>{const n=pu();l(n)?b(n,"utf-8",(e,o)=>{if(e)return console.error(e),void t.status(500).end("Failed to read log file");t.set({"Content-Type":"text/plain; charset=utf-8"});const i=o.split("\n").filter(e=>e.length>0).reverse().join("\n");let r=`--- Needle CLI v${wm()} (built ${Zh}) Log File (newest first) ---\n${n}\n\n`;r+=i,t.status(200).end(r)}):t.status(404).end("Log file not found")}),P.get("/api/info",(e,t)=>{var n;t.json({...Kh("https://cloud.needle.tools/api",wm()),...null==(n=A)?void 0:n.info})}),P.get(s,Qd(),async(e,t)=>{var n;if(!0===R.invalid_login){const e=ng(R);return t.status(e.status).json(e)}R.invalid_login=!1,t.status(null!=(n=e.user)&&n.isAuthenticated?200:400).send()}),P.get("/api/user",Qd(),async(e,t)=>{var n;const o=e.user;if(null==o||!o.isAuthenticated){if(!0===R.invalid_login){const e=ng(R);return t.status(e.status).json(e)}return t.status(401).json({error:"Not authenticated"})}if(R.invalid_login=!1,!await sm(o))return Td(),t.status(403).json({error:"You have been logged out from this machine"});if(null==o||!o.claims)return t.status(400).json({error:"User claims not found"});if(null==o||!o.userInfo)return t.status(400).json({error:"User info not found"});const i=null==o||null==(n=o.claims)?void 0:n.organization_roles,r=null==o?void 0:o.userInfo.custom_data,a={authenticated:o.isAuthenticated,id:o.userInfo.sub,name:Zd(o),email:o.claims.email||o.userInfo.email||"",profile_picture:o.userInfo.picture||"",default_org_id:(null==r?void 0:r.default_org)||"none",orgs:[]},s=["manage","owner","member","developer"];o.userInfo.organization_data&&(a.orgs=o.userInfo.organization_data.map(e=>{var t;const n={id:e.id,name:e.name,roles:(null==i?void 0:i.filter(t=>t.startsWith(e.id)).map(e=>e.split(":")[1]))||[],canWrite:!1};return n.canWrite=null==(t=n.roles)?void 0:t.some(e=>s.includes(e)),n}).sort((e,t)=>e.id===a.default_org_id?-1:t.id===a.default_org_id?1:e.name.localeCompare(t.name))),t.json(a)}),P.get("/api/license",Qd(),async(t,n)=>{var o,i,r;const a=null==(o=t.query.token)?void 0:o.toString(),s=null==(i=t.query.org)?void 0:i.toString();let c=null;if(a)c={authToken:a};else{const e=await Hd();if(!e||!e.isAuthenticated)return n.status(401).json({error:"Not authenticated",code:"not_authenticated"});if(!await sm(e))return Td(),n.status(403).json({error:"Invalid login"});c=await Xd(e,s||null).catch(e=>({status:500,error:e.message}))}if(!c)return n.status(500).json({error:"Failed to fetch licenses (Missing auth)"});if("error"in c)return n.status(c.status).json({error:c.error});const l=bt(c),p=null==(r=t.query.integration)?void 0:r.toLocaleString(),u={...l,"x-needle":"cli","x-needle-integration":null!=p&&p.length?p:"unknown"},d=await e(`https://cloud.needle.tools/api${vt.account.get_licenses}`,{method:"GET",headers:u}).catch(e=>{const t=eg(e);return console.error("Failed to fetch licenses:",t),mu(`Failed to fetch licenses: "${t}" - is https://cloud.needle.tools/api reachable?`),null});if(!d)return n.status(502).json({error:"Failed to fetch licenses: upstream API unreachable"});if(d.ok){const e=await d.json();return void 0===e.can_use_editor&&(e.can_use_editor=!0),n.json(e)}return n.status(d.status).json({error:d.statusText})}),P.get("/api/deployments",Qd(),async(e,t)=>{var n;const o=await Hd();if(!o||!o.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const i=null==(n=e.query.org)?void 0:n.toString(),r=await Xd(o,i).catch(e=>({status:500,error:e.message}));if("error"in r)return t.status(r.status).json({error:r.error});if(i&&!r.org)return t.status(400).json({error:"Organization not found"});const a=await Zu({endpoint:"https://cloud.needle.tools/api",authToken:r.authToken,org:r.org||void 0,limit:20,offset:0,names:void 0}).catch(e=>(console.error("List Deployments error: "+e.message),{status:502,error:"Failed to list deployments: upstream API unreachable"}));if("error"in a)return t.status(a.status).json({error:a.error});for(const e of a.deployments)e.editUrl=`${Yp()}/${e.id}`;const s={...a};return t.json(s)}),P.get(p,Qd(),async(e,t)=>{var n,o,i,r,a,s,c,l;const p=await Hd();if(!p||!p.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const u=(null==(n=e.query.org)?void 0:n.toString())||(null==(o=p.userInfo)||null==(o=o.custom_data)?void 0:o.default_org)||void 0,d=await Xd(p,u).catch(e=>({status:500,error:e.message}));if("error"in d)return t.status(d.status).json({error:d.error});const m={content_type:(null==(i=e.query.content_type)?void 0:i.toString())||void 0,content_format:(null==(r=e.query.content_format)?void 0:r.toString())||void 0,search:(null==(a=e.query.search)?void 0:a.toString())||void 0,tags:(null==(s=e.query.tags)?void 0:s.toString())||void 0,types:(null==(c=e.query.types)?void 0:c.toString())||void 0,trash:"true"===e.query.trash||void 0,collection_id:(null==(l=e.query.collection_id)?void 0:l.toString())||void 0,limit:e.query.limit?parseInt(e.query.limit.toString()):void 0,page:e.query.page?parseInt(e.query.page.toString()):void 0,offset:e.query.offset?parseInt(e.query.offset.toString()):void 0},f=await sp({baseUrl:"https://cloud.needle.tools/api",authToken:d.authToken,org:d.org||void 0},m).catch(e=>(console.error("List content error: "+e.message),{status:502,error:"Failed to list content: upstream API unreachable"}));return"error"in f?t.status(f.status).json({error:f.error}):t.json(f)}),P.get(p+"/:identifier",Qd(),async(e,t)=>{var n,o;const i=await Hd();if(!i||!i.isAuthenticated)return t.status(401).json({error:"Not authenticated"});const r=(null==(n=e.query.org)?void 0:n.toString())||(null==(o=i.userInfo)||null==(o=o.custom_data)?void 0:o.default_org)||void 0,a=await Xd(i,r).catch(e=>({status:500,error:e.message}));if("error"in a)return t.status(a.status).json({error:a.error});const s=await cp({baseUrl:"https://cloud.needle.tools/api",authToken:a.authToken,org:a.org||void 0},e.params.identifier).catch(e=>(console.error("Get content error: "+e.message),{status:502,error:"Failed to get content: upstream API unreachable"}));return"error"in s?t.status(s.status).json({error:s.error}):t.json(s)}),P.get(c,Qd(),async(t,n)=>{const o=await Hd();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i=`https://cloud.needle.tools/api${vt.local_projects.get.user}`,r=await e(i,{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}}).catch(e=>(console.error("Failed to fetch projects:",eg(e)),null));if(!r)return n.status(502).json({error:"Failed to fetch projects: upstream API unreachable"});if(!r.ok)return n.status(r.status).json({error:r.statusText});const a=await r.json().catch(e=>console.error(e));return n.json(a)}),P.get(c+"/:id",Qd(),async(t,n)=>{var o;const i=await Hd();if(!i||!i.isAuthenticated)return n.status(401).json({error:"Not authenticated"});let r=null==(o=t.query.org)?void 0:o.toString();const a=await Xd(i,r).catch(e=>({status:500,error:e.message}));if(!a)return n.status(500).json({error:"Failed to fetch projects"});if("error"in a)return n.status(a.status).json({error:a.error});const s=bt(a),c=`https://cloud.needle.tools/api${vt.local_projects.get.by_id}${encodeURIComponent(t.params.id)}`,l=await e(c,{method:"GET",headers:{...s}}).catch(e=>(console.error("Failed to fetch project:",eg(e)),null));if(!l)return n.status(502).json({error:"Failed to fetch project: upstream API unreachable. Please try again later or contact hi@needle.tools"});if(!l.ok)return n.status(l.status).json({error:l.statusText});const p=await l.json().catch(e=>(console.error(e),null));return p?n.json(p):n.status(500).json({error:"Failed to parse data. Please try again later or contact hi@needle.tools"})}),P.post("/api/projects",Qd(),async(t,n)=>{const o=await Hd();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i="string"==typeof t.body?JSON.parse(t.body):t.body,r={machine_id:await cm(),project_id:i.project_id,project_name:i.project_name,scene_name:i.scene_name,web_project_path:i.web_project_path,editor_name:i.editor_name,editor_version:i.editor_version};if(!r.project_id||!r.project_name)return n.status(400).json({error:"Invalid request"});const a=`https://cloud.needle.tools/api${vt.local_projects.post}`,s=await e(a,{method:"POST",headers:{Authorization:`Bearer ${o.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(r)}).catch(e=>(console.error("Failed to upsert project:",eg(e)),null));return s?s.ok?n.send("OK"):n.status(s.status).json({error:s.statusText}):n.status(502).json({error:"Failed to upsert project: upstream API unreachable"})}),P.get("/api/public_key",Qd(),async(t,n)=>{var o,i;const r=await Hd();if(!r||!r.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const a=null==(o=t.query.org)?void 0:o.toString(),s=await Xd(r,a).catch(e=>({error:e.message,status:500}));if(!s)return n.status(500).json({error:"Failed to fetch public key"});if("error"in s)return n.status(s.status).json({error:s.error});const c={project_id:(null==(i=t.query.project_id)?void 0:i.toString())||void 0,machine_id:await cm()},l=await e(`https://cloud.needle.tools/api${vt.account.public_key}`,{method:"POST",headers:{...bt(s),"Content-Type":"application/json"},body:JSON.stringify(c)}).catch(e=>(console.error("Failed to fetch public key:",eg(e)),null));if(!l)return n.status(502).json({error:"Failed to fetch public key: upstream API unreachable"});if(l.ok){const e=await l.json().catch(console.error);return null!=e&&e.public_key?n.json(e):n.status(500).json({error:"Failed to fetch public key"})}return n.status(l.status).json({error:l.statusText})}),P.get("/api/local_project_id",async(e,t)=>{const n=e.query.paths;if(!n)return t.status(400).json({error:"Missing paths"});let o=[];"string"==typeof n?o=n.split(",").map(e=>e.trim()).filter(e=>e.length>0):Array.isArray(n)&&(o=n.map(e=>e.toString().trim()).filter(e=>e.length>0));const i=Uh(o);return i?t.json({project_id:i}):t.status(404).json({error:"Project ID not found"})}),P.post("/api/project/info",Qd(),async(e,t)=>{(function(e){try{!function(e){var t,n,o,i;const r={last_accessed:Date.now(),editor:null!=(t=e.scene_path)&&t.endsWith(".unity")?"unity":null!=(n=e.scene_path)&&n.endsWith(".blend")?"blender":"unknown",editor_version:e.editor_version,editor_installation_path:e.editor_installation_path,log_location:e.editor_log_path,project_location:e.unity_project_path||e.blender_project_path||e.scene_path,scene_location:e.scene_path,web_location:e.web_project_path,needle_engine_integration_location:e.needle_sourcecode_location},a=bm();let s=ym();const c=s.entries.findIndex(e=>e.project_location===r.project_location),l=null==(o=s.entries[0])?void 0:o.project_location;-1!==c?s.entries[c]=r:s.entries.push(r),s.entries.sort((e,t)=>t.last_accessed-e.last_accessed);let p=0;s.entries=s.entries.filter(e=>"cli"===e.source||++p<=30);const u=null==(i=s.entries[0])?void 0:i.project_location;u&&u!==l&&mu(`Active project changed: ${l||"(none)"} → ${u}`);try{um=s;const e=JSON.stringify(s);h(a,e,"utf-8")}catch(e){console.error("Failed to save project info:",e)}}(e)}catch(e){mu("Error saving project info: "+e)}})("string"==typeof e.body?JSON.parse(e.body):e.body),t.send("OK")});let J=null;const V=new Promise(e=>J=e);let K=!1;if(N=(v=P,tt({maxHeaderSize:131072},v)).listen(td,()=>{null==J||J()}),N.on("error",e=>{if("EADDRINUSE"===(null==e?void 0:e.code))return mu(`License server port ${td} already in use — a server is already running; not starting a second one.`),K=!0,u.isHost=!1,void(null==J||J());console.error("[needle] License server failed to start:",(null==e?void 0:e.message)||e),mu(`License server failed to start: ${(null==e?void 0:e.message)||e}`),process.exit(1)}),function(e,t){e.on("connection",e=>{const n=e.remoteAddress;if(!function(e){if(!e)return!1;const t=e.includes("%")?e.slice(0,e.indexOf("%")):e;return"127.0.0.1"===t||"::1"===t||"::ffff:127.0.0.1"===t}(n)){try{null==t||t(`Local server: rejected non-loopback connection from ${n||"unknown"}`)}catch{}e.destroy()}})}(N,mu),N.on("close",g),process.on("exit",g),process.on("SIGINT",()=>{var e;null==(e=A)||e.shutdownRequested("SIGINT"),g(),process.exit(0)}),await V.catch(e=>{console.error(e),mu(`Error starting the auth server (promise failed): ${e.message}`)}),K)return u;function g(){mu("Cleaning up auth server...")}A=function(e){var t,n;const o=null!=(t=e.proc)?t:process,i=null!=(n=e.log)?n:du,a={instance_id:r(16).toString("hex"),started_at:(new Date).toISOString(),pid:o.pid,parent_pid:o.ppid,version:Wh(e.version),integration:Wh(e.integration)};let s;const c=(e,t={})=>i(`[local-server] ${JSON.stringify({...a,event:e,...t})}`),l=(e,t={})=>{null!=s||(s=e),c("shutdown_requested",{reason:e,requester:{integration:Wh(t.integration),version:Wh(t.version),pid:"number"==typeof t.pid&&Number.isSafeInteger(t.pid)&&t.pid>0?t.pid:void 0}})};return o.on("exit",e=>{var t;return c("exit",{exit_code:e,reason:null!=(t=s)?t:"unexpected_exit"})}),o.on("uncaughtExceptionMonitor",(e,t)=>c("crash",{error_name:Wh(null==e?void 0:e.name),error_code:Wh(e&&"code"in e?e.code:void 0),origin:Wh(t)})),o.on("SIGTERM",()=>{l("SIGTERM"),o.exit(143)}),{info:a,started:()=>c("started"),shutdownRequested:l}}({version:wm(),integration:t.integration}),A.started();const Y=function(e,t){const n=new He({server:e,path:"/mcp/ws",verifyClient:({req:e},t)=>{var n;if(!zh(e.headers.host))return mu(`${Bh} rejected WS upgrade: host not allowed`),void t(!1,403,"Forbidden: host not allowed");const o=null==(n=e.headers)?void 0:n.origin;if(o&&!qh(o))return mu(`${Bh} rejected WS upgrade: disallowed origin ${o}`),void t(!1,403,"Forbidden: origin not allowed");t(!0)}});mu("MCP websocket server created.");let o=0,i=new Map;return n.on("connection",e=>{const t=++o;Mh.push(e),console.log(`${Bh} client connected (#${t})`),mu(`${Bh} client connected (#${t})`),e.on("close",()=>{const n=Mh.indexOf(e);-1!==n&&Mh.splice(n,1);const o=i.get(t);if(o){for(const e of o)$m(e,mh);i.delete(t)}console.log(`${Bh} client disconnected (#${t})`),mu(`${Bh} client disconnected (#${t})`)});const n=new Map;e.on("message",o=>{try{const r=o.toString(),a=JSON.parse(r);switch(a.command){default:console.log(`${Bh} Unknown command: ${a.command}`),mu(`Unknown MCP websocket command received: ${a.command}`);break;case"get_connected_clients":!function(t,n){const o={clients:[...oh()],command:"mcp_server_response",messageId:"messageId"in t?t.messageId:void 0};e.send(JSON.stringify(o))}(a);break;case"register_tools":{const o=a.tools,r=a.source;if("cli"===r||"cloud"===r)throw new Error("The CLI and cloud tool sources are reserved for built-in tools.");r&&Tm(r,mh);const s=r||"unknown";console.log(`${Bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`),mu(`${Bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`);const c=i.get(t)||new Set;i.set(t,c);for(const t of o)Im(t,async o=>{console.log(`Tool ${t.name} executed via WebSocket with args:`,o);const i=`${t.name}-${Date.now()}-${Math.random()}`;return await new Promise((r,a)=>{const s=setTimeout(()=>{n.has(i)&&(console.error(`${Bh} Tool execution timed out for tool: ${t.name}`),n.delete(i),a(new Error(`Tool execution timed out for tool: ${t.name}`)))},3e4);n.set(i,{resolve:e=>{r(e),clearTimeout(s)},reject:a}),e.send(JSON.stringify({command:"execute_tool",toolName:t.name,args:o,requestId:i}))})},{source:r},mh),c.add(t.name);break}case"tool_result":{const e=a.requestId,t=a.result;if(console.log(`${Bh} Received tool result for requestId: ${e}`,t),n.has(e)){const o=n.get(e);null==o||o.resolve(t),n.delete(e)}else console.error(`${Bh} No pending tool execution found for requestId: ${e}`);break}}}catch(e){console.error(`${Bh} Error processing WebSocket message:`,e)}})}),n}(N);zf({logToolCount:!0}),Th();const Z=gf(U,()=>{df()?(mu("Settings changed: remote_ai_tools disabled — closing cloud connection"),$h("remote_ai_tools setting disabled")):(mu("Settings changed: remote_ai_tools enabled — opening cloud connection"),Th())});tm(P,L,()=>{mu("Authenticated stop requested; shutting down the local Needle server."),N&&nm(N,Y,()=>{Z(),$h("stop requested")})},e=>{var t;return null==(t=A)?void 0:t.shutdownRequested("stop",e)}),process.on("exit",()=>{Z(),$h("process exit")})}var v,y;return u}function ng(e){let t="";return t=e.error?e.error:e.logged_in_machine_names.length>0?`You're already authenticated on ${e.logged_in_machine_names.length} other machine(s)${e.user_email?` with ${e.user_email}`:""}. Please logout from other machines first on ${Kp()}. You're currently logged in on: ${e.logged_in_machine_names.join(", ")}`:"An unknown error occured.",{status:403,error:t}}async function og(e={headless:!1,silent:!1,clearAuthData:!1}){return!0===e.clearAuthData&&await Td(),rg("sign-in",{...e})}function ig(e={}){return rg("sign-out",{...e})}function rg(t,n){return new Promise(async(o,i)=>{let r=!1;if("sign-in"==t){const e=await Hd();if(null!=e&&e.isAuthenticated&&e.accessToken)return await pm(e)?(r=!0,n.ora&&(n.ora.text=`Authorized as ${Zd(e)}`),"gotoAccountPage"in n&&!0===n.gotoAccountPage&&(n.ora&&(n.ora.text="Opening account page in the browser"),Zp(Kp()),await new Promise(e=>setTimeout(e,2e3))),o(e)):o(null);if(!0===n.headless)return o(null)}else if("sign-out"==t&&!0===n.headless){r=!0,Td();const t=await tg(),n=await e(t.auth_endpoints["sign-out"],{follow:2});return o(n.ok)}const a=await tg();switch(n.timeout||(n.timeout=6e5),"number"==typeof n.timeout&&n.timeout>0&&setTimeout(()=>{r||(n.ora&&n.ora.fail('Timeout "'+t+'"'),o(null))},n.timeout),t){case"sign-in":const e=a.auth_endpoints["sign-in"];setTimeout(()=>Zp(e),300),n.ora&&(n.ora.text=`Please authenticate in the browser: ${e}`),setTimeout(l,2e3);break;case"sign-out":Td(),Zp(a.auth_endpoints["sign-out"]),setTimeout(l,2e3)}let s=0;const c=10;function l(){e(a.auth_endpoints["is-authenticated"]).then(async e=>{if(200===e.status||400===e.status||403===e.status)switch(t){case"sign-in":if(200===e.status){const e=await Hd();return e&&!await pm(e)?o(null):(r=!0,n.ora&&e&&(n.ora.text="User is authenticated"),o(e))}if(403===e.status){n.ora&&n.ora.fail("Authentication failed");const t=await e.text();if(t.startsWith("{")){const e=JSON.parse(t);if("logged_in_machine_names"in e&&Array.isArray(e.logged_in_machine_names)){const t=e.logged_in_machine_names;$().fail(`You're already authenticated on ${t.length} other machine(s). Please logout from other machines first. You're currently logged in on: ${t.join(", ")}`)}}return o(null)}break;case"sign-out":if(400===e.status)return r=!0,Td(),n.ora&&(n.ora.text="User is signed-out"),o(!0)}else if(s++,s>c)return n.ora?n.ora.fail(`Failed to complete auth flow. Please try again. Make sure that port ${a.port} is not blocked`):n.silent||console.error(`Failed to complete auth flow. Please try again. Make sure that port ${a.port} is not blocked`),o(null);setTimeout(l,1e3)}).catch(e=>{s>=10&&console.debug("Error polling auth status: "+e.message)})}})}globalThis.fetch||(globalThis.fetch=e),globalThis.File||(globalThis.File=t),globalThis.crypto||(globalThis.crypto=n.webcrypto),function(e={}){var t,n,o;const i=null!=(t=e.proc)?t:process,r=null!=(n=e.log)?n:du,a=null!=(o=e.error)?o:e=>console.error(e),s=(e,t)=>{const n=t instanceof Error&&t.message||String(t);try{const o=t instanceof Error&&t.stack?`\n${t.stack}`:"";r(`CLI crashed (${e}): ${n}${o}`)}catch{}try{a(`error: ${n}`)}catch{}try{i.exit(1)}catch{}};i.on("unhandledRejection",e=>s("unhandled rejection",e)),i.on("uncaughtException",e=>s("uncaught exception",e))}();const ag=process.argv.includes("--silent"),sg=JSON.parse(u(new URL("../package.json",import.meta.url),"utf-8")),cg="The access token to use. Use the login command or get a token from https://cloud.needle.tools. You can pass the access token with your command or set the environment variable NEEDLE_CLOUD_TOKEN";async function lg(e,t=null,n=!0){let o,i=null==e?void 0:e.toString();var r;if(i||(Fe.config(),process.env.NEEDLE_CLOUD_TOKEN&&(i=process.env.NEEDLE_CLOUD_TOKEN,null!=(r=i)&&r.length&&console.error("Using NEEDLE_CLOUD_TOKEN token from env"))),""===i||"true"===i){if(!n)throw new Error("--token requires a value in non-interactive mode.");const e=(await import("node:readline")).createInterface({input:process.stdin}),t=10;let i,r="",a=!1;return new Promise(n=>{const s="Paste your https://cloud.needle.tools/team#token access token here:",c=$({text:s,interval:200,spinner:"moon"}).start();process.stdin.setRawMode(!0),process.stdin.on("data",l=>{const p=l.toString();""===p&&process.exit();const u="\n"===p||"\r"===p;if(!u&&"\n"!==p&&"\r"!==p){""===p||"\b"===p?r=r.slice(0,-1):r+=p;const e=r.replace(/./g,"*");c.text=`${s} ${e}`}clearTimeout(i),i=setTimeout(()=>{if(!a&&(u||r.trim().length>t)){process.stdin.setRawMode(!1),e.close(),a=!0;const t=r.trim();if(t.length>0){const e=t.slice(3,-3).replace(/./g,"*");c.succeed("Access token received: "+e)}else c.fail("No access token provided");n({accessToken:t,org_id:o})}},150)})})}if(!i){let e;n&&!await async function(){const e=await Hd();return null==e?void 0:e.isAuthenticated}()&&(e=ag?void 0:$("No access token found. Please sign in to authenticate...").start()),mu("No access token provided, attempting login. Org: "+t);const r=og({headless:!n,ora:e,timeout:12e4}),d=await r;if(d&&!await sm(d)){var a;if(!n)throw new Error("Saved authentication is invalid. Provide --token or NEEDLE_CLOUD_TOKEN.");null==(a=e)||a.fail("You are not logged in from this machine. Please login again."),await ig({headless:!0}),process.exit(1)}else e&&(mu("User logged in via getAccessToken "+(null==d?void 0:d.isAuthenticated)),d?e.succeed("Logged in"):e.fail("Login failed"));if(null!=d&&d.isAuthenticated){var s;if(null==t){const e=await Jd(d);"string"==typeof e&&(t=e)}else t===(null==(s=d.userInfo)?void 0:s.sub)&&(t=null);if(t){var c,l,p;if(o=null==(c=d.userInfo)||null==(c=c.organization_data)||null==(c=c.find(e=>e.id===t))?void 0:c.id,o||(t=null==(l=t.toString())?void 0:l.toLowerCase(),null!=o||(o=null==(p=d.userInfo)||null==(p=p.organization_data)||null==(p=p.find(e=>e.name.toLowerCase()===t))?void 0:p.id)),!o)throw new Error(`ERR: You (${Zd(d)}) are not a member of the team "${t}" or the team does not exist. Please check the team name/id and try again.`);i=await(null==d?void 0:d.client.getOrganizationToken(o)),mu("Getting access token for org "+o+", "+i.substring(0,8)+"...")}else{var u;mu("Getting access token for user "+(null==(u=d.userInfo)?void 0:u.sub)),i=null==d?void 0:d.accessToken}}}if(!i)throw mu("ERR: Missing NEEDLE_CLOUD_TOKEN token. Org: "+o),new Error("Missing authentication. Provide --token, set NEEDLE_CLOUD_TOKEN, or run needle-cloud login.");return{accessToken:i,org_id:o}}function pg(e){return null!=e.org&&console.warn("Warning: --org is deprecated. Use --team instead."),e.team||e.org}const ug=ht.program;async function dg(){const{spawn:e}=await import("node:child_process");e(process.execPath,[process.argv[1],"start","--integration","cli-login"],{stdio:"inherit",env:{...process.env,NEEDLE_CLOUD_TOKEN:process.env.NEEDLE_CLOUD_TOKEN||""}}),await new Promise(e=>setTimeout(e,1e3))}ug.version(sg.version).description("Command-line interface (CLI) for Needle Cloud"),ug.command("version","Print the CLI version").configure({visible:!1}).action(()=>{ag||console.log(`☁ Needle CLI — ${sg.version}, Node ${process.version}`)}),ug.command("start","Starts the Needle Auth server").alias("start-server").configure({visible:!1,strictOptions:!1}).help("Start the local server for Needle Cloud. This is required to authenticate with Needle Cloud and access your account and data.").option("--restart <restart>","Restarts the server",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--integration <integration>","Hint for the process which integration triggered this command",{required:!1,validator:ug.STRING}).action(async({options:e})=>{const t=e.integration,n=ag?void 0:$("Starting Needle License server "+(t?`(from ${t})`:"")).start();tg({ora:n,restart:e.restart,integration:t}).catch(e=>{console.error("Failed to start server:",e),null==n||n.fail("Failed to start server: "+e.message),process.exit(1)}).then(e=>{null!=e&&e.baseUrl&&e.isHost?null==n||n.succeed(`Server started on ${e.baseUrl} (v${wm()}, built ${function(e){if("string"!=typeof Zh||0===Zh.length)return"unknown";const t=new Date(Zh);if(Number.isNaN(t.getTime()))return"unknown";const n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}()})`):!1===(null==e?void 0:e.isHost)?(t||null==n||n.warn(`Server is running on ${e.baseUrl||e.port}`),process.exit(0)):(null==n||n.fail("Failed to start server"),process.exit(1))})}),ug.command("stop","Stop the local Needle license server").alias("quit").help("Request an authenticated shutdown of the local Needle server, then exit. Does not sign out or stop Unity. Older servers without stop support must be closed manually.").action(async()=>{try{const{stopLocalServer:e}=await Promise.resolve().then(function(){return om}),t=await e({version:wm()});ag||console.log("not-running"===t?"Needle server is not running.":"Needle server shutdown requested."),process.exit(0)}catch(e){console.error(`Could not stop the Needle server: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}),ug.command("settings","Show current Needle CLI settings").action(async()=>{const{readSettings:e,KNOWN_SETTINGS:t}=await Promise.resolve().then(function(){return vf}),n=e();for(const[e,o]of Object.entries(t)){const t=n[e],i=void 0!==t?String(t):o.default;console.log(`\n ${"enabled"===i?"[x]":"[ ]"} ${o.displayName}: ${i}${void 0===t?" (default)":""}`),console.log(` ${o.description}`),console.log(` Change: ${o.command}`)}console.log("")}),ug.command("settings remote-ai-tools","Enable or disable cloud AI tool dispatch to this machine").help("When disabled, the CLI does NOT connect to the Needle Cloud AI tool dispatcher (wss://cloud.needle.tools/v1/cli/ws), so cloud-side AI chats cannot invoke tools (file reads, grep, etc.) on this machine. The local /mcp/ws endpoint used by Unity/Blender stays available. Setting persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings remote-ai-tools",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled,i=n();o?(t(i,"remote_ai_tools",null),console.log("Remote AI tools enabled (default)."),mu("Settings: remote_ai_tools set to enabled (default) via CLI command")):(t(i,"remote_ai_tools","disabled"),console.log("Remote AI tools disabled. The cloud AI chat will not be able to dispatch tools to this machine."),mu("Settings: remote_ai_tools set to disabled via CLI command"))})),ug.command("settings local-file-edits","Enable or disable AI file changes on this machine").help("This local setting is checked for every AI write, delete, rename, Undo, and Redo. Cloud chat approval cannot override it. Persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings local-file-edits",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled;t(n(),"local_file_edits",o?null:"disabled"),console.log(`Local AI file edits ${o?"enabled":"disabled"}.`)})),ug.command("settings local-project-commands","Enable or disable approved AI project commands on this machine").help("Allows separately approved AI package installs, project creation, builds, and deploys. Enabled by default; Cloud chat approval cannot override this setting. Persists in ~/.needle/settings.json.").argument("<enabled>","true to enable, false to disable",{validator:ug.BOOLEAN}).action(yu("settings local-project-commands",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return vf}),o=e.enabled;t(n(),"local_project_commands",o?null:"disabled"),console.log(`Local AI project commands ${o?"enabled":"disabled"}.`)})),ug.command("status","Show the local Needle server status and process ID").action(yu("status",async()=>{const{getLocalServerStatus:e,formatLocalServerStatus:t}=await Promise.resolve().then(function(){return Yh});console.log(t(await e()))})),ug.command("mcp","Start MCP server for AI agents (stdio transport)").help('Start the Needle Cloud MCP server using stdio transport.\nReuses or starts the shared local server for Inspector/Unity tools and cloud connections.\nThis is the standard way to connect AI agents (Claude Desktop, Cursor, VS Code, etc.).\n\nAdd to your MCP client config:\n{\n "mcpServers": {\n "needle": {\n "command": "npx",\n "args": ["-y", "needle-cloud", "mcp"]\n }\n }\n}').action(yu("mcp",async()=>{const{startStdio:e}=await Promise.resolve().then(function(){return uh});e()})),ug.command("get-project-id","Gets the project id for a local project").configure({visible:!1,strictOptions:!1}).argument("<paths...>","The path to the local project (web project directory)").action(async({args:e})=>{const t=Uh(e.paths);t?console.log(`Found project ID: "${t}"`):console.log("No project ID found.")}),ug.command("send-logs","Upload CLI, editor, and optimization-pipeline logs to Needle (secrets and sensitive info redacted)").help("Stream the current and previous CLI log, the most recent editor log (Unity or Blender), and the optimization-pipeline log to Needle for support diagnosis. Before upload, tokens, Bearer/Authorization values, UUIDs, home-directory paths, email addresses, Username/User fields, and *_KEY / *_TOKEN / *_SECRET / *_PASSWORD env-var values are redacted (replaced with <redacted:Nch> so the length is preserved for debugging). Returns a reference ID to paste into your bug report. Requires sign-in; the upload is tagged with your Needle account.").option("--crash <crash>","Mark this upload as a crash report (uses the crash-mode daily quota)",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--note <note>","One-line note attached to the upload",{required:!1}).option("--dry-run <dryRun>","Print the redacted payload without uploading",{required:!1,validator:ug.BOOLEAN,default:!1}).action(yu("send-logs",async({options:e})=>{var t,n,o,i,r,a,s;const{runSendLogs:c,HAYSTACK_RESOURCE:l}=await Promise.resolve().then(function(){return _d}),{tryGetFreshAccessTokenForResource:p}=await Promise.resolve().then(function(){return Yd}),{findActiveEditorLog:u}=await import("./cli.send-logs.discovery-4b1a3fdf.js"),{getLogFilePath:d,getPrevLogsFilePath:m,getPipelineLogFilePath:f}=await Promise.resolve().then(function(){return fu}),{homedir:h,platform:g}=await import("os"),{existsSync:v}=await import("fs"),{BUILD_TIME:b}=await Promise.resolve().then(function(){return Xh}),{getNodeVersion:y,getNpmVersion:x,getArch:w,getOsRelease:_,getCpuCount:S,getTotalMemoryMb:j,getTzOffsetMinutes:k,isCi:E,isTty:T}=await import("./cli.runtime-465aa7a3.js"),I=null!=(t=null!=(n=null==(o=e.crash)||null==o.valueOf?void 0:o.valueOf())?n:e.crash)&&t?"crash":"normal",C=e.note,O=null!=(i=null!=(r=null==(a=e.dryRun)||null==a.valueOf?void 0:a.valueOf())?r:e.dryRun)&&i,A=d(),N=m(),R=f(),P={getAccessToken:()=>p(l),fetch:globalThis.fetch,paths:{cliLogPath:v(A)?A:null,prevLogPath:v(N)?N:null,pipelineLogPath:v(R)?R:null,homeDir:h()},meta:{cli_version:wm(),build_time:b,os:g(),os_release:_(),arch:w(),node_version:y(),npm_version:null!=(s=x())?s:"unknown",cpu_count:S(),total_memory_mb:j(),tz_offset_minutes:k(),is_ci:E(),is_tty:T()},findActiveEditorLog:u,stdout:process.stdout,stderr:process.stderr},U=O?"Building payload (dry-run)":"Uploading logs",L=ag?void 0:$(U).start();P.recoverAuth=async()=>{null==L||L.stop();try{await dg();const e=await og({clearAuthData:!0,silent:ag,ora:void 0});if(null==e||!e.isAuthenticated)return null}catch(e){return mu(`send-logs: auto-recovery login failed: ${e instanceof Error?e.message:e}`),null}finally{null==L||L.start(U)}return await p(l)};const z=await c({mode:I,note:C,dryRun:O},P);z.ok?O?null==L||L.succeed("Dry-run payload printed above. Nothing was uploaded."):z.truncated?(null==L||L.warn(`Uploaded (truncated at server cap). Reference: ${z.refId}`),console.log(`Share ${z.refId} in your bug report.`)):(null==L||L.succeed(`Uploaded. Reference: ${z.refId}`),console.log(`Share ${z.refId} in your bug report.`)):(null==L||L.fail(z.error||"Upload failed"),process.exitCode=1)})),ug.command("login","Login to Needle Cloud").help("Login to Needle Cloud. If you are already logged in, this will refresh the access token.").option("--headless <headless>","The headless process will not open a browser window to login. If the user is not authorized then no auth flow can be started. Use this if you only want to **check** if the user is authenticated",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--clear <clear>","Refresh the access token",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({options:e})=>{const t=_u(e),n=!0===e.nonInteractive||!0===e.headless;n||await dg();const o=!0===e.clear,i=ag?void 0:$("Login").start();await og({headless:n,silent:ag,clearAuthData:o,ora:i}).then(async e=>{"json"===t&&ku({authenticated:!0===(null==e?void 0:e.isAuthenticated)}),null!=e&&e.isAuthenticated?null==i||i.succeed("Successfully logged in as "+Zd(e)):0==n?null!=e&&e.claims||null!=e&&e.userInfo?null==i||i.warn(`You (${Zd(e)}) are not authenticated...`):null==i||i.fail("Login failed"):ag||null==i||i.warn("Not logged in"),await Eu(null!=e&&e.isAuthenticated?0:1)})})),ug.command("logout","Logout of Needle Cloud").help("Logout of Needle Cloud (if you have logged in before).").option("--headless <headless>","Headless will not open a browser window to logout",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({options:e})=>{const t=_u(e),n=!0===e.nonInteractive||!0===e.headless;n||await dg(),await ig({headless:n}).then(async e=>{"json"===t&&ku({success:e}),e?$("Logged out").succeed():$("Logout failed").fail(),await Eu(e?0:1)})})),ug.command("me","Prints your user information").help("Prints basic informaton about the logged in Needle Cloud account (your account)").action(ju(async({options:e})=>{const t=_u(e),n=ag?void 0:$("Query user data").start(),o=await Hd(),i=Boolean((null==o?void 0:o.isAuthenticated)&&await sm(o));if("json"!==t)if(o&&i){const e=o.userInfo||o.claims;var r,a,s;e?(null==n||n.succeed(`You are logged in as ${Zd(o)}`),console.log(`- Name: ${Zd(o)}`),console.log(`- ID: ${e.sub}`),e.email&&console.log(`- Email: ${e.email}`),e.phone_number&&console.log(`- Phone: ${e.phone_number}`),null!=(r=o.userInfo)&&r.organization_data&&console.log(`- Teams [${null==(a=o.userInfo)?void 0:a.organization_data.length}]: ${null==(s=o.userInfo)?void 0:s.organization_data.sort((e,t)=>e.name.localeCompare(t.name)).map(e=>e.name).join(", ")}`)):null==n||n.fail("Failed to get user data")}else null==n||n.warn("You are not logged in");else{null==n||n.stop();const e=(null==o?void 0:o.userInfo)||(null==o?void 0:o.claims);var c,l;o&&i&&e?ku({authenticated:!0,id:e.sub,name:Zd(o),email:e.email,teams:(null!=(c=null==(l=o.userInfo)?void 0:l.organization_data)?c:[]).map(e=>({id:e.id,name:e.name}))}):(ku({authenticated:!1}),process.exitCode=1)}})),ug.command("get-pro","Start license flow for Needle Engine PRO").configure({visible:!1,strictArgsCount:!1,strictOptions:!1}).option("--team <team>","The team to purchase the license for",{validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{validator:ug.STRING,hidden:!0}).action(yu("get-pro",async({options:e})=>{var t;let n=(null==(t=pg(e))?void 0:t.toString())||null;const o=$().start("Start Needle Engine PRO purchase flow"),i=function(e){e=e||{};const t="undefined"!=typeof window?window.location:null;"current_page"===e.baseUrl&&(e.baseUrl=null==t?void 0:t.href);let n=e.pathname||(null==t?void 0:t.pathname),o=e.baseUrl||(null==t?void 0:t.href);if(!n||!o)return null;const i=new URL(n,o);return t&&(i.search=t.search),e.license||(e.license="needle-engine:pro"),i.searchParams.set("purchase_intent",e.license),e.account_id&&i.searchParams.set("account_id",e.account_id),e.return_url&&i.searchParams.set("return_url",e.return_url),e.checkout_if_possible&&i.searchParams.set("checkout_if_possible","true"),e.show_all_cards&&i.searchParams.set("show_all_cards","true"),e.affiliate_id&&i.searchParams.set("affiliate_id",e.affiliate_id),e.tracking_id&&i.searchParams.set("tracking_id",e.tracking_id),i}({baseUrl:"https://cloud.needle.tools",pathname:n?`/team/${n}`:"/account",account_id:n,license:"needle-engine:pro",return_url:null});if(!i)return void o.fail("Failed to get purchase url - please visit https://cloud.needle.tools");const r=i.toString();o.succeed(`Started Needle Engine PRO purchase flow: opening browser at ${r}`),Zp(r)}));const mg={account:{url:Kp}},fg=`"${Object.keys(mg).join('", "')}"`;ug.command("open",`Open a page in the default browser. Options are: ${fg}`).argument("<page>",`The page to open. Options are: ${fg}`,{validator:ug.STRING}).configure({strictOptions:!1,strictArgsCount:!1,visible:!1}).help("").action(async({args:e,logger:t})=>{const n=e.page.toString(),o=mg[n];o?"url"in o?Zp(o.url()):t.error(`Unknown argument: ${n}`):t.error(`Unknown argument: ${n}. Options are: ${fg}`)}),ug.command("list-deployments","Get a list of deployed websites").configure({visible:!1}).help("").option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--limit <limit>","Limit the number of deployments to show (min: 0, max: 100)",{validator:ug.NUMBER,default:10}).option("--offset <offset>","The offset for deployments (default: 0, min: 0)",{validator:ug.NUMBER,default:0}).option("--format <format>","Legacy output option: cli or json",{validator:ug.STRING,hidden:!0}).option("--name","Filter by one or multiple deployment names (separated by ;)",{validator:ug.STRING}).action(ju(async({options:e,logger:t})=>{var n,o,i,r;const a=_u(e,{legacyFormat:!0}),{accessToken:s,org_id:c}=await lg(e.token,pg(e),!0!==e.nonInteractive),l=(null==(n=e.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",p=Number(null!=(o=e.limit)?o:10),u=Number(null!=(i=e.offset)?i:0),d=(null==(r=e.name)?void 0:r.toString())||void 0;if(p<0)throw new Error("The limit cannot be negative.");if(p>100)throw new Error("The limit cannot exceed 100.");const m=$("Query deployments").start(),f=await Zu({endpoint:l,authToken:s,org:c,limit:p,offset:u,names:null==d?void 0:d.split(";")});if(f&&"error"in f)throw new Error(f.error+" (status: "+f.status+")");if(!f)throw new Error("Failed to query deployments.");if("json"===a)return m.succeed(`Found ${f.deployments.length} deployments`),void ku(f.deployments);f.deployments.length>0?(m.succeed(`Found ${f.deployments.length} deployments`),f.deployments.forEach((e,n)=>{t.info(`${n+p*u}: ${e.name} – ${e.url}`)})):m.warn("No deployments found")}));for(const e of["list","search"]){const t=ug.command(e,"search"===e?"Search content items by name, title or description":"List content items (3d assets, deployments, materials, etc.)");"list"===e?t.alias("list-content"):t.argument("<query>","Search by name, title or description",{validator:ug.STRING}),t.help(("search"===e?"Search":"List")+' content items stored in Needle Cloud.\n\nUse --type to filter by content type (e.g. "material", "3d-asset", "deployment").\nUse --format to filter by output format (e.g. "glb", "textures").\nUse --include-projects to include saved web projects; --type editor-project selects only projects.').option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--include-projects","Include saved web projects (default: uploaded content only)",{validator:ug.BOOLEAN,default:!1}).option("--trash","List deleted items instead of active content",{validator:ug.BOOLEAN,default:!1}).option("--interactive","Override automatic terminal browsing: true or false",{validator:ug.BOOLEAN}).option("--type <type>","Filter by content type (e.g. material, 3d-asset, deployment, editor-project)",{required:!1,validator:ug.STRING}).option("--format <format>","Filter by output format (e.g. glb, textures)",{required:!1,validator:ug.STRING}).option("--search <search>","Search by name, title or description",{required:!1,validator:ug.STRING}).option("--limit <limit>","Max number of items to show (default: 20, max: 100)",{validator:ug.NUMBER,default:20}).option("--offset <offset>","Offset for pagination (default: 0)",{validator:ug.NUMBER,default:0}).option("--output <output>","Output style: cli (default), json",{validator:ug.STRING,default:"cli"}).action(ju(async({args:t,options:n,logger:o})=>{var i,r,a,s,c,l,p;const u="search"===e?String(null!=(i=t.query)?i:"").trim():void 0;if("search"===e&&!u)throw new Error("Search query must not be empty.");if(u&&void 0!==n.search&&n.search.toString()!==u)throw new Error("Conflicting query and --search. Supply one search value.");const d=_u(n),m=Uu(n),f=Number(null!=(r=n.limit)?r:20),h=Number(null!=(a=n.offset)?a:0);if(!Number.isInteger(f)||f<1)throw new Error("--limit must be a positive integer.");if(!Number.isInteger(h)||h<0)throw new Error("--offset must be a nonnegative integer.");const g=null==(s=n.type)?void 0:s.toString(),v=null==(c=n.format)?void 0:c.toString();if(g&&"editor-project"!==g&&!rp.some(e=>e===g))throw new Error("Invalid --type. Use "+[...rp,"editor-project"].join(", ")+".");if(v&&!ap.some(e=>e===v))throw new Error("Invalid --format. Use "+ap.join(", ")+".");const{accessToken:b,org_id:y}=await lg(n.token,pg(n),!0!==n.nonInteractive),x=(null==(l=n.endpoint)?void 0:l.toString())||"https://cloud.needle.tools/api",w=Math.min(f,100),_=g||void 0,S=v||void 0,j=null!=u?u:(null==(p=n.search)?void 0:p.toString())||void 0,k={content_type:_,include_projects:!0===n.includeProjects,trash:!0===n.trash,content_format:S,search:j,limit:w,offset:h},E=$("Querying content...").start();try{const e=await sp({baseUrl:x,authToken:b,org:y},k);if(m)return E.stop(),await Wu({auth:{baseUrl:x,authToken:b,org:y},query:k,initial:e}),void await Eu(0);if("json"===d)return E.succeed(`Found ${e.items.length} of ${e.total} items`),void ku(e.items);0===e.items.length&&(E.warn("No content found"+(_?` (type: ${_})`:"")+(S?` (format: ${S})`:"")),process.exit(0)),E.succeed(`Found ${e.items.length} of ${e.total} items`);const t=e.items.map(e=>{var t;const n=e.title||"(untitled)";return{id:e.identifier,type:e.content_type||"?",formats:null!=(t=e.content_formats)&&t.length?e.content_formats.join(", "):"",name:n.length>20?n.slice(0,17)+"...":n,versions:String(e.version_count||0),date:e.created_at?Il(new Date(e.created_at),new Date,{allowSimple:!0,limitInDays:2}):""}}),n={id:Math.max(2,...t.map(e=>e.id.length)),type:Math.max(4,...t.map(e=>e.type.length)),formats:Math.max(7,...t.map(e=>e.formats.length)),name:Math.max(4,...t.map(e=>e.name.length))},i=ed(` ${"ID".padEnd(n.id)} ${"TYPE".padEnd(n.type)} ${"FORMATS".padEnd(n.formats)} ${"NAME".padEnd(n.name)} ${"#".padStart(3)} AGE`);o.info(i);for(const e of t){const t=Qu(e.type).padEnd(n.type+11),i=(e.formats?e.formats.split(", "):[]).map(e=>Qu(e)).join(", ")+" ".repeat(Math.max(0,n.formats-e.formats.length));o.info(` ${ed(e.id.padEnd(n.id))} ${t} ${i} ${e.name.padEnd(n.name)} ${e.versions.padStart(3)} ${ed(e.date)}`)}e.total>h+w&&o.info(` ... ${e.total-h-w} more (use --offset ${h+w})`),process.exit(0)}catch(e){E.fail(e.message),process.exit(1)}}))}ug.command("delete","Move a content item to the trash").help("Move a content item to the trash. This immediately frees total storage capacity but does not refund monthly usage. The item can be restored for 31 days if enough total storage is available.\n\nUsage:\n needle-cloud delete <identifier>").argument("<identifier>","Content item identifier",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The Needle Cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).action(ju(async({args:e,options:t})=>{var n;const o=_u(t),{accessToken:i,org_id:r}=await lg(t.token,pg(t),!0!==t.nonInteractive),a=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",s=String(e.identifier),c=$(`Deleting content "${s}"...`).start();try{const e=await Yu({identifier:s,endpoint:a,authToken:i,org:r});c.succeed(e.message||`Moved content "${s}" to the trash`),"json"===o&&ku(e)}catch(e){c.fail(e.message),process.exitCode=1}})),ug.command("download","Download a content item by identifier").help('Download files from a content item.\n\nUse --format to select which output format to download (e.g. "glb", "textures").\n\nUsage:\n needle-cloud download <identifier> [directory]\n needle-cloud download abc123 --format glb').argument("<identifier>","Content item identifier",{validator:ug.STRING}).argument("[directory]","Output directory (default: current directory)",{default:"."}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING}).option("--format <format>","Output format to download (e.g. glb, textures)",{required:!1,validator:ug.STRING}).option("--version <version>","Download this source version or derived output ID",{validator:ug.STRING}).option("--label <label>","Download the version served by this label",{validator:ug.STRING}).option("--name <name>","Output filename (without extension)",{required:!1,validator:ug.STRING}).option("--verbose","Show detailed download info",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(async({args:e,options:t})=>{var n,o,i,r,a,s;const c=_u(t),{accessToken:l,org_id:p}=await lg(t.token,pg(t),!0!==t.nonInteractive),u=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",d=String(e.identifier),m=(null==(o=e.directory)?void 0:o.toString())||".",f=(null==(i=t.name)?void 0:i.toString())||void 0,h=null!=(r=null==(a=t.verbose)?void 0:a.valueOf())&&r,g=(null==(s=t.format)?void 0:s.toString())||void 0,v=$("Looking up content...").start();try{var b,y;const e={baseUrl:u,authToken:l,org:p},n=await cp(e,d);if(!n)throw new Error(`Content not found: "${d}". Use the exact content identifier (see list).`);const o=function(e,t){if(void 0!==t.version&&!t.version.trim())throw new Error("--version requires a version ID.");if(void 0!==t.label&&!t.label.trim())throw new Error("--label requires a label name.");if(t.version&&t.label)throw new Error("Use either --version or --label, not both.");const n=e.versions[0];if(!n)throw new Error(`Content "${e.title||e.name}" has no upload versions.`);let o;if(t.version){const n=e.versions.find(e=>e.identifier===t.version);if(o=n?[n,...n.variants]:e.versions.flatMap(e=>e.variants).filter(e=>e.identifier===t.version),!o.length)throw new Error(`Version "${t.version}" does not belong to this content item.`)}else if(t.label){if(o=e.versions.flatMap(e=>[e,...e.variants]).filter(e=>e.labels.some(e=>e.label===t.label)),!o.length)throw new Error(`Label "${t.label}" was not found on this content item.`)}else o=t.format?e.versions.flatMap(e=>[e,...e.variants]):[n];const i=t.format?o.find(e=>e.content_format===t.format):o[0];if(!i)throw new Error(`No output with format "${t.format}" found for the requested content selection.`);if((t.version||t.label)&&i.status&&"completed"!==i.status)throw new Error(`Version "${i.identifier}" is ${i.status}; select a completed version.`);return i.identifier}(n,{version:null==(b=t.version)?void 0:b.toString(),label:null==(y=t.label)?void 0:y.toString(),format:g});v.text=`Downloading "${n.title||n.name}"${g?` (format: ${g})`:""}...`,v.stop();const i=await Gu({baseUrl:u,authToken:l,org:p,identifier:o,outDir:m,filename:f,verbose:h,content_format:g});if("error"in i)throw new Error(i.error);"json"===c&&ku(i)}catch(e){v.fail(e instanceof Error?e.message:String(e)),process.exitCode=1}})),ug.command("deploy","Deploy a website to Needle").help("").argument("<directory>","The directory to deploy",{validator:ug.STRING}).option("--label <label>","Create or move a label to the deployed version (latest is automatic; requires read/write access)",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to deploy to (not needed when using token/accesstoken)",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id to deloy to (not needed when using token/accesstoken)",{required:!1,validator:ug.STRING,hidden:!0}).option("--name <name>","The project name. This name will also be used in your website URL",{required:!1,validator:ug.STRING}).option("--entrypoint <entrypoint>",'The entrypoint file to use (e.g. "index.html"). This is useful if you want to deploy a folder with multiple HTML files and you want to configure which file to load initially or if you have multiple model files in one folder',{required:!1,validator:ug.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:ug.STRING,hidden:!0}).option("--open","Open the deployment in the default browser",{default:!0,validator:ug.BOOLEAN}).option("--verbose <verbose>","Enables verbose output logs",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--experimental","Use the experimental upload API. Mostly used for debugging (default: false)",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--raw","Use raw to disallow modifications like gzip compression on upload",{required:!1,validator:ug.BOOLEAN,default:!1,hidden:!0}).option("--no-provenance","Do not record which commit and CI run this deployment came from",{required:!1,validator:ug.BOOLEAN,default:!1}).action(ju(yu("deploy",async({args:e,options:t,logger:n})=>{var o,i,r,a,s;const c=null==(o=t.label)?void 0:o.toString();void 0!==c&&qp(c);const l=_u(t),p=!0!==t.nonInteractive&&t.open,{accessToken:u,org_id:d}=await lg(t.token,pg(t),!0!==t.nonInteractive),m=!0===t.verbose,f=!0===t.experimental,h=!0===t.raw,g=(null==(i=t.noProvenance)?void 0:i.valueOf())||!1,v=await gu({label:c,logger:n,endpoint:(null==(r=t.endpoint)?void 0:r.toString())||void 0,token:u,org_id:d,directory:String(e.directory),name:(null==(a=t.name)?void 0:a.toString())||void 0,entrypoint:(null==(s=t.entrypoint)?void 0:s.toString())||void 0,open:p,verbose:m||!1,experimental:f||!1,raw:h||!1,noProvenance:g});"json"===l&&null!=v&&v.success&&ku(v)}))),function(e,t){for(const n of["upload","optimize"]){const o="optimize"===n,i=e.command(n,o?"Upload and wait for optimized assets (shorthand for upload --wait)":"Upload source assets to Needle Cloud").help("Upload returns source file identities and links after the transfer completes. Optimization continues in the background. Use upload --wait or optimize to wait for the selected optimized variant. Public glTF/GLB URLs are imported by Cloud with their referenced files. URL imports return a queued job; --wait waits for import and optimization. URL source-url output requires --wait. Folders are collected recursively into one grouped upload. Use --format json for its file list. Original links always identify the uploaded source version.").argument("<path>","File, folder, or public glTF/GLB URL to upload",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Organization name or ID (deprecated; use --team)",{validator:e.STRING,hidden:!0}).option("--name <name>","Upload name or identifier of an existing asset",{validator:e.STRING}).option("--content-id <id>","Append to an existing 3D asset",{validator:e.STRING}).option("--format <format>","Legacy output option: cli, json, source-url or edit-url",{validator:e.STRING}).option("--outdir <outdir>","Download optimized files to this directory (requires waiting)",{validator:e.STRING}).option("--progressive","Use progressive loading when waiting for optimization",{validator:e.BOOLEAN,default:!!o||void 0}).option("--usecase <usecase>","Optimization variant: product or world (requires waiting)",{validator:e.STRING,default:o?"product":void 0}).option("--verbose <verbose>","Print detailed diagnostics to stderr",{validator:e.BOOLEAN,default:!1});o||i.alias("import"),o||i.option("--wait","Wait for the selected optimized result",{validator:e.BOOLEAN,default:!1}).option("--no-optimize","Store source files without requesting processing",{validator:e.BOOLEAN,default:!1}),i.action(yu(n,async({args:e,options:n})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Pe({stdout:a,stderr:a});try{var s,c;const i=_u(n,{legacyFormat:!0,links:!0}),r=o||!0===n.wait;if(r&&!0===n.noOptimize)throw new Error("--wait cannot be combined with --no-optimize.");if(!r&&(void 0!==n.outdir||void 0!==n.progressive||void 0!==n.usecase))throw new Error("--wait is required for --outdir, --progressive and --usecase.");const a=n.usecase;if(void 0!==a&&"product"!==a&&"world"!==a)throw new Error("Use case must be product or world.");void 0!==n.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await wu(t.getAccessToken,n);if(p!==n.token&&p!==process.env.NEEDLE_CLOUD_TOKEN){const e=await t.getUser();if(null==e||!e.isAuthenticated)throw new Error("Please login to upload files.");if(!u)throw new Error("Please provide a team to upload files.");if(r){var l;const e=await(null!=(l=t.getLicenses)?l:xt)({baseUrl:"https://cloud.needle.tools/api",authToken:p,org:u},{type:"org",org_id:u});if(null==e||!e.some(e=>"Needle Engine"===e.type&&("pro"===e.license||"enterprise"===e.license)))throw new Error("Update to Needle PRO or Enterprise required to optimize files via CLI. Visit https://cloud.needle.tools/get-pro")}}Vu(await(null!=(s=t.upload)?s:Hu)({token:p,org_id:u,fileOrDirectory:String(e.path),contentId:void 0===n.contentId?void 0:String(n.contentId),name:void 0===n.name?void 0:String(n.name),wait:r,noOptimize:!0===n.noOptimize,progressive:void 0===n.progressive?void 0:!0===n.progressive,usecase:a,outDir:void 0===n.outdir?void 0:String(n.outdir),verbose:!0===n.verbose,format:i}),i,null!=(c=t.write)?c:e=>{process.stdout.write(e)})}finally{globalThis.console=r}}))}$u(e)}(ug,{getAccessToken:lg,getUser:Hd}),function(e,t){e.command("label","List, create or move content labels");for(const n of["list","set"]){const o=e.command(`label ${n}`,"list"===n?"List content labels and their source/derived URLs":"Create or move a label to a completed content version").argument("<content-id>","Content item identifier",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Organization name or ID (deprecated; use --team)",{validator:e.STRING,hidden:!0}).option("--format <format>","Legacy output option: cli or json",{validator:e.STRING});"set"===n&&o.argument("<label>","Destination label; latest is managed automatically",{validator:e.STRING}).option("--version <version>","Completed version ID from this content item",{validator:e.STRING}).option("--from <label>","Select the version currently targeted by this label (for example latest)",{validator:e.STRING}).help("Provide exactly one of --version or --from. Moving a label also updates its related completed outputs. Both read and write access are required."),o.action(yu(`label ${n}`,async({args:e,options:o})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Pe({stdout:a,stderr:a});try{var s;const i=_u(o,{legacyFormat:!0}),r=String(e.contentId);Bp(r);const a={contentId:r,label:String(e.label),versionId:void 0===o.version?void 0:String(o.version),from:void 0===o.from?void 0:String(o.from)};"set"===n&&Mp(a),void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await wu(t.getAccessToken,o),d={baseUrl:"https://cloud.needle.tools/api",authToken:p,org:u},m=null!=(s=t.write)?s:e=>{process.stdout.write(e)};if("list"===n){var c;const e=await(null!=(c=t.listContentLabels)?c:Hp)(d,r);if("json"===i)m(JSON.stringify(e)+"\n");else if(e.labels.length)for(const t of e.labels)m(`${t.label}: ${t.sourceVersionIds.join(", ")}\n`),Iu(t.targets,m);else m(`No labels for ${r}.\n`)}else{var l;const e=await(null!=(l=t.setContentLabel)?l:Jp)(d,a);"json"===i?m(JSON.stringify(e)+"\n"):(m(`${e.label}: ${e.previousVersionIds.join(", ")||"(new label)"} -> ${e.versionId}\n`),Iu(e.targets,m))}}finally{globalThis.console=r}}))}$u(e)}(ug,{getAccessToken:lg}),function(e,t){const n={getContent:cp,updateContent:lp,restoreContent:up,...t},o={info:"Inspect content metadata, versions and processing state",versions:"List source versions and their derived outputs, newest first",update:"Update content metadata or its thumbnail",restore:"Restore a content item from Trash"};for(const i of["info","versions","update","restore"]){const r=e.command(i,o[i]).argument("<identifier>","Content identifier",{validator:e.STRING}).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Legacy alias for --team",{validator:e.STRING,hidden:!0}).option("--endpoint <endpoint>","Needle Cloud API endpoint",{validator:e.STRING}).option("--output <output>","Output style: cli (default) or json",{validator:e.STRING,default:"cli"});"update"===i&&r.option("--title <title>","Set the title; an empty string clears it",{validator:e.STRING}).option("--description <description>","Set the description; an empty string clears it",{validator:e.STRING}).option("--tags <tags>","Replace tags with a comma-separated list",{validator:e.STRING}).option("--thumbnail <path>","Set a JPEG, PNG or WebP thumbnail (up to 5 MiB)",{validator:e.STRING}),"restore"===i&&r.help("Restore an item within 31 days of deletion. Requires enough available storage. Use list --trash to find deleted items."),r.action(yu(i,async({args:e,options:o})=>{var r,a,s;const c=String(e.identifier);if(!c.trim()||/[/\\?#\s]/.test(c))throw new Error("Pass an exact content identifier from list.");const l=String(null!=(r=o.output)?r:"cli");if("cli"!==l&&"json"!==l)throw new Error("Invalid --output. Use cli or json.");const p="update"===i?await Ou(o):void 0,u=globalThis.console,d=null!=(a=t.stderr)?a:process.stderr,m=null!=(s=t.write)?s:e=>{process.stdout.write(e)};globalThis.console=new Pe({stdout:d,stderr:d});try{var f;void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:e,org_id:r}=await wu(t.getAccessToken,o),a={baseUrl:String(null!=(f=o.endpoint)?f:"https://cloud.needle.tools/api"),authToken:e,org:r};if("update"===i&&p){const e=await n.updateContent(a,c,p);if("error"in e)throw new Error(e.error);if(!e.success)throw new Error("Content update was not confirmed.");m("json"===l?JSON.stringify(e)+"\n":`Updated ${c}\n`)}else if("restore"===i){const e=await n.restoreContent(a,c);if(!e.restored)throw new Error("Content restore was not confirmed.");m("json"===l?JSON.stringify(e)+"\n":`Restored ${c}\n`)}else{const e=await n.getContent(a,c);var h,g;"json"===l?m(JSON.stringify("versions"===i?e.versions:e,null,2)+"\n"):("info"===i&&m(`${e.title||e.name} (${e.identifier})\n${null!=(h=e.description)?h:""}\nTags: ${(null!=(g=e.tags)?g:[]).join(", ")}\n`),m(e.versions.length?e.versions.map(Au).join(""):"No upload versions.\n"))}}finally{globalThis.console=u}}))}$u(e)}(ug,{getAccessToken:lg}),function(e,t){const n={queryCollections:bp,getCollectionMetadata:yp,listCollectionItems:xp,createCollection:fp,updateCollection:hp,deleteCollection:gp,addCollectionEntry:Sp,removeCollectionEntry:wp,reorderCollectionEntries:_p,...t},o={list:"List collections in the authenticated team",info:"Read collection metadata and membership IDs",items:"List collection items and their membership IDs",create:"Create a collection",update:"Edit collection metadata or thumbnail",delete:"Delete a collection; source content remains intact",add:"Add uploaded content to a collection",remove:"Remove a membership; source content remains intact",reorder:"Set the complete manual order using membership IDs"};e.command("collection","Manage collections and their items");for(const i of["list","info","items","create","update","delete","add","remove","reorder"]){const r=e.command(`collection ${i}`,o[i]).option("--token <token>","Access token; also accepts NEEDLE_CLOUD_TOKEN or a saved login",{validator:e.STRING}).option("--team <team>","Team name or ID",{validator:e.STRING}).option("--org <org>","Legacy alias for --team",{validator:e.STRING,hidden:!0}).option("--endpoint <endpoint>","Needle Cloud API endpoint",{validator:e.STRING});"create"===i?r.argument("<name>","Collection name",{validator:e.STRING}):"list"!==i&&r.argument("<identifier>","Collection identifier",{validator:e.STRING}),"add"===i&&r.argument("<content-id>","Uploaded content identifier",{validator:e.STRING}),"remove"===i&&r.argument("<entry-id>","Membership ID from collection items",{validator:e.STRING}),"reorder"===i&&r.argument("<entry-ids>","Complete comma-separated membership IDs in desired order",{validator:e.STRING}).help("Use collection info for all membership IDs, including unavailable items. Supply every ID exactly once."),"info"!==i&&"list"!==i||r.option("--diagnostics","Include collection eligibility counts and exclusion guidance",{validator:e.BOOLEAN,default:!1}),"items"===i&&r.option("--include-unavailable","Include excluded memberships and API guidance (team read access required)",{validator:e.BOOLEAN,default:!1}),"delete"===i&&r.option("--yes","Confirm collection deletion",{validator:e.BOOLEAN,default:!1}),"create"!==i&&"update"!==i||("update"===i&&r.option("--name <name>","Set the collection name",{validator:e.STRING}),r.option("--description <description>","Set description; an empty string clears it",{validator:e.STRING}).option("--tags <tags>","Replace comma-separated tags; an empty string clears them",{validator:e.STRING}).option("--visibility <visibility>","private, unlisted or public (subject to server availability)",{validator:e.STRING}),"update"===i&&r.option("--thumbnail <path>","JPEG, PNG or WebP thumbnail, up to 5 MiB",{validator:e.STRING}).option("--remove-thumbnail","Remove the collection thumbnail",{validator:e.BOOLEAN,default:!1})),"list"!==i&&"items"!==i||(r.option("--limit <limit>","Page size, 1..100 (default 20)",{validator:e.NUMBER}).option("--offset <offset>","Page offset (default 0)",{validator:e.NUMBER}),"list"===i?r.option("--search <search>","Filter collection names and descriptions",{validator:e.STRING}).option("--tags <tags>","Require all comma-separated collection tags",{validator:e.STRING}).option("--visibility <visibility>","Filter by private, unlisted or public",{validator:e.STRING}):r.option("--sort-by <sort>","manual (default), name, created_at or updated_at",{validator:e.STRING}).option("--sort-direction <direction>","asc (default) or desc",{validator:e.STRING})),r.action(yu(`collection ${i}`,async({args:e,options:o})=>{var r,a,s,c,l,p,u,d;const m=_u(o),f="list"!==i&&"create"!==i?String(e.identifier):"";"list"!==i&&"create"!==i&&Bp(f);const h="create"===i||"update"===i?await Pu(o,"create"===i?e.name:o.name):{};if("create"===i&&!h.name)throw new Error("Pass a collection name.");if("update"===i&&!Object.keys(h).length)throw new Error("Nothing to update. Pass --name, --description, --tags, --visibility, --thumbnail or --remove-thumbnail.");if("delete"===i&&!0!==o.yes)throw new Error("Pass --yes to confirm collection deletion.");const g=String(null!=(r=e.contentId)?r:"");"add"===i&&Bp(g);const v="remove"===i?Ru(e.entryId,"Membership ID",1):0,b="reorder"===i?String(e.entryIds).split(",").map(e=>Ru(e,"Membership ID",1)):[];if("reorder"===i&&new Set(b).size!==b.length)throw new Error("Membership IDs must not repeat.");const y="list"===i||"items"===i?Ru(null!=(a=o.limit)?a:20,"Limit",1,100):20,x="list"===i||"items"===i?Ru(null!=(s=o.offset)?s:0,"Offset",0):0,w=Nu(o.visibility),_=void 0===o.tags?void 0:mp(String(o.tags).split(",")),S=null!=(c=o.sortBy)?c:"manual";if("manual"!==S&&"name"!==S&&"created_at"!==S&&"updated_at"!==S)throw new Error("Invalid --sort-by. Use manual, name, created_at or updated_at.");const j=null!=(l=o.sortDirection)?l:"asc";if("asc"!==j&&"desc"!==j)throw new Error("Invalid --sort-direction. Use asc or desc.");const k=globalThis.console;globalThis.console=new Pe({stdout:null!=(p=t.stderr)?p:process.stderr,stderr:null!=(u=t.stderr)?u:process.stderr});const E=null!=(d=t.write)?d:e=>{process.stdout.write(e)};try{var T;void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:e,org_id:r}=await wu(t.getAccessToken,o),a={baseUrl:String(null!=(T=o.endpoint)?T:"https://cloud.needle.tools/api"),authToken:e,org:r};let s,c="";if("list"===i){if(!r)throw new Error("Select a team with --team to list its collections.");const e=await n.queryCollections(a,{org:r,limit:y,offset:x,...void 0!==o.search?{search:String(o.search)}:{},...void 0!==_?{tags:_}:{},...w?{visibility:w}:{},...o.diagnostics?{include_diagnostics:!0}:{}});s=e,c=e.collections.map(e=>`${e.identifier} ${e.name} (${e.item_count} items)\n`).join("")||"No collections.\n",c+=`Showing ${e.collections.length} of ${e.total}; offset ${e.offset}.\n`}else if("info"===i)s=await n.getCollectionMetadata(a,f,{include_memberships:!0,...o.diagnostics?{include_diagnostics:!0}:{}}),c=JSON.stringify(s,null,2)+"\n";else if("items"===i){const e=await n.listCollectionItems(a,f,{limit:y,offset:x,sort_by:S,sort_direction:j,...o.includeUnavailable?{include_unavailable:!0}:{}});s=e,c=e.items.map(e=>`${e.id} ${e.content_item_id} ${e.title||e.name||"(unavailable)"}${e.diagnostics?` — ${e.diagnostics.message}`:""}\n`).join("")||"No items.\n",c+=`Showing ${e.items.length} of ${e.total}; offset ${e.offset}.\n`}else if("create"===i){const e=await n.createCollection(a,{...h,name:h.name||""});if(!e.identifier)throw new Error("Collection creation was not confirmed.");s=e,c=`Created ${e.identifier}\n`}else if("update"===i||"delete"===i){const e="update"===i?await n.updateCollection(a,f,h):await n.deleteCollection(a,f);if(e.identifier!==f)throw new Error("Collection change was not confirmed.");s=e,c=`${"update"===i?"Updated":"Deleted"} ${f}\n`}else if("add"===i){const e=await n.addCollectionEntry(a,f,g);if(!Number.isSafeInteger(e.id)||e.id<1)throw new Error("Collection addition was not confirmed.");s=e,c=`Added ${g} to ${f}; membership ${e.id}\n`}else{const e="remove"===i?await n.removeCollectionEntry(a,f,v):await n.reorderCollectionEntries(a,f,b);if(!0!==e.success)throw new Error("Collection change was not confirmed.");s=e,c=`${"remove"===i?"Removed membership "+v+" from":"Reordered"} ${f}\n`}E("json"===m?JSON.stringify(s)+"\n":c)}finally{globalThis.console=k}}))}$u(e)}(ug,{getAccessToken:lg}),ug.command("generate-material","Generate a PBR material from a text prompt").help("").argument("<prompt>","The text prompt describing the material to generate",{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:ug.STRING,hidden:!0}).option("--resolution <resolution>","The material texture resolution (256, 512, 1k, 2k, 4k)",{default:"512",required:!1,validator:ug.STRING}).option("--name <name>","Output filename",{required:!1,validator:ug.STRING}).option("--outdir <outdir>","Output directory to download the generated file(s) to. If not set, the job ID is printed instead.",{required:!1,validator:ug.STRING}).action(ju(yu("generate-material",async({args:e,options:t,logger:n})=>{var o,i,r;const a=_u(t),{accessToken:s,org_id:c}=await lg(t.token,pg(t),!0!==t.nonInteractive),l=String(e.prompt),p=null==(o=t.resolution)?void 0:o.toString(),u=null==(i=t.outdir)?void 0:i.toString(),d=null==(r=t.name)?void 0:r.toString(),m=await async function(e){if(!e.token||e.token.length<=1||"string"!=typeof e.token||"true"===e.token)return{error:`Missing access token. Create a token at ${Kp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";mu(`[generate-material] Starting request to ${t}, prompt="${e.prompt}", resolution=${e.resolution||512}`,{emptyLineBefore:!0});const n=$("Requesting material generation...").start(),o=await Promise.race([op({baseUrl:t,authToken:e.token,org:e.org_id,trigger_type:"cli"},{prompt:e.prompt,resolution:e.resolution||512}).catch(e=>({error:e.message||"Request failed"})),new Promise(e=>setTimeout(()=>e({error:"Request timed out after 30s. Please try again."}),3e4))]);if("error"in o)return mu(`[generate-material] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(mu(`[generate-material] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return mu(`[generate-material] Job canceled: ${i.status_message||"quota exceeded"}`),n.fail(i.status_message||"Material generation was canceled (quota exceeded)"),{error:i.status_message||"Quota exceeded"};n.succeed(`Material generation requested: ${i.identifier}`);const r=$("Waiting for material generation...").start();r.color="gray";const a=Tc();for(;;){if("completed"===i.status){r.succeed("Material generation completed");break}let n=2e3;const o=await Ec(i.identifier,{baseUrl:t,authToken:e.token,org:i.org}),s=a.record(o);if(s)return r.fail(s.reason),{error:s.reason};if("new"===(null==o?void 0:o.status)||"pending"===(null==o?void 0:o.status))r.text="Your material is queued - waiting for generation to start",r.color="yellow",n=2e3;else if("running"===(null==o?void 0:o.status))r.text=`Generating material: ${o.progress?`${o.progress}%`:""} ${o.status_message?`— ${o.status_message}`:""}`,r.color="cyan",n=1e3;else{if("completed"===(null==o?void 0:o.status)){mu(`[generate-material] Job completed: ${i.identifier}`),r.succeed(`Material generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return mu(`[generate-material] Job canceled: ${i.identifier}, error=${o.error}`),r.fail(`Material generation canceled: ${o.error||""}`),{error:o.error||"Material generation canceled"};if("failed"===(null==o?void 0:o.status))return mu(`[generate-material] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`Material generation failed: ${o.error||""}`),{error:o.error||"Material generation failed"}}await $l(n)}if(e.outDir){const n=await Gu({baseUrl:t,authToken:e.token,org:e.org_id,identifier:i.identifier,outDir:e.outDir,filename:e.outputName});if("error"in n)return{error:n.error}}return{success:!0,identifier:i.identifier}}({logger:n,token:s,org_id:c,prompt:l,resolution:p,outputName:d,outDir:u});"error"in m&&(m.error&&n.error(m.error),process.exit(1)),"json"===a?ku(m):!u&&"identifier"in m&&console.log(m.identifier),await Eu(0)}))),ug.command("generate-3d","Generate a 3D model from a text prompt").help("").argument("<prompt>",'A description of the object to generate, e.g. "a weathered wooden crate with iron bands"',{validator:ug.STRING}).option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id",{required:!1,validator:ug.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:ug.STRING,hidden:!0}).option("--quality <quality>","Quality tier: standard (default, includes physically based material maps) or draft (faster and cheaper, base color only)",{default:"standard",required:!1,validator:ug.STRING}).option("--face-count <faceCount>","Target polygon count (40000-1500000). Leave unset to let the generator choose.",{required:!1,validator:ug.NUMBER}).option("--name <name>","Output filename",{required:!1,validator:ug.STRING}).option("--outdir <outdir>","Output directory to download the generated file(s) to. If not set, the job ID is printed instead.",{required:!1,validator:ug.STRING}).action(ju(yu("generate-3d",async({args:e,options:t,logger:n})=>{var o,i,r;const a=_u(t),s=null==(o=t.quality)?void 0:o.toString();if(void 0!==s&&"draft"!==s&&"standard"!==s)throw new Error("Quality must be draft or standard.");const c=null!=t.faceCount?Number(t.faceCount):void 0;if(void 0!==c&&(!Number.isInteger(c)||c<4e4||c>15e5))throw new Error("--face-count must be an integer from 40000 to 1500000.");const{accessToken:l,org_id:p}=await lg(t.token,pg(t),!0!==t.nonInteractive),u=String(e.prompt),d=null==(i=t.outdir)?void 0:i.toString(),m=null==(r=t.name)?void 0:r.toString(),f=await async function(e){if(!e.token||e.token.length<=1||"string"!=typeof e.token||"true"===e.token)return{error:`Missing access token. Create a token at ${Kp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";mu(`[generate-3d] Starting request to ${t}, prompt="${e.prompt}", quality=${e.quality||"draft"}`,{emptyLineBefore:!0});const n=$("Requesting 3D generation...").start(),o=await async function(e,t){var n;if(null!=(n=e.signal)&&n.aborted)return{error:"The 3D generation request was cancelled"};const o=e.baseUrl+vt.jobs.create,i={...bt(e),"content-type":"application/json"},r={type:"ai-3d-asset",triggered_by:e.trigger_type,parameters:{...t}},a=await fetch(o,{...yt,method:"POST",headers:i,body:JSON.stringify(r),signal:e.signal}).catch(e=>function(e){return"AbortError"===(null==e?void 0:e.name)||"TimeoutError"===(null==e?void 0:e.name)}(e)?{__aborted:!0}:(console.error(`Failed to request 3D asset generation: ${null==e?void 0:e.message}`),{__failed:(null==e?void 0:e.message)||"Request failed"}));if("__aborted"in a)return{error:"The 3D generation request was cancelled"};if("__failed"in a)return{error:a.__failed};if(!a.ok){const e=await a.text();return console.error(`Failed to request 3D asset generation (${a.status}): ${e}`),{error:e||`Request failed (${a.status})`}}const s=await a.json().catch(e=>(console.error(e),null));return null!=s&&s.job?s:{error:"The server did not return a job"}}({baseUrl:t,authToken:e.token,org:e.org_id,trigger_type:"cli",signal:AbortSignal.timeout(3e4)},{prompt:e.prompt,...e.quality?{quality:e.quality}:{},...e.face_count?{face_count:e.face_count}:{}});if("error"in o)return mu(`[generate-3d] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(mu(`[generate-3d] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return mu(`[generate-3d] Job canceled: ${i.status_message||"quota exceeded"}`),n.fail(i.status_message||"3D generation was canceled (quota exceeded)"),{error:i.status_message||"Quota exceeded"};n.succeed(`3D generation requested: ${i.identifier}`);const r=$("Waiting for the 3D model...").start();r.color="gray";const a=Tc();for(;;){if("completed"===i.status){r.succeed("3D generation completed");break}let n=2e3;const o=await Ec(i.identifier,{baseUrl:t,authToken:e.token,org:i.org}),s=a.record(o);if(s)return r.fail(s.reason),{error:s.reason};if("new"===(null==o?void 0:o.status)||"pending"===(null==o?void 0:o.status))r.text="Your model is queued - waiting for generation to start",r.color="yellow",n=2e3;else if("running"===(null==o?void 0:o.status))r.text=`Generating 3D model: ${o.progress?`${o.progress}%`:""} ${o.status_message?`— ${o.status_message}`:""}`,r.color="cyan",n=1e3;else{if("completed"===(null==o?void 0:o.status)){mu(`[generate-3d] Job completed: ${i.identifier}`),r.succeed(`3D generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return mu(`[generate-3d] Job canceled: ${i.identifier}, error=${o.error}`),r.fail(`3D generation canceled: ${o.error||""}`),{error:o.error||"3D generation canceled"};if("failed"===(null==o?void 0:o.status))return mu(`[generate-3d] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`3D generation failed: ${o.error||""}`),{error:o.error||"3D generation failed"}}await $l(n)}if(e.outDir){const n=await Gu({baseUrl:t,authToken:e.token,org:e.org_id,identifier:i.identifier,outDir:e.outDir,filename:e.outputName});if("error"in n)return{error:n.error}}return{success:!0,identifier:i.identifier}}({logger:n,token:l,org_id:p,prompt:u,quality:s,face_count:c,outputName:m,outDir:d});"error"in f&&(f.error&&n.error(f.error),process.exit(1)),"json"===a?ku(f):!d&&"identifier"in f&&console.log(f.identifier),await Eu(0)}))),ug.command("ask","Send a message to the Needle Cloud AI").help("Send a message to Needle Cloud AI. By default, starts an interactive conversation, optionally with an initial message. Use --once to send one message and exit, or --non-interactive to also prohibit authentication prompts and browser launches. Both require a message. --output json returns one complete response and exits. --no-stream prints the full answer as text. Use --slug to continue a conversation.").argument("[message...]","The message to send (omit for interactive mode)").option("--token <token>",cg,{validator:ug.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:ug.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:ug.STRING,hidden:!0}).option("--slug <slug>","Chat slug to continue an existing conversation",{required:!1,validator:ug.STRING}).option("--no-stream","Disable streaming (returns full response at once)",{required:!1,validator:ug.BOOLEAN,default:!1}).option("--once","Send one message and exit",{validator:ug.BOOLEAN,default:!1}).action(yu("ask",async({args:e,options:t})=>{var n,o;const i=_u(t),r=Array.isArray(e.message)?e.message:e.message?[e.message]:[],a=r.length?r.join(" "):void 0;if(!(!0!==t.nonInteractive&&!0!==t.once&&"json"!==i||null!=a&&a.trim()))throw new Error("A message is required for one-shot or non-interactive chat.");const{accessToken:s,org_id:c}=await lg(t.token,pg(t),!0!==t.nonInteractive),l=(null==(n=t.slug)?void 0:n.toString())||void 0,p=(null==(o=t.noStream)?void 0:o.valueOf())||!1;await async function(e){const{token:t,org_id:n,message:o,slug:i,stream:r}=e,a=i||function(e){try{const t=e.split(".")[1],n=JSON.parse(Buffer.from(t,"base64url").toString());if(n.sub)return n.sub+"-cli"}catch{}return"cli-"+Math.random().toString(36).slice(2,10)}(t);if(!0===e.nonInteractive||!0===e.once||"json"===e.output){if(null==o||!o.trim())throw new Error("A message is required for one-shot or non-interactive chat.");await Su("json"===e.output,()=>Ku({token:t,org_id:n,slug:a,message:o,stream:"json"!==e.output&&r,output:e.output}))}else await async function(e){const{token:t,org_id:n,slug:o,stream:i,initialMessage:r}=e,a=Ue({input:process.stdin,output:process.stdout});console.log(`Needle Cloud AI (chat: ${o})`),console.log('Type your message. Press Ctrl+C or type "exit" to quit.\n');try{for(r&&(console.log(`> ${r}`),await Ku({token:t,org_id:n,slug:o,message:r,stream:i}),console.log(""));;){const e=(await a.question("> ")).trim();if(e){if("exit"===e||"quit"===e)break;await Ku({token:t,org_id:n,slug:o,message:e,stream:i}),console.log("")}}}finally{a.close()}}({token:t,org_id:n,slug:a,stream:r,initialMessage:o})}({token:s,org_id:c,message:a,slug:l,stream:!p,nonInteractive:!0===t.nonInteractive,once:!0===t.once,output:"json"===i?"json":"cli"}),await Eu(0)})),$u(ug);export{dm as g,ug as p};
|
package/dist/cli.esm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node-fetch";import"@web-std/file";import"node:crypto";export{p as program}from"./cli-
|
|
1
|
+
import"node-fetch";import"@web-std/file";import"node:crypto";export{p as program}from"./cli-b220ba5f.js";import"fs";import"dotenv";import"ora";import"commander";import"child_process";import"open";import"path";import"node:fs";import"node:fs/promises";import"node:os";import"node:path";import"util";import"stream";import"http";import"https";import"url";import"crypto";import"net";import"tls";import"assert";import"tty";import"os";import"events";import"http2";import"zlib";import"node:console";import"node:readline/promises";import"node:util";import"@logto/node";import"node:readline";import"node:stream";import"node:zlib";import"express";import"ws";import"node:child_process";import"minimatch";import"node:url";import"node:timers/promises";import"body-parser";import"node:http";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as o,readdirSync as t,statSync as r}from"node:fs";import{dirname as i,join as e}from"node:path";import{g as n}from"./cli-
|
|
1
|
+
import{existsSync as o,readdirSync as t,statSync as r}from"node:fs";import{dirname as i,join as e}from"node:path";import{g as n}from"./cli-b220ba5f.js";import"node-fetch";import"@web-std/file";import"node:crypto";import"commander";import"fs";import"child_process";import"open";import"path";import"ora";import"node:fs/promises";import"node:os";import"util";import"stream";import"http";import"https";import"url";import"crypto";import"net";import"tls";import"assert";import"tty";import"os";import"events";import"http2";import"zlib";import"node:console";import"node:readline/promises";import"node:util";import"dotenv";import"@logto/node";import"node:readline";import"node:stream";import"node:zlib";import"express";import"ws";import"node:child_process";import"minimatch";import"node:url";import"node:timers/promises";import"body-parser";import"node:http";function p(){var p;let m;try{m=n()}catch{return null}const s=null==(p=m)||null==(p=p.entries)?void 0:p[0];if(!s)return null;if(!s.log_location)return null;if("unity"!==s.editor&&"blender"!==s.editor)return null;if(!o(s.log_location))return null;const l=s.log_location,d=function(o,i){const n=new Set([i]);try{for(const i of t(o)){if(!i.toLowerCase().endsWith(".log"))continue;const t=e(o,i);try{if(!r(t).isFile())continue}catch{continue}n.add(t)}}catch{}return[...n]}(i(l),l);return{editor:s.editor,path:l,paths:d}}export{p as findActiveEditorLog};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "needle-cloud",
|
|
3
|
-
"version": "3.6.0
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"needle-cloud": "./bin/cli.js"
|
|
@@ -38,4 +38,4 @@
|
|
|
38
38
|
"type": "git",
|
|
39
39
|
"url": "https://github.com/needle-tools/needle-cloud.git"
|
|
40
40
|
}
|
|
41
|
-
}
|
|
41
|
+
}
|