@pi-kaush/pi-tool-call-markers 0.3.25 → 0.3.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,7 +83,7 @@ A recognized `subagent` call renders as an unboxed plan in the shared tool aesth
83
83
 
84
84
  Single calls stay on one `▏ [<emoji>] [<profile>][<agent>] <task preview>` row — no tool label. Chain calls get a heading with the kind, count, and scope followed by numbered steps (parallel tasks list without numbers), with each step ordered emoji, profile badge, name badge. Agent display names (emoji + name) are scraped from the native plan component — including the single-call heading — with an args fallback, and render in `accent`; everything else stays muted, and failed subagents go full red. Subagents never join ordinary tool groups.
85
85
 
86
- Assigned agent emojis take priority. Without one, calls use 👾 for non-interactive runs or 🤖 for interactive launches and worker controls (`list`, `status`, `send`, `wait`, `stop`, and `resume`). Tasks using the `coder` profile default to 🧑‍💻 in either mode. An explicit model override disables that profile default, just as it hides the profile badge. These defaults also cover generic fallback rows such as `subagent 🤖 ... [user]`.
86
+ Assigned agent emojis always take priority. Without one, non-interactive runs use 👻; interactive launches and worker controls (`list`, `status`, `send`, `wait`, `stop`, and `resume`) use 👾. Profiles and explicit model overrides do not affect the fallback. These defaults also cover generic fallback rows such as `subagent 👾 ... [user]`.
87
87
 
88
88
  While a subagent runs, the plan headline's tail shows live progress from the streamed result details — `→ 1 turn · provider/model` in the warning tone — and a settled call keeps the same `→ N turns · provider/model` summary in muted (turns aggregate across tasks; the model shows only when every task used the same one).
89
89
 
@@ -107,8 +107,8 @@ The block reuses `pi-content-layout`'s submitted-prompt geometry — the same ra
107
107
 
108
108
  - **Shape-first recognition.** Any tool whose result carries an `answers` array of `{ question, answer | selected }` entries renders as a question block, so another author's question tool works without a change here. The tool name (`ask_user_question` and close variants) is the fallback for a call that failed before answering.
109
109
  - **Answers, not options.** Each question shows its answer: an option label, typed custom text, or multi-select labels joined with commas. A question left blank reads `User: (no answer)`, a decline reads `User declined to answer questions`, and a validation failure keeps Pi's native failure row.
110
- - **Quoted questions.** The question is the model's text read inside a user-input shell, so it renders italic under a `>` marker and the answer stays upright: the answer is the user's own words. A theme without italics renders the question plainly.
111
- - **Prompt-shell tones.** The rail uses `borderAccent` and the body paints on `userMessageBg`, with the question in `text`, the `User:` label in `muted`, the answer in `userMessageText`, and a live row's `awaiting your answer…` in `warning`.
110
+ - **Quoted questions.** The `>` marker and every line of the question use `muted` in italics. The `User:` label and reply use `userMessageText`. Only the actual reply is bold, not the label or the blank-answer placeholder.
111
+ - **Prompt-shell tones.** The rail uses `borderAccent` and the body uses `userMessageBg`. A live row's `awaiting your answer…` stays in `warning`.
112
112
  - **One blank row per question.** Questions are separated by a painted blank row so a multi-question ask stays scannable. A lone question keeps its outcome on the following line.
113
113
  - **No grouping.** Question blocks never join an adjacent tool group and carry no tool glyph. `Ctrl+O` still restores Pi's native expanded rendering.
114
114
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-kaush/pi-tool-call-markers",
3
- "version": "0.3.25",
3
+ "version": "0.3.27",
4
4
  "description": "Compact and group Pi tool calls, with a bundled extension for adjacent thinking blocks.",
5
5
  "license": "MIT",
6
6
  "author": "Kaushik Gopal",
package/src/index.ts CHANGED
@@ -50,6 +50,8 @@ const TOOL_CALL_GLYPHS: ReadonlyMap<string, string> = new Map([
50
50
  ["get_search_content", "↗"],
51
51
  ["codemode", "¢"],
52
52
  ]);
53
+ // Keep the historical slot so old, still-reachable delegates can be handed off.
54
+ const PRESENTATION_GENERATION = 4;
53
55
  const PRESENTATION_PATCHED = Symbol.for("kg.pi.toolPresentation.v3");
54
56
  const LEGACY_PRESENTATION_PATCHED = Symbol.for("kg.pi.toolPresentation.v2");
55
57
  const GROUPING_PATCHED = Symbol.for("kg.pi.toolGrouping.v1");
@@ -99,10 +101,11 @@ type ToolExecutionRow = {
99
101
  };
100
102
 
101
103
  type PresentationPatchState = {
104
+ generation?: number;
102
105
  owners: number;
103
106
  // Set at the final owner's shutdown. A wrapper that another extension has
104
107
  // buried cannot be uninstalled, so it delegates instead of outliving its
105
- // owner; a later install re-enables it.
108
+ // owner; a later compatible install re-enables it.
106
109
  disabled?: boolean;
107
110
  theme?: ThemeLike;
108
111
  cwd: string;
@@ -1086,15 +1089,26 @@ function isRecord(value: unknown): value is Record<string, unknown> {
1086
1089
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
1087
1090
  }
1088
1091
 
1089
- function defaultSubagentEmoji(args: unknown): string {
1090
- if (!isRecord(args)) return "👾";
1092
+ function subagentDisplayProfile(
1093
+ args: Record<string, unknown>,
1094
+ action: unknown,
1095
+ ): string | undefined {
1096
+ const { profile, model } = args;
1097
+ if (typeof profile !== "string") return undefined;
1098
+ // Blank model strings do not override launch profiles. Keep the existing
1099
+ // rendering of controls, unknown actions, and malformed model values.
1100
+ const launch =
1101
+ action === undefined || action === "run" || action === "interactive";
1091
1102
  if (
1092
- typeof args.profile === "string" &&
1093
- args.profile.trim() === "coder" &&
1094
- args.model === undefined
1103
+ model !== undefined &&
1104
+ (!launch || typeof model !== "string" || model.trim() !== "")
1095
1105
  )
1096
- return "🧑‍💻";
1097
- return typeof args.action === "string" &&
1106
+ return undefined;
1107
+ return profile.trim() || undefined;
1108
+ }
1109
+
1110
+ function defaultSubagentEmoji(action: unknown): string {
1111
+ return typeof action === "string" &&
1098
1112
  [
1099
1113
  "interactive",
1100
1114
  "list",
@@ -1103,15 +1117,32 @@ function defaultSubagentEmoji(args: unknown): string {
1103
1117
  "wait",
1104
1118
  "stop",
1105
1119
  "resume",
1106
- ].includes(args.action)
1107
- ? "🤖"
1108
- : "👾";
1120
+ ].includes(action)
1121
+ ? "👾"
1122
+ : "👻";
1109
1123
  }
1110
1124
 
1125
+ // Match a whole icon token, including joined emoji, flags, and keycaps.
1126
+ // ASCII digits, #, and * count only in keycap sequences.
1127
+ const SUBAGENT_EMOJI_TOKEN =
1128
+ /^(?:[#*0-9]\uFE0F?\u20E3|(?![#*0-9])\p{Emoji}[\uFE0E\uFE0F\u{E0020}-\u{E007F}]*\u200D?)+$/u;
1129
+
1111
1130
  function subagentFallbackLabel(args: unknown, summary: string): string {
1112
- const { displayName, bareName } = parseStepContent(summary);
1113
- const prefix =
1114
- displayName === bareName ? `${defaultSubagentEmoji(args)} ` : "";
1131
+ const input = isRecord(args) ? args : undefined;
1132
+ const match = /^(\S+)\s+(?=\S)/u.exec(summary);
1133
+ const icon = match?.[1] ?? "";
1134
+ const heading = match ? summary.slice(match[0].length) : "";
1135
+ const agent =
1136
+ typeof input?.agent === "string" ? sanitizeInline(input.agent).trim() : "";
1137
+ const startsWithAgent = (text: string) =>
1138
+ agent !== "" && (text === agent || text.startsWith(`${agent} `));
1139
+ // Subagents also accept configured Unicode symbols as icons. A token
1140
+ // directly before the known name can still be one of those assignments.
1141
+ const assigned = startsWithAgent(heading)
1142
+ ? /[^\x00-\x7f]/u.test(icon)
1143
+ : !startsWithAgent(summary) && SUBAGENT_EMOJI_TOKEN.test(icon);
1144
+ const action = input?.action;
1145
+ const prefix = assigned ? "" : `${defaultSubagentEmoji(action)} `;
1115
1146
  return `subagent ${prefix}${summary}`.trimEnd();
1116
1147
  }
1117
1148
 
@@ -1127,8 +1158,9 @@ type SubagentPlan = {
1127
1158
  steps: readonly [SubagentStep, ...SubagentStep[]];
1128
1159
  };
1129
1160
 
1130
- function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1131
- if (!isRecord(args)) return undefined;
1161
+ function parseSubagentArgs(
1162
+ args: Record<string, unknown>,
1163
+ ): SubagentPlan | undefined {
1132
1164
  const scope =
1133
1165
  args.agentScope === "project" || args.agentScope === "both"
1134
1166
  ? args.agentScope
@@ -1148,14 +1180,7 @@ function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1148
1180
  typeof item.agent === "string" && item.agent.trim()
1149
1181
  ? item.agent.trim()
1150
1182
  : "...",
1151
- // The subagent extension suppresses the profile badge when a model
1152
- // override is present; mirror that here.
1153
- profile:
1154
- typeof item.profile === "string" &&
1155
- item.profile.trim() &&
1156
- item.model === undefined
1157
- ? item.profile.trim()
1158
- : undefined,
1183
+ profile: subagentDisplayProfile(item, args.action),
1159
1184
  task: item.task,
1160
1185
  };
1161
1186
  };
@@ -1187,40 +1212,21 @@ function parseSubagentArgs(args: unknown): SubagentPlan | undefined {
1187
1212
  return { kind: "single", scope, steps: [single] };
1188
1213
  }
1189
1214
 
1190
- // Splits scraped plan content into the emoji-capable display name and its bare lookup name.
1191
- function parseStepContent(content: string): {
1192
- displayName: string;
1193
- bareName: string;
1194
- } {
1195
- const tokens = content.trim().split(/\s+/).filter(Boolean);
1196
- if (tokens.length === 0) return { displayName: "", bareName: "" };
1197
- const first = tokens[0]!;
1215
+ // Extract the existing emoji-capable prefix and its bare lookup name.
1216
+ function parseStepContent(
1217
+ content: string,
1218
+ ): { emoji: string; bareName: string } | undefined {
1219
+ const [first, bareName] = content.trim().split(/\s+/).filter(Boolean);
1220
+ if (!first || !bareName) return undefined;
1198
1221
  const hasEmoji = [...first].some((char) => (char.codePointAt(0) ?? 0) > 0x7f);
1199
- const nameTokens = hasEmoji && tokens.length > 1 ? 2 : 1;
1200
- const displayName = tokens.slice(0, nameTokens).join(" ");
1201
- return {
1202
- displayName,
1203
- bareName: tokens[nameTokens - 1] ?? displayName,
1204
- };
1205
- }
1206
-
1207
- // Splits a scraped "emoji name" display into its emoji prefix and bare name;
1208
- // plain names pass through with no emoji.
1209
- function splitEmojiName(
1210
- displayName: string,
1211
- bareName: string,
1212
- ): { emoji: string; name: string } {
1213
- const tokens = displayName.trim().split(/\s+/).filter(Boolean);
1214
- if (tokens.length > 1 && tokens[tokens.length - 1] === bareName) {
1215
- return { emoji: tokens.slice(0, -1).join(" "), name: bareName };
1216
- }
1217
- return { emoji: "", name: bareName };
1222
+ return hasEmoji ? { emoji: first, bareName } : undefined;
1218
1223
  }
1219
1224
 
1220
- // Agent display names (emoji + name) come from the subagent extension's own
1221
- // call component when available; args only carry the bare agent name.
1222
- function scrapeSubagentDisplayNames(
1225
+ // Assigned emojis come from the subagent extension's call component when
1226
+ // available; args only carry the bare agent name.
1227
+ function scrapeSubagentEmojis(
1223
1228
  row: ToolExecutionRow,
1229
+ kind: SubagentPlan["kind"],
1224
1230
  ): Map<string, string> {
1225
1231
  const names = new Map<string, string>();
1226
1232
  let component = row.callRendererComponent;
@@ -1230,20 +1236,21 @@ function scrapeSubagentDisplayNames(
1230
1236
  if (!component || typeof component.render !== "function") return names;
1231
1237
  try {
1232
1238
  for (const raw of component.render(120)) {
1233
- const line = sanitizeInline(stripAnsi(raw)).trim();
1239
+ const text = sanitizeInline(stripAnsi(raw));
1240
+ // Native single-call headings can wrap. The first indented line starts
1241
+ // the task preview; neither it nor its continuations carry identity.
1242
+ if (kind === "single" && text.startsWith(" ")) break;
1243
+ const line = text.trim();
1234
1244
  if (!line) continue;
1235
1245
  // Single calls carry the agent name on their "subagent <name>" heading
1236
1246
  // line; stripping the heading word (and step numbers) lets both shapes
1237
1247
  // flow through the same parse. Heading remainders without an emoji
1238
- // (e.g. "chain (2 steps)") degrade to displayName === bareName and are
1239
- // skipped by the guard below.
1248
+ // (e.g. "chain (2 steps)") are skipped.
1240
1249
  const content = line
1241
1250
  .replace(/^subagent\b\s*/, "")
1242
1251
  .replace(/^\d+\.\s*/, "");
1243
- const { displayName, bareName } = parseStepContent(content);
1244
- if (displayName && bareName && displayName !== bareName) {
1245
- names.set(bareName, displayName);
1246
- }
1252
+ const identity = parseStepContent(content);
1253
+ if (identity) names.set(identity.bareName, identity.emoji);
1247
1254
  }
1248
1255
  } catch {
1249
1256
  // Display-name scraping is cosmetic; args still carry the bare name.
@@ -1305,14 +1312,16 @@ function subagentPlanOutcome(
1305
1312
  return theme.fg("warning", "…");
1306
1313
  }
1307
1314
 
1308
- // Subagents use the collapsed rail with no separate glyph. A single call
1309
- // starts with its agent identity; a multi-step plan starts with a heading.
1315
+ // Single subagents use the agent emoji in the glyph slot. Plans leave that
1316
+ // slot empty for the heading and align each agent emoji with the slot below.
1310
1317
  // Agent identities use accent, and failures use error colors.
1311
1318
  function renderSubagentPlan(
1312
1319
  row: ToolExecutionRow,
1313
1320
  width: number,
1314
1321
  theme: ThemeLike,
1315
1322
  ): string[] | undefined {
1323
+ if (!isRecord(row.args)) return undefined;
1324
+ const { action } = row.args;
1316
1325
  const plan = parseSubagentArgs(row.args);
1317
1326
  if (!plan || width < 12) return undefined;
1318
1327
 
@@ -1320,30 +1329,29 @@ function renderSubagentPlan(
1320
1329
  const color = failed ? "error" : "muted";
1321
1330
  const nameColor = failed ? "error" : "accent";
1322
1331
  const suffix = fgCollapsed(theme, color, "…");
1323
- const displayNames = scrapeSubagentDisplayNames(row);
1332
+ const displayEmojis = scrapeSubagentEmojis(row, plan.kind);
1324
1333
  // Agent/profile/task values are model-supplied; sanitize them like every
1325
1334
  // other collapsed-row text so control bytes cannot reach the terminal.
1326
- // Identity order: emoji, then the profile and agent-name badges.
1327
1335
  const identityOf = (step: SubagentStep) => {
1328
- const displayName =
1329
- displayNames.get(step.agent) ?? sanitizeInline(step.agent);
1330
- const { emoji, name } = splitEmojiName(displayName, step.agent);
1336
+ const emoji = displayEmojis.get(step.agent);
1331
1337
  const accentPart = (text: string) => fgCollapsed(theme, nameColor, text);
1332
- const fallbackEmoji = defaultSubagentEmoji({
1333
- action: isRecord(row.args) ? row.args.action : undefined,
1334
- profile: step.profile,
1335
- });
1336
- const emojiPart = `${accentPart(emoji || fallbackEmoji)} `;
1337
- const profilePart = step.profile
1338
- ? accentPart(`[${sanitizeInline(step.profile)}]`)
1339
- : "";
1340
- return `${emojiPart}${profilePart}${accentPart(`[${sanitizeInline(name)}]`)}`;
1338
+ return {
1339
+ emoji: sanitizeInline(emoji || defaultSubagentEmoji(action)),
1340
+ label:
1341
+ (step.profile ? accentPart(`[${sanitizeInline(step.profile)}]`) : "") +
1342
+ accentPart(`[${sanitizeInline(step.agent)}]`),
1343
+ };
1341
1344
  };
1342
1345
  const detailColor = failed ? "error" : "toolOutput";
1343
1346
  const previewOf = (step: SubagentStep) =>
1344
1347
  fgCollapsed(theme, detailColor, ` ${subagentStepPreview(step.task)}`);
1345
1348
 
1346
- const marker = collapsedAnchor(theme, color, undefined);
1349
+ const firstIdentity = identityOf(plan.steps[0]);
1350
+ const marker = collapsedAnchor(
1351
+ theme,
1352
+ plan.kind === "single" ? nameColor : color,
1353
+ plan.kind === "single" ? firstIdentity.emoji : undefined,
1354
+ );
1347
1355
  const budget = Math.max(1, width - visibleWidth(marker));
1348
1356
  const progress = subagentProgressText(row);
1349
1357
  const outcome = subagentPlanOutcome(row, failed, progress, budget, theme);
@@ -1355,7 +1363,7 @@ function renderSubagentPlan(
1355
1363
 
1356
1364
  if (plan.kind === "single") {
1357
1365
  const step = plan.steps[0];
1358
- return [headline(identityOf(step) + previewOf(step))];
1366
+ return [headline(firstIdentity.label + previewOf(step))];
1359
1367
  }
1360
1368
 
1361
1369
  const kindLabel =
@@ -1364,10 +1372,15 @@ function renderSubagentPlan(
1364
1372
  : `parallel (${plan.steps.length} tasks)`;
1365
1373
  const lines = [
1366
1374
  headline(
1367
- fgCollapsed(theme, failed ? "error" : "toolTitle", "subagent", true) +
1375
+ " " +
1376
+ fgCollapsed(theme, failed ? "error" : "toolTitle", "subagents:", true) +
1368
1377
  " " +
1369
1378
  fgCollapsed(theme, failed ? "error" : "toolOutput", kindLabel) +
1370
- fgCollapsed(theme, failed ? "error" : "toolOutput", ` [${plan.scope}]`),
1379
+ fgCollapsed(
1380
+ theme,
1381
+ failed ? "error" : "toolOutput",
1382
+ ` [${plan.scope} level]`,
1383
+ ),
1371
1384
  ),
1372
1385
  ];
1373
1386
  const stepIndent = " ".repeat(
@@ -1376,11 +1389,13 @@ function renderSubagentPlan(
1376
1389
  const shown = plan.steps.slice(0, 3);
1377
1390
  for (let index = 0; index < shown.length; index++) {
1378
1391
  const step = shown[index]!;
1392
+ const identity = identityOf(step);
1379
1393
  const number =
1380
1394
  plan.kind === "chain"
1381
1395
  ? `${fgCollapsed(theme, color, `${index + 1}.`)} `
1382
1396
  : "";
1383
- lines.push(`${stepIndent}${number}${identityOf(step)}${previewOf(step)}`);
1397
+ const stepAnchor = collapsedAnchor(theme, nameColor, identity.emoji);
1398
+ lines.push(`${stepAnchor}${number}${identity.label}${previewOf(step)}`);
1384
1399
  }
1385
1400
  if (plan.steps.length > shown.length) {
1386
1401
  lines.push(
@@ -1732,12 +1747,16 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1732
1747
  if (!proto) return undefined;
1733
1748
 
1734
1749
  const existing = proto[PRESENTATION_PATCHED];
1735
- if (existing) {
1750
+ const retired =
1751
+ existing?.disabled && existing.generation !== PRESENTATION_GENERATION
1752
+ ? existing
1753
+ : undefined;
1754
+ if (existing && !retired) {
1736
1755
  existing.owners++;
1737
1756
  existing.disabled = false;
1738
1757
  return existing;
1739
1758
  }
1740
- const legacy = proto[LEGACY_PRESENTATION_PATCHED];
1759
+ const legacy = !existing && proto[LEGACY_PRESENTATION_PATCHED];
1741
1760
  if (legacy) {
1742
1761
  proto.render = legacy.originalRender;
1743
1762
  proto.updateDisplay = legacy.originalUpdateDisplay;
@@ -1748,17 +1767,25 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1748
1767
  )
1749
1768
  return undefined;
1750
1769
 
1770
+ const { render, updateDisplay } = proto;
1771
+ const buriedRender = retired && render !== retired.patchedRender;
1772
+ const buriedUpdate =
1773
+ retired && updateDisplay !== retired.patchedUpdateDisplay;
1774
+ const retiredMouse = retired?.originalHandleMouse;
1775
+
1751
1776
  const state: PresentationPatchState = {
1777
+ generation: PRESENTATION_GENERATION,
1752
1778
  owners: 1,
1753
1779
  cwd: process.cwd(),
1754
1780
  promptPaths: new Set(),
1755
- collapseParallel: envEnabled(COLLAPSE_PARALLEL_ENV, true),
1756
- expandedTools: envToolNames(EXPANDED_TOOLS_ENV),
1781
+ collapseParallel:
1782
+ retired?.collapseParallel ?? envEnabled(COLLAPSE_PARALLEL_ENV, true),
1783
+ expandedTools: retired?.expandedTools ?? envToolNames(EXPANDED_TOOLS_ENV),
1757
1784
  groupCache: new WeakMap(),
1758
1785
  collapsedCache: new WeakMap(),
1759
1786
  rowVersions: new WeakMap(),
1760
- originalRender: proto.render,
1761
- originalUpdateDisplay: proto.updateDisplay,
1787
+ originalRender: retired?.originalRender ?? render,
1788
+ originalUpdateDisplay: retired?.originalUpdateDisplay ?? updateDisplay,
1762
1789
  };
1763
1790
  const patchedUpdateDisplay = function updateDisplayWithToolPresentation(
1764
1791
  this: ToolExecutionRow,
@@ -1792,8 +1819,9 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1792
1819
  let patchedHandleMouse:
1793
1820
  | ((this: ToolExecutionRow, event: unknown) => unknown)
1794
1821
  | undefined;
1795
- if (typeof proto.handleMouse === "function") {
1796
- state.originalHandleMouse = proto.handleMouse;
1822
+ const originalHandleMouse = retiredMouse ?? proto.handleMouse;
1823
+ if (typeof originalHandleMouse === "function") {
1824
+ state.originalHandleMouse = originalHandleMouse;
1797
1825
  patchedHandleMouse = function handleMouseWithCollapsedToggle(
1798
1826
  this: ToolExecutionRow,
1799
1827
  event: unknown,
@@ -1815,7 +1843,7 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1815
1843
  }
1816
1844
  return state.originalHandleMouse?.call(this, event);
1817
1845
  };
1818
- proto.handleMouse = patchedHandleMouse;
1846
+ if (!retiredMouse) proto.handleMouse = patchedHandleMouse;
1819
1847
  }
1820
1848
  const patchedRender = function renderWithToolPresentation(
1821
1849
  this: ToolExecutionRow,
@@ -1895,15 +1923,24 @@ function installPresentationPatch(): PresentationPatchState | undefined {
1895
1923
  try {
1896
1924
  state.patchedUpdateDisplay = patchedUpdateDisplay;
1897
1925
  state.patchedRender = patchedRender;
1898
- proto.updateDisplay = patchedUpdateDisplay;
1899
- proto.render = patchedRender;
1926
+ if (!buriedUpdate) proto.updateDisplay = patchedUpdateDisplay;
1927
+ if (!buriedRender) proto.render = patchedRender;
1900
1928
  Object.defineProperty(proto, PRESENTATION_PATCHED, {
1901
1929
  configurable: true,
1902
1930
  value: state,
1903
1931
  });
1932
+ if (retired) {
1933
+ // Keep foreign wrappers on the outside, including on cached renders.
1934
+ // The retired closures stay disabled and only forward to these delegates.
1935
+ if (buriedRender) retired.originalRender = patchedRender;
1936
+ if (buriedUpdate) retired.originalUpdateDisplay = patchedUpdateDisplay;
1937
+ if (retiredMouse && patchedHandleMouse) {
1938
+ retired.originalHandleMouse = patchedHandleMouse;
1939
+ }
1940
+ }
1904
1941
  } catch {
1905
- proto.updateDisplay = state.originalUpdateDisplay;
1906
- proto.render = state.originalRender;
1942
+ if (!buriedUpdate) proto.updateDisplay = updateDisplay;
1943
+ if (!buriedRender) proto.render = render;
1907
1944
  return undefined;
1908
1945
  }
1909
1946
  return state;
@@ -158,7 +158,7 @@ export function renderRailedBlockLines(
158
158
  const margin = " ".repeat(inset);
159
159
  const leftPad = " ".repeat(padding.left);
160
160
  const rightPad = " ".repeat(padding.right);
161
- const contentWidth = Math.max(1, bodyWidth - padding.left - padding.right);
161
+ const contentWidth = promptBlockContentWidth(width, inset, padding);
162
162
  const surfaceBg = promptSurfaceBg(theme);
163
163
  return lines.map((line) => {
164
164
  const { controls, content } = splitLeadingSemanticControls(line);
@@ -16,7 +16,7 @@ import { sanitizeInline } from "./sanitize.ts";
16
16
  // any particular question-tool implementation is needed.
17
17
 
18
18
  type QuestionTheme = PromptShellTheme & {
19
- fg(color: string, text: string): string;
19
+ bold?(text: string): string;
20
20
  italic?(text: string): string;
21
21
  };
22
22
 
@@ -40,7 +40,7 @@ type AnswerEntry = {
40
40
 
41
41
  type QuestionLine =
42
42
  | { kind: "question"; text: string }
43
- | { kind: "answer"; text: string }
43
+ | { kind: "answer"; text: string | undefined }
44
44
  | { kind: "status"; text: string; tone: "muted" | "warning" }
45
45
  // A painted blank body row; the shell gives it the prompt surface.
46
46
  | { kind: "spacer" };
@@ -196,7 +196,7 @@ function questionLines(
196
196
  const groups: QuestionLine[][] = pairs.map((pair) => {
197
197
  const group: QuestionLine[] = [{ kind: "question", text: pair.question }];
198
198
  if (!pending && !declined) {
199
- group.push({ kind: "answer", text: pair.answer ?? NO_ANSWER_TEXT });
199
+ group.push({ kind: "answer", text: pair.answer });
200
200
  }
201
201
  return group;
202
202
  });
@@ -228,18 +228,21 @@ function fg(theme: QuestionTheme, token: string, text: string): string {
228
228
  }
229
229
  }
230
230
 
231
- // The question is the model's text read inside a user-input shell, so it takes
232
- // the quotation's italics; the answer is the user's own words and stays upright.
233
- // A theme without italics simply renders the question plainly.
234
- function italics(theme: QuestionTheme, text: string): string {
235
- if (text === "" || typeof theme.italic !== "function") return text;
231
+ function emphasize(
232
+ theme: QuestionTheme,
233
+ style: "bold" | "italic",
234
+ text: string,
235
+ ): string {
236
+ if (text === "" || typeof theme[style] !== "function") return text;
236
237
  try {
237
- return theme.italic(text);
238
+ return theme[style](text);
238
239
  } catch {
239
240
  return text;
240
241
  }
241
242
  }
242
243
 
244
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
245
+
243
246
  // Plain-text word wrap with a hanging indent, so a wrapped question stays
244
247
  // visually attached to its `> ` prefix. Wrapping before styling keeps the
245
248
  // width math exact and lets the shell's own fit pass stay a no-op.
@@ -261,15 +264,24 @@ function wrapPlain(text: string, width: number): string[] {
261
264
  return;
262
265
  }
263
266
  if (current !== "") lines.push(current);
264
- // A single token wider than the line is hard-split rather than truncated.
265
- let rest = word;
266
- while (visibleWidth(rest) > max) {
267
- let cut = rest.length;
268
- while (cut > 1 && visibleWidth(rest.slice(0, cut)) > max) cut--;
269
- lines.push(rest.slice(0, cut));
270
- rest = rest.slice(cut);
267
+ if (visibleWidth(word) <= max) {
268
+ current = word;
269
+ return;
270
+ }
271
+
272
+ current = "";
273
+ let columns = 0;
274
+ for (const { segment } of graphemes.segment(word)) {
275
+ const segmentWidth = visibleWidth(segment);
276
+ // Let the shell clip a grapheme wider than the whole line.
277
+ if (current !== "" && columns + segmentWidth > max) {
278
+ lines.push(current);
279
+ current = "";
280
+ columns = 0;
281
+ }
282
+ current += segment;
283
+ columns += segmentWidth;
271
284
  }
272
- current = rest;
273
285
  };
274
286
  for (const word of words) push(word);
275
287
  if (current !== "") lines.push(current);
@@ -288,22 +300,25 @@ function styleLine(
288
300
  : line.kind === "answer"
289
301
  ? ANSWER_PREFIX
290
302
  : "";
291
- const prefixToken = line.kind === "question" ? "borderAccent" : "muted";
292
- const textToken =
293
- line.kind === "question"
294
- ? "text"
295
- : line.kind === "answer"
296
- ? "userMessageText"
297
- : line.tone;
298
- const hang = " ".repeat(visibleWidth(prefix));
299
- const body = wrapPlain(line.text, Math.max(1, width - visibleWidth(prefix)));
300
- return body.map(
301
- (piece, index) =>
302
- fg(theme, prefixToken, index === 0 ? prefix : hang) +
303
- (line.kind === "question"
304
- ? italics(theme, fg(theme, textToken, piece))
305
- : fg(theme, textToken, piece)),
306
- );
303
+ const text =
304
+ line.kind === "answer" ? (line.text ?? NO_ANSWER_TEXT) : line.text;
305
+ const prefixWidth = visibleWidth(prefix);
306
+ const hang = " ".repeat(prefixWidth);
307
+ const body = wrapPlain(text, Math.max(1, width - prefixWidth));
308
+ return body.map((piece, index) => {
309
+ const leading = index === 0 ? prefix : hang;
310
+ switch (line.kind) {
311
+ case "question":
312
+ return fg(theme, "muted", emphasize(theme, "italic", leading + piece));
313
+ case "answer": {
314
+ const reply =
315
+ line.text === undefined ? piece : emphasize(theme, "bold", piece);
316
+ return fg(theme, "userMessageText", leading + reply);
317
+ }
318
+ case "status":
319
+ return fg(theme, line.tone, piece);
320
+ }
321
+ });
307
322
  }
308
323
 
309
324
  /**