mlai-code 0.0.0-stage → 0.3.1

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,621 @@
1
+ // Local workspaces for the web shell inside the desktop app (Contract C). A workspace `local-<uuid>` is one laptop
2
+ // session in ~/.mlai (shared with the `mlai` CLI). call(token, action, body) answers with the same JSON as
3
+ // POST /api/workspace for that action, reading the session folder (the harness's state root) and the project folder.
4
+ import {EventEmitter} from 'node:events';
5
+ import {execFile,spawn} from 'node:child_process';
6
+ import {createHash,randomUUID} from 'node:crypto';
7
+ import {readFile,writeFile,rename,rm,mkdir,readdir,stat,lstat,realpath,open} from 'node:fs/promises';
8
+ import {existsSync,readFileSync} from 'node:fs';
9
+ import net from 'node:net';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import {Session,agentEnv,IMAGE_NAME} from './session.mjs';
13
+ import {friendly} from './cloud.mjs';
14
+ import {sub,workerDir} from './home.mjs';
15
+ import {activeEngine} from './engine.mjs';
16
+ import {ensureRuntime} from './runtime.mjs';
17
+ import {createReviews} from './review.mjs';
18
+ import {killTree} from './winenv.mjs';
19
+ import {createWakeScheduler} from './wakeups.mjs';
20
+ import {starterSkills,validateSkill,importSession,POLICY_TEMPLATES,parseCheckpoints,checkpointRef,rewind,resumeTask,mimeType} from './parity.mjs';
21
+ import {twoWordTitle,nameWith} from './two-words.mjs';
22
+
23
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
24
+ export const isLocalToken=t=>typeof t==='string'&&t.startsWith('local-')&&UUID.test(t.slice(6));
25
+ const RAW_CHUNK=3_000_000,RAW_MAX=60_000_000;
26
+ const SKIP=/(^|\/)(node_modules|\.next|\.git|__pycache__|\.pytest_cache|\.turbo|\.vercel|\.venv|venv)\/|\.py[co]$|(^|\/)\.DS_Store$/;
27
+ const RUN_FIELDS=['mode','role','model','effort','planApproval','askFirst','designChoice','designReset','tools','connected','steps','buildAnswers','buildIntake','requestId','goal','wake'];
28
+ /** Cloud-only operations, with the reason shown to the person. */
29
+ const CLOUD_ONLY={task_checkpoint:'Team task hand-offs',lsp_setup:'Language server setup',assign:'Assigning sessions',backup_list:'Backups',backup_create:'Backups',backup_restore:'Backups',
30
+ release_plan:'Releases',release_publish:'Releases',release_rollback:'Releases',release_detail:'Releases',release_templates:'Release pipelines',release_template_install:'Release pipelines'};
31
+
32
+ const exec=(cmd,args,{cwd,timeout=60000,input,env,max=20e6}={})=>new Promise(resolve=>{
33
+ const c=execFile(cmd,args,{cwd,timeout,maxBuffer:max,env:env||process.env,windowsHide:true,encoding:'buffer'},(err,stdout,stderr)=>resolve({code:err?(typeof err.code==='number'?err.code:-1):0,stdout:String(stdout||''),stderr:String(stderr||err?.message||''),missing:err?.code==='ENOENT'}));
34
+ if(input!=null){c.stdin.end(input)}
35
+ });
36
+ async function git(root,args,opts={}){
37
+ const r=await exec('git',args,{cwd:root,...opts});
38
+ if(r.code&&!(opts.ok||[]).includes(r.code))throw new Error((r.stderr||r.stdout).trim().split('\n').slice(-2).join(' ')||'git '+args[0]+' failed');
39
+ return r.stdout;
40
+ }
41
+ const gitOut=async(root,args)=>{const r=await exec('git',args,{cwd:root,timeout:20000});return r.code?'':r.stdout.trim()};
42
+ async function readJson(file,fallback){try{return JSON.parse(await readFile(file,'utf8'))}catch{return fallback}}
43
+ async function writeJson(file,data){const tmp=file+'.'+process.pid+'.tmp';await writeFile(tmp,JSON.stringify(data));await rename(tmp,file)}
44
+ /** The harness version a run used (src/engine.mjs); the harness rewrites status.json mid-run, the turn keeps it. */
45
+ const withEngine=(st,e)=>st&&typeof st==='object'&&!st.engine&&e.session.meta.turns?.at(-1)?.engine?{...st,engine:e.session.meta.turns.at(-1).engine}:st;
46
+ async function optional(name){try{return await import('./'+name)}catch(e){if(e?.code==='ERR_MODULE_NOT_FOUND'&&String(e.message).includes(name))return null;throw e}}
47
+ const fail=(message,extra={})=>Object.assign(new Error(message),extra);
48
+ const pidAlive=pid=>{if(!(pid>0))return false;if(pid===process.pid)return true;try{process.kill(pid,0);return true}catch(e){return e.code==='EPERM'}};
49
+
50
+ /** Runs a harness helper script (worker/*.py) with the engine's Python; returns its last JSON line. */
51
+ async function py(script,args,{cwd,env={},input,timeout=120000}={}){
52
+ const python=await ensureRuntime();
53
+ const r=await exec(python,[path.join((await activeEngine()).dir,script),...args],{cwd,timeout,input,env:{...agentEnv(),PYTHONDONTWRITEBYTECODE:'1',...env}});
54
+ const line=r.stdout.trim().split('\n').pop()||'';
55
+ try{return JSON.parse(line)}catch{throw new Error('The local helper could not run: '+(r.stderr||r.stdout).trim().slice(-300))}
56
+ }
57
+ let packCache=null;
58
+ async function skillPack(){
59
+ if(packCache)return packCache;
60
+ try{const python=await ensureRuntime();const r=await exec(python,['-c','import sys,json;sys.path.insert(0,sys.argv[1]);from skill_pack import PACK;print(json.dumps([dict(s,builtin=True) for s in PACK]))',(await activeEngine()).dir],{timeout:30000});packCache=JSON.parse(r.stdout.trim().split('\n').pop()||'[]')}catch{packCache=[]}
61
+ return packCache;
62
+ }
63
+
64
+ /** Project files for the explorer: git's view when it is a repository, otherwise a bounded walk. */
65
+ async function projectFiles(root,isGit){
66
+ let files=[];
67
+ if(isGit)files=(await gitOut(root,['ls-files','--cached','--others','--exclude-standard'])).split('\n').filter(Boolean);
68
+ else{
69
+ const walk=async(dir,rel)=>{if(files.length>=3000)return;for(const d of await readdir(dir,{withFileTypes:true}).catch(()=>[])){const p=rel?rel+'/'+d.name:d.name;if(d.isDirectory()){if(!SKIP.test(p+'/'))await walk(path.join(dir,d.name),p)}else if(d.isFile())files.push(p);if(files.length>=3000)return}};
70
+ await walk(root,'');
71
+ }
72
+ return [...new Set(files.filter(f=>!SKIP.test(f)))].sort().slice(0,1000);
73
+ }
74
+ const isGitRepo=async root=>(await gitOut(root,['rev-parse','--is-inside-work-tree']))==='true';
75
+
76
+ /** Background jobs the harness supervises (worker/dev_jobs.py layout: <state>/jobs/<name>/{meta.json,exit,log}). */
77
+ async function jobs(dir,lines=4){
78
+ const base=path.join(dir,'jobs'),out=[];let keepalive=false;
79
+ for(const name of (await readdir(base).catch(()=>[])).sort()){
80
+ const meta=await readJson(path.join(base,name,'meta.json'),null);if(!meta||meta.name!==name)continue;
81
+ let state='stopped',code=null;const exit=await readFile(path.join(base,name,'exit'),'utf8').catch(()=>null);
82
+ if(exit!=null){code=Number.parseInt(exit.trim()||'1',10);if(Number.isNaN(code))code=1;state=code===0?'finished':'failed'}
83
+ else if(pidAlive(meta.pid))state='running';
84
+ const log=(await readFile(path.join(base,name,'log'),'utf8').catch(()=>'')).slice(-64000).split('\n').slice(-lines).join('\n').slice(-1500);
85
+ out.push({name,state,exit_code:code,restarts:meta.restarts||0,started:meta.started,command:String(meta.command||'').slice(0,300),tail:log});
86
+ if(state==='running'&&(meta.keepalive_until||0)>Date.now()/1000)keepalive=true;
87
+ }
88
+ return {jobs:out,keepalive};
89
+ }
90
+
91
+ /** Resolves a project-relative path for read/write, confined to the project folder (symlinks included). */
92
+ async function confined(root,file){
93
+ file=String(file||'');
94
+ if(!file||file.startsWith('/')||file.startsWith('\\')||/^[a-zA-Z]:/.test(file)||file.split(/[\\/]/).includes('..')||file.split(/[\\/]/).includes('.git')||file.includes('\0'))throw new Error('Invalid file path');
95
+ const base=await realpath(root),target=path.resolve(base,file);
96
+ // The deepest existing ancestor decides where a symlink really points.
97
+ let probe=target;while(!existsSync(probe)&&probe!==base)probe=path.dirname(probe);
98
+ const real=path.join(await realpath(probe),path.relative(probe,target));
99
+ const rel=path.relative(base,real);
100
+ if(rel.startsWith('..')||path.isAbsolute(rel)||rel.split(path.sep).includes('.git'))throw new Error('Invalid file path');
101
+ return real;
102
+ }
103
+
104
+ async function freePort(prefer=3000){
105
+ const free=p=>new Promise(r=>{const s=net.createServer();s.once('error',()=>r(false));s.listen(p,'127.0.0.1',()=>s.close(()=>r(true)))});
106
+ for(let p=prefer;p<prefer+20;p++)if(await free(p))return p;
107
+ return new Promise(r=>{const s=net.createServer();s.listen(0,'127.0.0.1',()=>{const p=s.address().port;s.close(()=>r(p))})});
108
+ }
109
+ async function httpReady(port){try{const r=await fetch('http://127.0.0.1:'+port,{redirect:'manual',signal:AbortSignal.timeout(2000)});return r.status>=200&&r.status<400}catch{return false}}
110
+
111
+ // The finished turn that is not archived into history yet, so other devices see the latest answer too.
112
+ const FINAL_STATES=['completed','error','stopped','limited','interrupted'];
113
+ function latestTurn(snap){
114
+ const state=snap.status?.state,evs=Array.isArray(snap.events)?snap.events:[];
115
+ if(!snap.task||!FINAL_STATES.includes(state))return [];
116
+ const answer=[...evs].reverse().find(x=>x.type==='answer')?.content??[...evs].reverse().find(x=>x.type==='assistant')?.content??'';
117
+ return [{id:String(snap.runId||'latest').slice(0,40),task:snap.task,answer:String(answer),state}];
118
+ }
119
+ function compactView(snap,meta,device){
120
+ const clip=(s,n)=>String(s||'').slice(0,n);
121
+ return {title:clip(meta.title||nameWith(meta.folder,'Chat'),160),state:snap.status?.state||'idle',task:clip(snap.task,2000),
122
+ conversation:[...(snap.conversation||[]),...latestTurn(snap)].slice(-12).map(c=>({id:c.id,task:clip(c.task,2000),answer:clip(c.answer,6000),state:c.state})),
123
+ todos:(Array.isArray(snap.todos)?snap.todos:[]).slice(0,50).map(t=>({...(t.id!=null?{id:clip(t.id,40)}:{}),content:clip(t.content??t.text??t.title,400),status:clip(t.status,20)||'pending'})),completion:snap.completion?{summary:clip(snap.completion.summary,4000),changedFiles:(snap.completion.changedFiles||[]).slice(0,50)}:null,
124
+ ...(snap.goal?.condition?{goal:{condition:clip(snap.goal.condition,500),status:snap.goal.status,attempts:snap.goal.attempts,maxTurns:snap.goal.maxTurns}}:{}),
125
+ updated:Date.now(),device};
126
+ }
127
+
128
+ /**
129
+ * cloud: a Cloud (src/cloud.mjs) or an async function returning one for the signed-in account (throws when signed out).
130
+ * home: optional ~/.mlai override (sets MLAI_HOME for this process). device: label shown to the account's other devices.
131
+ */
132
+ export function createLocalWorkspaces({cloud,home,device=os.hostname(),relay=false,hooks={},wakeups=process.env.MLAI_WAKEUPS!=='0'}={}){
133
+ // hooks (the desktop app's computer use): runEnv({token,dir}) adds env for a starting run, decision({token,dir,pending,
134
+ // approved}) sees each approval before the harness does, runEnded({token}) when the run is over. All optional.
135
+ if(home)process.env.MLAI_HOME=home;
136
+ const events=new EventEmitter();
137
+ const live=new Map(),terminals=new Map();
138
+ const getCloud=async()=>{try{return typeof cloud==='function'?await cloud():cloud}catch(e){throw fail(friendly(e)||'Sign in to ML AI Code to run tasks on this computer.',{status:401,code:'not_signed_in'})}};
139
+ const reviews=createReviews({python:()=>ensureRuntime(),workerDir,getCloud,env:agentEnv});
140
+ const describe=(m,state)=>({token:'local-'+m.id,name:'mini-'+(m.cloudProject||m.project),title:m.title||nameWith(m.folder,'Chat'),root:m.root,folder:m.folder,...(state!==undefined?{state}:{}),updated:m.updated||m.created,...(m.local?{}:{cli:true})});
141
+
142
+ async function entry(token){
143
+ if(!isLocalToken(token))throw fail('This session is not on this computer.',{status:404});
144
+ const id=token.slice(6);
145
+ if(live.has(id))return live.get(id);
146
+ let s;try{s=await Session.open(id)}catch{throw fail('This session is not on this computer anymore.',{status:404})}
147
+ const e={session:s,id,token,running:false,timer:null,pushed:'',pushTimer:null,changeTimer:null};
148
+ s.on('event',()=>change(e));s.on('started',()=>{change(e);pushView(e)});s.on('done',()=>{change(e);pushView(e);if(wakeups)waker.soon()});
149
+ live.set(id,e);return e;
150
+ }
151
+ function change(e){if(e.changeTimer)return;e.changeTimer=setTimeout(()=>{e.changeTimer=null;events.emit('change',{token:e.token})},200);e.changeTimer.unref?.()}
152
+ /** Best effort: never blocks or fails a run; older servers answer 400 and are ignored. */
153
+ function pushView(e){
154
+ if(e.pushTimer)return;
155
+ e.pushTimer=setTimeout(async()=>{e.pushTimer=null;try{const c=await getCloud();if(!c?.viewSave)return;const snap=await snapshot(e);const view=compactView(snap,e.session.meta,device);const key=JSON.stringify({...view,updated:0});if(key===e.pushed)return;e.pushed=key;await c.viewSave(describe(e.session.meta).name,view)}catch{}},1000);
156
+ e.pushTimer.unref?.();
157
+ }
158
+ const running=e=>e.running||pidAlive(Number(String(readLockSync(e))||0));
159
+ function readLockSync(e){try{return readFileSync(path.join(e.session.dir,'running.lock'),'utf8')}catch{return ''}}
160
+ const idle=(e,what)=>{if(running(e))throw fail('Wait for the agent to finish before '+what+'.',{status:409,code:'session_busy'})};
161
+
162
+ async function inspect(e){
163
+ const st=await readJson(path.join(e.session.dir,'status.json'),{state:'idle'});
164
+ if((st.state==='starting'||st.state==='running')&&!running(e))return {...st,state:'interrupted',error:st.state==='starting'?'Startup did not finish. Continue to recover; the previous task will not be replayed automatically.':'The worker stopped before finishing. Continue to inspect the workspace and recover safely.'};
165
+ return st;
166
+ }
167
+
168
+ async function snapshot(e){
169
+ const dir=e.session.dir,root=e.session.meta.root,read=(n,d)=>readJson(path.join(dir,n),d);
170
+ let events=(await readFile(path.join(dir,'events.jsonl'),'utf8').catch(()=>'')).split('\n').flatMap(l=>{try{return l.trim()?[JSON.parse(l)]:[]}catch{return []}});
171
+ const progress=await read('inference-progress.json',null);if(progress&&typeof progress==='object'&&progress.type==='inference_progress')events.push(progress);
172
+ const times=events.map(x=>x.time).filter(t=>typeof t==='number');const startedAt=times.length?Math.min(...times):null;
173
+ const latest=new Map();events.forEach((x,i)=>{if(x.type==='inference_progress')latest.set(x.id,i)});
174
+ events=events.filter((x,i)=>x.type!=='inference_progress'||latest.get(x.id)===i).slice(-400);
175
+ const request=await read('request.json',{});
176
+ const history=[],conversation=[];
177
+ const hdir=path.join(dir,'history');
178
+ for(const f of (await readdir(hdir).catch(()=>[])).filter(n=>n.endsWith('.json')).sort().reverse().slice(0,30)){
179
+ const h=await readJson(path.join(hdir,f),null);if(!h)continue;const id=f.slice(0,-5),state=h.status?.state||'unknown';
180
+ history.push({id,task:h.task||'Task',state});
181
+ if(conversation.length<12){
182
+ const msgs=h.events||[];
183
+ let answer=[...msgs].reverse().find(x=>x.type==='answer')?.content;
184
+ if(answer==null)answer=[...msgs].reverse().find(x=>x.type==='assistant')?.content??'';
185
+ conversation.push({id,task:String(h.task||'').slice(0,6000),answer:String(answer).slice(0,20000),state,web:((h.completion||{}).changedFiles||[]).some(x=>/\.(html?|[jt]sx?|css|vue|svelte)$/.test(String(x)))});
186
+ }
187
+ }
188
+ const proposal=await read('memory-proposal.json',null);
189
+ let plan='';try{const p=path.join(root,'PLAN.md');const s=await lstat(p);if(s.isFile()&&!s.isSymbolicLink())plan=(await readFile(p,'utf8')).slice(0,40000)}catch{}
190
+ const j=await jobs(dir);
191
+ return {runId:request.runId,completion:await read('completion.json',null),todos:await read('todos.json',[]),
192
+ memoryProposal:proposal&&Array.isArray(proposal.files)&&proposal.files.length?{files:proposal.files.map(f=>f.file).slice(0,4)}:null,
193
+ plan,checks:await read('checks.json',[]),goal:await read('goal.json',null),wakeup:await read('wakeup.json',null),history,conversation:conversation.reverse(),designDirections:await read('design-directions.json',null),designMemory:await read('design-memory.json',null),designReview:await read('design-review.json',null),
194
+ task:request.task||'',status:withEngine(await inspect(e),e),pending:await read('pending.json',null),events,startedAt,jobs:j.jobs,keepalive:j.keepalive,
195
+ files:await projectFiles(root,e.session.meta.git&&await isGitRepo(root))};
196
+ }
197
+
198
+ async function start(e,b,resume){
199
+ const s=e.session;
200
+ if(running(e))throw fail('A task is already running in this session',{status:409,code:'session_busy'});
201
+ let task=b.task,extra={};
202
+ if(resume){
203
+ const prev=await readJson(path.join(s.dir,'request.json'),{});
204
+ task=resumeTask(String(prev.task||''));if(!task)throw new Error('No previous task to continue');
205
+ extra={resume:true,priorTask:String(prev.task||''),designChoice:prev.designChoice??b.designChoice};
206
+ }else if(typeof task!=='string'||!task.trim())throw new Error('Enter a task');
207
+ if(task.length>30000)throw new Error('Enter a task under 30,000 characters');
208
+ const run={};for(const k of RUN_FIELDS)if(b[k]!==undefined)run[k]=b[k];Object.assign(run,extra);
209
+ const images=Array.isArray(b.images)?b.images.filter(n=>IMAGE_NAME.test(String(n))):undefined;
210
+ const c=await getCloud();
211
+ const offline=await optional('offline.mjs'),browser=await optional('browser-setup.mjs');
212
+ const plan=offline?.planRun?await offline.planRun({model:b.model,cloud:c}).catch(()=>null):null;
213
+ const hookEnv=hooks.runEnv?await hooks.runEnv({token:e.token,dir:s.dir}).catch(()=>null):null;
214
+ const extraEnv={...(browser?.browserEnv?await browser.browserEnv(s.dir).catch(()=>null):null),...hookEnv};
215
+ const extraRead=browser?.browserReadPaths?browser.browserReadPaths():null;
216
+ e.running=true;
217
+ let started=null;
218
+ const begun=new Promise(r=>s.once('started',x=>{started=x;r({started:x})}));
219
+ const done=s.send(task,{cloud:c,steps:Number(b.steps)||120,effort:b.effort||'medium',images,run,extraEnv,extraRead,
220
+ ...(plan?.offline?{starter:async()=>plan.started,finisher:async(_t,state)=>offline.recordLocalUsage(plan,state,{project:s.meta.cloudProject||s.meta.project,folder:s.meta.folder,title:twoWordTitle(task,'Offline Task')})}:{})})
221
+ .catch(err=>{const r={state:'error',error:friendly(err),code:err.code||err.error?.code||null};return {...r,failedToStart:!started,status:err.status}})
222
+ .finally(()=>{e.running=false;try{hooks.runEnded?.({token:e.token})}catch{}change(e);pushView(e)});
223
+ const first=await Promise.race([begun,done.then(r=>({result:r}))]);
224
+ if(first.result?.intake)return first.result.intake;
225
+ if(first.result?.failedToStart){const r=first.result;throw fail(r.error,{code:r.code||undefined,status:r.code==='billing_limit'?402:r.code==='session_busy'?409:r.status===401?401:400})}
226
+ if(!s.meta.local&&!s.meta.title)s.meta.title=twoWordTitle(task);
227
+ // Online again: offline runs recorded earlier go to the account history (best effort, never blocks the run).
228
+ if(!plan?.offline&&offline?.syncLocalUsage)offline.syncLocalUsage(c).catch(()=>{});
229
+ change(e);
230
+ return {ok:true,runId:first.started?.runId,harness:first.started?.harness||'mini'};
231
+ }
232
+
233
+ async function approve(e,b){
234
+ const dir=e.session.dir,root=e.session.meta.root;
235
+ if(!/^[a-f0-9]{16}$/.test(String(b.id)))throw new Error('Invalid approval');
236
+ const pending=await readJson(path.join(dir,'pending.json'),null);if(pending?.id!==b.id)throw new Error('This approval has expired');
237
+ // Atomic: the harness polls for these files and must never read a half-written one.
238
+ const put=async(name,content)=>{const f=path.join(dir,name),tmp=path.join(path.dirname(f),'.tmp-'+randomUUID());await writeFile(tmp,content);await rename(tmp,f)};
239
+ // The person's verdict reaches the hook first (computer use grants a session only from here, never from the harness).
240
+ if(hooks.decision){try{await hooks.decision({token:e.token,dir,pending,approved:b.approved===true})}catch{if(pending.kind==='computer')b={...b,approved:false}}}
241
+ if(pending.kind==='deploy'&&b.approved){
242
+ const deploy=await optional('deploy.mjs');
243
+ const result=deploy?.fulfilLocalDeploy?await deploy.fulfilLocalDeploy(pending,{cloud:await getCloud().catch(()=>null),dir,root,runId:(await readJson(path.join(dir,'request.json'),{})).runId,python:await ensureRuntime(),worker:(await activeEngine()).dir,approvedBy:b.auto===true?'auto':'person'}):{error:'Deploys from this computer are not available in this version. Deploy from a cloud workspace.'};
244
+ await put('result-'+b.id,JSON.stringify(result));
245
+ }
246
+ if(pending.kind==='browser'&&pending.install&&b.approved){const browser=await optional('browser-setup.mjs');if(browser?.installBrowserFor)await browser.installBrowserFor(dir,{python:await ensureRuntime()})}
247
+ if(pending.kind==='integration'&&b.approved){if(JSON.stringify(b.result||{}).length>70000)throw new Error('Tool result too large');await put('result-'+b.id,JSON.stringify(b.result||{error:'No result provided'}))}
248
+ if(pending.kind==='plan'&&b.approved&&b.look!==undefined){
249
+ if(typeof b.look!=='string'||!/^Look and feel: /.test(b.look)||b.look.length>600)throw new Error('Invalid look selection');
250
+ await mkdir(path.join(dir,'steering'),{recursive:true});
251
+ await put(path.join('steering',Date.now()+'-look-'+b.id+'.json'),JSON.stringify({message:b.look.replace(/\s+/g,' ').trim()+' (Chosen on the plan; apply it to the approved build.)',created:Date.now()}));
252
+ }
253
+ if(pending.kind==='plan'&&typeof b.revise==='string'&&b.revise.trim()){
254
+ await put('decision-'+b.id,'revise:'+b.revise.trim().replace(/\s+/g,' ').slice(0,2000));change(e);return {ok:true};
255
+ }
256
+ const verdict=b.approved?(pending.kind==='plan'&&Array.isArray(b.items)?'approve:'+b.items.filter(n=>Number.isInteger(n)&&n>=0&&n<40).join(','):b.all===true&&!['integration','plan','network','computer'].includes(pending.kind)?'approve_all':'approve'):'reject';
257
+ await put('decision-'+b.id,verdict);change(e);return {ok:true};
258
+ }
259
+
260
+ // ---------- git, PRs and safety checks, through the developer's own git and gh ----------
261
+ async function upstream(root){return gitOut(root,['rev-parse','--abbrev-ref','--symbolic-full-name','@{u}'])}
262
+ async function outgoingBase(root){const u=await upstream(root);return (u&&await gitOut(root,['merge-base','HEAD',u]))||await gitOut(root,['rev-parse','HEAD'])}
263
+ async function repoInfo(root){
264
+ const url=await gitOut(root,['remote','get-url','origin']);
265
+ const m=/github\.com[:/]([\w.-]+\/[\w.-]+?)(\.git)?$/.exec(url);
266
+ const def=(await gitOut(root,['symbolic-ref','--short','refs/remotes/origin/HEAD'])).replace(/^origin\//,'');
267
+ return {remote:url,repository:m?m[1]:url.replace(/^.*[:/]([^/]+\/[^/]+?)(\.git)?$/,'$1'),github:Boolean(m),branch:await gitOut(root,['branch','--show-current']),defaultBranch:def||'main'};
268
+ }
269
+ async function openPr(root){
270
+ const r=await exec('gh',['pr','view','--json','number,url,headRefName,state'],{cwd:root,timeout:15000});
271
+ if(r.code)return null;try{const j=JSON.parse(r.stdout);return j.state==='OPEN'?{number:j.number,url:j.url,branch:j.headRefName}:null}catch{return null}
272
+ }
273
+ async function scan(root){
274
+ if(!await isGitRepo(root))return [];
275
+ const base=await outgoingBase(root);
276
+ const r=await py('secret_scan.py',['diff',...(base?['--base',base]:[])],{cwd:root,env:{MINI_REPO:root}});
277
+ return Array.isArray(r.findings)?r.findings.slice(0,50):[];
278
+ }
279
+ async function assertSafe(root,{direct,branch,defaultBranch}){
280
+ const findings=await scan(root);
281
+ if(findings.length){const f=findings[0],where=f.file+':'+f.line;throw fail(findings.length===1?'A credential is about to leave this computer ('+where+'). Move it to an environment variable or the Vault, then push again.':findings.length+' credentials are about to leave this computer (first at '+where+'). Move them to environment variables or the Vault, then push again.',{code:'secret_found',findings})}
282
+ if(direct&&branch){const r=await py('repo_policy.py',['check-push',branch,defaultBranch||''],{cwd:root,env:{MINI_REPO:root}});if(r.blocked)throw fail(String(r.blocked),{code:'policy_blocked'})}
283
+ }
284
+ async function changeList(root){
285
+ const base=await outgoingBase(root);
286
+ const files=new Map();
287
+ for(const line of (await gitOut(root,['diff','--name-status','--no-renames',base||'HEAD'])).split('\n').filter(Boolean)){const [st,...p]=line.split('\t');files.set(p.join('\t'),st==='D')}
288
+ for(const f of (await gitOut(root,['ls-files','--others','--exclude-standard'])).split('\n').filter(Boolean))files.set(f,false);
289
+ const list=[...files].filter(([p])=>!SKIP.test(p)).map(([p,deleted])=>({path:p,deleted})).sort((a,b)=>a.path.localeCompare(b.path));
290
+ const diff=await gitOut(root,['diff',base||'HEAD','--binary']);
291
+ const planHash=createHash('sha256').update(JSON.stringify({base,list})).update(diff).update(JSON.stringify(await Promise.all(list.filter(f=>!f.deleted).slice(0,500).map(async f=>{try{const s=await stat(path.join(root,f.path));return [f.path,s.size,s.mtimeMs]}catch{return [f.path]}})))).digest('hex');
292
+ return {base,files:list,planHash};
293
+ }
294
+ async function commitAll(root,message){
295
+ await git(root,['add','-A']);
296
+ const staged=(await exec('git',['diff','--cached','--quiet'],{cwd:root})).code===1;
297
+ if(staged)await git(root,['commit','-q','-m',message]);
298
+ return staged;
299
+ }
300
+
301
+ async function terminal(e,b){
302
+ if(typeof b.command!=='string'||b.command.length>10000)throw new Error('Invalid command');
303
+ const id=typeof b.id==='string'&&/^[a-z0-9]{8,32}$/.test(b.id)?b.id:Math.random().toString(36).slice(2,12).padEnd(10,'0');
304
+ const win=process.platform==='win32';
305
+ const child=spawn(win?'cmd.exe':'bash',win?['/d','/s','/c',b.command]:['-lc',b.command],{cwd:e.session.meta.root,env:agentEnv(),detached:!win,windowsHide:true,stdio:['ignore','pipe','pipe']});
306
+ terminals.set(id,child);
307
+ let output='';const add=d=>{if(output.length<1_000_000)output+=d};child.stdout.on('data',add);child.stderr.on('data',add);
308
+ const timer=setTimeout(()=>killTree(child.pid),90000);
309
+ const exitCode=await new Promise(r=>{child.on('exit',(code,signal)=>r(code??(signal?124:1)));child.on('error',err=>{output+=err.message;r(127)})});
310
+ clearTimeout(timer);terminals.delete(id);
311
+ return {output,exitCode,id};
312
+ }
313
+
314
+ async function preview(e,b){
315
+ const dir=e.session.dir,root=e.session.meta.root,file=path.join(dir,'preview-local.json');
316
+ const meta=await readJson(file,{});
317
+ const status=async()=>{
318
+ const port=meta.port||3000,ready=await httpReady(port),alive=pidAlive(meta.pid);
319
+ const log=(await readFile(path.join(dir,'preview.log'),'utf8').catch(()=>'')).slice(-8000);
320
+ return {ready,running:alive,port,mode:ready||alive?'dev':null,notes:[],log,message:ready?'The preview is running on this computer.':alive?'The preview is starting.':'No preview is running. Start it to see the app.',url:ready?'http://localhost:'+port:undefined};
321
+ };
322
+ if(b.action!=='preview_start'){const r=await status();if(b.action==='preview'&&!r.ready)throw new Error(r.message);return r}
323
+ if(b.confirm!==true)throw new Error('Confirm running the project preview first');
324
+ if(pidAlive(meta.pid)&&await httpReady(meta.port))return status();
325
+ const pkg=await readJson(path.join(root,'package.json'),null);
326
+ const port=await freePort(3000);let cmd,args;
327
+ const script=['dev','start'].find(n=>typeof pkg?.scripts?.[n]==='string');
328
+ if(script){const s=pkg.scripts[script];cmd=process.platform==='win32'?'npm.cmd':'npm';args=['run',script,...(/\b(next|vite)\b/.test(s)?['--','--port',String(port)]:[])]}
329
+ else if(existsSync(path.join(root,'index.html'))){cmd=await ensureRuntime();args=['-m','http.server',String(port),'--bind','127.0.0.1']}
330
+ else throw new Error('This project has no dev or start script and no index.html to preview. Ask the agent to start a preview.');
331
+ const log=await open(path.join(dir,'preview.log'),'a');
332
+ const child=spawn(cmd,args,{cwd:root,env:{...agentEnv(),PORT:String(port)},detached:process.platform!=='win32',stdio:['ignore',log.fd,log.fd],windowsHide:true});
333
+ child.unref();await log.close().catch(()=>{});
334
+ Object.assign(meta,{pid:child.pid,port,command:[cmd,...args].join(' '),started:Date.now()});await writeJson(file,meta);
335
+ for(let i=0;i<60&&!(await httpReady(port))&&pidAlive(child.pid);i++)await new Promise(r=>setTimeout(r,500));
336
+ return status();
337
+ }
338
+
339
+ async function call(token,action,body={}){
340
+ const b={...(body&&typeof body==='object'?body:{}),action};
341
+ const e=await entry(token),s=e.session,dir=s.dir,root=s.meta.root,name=describe(s.meta).name;
342
+ const isGit=s.meta.git&&await isGitRepo(root);
343
+ if(CLOUD_ONLY[action])throw fail(CLOUD_ONLY[action]+' are not available for sessions on this computer yet. Use a cloud workspace for this.',{code:'local_unsupported'});
344
+ if(action.startsWith('deploy_')||action.startsWith('signals_')||/^(monitor|alert|schedule|schedules|releases|ingest|mission|missions|source|sources)_/.test(action))throw fail('This is not available for sessions on this computer yet. Use a cloud workspace for this.',{code:'local_unsupported'});
345
+ if(['skill_save','session_import','browser_setup'].includes(action)&&running(e))throw new Error('Wait for the current task to finish before changing its tools or context.');
346
+ switch(action){
347
+ case 'status':{const snap=await snapshot(e);const key=snap.status?.state+'|'+snap.history.length;if(key!==e.lastKey){e.lastKey=key;pushView(e)}return snap}
348
+ case 'view':return {view:null,at:0};
349
+ case 'review_start':return reviews.start(s,b);
350
+ case 'review_status':return reviews.status(s,b);
351
+ case 'review_dismiss':return reviews.dismiss(s,b);
352
+ case 'run':return start(e,b,false);
353
+ case 'resume':return start(e,b,true);
354
+ case 'approve':return approve(e,b);
355
+ case 'steer':{
356
+ const st=await readJson(path.join(dir,'status.json'),{});if(st.state!=='running')throw new Error('Wait for the task to start before sending an instruction.');
357
+ if(typeof b.message!=='string'||!b.message.trim()||b.message.length>5000)throw new Error('Enter an instruction under 5,000 characters');
358
+ if(!running(e))throw new Error('No task is running. Send a new task instead.');
359
+ await mkdir(path.join(dir,'steering'),{recursive:true});const id=Date.now()+'-'+randomUUID();
360
+ const tmp=path.join(dir,'steering','.tmp-'+id);await writeFile(tmp,JSON.stringify({message:b.message.trim(),created:Date.now()}));await rename(tmp,path.join(dir,'steering',id+'.json'));change(e);return {ok:true,id};
361
+ }
362
+ case 'stop':await writeFile(path.join(dir,'cancel'),'stop');if(s.child){const c=s.child;setTimeout(()=>{if(s.child===c)killTree(c.pid)},8000).unref()}change(e);return {ok:true};
363
+ case 'sleep':return {ok:true};
364
+ case 'goal_update':{
365
+ // Stop the goal (the running turn finishes, no further verifier pass) or cancel the pending wakeup.
366
+ if(b.op!=='stop'&&b.op!=='cancel_wakeup')throw new Error('Unknown goal action');
367
+ const gf=path.join(dir,'goal.json'),wf=path.join(dir,'wakeup.json');const g=await readJson(gf,null),w=await readJson(wf,null);let changed=false;
368
+ if(b.op==='stop'&&g?.status==='working'){await writeJson(gf,{...g,status:'stopped',reason:'Stopped by you.'});await writeFile(path.join(dir,'goal-stop'),'1');changed=true}
369
+ if(w?.state==='pending'&&(b.op==='cancel_wakeup'||w.kind==='goal')){await writeJson(wf,{...w,state:'cancelled',cancelled:new Date().toISOString()});changed=true}
370
+ change(e);return {ok:true,changed,goal:await readJson(gf,null),wakeup:await readJson(wf,null)};
371
+ }
372
+ case 'rename':{const title=typeof b.title==='string'?b.title.replace(/\s+/g,' ').trim().slice(0,160):'';if(!title)throw new Error('Enter a name for this session');s.meta.title=title;s.meta.renamed=true;await s.save();pushView(e);change(e);return {ok:true,title}}
373
+ case 'delete_workspace':{
374
+ if(b.confirmName!==name&&b.confirmName!==token)throw new Error('Confirm the exact workspace name before deletion');
375
+ if(running(e))throw new Error('Stop the current task before deleting the project');
376
+ // The session only: the project folder on this computer is never touched.
377
+ await rm(dir,{recursive:true,force:true});live.delete(e.id);events.emit('change',{token});return {ok:true};
378
+ }
379
+ case 'history':{if(!/^\d{16,22}$/.test(String(b.id)))throw new Error('Invalid history item');const h=await readJson(path.join(dir,'history',b.id+'.json'),null);if(!h)throw new Error('Task not found');return h}
380
+ case 'capabilities':{
381
+ const own=[];for(const f of (await readdir(path.join(dir,'skills')).catch(()=>[])).filter(n=>n.endsWith('.json')).sort().slice(0,40)){const x=await readJson(path.join(dir,'skills',f),null);if(x)own.push(x)}
382
+ const pack=await skillPack(),known=new Set(own.map(x=>x.id)),builtin=new Set(pack.map(x=>x.id));
383
+ const browser=await optional('browser-setup.mjs');
384
+ return {lspReady:false,browserReady:browser?.browserReady?Boolean(await browser.browserReady().catch(()=>false)):existsSync(path.join(dir,'browser-ready')),local:true,
385
+ skills:[...own.map(x=>builtin.has(x.id)?{...x,builtin:true}:x),...pack.filter(x=>!known.has(x.id)),...starterSkills.filter(x=>!known.has(x.id)&&!builtin.has(x.id)).map(x=>({...x,enabled:false}))]};
386
+ }
387
+ case 'browser_setup':{const browser=await optional('browser-setup.mjs');if(!browser?.installBrowserFor)throw fail('The browser tool cannot be set up on this computer in this version.',{code:'local_unsupported'});await browser.installBrowserFor(dir,{python:await ensureRuntime()});return {ok:true}}
388
+ case 'skill_save':{
389
+ const skill=validateSkill(b.skill),file=path.join(dir,'skills',skill.id+'.json');
390
+ const previous=await readFile(file).catch(()=>null);
391
+ if(previous){const h=path.join(dir,'skill-history',skill.id);await mkdir(h,{recursive:true});await writeFile(path.join(h,Date.now()+'-'+randomUUID()+'.json'),previous)}
392
+ await mkdir(path.join(dir,'skills'),{recursive:true});await writeFile(file,JSON.stringify(skill));return {ok:true,skill};
393
+ }
394
+ case 'skill_history':{
395
+ if(typeof b.id!=='string'||!/^[-a-z0-9]{1,60}$/.test(b.id))throw new Error('Invalid skill ID');
396
+ const h=path.join(dir,'skill-history',b.id),versions=[];
397
+ for(const f of (await readdir(h).catch(()=>[])).filter(n=>n.endsWith('.json')).sort().reverse().slice(0,20)){const skill=await readJson(path.join(h,f),null);if(skill)versions.push({version:f.slice(0,-5),skill})}
398
+ return {versions};
399
+ }
400
+ case 'memory_proposal':return {proposal:await readJson(path.join(dir,'memory-proposal.json'),null)};
401
+ case 'memory_apply':{
402
+ const proposal=await readJson(path.join(dir,'memory-proposal.json'),null);if(!proposal)throw new Error('There is no memory update waiting');
403
+ if(b.approved===true){
404
+ idle(e,'updating the repository memory');
405
+ const allowed=['ARCHITECTURE.md','CONVENTIONS.md','DECISIONS.md','DEPLOY.md'],pick=Array.isArray(b.files)?new Set(b.files.map(String)):null;
406
+ const files=(proposal.files||[]).filter(f=>allowed.includes(f.file)&&typeof f.after==='string'&&f.after.length<=8000&&(!pick||pick.has(f.file)));
407
+ if(!files.length)throw new Error('Pick at least one file to save');
408
+ await mkdir(path.join(root,'.mlai'),{recursive:true});
409
+ for(const f of files)await writeFile(path.join(root,'.mlai',f.file),f.after.endsWith('\n')?f.after:f.after+'\n');
410
+ await rm(path.join(dir,'memory-proposal.json'),{force:true});return {ok:true,saved:files.map(f=>'.mlai/'+f.file)};
411
+ }
412
+ await rm(path.join(dir,'memory-proposal.json'),{force:true});return {ok:true,saved:[]};
413
+ }
414
+ case 'memory_read':return readJson(path.join(dir,'project-memory.json'),{content:'',source:'user',updated:null});
415
+ case 'memory_save':{if(typeof b.content!=='string'||b.content.length>12000)throw new Error('Project memory must be under 12,000 characters');await writeJson(path.join(dir,'project-memory.json'),{content:b.content,source:'user',updated:new Date().toISOString()});return {ok:true}}
416
+ case 'session_import':{
417
+ if(typeof b.source!=='string')throw new Error('Choose a session export');const imported=importSession(b.source);
418
+ const id=String(BigInt(Date.now())*1000000n);await mkdir(path.join(dir,'history'),{recursive:true});
419
+ const evs=imported.messages.map(m=>({type:m.role==='assistant'?'assistant':'imported_user',content:m.content,time:Date.now()/1000}));
420
+ await writeFile(path.join(dir,'history',id+'.json'),JSON.stringify({task:imported.title,status:{state:'imported'},events:evs}));
421
+ await writeFile(path.join(dir,'imported-context.json'),JSON.stringify(imported));change(e);return {ok:true,count:imported.messages.length};
422
+ }
423
+ case 'session_export':{
424
+ const request=await readJson(path.join(dir,'request.json'),{});
425
+ const evs=(await readFile(path.join(dir,'events.jsonl'),'utf8').catch(()=>'')).split('\n').flatMap(l=>{try{return [JSON.parse(l)]}catch{return []}});
426
+ return {schema:'mini-code-session/v1',exportedAt:new Date().toISOString(),title:request.task||'Session',model:request.model,runId:request.runId,
427
+ messages:[{role:'user',content:request.task||''},...evs.filter(x=>x.type==='assistant'||x.type==='answer'||x.type==='steering').map(x=>({role:x.type==='steering'?'user':'assistant',content:x.content}))],events:evs,
428
+ limitations:['No files or credentials included','External effects and processes cannot be replayed','Import restores supported text as historical context only']};
429
+ }
430
+ case 'screenshot':{
431
+ if(!/^[a-f0-9]{16}\.png$/.test(String(b.name)))throw new Error('Invalid screenshot');
432
+ const buf=await readFile(path.join(dir,'screenshots',b.name)).catch(()=>null);if(!buf||buf.length>5000000)throw new Error('Screenshot unavailable or too large');
433
+ return {image:'data:image/png;base64,'+buf.toString('base64')};
434
+ }
435
+ case 'preview':case 'preview_status':case 'preview_start':return preview(e,b);
436
+ case 'read':case 'write':case 'read_raw':case 'write_raw':{
437
+ if(action==='write'||action==='write_raw')idle(e,'editing files. Stop the agent first');
438
+ const file=await confined(root,b.path);
439
+ if(action==='read_raw'){
440
+ const buf=await readFile(file).catch(()=>null);if(!buf)throw new Error('File not found');
441
+ if(buf.length>RAW_MAX)throw new Error('File is too large to preview here (over 60 MB). Download it from the terminal or the repository.');
442
+ const offset=Math.min(buf.length,Math.max(0,Math.floor(Number(b.offset)||0)));const part=buf.subarray(offset,offset+RAW_CHUNK);
443
+ return {size:buf.length,offset,base64:part.toString('base64'),done:offset+part.length>=buf.length,mime:mimeType(String(b.path))};
444
+ }
445
+ if(action==='write_raw'){
446
+ if(typeof b.base64!=='string'||b.base64.length>RAW_CHUNK*1.4)throw new Error('File is too large to save from the browser (3 MB limit)');
447
+ const data=Buffer.from(b.base64,'base64');if(!data.length)throw new Error('Empty file');
448
+ await mkdir(path.dirname(file),{recursive:true});await writeFile(file,data);change(e);return {ok:true,size:data.length};
449
+ }
450
+ if(action==='read'){const buf=await readFile(file).catch(()=>null);if(buf&&buf.length>500000)throw new Error('File is too large for the editor');return {content:buf?.toString()||''}}
451
+ if(typeof b.content!=='string'||b.content.length>500000)throw new Error('File is too large');
452
+ await mkdir(path.dirname(file),{recursive:true});await writeFile(file,b.content);change(e);return {ok:true};
453
+ }
454
+ case 'terminal':idle(e,'running manual commands. Stop the agent first');return terminal(e,b);
455
+ case 'terminal_stop':{const id=typeof b.id==='string'&&/^[a-z0-9]{8,32}$/.test(b.id)?b.id:'';if(!id)throw new Error('Nothing to stop');const c=terminals.get(id);if(!c)return {stopped:false};killTree(c.pid);return {stopped:true}}
456
+ case 'diff':{
457
+ if(!isGit)return {diff:'',untracked:'',skipped:[]};
458
+ let d=await git(root,['diff','HEAD','--no-ext-diff','-M'],{ok:[1]}).catch(()=>'');
459
+ const extra=(await gitOut(root,['ls-files','--others','--exclude-standard'])).split('\n').filter(Boolean),skipped=[];
460
+ for(const f of extra.slice(0,200)){
461
+ const p=path.join(root,f);let size=Infinity;try{const st=await stat(p);if(st.isFile())size=st.size}catch{}
462
+ if(d.length>400000||size>200000){skipped.push(f);continue}
463
+ d+=(await exec('git',['diff','--no-index','--no-ext-diff','--','/dev/null',f],{cwd:root})).stdout;
464
+ }
465
+ return {diff:d.slice(0,600000),untracked:extra.join('\n'),skipped:[...skipped,...extra.slice(200)]};
466
+ }
467
+ case 'export':{
468
+ if(!isGit)throw new Error('Exporting a patch needs a git repository.');
469
+ let patch=(await exec('git',['diff','HEAD','--binary'],{cwd:root})).stdout;
470
+ for(const f of (await gitOut(root,['ls-files','--others','--exclude-standard'])).split('\n').filter(Boolean))patch+=(await exec('git',['diff','--no-index','--binary','--','/dev/null',f],{cwd:root})).stdout;
471
+ return {patch};
472
+ }
473
+ case 'checkpoints':return {checkpoints:isGit?parseCheckpoints(await gitOut(root,['for-each-ref','--sort=-refname','--format=%(refname:short) %(objectname) %(contents:subject)','refs/mini-checkpoints/'])):[]};
474
+ case 'checkpoint_compare':{
475
+ const ref=checkpointRef(b.checkpoint);if(ref==='HEAD')throw new Error('Choose a checkpoint to compare');
476
+ const out=await py('checkpoints.py',['compare',ref.slice(5)],{cwd:root});if(out.error)throw new Error(out.error);return out;
477
+ }
478
+ case 'restore':{
479
+ idle(e,'restoring a checkpoint. Stop the agent first');
480
+ if(b.confirm!==true)throw new Error('Confirm discarding changes before restoring');
481
+ if(!isGit)throw new Error('Checkpoints need a git repository.');
482
+ const rescue=await rewind(b.checkpoint,args=>git(root,args));change(e);return {ok:true,...rescue};
483
+ }
484
+ case 'policy_get':return {...await py('repo_policy.py',['show'],{cwd:root,env:{MINI_REPO:root,MINI_ROOT:dir}}),templates:POLICY_TEMPLATES};
485
+ case 'policy_validate':if(typeof b.text!=='string')throw new Error('Policy text required');return validatePolicy(root,dir,b.text);
486
+ case 'policy_save':{
487
+ if(typeof b.text!=='string')throw new Error('Policy text required');idle(e,'saving the policy');
488
+ const v=await validatePolicy(root,dir,b.text);
489
+ if(!v.ok)throw fail('The policy has '+v.errors.length+' problem'+(v.errors.length===1?'':'s')+': '+v.errors.slice(0,3).join('; '),{code:'policy_invalid',errors:v.errors});
490
+ await mkdir(path.join(root,'.mlai'),{recursive:true});await writeFile(path.join(root,'.mlai','policy.yml'),b.text.endsWith('\n')?b.text:b.text+'\n');
491
+ return {...await py('repo_policy.py',['show'],{cwd:root,env:{MINI_REPO:root,MINI_ROOT:dir}}),templates:POLICY_TEMPLATES};
492
+ }
493
+ // Repository hooks file (.mlai/hooks.json), validated by the worker's own rules (worker/mlai_hooks.py).
494
+ case 'hooks_get':return py('mlai_hooks.py',['show'],{cwd:root,env:{MINI_REPO:root,MINI_ROOT:dir}});
495
+ case 'hooks_save':{
496
+ if(typeof b.text!=='string')throw new Error('Hooks file text required');idle(e,'saving the hooks file');
497
+ if(b.text.length>100000)throw fail('hooks.json is over 100,000 characters',{code:'hooks_invalid',errors:['hooks.json is over 100,000 characters']});
498
+ const v=await py('mlai_hooks.py',['validate'],{cwd:root,input:b.text,env:{MINI_REPO:root,MINI_ROOT:dir}});
499
+ if(!v.ok)throw fail('The hooks file has '+v.errors.length+' problem'+(v.errors.length===1?'':'s')+': '+v.errors.slice(0,3).join('; '),{code:'hooks_invalid',errors:v.errors});
500
+ const file=path.join(root,'.mlai','hooks.json');
501
+ if(await lstat(file).then(st=>st.isSymbolicLink(),()=>false))throw new Error('.mlai/hooks.json is a symbolic link; edit the real file instead.');
502
+ await mkdir(path.join(root,'.mlai'),{recursive:true});await writeFile(file,b.text.endsWith('\n')?b.text:b.text+'\n');
503
+ return py('mlai_hooks.py',['show'],{cwd:root,env:{MINI_REPO:root,MINI_ROOT:dir}});
504
+ }
505
+ case 'secret_scan':return {findings:await scan(root)};
506
+ case 'git_status':{
507
+ if(!isGit)return {linked:false,canPush:false};
508
+ const info=await repoInfo(root),canPush=Boolean(info.remote);
509
+ if(running(e))return {linked:true,running:true,canPush};
510
+ if(!info.remote)return {linked:false,canPush:false,branch:info.branch};
511
+ const u=await upstream(root);if(u)await exec('git',['fetch','--quiet','origin'],{cwd:root,timeout:20000});
512
+ const behind=u?Number(await gitOut(root,['rev-list','--count','HEAD..'+u]))||0:0;
513
+ const changes=(await gitOut(root,['status','--porcelain'])).split('\n').filter(Boolean).map(l=>l.slice(3));
514
+ return {linked:true,repository:info.repository,branch:info.branch,behind,remoteHead:u?await gitOut(root,['rev-parse',u]):null,changeCount:changes.length,changes:changes.slice(0,500),pr:await openPr(root),canPush};
515
+ }
516
+ case 'git_pull':{
517
+ idle(e,'syncing');if(!isGit)throw new Error('This folder is not a git repository.');
518
+ const info=await repoInfo(root),u=await upstream(root);if(!u)throw new Error('This branch has no upstream branch yet. Push it first.');
519
+ const before=await gitOut(root,['rev-parse','HEAD']);
520
+ const r=await exec('git',['pull','--rebase','--autostash','--quiet'],{cwd:root,timeout:120000});
521
+ if(r.code){
522
+ const conflicts=(await gitOut(root,['diff','--name-only','--diff-filter=U'])).split('\n').filter(Boolean);
523
+ await exec('git',['rebase','--abort'],{cwd:root});
524
+ if(conflicts.length)return {updated:false,conflicts,pulledFiles:0,branch:info.branch,remoteSha:await gitOut(root,['rev-parse',u])};
525
+ throw new Error((r.stderr||r.stdout).trim().split('\n').slice(-2).join(' ')||'git pull failed');
526
+ }
527
+ const after=await gitOut(root,['rev-parse','HEAD']);
528
+ const pulled=before===after?0:(await gitOut(root,['diff','--name-only',before,after])).split('\n').filter(Boolean).length;
529
+ change(e);return {updated:before!==after,conflicts:[],pulledFiles:pulled,branch:info.branch,remoteSha:after};
530
+ }
531
+ case 'git_push':{
532
+ if(b.confirm!==true)throw new Error('Review and approve this push first');idle(e,'pushing');
533
+ if(typeof b.message!=='string'||!b.message.trim()||b.message.length>2000)throw new Error('Enter a commit message');
534
+ if(!isGit)throw new Error('This folder is not a git repository.');
535
+ const info=await repoInfo(root);if(!info.remote)throw new Error('This repository has no remote named origin to push to.');
536
+ await assertSafe(root,{direct:true,branch:info.branch,defaultBranch:info.defaultBranch});
537
+ await commitAll(root,b.message.trim());
538
+ await git(root,['push',...(await upstream(root)?[]:['-u','origin',info.branch])],{timeout:180000});
539
+ const sha=await gitOut(root,['rev-parse','HEAD']);change(e);
540
+ return {sha,branch:info.branch,url:info.github?'https://github.com/'+info.repository+'/commit/'+sha:''};
541
+ }
542
+ case 'pr_plan':{
543
+ if(!isGit)throw new Error('Pull requests need a git repository.');
544
+ const info=await repoInfo(root),plan=await changeList(root);
545
+ return {repository:info.repository,base:info.defaultBranch,planHash:plan.planHash,files:plan.files,pr:await openPr(root),canPush:Boolean(info.remote)};
546
+ }
547
+ case 'pr_publish':{
548
+ if(b.confirm!==true)throw new Error('Review and approve this draft PR first');idle(e,'publishing');
549
+ if(typeof b.title!=='string'||!b.title.trim()||b.title.length>200)throw new Error('Enter a PR title under 200 characters');
550
+ if(!isGit)throw new Error('Pull requests need a git repository.');
551
+ const info=await repoInfo(root);if(!info.github)throw new Error('Draft pull requests from this computer need a GitHub remote named origin.');
552
+ if((await exec('gh',['--version'],{timeout:10000})).missing)throw new Error('Publishing a pull request from this computer needs the GitHub CLI (gh). Install it and run gh auth login, or push from the Changes panel.');
553
+ await assertSafe(root,{direct:false});
554
+ const plan=await changeList(root);if(plan.planHash!==String(b.planHash))throw new Error('Files changed after review. Refresh the PR review first.');
555
+ const open=await openPr(root);let branch=info.branch;
556
+ if(!open&&(!branch||branch===info.defaultBranch)){branch='mlai/'+(b.title.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,40)||'changes')+'-'+randomUUID().slice(0,6);await git(root,['switch','-q','-c',branch])}
557
+ const committed=await commitAll(root,b.title.trim());
558
+ await git(root,['push','-u','origin',branch],{timeout:180000});
559
+ if(open){change(e);return {url:open.url,number:open.number,branch,updated:true,unchanged:!committed}}
560
+ const r=await exec('gh',['pr','create','--draft','--title',b.title.trim(),'--body',String(b.body||'').slice(0,20000),'--base',info.defaultBranch,'--head',branch],{cwd:root,timeout:60000});
561
+ if(r.code)throw new Error('Pushed branch '+branch+', but GitHub would not open the PR: '+(r.stderr||r.stdout).trim().split('\n')[0]);
562
+ const url=(r.stdout.match(/https:\/\/\S+\/pull\/\d+/)||[''])[0];change(e);
563
+ return {url,number:Number(url.split('/').pop())||null,branch,updated:false,unchanged:false};
564
+ }
565
+ }
566
+ throw fail('This is not available for sessions on this computer yet.',{code:'local_unsupported'});
567
+ }
568
+ async function validatePolicy(root,dir,text){
569
+ if(text.length>50000)return {ok:false,errors:['Policy is over 50,000 characters']};
570
+ return py('repo_policy.py',['validate'],{cwd:root,input:text,env:{MINI_REPO:root,MINI_ROOT:dir}});
571
+ }
572
+
573
+ // Wakeups the agent scheduled for itself in a session on this computer (see wakeups.mjs).
574
+ const waker=createWakeScheduler({
575
+ sessions:async()=>(await Session.list()).filter(m=>!m.archived&&m.id&&UUID.test(m.id)).map(m=>({token:'local-'+m.id,dir:path.join(sub('sessions'),m.id)})),
576
+ running:async token=>{const e=live.get(token.slice(6));return e?running(e):pidAlive(Number(await readFile(path.join(sub('sessions'),token.slice(6),'running.lock'),'utf8').catch(()=>'0'))||0)},
577
+ start:(token,body)=>call(token,'run',body),
578
+ onFired:({token})=>events.emit('change',{token})});
579
+ if(wakeups)waker.start();
580
+ const api={
581
+ wakeups:waker,
582
+ async create({root,title}={}){
583
+ if(typeof root!=='string'||!path.isAbsolute(root))throw new Error('Choose an existing folder');
584
+ try{if(!(await stat(root)).isDirectory())throw 0}catch{throw new Error('Choose an existing folder')}
585
+ const s=await Session.create({cwd:root,mode:'guided'});
586
+ // One web workspace per chat: its server name mini-<id> matches the local token local-<id>.
587
+ s.meta.local=true;s.meta.cloudProject=s.meta.id;
588
+ const t=typeof title==='string'?title.replace(/\s+/g,' ').trim().slice(0,160):'';if(t){s.meta.title=t;s.meta.renamed=true}
589
+ await s.save();
590
+ const out=describe(s.meta);delete out.state;
591
+ return {token:out.token,name:out.name,title:out.title,root:out.root,folder:out.folder};
592
+ },
593
+ async list(){
594
+ const out=[];
595
+ for(const m of await Session.list()){
596
+ if(m.archived||!m.id||!UUID.test(m.id))continue;
597
+ const e=live.get(m.id)||{session:{dir:path.join(sub('sessions'),m.id),meta:m},running:false};
598
+ out.push(describe(m,(await inspect(e)).state||'idle'));
599
+ }
600
+ return out;
601
+ },
602
+ call,
603
+ on:(ev,fn)=>{events.on(ev,fn);return ()=>events.off(ev,fn)},
604
+ off:(ev,fn)=>events.off(ev,fn),
605
+ /** Sends the session's compact view to the account now (a terminal session shared with /remote-control runs outside this API). */
606
+ async syncView(token){pushView(await entry(token))},
607
+ async close(){waker.stop();await setRelay(false);for(const e of live.values())if(e.session.child)await e.session.cancel().catch(()=>{});for(const c of terminals.values())killTree(c.pid)},
608
+ setRelay:on=>setRelay(on),
609
+ };
610
+ // Live control from the account's other devices (relay.mjs): an outbound long-poll, only when the app turns it on.
611
+ let control=null,want=false;
612
+ async function setRelay(on){
613
+ want=Boolean(on);
614
+ if(!want){const c=control;control=null;await c?.stop();return false}
615
+ if(control)return true;
616
+ const m=await optional('relay.mjs');if(!m?.startRelay||!want||control)return Boolean(control);
617
+ control=m.startRelay({workspaces:api,getCloud});return true;
618
+ }
619
+ if(relay)void setRelay(true).catch(()=>{});
620
+ return api;
621
+ }