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
package/src/cli.mjs ADDED
@@ -0,0 +1,534 @@
1
+ // mlai: ML AI Code in the terminal. The agent works in this folder on this machine; the model runs in ML AI Code's cloud.
2
+ import readline from 'node:readline';
3
+ import {spawn,execFileSync} from 'node:child_process';
4
+ import {existsSync} from 'node:fs';
5
+ import {readFile} from 'node:fs/promises';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {VERSION,DEFAULT_SERVER,home} from './home.mjs';
10
+ import {activeEngine} from './engine.mjs';
11
+ import {saveLogin,loadLogin,clearLogin} from './credentials.mjs';
12
+ import {Client,ClientError,deviceLogin} from './sdk.mjs';
13
+ import {Cloud,friendly} from './cloud.mjs';
14
+ import {Session,sandboxKind} from './session.mjs';
15
+ import {MODES as CLI_MODES,modeName,nextMode,engineMode} from './modes.mjs';
16
+ import {loadSettings} from './settings.mjs';
17
+ import * as registry from './tui/commands.mjs';
18
+ import {Chat,answerOf} from './tui/chat.mjs';
19
+ import {plainUi} from './tui/plain.mjs';
20
+ import {projectRoot} from './project.mjs';
21
+ import {createWorktree} from './worktree.mjs';
22
+ import {EXT_FLAGS,EXT_COMMANDS,extFlag} from './cli-ext.mjs';
23
+ import {worktreeFromArg} from './tui/session-ops.mjs';
24
+ import {SANDBOXES} from './sandbox.mjs';
25
+ import {restrictedForced,refusedFlag} from './restricted.mjs';
26
+ import {gitForWindows} from './winenv.mjs';
27
+ import {ensureRuntime,runtimeInfo} from './runtime.mjs';
28
+ import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt} from './render.mjs';
29
+ import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
30
+
31
+ /** Every option, for --help and shell completion (src/completion.mjs). value: the placeholder when it takes one. */
32
+ export const FLAGS=[
33
+ {flag:'--print',alias:'-p',value:'[task]',summary:'Run one task without prompts and exit (scripts, CI); reads stdin when no task'},
34
+ {flag:'--model',alias:'-m',value:'<model>',summary:'Model for this session (see /model); any model your plan includes'},
35
+ {flag:'--mode',value:'<mode>',summary:'agent (default) asks before edits and commands; plan reads and proposes; ask answers\nquestions; auto works on its own inside an OS sandbox',choices:['agent','plan','ask','auto']},
36
+ {flag:'--effort',value:'<level>',summary:'Reasoning effort: low, medium (default), high or max, where the model takes it',choices:['low','medium','high','max']},
37
+ {flag:'--fallback-model',value:'<a,b>',summary:'Models to switch to, in order, when the chosen one is overloaded or unavailable'},
38
+ {flag:'--continue',alias:'-c',summary:'Continue the latest session in this folder'},
39
+ {flag:'--resume',alias:'-r',value:'[id|name]',summary:'Resume a session by id or name; without one, pick from a list'},
40
+ {flag:'--name',value:'<name>',summary:'Name the session (resume it later with -r <name>)'},
41
+ {flag:'--fork',summary:'With -c or -r: continue in a copy, leaving the original session as it was'},
42
+ {flag:'--output-format',value:'<format>',summary:'Headless output: text (default), json (one result object) or stream-json (one\nevent per line, then the result)',choices:['text','json','stream-json']},
43
+ {flag:'--max-steps',value:'<n>',summary:'Maximum agent steps per turn, 1 to 160 (default 120)'},
44
+ {flag:'--add-dir',value:'<path>',summary:'Let the agent read another folder too (repeatable)'},
45
+ {flag:'--image',value:'<path>',summary:'Attach an image (PNG, JPEG, WebP or GIF) to the first message (repeatable)'},
46
+ {flag:'--tui',summary:'Use the full terminal interface (overrides the tui setting)'},
47
+ {flag:'--no-tui',summary:'Use the plain line-based interface'},
48
+ {flag:'--worktree',alias:'-w',value:'[name|#PR|url]',summary:'Work in a new git worktree on its own mlai/<task> branch, leaving your working\ncopy untouched; #123 or a pull request URL checks out that pull request'},
49
+ {flag:'--yes',alias:'-y',summary:'Approve all edits and commands in agent mode (headless runs)'},
50
+ {flag:'--no-sandbox',summary:'Allow auto mode without an OS sandbox (commands get your full permissions)'},
51
+ {flag:'--dangerously-skip-permissions',summary:'Run every edit and command without asking (asks you to confirm once)'},
52
+ {flag:'--cloud',summary:'Run the task in a cloud agent on this project (pushed to a new branch) and follow it here'},
53
+ {flag:'--teleport',value:'[chat]',summary:'Bring a cloud chat (its branch, changes and conversation) into a local worktree session'},
54
+ {flag:'--bg',summary:'Run the task in the background; follow it with mlai attach, list with mlai agents'},
55
+ {flag:'--bg-child',summary:'Internal: the detached process of --bg',hidden:true},
56
+ {flag:'--rc',alias:'--remote-control',summary:'Share this session with the web app and your phone: send messages, approve, stop and steer\nfrom there while the work stays here'},
57
+ {flag:'--restricted',summary:'Shared-computer mode: no shell commands, file tools stay in this project, and no\npermission or sandbox bypass'},
58
+ {flag:'--server',value:'<url>',summary:'ML AI Code server (default '+DEFAULT_SERVER+')'},
59
+ {flag:'--verbose',alias:'-v',summary:'Show command output and retries'},
60
+ {flag:'--input-format',value:'<format>',summary:'With -p: text (default) or stream-json (one {"type":"user"} message per stdin line, each a turn)',choices:['text','stream-json']},
61
+ {flag:'--json-schema',value:'<file|json>',summary:'With -p: the answer must be JSON matching this schema (structuredOutput in json output)'},
62
+ {flag:'--max-turns',value:'<n>',summary:'With -p: stop after n agent steps (result subtype error_max_turns, exit 3)'},
63
+ {flag:'--max-budget-credits',value:'<n>',summary:'With -p: stop when the run has used n credits (the server enforces the cap; exit 3)'},
64
+ {flag:'--session-id',value:'<uuid>',summary:'Use this id for a new session, or continue the session that has it'},
65
+ {flag:'--no-session-persistence',summary:'With -p: delete the session when the run ends (a -c or -r session is copied first)'},
66
+ {flag:'--allowedTools',value:'<rules>',summary:'Rules that run without asking, e.g. "Bash(npm test:*),Edit(src/**)" (repeatable)'},
67
+ {flag:'--disallowedTools',value:'<rules>',summary:'Rules that never run, e.g. "Bash(git push:*),WebFetch" (repeatable)'},
68
+ {flag:'--tools',value:'<names>',summary:'Only these built-in tools: Bash, Edit, Read, WebFetch, WebSearch, Agent ("" for none)'},
69
+ {flag:'--append-system-prompt',value:'<text>',summary:'Instructions added ahead of every task in this run'},
70
+ ...EXT_FLAGS,
71
+ {flag:'--allowed-tools',value:'<rules>',summary:'Same as --allowedTools',hidden:true},
72
+ {flag:'--disallowed-tools',value:'<rules>',summary:'Same as --disallowedTools',hidden:true},
73
+ {flag:'--json',summary:'Same as --output-format stream-json',hidden:true},
74
+ {flag:'--steps',value:'<n>',summary:'Same as --max-steps',hidden:true},
75
+ {flag:'--fix',summary:'With doctor: install the coding engine',hidden:true},
76
+ {flag:'--help',alias:'-h',summary:'Show this help'},
77
+ {flag:'--version',alias:'-V',summary:'Show the version'},
78
+ ];
79
+ const wrap=(t,w)=>t.split('\n').flatMap(l=>{const out=[];let cur='';for(const word of l.split(' ')){if(cur&&cur.length+1+word.length>w){out.push(cur);cur=word}else cur=cur?cur+' '+word:word}out.push(cur);return out});
80
+ const options=()=>{const w=Math.max(30,Math.min(process.stdout.columns||100,100)-37);return FLAGS.filter(f=>!f.hidden).map(f=>{const head=' '+(f.alias?f.alias+', ':' ')+f.flag+(f.value?' '+f.value:'');return (head.length>=36?head+'\n'+' '.repeat(36):head.padEnd(36))+wrap(f.summary.replace(/\n/g,' '),w).join('\n'+' '.repeat(36))}).join('\n')};
81
+ const HELP=`ML AI Code ${VERSION}: an agent that codes in this folder, on this machine.
82
+
83
+ Usage
84
+ mlai Start an interactive session in the current project
85
+ mlai "task" Start a session with a first task
86
+ mlai -p "task" [options] Run one task without prompts and exit (scripts, CI)
87
+ mlai -c | -r [id|name] Continue the latest session here, or resume one
88
+ mlai login | logout | whoami Sign in with your browser, sign out, show the account
89
+ mlai sessions List recent sessions
90
+ mlai --bg "task" Run a task in the background
91
+ mlai agents | attach <id> Background agents: list, follow, stop, logs (mlai agents --help)
92
+ mlai --cloud "task" Run a task in a cloud agent and follow it here
93
+ mlai --teleport [chat] Continue a cloud chat on this computer
94
+ mlai doctor [--fix] Check this machine; --fix installs the coding engine
95
+ mlai review [options] Review changes, a branch or a pull request (mlai review --help)
96
+ mlai update Update the CLI now
97
+ mlai completion <shell> Print shell completion: bash, zsh, fish or powershell
98
+ mlai cloud <command> Cloud workspaces
99
+ mlai serve Run the local engine for the Mac app and editors (owner-only socket)
100
+ mlai runner Run as a remote machine for your account (needs MLAI_RUNNER_TOKEN)
101
+ mlai remote-control [task] Start a session you can also drive from the web app and your phone
102
+
103
+ Options
104
+ ${options()}
105
+
106
+ Exit codes: 0 done, 1 failed, 2 usage, 3 needs attention, 4 sign-in needed, 5 plan limit reached,
107
+ 130 stopped.
108
+
109
+ In a session: type a task; while it works, type to steer it. y / a / n answer approvals.
110
+ Type / for commands (/help lists them), Shift+Tab switches mode, Ctrl-C stops the task,
111
+ Ctrl-C twice exits.`;
112
+
113
+ const LEGACY_MODES={guided:'agent'};
114
+ export function parseArgs(argv){
115
+ const o={_:[],mode:null,json:false,yes:false,sandbox:true,steps:120,verbose:false,server:null,print:null,fix:false,worktree:false,
116
+ model:null,effort:null,continue:false,resume:null,name:null,fork:false,outputFormat:'text',addDirs:[],skipPermissions:false,maxStepsSet:false,
117
+ fallbackModel:null,inputFormat:'text',jsonSchema:null,maxTurns:null,maxBudgetCredits:null,sessionId:null,noSessionPersistence:false,allowedTools:[],disallowedTools:[],tools:null,appendSystemPrompt:null,cloud:false,teleport:null,bg:false,bgChild:false};
118
+ o.images=[];o.tui=null;
119
+ const mode=v=>{const m=modeName(LEGACY_MODES[v]||v);if(!m)throw new UsageError('Mode must be agent, plan, ask or auto');return m};
120
+ const steps=v=>{const n=Number(v);if(!Number.isInteger(n)||n<1||n>160)throw new UsageError('--max-steps must be 1 to 160');o.steps=n;o.maxStepsSet=true};
121
+ const optional=i=>argv[i+1]!==undefined&&!argv[i+1].startsWith('-');
122
+ for(let i=0;i<argv.length;i++){
123
+ let a=argv[i],inline=null;
124
+ if(a.startsWith('--')&&a.includes('=')){inline=a.slice(a.indexOf('=')+1);a=a.slice(0,a.indexOf('='))}
125
+ const next=()=>{if(inline!==null)return inline;const v=argv[++i];if(v===undefined)throw new UsageError('Missing value for '+a);return v};
126
+ if(a==='--')o._.push(...argv.slice(i+1)),i=argv.length;
127
+ else if(a==='-p'||a==='--print')o.print=inline!==null?inline:optional(i)?argv[++i]:'-';
128
+ else if(a==='--mode')o.mode=mode(next());
129
+ else if(a==='--model'||a==='-m'){const v=next();if(!/^[\w.:/-]{1,80}$/.test(v))throw new UsageError('Unknown model '+v+'. Run /model in a session to see the list.');o.model=v}
130
+ else if(a==='--effort'){const v=next();if(!['low','medium','high','max'].includes(v))throw new UsageError('--effort must be low, medium, high or max');o.effort=v}
131
+ else if(a==='--fallback-model'){const v=next().split(',').map(x=>x.trim()).filter(Boolean);if(!v.length||v.length>5||!v.every(x=>/^[\w.:/-]{1,80}$/.test(x)))throw new UsageError('--fallback-model takes up to 5 model ids, comma separated');o.fallbackModel=v}
132
+ else if(a==='--input-format'){const v=next();if(!['text','stream-json'].includes(v))throw new UsageError('--input-format must be text or stream-json');o.inputFormat=v}
133
+ else if(a==='--json-schema')o.jsonSchema=next();
134
+ else if(a==='--max-turns'){const n=Number(next());if(!Number.isInteger(n)||n<1||n>160)throw new UsageError('--max-turns must be 1 to 160');o.maxTurns=n}
135
+ else if(a==='--max-budget-credits'){const n=Number(next());if(!(n>0&&n<=100000))throw new UsageError('--max-budget-credits must be a positive number of credits');o.maxBudgetCredits=n}
136
+ else if(a==='--session-id'){const v=next();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v))throw new UsageError('--session-id must be a UUID');o.sessionId=v.toLowerCase()}
137
+ else if(a==='--no-session-persistence')o.noSessionPersistence=true;
138
+ else if(a==='--allowedTools'||a==='--allowed-tools')o.allowedTools.push(next());
139
+ else if(a==='--disallowedTools'||a==='--disallowed-tools')o.disallowedTools.push(next());
140
+ else if(a==='--tools')o.tools=next();
141
+ else if(a==='--append-system-prompt'){const v=next();if(v.length>20000)throw new UsageError('--append-system-prompt is limited to 20,000 characters');o.appendSystemPrompt=v}
142
+ else if(a==='--continue'||a==='-c')o.continue=true;
143
+ else if(a==='--resume'||a==='-r')o.resume=inline!==null?inline:optional(i)?argv[++i]:'';
144
+ else if(a==='--name')o.name=next();
145
+ else if(a==='--fork'||a==='--fork-session')o.fork=true;
146
+ else if(a==='--output-format'){const v=next();if(!['text','json','stream-json'].includes(v))throw new UsageError('--output-format must be text, json or stream-json');o.outputFormat=v;o.json=v!=='text'}
147
+ else if(a==='--json'){o.outputFormat='stream-json';o.json=true}
148
+ else if(a==='--max-steps'||a==='--steps')steps(next());
149
+ else if(a==='--add-dir'){const d=path.resolve(next());if(!existsSync(d))throw new UsageError('--add-dir: no folder '+d);o.addDirs.push(d)}
150
+ else if(a==='--image'){const f=path.resolve(next());if(!/\.(png|jpe?g|webp|gif)$/i.test(f))throw new UsageError('--image takes a PNG, JPEG, WebP or GIF file');if(!existsSync(f))throw new UsageError('--image: no file '+f);o.images.push(f)}
151
+ else if(a==='--tui')o.tui='full';
152
+ else if(a==='--no-tui')o.tui='plain';
153
+ else if(a==='--yes'||a==='-y')o.yes=true;
154
+ else if(a==='--no-sandbox')o.sandbox=false;
155
+ else if(a==='--dangerously-skip-permissions')o.skipPermissions=true;
156
+ else if(a==='--restricted')o.restricted=true;
157
+ else if(a==='--fix')o.fix=true;
158
+ else if(a==='--worktree'||a==='-w')o.worktree=inline!==null?inline:argv[i+1]!==undefined&&/^(#\d+|https?:\/\/\S+\/(pull|merge_requests)\/\d+)/.test(argv[i+1])?argv[++i]:true;
159
+ else if(a==='--server')o.server=next();
160
+ // CLI2 cloud and background (tui/cloud-cli.mjs, tui/bg.mjs).
161
+ else if(a==='--cloud')o.cloud=true;
162
+ else if(a==='--teleport')o.teleport=inline!==null?inline:optional(i)?argv[++i]:'';
163
+ else if(a==='--bg')o.bg=true;
164
+ else if(a==='--bg-child')o.bgChild=true;
165
+ else if(a==='--rc'||a==='--remote-control')o.rc=true; // remote control (tui/remote.mjs)
166
+ else if(a==='-v'||a==='--verbose')o.verbose=true;
167
+ else if(a==='-h'||a==='--help')o._.unshift('help');
168
+ else if(a==='--version'||a==='-V')o._.unshift('version');
169
+ else if(a.startsWith('-')&&a.length>1&&(()=>{try{return extFlag(o,a,next)}catch(e){throw new UsageError(e.message)}})());
170
+ else if(a.startsWith('-')&&a.length>1)throw new UsageError('Unknown option '+a+'. Run mlai --help.');
171
+ else o._.push(a);
172
+ }
173
+ if(o.fork&&!o.continue&&o.resume===null)throw new UsageError('--fork goes with -c or -r.');
174
+ if(o.cloud&&o.teleport!==null)throw new UsageError('Use --cloud or --teleport, not both.');
175
+ if(o.teleport!==null&&(o.continue||o.resume!==null))throw new UsageError('--teleport starts its own session; leave out -c and -r.');
176
+ if(o.bg&&o.print!==null)throw new UsageError('--bg runs on its own; leave out -p.');
177
+ if(o.rc&&(o.bg||o.cloud))throw new UsageError('--rc shares an interactive session; leave out '+(o.bg?'--bg':'--cloud')+'. Follow a background run with mlai attach.');
178
+ if(o.sessionId&&(o.continue||o.resume!==null))throw new UsageError('--session-id picks the session; leave out -c and -r.');
179
+ if(o.inputFormat==='stream-json'&&o.outputFormat!=='stream-json')throw new UsageError('--input-format stream-json needs --output-format stream-json.');
180
+ try{o.toolRules=toolRules(o);if(o.jsonSchema)loadSchema(o.jsonSchema)}catch(e){if(e instanceof HeadlessError)throw new UsageError(e.message);throw e}
181
+ return o;
182
+ }
183
+ class UsageError extends Error{}
184
+ const COMMANDS=['help','version','login','logout','whoami','sessions','resume','doctor','cloud','serve','runner','acp','remote-control'];
185
+
186
+ async function readStdin(){let s='';for await(const c of process.stdin)s+=c;return s}
187
+ function openBrowser(url){
188
+ const cmd=process.platform==='darwin'?'open':process.platform==='win32'?'cmd':'xdg-open';
189
+ const args=process.platform==='win32'?['/c','start','',url]:[url];
190
+ try{const p=spawn(cmd,args,{stdio:'ignore',detached:true});p.on('error',()=>{});p.unref()}catch{}
191
+ }
192
+ async function serverFor(o){
193
+ const saved=await loadLogin().catch(()=>null);
194
+ return (o.server||process.env.MLAI_SERVER||saved?.server||DEFAULT_SERVER).replace(/\/$/,'');
195
+ }
196
+ async function cloudFor(o){
197
+ const login=await loadLogin();
198
+ if(!login?.token)throw Object.assign(new Error('Not signed in. Run `mlai login`.'),{exit:EXIT.auth});
199
+ return new Cloud({server:await serverFor(o),token:login.token});
200
+ }
201
+ const loopback=u=>/^http:\/\/(127\.0\.0\.1|\[::1\])(:\d+)?$/.test(u);
202
+
203
+ export async function main(argv=process.argv.slice(2)){
204
+ if(['update','completion','__install','__complete'].includes(argv[0]))return (await import('./distribution.mjs')).distMain(argv);
205
+ await (await import('./distribution.mjs')).startup(argv);
206
+ // `mlai cloud ...` passes every argument, including --help, to the cloud workspace CLI.
207
+ if(argv[0]==='cloud')return await cloud(argv.slice(1));
208
+ // `mlai review ...` has its own flags (src/tui/review-cli.mjs).
209
+ // `mlai agents ...` and `mlai attach <id>`: background agents (src/tui/agents-cli.mjs), with their own flags.
210
+ if(argv[0]==='agents'||argv[0]==='attach')return await agentsCli(argv);
211
+ if(argv[0]==='review')return await (await import('./tui/review-cli.mjs')).reviewMain(argv.slice(1),{cloud:o=>cloudFor(o),color:palette(process.stdout.isTTY&&!process.env.NO_COLOR&&!argv.includes('--json'))});
212
+ if(EXT_COMMANDS[argv[0]])return await EXT_COMMANDS[argv[0]](argv.slice(1));
213
+ let o;
214
+ try{o=parseArgs(argv)}catch(e){process.stderr.write(e.message+'\n');return EXIT.usage}
215
+ const cmd=COMMANDS.includes(o._[0])?o._.shift():null;
216
+ const c=palette(process.stdout.isTTY&&!process.env.NO_COLOR&&!o.json);
217
+ const err=palette(process.stderr.isTTY&&!process.env.NO_COLOR);
218
+ try{
219
+ if(cmd==='help'){process.stdout.write(HELP+'\n');return 0}
220
+ if(cmd==='version'){process.stdout.write(VERSION+'\n');return 0}
221
+ if(cmd==='login')return await login(o);
222
+ if(cmd==='logout')return await logout(o);
223
+ if(cmd==='whoami'){const me=await (await cloudFor(o)).whoami();const l=await loadLogin();process.stdout.write(o.json?JSON.stringify({...me,server:await serverFor(o)})+'\n':`Signed in on this device as account ${me.owner}\nDevice: ${me.label||'this laptop'} · server ${await serverFor(o)} · stored in ${l?.store||'?'}\n`);return 0}
224
+ if(cmd==='sessions')return await sessions(o,c);
225
+ if(cmd==='doctor')return await doctor(o,c);
226
+ if(cmd==='cloud')return await cloud(argv.slice(argv.indexOf('cloud')+1));
227
+ if(cmd==='serve'){
228
+ const {serve}=await import('./server.mjs');const s=await serve();
229
+ process.stderr.write('ML AI Code engine listening on '+s.socket+'\n');
230
+ await new Promise(r=>{process.once('SIGINT',r);process.once('SIGTERM',r)});await s.close();return 0;
231
+ }
232
+ if(cmd==='runner')return await (await import('./runner.mjs')).runnerMain();
233
+ if(cmd==='acp')return await (await import('./tui/acp.mjs')).acpMain(o);
234
+ // `mlai resume [id] [task]` is the older spelling of -r; without an id it continues the latest session here.
235
+ if(cmd==='resume'){const id=o._.shift();if(id)o.resume=id;else o.continue=true}
236
+ if(cmd==='remote-control')o.rc=true; // `mlai remote-control [task]`: an interactive session shared with the web and phone
237
+ const streamIn=o.inputFormat==='stream-json';
238
+ let task=o.print!==null?(o.print==='-'?(streamIn?null:await readStdin()):o.print):o._.join(' ').trim()||null;
239
+ if(o.cloud)return await cloudRun(o,c,err,task);
240
+ if(o.bg)return await backgroundRun(o,err,task);
241
+ const headlessRun=o.print!==null||!process.stdin.isTTY||streamIn;
242
+ if(o.teleport!==null){const s=await teleportRun(o,err,{interactive:!headlessRun});if(!s)return EXIT.usage;if(headlessRun&&task?.trim())return await headless(o,c,err,task.trim(),s);if(headlessRun){process.stdout.write(s.meta.id+'\n');return 0}return await interactive(o,c,s,task)}
243
+ if(headlessRun&&!streamIn&&!task&&!process.stdin.isTTY&&o.print===null)task=await readStdin();
244
+ if(headlessRun&&!streamIn&&!task?.trim())throw new UsageError('Give a task: mlai -p "what to do"');
245
+ if(headlessRun&&o.rc)throw new UsageError('Remote control needs an interactive terminal. Run mlai --rc in a terminal, or use --bg for unattended work.');
246
+ // Restricted mode (src/restricted.mjs): the flag, or forced by the administrator for everyone on this computer.
247
+ const forced=restrictedForced();if(forced)o.restricted=true;
248
+ if(o.restricted){const no=refusedFlag(o);if(no){process.stderr.write(no+(forced?' It is forced on this computer ('+forced+').':'')+'\n');return EXIT.usage}}
249
+ if(o.skipPermissions&&!await confirmSkip(o,headlessRun))return EXIT.usage;
250
+ const s=await chooseSession(o,task,err,{interactive:!headlessRun});
251
+ if(headlessRun)return await headless(o,c,err,task?.trim()||null,s);
252
+ return await interactive(o,c,s,task);
253
+ }catch(e){
254
+ if(e instanceof UsageError||e instanceof HeadlessError){process.stderr.write(e.message+'\n');return EXIT.usage}
255
+ const message=friendly(e);
256
+ if(o.json)process.stdout.write(JSON.stringify({type:'result',state:'error',error:message,code:e.code||null,exitCode:e.exit||codeFor(e)})+'\n');
257
+ else process.stderr.write(err.red('error: ')+message+'\n');
258
+ if(o.bgChild&&o.resume)await (await import('./tui/bg.mjs')).finishBackground(path.join(home(),'sessions',o.resume),{state:'error',exitCode:e.exit||codeFor(e)}).catch(()=>{});
259
+ return e.exit||codeFor(e);
260
+ }
261
+ }
262
+ function codeFor(e){
263
+ if(e instanceof ClientError){if(e.status===401)return EXIT.auth;if(e.code==='billing_limit'||e.status===402)return EXIT.billing}
264
+ return EXIT.error;
265
+ }
266
+
267
+ async function login(o){
268
+ const server=(o.server||process.env.MLAI_SERVER||DEFAULT_SERVER).replace(/\/$/,'');
269
+ const label=(os.hostname().replace(/\.local$/,'')||'Laptop').slice(0,60);
270
+ process.stdout.write('Opening your browser to sign in to ML AI Code...\n');
271
+ const result=await deviceLogin({baseUrl:server,surface:'laptop',label,allowLoopback:loopback(server),openExternal:async url=>{
272
+ process.stdout.write('If it does not open, visit:\n '+url+'\n');if(!process.env.MLAI_NO_BROWSER)openBrowser(url);
273
+ }});
274
+ const store=await saveLogin({server,token:result.token,expires:result.expires,deviceId:result.deviceId||result.device?.id||null,label});
275
+ process.stdout.write(`Signed in. This device stays signed in until ${new Date(result.expires).toLocaleDateString()}; the credential is in your ${store==='keychain'?'system keychain':'~/.mlai folder (owner-only)'}.\n`);
276
+ return 0;
277
+ }
278
+ async function logout(o){
279
+ const l=await loadLogin().catch(()=>null);
280
+ if(l?.token&&l.store!=='env'){
281
+ const server=await serverFor(o);
282
+ try{await new Client({baseUrl:server,surface:'laptop',version:VERSION,tokenProvider:()=>l.token,allowLoopback:loopback(server)}).revoke()}catch{}
283
+ }
284
+ await clearLogin();process.stdout.write('Signed out on this device.\n');return 0;
285
+ }
286
+ async function sessions(o,c){
287
+ const all=await Session.list();
288
+ if(o.json){process.stdout.write(JSON.stringify(all.map(m=>({id:m.id,folder:m.folder,root:m.root,mode:m.mode,title:m.title,turns:m.turns.length,tokens:m.turns.reduce((a,t)=>a+(t.tokens||0),0),updated:m.updated||m.created})))+'\n');return 0}
289
+ if(!all.length){process.stdout.write('No sessions yet. Run mlai in a project folder.\n');return 0}
290
+ for(const m of all.slice(0,30)){
291
+ const tokens=m.turns.reduce((a,t)=>a+(t.tokens||0),0),last=m.turns.at(-1);
292
+ process.stdout.write(`${c.bold(m.id.slice(0,8))} ${m.folder.padEnd(18).slice(0,18)} ${String(m.title||'').slice(0,48).padEnd(48)} ${c.dim(m.turns.length+' turn'+(m.turns.length===1?'':'s')+' · '+fmt(tokens)+' tokens · '+(last?.state||'new')+' · '+String(m.updated||m.created).slice(0,16).replace('T',' '))}\n`);
293
+ }
294
+ process.stdout.write(c.dim('Continue one with: mlai resume <id>')+'\n');return 0;
295
+ }
296
+ async function doctor(o,c){
297
+ const rows=[];const add=(ok,label,detail)=>rows.push({ok,label,detail});
298
+ const major=Number(process.versions.node.split('.')[0]);add(major>=20,'Node.js',process.versions.node+(major>=20?'':' (20 or newer needed)'));
299
+ const server=await serverFor(o);
300
+ try{
301
+ const caps=await new Client({baseUrl:server,surface:'laptop',version:VERSION,allowLoopback:loopback(server)}).capabilities();
302
+ add(true,'Server',server);add((caps.execution||[]).includes('laptop'),'Laptop runs',(caps.execution||[]).includes('laptop')?'enabled':'not enabled on this server yet');
303
+ }catch(e){add(false,'Server',server+': '+friendly(e))}
304
+ const l=await loadLogin().catch(()=>null);
305
+ if(!l?.token)add(false,'Sign-in','not signed in (run mlai login)');
306
+ else try{const me=await new Cloud({server,token:l.token}).whoami();add(true,'Sign-in',(me.label||'device')+' · '+l.store+(l.expires?' · until '+new Date(l.expires).toLocaleDateString():''))}catch(e){add(false,'Sign-in',friendly(e))}
307
+ let git='';try{git=execFileSync('git',['--version'],{encoding:'utf8'}).trim()}catch{}add(Boolean(git),'git',git||'not found');
308
+ try{const h=await activeEngine();add(true,'Coding harness',h.source==='updated'?'updated '+h.version.slice(0,8):h.source==='custom'?'MLAI_WORKER_DIR='+h.dir:'bundled '+h.version.slice(0,8))}catch(e){add(false,'Coding harness',e.message)}
309
+ const rt=await runtimeInfo();
310
+ if(process.env.MLAI_PYTHON)add(existsSync(process.env.MLAI_PYTHON),'Coding engine','MLAI_PYTHON='+process.env.MLAI_PYTHON);
311
+ else if(rt.ready)add(true,'Coding engine',rt.dir);
312
+ else if(o.fix){try{await ensureRuntime({onProgress:m=>process.stdout.write(c.dim(m+'...')+'\n')});add(true,'Coding engine','installed')}catch(e){add(false,'Coding engine',e.message)}}
313
+ else add(false,'Coding engine','not installed yet; it installs on first run, or run mlai doctor --fix'+(rt.uv?' (uv found)':rt.python3?' (python3 found)':' (needs uv or python3)'));
314
+ if(process.platform==='win32'){const g=gitForWindows();add(Boolean(g),'Git Bash',g?path.join(g,'bin','bash.exe'):'not found: install Git for Windows from https://git-scm.com/download/win')}
315
+ const kind=sandboxKind();add(SANDBOXES.includes(kind),'OS sandbox',kind==='seatbelt'?'macOS Seatbelt (network off is enforced by the OS)':kind==='bwrap'?'bubblewrap (network off is enforced by the OS)':kind==='windows'?'Windows restricted token (writes limited; reads not limited; network off is the engine check only)':kind==='off'?'turned off (MLAI_SANDBOX=off)':'none: auto mode needs --no-sandbox; guided mode still works');
316
+ {const f=restrictedForced();if(f)add(true,'Restricted mode','on for everyone here ('+f+')')}
317
+ add(true,'Local data',home());
318
+ if(o.json)process.stdout.write(JSON.stringify(rows)+'\n');
319
+ else for(const r of rows)process.stdout.write((r.ok?c.green('ok '):c.yellow('!! '))+r.label.padEnd(15)+' '+r.detail+'\n');
320
+ return rows.every(r=>r.ok||['Coding engine','OS sandbox','Laptop runs'].includes(r.label))?0:1;
321
+ }
322
+ async function cloud(args){
323
+ const here=path.dirname(fileURLToPath(import.meta.url));
324
+ const bin=[path.join(here,'..','vendor','cloud-cli','mlai.mjs'),path.join(here,'..','..','cli','bin','mlai.mjs')].find(existsSync);
325
+ if(!bin)throw new Error('Cloud commands are not included in this install.');
326
+ return await new Promise(resolve=>{const p=spawn(process.execPath,[bin,...args],{stdio:'inherit'});p.on('exit',code=>resolve(code??1))});
327
+ }
328
+
329
+ /** Flags that override settings (settings.mjs), and the settings for a session's folder. */
330
+ const flagSettings=o=>({model:o.model||undefined,mode:o.mode||undefined,effort:o.effort||undefined,maxSteps:o.maxStepsSet?o.steps:undefined,fallbackModel:o.fallbackModel||undefined});
331
+ function settingsFor(o,s,err){
332
+ const st=loadSettings({root:s.meta.parent||s.meta.root,flags:flagSettings(o)});
333
+ for(const w of st.warnings)process.stderr.write(err.yellow('settings: ')+w+'\n');
334
+ return st;
335
+ }
336
+ const chatFlags=(o,st)=>({mode:o.mode,model:o.model,effort:o.effort,maxSteps:st.maxSteps,addDirs:o.addDirs,sandbox:o.sandbox,skipPermissions:o.skipPermissions,
337
+ fallbackModel:o.fallbackModel||st.fallbackModel,toolRules:o.toolRules||null,appendSystemPrompt:o.appendSystemPrompt||'',restricted:Boolean(o.restricted)});
338
+ /** --dangerously-skip-permissions: confirmed once (tui/cmd-extensibility.mjs), never silently without a TTY. */
339
+ async function confirmSkip(o,headlessRun){
340
+ const ext=await import('./tui/cmd-extensibility.mjs').catch(()=>null);
341
+ const ui=plainUi({ask:q=>askLine(q)});
342
+ if(ext?.confirmSkipPermissions){if(!await ext.confirmSkipPermissions(ui,{yes:o.yes}))return false}
343
+ else if(headlessRun?!o.yes:!await ui.confirm('Run every edit and command without asking?',{default:false})){process.stderr.write('--dangerously-skip-permissions needs --yes without a terminal.\n');return false}
344
+ o.yes=true;return true;
345
+ }
346
+ function askLine(q){
347
+ if(!process.stdin.isTTY)return Promise.resolve(null);
348
+ return new Promise(r=>{const rl=readline.createInterface({input:process.stdin,output:process.stderr,terminal:true});let done=false;rl.question(q,a=>{done=true;rl.close();r(a)});rl.on('close',()=>{if(!done)r(null)})});
349
+ }
350
+
351
+ /** The session for this run: -c, -r [id|name] (a picker without one), --fork, --name, or a new one. */
352
+ async function chooseSession(o,task,err,{interactive}){
353
+ const root=(await projectRoot(process.cwd()).catch(()=>({root:process.cwd()}))).root;
354
+ let meta=null;
355
+ if(o.sessionId){
356
+ meta=(await Session.list()).find(m=>m.id===o.sessionId)||null;
357
+ if(!meta){const s=await newSession(o,task,err,root);if(o.name){s.meta.title=String(o.name).replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,80);s.meta.renamed=true;await s.save()}return s}
358
+ }else if(o.continue){
359
+ meta=(await Session.list()).find(m=>m.root===root||m.parent===root);
360
+ if(!meta)throw new UsageError('No session for this folder yet. Run mlai to start one.');
361
+ }else if(o.resume!==null){
362
+ const {findSessions,sessionRow}=await import('./tui/cmd-core.mjs');
363
+ const found=await findSessions(o.resume,{root:o.resume?null:root});
364
+ if(!found.length)throw new UsageError(o.resume?'No session '+o.resume+'. Run mlai sessions.':'No session for this folder yet. Run mlai to start one.');
365
+ if(found.length===1||!interactive)meta=found[0];
366
+ else{const pick=await plainUi({ask:q=>askLine(q),write:t=>process.stderr.write(t)}).pick(found.slice(0,30).map(sessionRow),{title:'Resume a session'});if(!pick)throw new UsageError('No session chosen.');meta=found.find(m=>m.id===pick.value)}
367
+ }
368
+ let s;
369
+ // --no-session-persistence never deletes a saved session: it works on a copy.
370
+ if(meta)s=o.fork||o.noSessionPersistence?await Chat.fork(meta.id):await Session.open(meta.id);
371
+ else s=await newSession(o,task,err,root);
372
+ if(o.name){s.meta.title=String(o.name).replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,80);s.meta.renamed=true;await s.save()}
373
+ if(meta&&o.fork&&!o.noSessionPersistence)process.stderr.write(err.dim('Forked '+meta.id.slice(0,8)+' into '+s.meta.id.slice(0,8))+'\n');
374
+ return s;
375
+ }
376
+ /** A new session in this folder, or in its own worktree with --worktree. */
377
+ async function newSession(o,task,err,root){
378
+ const mode=engineMode(o.mode||loadSettings({root}).mode);
379
+ let s;
380
+ if(!o.worktree)s=await Session.create({cwd:process.cwd(),mode,id:o.sessionId||null});
381
+ else{
382
+ const {root:r,git}=await projectRoot(process.cwd());
383
+ if(!git)throw new UsageError('--worktree needs a git repository.');
384
+ let tree;try{tree=typeof o.worktree==='string'?await worktreeFromArg(r,o.worktree,{task}):await createWorktree(r,{name:task||undefined})}catch(e){throw new UsageError(e.message)}
385
+ process.stderr.write('Worktree '+tree.path+' on branch '+tree.branch+(tree.copied.length?' (copied '+tree.copied.join(', ')+')':'')+'\n');
386
+ s=await Session.create({mode,worktree:tree,id:o.sessionId||null});
387
+ }
388
+ s.meta.cliMode=modeName(o.mode)||modeName(loadSettings({root}).mode)||'agent';if(o.model)s.meta.model=o.model;await s.save();
389
+ return s;
390
+ }
391
+ async function headless(o,c,err,task,s){
392
+ const cloud=await cloudFor(o);
393
+ const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
394
+ if(o.model)await chat.setModel(o.model).catch(e=>{throw new UsageError(e.message)});
395
+ else await chat.loadModels();
396
+ if(o.effort)await chat.setEffort(o.effort).catch(e=>{throw new UsageError(e.message)});
397
+ const inputs=o.inputFormat==='stream-json'?streamInputs(stdinLines()):[{text:task,files:o.images||[]}];
398
+ const code=await runHeadless(o,{s,chat,err,inputs});
399
+ // mlai --bg: record how the background run ended (tui/bg.mjs).
400
+ if(o.bgChild){const st=await readFile(path.join(s.dir,'status.json'),'utf8').then(JSON.parse).catch(()=>({}));await (await import('./tui/bg.mjs')).finishBackground(s.dir,{state:code===0?'completed':st.state&&!['running','starting'].includes(st.state)?st.state:'failed',exitCode:code}).catch(()=>{})}
401
+ return code;
402
+ }
403
+
404
+ async function interactive(o,c,s,first){
405
+ const cloud=await cloudFor(o);
406
+ const err=palette(process.stderr.isTTY&&!process.env.NO_COLOR);
407
+ const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
408
+ await registry.loadCommands({warn:m=>process.stderr.write(err.yellow(m)+'\n')});
409
+ chat.loadModels().then(()=>{if(o.model)return chat.setModel(o.model)}).catch(e=>process.stderr.write(err.yellow(e.message)+'\n'));
410
+ const tui=await import('./tui/app.mjs').catch(()=>null);
411
+ if(tui?.useTui?.(process.env,process.stdout,process.stdin,{...settings,tui:o.tui||settings?.tui}))
412
+ return await withRemote(chat,()=>tui.runTui({session:s,settings,cloud,flags:o,first,chat,send:(t,opts)=>chat.send(t,opts),makeCtx:ui=>remoteOn(o,chat,chat.ctx(ui)),onSessionChange:n=>chat.setSession(n)}));
413
+ return await withRemote(chat,()=>plainLoop(o,c,chat,first));
414
+ }
415
+ /* Remote control (--rc, `mlai remote-control`, /remote-control): tui/remote.mjs; stops when the session ends. */
416
+ function remoteOn(o,chat,ctx){
417
+ if(o.rc)import('./tui/remote.mjs').then(async m=>ctx.out(m.remoteBanner(await m.startRemote({chat,ctx,cloud:ctx.server})))).catch(e=>ctx.out('Remote control did not start: '+friendly(e)));
418
+ return ctx;
419
+ }
420
+ async function withRemote(chat,fn){
421
+ try{return await fn()}finally{if(chat.remote)await chat.remote.stop().catch(()=>{})}
422
+ }
423
+
424
+ /** The line-based session (no full-screen TUI): readline, slash commands from the registry, approvals, steering. */
425
+ async function plainLoop(o,c,chat,first){
426
+ const out=t=>{readline.clearLine(process.stdout,0);readline.cursorTo(process.stdout,0);process.stdout.write(t+'\n')};
427
+ const kind=sandboxKind(),sandboxed=SANDBOXES.includes(kind);
428
+ const banner=()=>out(c.bold('ML AI Code')+c.dim(` · ${chat.session.meta.folder} · ${chat.modelLabel} · ${chat.mode} mode · sandbox ${sandboxed?kind:'none'}`));
429
+ banner();
430
+ out(c.dim('Type a task. While it works, type to steer it. Ctrl-C stops. Type / for commands, Shift+Tab switches mode.'));
431
+ let ctx=null;
432
+ const rl=readline.createInterface({input:process.stdin,output:process.stdout,terminal:true,historySize:500,
433
+ completer:(line,cb)=>{if(!line.startsWith('/'))return cb(null,[[],line]);registry.complete(ctx,line).then(l=>cb(null,[l,line]),()=>cb(null,[[],line]))}});
434
+ let pending=null,lastCtrlC=0,question=null;
435
+ const prompt=()=>{rl.setPrompt(question?question.text:pending?c.yellow('approve? [y]es / [a]ll / [n]o › '):chat.running?c.dim('steer › '):c.cyan(chat.mode==='agent'?'› ':chat.mode+' › '));rl.prompt(true)};
436
+ const ask=text=>new Promise(resolve=>{question={text,resolve};prompt()});
437
+ const ui=plainUi({write:t=>{for(const l of String(t).replace(/\n$/,'').split('\n'))out(l)},writeErr:t=>out(String(t).replace(/\n$/,'')),ask,color:c});
438
+ ctx=remoteOn(o,chat,chat.ctx({...ui,setMode:()=>prompt(),setSession:()=>{},dismissApproval:id=>{if(pending?.id===id){pending=null;prompt()}}}));
439
+ const onEvent=e=>{
440
+ if(e.type==='approval'){
441
+ if(o.yes){chat.session.decide(e.id,'approve_all').catch(()=>{});return}
442
+ pending=e;out(approvalView(e,c).text);prompt();return;
443
+ }
444
+ const line=renderEvent(e,{c,verbose:o.verbose});if(line){out(line);prompt()}
445
+ };
446
+ let bound=chat.session;bound.on('event',onEvent);
447
+ chat.on('session',n=>{bound.off('event',onEvent);bound=n;n.on('event',onEvent);banner();prompt()});
448
+ const run=async task=>{
449
+ prompt();
450
+ try{
451
+ const r=await chat.send(task,{onProgress:m=>out(c.dim(m+'...'))});
452
+ if(r.state!=='completed'&&r.error)out(c.yellow(r.error));
453
+ out(summaryLine(r,c));
454
+ // Plan mode ends with an offer to build the plan (like the app's Build it).
455
+ if(chat.mode==='plan'&&r.state==='completed'&&await ui.confirm('Build it? Switches to agent mode.',{default:false})){await chat.setMode('agent');pending=null;return run('Build the plan you proposed above.')}
456
+ }catch(e){out(c.red('error: ')+friendly(e))}
457
+ finally{pending=null;prompt()}
458
+ };
459
+ const handle=async result=>{
460
+ if(result?.exit){rl.close();return}
461
+ if(typeof result?.send==='string'&&result.send.trim())await run(result.send.trim());
462
+ };
463
+ process.stdin.on('keypress',(_s,k)=>{
464
+ if(k?.name==='tab'&&k.shift&&!question&&!pending){const m=nextMode(chat.mode,{sandbox:sandboxed||!o.sandbox});chat.setMode(m).then(()=>{out(c.dim('Mode: '+m+' · '+CLI_MODES[m].summary));prompt()}).catch(()=>{})}
465
+ });
466
+ rl.on('SIGINT',()=>{
467
+ if(question){const q=question;question=null;q.resolve(null);prompt();return}
468
+ if(chat.running){out(c.yellow('Stopping...'));chat.session.cancel().catch(()=>{});return}
469
+ if(Date.now()-lastCtrlC<1500){rl.close();return}
470
+ lastCtrlC=Date.now();out(c.dim('Press Ctrl-C again to exit.'));prompt();
471
+ });
472
+ rl.on('line',async raw=>{
473
+ if(question){const q=question;question=null;q.resolve(raw);return}
474
+ const line=raw.trim();
475
+ if(pending){
476
+ const v=line.toLowerCase();const verdict=v==='y'||v==='yes'?'approve':v==='a'||v==='all'?'approve_all':v==='n'||v==='no'?'reject':null;
477
+ if(!verdict){out('Answer y, a or n.');prompt();return}
478
+ const p=pending;pending=null;await chat.session.decide(p.id,verdict).catch(e=>out(c.red(e.message)));prompt();return;
479
+ }
480
+ if(!line){prompt();return}
481
+ if(line.startsWith('!')&&line.length>1){const r=await ctx.exec(line.slice(1));const t=(r.stdout+r.stderr).trimEnd();if(t)out(t);if(r.code)out(c.dim('exit '+r.code));prompt();return}
482
+ const input=registry.rewrite(line);
483
+ if(input.startsWith('/')){
484
+ const d=await registry.dispatch(ctx,input);
485
+ if(d.handled){await handle(d.result);if(!rl.closed)prompt();return}
486
+ }
487
+ if(chat.running){await chat.session.steer(line);out(c.dim('Sent to the agent.'));prompt();return}
488
+ await run(input);
489
+ });
490
+ const closed=new Promise(r=>rl.on('close',r));
491
+ if(first)run(first);else prompt();
492
+ await closed;
493
+ if(chat.running)await chat.session.cancel().catch(()=>{});
494
+ return 0;
495
+ }
496
+
497
+ // ---- CLI2 cloud and background agents (owner: agents_hub_engineer) ----
498
+ const renderDeps=()=>({renderEvent,approvalView,summaryLine,exitCode});
499
+ async function agentsCli(argv){
500
+ const [{agentsMain,attachMain},{findSessions}]=await Promise.all([import('./tui/agents-cli.mjs'),import('./tui/cmd-core.mjs')]);
501
+ const c=palette(process.stdout.isTTY&&!process.env.NO_COLOR&&!argv.includes('--json'));
502
+ const deps={Session,sessionsDir:path.join(home(),'sessions'),findSessions,render:renderDeps(),c,out:t=>process.stdout.write(t+'\n'),stdin:process.stdin,stdout:process.stdout};
503
+ try{return argv[0]==='attach'?await attachMain(argv.slice(1),deps):await agentsMain(argv.slice(1),deps)}
504
+ catch(e){process.stderr.write((e.usage?'':'error: ')+friendly(e)+'\n');return e.usage?EXIT.usage:EXIT.error}
505
+ }
506
+ /** mlai --bg "task": the session is chosen as usual (-c, -r, --worktree, --name work), then runs in a detached process. */
507
+ async function backgroundRun(o,err,task){
508
+ if(!task?.trim())throw new UsageError('Give a task: mlai --bg "what to do"');
509
+ await cloudFor(o);
510
+ const s=await chooseSession(o,task,err,{interactive:false});
511
+ const r=await (await import('./tui/bg.mjs')).startBackground(s,task.trim(),o);
512
+ if(o.json)process.stdout.write(JSON.stringify({type:'background',sessionId:r.id,pid:r.pid,log:r.log})+'\n');
513
+ else{process.stdout.write(r.id+'\n');process.stderr.write('Working in the background. Follow it: mlai attach '+r.id.slice(0,8)+' · list: mlai agents\n'+(o.yes?'':err.dim('It waits for you at each approval; mlai attach answers them. Pass --yes to approve everything.')+'\n'))}
514
+ return 0;
515
+ }
516
+ /** mlai --cloud "task" [-p] [--bg]: a cloud agent on this project, followed here (or started and left with --bg). */
517
+ async function cloudRun(o,c,err,task){
518
+ if(o.print==='-'||(!task&&!process.stdin.isTTY))task=task||await readStdin();
519
+ if(!task?.trim())throw new UsageError('Give a task: mlai --cloud "what to do"');
520
+ const cloud=await cloudFor(o);const ctl=new AbortController();const onInt=()=>ctl.abort();process.once('SIGINT',onInt);
521
+ try{
522
+ return await (await import('./tui/cloud-cli.mjs')).cloudMain(task.trim(),{cloud,out:t=>process.stdout.write(t+'\n'),log:t=>process.stderr.write(t+'\n'),
523
+ ask:process.stdin.isTTY&&o.print===null&&!o.json?q=>askLine(q):null,renderEvent,c:err,json:o.json,detach:o.bg,signal:ctl.signal});
524
+ }finally{process.off('SIGINT',onInt)}
525
+ }
526
+ /** mlai --teleport [chat]: the cloud chat's branch and changes in a new worktree, its conversation as context. */
527
+ async function teleportRun(o,err,{interactive}){
528
+ const cloud=await cloudFor(o);
529
+ const pick=interactive?(rows,opts)=>plainUi({ask:q=>askLine(q),write:t=>process.stderr.write(t)}).pick(rows,opts):null;
530
+ const s=await (await import('./tui/cloud-cli.mjs')).teleportMain(o.teleport,{cloud,log:t=>process.stderr.write(t+'\n'),c:err,pick,createWorktree,createSession:a=>Session.create(a)});
531
+ if(s&&(o.mode||o.model)){if(o.mode)s.meta.cliMode=modeName(o.mode);if(o.model)s.meta.model=o.model;await s.save()}
532
+ return s;
533
+ }
534
+ // ---- end CLI2 cloud and background agents ----
package/src/cloud.mjs ADDED
@@ -0,0 +1,29 @@
1
+ import {Client,ClientError} from './sdk.mjs';
2
+ import {VERSION} from './home.mjs';
3
+ const loopback=u=>/^http:\/\/(127\.0\.0\.1|\[::1\])(:\d+)?$/.test(u);
4
+ /** ML AI Code cloud calls made by the engine: start and finish laptop runs. */
5
+ export class Cloud{
6
+ constructor({server,token,fetchImpl=globalThis.fetch,surface='laptop'}){
7
+ this.server=server;this.token=token;this.fetchImpl=fetchImpl;
8
+ this.device=new Client({baseUrl:server,surface,version:VERSION,tokenProvider:()=>token,fetchImpl,allowLoopback:loopback(server),timeoutMs:45000});
9
+ }
10
+ whoami(){return this.device.request('/api/laptop',{action:'whoami'})}
11
+ /** `run` (optional): the web shell's run body; the server then builds the full run request (Contract A). */
12
+ start({project,folder,folderProject,repo,title,run}){return this.device.request('/api/laptop',{action:'start',project,folder,...(folderProject?{folderProject}:{}),...(repo?{repo}:{}),title,...(run?{run}:{})})}
13
+ /** A compact view of a laptop session for the account's other devices (metadata and conversation, never files). */
14
+ viewSave(name,view){return this.device.request('/api/laptop',{action:'view_save',name,view})}
15
+ /** The server's current harness (src/engine.mjs): its manifest, then only the files this computer lacks. */
16
+ engineManifest({signal}={}){return this.device.request('/api/laptop/engine',undefined,{method:'GET',readOnly:true,signal})}
17
+ engineFiles(files,{signal}={}){return this.device.request('/api/laptop/engine',{files},{signal})}
18
+ run(runToken){return new Client({baseUrl:this.server,surface:'laptop',version:VERSION,tokenProvider:()=>runToken,fetchImpl:this.fetchImpl,allowLoopback:loopback(this.server),timeoutMs:45000})}
19
+ finish(runToken,state,usage){return this.run(runToken).request('/api/laptop',{action:'finish',state,...(usage&&typeof usage==='object'?{usage}:{})})}
20
+ status(runToken){return this.run(runToken).request('/api/laptop',{action:'status'},{readOnly:true})}
21
+ }
22
+ export function friendly(error){
23
+ if(!(error instanceof ClientError))return error?.message||String(error);
24
+ if(error.status===401)return 'Your sign-in expired or was revoked. Run `mlai login`.';
25
+ if(error.code==='billing_limit')return error.message+' Manage your plan at code.ml.ai.';
26
+ if(error.status===429)return error.message;
27
+ if(error.code==='not_configured')return 'Laptop runs are not enabled on this server yet.';
28
+ return error.message;
29
+ }