@xingular/harness 1.3.1-unstable.3 → 1.3.1-unstable.4

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.
Files changed (77) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/cli.js +2513 -1296
  3. package/dist/sdk/cli.js +2 -0
  4. package/dist/sdk/commands/registry.d.ts +15 -0
  5. package/dist/sdk/commands/registry.js +2 -0
  6. package/dist/sdk/remote/addresses.d.ts +19 -0
  7. package/dist/sdk/remote/addresses.js +52 -0
  8. package/dist/sdk/remote/pairing.d.ts +59 -0
  9. package/dist/sdk/remote/pairing.js +160 -0
  10. package/dist/sdk/remote/seal.d.ts +28 -0
  11. package/dist/sdk/remote/seal.js +84 -0
  12. package/dist/sdk/remote/server.d.ts +28 -0
  13. package/dist/sdk/remote/server.js +158 -0
  14. package/dist/sdk/remote/service.d.ts +125 -0
  15. package/dist/sdk/remote/service.js +330 -0
  16. package/dist/sdk/remote/webClient.d.ts +4 -0
  17. package/dist/sdk/remote/webClient.js +444 -0
  18. package/dist/sdk/sessions/planMode.d.ts +26 -1
  19. package/dist/sdk/sessions/planMode.js +48 -1
  20. package/dist/sdk/sessions/runner.d.ts +2 -0
  21. package/dist/sdk/sessions/runner.js +17 -2
  22. package/dist/sdk/sessions/sessions.js +1 -0
  23. package/dist/sdk/sessions/workSlice.d.ts +5 -9
  24. package/dist/sdk/sessions/workSlice.js +8 -149
  25. package/dist/sdk/terminal/client.d.ts +2 -0
  26. package/dist/sdk/terminal/client.js +2 -0
  27. package/dist/sdk/terminal/controller.d.ts +13 -0
  28. package/dist/sdk/terminal/controller.js +56 -2
  29. package/dist/sdk/terminal/piExtension.js +71 -3
  30. package/dist/sdk/terminal/stallWatch.d.ts +13 -0
  31. package/dist/sdk/terminal/stallWatch.js +16 -0
  32. package/dist/sdk/terminal/standalone.d.ts +2 -0
  33. package/dist/sdk/terminal/standalone.js +9 -2
  34. package/dist/sdk/terminal/terminals.d.ts +12 -0
  35. package/dist/sdk/terminal/terminals.js +87 -2
  36. package/dist/sdk/terminal/tui/commandPages.d.ts +4 -1
  37. package/dist/sdk/terminal/tui/commandPages.js +12 -0
  38. package/dist/sdk/terminal/tui/commands.d.ts +2 -0
  39. package/dist/sdk/terminal/tui/commands.js +18 -1
  40. package/dist/sdk/terminal/tui/markdown.d.ts +16 -0
  41. package/dist/sdk/terminal/tui/markdown.js +55 -0
  42. package/dist/sdk/terminal/tui/pages/contextPage.d.ts +8 -0
  43. package/dist/sdk/terminal/tui/pages/contextPage.js +130 -39
  44. package/dist/sdk/terminal/tui/pages/remoteControlPage.d.ts +32 -0
  45. package/dist/sdk/terminal/tui/pages/remoteControlPage.js +170 -0
  46. package/dist/sdk/terminal/tui/qr.d.ts +4 -0
  47. package/dist/sdk/terminal/tui/qr.js +35 -0
  48. package/dist/sdk/terminal/tui/sideQuestion.d.ts +1 -0
  49. package/dist/sdk/terminal/tui/sideQuestion.js +8 -3
  50. package/dist/sdk/terminal/tui/status.d.ts +6 -0
  51. package/dist/sdk/terminal/tui/status.js +15 -1
  52. package/dist/sdk/terminal/tui/theme.d.ts +9 -0
  53. package/dist/sdk/terminal/tui/theme.js +9 -0
  54. package/dist/terminal-opentui.js +959 -174
  55. package/dist/terminal-pi.js +114 -116
  56. package/docs/architecture/02-sessions-and-runs.md +46 -22
  57. package/docs/architecture/04-prompt.md +10 -0
  58. package/docs/architecture/07-tools-and-gate.md +3 -1
  59. package/docs/architecture/10-server-protocol.md +24 -0
  60. package/docs/architecture/11-terminal.md +40 -8
  61. package/docs/architecture/12-storage.md +5 -2
  62. package/docs/architecture/14-surfaces-and-parity.md +4 -0
  63. package/docs/architecture/15-remote-control.md +118 -0
  64. package/docs/architecture/README.md +2 -0
  65. package/docs/architecture/proposals/PROP-0049-context-attribution.md +28 -1
  66. package/docs/architecture/proposals/README.md +2 -2
  67. package/docs/decisions/ADR-0039-progress-aware-stall-guards.md +4 -0
  68. package/docs/decisions/ADR-0053-no-repeated-work-guard.md +45 -0
  69. package/docs/decisions/ADR-0054-terminal-reply-heartbeat-and-stall.md +52 -0
  70. package/docs/decisions/ADR-0055-plan-output-repair.md +51 -0
  71. package/docs/decisions/ADR-0056-remote-control.md +53 -0
  72. package/docs/decisions/ADR-0057-structured-plan-outcomes.md +39 -0
  73. package/docs/decisions/ADR-0058-ask-user-only-plan-clarification.md +36 -0
  74. package/docs/parity.md +8 -4
  75. package/docs/releases/1.3.1-unstable.4.md +56 -0
  76. package/docs/terminal-tui.md +15 -3
  77. package/package.json +3 -1
@@ -20,12 +20,13 @@ import {
20
20
  initTheme,
21
21
  resizeImage
22
22
  } from "@earendil-works/pi-coding-agent";
23
- import { matchesKey as matchesKey19 } from "@earendil-works/pi-tui";
23
+ import { matchesKey as matchesKey20 } from "@earendil-works/pi-tui";
24
24
 
25
25
  // src/terminal/client.ts
26
26
  import { createConnection } from "net";
27
27
  var SOCKET_ENV = "XINGULAR_HARNESS_SOCKET";
28
28
  var TOKEN_ENV = "XINGULAR_HARNESS_TOKEN";
29
+ var REMOTE_CONTROL_ENV = "XINGULAR_HARNESS_REMOTE_CONTROL";
29
30
 
30
31
  class SocketError extends Error {
31
32
  code;
@@ -370,6 +371,7 @@ var CORE_COMMANDS = [
370
371
  { name: "session", aliases: ["resume"], args: "[path]", description: "Choose a saved session in this account and folder", group: "Session", kind: "session" },
371
372
  { name: "history", aliases: ["tree"], description: "Navigate branches in the current session", group: "Session", kind: "session", methods: ["sessions.tree", "sessions.navigate"] },
372
373
  { name: "fork", description: "Fork from an earlier message", group: "Session", kind: "session", methods: ["sessions.tree", "sessions.fork"] },
374
+ { name: "remote-control", aliases: ["rc"], args: "[off|tailscale|lan]", description: "Continue this session from your phone or iPad", group: "Session", kind: "page", methods: ["terminal.remoteControl.start", "terminal.remoteControl.stop", "terminal.remoteControl.status"] },
373
375
  { name: "clone", description: "Clone this branch into a new session", group: "Session", kind: "session", methods: ["sessions.clone"] },
374
376
  { name: "model", args: "[search]", description: "Choose the model", group: "Model", kind: "session", methods: ["accounts.models"] },
375
377
  { name: "effort", args: "[level]", description: "Choose the thinking effort", group: "Model", kind: "session" },
@@ -397,6 +399,7 @@ var CORE_COMMANDS = [
397
399
  { name: "subagents", description: "Watch current subagent tasks and activity", group: "Harness", kind: "page" },
398
400
  { name: "agents", description: "Browse and edit agent profiles", group: "Harness", kind: "page", methods: ["agents.list"] },
399
401
  { name: "log", description: "Harness diagnostics and this conversation's run events", group: "Inspect", kind: "page" },
402
+ { name: "context", args: "[growth]", description: "What the latest request was made of, and where the rest of the window went", group: "Inspect", kind: "page", methods: ["context.attribution"] },
400
403
  { name: "hotkeys", description: "Keyboard controls", group: "Core", kind: "local" },
401
404
  { name: "quit", description: "Restore the terminal and exit", group: "Core", kind: "local" }
402
405
  ];
@@ -1757,9 +1760,6 @@ function askUserTool(run) {
1757
1760
  };
1758
1761
  }
1759
1762
 
1760
- // src/sessions/workSlice.ts
1761
- import { createHash } from "crypto";
1762
-
1763
1763
  // src/sessions/runStore.ts
1764
1764
  import { appendFileSync, copyFileSync as copyFileSync2, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "fs";
1765
1765
  import { join as join7 } from "path";
@@ -2076,94 +2076,24 @@ function sliceLimitReached(policy, state, now = Date.now()) {
2076
2076
  return null;
2077
2077
  }
2078
2078
  var HANDOFF_TOOLS = new Set(["checkpoint_write", "session_name"]);
2079
- var POLLING_TOOLS = new Set(["wait_subagents", "subagents.list", "subagents.status"]);
2080
- function looksLikeCheck(command) {
2081
- return /\b(test|tests|typecheck|tsc|vitest|jest|cargo|check:|prove|lint|ci|build)\b/u.test(command);
2082
- }
2083
- function canonical(value, depth = 0) {
2084
- if (depth > 8)
2085
- return "\u2026";
2086
- if (value === null || typeof value !== "object")
2087
- return JSON.stringify(value) ?? "null";
2088
- if (Array.isArray(value))
2089
- return `[${value.map((item) => canonical(item, depth + 1)).join(",")}]`;
2090
- const entries = Object.entries(value).filter(([, item]) => item !== undefined);
2091
- entries.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
2092
- return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, depth + 1)}`).join(",")}}`;
2093
- }
2094
- var signature = (name, input) => `${name}\x00${createHash("sha256").update(canonical(input ?? null)).digest("hex")}`;
2095
2079
  var clip2 = (value, limit) => value.length <= limit ? value : `${value.slice(0, limit - 1)}\u2026`;
2096
2080
  function handoffRequest(limit, state, checkpointAvailable = true) {
2097
2081
  const handoff = checkpointAvailable ? "Call checkpoint_write now with what is done, the single next step, anything blocking, the files you touched and the checks that matter. Then tell the user in a few lines where you stopped." : "Stop using tools and return a concise partial research report with findings, blockers and the next useful research step. The Harness records an evidence-derived checkpoint.";
2098
2082
  return clip2(`This reply reached its work-slice limit (${limit}; step ${state.steps}). ${handoff} Do not call other tools.`, 600);
2099
2083
  }
2100
- function stalledNote(reason, checkpointAvailable = true) {
2101
- const handoff = checkpointAvailable ? "Choose a different approach, read what the earlier attempt returned, or call checkpoint_write with the blocker so the next slice can decide." : "Do not use more tools. Return concise findings and blockers in your final response; the Harness records an evidence-derived checkpoint.";
2102
- return clip2(`You are repeating work: ${reason}. Do not repeat it. ${handoff}`, 600);
2103
- }
2104
2084
  function workSliceGuard(options) {
2105
2085
  const { policy, state } = options;
2106
- const calls = new Map;
2107
- const checkCalls = new Set;
2108
- const edits = new Map;
2109
- const failures = new Map;
2110
- let nudged = false;
2111
2086
  const checkpointAvailable = () => typeof options.checkpointAvailable === "function" ? options.checkpointAvailable() : options.checkpointAvailable !== false;
2112
- const resetRepetition = () => {
2113
- calls.clear();
2114
- checkCalls.clear();
2115
- edits.clear();
2116
- failures.clear();
2117
- nudged = false;
2118
- };
2119
2087
  const end = (kind, limit) => {
2120
2088
  state.endedBy = kind;
2121
2089
  state.endedByLimit = limit;
2122
2090
  options.onEnd?.(kind, limit);
2123
2091
  const canCheckpoint = checkpointAvailable();
2124
- const reason = kind === "stuck" ? stalledNote(limit, canCheckpoint) : kind === "compaction-thrash" ? handoffRequest("three context compactions in one reply", state, canCheckpoint) : handoffRequest(limit, state, canCheckpoint);
2092
+ const reason = kind === "compaction-thrash" ? handoffRequest("three context compactions in one reply", state, canCheckpoint) : handoffRequest(limit, state, canCheckpoint);
2125
2093
  return { block: true, terminate: true, reason };
2126
2094
  };
2127
- const nudge = (reason) => {
2128
- if (nudged)
2129
- return end("stuck", reason);
2130
- nudged = true;
2131
- const canCheckpoint = checkpointAvailable();
2132
- if (!canCheckpoint) {
2133
- state.endedBy = "stuck";
2134
- state.endedByLimit = reason;
2135
- }
2136
- return { block: true, reason: stalledNote(reason, canCheckpoint) };
2137
- };
2138
- const repeated = (name, input) => {
2139
- if (POLLING_TOOLS.has(name))
2140
- return null;
2141
- const key = signature(name, input);
2142
- if (name === "bash") {
2143
- const command = input && typeof input === "object" ? String(input.command ?? "") : "";
2144
- if (command && looksLikeCheck(command))
2145
- checkCalls.add(key);
2146
- }
2147
- const count = (calls.get(key) ?? 0) + 1;
2148
- calls.set(key, count);
2149
- if (count < 3)
2150
- return null;
2151
- return name === "bash" ? `the same Bash command ${count} times (steps ending at ${state.steps})` : `the same ${name} call ${count} times (steps ending at ${state.steps})`;
2152
- };
2153
- const failing = (name, input) => {
2154
- if (name !== "bash")
2155
- return null;
2156
- const command = input && typeof input === "object" ? String(input.command ?? "") : "";
2157
- if (!command || !looksLikeCheck(command))
2158
- return null;
2159
- const count = failures.get(command) ?? 0;
2160
- return count >= 2 ? `the check ${command} failed ${count} times` : null;
2161
- };
2162
2095
  return (pi) => {
2163
- pi.on("agent_start", () => {
2164
- resetSliceState(state);
2165
- resetRepetition();
2166
- });
2096
+ pi.on("agent_start", () => resetSliceState(state));
2167
2097
  pi.on("message_end", (event) => {
2168
2098
  const usage = event.message.usage;
2169
2099
  if (event.message.role !== "assistant" || !usage)
@@ -2171,35 +2101,8 @@ function workSliceGuard(options) {
2171
2101
  state.tokens += (usage.input ?? 0) + (usage.cacheWrite ?? 0) + (usage.output ?? 0);
2172
2102
  });
2173
2103
  pi.on("tool_result", (event) => {
2174
- if (event.toolName === "checkpoint_write" && !event.isError) {
2104
+ if (event.toolName === "checkpoint_write" && !event.isError)
2175
2105
  state.checkpointWritten = true;
2176
- nudged = false;
2177
- }
2178
- if ((event.toolName === "edit" || event.toolName === "write") && event.isError === false) {
2179
- const path = event.input && typeof event.input === "object" ? String(event.input.path ?? "") : "";
2180
- if (path) {
2181
- edits.set(path, (edits.get(path) ?? 0) + 1);
2182
- failures.clear();
2183
- for (const key of checkCalls)
2184
- calls.delete(key);
2185
- checkCalls.clear();
2186
- nudged = false;
2187
- }
2188
- }
2189
- if (event.toolName !== "bash")
2190
- return;
2191
- const command = event.input && typeof event.input === "object" ? String(event.input.command ?? "") : "";
2192
- if (!command || !looksLikeCheck(command))
2193
- return;
2194
- if (event.isError) {
2195
- failures.set(command, (failures.get(command) ?? 0) + 1);
2196
- return;
2197
- }
2198
- failures.delete(command);
2199
- edits.clear();
2200
- calls.clear();
2201
- checkCalls.clear();
2202
- nudged = false;
2203
2106
  });
2204
2107
  pi.on("tool_call", (event) => {
2205
2108
  const name = event.toolName;
@@ -2226,25 +2129,6 @@ function workSliceGuard(options) {
2226
2129
  state.refusedAt ??= state.steps;
2227
2130
  return handoff ? undefined : { block: true, reason: handoffRequest(limit, state, canCheckpoint) };
2228
2131
  }
2229
- if (handoff)
2230
- return;
2231
- if (name === "todo_write")
2232
- return;
2233
- const edit = name === "edit" || name === "write";
2234
- const path = edit && event.input && typeof event.input === "object" ? String(event.input.path ?? "") : "";
2235
- if (edit && path) {
2236
- const count = edits.get(path) ?? 0;
2237
- if (count >= 4) {
2238
- const reason = `${path} was edited ${count} times with no passing check between`;
2239
- return nudge(reason);
2240
- }
2241
- }
2242
- const repeat = repeated(name, event.input);
2243
- const failure = failing(name, event.input);
2244
- const reason = repeat ?? failure;
2245
- if (!reason)
2246
- return;
2247
- return nudge(reason);
2248
2132
  });
2249
2133
  };
2250
2134
  }
@@ -5960,7 +5844,7 @@ function readTool2(env, context, params) {
5960
5844
  }
5961
5845
 
5962
5846
  // src/plugins/proposals.ts
5963
- import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
5847
+ import { createHash, randomUUID as randomUUID2 } from "crypto";
5964
5848
  import { dirname as dirname5, join as join15 } from "path";
5965
5849
 
5966
5850
  // src/pi/runtime.ts
@@ -6106,7 +5990,7 @@ function validate2(name, description, input) {
6106
5990
  throw invalid("A file cannot also be a directory.");
6107
5991
  const manifest = `${JSON.stringify({ name, version: "1.0.0", description }, null, 2)}
6108
5992
  `;
6109
- const hash = createHash2("sha256").update(JSON.stringify([name, description, manifest, Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)])).digest("hex");
5993
+ const hash = createHash("sha256").update(JSON.stringify([name, description, manifest, Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)])).digest("hex");
6110
5994
  return { name, description, files, manifest, hash };
6111
5995
  }
6112
5996
  function create2(root, name, description, files) {
@@ -13199,6 +13083,10 @@ import { Theme } from "@earendil-works/pi-coding-agent";
13199
13083
  * SOFTWARE.
13200
13084
  */
13201
13085
  var orange = { dark: "#ffb347", light: "#9a7326" };
13086
+ var SERIES_COLORS = {
13087
+ dark: ["#3987e5", "#d95926", "#199e70", "#c98500"],
13088
+ light: ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
13089
+ };
13202
13090
  var TITANIUM = {
13203
13091
  brushedTitanium: "#151820",
13204
13092
  darkTitanium: "#0f1216",
@@ -14120,6 +14008,653 @@ class UsagePage {
14120
14008
  }
14121
14009
  }
14122
14010
 
14011
+ // src/terminal/tui/pages/contextPage.ts
14012
+ import { matchesKey as matchesKey18, parseColor as parseColor4, truncateToWidth as truncateToWidth22, visibleWidth as visibleWidth14, wrapTextWithAnsi as wrapTextWithAnsi14 } from "@earendil-works/pi-tui";
14013
+ var BARS2 = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
14014
+ var CHARS = 4;
14015
+ var OWNER_TITLES = {
14016
+ foundation: "Foundation \xB7 harness",
14017
+ variant: "Variant",
14018
+ application: "Your application",
14019
+ conversation: "Conversation",
14020
+ reserved: "Reserved and free"
14021
+ };
14022
+ var OWNER_ORDER = ["foundation", "variant", "application", "conversation", "reserved"];
14023
+ var KIND_ORDER = ["System prompt", "Tools", "Memory", "Skills", "Messages", "Reserved"];
14024
+ function kindOf(row) {
14025
+ if (row.group === "reserved")
14026
+ return "Reserved";
14027
+ if (row.id === "messages" || row.id === "context-update" || row.id === "references" || row.id === "required-skills" || row.id === "wiki" || row.id === "session-state")
14028
+ return "Messages";
14029
+ if (row.id === "memory")
14030
+ return "Memory";
14031
+ if (row.id === "skills")
14032
+ return "Skills";
14033
+ if (row.id === "tools" || row.id === "tools-harness" || row.id === "tools-application" || row.id === "tool-guidance")
14034
+ return "Tools";
14035
+ return "System prompt";
14036
+ }
14037
+ function count3(value) {
14038
+ if (!Number.isFinite(value) || value <= 0)
14039
+ return "0";
14040
+ if (value >= 1e6)
14041
+ return `${(value / 1e6).toFixed(value % 1e6 === 0 ? 0 : 1)}M`;
14042
+ if (value >= 1000)
14043
+ return `${(value / 1000).toFixed(1)}K`;
14044
+ return String(Math.round(value));
14045
+ }
14046
+ function percent(value) {
14047
+ return value === null ? "?" : `${value.toFixed(1)}%`;
14048
+ }
14049
+ function tone(share) {
14050
+ if (share === null)
14051
+ return "dim";
14052
+ if (share >= 95)
14053
+ return "error";
14054
+ if (share >= 80)
14055
+ return "warning";
14056
+ return "success";
14057
+ }
14058
+ var SERIES_LABELS = {
14059
+ foundation: "foundation",
14060
+ variant: "variant",
14061
+ application: "your app",
14062
+ conversation: "conversation",
14063
+ reserved: "reserved"
14064
+ };
14065
+ function seriesColor(theme, index) {
14066
+ const palette = theme.appearance === "light" ? SERIES_COLORS.light : SERIES_COLORS.dark;
14067
+ return palette[index] ?? palette[palette.length - 1];
14068
+ }
14069
+ function allocateCells(values, total) {
14070
+ const cells = Math.max(0, Math.floor(total));
14071
+ const sum = values.reduce((acc, value) => acc + Math.max(0, value), 0);
14072
+ if (sum <= 0 || cells <= 0)
14073
+ return values.map(() => 0);
14074
+ const present = values.map((value, index) => ({ value: Math.max(0, value), index })).filter((entry) => entry.value > 0);
14075
+ if (cells < present.length) {
14076
+ const out = values.map(() => 0);
14077
+ for (const entry of [...present].sort((left, right) => right.value - left.value).slice(0, cells))
14078
+ out[entry.index] = 1;
14079
+ return out;
14080
+ }
14081
+ const exact = values.map((value) => Math.max(0, value) / sum * cells);
14082
+ const out = exact.map((value) => Math.floor(value));
14083
+ let left = cells - out.reduce((acc, value) => acc + value, 0);
14084
+ for (const entry of exact.map((value, index) => ({ rest: value - Math.floor(value), index })).sort((left_, right) => right.rest - left_.rest)) {
14085
+ if (left <= 0)
14086
+ break;
14087
+ out[entry.index] = (out[entry.index] ?? 0) + 1;
14088
+ left -= 1;
14089
+ }
14090
+ for (const entry of present) {
14091
+ if ((out[entry.index] ?? 0) > 0)
14092
+ continue;
14093
+ const donor = out.map((value, index) => ({ value, index })).filter((candidate) => candidate.index !== entry.index && candidate.value > 1).sort((a, b) => b.value - a.value)[0];
14094
+ if (!donor)
14095
+ break;
14096
+ out[donor.index] = (out[donor.index] ?? 0) - 1;
14097
+ out[entry.index] = 1;
14098
+ }
14099
+ return out;
14100
+ }
14101
+ function contextBar(data, width, theme) {
14102
+ const room = Math.max(1, width - 2);
14103
+ const parts = OWNER_ORDER.slice(0, 4).map((group, index) => ({ group, tokens: data.totals[group], color: seriesColor(theme, index) })).filter((part) => part.tokens > 0);
14104
+ const window = data.window;
14105
+ const share = window === null || window <= 0 ? 100 : Math.min(100, data.used / window * 100);
14106
+ const filled = Math.max(0, Math.min(room, Math.round(share / 100 * room)));
14107
+ const cells = allocateCells(parts.map((part) => part.tokens), filled);
14108
+ const runs = parts.flatMap((part, index) => (cells[index] ?? 0) > 0 ? [{ text: "\u2588".repeat(cells[index]), color: part.color }] : []);
14109
+ const trackCells = Math.max(0, room - filled);
14110
+ const reserve = data.compaction?.reserveTokens ?? null;
14111
+ const markerAt = reserve !== null && window !== null && window > 0 ? Math.round((data.used + reserve) / window * room) : null;
14112
+ const inTrack = markerAt !== null && markerAt >= filled && markerAt < room ? markerAt - filled : null;
14113
+ const bar = "[" + runs.map((run) => theme.style(run.text, { fg: parseColor4(run.color) })).join("") + (trackCells > 0 ? theme.fg("dim", "\u2591".repeat(inTrack ?? trackCells)) + (inTrack === null ? "" : theme.fg("warning", "\u2502") + theme.fg("dim", "\u2591".repeat(Math.max(0, trackCells - inTrack - 1)))) : inTrack === null ? "" : theme.fg("warning", "\u2502")) + "]";
14114
+ const entries = parts.map((part) => ({ text: `\u258C${SERIES_LABELS[part.group]} ${count3(part.tokens)}`, color: part.color }));
14115
+ entries.push({ text: `free ${data.free === null ? "?" : count3(data.free)}`, color: null });
14116
+ if (reserve !== null)
14117
+ entries.push({ text: `\u2502 compaction at ${count3(Math.min(window ?? data.used + reserve, data.used + reserve))}`, color: null });
14118
+ const legend = [];
14119
+ let line = "";
14120
+ for (const entry of entries) {
14121
+ const piece = entry.color ? theme.style(entry.text, { fg: parseColor4(entry.color) }) : theme.fg("dim", entry.text);
14122
+ const candidate = line ? `${line} ${piece}` : piece;
14123
+ if (line && visibleWidth14(candidate) > width) {
14124
+ legend.push(line);
14125
+ line = piece;
14126
+ } else
14127
+ line = candidate;
14128
+ }
14129
+ if (line)
14130
+ legend.push(line);
14131
+ return { bar, legend };
14132
+ }
14133
+ function spread2(left, right, width) {
14134
+ if (!right)
14135
+ return truncateToWidth22(left, width, "");
14136
+ const room = Math.max(0, width - visibleWidth14(left) - 2);
14137
+ const value = truncateToWidth22(right, room, "");
14138
+ return left + " ".repeat(Math.max(1, width - visibleWidth14(left) - visibleWidth14(value))) + value;
14139
+ }
14140
+
14141
+ class ContextPage {
14142
+ options;
14143
+ presentation = "fullscreen";
14144
+ focused = false;
14145
+ tab;
14146
+ grouping = "owner";
14147
+ data = null;
14148
+ detail = null;
14149
+ selectedId = null;
14150
+ folded = new Set;
14151
+ offset = 0;
14152
+ detailOffset = 0;
14153
+ maxOffset = 0;
14154
+ scrollRows = 1;
14155
+ busy = false;
14156
+ reloadPending = false;
14157
+ error = null;
14158
+ disposed = false;
14159
+ constructor(options) {
14160
+ this.options = options;
14161
+ this.tab = options.initialTab ?? "request";
14162
+ }
14163
+ tabs() {
14164
+ return [{ id: "request", title: "Request" }, { id: "growth", title: "Growth" }];
14165
+ }
14166
+ activeTab() {
14167
+ return this.tab;
14168
+ }
14169
+ selectTab(id) {
14170
+ if (id !== "request" && id !== "growth")
14171
+ return;
14172
+ if (id === this.tab)
14173
+ return;
14174
+ this.tab = id;
14175
+ this.offset = 0;
14176
+ this.detail = null;
14177
+ this.options.changed();
14178
+ if (!this.data)
14179
+ this.load();
14180
+ }
14181
+ hint() {
14182
+ if (this.detail)
14183
+ return "\u2191/\u2193 scroll \xB7 esc close \xB7 q close page";
14184
+ return this.tab === "request" ? "\u2191/\u2193 move \xB7 space fold \xB7 enter text \xB7 g group \xB7 c compact \xB7 v variant \xB7 r refresh \xB7 q close" : "\u2191/\u2193 scroll \xB7 r refresh \xB7 q close";
14185
+ }
14186
+ activate() {
14187
+ if (!this.data)
14188
+ this.load();
14189
+ }
14190
+ dispose() {
14191
+ this.disposed = true;
14192
+ }
14193
+ async load(section) {
14194
+ if (this.disposed)
14195
+ return;
14196
+ if (this.busy) {
14197
+ this.reloadPending = true;
14198
+ return;
14199
+ }
14200
+ this.busy = true;
14201
+ this.error = null;
14202
+ this.options.changed();
14203
+ try {
14204
+ const answer = await this.options.call("terminal.context", section ? { section } : {});
14205
+ if (this.disposed)
14206
+ return;
14207
+ this.data = answer.attribution ?? null;
14208
+ if (!this.entries().some((entry) => entry.row.id === this.selectedId))
14209
+ this.selectedId = this.entries()[0]?.row.id ?? null;
14210
+ if (section) {
14211
+ if (answer.text)
14212
+ this.detail = answer.text;
14213
+ else
14214
+ this.error = "That row carries no text: it is measured, not written.";
14215
+ this.detailOffset = 0;
14216
+ }
14217
+ } catch (cause) {
14218
+ this.error = cause instanceof Error ? cause.message : "The context could not be read.";
14219
+ } finally {
14220
+ this.busy = false;
14221
+ this.options.changed();
14222
+ if (this.reloadPending) {
14223
+ this.reloadPending = false;
14224
+ this.load();
14225
+ }
14226
+ }
14227
+ }
14228
+ handleInput(data) {
14229
+ if (this.detail) {
14230
+ const page = Math.max(1, this.scrollRows - 2);
14231
+ if (matchesKey18(data, "up"))
14232
+ this.detailOffset = Math.max(0, this.detailOffset - 1);
14233
+ else if (matchesKey18(data, "down"))
14234
+ this.detailOffset += 1;
14235
+ else if (matchesKey18(data, "pageUp"))
14236
+ this.detailOffset = Math.max(0, this.detailOffset - page);
14237
+ else if (matchesKey18(data, "pageDown"))
14238
+ this.detailOffset += page;
14239
+ else if (matchesKey18(data, "escape") || data === "q") {
14240
+ this.detail = null;
14241
+ this.options.changed();
14242
+ } else
14243
+ return false;
14244
+ this.options.changed();
14245
+ return true;
14246
+ }
14247
+ if (matchesKey18(data, "tab") || matchesKey18(data, "shift+tab")) {
14248
+ const tabs = ["request", "growth"];
14249
+ const direction = matchesKey18(data, "shift+tab") ? -1 : 1;
14250
+ this.selectTab(tabs[(tabs.indexOf(this.tab) + direction + tabs.length) % tabs.length]);
14251
+ return true;
14252
+ }
14253
+ const entries = this.entries();
14254
+ const found = entries.findIndex((entry) => entry.row.id === this.selectedId);
14255
+ const current = found >= 0 ? found : 0;
14256
+ if (!entries.length)
14257
+ return false;
14258
+ if (matchesKey18(data, "up"))
14259
+ this.move(entries, current - 1);
14260
+ else if (matchesKey18(data, "down"))
14261
+ this.move(entries, current + 1);
14262
+ else if (matchesKey18(data, "home"))
14263
+ this.offset = 0;
14264
+ else if (matchesKey18(data, "end"))
14265
+ this.offset = this.maxOffset;
14266
+ else if (data === " " && entries[current]) {
14267
+ const row = entries[current].row;
14268
+ if (this.folded.has(row.group))
14269
+ this.folded.delete(row.group);
14270
+ else
14271
+ this.folded.add(row.group);
14272
+ } else if (matchesKey18(data, "enter") && entries[current]) {
14273
+ this.load(entries[current].row.id);
14274
+ return true;
14275
+ } else if (data === "g") {
14276
+ this.grouping = this.grouping === "owner" ? "kind" : "owner";
14277
+ this.folded.clear();
14278
+ this.offset = 0;
14279
+ } else if (data === "r") {
14280
+ this.load();
14281
+ return true;
14282
+ } else if (data === "c") {
14283
+ this.compact();
14284
+ return true;
14285
+ } else if (data === "v") {
14286
+ this.options.openVariant?.();
14287
+ return true;
14288
+ } else
14289
+ return false;
14290
+ this.options.changed();
14291
+ return true;
14292
+ }
14293
+ move(entries, index) {
14294
+ if (!entries.length)
14295
+ return;
14296
+ const next = entries[Math.max(0, Math.min(entries.length - 1, index))];
14297
+ if (next)
14298
+ this.selectedId = next.row.id;
14299
+ }
14300
+ async compact() {
14301
+ if (!this.options.compact)
14302
+ return;
14303
+ const free = this.data?.free === null || this.data?.free === undefined ? null : this.data.free;
14304
+ const question = free === null ? "Pi will summarize this conversation and start the next request from the summary." : `Pi will summarize this conversation. About ${count3(free)} tokens are free before it does.`;
14305
+ if (this.options.confirm && !await this.options.confirm("Compact the conversation now?", question))
14306
+ return;
14307
+ try {
14308
+ await this.options.compact();
14309
+ await this.load();
14310
+ } catch (cause) {
14311
+ this.error = cause instanceof Error ? cause.message : "Compaction failed.";
14312
+ this.options.changed();
14313
+ }
14314
+ }
14315
+ entries() {
14316
+ const rows = this.data?.rows ?? [];
14317
+ if (this.grouping === "owner") {
14318
+ const ordered = [...rows].sort((left, right) => OWNER_ORDER.indexOf(left.group) - OWNER_ORDER.indexOf(right.group));
14319
+ const out = [];
14320
+ for (const row of ordered) {
14321
+ const previous = out.at(-1)?.row.group;
14322
+ out.push({ row, heading: previous === row.group ? null : OWNER_TITLES[row.group] ?? row.group, folded: this.folded.has(row.group) });
14323
+ }
14324
+ return out;
14325
+ }
14326
+ const ordered = [...rows].sort((left, right) => KIND_ORDER.indexOf(kindOf(left)) - KIND_ORDER.indexOf(kindOf(right)));
14327
+ const out = [];
14328
+ let last = null;
14329
+ for (const row of ordered) {
14330
+ const kind = kindOf(row);
14331
+ const folded = this.folded.has(kind);
14332
+ out.push({ row, heading: last === kind ? null : kind, folded });
14333
+ last = kind;
14334
+ }
14335
+ return out;
14336
+ }
14337
+ render(width, rows) {
14338
+ if (width < 1 || rows < 1)
14339
+ return [];
14340
+ const theme = this.options.theme();
14341
+ const body = this.detail ? this.detailBody(width, theme) : this.tab === "growth" ? this.growthBody(width, theme) : this.requestBody(width, theme);
14342
+ const room = Math.max(1, rows);
14343
+ this.scrollRows = room;
14344
+ this.maxOffset = Math.max(0, body.length - room);
14345
+ const wanted = this.detail ? this.detailOffset : this.offset;
14346
+ const offset = Math.max(0, Math.min(wanted, this.maxOffset));
14347
+ if (this.detail)
14348
+ this.detailOffset = offset;
14349
+ else
14350
+ this.offset = offset;
14351
+ return body.slice(offset, offset + room).map((line) => truncateToWidth22(line, width, ""));
14352
+ }
14353
+ requestBody(width, theme) {
14354
+ const data = this.data;
14355
+ if (!data) {
14356
+ return [padded(theme.fg(this.error ? "error" : "dim", this.error ?? (this.busy ? "Reading the recorded context\u2026" : "No reply yet: the next request records what it is made of.")), width)];
14357
+ }
14358
+ const inner = Math.max(8, width - CHROME_PAD * 2);
14359
+ const body = [];
14360
+ body.push(padded(spread2(theme.fg("text", `${count3(data.used)} of ${data.window === null ? "an unknown window" : count3(data.window)}`), theme.fg(tone(data.share), `${percent(data.share)} used \xB7 ${data.source}`), inner), width));
14361
+ const chart = contextBar(data, inner, theme);
14362
+ body.push(padded(chart.bar, width));
14363
+ for (const line of chart.legend)
14364
+ body.push(padded(line, width));
14365
+ body.push("");
14366
+ for (const entry of this.entries()) {
14367
+ if (entry.heading) {
14368
+ const total = data.rows.filter((row) => this.grouping === "owner" ? OWNER_TITLES[row.group] === entry.heading : kindOf(row) === entry.heading).reduce((sum, row) => sum + row.tokens, 0);
14369
+ const owner = this.grouping === "owner" ? OWNER_ORDER.find((group) => OWNER_TITLES[group] === entry.heading) : undefined;
14370
+ const swatch = owner ? theme.style("\u2588 ", { fg: parseColor4(seriesColor(theme, OWNER_ORDER.indexOf(owner))) }) : "";
14371
+ body.push(padded(swatch + theme.bold(theme.fg("accent", entry.heading)) + theme.fg("dim", ` ${count3(total)}`), width));
14372
+ }
14373
+ if (entry.folded)
14374
+ continue;
14375
+ body.push(this.rowLine(entry.row, inner, width, theme));
14376
+ }
14377
+ if (data.onDemand.length) {
14378
+ body.push("");
14379
+ body.push(padded(theme.fg("accent", "On demand") + theme.fg("dim", " not in this request"), width));
14380
+ for (const item of data.onDemand) {
14381
+ const cost = item.tokensEach === null ? item.note ?? "" : `about ${count3(item.tokensEach)} each \xB7 ${item.note ?? ""}`;
14382
+ body.push(padded(` ${theme.fg("text", item.title)} ${theme.fg("dim", `${item.items} available \xB7 ${cost}`)}`, width));
14383
+ }
14384
+ }
14385
+ if (data.note) {
14386
+ body.push("");
14387
+ body.push(...wrapTextWithAnsi14(theme.fg("dim", data.note), inner).map((line) => padded(line, width)));
14388
+ }
14389
+ if (this.error)
14390
+ body.push(padded(theme.fg("error", this.error), width));
14391
+ return body;
14392
+ }
14393
+ rowLine(row, inner, width, theme) {
14394
+ const selected = row.id === this.selectedId;
14395
+ const marker = selected ? "\u276F " : row.always ? " " : "\xB7 ";
14396
+ const tail = `${count3(row.tokens).padStart(7)}${percent(row.share).padStart(7)}`;
14397
+ const extras = [
14398
+ row.note ? row.note : "",
14399
+ row.budget ? `${count3(row.chars ?? row.tokens * CHARS)} of ${count3(row.budget)} chars` : "",
14400
+ row.tools?.length ? row.tools.map((tool) => `${tool.group} ${tool.count}`).join(" \xB7 ") : ""
14401
+ ].filter(Boolean);
14402
+ const room = () => Math.max(12, inner - visibleWidth14(tail) - 1 - (extras.length ? visibleWidth14(extras.join(" ")) + 2 : 0));
14403
+ let left = truncateToWidth22(`${marker}${row.title}`, room(), "\u2026");
14404
+ while (extras.length && visibleWidth14(left) + visibleWidth14(tail) + 2 + visibleWidth14(extras.join(" ")) > inner)
14405
+ extras.pop();
14406
+ const rest = extras.join(" ");
14407
+ const gap = Math.max(1, inner - visibleWidth14(left) - visibleWidth14(tail) - (rest ? visibleWidth14(rest) + 2 : 0));
14408
+ const line = `${left}${" ".repeat(gap)}${rest ? theme.fg("dim", rest) + " " : ""}${tail}`;
14409
+ if (selected)
14410
+ return selectedRow(padded(line, width), width, theme);
14411
+ return padded(line, width);
14412
+ }
14413
+ growthBody(width, theme) {
14414
+ const data = this.data;
14415
+ if (!data)
14416
+ return [padded(theme.fg("dim", this.busy ? "Reading the recorded context\u2026" : "No reply yet."), width)];
14417
+ const inner = Math.max(8, width - CHROME_PAD * 2);
14418
+ const body = [];
14419
+ const history = data.history.slice(-24);
14420
+ if (history.length) {
14421
+ const peak = Math.max(...history.map((point) => point.used), 1);
14422
+ const spark = history.map((point) => BARS2[Math.min(BARS2.length - 1, Math.round(point.used / peak * (BARS2.length - 1)))]).join("");
14423
+ body.push(padded(theme.fg("accent", spark), width));
14424
+ body.push(padded(theme.fg("dim", `${history.length} requests \xB7 peak ${count3(peak)}${data.compactions.length ? ` \xB7 ${data.compactions.length} compaction${data.compactions.length === 1 ? "" : "s"}` : ""}`), width));
14425
+ } else {
14426
+ body.push(padded(theme.fg("dim", "No measured request yet."), width));
14427
+ }
14428
+ body.push("");
14429
+ body.push(padded(spread2(theme.fg("dim", "REQUEST"), theme.fg("dim", "USED SHARE"), inner), width));
14430
+ for (const point of history.slice().reverse().slice(0, 12)) {
14431
+ body.push(padded(spread2(` ${point.request}`, `${count3(point.used).padStart(8)}${percent(point.share).padStart(8)}`, inner), width));
14432
+ }
14433
+ for (const compaction of data.compactions.slice(-3)) {
14434
+ const before = compaction.before === null ? "?" : count3(compaction.before);
14435
+ const after = compaction.after === null ? "?" : count3(compaction.after);
14436
+ body.push(padded(theme.fg("warning", ` compacted ${before} \u2192 ${after}`), width));
14437
+ }
14438
+ body.push("");
14439
+ body.push(...wrapTextWithAnsi14(theme.fg("dim", data.note ?? ""), inner).filter(Boolean).map((line) => padded(line, width)));
14440
+ return body;
14441
+ }
14442
+ detailBody(width, theme) {
14443
+ const detail = this.detail;
14444
+ const inner = Math.max(8, width - CHROME_PAD * 2);
14445
+ const body = [];
14446
+ body.push(padded(theme.bold(theme.fg("accent", detail.title)), width));
14447
+ body.push("");
14448
+ for (const line of detail.text.split(`
14449
+ `)) {
14450
+ if (!line.trim()) {
14451
+ body.push("");
14452
+ continue;
14453
+ }
14454
+ for (const wrapped of wrapTextWithAnsi14(theme.fg("text", line), inner))
14455
+ body.push(padded(wrapped, width));
14456
+ }
14457
+ return body;
14458
+ }
14459
+ }
14460
+
14461
+ // src/terminal/tui/pages/remoteControlPage.ts
14462
+ import { truncateToWidth as truncateToWidth23, visibleWidth as visibleWidth15, wrapTextWithAnsi as wrapTextWithAnsi15 } from "@earendil-works/pi-tui";
14463
+
14464
+ // src/terminal/tui/qr.ts
14465
+ import { encode } from "uqr";
14466
+ var QUIET = 2;
14467
+ var LIGHT_ON_DARK = "\x1B[38;5;231;48;5;16m";
14468
+ var RESET = "\x1B[0m";
14469
+ function qrModules(text) {
14470
+ const { data } = encode(text, { ecc: "L", border: 0 });
14471
+ const size = data.length + QUIET * 2;
14472
+ const blank = () => Array.from({ length: size }, () => false);
14473
+ return [
14474
+ ...Array.from({ length: QUIET }, blank),
14475
+ ...data.map((row) => [...Array.from({ length: QUIET }, () => false), ...row, ...Array.from({ length: QUIET }, () => false)]),
14476
+ ...Array.from({ length: QUIET }, blank)
14477
+ ];
14478
+ }
14479
+ function qrLines(text) {
14480
+ const modules = qrModules(text);
14481
+ const lines = [];
14482
+ for (let y = 0;y < modules.length; y += 2) {
14483
+ const top = modules[y];
14484
+ const bottom = modules[y + 1] ?? top.map(() => false);
14485
+ let line = "";
14486
+ for (let x = 0;x < top.length; x += 1) {
14487
+ const a = top[x];
14488
+ const b = bottom[x];
14489
+ line += !a && !b ? "\u2588" : !a && b ? "\u2580" : a && !b ? "\u2584" : " ";
14490
+ }
14491
+ lines.push(`${LIGHT_ON_DARK}${line}${RESET}`);
14492
+ }
14493
+ return lines;
14494
+ }
14495
+
14496
+ // src/terminal/tui/pages/remoteControlPage.ts
14497
+ var KIND_LABEL = { tailscale: "Tailscale", lan: "Wi-Fi" };
14498
+
14499
+ class RemoteControlPage {
14500
+ options;
14501
+ presentation = "fullscreen";
14502
+ status = null;
14503
+ error = null;
14504
+ showQr = true;
14505
+ busy = false;
14506
+ disposed = false;
14507
+ watching = null;
14508
+ constructor(options) {
14509
+ this.options = options;
14510
+ }
14511
+ tabs() {
14512
+ return [{ id: "remote", title: "Remote Control" }];
14513
+ }
14514
+ activeTab() {
14515
+ return "remote";
14516
+ }
14517
+ hint() {
14518
+ const status = this.status;
14519
+ if (status?.request)
14520
+ return "a allow \xB7 d deny";
14521
+ if (!status?.running)
14522
+ return "s start";
14523
+ const parts = ["space QR", "c copy link", "n new link"];
14524
+ if (status.kinds.length > 1)
14525
+ parts.push(`t use ${status.kind === "tailscale" ? "Wi-Fi" : "Tailscale"}`);
14526
+ parts.push("x stop");
14527
+ return parts.join(" \xB7 ");
14528
+ }
14529
+ activate() {
14530
+ this.watch();
14531
+ }
14532
+ dispose() {
14533
+ this.disposed = true;
14534
+ this.watching?.abort();
14535
+ }
14536
+ async watch() {
14537
+ const watching = new AbortController;
14538
+ this.watching = watching;
14539
+ let revision;
14540
+ while (!this.disposed && !watching.signal.aborted) {
14541
+ try {
14542
+ const status = await this.options.call(revision === undefined ? "terminal.remoteControl.status" : "terminal.remoteControl.status.wait", { revision });
14543
+ if (this.disposed)
14544
+ return;
14545
+ this.status = status;
14546
+ this.error = null;
14547
+ revision = status.revision;
14548
+ } catch (error) {
14549
+ if (this.disposed)
14550
+ return;
14551
+ this.error = error instanceof Error ? error.message : String(error);
14552
+ revision = undefined;
14553
+ await new Promise((resolve) => setTimeout(resolve, 1000));
14554
+ }
14555
+ this.options.changed();
14556
+ }
14557
+ }
14558
+ async act(method, params = {}, done) {
14559
+ if (this.busy)
14560
+ return;
14561
+ this.busy = true;
14562
+ this.options.changed();
14563
+ try {
14564
+ this.status = await this.options.call(method, params);
14565
+ this.error = null;
14566
+ if (done)
14567
+ this.options.notify(done);
14568
+ } catch (error) {
14569
+ this.error = error instanceof Error ? error.message : String(error);
14570
+ } finally {
14571
+ this.busy = false;
14572
+ this.options.changed();
14573
+ }
14574
+ }
14575
+ handleInput(data) {
14576
+ const status = this.status;
14577
+ if (status?.request) {
14578
+ if (data === "a" || data === "y")
14579
+ this.act("terminal.remoteControl.confirm", { requestId: status.request.id, allow: true }, `${status.request.label} can now control this session.`);
14580
+ else if (data === "d" || data === "n")
14581
+ this.act("terminal.remoteControl.confirm", { requestId: status.request.id, allow: false });
14582
+ return true;
14583
+ }
14584
+ if (!status?.running) {
14585
+ if (data === "s")
14586
+ this.act("terminal.remoteControl.start");
14587
+ return data === "s";
14588
+ }
14589
+ if (data === " ")
14590
+ this.showQr = !this.showQr;
14591
+ else if (data === "c" && status.url)
14592
+ this.options.copy(status.url).then(() => this.options.notify("Remote-control link copied"), (error) => this.options.notify(error instanceof Error ? error.message : String(error), "error"));
14593
+ else if (data === "n")
14594
+ this.act("terminal.remoteControl.rotate", {}, "New link. Paired devices were disconnected.");
14595
+ else if (data === "t" && status.kinds.length > 1)
14596
+ this.act("terminal.remoteControl.start", { interface: status.kind === "tailscale" ? "lan" : "tailscale" });
14597
+ else if (data === "x")
14598
+ this.act("terminal.remoteControl.stop", {}, "Remote control stopped.");
14599
+ else
14600
+ return false;
14601
+ return true;
14602
+ }
14603
+ render(width, rows) {
14604
+ const theme = this.options.theme();
14605
+ const status = this.status;
14606
+ const lines = [];
14607
+ const wrap = (text, color = "text") => {
14608
+ for (const line of wrapTextWithAnsi15(text, Math.max(1, width)))
14609
+ lines.push(theme.fg(color, line));
14610
+ };
14611
+ if (this.error) {
14612
+ wrap(this.error, "error");
14613
+ lines.push("");
14614
+ }
14615
+ if (!status) {
14616
+ wrap("Starting remote control\u2026", "dim");
14617
+ return lines.slice(0, rows);
14618
+ }
14619
+ if (status.request) {
14620
+ wrap(`${safeText(status.request.label)} wants to control this session.`, "warning");
14621
+ wrap("It will be able to send messages, stop replies, and answer approvals and questions. Press a to allow or d to deny.", "text");
14622
+ lines.push("");
14623
+ }
14624
+ if (!status.running) {
14625
+ wrap("Remote control is off.", "dim");
14626
+ wrap("Press s to start it, then scan the QR code with your phone or iPad.", "dim");
14627
+ return lines.slice(0, rows);
14628
+ }
14629
+ const kind = status.kind ? KIND_LABEL[status.kind] : "";
14630
+ lines.push(theme.fg("success", "\u25CF ") + theme.bold(`Remote control is on${kind ? ` \xB7 ${kind}` : ""}`));
14631
+ wrap(status.kind === "tailscale" ? "Scan with a phone or iPad signed in to the same Tailscale network, or open this link on it:" : "Scan with a phone or iPad on the same Wi-Fi, or open this link on it:", "dim");
14632
+ if (status.url)
14633
+ wrap(status.url, "accent");
14634
+ if (status.warning)
14635
+ wrap(safeText(status.warning), "warning");
14636
+ if (status.kind === "lan")
14637
+ wrap("On a network you do not trust, use Tailscale instead: anyone there can see that this computer is listening.", "dim");
14638
+ const devices = status.devices.length ? status.devices.map((device) => `${device.connected ? theme.fg("success", "\u25CF") : theme.fg("dim", "\u25CB")} ${safeText(device.label)}${device.connected ? "" : theme.fg("dim", " (paired, not connected)")}`) : [theme.fg("dim", "No device paired yet.")];
14639
+ const footer = ["", ...devices];
14640
+ if (this.showQr && status.url) {
14641
+ const qr = qrLines(status.url);
14642
+ const room = rows - lines.length - footer.length - 1;
14643
+ const qrWidth = visibleWidth15(qr[0] ?? "");
14644
+ if (qr.length <= room && qrWidth <= width) {
14645
+ lines.push("");
14646
+ const pad = " ".repeat(Math.max(0, Math.floor((width - qrWidth) / 2)));
14647
+ for (const line of qr)
14648
+ lines.push(pad + line);
14649
+ } else {
14650
+ lines.push("", theme.fg("dim", "Make the terminal larger to show the QR code, or press c to copy the link."));
14651
+ }
14652
+ }
14653
+ lines.push(...footer);
14654
+ return lines.slice(0, rows).map((line) => truncateToWidth23(line, width, ""));
14655
+ }
14656
+ }
14657
+
14123
14658
  // src/terminal/tui/settingsModel.ts
14124
14659
  var PRIVATE_ACCESS_ID = "browser.allowPrivate";
14125
14660
  var GROUP_ORDER = ["Theme", "Display", "Images", "Thinking", "Recovery", "Editor", "Queues", "Commands", "Terminal", "Keyboard", "Compaction", "Network"];
@@ -14256,6 +14791,20 @@ function createCommandPage(host, id, options = {}) {
14256
14791
  const theme = () => host.ui.theme;
14257
14792
  const notify = (message, type) => host.ui.notify(message, type === "error" || type === "warning" ? type : "info");
14258
14793
  switch (id) {
14794
+ case "remote-control":
14795
+ return new RemoteControlPage({ theme, call: host.control, changed: host.changed, copy: host.copyText, notify });
14796
+ case "context":
14797
+ return new ContextPage({
14798
+ theme,
14799
+ call: host.control,
14800
+ changed: host.changed,
14801
+ initialTab: options.contextTab === "growth" ? "growth" : "request",
14802
+ openVariant: () => options.navigate?.("harness"),
14803
+ compact: async () => {
14804
+ await host.session().compact?.();
14805
+ },
14806
+ confirm: (title, message) => host.ui.confirm(title, message)
14807
+ });
14259
14808
  case "usage":
14260
14809
  return new UsagePage({ theme, call: host.control, changed: host.changed, initialTab: options.usageTab === "limit" ? "limits" : options.usageTab === "accounts" ? "accounts" : "analysis", ...options.usagePeriod ? { initialPeriod: options.usagePeriod } : {} });
14261
14810
  case "doctor":
@@ -14641,7 +15190,10 @@ function createTerminalCommands(host) {
14641
15190
  };
14642
15191
  async function openPage(id, options = {}) {
14643
15192
  let close = () => {};
14644
- const page = createCommandPage(host, id, { ...options, close: () => close() });
15193
+ const page = createCommandPage(host, id, { ...options, close: () => close(), navigate: (target) => {
15194
+ close();
15195
+ setTimeout(() => void openPage(target), 0);
15196
+ } });
14645
15197
  await host.ui.custom((tui, _theme, _keys, done) => {
14646
15198
  close = () => done(undefined);
14647
15199
  return new PageOverlay({ page, tui, theme: () => host.ui.theme, close, changed: host.changed });
@@ -15057,6 +15609,23 @@ function createTerminalCommands(host) {
15057
15609
  case "log":
15058
15610
  await openPage("log");
15059
15611
  break;
15612
+ case "context":
15613
+ await openPage("context", { contextTab: argument === "growth" ? "growth" : "request" });
15614
+ break;
15615
+ case "remote-control": {
15616
+ const choice = argument.toLowerCase();
15617
+ if (choice === "off" || choice === "stop") {
15618
+ await host.control("terminal.remoteControl.stop");
15619
+ notify("Remote control stopped.");
15620
+ break;
15621
+ }
15622
+ if (choice && !["tailscale", "lan", "wifi", "wi-fi"].includes(choice))
15623
+ throw new Error("Use /remote-control, /remote-control off, /remote-control tailscale or /remote-control lan.");
15624
+ await host.control("terminal.remoteControl.start", { interface: choice === "tailscale" ? "tailscale" : choice ? "lan" : "auto" });
15625
+ host.watchRemoteControl?.();
15626
+ await openPage("remote-control");
15627
+ break;
15628
+ }
15060
15629
  case "compact":
15061
15630
  await session.compact(argument || undefined);
15062
15631
  break;
@@ -15161,6 +15730,14 @@ function planBashRefusal(args) {
15161
15730
  }
15162
15731
  var PLAN_OPEN_TAG = "<proposed_plan>";
15163
15732
  var PLAN_CLOSE_TAG = "</proposed_plan>";
15733
+ var PLAN_BLOCKED_OPEN_TAG = "<plan_blocked>";
15734
+ var PLAN_BLOCKED_CLOSE_TAG = "</plan_blocked>";
15735
+ var LEGACY_CLARIFICATION_TAGS = ["<plan_clarification>", "</plan_clarification>"];
15736
+ var PLAN_REPAIR_CUSTOM_TYPE = "xingular-plan-repair";
15737
+ var PLAN_REPAIR_INSTRUCTIONS = `Your last reply to this plan request did not end with the required plan block.
15738
+ - If you already proposed a sound plan, re-send it unchanged and complete inside one ${PLAN_OPEN_TAG} ... ${PLAN_CLOSE_TAG} block. Its first line must be the plan title as an H1 heading.
15739
+ - Do not research again or change an existing plan. If necessary user input is missing, call ${ASK_USER} when available, then return a complete plan informed by the answer. Never ask a question in free text.
15740
+ - Only if necessary input cannot be obtained because ${ASK_USER} is unavailable, return one ${PLAN_BLOCKED_OPEN_TAG} ... ${PLAN_BLOCKED_CLOSE_TAG} block with a nonempty explanation of the blocker, not a question. Do not invent an answer.`;
15164
15741
  var PLAN_INSTRUCTIONS = `Plan mode is on for this request. Research and design; do not carry out the work.
15165
15742
  - Classify the task and scale investigation and plan detail to it. For repository work, read the governing instructions and relevant source, callers and tests before asserting paths, symbols, behavior or checks. Cite inspected code as path:line; cite external research with source URLs, and mark unverified claims as unknown.
15166
15743
  - Separate facts you can discover from user-owned preferences. Do not ask about facts repository or source inspection can answer. Use ${ASK_USER} for consequential choices that materially change the plan; batch related questions, explain trade-offs and recommend a default. State a reasonable assumption when interaction is unavailable and the task can proceed.
@@ -15179,7 +15756,7 @@ ${PLAN_OPEN_TAG}
15179
15756
  # <Plan title>
15180
15757
  <Markdown: Goal or Summary first; Findings when useful; ordered Steps with files and behavior; Verification with expected results; material Assumptions>
15181
15758
  ${PLAN_CLOSE_TAG}
15182
- - If the user's input is necessary before a sound plan is possible, ask instead of proposing one.`;
15759
+ - If the user's input is necessary before a sound plan is possible, call ${ASK_USER} when available and continue planning after the answer. Never ask the user a question in free text. Only when ${ASK_USER} is unavailable and necessary input cannot be obtained, end with exactly one ${PLAN_BLOCKED_OPEN_TAG} ... ${PLAN_BLOCKED_CLOSE_TAG} block containing a nonempty explanation of the blocker, not a question, instead of a plan. Do not invent an answer.`;
15183
15760
  var PLAN_BASH = "bash";
15184
15761
  function planModeTools(normal, readOnly = [], planOnlyQuestions = []) {
15185
15762
  const allowed = new Set([...PLAN_READ_ONLY_TOOLS, ...PLAN_RESEARCH_TOOLS, SPAWN_SUBAGENT, PLAN_BASH, ...readOnly]);
@@ -15231,8 +15808,30 @@ function parseProposedPlan(text) {
15231
15808
  complete
15232
15809
  };
15233
15810
  }
15811
+ function parsePlanOutcome(text) {
15812
+ if (LEGACY_CLARIFICATION_TAGS.some((tag) => text.includes(tag)))
15813
+ return { kind: "invalid" };
15814
+ const tags = [PLAN_OPEN_TAG, PLAN_CLOSE_TAG, PLAN_BLOCKED_OPEN_TAG, PLAN_BLOCKED_CLOSE_TAG];
15815
+ const counts = tags.map((tag) => text.split(tag).length - 1);
15816
+ if (counts[0] === 1 && counts[1] === 1 && counts[2] === 0 && counts[3] === 0) {
15817
+ const plan = parseProposedPlan(text);
15818
+ const start = text.indexOf(PLAN_OPEN_TAG) + PLAN_OPEN_TAG.length;
15819
+ const end = text.indexOf(PLAN_CLOSE_TAG);
15820
+ if (plan?.complete && end >= start && text.slice(start, end).trim())
15821
+ return { kind: "plan_ready", plan };
15822
+ }
15823
+ if (counts[0] === 0 && counts[1] === 0 && counts[2] === 1 && counts[3] === 1) {
15824
+ const start = text.indexOf(PLAN_BLOCKED_OPEN_TAG) + PLAN_BLOCKED_OPEN_TAG.length;
15825
+ const end = text.indexOf(PLAN_BLOCKED_CLOSE_TAG);
15826
+ const reason = end >= start ? text.slice(start, end).trim() : "";
15827
+ if (reason)
15828
+ return { kind: "blocked", reason };
15829
+ }
15830
+ return { kind: "invalid" };
15831
+ }
15832
+
15234
15833
  // src/terminal/tui/dialogs.ts
15235
- import { Editor, matchesKey as matchesKey18, stripTerminalSequences as stripTerminalSequences11, truncateToWidth as truncateToWidth22, visibleWidth as visibleWidth14, wrapTextWithAnsi as wrapTextWithAnsi14 } from "@earendil-works/pi-tui";
15834
+ import { Editor, matchesKey as matchesKey19, stripTerminalSequences as stripTerminalSequences11, truncateToWidth as truncateToWidth24, visibleWidth as visibleWidth16, wrapTextWithAnsi as wrapTextWithAnsi16 } from "@earendil-works/pi-tui";
15236
15835
  function selectTheme(theme) {
15237
15836
  return {
15238
15837
  selectedPrefix: (text) => selectionText(theme, text),
@@ -15249,7 +15848,7 @@ class SecretInput extends MouseSafeInput {
15249
15848
  if (!this.getValue())
15250
15849
  return lines;
15251
15850
  const segments = new Intl.Segmenter(undefined, { granularity: "grapheme" });
15252
- return lines.map((line) => line.split(/(\x1b(?:\[[0-9;?]*[ -/]*[@-~]|_[^\x07]*\x07))/g).map((part, index) => index % 2 ? part : [...segments.segment(part)].map((item) => "\u2022".repeat(visibleWidth14(item.segment))).join("")).join(""));
15851
+ return lines.map((line) => line.split(/(\x1b(?:\[[0-9;?]*[ -/]*[@-~]|_[^\x07]*\x07))/g).map((part, index) => index % 2 ? part : [...segments.segment(part)].map((item) => "\u2022".repeat(visibleWidth16(item.segment))).join("")).join(""));
15253
15852
  }
15254
15853
  }
15255
15854
  var safe5 = safeText;
@@ -15305,7 +15904,7 @@ class SearchableSelect {
15305
15904
  return this.list.handleMouse(event);
15306
15905
  }
15307
15906
  handleInput(data) {
15308
- if (matchesKey18(data, "ctrl+c")) {
15907
+ if (matchesKey19(data, "ctrl+c")) {
15309
15908
  this.cancel();
15310
15909
  return;
15311
15910
  }
@@ -15322,7 +15921,7 @@ class SearchableSelect {
15322
15921
  this.list.handleInput(data === "j" ? "\x1B[B" : "\x1B[A");
15323
15922
  }
15324
15923
  render(width) {
15325
- return this.list.render(Math.max(4, width), this.windowRows() + this.searchRows()).map((line) => truncateToWidth22(line, width, ""));
15924
+ return this.list.render(Math.max(4, width), this.windowRows() + this.searchRows()).map((line) => truncateToWidth24(line, width, ""));
15326
15925
  }
15327
15926
  }
15328
15927
 
@@ -15378,8 +15977,8 @@ class DialogPanel {
15378
15977
  return mouseAware.handleMouse?.({ ...event, y: row });
15379
15978
  }
15380
15979
  handleInput(data) {
15381
- if (this.detailTotal > this.detailRows && (matchesKey18(data, "pageUp") || matchesKey18(data, "pageDown"))) {
15382
- const delta = matchesKey18(data, "pageUp") ? -1 : 1;
15980
+ if (this.detailTotal > this.detailRows && (matchesKey19(data, "pageUp") || matchesKey19(data, "pageDown"))) {
15981
+ const delta = matchesKey19(data, "pageUp") ? -1 : 1;
15383
15982
  this.detailOffset = Math.max(0, Math.min(this.detailTotal - this.detailRows, this.detailOffset + delta * Math.max(1, this.detailRows)));
15384
15983
  return;
15385
15984
  }
@@ -15390,7 +15989,7 @@ class DialogPanel {
15390
15989
  return [];
15391
15990
  const theme = this.theme();
15392
15991
  const inner = this.centered ? centerDialogContentWidth(width) : contentWidth(width);
15393
- const details = this.message ? wrapTextWithAnsi14(stripTerminalSequences11(this.message).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").replace(/\t/g, " "), inner) : [];
15992
+ const details = this.message ? wrapTextWithAnsi16(stripTerminalSequences11(this.message).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "").replace(/\t/g, " "), inner) : [];
15394
15993
  const content = this.content.render(inner);
15395
15994
  const frameRows = this.centered ? CENTER_DIALOG_PAD * 2 + 2 : CHROME_ROWS;
15396
15995
  const maxHeight = this.maxRows ? Math.max(3, Math.floor(this.maxRows())) : details.length + content.length + frameRows;
@@ -15420,7 +16019,7 @@ class DialogPanel {
15420
16019
  let footer = this.hint;
15421
16020
  if (details.length > detailBudget) {
15422
16021
  footer = `PgUp/PgDn details ${this.detailOffset + 1}-${this.detailOffset + detailBudget}/${details.length} \xB7 ${footer}`;
15423
- if (visibleWidth14(footer) > inner)
16022
+ if (visibleWidth16(footer) > inner)
15424
16023
  footer = "PgUp/PgDn details \xB7 Enter \xB7 Esc";
15425
16024
  }
15426
16025
  const frame = { title: this.title, meta: seconds, body, footer, width, theme };
@@ -15537,9 +16136,9 @@ class TerminalDialogs {
15537
16136
  editor.focused = value;
15538
16137
  },
15539
16138
  invalidate: () => editor.invalidate(),
15540
- render: (width) => editor.render(Math.max(4, width)).map((line) => truncateToWidth22(line, width, "")),
16139
+ render: (width) => editor.render(Math.max(4, width)).map((line) => truncateToWidth24(line, width, "")),
15541
16140
  handleInput: (data) => {
15542
- if (matchesKey18(data, "escape") || matchesKey18(data, "ctrl+c"))
16141
+ if (matchesKey19(data, "escape") || matchesKey19(data, "ctrl+c"))
15543
16142
  done(undefined);
15544
16143
  else
15545
16144
  editor.handleInput(data);
@@ -16455,7 +17054,7 @@ function withWorkspaceWriteScope(tool, note = "") {
16455
17054
  // src/core/workspaceWriteOperations.ts
16456
17055
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
16457
17056
  import { spawn as spawn2 } from "child_process";
16458
- import { createHash as createHash3 } from "crypto";
17057
+ import { createHash as createHash2 } from "crypto";
16459
17058
  import { constants as fsConstants, realpathSync as realpathSync3, statSync as statSync9 } from "fs";
16460
17059
  import { access, readFile } from "fs/promises";
16461
17060
  import { dirname as dirname8, resolve as resolve3 } from "path";
@@ -16640,7 +17239,7 @@ var workspaceEditOperations = {
16640
17239
  const content = await readFile(path);
16641
17240
  const authorization = writeAuthorization.getStore();
16642
17241
  if (authorization && resolve3(path) === authorization.path) {
16643
- authorization.expectedContentHash = createHash3("sha256").update(content).digest("hex");
17242
+ authorization.expectedContentHash = createHash2("sha256").update(content).digest("hex");
16644
17243
  }
16645
17244
  return content;
16646
17245
  },
@@ -16666,6 +17265,7 @@ function withWorkspaceWriteAuthorization(tool, authorizations) {
16666
17265
  }
16667
17266
 
16668
17267
  // src/terminal/piExtension.ts
17268
+ var STREAM_FLUSH_MS = 150;
16669
17269
  function resultSize(result) {
16670
17270
  const content = result?.content;
16671
17271
  if (!Array.isArray(content))
@@ -16692,8 +17292,12 @@ async function piExtension_default(pi, planRun, getSession) {
16692
17292
  let subagentParent = false;
16693
17293
  let stoppedChildren = null;
16694
17294
  let timer = null;
17295
+ let heartbeat = null;
17296
+ let turnStartedAt = 0;
16695
17297
  let polling = false;
16696
17298
  let failure;
17299
+ let planRepairAttempted = false;
17300
+ let lastPlanText = "";
16697
17301
  const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, requests: 0, costUsd: 0 });
16698
17302
  let usage = emptyUsage();
16699
17303
  let reasoningTokens;
@@ -16838,6 +17442,8 @@ async function piExtension_default(pi, planRun, getSession) {
16838
17442
  pi.on("before_agent_start", async (event, ctx) => {
16839
17443
  context = ctx;
16840
17444
  failure = undefined;
17445
+ planRepairAttempted = false;
17446
+ lastPlanText = "";
16841
17447
  usage = emptyUsage();
16842
17448
  reasoningTokens = undefined;
16843
17449
  costReported = false;
@@ -16846,6 +17452,20 @@ async function piExtension_default(pi, planRun, getSession) {
16846
17452
  if (!workspaceRoot)
16847
17453
  throw new Error("The active project workspace could not be resolved; the turn was not started.");
16848
17454
  pi.appendEntry(SUBAGENT_OWNER, { runId: begun.runId });
17455
+ turnStartedAt = Date.now();
17456
+ if (heartbeat)
17457
+ clearInterval(heartbeat);
17458
+ heartbeat = setInterval(() => {
17459
+ terminalCall("heartbeat", {
17460
+ steps: sliceState.steps,
17461
+ elapsedMs: Date.now() - turnStartedAt,
17462
+ lastTool: sliceState.lastTool,
17463
+ compactions: sliceState.compactions,
17464
+ slice: sliceState.slice,
17465
+ maxToolCalls: slicePolicy.enabled ? slicePolicy.maxToolCalls : 0
17466
+ }, 1e4).catch(() => {});
17467
+ }, 30000);
17468
+ heartbeat.unref?.();
16849
17469
  stoppedChildren = null;
16850
17470
  if (nativeSubagents) {
16851
17471
  const snapshot = await controlCall("terminal.subagents.register", { tools: pi.getActiveTools(), model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : null, effort: pi.getThinkingLevel(), plan: planRun?.active === true, history: subagentHistory(ctx.sessionManager.getBranch()) });
@@ -16991,15 +17611,53 @@ async function piExtension_default(pi, planRun, getSession) {
16991
17611
  };
16992
17612
  pi.on("turn_end", (event, ctx) => deliverChildren(event, ctx, false));
16993
17613
  pi.on("agent_before_settle", (event, ctx) => deliverChildren(event, ctx, true));
17614
+ pi.on("agent_before_settle", (event, ctx) => {
17615
+ if (!planRun?.active || planRepairAttempted || event.outcome !== "completed" || event.continue || ctx.signal?.aborted || failure || sliceState.endedBy || parsePlanOutcome(lastPlanText).kind !== "invalid")
17616
+ return;
17617
+ planRepairAttempted = true;
17618
+ return {
17619
+ entries: [...event.entries, { type: "custom_message", customType: PLAN_REPAIR_CUSTOM_TYPE, content: PLAN_REPAIR_INSTRUCTIONS, display: false, details: { reason: "invalid_plan_outcome" } }],
17620
+ continue: true
17621
+ };
17622
+ });
17623
+ let streamId = null;
17624
+ let streamText = "";
17625
+ let streamTimer = null;
17626
+ let streamCount = 0;
17627
+ const flushStream = () => {
17628
+ streamTimer = null;
17629
+ if (!streamId || !streamText)
17630
+ return;
17631
+ const text = streamText;
17632
+ streamText = "";
17633
+ terminalCall("delta", { id: streamId, text }).catch(() => {
17634
+ return;
17635
+ });
17636
+ };
17637
+ pi.on("message_update", (event) => {
17638
+ const update = event.assistantMessageEvent;
17639
+ if (event.message.role !== "assistant" || update.type !== "text_delta" || !update.delta)
17640
+ return;
17641
+ streamId ??= `${Date.now().toString(36)}-${++streamCount}`;
17642
+ streamText += update.delta;
17643
+ streamTimer ??= setTimeout(flushStream, STREAM_FLUSH_MS);
17644
+ });
16994
17645
  pi.on("message_end", async (event) => {
16995
17646
  if (event.message.role !== "assistant")
16996
17647
  return;
17648
+ const messageId = streamId;
17649
+ if (streamTimer)
17650
+ clearTimeout(streamTimer);
17651
+ streamTimer = null;
17652
+ streamText = "";
17653
+ streamId = null;
16997
17654
  if (event.message.stopReason === "error" || event.message.stopReason === "aborted")
16998
17655
  failure = event.message.errorMessage ?? `Pi stopped: ${event.message.stopReason}`;
16999
17656
  const text = event.message.content.filter((part) => part.type === "text").map((part) => part.text).join(`
17000
17657
  `);
17658
+ lastPlanText = text;
17001
17659
  if (text)
17002
- await terminalCall("message", { text });
17660
+ await terminalCall("message", messageId ? { id: messageId, text } : { text });
17003
17661
  if (event.message.usage) {
17004
17662
  const reported = event.message.usage;
17005
17663
  usage.inputTokens += reported.input ?? 0;
@@ -17116,6 +17774,9 @@ async function piExtension_default(pi, planRun, getSession) {
17116
17774
  await terminalCall("file", { path, change: "modified" });
17117
17775
  });
17118
17776
  pi.on("agent_settled", async (event, ctx) => {
17777
+ if (heartbeat)
17778
+ clearInterval(heartbeat);
17779
+ heartbeat = null;
17119
17780
  if (subagentParent && !event.aborted && !failure) {
17120
17781
  try {
17121
17782
  await controlCall("terminal.subagents.verify", { history: subagentHistory(ctx.sessionManager.getBranch()) }, 2147483647);
@@ -17124,7 +17785,7 @@ async function piExtension_default(pi, planRun, getSession) {
17124
17785
  }
17125
17786
  }
17126
17787
  subagentParent = false;
17127
- const reason = sliceState.endedBy ? sliceState.endedBy === "stuck" ? "stalled" : "slice_complete" : undefined;
17788
+ const reason = sliceState.endedBy ? "slice_complete" : undefined;
17128
17789
  await terminalCall("settled", { error: failure, aborted: event.aborted, ...reason ? { reason } : {} });
17129
17790
  });
17130
17791
  pi.on("user_bash", async () => {
@@ -17134,6 +17795,9 @@ async function piExtension_default(pi, planRun, getSession) {
17134
17795
  if (timer)
17135
17796
  clearInterval(timer);
17136
17797
  timer = null;
17798
+ if (heartbeat)
17799
+ clearInterval(heartbeat);
17800
+ heartbeat = null;
17137
17801
  context = null;
17138
17802
  sessionState = null;
17139
17803
  stateDelivered = false;
@@ -17205,7 +17869,6 @@ async function piExtension_default(pi, planRun, getSession) {
17205
17869
  });
17206
17870
  await terminalCall("startup", { phase: "Pi hooks registered" });
17207
17871
  }
17208
-
17209
17872
  // src/usage/limits/capture.ts
17210
17873
  var WRAPPED = Symbol("xingular-usage-observed");
17211
17874
  function wrap(provider, method, observe) {
@@ -17840,7 +18503,60 @@ async function createTerminalRuntime(args, host) {
17840
18503
  }
17841
18504
 
17842
18505
  // src/terminal/tui/sideQuestion.ts
17843
- import { truncateToWidth as truncateToWidth23, visibleWidth as visibleWidth15, wrapTextWithAnsi as wrapTextWithAnsi15 } from "@earendil-works/pi-tui";
18506
+ import { truncateToWidth as truncateToWidth25, visibleWidth as visibleWidth17, wrapTextWithAnsi as wrapTextWithAnsi17 } from "@earendil-works/pi-tui";
18507
+
18508
+ // src/terminal/tui/markdown.ts
18509
+ import { Markdown, stripTerminalSequences as stripTerminalSequences12 } from "@earendil-works/pi-tui";
18510
+ function markdownTheme(theme) {
18511
+ return {
18512
+ heading: (text) => theme.fg("mdHeading", text),
18513
+ link: (text) => theme.fg("mdLink", text),
18514
+ linkUrl: (text) => theme.fg("mdLinkUrl", text),
18515
+ code: (text) => theme.fg("mdCode", text),
18516
+ codeBlock: (text) => theme.fg("mdCodeBlock", text),
18517
+ codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
18518
+ quote: (text) => theme.fg("mdQuote", text),
18519
+ quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
18520
+ hr: (text) => theme.fg("mdHr", text),
18521
+ listBullet: (text) => theme.fg("mdListBullet", text),
18522
+ bold: (text) => theme.bold(text),
18523
+ italic: (text) => theme.italic(text),
18524
+ underline: (text) => theme.underline(text),
18525
+ strikethrough: (text) => theme.strikethrough(text),
18526
+ highlightCode: (code) => code.split(`
18527
+ `).map((line) => theme.fg("mdCodeBlock", line))
18528
+ };
18529
+ }
18530
+ function markdownSource(text) {
18531
+ return stripTerminalSequences12(text).replace(/\r\n?/gu, `
18532
+ `).replace(/[\x00-\x08\x0b-\x1f\x7f]/gu, " ");
18533
+ }
18534
+
18535
+ class MarkdownBlock {
18536
+ component;
18537
+ theme;
18538
+ text = "";
18539
+ lines(text, width, theme) {
18540
+ if (width < 1 || !text.trim())
18541
+ return [];
18542
+ if (!this.component || this.theme !== theme) {
18543
+ this.component = new Markdown("", 0, 0, markdownTheme(theme));
18544
+ this.theme = theme;
18545
+ this.text = "";
18546
+ }
18547
+ if (this.text !== text) {
18548
+ this.component.setText(text);
18549
+ this.text = text;
18550
+ }
18551
+ const lines = this.component.render(width);
18552
+ let end = lines.length;
18553
+ while (end > 0 && !stripTerminalSequences12(lines[end - 1]).trim())
18554
+ end -= 1;
18555
+ return lines.slice(0, end);
18556
+ }
18557
+ }
18558
+
18559
+ // src/terminal/tui/sideQuestion.ts
17844
18560
  var QUESTION_ROWS = 2;
17845
18561
  var ANSWER_ROWS = 8;
17846
18562
  var MAX_CLIENT_CONTEXT_CHARS = 300000;
@@ -17919,6 +18635,7 @@ class SideQuestion {
17919
18635
  startedAt = 0;
17920
18636
  afterSequence = -1;
17921
18637
  answerOffset = 0;
18638
+ answerMarkdown = new MarkdownBlock;
17922
18639
  dock;
17923
18640
  constructor(options) {
17924
18641
  this.options = options;
@@ -18048,21 +18765,20 @@ class SideQuestion {
18048
18765
  const inner = contentWidth(width);
18049
18766
  const spinner = this.current === "thinking" ? spinnerFrameAt(Date.now() - this.startedAt, getWorkingSpinnerFrames(process.env.TERM), SPINNER_INTERVAL_MS) : "";
18050
18767
  const marker = `${spinner ? `${spinner} ` : ""}/btw`;
18051
- const markerWidth = visibleWidth15(marker) + 1;
18052
- const asked = wrapTextWithAnsi15(safeText(this.question), Math.max(1, inner - markerWidth));
18768
+ const markerWidth = visibleWidth17(marker) + 1;
18769
+ const asked = wrapTextWithAnsi17(safeText(this.question), Math.max(1, inner - markerWidth));
18053
18770
  const question = asked.slice(0, QUESTION_ROWS).map((line, index) => {
18054
18771
  const prefix = index === 0 ? `${theme.bold(theme.fg("accent", marker))} ` : " ".repeat(markerWidth);
18055
18772
  return prefix + theme.fg("muted", line);
18056
18773
  });
18057
18774
  if (asked.length > QUESTION_ROWS)
18058
- question[QUESTION_ROWS - 1] = truncateToWidth23(question[QUESTION_ROWS - 1], inner - 1, "") + theme.fg("muted", "\u2026");
18059
- const text = this.current === "failed" ? `${this.answerText ? `${this.answerText}
18060
- ` : ""}${this.error ?? "The side question failed."}` : this.answerText;
18061
- const wrapped = text ? text.split(`
18062
- `).flatMap((line) => line ? wrapTextWithAnsi15(safeText(line), inner) : [""]) : [];
18775
+ question[QUESTION_ROWS - 1] = truncateToWidth25(question[QUESTION_ROWS - 1], inner - 1, "") + theme.fg("muted", "\u2026");
18776
+ const answer = this.answerText ? this.answerMarkdown.lines(markdownSource(this.answerText), inner, theme) : [];
18777
+ const failure = this.current === "failed" ? wrapTextWithAnsi17(safeText(this.error ?? "The side question failed."), inner).map((line) => theme.fg("error", line)) : [];
18778
+ const wrapped = [...answer, ...answer.length && failure.length ? [""] : [], ...failure];
18063
18779
  const maxOffset = Math.max(0, wrapped.length - ANSWER_ROWS);
18064
18780
  this.answerOffset = Math.min(this.answerOffset, maxOffset);
18065
- const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS).map((line) => this.current === "failed" ? theme.fg("error", line) : line);
18781
+ const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS);
18066
18782
  const before = this.answerOffset;
18067
18783
  const after = Math.max(0, wrapped.length - before - shown.length);
18068
18784
  const textHint = before || after ? `PgUp/PgDn browse \xB7 ${before ? `${before} above` : ""}${before && after ? " \xB7 " : ""}${after ? `${after} below` : ""} \xB7 ` : "";
@@ -18072,13 +18788,13 @@ class SideQuestion {
18072
18788
  ...shown.length ? ["", ...shown.map((line) => padded(line, width))] : [],
18073
18789
  "",
18074
18790
  footerRow(`${textHint}Ctrl+X copy \xB7 /btw or Esc dismiss`, width, theme)
18075
- ].map((line) => truncateToWidth23(line, width, ""));
18791
+ ].map((line) => truncateToWidth25(line, width, ""));
18076
18792
  }
18077
18793
  }
18078
18794
 
18079
18795
  // src/terminal/tui/ui.ts
18080
18796
  import { Theme as Theme2 } from "@earendil-works/pi-coding-agent";
18081
- import { stripTerminalSequences as stripTerminalSequences12 } from "@earendil-works/pi-tui";
18797
+ import { stripTerminalSequences as stripTerminalSequences13 } from "@earendil-works/pi-tui";
18082
18798
  function createTerminalUi(options) {
18083
18799
  const state = {
18084
18800
  theme: options.theme,
@@ -18163,7 +18879,7 @@ function createTerminalUi(options) {
18163
18879
  changed();
18164
18880
  },
18165
18881
  setTitle(title) {
18166
- options.tui.terminal.setTitle(stripTerminalSequences12(title).replace(/[\x00-\x1f\x7f]/g, " "));
18882
+ options.tui.terminal.setTitle(stripTerminalSequences13(title).replace(/[\x00-\x1f\x7f]/g, " "));
18167
18883
  },
18168
18884
  pasteToEditor(text) {
18169
18885
  const editor = options.getEditor?.();
@@ -19458,7 +20174,7 @@ class TranscriptModel {
19458
20174
  }
19459
20175
 
19460
20176
  // src/terminal/opentui/palette.ts
19461
- import { stripTerminalSequences as stripTerminalSequences13, truncateToWidth as truncateToWidth24, wrapTextWithAnsi as wrapTextWithAnsi16 } from "@earendil-works/pi-tui";
20177
+ import { stripTerminalSequences as stripTerminalSequences14, truncateToWidth as truncateToWidth26, wrapTextWithAnsi as wrapTextWithAnsi18 } from "@earendil-works/pi-tui";
19462
20178
  function paletteCommandColumnWidth(items, terminalWidth) {
19463
20179
  const widestName = items.reduce((width, item) => Math.max(width, formatTerminalCommandLabel(item.name, item.aliases).length + 1), 1);
19464
20180
  const commandLimit = Math.max(1, Math.floor((terminalWidth - 8) / 2));
@@ -19466,13 +20182,13 @@ function paletteCommandColumnWidth(items, terminalWidth) {
19466
20182
  }
19467
20183
  function paletteTextLines(text, width) {
19468
20184
  const columns = Math.max(1, width);
19469
- const safe = stripTerminalSequences13(text).replace(/[\x00-\x09\x0b-\x1f\x7f]/gu, " ");
20185
+ const safe = stripTerminalSequences14(text).replace(/[\x00-\x09\x0b-\x1f\x7f]/gu, " ");
19470
20186
  const lines = safe.split(`
19471
- `).flatMap((line) => line ? wrapTextWithAnsi16(line, columns) : [""]);
20187
+ `).flatMap((line) => line ? wrapTextWithAnsi18(line, columns) : [""]);
19472
20188
  if (lines.length <= 3)
19473
20189
  return lines;
19474
20190
  const result = lines.slice(0, 3);
19475
- result[2] = `${truncateToWidth24(result[2] ?? "", columns - 1, "", false)}\u2026`;
20191
+ result[2] = `${truncateToWidth26(result[2] ?? "", columns - 1, "", false)}\u2026`;
19476
20192
  return result;
19477
20193
  }
19478
20194
  function rank(item, query) {
@@ -20152,6 +20868,9 @@ class OpenTuiApplication {
20152
20868
  });
20153
20869
  pendingBusy = false;
20154
20870
  decisionWatch;
20871
+ remoteWatch;
20872
+ remoteState = null;
20873
+ remoteAsked = new Set;
20155
20874
  pendingRequests = [];
20156
20875
  pendingAbort;
20157
20876
  pendingId;
@@ -20489,7 +21208,8 @@ class OpenTuiApplication {
20489
21208
  subagents: () => this.subagents,
20490
21209
  editFile: (path) => this.editFile(path),
20491
21210
  suspend: () => this.suspend(),
20492
- hotkeys: () => this.hotkeys()
21211
+ hotkeys: () => this.hotkeys(),
21212
+ watchRemoteControl: () => this.watchRemoteControl()
20493
21213
  });
20494
21214
  this.cleanup.push(this.runtime.subscribe((event) => this.accept(event)));
20495
21215
  this.cleanup.push(this.runtime.onBeforeSessionChange(() => this.resetPresentation()));
@@ -20524,6 +21244,8 @@ class OpenTuiApplication {
20524
21244
  });
20525
21245
  await this.refreshBranch();
20526
21246
  this.change();
21247
+ if (process.env[REMOTE_CONTROL_ENV] === "1")
21248
+ this.commands.execute("/remote-control");
20527
21249
  } catch (error) {
20528
21250
  this.failure = error instanceof Error ? error : new Error(String(error));
20529
21251
  this.notify(this.failure.message, "error");
@@ -20819,6 +21541,51 @@ class OpenTuiApplication {
20819
21541
  this.transcript.invalidate();
20820
21542
  this.change();
20821
21543
  }
21544
+ watchRemoteControl() {
21545
+ if (this.remoteWatch || this.stopped)
21546
+ return;
21547
+ const watch = new AbortController;
21548
+ this.remoteWatch = watch;
21549
+ this.cleanup.push(() => watch.abort());
21550
+ (async () => {
21551
+ let revision;
21552
+ try {
21553
+ while (!watch.signal.aborted && !this.stopped) {
21554
+ let status;
21555
+ try {
21556
+ status = await controlCall(revision === undefined ? "terminal.remoteControl.status" : "terminal.remoteControl.status.wait", { revision }, 25000, watch.signal);
21557
+ } catch {
21558
+ if (watch.signal.aborted || this.stopped)
21559
+ return;
21560
+ revision = undefined;
21561
+ await new Promise((resolve) => setTimeout(resolve, 1000));
21562
+ continue;
21563
+ }
21564
+ revision = status.revision;
21565
+ const state = !status.running ? null : status.devices.some((device) => device.connected) ? "connected" : "waiting";
21566
+ if (state !== this.remoteState) {
21567
+ this.remoteState = state;
21568
+ this.change();
21569
+ }
21570
+ const request = status.request;
21571
+ const ui = this.ui;
21572
+ if (request && ui && !this.remoteAsked.has(request.id) && !this.host.hasOverlay()) {
21573
+ this.remoteAsked.add(request.id);
21574
+ ui.confirm("Allow remote control?", `${request.label} wants to control this session: send messages, stop replies, and answer approvals and questions.`).then((allow) => controlCall("terminal.remoteControl.confirm", { requestId: request.id, allow })).catch((error) => this.notify(error instanceof Error ? error.message : String(error), "error"));
21575
+ }
21576
+ if (!status.running && !request)
21577
+ return;
21578
+ }
21579
+ } finally {
21580
+ if (this.remoteWatch === watch)
21581
+ this.remoteWatch = undefined;
21582
+ if (this.remoteState !== null) {
21583
+ this.remoteState = null;
21584
+ this.change();
21585
+ }
21586
+ }
21587
+ })();
21588
+ }
20822
21589
  async watchDecisions(signal) {
20823
21590
  let revision;
20824
21591
  while (!signal.aborted && !this.stopped) {
@@ -21126,7 +21893,7 @@ class OpenTuiApplication {
21126
21893
  this.session.setThinkingLevel(next);
21127
21894
  }
21128
21895
  extensionShortcut(data) {
21129
- const shortcut = [...this.session.extensionRunner.getShortcuts(this.keybindings.getResolvedBindings()).entries()].find(([key]) => matchesKey19(data, key));
21896
+ const shortcut = [...this.session.extensionRunner.getShortcuts(this.keybindings.getResolvedBindings()).entries()].find(([key]) => matchesKey20(data, key));
21130
21897
  if (!shortcut)
21131
21898
  return false;
21132
21899
  this.attempt(() => shortcut[1].handler(this.session.extensionRunner.createContext()));
@@ -21519,9 +22286,16 @@ class OpenTuiApplication {
21519
22286
  const last = this.session.messages.at(-1);
21520
22287
  if (last?.role !== "assistant" || last.stopReason === "error" || last.stopReason === "aborted")
21521
22288
  return;
21522
- const plan = parseProposedPlan(this.session.getLastAssistantText() ?? "");
21523
- if (plan?.complete)
21524
- this.planChoice.show(plan.title);
22289
+ const outcome = parsePlanOutcome(this.session.getLastAssistantText() ?? "");
22290
+ if (outcome.kind === "plan_ready")
22291
+ this.planChoice.show(outcome.plan.title);
22292
+ else {
22293
+ this.planChoice.clear();
22294
+ if (outcome.kind === "blocked")
22295
+ this.notify("Planning stopped because user input is unavailable.", "warning");
22296
+ else if (outcome.kind === "invalid")
22297
+ this.notify("The plan reply did not include a valid plan or blocked outcome.", "warning");
22298
+ }
21525
22299
  }
21526
22300
  implementPlan(title) {
21527
22301
  this.planChoice.clear();
@@ -22022,6 +22796,7 @@ class OpenTuiApplication {
22022
22796
  (widget.placement === "belowEditor" ? below : above).push(lines);
22023
22797
  }
22024
22798
  return {
22799
+ remoteControl: this.remoteState,
22025
22800
  home: !transcript.hasMultilineNotice && transcript.items.every((item) => item.kind === "notice"),
22026
22801
  sessionName: snapshot?.name,
22027
22802
  cwd: snapshot?.cwd ?? process.cwd(),
@@ -23310,7 +24085,7 @@ function terminalSelectionText(selection) {
23310
24085
  }
23311
24086
 
23312
24087
  // src/terminal/opentui/composerMarks.ts
23313
- import { visibleWidth as visibleWidth16 } from "@earendil-works/pi-tui";
24088
+ import { visibleWidth as visibleWidth18 } from "@earendil-works/pi-tui";
23314
24089
 
23315
24090
  // src/terminal/opentui/slashCommandHighlight.ts
23316
24091
  function leadingSlashCommandRange(text, names) {
@@ -23351,7 +24126,7 @@ function bufferOffset(text, index) {
23351
24126
  `);
23352
24127
  let offset = 0;
23353
24128
  for (const [position, line] of lines.entries())
23354
- offset += visibleWidth16(line) + (position < lines.length - 1 ? 1 : 0);
24129
+ offset += visibleWidth18(line) + (position < lines.length - 1 ? 1 : 0);
23355
24130
  return offset;
23356
24131
  }
23357
24132
  function indexForBufferOffset(text, offset) {
@@ -23361,7 +24136,7 @@ function indexForBufferOffset(text, offset) {
23361
24136
  if (cells >= offset)
23362
24137
  return index;
23363
24138
  cells += character === `
23364
- ` ? 1 : visibleWidth16(character);
24139
+ ` ? 1 : visibleWidth18(character);
23365
24140
  index += character.length;
23366
24141
  }
23367
24142
  return text.length;
@@ -23372,7 +24147,7 @@ function skillInvocationRanges(text, names) {
23372
24147
  function syncTextMarks(target, ranges, typeId, styleId) {
23373
24148
  const expected = ranges.map((range) => {
23374
24149
  const start = bufferOffset(target.plainText, range.start);
23375
- return { start, end: start + visibleWidth16(target.plainText.slice(range.start, range.end)) };
24150
+ return { start, end: start + visibleWidth18(target.plainText.slice(range.start, range.end)) };
23376
24151
  });
23377
24152
  const marks = target.extmarks.getAllForTypeId(typeId).sort((left, right) => left.start - right.start);
23378
24153
  if (marks.length === expected.length && expected.every((range, index) => marks[index].start === range.start && marks[index].end === range.end))
@@ -23430,6 +24205,12 @@ function syncAttachmentMarks(target, labels, typeId, styleId) {
23430
24205
  }
23431
24206
 
23432
24207
  // src/terminal/opentui/statusBar.ts
24208
+ function contextReading(percent, window) {
24209
+ if (percent === null || percent === undefined || !Number.isFinite(percent))
24210
+ return "?";
24211
+ const bounded = Math.max(0, Math.min(999, percent));
24212
+ return `${bounded.toFixed(1)}%/${window && window > 0 ? formatTokenCount(window) : "?"}`;
24213
+ }
23433
24214
  function cacheHitRate(cacheReadTokens, inputTokens) {
23434
24215
  const total = Number.isFinite(inputTokens) ? Math.max(0, inputTokens) : 0;
23435
24216
  const reads = Number.isFinite(cacheReadTokens) ? Math.max(0, cacheReadTokens) : 0;
@@ -23443,15 +24224,19 @@ function statusBarGroups(state) {
23443
24224
  return [
23444
24225
  `${project}:${branch}`,
23445
24226
  `${singleLine(state.account ?? "") || "account unknown"} ${model} ${singleLine(state.thinking) || "off"}`,
23446
- `\u2191${formatTokenCount(state.inputTokens)} ${cacheHitRate(state.cacheReadTokens, state.inputTokens)} \u2193${formatTokenCount(state.outputTokens)}`
23447
- ];
24227
+ [
24228
+ `\u2191${formatTokenCount(state.inputTokens)} ${cacheHitRate(state.cacheReadTokens, state.inputTokens)} \u2193${formatTokenCount(state.outputTokens)}`,
24229
+ state.contextPercent === undefined ? "" : contextReading(state.contextPercent, state.contextWindow)
24230
+ ].filter(Boolean).join(" "),
24231
+ state.remoteControl === "connected" ? "rc \u25CF" : state.remoteControl === "waiting" ? "rc" : ""
24232
+ ].filter(Boolean);
23448
24233
  }
23449
24234
  function statusBarText(state) {
23450
24235
  return statusBarGroups(state).join(" | ");
23451
24236
  }
23452
24237
 
23453
24238
  // src/terminal/opentui/workingLine.ts
23454
- import { stripTerminalSequences as stripTerminalSequences14, truncateToWidth as truncateToWidth25, visibleWidth as visibleWidth17 } from "@earendil-works/pi-tui";
24239
+ import { stripTerminalSequences as stripTerminalSequences15, truncateToWidth as truncateToWidth27, visibleWidth as visibleWidth19 } from "@earendil-works/pi-tui";
23455
24240
  var SHIMMER_INTERVAL_MS = 120;
23456
24241
  var SHIMMER_RADIUS = 2;
23457
24242
  function workingLineParts(state, width) {
@@ -23482,8 +24267,8 @@ function workingLineParts(state, width) {
23482
24267
  return { prefix, label, suffix };
23483
24268
  let remaining = Math.max(0, Math.floor(width));
23484
24269
  const fit = (text) => {
23485
- const fitted = stripTerminalSequences14(truncateToWidth25(text, remaining, "\u2026", false));
23486
- remaining = Math.max(0, remaining - visibleWidth17(fitted));
24270
+ const fitted = stripTerminalSequences15(truncateToWidth27(text, remaining, "\u2026", false));
24271
+ remaining = Math.max(0, remaining - visibleWidth19(fitted));
23487
24272
  return fitted;
23488
24273
  };
23489
24274
  return { prefix: fit(prefix), label: fit(label), suffix: fit(suffix) };
@@ -23534,7 +24319,7 @@ function homeBrand(productName) {
23534
24319
  }
23535
24320
 
23536
24321
  // src/terminal/opentui/pendingMessages.ts
23537
- import { stripTerminalSequences as stripTerminalSequences15, truncateToWidth as truncateToWidth26 } from "@earendil-works/pi-tui";
24322
+ import { stripTerminalSequences as stripTerminalSequences16, truncateToWidth as truncateToWidth28 } from "@earendil-works/pi-tui";
23538
24323
  var labels = {
23539
24324
  steering: "Steering",
23540
24325
  followUp: "Follow-up",
@@ -23548,7 +24333,7 @@ function pendingMessageLines(messages, width, maxRows = 4) {
23548
24333
  if (!columns || !rows || !messages.length)
23549
24334
  return [];
23550
24335
  const shown = messages.length > rows ? rows - 1 : rows;
23551
- const fit = (text) => stripTerminalSequences15(truncateToWidth26(text, columns, "\u2026", false));
24336
+ const fit = (text) => stripTerminalSequences16(truncateToWidth28(text, columns, "\u2026", false));
23552
24337
  const result = messages.slice(0, shown).map((message) => {
23553
24338
  const text = singleLine(message.text.replace(/[\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, " "));
23554
24339
  return fit(`${labels[message.kind]} \xB7 ${text || "(empty)"}`);