@xingular/harness 1.3.1-unstable.2 → 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 (125) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.md +1 -1
  3. package/dist/cli.js +3680 -1947
  4. package/dist/sdk/cli.js +2 -0
  5. package/dist/sdk/commands/registry.d.ts +15 -0
  6. package/dist/sdk/commands/registry.js +2 -0
  7. package/dist/sdk/computer/screenshot.d.ts +32 -0
  8. package/dist/sdk/computer/screenshot.js +35 -0
  9. package/dist/sdk/context/attribution.d.ts +18 -0
  10. package/dist/sdk/context/attribution.js +295 -0
  11. package/dist/sdk/context/types.d.ts +94 -0
  12. package/dist/sdk/context/types.js +10 -0
  13. package/dist/sdk/index.d.ts +2 -1
  14. package/dist/sdk/index.js +2 -1
  15. package/dist/sdk/plugins/builtin.js +1 -0
  16. package/dist/sdk/prompt/compile.d.ts +42 -2
  17. package/dist/sdk/prompt/compile.js +87 -15
  18. package/dist/sdk/remote/addresses.d.ts +19 -0
  19. package/dist/sdk/remote/addresses.js +52 -0
  20. package/dist/sdk/remote/pairing.d.ts +59 -0
  21. package/dist/sdk/remote/pairing.js +160 -0
  22. package/dist/sdk/remote/seal.d.ts +28 -0
  23. package/dist/sdk/remote/seal.js +84 -0
  24. package/dist/sdk/remote/server.d.ts +28 -0
  25. package/dist/sdk/remote/server.js +158 -0
  26. package/dist/sdk/remote/service.d.ts +125 -0
  27. package/dist/sdk/remote/service.js +330 -0
  28. package/dist/sdk/remote/webClient.d.ts +4 -0
  29. package/dist/sdk/remote/webClient.js +444 -0
  30. package/dist/sdk/server/methods.js +3 -0
  31. package/dist/sdk/sessions/contracts.d.ts +4 -0
  32. package/dist/sdk/sessions/contracts.js +2 -0
  33. package/dist/sdk/sessions/planMode.d.ts +26 -1
  34. package/dist/sdk/sessions/planMode.js +48 -1
  35. package/dist/sdk/sessions/runner.d.ts +12 -0
  36. package/dist/sdk/sessions/runner.js +34 -2
  37. package/dist/sdk/sessions/sessions.js +1 -0
  38. package/dist/sdk/sessions/subagentService.d.ts +11 -1
  39. package/dist/sdk/sessions/subagentService.js +120 -38
  40. package/dist/sdk/sessions/subagents.d.ts +31 -0
  41. package/dist/sdk/sessions/subagents.js +45 -0
  42. package/dist/sdk/sessions/workSlice.d.ts +5 -9
  43. package/dist/sdk/sessions/workSlice.js +8 -149
  44. package/dist/sdk/terminal/client.d.ts +3 -1
  45. package/dist/sdk/terminal/client.js +15 -6
  46. package/dist/sdk/terminal/control.d.ts +1 -1
  47. package/dist/sdk/terminal/control.js +2 -2
  48. package/dist/sdk/terminal/controller.d.ts +22 -0
  49. package/dist/sdk/terminal/controller.js +104 -13
  50. package/dist/sdk/terminal/piExtension.js +106 -4
  51. package/dist/sdk/terminal/stallWatch.d.ts +13 -0
  52. package/dist/sdk/terminal/stallWatch.js +16 -0
  53. package/dist/sdk/terminal/standalone.d.ts +2 -0
  54. package/dist/sdk/terminal/standalone.js +9 -2
  55. package/dist/sdk/terminal/terminals.d.ts +14 -0
  56. package/dist/sdk/terminal/terminals.js +98 -2
  57. package/dist/sdk/terminal/tui/commandPages.d.ts +4 -1
  58. package/dist/sdk/terminal/tui/commandPages.js +12 -0
  59. package/dist/sdk/terminal/tui/commands.d.ts +3 -2
  60. package/dist/sdk/terminal/tui/commands.js +19 -5
  61. package/dist/sdk/terminal/tui/dialogs.d.ts +3 -2
  62. package/dist/sdk/terminal/tui/dialogs.js +4 -3
  63. package/dist/sdk/terminal/tui/keybindings.d.ts +1 -1
  64. package/dist/sdk/terminal/tui/keybindings.js +1 -1
  65. package/dist/sdk/terminal/tui/markdown.d.ts +16 -0
  66. package/dist/sdk/terminal/tui/markdown.js +55 -0
  67. package/dist/sdk/terminal/tui/modeChoices.d.ts +3 -2
  68. package/dist/sdk/terminal/tui/modeChoices.js +4 -4
  69. package/dist/sdk/terminal/tui/mouseReport.d.ts +30 -0
  70. package/dist/sdk/terminal/tui/mouseReport.js +80 -0
  71. package/dist/sdk/terminal/tui/pages/annotatePage.js +3 -2
  72. package/dist/sdk/terminal/tui/pages/browserPage.d.ts +1 -1
  73. package/dist/sdk/terminal/tui/pages/contextPage.d.ts +62 -0
  74. package/dist/sdk/terminal/tui/pages/contextPage.js +484 -0
  75. package/dist/sdk/terminal/tui/pages/remoteControlPage.d.ts +32 -0
  76. package/dist/sdk/terminal/tui/pages/remoteControlPage.js +170 -0
  77. package/dist/sdk/terminal/tui/pages/trajectoryPage.js +5 -4
  78. package/dist/sdk/terminal/tui/qr.d.ts +4 -0
  79. package/dist/sdk/terminal/tui/qr.js +35 -0
  80. package/dist/sdk/terminal/tui/runtime.js +8 -2
  81. package/dist/sdk/terminal/tui/search.js +3 -2
  82. package/dist/sdk/terminal/tui/sideQuestion.d.ts +1 -0
  83. package/dist/sdk/terminal/tui/sideQuestion.js +8 -3
  84. package/dist/sdk/terminal/tui/skillInvocation.d.ts +21 -2
  85. package/dist/sdk/terminal/tui/skillInvocation.js +31 -11
  86. package/dist/sdk/terminal/tui/status.d.ts +6 -0
  87. package/dist/sdk/terminal/tui/status.js +15 -1
  88. package/dist/sdk/terminal/tui/theme.d.ts +9 -0
  89. package/dist/sdk/terminal/tui/theme.js +9 -0
  90. package/dist/sdk/tools/defaultSkills.d.ts +19 -0
  91. package/dist/sdk/tools/defaultSkills.js +27 -1
  92. package/dist/sdk/tools/dispatch.js +8 -9
  93. package/dist/sdk/tools/spawnSubagent.d.ts +1 -1
  94. package/dist/sdk/tools/spawnSubagent.js +4 -2
  95. package/dist/terminal-opentui.js +1607 -492
  96. package/dist/terminal-pi.js +256 -144
  97. package/docs/README.md +1 -0
  98. package/docs/architecture/02-sessions-and-runs.md +55 -22
  99. package/docs/architecture/04-prompt.md +23 -4
  100. package/docs/architecture/07-tools-and-gate.md +4 -2
  101. package/docs/architecture/10-server-protocol.md +24 -0
  102. package/docs/architecture/11-terminal.md +52 -10
  103. package/docs/architecture/12-storage.md +5 -2
  104. package/docs/architecture/13-world-tools.md +17 -3
  105. package/docs/architecture/14-surfaces-and-parity.md +7 -3
  106. package/docs/architecture/15-remote-control.md +118 -0
  107. package/docs/architecture/README.md +3 -0
  108. package/docs/architecture/proposals/PROP-0049-context-attribution.md +409 -0
  109. package/docs/architecture/proposals/README.md +2 -1
  110. package/docs/decisions/ADR-0039-progress-aware-stall-guards.md +4 -0
  111. package/docs/decisions/ADR-0048-required-skills-from-a-message.md +42 -0
  112. package/docs/decisions/ADR-0050-approved-window-screenshots.md +19 -0
  113. package/docs/decisions/ADR-0051-terminal-decision-wait.md +10 -0
  114. package/docs/decisions/ADR-0052-per-profile-subagent-budgets.md +25 -0
  115. package/docs/decisions/ADR-0053-no-repeated-work-guard.md +45 -0
  116. package/docs/decisions/ADR-0054-terminal-reply-heartbeat-and-stall.md +52 -0
  117. package/docs/decisions/ADR-0055-plan-output-repair.md +51 -0
  118. package/docs/decisions/ADR-0056-remote-control.md +53 -0
  119. package/docs/decisions/ADR-0057-structured-plan-outcomes.md +39 -0
  120. package/docs/decisions/ADR-0058-ask-user-only-plan-clarification.md +36 -0
  121. package/docs/parity.md +14 -10
  122. package/docs/releases/1.3.1-unstable.3.md +54 -0
  123. package/docs/releases/1.3.1-unstable.4.md +56 -0
  124. package/docs/terminal-tui.md +43 -18
  125. package/package.json +3 -1
@@ -2,8 +2,10 @@
2
2
  // session does to the harness, asks before each tool call, takes instructions the harness
3
3
  // queues for it, and gives the session the harness's own tools. It runs in the `pi` process,
4
4
  // so everything it knows about the harness comes through the session socket.
5
+ import { readFileSync } from 'node:fs';
5
6
  import { createBashTool, createEditTool, createPowerShellTool, createWriteTool } from '@earendil-works/pi-coding-agent';
6
7
  import { Type } from 'typebox';
8
+ import { bodyOf } from "../core/frontmatter.js";
7
9
  import { connectionFromEnv, socketCall, terminalCall } from "./client.js";
8
10
  import { controlCall } from "./control.js";
9
11
  import { SPAWN_SUBAGENT, SUBAGENT_OWNER, SUBAGENT_RECEIPT, SUBAGENT_RESULTS, subagentHistory } from "../sessions/subagents.js";
@@ -15,16 +17,19 @@ import { createSliceState, parseWorkSlice, workSliceGuard } from "../sessions/wo
15
17
  import { DEFAULT_COMMAND_TIMEOUT_SECONDS, withCommandBudget } from "../core/commandBudget.js";
16
18
  import { SESSION_NAME, deriveSessionName, sessionNameTool } from "../tools/sessionName.js";
17
19
  import { CAPABILITY_DISCOVERY, describeCapabilities } from "../tools/getCapabilities.js";
18
- 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";
19
21
  import { compactionCheckpoint } from "../sessions/compactionCheckpoint.js";
20
- import { sessionStateText } from "../prompt/compile.js";
22
+ import { requiredSkillsText, sessionStateText } from "../prompt/compile.js";
21
23
  import { pruneToolImages } from "../world/images.js";
22
24
  import { parseInitialBashCommand } from "../sessions/initialBash.js";
25
+ import { skillInvocations } from "./tui/skillInvocation.js";
23
26
  import { inspectWorkspaceWrite } from "../sessions/workspaceBoundary.js";
24
27
  import { createWorkspaceShellTool } from "../core/workspaceBashTool.js";
25
28
  import { createWorkspaceBashOperations, runWithWorkspaceWriteScope } from "../core/workspaceSandbox.js";
26
29
  import { withWorkspaceWriteAuthorization, workspaceEditOperations, workspaceWriteOperations } from "../core/workspaceWriteOperations.js";
27
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;
28
33
  /** How much text a tool handed back to the model. */
29
34
  function resultSize(result) {
30
35
  const content = result?.content;
@@ -51,8 +56,12 @@ export default async function (pi, planRun, getSession) {
51
56
  let subagentParent = false;
52
57
  let stoppedChildren = null;
53
58
  let timer = null;
59
+ let heartbeat = null;
60
+ let turnStartedAt = 0;
54
61
  let polling = false;
55
62
  let failure;
63
+ let planRepairAttempted = false;
64
+ let lastPlanText = '';
56
65
  const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, requests: 0, costUsd: 0 });
57
66
  let usage = emptyUsage();
58
67
  let reasoningTokens;
@@ -210,6 +219,8 @@ export default async function (pi, planRun, getSession) {
210
219
  pi.on('before_agent_start', async (event, ctx) => {
211
220
  context = ctx;
212
221
  failure = undefined;
222
+ planRepairAttempted = false;
223
+ lastPlanText = '';
213
224
  usage = emptyUsage();
214
225
  reasoningTokens = undefined;
215
226
  costReported = false;
@@ -220,6 +231,22 @@ export default async function (pi, planRun, getSession) {
220
231
  throw new Error('The active project workspace could not be resolved; the turn was not started.');
221
232
  // Every turn marks its run on the branch, so a reopened conversation finds its latest one.
222
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?.();
223
250
  stoppedChildren = null;
224
251
  if (nativeSubagents) {
225
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()) });
@@ -298,6 +325,37 @@ export default async function (pi, planRun, getSession) {
298
325
  if (notice)
299
326
  return { message: { customType: SUBAGENT_RESULTS, content: notice.text, display: false, details: { [SUBAGENT_RECEIPT]: notice.receipt } } };
300
327
  });
328
+ // A `$name` anywhere in the message makes that skill required for this request. The skill's text is
329
+ // delivered as a hidden request-scoped message, so the person's own wording reaches the model unchanged.
330
+ pi.on('before_agent_start', async (event) => {
331
+ if (event.messageType !== 'user' || /^\s*!/u.test(event.prompt))
332
+ return;
333
+ if (pi.getSettings?.().enableSkillCommands === false)
334
+ return;
335
+ const skills = (pi.getCommands?.() ?? [])
336
+ .filter((command) => command.source === 'skill')
337
+ .map((command) => ({
338
+ name: command.name.replace(/^skill:/, ''),
339
+ path: command.sourceInfo.path,
340
+ ...(command.sourceInfo.baseDir ? { baseDir: command.sourceInfo.baseDir } : {})
341
+ }));
342
+ if (!skills.length)
343
+ return;
344
+ const names = skillInvocations(event.prompt, new Set(skills.map((skill) => skill.name)));
345
+ if (!names.length)
346
+ return;
347
+ const entries = names.map((name) => {
348
+ const skill = skills.find((candidate) => candidate.name === name);
349
+ try {
350
+ return { name, path: skill.path, baseDir: skill.baseDir, body: bodyOf(readFileSync(skill.path, 'utf8')) };
351
+ }
352
+ catch {
353
+ return { name, path: skill.path, body: '' };
354
+ }
355
+ });
356
+ const content = requiredSkillsText(entries);
357
+ return content ? { message: { customType: 'xingular-required-skills', content, display: false, details: { skills: names } } } : undefined;
358
+ });
301
359
  // A new user turn starts with an empty todo. The previous list is context, not this run's list.
302
360
  // A substantive first turn also gets a provisional name when the terminal policy allows it.
303
361
  pi.on('before_agent_start', async (event, ctx) => {
@@ -346,14 +404,52 @@ export default async function (pi, planRun, getSession) {
346
404
  };
347
405
  pi.on('turn_end', (event, ctx) => deliverChildren(event, ctx, false));
348
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
+ });
349
438
  pi.on('message_end', async (event) => {
350
439
  if (event.message.role !== 'assistant')
351
440
  return;
441
+ const messageId = streamId;
442
+ if (streamTimer)
443
+ clearTimeout(streamTimer);
444
+ streamTimer = null;
445
+ streamText = '';
446
+ streamId = null;
352
447
  if (event.message.stopReason === 'error' || event.message.stopReason === 'aborted')
353
448
  failure = event.message.errorMessage ?? `Pi stopped: ${event.message.stopReason}`;
354
449
  const text = event.message.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n');
450
+ lastPlanText = text;
355
451
  if (text)
356
- await terminalCall('message', { text });
452
+ await terminalCall('message', messageId ? { id: messageId, text } : { text });
357
453
  if (event.message.usage) {
358
454
  const reported = event.message.usage;
359
455
  usage.inputTokens += reported.input ?? 0;
@@ -475,6 +571,9 @@ export default async function (pi, planRun, getSession) {
475
571
  await terminalCall('file', { path, change: 'modified' });
476
572
  });
477
573
  pi.on('agent_settled', async (event, ctx) => {
574
+ if (heartbeat)
575
+ clearInterval(heartbeat);
576
+ heartbeat = null;
478
577
  if (subagentParent && !event.aborted && !failure) {
479
578
  try {
480
579
  await controlCall('terminal.subagents.verify', { history: subagentHistory(ctx.sessionManager.getBranch()) }, 2_147_483_647);
@@ -486,7 +585,7 @@ export default async function (pi, planRun, getSession) {
486
585
  subagentParent = false;
487
586
  // A reply that stopped at its work-slice boundary is not a completed task: the record says so,
488
587
  // so a host can offer the continuation instead of treating it as done (PROP-0041).
489
- const reason = sliceState.endedBy ? sliceState.endedBy === 'stuck' ? 'stalled' : 'slice_complete' : undefined;
588
+ const reason = sliceState.endedBy ? 'slice_complete' : undefined;
490
589
  await terminalCall('settled', { error: failure, aborted: event.aborted, ...(reason ? { reason } : {}) });
491
590
  });
492
591
  pi.on('user_bash', async () => {
@@ -496,6 +595,9 @@ export default async function (pi, planRun, getSession) {
496
595
  if (timer)
497
596
  clearInterval(timer);
498
597
  timer = null;
598
+ if (heartbeat)
599
+ clearInterval(heartbeat);
600
+ heartbeat = null;
499
601
  context = null;
500
602
  sessionState = null;
501
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);
@@ -25,6 +25,7 @@ import type { AnnotationCapture } from "../annotations/capture.js";
25
25
  import type { NoteDeliveries } from "../annotations/delivery.js";
26
26
  import type { Usage } from "../usage/service.js";
27
27
  import type { UsageLimits } from "../usage/limits/service.js";
28
+ import { type RemoteControlOptions } from "../remote/service.js";
28
29
  /** The files a terminal session needs on disk, outside this process. */
29
30
  export interface TerminalAssets {
30
31
  /** The Node binary that runs the commands. */
@@ -110,6 +111,8 @@ export interface TerminalsOptions {
110
111
  usage?: Usage;
111
112
  /** Provider plan windows, balances and rate limits (`/usage:limit`). */
112
113
  usageLimits?: UsageLimits;
114
+ /** Where `/remote-control` listens; tests bind loopback here. */
115
+ remoteControl?: RemoteControlOptions;
113
116
  }
114
117
  /** What `/plugins` in a terminal can do. Each takes the session's folder, account and project. */
115
118
  export interface PluginControl {
@@ -156,6 +159,8 @@ export declare class Terminals {
156
159
  private readonly relaunches;
157
160
  /** The managed worktree each live session holds. */
158
161
  private readonly worktreeLeases;
162
+ /** `/remote-control` for each live session that opened it. */
163
+ private readonly remotes;
159
164
  /** Each child's profile name and colour, looked up once per child run. */
160
165
  private readonly childProfiles;
161
166
  private subagentProfile;
@@ -198,6 +203,8 @@ export declare class Terminals {
198
203
  private agentsCall;
199
204
  /** `/worktree`: the managed worktrees of the repository this session works in. */
200
205
  private worktreesCall;
206
+ /** `/context`: what the session's latest request was made of, and one row's text on request. */
207
+ private contextCall;
201
208
  /** `/usage:analysis` and `/usage:limit`: usage for this session's own account, project or session. */
202
209
  private usageCall;
203
210
  /** `/annotate:notes` and `/annotate:`: Web annotations and their visible capture browser. */
@@ -239,6 +246,13 @@ export declare class Terminals {
239
246
  active: boolean;
240
247
  };
241
248
  has(sessionId: string): boolean;
249
+ private remote;
250
+ /**
251
+ * What a paired phone reaches: this session's own runs and the same send, interrupt and
252
+ * decision calls the terminal makes (INV-RC-3).
253
+ */
254
+ private remotePort;
255
+ private remoteCall;
242
256
  /** The terminal process ended (or never started): its turn, tokens, and written credentials go with it. */
243
257
  dispose(sessionId: string): Promise<void>;
244
258
  close(): Promise<void>;
@@ -2,7 +2,7 @@
2
2
  // This service prepares the isolated account, compiled context, trusted resource selection and
3
3
  // socket bridge. The default launch runs our frontend with Pi's persistent SDK runtime.
4
4
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
5
- import { dirname, join } from 'node:path';
5
+ import { basename, dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { Type } from 'typebox';
8
8
  import { freezeRun } from "../capabilities/runSnapshot.js";
@@ -21,9 +21,10 @@ import { defaultSkillPaths } from "../tools/defaultSkills.js";
21
21
  import { materialise } from "../variant/materialise.js";
22
22
  import * as componentLibrary from "../variant/components.js";
23
23
  import * as variantStore from "../variant/store.js";
24
+ import { attribution, rowText } from "../context/attribution.js";
24
25
  import { compile, copyToRun, record, render, saveForSession } from "../prompt/compile.js";
25
26
  import { isActiveStatus } from "../sessions/contracts.js";
26
- import { findRun, loadRun, readEvents, recordedSubagents, saveRun, updateRun } from "../sessions/runStore.js";
27
+ import { findRun, listRuns, loadRun, readEvents, recordedSubagents, saveRun, updateRun } from "../sessions/runStore.js";
27
28
  import { combineWorkspaceScope, inspectRunWorkspaceWrite } from "../sessions/workspaceBoundary.js";
28
29
  import { TODO_WRITE } from "../tools/todo.js";
29
30
  import { DEFAULT_TOOL_NAMES } from "../tools/definitions.js";
@@ -45,6 +46,7 @@ import { SessionSocket, socketPath } from "./socket.js";
45
46
  import { harnessLogInfo, readHarnessLogChunk } from "./logs.js";
46
47
  import { listTerminalTrajectoryRuns, readTerminalTrajectory, latestTerminalTodo } from "./trajectory.js";
47
48
  import { BrowserControl } from "./browserControl.js";
49
+ import { RemoteControl } from "../remote/service.js";
48
50
  /** Identity of the exact resource decision that this terminal was prepared with. */
49
51
  function resourceIdentity(loading) {
50
52
  if (!loading)
@@ -84,6 +86,8 @@ export class Terminals {
84
86
  relaunches = new Map();
85
87
  /** The managed worktree each live session holds. */
86
88
  worktreeLeases = new Map();
89
+ /** `/remote-control` for each live session that opened it. */
90
+ remotes = new Map();
87
91
  /** Each child's profile name and colour, looked up once per child run. */
88
92
  childProfiles = new Map();
89
93
  subagentProfile(record) {
@@ -575,6 +579,14 @@ export class Terminals {
575
579
  throw new HarnessError('unknown_method', `Unknown call ${call}.`);
576
580
  }
577
581
  }
582
+ /** `/context`: what the session's latest request was made of, and one row's text on request. */
583
+ contextCall(live, params) {
584
+ const runId = live.controller.lastRun;
585
+ if (!runId)
586
+ return { attribution: null, text: null };
587
+ const text = typeof params.section === 'string' && params.section ? rowText(this.options.env, runId, params.section) : null;
588
+ return { attribution: attribution(this.options.env, runId), text };
589
+ }
578
590
  /** `/usage:analysis` and `/usage:limit`: usage for this session's own account, project or session. */
579
591
  async usageCall(live, call, params) {
580
592
  const usage = this.options.usage;
@@ -1290,6 +1302,10 @@ export class Terminals {
1290
1302
  }
1291
1303
  if (call.startsWith('terminal.usage.'))
1292
1304
  return this.usageCall(live, call, params);
1305
+ if (call === 'terminal.context')
1306
+ return this.contextCall(live, params);
1307
+ if (call.startsWith('terminal.remoteControl.'))
1308
+ return this.remoteCall(live, call, params);
1293
1309
  if (call !== 'terminal.resources')
1294
1310
  return live.controller.control(call, params);
1295
1311
  const current = await this.options.plugins?.loading({ cwd: input.cwd, agentDir: configDir(accounts.dir, preparedAccount), install: false, caller: { projectId: input.projectId ?? null } }) ?? null;
@@ -1392,6 +1408,83 @@ export class Terminals {
1392
1408
  has(sessionId) {
1393
1409
  return this.sessions.has(sessionId);
1394
1410
  }
1411
+ remote(live) {
1412
+ const sessionId = live.input.sessionId;
1413
+ let remote = this.remotes.get(sessionId);
1414
+ if (!remote) {
1415
+ remote = new RemoteControl(this.remotePort(live), { productName: this.options.env.productName, ...this.options.remoteControl });
1416
+ this.remotes.set(sessionId, remote);
1417
+ }
1418
+ return remote;
1419
+ }
1420
+ /**
1421
+ * What a paired phone reaches: this session's own runs and the same send, interrupt and
1422
+ * decision calls the terminal makes (INV-RC-3).
1423
+ */
1424
+ remotePort(live) {
1425
+ const { root } = this.options.env;
1426
+ const sessionId = live.input.sessionId;
1427
+ const own = new Map();
1428
+ const isOwn = (runId) => {
1429
+ let known = own.get(runId);
1430
+ if (known === undefined) {
1431
+ const record = findRun(root, runId);
1432
+ known = !!record && !record.relation && record.trigger !== 'side-question';
1433
+ if (own.size > 1000)
1434
+ own.clear();
1435
+ if (record)
1436
+ own.set(runId, known);
1437
+ }
1438
+ return known;
1439
+ };
1440
+ return {
1441
+ sessionId,
1442
+ title: () => basename(live.input.cwd) || this.options.env.productName,
1443
+ send: (text) => this.send({ sessionId, text }),
1444
+ control: (call, params) => live.controller.control(call, params),
1445
+ history: () => {
1446
+ const native = live.controller.nativeSessionId;
1447
+ if (!native)
1448
+ return [];
1449
+ const runs = listRuns(root, { sessionId })
1450
+ .filter((run) => run.nativeSessionId === native && !run.relation && run.trigger !== 'side-question')
1451
+ .slice(0, 20)
1452
+ .reverse();
1453
+ return runs.flatMap((run) => readEvents(root, run.id));
1454
+ },
1455
+ listen: (listener) => this.options.runs.listen((event) => {
1456
+ if (event.sessionId === sessionId && isOwn(event.runId))
1457
+ listener(event);
1458
+ }),
1459
+ state: () => {
1460
+ const state = live.controller.state();
1461
+ return { ready: state.ready, active: state.active };
1462
+ }
1463
+ };
1464
+ }
1465
+ async remoteCall(live, call, params) {
1466
+ const remote = this.remote(live);
1467
+ if (call === 'terminal.remoteControl.status')
1468
+ return remote.status();
1469
+ if (call === 'terminal.remoteControl.status.wait')
1470
+ return remote.waitStatus(params.revision);
1471
+ if (call === 'terminal.remoteControl.start') {
1472
+ const choice = params.interface ?? 'auto';
1473
+ if (!['auto', 'tailscale', 'lan'].includes(choice))
1474
+ throw invalid('Choose auto, tailscale or lan.');
1475
+ return remote.start(choice);
1476
+ }
1477
+ if (call === 'terminal.remoteControl.stop')
1478
+ return remote.stop();
1479
+ if (call === 'terminal.remoteControl.rotate')
1480
+ return remote.rotate();
1481
+ if (call === 'terminal.remoteControl.confirm') {
1482
+ if (typeof params.requestId !== 'string' || typeof params.allow !== 'boolean')
1483
+ throw invalid('A pairing request id and a boolean choice are required.');
1484
+ return remote.confirm(params.requestId, params.allow);
1485
+ }
1486
+ throw new HarnessError('unknown_method', `Unknown terminal control ${call}.`);
1487
+ }
1395
1488
  /** The terminal process ended (or never started): its turn, tokens, and written credentials go with it. */
1396
1489
  async dispose(sessionId) {
1397
1490
  const live = this.sessions.get(sessionId);
@@ -1404,6 +1497,9 @@ export class Terminals {
1404
1497
  }
1405
1498
  this.sessions.delete(sessionId);
1406
1499
  this.worldNames.delete(sessionId);
1500
+ const remote = this.remotes.get(sessionId);
1501
+ this.remotes.delete(sessionId);
1502
+ await remote?.dispose().catch(() => undefined);
1407
1503
  const worktreeId = this.worktreeLeases.get(sessionId);
1408
1504
  this.worktreeLeases.delete(sessionId);
1409
1505
  if (worktreeId)
@@ -1,7 +1,8 @@
1
1
  import type { TerminalPage } from "./page.js";
2
2
  import type { TerminalCommandHost } from "./commands.js";
3
3
  import { type AnnotateStart } from "./pages/annotatePage.js";
4
- export type CommandPageId = 'doctor' | 'accounts' | 'permissions' | 'plugins' | 'hub' | 'components' | 'settings' | 'trajectory' | 'log' | 'harness' | 'skills' | 'connections' | 'tools' | 'worktree' | 'notes' | 'annotate' | 'subagents' | 'agents' | 'usage';
4
+ import { type ContextTab } from "./pages/contextPage.js";
5
+ export type CommandPageId = 'doctor' | 'accounts' | 'permissions' | 'plugins' | 'hub' | 'components' | 'settings' | 'trajectory' | 'log' | 'harness' | 'skills' | 'connections' | 'tools' | 'worktree' | 'notes' | 'annotate' | 'subagents' | 'agents' | 'usage' | 'context' | 'remote-control';
5
6
  /** Construct one independent full-screen page for a slash command. */
6
7
  export declare function createCommandPage(host: TerminalCommandHost, id: CommandPageId, options?: {
7
8
  runId?: string;
@@ -9,5 +10,7 @@ export declare function createCommandPage(host: TerminalCommandHost, id: Command
9
10
  annotate?: AnnotateStart;
10
11
  usageTab?: 'analysis' | 'limit' | 'accounts';
11
12
  usagePeriod?: 'today' | '7d' | '30d' | 'all';
13
+ contextTab?: ContextTab;
12
14
  close?(): void;
15
+ navigate?(id: CommandPageId): void;
13
16
  }): TerminalPage;
@@ -12,12 +12,24 @@ import { AnnotatePage } from "./pages/annotatePage.js";
12
12
  import { SubagentsPage } from "./pages/subagentsPage.js";
13
13
  import { AgentsPage } from "./pages/agentsPage.js";
14
14
  import { UsagePage } from "./pages/usagePage.js";
15
+ import { ContextPage } from "./pages/contextPage.js";
16
+ import { RemoteControlPage } from "./pages/remoteControlPage.js";
15
17
  import { createSettingsModel } from "./settingsModel.js";
16
18
  /** Construct one independent full-screen page for a slash command. */
17
19
  export function createCommandPage(host, id, options = {}) {
18
20
  const theme = () => host.ui.theme;
19
21
  const notify = (message, type) => host.ui.notify(message, type === 'error' || type === 'warning' ? type : 'info');
20
22
  switch (id) {
23
+ case 'remote-control':
24
+ return new RemoteControlPage({ theme, call: host.control, changed: host.changed, copy: host.copyText, notify });
25
+ case 'context':
26
+ return new ContextPage({
27
+ theme, call: host.control, changed: host.changed,
28
+ initialTab: options.contextTab === 'growth' ? 'growth' : 'request',
29
+ openVariant: () => options.navigate?.('harness'),
30
+ compact: async () => { await host.session().compact?.(); },
31
+ confirm: (title, message) => host.ui.confirm(title, message)
32
+ });
21
33
  case 'usage':
22
34
  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 } : {}) });
23
35
  case 'doctor':
@@ -1,5 +1,5 @@
1
1
  import { type AgentSession, type ExtensionUIContext } from '@earendil-works/pi-coding-agent';
2
- import { type SkillEntry } from "./skillInvocation.js";
2
+ import type { SkillEntry } from "./skillInvocation.js";
3
3
  import type { TerminalRuntime } from "./runtime.js";
4
4
  import type { TerminalTrajectoryRun, TerminalTrajectorySnapshot } from "../trajectory.js";
5
5
  import type { TodoEntry } from "../opentui/model.js";
@@ -34,6 +34,8 @@ export interface TerminalCommandHost {
34
34
  /** Opens a file in the person's editor and resolves once the editor closes. */
35
35
  editFile?(path: string): Promise<void>;
36
36
  hotkeys?(): string;
37
+ /** Follow `/remote-control` after it starts: the status bar, and pairing requests. */
38
+ watchRemoteControl?(): void;
37
39
  logs: {
38
40
  read(): Promise<string>;
39
41
  };
@@ -47,6 +49,5 @@ export declare function createTerminalCommands(host: TerminalCommandHost): {
47
49
  execute: (text: string) => Promise<boolean>;
48
50
  completions: () => TerminalCommandCompletion[];
49
51
  skills: () => SkillEntry[];
50
- expandSkill: (text: string) => string;
51
52
  legacyAliases: () => string[];
52
53
  };
@@ -10,7 +10,6 @@ import { TreePicker } from "./treePicker.js";
10
10
  import { createCommandPage } from "./commandPages.js";
11
11
  import { pageOverlayOptions } from "./dialogGeometry.js";
12
12
  import { ResumeSessionsPage } from "./sessionPicker.js";
13
- import { expandSkillInvocation } from "./skillInvocation.js";
14
13
  import { groupTerminalCommands } from "../commandHelp.js";
15
14
  import { createBuiltinPluginCommandHandlers } from "./pluginCommands.js";
16
15
  export { parseAnnotate } from "./pluginCommands.js";
@@ -43,11 +42,9 @@ export function createTerminalCommands(host) {
43
42
  return [];
44
43
  return session.resourceLoader.getSkills().skills.map((skill) => ({ name: skill.name, description: skill.description }));
45
44
  };
46
- /** The text to send: a leading `$name` of a loaded skill becomes the `/skill:name` form Pi expands. */
47
- const expandSkill = (text) => expandSkillInvocation(text, new Set(skills().map((skill) => skill.name)));
48
45
  async function openPage(id, options = {}) {
49
46
  let close = () => { };
50
- const page = createCommandPage(host, id, { ...options, close: () => close() });
47
+ const page = createCommandPage(host, id, { ...options, close: () => close(), navigate: (target) => { close(); setTimeout(() => void openPage(target), 0); } });
51
48
  await host.ui.custom((tui, _theme, _keys, done) => {
52
49
  close = () => done(undefined);
53
50
  return new PageOverlay({ page, tui, theme: () => host.ui.theme, close, changed: host.changed });
@@ -452,6 +449,23 @@ export function createTerminalCommands(host) {
452
449
  case 'log':
453
450
  await openPage('log');
454
451
  break;
452
+ case 'context':
453
+ await openPage('context', { contextTab: argument === 'growth' ? 'growth' : 'request' });
454
+ break;
455
+ case 'remote-control': {
456
+ const choice = argument.toLowerCase();
457
+ if (choice === 'off' || choice === 'stop') {
458
+ await host.control('terminal.remoteControl.stop');
459
+ notify('Remote control stopped.');
460
+ break;
461
+ }
462
+ if (choice && !['tailscale', 'lan', 'wifi', 'wi-fi'].includes(choice))
463
+ throw new Error('Use /remote-control, /remote-control off, /remote-control tailscale or /remote-control lan.');
464
+ await host.control('terminal.remoteControl.start', { interface: choice === 'tailscale' ? 'tailscale' : choice ? 'lan' : 'auto' });
465
+ host.watchRemoteControl?.();
466
+ await openPage('remote-control');
467
+ break;
468
+ }
455
469
  case 'compact':
456
470
  await session.compact(argument || undefined);
457
471
  break;
@@ -486,5 +500,5 @@ export function createTerminalCommands(host) {
486
500
  }
487
501
  return true;
488
502
  }
489
- return { execute, completions, skills, expandSkill, legacyAliases };
503
+ return { execute, completions, skills, legacyAliases };
490
504
  }
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionUIContext, ExtensionUIDialogOptions, KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
- import { Input, type Component, type Focusable, type SelectListTheme, type TUI, type TuiMouseEventResult } from '@earendil-works/pi-tui';
2
+ import { type Component, type Focusable, type SelectListTheme, type TUI, type TuiMouseEventResult } from '@earendil-works/pi-tui';
3
3
  import type { TerminalMouseInput } from "./mouse.js";
4
+ import { MouseSafeInput } from "./mouseReport.js";
4
5
  export interface GroupedSelectOption {
5
6
  label: string;
6
7
  group?: string;
@@ -12,7 +13,7 @@ export type TerminalDialogOptions = ExtensionUIDialogOptions & {
12
13
  export type DialogVariant = 'block' | 'page';
13
14
  export declare function selectTheme(theme: Theme): SelectListTheme;
14
15
  /** Input keeps the original value; only its rendered cells are masked. */
15
- export declare class SecretInput extends Input {
16
+ export declare class SecretInput extends MouseSafeInput {
16
17
  render(width: number): string[];
17
18
  }
18
19
  /** Choices as a `FilterList`, with the standard search field visible for every list. */
@@ -1,8 +1,9 @@
1
- import { Editor, Input, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
1
+ import { Editor, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
2
2
  import { CENTER_DIALOG_PAD, CHROME_ROWS, blockFrame, centerDialogChromeRows, centerDialogContentWidth, centerDialogFrame, centerDialogVerticalPad, contentWidth, pageFrame, safeText, selectionText } from "./chrome.js";
3
3
  import { centeredDialogHost, dialogFits, pageOverlayOptions, pageRows } from "./dialogGeometry.js";
4
4
  import { FilterList } from "./list.js";
5
5
  import { searchFieldRowsFor } from "./search.js";
6
+ import { MouseSafeInput } from "./mouseReport.js";
6
7
  export function selectTheme(theme) {
7
8
  return {
8
9
  selectedPrefix: text => selectionText(theme, text), selectedText: text => selectionText(theme, text.replace(/^→/, '❯')),
@@ -11,7 +12,7 @@ export function selectTheme(theme) {
11
12
  };
12
13
  }
13
14
  /** Input keeps the original value; only its rendered cells are masked. */
14
- export class SecretInput extends Input {
15
+ export class SecretInput extends MouseSafeInput {
15
16
  render(width) {
16
17
  const lines = super.render(width);
17
18
  if (!this.getValue())
@@ -280,7 +281,7 @@ export class TerminalDialogs {
280
281
  }
281
282
  input(title, placeholder, opts, secret = false) {
282
283
  return this.show(done => {
283
- const InputType = secret ? SecretInput : Input;
284
+ const InputType = secret ? SecretInput : MouseSafeInput;
284
285
  const input = new InputType({ prompt: secret ? '' : '> ', placeholder, placeholderStyle: text => this.theme().fg('dim', text) });
285
286
  input.onSubmit = done;
286
287
  input.onEscape = () => done(undefined);