needle-cloud 3.3.0-rc.1792931613.dc45ef3 → 3.3.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 sf(e,t,n,o){rm(e,async(e,n)=>{try{const o=await t(e,n);return"string"==typeof o?gm(o):{...o,content:o.content.map(e=>"text"===e.type?{...e,text:gm(e.text)}:e)}}catch(e){throw new Error(gm(e instanceof Error?e.message:String(e)))}},n,o)}const cf=function(e,t=$m,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=Am(d),a=await t(d);o={project:d,result:{...a,...a.message?{message:gm(a.message)}:{},...a.output?{output:gm(a.output)}:{},diagnostics:(null!=(m=a.diagnostics)?m:[]).map(e=>({...e,message:gm(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=Am(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:Om(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:Om(e.file,300)}:{},message:Om(e.message,_),messageTruncated:e.message.length>_})),..."error"!==u&&x+w.length<y.length?{nextOffset:x+w.length}:{},...g.message||h?{message:Om([g.message,h?"Could not scan project files for changes; this check is marked stale.":null].filter(Boolean).join(" "),500)}:{},...g.output?{output:Om(g.output,"error"===u?2e3:500),outputTruncated:g.output.length>("error"===u?2e3:500)}:{}}},{markStale(){i++}});return r}(()=>{var e;return null==(e=hf())?void 0:e.web_location}),lf=function(e,t=se(ne(),".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||ce(n)!==ce(t.project))throw new Error("The approved local project has changed.");return{root:O(n),grant:t}}function s(e,t,n){if("string"!=typeof t||!t||t.includes("\0")||ue(t)||me.isAbsolute(t)||fe.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=ce(e,t);if(!o.startsWith(e+de))throw new Error("Path escapes the selected local project.");let i=e;const r=le(e,o).split(de);for(let e=0;e<r.length;e++){if(i=se(i,r[e]),!$(i)){if(e!==r.length-1||!n)throw new Error("The file or its parent directory does not exist.");continue}const t=B(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{G(n,t,{flag:"wx",mode:384}),A(n,e)}finally{$(n)&&W(n)}}function l(){return $(t)?q(t).filter(e=>e.endsWith(".json")).reduce((e,n)=>e+C(se(t,n)).size,0):0}function p(e){if(!r){if($(t))for(const e of q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e))){const n=JSON.parse(M(se(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)>Nm)throw new Error("Checkpoint storage is full; no file was changed.");I(t,{recursive:!0,mode:448});const s=i(),c=se(t,`${s}.json`);return G(c,a,{flag:"wx",mode:384}),{id:s,file:c}}function u(e,t){if(e.byteLength>Cm)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(Rm(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 $(n)?M(n):null},o=n(t.path),i=null===t.before?null:Rm(Buffer.from(t.before,"base64"));if("rename"===t.operation){if(!t.newPath)return"conflicted";const e=n(t.newPath);if(null===o&&e&&Rm(e)===t.afterSha256)return"applied";if(null===e&&o&&Rm(o)===i)return"undone"}else if("delete"===t.operation){if(null===o)return"applied";if(o&&Rm(o)===i)return"undone"}else{if(o&&Rm(o)===t.afterSha256)return"applied";if(null===o&&null===t.before||o&&Rm(o)===i)return"undone"}return"conflicted"}catch{return"conflicted"}}return{list(e){const{root:n,grant:o}=a(e);if(!$(t))return{changes:[],total:0};const i=q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({...JSON.parse(M(se(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=O(n),i=s(o,t,!0);if(!$(i))return{path:t,exists:!1};const r=C(i).size;if(r>Cm)throw new Error("File exceeds the 1 MiB edit limit.");const a=wm(o,t,{maxBytes:Cm});return _m(a),{path:t,exists:!0,sha256:Rm(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>Cm||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=$(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?M(d):null;if(f&&u(f,e.expectedSha256),f&&Rm(f)===Rm(l))throw new Error("File already has this content; no edit was saved.");const h={project:i,path:le(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:Rm(l),createdAt:(new Date).toISOString(),operation:"write"},g=p(h);try{if(s(i,e.path,!0===e.create),!0===e.create){if($(d))throw new Error("The file was created since it was checked; check it again.")}else if(!$(d)||Rm(M(d))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");c(d,l)}catch(e){throw W(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=M(r);u(c,e.expectedSha256);const l=p({project:o,path:le(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),Rm(M(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");W(r)}catch(e){throw W(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($(c))throw new Error("Destination file already exists.");const l=M(r);u(l,e.expectedSha256);const d={project:o,path:le(o,r),newPath:le(o,c),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:l.toString("base64"),after:l.toString("base64"),afterSha256:Rm(l),createdAt:(new Date).toISOString(),operation:"rename"},m=p(d);try{if(s(o,e.path,!1),s(o,e.newPath,!0),$(c))throw new Error("Destination file already exists.");if(Rm(M(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");A(r,c)}catch(e){throw W(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=se(t,`${e.checkpointId}.json`),u=JSON.parse(M(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($(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($(d)||Rm(M(e))!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");A(e,d)}else{const e=M(d);if(Rm(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()-C(e).size+Buffer.byteLength(n)>Nm)throw new Error("Checkpoint storage is full; no file was changed.");c(e,Buffer.from(n))}(p,u)),null===u.before?W(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=se(t,`${e.checkpointId}.json`),p=JSON.parse(M(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(!$(u)||Rm(M(u))!==Rm(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),W(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(!$(u)||$(e)||Rm(M(u))!==Rm(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),A(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(Rm(e)!==p.afterSha256)throw new Error("Checkpoint content is damaged; Redo was refused.");if(null===p.before?$(u):!$(u)||Rm(M(u))!==Rm(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(!$(t))throw new Error("No checkpoints found for this turn.");const r=q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({checkpoint:JSON.parse(M(se(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=$(n)?M(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||Rm(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||Rm(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=hf())?void 0:e.web_location},void 0,()=>cf.markStale()),pf=function(e=se(ne(),".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")||ue(t.path)||me.isAbsolute(t.path)||fe.isAbsolute(t.path))throw new Error("A project-relative file path and chat are required.");const n=O(t.root),o=ce(n,t.path);if(xm(n,t.path,{allowMissing:!0}),!o.startsWith(n+de))throw new Error("File path escapes the project.");const i=le(n,o).split(de).join("/");return{project:n,target:o,path:i,file:se(e,Um(n),Um(t.chatId),`${Um(i)}.json`)}}function n(e){if(!$(e.target))return null;if(C(xm(e.project,e.target).path).size>Pm)return{unsupported:"File exceeds the 1 MiB observation limit."};const t=wm(e.project,e.target,{maxBytes:Pm}),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(Um),fileSha256:Um(t)}}function o(e){if(!$(e.file))return null;const t=JSON.parse(M(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};I(se(e,Um(t.project),Um(o)),{recursive:!0,mode:448});const a=`${t.file}.${i()}.tmp`;try{G(a,JSON.stringify(r),{flag:"wx",mode:384}),A(a,t.file)}finally{$(a)&&W(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)."}}}}(),uf=function(e,t=y){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()||ue(n.path)||n.path.includes("\0"))throw new Error("Use a nonempty project-relative path.");const r=O.native(i),a=ce(r,n.path),s=le(r,a);if(".."===s||s.startsWith(`..${de}`)||ue(s))throw new Error("File path is outside the selected project.");const c=O.native(a),l=le(r,c);if(".."===l||l.startsWith(`..${de}`)||ue(l))throw new Error("File path is outside the selected project.");const p=C(c);if(!p.isFile()&&!p.isDirectory())throw new Error("The selected path is not a file or directory.");if(Lm.has(re(c).toLowerCase()))throw new Error("Opening executable file types is not supported.");return await t(c),{opened:!0,project:n.project,path:le(r,c)||"."}}}(hf),df=function(e){const{getProject:t,getHome:n=ne,run:o=nf,commandsEnabled:r=(()=>!Wm()),onFailure:a,onCreated:s,onApprovedProject:c,now:l=Date.now,getProcessIdentity:p=Vm}=e,u=function(e=se(ne(),".needle","cli","ai-jobs"),t=Date.now){const n=t=>{if(!Jm.test(t))throw new Error("Invalid project job ID.");return se(e,`${t}.json`)};return{runtimeFile:t=>(n(t),se(e,`${t}.runtime.json`)),runtime(e){const t=this.runtimeFile(e);if(!$(t))return;const n=JSON.parse(M(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);I(e,{recursive:!0,mode:448});const r=se(e,`${t.jobId}.${i()}.tmp`);try{G(r,JSON.stringify(t),{flag:"wx",mode:384}),A(r,o)}finally{$(r)&&W(r)}},get(e){const o=n(e);if(!$(o))return;const i=JSON.parse(M(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;{W(o);const t=this.runtimeFile(e);$(t)&&W(t)}},list(){return $(e)?q(e).filter(e=>Jm.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);$(t)&&W(t);const o=this.runtimeFile(e);$(o)&&W(o)}}}(se(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=ef(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=gm(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={...ef(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||pe(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=gm(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=gm(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=gm(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.");G(`${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=hf())?void 0:e.web_location},onCreated:Hd,onApprovedProject:Hd,onFailure:e=>{var t;return Bp(`[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 mf(e){if(null==e||!e.editGrant)throw new Error("Local file edit approval is required.");if(Mm())throw new Error("AI file edits are disabled in local Needle CLI settings.");return e.editGrant}function ff(e={}){sf({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=Bd();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=l(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"},()=>{}),sf({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=Bd();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"},()=>{}),sf({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=Bd();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"},()=>{}),sf({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=hf();return t.content.push(null!=n&&n.web_location?{type:"text",text:w(n.web_location)}:{type:"text",text:"No selected web project is known."}),t},{source:"cli"},()=>{}),sf({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?pf.snapshot(i):pf.diff(i);return{content:[{type:"text",text:JSON.stringify(r)}]}},{source:"cli"},()=>{}),sf({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 uf(e))}]}),{source:"cli"},()=>{}),sf({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=l(n.resolved).mtime.toISOString(),r=km(n.root,n.resolved).text.split("\n");let a="";try{var o;const e=pf.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=of(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),p=r.slice(s-1,s-1+c),u=p.map((e,t)=>`${s+t}: ${e}`).join("\n");return{content:[{type:"text",text:`File: ${n.resolved} (${r.length} lines, modified: ${i}, showing ${s}-${s+p.length-1})`+a+"\n"+u}]}}catch(e){return{content:[{type:"text",text:`Error reading file: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),sf({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=vf();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=>Em(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"},()=>{}),sf({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=hf();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:w(t.project_location),label:n}),e.project&&"web"!==e.project||!t.web_location||o.push({root:w(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=gf(e.path||".",t);if(o)try{var a;e.recursive||r.push(...u(o,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"node_modules"!==e.name).map(e=>`${n}/${j(t,_(o,e.name))}`));const s=xf(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"},()=>{}),sf({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=hf();var n;if(null==t||!t.log_location)return Mp(`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=km(pe(t.log_location),ae(t.log_location),{maxBytes:67108864,allowPrivateKeys:!0}).text.split("\n");let o,i;if(e.filter){const t=of(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"},()=>{}),sf({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(!c(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=km(t,e).text;return JSON.parse(n)}if(n.endsWith(".glb")){const n=wm(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=wm(t,e,{maxBytes:67108864,range:{offset:20,length:o}}).toString("utf-8"),r=mm(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=yf(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 j,k;h.push(` - ${t.name||"(unnamed)"} (${null!=(j=null==(k=t.joints)?void 0:k.length)?j: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)}]});sf({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=af.replace("__PORT__",String(e)).replace("__HOST__",t),o=Buffer.from(n,"utf16le").toString("base64"),{stdout:i}=await rf("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 V(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 Y("/proc",{withFileTypes:!0});for(const e of o){if(!e.isDirectory()||!/^\d+$/.test(e.name))continue;let n;try{n=await Y(`/proc/${e.name}/fd`)}catch{continue}for(const o of n)try{const n=await K(`/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 rf("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 K(`/proc/${e}/cwd`):await async function(e){const{stdout:t}=await rf("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"},()=>{}),sf({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(Bd().entries.filter(e=>e.web_location).map(e=>({path:e.web_location,selected:e===hf(),editor:e.editor}))),{source:"cli"},()=>{}),sf({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:Jd(t.path).web_location}),{source:"cli"},()=>{}),sf({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:Km},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?df.getPlan(t.planId,n.chatId):df.plan(t,n.chatId))},{source:"cli"},()=>{}),sf({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(Wm())throw new Error("AI project commands are disabled in local Needle CLI settings.");return e(await df.start(t.planId,n.commandGrant))},{source:"cli"},()=>{}),sf({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(df.status(t.jobId,n.chatId))},{source:"cli"},()=>{}),sf({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 df.cancel(t.jobId,n.chatId))},{source:"cli"},()=>{})}(),sf(sp.schema,async e=>{const t=await sp.execute(e);return"error"in t?{content:[{type:"text",text:t.error}]}:{content:[{type:"text",text:t.content}]}},{source:"cli"},()=>{}),sf({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(lf.stat(e.path))}]}),{source:"cli"},()=>{}),sf({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(lf.write(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.delete(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.rename(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.undo(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.redo(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.undoTurn(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.list(mf(t)))}]}),{source:"cli"},()=>{}),sf({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 cf(e);return{content:[{type:"text",text:JSON.stringify(t)}],isError:"error"===t.status||"unavailable"===t.status}},{source:"cli"},()=>{}),null!=e&&e.logToolCount&&Mp(`[MCP] registered ${em.length} built-in tools: ${em.map(e=>e.name).join(", ")}`)}function hf(){return Gd()}function gf(e,t){const n=w(t,e),o=w(t),i=j(o,n);return k(i)||".."===i||i.startsWith(".."+S)?null:xm(o,n,{allowMissing:!0}).path}function vf(){const e=hf();if(!e)return[];const t=[];return e.project_location&&t.push(w(e.project_location)),e.web_location&&t.push(w(e.web_location)),t}function bf(e){const t=vf();for(const n of t){const t=gf(e,n);if(t&&c(t))return{resolved:t,root:n}}for(const n of t){const t=gf(e,n);if(t)return{resolved:t,root:n}}const n=w(e);for(const e of t)if(n.startsWith(e+S)||n===e)return{resolved:n,root:e};return null}function yf(e,t){if(0===t.length||null==e)return e;const[n,...o]=t;if("*"!==n)return yf(e[/^\d+$/.test(n)?Number(n):n],o);if(Array.isArray(e)){const t=e.map(e=>yf(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=yf(e[n],o);void 0!==i&&(t[n]=i)}return Object.keys(t).length>0?t:void 0}}function xf(e,t,n,o,i){if(i>10)return[];const r=[],a=u(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=_(e,c.name);if(!bm(j(t,a))&&!c.isSymbolicLink())if(xm(t,a),c.isDirectory())n&&r.push(...xf(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=>Ye(c.name,e,{nocase:!0})))continue;r.push(a)}}return r}process.once("exit",()=>df.dispose());const wf="cli-installation-id",_f=/^[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 kf(e){return{jsonrpc:"2.0",id:e,result:{protocolVersion:jf,capabilities:{tools:{listChanged:!0}},serverInfo:Sf}}}const Sf={name:"Needle Cloud MCP",version:"1.0.0"};function Ef(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 Tf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}let $f=!1;const If=Me(),Af=new Map,Of=new Map;let Cf=0;function Nf(){const e=[];for(const[t,{connectedAt:n,userAgent:o}]of Of)e.push({id:t,connectedAt:n,userAgent:o});return e}function Rf(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?Af.get(a):void 0)?r:t.headers["user-agent"])?i:"",c=()=>{clearInterval(l),Of.delete(e)&&(console.log(`[MCP] SSE client disconnected (ID: ${e}): ${s}`),Mp(`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()}),Of.set(e,{id:e,client:n,connectedAt:Date.now(),userAgent:s,dispose:c}),console.log(`[MCP] SSE client connected (ID: ${e}) ${s}. Total clients: ${Of.size}`),Mp(`MCP SSE client connected (ID: ${e}) ${s}. Total clients: ${Of.size}`),!0}return!1}function Pf(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}async function Uf(e=se(ne(),".needle")){let t,n;try{t=await V(se(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 Lf(){const e=await Uf();try{const t=await fetch(`${Cu}/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 zf(e,t=process.argv[1]){await new Promise((n,o)=>{const i=Ke(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.`)})})}If.get("/mcp",async(e,t)=>{if(Rf(Cf++,e,t))return;const n=function(e){const t=[...em].sort((e,t)=>e.name.localeCompare(t.name)),n=t.map(e=>`\n <div class="tool">\n <span class="tool-name">${Tf(e.name)}</span>\n <span class="tool-desc">${Tf(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)}),If.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=Cf++,o=Ef(null==(a=e.body.params)?void 0:a.clientInfo);if(Rf(n,e,t,o?`${o.name}/${o.version}`:void 0)){$f=!0;const e=kf(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 kf(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{ff()}catch{}return{jsonrpc:"2.0",id:i,result:{tools:em}}}if("tools/call"===n){const e=null==o?void 0:o.name;try{ff()}catch{}try{return{jsonrpc:"2.0",id:i,result:await sm(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;$f=!0;const n=_e(),i=Ef(null==(s=e.body.params)?void 0:s.clientInfo);Af.set(n,i?`${i.name}/${i.version}`:void 0),t.setHeader("Mcp-Session-Id",n),console.log(`[MCP] New session created: ${n} for ${o}`),Mp(`MCP New session: ${n} for ${o}`)}if(null===l)return t.status(204).end();if(Mp(`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)}}),If.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 Ff=!1;function Df(e,t={}){Ff&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n")}var qf={__proto__:null,sendStdioNotification:Df,startStdio:function(){Ff=!0,console.log=console.info=console.debug=console.error.bind(console);const e=e=>{console.error(e),Mp(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(!Pf(s)||"2.0"!==s.jsonrpc||s.id!==t.id||!Pf(s.result)&&!Pf(s.error))throw new Error("Invalid response from local MCP server");if(Pf(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?j():y.abort(new Error("MCP notification stream connection timed out"))},e)},j=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 j=new TextDecoder;let k="";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),k+=j.decode(e,{stream:!0});o=/\r?\n\r?\n/.exec(k);){const e=k.slice(0,o.index);k=k.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);Pf(i)&&"2.0"===i.jsonrpc&&"notifications/tools/list_changed"===i.method&&m&&n("notifications/tools/list_changed")}if(k.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 Xe(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=Ef(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:`${Cu}/mcp`,ensureServer:t=>async function(e={}){const{signal:t,lockPath:n=se(ne(),".needle","mcp-server-start.lock"),probe:o=Lf,log:i=(e=>console.error(e)),launch:r=(()=>zf(i)),timeoutMs:a=2e4,pollMs:s=100}=e;if(null==t||t.throwIfAborted(),await o())return;await Z(pe(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 X(n,"wx",384)}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e;try{const e=await Q(n);Date.now()-e.mtimeMs>12e4&&(i("Removing an expired MCP server startup lock."),await ee(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 Xe(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 ee(n))}}({signal:t,log:e}),notify:Df,log:e,getToken:()=>async function(e){const t=await Uf(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=De({input:process.stdin,terminal:!1}),o=e=>{Ff&&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(!Pf(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&&!Pf(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(kf(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",()=>{Ff=!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 Bf=null;function Mf(){Bf&&clearTimeout(Bf),Bf=setTimeout(()=>{!function(e,t={}){if(0===Of.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 Of)try{t.write(n)}catch(n){console.error(`[MCP] Error sending notification to client (${e}):`,n),o(),t.destroy()}}(),Df("notifications/tools/list_changed"),rh(),Bf=null},10)}const Wf=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(!Yf||Yf.readyState!==We.OPEN)throw new Error("Needle Cloud disconnected.");Yf.send(JSON.stringify(e))},register:(e,t)=>rm(e,t,{source:"cloud"},Mf),clear:()=>om("cloud",Mf),onError:e=>Mp(`[Cloud MCP] ${e}`)}),Gf=2e3,Hf=6e4,Jf=25e3,Vf=1e4,Kf=i();let Yf=null,Zf=null,Xf=null,Qf=null,eh=Gf,th=!1,nh=!1;function oh(){Yf||(qm()?Mp("Needle Cloud connection: skipped (remote_ai_tools disabled in settings)"):(th=!1,Zf&&(clearTimeout(Zf),Zf=null),eh=Gf,ah()))}function ih(e){Wf.disconnect(),th=!0,sh(),Zf&&(clearTimeout(Zf),Zf=null),Yf?(Mp(`Needle Cloud connection: closing (reason: ${null!=e?e:"shutdown"})`),Yf.close(1e3,null!=e?e:"shutdown"),Yf=null):e&&Mp(`Needle Cloud connection: disconnect requested (reason: ${e}) — no active connection`)}function rh(){if(!Yf||Yf.readyState!==We.OPEN)return;try{ff()}catch(e){Mp(`Needle Cloud connection: registerServerTools failed: ${e}`)}const e=em.filter(e=>!Wf.isCloudTool(e.name)),t=e.map(e=>e.name);var n;Mp(`Needle Cloud connection: sending ${t.length} tools: ${t.join(", ")}`),Yf.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 ah(){let e,t,n=await wd();if(n||(n=function(){const e=ud("accessToken");if(s.existsSync(e)){const t=s.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&&Mp("Needle Cloud connection: using cached token (refresh failed)")),!n)return nh||(Mp("Needle Cloud connection: skipped (not logged in)"),nh=!0),void ch(!0);nh=!1;try{e=function(e=Fm()){I(e,{recursive:!0,mode:448});const t=se(e,wf);try{G(t,i(),{flag:"wx",mode:384})}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw e}const n=M(t,"utf8").trim();if(!_f.test(n))throw new Error("Invalid local CLI installation ID.");return n}()}catch(e){return Mp(`Needle Cloud connection: could not read local CLI installation identity: ${e instanceof Error?e.message:String(e)}`),void ch(!0)}try{t=await async function(e,t={getUser:_d,getDefaultOrg:jd,authHeaders:$d}){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 Mp(`Needle Cloud connection: team authentication failed: ${e instanceof Error?e.message:String(e)}`),void ch()}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(Kf)+"&installation="+encodeURIComponent(e);Mp("Needle Cloud connection: connecting...");const r=`needle-cloud/${Zd()} Node/${process.versions.node}`;Yf=new We(o,{headers:{"User-Agent":r,Origin:"cli://needle-cloud"}}),Yf.on("open",()=>{eh=Gf,Mp("Needle Cloud connection: established"),lh(),rh(),sh(),Xf=setInterval(()=>{Yf&&Yf.readyState===We.OPEN&&(Yf.ping(),Qf=setTimeout(()=>{Mp("Needle Cloud connection: pong timeout, terminating"),Yf&&Yf.terminate()},Vf))},Jf),Wf.connect()}),Yf.on("pong",()=>{Qf&&(clearTimeout(Qf),Qf=null)}),Yf.on("message",e=>{try{const n=JSON.parse(e.toString());if(Wf.receive(n))return;var t;"execute_tool"===n.type&&n.requestId&&n.toolName&&async function(e,t,n,o,i,r){Mp(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(Wf.isCloudTool(t))throw new Error("Cloud tools cannot be executed as local tools.");"local_project_action"===t&&lh();const l=await sm(t,n,{chatId:o,editGrant:i,commandGrant:r});"local_project_select"!==t&&"local_project_start"!==t&&"local_project_status"!==t||lh(),Mp(`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}]`),Yf&&Yf.readyState===We.OPEN&&Yf.send(JSON.stringify({type:"tool_result",requestId:e,result:l}))}catch(n){const o=n instanceof Error?n.message:String(n);Mp(`Cloud tool error: ${t} → ${o} in ${Date.now()-a}ms [${e}]`),Yf&&Yf.readyState===We.OPEN&&Yf.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{}}),Yf.on("close",(e,t)=>{const n=(null==t?void 0:t.toString())||"";Mp(`Needle Cloud connection: closed (code=${e}${n?" "+n:""})`),sh(),Wf.disconnect(),Yf=null,th||ch()}),Yf.on("error",e=>{Mp(`Needle Cloud connection: error - ${e.message||"connection refused"} (is https://cloud.needle.tools/api reachable?)`)})}function sh(){Xf&&(clearInterval(Xf),Xf=null),Qf&&(clearTimeout(Qf),Qf=null)}function ch(e=!1){th||Zf||(e||Mp(`Needle Cloud connection: reconnecting in ${eh/1e3}s`),Zf=setTimeout(()=>{Zf=null,ah()},eh),eh=Math.min(2*eh,Hf))}function lh(){Yf&&Yf.readyState===We.OPEN&&Yf.send(JSON.stringify(function(){var e,t,n;const o=Gd();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?ce(o.web_location):null,cli_version:Zd()}}()))}const ph=e=>{const t=Me();return t.use("/:action",async(t,n,o)=>{const{action:i}=t.params,r=kd({navigate:e=>{n.redirect(e)}});switch(i){case"sign-in":e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,Mp("Sign in..."),await r.clearAllTokens(),hd();try{await r.signIn(`${Cu}/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 Mp(o),console.error(o),n.status(502).send(o)}break;case"sign-out":{var a,s;const t=await _d(),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;Mp(`Sign out... (${n})`),n&&o&&await async function(e){return!e.accessToken||import("node-machine-id").then(async t=>{const n=await zd();return Rd=n,await fetch("https://cloud.needle.tools/api"+ht.account.post_machine,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({action:"logout",machine_id:n,machine_name:Fd()})}).catch(e=>{Mp(`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),Mp(`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(td()),hd();break}case"auth-callback":if(t.url){const o=await r.handleSignInCallback(`${Cu}${t.originalUrl}`).catch(e=>({error:e}));if(hd(),o&&"error"in o){Mp(`Error during sign in: ${o.error}`);const e=o.error instanceof Error?o.error.message:String(o.error);n.redirect(Cu+"?cancelled&message="+encodeURIComponent(e))}else{var c,l,p,u;const t=await _d();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=[...Pd(t)];const o=await Dd(t,{signout:!0});if(!o)return e.invalid_login=!0,e.invalid_login_type="too-many-logins",n.redirect(td("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(td("error"));hd()}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)}`),Mp(`User logged in: ${(null==t||null==(p=t.userInfo)?void 0:p.sub)||(null==t||null==(u=t.claims)?void 0:u.sub)}`),oh(),n.redirect(Cu)}}break;default:o()}}),t};function uh(e,t,n){return!!n||e===kp||"string"==typeof t&&t===e}function dh(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!==c(t))try{const e=mh(t);if(e)return e}catch(e){}}function mh(e){const t=_(e,".git");if(c(t)){const e=function(e){const t=g(e);if(t.isDirectory())return _(e,"config");if(t.isFile()){const t=p(e,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(t){let n=t[1].trim();k(n)||(n=w(E(e),n));const o=_(n,"config");if(c(o))return o;const i=_(n,"commondir");if(c(i)){let e=p(i,"utf-8").trim();return k(e)||(e=w(n,e)),_(e,"config")}}}return null}(t);if(e&&c(e)){const t=function(e){const t=p(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=_(e,".plastic");if(c(n)){const e=_(n,"replicas.db");if(c(e)){const t=p(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=_(e,"..");return o===e?null:mh(o)}function fh(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 hh=new Set(["https://cloud.needle.tools","https://needle.tools","https://engine.needle.tools","https://docs.needle.tools","chrome-extension://kjcepmifiddcepiocokclhibpkgcdomk","chrome-extension://jonplpbnhmanoekkgcepnedhghflblmo"]),gh=new Set(["localhost","127.0.0.1","[::1]","::1"]);function vh(e){if("string"!=typeof e||0===e.length)return!1;if(hh.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!!gh.has(n)||"::1"===n}const bh="[MCP]",yh=new Array;function xh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function wh(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>0}async function _h(){try{return JSON.parse(await V(se(ne(),".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 jh(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 Sh={__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(`${Cu}/api/info`,{signal:AbortSignal.timeout(3e3)})}catch(e){if(e instanceof Error&&xh(e.cause)&&"ECONNREFUSED"===e.cause.code)return{running:!1,url:Cu};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(!xh(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&&!wh(a.pid))throw new Error("Invalid local server PID.");if(wh(a.pid))return{running:!0,url:Cu,version:a.version,pid:a.pid,pidSource:"server"};const s=await(null!=(n=e.readServerRecord)?n:_h)();return xh(s)&&s.port===Ou&&wh(s.pid)&&(null!=(o=e.isProcessAlive)?o:jh)(s.pid)?{running:!0,url:Cu,version:a.version,pid:s.pid,pidSource:"record"}:{running:!0,url:Cu,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 Eh="2026-10-25T12:32:57.969Z";var Th={__proto__:null,BUILD_TIME:Eh};const{json:$h}=Qe;function Ih(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 Ah(t={restart:!1}){const n=!0===t.restart,o=await e(Cu).catch(e=>({ok:!1})),r="/sign-in",a="/api/authenticated",s="/api/projects",l="/api/content",p={baseUrl:Cu,port:Ou,isHost:!1,auth_endpoints:{"sign-in":`${Cu}${r}`,"sign-out":`${Cu}/sign-out`,"is-authenticated":`${Cu}${a}`}};let u=o.ok;if(u){var d;const g=await e(`${Cu}/api/info`).catch(()=>null);if(null!=g&&g.ok){const b=await g.json().catch(()=>null);if(null!=b&&b.api_endpoint&&"https://cloud.needle.tools/api"!==b.api_endpoint){if(!uh(b.api_endpoint,"https://cloud.needle.tools/api",n))return Mp(`Keeping CLI server for ${b.api_endpoint}; https://cloud.needle.tools/api did not request an explicit restart.`),p;Mp(`Running server uses different API endpoint (${b.api_endpoint} vs https://cloud.needle.tools/api), restarting...`),t||(t={}),t.restart=!0}}if(!0===(null==(d=t)?void 0:d.restart)){Mp("Restarting auth server...");const y=`${Cu}/restart`;t.ora&&(t.ora.text="Sending restart request to server");const x=new AbortController;setTimeout(()=>x.abort(),1e4);let w={};try{const k=_($e(),".needle","local-server-token"),S=JSON.parse((await import("fs")).readFileSync(k,"utf-8"));S.token&&(w={Authorization:`Bearer ${S.token}`})}catch{}const j=await e(y,{method:"post",signal:x.signal,headers:{...w,"x-needle-api-endpoint":"https://cloud.needle.tools/api",...n?{"x-needle-explicit-restart":"true"}:{}}}).catch(e=>({ok:!1,status:400,error:e}));if(j.ok)return await kl(300),Ah({restart:!1});409!==j.status&&console.error("Failed to restart server",j.status),Mp(`Failed to restart server: ${j.status}`)}}if(!u){process.title="Needle CLI server";const E=await import("express").catch(e=>{throw console.error("Error starting the auth server (express not found)",e),Mp("Error starting the auth server"),new Error("Failed to load express module")});if(!E)throw Mp("Error loading auth server module"),new Error("Failed to load express module");Mp(`Starting Needle CLI server ${Zd()} (built ${Eh})... (Using api at https://cloud.needle.tools/api)`,{emptyLineBefore:!0}),p.isHost=!0;let T=null;const A={invalid_login:!1,invalid_login_type:null,user_email:null,logged_in_machine_names:[]};let O=E.default();const C=_($e(),".needle"),N=function(e,t){var n;const o=se(e,"local-server-token"),r=null!=(n=function(e){if(!$(e))return null;try{const t=M(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();I(e,{recursive:!0});const a=JSON.stringify({token:r,pid:process.pid,port:t},null,2);if(G(o,a,{encoding:"utf-8",mode:384}),"win32"===process.platform)try{const e=process.env.USERNAME||process.env.USER||"";e&&He("icacls",[o,"/inheritance:r","/grant:r",`${e}:(F)`],{stdio:"ignore",timeout:5e3})}catch{}return r}(C,Ou);Mp(`Local token written to ${_(C,"local-server-token")}`);const R=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=>Mp(`Denied: ${e}`),5e3);O.use((h={onDenied:R},(e,t,n)=>{var o;return fh(e.headers.host)?n():(null==h||null==h.onDenied||h.onDenied(`host|${null!=(o=e.headers.host)?o:"missing"}`,"HTTP Host is not a loopback authority"),t.status(403).send("Forbidden: host not allowed"))})),O.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(vh(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:R})),O.use($h({limit:"10mb"}));const P=new Set(["/","/sign-in","/sign-out","/auth-callback","/api/info","/api/authenticated","/api/public_key","/mcp","/register"]),U="needle_local";O.use((e,t,n)=>{var o,i,r;if("OPTIONS"===e.method)return n();if(P.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]===N)return n()}if((null==(i=e.query)?void 0:i.token)===N)return n();const s=((null==(r=e.headers)?void 0:r.cookie)||"").split(";").map(e=>e.trim()).find(e=>e.startsWith(U+"="));if(s&&s.split("=")[1]===N)return n();try{var c,l;const t=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown";R(`token|${t}|${e.path}`,`path=${e.path} ua="${t}" — no valid token or cookie`)}catch{}return t.status(401).send("Unauthorized: token required")}),O.use(ph(A)),t.ora?(t.ora.start("Starting MCP server..."),t.ora.succeed(`MCP server available at ${Cu}/mcp`)):console.log(`\nMCP server available at ${Cu}/mcp .`),O.use(If);const L="\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>",z=`<div class="main_panel"><img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" title="Needle Logo (${Zd()})"/>`,F="</div>";let D="";O.get("/",Id(),async(e,t)=>{var n,o;if(null!=(n=e.user)&&n.isAuthenticated?t.cookie(U,N,{httpOnly:!0,sameSite:"strict",path:"/"}):t.clearCookie(U,{path:"/"}),t.set({"Content-Type":"text/html; charset=utf-8"}),t.write(L),null!=e.query.cancelled)return t.end("Login cancelled. You can close this window now."),void Mp("Login cancelled by user");if(null!=e.query["too-many-logins"]&&A.logged_in_machine_names.length){var i;const e=Sp();let n="<div>";return n+="<strong>You have reached the maximum number of allowed device logins!</strong><br/><br/>",n+=(null==(i=A.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="${r}">sign-in on this machine</a>.<br/><br/>`,n+="</div>",t.status(406),t.end(z+n+F),void Mp(`Login failed: Too many logins from different machines: [${A.logged_in_machine_names.join(", ")}]`)}if(null!=e.query.error)return t.status(500),void t.end(`${z}\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="${r}">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://${Dp()}" target="_blank">${Dp()}</a></span>\n </div>\n ${F}`);if(null!=(o=e.user)&&o.isAuthenticated){var a;if(!await Ld(e.user)){if(A.invalid_login=!0,A.logged_in_machine_names=[...Pd(e.user)],od(),Mp("Cleared stored auth data"),"client"in e.user){const t=e.user;await t.client.clearAccessToken(),await t.client.clearAllTokens(),Mp("Cleared all tokens")}return t.end(`${z}<div>You have been logged out from this machine. You can close this window now or try to <a href="${r}">sign in</a> again</div>${F}`)}A.invalid_login=!1,t.end(`${z}\n <div>\n Hi ${Td(e.user)} — you logged in successfully. You can close this window now.\n </div>\n ${F}`);const n=`Logged in successfully as ${Td(e.user)} (${null==(a=e.user.userInfo)?void 0:a.sub})`;return void(D!==n&&(D=n,Mp(D)))}let s=`<span><a href="${r}">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(z+s+F),t.end()}),O.post("/restart",(e,n)=>{var o;if(!uh("https://cloud.needle.tools/api",e.headers["x-needle-api-endpoint"],"true"===e.headers["x-needle-explicit-restart"]))return Mp("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.");t.ora&&(t.ora.text="Received restart event. This instance will close"),null==(o=T)||o.close(e=>{e&&console.error(e)}),setTimeout(()=>{process.exit(0)},100),n.status(200).end("Server is restarting"),Mp("Server is restarting\n")}),O.get("/api/logs",async(e,t)=>{const n=Dp();c(n)?v(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${Zd()} (built ${Eh}) Log File (newest first) ---\n${n}\n\n`;r+=i,t.status(200).end(r)}):t.status(404).end("Log file not found")}),O.get("/api/info",(e,t)=>{t.json(kh("https://cloud.needle.tools/api",Zd()))}),O.get(a,Id(),async(e,t)=>{var n;if(!0===A.invalid_login){const e=Oh(A);return t.status(e.status).json(e)}A.invalid_login=!1,t.status(null!=(n=e.user)&&n.isAuthenticated?200:400).send()}),O.get("/api/user",Id(),async(e,t)=>{var n;const o=e.user;if(null==o||!o.isAuthenticated){if(!0===A.invalid_login){const e=Oh(A);return t.status(e.status).json(e)}return t.status(401).json({error:"Not authenticated"})}if(A.invalid_login=!1,!await Ld(o))return od(),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:Td(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)}),O.get("/api/license",Id(),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 _d();if(!e||!e.isAuthenticated)return n.status(401).json({error:"Not authenticated",code:"not_authenticated"});if(!await Ld(e))return od(),n.status(403).json({error:"Invalid login"});c=await $d(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=gt(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${ht.account.get_licenses}`,{method:"GET",headers:u}).catch(e=>{const t=Ih(e);return console.error("Failed to fetch licenses:",t),Mp(`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})}),O.get("/api/deployments",Id(),async(e,t)=>{var n;const o=await _d();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 $d(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 Tu({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=`${Ep()}/${e.id}`;const s={...a};return t.json(s)}),O.get(l,Id(),async(e,t)=>{var n,o,i,r,a,s,c,l;const p=await _d();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 $d(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 np({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)}),O.get(l+"/:identifier",Id(),async(e,t)=>{var n,o;const i=await _d();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 $d(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 op({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)}),O.get(s,Id(),async(t,n)=>{const o=await _d();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i=`https://cloud.needle.tools/api${ht.local_projects.get.user}`,r=await e(i,{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}}).catch(e=>(console.error("Failed to fetch projects:",Ih(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)}),O.get(s+"/:id",Id(),async(t,n)=>{var o;const i=await _d();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 $d(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=gt(a),c=`https://cloud.needle.tools/api${ht.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:",Ih(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"})}),O.post("/api/projects",Id(),async(t,n)=>{const o=await _d();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 zd(),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${ht.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:",Ih(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"})}),O.get("/api/public_key",Id(),async(t,n)=>{var o,i;const r=await _d();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 $d(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 zd()},l=await e(`https://cloud.needle.tools/api${ht.account.public_key}`,{method:"POST",headers:{...gt(s),"Content-Type":"application/json"},body:JSON.stringify(c)}).catch(e=>(console.error("Failed to fetch public key:",Ih(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})}),O.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=dh(o);return i?t.json({project_id:i}):t.status(404).json({error:"Project ID not found"})}),O.post("/api/project/info",Id(),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=Vd();let s=Kd();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&&Mp(`Active project changed: ${l||"(none)"} → ${u}`);try{qd=s;const e=JSON.stringify(s);f(a,e,"utf-8")}catch(e){console.error("Failed to save project info:",e)}}(e)}catch(e){Mp("Error saving project info: "+e)}})("string"==typeof e.body?JSON.parse(e.body):e.body),t.send("OK")});let q=null;const B=new Promise(e=>q=e);let W=!1;if(T=O.listen(Ou,()=>{null==q||q()}),T.on("error",e=>{if("EADDRINUSE"===(null==e?void 0:e.code))return Mp(`License server port ${Ou} already in use — a server is already running; not starting a second one.`),W=!0,p.isHost=!1,void(null==q||q());console.error("[needle] License server failed to start:",(null==e?void 0:e.message)||e),Mp(`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()}})}(T,Mp),T.on("close",m),process.on("exit",m),process.on("SIGINT",()=>{m(),process.exit(0)}),await B.catch(e=>{console.error(e),Mp(`Error starting the auth server (promise failed): ${e.message}`)}),W)return p;function m(){Mp("Cleaning up auth server...")}const H=function(e,t){const n=new Ge({server:e,path:"/mcp/ws",verifyClient:({req:e},t)=>{var n;if(!fh(e.headers.host))return Mp(`${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&&!vh(o))return Mp(`${bh} rejected WS upgrade: disallowed origin ${o}`),void t(!1,403,"Forbidden: origin not allowed");t(!0)}});Mp("MCP websocket server created.");let o=0,i=new Map;return n.on("connection",e=>{const t=++o;yh.push(e),console.log(`${bh} client connected (#${t})`),Mp(`${bh} client connected (#${t})`),e.on("close",()=>{const n=yh.indexOf(e);-1!==n&&yh.splice(n,1);const o=i.get(t);if(o){for(const e of o)im(e,Mf);i.delete(t)}console.log(`${bh} client disconnected (#${t})`),Mp(`${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}`),Mp(`Unknown MCP websocket command received: ${a.command}`);break;case"get_connected_clients":!function(t,n){const o={clients:[...Nf()],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&&om(r,Mf);const s=r||"unknown";console.log(`${bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`),Mp(`${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)rm(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},Mf),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}(T);ff({logToolCount:!0}),oh();const J=Gm(C,()=>{qm()?(Mp("Settings changed: remote_ai_tools disabled — closing cloud connection"),ih("remote_ai_tools setting disabled")):(Mp("Settings changed: remote_ai_tools enabled — opening cloud connection"),oh())});Od(O,N,()=>{Mp("Authenticated stop requested; shutting down the local Needle server."),T&&Cd(T,H,()=>{J(),ih("stop requested")})}),process.on("exit",()=>{J(),ih("process exit")})}var h;return p}function Oh(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 ${Sp()}. You're currently logged in on: ${e.logged_in_machine_names.join(", ")}`:"An unknown error occured.",{status:403,error:t}}async function Ch(e={headless:!1,silent:!1,clearAuthData:!1}){return!0===e.clearAuthData&&await od(),Rh("sign-in",{...e})}function Nh(e={}){return Rh("sign-out",{...e})}function Rh(t,n){return new Promise(async(o,i)=>{let r=!1;if("sign-in"==t){const e=await _d();if(null!=e&&e.isAuthenticated&&e.accessToken)return await Dd(e)?(r=!0,n.ora&&(n.ora.text=`Authorized as ${Td(e)}`),"gotoAccountPage"in n&&!0===n.gotoAccountPage&&(n.ora&&(n.ora.text="Opening account page in the browser"),Tp(Sp()),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,od();const t=await Ah(),n=await e(t.auth_endpoints["sign-out"],{follow:2});return o(n.ok)}const a=await Ah();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(()=>Tp(e),300),n.ora&&(n.ora.text=`Please authenticate in the browser: ${e}`),setTimeout(l,2e3);break;case"sign-out":od(),Tp(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 _d();return e&&!await Dd(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;T().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,od(),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:Bp,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 Ph=process.argv.includes("--silent"),Uh=JSON.parse(p(new URL("../package.json",import.meta.url),"utf-8")),Lh="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 zh(e,t=null,n=!0){let o,i=null==e?void 0:e.toString();var r;if(i||(ze.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=T({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 _d();return null==e?void 0:e.isAuthenticated}()&&(e=Ph?void 0:T("No access token found. Please sign in to authenticate...").start()),Mp("No access token provided, attempting login. Org: "+t);const r=Ch({headless:!n,ora:e,timeout:12e4}),d=await r;if(d&&!await Ld(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 Nh({headless:!0}),process.exit(1)}else e&&(Mp("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 (${Td(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)),Mp("Getting access token for org "+o+", "+i.substring(0,8)+"...")}else{var u;Mp("Getting access token for user "+(null==(u=d.userInfo)?void 0:u.sub)),i=null==d?void 0:d.accessToken}}}if(!i)throw Mp("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 Fh(e){return null!=e.org&&console.warn("Warning: --org is deprecated. Use --team instead."),e.team||e.org}const Dh=mt.program;async function qh(){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))}Dh.version(Uh.version).description("Command-line interface (CLI) for Needle Cloud"),Dh.command("version","Print the CLI version").configure({visible:!1}).action(()=>{Ph||console.log(`☁ Needle CLI — ${Uh.version}, Node ${process.version}`)}),Dh.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:Dh.BOOLEAN,default:!1}).option("--integration <integration>","Hint for the process which integration triggered this command",{required:!1,validator:Dh.STRING}).action(async({options:e})=>{const t=e.integration,n=Ph?void 0:T("Starting Needle License server "+(t?`(from ${t})`:"")).start();Ah({ora:n,restart:e.restart}).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${Zd()}, built ${function(e){if("string"!=typeof Eh||0===Eh.length)return"unknown";const t=new Date(Eh);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))})}),Dh.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 Nd}),t=await e();Ph||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)}}),Dh.command("settings","Show current Needle CLI settings").action(async()=>{const{readSettings:e,KNOWN_SETTINGS:t}=await Promise.resolve().then(function(){return Hm}),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("")}),Dh.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:Dh.BOOLEAN}).action(nu("settings remote-ai-tools",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled,i=n();o?(t(i,"remote_ai_tools",null),console.log("Remote AI tools enabled (default)."),Mp("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."),Mp("Settings: remote_ai_tools set to disabled via CLI command"))})),Dh.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:Dh.BOOLEAN}).action(nu("settings local-file-edits",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled;t(n(),"local_file_edits",o?null:"disabled"),console.log(`Local AI file edits ${o?"enabled":"disabled"}.`)})),Dh.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:Dh.BOOLEAN}).action(nu("settings local-project-commands",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled;t(n(),"local_project_commands",o?null:"disabled"),console.log(`Local AI project commands ${o?"enabled":"disabled"}.`)})),Dh.command("status","Show the local Needle server status and process ID").action(nu("status",async()=>{const{getLocalServerStatus:e,formatLocalServerStatus:t}=await Promise.resolve().then(function(){return Sh});console.log(t(await e()))})),Dh.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(nu("mcp",async()=>{const{startStdio:e}=await Promise.resolve().then(function(){return qf});e()})),Dh.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=dh(e.paths);t?console.log(`Found project ID: "${t}"`):console.log("No project ID found.")}),Dh.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:Dh.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:Dh.BOOLEAN,default:!1}).action(nu("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 Xu}),{tryGetFreshAccessTokenForResource:p}=await Promise.resolve().then(function(){return Ed}),{findActiveEditorLog:u}=await import("./cli.send-logs.discovery-564639d7.js"),{getLogFilePath:d,getPrevLogsFilePath:m,getPipelineLogFilePath:f}=await Promise.resolve().then(function(){return Wp}),{homedir:h,platform:g}=await import("os"),{existsSync:v}=await import("fs"),{BUILD_TIME:b}=await Promise.resolve().then(function(){return Th}),{getNodeVersion:y,getNpmVersion:x,getArch:w,getOsRelease:_,getCpuCount:j,getTotalMemoryMb:k,getTzOffsetMinutes:S,isCi:E,isTty:$}=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",A=e.note,O=null!=(i=null!=(r=null==(a=e.dryRun)||null==a.valueOf?void 0:a.valueOf())?r:e.dryRun)&&i,C=d(),N=m(),R=f(),P={getAccessToken:()=>p(l),fetch:globalThis.fetch,paths:{cliLogPath:v(C)?C:null,prevLogPath:v(N)?N:null,pipelineLogPath:v(R)?R:null,homeDir:h()},meta:{cli_version:Zd(),build_time:b,os:g(),os_release:_(),arch:w(),node_version:y(),npm_version:null!=(s=x())?s:"unknown",cpu_count:j(),total_memory_mb:k(),tz_offset_minutes:S(),is_ci:E(),is_tty:$()},findActiveEditorLog:u,stdout:process.stdout,stderr:process.stderr},U=O?"Building payload (dry-run)":"Uploading logs",L=Ph?void 0:T(U).start();P.recoverAuth=async()=>{null==L||L.stop();try{await qh();const e=await Ch({clearAuthData:!0,silent:Ph,ora:void 0});if(null==e||!e.isAuthenticated)return null}catch(e){return Mp(`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:A,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)})),Dh.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:Dh.BOOLEAN,default:!1}).option("--clear <clear>","Refresh the access token",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(async({options:e})=>{const t=ru(e),n=!0===e.nonInteractive||!0===e.headless;n||await qh();const o=!0===e.clear,i=Ph?void 0:T("Login").start();await Ch({headless:n,silent:Ph,clearAuthData:o,ora:i}).then(async e=>{"json"===t&&cu({authenticated:!0===(null==e?void 0:e.isAuthenticated)}),null!=e&&e.isAuthenticated?null==i||i.succeed("Successfully logged in as "+Td(e)):0==n?null!=e&&e.claims||null!=e&&e.userInfo?null==i||i.warn(`You (${Td(e)}) are not authenticated...`):null==i||i.fail("Login failed"):Ph||null==i||i.warn("Not logged in"),await lu(null!=e&&e.isAuthenticated?0:1)})})),Dh.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:Dh.BOOLEAN,default:!1}).action(su(async({options:e})=>{const t=ru(e),n=!0===e.nonInteractive||!0===e.headless;n||await qh(),await Nh({headless:n}).then(async e=>{"json"===t&&cu({success:e}),e?T("Logged out").succeed():T("Logout failed").fail(),await lu(e?0:1)})})),Dh.command("me","Prints your user information").help("Prints basic informaton about the logged in Needle Cloud account (your account)").action(su(async({options:e})=>{const t=ru(e),n=Ph?void 0:T("Query user data").start(),o=await _d(),i=Boolean((null==o?void 0:o.isAuthenticated)&&await Ld(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 ${Td(o)}`),console.log(`- Name: ${Td(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?cu({authenticated:!0,id:e.sub,name:Td(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}))}):(cu({authenticated:!1}),process.exitCode=1)}})),Dh.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:Dh.STRING}).option("--org <org>","Legacy alias for --team",{validator:Dh.STRING,hidden:!0}).action(nu("get-pro",async({options:e})=>{var t;let n=(null==(t=Fh(e))?void 0:t.toString())||null;const o=T().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}`),Tp(r)}));const Bh={account:{url:Sp}},Mh=`"${Object.keys(Bh).join('", "')}"`;Dh.command("open",`Open a page in the default browser. Options are: ${Mh}`).argument("<page>",`The page to open. Options are: ${Mh}`,{validator:Dh.STRING}).configure({strictOptions:!1,strictArgsCount:!1,visible:!1}).help("").action(async({args:e,logger:t})=>{const n=e.page.toString(),o=Bh[n];o?"url"in o?Tp(o.url()):t.error(`Unknown argument: ${n}`):t.error(`Unknown argument: ${n}. Options are: ${Mh}`)}),Dh.command("list-deployments","Get a list of deployed websites").configure({visible:!1}).help("").option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--limit <limit>","Limit the number of deployments to show (min: 0, max: 100)",{validator:Dh.NUMBER,default:10}).option("--offset <offset>","The offset for deployments (default: 0, min: 0)",{validator:Dh.NUMBER,default:0}).option("--format <format>","Legacy output option: cli or json",{validator:Dh.STRING,hidden:!0}).option("--name","Filter by one or multiple deployment names (separated by ;)",{validator:Dh.STRING}).action(su(async({options:e,logger:t})=>{var n,o,i,r;const a=ru(e,{legacyFormat:!0}),{accessToken:s,org_id:c}=await zh(e.token,Fh(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=T("Query deployments").start(),f=await Tu({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 cu(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")})),Dh.command("list","List content items (3d assets, deployments, materials, etc.)").alias("list-content").help('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>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--include-projects","Include saved web projects (default: uploaded content only)",{validator:Dh.BOOLEAN,default:!1}).option("--trash","List deleted items instead of active content",{validator:Dh.BOOLEAN,default:!1}).option("--interactive","Override automatic terminal browsing: true or false",{validator:Dh.BOOLEAN}).option("--type <type>","Filter by content type (e.g. material, 3d-asset, deployment, editor-project)",{required:!1,validator:Dh.STRING}).option("--format <format>","Filter by output format (e.g. glb, textures)",{required:!1,validator:Dh.STRING}).option("--search <search>","Search by name, title or description",{required:!1,validator:Dh.STRING}).option("--limit <limit>","Max number of items to show (default: 20, max: 100)",{validator:Dh.NUMBER,default:20}).option("--offset <offset>","Offset for pagination (default: 0)",{validator:Dh.NUMBER,default:0}).option("--output <output>","Output style: cli (default), json",{validator:Dh.STRING,default:"cli"}).action(su(async({options:e,logger:t})=>{var n,o,i,r,a,s;const c=ru(e),l=function(e,t={input:!0===process.stdin.isTTY,output:!0===process.stdout.isTTY}){return!0===e.interactive?(hu(e,t),!0):!(!1===e.interactive||!0===e.nonInteractive||"json"===e.output||!t.input||!t.output||(hu({...e,interactive:!0},t),0))}(e),p=Number(null!=(n=e.limit)?n:20),u=Number(null!=(o=e.offset)?o:0);if(!Number.isInteger(p)||p<1)throw new Error("--limit must be a positive integer.");if(!Number.isInteger(u)||u<0)throw new Error("--offset must be a nonnegative integer.");const d=null==(i=e.type)?void 0:i.toString(),m=null==(r=e.format)?void 0:r.toString();if(d&&"editor-project"!==d&&!ep.some(e=>e===d))throw new Error("Invalid --type. Use "+[...ep,"editor-project"].join(", ")+".");if(m&&!tp.some(e=>e===m))throw new Error("Invalid --format. Use "+tp.join(", ")+".");const{accessToken:f,org_id:h}=await zh(e.token,Fh(e),!0!==e.nonInteractive),g=(null==(a=e.endpoint)?void 0:a.toString())||"https://cloud.needle.tools/api",v=Math.min(p,100),b=d||void 0,y=m||void 0,x=(null==(s=e.search)?void 0:s.toString())||void 0,w={content_type:b,include_projects:!0===e.includeProjects,trash:!0===e.trash,content_format:y,search:x,limit:v,offset:u},_=T("Querying content...").start();try{const e=await np({baseUrl:g,authToken:f,org:h},w);if(l)return _.stop(),await async function(e,t={}){var n,o,i,r;const a=null!=(n=t.terminal)?n:function(){const e=Pe({input:process.stdin,output:process.stdout,terminal:!0,historySize:0}),t=new AbortController;return e.on("SIGINT",()=>{t.abort(),e.close()}),e.on("close",()=>t.abort()),{get columns(){return process.stdout.columns||80},color:void 0===process.env.NO_COLOR&&"dumb"!==process.env.TERM,write:e=>{process.stdout.write(e)},async readLine(n){if(t.signal.aborted)return null;try{return await e.question(n,{signal:t.signal})}catch(e){if(t.signal.aborted)return null;throw e}},close:()=>e.close()}}(),s=null!=(o=t.listContent)?o:np,c=null!=(i=t.getContent)?i:op,l=null!=(r=t.open)?r:Tp;let p,u={...e.query},d=e.initial;try{for(yu(a,d,u);;){var m,f;const t=await a.readLine(bu(a,"\n › ","brand"));if(null===t)break;const n=t.trim();if("q"===n||"quit"===n)break;if(p){"b"===n?(p=void 0,yu(a,d,u)):u.trash||"o"!==n?u.trash||"e"!==n?a.write(" Choose o/e to open, b to go back, or q to quit.\n"):await wu(p.edit_url,a,l):await wu(p.view_url||p.url,a,l);continue}if(/^\d+$/.test(n)){var h;const t=d.items[Number(n)-1];if(!t){a.write(" Choose a number shown on this page.\n");continue}const o=u.trash?void 0:await c(e.auth,t.identifier,{item:null!=(h=t.item_type)?h:"content"});p=t,xu(a,t,o,!0===u.trash);continue}if("?"===n||"help"===n){a.write("\n Type a number and Enter to inspect an item.\n /wood searches; / clears search. n/p move between pages.\n t switches between content and Trash; r refreshes the page.\n Browsing never changes content. Opening a browser requires o/e.\n q, Ctrl+C or end of input leaves the browser.\n");continue}const o=null!=(m=u.offset)?m:0,i=null!=(f=u.limit)?f:20;if("n"===n){if(o+d.items.length>=d.total){a.write(" No next page.\n");continue}u={...u,offset:o+i}}else if("p"===n){if(!o){a.write(" Already on the first page.\n");continue}u={...u,offset:Math.max(0,o-i)}}else if(n.startsWith("/"))u={...u,offset:0,search:n.slice(1).trim()||void 0};else if("t"===n)u={...u,offset:0,trash:!u.trash};else if("r"!==n){a.write(" Type a number, /search, n, p, t, r, ? or q.\n");continue}d=await s(e.auth,u),yu(a,d,u)}a.write("\n Back to your terminal.\n")}finally{a.close()}}({auth:{baseUrl:g,authToken:f,org:h},query:w,initial:e}),void await lu(0);if("json"===c)return _.succeed(`Found ${e.items.length} of ${e.total} items`),void cu(e.items);0===e.items.length&&(_.warn("No content found"+(b?` (type: ${b})`:"")+(y?` (format: ${y})`:"")),process.exit(0)),_.succeed(`Found ${e.items.length} of ${e.total} items`);const n=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?Sl(new Date(e.created_at),new Date,{allowSimple:!0,limitInDays:2}):""}}),o={id:Math.max(2,...n.map(e=>e.id.length)),type:Math.max(4,...n.map(e=>e.type.length)),formats:Math.max(7,...n.map(e=>e.formats.length)),name:Math.max(4,...n.map(e=>e.name.length))},i=Au(` ${"ID".padEnd(o.id)} ${"TYPE".padEnd(o.type)} ${"FORMATS".padEnd(o.formats)} ${"NAME".padEnd(o.name)} ${"#".padStart(3)} AGE`);t.info(i);for(const e of n){const n=Iu(e.type).padEnd(o.type+11),i=(e.formats?e.formats.split(", "):[]).map(e=>Iu(e)).join(", ")+" ".repeat(Math.max(0,o.formats-e.formats.length));t.info(` ${Au(e.id.padEnd(o.id))} ${n} ${i} ${e.name.padEnd(o.name)} ${e.versions.padStart(3)} ${Au(e.date)}`)}e.total>u+v&&t.info(` ... ${e.total-u-v} more (use --offset ${u+v})`),process.exit(0)}catch(e){_.fail(e.message),process.exit(1)}})),Dh.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:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The Needle Cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).action(su(async({args:e,options:t})=>{var n;const o=ru(t),{accessToken:i,org_id:r}=await zh(t.token,Fh(t),!0!==t.nonInteractive),a=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",s=String(e.identifier),c=T(`Deleting content "${s}"...`).start();try{const e=await Eu({identifier:s,endpoint:a,authToken:i,org:r});c.succeed(e.message||`Moved content "${s}" to the trash`),"json"===o&&cu(e)}catch(e){c.fail(e.message),process.exitCode=1}})),Dh.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:Dh.STRING}).argument("[directory]","Output directory (default: current directory)",{default:"."}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--format <format>","Output format to download (e.g. glb, textures)",{required:!1,validator:Dh.STRING}).option("--version <version>","Download this source version or derived output ID",{validator:Dh.STRING}).option("--label <label>","Download the version served by this label",{validator:Dh.STRING}).option("--name <name>","Output filename (without extension)",{required:!1,validator:Dh.STRING}).option("--verbose","Show detailed download info",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(async({args:e,options:t})=>{var n,o,i,r,a,s;const c=ru(t),{accessToken:l,org_id:p}=await zh(t.token,Fh(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=T("Looking up content...").start();try{var b,y;const e={baseUrl:u,authToken:l,org:p},n=await op(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 _u({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&&cu(i)}catch(e){v.fail(e instanceof Error?e.message:String(e)),process.exitCode=1}})),Dh.command("deploy","Deploy a website to Needle").help("").argument("<directory>","The directory to deploy",{validator:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to deploy to (not needed when using token/accesstoken)",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id to deloy to (not needed when using token/accesstoken)",{required:!1,validator:Dh.STRING,hidden:!0}).option("--name <name>","The project name. This name will also be used in your website URL",{required:!1,validator:Dh.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:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING,hidden:!0}).option("--open","Open the deployment in the default browser",{default:!0,validator:Dh.BOOLEAN}).option("--verbose <verbose>","Enables verbose output logs",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--experimental","Use the experimental upload API. Mostly used for debugging (default: false)",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--raw","Use raw to disallow modifications like gzip compression on upload",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--no-provenance","Do not record which commit and CI run this deployment came from",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(nu("deploy",async({args:e,options:t,logger:n})=>{var o,i,r,a;const s=ru(t),c=!0!==t.nonInteractive&&t.open,{accessToken:l,org_id:p}=await zh(t.token,Fh(t),!0!==t.nonInteractive),u=!0===t.verbose,d=!0===t.experimental,m=!0===t.raw,f=(null==(o=t.noProvenance)?void 0:o.valueOf())||!1,h=await Hp({logger:n,endpoint:(null==(i=t.endpoint)?void 0:i.toString())||void 0,token:l,org_id:p,directory:String(e.directory),name:(null==(r=t.name)?void 0:r.toString())||void 0,entrypoint:(null==(a=t.entrypoint)?void 0:a.toString())||void 0,open:c,verbose:u||!1,experimental:d||!1,raw:m||!1,noProvenance:f});"json"===s&&null!=h&&h.success&&cu(h)}))),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. 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 or folder 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("--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.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(nu(n,async({args:e,options:n})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Re({stdout:a,stderr:a});try{var s,c;const i=ru(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 iu(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:bt)({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")}}ku(await(null!=(s=t.upload)?s:ju)({token:p,org_id:u,fileOrDirectory:String(e.path),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}}))}uu(e)}(Dh,{getAccessToken:zh,getUser:_d}),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(nu(`label ${n}`,async({args:e,options:o})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Re({stdout:a,stderr:a});try{var s;const i=ru(o,{legacyFormat:!0}),r=String(e.contentId);Kp(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&&Yp(a),void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await iu(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:Qp)(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`),du(t.targets,m);else m(`No labels for ${r}.\n`)}else{var l;const e=await(null!=(l=t.setContentLabel)?l:eu)(d,a);"json"===i?m(JSON.stringify(e)+"\n"):(m(`${e.label}: ${e.previousVersionIds.join(", ")||"(new label)"} -> ${e.versionId}\n`),du(e.targets,m))}}finally{globalThis.console=r}}))}uu(e)}(Dh,{getAccessToken:zh}),function(e,t){const n={getContent:op,updateContent:ip,restoreContent:ap,...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(nu(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 mu(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 Re({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 iu(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(fu).join(""):"No upload versions.\n"))}}finally{globalThis.console=u}}))}uu(e)}(Dh,{getAccessToken:zh}),Dh.command("generate-material","Generate a PBR material from a text prompt").help("").argument("<prompt>","The text prompt describing the material to generate",{validator:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:Dh.STRING,hidden:!0}).option("--resolution <resolution>","The material texture resolution (256, 512, 1k, 2k, 4k)",{default:"512",required:!1,validator:Dh.STRING}).option("--name <name>","Output filename",{required:!1,validator:Dh.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:Dh.STRING}).action(su(nu("generate-material",async({args:e,options:t,logger:n})=>{var o,i,r;const a=ru(t),{accessToken:s,org_id:c}=await zh(t.token,Fh(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 ${Sp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";Mp(`[generate-material] Starting request to ${t}, prompt="${e.prompt}", resolution=${e.resolution||512}`,{emptyLineBefore:!0});const n=T("Requesting material generation...").start(),o=await Promise.race([Ql({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 Mp(`[generate-material] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(Mp(`[generate-material] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return Mp(`[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=T("Waiting for material generation...").start();r.color="gray";const a=kc();for(;;){if("completed"===i.status){r.succeed("Material generation completed");break}let n=2e3;const o=await jc(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)){Mp(`[generate-material] Job completed: ${i.identifier}`),r.succeed(`Material generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return Mp(`[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 Mp(`[generate-material] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`Material generation failed: ${o.error||""}`),{error:o.error||"Material generation failed"}}await kl(n)}if(e.outDir){const n=await _u({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?cu(m):!u&&"identifier"in m&&console.log(m.identifier),await lu(0)}))),Dh.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:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:Dh.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:Dh.STRING}).option("--face-count <faceCount>","Target polygon count (40000-1500000). Leave unset to let the generator choose.",{required:!1,validator:Dh.NUMBER}).option("--name <name>","Output filename",{required:!1,validator:Dh.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:Dh.STRING}).action(su(nu("generate-3d",async({args:e,options:t,logger:n})=>{var o,i,r;const a=ru(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 zh(t.token,Fh(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 ${Sp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";Mp(`[generate-3d] Starting request to ${t}, prompt="${e.prompt}", quality=${e.quality||"draft"}`,{emptyLineBefore:!0});const n=T("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+ht.jobs.create,i={...gt(e),"content-type":"application/json"},r={type:"ai-3d-asset",triggered_by:e.trigger_type,parameters:{...t}},a=await fetch(o,{...vt,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 Mp(`[generate-3d] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(Mp(`[generate-3d] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return Mp(`[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=T("Waiting for the 3D model...").start();r.color="gray";const a=kc();for(;;){if("completed"===i.status){r.succeed("3D generation completed");break}let n=2e3;const o=await jc(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)){Mp(`[generate-3d] Job completed: ${i.identifier}`),r.succeed(`3D generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return Mp(`[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 Mp(`[generate-3d] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`3D generation failed: ${o.error||""}`),{error:o.error||"3D generation failed"}}await kl(n)}if(e.outDir){const n=await _u({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?cu(f):!d&&"identifier"in f&&console.log(f.identifier),await lu(0)}))),Dh.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>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--slug <slug>","Chat slug to continue an existing conversation",{required:!1,validator:Dh.STRING}).option("--no-stream","Disable streaming (returns full response at once)",{required:!1,validator:Dh.BOOLEAN,default:!1}).option("--once","Send one message and exit",{validator:Dh.BOOLEAN,default:!1}).action(nu("ask",async({args:e,options:t})=>{var n,o;const i=ru(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 zh(t.token,Fh(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 au("json"===e.output,()=>Su({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=Pe({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 Su({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 Su({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 lu(0)})),uu(Dh);export{Bd as g,Dh as p};
|
|
63
|
+
`;function sf(e,t,n,o){rm(e,async(e,n)=>{try{const o=await t(e,n);return"string"==typeof o?gm(o):{...o,content:o.content.map(e=>"text"===e.type?{...e,text:gm(e.text)}:e)}}catch(e){throw new Error(gm(e instanceof Error?e.message:String(e)))}},n,o)}const cf=function(e,t=$m,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=Am(d),a=await t(d);o={project:d,result:{...a,...a.message?{message:gm(a.message)}:{},...a.output?{output:gm(a.output)}:{},diagnostics:(null!=(m=a.diagnostics)?m:[]).map(e=>({...e,message:gm(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=Am(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:Om(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:Om(e.file,300)}:{},message:Om(e.message,_),messageTruncated:e.message.length>_})),..."error"!==u&&x+w.length<y.length?{nextOffset:x+w.length}:{},...g.message||h?{message:Om([g.message,h?"Could not scan project files for changes; this check is marked stale.":null].filter(Boolean).join(" "),500)}:{},...g.output?{output:Om(g.output,"error"===u?2e3:500),outputTruncated:g.output.length>("error"===u?2e3:500)}:{}}},{markStale(){i++}});return r}(()=>{var e;return null==(e=hf())?void 0:e.web_location}),lf=function(e,t=se(ne(),".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||ce(n)!==ce(t.project))throw new Error("The approved local project has changed.");return{root:O(n),grant:t}}function s(e,t,n){if("string"!=typeof t||!t||t.includes("\0")||ue(t)||me.isAbsolute(t)||fe.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=ce(e,t);if(!o.startsWith(e+de))throw new Error("Path escapes the selected local project.");let i=e;const r=le(e,o).split(de);for(let e=0;e<r.length;e++){if(i=se(i,r[e]),!$(i)){if(e!==r.length-1||!n)throw new Error("The file or its parent directory does not exist.");continue}const t=B(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{G(n,t,{flag:"wx",mode:384}),A(n,e)}finally{$(n)&&W(n)}}function l(){return $(t)?q(t).filter(e=>e.endsWith(".json")).reduce((e,n)=>e+C(se(t,n)).size,0):0}function p(e){if(!r){if($(t))for(const e of q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e))){const n=JSON.parse(M(se(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)>Nm)throw new Error("Checkpoint storage is full; no file was changed.");I(t,{recursive:!0,mode:448});const s=i(),c=se(t,`${s}.json`);return G(c,a,{flag:"wx",mode:384}),{id:s,file:c}}function u(e,t){if(e.byteLength>Cm)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(Rm(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 $(n)?M(n):null},o=n(t.path),i=null===t.before?null:Rm(Buffer.from(t.before,"base64"));if("rename"===t.operation){if(!t.newPath)return"conflicted";const e=n(t.newPath);if(null===o&&e&&Rm(e)===t.afterSha256)return"applied";if(null===e&&o&&Rm(o)===i)return"undone"}else if("delete"===t.operation){if(null===o)return"applied";if(o&&Rm(o)===i)return"undone"}else{if(o&&Rm(o)===t.afterSha256)return"applied";if(null===o&&null===t.before||o&&Rm(o)===i)return"undone"}return"conflicted"}catch{return"conflicted"}}return{list(e){const{root:n,grant:o}=a(e);if(!$(t))return{changes:[],total:0};const i=q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({...JSON.parse(M(se(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=O(n),i=s(o,t,!0);if(!$(i))return{path:t,exists:!1};const r=C(i).size;if(r>Cm)throw new Error("File exceeds the 1 MiB edit limit.");const a=wm(o,t,{maxBytes:Cm});return _m(a),{path:t,exists:!0,sha256:Rm(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>Cm||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=$(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?M(d):null;if(f&&u(f,e.expectedSha256),f&&Rm(f)===Rm(l))throw new Error("File already has this content; no edit was saved.");const h={project:i,path:le(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:Rm(l),createdAt:(new Date).toISOString(),operation:"write"},g=p(h);try{if(s(i,e.path,!0===e.create),!0===e.create){if($(d))throw new Error("The file was created since it was checked; check it again.")}else if(!$(d)||Rm(M(d))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");c(d,l)}catch(e){throw W(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=M(r);u(c,e.expectedSha256);const l=p({project:o,path:le(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),Rm(M(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");W(r)}catch(e){throw W(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($(c))throw new Error("Destination file already exists.");const l=M(r);u(l,e.expectedSha256);const d={project:o,path:le(o,r),newPath:le(o,c),chatId:i.chatId,sessionId:i.sessionId,turnId:i.turnId,before:l.toString("base64"),after:l.toString("base64"),afterSha256:Rm(l),createdAt:(new Date).toISOString(),operation:"rename"},m=p(d);try{if(s(o,e.path,!1),s(o,e.newPath,!0),$(c))throw new Error("Destination file already exists.");if(Rm(M(r))!==e.expectedSha256)throw new Error("The file changed since it was read; check it again.");A(r,c)}catch(e){throw W(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=se(t,`${e.checkpointId}.json`),u=JSON.parse(M(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($(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($(d)||Rm(M(e))!==u.afterSha256)throw new Error("File changed after the AI edit; Undo would overwrite later work.");A(e,d)}else{const e=M(d);if(Rm(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()-C(e).size+Buffer.byteLength(n)>Nm)throw new Error("Checkpoint storage is full; no file was changed.");c(e,Buffer.from(n))}(p,u)),null===u.before?W(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=se(t,`${e.checkpointId}.json`),p=JSON.parse(M(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(!$(u)||Rm(M(u))!==Rm(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),W(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(!$(u)||$(e)||Rm(M(u))!==Rm(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),A(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(Rm(e)!==p.afterSha256)throw new Error("Checkpoint content is damaged; Redo was refused.");if(null===p.before?$(u):!$(u)||Rm(M(u))!==Rm(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(!$(t))throw new Error("No checkpoints found for this turn.");const r=q(t).filter(e=>/^[a-f0-9-]{36}\.json$/.test(e)).map(e=>({checkpoint:JSON.parse(M(se(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=$(n)?M(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||Rm(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||Rm(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=hf())?void 0:e.web_location},void 0,()=>cf.markStale()),pf=function(e=se(ne(),".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")||ue(t.path)||me.isAbsolute(t.path)||fe.isAbsolute(t.path))throw new Error("A project-relative file path and chat are required.");const n=O(t.root),o=ce(n,t.path);if(xm(n,t.path,{allowMissing:!0}),!o.startsWith(n+de))throw new Error("File path escapes the project.");const i=le(n,o).split(de).join("/");return{project:n,target:o,path:i,file:se(e,Um(n),Um(t.chatId),`${Um(i)}.json`)}}function n(e){if(!$(e.target))return null;if(C(xm(e.project,e.target).path).size>Pm)return{unsupported:"File exceeds the 1 MiB observation limit."};const t=wm(e.project,e.target,{maxBytes:Pm}),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(Um),fileSha256:Um(t)}}function o(e){if(!$(e.file))return null;const t=JSON.parse(M(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};I(se(e,Um(t.project),Um(o)),{recursive:!0,mode:448});const a=`${t.file}.${i()}.tmp`;try{G(a,JSON.stringify(r),{flag:"wx",mode:384}),A(a,t.file)}finally{$(a)&&W(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)."}}}}(),uf=function(e,t=y){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()||ue(n.path)||n.path.includes("\0"))throw new Error("Use a nonempty project-relative path.");const r=O.native(i),a=ce(r,n.path),s=le(r,a);if(".."===s||s.startsWith(`..${de}`)||ue(s))throw new Error("File path is outside the selected project.");const c=O.native(a),l=le(r,c);if(".."===l||l.startsWith(`..${de}`)||ue(l))throw new Error("File path is outside the selected project.");const p=C(c);if(!p.isFile()&&!p.isDirectory())throw new Error("The selected path is not a file or directory.");if(Lm.has(re(c).toLowerCase()))throw new Error("Opening executable file types is not supported.");return await t(c),{opened:!0,project:n.project,path:le(r,c)||"."}}}(hf),df=function(e){const{getProject:t,getHome:n=ne,run:o=nf,commandsEnabled:r=(()=>!Wm()),onFailure:a,onCreated:s,onApprovedProject:c,now:l=Date.now,getProcessIdentity:p=Vm}=e,u=function(e=se(ne(),".needle","cli","ai-jobs"),t=Date.now){const n=t=>{if(!Jm.test(t))throw new Error("Invalid project job ID.");return se(e,`${t}.json`)};return{runtimeFile:t=>(n(t),se(e,`${t}.runtime.json`)),runtime(e){const t=this.runtimeFile(e);if(!$(t))return;const n=JSON.parse(M(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);I(e,{recursive:!0,mode:448});const r=se(e,`${t.jobId}.${i()}.tmp`);try{G(r,JSON.stringify(t),{flag:"wx",mode:384}),A(r,o)}finally{$(r)&&W(r)}},get(e){const o=n(e);if(!$(o))return;const i=JSON.parse(M(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;{W(o);const t=this.runtimeFile(e);$(t)&&W(t)}},list(){return $(e)?q(e).filter(e=>Jm.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);$(t)&&W(t);const o=this.runtimeFile(e);$(o)&&W(o)}}}(se(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=ef(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=gm(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={...ef(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||pe(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=gm(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=gm(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=gm(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.");G(`${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=hf())?void 0:e.web_location},onCreated:Hd,onApprovedProject:Hd,onFailure:e=>{var t;return Bp(`[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 mf(e){if(null==e||!e.editGrant)throw new Error("Local file edit approval is required.");if(Mm())throw new Error("AI file edits are disabled in local Needle CLI settings.");return e.editGrant}function ff(e={}){sf({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=Bd();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=l(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"},()=>{}),sf({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=Bd();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"},()=>{}),sf({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=Bd();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"},()=>{}),sf({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=hf();return t.content.push(null!=n&&n.web_location?{type:"text",text:w(n.web_location)}:{type:"text",text:"No selected web project is known."}),t},{source:"cli"},()=>{}),sf({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?pf.snapshot(i):pf.diff(i);return{content:[{type:"text",text:JSON.stringify(r)}]}},{source:"cli"},()=>{}),sf({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 uf(e))}]}),{source:"cli"},()=>{}),sf({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=l(n.resolved).mtime.toISOString(),r=km(n.root,n.resolved).text.split("\n");let a="";try{var o;const e=pf.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=of(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),p=r.slice(s-1,s-1+c),u=p.map((e,t)=>`${s+t}: ${e}`).join("\n");return{content:[{type:"text",text:`File: ${n.resolved} (${r.length} lines, modified: ${i}, showing ${s}-${s+p.length-1})`+a+"\n"+u}]}}catch(e){return{content:[{type:"text",text:`Error reading file: ${e instanceof Error?e.message:String(e)}`}]}}},{source:"cli"},()=>{}),sf({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=vf();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=>Em(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"},()=>{}),sf({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=hf();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:w(t.project_location),label:n}),e.project&&"web"!==e.project||!t.web_location||o.push({root:w(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=gf(e.path||".",t);if(o)try{var a;e.recursive||r.push(...u(o,{withFileTypes:!0}).filter(e=>e.isDirectory()&&!e.name.startsWith(".")&&"node_modules"!==e.name).map(e=>`${n}/${j(t,_(o,e.name))}`));const s=xf(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"},()=>{}),sf({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=hf();var n;if(null==t||!t.log_location)return Mp(`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=km(pe(t.log_location),ae(t.log_location),{maxBytes:67108864,allowPrivateKeys:!0}).text.split("\n");let o,i;if(e.filter){const t=of(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"},()=>{}),sf({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(!c(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=km(t,e).text;return JSON.parse(n)}if(n.endsWith(".glb")){const n=wm(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=wm(t,e,{maxBytes:67108864,range:{offset:20,length:o}}).toString("utf-8"),r=mm(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=yf(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 j,k;h.push(` - ${t.name||"(unnamed)"} (${null!=(j=null==(k=t.joints)?void 0:k.length)?j: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)}]});sf({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=af.replace("__PORT__",String(e)).replace("__HOST__",t),o=Buffer.from(n,"utf16le").toString("base64"),{stdout:i}=await rf("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 V(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 Y("/proc",{withFileTypes:!0});for(const e of o){if(!e.isDirectory()||!/^\d+$/.test(e.name))continue;let n;try{n=await Y(`/proc/${e.name}/fd`)}catch{continue}for(const o of n)try{const n=await K(`/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 rf("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 K(`/proc/${e}/cwd`):await async function(e){const{stdout:t}=await rf("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"},()=>{}),sf({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(Bd().entries.filter(e=>e.web_location).map(e=>({path:e.web_location,selected:e===hf(),editor:e.editor}))),{source:"cli"},()=>{}),sf({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:Jd(t.path).web_location}),{source:"cli"},()=>{}),sf({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:Km},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?df.getPlan(t.planId,n.chatId):df.plan(t,n.chatId))},{source:"cli"},()=>{}),sf({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(Wm())throw new Error("AI project commands are disabled in local Needle CLI settings.");return e(await df.start(t.planId,n.commandGrant))},{source:"cli"},()=>{}),sf({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(df.status(t.jobId,n.chatId))},{source:"cli"},()=>{}),sf({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 df.cancel(t.jobId,n.chatId))},{source:"cli"},()=>{})}(),sf(sp.schema,async e=>{const t=await sp.execute(e);return"error"in t?{content:[{type:"text",text:t.error}]}:{content:[{type:"text",text:t.content}]}},{source:"cli"},()=>{}),sf({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(lf.stat(e.path))}]}),{source:"cli"},()=>{}),sf({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(lf.write(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.delete(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.rename(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.undo(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.redo(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.undoTurn(e,mf(t)))}]}),{source:"cli"},()=>{}),sf({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(lf.list(mf(t)))}]}),{source:"cli"},()=>{}),sf({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 cf(e);return{content:[{type:"text",text:JSON.stringify(t)}],isError:"error"===t.status||"unavailable"===t.status}},{source:"cli"},()=>{}),null!=e&&e.logToolCount&&Mp(`[MCP] registered ${em.length} built-in tools: ${em.map(e=>e.name).join(", ")}`)}function hf(){return Gd()}function gf(e,t){const n=w(t,e),o=w(t),i=j(o,n);return k(i)||".."===i||i.startsWith(".."+S)?null:xm(o,n,{allowMissing:!0}).path}function vf(){const e=hf();if(!e)return[];const t=[];return e.project_location&&t.push(w(e.project_location)),e.web_location&&t.push(w(e.web_location)),t}function bf(e){const t=vf();for(const n of t){const t=gf(e,n);if(t&&c(t))return{resolved:t,root:n}}for(const n of t){const t=gf(e,n);if(t)return{resolved:t,root:n}}const n=w(e);for(const e of t)if(n.startsWith(e+S)||n===e)return{resolved:n,root:e};return null}function yf(e,t){if(0===t.length||null==e)return e;const[n,...o]=t;if("*"!==n)return yf(e[/^\d+$/.test(n)?Number(n):n],o);if(Array.isArray(e)){const t=e.map(e=>yf(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=yf(e[n],o);void 0!==i&&(t[n]=i)}return Object.keys(t).length>0?t:void 0}}function xf(e,t,n,o,i){if(i>10)return[];const r=[],a=u(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=_(e,c.name);if(!bm(j(t,a))&&!c.isSymbolicLink())if(xm(t,a),c.isDirectory())n&&r.push(...xf(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=>Ye(c.name,e,{nocase:!0})))continue;r.push(a)}}return r}process.once("exit",()=>df.dispose());const wf="cli-installation-id",_f=/^[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 kf(e){return{jsonrpc:"2.0",id:e,result:{protocolVersion:jf,capabilities:{tools:{listChanged:!0}},serverInfo:Sf}}}const Sf={name:"Needle Cloud MCP",version:"1.0.0"};function Ef(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 Tf(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}let $f=!1;const If=Me(),Af=new Map,Of=new Map;let Cf=0;function Nf(){const e=[];for(const[t,{connectedAt:n,userAgent:o}]of Of)e.push({id:t,connectedAt:n,userAgent:o});return e}function Rf(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?Af.get(a):void 0)?r:t.headers["user-agent"])?i:"",c=()=>{clearInterval(l),Of.delete(e)&&(console.log(`[MCP] SSE client disconnected (ID: ${e}): ${s}`),Mp(`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()}),Of.set(e,{id:e,client:n,connectedAt:Date.now(),userAgent:s,dispose:c}),console.log(`[MCP] SSE client connected (ID: ${e}) ${s}. Total clients: ${Of.size}`),Mp(`MCP SSE client connected (ID: ${e}) ${s}. Total clients: ${Of.size}`),!0}return!1}function Pf(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}async function Uf(e=se(ne(),".needle")){let t,n;try{t=await V(se(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 Lf(){const e=await Uf();try{const t=await fetch(`${Cu}/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 zf(e,t=process.argv[1]){await new Promise((n,o)=>{const i=Ke(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.`)})})}If.get("/mcp",async(e,t)=>{if(Rf(Cf++,e,t))return;const n=function(e){const t=[...em].sort((e,t)=>e.name.localeCompare(t.name)),n=t.map(e=>`\n <div class="tool">\n <span class="tool-name">${Tf(e.name)}</span>\n <span class="tool-desc">${Tf(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)}),If.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=Cf++,o=Ef(null==(a=e.body.params)?void 0:a.clientInfo);if(Rf(n,e,t,o?`${o.name}/${o.version}`:void 0)){$f=!0;const e=kf(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 kf(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{ff()}catch{}return{jsonrpc:"2.0",id:i,result:{tools:em}}}if("tools/call"===n){const e=null==o?void 0:o.name;try{ff()}catch{}try{return{jsonrpc:"2.0",id:i,result:await sm(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;$f=!0;const n=_e(),i=Ef(null==(s=e.body.params)?void 0:s.clientInfo);Af.set(n,i?`${i.name}/${i.version}`:void 0),t.setHeader("Mcp-Session-Id",n),console.log(`[MCP] New session created: ${n} for ${o}`),Mp(`MCP New session: ${n} for ${o}`)}if(null===l)return t.status(204).end();if(Mp(`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)}}),If.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 Ff=!1;function Df(e,t={}){Ff&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",method:e,params:t})+"\n")}var qf={__proto__:null,sendStdioNotification:Df,startStdio:function(){Ff=!0,console.log=console.info=console.debug=console.error.bind(console);const e=e=>{console.error(e),Mp(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(!Pf(s)||"2.0"!==s.jsonrpc||s.id!==t.id||!Pf(s.result)&&!Pf(s.error))throw new Error("Invalid response from local MCP server");if(Pf(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?j():y.abort(new Error("MCP notification stream connection timed out"))},e)},j=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 j=new TextDecoder;let k="";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),k+=j.decode(e,{stream:!0});o=/\r?\n\r?\n/.exec(k);){const e=k.slice(0,o.index);k=k.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);Pf(i)&&"2.0"===i.jsonrpc&&"notifications/tools/list_changed"===i.method&&m&&n("notifications/tools/list_changed")}if(k.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 Xe(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=Ef(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:`${Cu}/mcp`,ensureServer:t=>async function(e={}){const{signal:t,lockPath:n=se(ne(),".needle","mcp-server-start.lock"),probe:o=Lf,log:i=(e=>console.error(e)),launch:r=(()=>zf(i)),timeoutMs:a=2e4,pollMs:s=100}=e;if(null==t||t.throwIfAborted(),await o())return;await Z(pe(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 X(n,"wx",384)}catch(e){if(!(e instanceof Error&&"code"in e&&"EEXIST"===e.code))throw e;try{const e=await Q(n);Date.now()-e.mtimeMs>12e4&&(i("Removing an expired MCP server startup lock."),await ee(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 Xe(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 ee(n))}}({signal:t,log:e}),notify:Df,log:e,getToken:()=>async function(e){const t=await Uf(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=De({input:process.stdin,terminal:!1}),o=e=>{Ff&&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(!Pf(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&&!Pf(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(kf(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",()=>{Ff=!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 Bf=null;function Mf(){Bf&&clearTimeout(Bf),Bf=setTimeout(()=>{!function(e,t={}){if(0===Of.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 Of)try{t.write(n)}catch(n){console.error(`[MCP] Error sending notification to client (${e}):`,n),o(),t.destroy()}}(),Df("notifications/tools/list_changed"),rh(),Bf=null},10)}const Wf=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(!Yf||Yf.readyState!==We.OPEN)throw new Error("Needle Cloud disconnected.");Yf.send(JSON.stringify(e))},register:(e,t)=>rm(e,t,{source:"cloud"},Mf),clear:()=>om("cloud",Mf),onError:e=>Mp(`[Cloud MCP] ${e}`)}),Gf=2e3,Hf=6e4,Jf=25e3,Vf=1e4,Kf=i();let Yf=null,Zf=null,Xf=null,Qf=null,eh=Gf,th=!1,nh=!1;function oh(){Yf||(qm()?Mp("Needle Cloud connection: skipped (remote_ai_tools disabled in settings)"):(th=!1,Zf&&(clearTimeout(Zf),Zf=null),eh=Gf,ah()))}function ih(e){Wf.disconnect(),th=!0,sh(),Zf&&(clearTimeout(Zf),Zf=null),Yf?(Mp(`Needle Cloud connection: closing (reason: ${null!=e?e:"shutdown"})`),Yf.close(1e3,null!=e?e:"shutdown"),Yf=null):e&&Mp(`Needle Cloud connection: disconnect requested (reason: ${e}) — no active connection`)}function rh(){if(!Yf||Yf.readyState!==We.OPEN)return;try{ff()}catch(e){Mp(`Needle Cloud connection: registerServerTools failed: ${e}`)}const e=em.filter(e=>!Wf.isCloudTool(e.name)),t=e.map(e=>e.name);var n;Mp(`Needle Cloud connection: sending ${t.length} tools: ${t.join(", ")}`),Yf.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 ah(){let e,t,n=await wd();if(n||(n=function(){const e=ud("accessToken");if(s.existsSync(e)){const t=s.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&&Mp("Needle Cloud connection: using cached token (refresh failed)")),!n)return nh||(Mp("Needle Cloud connection: skipped (not logged in)"),nh=!0),void ch(!0);nh=!1;try{e=function(e=Fm()){I(e,{recursive:!0,mode:448});const t=se(e,wf);try{G(t,i(),{flag:"wx",mode:384})}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"EEXIST"!==e.code)throw e}const n=M(t,"utf8").trim();if(!_f.test(n))throw new Error("Invalid local CLI installation ID.");return n}()}catch(e){return Mp(`Needle Cloud connection: could not read local CLI installation identity: ${e instanceof Error?e.message:String(e)}`),void ch(!0)}try{t=await async function(e,t={getUser:_d,getDefaultOrg:jd,authHeaders:$d}){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 Mp(`Needle Cloud connection: team authentication failed: ${e instanceof Error?e.message:String(e)}`),void ch()}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(Kf)+"&installation="+encodeURIComponent(e);Mp("Needle Cloud connection: connecting...");const r=`needle-cloud/${Zd()} Node/${process.versions.node}`;Yf=new We(o,{headers:{"User-Agent":r,Origin:"cli://needle-cloud"}}),Yf.on("open",()=>{eh=Gf,Mp("Needle Cloud connection: established"),lh(),rh(),sh(),Xf=setInterval(()=>{Yf&&Yf.readyState===We.OPEN&&(Yf.ping(),Qf=setTimeout(()=>{Mp("Needle Cloud connection: pong timeout, terminating"),Yf&&Yf.terminate()},Vf))},Jf),Wf.connect()}),Yf.on("pong",()=>{Qf&&(clearTimeout(Qf),Qf=null)}),Yf.on("message",e=>{try{const n=JSON.parse(e.toString());if(Wf.receive(n))return;var t;"execute_tool"===n.type&&n.requestId&&n.toolName&&async function(e,t,n,o,i,r){Mp(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(Wf.isCloudTool(t))throw new Error("Cloud tools cannot be executed as local tools.");"local_project_action"===t&&lh();const l=await sm(t,n,{chatId:o,editGrant:i,commandGrant:r});"local_project_select"!==t&&"local_project_start"!==t&&"local_project_status"!==t||lh(),Mp(`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}]`),Yf&&Yf.readyState===We.OPEN&&Yf.send(JSON.stringify({type:"tool_result",requestId:e,result:l}))}catch(n){const o=n instanceof Error?n.message:String(n);Mp(`Cloud tool error: ${t} → ${o} in ${Date.now()-a}ms [${e}]`),Yf&&Yf.readyState===We.OPEN&&Yf.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{}}),Yf.on("close",(e,t)=>{const n=(null==t?void 0:t.toString())||"";Mp(`Needle Cloud connection: closed (code=${e}${n?" "+n:""})`),sh(),Wf.disconnect(),Yf=null,th||ch()}),Yf.on("error",e=>{Mp(`Needle Cloud connection: error - ${e.message||"connection refused"} (is https://cloud.needle.tools/api reachable?)`)})}function sh(){Xf&&(clearInterval(Xf),Xf=null),Qf&&(clearTimeout(Qf),Qf=null)}function ch(e=!1){th||Zf||(e||Mp(`Needle Cloud connection: reconnecting in ${eh/1e3}s`),Zf=setTimeout(()=>{Zf=null,ah()},eh),eh=Math.min(2*eh,Hf))}function lh(){Yf&&Yf.readyState===We.OPEN&&Yf.send(JSON.stringify(function(){var e,t,n;const o=Gd();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?ce(o.web_location):null,cli_version:Zd()}}()))}const ph=e=>{const t=Me();return t.use("/:action",async(t,n,o)=>{const{action:i}=t.params,r=kd({navigate:e=>{n.redirect(e)}});switch(i){case"sign-in":e.invalid_login=!1,e.invalid_login_type=null,e.error=void 0,Mp("Sign in..."),await r.clearAllTokens(),hd();try{await r.signIn(`${Cu}/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 Mp(o),console.error(o),n.status(502).send(o)}break;case"sign-out":{var a,s;const t=await _d(),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;Mp(`Sign out... (${n})`),n&&o&&await async function(e){return!e.accessToken||import("node-machine-id").then(async t=>{const n=await zd();return Rd=n,await fetch("https://cloud.needle.tools/api"+ht.account.post_machine,{method:"POST",headers:{Authorization:"Bearer "+e.accessToken,"Content-Type":"application/json"},body:JSON.stringify({action:"logout",machine_id:n,machine_name:Fd()})}).catch(e=>{Mp(`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),Mp(`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(td()),hd();break}case"auth-callback":if(t.url){const o=await r.handleSignInCallback(`${Cu}${t.originalUrl}`).catch(e=>({error:e}));if(hd(),o&&"error"in o){Mp(`Error during sign in: ${o.error}`);const e=o.error instanceof Error?o.error.message:String(o.error);n.redirect(Cu+"?cancelled&message="+encodeURIComponent(e))}else{var c,l,p,u;const t=await _d();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=[...Pd(t)];const o=await Dd(t,{signout:!0});if(!o)return e.invalid_login=!0,e.invalid_login_type="too-many-logins",n.redirect(td("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(td("error"));hd()}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)}`),Mp(`User logged in: ${(null==t||null==(p=t.userInfo)?void 0:p.sub)||(null==t||null==(u=t.claims)?void 0:u.sub)}`),oh(),n.redirect(Cu)}}break;default:o()}}),t};function uh(e,t,n){return!!n||e===kp||"string"==typeof t&&t===e}function dh(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!==c(t))try{const e=mh(t);if(e)return e}catch(e){}}function mh(e){const t=_(e,".git");if(c(t)){const e=function(e){const t=g(e);if(t.isDirectory())return _(e,"config");if(t.isFile()){const t=p(e,"utf-8").trim().match(/^gitdir:\s*(.+)$/);if(t){let n=t[1].trim();k(n)||(n=w(E(e),n));const o=_(n,"config");if(c(o))return o;const i=_(n,"commondir");if(c(i)){let e=p(i,"utf-8").trim();return k(e)||(e=w(n,e)),_(e,"config")}}}return null}(t);if(e&&c(e)){const t=function(e){const t=p(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=_(e,".plastic");if(c(n)){const e=_(n,"replicas.db");if(c(e)){const t=p(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=_(e,"..");return o===e?null:mh(o)}function fh(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 hh=new Set(["https://cloud.needle.tools","https://needle.tools","https://engine.needle.tools","https://docs.needle.tools","chrome-extension://kjcepmifiddcepiocokclhibpkgcdomk","chrome-extension://jonplpbnhmanoekkgcepnedhghflblmo"]),gh=new Set(["localhost","127.0.0.1","[::1]","::1"]);function vh(e){if("string"!=typeof e||0===e.length)return!1;if(hh.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!!gh.has(n)||"::1"===n}const bh="[MCP]",yh=new Array;function xh(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function wh(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>0}async function _h(){try{return JSON.parse(await V(se(ne(),".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 jh(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 Sh={__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(`${Cu}/api/info`,{signal:AbortSignal.timeout(3e3)})}catch(e){if(e instanceof Error&&xh(e.cause)&&"ECONNREFUSED"===e.cause.code)return{running:!1,url:Cu};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(!xh(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&&!wh(a.pid))throw new Error("Invalid local server PID.");if(wh(a.pid))return{running:!0,url:Cu,version:a.version,pid:a.pid,pidSource:"server"};const s=await(null!=(n=e.readServerRecord)?n:_h)();return xh(s)&&s.port===Ou&&wh(s.pid)&&(null!=(o=e.isProcessAlive)?o:jh)(s.pid)?{running:!0,url:Cu,version:a.version,pid:s.pid,pidSource:"record"}:{running:!0,url:Cu,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 Eh="2026-10-26T16:04:39.957Z";var Th={__proto__:null,BUILD_TIME:Eh};const{json:$h}=Qe;function Ih(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 Ah(t={restart:!1}){const n=!0===t.restart,o=await e(Cu).catch(e=>({ok:!1})),r="/sign-in",a="/api/authenticated",s="/api/projects",l="/api/content",p={baseUrl:Cu,port:Ou,isHost:!1,auth_endpoints:{"sign-in":`${Cu}${r}`,"sign-out":`${Cu}/sign-out`,"is-authenticated":`${Cu}${a}`}};let u=o.ok;if(u){var d;const g=await e(`${Cu}/api/info`).catch(()=>null);if(null!=g&&g.ok){const b=await g.json().catch(()=>null);if(null!=b&&b.api_endpoint&&"https://cloud.needle.tools/api"!==b.api_endpoint){if(!uh(b.api_endpoint,"https://cloud.needle.tools/api",n))return Mp(`Keeping CLI server for ${b.api_endpoint}; https://cloud.needle.tools/api did not request an explicit restart.`),p;Mp(`Running server uses different API endpoint (${b.api_endpoint} vs https://cloud.needle.tools/api), restarting...`),t||(t={}),t.restart=!0}}if(!0===(null==(d=t)?void 0:d.restart)){Mp("Restarting auth server...");const y=`${Cu}/restart`;t.ora&&(t.ora.text="Sending restart request to server");const x=new AbortController;setTimeout(()=>x.abort(),1e4);let w={};try{const k=_($e(),".needle","local-server-token"),S=JSON.parse((await import("fs")).readFileSync(k,"utf-8"));S.token&&(w={Authorization:`Bearer ${S.token}`})}catch{}const j=await e(y,{method:"post",signal:x.signal,headers:{...w,"x-needle-api-endpoint":"https://cloud.needle.tools/api",...n?{"x-needle-explicit-restart":"true"}:{}}}).catch(e=>({ok:!1,status:400,error:e}));if(j.ok)return await kl(300),Ah({restart:!1});409!==j.status&&console.error("Failed to restart server",j.status),Mp(`Failed to restart server: ${j.status}`)}}if(!u){process.title="Needle CLI server";const E=await import("express").catch(e=>{throw console.error("Error starting the auth server (express not found)",e),Mp("Error starting the auth server"),new Error("Failed to load express module")});if(!E)throw Mp("Error loading auth server module"),new Error("Failed to load express module");Mp(`Starting Needle CLI server ${Zd()} (built ${Eh})... (Using api at https://cloud.needle.tools/api)`,{emptyLineBefore:!0}),p.isHost=!0;let T=null;const A={invalid_login:!1,invalid_login_type:null,user_email:null,logged_in_machine_names:[]};let O=E.default();const C=_($e(),".needle"),N=function(e,t){var n;const o=se(e,"local-server-token"),r=null!=(n=function(e){if(!$(e))return null;try{const t=M(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();I(e,{recursive:!0});const a=JSON.stringify({token:r,pid:process.pid,port:t},null,2);if(G(o,a,{encoding:"utf-8",mode:384}),"win32"===process.platform)try{const e=process.env.USERNAME||process.env.USER||"";e&&He("icacls",[o,"/inheritance:r","/grant:r",`${e}:(F)`],{stdio:"ignore",timeout:5e3})}catch{}return r}(C,Ou);Mp(`Local token written to ${_(C,"local-server-token")}`);const R=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=>Mp(`Denied: ${e}`),5e3);O.use((h={onDenied:R},(e,t,n)=>{var o;return fh(e.headers.host)?n():(null==h||null==h.onDenied||h.onDenied(`host|${null!=(o=e.headers.host)?o:"missing"}`,"HTTP Host is not a loopback authority"),t.status(403).send("Forbidden: host not allowed"))})),O.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(vh(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:R})),O.use($h({limit:"10mb"}));const P=new Set(["/","/sign-in","/sign-out","/auth-callback","/api/info","/api/authenticated","/api/public_key","/mcp","/register"]),U="needle_local";O.use((e,t,n)=>{var o,i,r;if("OPTIONS"===e.method)return n();if(P.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]===N)return n()}if((null==(i=e.query)?void 0:i.token)===N)return n();const s=((null==(r=e.headers)?void 0:r.cookie)||"").split(";").map(e=>e.trim()).find(e=>e.startsWith(U+"="));if(s&&s.split("=")[1]===N)return n();try{var c,l;const t=null!=(c=null==(l=e.headers)?void 0:l["user-agent"])?c:"unknown";R(`token|${t}|${e.path}`,`path=${e.path} ua="${t}" — no valid token or cookie`)}catch{}return t.status(401).send("Unauthorized: token required")}),O.use(ph(A)),t.ora?(t.ora.start("Starting MCP server..."),t.ora.succeed(`MCP server available at ${Cu}/mcp`)):console.log(`\nMCP server available at ${Cu}/mcp .`),O.use(If);const L="\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>",z=`<div class="main_panel"><img class="logo" src="https://cdn.needle.tools/static/branding/logo_needle.png" alt="Needle Logo" title="Needle Logo (${Zd()})"/>`,F="</div>";let D="";O.get("/",Id(),async(e,t)=>{var n,o;if(null!=(n=e.user)&&n.isAuthenticated?t.cookie(U,N,{httpOnly:!0,sameSite:"strict",path:"/"}):t.clearCookie(U,{path:"/"}),t.set({"Content-Type":"text/html; charset=utf-8"}),t.write(L),null!=e.query.cancelled)return t.end("Login cancelled. You can close this window now."),void Mp("Login cancelled by user");if(null!=e.query["too-many-logins"]&&A.logged_in_machine_names.length){var i;const e=Sp();let n="<div>";return n+="<strong>You have reached the maximum number of allowed device logins!</strong><br/><br/>",n+=(null==(i=A.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="${r}">sign-in on this machine</a>.<br/><br/>`,n+="</div>",t.status(406),t.end(z+n+F),void Mp(`Login failed: Too many logins from different machines: [${A.logged_in_machine_names.join(", ")}]`)}if(null!=e.query.error)return t.status(500),void t.end(`${z}\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="${r}">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://${Dp()}" target="_blank">${Dp()}</a></span>\n </div>\n ${F}`);if(null!=(o=e.user)&&o.isAuthenticated){var a;if(!await Ld(e.user)){if(A.invalid_login=!0,A.logged_in_machine_names=[...Pd(e.user)],od(),Mp("Cleared stored auth data"),"client"in e.user){const t=e.user;await t.client.clearAccessToken(),await t.client.clearAllTokens(),Mp("Cleared all tokens")}return t.end(`${z}<div>You have been logged out from this machine. You can close this window now or try to <a href="${r}">sign in</a> again</div>${F}`)}A.invalid_login=!1,t.end(`${z}\n <div>\n Hi ${Td(e.user)} — you logged in successfully. You can close this window now.\n </div>\n ${F}`);const n=`Logged in successfully as ${Td(e.user)} (${null==(a=e.user.userInfo)?void 0:a.sub})`;return void(D!==n&&(D=n,Mp(D)))}let s=`<span><a href="${r}">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(z+s+F),t.end()}),O.post("/restart",(e,n)=>{var o;if(!uh("https://cloud.needle.tools/api",e.headers["x-needle-api-endpoint"],"true"===e.headers["x-needle-explicit-restart"]))return Mp("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.");t.ora&&(t.ora.text="Received restart event. This instance will close"),null==(o=T)||o.close(e=>{e&&console.error(e)}),setTimeout(()=>{process.exit(0)},100),n.status(200).end("Server is restarting"),Mp("Server is restarting\n")}),O.get("/api/logs",async(e,t)=>{const n=Dp();c(n)?v(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${Zd()} (built ${Eh}) Log File (newest first) ---\n${n}\n\n`;r+=i,t.status(200).end(r)}):t.status(404).end("Log file not found")}),O.get("/api/info",(e,t)=>{t.json(kh("https://cloud.needle.tools/api",Zd()))}),O.get(a,Id(),async(e,t)=>{var n;if(!0===A.invalid_login){const e=Oh(A);return t.status(e.status).json(e)}A.invalid_login=!1,t.status(null!=(n=e.user)&&n.isAuthenticated?200:400).send()}),O.get("/api/user",Id(),async(e,t)=>{var n;const o=e.user;if(null==o||!o.isAuthenticated){if(!0===A.invalid_login){const e=Oh(A);return t.status(e.status).json(e)}return t.status(401).json({error:"Not authenticated"})}if(A.invalid_login=!1,!await Ld(o))return od(),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:Td(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)}),O.get("/api/license",Id(),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 _d();if(!e||!e.isAuthenticated)return n.status(401).json({error:"Not authenticated",code:"not_authenticated"});if(!await Ld(e))return od(),n.status(403).json({error:"Invalid login"});c=await $d(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=gt(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${ht.account.get_licenses}`,{method:"GET",headers:u}).catch(e=>{const t=Ih(e);return console.error("Failed to fetch licenses:",t),Mp(`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})}),O.get("/api/deployments",Id(),async(e,t)=>{var n;const o=await _d();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 $d(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 Tu({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=`${Ep()}/${e.id}`;const s={...a};return t.json(s)}),O.get(l,Id(),async(e,t)=>{var n,o,i,r,a,s,c,l;const p=await _d();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 $d(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 np({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)}),O.get(l+"/:identifier",Id(),async(e,t)=>{var n,o;const i=await _d();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 $d(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 op({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)}),O.get(s,Id(),async(t,n)=>{const o=await _d();if(!o||!o.isAuthenticated)return n.status(401).json({error:"Not authenticated"});const i=`https://cloud.needle.tools/api${ht.local_projects.get.user}`,r=await e(i,{method:"GET",headers:{Authorization:`Bearer ${o.accessToken}`}}).catch(e=>(console.error("Failed to fetch projects:",Ih(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)}),O.get(s+"/:id",Id(),async(t,n)=>{var o;const i=await _d();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 $d(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=gt(a),c=`https://cloud.needle.tools/api${ht.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:",Ih(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"})}),O.post("/api/projects",Id(),async(t,n)=>{const o=await _d();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 zd(),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${ht.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:",Ih(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"})}),O.get("/api/public_key",Id(),async(t,n)=>{var o,i;const r=await _d();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 $d(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 zd()},l=await e(`https://cloud.needle.tools/api${ht.account.public_key}`,{method:"POST",headers:{...gt(s),"Content-Type":"application/json"},body:JSON.stringify(c)}).catch(e=>(console.error("Failed to fetch public key:",Ih(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})}),O.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=dh(o);return i?t.json({project_id:i}):t.status(404).json({error:"Project ID not found"})}),O.post("/api/project/info",Id(),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=Vd();let s=Kd();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&&Mp(`Active project changed: ${l||"(none)"} → ${u}`);try{qd=s;const e=JSON.stringify(s);f(a,e,"utf-8")}catch(e){console.error("Failed to save project info:",e)}}(e)}catch(e){Mp("Error saving project info: "+e)}})("string"==typeof e.body?JSON.parse(e.body):e.body),t.send("OK")});let q=null;const B=new Promise(e=>q=e);let W=!1;if(T=O.listen(Ou,()=>{null==q||q()}),T.on("error",e=>{if("EADDRINUSE"===(null==e?void 0:e.code))return Mp(`License server port ${Ou} already in use — a server is already running; not starting a second one.`),W=!0,p.isHost=!1,void(null==q||q());console.error("[needle] License server failed to start:",(null==e?void 0:e.message)||e),Mp(`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()}})}(T,Mp),T.on("close",m),process.on("exit",m),process.on("SIGINT",()=>{m(),process.exit(0)}),await B.catch(e=>{console.error(e),Mp(`Error starting the auth server (promise failed): ${e.message}`)}),W)return p;function m(){Mp("Cleaning up auth server...")}const H=function(e,t){const n=new Ge({server:e,path:"/mcp/ws",verifyClient:({req:e},t)=>{var n;if(!fh(e.headers.host))return Mp(`${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&&!vh(o))return Mp(`${bh} rejected WS upgrade: disallowed origin ${o}`),void t(!1,403,"Forbidden: origin not allowed");t(!0)}});Mp("MCP websocket server created.");let o=0,i=new Map;return n.on("connection",e=>{const t=++o;yh.push(e),console.log(`${bh} client connected (#${t})`),Mp(`${bh} client connected (#${t})`),e.on("close",()=>{const n=yh.indexOf(e);-1!==n&&yh.splice(n,1);const o=i.get(t);if(o){for(const e of o)im(e,Mf);i.delete(t)}console.log(`${bh} client disconnected (#${t})`),Mp(`${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}`),Mp(`Unknown MCP websocket command received: ${a.command}`);break;case"get_connected_clients":!function(t,n){const o={clients:[...Nf()],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&&om(r,Mf);const s=r||"unknown";console.log(`${bh} ${s} registered ${o.length} tool${1===o.length?"":"s"}`),Mp(`${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)rm(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},Mf),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}(T);ff({logToolCount:!0}),oh();const J=Gm(C,()=>{qm()?(Mp("Settings changed: remote_ai_tools disabled — closing cloud connection"),ih("remote_ai_tools setting disabled")):(Mp("Settings changed: remote_ai_tools enabled — opening cloud connection"),oh())});Od(O,N,()=>{Mp("Authenticated stop requested; shutting down the local Needle server."),T&&Cd(T,H,()=>{J(),ih("stop requested")})}),process.on("exit",()=>{J(),ih("process exit")})}var h;return p}function Oh(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 ${Sp()}. You're currently logged in on: ${e.logged_in_machine_names.join(", ")}`:"An unknown error occured.",{status:403,error:t}}async function Ch(e={headless:!1,silent:!1,clearAuthData:!1}){return!0===e.clearAuthData&&await od(),Rh("sign-in",{...e})}function Nh(e={}){return Rh("sign-out",{...e})}function Rh(t,n){return new Promise(async(o,i)=>{let r=!1;if("sign-in"==t){const e=await _d();if(null!=e&&e.isAuthenticated&&e.accessToken)return await Dd(e)?(r=!0,n.ora&&(n.ora.text=`Authorized as ${Td(e)}`),"gotoAccountPage"in n&&!0===n.gotoAccountPage&&(n.ora&&(n.ora.text="Opening account page in the browser"),Tp(Sp()),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,od();const t=await Ah(),n=await e(t.auth_endpoints["sign-out"],{follow:2});return o(n.ok)}const a=await Ah();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(()=>Tp(e),300),n.ora&&(n.ora.text=`Please authenticate in the browser: ${e}`),setTimeout(l,2e3);break;case"sign-out":od(),Tp(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 _d();return e&&!await Dd(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;T().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,od(),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:Bp,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 Ph=process.argv.includes("--silent"),Uh=JSON.parse(p(new URL("../package.json",import.meta.url),"utf-8")),Lh="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 zh(e,t=null,n=!0){let o,i=null==e?void 0:e.toString();var r;if(i||(ze.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=T({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 _d();return null==e?void 0:e.isAuthenticated}()&&(e=Ph?void 0:T("No access token found. Please sign in to authenticate...").start()),Mp("No access token provided, attempting login. Org: "+t);const r=Ch({headless:!n,ora:e,timeout:12e4}),d=await r;if(d&&!await Ld(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 Nh({headless:!0}),process.exit(1)}else e&&(Mp("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 (${Td(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)),Mp("Getting access token for org "+o+", "+i.substring(0,8)+"...")}else{var u;Mp("Getting access token for user "+(null==(u=d.userInfo)?void 0:u.sub)),i=null==d?void 0:d.accessToken}}}if(!i)throw Mp("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 Fh(e){return null!=e.org&&console.warn("Warning: --org is deprecated. Use --team instead."),e.team||e.org}const Dh=mt.program;async function qh(){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))}Dh.version(Uh.version).description("Command-line interface (CLI) for Needle Cloud"),Dh.command("version","Print the CLI version").configure({visible:!1}).action(()=>{Ph||console.log(`☁ Needle CLI — ${Uh.version}, Node ${process.version}`)}),Dh.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:Dh.BOOLEAN,default:!1}).option("--integration <integration>","Hint for the process which integration triggered this command",{required:!1,validator:Dh.STRING}).action(async({options:e})=>{const t=e.integration,n=Ph?void 0:T("Starting Needle License server "+(t?`(from ${t})`:"")).start();Ah({ora:n,restart:e.restart}).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${Zd()}, built ${function(e){if("string"!=typeof Eh||0===Eh.length)return"unknown";const t=new Date(Eh);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))})}),Dh.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 Nd}),t=await e();Ph||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)}}),Dh.command("settings","Show current Needle CLI settings").action(async()=>{const{readSettings:e,KNOWN_SETTINGS:t}=await Promise.resolve().then(function(){return Hm}),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("")}),Dh.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:Dh.BOOLEAN}).action(nu("settings remote-ai-tools",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled,i=n();o?(t(i,"remote_ai_tools",null),console.log("Remote AI tools enabled (default)."),Mp("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."),Mp("Settings: remote_ai_tools set to disabled via CLI command"))})),Dh.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:Dh.BOOLEAN}).action(nu("settings local-file-edits",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled;t(n(),"local_file_edits",o?null:"disabled"),console.log(`Local AI file edits ${o?"enabled":"disabled"}.`)})),Dh.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:Dh.BOOLEAN}).action(nu("settings local-project-commands",async({args:e})=>{const{writeSetting:t,defaultSettingsDir:n}=await Promise.resolve().then(function(){return Hm}),o=e.enabled;t(n(),"local_project_commands",o?null:"disabled"),console.log(`Local AI project commands ${o?"enabled":"disabled"}.`)})),Dh.command("status","Show the local Needle server status and process ID").action(nu("status",async()=>{const{getLocalServerStatus:e,formatLocalServerStatus:t}=await Promise.resolve().then(function(){return Sh});console.log(t(await e()))})),Dh.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(nu("mcp",async()=>{const{startStdio:e}=await Promise.resolve().then(function(){return qf});e()})),Dh.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=dh(e.paths);t?console.log(`Found project ID: "${t}"`):console.log("No project ID found.")}),Dh.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:Dh.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:Dh.BOOLEAN,default:!1}).action(nu("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 Xu}),{tryGetFreshAccessTokenForResource:p}=await Promise.resolve().then(function(){return Ed}),{findActiveEditorLog:u}=await import("./cli.send-logs.discovery-29fa4e4a.js"),{getLogFilePath:d,getPrevLogsFilePath:m,getPipelineLogFilePath:f}=await Promise.resolve().then(function(){return Wp}),{homedir:h,platform:g}=await import("os"),{existsSync:v}=await import("fs"),{BUILD_TIME:b}=await Promise.resolve().then(function(){return Th}),{getNodeVersion:y,getNpmVersion:x,getArch:w,getOsRelease:_,getCpuCount:j,getTotalMemoryMb:k,getTzOffsetMinutes:S,isCi:E,isTty:$}=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",A=e.note,O=null!=(i=null!=(r=null==(a=e.dryRun)||null==a.valueOf?void 0:a.valueOf())?r:e.dryRun)&&i,C=d(),N=m(),R=f(),P={getAccessToken:()=>p(l),fetch:globalThis.fetch,paths:{cliLogPath:v(C)?C:null,prevLogPath:v(N)?N:null,pipelineLogPath:v(R)?R:null,homeDir:h()},meta:{cli_version:Zd(),build_time:b,os:g(),os_release:_(),arch:w(),node_version:y(),npm_version:null!=(s=x())?s:"unknown",cpu_count:j(),total_memory_mb:k(),tz_offset_minutes:S(),is_ci:E(),is_tty:$()},findActiveEditorLog:u,stdout:process.stdout,stderr:process.stderr},U=O?"Building payload (dry-run)":"Uploading logs",L=Ph?void 0:T(U).start();P.recoverAuth=async()=>{null==L||L.stop();try{await qh();const e=await Ch({clearAuthData:!0,silent:Ph,ora:void 0});if(null==e||!e.isAuthenticated)return null}catch(e){return Mp(`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:A,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)})),Dh.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:Dh.BOOLEAN,default:!1}).option("--clear <clear>","Refresh the access token",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(async({options:e})=>{const t=ru(e),n=!0===e.nonInteractive||!0===e.headless;n||await qh();const o=!0===e.clear,i=Ph?void 0:T("Login").start();await Ch({headless:n,silent:Ph,clearAuthData:o,ora:i}).then(async e=>{"json"===t&&cu({authenticated:!0===(null==e?void 0:e.isAuthenticated)}),null!=e&&e.isAuthenticated?null==i||i.succeed("Successfully logged in as "+Td(e)):0==n?null!=e&&e.claims||null!=e&&e.userInfo?null==i||i.warn(`You (${Td(e)}) are not authenticated...`):null==i||i.fail("Login failed"):Ph||null==i||i.warn("Not logged in"),await lu(null!=e&&e.isAuthenticated?0:1)})})),Dh.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:Dh.BOOLEAN,default:!1}).action(su(async({options:e})=>{const t=ru(e),n=!0===e.nonInteractive||!0===e.headless;n||await qh(),await Nh({headless:n}).then(async e=>{"json"===t&&cu({success:e}),e?T("Logged out").succeed():T("Logout failed").fail(),await lu(e?0:1)})})),Dh.command("me","Prints your user information").help("Prints basic informaton about the logged in Needle Cloud account (your account)").action(su(async({options:e})=>{const t=ru(e),n=Ph?void 0:T("Query user data").start(),o=await _d(),i=Boolean((null==o?void 0:o.isAuthenticated)&&await Ld(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 ${Td(o)}`),console.log(`- Name: ${Td(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?cu({authenticated:!0,id:e.sub,name:Td(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}))}):(cu({authenticated:!1}),process.exitCode=1)}})),Dh.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:Dh.STRING}).option("--org <org>","Legacy alias for --team",{validator:Dh.STRING,hidden:!0}).action(nu("get-pro",async({options:e})=>{var t;let n=(null==(t=Fh(e))?void 0:t.toString())||null;const o=T().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}`),Tp(r)}));const Bh={account:{url:Sp}},Mh=`"${Object.keys(Bh).join('", "')}"`;Dh.command("open",`Open a page in the default browser. Options are: ${Mh}`).argument("<page>",`The page to open. Options are: ${Mh}`,{validator:Dh.STRING}).configure({strictOptions:!1,strictArgsCount:!1,visible:!1}).help("").action(async({args:e,logger:t})=>{const n=e.page.toString(),o=Bh[n];o?"url"in o?Tp(o.url()):t.error(`Unknown argument: ${n}`):t.error(`Unknown argument: ${n}. Options are: ${Mh}`)}),Dh.command("list-deployments","Get a list of deployed websites").configure({visible:!1}).help("").option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--limit <limit>","Limit the number of deployments to show (min: 0, max: 100)",{validator:Dh.NUMBER,default:10}).option("--offset <offset>","The offset for deployments (default: 0, min: 0)",{validator:Dh.NUMBER,default:0}).option("--format <format>","Legacy output option: cli or json",{validator:Dh.STRING,hidden:!0}).option("--name","Filter by one or multiple deployment names (separated by ;)",{validator:Dh.STRING}).action(su(async({options:e,logger:t})=>{var n,o,i,r;const a=ru(e,{legacyFormat:!0}),{accessToken:s,org_id:c}=await zh(e.token,Fh(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=T("Query deployments").start(),f=await Tu({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 cu(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")})),Dh.command("list","List content items (3d assets, deployments, materials, etc.)").alias("list-content").help('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>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--include-projects","Include saved web projects (default: uploaded content only)",{validator:Dh.BOOLEAN,default:!1}).option("--trash","List deleted items instead of active content",{validator:Dh.BOOLEAN,default:!1}).option("--interactive","Override automatic terminal browsing: true or false",{validator:Dh.BOOLEAN}).option("--type <type>","Filter by content type (e.g. material, 3d-asset, deployment, editor-project)",{required:!1,validator:Dh.STRING}).option("--format <format>","Filter by output format (e.g. glb, textures)",{required:!1,validator:Dh.STRING}).option("--search <search>","Search by name, title or description",{required:!1,validator:Dh.STRING}).option("--limit <limit>","Max number of items to show (default: 20, max: 100)",{validator:Dh.NUMBER,default:20}).option("--offset <offset>","Offset for pagination (default: 0)",{validator:Dh.NUMBER,default:0}).option("--output <output>","Output style: cli (default), json",{validator:Dh.STRING,default:"cli"}).action(su(async({options:e,logger:t})=>{var n,o,i,r,a,s;const c=ru(e),l=function(e,t={input:!0===process.stdin.isTTY,output:!0===process.stdout.isTTY}){return!0===e.interactive?(hu(e,t),!0):!(!1===e.interactive||!0===e.nonInteractive||"json"===e.output||!t.input||!t.output||(hu({...e,interactive:!0},t),0))}(e),p=Number(null!=(n=e.limit)?n:20),u=Number(null!=(o=e.offset)?o:0);if(!Number.isInteger(p)||p<1)throw new Error("--limit must be a positive integer.");if(!Number.isInteger(u)||u<0)throw new Error("--offset must be a nonnegative integer.");const d=null==(i=e.type)?void 0:i.toString(),m=null==(r=e.format)?void 0:r.toString();if(d&&"editor-project"!==d&&!ep.some(e=>e===d))throw new Error("Invalid --type. Use "+[...ep,"editor-project"].join(", ")+".");if(m&&!tp.some(e=>e===m))throw new Error("Invalid --format. Use "+tp.join(", ")+".");const{accessToken:f,org_id:h}=await zh(e.token,Fh(e),!0!==e.nonInteractive),g=(null==(a=e.endpoint)?void 0:a.toString())||"https://cloud.needle.tools/api",v=Math.min(p,100),b=d||void 0,y=m||void 0,x=(null==(s=e.search)?void 0:s.toString())||void 0,w={content_type:b,include_projects:!0===e.includeProjects,trash:!0===e.trash,content_format:y,search:x,limit:v,offset:u},_=T("Querying content...").start();try{const e=await np({baseUrl:g,authToken:f,org:h},w);if(l)return _.stop(),await async function(e,t={}){var n,o,i,r;const a=null!=(n=t.terminal)?n:function(){const e=Pe({input:process.stdin,output:process.stdout,terminal:!0,historySize:0}),t=new AbortController;return e.on("SIGINT",()=>{t.abort(),e.close()}),e.on("close",()=>t.abort()),{get columns(){return process.stdout.columns||80},color:void 0===process.env.NO_COLOR&&"dumb"!==process.env.TERM,write:e=>{process.stdout.write(e)},async readLine(n){if(t.signal.aborted)return null;try{return await e.question(n,{signal:t.signal})}catch(e){if(t.signal.aborted)return null;throw e}},close:()=>e.close()}}(),s=null!=(o=t.listContent)?o:np,c=null!=(i=t.getContent)?i:op,l=null!=(r=t.open)?r:Tp;let p,u={...e.query},d=e.initial;try{for(yu(a,d,u);;){var m,f;const t=await a.readLine(bu(a,"\n › ","brand"));if(null===t)break;const n=t.trim();if("q"===n||"quit"===n)break;if(p){"b"===n?(p=void 0,yu(a,d,u)):u.trash||"o"!==n?u.trash||"e"!==n?a.write(" Choose o/e to open, b to go back, or q to quit.\n"):await wu(p.edit_url,a,l):await wu(p.view_url||p.url,a,l);continue}if(/^\d+$/.test(n)){var h;const t=d.items[Number(n)-1];if(!t){a.write(" Choose a number shown on this page.\n");continue}const o=u.trash?void 0:await c(e.auth,t.identifier,{item:null!=(h=t.item_type)?h:"content"});p=t,xu(a,t,o,!0===u.trash);continue}if("?"===n||"help"===n){a.write("\n Type a number and Enter to inspect an item.\n /wood searches; / clears search. n/p move between pages.\n t switches between content and Trash; r refreshes the page.\n Browsing never changes content. Opening a browser requires o/e.\n q, Ctrl+C or end of input leaves the browser.\n");continue}const o=null!=(m=u.offset)?m:0,i=null!=(f=u.limit)?f:20;if("n"===n){if(o+d.items.length>=d.total){a.write(" No next page.\n");continue}u={...u,offset:o+i}}else if("p"===n){if(!o){a.write(" Already on the first page.\n");continue}u={...u,offset:Math.max(0,o-i)}}else if(n.startsWith("/"))u={...u,offset:0,search:n.slice(1).trim()||void 0};else if("t"===n)u={...u,offset:0,trash:!u.trash};else if("r"!==n){a.write(" Type a number, /search, n, p, t, r, ? or q.\n");continue}d=await s(e.auth,u),yu(a,d,u)}a.write("\n Back to your terminal.\n")}finally{a.close()}}({auth:{baseUrl:g,authToken:f,org:h},query:w,initial:e}),void await lu(0);if("json"===c)return _.succeed(`Found ${e.items.length} of ${e.total} items`),void cu(e.items);0===e.items.length&&(_.warn("No content found"+(b?` (type: ${b})`:"")+(y?` (format: ${y})`:"")),process.exit(0)),_.succeed(`Found ${e.items.length} of ${e.total} items`);const n=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?Sl(new Date(e.created_at),new Date,{allowSimple:!0,limitInDays:2}):""}}),o={id:Math.max(2,...n.map(e=>e.id.length)),type:Math.max(4,...n.map(e=>e.type.length)),formats:Math.max(7,...n.map(e=>e.formats.length)),name:Math.max(4,...n.map(e=>e.name.length))},i=Au(` ${"ID".padEnd(o.id)} ${"TYPE".padEnd(o.type)} ${"FORMATS".padEnd(o.formats)} ${"NAME".padEnd(o.name)} ${"#".padStart(3)} AGE`);t.info(i);for(const e of n){const n=Iu(e.type).padEnd(o.type+11),i=(e.formats?e.formats.split(", "):[]).map(e=>Iu(e)).join(", ")+" ".repeat(Math.max(0,o.formats-e.formats.length));t.info(` ${Au(e.id.padEnd(o.id))} ${n} ${i} ${e.name.padEnd(o.name)} ${e.versions.padStart(3)} ${Au(e.date)}`)}e.total>u+v&&t.info(` ... ${e.total-u-v} more (use --offset ${u+v})`),process.exit(0)}catch(e){_.fail(e.message),process.exit(1)}})),Dh.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:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The Needle Cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).action(su(async({args:e,options:t})=>{var n;const o=ru(t),{accessToken:i,org_id:r}=await zh(t.token,Fh(t),!0!==t.nonInteractive),a=(null==(n=t.endpoint)?void 0:n.toString())||"https://cloud.needle.tools/api",s=String(e.identifier),c=T(`Deleting content "${s}"...`).start();try{const e=await Eu({identifier:s,endpoint:a,authToken:i,org:r});c.succeed(e.message||`Moved content "${s}" to the trash`),"json"===o&&cu(e)}catch(e){c.fail(e.message),process.exitCode=1}})),Dh.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:Dh.STRING}).argument("[directory]","Output directory (default: current directory)",{default:"."}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING}).option("--format <format>","Output format to download (e.g. glb, textures)",{required:!1,validator:Dh.STRING}).option("--version <version>","Download this source version or derived output ID",{validator:Dh.STRING}).option("--label <label>","Download the version served by this label",{validator:Dh.STRING}).option("--name <name>","Output filename (without extension)",{required:!1,validator:Dh.STRING}).option("--verbose","Show detailed download info",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(async({args:e,options:t})=>{var n,o,i,r,a,s;const c=ru(t),{accessToken:l,org_id:p}=await zh(t.token,Fh(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=T("Looking up content...").start();try{var b,y;const e={baseUrl:u,authToken:l,org:p},n=await op(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 _u({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&&cu(i)}catch(e){v.fail(e instanceof Error?e.message:String(e)),process.exitCode=1}})),Dh.command("deploy","Deploy a website to Needle").help("").argument("<directory>","The directory to deploy",{validator:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to deploy to (not needed when using token/accesstoken)",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id to deloy to (not needed when using token/accesstoken)",{required:!1,validator:Dh.STRING,hidden:!0}).option("--name <name>","The project name. This name will also be used in your website URL",{required:!1,validator:Dh.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:Dh.STRING,hidden:!0}).option("--endpoint <endpoint>","The needle cloud endpoint to use - e.g. https://cloud.needle.tools/api",{required:!1,validator:Dh.STRING,hidden:!0}).option("--open","Open the deployment in the default browser",{default:!0,validator:Dh.BOOLEAN}).option("--verbose <verbose>","Enables verbose output logs",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--experimental","Use the experimental upload API. Mostly used for debugging (default: false)",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--raw","Use raw to disallow modifications like gzip compression on upload",{required:!1,validator:Dh.BOOLEAN,default:!1,hidden:!0}).option("--no-provenance","Do not record which commit and CI run this deployment came from",{required:!1,validator:Dh.BOOLEAN,default:!1}).action(su(nu("deploy",async({args:e,options:t,logger:n})=>{var o,i,r,a;const s=ru(t),c=!0!==t.nonInteractive&&t.open,{accessToken:l,org_id:p}=await zh(t.token,Fh(t),!0!==t.nonInteractive),u=!0===t.verbose,d=!0===t.experimental,m=!0===t.raw,f=(null==(o=t.noProvenance)?void 0:o.valueOf())||!1,h=await Hp({logger:n,endpoint:(null==(i=t.endpoint)?void 0:i.toString())||void 0,token:l,org_id:p,directory:String(e.directory),name:(null==(r=t.name)?void 0:r.toString())||void 0,entrypoint:(null==(a=t.entrypoint)?void 0:a.toString())||void 0,open:c,verbose:u||!1,experimental:d||!1,raw:m||!1,noProvenance:f});"json"===s&&null!=h&&h.success&&cu(h)}))),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. 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 or folder 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("--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.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(nu(n,async({args:e,options:n})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Re({stdout:a,stderr:a});try{var s,c;const i=ru(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 iu(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:bt)({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")}}ku(await(null!=(s=t.upload)?s:ju)({token:p,org_id:u,fileOrDirectory:String(e.path),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}}))}uu(e)}(Dh,{getAccessToken:zh,getUser:_d}),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(nu(`label ${n}`,async({args:e,options:o})=>{var i;const r=globalThis.console,a=null!=(i=t.stderr)?i:process.stderr;globalThis.console=new Re({stdout:a,stderr:a});try{var s;const i=ru(o,{legacyFormat:!0}),r=String(e.contentId);Kp(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&&Yp(a),void 0!==o.org&&console.warn("Warning: --org is deprecated. Use --team instead.");const{accessToken:p,org_id:u}=await iu(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:Qp)(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`),du(t.targets,m);else m(`No labels for ${r}.\n`)}else{var l;const e=await(null!=(l=t.setContentLabel)?l:eu)(d,a);"json"===i?m(JSON.stringify(e)+"\n"):(m(`${e.label}: ${e.previousVersionIds.join(", ")||"(new label)"} -> ${e.versionId}\n`),du(e.targets,m))}}finally{globalThis.console=r}}))}uu(e)}(Dh,{getAccessToken:zh}),function(e,t){const n={getContent:op,updateContent:ip,restoreContent:ap,...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(nu(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 mu(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 Re({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 iu(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(fu).join(""):"No upload versions.\n"))}}finally{globalThis.console=u}}))}uu(e)}(Dh,{getAccessToken:zh}),Dh.command("generate-material","Generate a PBR material from a text prompt").help("").argument("<prompt>","The text prompt describing the material to generate",{validator:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:Dh.STRING,hidden:!0}).option("--resolution <resolution>","The material texture resolution (256, 512, 1k, 2k, 4k)",{default:"512",required:!1,validator:Dh.STRING}).option("--name <name>","Output filename",{required:!1,validator:Dh.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:Dh.STRING}).action(su(nu("generate-material",async({args:e,options:t,logger:n})=>{var o,i,r;const a=ru(t),{accessToken:s,org_id:c}=await zh(t.token,Fh(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 ${Sp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";Mp(`[generate-material] Starting request to ${t}, prompt="${e.prompt}", resolution=${e.resolution||512}`,{emptyLineBefore:!0});const n=T("Requesting material generation...").start(),o=await Promise.race([Ql({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 Mp(`[generate-material] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(Mp(`[generate-material] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return Mp(`[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=T("Waiting for material generation...").start();r.color="gray";const a=kc();for(;;){if("completed"===i.status){r.succeed("Material generation completed");break}let n=2e3;const o=await jc(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)){Mp(`[generate-material] Job completed: ${i.identifier}`),r.succeed(`Material generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return Mp(`[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 Mp(`[generate-material] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`Material generation failed: ${o.error||""}`),{error:o.error||"Material generation failed"}}await kl(n)}if(e.outDir){const n=await _u({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?cu(m):!u&&"identifier"in m&&console.log(m.identifier),await lu(0)}))),Dh.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:Dh.STRING}).option("--token <token>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id",{required:!1,validator:Dh.STRING}).option("--org <org>","The organization name or id",{required:!1,validator:Dh.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:Dh.STRING}).option("--face-count <faceCount>","Target polygon count (40000-1500000). Leave unset to let the generator choose.",{required:!1,validator:Dh.NUMBER}).option("--name <name>","Output filename",{required:!1,validator:Dh.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:Dh.STRING}).action(su(nu("generate-3d",async({args:e,options:t,logger:n})=>{var o,i,r;const a=ru(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 zh(t.token,Fh(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 ${Sp()}`};if(!e.prompt||e.prompt.length<=0)return{error:"A prompt is required"};const t="https://cloud.needle.tools/api";Mp(`[generate-3d] Starting request to ${t}, prompt="${e.prompt}", quality=${e.quality||"draft"}`,{emptyLineBefore:!0});const n=T("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+ht.jobs.create,i={...gt(e),"content-type":"application/json"},r={type:"ai-3d-asset",triggered_by:e.trigger_type,parameters:{...t}},a=await fetch(o,{...vt,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 Mp(`[generate-3d] Request failed: ${o.error}`),n.fail(o.error),{error:o.error};const i=o.job;if(Mp(`[generate-3d] Job created: ${i.identifier}, status=${i.status}`),"canceled"===i.status)return Mp(`[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=T("Waiting for the 3D model...").start();r.color="gray";const a=kc();for(;;){if("completed"===i.status){r.succeed("3D generation completed");break}let n=2e3;const o=await jc(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)){Mp(`[generate-3d] Job completed: ${i.identifier}`),r.succeed(`3D generation completed: ${o.status_message||""}`);break}if("canceled"===(null==o?void 0:o.status))return Mp(`[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 Mp(`[generate-3d] Job failed: ${i.identifier}, error=${o.error}`),r.fail(`3D generation failed: ${o.error||""}`),{error:o.error||"3D generation failed"}}await kl(n)}if(e.outDir){const n=await _u({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?cu(f):!d&&"identifier"in f&&console.log(f.identifier),await lu(0)}))),Dh.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>",Lh,{validator:Dh.STRING}).option("--team <team>","The team name or id to authenticate for",{required:!1,validator:Dh.STRING}).option("--org <org>","Legacy alias for --team",{required:!1,validator:Dh.STRING,hidden:!0}).option("--slug <slug>","Chat slug to continue an existing conversation",{required:!1,validator:Dh.STRING}).option("--no-stream","Disable streaming (returns full response at once)",{required:!1,validator:Dh.BOOLEAN,default:!1}).option("--once","Send one message and exit",{validator:Dh.BOOLEAN,default:!1}).action(nu("ask",async({args:e,options:t})=>{var n,o;const i=ru(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 zh(t.token,Fh(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 au("json"===e.output,()=>Su({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=Pe({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 Su({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 Su({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 lu(0)})),uu(Dh);export{Bd as g,Dh as p};
|