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.
- package/README.md +12 -2
- package/bin/mlai.mjs +3 -0
- package/package.json +18 -3
- package/src/browser-setup.mjs +77 -0
- package/src/cli-ext.mjs +146 -0
- package/src/cli.mjs +534 -0
- package/src/cloud.mjs +29 -0
- package/src/completion.mjs +159 -0
- package/src/credentials.mjs +54 -0
- package/src/deploy.mjs +134 -0
- package/src/distribution.mjs +373 -0
- package/src/engine-key.mjs +4 -0
- package/src/engine.mjs +167 -0
- package/src/headless.mjs +196 -0
- package/src/home.mjs +22 -0
- package/src/host.mjs +123 -0
- package/src/local-models.mjs +64 -0
- package/src/modes.mjs +38 -0
- package/src/netbox.mjs +97 -0
- package/src/netjail.py +59 -0
- package/src/offline.mjs +98 -0
- package/src/parity.mjs +86 -0
- package/src/project.mjs +68 -0
- package/src/relay.mjs +140 -0
- package/src/render.mjs +73 -0
- package/src/restricted.mjs +47 -0
- package/src/review.mjs +70 -0
- package/src/runner.mjs +127 -0
- package/src/runtime.mjs +75 -0
- package/src/sandbox.mjs +135 -0
- package/src/sdk.mjs +11 -0
- package/src/server.mjs +110 -0
- package/src/session.mjs +290 -0
- package/src/settings.mjs +135 -0
- package/src/shared-data.mjs +3 -0
- package/src/tui/acp.mjs +145 -0
- package/src/tui/agents-cli.mjs +114 -0
- package/src/tui/agents-local.mjs +65 -0
- package/src/tui/ansi.mjs +123 -0
- package/src/tui/app.mjs +710 -0
- package/src/tui/approval.mjs +88 -0
- package/src/tui/bg.mjs +172 -0
- package/src/tui/bgterm.mjs +79 -0
- package/src/tui/chat.mjs +230 -0
- package/src/tui/clipboard.mjs +74 -0
- package/src/tui/cloud-cli.mjs +57 -0
- package/src/tui/cloud-run.mjs +123 -0
- package/src/tui/cmd-agents.mjs +130 -0
- package/src/tui/cmd-auto-review.mjs +94 -0
- package/src/tui/cmd-cloud.mjs +17 -0
- package/src/tui/cmd-config.mjs +104 -0
- package/src/tui/cmd-core.mjs +160 -0
- package/src/tui/cmd-distribution.mjs +15 -0
- package/src/tui/cmd-ecosystem.mjs +169 -0
- package/src/tui/cmd-extensibility.mjs +333 -0
- package/src/tui/cmd-remote.mjs +18 -0
- package/src/tui/cmd-review.mjs +58 -0
- package/src/tui/cmd-session-extra.mjs +152 -0
- package/src/tui/cmd-tui.mjs +200 -0
- package/src/tui/commands.mjs +160 -0
- package/src/tui/custom-commands.mjs +98 -0
- package/src/tui/diff.mjs +60 -0
- package/src/tui/editor.mjs +190 -0
- package/src/tui/ext-state.mjs +16 -0
- package/src/tui/extensions-local.mjs +140 -0
- package/src/tui/files.mjs +72 -0
- package/src/tui/handoff.mjs +110 -0
- package/src/tui/import-setups.mjs +151 -0
- package/src/tui/init.mjs +104 -0
- package/src/tui/keymap.mjs +70 -0
- package/src/tui/keys.mjs +101 -0
- package/src/tui/loop.mjs +75 -0
- package/src/tui/markdown.mjs +118 -0
- package/src/tui/mcp-config.mjs +225 -0
- package/src/tui/mcp-oauth.mjs +162 -0
- package/src/tui/permissions.mjs +189 -0
- package/src/tui/plain.mjs +32 -0
- package/src/tui/plugins-local.mjs +103 -0
- package/src/tui/remote.mjs +125 -0
- package/src/tui/review-cli.mjs +332 -0
- package/src/tui/review-github.mjs +59 -0
- package/src/tui/screen.mjs +60 -0
- package/src/tui/session-ops.mjs +104 -0
- package/src/tui/skills-local.mjs +92 -0
- package/src/tui/snapshots.mjs +87 -0
- package/src/tui/statusline.mjs +98 -0
- package/src/tui/transcript.mjs +116 -0
- package/src/two-words.mjs +36 -0
- package/src/wakeups.mjs +53 -0
- package/src/winenv.mjs +94 -0
- package/src/winsandbox.py +351 -0
- package/src/workspace-api.mjs +621 -0
- package/src/worktree.mjs +128 -0
- package/vendor/client-sdk/controller.cjs +115 -0
- package/vendor/client-sdk/files.cjs +38 -0
- package/vendor/client-sdk/index.cjs +133 -0
- package/vendor/client-sdk/login.cjs +52 -0
- package/vendor/client-sdk/updates.cjs +41 -0
- package/vendor/cloud-cli/mlai.mjs +394 -0
- package/worker/architecture_parse.cjs +23 -0
- package/worker/architecture_worker.py +394 -0
- package/worker/ask_first.py +96 -0
- package/worker/attachment_reader.py +66 -0
- package/worker/background_jobs.py +111 -0
- package/worker/brief_questions.py +56 -0
- package/worker/browser_local.py +49 -0
- package/worker/browser_pane.py +89 -0
- package/worker/browser_tool.py +101 -0
- package/worker/build_planner.py +187 -0
- package/worker/chat_fork.py +277 -0
- package/worker/checkpoints.py +133 -0
- package/worker/cloud_pty.py +351 -0
- package/worker/command_policy.py +39 -0
- package/worker/command_safety.py +717 -0
- package/worker/computer_card.sh +23 -0
- package/worker/computer_setup.sh +86 -0
- package/worker/computer_use.py +221 -0
- package/worker/connector_search.py +43 -0
- package/worker/context_manager.py +60 -0
- package/worker/conversation.py +144 -0
- package/worker/deploy_pack.py +116 -0
- package/worker/design_director.py +240 -0
- package/worker/dev_jobs.py +166 -0
- package/worker/edit_guard.py +99 -0
- package/worker/env_setup.py +129 -0
- package/worker/evidence.py +109 -0
- package/worker/fast_search.py +24 -0
- package/worker/git_sync.py +333 -0
- package/worker/goals.py +156 -0
- package/worker/handover.py +98 -0
- package/worker/harness_memory.py +194 -0
- package/worker/image_generation.py +173 -0
- package/worker/intelligence.py +149 -0
- package/worker/intent_model.py +78 -0
- package/worker/intent_weights.json +1 -0
- package/worker/ios_simulator.py +87 -0
- package/worker/kimi_bridge.py +997 -0
- package/worker/kimi_compact.py +93 -0
- package/worker/kimi_gates.py +304 -0
- package/worker/kimi_hook.py +617 -0
- package/worker/lifecycle.py +95 -0
- package/worker/lsp.py +77 -0
- package/worker/mcp_local.py +293 -0
- package/worker/memory.py +99 -0
- package/worker/mlai_auto_review.py +177 -0
- package/worker/mlai_hooks.py +966 -0
- package/worker/mlai_mcp.py +441 -0
- package/worker/mlai_permissions.py +283 -0
- package/worker/model_stream.py +75 -0
- package/worker/nested_repos.py +76 -0
- package/worker/offline_guard.py +17 -0
- package/worker/preview.py +806 -0
- package/worker/proc_watch.py +124 -0
- package/worker/project_context.py +72 -0
- package/worker/project_rules.py +99 -0
- package/worker/quality.py +180 -0
- package/worker/reply_language.py +56 -0
- package/worker/repo_hygiene.py +132 -0
- package/worker/repo_memory.py +101 -0
- package/worker/repo_policy.py +269 -0
- package/worker/roles.json +3173 -0
- package/worker/roles.py +303 -0
- package/worker/runner.py +1795 -0
- package/worker/runtime_control.py +205 -0
- package/worker/secret_scan.py +168 -0
- package/worker/session_hub.py +80 -0
- package/worker/skill_library.py +129 -0
- package/worker/skill_pack.py +533 -0
- package/worker/subagents.py +91 -0
- package/worker/task_controller.py +139 -0
- package/worker/task_skills.py +159 -0
- package/worker/team_checkpoint.py +33 -0
- package/worker/token_count.py +32 -0
- package/worker/tool_catalog.py +38 -0
- package/worker/upload_storage.py +531 -0
- package/worker/verification.py +725 -0
- package/worker/vision.py +84 -0
- package/worker/wakeups.py +63 -0
- package/worker/web_tools.py +203 -0
- package/worker/winproc.py +135 -0
- package/worker/work_ledger.py +117 -0
- package/worker/worktrees.py +79 -0
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shell completion for `mlai`: `mlai completion bash|zsh|fish|powershell` prints a script for that shell.
|
|
3
|
+
* Subcommands and flags come from cli.mjs (FLAGS, when it exports them) so the scripts cannot drift from the parser;
|
|
4
|
+
* test/distribution.test.mjs fails if a flag in cli.mjs is missing here. Session ids complete through
|
|
5
|
+
* `mlai __complete sessions`, so they are always current.
|
|
6
|
+
*/
|
|
7
|
+
import {MODE_NAMES} from './modes.mjs';
|
|
8
|
+
|
|
9
|
+
export const SHELLS=['bash','zsh','fish','powershell'];
|
|
10
|
+
|
|
11
|
+
export const SUBCOMMANDS=[
|
|
12
|
+
['login','Sign in with your browser'],['logout','Sign out on this device'],['whoami','Show the signed-in account'],
|
|
13
|
+
['sessions','List recent sessions'],['resume','Continue a session'],['doctor','Check this machine'],
|
|
14
|
+
['update','Update the CLI'],['completion','Print a shell completion script'],['cloud','Cloud workspaces'],['remote-control','Continue this session from the web or your phone'],
|
|
15
|
+
['serve','Run the local engine for the app and editors'],['runner','Run as a remote machine for your account'],
|
|
16
|
+
['review','Review changes, a branch or a pull request'],['acp','Run as an Agent Client Protocol server for editors'],
|
|
17
|
+
['help','Show help'],['version','Show the version'],
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
/** Fixed value lists by flag (or by the `value` kind cli.mjs gives). */
|
|
21
|
+
const VALUES={
|
|
22
|
+
'--mode':MODE_NAMES,'--effort':['low','medium','high'],'--output-format':['text','json','stream-json'],
|
|
23
|
+
'--permission-mode':MODE_NAMES,
|
|
24
|
+
};
|
|
25
|
+
const FILE_VALUES=new Set(['--add-dir','--image','--settings','--cwd','--file']);
|
|
26
|
+
|
|
27
|
+
/** The visible flags from cli.mjs FLAGS ([{flag, alias?, value?, choices?, summary, hidden?}]). */
|
|
28
|
+
export async function flags(){
|
|
29
|
+
const {FLAGS}=await import('./cli.mjs');
|
|
30
|
+
return FLAGS.filter(f=>f&&typeof f.flag==='string'&&f.flag.startsWith('--')&&!f.hidden).map(f=>({...f,summary:String(f.summary||'').replace(/\s*\n\s*/g,' ')}));
|
|
31
|
+
}
|
|
32
|
+
const SESSION_FLAGS=new Set(['--resume']);
|
|
33
|
+
const valuesFor=f=>(Array.isArray(f.choices)&&f.choices.length?f.choices:null)||VALUES[f.flag]||null;
|
|
34
|
+
const takesValue=f=>!!(f.value||VALUES[f.flag]||FILE_VALUES.has(f.flag));
|
|
35
|
+
const q=s=>"'"+String(s).replace(/'/g,"'\\''")+"'";
|
|
36
|
+
const psq=s=>"'"+String(s).replace(/'/g,"''")+"'";
|
|
37
|
+
|
|
38
|
+
export async function completionScript(shell){
|
|
39
|
+
const fl=await flags();
|
|
40
|
+
const names=fl.flatMap(f=>[f.flag,f.alias].filter(Boolean));
|
|
41
|
+
const subs=SUBCOMMANDS.map(s=>s[0]);
|
|
42
|
+
const valued=fl.filter(f=>valuesFor(f));
|
|
43
|
+
const files=fl.filter(f=>FILE_VALUES.has(f.flag));
|
|
44
|
+
const sessions=fl.filter(f=>SESSION_FLAGS.has(f.flag));
|
|
45
|
+
const free=fl.filter(f=>takesValue(f)&&!valuesFor(f)&&!FILE_VALUES.has(f.flag)&&!SESSION_FLAGS.has(f.flag));
|
|
46
|
+
const pat=f=>[f.flag,f.alias].filter(Boolean).join('|');
|
|
47
|
+
if(shell==='bash')return `# mlai completion for bash.
|
|
48
|
+
# Load now: eval "$(mlai completion bash)"
|
|
49
|
+
# Install: mlai completion bash > ~/.local/share/bash-completion/completions/mlai
|
|
50
|
+
_mlai() {
|
|
51
|
+
local cur prev
|
|
52
|
+
cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
53
|
+
prev="\${COMP_WORDS[COMP_CWORD-1]}"
|
|
54
|
+
COMPREPLY=()
|
|
55
|
+
case "$prev" in
|
|
56
|
+
${valued.map(f=>` ${pat(f)}) COMPREPLY=($(compgen -W ${q(valuesFor(f).join(' '))} -- "$cur")); return 0;;`).join('\n')}
|
|
57
|
+
${files.length?` ${files.map(pat).join('|')}) COMPREPLY=($(compgen -f -- "$cur")); return 0;;\n`:''}${free.length?` ${free.map(pat).join('|')}) return 0;;\n`:''} completion) [ "$COMP_CWORD" -eq 2 ] && COMPREPLY=($(compgen -W ${q(SHELLS.join(' '))} -- "$cur")); return 0;;
|
|
58
|
+
resume${sessions.map(f=>'|'+pat(f)).join('')}) COMPREPLY=($(compgen -W "$(mlai __complete sessions 2>/dev/null)" -- "$cur")); return 0;;
|
|
59
|
+
update) COMPREPLY=($(compgen -W '--check --json' -- "$cur")); return 0;;
|
|
60
|
+
esac
|
|
61
|
+
if [[ "$cur" == -* ]]; then
|
|
62
|
+
COMPREPLY=($(compgen -W ${q(names.join(' '))} -- "$cur"))
|
|
63
|
+
elif [ "$COMP_CWORD" -eq 1 ]; then
|
|
64
|
+
COMPREPLY=($(compgen -W ${q(subs.join(' '))} -- "$cur"))
|
|
65
|
+
fi
|
|
66
|
+
return 0
|
|
67
|
+
}
|
|
68
|
+
complete -o default -F _mlai mlai
|
|
69
|
+
`;
|
|
70
|
+
if(shell==='zsh'){
|
|
71
|
+
const zesc=s=>String(s).replace(/:/g,'\\:').replace(/'/g,"'\\''");
|
|
72
|
+
return `#compdef mlai
|
|
73
|
+
# mlai completion for zsh.
|
|
74
|
+
# Load now: source <(mlai completion zsh)
|
|
75
|
+
# Install: mlai completion zsh > "\${fpath[1]}/_mlai" (then restart the shell)
|
|
76
|
+
_mlai() {
|
|
77
|
+
local -a subcmds opts
|
|
78
|
+
subcmds=(
|
|
79
|
+
${SUBCOMMANDS.map(([n,d])=>` '${zesc(n)}:${zesc(d)}'`).join('\n')}
|
|
80
|
+
)
|
|
81
|
+
opts=(
|
|
82
|
+
${fl.flatMap(f=>[f.flag,f.alias].filter(Boolean).map(n=>` '${zesc(n)}:${zesc(f.summary||'')}'`)).join('\n')}
|
|
83
|
+
)
|
|
84
|
+
case "\${words[CURRENT-1]}" in
|
|
85
|
+
${valued.map(f=>` ${pat(f)}) compadd -- ${valuesFor(f).join(' ')}; return;;`).join('\n')}
|
|
86
|
+
${files.length?` ${files.map(pat).join('|')}) _files; return;;\n`:''}${free.length?` ${free.map(pat).join('|')}) return;;\n`:''} completion) (( CURRENT == 3 )) && compadd -- ${SHELLS.join(' ')}; return;;
|
|
87
|
+
resume) (( CURRENT == 3 )) && compadd -- \${(f)"$(mlai __complete sessions 2>/dev/null)"}; return;;
|
|
88
|
+
update) compadd -- --check --json; return;;
|
|
89
|
+
esac
|
|
90
|
+
if [[ "\${words[CURRENT]}" == -* ]]; then
|
|
91
|
+
_describe -t options 'option' opts
|
|
92
|
+
elif (( CURRENT == 2 )); then
|
|
93
|
+
_describe -t commands 'command' subcmds
|
|
94
|
+
else
|
|
95
|
+
_files
|
|
96
|
+
fi
|
|
97
|
+
}
|
|
98
|
+
if [ "\${funcstack[1]}" = "_mlai" ]; then
|
|
99
|
+
_mlai "$@"
|
|
100
|
+
else
|
|
101
|
+
compdef _mlai mlai
|
|
102
|
+
fi
|
|
103
|
+
`;
|
|
104
|
+
}
|
|
105
|
+
if(shell==='fish'){
|
|
106
|
+
const fesc=s=>"'"+String(s).replace(/\\/g,'\\\\').replace(/'/g,"\\'")+"'";
|
|
107
|
+
const line=f=>{
|
|
108
|
+
const parts=['complete -c mlai','-l '+f.flag.slice(2)];
|
|
109
|
+
if(f.alias&&/^-[A-Za-z]$/.test(f.alias))parts.push('-s '+f.alias.slice(1));
|
|
110
|
+
const v=valuesFor(f);
|
|
111
|
+
if(v)parts.push('-x -a '+fesc(v.join(' ')));else if(SESSION_FLAGS.has(f.flag))parts.push("-x -a '(mlai __complete sessions 2>/dev/null)'");else if(FILE_VALUES.has(f.flag))parts.push('-r -F');else if(takesValue(f))parts.push('-x');
|
|
112
|
+
if(f.summary)parts.push('-d '+fesc(f.summary));
|
|
113
|
+
return parts.join(' ');
|
|
114
|
+
};
|
|
115
|
+
return `# mlai completion for fish.
|
|
116
|
+
# Load now: mlai completion fish | source
|
|
117
|
+
# Install: mlai completion fish > ~/.config/fish/completions/mlai.fish
|
|
118
|
+
complete -c mlai -e
|
|
119
|
+
${SUBCOMMANDS.map(([n,d])=>`complete -c mlai -f -n '__fish_use_subcommand' -a ${n} -d ${fesc(d)}`).join('\n')}
|
|
120
|
+
${fl.map(line).join('\n')}
|
|
121
|
+
complete -c mlai -f -n '__fish_seen_subcommand_from completion' -a ${fesc(SHELLS.join(' '))}
|
|
122
|
+
complete -c mlai -f -n '__fish_seen_subcommand_from resume' -a '(mlai __complete sessions 2>/dev/null)'
|
|
123
|
+
complete -c mlai -f -n '__fish_seen_subcommand_from update' -l check -d 'Only report whether an update is available'
|
|
124
|
+
`;
|
|
125
|
+
}
|
|
126
|
+
if(shell==='powershell'){
|
|
127
|
+
const valueMap=valued.flatMap(f=>[f.flag,f.alias].filter(Boolean).map(n=>` ${psq(n)} = @(${valuesFor(f).map(psq).join(', ')})`));
|
|
128
|
+
return `# mlai completion for PowerShell.
|
|
129
|
+
# Load now: mlai completion powershell | Out-String | Invoke-Expression
|
|
130
|
+
# Install: add that line to $PROFILE
|
|
131
|
+
Register-ArgumentCompleter -Native -CommandName mlai, mlai.cmd -ScriptBlock {
|
|
132
|
+
param($wordToComplete, $commandAst, $cursorPosition)
|
|
133
|
+
$words = @($commandAst.CommandElements | ForEach-Object { $_.ToString() })
|
|
134
|
+
$index = if ($wordToComplete) { $words.Count - 1 } else { $words.Count }
|
|
135
|
+
$prev = if ($index -ge 1) { $words[$index - 1] } else { '' }
|
|
136
|
+
$subcommands = @(${subs.map(psq).join(', ')})
|
|
137
|
+
$flags = @(${names.map(psq).join(', ')})
|
|
138
|
+
$values = @{
|
|
139
|
+
${valueMap.join('\n')}
|
|
140
|
+
}
|
|
141
|
+
$candidates = if ($values.ContainsKey($prev)) { $values[$prev] }
|
|
142
|
+
elseif ($prev -eq 'completion' -and $index -eq 2) { @(${SHELLS.map(psq).join(', ')}) }
|
|
143
|
+
elseif (($prev -eq 'resume' -and $index -eq 2)${sessions.flatMap(f=>[f.flag,f.alias].filter(Boolean)).map(n=>` -or $prev -eq ${psq(n)}`).join('')}) { @(mlai __complete sessions 2>$null) }
|
|
144
|
+
elseif ($wordToComplete -like '-*') { $flags }
|
|
145
|
+
elseif ($index -eq 1) { $subcommands }
|
|
146
|
+
else { @() }
|
|
147
|
+
$candidates | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
|
|
148
|
+
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
`;
|
|
152
|
+
}
|
|
153
|
+
throw new Error('Shells: '+SHELLS.join(', '));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const INSTALL_HELP=` bash eval "$(mlai completion bash)" (add to ~/.bashrc)
|
|
157
|
+
zsh source <(mlai completion zsh) (add to ~/.zshrc)
|
|
158
|
+
fish mlai completion fish > ~/.config/fish/completions/mlai.fish
|
|
159
|
+
powershell mlai completion powershell | Out-String | Invoke-Expression (add to $PROFILE)`;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {execFile} from 'node:child_process';
|
|
2
|
+
import {promisify} from 'node:util';
|
|
3
|
+
import {readFile,writeFile,rm,chmod} from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {home} from './home.mjs';
|
|
6
|
+
const run=promisify(execFile);
|
|
7
|
+
const SERVICE='ML AI Code',ACCOUNT='device-token';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The device credential is kept in the OS keychain (macOS Keychain, or the Secret Service on Linux).
|
|
11
|
+
* Without a keychain it falls back to a 0600 file in ~/.mlai. MLAI_TOKEN overrides both for CI.
|
|
12
|
+
* Metadata (server, expiry, label) is stored separately and never contains the token.
|
|
13
|
+
*/
|
|
14
|
+
async function keychain(){
|
|
15
|
+
if(process.env.MLAI_KEYCHAIN==='file')return null;
|
|
16
|
+
if(process.platform==='darwin')return {
|
|
17
|
+
get:async()=>(await run('security',['find-generic-password','-s',SERVICE,'-a',ACCOUNT,'-w'])).stdout.trim(),
|
|
18
|
+
set:async v=>{await run('security',['add-generic-password','-U','-s',SERVICE,'-a',ACCOUNT,'-w',v])},
|
|
19
|
+
del:async()=>{await run('security',['delete-generic-password','-s',SERVICE,'-a',ACCOUNT]).catch(()=>{})},
|
|
20
|
+
};
|
|
21
|
+
if(process.platform==='linux'){
|
|
22
|
+
try{await run('secret-tool',['--version'])}catch{return null}
|
|
23
|
+
return {
|
|
24
|
+
get:async()=>(await run('secret-tool',['lookup','service',SERVICE,'account',ACCOUNT])).stdout.trim(),
|
|
25
|
+
set:async v=>{await new Promise((resolve,reject)=>{const c=execFile('secret-tool',['store','--label',SERVICE,'service',SERVICE,'account',ACCOUNT],e=>e?reject(e):resolve());c.stdin.end(v)})},
|
|
26
|
+
del:async()=>{await run('secret-tool',['clear','service',SERVICE,'account',ACCOUNT]).catch(()=>{})},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const metaFile=()=>path.join(home(),'auth.json');
|
|
32
|
+
const tokenFile=()=>path.join(home(),'.device-token');
|
|
33
|
+
|
|
34
|
+
export async function saveLogin({server,token,expires,deviceId,label}){
|
|
35
|
+
const k=await keychain();let store='file';
|
|
36
|
+
if(k){try{await k.set(token);store='keychain'}catch{}}
|
|
37
|
+
if(store==='file'){await writeFile(tokenFile(),token,{mode:0o600});await chmod(tokenFile(),0o600)}
|
|
38
|
+
else await rm(tokenFile(),{force:true});
|
|
39
|
+
await writeFile(metaFile(),JSON.stringify({server,expires,deviceId,label,store},null,1),{mode:0o600});
|
|
40
|
+
return store;
|
|
41
|
+
}
|
|
42
|
+
export async function loadLogin(){
|
|
43
|
+
if(process.env.MLAI_TOKEN)return {server:process.env.MLAI_SERVER,token:process.env.MLAI_TOKEN,expires:null,store:'env'};
|
|
44
|
+
let meta;try{meta=JSON.parse(await readFile(metaFile(),'utf8'))}catch{return null}
|
|
45
|
+
let token='';
|
|
46
|
+
if(meta.store==='keychain'){const k=await keychain();try{token=k?await k.get():''}catch{}}
|
|
47
|
+
else{try{token=(await readFile(tokenFile(),'utf8')).trim()}catch{}}
|
|
48
|
+
if(!token)return null;
|
|
49
|
+
return {...meta,token};
|
|
50
|
+
}
|
|
51
|
+
export async function clearLogin(){
|
|
52
|
+
const k=await keychain();if(k)await k.del();
|
|
53
|
+
await rm(tokenFile(),{force:true});await rm(metaFile(),{force:true});
|
|
54
|
+
}
|
package/src/deploy.mjs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deploys requested by a local run (worker/mlai_mcp.py deploy tool -> pending approval of kind 'deploy').
|
|
3
|
+
*
|
|
4
|
+
* Design: the Mac never holds a host token. Deploy tokens are hidden from agent runs (agent:false in the Vault) and a
|
|
5
|
+
* production-capable credential on a laptop, next to the agent's processes, is the wrong trade. Instead the Mac packs
|
|
6
|
+
* the project with worker/deploy_pack.py (the same MLAIPACK1 bundle cloud uses), uploads it to ML AI Code with the
|
|
7
|
+
* device credential, and the server deploys it with the account's deploy target, exactly like cloud. The run token is
|
|
8
|
+
* never used: the agent's processes hold it, so a run-token deploy would skip the person's approval.
|
|
9
|
+
*
|
|
10
|
+
* Preview first; production only after a person approves the promotion (an automatic approval never promotes from
|
|
11
|
+
* this Mac, whatever the repository policy says).
|
|
12
|
+
*
|
|
13
|
+
* Server API (POST /api/laptop/deploy, device credential only, lib/laptop-deploy.ts):
|
|
14
|
+
* {op:'target'|'upload'|'chunk'|'preview'|'status'|'logs'|'promote', runId, project, ...}
|
|
15
|
+
*/
|
|
16
|
+
import {spawn,execFile} from 'node:child_process';
|
|
17
|
+
import {promisify} from 'node:util';
|
|
18
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
19
|
+
import {readFile,rm,stat} from 'node:fs/promises';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import {wrap} from './sandbox.mjs';
|
|
23
|
+
import {home} from './home.mjs';
|
|
24
|
+
const git=promisify(execFile);
|
|
25
|
+
|
|
26
|
+
export const CHUNK_BYTES=2_500_000;
|
|
27
|
+
export const MAX_BUNDLE=50_000_000;
|
|
28
|
+
export const PERSON_NEEDED='Production promotion needs a person to approve it. Open the card to review and promote.';
|
|
29
|
+
const ID=/^[A-Za-z0-9_-]{4,80}$/;
|
|
30
|
+
|
|
31
|
+
/** "owner/name" from a GitHub remote, or ''. */
|
|
32
|
+
export function repoSlug(url){
|
|
33
|
+
const m=/github\.com[:/]+([\w.-]+)\/([\w.-]+?)(\.git)?\/?$/i.exec(String(url||'').trim());
|
|
34
|
+
return m?m[1]+'/'+m[2]:'';
|
|
35
|
+
}
|
|
36
|
+
async function gitOut(root,args){try{return (await git('git',['-C',root,...args],{timeout:15000})).stdout.trim()}catch{return ''}}
|
|
37
|
+
export async function sourceMeta(root){
|
|
38
|
+
const [remote,branch,commit,dirty,message]=await Promise.all([gitOut(root,['config','--get','remote.origin.url']),gitOut(root,['rev-parse','--abbrev-ref','HEAD']),gitOut(root,['rev-parse','HEAD']),gitOut(root,['status','--porcelain']),gitOut(root,['log','-1','--format=%s'])]);
|
|
39
|
+
return {repository:repoSlug(remote),branch:branch==='HEAD'?'':branch,commit:/^[0-9a-f]{40}$/.test(commit)?commit:'',dirty:Boolean(dirty),message:message.slice(0,140)};
|
|
40
|
+
}
|
|
41
|
+
async function localChecks(dir){
|
|
42
|
+
try{const c=JSON.parse(await readFile(path.join(dir,'completion.json'),'utf8'));return {passed:Number(c.checksPassed)||0,failed:Number(c.checksFailed)||0}}catch{return null}
|
|
43
|
+
}
|
|
44
|
+
function run(cmd,args,{cwd,env,timeoutMs=600000,spawnImpl=spawn}){
|
|
45
|
+
return new Promise((resolve,reject)=>{
|
|
46
|
+
const c=spawnImpl(cmd,args,{cwd,env,stdio:['ignore','pipe','pipe']});let out='',err='';
|
|
47
|
+
const t=setTimeout(()=>{try{c.kill('SIGKILL')}catch{}},timeoutMs);
|
|
48
|
+
c.stdout?.on('data',d=>{out=(out+d).slice(-20000)});c.stderr?.on('data',d=>{err=(err+d).slice(-4000)});
|
|
49
|
+
c.on('error',e=>{clearTimeout(t);reject(e)});c.on('exit',code=>{clearTimeout(t);resolve({code,out,err})});
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/** Packs the project (or a build output folder) with the harness's own packer. Returns the bundle and its stats. */
|
|
53
|
+
export async function packProject({root,python,worker,outputDir,spawnImpl}){
|
|
54
|
+
const out=path.join(os.tmpdir(),'mlai-deploy-'+randomBytes(6).toString('hex')+'.pack');
|
|
55
|
+
try{
|
|
56
|
+
const args=[path.join(worker,'deploy_pack.py'),out,...(outputDir?['--root',outputDir]:[])];
|
|
57
|
+
const r=await run(python,args,{cwd:root,env:{PATH:process.env.PATH||'',HOME:process.env.HOME||'',MINI_REPO:root,PYTHONDONTWRITEBYTECODE:'1'},spawnImpl,timeoutMs:180000});
|
|
58
|
+
let stats={};try{stats=JSON.parse(r.out.trim().split('\n').pop()||'{}')}catch{}
|
|
59
|
+
if(r.code!==0||stats.error)throw new Error(stats.error||'Packing the project failed: '+r.err.trim().split('\n').slice(-2).join(' '));
|
|
60
|
+
const bundle=await readFile(out);
|
|
61
|
+
if(bundle.length>MAX_BUNDLE)throw new Error('The project is larger than 50 MB after skipping dependencies and build folders. Add a .vercelignore for large assets.');
|
|
62
|
+
return {bundle,stats};
|
|
63
|
+
}finally{await rm(out,{force:true})}
|
|
64
|
+
}
|
|
65
|
+
/** Builds a static site inside the same OS sandbox as the agent (the command is the person's own deploy setting). */
|
|
66
|
+
async function buildStatic({root,dir,python,worker,build,spawnImpl}){
|
|
67
|
+
if(!build?.command)return;
|
|
68
|
+
const box={repo:root,state:dir,runtime:path.dirname(path.dirname(python)),worker,mlaiHome:home()};
|
|
69
|
+
const w=wrap('/bin/sh',['-c',build.command],box)||{cmd:'/bin/sh',args:['-c',build.command]};
|
|
70
|
+
const r=await run(w.cmd,w.args,{cwd:root,env:{PATH:process.env.PATH||'',HOME:process.env.HOME||'',CI:'1',...(w.env||{})},spawnImpl});
|
|
71
|
+
if(r.code!==0)throw new Error('The build command failed: '+(r.err||r.out).trim().split('\n').slice(-4).join(' ').slice(0,600));
|
|
72
|
+
}
|
|
73
|
+
async function readJsonFile(f){try{return JSON.parse(await readFile(f,'utf8'))}catch{return null}}
|
|
74
|
+
/** Static hosts: the saved build settings, or (none saved) `npm run build` when package.json has a build script. */
|
|
75
|
+
export async function staticBuild(root,b){
|
|
76
|
+
if(!b.detect)return {command:String(b.command||''),output:String(b.output||'').replace(/^\.?\/+/,'').replace(/\/+$/,'')};
|
|
77
|
+
const pkg=await readJsonFile(path.join(root,'package.json'));
|
|
78
|
+
return {command:pkg?.scripts?.build?'npm run build':'',output:''};
|
|
79
|
+
}
|
|
80
|
+
export async function findOutput(root){
|
|
81
|
+
for(const d of ['dist','build','out','public','_site']){try{if((await stat(path.join(root,d,'index.html'))).isFile())return d}catch{/* next */}}
|
|
82
|
+
return '';
|
|
83
|
+
}
|
|
84
|
+
const call=(cloud,body)=>cloud.device.request('/api/laptop/deploy',body);
|
|
85
|
+
|
|
86
|
+
/** Uploads a bundle in chunks under the request body limit; the server checks the hash. */
|
|
87
|
+
export async function uploadBundle(cloud,runId,bundle,project){
|
|
88
|
+
const sha256=createHash('sha256').update(bundle).digest('hex');
|
|
89
|
+
const u=await call(cloud,{op:'upload',runId,project,size:bundle.length,sha256});
|
|
90
|
+
if(!u?.uploadId)throw new Error('The deploy upload did not start. Try again.');
|
|
91
|
+
const size=Math.min(CHUNK_BYTES,Number(u.chunkBytes)||CHUNK_BYTES),total=Math.max(1,Math.ceil(bundle.length/size));
|
|
92
|
+
for(let i=0;i<total;i++)await call(cloud,{op:'chunk',runId,project,uploadId:u.uploadId,index:i,total,data:bundle.subarray(i*size,(i+1)*size).toString('base64')});
|
|
93
|
+
return {uploadId:u.uploadId,sha256};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Performs one approved deploy request and returns what the harness reads from result-<id>. Never throws: errors come
|
|
98
|
+
* back as {error} so the agent reports them. approvedBy is 'person' when someone tapped Approve, 'auto' otherwise.
|
|
99
|
+
*/
|
|
100
|
+
export async function fulfilLocalDeploy(pending,{cloud,dir,root,runId,python,worker,approvedBy='auto',spawnImpl}={}){
|
|
101
|
+
const action=String(pending?.action||'');
|
|
102
|
+
try{
|
|
103
|
+
if(!['preview','status','logs','promote'].includes(action))return {error:'Unknown deploy request'};
|
|
104
|
+
if(action==='promote'&&approvedBy!=='person')return {error:PERSON_NEEDED,code:'person_required'};
|
|
105
|
+
if(!runId||String(runId).startsWith('local-'))return {error:'Deploys are not available offline. Reconnect, then ask again.',code:'offline'};
|
|
106
|
+
if(!cloud?.device)return {error:'Sign in to ML AI Code on this Mac to deploy.',code:'device_required'};
|
|
107
|
+
// Shell-created workspaces keep the server project in cloudProject (meta.project is the local one), as the engine's start does.
|
|
108
|
+
const sess=await readJsonFile(path.join(dir||'','session.json'));
|
|
109
|
+
const project=String(sess?.cloudProject||sess?.project||'');
|
|
110
|
+
const dep=String(pending.deployment||'');
|
|
111
|
+
if(action!=='preview'&&!ID.test(dep))return {error:'Pass the deployment id returned by deploy preview'};
|
|
112
|
+
if(action==='status')return await call(cloud,{op:'status',runId,project,deployment:dep,wait:60000});
|
|
113
|
+
if(action==='logs')return await call(cloud,{op:'logs',runId,project,deployment:dep});
|
|
114
|
+
if(action==='promote')return await call(cloud,{op:'promote',runId,project,deployment:dep,confirm:true,by:'person',checks:await localChecks(dir),reason:String(pending.reason||'').slice(0,300)});
|
|
115
|
+
// Preview: pack here, upload, the server deploys with the account's target. Static hosts get their build run here first.
|
|
116
|
+
const meta=await sourceMeta(root);
|
|
117
|
+
const target=await call(cloud,{op:'target',runId,project,meta});
|
|
118
|
+
let outputDir;
|
|
119
|
+
const build=target?.build?await staticBuild(root,target.build):null;
|
|
120
|
+
if(build?.command)await buildStatic({root,dir,python,worker,build,spawnImpl});
|
|
121
|
+
if(build){
|
|
122
|
+
const out=build.output||(build.command?await findOutput(root):'');
|
|
123
|
+
if(build.command&&!out)return {error:'The build finished, but there is no dist, build, out or public folder with an index.html. Set the output folder in Deploys.'};
|
|
124
|
+
if(out){outputDir=path.resolve(root,out);if(path.relative(root,outputDir).startsWith('..'))return {error:'The output folder must be inside the project.'}}
|
|
125
|
+
}
|
|
126
|
+
const packed=await packProject({root,python,worker,outputDir,spawnImpl});
|
|
127
|
+
const up=await uploadBundle(cloud,runId,packed.bundle,project);
|
|
128
|
+
return await call(cloud,{op:'preview',runId,project,uploadId:up.uploadId,sha256:up.sha256,meta,checks:await localChecks(dir),stats:{files:packed.stats.files,bytes:packed.stats.bytes,skipped:(packed.stats.skipped||[]).slice(0,20)}});
|
|
129
|
+
}catch(e){
|
|
130
|
+
const msg=String(e?.message||e).slice(0,800);
|
|
131
|
+
if(e?.status===404||/Unknown laptop operation/i.test(msg))return {error:'Deploys from this Mac need a newer ML AI Code server. Deploy from the web app for now.',code:'not_supported'};
|
|
132
|
+
return {error:msg,...(e?.code?{code:e.code}:{})};
|
|
133
|
+
}
|
|
134
|
+
}
|