pal-code 0.0.11 → 0.0.13

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.
@@ -27,17 +27,29 @@ import {
27
27
  } from '@earendil-works/pi-tui';
28
28
  import type {TUI} from '@earendil-works/pi-tui';
29
29
  import {c, editorTheme, agentColors, agentLabels, colorByName} from './theme.js';
30
- import {generateTitle, sanitizeTitle, formatMessageTimestamp} from './utils/format.js';
30
+ import {
31
+ generateTitle,
32
+ sanitizeTitle,
33
+ formatMessageTimestamp,
34
+ subagentStatusText,
35
+ } from './utils/format.js';
31
36
  import {MessageBox} from './components/message-box.js';
32
37
  import {renderHistory} from './components/render-history.js';
33
38
  import {loadConfig} from './config.js';
34
39
  import {StatusLine} from './components/status-line.js';
35
40
  import {PermissionPrompt} from './components/permission-prompt.js';
36
- import {state} from './state.js';
41
+ import {dequeueMessage, enqueueMessage, queuedStatusText, state} from './state.js';
37
42
  import {Sidebar} from './components/sidebar.js';
38
43
  import {cmdHelp, cmdCost} from './commands.js';
44
+ import {
45
+ loadUpdateCache,
46
+ planStartupNotice,
47
+ refreshUpdateCheck,
48
+ saveUpdateCache,
49
+ } from './commands/update-check.js';
39
50
  import {showSessionSelector, cmdResume} from './overlays/session-picker.js';
40
51
  import {loadCostManifest, estimateCost, isPricedModel} from './utils/cost.js';
52
+ import {buildOsc52Sequence, lastAssistantText, lastCodeBlock} from './utils/osc52.js';
41
53
  import {openAgentsPanel, closeAgentsPanel} from './agent-panel.js';
42
54
  import {
43
55
  createOpenRouterProvider,
@@ -59,6 +71,8 @@ import {
59
71
  restoreSnapshot,
60
72
  listSnapshots,
61
73
  onAgentEvent,
74
+ getSubagentStatus,
75
+ onSubagentStatusChange,
62
76
  providerAccessible,
63
77
  rollbackTurn,
64
78
  seqToCount,
@@ -81,7 +95,7 @@ import type {SessionStore as SessionStoreType} from '@pal-code/core';
81
95
  // (see buildModelOptions). Static curated lists live in @pal-code/core PROVIDERS as fallback.
82
96
 
83
97
  // Version synced from version.json via `node scripts/sync-version.js`.
84
- const VERSION = '0.0.11';
98
+ const VERSION = '0.0.13';
85
99
 
86
100
  import {showModelSelector} from './overlays/model-picker.js';
87
101
  import {showKeyInput} from './overlays/key-input.js';
@@ -115,7 +129,7 @@ async function main() {
115
129
  // Handle CLI extension commands (no TUI needed)
116
130
  if (process.argv[2] === 'add' && process.argv[3]) {
117
131
  const {extAdd} = await import('./commands/ext.js');
118
- const result = extAdd(process.argv[3]);
132
+ const result = await extAdd(process.argv[3]);
119
133
  console.log(result.message);
120
134
  process.exit(result.ok ? 0 : 1);
121
135
  }
@@ -125,6 +139,29 @@ async function main() {
125
139
  console.log(result.message);
126
140
  process.exit(result.ok ? 0 : 1);
127
141
  }
142
+ if (process.argv[2] === 'export') {
143
+ const {exportConfig} = await import('./commands/config-export.js');
144
+ const result = exportConfig(process.argv[3]);
145
+ console.log(result.message);
146
+ process.exit(result.ok ? 0 : 1);
147
+ }
148
+ if (process.argv[2] === 'import') {
149
+ const {importConfig} = await import('./commands/config-io.js');
150
+ const file = process.argv[3];
151
+ if (!file) {
152
+ console.log('Usage: pal import <file>');
153
+ process.exit(1);
154
+ }
155
+ const result = importConfig(file);
156
+ console.log(result.message);
157
+ process.exit(result.ok ? 0 : 1);
158
+ }
159
+ if (process.argv[2] === 'update' || process.argv[2] === 'upgrade') {
160
+ const {palUpdate} = await import('./commands/update.js');
161
+ const result = await palUpdate();
162
+ console.log(result.message);
163
+ process.exit(result.ok ? 0 : 1);
164
+ }
128
165
  // ── BYOK gate: force setup when no key is configured ──
129
166
  let allKeys = resolveAllKeys();
130
167
  const forceSetup = process.argv.includes('--setup') || process.argv.includes('--login');
@@ -222,6 +259,24 @@ async function main() {
222
259
  messagesContainer.addChild(
223
260
  new Text(`${c.dim}Model: ${config.model} (${providerName})${c.reset}`, 1, 0),
224
261
  );
262
+
263
+ // ── Update check ──
264
+ // Sync from the daily cache so startup never blocks; refresh below is
265
+ // fire-and-forget. Hint once per version (`notified`); yellow `critical`
266
+ // banner every launch until local catches up. Never auto-updates.
267
+ const updateCache = loadUpdateCache();
268
+ const updateNotice = planStartupNotice(updateCache, VERSION);
269
+ if (updateNotice.changed) saveUpdateCache({...updateCache, notified: updateNotice.notified});
270
+ if (updateNotice.banner) {
271
+ messagesContainer.addChild(new Text(`${c.yellow}${updateNotice.banner}${c.reset}`, 1, 0));
272
+ }
273
+ if (updateNotice.hint) {
274
+ messagesContainer.addChild(new Text(`${c.dim}${updateNotice.hint}${c.reset}`, 1, 0));
275
+ }
276
+ refreshUpdateCheck().catch(() => {
277
+ // silent by design — refreshUpdateCheck swallows its own errors
278
+ });
279
+
225
280
  if (!hasAnyKey(allKeys)) {
226
281
  messagesContainer.addChild(
227
282
  new Text(`${c.yellow} No API key configured. Type /keys to see status.${c.reset}`, 1, 0),
@@ -363,7 +418,7 @@ async function main() {
363
418
 
364
419
  tui.addInputListener((data) => {
365
420
  // SGR mouse: ESC [ < b ; x ; y M|m (preferred, enabled via ?1006h)
366
- const mouse = data.match(/^\x1b\[<(\d+);\d+;\d+[Mm]$/);
421
+ const mouse = data.startsWith('\x1b[<') ? data.slice(3).match(/^(\d+);\d+;\d+[Mm]$/) : null;
367
422
  if (mouse) {
368
423
  const btn = Number(mouse[1]) & 0xff;
369
424
  if (btn === 64) {
@@ -471,6 +526,9 @@ async function main() {
471
526
  {name: 'cost', description: 'Show token usage and cost'},
472
527
  {name: 'model', description: 'Switch model'},
473
528
  {name: 'ext', description: 'Manage extensions'},
529
+ {name: 'export', description: 'Export config to a versionable JSON file'},
530
+ {name: 'import', description: 'Import config from an export file'},
531
+ {name: 'roles', description: 'List agent roles'},
474
532
  ],
475
533
  process.cwd(),
476
534
  ),
@@ -497,6 +555,9 @@ async function main() {
497
555
  const agentStr = state.backgroundAgents.length
498
556
  ? ` ${c.yellow}⛭ ${running}/${state.backgroundAgents.length} agents${c.reset}`
499
557
  : '';
558
+ const sub = getSubagentStatus();
559
+ const subLine = subagentStatusText(sub.active, sub.startedAt);
560
+ const subStr = subLine ? ` ${c.yellow}${subLine}${c.reset}` : '';
500
561
  // The status line now only carries identity/nav; token, cost and context
501
562
  // usage live in the sidebar's Info block.
502
563
  //
@@ -513,8 +574,12 @@ async function main() {
513
574
  `${c.cyan}↕ scrolled${c.reset} ${c.dim}· PgDn/↓ End or Esc to resume${c.reset}`,
514
575
  );
515
576
  } else {
577
+ // `queued (N)` — messages submitted while a turn runs (drained on
578
+ // settle). Empty at N=0, so the idle status line stays byte-identical.
579
+ const queuedText = queuedStatusText(state.pendingMessages.length);
580
+ const queuedStr = queuedText ? ` ${c.yellow}${queuedText}${c.reset}` : '';
516
581
  statusLine.setText(
517
- `${modelShort} ${c.dim}${providerName}${agentStr}${c.reset} ${c.dim}/help${c.reset}`,
582
+ `${modelShort} ${c.dim}${providerName}${agentStr}${subStr}${queuedStr}${c.reset} ${c.dim}/help${c.reset}`,
518
583
  );
519
584
  }
520
585
  sidebar.setStats({
@@ -797,7 +862,9 @@ async function main() {
797
862
  const teardownPermission = (): void => {
798
863
  // Remove the centered prompt from the message area
799
864
  if (state.permissionPrompt) {
800
- try { messagesContainer.removeChild(state.permissionPrompt); } catch {}
865
+ try {
866
+ messagesContainer.removeChild(state.permissionPrompt);
867
+ } catch {}
801
868
  }
802
869
  // Restore the editor
803
870
  editorRow.addChild(editor);
@@ -907,6 +974,20 @@ async function main() {
907
974
  }
908
975
  });
909
976
 
977
+ // Fan-out status line (OMO unit 3): core's spawn/settle counter drives the
978
+ // segment in updateStatusLine. Tick advances elapsed seconds while the main
979
+ // loop awaits children; at zero the segment vanishes and the tick clears.
980
+ let subagentTick: ReturnType<typeof setInterval> | undefined;
981
+ onSubagentStatusChange((sub) => {
982
+ if (sub.active > 0 && subagentTick === undefined) {
983
+ subagentTick = setInterval(() => state.refreshStatusLine(), 1000);
984
+ } else if (sub.active === 0 && subagentTick !== undefined) {
985
+ clearInterval(subagentTick);
986
+ subagentTick = undefined;
987
+ }
988
+ state.refreshStatusLine();
989
+ });
990
+
910
991
  // ═══════════════════════════════════════════════════════════════════════════
911
992
  // Editor submit handler
912
993
  // ═══════════════════════════════════════════════════════════════════════════
@@ -920,12 +1001,25 @@ async function main() {
920
1001
  let autoExecuted = false;
921
1002
 
922
1003
  editor.onSubmit = async (text) => {
923
- if (isProcessing) return;
924
1004
  // `let` so `/plan <task>` and `/execute <task>` can rewrite the input and
925
1005
  // fall through to the normal turn dispatch below.
926
1006
  let trimmed = text.trim();
927
1007
  if (!trimmed) return;
928
1008
 
1009
+ // A turn is running: the editor stays submittable — park the message on
1010
+ // the queue instead of starting a second turn. The settle path below
1011
+ // drains one message per settled turn (completion, error, or abort; an
1012
+ // abort never discards the queue). Slash commands queue the same way and
1013
+ // run in order when drained. A permission overlay consumes all keys
1014
+ // before this handler can run, so queueing never races the permission
1015
+ // prompt's own queue. Quitting the TUI (ctrl+c/d) drops whatever is
1016
+ // still queued — the queue is in-memory only.
1017
+ if (isProcessing) {
1018
+ enqueueMessage(state.pendingMessages, trimmed);
1019
+ state.refreshStatusLine();
1020
+ return;
1021
+ }
1022
+
929
1023
  editor.setText('');
930
1024
 
931
1025
  // ── Slash commands ──
@@ -1055,9 +1149,7 @@ async function main() {
1055
1149
  state.currentTodos = [];
1056
1150
  state.permissionWhitelist = [];
1057
1151
  refreshSidebar();
1058
- messagesContainer.addChild(
1059
- new Text(`${c.yellow}New session started.${c.reset}`, 1, 0),
1060
- );
1152
+ messagesContainer.addChild(new Text(`${c.yellow}New session started.${c.reset}`, 1, 0));
1061
1153
  tui.requestRender();
1062
1154
  return;
1063
1155
  }
@@ -1065,7 +1157,11 @@ async function main() {
1065
1157
  // /clear was removed in favour of /new: history is append-only now, so
1066
1158
  // "erase this session" has no clean representation. Point users at /new.
1067
1159
  messagesContainer.addChild(
1068
- new Text(`${c.dim} /clear was removed — use /new to start a fresh session.${c.reset}`, 1, 0),
1160
+ new Text(
1161
+ `${c.dim} /clear was removed — use /new to start a fresh session.${c.reset}`,
1162
+ 1,
1163
+ 0,
1164
+ ),
1069
1165
  );
1070
1166
  tui.requestRender();
1071
1167
  return;
@@ -1132,11 +1228,7 @@ async function main() {
1132
1228
  store.recordCompaction(currentSessionId, alreadyUpto, newMark, summary);
1133
1229
  }
1134
1230
  messagesContainer.addChild(
1135
- new Text(
1136
- `${c.green}Compacted ${boundary} messages into a checkpoint.${c.reset}`,
1137
- 1,
1138
- 0,
1139
- ),
1231
+ new Text(`${c.green}Compacted ${boundary} messages into a checkpoint.${c.reset}`, 1, 0),
1140
1232
  );
1141
1233
  tui.requestRender();
1142
1234
  return;
@@ -1180,8 +1272,11 @@ async function main() {
1180
1272
  } else {
1181
1273
  for (const rule of perm.rules) {
1182
1274
  const tools = Array.isArray(rule.tool) ? rule.tool.join(',') : rule.tool;
1183
- const color = rule.action === 'allow' ? c.green : rule.action === 'deny' ? c.red : c.yellow;
1184
- lines.push(` ${tools.padEnd(20)} ${rule.match.padEnd(20)} ${color}${rule.action}${c.reset}`);
1275
+ const color =
1276
+ rule.action === 'allow' ? c.green : rule.action === 'deny' ? c.red : c.yellow;
1277
+ lines.push(
1278
+ ` ${tools.padEnd(20)} ${rule.match.padEnd(20)} ${color}${rule.action}${c.reset}`,
1279
+ );
1185
1280
  }
1186
1281
  }
1187
1282
  if (state.permissionWhitelist.length > 0) {
@@ -1192,7 +1287,9 @@ async function main() {
1192
1287
  }
1193
1288
  }
1194
1289
  lines.push('');
1195
- lines.push(`${c.dim}Edit permissions.json in your project root or ~/.pal/ to customize.${c.reset}`);
1290
+ lines.push(
1291
+ `${c.dim}Edit permissions.json in your project root or ~/.pal/ to customize.${c.reset}`,
1292
+ );
1196
1293
  for (const line of lines) {
1197
1294
  messagesContainer.addChild(new Text(line, 1, 0));
1198
1295
  }
@@ -1282,10 +1379,19 @@ async function main() {
1282
1379
 
1283
1380
  if (sub === 'add' && pkg) {
1284
1381
  const {extAdd} = await import('./commands/ext.js');
1285
- const result = extAdd(pkg);
1382
+ const result = await extAdd(pkg);
1286
1383
  messagesContainer.addChild(
1287
1384
  new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1288
1385
  );
1386
+ } else if (sub === 'search') {
1387
+ const {extSearchOrBrowse} = await import('./commands/ext.js');
1388
+ const result = await extSearchOrBrowse(parts.slice(1).join(' '));
1389
+ messagesContainer.addChild(
1390
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1391
+ );
1392
+ } else if (sub === 'browse') {
1393
+ const {formatBrowse} = await import('./commands/ext-registry.js');
1394
+ messagesContainer.addChild(new Text(formatBrowse(c), 1, 0));
1289
1395
  } else if (sub === 'remove' && pkg) {
1290
1396
  const {extRemove} = await import('./commands/ext.js');
1291
1397
  const result = extRemove(pkg);
@@ -1299,7 +1405,8 @@ async function main() {
1299
1405
  return ` ${ext.name.padEnd(24)} ${status}`;
1300
1406
  });
1301
1407
  if (lines.length === 0) {
1302
- messagesContainer.addChild(new Text(`${c.dim} No extensions loaded.${c.reset}`, 1, 0));
1408
+ const {emptyListMessage} = await import('./commands/ext-registry.js');
1409
+ messagesContainer.addChild(new Text(`${c.dim} ${emptyListMessage()}${c.reset}`, 1, 0));
1303
1410
  } else {
1304
1411
  messagesContainer.addChild(
1305
1412
  new Text(`${c.bold}Loaded extensions${c.reset}\n${lines.join('\n')}`, 1, 0),
@@ -1308,7 +1415,7 @@ async function main() {
1308
1415
  } else {
1309
1416
  messagesContainer.addChild(
1310
1417
  new Text(
1311
- `${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext list${c.reset}`,
1418
+ `${c.dim} Usage: /ext add <name> | /ext remove <name> | /ext search <query> | /ext list | /ext browse${c.reset}`,
1312
1419
  1,
1313
1420
  0,
1314
1421
  ),
@@ -1318,6 +1425,32 @@ async function main() {
1318
1425
  return;
1319
1426
  }
1320
1427
 
1428
+ if (trimmed === '/export' || trimmed.startsWith('/export ')) {
1429
+ const file = trimmed.slice('/export'.length).trim();
1430
+ const {exportConfig} = await import('./commands/config-export.js');
1431
+ const result = exportConfig(file || undefined);
1432
+ messagesContainer.addChild(
1433
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1434
+ );
1435
+ tui.requestRender();
1436
+ return;
1437
+ }
1438
+
1439
+ if (trimmed === '/import' || trimmed.startsWith('/import ')) {
1440
+ const file = trimmed.slice('/import'.length).trim();
1441
+ if (!file) {
1442
+ messagesContainer.addChild(new Text(`${c.dim} Usage: /import <file>${c.reset}`, 1, 0));
1443
+ } else {
1444
+ const {importConfig} = await import('./commands/config-io.js');
1445
+ const result = importConfig(file);
1446
+ messagesContainer.addChild(
1447
+ new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1448
+ );
1449
+ }
1450
+ tui.requestRender();
1451
+ return;
1452
+ }
1453
+
1321
1454
  if (trimmed === '/mcp' || trimmed.startsWith('/mcp ')) {
1322
1455
  const args = trimmed.slice('/mcp'.length).trim();
1323
1456
  const parts = args.split(/\s+/);
@@ -1347,7 +1480,11 @@ async function main() {
1347
1480
  }
1348
1481
  }
1349
1482
  const {mcpAddRemote} = await import('./commands/mcp.js');
1350
- const result = mcpAddRemote(name, url, Object.keys(headers).length > 0 ? headers : undefined);
1483
+ const result = mcpAddRemote(
1484
+ name,
1485
+ url,
1486
+ Object.keys(headers).length > 0 ? headers : undefined,
1487
+ );
1351
1488
  messagesContainer.addChild(
1352
1489
  new Text(`${result.ok ? c.green : c.red} ${result.message}${c.reset}`, 1, 0),
1353
1490
  );
@@ -1360,9 +1497,7 @@ async function main() {
1360
1497
  } else if (sub === 'list') {
1361
1498
  const {mcpList} = await import('./commands/mcp.js');
1362
1499
  const lines = mcpList();
1363
- messagesContainer.addChild(
1364
- new Text(`${c.bold}${lines.join('\n')}${c.reset}`, 1, 0),
1365
- );
1500
+ messagesContainer.addChild(new Text(`${c.bold}${lines.join('\n')}${c.reset}`, 1, 0));
1366
1501
  } else if (sub === 'browse') {
1367
1502
  const {REGISTRY} = await import('./commands/mcp-registry.js');
1368
1503
  const lines: string[] = [`${c.bold}Curated MCP Servers${c.reset}`, ''];
@@ -1371,10 +1506,14 @@ async function main() {
1371
1506
  lines.push(` ${c.dim}${entry.description}${c.reset}`);
1372
1507
  if (entry.url) {
1373
1508
  // Remote server
1374
- lines.push(` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`);
1509
+ lines.push(
1510
+ ` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`,
1511
+ );
1375
1512
  } else if (entry.package) {
1376
1513
  // Local server
1377
- lines.push(` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`);
1514
+ lines.push(
1515
+ ` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`,
1516
+ );
1378
1517
  }
1379
1518
  lines.push('');
1380
1519
  }
@@ -1388,16 +1527,17 @@ async function main() {
1388
1527
  new Text(`${c.dim} No MCP servers found for "${query}".${c.reset}`, 1, 0),
1389
1528
  );
1390
1529
  } else {
1391
- const lines: string[] = [
1392
- `${c.bold}Search results for "${query}"${c.reset}`,
1393
- '',
1394
- ];
1530
+ const lines: string[] = [`${c.bold}Search results for "${query}"${c.reset}`, ''];
1395
1531
  for (const entry of results) {
1396
1532
  lines.push(` ${c.cyan}${entry.name}${c.reset} — ${entry.description}`);
1397
1533
  if (entry.url) {
1398
- lines.push(` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`);
1534
+ lines.push(
1535
+ ` ${c.green}/mcp add-remote ${entry.name.toLowerCase()} ${entry.url}${c.reset}`,
1536
+ );
1399
1537
  } else if (entry.package) {
1400
- lines.push(` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`);
1538
+ lines.push(
1539
+ ` ${c.green}/mcp add ${entry.name.toLowerCase()} npx -y ${entry.package}${c.reset}`,
1540
+ );
1401
1541
  }
1402
1542
  lines.push('');
1403
1543
  }
@@ -1416,6 +1556,35 @@ async function main() {
1416
1556
  return;
1417
1557
  }
1418
1558
 
1559
+ if (trimmed === '/copy' || trimmed.startsWith('/copy ')) {
1560
+ const target = trimmed.slice('/copy'.length).trim();
1561
+ if (target !== '' && target !== 'code') {
1562
+ messagesContainer.addChild(
1563
+ new Text(
1564
+ `${c.dim} Usage: /copy Copy the last assistant reply to the clipboard${c.reset}\n` +
1565
+ `${c.dim} /copy code Copy the last code block from the conversation${c.reset}`,
1566
+ 1,
1567
+ 0,
1568
+ ),
1569
+ );
1570
+ } else {
1571
+ const text = target === 'code' ? lastCodeBlock(messages) : lastAssistantText(messages);
1572
+ if (text === null) {
1573
+ const empty = target === 'code' ? 'No code block found.' : 'Nothing to copy yet.';
1574
+ messagesContainer.addChild(new Text(`${c.dim} ${empty}${c.reset}`, 1, 0));
1575
+ } else {
1576
+ // pi-tui owns the screen but exposes its writer: OSC 52 must reach the
1577
+ // terminal verbatim (it is consumed by the terminal, not drawn).
1578
+ tui.terminal.write(buildOsc52Sequence(text));
1579
+ messagesContainer.addChild(
1580
+ new Text(`${c.green} Copied ${text.length} chars to clipboard${c.reset}`, 1, 0),
1581
+ );
1582
+ }
1583
+ }
1584
+ tui.requestRender();
1585
+ return;
1586
+ }
1587
+
1419
1588
  // ── Clear finished todos when user moves on to something new ──
1420
1589
  if (state.currentTodos.length > 0) {
1421
1590
  const allTerminal = state.currentTodos.every(
@@ -1433,15 +1602,18 @@ async function main() {
1433
1602
  // Record the role for this user turn so repaint can colour it correctly.
1434
1603
  userRoles.set(messages.length, activeRole);
1435
1604
  messagesContainer.addChild(new Spacer(1));
1436
- messagesContainer.addChild(new MessageBox(trimmed, activeRole, formatMessageTimestamp(Date.now())));
1605
+ messagesContainer.addChild(
1606
+ new MessageBox(trimmed, activeRole, formatMessageTimestamp(Date.now())),
1607
+ );
1437
1608
  messagesContainer.addChild(new Spacer(1));
1438
1609
  tui.requestRender();
1439
1610
 
1440
1611
  // ── Agent turn ──
1441
1612
  // The selected primary agent shapes the turn itself (system prompt + tool
1442
1613
  // set) rather than being described in the message — see agentLoop.
1614
+ // The editor is NOT submission-gated: a submit during the turn queues
1615
+ // (see onSubmit) and drains when the turn settles.
1443
1616
  isProcessing = true;
1444
- editor.disableSubmit = true;
1445
1617
  autoExecuted = false;
1446
1618
 
1447
1619
  /**
@@ -1558,8 +1730,40 @@ async function main() {
1558
1730
  }
1559
1731
 
1560
1732
  isProcessing = false;
1561
- editor.disableSubmit = false;
1562
1733
  tui.requestRender();
1734
+
1735
+ // ── Drain queued messages ──
1736
+ // Every settle — completion, error, or abort — hands the next queued
1737
+ // message back to the normal submit path (identical to a fresh
1738
+ // submission). A submission that actually starts a turn stops the drain;
1739
+ // that turn's settle drains the one after it, so exactly one turn runs
1740
+ // per settle. An abort settles like any other turn: it never eats the
1741
+ // queue. A permission overlay cannot be open here (the loop awaits each
1742
+ // prompt and the overlay closes before the turn resumes), so drain never
1743
+ // conflicts with the permission queue. Quitting the TUI with messages
1744
+ // still queued drops them — in-memory only, see the enqueue comment.
1745
+ const firstQueued = dequeueMessage(state.pendingMessages);
1746
+ if (firstQueued !== null) {
1747
+ let nextQueued: string | null = firstQueued;
1748
+ while (nextQueued !== null) {
1749
+ // The submit handler clears the input synchronously — preserve
1750
+ // whatever the user has typed since their last submission.
1751
+ const draft = editor.getText();
1752
+ // Keep the handler's promise: a queued message can suspend BEFORE it
1753
+ // sets isProcessing (e.g. /plan awaits ensureExtensionsLoaded, then
1754
+ // falls through to a turn), which would let this loop start a second
1755
+ // turn concurrently. Awaiting makes each submission fully settle —
1756
+ // turn, inline command, or its own nested drain — before the next.
1757
+ const submitted = editor.onSubmit?.(nextQueued) ?? Promise.resolve();
1758
+ if (draft.length > 0) editor.setText(draft);
1759
+ await submitted;
1760
+ // A user submit can win the race during an inline command's await;
1761
+ // its settle will drain the rest of the queue.
1762
+ if (isProcessing) break;
1763
+ nextQueued = dequeueMessage(state.pendingMessages);
1764
+ }
1765
+ state.refreshStatusLine(); // drop the `queued (N)` indicator
1766
+ }
1563
1767
  };
1564
1768
 
1565
1769
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1584,7 +1788,8 @@ async function main() {
1584
1788
  // Restore the terminal: leaving SGR mouse reporting on would make the
1585
1789
  // parent shell print raw mouse escape codes.
1586
1790
  disableMouse();
1587
- });}
1791
+ });
1792
+ }
1588
1793
 
1589
1794
  main().catch((err) => {
1590
1795
  // A startup failure (e.g. locked DB, broken import) after tui.start() leaves
@@ -1598,7 +1803,9 @@ main().catch((err) => {
1598
1803
  if (process.stdin.isTTY) process.stdin.setRawMode(false);
1599
1804
  // 3. Show the cursor in case it was hidden.
1600
1805
  process.stdout.write('\x1b[?25h');
1601
- } catch { /* best-effort — may crash again if stdin/stdout are gone */ }
1806
+ } catch {
1807
+ /* best-effort — may crash again if stdin/stdout are gone */
1808
+ }
1602
1809
  console.error(err);
1603
1810
  process.exit(1);
1604
1811
  });
@@ -80,6 +80,8 @@ export interface AppState {
80
80
  activeAbort: AbortController | null;
81
81
  /** The most recently collapsed run, for ctrl+o. */
82
82
  lastRun: RunView | null;
83
+ /** Messages submitted while a turn was running; drained one per settled turn. */
84
+ pendingMessages: string[];
83
85
  /** Loaded extensions and their status. */
84
86
  extensions: ExtensionInfo[];
85
87
  /** MCP servers discovered during startup. */
@@ -120,6 +122,7 @@ export const state: AppState = {
120
122
  activeRun: null,
121
123
  activeAbort: null,
122
124
  lastRun: null,
125
+ pendingMessages: [],
123
126
  extensions: [],
124
127
  mcpServers: [],
125
128
  currentAgentRole: 'pal',
@@ -131,3 +134,26 @@ export const state: AppState = {
131
134
  permissionPrompt: null,
132
135
  permissionQueue: [],
133
136
  };
137
+
138
+ /**
139
+ * Park a message submitted while a turn is running. Pure over `queue` so the
140
+ * decision logic is testable without the TUI. Returns the new length for the
141
+ * `queued (N)` status-line indicator.
142
+ */
143
+ export function enqueueMessage(queue: string[], message: string): number {
144
+ queue.push(message);
145
+ return queue.length;
146
+ }
147
+
148
+ /**
149
+ * Take the next message to run when a turn settles — completed, errored, or
150
+ * aborted alike. Returns null when nothing is queued.
151
+ */
152
+ export function dequeueMessage(queue: string[]): string | null {
153
+ return queue.shift() ?? null;
154
+ }
155
+
156
+ /** Status-line fragment: '' at 0 so the idle status line stays byte-identical. */
157
+ export function queuedStatusText(count: number): string {
158
+ return count > 0 ? `queued (${count})` : '';
159
+ }