mlai-code 0.3.8 → 0.3.9

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 CHANGED
@@ -1,4 +1,4 @@
1
- # mlai-code 0.3.8
1
+ # mlai-code 0.3.9
2
2
 
3
3
  ML AI Code in your terminal. The agent works in your project on this machine; models run in ML AI Code's cloud.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mlai-code",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "description": "ML AI Code in your terminal: an agent that reads, edits and runs code in your project, on your machine.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/home.mjs CHANGED
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import {mkdirSync,chmodSync,statSync} from 'node:fs';
4
4
  import {fileURLToPath} from 'node:url';
5
5
 
6
- export const VERSION='0.3.8';
6
+ export const VERSION='0.3.9';
7
7
  // BUG-0469: the production CLI signs in and calls the production domain.
8
8
  export const DEFAULT_SERVER='https://code.ml.ai';
9
9
  /** All local state lives here; nothing is written into the user's repository except what the agent edits. */
package/src/render.mjs CHANGED
@@ -56,6 +56,7 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
56
56
  case 'todos':return (e.items||[]).map(t=>c.gray((t.status==='done'?'[x] ':t.status==='in_progress'?'[>] ':'[ ] ')+clip(t.text,120))).join('\n')||null;
57
57
  case 'edit_guard':return c.yellow('blocked edit '+clip(e.path,120)+': '+clip(e.content,300));
58
58
  case 'steering':return c.cyan('steering received');
59
+ case 'process_stopped':return c.yellow('stopped a hung command: '+clip(e.command,160)+(e.reason?' ('+clip(e.reason,160)+')':'')+'; the agent continues'); // worker/proc_watch.py (CLI r7)
59
60
  case 'retry':return verbose?c.gray('retry: '+clip(e.content,200)):null;
60
61
  case 'error':return c.red(clip(e.content||e.error||'Error',2000));
61
62
  case 'completion':{
package/src/tui/app.mjs CHANGED
@@ -172,6 +172,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
172
172
  if(e.type==='stage'&&e.content&&st.running){st.activity=strip(String(e.content)).slice(0,80);st.stageActivity=true}
173
173
  if(e.type==='tool'&&e.name!=='todo'){st.activity=strip(tr.tool(e.name,e.target)[0]).replace(/^\S+ /,'');st.stageActivity=false}
174
174
  if(e.type==='command'){st.activity='Running '+truncate(String(e.command||'').split('\n')[0],60);st.stageActivity=false}
175
+ if(e.type==='process_stopped'&&st.running){st.activity='Stopped a hung command; continuing';st.stageActivity=false}
175
176
  tr.cols=screen.cols;let lines=tr.lines(e);
176
177
  // An approved edit's card already printed its "● Edit file" row; the tool row that follows is not repeated.
177
178
  if(e.type==='tool'&&st.cardHead&&lines.length===1&&strip(lines[0]).trim()===st.cardHead){st.cardHead=null;draw();return}
@@ -100,10 +100,23 @@ export class Transcript{
100
100
  }
101
101
  todos(items){
102
102
  const t=this.t;if(!Array.isArray(items)||!items.length)return [];
103
+ // Tester report (CLI 0.3.8): the same plan was printed twice in a row. A list repeated with nothing shown since, or
104
+ // identical to the last one shown, adds nothing.
105
+ const names=JSON.stringify(items.slice(0,30).map(it=>String(it?.text??'')));
106
+ const full=JSON.stringify(items.slice(0,30).map(it=>[String(it?.text??''),it?.status||'']));
107
+ const repeat=full===this.lastTodos||(names===this.lastTodoNames&&!this.shownSinceTodos);
108
+ this.lastTodos=full;this.lastTodoNames=names;
109
+ if(repeat)return [];
110
+ this.shownSinceTodos=false;
103
111
  return [this.dot(t.tool)+t.toolHead('Plan'),...items.slice(0,30).map(it=>{const s=it.status;const mark=s==='done'?t.ok('[x]'):s==='in_progress'?t.accent('[>]'):t.dim('[ ]');return ' '+mark+' '+(s==='done'?t.faint(truncate(it.text,this.cols-10)):truncate(String(it.text),this.cols-10))})];
104
112
  }
105
113
  /** Lines for one event; [] for events that stay quiet. */
106
114
  lines(e){
115
+ const out=this.eventLines(e);
116
+ if(out.length&&e?.type!=='todos')this.shownSinceTodos=true;
117
+ return out;
118
+ }
119
+ eventLines(e){
107
120
  const t=this.t;
108
121
  switch(e?.type){
109
122
  case 'assistant':return this.assistant(e.content);
@@ -42,6 +42,37 @@ def as_preview(value):
42
42
  u=urlparse(value)
43
43
  return u._replace(netloc=PREVIEW_HOST+':3000').geturl() if u.hostname in ('127.0.0.1','localhost') else value
44
44
 
45
+ FOREIGN=('{who} This check opened another application, not this project, so it is not evidence for this workspace. '
46
+ '{hint}')
47
+
48
+ def workspace_server(url):
49
+ """Who serves the checked address, for this workspace (MINI_REPO / MINI_ROOT): see preview.server_owner. CLI 0.3.8: port
50
+ 3000 served another workspace's app and its checks passed as the Notes app's evidence."""
51
+ repo,state=os.getenv('MINI_REPO'),os.getenv('MINI_ROOT')
52
+ if not repo or not Path(repo).is_dir():return {}
53
+ try:
54
+ import preview
55
+ port=urlparse(url).port or 80
56
+ return preview.server_owner(port,repo,state)
57
+ except Exception:return {}
58
+
59
+ def preview_url():
60
+ """This workspace's preview address (laptop previews move off port 3000 when another app holds it)."""
61
+ try:
62
+ import preview
63
+ return preview.base_url(preview.recorded_port(os.getenv('MINI_ROOT') or '/nonexistent')) if on_laptop() else 'http://127.0.0.1:3000'
64
+ except Exception:return 'http://127.0.0.1:3000'
65
+
66
+ def foreign_result(owner,url,width,height,timeline=None):
67
+ try:
68
+ import preview
69
+ who=preview.foreign_text(owner)
70
+ except Exception:who='Port %s is served by another app.'%owner.get('port')
71
+ mine=preview_url()
72
+ hint=('Use this project\'s preview at '+mine+' (start it with preview first).') if urlparse(mine).port!=owner.get('port') else 'Start the preview of this project first (it reports the address to check).'
73
+ return {'success':False,'workspaceEvidence':False,'foreignServer':owner,'error':FOREIGN.format(who=who,hint=hint),'checkedAt':url,'url':url,'timeline':timeline or [],
74
+ 'pageErrors':[],'consoleErrors':[],'networkFailures':[],'screenshot':None,'viewport':{'width':width,'height':height}}
75
+
45
76
  HYDRATION='''() => {
46
77
  const next = !!document.querySelector('script[src*="/_next/"]');
47
78
  if (!next) return {framework: null, interactive: true};
@@ -85,9 +116,7 @@ def scenario(args,output):
85
116
  if not (local and os.getenv('PLAYWRIGHT_BROWSERS_PATH')):os.environ['PLAYWRIGHT_BROWSERS_PATH']=str(output.parent.parent/'pw-browsers')
86
117
  # Windows bug list (round 6): a missing module surfaced as a bare "No module named 'fcntl'" and the agent spent many
87
118
  # calls building its own Puppeteer harness. A runtime that cannot start now says so and what to do instead.
88
- try:from playwright.sync_api import sync_playwright
89
- except ImportError as exc:raise unavailable(exc) from exc
90
- url=args.get('url','http://127.0.0.1:3000')
119
+ url=args.get('url') or preview_url()
91
120
  if not local_url(url):raise ValueError('Browser is restricted to the local app on this computer' if local else 'Browser is restricted to the local app on port 3000')
92
121
  url=as_preview(url)
93
122
  steps=args.get('steps',[])
@@ -95,6 +124,10 @@ def scenario(args,output):
95
124
  width=args.get('width',1280);height=args.get('height',800)
96
125
  if type(width)!=int or type(height)!=int or not 320<=width<=1920 or not 400<=height<=1200:raise ValueError('Unsupported viewport')
97
126
  errors=[];console=[];noise=[];timeline=[];network=[];page=None
127
+ owner=workspace_server(url)
128
+ if owner.get('owner')=='foreign':return foreign_result(owner,url,width,height)
129
+ try:from playwright.sync_api import sync_playwright
130
+ except ImportError as exc:raise unavailable(exc) from exc
98
131
  with sync_playwright() as p:
99
132
  try:browser=p.chromium.launch(headless=True,args=browser_local.launch_args() if local else ['--no-sandbox','--host-resolver-rules=MAP '+PREVIEW_HOST+' 127.0.0.1','--unsafely-treat-insecure-origin-as-secure=http://'+PREVIEW_HOST+':3000'])
100
133
  except Exception as exc:raise unavailable(exc) from exc
@@ -128,7 +161,12 @@ def scenario(args,output):
128
161
  interactive=hydrated(page)
129
162
  if interactive is False:errors.insert(0,NOT_INTERACTIVE)
130
163
  checked=actual(page,checked,local)
131
- return {'success':not errors,'interactive':interactive,'checkedAt':checked,**({'requestedUrl':url} if checked!=url and local else {}),'timeline':timeline,'url':page.url,'title':page.title(),'text':page.locator('body').inner_text()[:16000],'pageErrors':errors[:20],'consoleErrors':console[:20],**({'ignoredExtensionNoise':noise[:5]} if noise else {}),'networkFailures':network[:30],'horizontalOverflow':page.evaluate('document.documentElement.scrollWidth>innerWidth'),'screenshot':output.name,'viewport':{'width':width,'height':height}}
164
+ ended=page.url
165
+ if urlparse(ended).port!=urlparse(url).port:
166
+ moved=workspace_server(ended)
167
+ if moved.get('owner')=='foreign':return foreign_result(moved,ended,width,height,timeline)
168
+ owner=moved or owner
169
+ return {'success':not errors,**({'workspaceEvidence':True} if owner.get('owner') in ('ours','workspace') else {}),'interactive':interactive,'checkedAt':checked,**({'requestedUrl':url} if checked!=url and local else {}),'timeline':timeline,'url':page.url,'title':page.title(),'text':page.locator('body').inner_text()[:16000],'pageErrors':errors[:20],'consoleErrors':console[:20],**({'ignoredExtensionNoise':noise[:5]} if noise else {}),'networkFailures':network[:30],'horizontalOverflow':page.evaluate('document.documentElement.scrollWidth>innerWidth'),'screenshot':output.name,'viewport':{'width':width,'height':height}}
132
170
  except Exception as exc:
133
171
  if timeline and timeline[-1]['state']=='started':timeline[-1]['state']='failed'
134
172
  captured=False
@@ -231,7 +231,8 @@ def prepare(config,model,root,emit):
231
231
  def browser_review(records,current_fingerprint):
232
232
  fresh=[r for r in records if isinstance(r,dict) and r.get('sourceFingerprint')==current_fingerprint]
233
233
  def valid(r):
234
- return r.get('success') is True and r.get('horizontalOverflow') is False and not r.get('pageErrors') and not r.get('consoleErrors') and not r.get('networkFailures') and bool(r.get('screenshot')) and any(s.get('action')=='assert_text' and s.get('state')=='passed' for s in r.get('timeline',[]) if isinstance(s,dict))
234
+ # A check against another app's server (CLI 0.3.8: port 3000 served a different workspace) is not evidence here.
235
+ return r.get('workspaceEvidence') is not False and not r.get('foreignServer') and r.get('success') is True and r.get('horizontalOverflow') is False and not r.get('pageErrors') and not r.get('consoleErrors') and not r.get('networkFailures') and bool(r.get('screenshot')) and any(s.get('action')=='assert_text' and s.get('state')=='passed' for s in r.get('timeline',[]) if isinstance(s,dict))
235
236
  good=[r for r in fresh if valid(r)]
236
237
  mobile=any(320<=r.get('viewport',{}).get('width',0)<=480 for r in good)
237
238
  desktop=any(r.get('viewport',{}).get('width',0)>=1024 for r in good)
@@ -684,7 +684,10 @@ class StreamMapper:
684
684
  except Exception: pass
685
685
  def todos(self, items):
686
686
  shown = [{'text': str(t.get('title', ''))[:300], 'status': t.get('status') if t.get('status') in ('pending', 'in_progress', 'done') else 'pending'} for t in items if isinstance(t, dict)][:40]
687
- write('todos.json', shown); event('todos', items=shown)
687
+ write('todos.json', shown)
688
+ # The same list again (a repeated TodoList call) is not shown twice (tester report, CLI 0.3.8).
689
+ if shown != getattr(self, 'last_todos', None): event('todos', items=shown)
690
+ self.last_todos = shown
688
691
  def announce(self, name, args):
689
692
  if name == 'Bash': event('command', command=str(args.get('command', ''))[:20000])
690
693
  elif name in ('Agent', 'AgentSwarm'): event('subagent', state='running', content=str(args.get('description') or args.get('prompt') or '')[:400])
@@ -712,6 +715,7 @@ class StreamMapper:
712
715
  try: args = json.loads(fn.get('arguments') or '{}')
713
716
  except ValueError: args = {}
714
717
  self.calls[call.get('id')] = (name, args)
718
+ if name == 'Bash' and not args.get('run_in_background'): proc_watch.foreground(call.get('id'), args.get('command')) # CLI r7
715
719
  if name == 'TodoList' and isinstance(args.get('todos'), list): self.todos(args['todos'])
716
720
  elif len(calls) == 1: self.announce(name, args)
717
721
  # Parallel calls are announced with their results so each step pairs with its own output.
@@ -725,6 +729,7 @@ class StreamMapper:
725
729
  return
726
730
  if role == 'tool':
727
731
  name, args = self.calls.get(msg.get('tool_call_id'), ('', {}))
732
+ proc_watch.done(msg.get('tool_call_id'))
728
733
  content = msg.get('content')
729
734
  if isinstance(content, list): content = '\n'.join(p.get('text', '') for p in content if isinstance(p, dict))
730
735
  content = str(content or '')
@@ -931,11 +936,11 @@ def recheck_stale(state, env, seconds_left, limit=3):
931
936
  if budget < 20 or stopped(): break
932
937
  command = str(check.get('command'))
933
938
  began = time.time()
934
- try:
935
- r = subprocess.run(['bash', '-lc', command], cwd=REPO, env=env, capture_output=True, text=True, timeout=min(REPLAY_SECONDS, budget))
936
- code, output = r.returncode, (r.stdout + r.stderr)[-4000:]
937
- except subprocess.TimeoutExpired:
938
- code, output = None, 'Timed out when rerun on the final code.'
939
+ # Bounded on every OS: output goes to a file and the whole tree is stopped on timeout or Esc (a headless browser
940
+ # left by an e2e script kept a Windows run at "Working" for 45 minutes after its final answer).
941
+ code, output, why = verification.bounded_run(['bash', '-lc', command], cwd=REPO, env=env, timeout=int(min(REPLAY_SECONDS, budget)), stop=stopped)
942
+ if why == 'stopped': break
943
+ if code is None: output = (output + '\n' if output else '') + 'Timed out when rerun on the final code.'
939
944
  budget -= time.time() - began
940
945
  check_code, integrity = verification.check_exit(command, code, output, is_check) if code is not None else (None, '')
941
946
  code = check_code if check_code is not None else code
@@ -1367,7 +1372,7 @@ def main():
1367
1372
  research_proxy = start_research_proxy()
1368
1373
  write('status.json', {'state': 'running', 'started': time.time(), 'boot': boot_id(), 'process': identity(os.getpid()), 'harness': 'kimi'})
1369
1374
  (ROOT / 'kimi-stderr.log').unlink(missing_ok=True)
1370
- for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BACKGROUND_CHECKS, BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
1375
+ for name in ('kimi-state.json', 'kimi-progress.json', 'kimi-hook.json', 'usage.json', 'kimi-stop-count', 'design-browser-evidence.json', 'design-review.json', 'browser-unavailable.json', 'acceptance.json', 'budget-declined', 'hard-deny-targets.json', BACKGROUND_CHECKS, BLOCKED_CALLS): (ROOT / name).unlink(missing_ok=True)
1371
1376
  # "Approve all" covers the rest of the request: a Resume of the same request keeps it, a new request asks afresh.
1372
1377
  if not config.get('resuming') or config.get('subagent'): (ROOT / 'kimi-approve-all').unlink(missing_ok=True)
1373
1378
  shutil.rmtree(ROOT / 'acceptance', ignore_errors=True)
@@ -1535,6 +1540,9 @@ def main():
1535
1540
  elif time.time() - (load(ROOT, 'kimi-stopped', {}) or {}).get('time', 1e18) > FINISH_GRACE: killed['reason'] = 'finished'
1536
1541
  if killed['reason']:
1537
1542
  if killed['reason'] == 'finished': event('note', content='Work finished; background processes such as preview servers keep running')
1543
+ # CLI r7: Windows has no process groups; end every process this run owns first, also a headless
1544
+ # browser whose parent already exited (it holds the engine's pipes, so Stop never finished).
1545
+ if os.name == 'nt' and killed['reason'] != 'finished': proc_watch.kill_all(child.pid, supervisor)
1538
1546
  try:
1539
1547
  os.killpg(child.pid, signal.SIGTERM)
1540
1548
  # Up to 3 s to exit cleanly, but no longer than it takes: Stop used to wait the full 3 s (BUG-0133).
@@ -408,7 +408,19 @@ def final_issues(config, st, answer, done, model, root, repo, event, allow_accep
408
408
  except (OSError, ValueError): records = []
409
409
  report = browser_review(records, fingerprint(repo, st.get('base') or 'HEAD'))
410
410
  (Path(root) / 'design-review.json').write_text(json.dumps(report)); event('design_review', designReview=report)
411
- if report['status'] != 'passed':
411
+ unavailable = None
412
+ try: unavailable = json.loads((Path(root) / 'browser-unavailable.json').read_text())
413
+ except (OSError, ValueError): pass
414
+ if report['status'] != 'passed' and unavailable:
415
+ # Browser checks cannot run on this computer: asking again only loops the run (27 minutes in one Windows
416
+ # report). The review stays "not verified" and the agent's summary says why.
417
+ if 'design-unavailable' not in done:
418
+ done.add('design-unavailable')
419
+ event('note', content='Browser checks are not available on this computer, so the design review is reported as not verified.')
420
+ elif report['status'] != 'passed' and 'design-final' in done:
421
+ pass # asked once already in a final round; the outer bridge reports it as unresolved instead of looping
422
+ elif report['status'] != 'passed':
423
+ done.add('design-final')
412
424
  issues.append(report['message'] + ' Start the app with mcp__mlai__preview {"action":"start"}, then run mcp__mlai__browser at width 390 and at width 1280, each with at least one click/fill/press and an assert_text. Fix overflow, console or page errors and failed requests, then check again.')
413
425
  from conversation import research_required
414
426
  from evidence import EvidenceLedger
@@ -859,7 +859,9 @@ def stop(payload, st):
859
859
  from quality import fingerprint
860
860
  report = browser_review(load('design-browser-evidence.json', []), fingerprint(REPO, st.get('base') or 'HEAD'))
861
861
  save('design-review.json', report); event('design_review', designReview=report)
862
- if report['status'] != 'passed':
862
+ if report['status'] != 'passed' and (ROOT / 'browser-unavailable.json').exists():
863
+ done.add('design') # the browser cannot run here; the agent was told to verify with tests and build instead
864
+ elif report['status'] != 'passed':
863
865
  done.add('design'); issues.append(report['message'] + ' Start the app with mcp__mlai__preview {"action":"start"}, then run mcp__mlai__browser at width 390 and at width 1280, each with at least one click/fill/press and an assert_text. Fix overflow, console or page errors and failed requests.')
864
866
  except Exception: pass
865
867
  if 'evidence' not in done:
@@ -37,7 +37,7 @@ WRITE_TOOLS = [IMAGE_TOOL, STOCK_TOOL, BRAND_TOOL, *deck_tools.TOOLS, MEMORY_PRO
37
37
  {'name': 'browser', 'description': 'Built-in Playwright browser checks (BUG-0202: this is the browser tool; no Playwright install is needed). Open the local app (http://127.0.0.1:3000 by default, start it with preview first; it is browsed under a preview-style *.vercel.run host, the way the user reaches it, so dev-server host and origin blocks show up here) in headless Chromium at a given viewport, run up to 12 steps and take a screenshot. Reports page errors, console errors, failed requests, horizontal overflow, visible text and whether the page became interactive (hydrated). For UI work check a phone width (<=480) and a desktop width (>=1024) with at least one click/fill/press and an assert_text. Each call starts a fresh browser profile: localStorage, cookies and sessions from an earlier call are gone, so do every step that depends on saved state (sign in, add items, then a goto step to the same URL to reload, then assert_text) inside one call.',
38
38
  'inputSchema': {'type': 'object', 'properties': {'url': {'type': 'string'}, 'width': {'type': 'integer', 'minimum': 320, 'maximum': 1920}, 'height': {'type': 'integer', 'minimum': 400, 'maximum': 1200},
39
39
  'steps': {'type': 'array', 'maxItems': 12, 'items': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['goto', 'click', 'fill', 'press', 'assert_text']}, 'role': {'type': 'string'}, 'name': {'type': 'string'}, 'selector': {'type': 'string'}, 'value': {'type': 'string'}, 'key': {'type': 'string'}, 'text': {'type': 'string'}, 'url': {'type': 'string'}}, 'required': ['action']}}}}},
40
- {'name': 'preview', 'description': 'Start (or check) the managed preview of this project on port 3000: Next.js and Vite dev/start scripts, or a static index.html. Installs missing packages first and runs the dev server (hot reload) during the task; after the task it is swapped for the production build the user opens and shares. Servers started with Bash in the background stop when the task ends.',
40
+ {'name': 'preview', 'description': 'Start (or check) the managed preview of this project on port 3000 (on a laptop it moves to a free port when another app already answers on 3000; always check the url it reports, and never treat another app on the port as this project): Next.js and Vite dev/start scripts, or a static index.html. Installs missing packages first and runs the dev server (hot reload) during the task; after the task it is swapped for the production build the user opens and shares. Servers started with Bash in the background stop when the task ends.',
41
41
  'inputSchema': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['start', 'status']}}, 'required': ['action']}},
42
42
  {'name': 'job', 'description': 'Run long work (training, benchmark sweeps, data pipelines, servers other than the preview) as a supervised background job that outlives this turn. start {name, command, resume?, restart?, keepalive_hours?}: resume is the command that continues from the last checkpoint after an unexpected stop (defaults to command); restart on-failure (default) restarts it automatically up to 3 times; keepalive_hours (max 12) keeps the workspace awake while it runs. status lists jobs with state and log tail; logs {name, lines?}; stop {name}. Make long jobs checkpoint their progress so a restart continues instead of starting over.',
43
43
  'inputSchema': {'type': 'object', 'properties': {'action': {'type': 'string', 'enum': ['start', 'status', 'logs', 'stop']}, 'name': {'type': 'string'}, 'command': {'type': 'string'}, 'resume': {'type': 'string'},
@@ -236,7 +236,22 @@ def readonly_browser():
236
236
  if os.getenv('MINI_SUBAGENT') == '1': return []
237
237
  return [t for t in WRITE_TOOLS if t.get('name') == 'browser']
238
238
 
239
+ def browser_unavailable(reason):
240
+ """Remembers for this run that browser checks cannot run on this computer, so the final gates stop asking for them
241
+ (a Windows run spent 27 minutes being told to rerun a browser check that could not start)."""
242
+ try: (ROOT / 'browser-unavailable.json').write_text(json.dumps({'reason': str(reason)[:500], 'time': time.time()}))
243
+ except OSError: pass
244
+ return reason
245
+
239
246
  def browser(args):
247
+ try: return _browser(args)
248
+ except ValueError as exc:
249
+ from browser_tool import BrowserUnavailable
250
+ if isinstance(exc, BrowserUnavailable) or re.search(r'not installed in this workspace|declined the browser download|could not be installed', str(exc)):
251
+ browser_unavailable(exc)
252
+ raise
253
+
254
+ def _browser(args):
240
255
  args = {k: v for k, v in args.items() if k in ('url', 'width', 'height', 'steps')}
241
256
  installed = False
242
257
  if not (ROOT / 'browser-ready').exists():