mlai-code 0.3.4 → 0.3.6
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 +1 -1
- package/package.json +1 -1
- package/src/cli.mjs +6 -6
- package/src/headless.mjs +18 -6
- package/src/home.mjs +1 -1
- package/src/render.mjs +15 -4
- package/src/tui/ansi.mjs +47 -7
- package/src/tui/app.mjs +8 -7
- package/src/tui/markdown.mjs +58 -18
- package/src/tui/transcript.mjs +28 -12
- package/worker/browser_tool.py +12 -2
- package/worker/conversation.py +90 -2
- package/worker/kimi_bridge.py +60 -20
- package/worker/kimi_gates.py +1 -1
- package/worker/kimi_hook.py +20 -2
- package/worker/mlai_hooks.py +1 -1
- package/worker/mlai_mcp.py +11 -0
- package/worker/runner.py +95 -11
- package/worker/runtime_control.py +109 -10
- package/worker/tool_catalog.py +4 -1
- package/worker/verification.py +24 -7
package/README.md
CHANGED
package/package.json
CHANGED
package/src/cli.mjs
CHANGED
|
@@ -25,7 +25,7 @@ import {SANDBOXES} from './sandbox.mjs';
|
|
|
25
25
|
import {restrictedForced,refusedFlag} from './restricted.mjs';
|
|
26
26
|
import {gitForWindows} from './winenv.mjs';
|
|
27
27
|
import {ensureRuntime,runtimeInfo,PY_VERSION,hideEngineName} from './runtime.mjs';
|
|
28
|
-
import {palette,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits} from './render.mjs';
|
|
28
|
+
import {palette,colorAllowed,renderEvent,approvalView,summaryLine,exitCode,EXIT,fmt,credits} from './render.mjs';
|
|
29
29
|
import {runHeadless,streamInputs,stdinLines,toolRules,loadSchema,HeadlessError} from './headless.mjs';
|
|
30
30
|
import {terminals,backgroundCommand} from './tui/bgterm.mjs';
|
|
31
31
|
|
|
@@ -261,14 +261,14 @@ export async function main(argv=process.argv.slice(2)){
|
|
|
261
261
|
// `mlai review ...` has its own flags (src/tui/review-cli.mjs).
|
|
262
262
|
// `mlai agents ...` and `mlai attach <id>`: background agents (src/tui/agents-cli.mjs), with their own flags.
|
|
263
263
|
if(argv[0]==='agents'||argv[0]==='attach')return await agentsCli(argv);
|
|
264
|
-
if(argv[0]==='review')return await (await import('./tui/review-cli.mjs')).reviewMain(argv.slice(1),{cloud:o=>cloudFor(o),color:palette(
|
|
264
|
+
if(argv[0]==='review')return await (await import('./tui/review-cli.mjs')).reviewMain(argv.slice(1),{cloud:o=>cloudFor(o),color:palette(!argv.includes('--json')&&colorAllowed(process.stdout))});
|
|
265
265
|
if(EXT_COMMANDS[argv[0]])return await EXT_COMMANDS[argv[0]](argv.slice(1));
|
|
266
266
|
let o;
|
|
267
267
|
try{o=parseArgs(argv)}catch(e){if(jsonArgv(argv))process.stdout.write(JSON.stringify({type:'result',state:'error',subtype:'error_usage',error:e.message,exitCode:EXIT.usage})+'\n');else process.stderr.write(e.message+'\n');return EXIT.usage}
|
|
268
268
|
const cmd=COMMANDS.includes(o._[0])?o._.shift():null;
|
|
269
269
|
if(!cmd){const slip=commandSlip(o);if(slip){process.stderr.write(slip+'\n');return EXIT.usage}}
|
|
270
|
-
const c=palette(process.stdout
|
|
271
|
-
const err=palette(process.stderr
|
|
270
|
+
const c=palette(!o.json&&colorAllowed(process.stdout));
|
|
271
|
+
const err=palette(colorAllowed(process.stderr));
|
|
272
272
|
try{
|
|
273
273
|
if(cmd==='help'){process.stdout.write((SUB_HELP[o._[0]]||HELP)+'\n');return 0}
|
|
274
274
|
if(cmd==='version'){process.stdout.write(VERSION+'\n');return 0}
|
|
@@ -523,7 +523,7 @@ async function headless(o,c,err,task,s){
|
|
|
523
523
|
|
|
524
524
|
async function interactive(o,c,s,first){
|
|
525
525
|
const cloud=await cloudFor(o);
|
|
526
|
-
const err=palette(process.stderr
|
|
526
|
+
const err=palette(colorAllowed(process.stderr));
|
|
527
527
|
const settings=settingsFor(o,s,err),chat=new Chat({session:s,settings,cloud,flags:chatFlags(o,settings)});
|
|
528
528
|
await registry.loadCommands({warn:m=>process.stderr.write(err.yellow(m)+'\n')});
|
|
529
529
|
chat.loadModels().then(()=>{if(o.model)return chat.setModel(o.model)}).catch(e=>process.stderr.write(err.yellow(e.message)+'\n'));
|
|
@@ -645,7 +645,7 @@ async function plainLoop(o,c,chat,first){
|
|
|
645
645
|
const renderDeps=()=>({renderEvent,approvalView,summaryLine,exitCode});
|
|
646
646
|
async function agentsCli(argv){
|
|
647
647
|
const [{agentsMain,attachMain},{findSessions}]=await Promise.all([import('./tui/agents-cli.mjs'),import('./tui/cmd-core.mjs')]);
|
|
648
|
-
const c=palette(
|
|
648
|
+
const c=palette(!argv.includes('--json')&&colorAllowed(process.stdout));
|
|
649
649
|
const deps={Session,sessionsDir:path.join(home(),'sessions'),findSessions,render:renderDeps(),c,out:t=>process.stdout.write(t+'\n'),stdin:process.stdin,stdout:process.stdout};
|
|
650
650
|
try{return argv[0]==='attach'?await attachMain(argv.slice(1),deps):await agentsMain(argv.slice(1),deps)}
|
|
651
651
|
catch(e){process.stderr.write((e.usage?'':'error: ')+friendly(e)+'\n');return e.usage?EXIT.usage:EXIT.error}
|
package/src/headless.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import {readFileSync,existsSync} from 'node:fs';
|
|
|
13
13
|
import {readFile,rm} from 'node:fs/promises';
|
|
14
14
|
import {normalizeRule} from './tui/permissions.mjs';
|
|
15
15
|
import {TOKENS_PER_CREDIT,creditsFor,answerOf} from './tui/chat.mjs';
|
|
16
|
-
import {renderEvent,summaryLine,exitCode,EXIT} from './render.mjs';
|
|
16
|
+
import {renderEvent,summaryLine,exitCode,EXIT,prose as proseOf} from './render.mjs';
|
|
17
17
|
|
|
18
18
|
export const TOOL_NAMES=['Bash','Edit','Read','WebFetch','WebSearch','Agent'];
|
|
19
19
|
export class HeadlessError extends Error{}
|
|
@@ -122,7 +122,7 @@ const finalText=(r,events)=>answerOf({events,status:{result:r.result,error:r.err
|
|
|
122
122
|
* Runs the print-mode turns. o: parsed flags; s: the Session; chat: its Chat (toolRules, appendPrompt, fallbacks set).
|
|
123
123
|
* inputs: an async iterable of {text, images} (one item without --input-format stream-json). Returns the exit code.
|
|
124
124
|
*/
|
|
125
|
-
export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.write(t),log=t=>process.stderr.write(t)}){
|
|
125
|
+
export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.write(t),log=t=>process.stderr.write(t),tty=!!(process.stdout.isTTY&&process.stderr.isTTY)}){
|
|
126
126
|
const stream=o.outputFormat==='stream-json',json=o.outputFormat==='json';
|
|
127
127
|
const write=x=>out(JSON.stringify(x)+'\n');
|
|
128
128
|
const schema=o.jsonSchema?loadSchema(o.jsonSchema):null;
|
|
@@ -133,13 +133,25 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
133
133
|
// BUG-0557: the engine must not promise an automatic continue that a one-shot process will never run.
|
|
134
134
|
const oneShot=process.env.MINI_ONE_SHOT;process.env.MINI_ONE_SHOT='1';
|
|
135
135
|
// BUG-0561: the agent's last message is also the final answer on stdout; held back so a terminal shows it once.
|
|
136
|
-
|
|
136
|
+
// The run's closing events (the "N files changed" summary, notes, retries) arrive after the answer; they are printed
|
|
137
|
+
// without releasing the held prose, so the answer is not shown once as prose and again as the final text.
|
|
138
|
+
const CLOSING=new Set(['completion','note','finished','questions','retry','intent','mode','budget','run_metrics','done_gate','verification_report','policy']);
|
|
139
|
+
let prose=null,proseRaw=null,after=[];const shown=[];
|
|
140
|
+
const flushProse=()=>{if(prose!=null){log(prose+'\n');shown.push(proseOf(proseRaw));if(shown.length>8)shown.shift();prose=null}for(const l of after)log(l+'\n');after=[]};
|
|
137
141
|
const sameText=(a,b)=>{const x=String(a||'').replace(/\s+/g,' ').trim();return !!x&&String(b||'').replace(/\s+/g,' ').includes(x)};
|
|
142
|
+
// In a terminal (stdout and stderr both on screen) an answer the agent already wrote as prose is not printed again:
|
|
143
|
+
// only what the harness added to it (a verification note) is. Piped stdout always gets the full answer.
|
|
144
|
+
const unseen=text=>{
|
|
145
|
+
if(!tty||!text)return text;
|
|
146
|
+
for(const p of shown){const raw=String(p||'').trim();if(!raw)continue;
|
|
147
|
+
if(String(text).replace(/\s+/g,' ').trim()===raw.replace(/\s+/g,' ').trim())return '';
|
|
148
|
+
if(raw.length>40&&String(text).includes(raw))return String(text).replace(raw,'').trim()}
|
|
149
|
+
return text};
|
|
138
150
|
const stop=()=>{s.cancel().catch(()=>{})};process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
139
151
|
const onEvent=e=>{
|
|
140
152
|
events.push(e);
|
|
141
153
|
if(stream)write(e);
|
|
142
|
-
else if(!json){const line=renderEvent(e,{c:err,verbose:o.verbose});if(line&&e.type!=='answer'){flushProse();if(e.type==='assistant'){prose=line;proseRaw=e.content}else log(line+'\n')}}
|
|
154
|
+
else if(!json){const line=renderEvent(e,{c:err,verbose:o.verbose});if(line&&e.type!=='answer'){if(prose!=null&&CLOSING.has(e.type))after.push(line);else{flushProse();if(e.type==='assistant'){prose=line;proseRaw=e.content}else log(line+'\n')}}}
|
|
143
155
|
if(e.type==='approval'){
|
|
144
156
|
if(o.yes)s.decide(e.id,'approve_all').catch(()=>{});
|
|
145
157
|
else if(o.bgChild){} // a background run (mlai --bg) waits for mlai attach to answer
|
|
@@ -192,12 +204,12 @@ export async function runHeadless(o,{s,chat,err,inputs,out=t=>process.stdout.wri
|
|
|
192
204
|
if(exit!==EXIT.completed)code=exit;
|
|
193
205
|
last={type:'result',subtype,state:r.state,exitCode:exit,sessionId:s.meta.id,name:s.meta.title||null,mode:chat.mode,model:chat.model||chat.info?.id||null,effort:chat.effort,text,
|
|
194
206
|
...(schema?{structuredOutput:structured??null}:{}),error:subtype==='success'?null:(r.error||null),usage:r.usage||null,
|
|
195
|
-
credits:creditsFor(spent),turns,changedFiles:r.completion?.changedFiles||[],checksPassed:r.completion?.checksPassed||0,checksFailed:r.completion?.checksFailed||0,rejectedApprovals:refused,
|
|
207
|
+
credits:creditsFor(spent),turns,changedFiles:r.completion?.changedFiles||[],checksPassed:(r.completion?.checksPassed||0)+(r.completion?.supportingChecksPassed||0),checksFailed:(r.completion?.checksFailed||0)+(r.completion?.supportingChecksFailed||0),rejectedApprovals:refused,
|
|
196
208
|
persisted:!o.noSessionPersistence,
|
|
197
209
|
// BUG-0555: with -w the work is in its own worktree; say where, so scripts and people can find it.
|
|
198
210
|
...(s.meta.worktree&&!s.meta.worktree.removed?{worktree:{path:s.meta.worktree.path,branch:s.meta.worktree.branch}}:{})};
|
|
199
211
|
if(stream)write(last);
|
|
200
|
-
else if(!json){if(prose!=null&&(sameText(proseRaw,text)||sameText(prose,text)))prose=null;flushProse();if(schema&&structured!==undefined)out(JSON.stringify(structured)+'\n');else if(
|
|
212
|
+
else if(!json){if(prose!=null&&(sameText(proseRaw,text)||sameText(prose,text)))prose=null;flushProse();const fresh=unseen(text);if(schema&&structured!==undefined)out(JSON.stringify(structured)+'\n');else if(fresh)out(fresh.trim()+'\n');log(summaryLine(r,err)+'\n');if(last.worktree&&last.changedFiles.length)log(err.dim('The changes are in the worktree '+last.worktree.path+' on branch '+last.worktree.branch+', not in your folder. Look with: cd '+last.worktree.path+' · bring them back with: git merge '+last.worktree.branch+' (after committing them there)')+'\n')}
|
|
201
213
|
if(['error_max_budget','stopped'].includes(subtype))break;
|
|
202
214
|
}
|
|
203
215
|
if(json&&last)write(last);
|
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.
|
|
6
|
+
export const VERSION='0.3.6';
|
|
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
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
// Turns harness events into terminal output. Pure functions so they can be tested without a terminal.
|
|
2
|
+
// Colors for line output (mlai -p, mlai agents, mlai review): on only when colorAllowed says so (a terminal, or
|
|
3
|
+
// FORCE_COLOR; never with NO_COLOR, TERM=dumb or a pipe). Same meaning as the TUI's palette: gray = tool activity and
|
|
4
|
+
// logs, green = success, yellow = needs attention, red = errors.
|
|
5
|
+
export {colorAllowed} from './tui/ansi.mjs';
|
|
2
6
|
const ESC=s=>'\x1b['+s+'m';
|
|
3
7
|
export function palette(on){
|
|
4
8
|
const w=(a,b)=>s=>on?ESC(a)+s+ESC(b):String(s);
|
|
@@ -45,6 +49,7 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
|
|
|
45
49
|
case 'output':{
|
|
46
50
|
if(e.returncode===0&&!verbose)return null;
|
|
47
51
|
const tail=String(e.output||'').trim().split('\n').slice(verbose?-20:-4).join('\n');
|
|
52
|
+
if(e.blocked)return c.yellow('not run: '+tail); // refused before it ran: there is no exit code (CLI 0.3.4)
|
|
48
53
|
return e.returncode===0?c.gray(tail):c.yellow('exit '+e.returncode+(tail?'\n'+tail:''));
|
|
49
54
|
}
|
|
50
55
|
case 'verification':{const ok=e.verdict?.status==='passed'||(e.verdict==null&&e.returncode===0);return (ok?c.green('check passed'):c.red('check '+(e.verdict?.status||'failed')))+' '+clip(e.label,120)}
|
|
@@ -55,9 +60,15 @@ export function renderEvent(e,{c=palette(false),verbose=false}={}){
|
|
|
55
60
|
case 'error':return c.red(clip(e.content||e.error||'Error',2000));
|
|
56
61
|
case 'completion':{
|
|
57
62
|
const files=(e.changedFiles||[]).map(f=>String(f).replace(/^\w+\t/,''));
|
|
58
|
-
const
|
|
59
|
-
parts.push(
|
|
60
|
-
|
|
63
|
+
const total=Math.max(files.length,Number(e.changedFilesTotal)||0);
|
|
64
|
+
const parts=[];if(files.length)parts.push(total+' file'+(total===1?'':'s')+' changed: '+clip(files.join(', '),300));
|
|
65
|
+
// A turn that ran no checks has nothing to report: a question shows no "0 checks passed" line, and a change says so plainly.
|
|
66
|
+
// Evidence checks an inspect-only turn ran count too: they ran and passed or failed (CLI 0.3.4: "0 checks passed").
|
|
67
|
+
const passed=(Number(e.checksPassed)||0)+(Number(e.supportingChecksPassed)||0),failed=(Number(e.checksFailed)||0)+(Number(e.supportingChecksFailed)||0);
|
|
68
|
+
if(passed)parts.push(passed+' check'+(passed===1?'':'s')+' passed'+(failed?', '+failed+' failed':''));
|
|
69
|
+
else if(failed)parts.push(failed+' check'+(failed===1?'':'s')+' failed');
|
|
70
|
+
else if(files.length)parts.push('no checks ran');
|
|
71
|
+
return parts.length?c.dim(parts.join(' · ')):null;
|
|
61
72
|
}
|
|
62
73
|
case 'policy':return e.autoReview?(e.decision==='deny'?c.yellow(clip(e.content,300)+' · /approve allows it once'):c.gray(clip(e.content,200))):null; // worker/mlai_auto_review.py
|
|
63
74
|
case 'intent':return verbose?c.gray('route '+e.intent+' ('+e.mode+')'):null;
|
|
@@ -78,5 +89,5 @@ export function exitCode(result){
|
|
|
78
89
|
export function summaryLine(result,c=palette(false)){
|
|
79
90
|
const u=result.usage||{};
|
|
80
91
|
const state=result.state==='completed'&&result.cannotComplete?c.yellow('Could not be done'):result.state==='completed'?c.green('Done'):result.state==='limited'?c.yellow('Needs attention'):result.state==='stopped'?c.yellow('Stopped'):c.red('Failed');
|
|
81
|
-
return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+' model calls');
|
|
92
|
+
return state+c.dim(' · '+credits(u.tokens)+' · '+fmt(u.calls)+(Number(u.calls)===1?' model call':' model calls'));
|
|
82
93
|
}
|
package/src/tui/ansi.mjs
CHANGED
|
@@ -33,12 +33,15 @@ export function wrap(text,cols){
|
|
|
33
33
|
if(width(line)<=cols){out.push(line);continue}
|
|
34
34
|
let cur='',w=0,active='',lastSpace=-1,lastSpaceW=0;
|
|
35
35
|
const tokens=line.match(new RegExp(SGR.source+'|[\\s\\S]','gu'))||[];
|
|
36
|
-
for(
|
|
36
|
+
for(let i=0;i<tokens.length;i++){
|
|
37
|
+
const t=tokens[i];
|
|
37
38
|
if(t.startsWith('\x1b')){cur+=t;active=/\x1b\[0?m/.test(t)?'':active+t;continue}
|
|
38
39
|
const cw=charWidth(t);
|
|
39
40
|
if(w+cw>cols){
|
|
40
41
|
if(/\s/.test(t)){out.push(cur+(active?'\x1b[0m':''));cur=active;w=0;lastSpace=-1;continue}
|
|
41
|
-
|
|
42
|
+
// Break at the last space so words stay whole; only a word longer than a whole line (a long URL) is split,
|
|
43
|
+
// and then only when breaking at the space would leave the line mostly empty.
|
|
44
|
+
if(lastSpace>0&&(lastSpaceW>cols/3||wordWidth(tokens,i,w-lastSpaceW-1)<=cols)){out.push(cur.slice(0,lastSpace)+(active?'\x1b[0m':''));cur=active+cur.slice(lastSpace+1);w=width(cur)}
|
|
42
45
|
else{out.push(cur+(active?'\x1b[0m':''));cur=active;w=0}
|
|
43
46
|
lastSpace=-1;
|
|
44
47
|
}
|
|
@@ -49,6 +52,8 @@ export function wrap(text,cols){
|
|
|
49
52
|
}
|
|
50
53
|
return out;
|
|
51
54
|
}
|
|
55
|
+
/** Columns of the word that has `sofar` columns before token i and continues to the next whitespace. */
|
|
56
|
+
function wordWidth(tokens,i,sofar){let w=sofar;for(;i<tokens.length;i++){const t=tokens[i];if(t.startsWith('\x1b'))continue;if(/\s/.test(t))break;w+=charWidth(t)}return w}
|
|
52
57
|
/** Cuts a styled string to `cols` columns, adding an ellipsis when it was longer. */
|
|
53
58
|
export function truncate(s,cols,ellipsis='…'){
|
|
54
59
|
s=String(s??'');if(width(s)<=cols)return s;
|
|
@@ -66,13 +71,38 @@ export const pad=(s,cols)=>s+' '.repeat(Math.max(0,cols-width(s)));
|
|
|
66
71
|
* A theme with color:false returns text unchanged for every role (NO_COLOR, TERM=dumb, pipes).
|
|
67
72
|
*/
|
|
68
73
|
const THEMES={
|
|
69
|
-
dark:{text:'39',dim:'90',faint:'2',bold:'1',italic:'3',under:'4',accent:'36',accent2:'35',ok:'32',warn:'
|
|
74
|
+
dark:{text:'39',dim:'90',faint:'2',bold:'1',italic:'3',under:'4',accent:'36',accent2:'35',ok:'32',warn:'38;5;208',bad:'31',
|
|
70
75
|
add:'32',del:'31',addBg:'48;5;22',delBg:'48;5;52',hunk:'36',border:'90',borderFocus:'36',borderShell:'35',borderPlan:'34',
|
|
71
|
-
code:'38;5;180',keyword:'38;5;176',string:'38;5;114',number:'38;5;209',comment:'38;5;245',fn:'38;5;117',
|
|
76
|
+
code:'38;5;180',keyword:'38;5;176',string:'38;5;114',number:'38;5;209',comment:'38;5;245',fn:'38;5;117',quote:'90',sel:'7',
|
|
77
|
+
// Transcript roles: who said what, and what is happening in the background (see SEMANTIC below).
|
|
78
|
+
user:'1;36',assistant:'37',head:'1;97',head2:'1;37',important:'33',tool:'90',toolHead:'1;90',link:'38;5;75',bullet:'90'},
|
|
72
79
|
light:{text:'39',dim:'38;5;242',faint:'38;5;246',bold:'1',italic:'3',under:'4',accent:'38;5;25',accent2:'38;5;91',ok:'38;5;28',warn:'38;5;130',bad:'38;5;160',
|
|
73
80
|
add:'38;5;28',del:'38;5;160',addBg:'48;5;194',delBg:'48;5;224',hunk:'38;5;25',border:'38;5;248',borderFocus:'38;5;25',borderShell:'38;5;91',borderPlan:'38;5;26',
|
|
74
|
-
code:'38;5;94',keyword:'38;5;90',string:'38;5;28',number:'38;5;166',comment:'38;5;244',fn:'38;5;25',
|
|
81
|
+
code:'38;5;94',keyword:'38;5;90',string:'38;5;28',number:'38;5;166',comment:'38;5;244',fn:'38;5;25',quote:'38;5;242',sel:'7',
|
|
82
|
+
user:'1;38;5;25',assistant:'39',head:'1;38;5;16',head2:'1',important:'38;5;136',tool:'38;5;244',toolHead:'1;38;5;244',link:'38;5;25',bullet:'38;5;244'},
|
|
75
83
|
};
|
|
84
|
+
/**
|
|
85
|
+
* The semantic palette the transcript uses, so each kind of text has one look everywhere:
|
|
86
|
+
* user the person's message bold cyan (dark) / bold blue (light)
|
|
87
|
+
* assistant the answer's prose white (dark) / the terminal's text color (light)
|
|
88
|
+
* head headings (h1, h2); head2 = h3+ bold bright white / bold
|
|
89
|
+
* important notes worth seeing yellow
|
|
90
|
+
* ok success (Done, Check passed) green
|
|
91
|
+
* bad errors red
|
|
92
|
+
* warn warnings orange on 256-color terminals, yellow on 16-color ones
|
|
93
|
+
* tool tool rows and logs dim grey; toolHead = the verb on the row (bold grey)
|
|
94
|
+
* link URLs light blue
|
|
95
|
+
*/
|
|
96
|
+
export const SEMANTIC=['user','assistant','head','head2','important','ok','bad','warn','tool','toolHead','link','bullet'];
|
|
97
|
+
/** Roles that use a 256-color code, mapped to the closest basic color for 16-color terminals. */
|
|
98
|
+
const BASIC={dark:{warn:'33',link:'94'},light:{warn:'33',link:'34',important:'33',user:'1;34',tool:'90',toolHead:'1;90',bullet:'90',head:'1'}};
|
|
99
|
+
/** Whether the terminal shows 256 colors. Most do; TERM=xterm/linux/vt100 without COLORTERM are the exceptions. */
|
|
100
|
+
export function colorDepth(env=process.env){
|
|
101
|
+
if(env.MLAI_COLORS==='16')return 16;
|
|
102
|
+
if(/^(truecolor|24bit)$/i.test(env.COLORTERM||'')||/256|direct|kitty|alacritty|wezterm|ghostty/i.test(env.TERM||''))return 256;
|
|
103
|
+
if(env.TERM_PROGRAM||env.WT_SESSION||env.ConEmuANSI)return 256;
|
|
104
|
+
return /^(xterm|linux|vt\d+|screen|ansi|cygwin)$/.test(env.TERM||'')?16:256;
|
|
105
|
+
}
|
|
76
106
|
export const THEME_NAMES=['dark','light'];
|
|
77
107
|
/**
|
|
78
108
|
* Syntax themes recolor fenced code only (code, keyword, string, number, comment, function names). 'default' keeps
|
|
@@ -98,9 +128,9 @@ export function resolveTheme(name,env=process.env){
|
|
|
98
128
|
const bg=Number(String(env.COLORFGBG||'').split(';').pop());
|
|
99
129
|
return Number.isFinite(bg)&&(bg===7||bg===15||(bg>=9&&bg!==8&&bg<16&&bg!==0))?'light':'dark';
|
|
100
130
|
}
|
|
101
|
-
export function theme(name='dark',{color=true,syntax='default'}={}){
|
|
131
|
+
export function theme(name='dark',{color=true,syntax='default',depth=256}={}){
|
|
102
132
|
const base=THEMES[name]?name:'dark';
|
|
103
|
-
const roles={...THEMES[base],...(SYNTAX[syntax]?.[base]||{})};
|
|
133
|
+
const roles={...THEMES[base],...(SYNTAX[syntax]?.[base]||{}),...(depth<256?BASIC[base]:{})};
|
|
104
134
|
const t={name:base,color,syntax:SYNTAX[syntax]?syntax:'default'};
|
|
105
135
|
// Nested styles: an inner reset re-opens the outer style, so bold inside a colored row keeps the row's color.
|
|
106
136
|
for(const [k,v] of Object.entries(roles)){const open=CSI+v+'m';t[k]=color?s=>open+String(s).split(CSI+'0m').join(CSI+'0m'+open)+CSI+'0m':s=>String(s)}
|
|
@@ -108,6 +138,16 @@ export function theme(name='dark',{color=true,syntax='default'}={}){
|
|
|
108
138
|
t.reset=color?CSI+'0m':'';
|
|
109
139
|
return t;
|
|
110
140
|
}
|
|
141
|
+
/** Fills the semantic roles for a theme-like object that predates them (or a hand-made one in a test). */
|
|
142
|
+
const FALLBACK={user:'accent',assistant:'text',head:'bold',head2:'bold',important:'warn',tool:'dim',toolHead:'bold',link:'accent',bullet:'dim'};
|
|
143
|
+
const filled=new WeakMap();
|
|
144
|
+
export function withRoles(t){
|
|
145
|
+
if(!t||SEMANTIC.every(k=>typeof t[k]==='function'))return t;
|
|
146
|
+
let f=filled.get(t);if(f)return f;
|
|
147
|
+
const id=s=>String(s);f={...t};
|
|
148
|
+
for(const k of SEMANTIC)if(typeof f[k]!=='function')f[k]=t[FALLBACK[k]]||t.text||id;
|
|
149
|
+
filled.set(t,f);return f;
|
|
150
|
+
}
|
|
111
151
|
/** Whether colors are allowed for this stream and environment. */
|
|
112
152
|
export function colorAllowed(stream=process.stdout,env=process.env){
|
|
113
153
|
if('NO_COLOR' in env&&env.NO_COLOR!=='')return false;
|
package/src/tui/app.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
import {readFile} from 'node:fs/promises';
|
|
12
12
|
import {spawn} from 'node:child_process';
|
|
13
13
|
import path from 'node:path';
|
|
14
|
-
import {theme as makeTheme,resolveTheme,colorAllowed,boxChars,width,truncate,wrap,charWidth,strip} from './ansi.mjs';
|
|
14
|
+
import {theme as makeTheme,resolveTheme,colorAllowed,colorDepth,boxChars,width,truncate,wrap,charWidth,strip} from './ansi.mjs';
|
|
15
15
|
import {keyReader} from './keys.mjs';
|
|
16
16
|
import {Editor,loadHistory,saveHistory} from './editor.mjs';
|
|
17
17
|
import {Screen} from './screen.mjs';
|
|
@@ -71,10 +71,10 @@ export function layoutInput(text,cursor,cols){
|
|
|
71
71
|
|
|
72
72
|
export async function runTui({session,settings={},cloud=null,flags={},first=null,images=[],send,makeCtx,onSessionChange,chat=null,
|
|
73
73
|
stdin=process.stdin,stdout=process.stdout,env=process.env,historyFile=path.join(sub('state'),'history.jsonl')}={}){
|
|
74
|
-
const color=colorAllowed(stdout,env);
|
|
74
|
+
const color=colorAllowed(stdout,env),depth=colorDepth(env);
|
|
75
75
|
let themeName=resolveTheme(settings.theme||'auto',env);
|
|
76
76
|
let syntaxName=settings.syntaxTheme||'default';
|
|
77
|
-
let t=makeTheme(themeName,{color,syntax:syntaxName});
|
|
77
|
+
let t=makeTheme(themeName,{color,syntax:syntaxName,depth});
|
|
78
78
|
const box=boxChars(env);
|
|
79
79
|
const screen=new Screen(stdout);
|
|
80
80
|
const editor=new Editor({history:await loadHistory(historyFile),vim:Boolean(settings.vim)});
|
|
@@ -91,7 +91,8 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
|
|
|
91
91
|
const setModeAll=async m=>{if(chat?.setMode)await chat.setMode(m);else await applyMode(session,m)};
|
|
92
92
|
const curMode=()=>modeName(chat?.mode)||(session?.meta?sessionMode(session.meta):'agent');
|
|
93
93
|
// ---------- output helpers ----------
|
|
94
|
-
|
|
94
|
+
// One blank line between blocks: a block that opens with a blank line right after one that ended with one keeps one.
|
|
95
|
+
const print=lines=>{tr.cols=screen.cols;let l=Array.isArray(lines)?lines:String(lines).split('\n');if(st.blankEnd&&l[0]==='')l=l.slice(1);if(!l.length){draw();return}screen.print(l);st.lastLine=strip(l.at(-1)??'').trim();st.blankEnd=l.at(-1)==='';draw()};
|
|
95
96
|
const flash=(text,ms=2500)=>{st.hint=text;st.hintUntil=Date.now()+ms;draw()};
|
|
96
97
|
const title=s=>{if(stdout.isTTY)stdout.write('\x1b]0;'+s.replace(/[\x00-\x1f]/g,'')+'\x07')};
|
|
97
98
|
const titleMode=()=>{const v=liveSettings?.()?.terminalTitle??settings.terminalTitle;return typeof v==='string'&&v?v:'auto'};
|
|
@@ -120,9 +121,9 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
|
|
|
120
121
|
attachImage:async p=>attachImage(p),
|
|
121
122
|
toggleTools:()=>toggleTools(),
|
|
122
123
|
setVim:on=>{editor.vim=Boolean(on);editor.vimMode='insert';draw()},
|
|
123
|
-
setTheme:name=>{themeName=resolveTheme(name,env);t=makeTheme(themeName,{color,syntax:syntaxName});tr.t=t;draw()},
|
|
124
|
+
setTheme:name=>{themeName=resolveTheme(name,env);t=makeTheme(themeName,{color,syntax:syntaxName,depth});tr.t=t;draw()},
|
|
124
125
|
get syntax(){return syntaxName},
|
|
125
|
-
setSyntax:name=>{syntaxName=name;t=makeTheme(themeName,{color,syntax:syntaxName});tr.t=t;draw()},
|
|
126
|
+
setSyntax:name=>{syntaxName=name;t=makeTheme(themeName,{color,syntax:syntaxName,depth});tr.t=t;draw()},
|
|
126
127
|
get raw(){return tr.raw},
|
|
127
128
|
setRaw:on=>{tr.raw=Boolean(on);draw()},
|
|
128
129
|
setTitle:text=>{st.title=text==null||text==='auto'||text==='off'?null:String(text).slice(0,200);if(text==='off'&&!st.title)title('');setTitle();draw()},
|
|
@@ -240,7 +241,7 @@ export async function runTui({session,settings={},cloud=null,flags={},first=null
|
|
|
240
241
|
}
|
|
241
242
|
if(result&&!result.intake){
|
|
242
243
|
if(result.state!=='completed'&&result.error&&!st.errorShown)print(t.warn(' '+result.error));
|
|
243
|
-
print(['',' '+summaryLine(result,{dim:t.dim,green:t.ok,yellow:t.
|
|
244
|
+
print(['',' '+summaryLine(result,{dim:t.dim,green:s=>t.ok(t.bold(s)),yellow:s=>t.important(t.bold(s)),red:s=>t.bad(t.bold(s)),bold:t.bold})+t.dim(' · '+elapsed(Date.now()-st.started))]);
|
|
244
245
|
try{const req=JSON.parse(await readFile(path.join(session.dir,'request.json'),'utf8'));if(req.contextWindow){st.window=req.contextWindow;if(st.context)st.context.window=req.contextWindow}}catch{}
|
|
245
246
|
const mode=curMode();
|
|
246
247
|
if(mode==='plan'&&result.state==='completed'&&!st.exiting&&!st.queue.length){
|
package/src/tui/markdown.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* and fenced code with syntax highlighting. render(text) returns styled lines wrapped to the width.
|
|
4
4
|
* A Stream renders text that is still arriving: complete blocks are final, the open tail is redrawn.
|
|
5
5
|
*/
|
|
6
|
-
import {wrap,width,pad} from './ansi.mjs';
|
|
6
|
+
import {wrap,width,pad,withRoles} from './ansi.mjs';
|
|
7
7
|
|
|
8
8
|
const KEYWORDS={
|
|
9
9
|
js:'await break case catch class const continue debugger default delete do else export extends finally for from function if import in instanceof let new of return static super switch this throw try typeof var void while with yield async true false null undefined',
|
|
@@ -46,18 +46,37 @@ export function highlightLine(line,lang,t,state={}){
|
|
|
46
46
|
return {text:out,state};
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
// Inline markdown: `code`, **bold**, *em* or _em_, ~~strike~~, [text](url).
|
|
49
|
+
// Inline markdown: `code`, **bold**, *em* or _em_, ~~strike~~, [text](url), bare URLs.
|
|
50
|
+
const URL_RE=/<?\bhttps?:\/\/[^\s<>]+/g;
|
|
51
|
+
const urlEnd=u=>{
|
|
52
|
+
// Trailing punctuation belongs to the sentence, and a closing parenthesis only to a URL that opened one.
|
|
53
|
+
let tail='';u=u.replace(/^</,'');
|
|
54
|
+
while(/[.,;:!?'"*>]$/.test(u)||(u.endsWith(')')&&(u.match(/\(/g)||[]).length<(u.match(/\)/g)||[]).length)){tail=u.slice(-1)+tail;u=u.slice(0,-1)}
|
|
55
|
+
return [u,tail.replace(/^>/,'')];
|
|
56
|
+
};
|
|
50
57
|
export function inline(text,t){
|
|
51
58
|
const parts=[];let s=String(text);
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
s=s.replace(
|
|
59
|
+
const hold=v=>{parts.push(v);return '\u0000'+(parts.length-1)+'\u0000'};
|
|
60
|
+
// Pull code spans and URLs out first so their contents are not styled (underscores in a URL are not emphasis).
|
|
61
|
+
s=s.replace(/`([^`]+)`/g,(_,c)=>hold(t.code(c)));
|
|
62
|
+
s=s.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,(_,label,url)=>hold(t.under(label)+t.dim(' (')+t.link(url)+t.dim(')')));
|
|
63
|
+
s=s.replace(URL_RE,m=>{const [u,tail]=urlEnd(m);return hold(t.link(u))+tail});
|
|
55
64
|
s=s.replace(/\*\*([^*]+)\*\*|__([^_]+)__/g,(_,a,b)=>t.bold(a||b));
|
|
56
65
|
s=s.replace(/(^|[^\w*])\*([^*\s][^*]*?)\*(?!\w)/g,(_,p,a)=>p+t.italic(a));
|
|
57
66
|
s=s.replace(/(^|[^\w])_([^_\s][^_]*?)_(?!\w)/g,(_,p,a)=>p+t.italic(a));
|
|
58
67
|
s=s.replace(/~~([^~]+)~~/g,(_,a)=>t.faint(a));
|
|
59
68
|
return s.replace(/\u0000(\d+)\u0000/g,(_,n)=>parts[Number(n)]);
|
|
60
69
|
}
|
|
70
|
+
/** "Note:", "Important:" lead-ins read as important (yellow); "Warning:", "Caution:" as warnings. */
|
|
71
|
+
const LEAD=/^(\*\*|__)?(note|notes|important|heads up|tip|nb|warning|caution)(\*\*|__)?:(\*\*|__)?\s*/i;
|
|
72
|
+
function lead(text,t){
|
|
73
|
+
const m=LEAD.exec(text);if(!m)return inline(text,t);
|
|
74
|
+
const label=text.slice(0,m[0].length).replace(/[*_]/g,'').trim();
|
|
75
|
+
const style=/^(warning|caution)/i.test(m[2])?t.warn:t.important;
|
|
76
|
+
return t.bold(style(label))+' '+inline(text.slice(m[0].length),t);
|
|
77
|
+
}
|
|
78
|
+
/** A line that only names a sources block ("Sources:", "**References**"). */
|
|
79
|
+
const SOURCES=/^\s*(\*\*|__)?(sources?|references?|citations?|links|further reading)(\*\*|__)?:?(\*\*|__)?\s*$/i;
|
|
61
80
|
|
|
62
81
|
function table(rows,t,cols){
|
|
63
82
|
const cells=rows.map(r=>r.replace(/^\s*\|/,'').replace(/\|\s*$/,'').split('|').map(c=>c.trim()));
|
|
@@ -72,32 +91,53 @@ function table(rows,t,cols){
|
|
|
72
91
|
}).flatMap(l=>l.split('\n'));
|
|
73
92
|
}
|
|
74
93
|
|
|
75
|
-
/**
|
|
76
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Renders a whole markdown text to lines no wider than cols. Prose (paragraphs, lists, quotes) wraps at maxWidth
|
|
96
|
+
* at most so long answers stay readable on wide terminals; code and tables may use the full width.
|
|
97
|
+
* Blocks are separated by one blank line: before headings and source lists, around lists, code and tables, and
|
|
98
|
+
* between paragraphs. Models often end a paragraph with a single newline, so two consecutive lines are separate
|
|
99
|
+
* paragraphs when either is a full paragraph (longer than a hard-wrapped line); short lines (an address, a poem)
|
|
100
|
+
* stay together.
|
|
101
|
+
*/
|
|
102
|
+
export const PROSE_MAX=100;
|
|
103
|
+
export function render(text,{t,cols=80,box,maxWidth=PROSE_MAX}={}){
|
|
104
|
+
t=withRoles(t);
|
|
77
105
|
const out=[];const lines=String(text??'').replace(/\r\n?/g,'\n').split('\n');
|
|
78
|
-
const
|
|
106
|
+
const pcols=Math.max(4,Math.min(cols,maxWidth||cols));
|
|
107
|
+
const push=(s,indent='',first=indent)=>{const w=wrap(s,pcols-width(first));w.forEach((x,i)=>out.push((i?indent:first)+x))};
|
|
108
|
+
// prev: the kind of the last block ('head', 'label', 'para', 'list', 'code', 'table', 'quote', 'rule'); long: it was a full paragraph.
|
|
109
|
+
let prev=null,long=false;
|
|
110
|
+
const gap=()=>{if(out.length&&out.at(-1)!=='')out.push('')};
|
|
111
|
+
const LONG=100; // source characters: hard-wrapped text stays under it
|
|
79
112
|
for(let i=0;i<lines.length;i++){
|
|
80
113
|
const line=lines[i];let m;
|
|
81
114
|
if((m=/^(\s*)(```+|~~~+)\s*([\w+#.-]*)/.exec(line))){
|
|
82
115
|
const fence=m[2],lang=m[3];const code=[];i++;
|
|
83
116
|
while(i<lines.length&&!lines[i].trimStart().startsWith(fence))code.push(lines[i++]);
|
|
117
|
+
gap();
|
|
84
118
|
const bar=t.dim(box?.bar||'▌')+' ';
|
|
85
119
|
if(lang)out.push(t.dim(box?.bar||'▌')+' '+t.faint(lang));
|
|
86
120
|
let state={};
|
|
87
121
|
for(const c of code){const h=highlightLine(c.replace(/\t/g,' '),lang,t,state);state=h.state;for(const w of wrap(h.text,cols-2))out.push(bar+w)}
|
|
88
|
-
continue;
|
|
122
|
+
prev='code';continue;
|
|
89
123
|
}
|
|
90
|
-
if(!line.trim()){if(
|
|
91
|
-
|
|
92
|
-
if(
|
|
93
|
-
if(
|
|
94
|
-
if((
|
|
95
|
-
if(
|
|
96
|
-
if((m=/^(\s*)
|
|
97
|
-
|
|
98
|
-
push(inline(
|
|
124
|
+
if(!line.trim()){gap();if(prev!=='head'&&prev!=='label')prev='blank';continue}
|
|
125
|
+
const after=k=>{if(prev&&prev!=='blank'&&prev!==k&&prev!=='head'&&prev!=='label')gap()};
|
|
126
|
+
if((m=/^(#{1,6})\s+(.*)$/.exec(line))){const txt=inline(m[2].replace(/\s*#+\s*$/,''),t);gap();push(m[1].length<=2?t.head(txt):t.head2(txt));prev='head';continue}
|
|
127
|
+
if(SOURCES.test(line)){gap();push(t.head2(line.replace(/[*_]/g,'').trim()));prev='label';continue}
|
|
128
|
+
if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)){gap();out.push(t.dim((box?.h||'─').repeat(Math.min(pcols,40))));prev='rule';continue}
|
|
129
|
+
if(/^\s*\|.*\|\s*$/.test(line)){const rows=[];while(i<lines.length&&/^\s*\|.*\|\s*$/.test(lines[i]))rows.push(lines[i++]);i--;if(prev!=='head'&&prev!=='label')gap();for(const r of table(rows,t,cols))out.push(r);prev='table';continue}
|
|
130
|
+
if((m=/^(\s*)>\s?(.*)$/.exec(line))){after('quote');push(t.quote(lead(m[2],t)),t.quote('│ '),t.quote('│ '));prev='quote';continue}
|
|
131
|
+
// Lists: indented under the text, with a hanging indent so wrapped lines line up after the marker.
|
|
132
|
+
if((m=/^(\s*)([-*+])\s+\[([ xX])\]\s+(.*)$/.exec(line))){after('list');const ind=' '+' '.repeat(Math.min(8,m[1].length));const done=m[3]!==' ';push(done?t.faint(inline(m[4],t)):inline(m[4],t),ind+' ',ind+(done?t.ok('[x] '):t.dim('[ ] ')));prev='list';continue}
|
|
133
|
+
if((m=/^(\s*)([-*+])\s+(.*)$/.exec(line))){after('list');const ind=' '+' '.repeat(Math.min(8,m[1].length));push(lead(m[3],t),ind+' ',ind+t.bullet((box?.dot||'•')==='*'?'- ':'• '));prev='list';continue}
|
|
134
|
+
if((m=/^(\s*)(\d+)[.)]\s+(.*)$/.exec(line))){after('list');const ind=' '+' '.repeat(Math.min(8,m[1].length)),num=m[2]+'. ';push(lead(m[3],t),ind+' '.repeat(num.length),ind+t.bold(num));prev='list';continue}
|
|
135
|
+
const isLong=width(line)>LONG;
|
|
136
|
+
if(prev==='para'?(long||isLong):prev&&prev!=='blank'&&prev!=='head'&&prev!=='label')gap();
|
|
137
|
+
push(lead(line,t));prev='para';long=isLong;
|
|
99
138
|
}
|
|
100
139
|
while(out.length&&out.at(-1)==='')out.pop();
|
|
140
|
+
while(out.length&&out[0]==='')out.shift();
|
|
101
141
|
return out;
|
|
102
142
|
}
|
|
103
143
|
|
package/src/tui/transcript.mjs
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Harness events -> transcript lines for the TUI. Tool calls are one row each (read, edit, run, search ...);
|
|
3
3
|
* their output is collapsed to a summary unless expanded (Ctrl-O). Pure, so it is tested without a terminal.
|
|
4
4
|
*/
|
|
5
|
-
import {render as markdown} from './markdown.mjs';
|
|
6
|
-
import {wrap,truncate,width} from './ansi.mjs';
|
|
5
|
+
import {render as markdown,PROSE_MAX} from './markdown.mjs';
|
|
6
|
+
import {wrap,truncate,width,withRoles} from './ansi.mjs';
|
|
7
7
|
import {prose,renderEvent} from '../render.mjs';
|
|
8
8
|
|
|
9
9
|
/** Tool names from the harness -> the verb shown on the row. */
|
|
@@ -33,31 +33,47 @@ export const legacy=t=>({dim:t.dim,bold:t.bold,red:t.bad,green:t.ok,yellow:t.war
|
|
|
33
33
|
export const finishless=s=>String(s||'').replace(/```[a-z]*\s*\n\s*echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*\n```/g,'').replace(/^\s*echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT\s*$/gm,'');
|
|
34
34
|
export class Transcript{
|
|
35
35
|
constructor({t,box,cols=80,expanded=false,verbose=false,raw=false}={}){this.t=t;this.box=box;this.cols=cols;this.expanded=expanded;this.verbose=verbose;this.raw=raw;this.collapsed=[];this.lastAssistant=''}
|
|
36
|
+
/** The theme; set by the app when the theme changes. Older theme objects get the semantic roles filled in. */
|
|
37
|
+
get t(){return this._t}
|
|
38
|
+
set t(v){this._t=withRoles(v)}
|
|
36
39
|
dot(style){return style(this.box?.dot||'●')+' '}
|
|
37
40
|
elbow(){return this.t.dim(this.box?.ascii?' L ':' ⎿ ')}
|
|
38
41
|
/** The user's message as it goes to the agent. */
|
|
39
42
|
user(text,{images=0,shell=false}={}){
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
+
// Bold cyan with a marker, then a blank line, so what was asked stands apart from the work and the answer below it.
|
|
44
|
+
const t=this.t,style=shell?t.borderShell:t.user,mark=shell?t.borderShell('!'):t.user(this.box?.arrow||'›');
|
|
45
|
+
const lines=this.raw?String(text).split('\n'):wrap(String(text),Math.min(this.cols,PROSE_MAX+2)-4);
|
|
46
|
+
return ['',...lines.map((l,i)=>(i?' ':mark+' ')+style(l)),...(images?[t.dim(' + '+images+' image'+(images===1?'':'s'))]:[]),''];
|
|
43
47
|
}
|
|
44
48
|
assistant(content){
|
|
45
49
|
const p=prose(finishless(content));if(!p||p===this.lastAssistant)return [];
|
|
46
|
-
this.lastAssistant=p;
|
|
50
|
+
this.lastAssistant=p;this.shown=[...(this.shown||[]),p].slice(-8);
|
|
47
51
|
// Raw scrollback: the reply exactly as written (markdown source, no wrapping or color), for copying.
|
|
48
52
|
if(this.raw)return ['',...p.split('\n')];
|
|
49
53
|
const md=markdown(p,{t:this.t,cols:this.cols-2,box:this.box});
|
|
50
|
-
|
|
54
|
+
const a=this.t.assistant;
|
|
55
|
+
return ['',...md.map((l,i)=>(i?(l?' ':''):this.dot(a))+(l?a(l):''))];
|
|
56
|
+
}
|
|
57
|
+
/** The final answer. When the agent already wrote it as a reply above, it is not shown again; only what the harness
|
|
58
|
+
added to it (a verification note, a source list) is. */
|
|
59
|
+
answer(content){
|
|
60
|
+
const p=prose(finishless(content));if(!p)return [];
|
|
61
|
+
const norm=x=>x.replace(/\s+/g,' ').trim();
|
|
62
|
+
for(const seen of this.shown||[]){
|
|
63
|
+
if(norm(seen)===norm(p))return [];
|
|
64
|
+
if(seen.length>40&&p.includes(seen)){const rest=p.replace(seen,'').trim();return rest?this.assistant(rest):[]}
|
|
65
|
+
}
|
|
66
|
+
return this.assistant(p);
|
|
51
67
|
}
|
|
52
68
|
tool(name,target){
|
|
53
69
|
const t=this.t,v=verb(name);
|
|
54
70
|
const tgt=target?' '+truncate(String(target),Math.max(10,this.cols-width(v)-6)):'';
|
|
55
|
-
return [this.dot(t.tool)+t.
|
|
71
|
+
return [this.dot(t.tool)+t.toolHead(v)+t.tool(tgt)];
|
|
56
72
|
}
|
|
57
73
|
command(cmd){
|
|
58
74
|
const t=this.t,first=String(cmd||'').split('\n');
|
|
59
75
|
const head=truncate(first[0],this.cols-8)+(first.length>1?t.dim(' (+'+(first.length-1)+' lines)'):'');
|
|
60
|
-
return [this.dot(t.tool)+t.
|
|
76
|
+
return [this.dot(t.tool)+t.toolHead('Run ')+t.tool(head)];
|
|
61
77
|
}
|
|
62
78
|
output(e){
|
|
63
79
|
const t=this.t,text=String(e.output||'').replace(/\s+$/,'');const rows=text?text.split('\n'):[];const ok=e.returncode===0;
|
|
@@ -82,19 +98,19 @@ export class Transcript{
|
|
|
82
98
|
}
|
|
83
99
|
todos(items){
|
|
84
100
|
const t=this.t;if(!Array.isArray(items)||!items.length)return [];
|
|
85
|
-
return [this.dot(t.tool)+t.
|
|
101
|
+
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))})];
|
|
86
102
|
}
|
|
87
103
|
/** Lines for one event; [] for events that stay quiet. */
|
|
88
104
|
lines(e){
|
|
89
105
|
const t=this.t;
|
|
90
106
|
switch(e?.type){
|
|
91
107
|
case 'assistant':return this.assistant(e.content);
|
|
92
|
-
case 'answer':return e.content?this.
|
|
108
|
+
case 'answer':return e.content?this.answer(String(e.content)):[];
|
|
93
109
|
case 'tool':return e.name==='todo'?[]:this.tool(e.name,e.target);
|
|
94
110
|
case 'command':return this.command(e.command);
|
|
95
111
|
case 'output':return this.output(e);
|
|
96
112
|
case 'todos':return this.todos(e.items);
|
|
97
|
-
case 'verification':{const ok=e.verdict?.status==='passed'||(e.verdict==null&&e.returncode===0);return [this.dot(ok?t.ok:t.bad)+t.
|
|
113
|
+
case 'verification':{const ok=e.verdict?.status==='passed'||(e.verdict==null&&e.returncode===0);return [this.dot(ok?t.ok:t.bad)+(ok?t.ok('Check passed'):t.bad(t.bold('Check '+(e.verdict?.status||'failed'))))+t.tool(' '+truncate(String(e.label||''),this.cols-20))]}
|
|
98
114
|
case 'edit_guard':return [this.dot(t.warn)+t.warn('Blocked edit ')+truncate(String(e.path||''),60)+t.dim(': '+truncate(String(e.content||''),this.cols-30))];
|
|
99
115
|
case 'steering':return [this.elbow()+t.accent('Steering received')];
|
|
100
116
|
case 'mode':return e.content?[this.elbow()+t.dim(String(e.content))]:[];
|
package/worker/browser_tool.py
CHANGED
|
@@ -63,6 +63,13 @@ def hydrated(page):
|
|
|
63
63
|
try:return bool(page.evaluate(HYDRATION)['interactive'])
|
|
64
64
|
except Exception:return None
|
|
65
65
|
|
|
66
|
+
def actual(page,checked,local):
|
|
67
|
+
"""The address the browser ended on, so a check that navigated (a goto step) is attributed to the page it checked, not to
|
|
68
|
+
the address it started from (CLI 0.3.4). Cloud checks keep the preview-host description."""
|
|
69
|
+
try:url=page.url if page else ''
|
|
70
|
+
except Exception:url=''
|
|
71
|
+
return url if local and url and url!='about:blank' else checked
|
|
72
|
+
|
|
66
73
|
def scenario(args,output):
|
|
67
74
|
local=on_laptop()
|
|
68
75
|
if not (local and os.getenv('PLAYWRIGHT_BROWSERS_PATH')):os.environ['PLAYWRIGHT_BROWSERS_PATH']=str(output.parent.parent/'pw-browsers')
|
|
@@ -106,7 +113,8 @@ def scenario(args,output):
|
|
|
106
113
|
page.screenshot(path=str(output),full_page=False,timeout=10000)
|
|
107
114
|
interactive=hydrated(page)
|
|
108
115
|
if interactive is False:errors.insert(0,NOT_INTERACTIVE)
|
|
109
|
-
|
|
116
|
+
checked=actual(page,checked,local)
|
|
117
|
+
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}}
|
|
110
118
|
except Exception as exc:
|
|
111
119
|
if timeline and timeline[-1]['state']=='started':timeline[-1]['state']='failed'
|
|
112
120
|
captured=False
|
|
@@ -115,5 +123,7 @@ def scenario(args,output):
|
|
|
115
123
|
except Exception:pass
|
|
116
124
|
interactive=hydrated(page) if page else None
|
|
117
125
|
reason=(NOT_INTERACTIVE+' Step error: ' if interactive is False else '')+str(exc)[:2000]
|
|
118
|
-
|
|
126
|
+
checked=actual(page,checked,local)
|
|
127
|
+
return {'success':False,'error':reason,'interactive':interactive,'checkedAt':checked,**({'requestedUrl':url} if checked!=url and local else {}),
|
|
128
|
+
'timeline':timeline,'pageErrors':errors[:20],'consoleErrors':console[:20],'networkFailures':network[:30],'screenshot':output.name if captured else None,'viewport':{'width':width,'height':height}}
|
|
119
129
|
finally:browser.close()
|