agent-mp 0.4.1 → 0.4.3

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.
@@ -716,12 +716,10 @@ function cmdHelp(fi) {
716
716
  { key: '/setup explorer', value: 'Reconfigure explorer only' },
717
717
  { key: '/config-multi', value: 'Reconfigure all agents at once' },
718
718
  { key: '/status', value: 'Show current configuration and tasks' },
719
- { key: '/explorer <task>', value: 'Run explorer agent on a task/question' },
720
719
  { key: '/run <task>', value: 'Full cycle: orchestrator → implementor → reviewer' },
721
720
  { key: '/run orch <task>', value: 'Run only orchestrator' },
722
721
  { key: '/run impl <id>', value: 'Run only implementor' },
723
722
  { key: '/run rev <id>', value: 'Run only reviewer' },
724
- { key: '/run explorer <task>', value: 'Run only explorer' },
725
723
  { key: '/models', value: 'List models for all installed CLIs' },
726
724
  { key: '/models <cli>', value: 'List models for a specific CLI' },
727
725
  { key: '/login', value: 'Login (Qwen OAuth or CLI auth)' },
@@ -1037,12 +1035,6 @@ export async function runRepl(resumeSession) {
1037
1035
  const progress = await readJson(path.join(taskDir, 'progress.json'));
1038
1036
  await engine.runReviewer(taskId, plan, progress);
1039
1037
  }
1040
- else if (args[0] === 'explorer' || args[0] === 'exp') {
1041
- const task = args.slice(1).join(' ') || undefined;
1042
- const engine = new AgentEngine(config, dir, gCoordinatorCmd, rl, fi, handleCmd);
1043
- const result = await engine.runExplorer(task);
1044
- fi.println(result);
1045
- }
1046
1038
  else {
1047
1039
  const task = args.join(' ');
1048
1040
  const engine = new AgentEngine(config, dir, gCoordinatorCmd, rl, fi, handleCmd);
@@ -1050,20 +1042,6 @@ export async function runRepl(resumeSession) {
1050
1042
  }
1051
1043
  break;
1052
1044
  }
1053
- case 'explorer': {
1054
- const task = args.join(' ') || undefined;
1055
- try {
1056
- const dir = process.cwd();
1057
- const config = await loadProjectConfig(dir);
1058
- const engine = new AgentEngine(config, dir, gCoordinatorCmd, rl, fi, handleCmd);
1059
- const result = await engine.runExplorer(task);
1060
- fi.println(result);
1061
- }
1062
- catch (err) {
1063
- fi.println(chalk.red(` Explorer error: ${err.message}`));
1064
- }
1065
- break;
1066
- }
1067
1045
  case 'models':
1068
1046
  case 'model':
1069
1047
  await withRl((rl) => cmdModels(args[0], fi, rl));
@@ -1225,12 +1203,6 @@ export async function runRole(role, arg, model) {
1225
1203
  await engine.runReviewer(arg, plan, progress);
1226
1204
  break;
1227
1205
  }
1228
- case 'explorer':
1229
- case 'exp': {
1230
- const result = await engine.runExplorer(arg || undefined);
1231
- console.log(result);
1232
- break;
1233
- }
1234
1206
  case 'coordinator':
1235
1207
  case 'coord': {
1236
1208
  console.log(chalk.yellow(' Coordinator mode requires interactive REPL.'));
@@ -1238,7 +1210,7 @@ export async function runRole(role, arg, model) {
1238
1210
  process.exit(1);
1239
1211
  }
1240
1212
  default:
1241
- console.log(chalk.red(` Unknown role: ${role}. Use: orchestrator, implementor, reviewer, explorer`));
1213
+ console.log(chalk.red(` Unknown role: ${role}. Use: orchestrator, implementor, reviewer`));
1242
1214
  process.exit(1);
1243
1215
  }
1244
1216
  }
@@ -16,8 +16,10 @@ export declare class AgentEngine {
16
16
  private totalTokens;
17
17
  private phaseTokens;
18
18
  constructor(config: AgentConfig, projectDir: string, coordinatorCmd?: string, rl?: readline.Interface, fi?: FixedInput, slashHandler?: SlashHandler);
19
- /** Start an animated spinner on the status row. Returns a stop function. */
19
+ /** Start the activity box for a subagent call. Returns { stop, push }. */
20
20
  private _startSpinner;
21
+ /** Extract readable text lines from a qwen/CLI streaming chunk. */
22
+ private _parseChunk;
21
23
  /**
22
24
  * FASE 0 — Clarificacion con el programador.
23
25
  * El coordinador (CLI activo, ej: Qwen) conversa con el usuario
@@ -219,19 +219,54 @@ export class AgentEngine {
219
219
  this.fi = fi;
220
220
  this.slashHandler = slashHandler;
221
221
  }
222
- /** Start an animated spinner on the status row. Returns a stop function. */
222
+ /** Start the activity box for a subagent call. Returns { stop, push }. */
223
223
  _startSpinner(label) {
224
+ const noop = { stop() { }, push(_) { } };
224
225
  if (!this.fi)
225
- return () => { };
226
+ return noop;
226
227
  const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
227
228
  let i = 0;
228
229
  const t0 = Date.now();
229
230
  const fi = this.fi;
231
+ fi.startActivity(`${frames[0]} ${label} 0s`);
230
232
  const iv = setInterval(() => {
231
233
  const s = Math.floor((Date.now() - t0) / 1000);
232
- fi.setStatus(` ${frames[i++ % frames.length]} ${label} ${s}s`);
234
+ fi.updateActivityHeader(`${frames[i++ % frames.length]} ${label} ${s}s`);
233
235
  }, 100);
234
- return () => { clearInterval(iv); fi.setStatus(null); };
236
+ return {
237
+ stop() { clearInterval(iv); fi.stopActivity(); },
238
+ push(line) { fi.pushActivity(line); },
239
+ };
240
+ }
241
+ /** Extract readable text lines from a qwen/CLI streaming chunk. */
242
+ _parseChunk(chunk) {
243
+ const out = [];
244
+ for (const raw of chunk.split('\n')) {
245
+ const line = raw.trim();
246
+ if (!line)
247
+ continue;
248
+ // Try to extract text from JSON streaming events
249
+ if (line.startsWith('{')) {
250
+ try {
251
+ const obj = JSON.parse(line);
252
+ const text = obj.result ||
253
+ obj.data?.content ||
254
+ obj.message?.content?.[0]?.text ||
255
+ obj.choices?.[0]?.delta?.content ||
256
+ obj.choices?.[0]?.message?.content ||
257
+ '';
258
+ if (text.trim())
259
+ out.push(text.trim());
260
+ continue;
261
+ }
262
+ catch { /* not JSON — fall through */ }
263
+ }
264
+ // Skip lines that look like SSE metadata
265
+ if (line.startsWith('data:') || line.startsWith('event:') || line === '[DONE]')
266
+ continue;
267
+ out.push(line);
268
+ }
269
+ return out;
235
270
  }
236
271
  /**
237
272
  * FASE 0 — Clarificacion con el programador.
@@ -268,14 +303,14 @@ INSTRUCCIONES:
268
303
  // Use Qwen API directly — avoids the qwen CLI's own OAuth flow
269
304
  // which causes mid-session auth popups and breaks display.
270
305
  const model = this.coordinatorCmd.match(/(?:-m|--model)\s+(\S+)/)?.[1] || 'coder-model';
271
- const stopSpin = this._startSpinner(`coordinador ${model}`);
306
+ const sp = this._startSpinner(`coordinador ${model}`);
272
307
  try {
273
- const result = await callQwenAPI(prompt, model);
274
- stopSpin();
308
+ const result = await callQwenAPI(prompt, model, (c) => this._parseChunk(c).forEach(l => sp.push(l)));
309
+ sp.stop();
275
310
  return result;
276
311
  }
277
312
  catch (err) {
278
- stopSpin();
313
+ sp.stop();
279
314
  if (err.message?.startsWith('QWEN_AUTH_EXPIRED')) {
280
315
  console.log(chalk.red('\n ✗ Sesión Qwen expirada.'));
281
316
  console.log(chalk.yellow(' Ejecutá: /login para re-autenticarte.\n'));
@@ -287,9 +322,9 @@ INSTRUCCIONES:
287
322
  }
288
323
  }
289
324
  else {
290
- const stopSpin = this._startSpinner(`coordinador`);
325
+ const sp = this._startSpinner(`coordinador`);
291
326
  res = await runCli(this.coordinatorCmd, prompt, 600000, envOverride);
292
- stopSpin();
327
+ sp.stop();
293
328
  }
294
329
  // Extract readable text — search for JSON array even if there's prefix text
295
330
  let responseText = res.output.trim();
@@ -386,19 +421,19 @@ INSTRUCCIONES:
386
421
  const rolePrompt = this.buildRolePrompt(roleName, prompt);
387
422
  /** Try a cmd, and if it fails, auto-detect flags from --help and retry */
388
423
  const tryWithAutoRepair = async (cliName, model, currentCmd) => {
389
- const stopSpin = this._startSpinner(`${cliName} ${model}`);
424
+ const sp = this._startSpinner(`${cliName} ${model}`);
390
425
  try {
391
426
  const result = await runCli(currentCmd, rolePrompt);
392
427
  if (result.exitCode !== 0) {
393
- stopSpin();
428
+ sp.stop();
394
429
  const detail = result.output.trim().slice(0, 500);
395
430
  throw new Error(`${cliName} exited with code ${result.exitCode}${detail ? `\n${detail}` : ''}`);
396
431
  }
397
- stopSpin();
432
+ sp.stop();
398
433
  return result.output;
399
434
  }
400
435
  catch (err) {
401
- stopSpin();
436
+ sp.stop();
402
437
  log.warn(`${cliName} failed, detecting flags from --help: ${err.message}`);
403
438
  const detected = detectCliFlags(cliName);
404
439
  if (Object.keys(detected).length === 0) {
@@ -450,10 +485,10 @@ INSTRUCCIONES:
450
485
  // Config file might not exist yet
451
486
  }
452
487
  // Retry with new command
453
- const stopSpin2 = this._startSpinner(`${cliName} ${model} (retry)`);
488
+ const sp2 = this._startSpinner(`${cliName} ${model} (retry)`);
454
489
  try {
455
490
  const result = await runCli(newCmd, rolePrompt);
456
- stopSpin2();
491
+ sp2.stop();
457
492
  if (result.exitCode !== 0) {
458
493
  const detail = result.output.trim().slice(0, 500);
459
494
  throw new Error(`${cliName} (repaired) exited with code ${result.exitCode}${detail ? `\n${detail}` : ''}`);
@@ -462,7 +497,7 @@ INSTRUCCIONES:
462
497
  return result.output;
463
498
  }
464
499
  catch (retryErr) {
465
- stopSpin2();
500
+ sp2.stop();
466
501
  log.warn(`Repaired ${cliName} also failed: ${retryErr.message}`);
467
502
  return null;
468
503
  }
@@ -479,15 +514,15 @@ INSTRUCCIONES:
479
514
  log.warn(`${cliName} has no credentials — run: ${cliName} --login`);
480
515
  return null;
481
516
  }
482
- const stopSpin = this._startSpinner(`${cliName} ${model}`);
517
+ const sp = this._startSpinner(`${cliName} ${model}`);
483
518
  try {
484
519
  log.info(`${cliName}: calling Qwen API with own credentials (${model})`);
485
- const result = await callQwenAPIFromCreds(rolePrompt, model, credsPath);
486
- stopSpin();
520
+ const result = await callQwenAPIFromCreds(rolePrompt, model, credsPath, (c) => this._parseChunk(c).forEach(l => sp.push(l)));
521
+ sp.stop();
487
522
  return result;
488
523
  }
489
524
  catch (err) {
490
- stopSpin();
525
+ sp.stop();
491
526
  if (err.message?.startsWith('QWEN_AUTH_EXPIRED')) {
492
527
  console.log(chalk.red(`\n ✗ Sesión expirada para ${cliName}.`));
493
528
  console.log(chalk.yellow(` Ejecutá: ${cliName} --login\n`));
@@ -953,13 +988,13 @@ REGLAS:
953
988
  - Escribe UNICAMENTE los archivos indicados: ${archPath} y ${contextDir}/<servicio>/architecture.md
954
989
  - NO crees archivos adicionales ni con otros nombres en ningun directorio`);
955
990
  let result;
956
- const stopSpin = this._startSpinner(`agent-explorer ${role.model}`);
991
+ const sp = this._startSpinner(`agent-explorer ${role.model}`);
957
992
  try {
958
- result = await callQwenAPI(prompt, role.model);
959
- stopSpin();
993
+ result = await callQwenAPI(prompt, role.model, (c) => this._parseChunk(c).forEach(l => sp.push(l)));
994
+ sp.stop();
960
995
  }
961
996
  catch (err) {
962
- stopSpin();
997
+ sp.stop();
963
998
  if (err.message?.startsWith('QWEN_AUTH_EXPIRED')) {
964
999
  console.log(chalk.red('\n ✗ Sesión Qwen expirada.'));
965
1000
  console.log(chalk.yellow(' Ejecutá: agent-mp --login (o agent-explorer --login)\n'));
@@ -6,29 +6,36 @@ export declare class FixedInput {
6
6
  private _pasting;
7
7
  private _pasteAccum;
8
8
  private _drawPending;
9
- private _statusText;
9
+ private _activityHeader;
10
+ private _activityLines;
10
11
  private get rows();
11
12
  get cols(): number;
13
+ private get _reservedRows();
12
14
  private get scrollBottom();
13
15
  private _contentRows;
14
16
  setup(): void;
15
17
  teardown(): void;
16
18
  redrawBox(): void;
17
- /** Show or clear the status / spinner line above the input box. */
18
- setStatus(text: string | null): void;
19
19
  suspend(): () => void;
20
+ /** Enter activity mode: show the 5-line log box instead of the input box. */
21
+ startActivity(header: string): void;
22
+ /** Update the header line (spinner frame + elapsed time) without clearing lines. */
23
+ updateActivityHeader(header: string): void;
24
+ /**
25
+ * Append a line to the activity log (keeps last ACTIVITY_LINES lines).
26
+ * Strips ANSI codes and skips blank or pure-JSON lines.
27
+ */
28
+ pushActivity(rawLine: string): void;
29
+ /** Leave activity mode and restore the normal input box. */
30
+ stopActivity(): void;
20
31
  readLine(): Promise<string>;
21
32
  println(text: string): void;
22
33
  printSeparator(): void;
23
- /** Repaint the status row (between scroll region and input box). */
24
- private _drawStatusRow;
25
- /** Debounced draw: coalesces rapid calls (e.g. during paste) into a single repaint. */
26
34
  private _scheduleDraw;
27
- /** Set DECSTBM once — only called in setup() and on resize, never during typing. */
28
35
  private _setScrollRegion;
29
- /** Blank every row in the reserved area. */
30
36
  private _clearReserved;
31
37
  private _drawBox;
32
- /** Split text into visual lines: split on \n, then wrap each segment. */
38
+ private _drawActivityBox;
39
+ private _drawInputBox;
33
40
  private _wrapText;
34
41
  }
package/dist/ui/input.js CHANGED
@@ -5,31 +5,35 @@ const B = (s) => chalk.rgb(30, 110, 185)(s); // blue — prompt arrow
5
5
  const PREFIX = T('│') + B(' > ');
6
6
  const PREFIX_CONT = T('│') + B(' '); // continuation lines
7
7
  const PREFIX_COLS = 4; // visual width of "│ > " and "│ "
8
- // Maximum content rows the box can grow to (Shift+Enter / word-wrap).
9
- // The reserved area at the bottom is MAX_CONTENT_ROWS + 2 (borders) + 1 (status row).
8
+ // Maximum content rows the input box can grow to (Shift+Enter / word-wrap).
10
9
  const MAX_CONTENT_ROWS = 4;
11
- const RESERVED_ROWS = MAX_CONTENT_ROWS + 3; // 7 = 4 content + 2 borders + 1 status
10
+ const ACTIVITY_LINES = 5;
11
+ // Reserved rows at the bottom:
12
+ // Idle: 7 = 1 status row + up to 4 content + 2 borders
13
+ // Active: 10 = 7 (activity box) + 3 (input box: 1 content + 2 borders)
14
+ // The scroll region is updated whenever activity mode toggles.
15
+ const IDLE_RESERVED = MAX_CONTENT_ROWS + 3; // 7
16
+ const ACTIVE_RESERVED = ACTIVITY_LINES + 2 + 3; // 10 = activity(7) + input(3)
12
17
  // ─── FixedInput ──────────────────────────────────────────────────────────────
13
- // Keeps an input box pinned to the physical bottom of the terminal.
14
- // The box starts as 3 rows (border + 1 content + border) and grows up to
15
- // RESERVED_ROWS when the user types multiline text (Shift+Enter) or the
16
- // text wraps. The scroll region is set ONCE at setup (and on resize) to
17
- // [1 .. rows-RESERVED_ROWS] so DECSTBM never fires during normal typing.
18
18
  export class FixedInput {
19
19
  buf = '';
20
20
  history = [];
21
21
  histIdx = -1;
22
22
  origLog;
23
- _pasting = false; // true while inside bracketed paste sequence
24
- _pasteAccum = ''; // accumulates paste content between \x1b[200~ and \x1b[201~
25
- _drawPending = false; // debounce flag
26
- _statusText = ''; // spinner / status line above the input box
23
+ _pasting = false;
24
+ _pasteAccum = '';
25
+ _drawPending = false;
26
+ // ── Activity box state (null = input mode, string = activity mode) ──────────
27
+ _activityHeader = null;
28
+ _activityLines = [];
27
29
  get rows() { return process.stdout.rows || 24; }
28
30
  get cols() { return process.stdout.columns || 80; }
29
- // The scroll region always ends here everything below is reserved for the box.
30
- get scrollBottom() { return this.rows - RESERVED_ROWS; }
31
- // How many content rows the current buffer needs (1 .. MAX_CONTENT_ROWS).
31
+ get _reservedRows() { return this._activityHeader !== null ? ACTIVE_RESERVED : IDLE_RESERVED; }
32
+ get scrollBottom() { return this.rows - this._reservedRows; }
32
33
  _contentRows() {
34
+ // During activity mode only 1 content row fits below the activity box
35
+ if (this._activityHeader !== null)
36
+ return 1;
33
37
  const w = this.cols - PREFIX_COLS - 2;
34
38
  if (w <= 0)
35
39
  return 1;
@@ -51,7 +55,7 @@ export class FixedInput {
51
55
  process.stdout.write(`\x1b[${this.scrollBottom};1H`);
52
56
  this._clearReserved();
53
57
  this._drawBox();
54
- process.stdout.write('\x1b[?2004h'); // enable bracketed paste mode
58
+ process.stdout.write('\x1b[?2004h');
55
59
  process.stdout.on('resize', () => {
56
60
  this._setScrollRegion();
57
61
  this._clearReserved();
@@ -59,21 +63,18 @@ export class FixedInput {
59
63
  });
60
64
  }
61
65
  teardown() {
66
+ this._activityHeader = null;
67
+ this._activityLines = [];
62
68
  console.log = this.origLog;
63
- process.stdout.write('\x1b[?2004l'); // disable bracketed paste mode
64
- process.stdout.write('\x1b[r'); // reset scroll region
65
- process.stdout.write('\x1b[?25h'); // show cursor
69
+ process.stdout.write('\x1b[?2004l');
70
+ process.stdout.write('\x1b[r');
71
+ process.stdout.write('\x1b[?25h');
66
72
  process.stdout.write(`\x1b[${this.rows};1H\n`);
67
73
  }
68
74
  redrawBox() { this._drawBox(); }
69
- /** Show or clear the status / spinner line above the input box. */
70
- setStatus(text) {
71
- this._statusText = text || '';
72
- this._drawBox();
73
- }
74
75
  suspend() {
75
76
  console.log = this.origLog;
76
- process.stdout.write('\x1b[?2004l'); // disable bracketed paste while suspended
77
+ process.stdout.write('\x1b[?2004l');
77
78
  process.stdout.write('\x1b[r');
78
79
  this._clearReserved();
79
80
  process.stdout.write(`\x1b[${this.scrollBottom};1H`);
@@ -85,9 +86,48 @@ export class FixedInput {
85
86
  this._setScrollRegion();
86
87
  this._clearReserved();
87
88
  this._drawBox();
88
- process.stdout.write('\x1b[?2004h'); // re-enable bracketed paste mode
89
+ process.stdout.write('\x1b[?2004h');
89
90
  };
90
91
  }
92
+ // ── Activity box API ───────────────────────────────────────────────────────
93
+ /** Enter activity mode: show the 5-line log box instead of the input box. */
94
+ startActivity(header) {
95
+ this._activityHeader = header;
96
+ this._activityLines = [];
97
+ this._setScrollRegion();
98
+ this._drawBox();
99
+ }
100
+ /** Update the header line (spinner frame + elapsed time) without clearing lines. */
101
+ updateActivityHeader(header) {
102
+ this._activityHeader = header;
103
+ this._drawBox();
104
+ }
105
+ /**
106
+ * Append a line to the activity log (keeps last ACTIVITY_LINES lines).
107
+ * Strips ANSI codes and skips blank or pure-JSON lines.
108
+ */
109
+ pushActivity(rawLine) {
110
+ if (this._activityHeader === null)
111
+ return;
112
+ // Strip ANSI escape sequences
113
+ const clean = rawLine
114
+ .replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')
115
+ .replace(/[^\x20-\x7e\u00a0-\uffff]/g, '')
116
+ .trim();
117
+ if (!clean)
118
+ return;
119
+ this._activityLines.push(clean);
120
+ if (this._activityLines.length > ACTIVITY_LINES)
121
+ this._activityLines.shift();
122
+ this._scheduleDraw();
123
+ }
124
+ /** Leave activity mode and restore the normal input box. */
125
+ stopActivity() {
126
+ this._activityHeader = null;
127
+ this._activityLines = [];
128
+ this._setScrollRegion();
129
+ this._drawBox();
130
+ }
91
131
  // ── Input ──────────────────────────────────────────────────────────────────
92
132
  readLine() {
93
133
  this.buf = '';
@@ -111,7 +151,6 @@ export class FixedInput {
111
151
  if (key.includes('\x1b[200~')) {
112
152
  this._pasting = true;
113
153
  this._pasteAccum = '';
114
- // Strip the start marker and handle any content after it in the same chunk
115
154
  const after = key.slice(key.indexOf('\x1b[200~') + 6);
116
155
  if (after)
117
156
  this._pasteAccum += after;
@@ -120,7 +159,6 @@ export class FixedInput {
120
159
  // ── Bracketed paste: accumulate ───────────────────────────────
121
160
  if (this._pasting) {
122
161
  if (key.includes('\x1b[201~')) {
123
- // End marker — append everything before it, then commit
124
162
  const before = key.slice(0, key.indexOf('\x1b[201~'));
125
163
  this._pasteAccum += before;
126
164
  this.buf += this._pasteAccum;
@@ -133,17 +171,15 @@ export class FixedInput {
133
171
  }
134
172
  return;
135
173
  }
136
- // ── Shift+Enter → insert newline into buffer ──────────────────
137
- // Different terminals send different sequences:
138
- if (hex === '5c0d' || // \\\r (GNOME Terminal, ThinkPad, many Linux)
139
- key === '\x0a' || // LF (Ctrl+J, some terminals)
140
- hex === '1b5b31333b327e' || // \x1b[13;2~ xterm
141
- hex === '1b5b31333b3275' || // \x1b[13;2u kitty
142
- hex === '1b4f4d' // \x1bOM DECNKP
143
- ) {
174
+ // ── Shift+Enter → newline ────────────────────────────────────
175
+ if (hex === '5c0d' ||
176
+ key === '\x0a' ||
177
+ hex === '1b5b31333b327e' ||
178
+ hex === '1b5b31333b3275' ||
179
+ hex === '1b4f4d') {
144
180
  this.buf += '\n';
145
181
  this._scheduleDraw();
146
- // ── Enter → submit ────────────────────────────────────────────
182
+ // ── Enter → submit ───────────────────────────────────────────
147
183
  }
148
184
  else if (key === '\r') {
149
185
  const line = this.buf;
@@ -154,20 +190,20 @@ export class FixedInput {
154
190
  }
155
191
  done(line);
156
192
  }
157
- else if (key === '\x7f' || key === '\x08') { // Backspace
193
+ else if (key === '\x7f' || key === '\x08') {
158
194
  if (this.buf.length > 0) {
159
195
  this.buf = this.buf.slice(0, -1);
160
196
  this._scheduleDraw();
161
197
  }
162
198
  }
163
- else if (key === '\x03') { // Ctrl+C
199
+ else if (key === '\x03') {
164
200
  this.teardown();
165
201
  process.exit(0);
166
202
  }
167
- else if (key === '\x04') { // Ctrl+D
203
+ else if (key === '\x04') {
168
204
  done('/exit');
169
205
  }
170
- else if (key === '\x15') { // Ctrl+U
206
+ else if (key === '\x15') {
171
207
  this.buf = '';
172
208
  this._scheduleDraw();
173
209
  }
@@ -207,49 +243,58 @@ export class FixedInput {
207
243
  this.println(chalk.rgb(0, 120, 116)('─'.repeat(this.cols - 1)));
208
244
  }
209
245
  // ── Private drawing ────────────────────────────────────────────────────────
210
- /** Repaint the status row (between scroll region and input box). */
211
- _drawStatusRow() {
212
- const row = this.scrollBottom + 1;
213
- process.stdout.write(`\x1b[${row};1H\x1b[2K`);
214
- if (this._statusText) {
215
- process.stdout.write(chalk.rgb(0, 185, 180)(this._statusText));
216
- }
217
- }
218
- /** Debounced draw: coalesces rapid calls (e.g. during paste) into a single repaint. */
219
246
  _scheduleDraw() {
220
247
  if (this._drawPending)
221
248
  return;
222
249
  this._drawPending = true;
223
- setImmediate(() => {
224
- this._drawPending = false;
225
- this._drawBox();
226
- });
250
+ setImmediate(() => { this._drawPending = false; this._drawBox(); });
227
251
  }
228
- /** Set DECSTBM once — only called in setup() and on resize, never during typing. */
229
252
  _setScrollRegion() {
230
253
  const sb = this.scrollBottom;
231
254
  if (sb >= 1)
232
255
  process.stdout.write(`\x1b[1;${sb}r`);
233
256
  }
234
- /** Blank every row in the reserved area. */
235
257
  _clearReserved() {
236
258
  for (let r = this.scrollBottom + 1; r <= this.rows; r++)
237
259
  process.stdout.write(`\x1b[${r};1H\x1b[2K`);
238
260
  }
239
261
  _drawBox() {
262
+ process.stdout.write('\x1b[?25l');
263
+ this._clearReserved();
264
+ if (this._activityHeader !== null) {
265
+ this._drawActivityBox();
266
+ }
267
+ this._drawInputBox();
268
+ process.stdout.write('\x1b[?25h');
269
+ }
270
+ // ── Activity box (shown while a subagent is running) ───────────────────────
271
+ _drawActivityBox() {
272
+ const cols = this.cols;
273
+ const inner = cols - 4; // │ + space + content + space + │
274
+ const topRow = this.scrollBottom + 1;
275
+ const header = (this._activityHeader || '').slice(0, cols - 4);
276
+ const dashFill = Math.max(0, cols - 3 - header.length);
277
+ // Top border with header text
278
+ process.stdout.write(`\x1b[${topRow};1H`);
279
+ process.stdout.write(T('╭─') + chalk.bold.white(header) + T('─'.repeat(dashFill)) + T('╮'));
280
+ // Content rows (last ACTIVITY_LINES lines, or blank)
281
+ for (let i = 0; i < ACTIVITY_LINES; i++) {
282
+ const row = topRow + 1 + i;
283
+ const line = (this._activityLines[i] ?? '').slice(0, inner);
284
+ const pad = inner - line.length;
285
+ process.stdout.write(`\x1b[${row};1H`);
286
+ process.stdout.write(T('│') + ' ' + chalk.rgb(180, 210, 210)(line) + ' '.repeat(pad) + ' ' + T('│'));
287
+ }
288
+ // Bottom border
289
+ process.stdout.write(`\x1b[${topRow + ACTIVITY_LINES + 1};1H`);
290
+ process.stdout.write(T('╰') + T('─'.repeat(cols - 2)) + T('╯'));
291
+ }
292
+ // ── Normal input box ───────────────────────────────────────────────────────
293
+ _drawInputBox() {
240
294
  const cols = this.cols;
241
295
  const cRows = this._contentRows();
242
296
  const cWidth = cols - PREFIX_COLS - 2;
243
- // The box occupies the bottom of the terminal:
244
- // topBorder = rows - cRows - 1
245
- // content rows = rows - cRows ... rows - 1
246
- // bottomBorder = rows
247
297
  const topBorder = this.rows - cRows - 1;
248
- // Hide cursor while repainting
249
- process.stdout.write('\x1b[?25l');
250
- // Clear entire reserved area (removes stale content from previous draws)
251
- this._clearReserved();
252
- this._drawStatusRow();
253
298
  // ── Top border ───────────────────────────────────────────────
254
299
  process.stdout.write(`\x1b[${topBorder};1H`);
255
300
  process.stdout.write(T('╭') + T('─'.repeat(cols - 2)));
@@ -261,7 +306,6 @@ export class FixedInput {
261
306
  for (let i = 0; i < cRows; i++) {
262
307
  const row = topBorder + 1 + i;
263
308
  let line = visible[i] ?? '';
264
- // Show overflow indicator when content is clipped above
265
309
  if (i === 0 && showStart > 0)
266
310
  line = '… ' + line.slice(0, Math.max(0, cWidth - 2));
267
311
  else
@@ -275,18 +319,14 @@ export class FixedInput {
275
319
  process.stdout.write(`\x1b[${this.rows};1H`);
276
320
  process.stdout.write(T('╰') + T('─'.repeat(cols - 2)));
277
321
  process.stdout.write(`\x1b[${cols}G` + T('╯'));
278
- // ── Position cursor at end of last visible line ──────────────
322
+ // ── Position cursor ──────────────────────────────────────────
279
323
  const lastLine = visible[visible.length - 1] ?? '';
280
- const cursorRow = topBorder + cRows; // last content row
324
+ const cursorRow = topBorder + cRows;
281
325
  const cursorCol = PREFIX_COLS + 1 + lastLine.length;
282
326
  process.stdout.write(`\x1b[${cursorRow};${cursorCol}H`);
283
- process.stdout.write('\x1b[?25h');
284
327
  }
285
- /** Split text into visual lines: split on \n, then wrap each segment. */
286
328
  _wrapText(text, maxWidth) {
287
- if (!text)
288
- return [''];
289
- if (maxWidth <= 0)
329
+ if (!text || maxWidth <= 0)
290
330
  return [''];
291
331
  const result = [];
292
332
  for (const seg of text.split('\n')) {
@@ -15,7 +15,7 @@ export declare function getQwenAccessToken(): Promise<string | null>;
15
15
  * The qwen CLI manages its own token refresh and uses the correct API format.
16
16
  * Falls back to direct HTTP call if the qwen CLI is not available.
17
17
  */
18
- export declare function callQwenAPI(prompt: string, model?: string): Promise<string>;
18
+ export declare function callQwenAPI(prompt: string, model?: string, onData?: (chunk: string) => void): Promise<string>;
19
19
  /**
20
20
  * Call Qwen API using credentials from a specific file path (for role binaries).
21
21
  * The role binary CLI (e.g. agent-explorer) manages its own qwen auth via the
@@ -23,4 +23,4 @@ export declare function callQwenAPI(prompt: string, model?: string): Promise<str
23
23
  * in non-interactive mode without TTY issues.
24
24
  * Falls back to direct HTTP if the role binary is not found.
25
25
  */
26
- export declare function callQwenAPIFromCreds(prompt: string, model: string, credsPath: string): Promise<string>;
26
+ export declare function callQwenAPIFromCreds(prompt: string, model: string, credsPath: string, onData?: (chunk: string) => void): Promise<string>;
@@ -1,7 +1,25 @@
1
1
  import * as fs from 'fs/promises';
2
2
  import * as path from 'path';
3
3
  import * as crypto from 'crypto';
4
- import { spawnSync } from 'child_process';
4
+ import { spawn } from 'child_process';
5
+ /** Async alternative to spawnSync — keeps the event loop free so UI can update. */
6
+ function spawnAsync(bin, args, input, timeout, onData) {
7
+ return new Promise((resolve, reject) => {
8
+ const child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] });
9
+ let stdout = '';
10
+ child.stdout?.on('data', (d) => {
11
+ const s = d.toString();
12
+ stdout += s;
13
+ onData?.(s);
14
+ });
15
+ child.stderr?.on('data', (d) => { stdout += d.toString(); });
16
+ const timer = setTimeout(() => { child.kill(); reject(new Error('qwen timeout')); }, timeout);
17
+ child.on('close', (code) => { clearTimeout(timer); resolve({ stdout, status: code ?? 0 }); });
18
+ child.on('error', (err) => { clearTimeout(timer); reject(err); });
19
+ child.stdin?.write(input, 'utf-8');
20
+ child.stdin?.end();
21
+ });
22
+ }
5
23
  import open from 'open';
6
24
  import { AGENT_HOME } from './config.js';
7
25
  const QWEN_OAUTH_BASE_URL = 'https://chat.qwen.ai';
@@ -279,17 +297,12 @@ async function callQwenAPIWithToken(token, prompt, model) {
279
297
  * The qwen CLI manages its own token refresh and uses the correct API format.
280
298
  * Falls back to direct HTTP call if the qwen CLI is not available.
281
299
  */
282
- export async function callQwenAPI(prompt, model = 'coder-model') {
300
+ export async function callQwenAPI(prompt, model = 'coder-model', onData) {
283
301
  // Try using the qwen CLI subprocess first — it handles auth/refresh/format automatically
284
302
  const qwenBin = process.env.QWEN_BIN || 'qwen';
285
303
  try {
286
- const result = spawnSync(qwenBin, [], {
287
- input: prompt,
288
- encoding: 'utf-8',
289
- timeout: 300000, // 5 minutes
290
- maxBuffer: 10 * 1024 * 1024,
291
- });
292
- if (result.status === 0 && result.stdout?.trim()) {
304
+ const result = await spawnAsync(qwenBin, [], prompt, 300000, onData);
305
+ if (result.status === 0 && result.stdout.trim()) {
293
306
  return result.stdout.trim();
294
307
  }
295
308
  // qwen not available or failed — fall through to direct API
@@ -325,19 +338,14 @@ export async function callQwenAPI(prompt, model = 'coder-model') {
325
338
  * in non-interactive mode without TTY issues.
326
339
  * Falls back to direct HTTP if the role binary is not found.
327
340
  */
328
- export async function callQwenAPIFromCreds(prompt, model, credsPath) {
341
+ export async function callQwenAPIFromCreds(prompt, model, credsPath, onData) {
329
342
  // Derive the role binary name from the creds path (e.g. ~/.agent-explorer/ → agent-explorer)
330
343
  const cliName = path.basename(path.dirname(credsPath)).replace(/^\./, '');
331
- // Try spawning the role binary with piped stdin (non-interactive mode)
344
+ // Try spawning the qwen CLI with piped stdin (async — keeps event loop free)
332
345
  const qwenBin = process.env.QWEN_BIN || 'qwen';
333
346
  try {
334
- const result = spawnSync(qwenBin, [], {
335
- input: prompt,
336
- encoding: 'utf-8',
337
- timeout: 300000,
338
- maxBuffer: 10 * 1024 * 1024,
339
- });
340
- if (result.status === 0 && result.stdout?.trim()) {
347
+ const result = await spawnAsync(qwenBin, [], prompt, 300000, onData);
348
+ if (result.status === 0 && result.stdout.trim()) {
341
349
  return result.stdout.trim();
342
350
  }
343
351
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mp",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "description": "Deterministic multi-agent CLI orchestrator — plan, code, review",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",