@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
@@ -1,7 +1,7 @@
1
1
  import type { Checkpoint } from "./contracts.js";
2
2
  export declare const WORK_SLICE_EXTENSION = "work-slice";
3
3
  export interface WorkSliceInput {
4
- /** False turns the guard off for this run: no budget, no stall notes, no continuation. */
4
+ /** False turns the guard off for this run: no budget, no handoff request, no continuation. */
5
5
  enabled?: boolean;
6
6
  /** Tool calls in one reply; 0 disables this limit. */
7
7
  maxToolCalls?: number;
@@ -32,7 +32,7 @@ export declare class WorkSliceError extends Error {
32
32
  * defaults.
33
33
  */
34
34
  export declare function parseWorkSlice(input: unknown): SlicePolicy;
35
- export type SliceEnd = 'budget' | 'stuck' | 'compaction-thrash';
35
+ export type SliceEnd = 'budget' | 'compaction-thrash';
36
36
  /** What a live reply tracks for its slice; the runner reads it after the reply. */
37
37
  export interface SliceState {
38
38
  slice: number;
@@ -54,16 +54,12 @@ export declare function createSliceState(_policy: SlicePolicy, slice?: number, n
54
54
  export declare function resetSliceState(state: SliceState, now?: number): void;
55
55
  /** The first limit this reply has passed, named as a person would say it. */
56
56
  export declare function sliceLimitReached(policy: SlicePolicy, state: SliceState, now?: number): string | null;
57
- /** Commands that read as a check for the repeated-failure rule. */
58
- export declare function looksLikeCheck(command: string): boolean;
59
57
  interface ToolCall {
60
58
  toolName: string;
61
- input?: unknown;
62
59
  }
63
60
  interface ToolResult {
64
61
  toolName: string;
65
62
  isError?: boolean;
66
- input?: unknown;
67
63
  }
68
64
  /** The part of Pi's extension API this guard uses. Structural, so the module needs no Pi import. */
69
65
  interface GuardApi {
@@ -91,9 +87,9 @@ export interface WorkSliceGuardOptions {
91
87
  onEnd?: (end: SliceEnd, limit: string) => void;
92
88
  }
93
89
  /**
94
- * Bounds one reply and names repeated work. Refusals request a checkpoint when available; without
95
- * one, they ask for a partial report and prohibit further tools. A repeated call or failing command
96
- * is named once, then ends the reply.
90
+ * Bounds one reply. A call past the budget is refused, with one wrap-up request when a checkpoint
91
+ * is available, and an ended reply lets only a handoff call through. Three compactions in one reply
92
+ * end it too. Every other call is allowed, however often it is made.
97
93
  */
98
94
  export declare function workSliceGuard(options: WorkSliceGuardOptions): (pi: GuardApi) => void;
99
95
  /**
@@ -1,8 +1,3 @@
1
- // A reply's work slice (PROP-0041): a bounded amount of work, then a handoff checkpoint, then a
2
- // continuation. The guard here refuses the call that would run past the budget, once with a
3
- // request for the checkpoint, and ends the reply if the model keeps calling tools. It also names
4
- // repeated work before it becomes a loop. All decisions are deterministic; no model is consulted.
5
- import { createHash } from 'node:crypto';
6
1
  import { findRun } from "./runStore.js";
7
2
  export const WORK_SLICE_EXTENSION = 'work-slice';
8
3
  /** The foundation defaults: enough for one meaningful step of work, short enough to report. */
@@ -99,34 +94,6 @@ export function sliceLimitReached(policy, state, now = Date.now()) {
99
94
  }
100
95
  /** Tools a reply may still call while it writes its handoff. A plan update waits for the next slice. */
101
96
  const HANDOFF_TOOLS = new Set(['checkpoint_write', 'session_name']);
102
- /** Tools whose repetition is how waiting works, not a loop. */
103
- const POLLING_TOOLS = new Set(['wait_subagents', 'subagents.list', 'subagents.status']);
104
- /** Commands that read as a check for the repeated-failure rule. */
105
- export function looksLikeCheck(command) {
106
- return /\b(test|tests|typecheck|tsc|vitest|jest|cargo|check:|prove|lint|ci|build)\b/u.test(command);
107
- }
108
- /**
109
- * A stable rendering of a value: object keys sorted, so argument order never changes the result.
110
- * Depth is bounded so a cyclic or absurdly nested input cannot recurse forever.
111
- */
112
- function canonical(value, depth = 0) {
113
- if (depth > 8)
114
- return '…';
115
- if (value === null || typeof value !== 'object')
116
- return JSON.stringify(value) ?? 'null';
117
- if (Array.isArray(value))
118
- return `[${value.map((item) => canonical(item, depth + 1)).join(',')}]`;
119
- const entries = Object.entries(value).filter(([, item]) => item !== undefined);
120
- entries.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
121
- return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, depth + 1)}`).join(',')}}`;
122
- }
123
- /**
124
- * A call's identity: its name and every argument, hashed so the key stays small even when an
125
- * argument is a whole file. A changed argument is a different call; only an identical one repeats.
126
- * Reading a fixed handful of fields made every `todo_write` look identical, so a reply that
127
- * reported its progress was told it was repeating work.
128
- */
129
- const signature = (name, input) => `${name}\u0000${createHash('sha256').update(canonical(input ?? null)).digest('hex')}`;
130
97
  const clip = (value, limit) => (value.length <= limit ? value : `${value.slice(0, limit - 1)}…`);
131
98
  function handoffRequest(limit, state, checkpointAvailable = true) {
132
99
  const handoff = checkpointAvailable
@@ -134,87 +101,28 @@ function handoffRequest(limit, state, checkpointAvailable = true) {
134
101
  : '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.';
135
102
  return clip(`This reply reached its work-slice limit (${limit}; step ${state.steps}). ${handoff} Do not call other tools.`, 600);
136
103
  }
137
- function stalledNote(reason, checkpointAvailable = true) {
138
- const handoff = checkpointAvailable
139
- ? 'Choose a different approach, read what the earlier attempt returned, or call checkpoint_write with the blocker so the next slice can decide.'
140
- : 'Do not use more tools. Return concise findings and blockers in your final response; the Harness records an evidence-derived checkpoint.';
141
- return clip(`You are repeating work: ${reason}. Do not repeat it. ${handoff}`, 600);
142
- }
143
104
  /**
144
- * Bounds one reply and names repeated work. Refusals request a checkpoint when available; without
145
- * one, they ask for a partial report and prohibit further tools. A repeated call or failing command
146
- * is named once, then ends the reply.
105
+ * Bounds one reply. A call past the budget is refused, with one wrap-up request when a checkpoint
106
+ * is available, and an ended reply lets only a handoff call through. Three compactions in one reply
107
+ * end it too. Every other call is allowed, however often it is made.
147
108
  */
148
109
  export function workSliceGuard(options) {
149
110
  const { policy, state } = options;
150
- const calls = new Map();
151
- const checkCalls = new Set();
152
- const edits = new Map();
153
- const failures = new Map();
154
- let nudged = false;
155
111
  const checkpointAvailable = () => typeof options.checkpointAvailable === 'function'
156
112
  ? options.checkpointAvailable()
157
113
  : options.checkpointAvailable !== false;
158
- /** Repetition is judged inside one reply; the next reply starts from a clean count. */
159
- const resetRepetition = () => {
160
- calls.clear();
161
- checkCalls.clear();
162
- edits.clear();
163
- failures.clear();
164
- nudged = false;
165
- };
166
114
  const end = (kind, limit) => {
167
115
  state.endedBy = kind;
168
116
  state.endedByLimit = limit;
169
117
  options.onEnd?.(kind, limit);
170
118
  const canCheckpoint = checkpointAvailable();
171
- const reason = kind === 'stuck'
172
- ? stalledNote(limit, canCheckpoint)
173
- : kind === 'compaction-thrash'
174
- ? handoffRequest('three context compactions in one reply', state, canCheckpoint)
175
- : handoffRequest(limit, state, canCheckpoint);
119
+ const reason = kind === 'compaction-thrash'
120
+ ? handoffRequest('three context compactions in one reply', state, canCheckpoint)
121
+ : handoffRequest(limit, state, canCheckpoint);
176
122
  return { block: true, terminate: true, reason };
177
123
  };
178
- const nudge = (reason) => {
179
- if (nudged)
180
- return end('stuck', reason);
181
- nudged = true;
182
- const canCheckpoint = checkpointAvailable();
183
- if (!canCheckpoint) {
184
- state.endedBy = 'stuck';
185
- state.endedByLimit = reason;
186
- }
187
- return { block: true, reason: stalledNote(reason, canCheckpoint) };
188
- };
189
- const repeated = (name, input) => {
190
- if (POLLING_TOOLS.has(name))
191
- return null;
192
- const key = signature(name, input);
193
- if (name === 'bash') {
194
- const command = input && typeof input === 'object' ? String(input.command ?? '') : '';
195
- if (command && looksLikeCheck(command))
196
- checkCalls.add(key);
197
- }
198
- const count = (calls.get(key) ?? 0) + 1;
199
- calls.set(key, count);
200
- if (count < 3)
201
- return null;
202
- 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})`;
203
- };
204
- const failing = (name, input) => {
205
- if (name !== 'bash')
206
- return null;
207
- const command = input && typeof input === 'object' ? String(input.command ?? '') : '';
208
- if (!command || !looksLikeCheck(command))
209
- return null;
210
- const count = failures.get(command) ?? 0;
211
- return count >= 2 ? `the check ${command} failed ${count} times` : null;
212
- };
213
124
  return (pi) => {
214
- pi.on('agent_start', () => {
215
- resetSliceState(state);
216
- resetRepetition();
217
- });
125
+ pi.on('agent_start', () => resetSliceState(state));
218
126
  pi.on('message_end', (event) => {
219
127
  const usage = event.message.usage;
220
128
  if (event.message.role !== 'assistant' || !usage)
@@ -223,36 +131,8 @@ export function workSliceGuard(options) {
223
131
  state.tokens += (usage.input ?? 0) + (usage.cacheWrite ?? 0) + (usage.output ?? 0);
224
132
  });
225
133
  pi.on('tool_result', (event) => {
226
- if (event.toolName === 'checkpoint_write' && !event.isError) {
134
+ if (event.toolName === 'checkpoint_write' && !event.isError)
227
135
  state.checkpointWritten = true;
228
- nudged = false;
229
- }
230
- if ((event.toolName === 'edit' || event.toolName === 'write') && event.isError === false) {
231
- const path = event.input && typeof event.input === 'object' ? String(event.input.path ?? '') : '';
232
- if (path) {
233
- edits.set(path, (edits.get(path) ?? 0) + 1);
234
- failures.clear();
235
- for (const key of checkCalls)
236
- calls.delete(key);
237
- checkCalls.clear();
238
- nudged = false;
239
- }
240
- }
241
- if (event.toolName !== 'bash')
242
- return;
243
- const command = event.input && typeof event.input === 'object' ? String(event.input.command ?? '') : '';
244
- if (!command || !looksLikeCheck(command))
245
- return;
246
- if (event.isError) {
247
- failures.set(command, (failures.get(command) ?? 0) + 1);
248
- return;
249
- }
250
- // A passing check is progress: the repetition rules start over.
251
- failures.delete(command);
252
- edits.clear();
253
- calls.clear();
254
- checkCalls.clear();
255
- nudged = false;
256
136
  });
257
137
  pi.on('tool_call', (event) => {
258
138
  const name = event.toolName;
@@ -284,27 +164,6 @@ export function workSliceGuard(options) {
284
164
  state.refusedAt ??= state.steps;
285
165
  return handoff ? undefined : { block: true, reason: handoffRequest(limit, state, canCheckpoint) };
286
166
  }
287
- if (handoff)
288
- return undefined;
289
- // Todo updates are bookkeeping, not evidence of progress or a stall. They still count above
290
- // toward the reply's overall tool-call budget.
291
- if (name === 'todo_write')
292
- return undefined;
293
- const edit = name === 'edit' || name === 'write';
294
- const path = edit && event.input && typeof event.input === 'object' ? String(event.input.path ?? '') : '';
295
- if (edit && path) {
296
- const count = edits.get(path) ?? 0;
297
- if (count >= 4) {
298
- const reason = `${path} was edited ${count} times with no passing check between`;
299
- return nudge(reason);
300
- }
301
- }
302
- const repeat = repeated(name, event.input);
303
- const failure = failing(name, event.input);
304
- const reason = repeat ?? failure;
305
- if (!reason)
306
- return undefined;
307
- return nudge(reason);
308
167
  });
309
168
  };
310
169
  }
@@ -1,5 +1,7 @@
1
1
  export declare const SOCKET_ENV = "XINGULAR_HARNESS_SOCKET";
2
2
  export declare const TOKEN_ENV = "XINGULAR_HARNESS_TOKEN";
3
+ /** Set by `xagent --remote-control`: the terminal turns on `/remote-control` as it opens. */
4
+ export declare const REMOTE_CONTROL_ENV = "XINGULAR_HARNESS_REMOTE_CONTROL";
3
5
  export declare class SocketError extends Error {
4
6
  readonly code: string;
5
7
  constructor(code: string, message: string);
@@ -5,6 +5,8 @@
5
5
  import { createConnection } from 'node:net';
6
6
  export const SOCKET_ENV = 'XINGULAR_HARNESS_SOCKET';
7
7
  export const TOKEN_ENV = 'XINGULAR_HARNESS_TOKEN';
8
+ /** Set by `xagent --remote-control`: the terminal turns on `/remote-control` as it opens. */
9
+ export const REMOTE_CONTROL_ENV = 'XINGULAR_HARNESS_REMOTE_CONTROL';
8
10
  export class SocketError extends Error {
9
11
  code;
10
12
  constructor(code, message) {
@@ -73,6 +73,11 @@ export declare class TerminalController {
73
73
  private nativeId;
74
74
  private readonly seen;
75
75
  private readonly commands;
76
+ /** When the reply last produced something other than a heartbeat; silence is what a stall is. */
77
+ private progressAt;
78
+ private readonly runningTools;
79
+ private stallRequested;
80
+ private stallTimer;
76
81
  constructor(hooks: ControllerHooks);
77
82
  private pendingChanged;
78
83
  private setPending;
@@ -90,6 +95,14 @@ export declare class TerminalController {
90
95
  private requestId;
91
96
  private begin;
92
97
  private finish;
98
+ private watchProgress;
99
+ private stopStallWatch;
100
+ /**
101
+ * Ends a reply its native turn can no longer finish: the process is alive and keeps reporting, but
102
+ * the reply produced nothing for the whole window (a model request that never came back). A person
103
+ * may already be answering an approval, and a tool may still be working, so neither is cut short.
104
+ */
105
+ private checkStall;
93
106
  /** Hands the native process an instruction and waits until it acknowledges the prompt. */
94
107
  send(runId: string, text: string): Promise<void>;
95
108
  /** What the person typed into the terminal, so an instruction is never sent over their draft. */
@@ -7,6 +7,7 @@ import { HarnessError } from "../core/errors.js";
7
7
  import { runStatusSchema } from "../sessions/contracts.js";
8
8
  import { briefTitle } from "../sessions/subagents.js";
9
9
  import { MAIN_PROFILE, SubagentMonitor } from "./subagentMonitor.js";
10
+ import { replyStalled } from "./stallWatch.js";
10
11
  function monitorRun(record, relation, profile, runtime) {
11
12
  return {
12
13
  id: record.id,
@@ -23,6 +24,8 @@ function monitorRun(record, relation, profile, runtime) {
23
24
  }
24
25
  const READY_TIMEOUT_MS = 90_000;
25
26
  const ACK_TIMEOUT_MS = 25_000;
27
+ /** How often a live reply's progress is checked against the stall windows. */
28
+ const STALL_CHECK_MS = 30_000;
26
29
  export class TerminalController {
27
30
  hooks;
28
31
  run = null;
@@ -42,6 +45,11 @@ export class TerminalController {
42
45
  nativeId;
43
46
  seen = new Map();
44
47
  commands = [];
48
+ /** When the reply last produced something other than a heartbeat; silence is what a stall is. */
49
+ progressAt = 0;
50
+ runningTools = new Map();
51
+ stallRequested = null;
52
+ stallTimer = null;
45
53
  constructor(hooks) {
46
54
  this.hooks = hooks;
47
55
  this.nativeId = hooks.nativeSessionId;
@@ -99,6 +107,7 @@ export class TerminalController {
99
107
  this.run = run;
100
108
  this.lastRunId = run.runId;
101
109
  this.subagentParentRunId = run.runId;
110
+ this.watchProgress();
102
111
  this.subagents.begin(run.runId);
103
112
  run.onInterrupt(() => void this.commands.push({ type: 'interrupt' }));
104
113
  if (text)
@@ -108,6 +117,7 @@ export class TerminalController {
108
117
  return run;
109
118
  }
110
119
  finish(outcome, message, reason) {
120
+ this.stopStallWatch();
111
121
  this.run?.finish(outcome, message ? { code: 'terminal_attention', message } : undefined, reason);
112
122
  this.run = null;
113
123
  this.seen.clear();
@@ -116,6 +126,37 @@ export class TerminalController {
116
126
  this.pendingChanged();
117
127
  }
118
128
  }
129
+ watchProgress() {
130
+ this.progressAt = Date.now();
131
+ this.runningTools.clear();
132
+ this.stallRequested = null;
133
+ if (this.stallTimer)
134
+ clearInterval(this.stallTimer);
135
+ this.stallTimer = setInterval(() => this.checkStall(), STALL_CHECK_MS);
136
+ this.stallTimer.unref?.();
137
+ }
138
+ stopStallWatch() {
139
+ if (this.stallTimer)
140
+ clearInterval(this.stallTimer);
141
+ this.stallTimer = null;
142
+ this.stallRequested = null;
143
+ this.runningTools.clear();
144
+ }
145
+ /**
146
+ * Ends a reply its native turn can no longer finish: the process is alive and keeps reporting, but
147
+ * the reply produced nothing for the whole window (a model request that never came back). A person
148
+ * may already be answering an approval, and a tool may still be working, so neither is cut short.
149
+ */
150
+ checkStall() {
151
+ const run = this.activeRun;
152
+ if (!run || this.stallRequested || this.pending.size)
153
+ return;
154
+ if (!replyStalled({ now: Date.now(), progressAt: this.progressAt, runningTools: [...this.runningTools.values()] }))
155
+ return;
156
+ this.stallRequested = run.runId;
157
+ this.hooks.telemetry('stall');
158
+ this.commands.push({ type: 'interrupt' });
159
+ }
119
160
  /** Hands the native process an instruction and waits until it acknowledges the prompt. */
120
161
  async send(runId, text) {
121
162
  if (this.disposed)
@@ -343,7 +384,8 @@ export class TerminalController {
343
384
  async accept(event, data) {
344
385
  if (this.disposed)
345
386
  throw new Error('This terminal controller was disposed.');
346
- if (event !== 'poll')
387
+ // Streamed reply text is frequent and only feeds run events; it is not host telemetry.
388
+ if (event !== 'poll' && event !== 'delta')
347
389
  this.hooks.telemetry(event);
348
390
  if (event === 'startup') {
349
391
  this.startupPhase = String(data.phase);
@@ -357,6 +399,9 @@ export class TerminalController {
357
399
  }
358
400
  if (event === 'poll')
359
401
  return { command: this.commands.shift() ?? null };
402
+ // A heartbeat proves the turn is alive, not that it is working; only real events restart the clock.
403
+ if (event !== 'heartbeat')
404
+ this.progressAt = Date.now();
360
405
  if (event === 'ready') {
361
406
  if (!this.ready) {
362
407
  this.dirty = false;
@@ -391,7 +436,8 @@ export class TerminalController {
391
436
  if (event === 'settled') {
392
437
  // A reply that stopped at its work-slice boundary is interrupted, not completed: the record
393
438
  // says `slice_complete` (or `stalled`) so a host can continue it (PROP-0041).
394
- const reason = typeof data.reason === 'string' ? data.reason : undefined;
439
+ const stalled = this.stallRequested !== null && this.stallRequested === this.run?.runId;
440
+ const reason = stalled ? 'stalled' : typeof data.reason === 'string' ? data.reason : undefined;
395
441
  const outcome = data.error ? 'failed' : data.aborted || reason ? 'interrupted' : 'completed';
396
442
  this.finish(outcome, data.error ? String(data.error) : undefined, reason);
397
443
  return {};
@@ -438,15 +484,23 @@ export class TerminalController {
438
484
  }
439
485
  if (event === 'usage')
440
486
  run.emit('usage.updated', data);
487
+ else if (event === 'heartbeat')
488
+ run.emit('heartbeat', data);
441
489
  else if (event === 'todo' || event === 'checklist')
442
490
  run.emit('todo.updated', { items: data.items });
443
491
  else if (event === 'checkpoint')
444
492
  run.emit('checkpoint', data);
445
493
  else if (event === 'file')
446
494
  run.emit('file.changed', data);
495
+ else if (event === 'delta')
496
+ run.emit('message.delta', { messageId: String(data.id ?? ''), text: String(data.text ?? '') });
447
497
  else if (event === 'message')
448
498
  run.emit('message.completed', { messageId: data.id ?? randomUUID(), role: data.role ?? 'assistant', text: String(data.text) });
449
499
  else if (event === 'tool') {
500
+ if (data.phase === 'start')
501
+ this.runningTools.set(String(data.id), Date.now());
502
+ else
503
+ this.runningTools.delete(String(data.id));
450
504
  run.emit(data.phase === 'start' ? 'tool.started' : 'tool.completed', {
451
505
  toolCallId: String(data.id),
452
506
  name: String(data.name),
@@ -17,7 +17,7 @@ import { createSliceState, parseWorkSlice, workSliceGuard } from "../sessions/wo
17
17
  import { DEFAULT_COMMAND_TIMEOUT_SECONDS, withCommandBudget } from "../core/commandBudget.js";
18
18
  import { SESSION_NAME, deriveSessionName, sessionNameTool } from "../tools/sessionName.js";
19
19
  import { CAPABILITY_DISCOVERY, describeCapabilities } from "../tools/getCapabilities.js";
20
- import { PLAN_INSTRUCTIONS, planRefusal } from "../sessions/planMode.js";
20
+ import { PLAN_INSTRUCTIONS, PLAN_REPAIR_CUSTOM_TYPE, PLAN_REPAIR_INSTRUCTIONS, parsePlanOutcome, planRefusal } from "../sessions/planMode.js";
21
21
  import { compactionCheckpoint } from "../sessions/compactionCheckpoint.js";
22
22
  import { requiredSkillsText, sessionStateText } from "../prompt/compile.js";
23
23
  import { pruneToolImages } from "../world/images.js";
@@ -28,6 +28,8 @@ import { createWorkspaceShellTool } from "../core/workspaceBashTool.js";
28
28
  import { createWorkspaceBashOperations, runWithWorkspaceWriteScope } from "../core/workspaceSandbox.js";
29
29
  import { withWorkspaceWriteAuthorization, workspaceEditOperations, workspaceWriteOperations } from "../core/workspaceWriteOperations.js";
30
30
  import { BUDGET_GUARD, OUTPUT_TRIM, budgetGuard, outputTrim } from "../plugins/firstParty.js";
31
+ /** How long reply text gathers before it is sent on to a paired phone. */
32
+ const STREAM_FLUSH_MS = 150;
31
33
  /** How much text a tool handed back to the model. */
32
34
  function resultSize(result) {
33
35
  const content = result?.content;
@@ -54,8 +56,12 @@ export default async function (pi, planRun, getSession) {
54
56
  let subagentParent = false;
55
57
  let stoppedChildren = null;
56
58
  let timer = null;
59
+ let heartbeat = null;
60
+ let turnStartedAt = 0;
57
61
  let polling = false;
58
62
  let failure;
63
+ let planRepairAttempted = false;
64
+ let lastPlanText = '';
59
65
  const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, requests: 0, costUsd: 0 });
60
66
  let usage = emptyUsage();
61
67
  let reasoningTokens;
@@ -213,6 +219,8 @@ export default async function (pi, planRun, getSession) {
213
219
  pi.on('before_agent_start', async (event, ctx) => {
214
220
  context = ctx;
215
221
  failure = undefined;
222
+ planRepairAttempted = false;
223
+ lastPlanText = '';
216
224
  usage = emptyUsage();
217
225
  reasoningTokens = undefined;
218
226
  costReported = false;
@@ -223,6 +231,22 @@ export default async function (pi, planRun, getSession) {
223
231
  throw new Error('The active project workspace could not be resolved; the turn was not started.');
224
232
  // Every turn marks its run on the branch, so a reopened conversation finds its latest one.
225
233
  pi.appendEntry(SUBAGENT_OWNER, { runId: begun.runId });
234
+ // A live reply reports progress so a person and the watchdog can tell a long turn from a wedged
235
+ // one; a turn that stops producing anything is settled with reason `stalled` (INV-RUN-14).
236
+ turnStartedAt = Date.now();
237
+ if (heartbeat)
238
+ clearInterval(heartbeat);
239
+ heartbeat = setInterval(() => {
240
+ void terminalCall('heartbeat', {
241
+ steps: sliceState.steps,
242
+ elapsedMs: Date.now() - turnStartedAt,
243
+ lastTool: sliceState.lastTool,
244
+ compactions: sliceState.compactions,
245
+ slice: sliceState.slice,
246
+ maxToolCalls: slicePolicy.enabled ? slicePolicy.maxToolCalls : 0
247
+ }, 10_000).catch(() => { });
248
+ }, 30_000);
249
+ heartbeat.unref?.();
226
250
  stoppedChildren = null;
227
251
  if (nativeSubagents) {
228
252
  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()) });
@@ -380,14 +404,52 @@ export default async function (pi, planRun, getSession) {
380
404
  };
381
405
  pi.on('turn_end', (event, ctx) => deliverChildren(event, ctx, false));
382
406
  pi.on('agent_before_settle', (event, ctx) => deliverChildren(event, ctx, true));
407
+ pi.on('agent_before_settle', (event, ctx) => {
408
+ if (!planRun?.active || planRepairAttempted || event.outcome !== 'completed' || event.continue || ctx.signal?.aborted || failure || sliceState.endedBy || parsePlanOutcome(lastPlanText).kind !== 'invalid')
409
+ return;
410
+ planRepairAttempted = true;
411
+ return {
412
+ entries: [...event.entries, { type: 'custom_message', customType: PLAN_REPAIR_CUSTOM_TYPE, content: PLAN_REPAIR_INSTRUCTIONS, display: false, details: { reason: 'invalid_plan_outcome' } }],
413
+ continue: true
414
+ };
415
+ });
416
+ // Reply text as it streams, batched, for a paired phone (remote control). The completed message
417
+ // carries the same id and replaces whatever streamed.
418
+ let streamId = null;
419
+ let streamText = '';
420
+ let streamTimer = null;
421
+ let streamCount = 0;
422
+ const flushStream = () => {
423
+ streamTimer = null;
424
+ if (!streamId || !streamText)
425
+ return;
426
+ const text = streamText;
427
+ streamText = '';
428
+ void terminalCall('delta', { id: streamId, text }).catch(() => undefined);
429
+ };
430
+ pi.on('message_update', (event) => {
431
+ const update = event.assistantMessageEvent;
432
+ if (event.message.role !== 'assistant' || update.type !== 'text_delta' || !update.delta)
433
+ return;
434
+ streamId ??= `${Date.now().toString(36)}-${++streamCount}`;
435
+ streamText += update.delta;
436
+ streamTimer ??= setTimeout(flushStream, STREAM_FLUSH_MS);
437
+ });
383
438
  pi.on('message_end', async (event) => {
384
439
  if (event.message.role !== 'assistant')
385
440
  return;
441
+ const messageId = streamId;
442
+ if (streamTimer)
443
+ clearTimeout(streamTimer);
444
+ streamTimer = null;
445
+ streamText = '';
446
+ streamId = null;
386
447
  if (event.message.stopReason === 'error' || event.message.stopReason === 'aborted')
387
448
  failure = event.message.errorMessage ?? `Pi stopped: ${event.message.stopReason}`;
388
449
  const text = event.message.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
450
+ lastPlanText = text;
389
451
  if (text)
390
- await terminalCall('message', { text });
452
+ await terminalCall('message', messageId ? { id: messageId, text } : { text });
391
453
  if (event.message.usage) {
392
454
  const reported = event.message.usage;
393
455
  usage.inputTokens += reported.input ?? 0;
@@ -509,6 +571,9 @@ export default async function (pi, planRun, getSession) {
509
571
  await terminalCall('file', { path, change: 'modified' });
510
572
  });
511
573
  pi.on('agent_settled', async (event, ctx) => {
574
+ if (heartbeat)
575
+ clearInterval(heartbeat);
576
+ heartbeat = null;
512
577
  if (subagentParent && !event.aborted && !failure) {
513
578
  try {
514
579
  await controlCall('terminal.subagents.verify', { history: subagentHistory(ctx.sessionManager.getBranch()) }, 2_147_483_647);
@@ -520,7 +585,7 @@ export default async function (pi, planRun, getSession) {
520
585
  subagentParent = false;
521
586
  // A reply that stopped at its work-slice boundary is not a completed task: the record says so,
522
587
  // so a host can offer the continuation instead of treating it as done (PROP-0041).
523
- const reason = sliceState.endedBy ? sliceState.endedBy === 'stuck' ? 'stalled' : 'slice_complete' : undefined;
588
+ const reason = sliceState.endedBy ? 'slice_complete' : undefined;
524
589
  await terminalCall('settled', { error: failure, aborted: event.aborted, ...(reason ? { reason } : {}) });
525
590
  });
526
591
  pi.on('user_bash', async () => {
@@ -530,6 +595,9 @@ export default async function (pi, planRun, getSession) {
530
595
  if (timer)
531
596
  clearInterval(timer);
532
597
  timer = null;
598
+ if (heartbeat)
599
+ clearInterval(heartbeat);
600
+ heartbeat = null;
533
601
  context = null;
534
602
  sessionState = null;
535
603
  stateDelivered = false;
@@ -0,0 +1,13 @@
1
+ /** Silence with no tool running: the model request never came back. */
2
+ export declare const REPLY_STALL_MS: number;
3
+ /** One tool may run this long; past it the reply is wedged, not busy. */
4
+ export declare const TOOL_STALL_MS: number;
5
+ export interface ReplyProgress {
6
+ now: number;
7
+ /** When the reply last produced something other than a heartbeat. */
8
+ progressAt: number;
9
+ /** When each tool that started and has not finished began. */
10
+ runningTools: readonly number[];
11
+ }
12
+ /** Whether a live reply has gone too long without progress and should be ended. The oldest running tool counts. */
13
+ export declare function replyStalled({ now, progressAt, runningTools }: ReplyProgress): boolean;
@@ -0,0 +1,16 @@
1
+ // A live terminal reply that produced nothing for too long is not working: the person should be
2
+ // told instead of watching a run that never settles. This is the turn-level rule; the run-store
3
+ // sweep (`reconcileStaleRuns`) settles a record whose owner stopped reporting, and both use the
4
+ // same reason, `stalled` (INV-RUN-14).
5
+ /** Silence with no tool running: the model request never came back. */
6
+ export const REPLY_STALL_MS = 15 * 60_000;
7
+ /** One tool may run this long; past it the reply is wedged, not busy. */
8
+ export const TOOL_STALL_MS = 30 * 60_000;
9
+ /** Whether a live reply has gone too long without progress and should be ended. The oldest running tool counts. */
10
+ export function replyStalled({ now, progressAt, runningTools }) {
11
+ if (!Number.isFinite(now))
12
+ return false;
13
+ return runningTools.length
14
+ ? now - Math.min(...runningTools) >= TOOL_STALL_MS
15
+ : now - progressAt >= REPLY_STALL_MS;
16
+ }
@@ -9,6 +9,8 @@ export interface StandalonePaths {
9
9
  worktree?: string | true | null;
10
10
  /** `--variant <scope>`: run on that scope's head, as a host's agent of that scope does. */
11
11
  variant?: string | null;
12
+ /** `--remote-control`, `--rc`: turn on `/remote-control` as the terminal opens. */
13
+ remoteControl?: boolean;
12
14
  }
13
15
  export interface StandaloneDependencies {
14
16
  home?: string;
@@ -10,6 +10,7 @@ import { interactiveProfileSecretStore, resolveInteractiveProfile } from "../cor
10
10
  import { createHarness } from "../harness.js";
11
11
  import { seedVariant } from "../variant/seed.js";
12
12
  import * as variantStore from "../variant/store.js";
13
+ import { REMOTE_CONTROL_ENV } from "./client.js";
13
14
  export function standaloneArguments(argv) {
14
15
  const command = argv[0];
15
16
  if (!command || command.startsWith('-'))
@@ -21,8 +22,13 @@ function resolveStandaloneOptions(argv, home = homedir(), cwd = process.cwd()) {
21
22
  const given = new Set();
22
23
  let worktree;
23
24
  let variant;
25
+ let remoteControl = false;
24
26
  for (let index = 0; index < argv.length; index += 1) {
25
27
  const argument = argv[index];
28
+ if (argument === '--remote-control' || argument === '--rc') {
29
+ remoteControl = true;
30
+ continue;
31
+ }
26
32
  if (argument === '--worktree' || argument === '-w') {
27
33
  const name = argv[index + 1];
28
34
  if (name && !name.startsWith('-')) {
@@ -95,7 +101,8 @@ function resolveStandaloneOptions(argv, home = homedir(), cwd = process.cwd()) {
95
101
  dataRoot: profile.dataRoot,
96
102
  stateDir: profile.stateDir,
97
103
  ...(worktree !== undefined ? { worktree } : {}),
98
- ...(variant !== undefined ? { variant } : {})
104
+ ...(variant !== undefined ? { variant } : {}),
105
+ ...(remoteControl ? { remoteControl } : {})
99
106
  }
100
107
  };
101
108
  }
@@ -220,7 +227,7 @@ export async function runStandaloneTerminal(argv, dependencies = {}) {
220
227
  for (;;) {
221
228
  const sessionFolder = join(paths.dataRoot, 'sessions', 'terminal', createHash('sha256').update(cwd).digest('hex'));
222
229
  const launch = await harness.terminals.prepare({ ...current, cwd, sessionFolder, variant: { scope: variantScope }, ...(worktreeId ? { run: { worktreeId } } : {}) });
223
- const code = await spawnFrontend(launch, cwd, dependencies.spawn);
230
+ const code = await spawnFrontend(paths.remoteControl ? { ...launch, env: { ...launch.env, [REMOTE_CONTROL_ENV]: '1' } } : launch, cwd, dependencies.spawn);
224
231
  // `/accounts` and `/worktree` ask for a switch and end the frontend. An account switch resumes
225
232
  // the conversation; a folder switch starts a new one there.
226
233
  const next = harness.terminals.takeRelaunch(current.sessionId);