mlai-code 0.0.0-stage → 0.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.
Files changed (182) hide show
  1. package/README.md +12 -2
  2. package/bin/mlai.mjs +3 -0
  3. package/package.json +18 -3
  4. package/src/browser-setup.mjs +77 -0
  5. package/src/cli-ext.mjs +146 -0
  6. package/src/cli.mjs +534 -0
  7. package/src/cloud.mjs +29 -0
  8. package/src/completion.mjs +159 -0
  9. package/src/credentials.mjs +54 -0
  10. package/src/deploy.mjs +134 -0
  11. package/src/distribution.mjs +373 -0
  12. package/src/engine-key.mjs +4 -0
  13. package/src/engine.mjs +167 -0
  14. package/src/headless.mjs +196 -0
  15. package/src/home.mjs +22 -0
  16. package/src/host.mjs +123 -0
  17. package/src/local-models.mjs +64 -0
  18. package/src/modes.mjs +38 -0
  19. package/src/netbox.mjs +97 -0
  20. package/src/netjail.py +59 -0
  21. package/src/offline.mjs +98 -0
  22. package/src/parity.mjs +86 -0
  23. package/src/project.mjs +68 -0
  24. package/src/relay.mjs +140 -0
  25. package/src/render.mjs +73 -0
  26. package/src/restricted.mjs +47 -0
  27. package/src/review.mjs +70 -0
  28. package/src/runner.mjs +127 -0
  29. package/src/runtime.mjs +75 -0
  30. package/src/sandbox.mjs +135 -0
  31. package/src/sdk.mjs +11 -0
  32. package/src/server.mjs +110 -0
  33. package/src/session.mjs +290 -0
  34. package/src/settings.mjs +135 -0
  35. package/src/shared-data.mjs +3 -0
  36. package/src/tui/acp.mjs +145 -0
  37. package/src/tui/agents-cli.mjs +114 -0
  38. package/src/tui/agents-local.mjs +65 -0
  39. package/src/tui/ansi.mjs +123 -0
  40. package/src/tui/app.mjs +710 -0
  41. package/src/tui/approval.mjs +88 -0
  42. package/src/tui/bg.mjs +172 -0
  43. package/src/tui/bgterm.mjs +79 -0
  44. package/src/tui/chat.mjs +230 -0
  45. package/src/tui/clipboard.mjs +74 -0
  46. package/src/tui/cloud-cli.mjs +57 -0
  47. package/src/tui/cloud-run.mjs +123 -0
  48. package/src/tui/cmd-agents.mjs +130 -0
  49. package/src/tui/cmd-auto-review.mjs +94 -0
  50. package/src/tui/cmd-cloud.mjs +17 -0
  51. package/src/tui/cmd-config.mjs +104 -0
  52. package/src/tui/cmd-core.mjs +160 -0
  53. package/src/tui/cmd-distribution.mjs +15 -0
  54. package/src/tui/cmd-ecosystem.mjs +169 -0
  55. package/src/tui/cmd-extensibility.mjs +333 -0
  56. package/src/tui/cmd-remote.mjs +18 -0
  57. package/src/tui/cmd-review.mjs +58 -0
  58. package/src/tui/cmd-session-extra.mjs +152 -0
  59. package/src/tui/cmd-tui.mjs +200 -0
  60. package/src/tui/commands.mjs +160 -0
  61. package/src/tui/custom-commands.mjs +98 -0
  62. package/src/tui/diff.mjs +60 -0
  63. package/src/tui/editor.mjs +190 -0
  64. package/src/tui/ext-state.mjs +16 -0
  65. package/src/tui/extensions-local.mjs +140 -0
  66. package/src/tui/files.mjs +72 -0
  67. package/src/tui/handoff.mjs +110 -0
  68. package/src/tui/import-setups.mjs +151 -0
  69. package/src/tui/init.mjs +104 -0
  70. package/src/tui/keymap.mjs +70 -0
  71. package/src/tui/keys.mjs +101 -0
  72. package/src/tui/loop.mjs +75 -0
  73. package/src/tui/markdown.mjs +118 -0
  74. package/src/tui/mcp-config.mjs +225 -0
  75. package/src/tui/mcp-oauth.mjs +162 -0
  76. package/src/tui/permissions.mjs +189 -0
  77. package/src/tui/plain.mjs +32 -0
  78. package/src/tui/plugins-local.mjs +103 -0
  79. package/src/tui/remote.mjs +125 -0
  80. package/src/tui/review-cli.mjs +332 -0
  81. package/src/tui/review-github.mjs +59 -0
  82. package/src/tui/screen.mjs +60 -0
  83. package/src/tui/session-ops.mjs +104 -0
  84. package/src/tui/skills-local.mjs +92 -0
  85. package/src/tui/snapshots.mjs +87 -0
  86. package/src/tui/statusline.mjs +98 -0
  87. package/src/tui/transcript.mjs +116 -0
  88. package/src/two-words.mjs +36 -0
  89. package/src/wakeups.mjs +53 -0
  90. package/src/winenv.mjs +94 -0
  91. package/src/winsandbox.py +351 -0
  92. package/src/workspace-api.mjs +621 -0
  93. package/src/worktree.mjs +128 -0
  94. package/vendor/client-sdk/controller.cjs +115 -0
  95. package/vendor/client-sdk/files.cjs +38 -0
  96. package/vendor/client-sdk/index.cjs +133 -0
  97. package/vendor/client-sdk/login.cjs +52 -0
  98. package/vendor/client-sdk/updates.cjs +41 -0
  99. package/vendor/cloud-cli/mlai.mjs +394 -0
  100. package/worker/architecture_parse.cjs +23 -0
  101. package/worker/architecture_worker.py +394 -0
  102. package/worker/ask_first.py +96 -0
  103. package/worker/attachment_reader.py +66 -0
  104. package/worker/background_jobs.py +111 -0
  105. package/worker/brief_questions.py +56 -0
  106. package/worker/browser_local.py +49 -0
  107. package/worker/browser_pane.py +89 -0
  108. package/worker/browser_tool.py +101 -0
  109. package/worker/build_planner.py +187 -0
  110. package/worker/chat_fork.py +277 -0
  111. package/worker/checkpoints.py +133 -0
  112. package/worker/cloud_pty.py +351 -0
  113. package/worker/command_policy.py +39 -0
  114. package/worker/command_safety.py +717 -0
  115. package/worker/computer_card.sh +23 -0
  116. package/worker/computer_setup.sh +86 -0
  117. package/worker/computer_use.py +221 -0
  118. package/worker/connector_search.py +43 -0
  119. package/worker/context_manager.py +60 -0
  120. package/worker/conversation.py +144 -0
  121. package/worker/deploy_pack.py +116 -0
  122. package/worker/design_director.py +240 -0
  123. package/worker/dev_jobs.py +166 -0
  124. package/worker/edit_guard.py +99 -0
  125. package/worker/env_setup.py +129 -0
  126. package/worker/evidence.py +109 -0
  127. package/worker/fast_search.py +24 -0
  128. package/worker/git_sync.py +333 -0
  129. package/worker/goals.py +156 -0
  130. package/worker/handover.py +98 -0
  131. package/worker/harness_memory.py +194 -0
  132. package/worker/image_generation.py +173 -0
  133. package/worker/intelligence.py +149 -0
  134. package/worker/intent_model.py +78 -0
  135. package/worker/intent_weights.json +1 -0
  136. package/worker/ios_simulator.py +87 -0
  137. package/worker/kimi_bridge.py +997 -0
  138. package/worker/kimi_compact.py +93 -0
  139. package/worker/kimi_gates.py +304 -0
  140. package/worker/kimi_hook.py +617 -0
  141. package/worker/lifecycle.py +95 -0
  142. package/worker/lsp.py +77 -0
  143. package/worker/mcp_local.py +293 -0
  144. package/worker/memory.py +99 -0
  145. package/worker/mlai_auto_review.py +177 -0
  146. package/worker/mlai_hooks.py +966 -0
  147. package/worker/mlai_mcp.py +441 -0
  148. package/worker/mlai_permissions.py +283 -0
  149. package/worker/model_stream.py +75 -0
  150. package/worker/nested_repos.py +76 -0
  151. package/worker/offline_guard.py +17 -0
  152. package/worker/preview.py +806 -0
  153. package/worker/proc_watch.py +124 -0
  154. package/worker/project_context.py +72 -0
  155. package/worker/project_rules.py +99 -0
  156. package/worker/quality.py +180 -0
  157. package/worker/reply_language.py +56 -0
  158. package/worker/repo_hygiene.py +132 -0
  159. package/worker/repo_memory.py +101 -0
  160. package/worker/repo_policy.py +269 -0
  161. package/worker/roles.json +3173 -0
  162. package/worker/roles.py +303 -0
  163. package/worker/runner.py +1795 -0
  164. package/worker/runtime_control.py +205 -0
  165. package/worker/secret_scan.py +168 -0
  166. package/worker/session_hub.py +80 -0
  167. package/worker/skill_library.py +129 -0
  168. package/worker/skill_pack.py +533 -0
  169. package/worker/subagents.py +91 -0
  170. package/worker/task_controller.py +139 -0
  171. package/worker/task_skills.py +159 -0
  172. package/worker/team_checkpoint.py +33 -0
  173. package/worker/token_count.py +32 -0
  174. package/worker/tool_catalog.py +38 -0
  175. package/worker/upload_storage.py +531 -0
  176. package/worker/verification.py +725 -0
  177. package/worker/vision.py +84 -0
  178. package/worker/wakeups.py +63 -0
  179. package/worker/web_tools.py +203 -0
  180. package/worker/winproc.py +135 -0
  181. package/worker/work_ledger.py +117 -0
  182. package/worker/worktrees.py +79 -0
@@ -0,0 +1,128 @@
1
+ // Git worktrees: each session can work in its own checkout and branch, so several tasks run at once
2
+ // without touching each other or the developer's own working copy. Shared by the app and `mlai --worktree`.
3
+ import {execFile} from 'node:child_process';
4
+ import {promisify} from 'node:util';
5
+ import {mkdir,readFile,copyFile,stat,rm} from 'node:fs/promises';
6
+ import {createHash,randomBytes} from 'node:crypto';
7
+ import {realpathSync} from 'node:fs';
8
+ import path from 'node:path';
9
+ import {home} from './home.mjs';
10
+ const run=promisify(execFile);
11
+
12
+ export class WorktreeError extends Error{constructor(message,code){super(message);this.code=code}}
13
+ const git=async(cwd,args,opts={})=>{
14
+ try{return (await run('git',args,{cwd,maxBuffer:8e6,timeout:opts.timeout||60000,windowsHide:true,env:{...process.env,GIT_TERMINAL_PROMPT:'0'}})).stdout}
15
+ catch(e){const out=(String(e.stderr||'')+'\n'+String(e.stdout||'')).trim()||String(e.message||'');throw new WorktreeError(out.split('\n').filter(Boolean).slice(-6).join(' ')||'git failed','git')}
16
+ };
17
+ // Machines without a git identity still get commits; the developer's own name is used whenever it is set.
18
+ const identity=async cwd=>(await git(cwd,['config','user.email']).catch(()=>'')).trim()?[]:['-c','user.name=ML AI Code','-c','user.email=code@mlai.local'];
19
+ const ok=async(cwd,args)=>{try{await git(cwd,args);return true}catch{return false}};
20
+
21
+ /** A branch-safe slug from free text: lowercase words joined by dashes, at most 40 characters. */
22
+ export function slug(text){
23
+ const s=String(text||'').toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g,' ').replace(/_/g,' ').trim().split(/\s+/).filter(Boolean).slice(0,6).join('-').replace(/-+/g,'-').slice(0,40).replace(/-+$/,'');
24
+ return s||'task';
25
+ }
26
+ /**
27
+ * Where worktrees for a repository live: ~/.mlai-worktrees/<repo>-<hash of its path>.
28
+ * Next to ~/.mlai rather than inside it, because the OS sandbox hides ~/.mlai from commands.
29
+ */
30
+ export function worktreeBase(root){
31
+ const h=createHash('sha256').update(root).digest('hex').slice(0,8);
32
+ const base=path.join(path.dirname(home()),path.basename(home())+'-worktrees');
33
+ return path.join(base,path.basename(root).replace(/[^\w.-]/g,'_')+'-'+h);
34
+ }
35
+ /** Can this folder have worktrees? It needs to be the top of a git repository with at least one commit. */
36
+ export async function canWorktree(root){
37
+ if(!(await ok(root,['rev-parse','--verify','HEAD'])))return {ok:false,reason:'This folder has no commits yet, so a worktree cannot start from it.'};
38
+ const top=(await git(root,['rev-parse','--show-toplevel']).catch(()=>'')).trim();
39
+ if(!top)return {ok:false,reason:'This folder is not a git repository.'};
40
+ return {ok:true};
41
+ }
42
+ /** Lines from .worktreeinclude: gitignored files to copy into each new worktree (for example .env.local). */
43
+ async function includes(root){
44
+ let text='';try{text=await readFile(path.join(root,'.worktreeinclude'),'utf8')}catch{return []}
45
+ return text.split(/\r?\n/).map(l=>l.trim()).filter(l=>l&&!l.startsWith('#')).slice(0,50)
46
+ .filter(l=>!path.isAbsolute(l)&&!l.split(/[\\/]/).includes('..'));
47
+ }
48
+
49
+ /**
50
+ * Creates a worktree on a new branch mlai/<name> from the current HEAD of root (or from the commit `from`, for
51
+ * example a fetched pull request). Returns {path, branch, base, baseBranch, parent, copied}.
52
+ */
53
+ export async function createWorktree(root,{name,from=null}={}){
54
+ const can=await canWorktree(root);if(!can.ok)throw new WorktreeError(can.reason,'no_worktree');
55
+ const base=(await git(root,['rev-parse',from?String(from)+'^{commit}':'HEAD'])).trim();
56
+ const baseBranch=from?null:(await git(root,['rev-parse','--abbrev-ref','HEAD'])).trim();
57
+ const short=name?slug(name):'session-'+randomBytes(2).toString('hex');
58
+ let branch='mlai/'+short;
59
+ for(let i=2;await ok(root,['rev-parse','--verify','--quiet','refs/heads/'+branch]);i++)branch='mlai/'+short+'-'+i;
60
+ const dir=path.join(worktreeBase(root),branch.slice(5));
61
+ await mkdir(path.dirname(dir),{recursive:true,mode:0o700});
62
+ await git(root,['worktree','add','-b',branch,dir,base],{timeout:180000});
63
+ const real=realpathSync.native(dir);
64
+ const copied=[];
65
+ for(const rel of await includes(root)){
66
+ const from=path.join(root,rel),to=path.join(real,rel);
67
+ try{if(!(await stat(from)).isFile())continue;await mkdir(path.dirname(to),{recursive:true});await copyFile(from,to);copied.push(rel)}catch{}
68
+ }
69
+ return {path:real,branch,base,baseBranch:!baseBranch||baseBranch==='HEAD'?null:baseBranch,parent:root,copied,named:!!name};
70
+ }
71
+ /** Renames the branch once the first task says what the work is, if nothing has been pushed yet. */
72
+ export async function renameBranch(wt,name){
73
+ const want='mlai/'+slug(name);
74
+ if(wt.branch===want||wt.named)return wt;
75
+ let next=want;for(let i=2;await ok(wt.path,['rev-parse','--verify','--quiet','refs/heads/'+next]);i++)next=want+'-'+i;
76
+ if(await ok(wt.path,['rev-parse','--verify','--quiet','refs/remotes/origin/'+wt.branch]))return {...wt,named:true};
77
+ await git(wt.path,['branch','-m',wt.branch,next]);
78
+ return {...wt,branch:next,named:true};
79
+ }
80
+ /** Commits ahead of the base, uncommitted files, and whether the worktree folder still exists. */
81
+ export async function worktreeStatus(wt){
82
+ const exists=await stat(wt.path).then(s=>s.isDirectory(),()=>false);
83
+ if(!exists)return {exists:false,ahead:0,dirty:0,files:[]};
84
+ const [ahead,status,stat2,unmerged]=await Promise.all([
85
+ git(wt.path,['rev-list','--count',wt.base+'..HEAD']).then(s=>Number(s.trim())||0,()=>0),
86
+ git(wt.path,['status','--porcelain']).catch(()=>''),
87
+ git(wt.path,['diff','--shortstat',wt.base]).catch(()=>''),
88
+ wt.parent?git(wt.parent,['rev-list','--count','HEAD..'+wt.branch]).then(s=>Number(s.trim())||0,()=>0):0,
89
+ ]);
90
+ const files=status.split('\n').filter(Boolean).map(l=>l.slice(3));
91
+ return {exists:true,ahead,unmerged,dirty:files.length,files:files.slice(0,50),shortstat:stat2.trim()};
92
+ }
93
+ /** Commits whatever is uncommitted in the worktree with the given message. */
94
+ export async function commitAll(wt,message){
95
+ const s=await worktreeStatus(wt);if(!s.exists)throw new WorktreeError('The worktree folder is gone.','missing');
96
+ if(!s.dirty)return {committed:false};
97
+ await git(wt.path,['add','-A']);
98
+ await git(wt.path,[...await identity(wt.path),'commit','-q','-m',String(message||'Work from ML AI Code').slice(0,500)]);
99
+ return {committed:true};
100
+ }
101
+ /**
102
+ * Merges the worktree's branch into whatever branch the main folder has checked out.
103
+ * Uncommitted work in the worktree is committed first. On a conflict the merge is aborted and nothing changes.
104
+ */
105
+ export async function mergeWorktree(wt,{message}={}){
106
+ const parent=wt.parent;
107
+ await commitAll(wt,message);
108
+ const into=(await git(parent,['rev-parse','--abbrev-ref','HEAD'])).trim();
109
+ // Commits on the session branch that the main folder's branch does not have yet.
110
+ const ahead=Number((await git(parent,['rev-list','--count','HEAD..'+wt.branch])).trim())||0;
111
+ if(!ahead)return {merged:false,reason:'There is nothing to merge yet.'};
112
+ if(into===wt.branch)throw new WorktreeError('The main folder has the session branch checked out.','same_branch');
113
+ const who=await identity(parent);
114
+ try{await git(parent,[...who,'merge','--no-ff','--no-edit','-m','Merge '+wt.branch+(message?': '+String(message).slice(0,200):''),wt.branch],{timeout:120000})}
115
+ catch(e){
116
+ await git(parent,['merge','--abort']).catch(()=>{});
117
+ const local=/overwritten by merge|commit your changes|local changes/i.test(e.message);
118
+ if(!local&&!/conflict/i.test(e.message))throw new WorktreeError('Merge failed: '+e.message,'git');
119
+ throw new WorktreeError(local?'Your main folder has uncommitted changes in the same files. Commit or stash them, then merge again.':'The branch conflicts with '+into+'. Nothing was changed. Open the branch in your editor to resolve it, or ask the agent to rebase it.',local?'dirty':'conflict');
120
+ }
121
+ return {merged:true,into,commits:ahead};
122
+ }
123
+ /** Removes the worktree folder. The branch is kept unless deleteBranch is set. */
124
+ export async function removeWorktree(wt,{deleteBranch=false}={}){
125
+ await git(wt.parent,['worktree','remove','--force',wt.path]).catch(async()=>{await rm(wt.path,{recursive:true,force:true});await git(wt.parent,['worktree','prune']).catch(()=>{})});
126
+ if(deleteBranch)await git(wt.parent,['branch','-D',wt.branch]).catch(()=>{});
127
+ return {removed:true,branchKept:!deleteBranch};
128
+ }
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+ const {Client,ClientError,diagnostic,redact}=require('./index.cjs');
3
+ const {login}=require('./login.cjs');
4
+
5
+ function relativePath(value){
6
+ if(typeof value!=='string'||!value||value.length>1000||value.includes('\\')||value.includes(':')||value.startsWith('/')||value.includes('\0')||value.split('/').some(x=>['..','.git',''].includes(x.toLowerCase())))throw new ClientError('Invalid project file path');
7
+ return value;
8
+ }
9
+ /** Host-side state: credentials and workspace access tokens never enter the UI bridge. */
10
+ class Controller{
11
+ constructor({surface,version='0.1.0',storage,openExternal,baseUrl,fetchImpl,allowLoopback=false,onReview,onApplyReview,onLocal,onReport}){
12
+ this.surface=surface;this.version=version;this.storage=storage;this.openExternal=openExternal;
13
+ this.onReview=onReview;this.onApplyReview=onApplyReview;this.onLocal=onLocal;this.onReport=onReport;
14
+ this.credential=null;this.projects=[];this.selected=null;this.identity=null;this.loginAbort=null;this.disposed=false;
15
+ this.abort=new AbortController();this.fetchOptions={signal:this.abort.signal};
16
+ this.client=new Client({surface,version,baseUrl,fetchImpl,allowLoopback,tokenProvider:()=>this.credential?.token});
17
+ this.loginOptions={baseUrl:this.client.baseUrl,surface,fetchImpl,allowLoopback};
18
+ }
19
+ async refresh(){
20
+ this.identity=await this.client.identity(this.fetchOptions);
21
+ const account=await this.client.projects(this.fetchOptions);
22
+ this.projects=Array.isArray(account.workspaces)?account.workspaces.filter(w=>typeof w.name==='string'&&typeof w.token==='string'):[];
23
+ this.selected=this.projects.find(w=>w.name===this.selected?.name)||this.projects[0]||null;
24
+ return this.summary();
25
+ }
26
+ summary(){return {signedIn:!!this.identity,identity:this.identity?{label:this.identity.label,expires:this.identity.expires}:null,projects:this.projects.map(({name,label,repo})=>({name,label:label||repo||name,repo})),selected:this.selected?.name||null,surface:this.surface,localAvailable:!!this.onLocal,reviewAvailable:!!this.onReview}}
27
+ selectedToken(){if(!this.selected)throw new ClientError('Choose a project first');return this.selected.token}
28
+ async dispatch(method,args={}){
29
+ try{return await this.perform(method,args)}catch(e){
30
+ if(e.status===401){this.credential=null;this.identity=null;this.projects=[];this.selected=null;await this.storage.set(null).catch(()=>{})}
31
+ throw e;
32
+ }
33
+ }
34
+ async perform(method,args={}){
35
+ if(this.disposed)throw new ClientError('Client has been closed');
36
+ if(!args||typeof args!=='object'||Array.isArray(args)||JSON.stringify(args).length>50000)throw new ClientError('Invalid bridge request');
37
+ switch(method){
38
+ case 'init':{
39
+ this.credential=await this.storage.get();
40
+ if(this.credential?.baseUrl!==this.client.baseUrl)this.credential=null;
41
+ if(!this.credential)return this.summary();
42
+ try{await this.client.connect(this.fetchOptions);return await this.refresh()}
43
+ catch(e){if(e.status===401){this.credential=null;await this.storage.set(null)}throw e}
44
+ }
45
+ case 'login':{
46
+ if(this.loginAbort)throw new ClientError('Sign-in is already open in your browser');
47
+ this.loginAbort=new AbortController();
48
+ try{
49
+ await this.storage.prepare?.();
50
+ const credential=await login({...this.loginOptions,openExternal:this.openExternal,signal:this.loginAbort.signal});
51
+ if(this.disposed)throw new ClientError('Client has been closed');
52
+ await this.storage.set(credential);this.credential=credential;
53
+ await this.client.connect(this.fetchOptions);return await this.refresh();
54
+ }finally{this.loginAbort=null}
55
+ }
56
+ case 'cancelLogin':this.loginAbort?.abort();return {ok:true};
57
+ case 'logout':{
58
+ this.loginAbort?.abort();
59
+ let warning;
60
+ try{if(this.credential)await this.client.revoke(this.fetchOptions)}catch{warning='Signed out here. Could not confirm remote revocation; revoke this device in the web app Settings → API keys.'}
61
+ this.credential=null;this.identity=null;this.projects=[];this.selected=null;
62
+ try{await this.storage.set(null)}catch{warning=(warning?warning+' ':'')+'Local credential removal could not be confirmed. Revoke this device in web Settings.'}
63
+ return {...this.summary(),warning};
64
+ }
65
+ case 'projects':return this.refresh();
66
+ case 'select':{
67
+ const p=this.projects.find(p=>p.name===args.name);if(!p)throw new ClientError('Project is no longer available');
68
+ this.selected=p;return this.summary();
69
+ }
70
+ case 'snapshot':{
71
+ const s=await this.client.status(this.selectedToken(),this.fetchOptions);
72
+ return {status:s.status,runId:s.runId,pending:s.pending,events:s.events,files:s.files,completion:s.completion,checks:s.checks,task:s.task};
73
+ }
74
+ case 'run':return this.client.start(this.selectedToken(),args.task,{mode:args.mode||'approve',...this.fetchOptions});
75
+ case 'stop':return this.client.stop(this.selectedToken(),this.fetchOptions);
76
+ case 'approve':{
77
+ const token=this.selectedToken(),s=await this.client.status(token,this.fetchOptions);
78
+ if(!s.pending||s.pending.id!==args.id)throw new ClientError('This approval changed. Refresh before deciding.');
79
+ return this.client.approve(token,args.id,args.approved,this.fetchOptions);
80
+ }
81
+ case 'read':return this.client.read(this.selectedToken(),relativePath(args.path),this.fetchOptions);
82
+ case 'review':{
83
+ if(!this.onReview)throw new ClientError('Local review is not available in this host');
84
+ const file=relativePath(args.path),result=await this.client.read(this.selectedToken(),file,this.fetchOptions);
85
+ if(typeof result.content!=='string'||Buffer.byteLength(result.content)>500000)throw new ClientError('File is too large to review');
86
+ return this.onReview(file,result.content);
87
+ }
88
+ case 'applyReview':{
89
+ if(!this.onApplyReview||typeof args.id!=='string')throw new ClientError('No reviewed edit is available');
90
+ return this.onApplyReview(args.id);
91
+ }
92
+ case 'architecture':{
93
+ if(!['list','get','refresh','pin'].includes(args.action))throw new ClientError('Invalid architecture action');
94
+ const {action,id,snapshot,entity,body,supersedes}=args;
95
+ return this.client.request('/api/architecture',{action,id,snapshot,entity,body,supersedes,token:this.selectedToken()},{...this.fetchOptions,readOnly:['list','get'].includes(action)});
96
+ }
97
+ case 'create':{
98
+ const repo=args.repo||'';
99
+ if(repo&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$/.test(repo))throw new ClientError('Use a GitHub repository URL without credentials or query parameters');
100
+ await this.client.request('/api/workspace',{action:'create',repo,profile:'small',fit:true},this.fetchOptions);
101
+ return this.refresh();
102
+ }
103
+ case 'local':if(!this.onLocal)throw new ClientError('Local mode is unavailable');return this.onLocal();
104
+ case 'web':await this.openExternal(this.client.baseUrl+'/');return {ok:true};
105
+ case 'report':{
106
+ const report=diagnostic({surface:this.surface,version:this.version,os:process.platform,arch:process.arch,code:args.code});
107
+ if(this.onReport)await this.onReport(report);
108
+ return {report};
109
+ }
110
+ default:throw new ClientError('Unknown bridge operation');
111
+ }
112
+ }
113
+ dispose(){this.disposed=true;this.loginAbort?.abort();this.abort.abort();this.credential=null;this.projects=[];this.identity=null}
114
+ }
115
+ module.exports={Controller,relativePath};
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ const fs=require('node:fs/promises'),path=require('node:path'),{createHash,randomUUID}=require('node:crypto');
3
+ const {relativePath}=require('./controller.cjs');
4
+ const hash=s=>createHash('sha256').update(s).digest('hex');
5
+ async function target(root,file){
6
+ relativePath(file);
7
+ if(file.includes(':')||file.split('/').some(s=>s.toLowerCase()==='.git'))throw Error('Protected file path');
8
+ const base=await fs.realpath(root),dest=path.resolve(base,file);
9
+ if(!dest.startsWith(base+path.sep))throw Error('File leaves the selected folder');
10
+ let parent=path.dirname(dest);
11
+ while(true){
12
+ try{const real=await fs.realpath(parent);if(real!==base&&!real.startsWith(base+path.sep))throw Error('A symlink leaves the selected folder');break}
13
+ catch(e){if(e.code!=='ENOENT')throw e;const up=path.dirname(parent);if(up===parent)throw e;parent=up}
14
+ }
15
+ try{const s=await fs.lstat(dest);if(s.isSymbolicLink()||!s.isFile())throw Error('Review only regular files');if(s.size>500000)throw Error('File is too large for reviewed editing')}
16
+ catch(e){if(e.code!=='ENOENT')throw e}
17
+ return dest;
18
+ }
19
+ async function read(root,file){const dest=await target(root,file);try{return await fs.readFile(dest,'utf8')}catch(e){if(e.code==='ENOENT')return null;throw e}}
20
+ async function review(root,file,content){
21
+ if(typeof content!=='string'||Buffer.byteLength(content)>500000||content.includes('\0'))throw Error('Review only bounded text files');
22
+ const before=await read(root,file);if(before?.includes('\0'))throw Error('Binary files cannot be reviewed as text');
23
+ return {id:randomUUID(),root:await fs.realpath(root),path:file,before,after:content,baseHash:before===null?null:hash(before)};
24
+ }
25
+ async function apply(review){
26
+ const current=await read(review.root,review.path);
27
+ if((current===null?null:hash(current))!==review.baseHash)throw Error('Local file changed after review. Compare it again before applying.');
28
+ const dest=await target(review.root,review.path);await fs.mkdir(path.dirname(dest),{recursive:true});await target(review.root,review.path);
29
+ const mode=current===null?0o644:(await fs.stat(dest)).mode&0o777;
30
+ if(current===null){await fs.writeFile(dest,review.after,{flag:'wx',mode});return {applied:true}}
31
+ const temp=dest+'.mlai-review-'+randomUUID();
32
+ try{
33
+ await fs.writeFile(temp,review.after,{flag:'wx',mode});
34
+ if(hash(await fs.readFile(dest,'utf8'))!==review.baseHash)throw Error('Local file changed. Review again.');
35
+ await fs.rename(temp,dest);return {applied:true};
36
+ }finally{await fs.rm(temp,{force:true})}
37
+ }
38
+ module.exports={target,read,review,apply};
@@ -0,0 +1,133 @@
1
+ 'use strict';
2
+ const {createHash,randomUUID}=require('node:crypto');
3
+ const {setTimeout:delay}=require('node:timers/promises');
4
+
5
+ const DEFAULT_URL='https://mlai-mini-code.vercel.app';
6
+ const PROTOCOL=1;
7
+ const TERMINAL=new Set(['completed','failed','error','stopped','interrupted','limited','lost']);
8
+ class ClientError extends Error{
9
+ constructor(message,{status=0,code='client_error',retryable=false}={}){
10
+ super(message);this.name='ClientError';this.status=status;this.code=code;this.retryable=retryable;
11
+ }
12
+ }
13
+ function serverOrigin(value=DEFAULT_URL,{allowLoopback=false}={}){
14
+ let u;try{u=new URL(value)}catch{throw new ClientError('Invalid server address')}
15
+ if(u.username||u.password||u.search||u.hash||!['','/'].includes(u.pathname))throw new ClientError('Use a server origin without credentials, path or query');
16
+ if(u.protocol!=='https:'&&!(allowLoopback&&u.protocol==='http:'&&['127.0.0.1','[::1]'].includes(u.hostname)))throw new ClientError('A secure HTTPS server is required');
17
+ return u.origin;
18
+ }
19
+ function string(value,label,max=30000){
20
+ if(typeof value!=='string'||!value.trim()||value.length>max)throw new ClientError(`Invalid ${label}`,{code:'invalid_input'});
21
+ return value;
22
+ }
23
+ function abortError(){return new ClientError('Operation cancelled',{code:'cancelled'})}
24
+ async function boundedText(response){
25
+ const limit=8*1024*1024;
26
+ if(Number(response.headers?.get('content-length'))>limit){await response.body?.cancel();throw new ClientError('Server response exceeds the client safety limit',{code:'response_too_large'})}
27
+ if(!response.body?.getReader){const text=await response.text();if(Buffer.byteLength(text)>limit)throw new ClientError('Server response exceeds the client safety limit',{code:'response_too_large'});return text}
28
+ const reader=response.body.getReader(),chunks=[];let length=0;
29
+ try{
30
+ for(;;){const {done,value}=await reader.read();if(done)break;length+=value.byteLength;if(length>limit){await reader.cancel();throw new ClientError('Server response exceeds the client safety limit',{code:'response_too_large'})}chunks.push(value)}
31
+ return Buffer.concat(chunks,length).toString('utf8');
32
+ }finally{reader.releaseLock()}
33
+ }
34
+ function redact(value){
35
+ return String(value)
36
+ .replace(/\b(?:mlaid_[A-Za-z0-9_.-]+|mlai_sk_[A-Za-z0-9]+|mlai_[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|gh[pousr]_[A-Za-z0-9]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{8,})\b/g,'[credential]')
37
+ .replace(/\bBearer\s+\S+/gi,'Bearer [credential]')
38
+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,'[email]')
39
+ .replace(/(?:\/(?:Users|home)\/|[A-Z]:\\Users\\)[^\s"']+/gi,'[local-path]')
40
+ .slice(0,2000);
41
+ }
42
+ /** An allowlisted report: no logs, stack locals, prompts, source text or environment. */
43
+ function diagnostic({surface,version,os,arch,code,status,protocol=PROTOCOL}={}){
44
+ const safe=x=>redact(x||'unknown').replace(/[^\w.@-]/g,'_').slice(0,100);
45
+ return {schema:'mlai.diagnostic.v1',surface:safe(surface),version:safe(version),os:safe(os),arch:safe(arch),code:safe(code),status:Number.isInteger(status)?status:0,protocol};
46
+ }
47
+ class Client{
48
+ constructor({baseUrl=DEFAULT_URL,tokenProvider=()=>null,fetchImpl=globalThis.fetch,surface='desktop',version='0.1.0',allowLoopback=false,timeoutMs=30000}={}){
49
+ this.baseUrl=serverOrigin(baseUrl,{allowLoopback});this.tokenProvider=tokenProvider;this.fetch=fetchImpl;
50
+ if(!['desktop','vscode','jetbrains','acp','laptop'].includes(surface))throw new ClientError('Invalid client surface');
51
+ this.surface=surface;this.version=string(version,'version',60);this.timeoutMs=timeoutMs;
52
+ }
53
+ async request(path,body,{method='POST',signal,authenticated=true,readOnly=false}={}){
54
+ if(!/^\/api\/[a-z0-9/_-]+$/.test(path))throw new ClientError('Invalid API route');
55
+ const token=authenticated?await this.tokenProvider():null;
56
+ if(authenticated&&!token)throw new ClientError('Sign in to ML AI Code first',{status:401,code:'sign_in_required'});
57
+ const retries=readOnly?2:0;
58
+ for(let attempt=0;;attempt++){
59
+ if(signal?.aborted)throw abortError();
60
+ const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),this.timeoutMs);
61
+ const abort=()=>controller.abort();signal?.addEventListener('abort',abort,{once:true});
62
+ try{
63
+ const response=await this.fetch(this.baseUrl+path,{
64
+ method,redirect:'error',signal:controller.signal,
65
+ headers:{'Content-Type':'application/json','Accept':'application/json','X-MLAI-Client':this.surface,'X-MLAI-Version':this.version,'X-MLAI-Protocol':String(PROTOCOL),...(token?{Authorization:'Bearer '+token}:{})},
66
+ ...(body===undefined?{}:{body:JSON.stringify(body)}),
67
+ });
68
+ const text=await boundedText(response);
69
+ let data;try{data=JSON.parse(text)}catch{throw new ClientError('The server returned an unreadable response',{status:response.status,code:'invalid_response'})}
70
+ if(!data||typeof data!=='object'||Array.isArray(data))throw new ClientError('The server returned an unexpected response shape',{status:response.status,code:'invalid_response'});
71
+ if(!response.ok){
72
+ const error=new ClientError(redact(data.error||'Request failed'),{status:response.status,code:typeof data.code==='string'?data.code:'http_error',retryable:[429,502,503,504].includes(response.status)});
73
+ if(error.retryable&&attempt<retries){await delay(Math.min(1000*2**attempt,4000),undefined,{signal});continue}
74
+ throw error;
75
+ }
76
+ return data;
77
+ }catch(error){
78
+ if(signal?.aborted)throw abortError();
79
+ if(error instanceof ClientError)throw error;
80
+ if(attempt<retries){await delay(300*2**attempt,undefined,{signal});continue}
81
+ throw new ClientError('Connection interrupted. Refresh status before retrying a write.',{code:'connection_interrupted',retryable:readOnly});
82
+ }finally{clearTimeout(timer);signal?.removeEventListener('abort',abort)}
83
+ }
84
+ }
85
+ capabilities(options){return this.request('/api/clients',undefined,{...options,method:'GET',authenticated:false,readOnly:true})}
86
+ async connect(options){
87
+ const c=await this.capabilities(options);
88
+ if(!Number.isInteger(c.protocol)||c.minimumProtocol>PROTOCOL||c.protocol<PROTOCOL)throw new ClientError('Update this client to use this server',{code:'protocol_mismatch'});
89
+ if(c.disabled?.includes(this.surface))throw new ClientError('This client is temporarily disabled. Use the web app.',{code:'client_disabled'});
90
+ return c;
91
+ }
92
+ identity(options){return this.request('/api/clients',{action:'identity'},{...options,readOnly:true})}
93
+ revoke(options){return this.request('/api/clients',{action:'revoke'},options)}
94
+ projects(options){return this.request('/api/account',undefined,{...options,method:'GET',readOnly:true})}
95
+ workspace(token,action,extra={},options){
96
+ string(token,'workspace',1800);
97
+ return this.request('/api/workspace',{...extra,action,token},options);
98
+ }
99
+ status(token,options){return this.workspace(token,'status',{}, {...options,readOnly:true})}
100
+ start(token,task,{mode='approve',requestId=randomUUID(),signal}={}){
101
+ string(task,'task');if(!['plan','brief','approve'].includes(mode))throw new ClientError('Unsupported task mode');
102
+ if(!/^[a-f0-9-]{36}$/.test(requestId))throw new ClientError('Invalid request ID');
103
+ return this.workspace(token,'run',{task,mode,planApproval:'guided',requestId},{signal});
104
+ }
105
+ approve(token,id,approved,{signal,revise}={}){
106
+ string(id,'approval ID',150);if(typeof approved!=='boolean')throw new ClientError('Approval must be explicit');
107
+ return this.workspace(token,'approve',{id,approved,...(revise?{revise:string(revise,'revision',5000)}:{})},{signal});
108
+ }
109
+ stop(token,options){return this.workspace(token,'stop',{},options)}
110
+ async files(token,options){const s=await this.status(token,options);return {files:s.files||[]}}
111
+ read(token,path,options){return this.workspace(token,'read',{path:string(path,'path',1000)}, {...options,readOnly:true})}
112
+ exportPatch(token,options){return this.workspace(token,'export',{}, {...options,readOnly:true})}
113
+ /** Polling is sequential and bounded. A run change resets dedupe; terminal includes failures. */
114
+ async watch(token,{signal,onSnapshot=()=>{},onEvent=()=>{},intervalMs=1500,maxPolls=2400}={}){
115
+ let run=null,seen=new Set();
116
+ for(let polls=0;polls<maxPolls;polls++){
117
+ if(signal?.aborted)throw abortError();
118
+ const snapshot=await this.status(token,{signal});
119
+ const id=snapshot.status?.runId||snapshot.runId||null;
120
+ if(id!==run){run=id;seen=new Set()}
121
+ for(const e of Array.isArray(snapshot.events)?snapshot.events:[]){
122
+ const key=createHash('sha256').update(JSON.stringify(e)).digest('hex');
123
+ if(!seen.has(key)){seen.add(key);await onEvent(e)}
124
+ }
125
+ if(seen.size>10000)seen=new Set([...seen].slice(-5000));
126
+ await onSnapshot(snapshot);
127
+ if(TERMINAL.has(snapshot.status?.state))return snapshot;
128
+ await delay(intervalMs,undefined,{signal}).catch(()=>{throw abortError()});
129
+ }
130
+ throw new ClientError('Watching paused. Reconnect to check the task; it was not cancelled.',{code:'watch_timeout'});
131
+ }
132
+ }
133
+ module.exports={Client,ClientError,DEFAULT_URL,PROTOCOL,TERMINAL,serverOrigin,redact,diagnostic};
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ const {createServer}=require('node:http');
3
+ const {randomBytes,createHash,timingSafeEqual}=require('node:crypto');
4
+ const {Client,ClientError,serverOrigin}=require('./index.cjs');
5
+
6
+ /** The browser receives only an opaque, short-lived handoff, never an access token. */
7
+ async function login({openExternal,baseUrl,surface='desktop',label=surface,signal,timeoutMs=180000,allowLoopback=false,fetchImpl}={}){
8
+ if(typeof openExternal!=='function')throw new ClientError('A system-browser opener is required');
9
+ const origin=serverOrigin(baseUrl,{allowLoopback});
10
+ const verifier=randomBytes(32).toString('base64url'),state=randomBytes(24).toString('base64url');
11
+ const challenge=createHash('sha256').update(verifier).digest('base64url');
12
+ let server,timer,done=false,accepting=false;
13
+ return new Promise((resolve,reject)=>{
14
+ const finish=(error,value)=>{
15
+ if(done)return;done=true;clearTimeout(timer);signal?.removeEventListener('abort',cancel);
16
+ server?.close();server?.closeAllConnections?.();error?reject(error):resolve(value);
17
+ };
18
+ const cancel=()=>finish(new ClientError('Sign-in cancelled',{code:'cancelled'}));
19
+ server=createServer(async(req,res)=>{
20
+ const headers={'Content-Type':'text/plain; charset=utf-8','Cache-Control':'no-store','Referrer-Policy':'no-referrer','Content-Security-Policy':"default-src 'none'; frame-ancestors 'none'"};
21
+ let u;try{u=new URL(req.url,'http://127.0.0.1')}catch{res.writeHead(400,headers);res.end('Invalid request');return}
22
+ const incoming=u.searchParams.get('state')||'',code=u.searchParams.get('code')||'';
23
+ if(req.method!=='GET'||u.pathname!=='/callback'||req.headers.host!==`127.0.0.1:${server.address()?.port}`||!/^[A-Za-z0-9_-]{32}$/.test(incoming)||!timingSafeEqual(Buffer.from(incoming),Buffer.from(state))){
24
+ res.writeHead(400,headers);res.end('Invalid sign-in callback');return;
25
+ }
26
+ if(accepting){res.writeHead(409,headers);res.end('Sign-in is already completing');return}
27
+ if(u.searchParams.get('error')==='access_denied'&&!code){
28
+ res.on('finish',cancel);res.writeHead(200,headers);res.end('Sign-in cancelled. Return to your app.');return;
29
+ }
30
+ if(u.searchParams.has('error')||code.length<50||code.length>3500){res.writeHead(400,headers);res.end('Invalid sign-in callback');return}
31
+ accepting=true;
32
+ try{
33
+ const client=new Client({baseUrl:origin,surface,allowLoopback,fetchImpl});
34
+ const result=await client.request('/api/clients',{action:'exchange',code,verifier},{authenticated:false,signal});
35
+ if(typeof result.token!=='string'||!result.token.startsWith('mlaid_')||!Number.isFinite(result.expires)||result.surface!==surface)throw new ClientError('Invalid sign-in response');
36
+ res.on('finish',()=>finish(null,{...result,baseUrl:origin}));
37
+ res.writeHead(200,headers);res.end('ML AI Code is connected. You can close this tab and return to your app.');
38
+ }catch(error){res.on('finish',()=>finish(error));res.writeHead(400,headers);res.end('Sign-in could not finish. Start again from the app.')}
39
+ });
40
+ server.on('error',e=>finish(new ClientError('Could not open the local sign-in listener',{code:'login_listener_failed'})));
41
+ signal?.addEventListener('abort',cancel,{once:true});
42
+ if(signal?.aborted){cancel();return}
43
+ timer=setTimeout(()=>finish(new ClientError('Sign-in timed out. Try again.',{code:'login_timeout'})),timeoutMs);
44
+ server.listen(0,'127.0.0.1',async()=>{
45
+ if(done)return;
46
+ const u=new URL('/clients/auth',origin);
47
+ for(const [k,v] of Object.entries({port:String(server.address().port),state,challenge,surface,label:String(label).slice(0,60)}))u.searchParams.set(k,v);
48
+ try{await openExternal(u.toString())}catch{finish(new ClientError('Could not open the system browser',{code:'browser_open_failed'}))}
49
+ });
50
+ });
51
+ }
52
+ module.exports={login};
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ const ORIGIN='https://mlai-mini-code.vercel.app';
3
+ const CDN='g0ngwb3xrtnagcno.public.blob.vercel-storage.com';
4
+ const CLIENTS=new Set(['desktop','vscode','jetbrains','acp']);
5
+ function version(value){
6
+ if(typeof value!=='string'||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value))throw Error('Invalid release version');
7
+ const parts=value.split('.').map(Number);if(parts.some(n=>!Number.isSafeInteger(n)))throw Error('Invalid release version');return parts;
8
+ }
9
+ function compareVersions(a,b){const x=version(a),y=version(b);for(let i=0;i<3;i++)if(x[i]!==y[i])return x[i]>y[i]?1:-1;return 0}
10
+ function validateCatalog(input){
11
+ if(!input||input.schema!==1||!Array.isArray(input.assets)||input.assets.length>80||typeof input.notes!=='string'||input.notes.length>4000)throw Error('Invalid release catalog');
12
+ const ids=new Set();
13
+ for(const a of input.assets){
14
+ if(!a||!CLIENTS.has(a.client)||typeof a.id!=='string'||!/^[a-z0-9-]{1,80}$/.test(a.id)||ids.has(a.id))throw Error('Invalid or duplicate asset');ids.add(a.id);
15
+ version(a.version);
16
+ if(!['mac-arm64','mac-x64','windows-x64','any'].includes(a.platform)||!['dmg','zip','exe','vsix','tgz'].includes(a.format)||!['preview','signed'].includes(a.trust)||typeof a.enabled!=='boolean')throw Error('Invalid asset target');
17
+ if(!Number.isSafeInteger(a.size)||a.size<1||a.size>2_000_000_000||!/^[a-f0-9]{64}$/.test(a.sha256)||!/^[A-Za-z0-9+/]{86}==$/.test(a.sha512))throw Error('Invalid asset integrity');
18
+ if(typeof a.filename!=='string'||a.filename.length>160||!/^[-a-zA-Z0-9 .]+$/.test(a.filename)||!a.filename.endsWith('.'+a.format))throw Error('Invalid asset filename');
19
+ const u=new URL(a.url);
20
+ if(u.protocol!=='https:'||u.hostname!==CDN||u.port||u.username||u.password||u.search||u.hash||!u.pathname.startsWith('/releases/clients/')||/%(?:2f|5c|2e)/i.test(u.pathname))throw Error('Untrusted release URL');
21
+ if(a.client==='desktop'?(a.platform==='any'||!['zip','dmg','exe'].includes(a.format)):(a.platform!=='any'))throw Error('Mismatched release target');
22
+ if(a.client==='vscode'&&a.format!=='vsix'||a.client==='jetbrains'&&a.format!=='zip'||a.client==='acp'&&a.format!=='tgz')throw Error('Mismatched release format');
23
+ if(a.trust==='signed'&&a.client==='desktop'&&(!a.publisher||typeof a.publisher!=='string'))throw Error('Signed desktop releases need publisher evidence');
24
+ }
25
+ return input;
26
+ }
27
+ function latestAsset(catalog,client,platform,format){
28
+ validateCatalog(catalog);
29
+ return catalog.assets.filter(a=>a.enabled&&a.client===client&&a.platform===platform&&(!format||a.format===format)).sort((a,b)=>compareVersions(b.version,a.version))[0]||null;
30
+ }
31
+ async function fetchCatalog(fetchImpl=globalThis.fetch){
32
+ const r=await fetchImpl(ORIGIN+'/api/clients/releases',{signal:AbortSignal.timeout(10000),redirect:'error',credentials:'omit',headers:{Accept:'application/json'}});
33
+ if(!r.ok)throw Error('Release service unavailable');
34
+ if(Number(r.headers.get('content-length'))>100000)throw Error('Release catalog too large');
35
+ let bytes=0;const parts=[];if(!r.body)throw Error('Empty release response');
36
+ for await(const chunk of r.body){bytes+=chunk.length;if(bytes>100000)throw Error('Release catalog too large');parts.push(Buffer.from(chunk))}
37
+ return validateCatalog(JSON.parse(Buffer.concat(parts).toString('utf8')));
38
+ }
39
+ function downloadPage(asset){return ORIGIN+'/downloads#'+(asset.client==='desktop'?'desktop':asset.client)}
40
+ function targetPlatform(platform,arch){if(platform==='darwin'&&['arm64','x64'].includes(arch))return 'mac-'+arch;if(platform==='win32'&&arch==='x64')return 'windows-x64';return null}
41
+ module.exports={ORIGIN,CDN,version,compareVersions,validateCatalog,latestAsset,fetchCatalog,downloadPage,targetPlatform};