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,177 @@
1
+ """Auto-review: in auto mode, a reviewer model pass gates risky actions before they run.
2
+
3
+ risk() flags an action with a short reason (or None); gate() asks the reviewer model once per action and returns a
4
+ block message when it denies. Denied actions are recorded in ROOT/auto-review/denied.json; the CLI's /approve writes
5
+ the fingerprint to approved.json and the next identical action runs once without review (the grant is consumed).
6
+ Settings come from request.json extensions.autoReview: {enabled: bool, model: str}. Off unless enabled is true.
7
+ """
8
+ import hashlib, json, os, re, time, urllib.request
9
+ from pathlib import Path
10
+
11
+ DIR = 'auto-review'
12
+ MAX_DENIED = 50
13
+ TIMEOUT = 45
14
+
15
+ # (pattern, reason): commands that can destroy work, leave the machine, or change things outside the repository.
16
+ COMMANDS = [
17
+ (r'\brm\s+(-\w*[rf]\w*\s+)+', 'deletes files recursively or by force'),
18
+ (r'\bgit\s+push\b', 'pushes to a remote'),
19
+ (r'\bgit\s+reset\s+--hard\b', 'discards uncommitted work'),
20
+ (r'\bgit\s+clean\s+-\w*f', 'deletes untracked files'),
21
+ (r'\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)', 'discards uncommitted changes'),
22
+ (r'\bgit\s+(branch\s+-D|stash\s+(drop|clear)|rebase|filter-branch|update-ref\s+-d)\b', 'rewrites or drops git history'),
23
+ (r'\bsudo\b|\bdoas\b', 'runs as administrator'),
24
+ (r'\b(curl|wget)\b[^|;&]*\|\s*(sudo\s+)?(ba|z|da)?sh\b', 'pipes a download into a shell'),
25
+ (r'\b(curl|wget|http)\b.*\s(-X\s*(POST|PUT|PATCH|DELETE)|--data|-d\s|-F\s|--upload-file|-T\s)', 'sends data to a server'),
26
+ (r'\b(scp|rsync|sftp|ssh)\s', 'connects to another machine'),
27
+ (r'\bchmod\s+(-R\s+)?(777|a\+w|-R)|\bchown\b', 'changes file permissions or owners'),
28
+ (r'\b(dd\s+if=|mkfs|diskutil\s+erase|shred)\b', 'writes raw disks'),
29
+ (r'\b(kill\s+-9|killall|pkill)\b', 'kills processes'),
30
+ (r'\b(npm|pnpm|yarn)\s+publish\b|\b(twine|cargo|gem)\s+(upload|publish|push)\b', 'publishes a package'),
31
+ (r'\b(vercel|netlify|fly|heroku)\b.*\b(deploy|--prod)\b|\bgh\s+(pr\s+merge|release\s+create|repo\s+delete|secret)\b', 'deploys or changes a hosted service'),
32
+ (r'\b(terraform|pulumi)\s+(apply|destroy)\b|\bkubectl\s+(apply|delete|drain)\b|\bhelm\s+(install|upgrade|uninstall)\b', 'changes infrastructure'),
33
+ (r'\bdocker\s+(system\s+prune|rm|rmi|volume\s+rm)\b', 'deletes containers or images'),
34
+ (r'\b(drop\s+(table|database|schema)|truncate\s+table|delete\s+from)\b', 'deletes database data'),
35
+ (r'\b(pip|pip3|npm|pnpm|yarn|brew|apt|apt-get)\s+(install|add|i)\b[^;&|]*\b(-g|--global|git\+|https?://)', 'installs software globally or from a URL'),
36
+ (r'\b(printenv|env)\s*($|\|)|\bcat\s+[^;&|]*(\.env|id_rsa|\.npmrc|\.netrc|credentials)', 'reads secrets'),
37
+ (r'>\s*(/etc|/usr|/System|~/\.|\$HOME/\.)', 'writes outside the repository'),
38
+ (r'\bcrontab\b|\blaunchctl\s+(load|bootstrap)\b|\bsystemctl\s+(enable|start)\b', 'installs a background service'),
39
+ ]
40
+ _COMPILED = [(re.compile(p, re.I), r) for p, r in COMMANDS]
41
+ SENSITIVE = re.compile(r'(^|/)(\.env(\..*)?|\.github/workflows/.*|\.mlai/settings(\.local)?\.json|\.npmrc|\.netrc|id_rsa.*|.*\.pem|.*\.key)$', re.I)
42
+ EDIT_TOOLS = ('write', 'edit', 'create', 'patch', 'delete', 'move', 'rename', 'apply')
43
+
44
+ PROMPT = ('You review actions an autonomous coding agent wants to take on the user\'s computer without asking. '
45
+ 'Allow an action when it is a reasonable, expected step for the user\'s task. Deny it when it is destructive beyond '
46
+ 'what the task needs, sends code or secrets somewhere the task did not ask for, changes things outside the project, '
47
+ 'or looks like the agent working around a restriction. Reply with JSON only: {"decision":"allow"|"deny","reason":"one short sentence"}.')
48
+
49
+
50
+ def _dir(root): return Path(root) / DIR
51
+ def _read(p, default):
52
+ try: return json.loads(Path(p).read_text())
53
+ except (OSError, ValueError): return default
54
+ def _write(p, v):
55
+ try: Path(p).parent.mkdir(parents=True, exist_ok=True); tmp = Path(str(p) + '.tmp'); tmp.write_text(json.dumps(v, indent=1)); tmp.replace(p)
56
+ except OSError: pass
57
+
58
+
59
+ def config(root):
60
+ """extensions.autoReview from request.json: {'enabled': bool, 'model': str|None}."""
61
+ req = _read(Path(root) / 'request.json', {})
62
+ ar = (req.get('extensions') or {}).get('autoReview') if isinstance(req.get('extensions'), dict) else None
63
+ if ar is True: ar = {'enabled': True}
64
+ if not isinstance(ar, dict): return {'enabled': False}
65
+ return {'enabled': ar.get('enabled') is True, 'model': ar.get('model') if isinstance(ar.get('model'), str) and ar.get('model').strip() else None}
66
+
67
+
68
+ def _paths(path): return [p for p in ([path] if isinstance(path, str) else list(path or [])) if isinstance(p, str) and p]
69
+
70
+
71
+ def _outside(p, repo):
72
+ if not repo: return False
73
+ try: full = (Path(repo) / os.path.expanduser(p)).resolve(); return not str(full).startswith(str(Path(repo).resolve()) + os.sep) and full != Path(repo).resolve()
74
+ except (OSError, ValueError): return False
75
+
76
+
77
+ def risk(tool, args, command=None, path=None, repo=None):
78
+ """A short reason when the action is risky enough for review, else None."""
79
+ if command:
80
+ for rx, why in _COMPILED:
81
+ if rx.search(command): return why
82
+ name = str(tool or '').lower()
83
+ if name.startswith('connector:') or name.startswith('mcp__') and not name.startswith('mcp__mlai__'): return 'uses a connected service'
84
+ if any(k in name for k in EDIT_TOOLS):
85
+ for p in _paths(path):
86
+ if _outside(p, repo): return 'edits a file outside the repository'
87
+ if SENSITIVE.search(p.replace('\\', '/')): return 'edits a sensitive file (' + p + ')'
88
+ return None
89
+
90
+
91
+ def fingerprint(tool, command=None, path=None):
92
+ return hashlib.sha256(json.dumps([str(tool or ''), str(command or '').strip(), sorted(_paths(path))]).encode()).hexdigest()[:16]
93
+
94
+
95
+ def describe(tool, args, command=None, path=None):
96
+ if command: return command[:400]
97
+ ps = _paths(path)
98
+ return (str(tool) + (' ' + ', '.join(ps[:5]) if ps else '') + ('' if ps else ' ' + json.dumps(args, default=str)[:300])).strip()
99
+
100
+
101
+ def _parse(text):
102
+ m = re.search(r'\{.*\}', str(text or ''), re.S)
103
+ try: v = json.loads(m.group(0)) if m else None
104
+ except ValueError: v = None
105
+ if isinstance(v, dict) and v.get('decision') in ('allow', 'deny'): return v['decision'], str(v.get('reason') or '')[:300]
106
+ low = str(text or '').strip().lower()
107
+ if low.startswith('allow'): return 'allow', ''
108
+ if low.startswith('deny'): return 'deny', str(text).strip()[4:].strip(' :.-')[:300]
109
+ return None, 'The reviewer gave no clear decision.'
110
+
111
+
112
+ def ask_model(action, why, task, root, model=None, opener=None):
113
+ """One reviewer call through the run's endpoint and token. Returns (decision, reason); decision None on failure."""
114
+ req = _read(Path(root) / 'request.json', {})
115
+ endpoint = str(req.get('endpoint') or '').rstrip('/'); key = os.environ.get('MODEL_API_KEY', '')
116
+ if not endpoint: return None, 'No model endpoint for the reviewer.'
117
+ model = model or req.get('model') or 'mlai-code'; provider = req.get('provider')
118
+ user = 'Task: ' + str(task or req.get('task') or '')[:3000] + '\n\nAction: ' + action + '\nWhy it was flagged: ' + why
119
+ if provider == 'anthropic':
120
+ payload = {'model': model, 'max_tokens': 200, 'system': PROMPT, 'messages': [{'role': 'user', 'content': user}]}
121
+ headers = {'x-api-key': key, 'anthropic-version': '2023-06-01', 'Content-Type': 'application/json'}; suffix = '/messages'
122
+ else:
123
+ payload = {'model': model, 'messages': [{'role': 'system', 'content': PROMPT}, {'role': 'user', 'content': user}], 'temperature': 0}
124
+ payload['max_completion_tokens' if provider == 'openai' else 'max_tokens'] = 200
125
+ headers = {'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'}; suffix = '/chat/completions'
126
+ try:
127
+ r = (opener or urllib.request.urlopen)(urllib.request.Request(endpoint + suffix, data=json.dumps(payload).encode(), headers=headers), timeout=TIMEOUT)
128
+ body = json.loads(r.read().decode())
129
+ except Exception as exc: return None, 'The reviewer could not be reached (' + type(exc).__name__ + ').'
130
+ if provider == 'anthropic': text = ''.join(b.get('text', '') for b in body.get('content') or [] if isinstance(b, dict))
131
+ else: text = ((body.get('choices') or [{}])[0].get('message') or {}).get('content') or ''
132
+ return _parse(text)
133
+
134
+
135
+ def _emit(root, **data):
136
+ try:
137
+ with (Path(root) / 'events.jsonl').open('a') as f: f.write(json.dumps({'type': 'policy', 'time': time.time(), 'autoReview': True, **data}) + '\n')
138
+ except OSError: pass
139
+
140
+
141
+ def take_approval(root, fp):
142
+ """Consumes a one-shot /approve grant for this fingerprint. True when there was one."""
143
+ p = _dir(root) / 'approved.json'; grants = _read(p, [])
144
+ if not isinstance(grants, list) or fp not in grants: return False
145
+ grants.remove(fp); _write(p, grants); return True
146
+
147
+
148
+ def record_denied(root, item):
149
+ p = _dir(root) / 'denied.json'; items = _read(p, [])
150
+ items = [i for i in (items if isinstance(items, list) else []) if isinstance(i, dict) and i.get('fingerprint') != item['fingerprint']]
151
+ _write(p, (items + [item])[-MAX_DENIED:])
152
+
153
+
154
+ _ALLOWED = {} # fingerprint -> True for this process: an allowed action is not reviewed again in the same run
155
+
156
+
157
+ def gate(tool, args, command=None, path=None, run=None, root=None, repo=None, opener=None):
158
+ """Block message when the reviewer denies a risky action in auto mode, else None."""
159
+ run = run or {}
160
+ if run.get('mode') != 'auto' or run.get('subagent') == 'review': return None
161
+ cfg = config(root)
162
+ if not cfg['enabled']: return None
163
+ why = risk(tool, args, command, path, repo)
164
+ if not why: return None
165
+ fp = fingerprint(tool, command, path); action = describe(tool, args, command, path)
166
+ if take_approval(root, fp):
167
+ _emit(root, decision='allow', rule='approved once', content='Approved once by the user: ' + action[:300], command=action[:300]); _ALLOWED[fp] = True; return None
168
+ if _ALLOWED.get(fp): return None
169
+ decision, reason = ask_model(action, why, run.get('task'), root, cfg.get('model'), opener)
170
+ if decision == 'allow':
171
+ _ALLOWED[fp] = True
172
+ _emit(root, decision='allow', rule='auto-review', content='Auto-review allowed: ' + action[:200] + (' (' + reason + ')' if reason else ''), command=action[:300]); return None
173
+ reason = reason or 'The reviewer denied it.'
174
+ record_denied(root, {'fingerprint': fp, 'tool': str(tool), 'action': action, 'risk': why, 'reason': reason, 'runId': run.get('runId'), 'at': int(time.time())})
175
+ _emit(root, decision='deny', rule='auto-review', content='Auto-review denied: ' + action[:200] + ' (' + reason + ')', command=action[:300])
176
+ return ('Auto-review blocked this action (' + why + '): ' + reason + ' Do not work around this. Continue without it if you can; '
177
+ 'otherwise stop and say what you need. The user can allow it once with /approve, then you may retry the exact same action.')