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,806 @@
1
+ """Explicitly approved local preview launcher: installs what the project declares, serves the production build on
2
+ shared links and the dev server while the agent edits. Never calls an LLM."""
3
+ import argparse, fcntl, json, os, pathlib, re, shutil, subprocess, sys, urllib.request, urllib.error
4
+
5
+
6
+ def plan(repo):
7
+ repo = pathlib.Path(repo).resolve()
8
+ package = repo / 'package.json'
9
+ if package.is_file() and not package.is_symlink():
10
+ try:
11
+ if package.stat().st_size > 1000000: return None
12
+ data = json.loads(package.read_text())
13
+ except (OSError, ValueError): return None
14
+ if not isinstance(data, dict) or any(not isinstance(data.get(key, {}), dict) for key in ('scripts', 'dependencies', 'devDependencies')): return None
15
+ scripts = data.get('scripts', {})
16
+ deps = {**data.get('dependencies', {}), **data.get('devDependencies', {})}
17
+ for name in ('dev', 'start'):
18
+ script = scripts.get(name, '')
19
+ if not isinstance(script, str): continue
20
+ # Only standard framework entrypoints; compound scripts need agent review.
21
+ if 'next' in deps and re.fullmatch(r'next (dev|start)(?: --(?:hostname|port) [a-zA-Z0-9.:-]+)*', script.strip()):
22
+ return {'command': ['npm', 'run', name, '--', '--hostname', '0.0.0.0', '--port', '3000'], 'label': 'Next.js', 'cwd': str(repo)}
23
+ if 'vite' in deps and re.fullmatch(r'vite(?: --host)?', script.strip()):
24
+ return {'command': ['npm', 'run', name, '--', '--host', '0.0.0.0', '--port', '3000', '--strictPort'], 'label': 'Vite', 'cwd': str(repo)}
25
+ return None
26
+ index = repo / 'index.html'
27
+ if index.is_file() and not index.is_symlink():
28
+ return {'command': [sys.executable, str(pathlib.Path(__file__).resolve()), 'serve', '--root', str(repo)], 'label': 'Static website', 'cwd': str(repo)}
29
+ return None
30
+
31
+
32
+ def identity(pid):
33
+ try:
34
+ stat = pathlib.Path('/proc', str(pid), 'stat').read_text().rsplit(')', 1)[1].split()
35
+ return None if stat[0] == 'Z' else stat[19]
36
+ except (OSError, IndexError):
37
+ return None
38
+
39
+
40
+ NEXT_CONFIGS = ('next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs', 'next.config.mts')
41
+ PREVIEW_ORIGIN = '*.vercel.run'
42
+
43
+
44
+ def next_dev(repo):
45
+ """True when the preview plan runs `next dev` (only dev mode checks allowedDevOrigins)."""
46
+ try: data = json.loads((pathlib.Path(repo) / 'package.json').read_text())
47
+ except (OSError, ValueError): return False
48
+ selected = plan(repo)
49
+ if not selected or selected.get('label') != 'Next.js': return False
50
+ script = str((data.get('scripts') or {}).get(selected['command'][2], ''))
51
+ return script.strip().startswith('next dev')
52
+
53
+
54
+ def ensure_next_dev_origins(repo):
55
+ """Next.js dev serves its client scripts and HMR only to allowedDevOrigins, so on the public preview
56
+ host (*.vercel.run) pages render but never hydrate: buttons, forms and sign-in silently do nothing.
57
+ Add the preview host to the project's config. Returns the changed file name, '' when already allowed,
58
+ or None when the config is too unusual to edit safely."""
59
+ repo = pathlib.Path(repo)
60
+ found = [repo / name for name in NEXT_CONFIGS if (repo / name).is_file() and not (repo / name).is_symlink()]
61
+ if not found:
62
+ (repo / 'next.config.mjs').write_text('/** @type {import(\'next\').NextConfig} */\nconst nextConfig = {\n // Lets the ML AI Code preview address load dev scripts (otherwise pages never become interactive).\n allowedDevOrigins: ["' + PREVIEW_ORIGIN + '"],\n};\n\nexport default nextConfig;\n')
63
+ return 'next.config.mjs'
64
+ path = found[0]
65
+ try:
66
+ if path.stat().st_size > 200000: return None
67
+ text = path.read_text()
68
+ except OSError: return None
69
+ match = re.search(r'allowedDevOrigins\s*:\s*\[([^\]]*)\]', text)
70
+ if match:
71
+ if 'vercel.run' in match.group(1): return ''
72
+ inner = match.group(1)
73
+ updated = text[:match.start(1)] + '"' + PREVIEW_ORIGIN + '"' + (', ' if inner.strip() else '') + inner.lstrip() + text[match.end(1):]
74
+ elif 'allowedDevOrigins' in text: return None
75
+ else:
76
+ anchor = re.search(r'(?:const\s+\w+\s*(?::\s*NextConfig)?\s*=\s*\{|module\.exports\s*=\s*\{|export\s+default\s+\{)', text)
77
+ if not anchor: return None
78
+ updated = text[:anchor.end()] + '\n allowedDevOrigins: ["' + PREVIEW_ORIGIN + '"],' + text[anchor.end():]
79
+ tmp = path.with_name(path.name + '.mlai-tmp'); tmp.write_text(updated); tmp.replace(path)
80
+ return path.name
81
+
82
+
83
+ def next_origin_blocked():
84
+ """Next.js dev answers 403 'Unauthorized' to /_next requests from an origin outside allowedDevOrigins."""
85
+ try:
86
+ request = urllib.request.Request('http://127.0.0.1:3000/_next/mlai-origin-probe', headers={'Origin': 'https://preview.vercel.run', 'Host': 'preview.vercel.run'})
87
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
88
+ with opener.open(request, timeout=3): return False
89
+ except urllib.error.HTTPError as error:
90
+ try: body = error.read(200).decode(errors='replace')
91
+ except OSError: body = ''
92
+ return error.code == 403 and body.strip() == 'Unauthorized'
93
+ except (OSError, urllib.error.URLError): return False
94
+
95
+
96
+ def host_blocked():
97
+ """Vite answers loopback but rejects the public preview host with 403 'Blocked request'."""
98
+ try:
99
+ request = urllib.request.Request('http://127.0.0.1:3000', headers={'Host': 'preview.vercel.run'})
100
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
101
+ with opener.open(request, timeout=2): return False
102
+ except urllib.error.HTTPError as error:
103
+ try: body = error.read(2000).decode(errors='replace')
104
+ except OSError: body = ''
105
+ return error.code == 403 and 'allowedHosts' in body
106
+ except (OSError, urllib.error.URLError): return False
107
+
108
+
109
+ def status(state):
110
+ code = 0
111
+ try:
112
+ # Do not follow redirects off the local app or send loopback through an HTTP proxy.
113
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
114
+ def redirect_request(self, *args, **kwargs): return None
115
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
116
+ with opener.open('http://127.0.0.1:3000', timeout=2) as response: code = response.status
117
+ except urllib.error.HTTPError as error: code = error.code
118
+ except (OSError, urllib.error.URLError): pass
119
+ meta = {}
120
+ try: meta = json.loads((state / 'preview-process.json').read_text())
121
+ except (OSError, ValueError): pass
122
+ running = bool(meta.get('pid') and meta.get('start') and identity(meta['pid']) == meta['start'])
123
+ log = ''
124
+ try:
125
+ with (state / 'preview.log').open('rb') as file:
126
+ file.seek(0, 2);file.seek(max(0, file.tell() - 8000));log = file.read().decode(errors='replace')
127
+ except OSError: pass
128
+ ready = 200 <= code < 400
129
+ work = job(state); mode = meta.get('mode', 'dev') if running or ready else ''
130
+ if work.get('alive') and (work.get('step') or '').startswith(('Building', 'Installing', 'Adding')): log = tail(state / 'preview-build.log', 8000) or log
131
+ extra = {'mode': mode or None, 'notes': [n for n in work.get('notes') or [] if isinstance(n, str)][:4]}
132
+ if work.get('alive'): extra['building'] = True; extra['step'] = work.get('step') or ''
133
+ if work.get('fixed'): extra['notes'].append('Added packages the code imports but package.json was missing: ' + ', '.join(work['fixed'][:8]) + '.')
134
+ if mode == 'prod' and work.get('state') != 'failed' and isinstance(work.get('buildWarning'), str) and work['buildWarning']: extra['notes'].append(work['buildWarning'])
135
+ if work.get('state') == 'failed' and work.get('error'):
136
+ extra['buildError'] = work['error']
137
+ extra['notes'].append(('The production build failed, so this is the development preview. ' if ready else '') + 'Problem: ' + work['error'] + ' Ask the agent to fix it.')
138
+ if ready and next_origin_blocked():
139
+ return {'ready': False, 'running': running, 'httpStatus': code, 'hostBlocked': True, 'originBlocked': True, 'message': 'The Next.js dev server blocks the preview address, so pages load but buttons, forms and sign-in do nothing. Start the preview again to fix it (it adds "*.vercel.run" to allowedDevOrigins in next.config).', 'log': log}
140
+ if ready and host_blocked():
141
+ return {'ready': False, 'running': running, 'httpStatus': 403, 'hostBlocked': True, 'message': 'The dev server is blocking the preview address. Restart it with server.allowedHosts set (or ask the agent to restart the preview).', 'log': log}
142
+ if ready: message = 'Live preview' if mode == 'prod' else ('Live preview (development). Preparing the production version…' if work.get('alive') else 'Live preview (development)')
143
+ elif work.get('alive'): message = (work.get('step') or 'Preparing the preview') + '…'
144
+ else: message = 'The app returned HTTP '+str(code)+'. Check the startup log.' if code else ('Starting your app…' if running else ('Preview could not start. ' + work['error'] if work.get('state') == 'failed' and work.get('error') else 'No app is running on port 3000.'))
145
+ return {'ready': ready, 'running': running or bool(work.get('alive')), 'httpStatus': code or None, 'message': message, 'log': log, **extra}
146
+
147
+
148
+
149
+ def port_owners(port=3000):
150
+ """PIDs holding a listening socket on the port (read from /proc; no lsof/fuser needed)."""
151
+ inodes = set()
152
+ for table in ('/proc/net/tcp', '/proc/net/tcp6'):
153
+ try: lines = pathlib.Path(table).read_text().splitlines()[1:]
154
+ except OSError: continue
155
+ for line in lines:
156
+ parts = line.split()
157
+ if len(parts) > 9 and parts[3] == '0A' and int(parts[1].rsplit(':', 1)[1], 16) == port: inodes.add(parts[9])
158
+ owners = set()
159
+ for proc in pathlib.Path('/proc').iterdir():
160
+ if not proc.name.isdigit(): continue
161
+ try:
162
+ for fd in (proc / 'fd').iterdir():
163
+ link = os.readlink(fd)
164
+ if link.startswith('socket:[') and link[8:-1] in inodes: owners.add(int(proc.name))
165
+ except OSError: continue
166
+ return owners
167
+
168
+
169
+ def stop_port(port=3000):
170
+ import signal, time
171
+ for pid in port_owners(port):
172
+ try: os.killpg(os.getpgid(pid), signal.SIGTERM)
173
+ except OSError:
174
+ try: os.kill(pid, signal.SIGTERM)
175
+ except OSError: pass
176
+ for _ in range(30):
177
+ if not port_owners(port): return True
178
+ time.sleep(0.2)
179
+ return not port_owners(port)
180
+
181
+
182
+ # ---------------------------------------------------------------- production preview and dependency doctor
183
+ # Shared links show the optimized production build (`next build` + `next start`, `vite build` + `vite preview`):
184
+ # no dev overlay, no hydration warnings from browser extensions, real speed. The agent keeps the fast dev server
185
+ # (hot reload) while it edits; when the run ends the production build is prepared in the background and swapped
186
+ # in only after it builds and answers. Before anything starts, the doctor installs exactly what the lockfile pins,
187
+ # adds packages the build reports missing, and explains missing env keys or a Node version mismatch in plain words.
188
+ SAFE_ENV = ('PATH', 'HOME', 'LANG', 'LC_ALL', 'TMPDIR')
189
+ SKIP_DIRS = {'node_modules', '.next', 'dist', 'out', '.git', '.turbo', '.vercel', '.cache', 'coverage', '.mini', '.venv', '__pycache__', '.svelte-kit', '.output', '.parcel-cache'}
190
+ SKIP_FILES = {'next-env.d.ts', 'tsconfig.tsbuildinfo', '.DS_Store'}
191
+ BUILD_SECONDS, INSTALL_SECONDS, SERVE_WAIT = 600, 300, 45
192
+ NPM_NAME = re.compile(r'^(@[a-z0-9][a-z0-9._-]*/)?[a-z0-9][a-z0-9._-]{0,213}$')
193
+ BUILTINS = {'assert', 'async_hooks', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram', 'diagnostics_channel', 'dns', 'domain', 'events', 'fs', 'http', 'http2', 'https', 'inspector', 'module', 'net', 'os', 'path', 'perf_hooks', 'process', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', 'tls', 'trace_events', 'tty', 'url', 'util', 'v8', 'vm', 'wasi', 'worker_threads', 'zlib', 'test', 'sqlite'}
194
+ MISSING = (r"Module not found: (?:Error: )?Can't resolve '([^']+)'", r"Cannot find module '([^']+)'", r'Failed to resolve import "([^"]+)"',
195
+ r'Could not resolve "([^"]+)"', r"Cannot find package '([^']+)'", r'Rollup failed to resolve import "([^"]+)"', r"Module not found: Can't resolve \"([^\"]+)\"")
196
+ # Script shapes we run as-is for a production build; anything else uses the framework binary directly.
197
+ BUILD_PREFIX = r'(?:(?:prisma generate|tsc(?: -b| --noEmit| -p [\w./-]+)*|next lint)\s*&&\s*)*'
198
+ NEXT_BUILD = re.compile(BUILD_PREFIX + r'next build(?: --(?:turbopack|turbo|webpack|no-lint|experimental-build-mode=\w+))*')
199
+ VITE_BUILD = re.compile(BUILD_PREFIX + r'vite build(?: --mode \w+)?')
200
+
201
+
202
+ def read_package(repo):
203
+ p = pathlib.Path(repo) / 'package.json'
204
+ try:
205
+ if not p.is_file() or p.is_symlink() or p.stat().st_size > 1000000: return None
206
+ data = json.loads(p.read_text())
207
+ except (OSError, ValueError): return None
208
+ return data if isinstance(data, dict) else None
209
+
210
+
211
+ def declared(data):
212
+ out = {}
213
+ for key in ('dependencies', 'devDependencies'):
214
+ part = (data or {}).get(key)
215
+ if isinstance(part, dict): out.update(part)
216
+ return out
217
+
218
+
219
+ NETWORK_ENV = ('HTTP_PROXY', 'HTTPS_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'no_proxy', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'COREPACK_HOME', 'PNPM_HOME', 'XDG_CACHE_HOME', 'npm_config_cache', 'NPM_CONFIG_CACHE', 'npm_config_registry', 'NPM_CONFIG_REGISTRY')
220
+
221
+
222
+ def preview_env():
223
+ # Only what installs and servers need to reach the registry; never model keys, Vault secrets or registry tokens.
224
+ env = {k: v for k, v in os.environ.items() if k in SAFE_ENV or k in NETWORK_ENV}
225
+ env.update({'PORT': '3000', 'HOST': '0.0.0.0', 'BROWSER': 'none', '__VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS': '.vercel.run', 'NEXT_TELEMETRY_DISABLED': '1', 'npm_config_update_notifier': 'false'})
226
+ return env
227
+
228
+
229
+ def next_major(repo):
230
+ try: return int(json.loads((pathlib.Path(repo) / 'node_modules' / 'next' / 'package.json').read_text())['version'].split('.')[0])
231
+ except (OSError, ValueError, KeyError, IndexError, TypeError): return 0
232
+
233
+
234
+ def static_export(repo):
235
+ for name in NEXT_CONFIGS:
236
+ try: text = (pathlib.Path(repo) / name).read_text()[:200000]
237
+ except OSError: continue
238
+ if re.search(r'''output\s*:\s*['"]export['"]''', text): return True
239
+ return False
240
+
241
+
242
+ def prod_plan(repo):
243
+ """How to build and serve the optimized app, or None when only the dev server (or nothing) applies."""
244
+ repo = pathlib.Path(repo).resolve()
245
+ selected = plan(repo)
246
+ if not selected: return None
247
+ if selected['label'] == 'Static website': return {'label': 'Static website', 'build': None, 'serve': selected['command'], 'concurrent': True}
248
+ data = read_package(repo) or {}
249
+ scripts = data.get('scripts') or {}
250
+ script = scripts.get('build') if isinstance(scripts.get('build'), str) else ''
251
+ bin_dir = repo / 'node_modules' / '.bin'
252
+ me = [sys.executable, str(pathlib.Path(__file__).resolve()), 'serve', '--root']
253
+ if selected['label'] == 'Next.js':
254
+ direct = [str(bin_dir / 'next'), 'build']
255
+ build = ['npm', 'run', 'build'] if NEXT_BUILD.fullmatch(script.strip()) else direct
256
+ serve = me + [str(repo / 'out')] if static_export(repo) else [str(bin_dir / 'next'), 'start', '--hostname', '0.0.0.0', '--port', '3000']
257
+ # Next.js 16+ builds into .next while dev uses .next/dev, so the dev preview keeps serving during the build.
258
+ return {'label': 'Next.js', 'build': build, 'fallback': direct if build != direct else None, 'serve': serve, 'concurrent': next_major(repo) >= 16, 'artifact': 'out' if static_export(repo) else '.next/BUILD_ID'}
259
+ direct = [str(bin_dir / 'vite'), 'build']
260
+ build = ['npm', 'run', 'build'] if VITE_BUILD.fullmatch(script.strip()) else direct
261
+ return {'label': 'Vite', 'build': build, 'fallback': direct if build != direct else None, 'serve': [str(bin_dir / 'vite'), 'preview', '--host', '0.0.0.0', '--port', '3000', '--strictPort'], 'concurrent': True, 'artifact': 'dist/index.html'}
262
+
263
+
264
+ def fingerprint(repo, limit=40000):
265
+ """Cheap source identity (path, size, mtime) that ignores build output, packages and files the build rewrites."""
266
+ import hashlib
267
+ h = hashlib.sha256(); n = 0
268
+ for base, dirs, files in os.walk(repo):
269
+ dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.startswith('.mlai-'))
270
+ for name in sorted(files):
271
+ if name in SKIP_FILES or name.endswith(('.log', '.tsbuildinfo', '.mlai-tmp')): continue
272
+ path = os.path.join(base, name)
273
+ try: st = os.lstat(path)
274
+ except OSError: continue
275
+ h.update(f'{os.path.relpath(path, repo)}\0{st.st_size}\0{st.st_mtime_ns}\n'.encode()); n += 1
276
+ if n >= limit: return 'big:' + h.hexdigest()[:20]
277
+ return h.hexdigest()[:20]
278
+
279
+
280
+ def package_manager(repo):
281
+ r = pathlib.Path(repo)
282
+ if (r / 'pnpm-lock.yaml').is_file(): return 'pnpm'
283
+ if (r / 'yarn.lock').is_file(): return 'yarn'
284
+ if ((r / 'bun.lockb').is_file() or (r / 'bun.lock').is_file()) and shutil.which('bun'): return 'bun'
285
+ return 'npm'
286
+
287
+
288
+ def install_command(repo):
289
+ """Install exactly what the lockfile pins (and write a lockfile when there is none), reusing the local package cache."""
290
+ pm = package_manager(repo)
291
+ if pm == 'pnpm': return 'corepack enable >/dev/null 2>&1 || npm install -g pnpm >/dev/null 2>&1; pnpm install --frozen-lockfile --prefer-offline || pnpm install --prefer-offline'
292
+ if pm == 'yarn': return 'corepack enable >/dev/null 2>&1 || npm install -g yarn >/dev/null 2>&1; yarn install --frozen-lockfile --prefer-offline || yarn install --prefer-offline'
293
+ if pm == 'bun': return 'bun install --frozen-lockfile || bun install'
294
+ if (pathlib.Path(repo) / 'package-lock.json').is_file(): return 'npm ci --prefer-offline --no-audit --no-fund || npm install --prefer-offline --no-audit --no-fund'
295
+ return 'npm install --prefer-offline --no-audit --no-fund'
296
+
297
+
298
+ def add_command(repo, names):
299
+ import shlex
300
+ quoted = ' '.join(shlex.quote(n) for n in names)
301
+ pm = package_manager(repo)
302
+ return {'pnpm': 'pnpm add ', 'yarn': 'yarn add ', 'bun': 'bun add '}.get(pm, 'npm install --prefer-offline --no-audit --no-fund ') + quoted
303
+
304
+
305
+ def missing_installed(repo, data=None):
306
+ """Declared packages that are not in node_modules (a fresh clone, or the agent edited package.json without installing)."""
307
+ data = data if data is not None else read_package(repo)
308
+ if data is None: return []
309
+ modules = pathlib.Path(repo) / 'node_modules'
310
+ if not modules.is_dir(): return sorted(declared(data)) or ['node_modules']
311
+ return sorted(name for name, spec in declared(data).items() if isinstance(spec, str) and not spec.startswith(('link:', 'file:', 'workspace:', 'portal:')) and not (modules / name / 'package.json').exists())
312
+
313
+
314
+ def package_name(spec):
315
+ spec = spec.strip()
316
+ if not spec or spec.startswith(('.', '/', '~', '#', 'node:', '@/', 'virtual:', '\0', 'data:', 'http:', 'https:')): return None
317
+ parts = spec.split('/')
318
+ name = '/'.join(parts[:2]) if spec.startswith('@') else parts[0]
319
+ if name in BUILTINS or not NPM_NAME.match(name): return None
320
+ return name
321
+
322
+
323
+ SOURCE_EXT = ('.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.mts', '.vue', '.svelte', '.astro')
324
+ IMPORT = re.compile(r"""(?:^|[\s;}])(?:import|export)\s+(?:type\s+)?(?:[\w*{}\s,$]+\s+from\s+)?['"]([^'"\n]+)['"]""", re.M) # static imports only: bare dynamic imports are often optional
325
+ NOT_APP = {'test', 'tests', '__tests__', 'e2e', 'cypress', 'playwright', 'scripts', 'benchmarks', 'docs', 'examples', 'fixtures', 'stories', 'storybook', '__mocks__'}
326
+ PROVIDED = {'server-only', 'client-only', 'styled-jsx'} # resolved by Next.js itself
327
+
328
+
329
+ def path_aliases(repo):
330
+ """First segments that tsconfig/jsconfig paths or a Vite resolve.alias map to local folders (not packages)."""
331
+ repo = pathlib.Path(repo); out = set()
332
+ for cfg in ('tsconfig.json', 'jsconfig.json', 'tsconfig.app.json'):
333
+ try: text = (repo / cfg).read_text()[:200000]
334
+ except OSError: continue
335
+ out.update(m.split('/')[0] for m in re.findall(r'"([^"\n]+)/\*"\s*:', text))
336
+ out.update(re.findall(r'"([@~#$\w-][^"/\n]*)"\s*:\s*\[', text))
337
+ for cfg in ('vite.config.ts', 'vite.config.js', 'vite.config.mjs', 'vite.config.mts'):
338
+ try: text = (repo / cfg).read_text()[:200000]
339
+ except OSError: continue
340
+ block = re.search(r'alias\s*:\s*[\[{](.*?)[\]}]\s*[,}]', text, re.S)
341
+ if block: out.update(re.findall(r"""['"]?([@~#$\w-][\w@~#$/-]*)['"]?\s*:""", block.group(1)) + re.findall(r"""find\s*:\s*['"]([^'"]+)['"]""", block.group(1)))
342
+ return {a.split('/')[0] for a in out if a}
343
+
344
+
345
+ def undeclared_imports(repo, data=None, limit=4000):
346
+ """Bare packages the source imports that package.json does not list (the agent wrote the import but never
347
+ added the dependency). Local folders, path aliases, Node built-ins and framework-provided modules are skipped."""
348
+ repo = pathlib.Path(repo); data = data if data is not None else read_package(repo)
349
+ if data is None: return []
350
+ have = set(declared(data)) | PROVIDED | {str(data.get('name') or '')}
351
+ aliases = path_aliases(repo); found = []; seen = 0
352
+ for base, dirs, files in os.walk(repo):
353
+ # Nested packages (monorepo apps, editor extensions) declare their own dependencies.
354
+ dirs[:] = [d for d in dirs if d not in SKIP_DIRS and not d.startswith('.') and d not in ('public', 'static', 'build', 'vendor') and d not in NOT_APP and not os.path.exists(os.path.join(base, d, 'package.json'))]
355
+ for name in files:
356
+ if not name.endswith(SOURCE_EXT) or name.endswith(('.d.ts', '.min.js')) or re.search(r'\.(test|spec|stories|e2e)\.', name) or re.match(r'(playwright|vitest|jest|cypress|eslint|prettier)\.config\.', name): continue
357
+ seen += 1
358
+ if seen > limit: return found[:6]
359
+ try:
360
+ path = pathlib.Path(base, name)
361
+ if path.is_symlink() or path.stat().st_size > 400000: continue
362
+ text = path.read_text(errors='replace')
363
+ except OSError: continue
364
+ text = re.sub(r'/\*.*?\*/', '', text, flags=re.S); text = re.sub(r'(?m)^\s*//.*$', '', text)
365
+ for spec in IMPORT.findall(text):
366
+ pkg = package_name(spec)
367
+ if not pkg or pkg in have or pkg in found or pkg.split('/')[0] in aliases: continue
368
+ if pkg.startswith('@types/') or (repo / pkg).exists() or (repo / 'src' / pkg).exists(): continue
369
+ if (repo / 'node_modules' / pkg / 'package.json').exists(): continue
370
+ found.append(pkg)
371
+ return found[:6]
372
+
373
+
374
+ def missing_from_log(text, repo, data=None):
375
+ """Packages a build/start log says it cannot resolve, minus relative imports, aliases and Node built-ins."""
376
+ data = data if data is not None else read_package(repo) or {}
377
+ text = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', text or '')
378
+ found = []
379
+ for pattern in MISSING:
380
+ for spec in re.findall(pattern, text or ''):
381
+ name = package_name(spec)
382
+ if name and name not in found: found.append(name)
383
+ # Path aliases from tsconfig/jsconfig (for example "@components/*") are not packages.
384
+ aliases = set()
385
+ for cfg in ('tsconfig.json', 'jsconfig.json'):
386
+ try: aliases.update(k.split('/')[0] for k in json.loads(re.sub(r'(?m)^\s*//.*$', '', (pathlib.Path(repo) / cfg).read_text())).get('compilerOptions', {}).get('paths', {}))
387
+ except (OSError, ValueError, AttributeError): pass
388
+ return [n for n in found if n.split('/')[0] not in aliases][:6]
389
+
390
+
391
+ def node_check(repo, data=None):
392
+ """Plain-words warning when the project asks for a different Node major than this computer has."""
393
+ repo = pathlib.Path(repo); want = ''
394
+ for name in ('.nvmrc', '.node-version'):
395
+ try: want = (repo / name).read_text().strip().lstrip('v'); break
396
+ except OSError: pass
397
+ engines = ((data if data is not None else read_package(repo)) or {}).get('engines') or {}
398
+ rng = engines.get('node') if isinstance(engines, dict) and isinstance(engines.get('node'), str) else ''
399
+ try: have = int(subprocess.run(['node', '-v'], capture_output=True, text=True, timeout=5).stdout.strip().lstrip('v').split('.')[0])
400
+ except (OSError, ValueError, subprocess.SubprocessError): return ''
401
+ if want and re.match(r'^\d+', want):
402
+ major = int(re.match(r'^\d+', want).group())
403
+ if major != have: return f'This project pins Node {major} (in .nvmrc/.node-version) but this computer runs Node {have}. It usually still works; if the build fails on syntax or native packages, ask the agent to switch Node versions.'
404
+ if rng:
405
+ low = re.search(r'>=\s*v?(\d+)', rng); exact = re.fullmatch(r'\s*[\^~]?v?(\d+)(?:\.[\dx*]+)*\s*', rng)
406
+ if low and have < int(low.group(1)) or exact and have != int(exact.group(1)):
407
+ return f'package.json asks for Node "{rng}" but this computer runs Node {have}. If the build fails, ask the agent to switch Node versions.'
408
+ return ''
409
+
410
+
411
+ ENV_EXAMPLES = ('.env.example', '.env.sample', '.env.template', '.env.local.example', '.env.dist')
412
+ ENV_FILES = ('.env', '.env.local', '.env.production', '.env.production.local', '.env.development', '.env.development.local')
413
+
414
+
415
+ def env_keys(path):
416
+ try:
417
+ if path.is_symlink() or path.stat().st_size > 200000: return {}
418
+ lines = path.read_text(errors='replace').splitlines()
419
+ except OSError: return {}
420
+ out = {}
421
+ for line in lines:
422
+ m = re.match(r'^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$', line)
423
+ if m: out[m.group(1)] = m.group(2).strip().strip('"\'')
424
+ return out
425
+
426
+
427
+ def env_missing(repo):
428
+ """Keys the project's example env file lists that no env file sets (names only; values are never read out)."""
429
+ repo = pathlib.Path(repo); wanted = {}
430
+ for name in ENV_EXAMPLES: wanted.update(env_keys(repo / name))
431
+ if not wanted: return []
432
+ have = set()
433
+ for name in ENV_FILES: have.update(k for k, v in env_keys(repo / name).items() if v)
434
+ return sorted(k for k in wanted if k not in have)[:30]
435
+
436
+
437
+ def doctor_notes(repo, data=None):
438
+ notes = []
439
+ warn = node_check(repo, data)
440
+ if warn: notes.append(warn)
441
+ keys = env_missing(repo)
442
+ if keys: notes.append('Missing settings: ' + ', '.join(keys) + '. They are listed in the example env file but not set in .env or .env.local, so features that need them may not work. Ask the agent to add them to .env.local (values stay in your workspace).')
443
+ return notes
444
+
445
+
446
+ def tail(path, size=6000):
447
+ try:
448
+ with open(path, 'rb') as f:
449
+ f.seek(0, 2); f.seek(max(0, f.tell() - size)); return f.read().decode(errors='replace')
450
+ except OSError: return ''
451
+
452
+
453
+ def first_error(text):
454
+ text = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', text or '')
455
+ for line in text.splitlines():
456
+ s = line.strip()
457
+ if re.search(r'(?i)\b(error|failed to compile|cannot find|can.t resolve|type error)\b', s) and len(s) > 8: return s[:300]
458
+ lines = [l.strip() for l in (text or '').splitlines() if l.strip()]
459
+ return lines[-1][:300] if lines else ''
460
+
461
+
462
+ def job(state):
463
+ """The background preview job (install, build, switch), if one is running."""
464
+ try: data = json.loads((pathlib.Path(state) / 'preview-build.json').read_text())
465
+ except (OSError, ValueError): return {}
466
+ data['alive'] = bool(data.get('pid') and data.get('start') and identity(data['pid']) == data['start'] and data.get('state') == 'running')
467
+ return data
468
+
469
+
470
+ def set_job(state_dir, **fields):
471
+ path = pathlib.Path(state_dir) / 'preview-build.json'
472
+ try: data = json.loads(path.read_text())
473
+ except (OSError, ValueError): data = {}
474
+ data.update(fields); data['updated'] = __import__('time').time()
475
+ tmp = path.with_suffix('.tmp'); tmp.write_text(json.dumps(data)); tmp.replace(path)
476
+ return data
477
+
478
+
479
+ def stop_job(state):
480
+ import signal
481
+ current = job(state)
482
+ if current.get('alive'):
483
+ try: os.killpg(os.getpgid(current['pid']), signal.SIGTERM)
484
+ except OSError:
485
+ try: os.kill(current['pid'], signal.SIGTERM)
486
+ except OSError: pass
487
+ set_job(state, state='cancelled', step='Stopped because the agent started editing')
488
+
489
+
490
+ def run_logged(command, cwd, env, log_path, timeout, shell=False):
491
+ with open(log_path, 'ab') as log:
492
+ log.write(('\n$ ' + (command if shell else ' '.join(command)) + '\n').encode()); log.flush()
493
+ try:
494
+ p = subprocess.run(['bash', '-lc', command] if shell else command, cwd=str(cwd), env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, timeout=timeout)
495
+ return p.returncode
496
+ except subprocess.TimeoutExpired: return 124
497
+ except OSError as error:
498
+ log.write(str(error).encode()); return 127
499
+
500
+
501
+ def ensure_packages(repo, state, env, log_path):
502
+ """Install when anything declared is missing, and add packages the code imports but package.json lacks.
503
+ Returns (ok, message)."""
504
+ data = read_package(repo)
505
+ if data is None: return True, ''
506
+ added = undeclared_imports(repo, data)
507
+ if added:
508
+ set_job(state, step='Adding missing packages: ' + ', '.join(added))
509
+ if run_logged(add_command(repo, added), repo, env, log_path, INSTALL_SECONDS, shell=True) == 0:
510
+ set_job(state, fixed=(job(state).get('fixed') or []) + added)
511
+ data = read_package(repo) or data
512
+ missing = missing_installed(repo, data)
513
+ if not missing: return True, ''
514
+ set_job(state, step='Installing packages')
515
+ code = run_logged(install_command(repo), repo, env, log_path, INSTALL_SECONDS, shell=True)
516
+ still = missing_installed(repo)
517
+ if code == 0 and not still: return True, 'Installed packages from the lockfile.'
518
+ return False, 'Package install failed' + (' (still missing: ' + ', '.join(still[:6]) + ')' if still else '') + ': ' + first_error(tail(log_path, 4000))
519
+
520
+
521
+ def wait_ready(seconds, proc=None):
522
+ import time
523
+ end = time.time() + seconds
524
+ while time.time() < end:
525
+ if proc is not None and proc.poll() is not None: return False
526
+ if listening(3000):
527
+ try:
528
+ class NoRedirect(urllib.request.HTTPRedirectHandler):
529
+ def redirect_request(self, *args, **kwargs): return None
530
+ with urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()).open('http://127.0.0.1:3000', timeout=20) as r: return r.status < 500
531
+ except urllib.error.HTTPError as error: return error.code < 500
532
+ except (OSError, urllib.error.URLError): pass
533
+ time.sleep(0.5)
534
+ return False
535
+
536
+
537
+ def start_server(command, cwd, state, env, mode, fp=None):
538
+ with (pathlib.Path(state) / 'preview.log').open('ab') as log:
539
+ proc = subprocess.Popen(command, cwd=str(cwd), env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
540
+ (pathlib.Path(state) / 'preview-process.json').write_text(json.dumps({'pid': proc.pid, 'start': identity(proc.pid), 'mode': mode, **({'fingerprint': fp} if fp else {})}))
541
+ return proc
542
+
543
+
544
+ def supervise(repo, state, mode):
545
+ """Background preview job: packages, then the dev server, or a production build swapped in once it works."""
546
+ import time
547
+ repo, state = pathlib.Path(repo).resolve(), pathlib.Path(state)
548
+ with (state / 'preview-build.lock').open('a') as lock:
549
+ try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
550
+ except OSError: return {'skipped': 'another preview job is running'}
551
+ env = preview_env(); build_log = state / 'preview-build.log'
552
+ build_log.write_bytes(b'')
553
+ data = read_package(repo)
554
+ notes = doctor_notes(repo, data) if data is not None or (repo / '.env.example').exists() else []
555
+ started = time.time()
556
+ set_job(state, pid=os.getpid(), start=identity(os.getpid()), mode=mode, state='running', step='Checking packages', notes=notes, error='', fixed=[], time=started)
557
+ ok, message = ensure_packages(repo, state, env, build_log)
558
+ if not ok:
559
+ set_job(state, state='failed', step='Packages', error=message); return {'error': message}
560
+ if mode == 'dev':
561
+ selected = plan(repo)
562
+ if not selected: set_job(state, state='failed', error='No supported web app found'); return {}
563
+ if not listening(3000): start_server(selected['command'], selected['cwd'], state, env, 'dev')
564
+ set_job(state, state='done', step='Development preview', seconds=round(time.time() - started, 1)); return {'mode': 'dev'}
565
+ pp = prod_plan(repo)
566
+ if not pp: set_job(state, state='failed', error='No supported web app found'); return {}
567
+ fp = fingerprint(repo); built = job(state).get('built') or {}
568
+ cached = pp['build'] is None or (built.get('fingerprint') == fp and (repo / pp.get('artifact', '')).exists())
569
+ dev = plan(repo); interim = None
570
+ if not cached:
571
+ if not pp['concurrent']: stop_port()
572
+ elif not listening(3000) and dev and dev['label'] != 'Static website':
573
+ # Show the dev preview right away while the production build runs (Next.js 16+ and Vite build into separate folders).
574
+ if next_dev(repo): ensure_next_dev_origins(repo)
575
+ interim = start_server(dev['command'], dev['cwd'], state, env, 'dev')
576
+ set_job(state, step='Building the production version')
577
+ command, fixed, tried_fallback, code, checked = pp['build'], [], False, 1, ''
578
+ for _ in range(4):
579
+ if (state / 'run.lock').exists(): set_job(state, state='cancelled', step='The agent started a new task'); return {}
580
+ code = run_logged(command, repo, {**env, 'NODE_ENV': 'production'}, build_log, BUILD_SECONDS)
581
+ if code == 0: break
582
+ text = tail(build_log, 20000)
583
+ need = [n for n in missing_from_log(text, repo, read_package(repo)) if n not in fixed]
584
+ if need and len(fixed) < 10:
585
+ set_job(state, step='Adding missing packages: ' + ', '.join(need))
586
+ if run_logged(add_command(repo, need), repo, env, build_log, INSTALL_SECONDS, shell=True) == 0:
587
+ fixed += need; set_job(state, fixed=fixed, step='Building the production version'); continue
588
+ if missing_installed(repo):
589
+ if ensure_packages(repo, state, env, build_log)[0]: continue
590
+ if pp.get('fallback') and not tried_fallback:
591
+ # The project's build script failed (often a strict type check); try the plain framework build once.
592
+ checked = first_error(text) or 'see the build log'
593
+ tried_fallback, command = True, pp['fallback']; continue
594
+ break
595
+ if code != 0:
596
+ error = first_error(tail(build_log, 20000))
597
+ set_job(state, state='failed', step='Production build failed', error=error, fixed=fixed, seconds=round(time.time() - started, 1))
598
+ # An older production server would show stale code; replace it with the dev server so the preview matches the files.
599
+ if serving_mode(state).get('mode') == 'prod' and not (state / 'run.lock').exists(): stop_port()
600
+ if not listening(3000) and dev and not (state / 'run.lock').exists():
601
+ if next_dev(repo): ensure_next_dev_origins(repo)
602
+ start_server(dev['command'], dev['cwd'], state, env, 'dev')
603
+ return {'error': error}
604
+ fp = fingerprint(repo)
605
+ warning = ('The project build script failed (' + checked + '), so the preview uses the plain framework build. Ask the agent to fix it.') if tried_fallback else ''
606
+ set_job(state, built={'fingerprint': fp, 'time': time.time(), 'seconds': round(time.time() - started, 1)}, fixed=fixed, buildWarning=warning)
607
+ if (state / 'run.lock').exists(): set_job(state, state='cancelled', step='The agent started a new task'); return {}
608
+ set_job(state, step='Switching to the production version')
609
+ stop_port()
610
+ proc = start_server(pp['serve'], repo, state, env, 'prod', fp)
611
+ if wait_ready(SERVE_WAIT, proc):
612
+ set_job(state, state='done', step='Production preview', seconds=round(time.time() - started, 1)); return {'mode': 'prod'}
613
+ error = 'The production server did not start: ' + first_error(tail(state / 'preview.log', 4000))
614
+ stop_port()
615
+ if dev and not (state / 'run.lock').exists():
616
+ if next_dev(repo): ensure_next_dev_origins(repo)
617
+ start_server(dev['command'], dev['cwd'], state, env, 'dev')
618
+ set_job(state, state='failed', step='Production server failed', error=error, built={}); return {'error': error}
619
+
620
+
621
+ def spawn(state, mode, root):
622
+ """Run the preview job detached (it outlives this command and the API request)."""
623
+ state = pathlib.Path(state)
624
+ with (state / 'preview.log').open('ab') as log:
625
+ paths = ['--repo', str(PATHS['repo']), '--state', str(state)] if PATHS.get('repo') else []
626
+ proc = subprocess.Popen([sys.executable, str(pathlib.Path(__file__).resolve()), 'supervise', '--mode', mode, '--root', str(root)] + paths, env=preview_env(), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
627
+ set_job(state, pid=proc.pid, start=identity(proc.pid), mode=mode, state='running', step='Checking packages', error='')
628
+ return proc
629
+
630
+
631
+ def serving_mode(state):
632
+ try: meta = json.loads((pathlib.Path(state) / 'preview-process.json').read_text())
633
+ except (OSError, ValueError): return {}
634
+ return meta if meta.get('pid') and identity(meta['pid']) == meta.get('start') else {}
635
+
636
+
637
+ def launch(repo, state, confirmed=False, agent=False, mode=None):
638
+ """Agent: development server (hot reload). Everyone else: the production build (built in the background)."""
639
+ if not confirmed: raise ValueError('Confirm running the project preview first')
640
+ state = pathlib.Path(state);state.mkdir(parents=True, exist_ok=True)
641
+ repo = pathlib.Path(repo)
642
+ mode = mode or ('dev' if agent else 'prod')
643
+ with (state / 'preview.lock').open('a') as lock:
644
+ fcntl.flock(lock, fcntl.LOCK_EX)
645
+ changed = ensure_next_dev_origins(repo) if next_dev(repo) else ''
646
+ current = status(state)
647
+ # A confirmed start replaces a dev server that rejects the preview host (for example one started without allowedHosts / allowedDevOrigins).
648
+ if current.get('hostBlocked') and (agent or not (state / 'run.lock').exists()):
649
+ stop_port();current = status(state)
650
+ if changed: current['configChanged'] = changed
651
+ if changed is None and next_dev(repo): current['warning'] = 'Could not add "*.vercel.run" to allowedDevOrigins automatically. Add it to next.config by hand, or the preview will not be interactive.'
652
+ serving = serving_mode(state); busy = job(state).get('alive')
653
+ up = bool(current['ready'] or current['httpStatus'] or (current['running'] and not busy))
654
+ if mode == 'dev':
655
+ if busy: stop_job(state)
656
+ # The agent edits files next: a production server would not pick the edits up.
657
+ if up and serving.get('mode') == 'prod' and (plan(repo) or {}).get('label') != 'Static website': stop_port(); current = status(state); up = current['ready'] or current['httpStatus']
658
+ if up: return current
659
+ else:
660
+ if busy: return {**current, 'building': True, 'message': current['message'] if current['ready'] else 'Preparing the production preview…'}
661
+ pp = prod_plan(repo)
662
+ if up and (pp is None or pp['build'] is None or (serving.get('mode') == 'prod' and serving.get('fingerprint') == fingerprint(repo))): return current
663
+ # The run lock keeps the manual button from racing the agent; the agent's own preview tool may start it.
664
+ if (state / 'run.lock').exists() and not agent: raise ValueError('Wait for the agent to finish before starting the preview manually')
665
+ selected = plan(repo)
666
+ if not selected: raise ValueError('No supported root web app found. Ask the agent to configure its preview command.')
667
+ if selected['label'] == 'Static website' or (mode == 'dev' and not missing_installed(repo)):
668
+ # Fast path: everything is installed, so start the dev server directly.
669
+ with (state / 'preview.log').open('wb') as log:
670
+ process = subprocess.Popen(selected['command'], cwd=selected['cwd'], env=preview_env(), stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
671
+ (state / 'preview-process.json').write_text(json.dumps({'pid': process.pid, 'start': identity(process.pid), 'mode': 'prod' if selected['label'] == 'Static website' else 'dev'}))
672
+ message = 'Starting ' + selected['label'] + '…'
673
+ else:
674
+ if not up: (state / 'preview.log').write_bytes(b'')
675
+ spawn(state, mode, repo.parent)
676
+ message = 'Installing packages and starting your app…' if mode == 'dev' else ('Preparing the production preview…' if not current['ready'] else current['message'])
677
+ building = mode == 'prod' and selected['label'] != 'Static website'
678
+ return {'ready': bool(current['ready']) and building, 'running': True, 'building': building, 'message': message, 'log': '', **({'configChanged': changed} if changed else {}), **({'warning': current['warning']} if current.get('warning') else {})}
679
+
680
+
681
+ def agent_takeover(repo, state):
682
+ """A new agent task edits files: replace a production server (or a production build in progress) with the
683
+ dev server so edits show up and browser checks never test a stale build. True when something changed."""
684
+ state = pathlib.Path(state)
685
+ if not (state / 'preview-process.json').exists(): return False
686
+ if (plan(repo) or {}).get('label') == 'Static website': return False
687
+ if serving_mode(state).get('mode') != 'prod' and not job(state).get('alive'): return False
688
+ try: launch(repo, state, confirmed=True, agent=True)
689
+ except Exception: return False
690
+ return True
691
+
692
+
693
+ def finalize(repo, state):
694
+ """After an agent run: if the user has a preview, swap the dev server for the production build."""
695
+ state = pathlib.Path(state)
696
+ if (state / 'run.lock').exists() or not (state / 'preview-process.json').exists() or os.getenv('MINI_PREVIEW_PROD', '1') == '0': return {}
697
+ pp = prod_plan(repo)
698
+ if not pp or pp['build'] is None: return {}
699
+ serving = serving_mode(state)
700
+ if serving.get('mode') == 'prod' and serving.get('fingerprint') == fingerprint(repo): return {}
701
+ return supervise(repo, state, 'prod')
702
+
703
+
704
+ SERVICE_PORTS = {'postgres': 5432, 'redis': 6379, 'mysql': 3306}
705
+ SERVICE_URL = {'postgres': r'postgres(?:ql)?://[^\s"\']*@(?:localhost|127\.0\.0\.1)\b', 'redis': r'redis://[^\s"\']*(?:localhost|127\.0\.0\.1)\b', 'mysql': r'(?:mysql|mariadb)://[^\s"\']*@(?:localhost|127\.0\.0\.1)\b'}
706
+
707
+
708
+ def wanted_services(repo):
709
+ """Local databases the project's env files point at (a stopped/resumed workspace boots with none running)."""
710
+ repo = pathlib.Path(repo);text = ''
711
+ for name in ('.env', '.env.local', '.env.development', '.env.development.local'):
712
+ f = repo / name
713
+ try:
714
+ if f.is_file() and not f.is_symlink() and f.stat().st_size < 200000: text += f.read_text(errors='replace') + '\n'
715
+ except OSError: pass
716
+ return [name for name, pattern in SERVICE_URL.items() if re.search(pattern, text)]
717
+
718
+
719
+ def listening(port):
720
+ import socket
721
+ with socket.socket() as sock:
722
+ sock.settimeout(0.5)
723
+ return sock.connect_ex(('127.0.0.1', port)) == 0
724
+
725
+
726
+ def start_service(name):
727
+ helper = '/usr/local/bin/mlai-service'
728
+ cmd = [helper, 'start', name] if os.path.exists(helper) else ['sudo', '-n', 'service', {'postgres': 'postgresql', 'mysql': 'mariadb'}.get(name, name), 'start']
729
+ if name == 'redis' and not os.path.exists(helper): cmd = ['sudo', '-n', 'redis-server', '--daemonize', 'yes']
730
+ try: subprocess.run(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=40)
731
+ except (OSError, subprocess.SubprocessError): return False
732
+ import time
733
+ for _ in range(20):
734
+ if listening(SERVICE_PORTS[name]): return True
735
+ time.sleep(0.25)
736
+ return False
737
+
738
+
739
+ def revive(repo, state):
740
+ """After the workspace stops and wakes up, nothing is running. Bring back the local databases the app uses
741
+ and the preview the user already approved. Never runs while an agent task holds the run lock, and backs off
742
+ when the app keeps crashing so a broken app is not restarted every poll."""
743
+ import time
744
+ state = pathlib.Path(state);done = {}
745
+ if (state / 'run.lock').exists() or not (state / 'preview-process.json').exists(): return done
746
+ try: meta = json.loads((state / 'preview-process.json').read_text())
747
+ except (OSError, ValueError): return done
748
+ if meta.get('pid') and identity(meta['pid']) == meta.get('start'): return done
749
+ if listening(3000): return done
750
+ try: last = json.loads((state / 'preview-revive.json').read_text())
751
+ except (OSError, ValueError): last = {}
752
+ recent = [t for t in last.get('times', []) if time.time() - t < 600]
753
+ if len(recent) >= 3: return {'reviveSkipped': 'The app stopped 3 times in 10 minutes, so it was not restarted automatically. Check the startup log.'}
754
+ started = []
755
+ for name in wanted_services(repo):
756
+ if not listening(SERVICE_PORTS[name]) and start_service(name): started.append(name)
757
+ (state / 'preview-revive.json').write_text(json.dumps({'times': recent + [time.time()], 'services': started}))
758
+ try: launch(repo, state, confirmed=True)
759
+ except Exception as error: return {'revived': started, 'reviveError': str(error)[:300]}
760
+ return {'revived': started + ['preview']}
761
+
762
+
763
+ def static_path_allowed(repo, request_path):
764
+ from urllib.parse import unquote, urlsplit
765
+ path = pathlib.PurePosixPath(unquote(urlsplit(request_path).path))
766
+ if any(part.startswith('.') for part in path.parts if part != '/'): return False
767
+ candidate = pathlib.Path(repo).joinpath(*[part for part in path.parts if part != '/'])
768
+ return candidate.resolve().is_relative_to(pathlib.Path(repo).resolve()) and not any(p.is_symlink() for p in [candidate, *candidate.parents] if p != pathlib.Path(repo).parent)
769
+
770
+
771
+ def serve(repo):
772
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
773
+ class Handler(SimpleHTTPRequestHandler):
774
+ def __init__(self, *args, **kwargs): super().__init__(*args, directory=str(repo), **kwargs)
775
+ def send_head(self):
776
+ if not static_path_allowed(repo, self.path):
777
+ self.send_error(403);return None
778
+ return super().send_head()
779
+ def list_directory(self, path):
780
+ self.send_error(403);return None
781
+ ThreadingHTTPServer(('0.0.0.0', 3000), Handler).serve_forever()
782
+
783
+
784
+ PATHS = {} # explicit repo/state (laptop runs keep the session state apart from the user's folder)
785
+
786
+ def main():
787
+ parser = argparse.ArgumentParser();parser.add_argument('action', choices=['status', 'start', 'serve', 'supervise', 'finalize']);parser.add_argument('--mode', choices=['dev', 'prod']);parser.add_argument('--root', default='/vercel/sandbox');parser.add_argument('--repo');parser.add_argument('--state');parser.add_argument('--confirmed', action='store_true');parser.add_argument('--agent', action='store_true');parser.add_argument('--revive', action='store_true');args = parser.parse_args()
788
+ root = pathlib.Path(args.root);state = pathlib.Path(args.state) if args.state else root / '.mini'
789
+ if args.action == 'serve': return serve(root)
790
+ repo = pathlib.Path(args.repo) if args.repo else root / 'repo'
791
+ if args.repo: PATHS['repo'] = repo
792
+ if args.action in ('supervise', 'finalize'):
793
+ result = supervise(repo, state, args.mode or 'prod') if args.action == 'supervise' else finalize(repo, state)
794
+ print(json.dumps(result)); return
795
+ try:
796
+ revived = revive(repo, state) if args.action == 'status' and args.revive else {}
797
+ result = launch(repo, state, args.confirmed, args.agent, args.mode) if args.action == 'start' else status(state)
798
+ result.update(revived)
799
+ if revived.get('revived') and not result.get('ready'): result['message'] = 'Restarting your app after the computer woke up…'
800
+ result['canStart'] = plan(repo) is not None
801
+ print(json.dumps(result))
802
+ except Exception as error:
803
+ print(json.dumps({'error': str(error)}));sys.exit(1)
804
+
805
+
806
+ if __name__ == '__main__': main()