@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
@@ -1,11 +1,12 @@
1
1
  import { matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
2
2
  import { FilterList } from "../list.js";
3
+ import { stripMouseReports } from "../mouseReport.js";
3
4
  const ACTIVE = new Set(['queued', 'running', 'waiting_for_approval', 'waiting_for_input']);
4
5
  const payloadOf = (event) => event.payload && typeof event.payload === 'object' ? event.payload : {};
5
6
  const stringOf = (value) => typeof value === 'string' ? value : undefined;
6
7
  const numberOf = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
7
8
  function safe(value) {
8
- return stripTerminalSequences(value).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ' ');
9
+ return stripTerminalSequences(stripMouseReports(value)).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ' ');
9
10
  }
10
11
  function timeOf(value) {
11
12
  const parsed = Date.parse(value);
@@ -220,8 +221,8 @@ export class TrajectoryPage {
220
221
  return this.events.map(event => ({
221
222
  id: String(event.sequence),
222
223
  label: `${timeOf(event.timestamp)} ${event.type}`,
223
- detail: eventDescription(event),
224
- searchText: `${event.timestamp} ${event.type} ${eventDescription(event)} ${safe(JSON.stringify(payloadOf(event)))}`,
224
+ detail: safe(eventDescription(event)),
225
+ searchText: `${event.timestamp} ${event.type} ${safe(eventDescription(event))} ${safe(JSON.stringify(payloadOf(event)))}`,
225
226
  data: event
226
227
  }));
227
228
  }
@@ -366,7 +367,7 @@ export class TrajectoryPage {
366
367
  if (rows >= 4)
367
368
  lines.push(theme.fg('muted', usageLine(this.events)));
368
369
  if (rows >= 6)
369
- lines.push(theme.fg('dim', this.run.goal ? `Prompt: ${this.run.goal.replace(/\s+/g, ' ').slice(0, 140)}` : 'Prompt text unavailable'));
370
+ lines.push(theme.fg('dim', this.run.goal ? `Prompt: ${safe(this.run.goal).replace(/\s+/g, ' ').slice(0, 140)}` : 'Prompt text unavailable'));
370
371
  if (this.error)
371
372
  lines.push(theme.fg('error', `Read error: ${this.error}`));
372
373
  return lines.slice(0, Math.min(rows, 5)).map(line => truncateToWidth(line, width, ''));
@@ -0,0 +1,4 @@
1
+ /** The modules, `true` for dark, with a quiet zone of light modules around them. */
2
+ export declare function qrModules(text: string): boolean[][];
3
+ /** One line per two module rows; each line is as wide as the code. */
4
+ export declare function qrLines(text: string): string[];
@@ -0,0 +1,35 @@
1
+ // A QR code drawn with half-block characters: two modules per terminal row. Colours are fixed
2
+ // black on white, whatever the theme, because phone cameras need dark modules on a light ground.
3
+ import { encode } from 'uqr';
4
+ const QUIET = 2;
5
+ const LIGHT_ON_DARK = '\x1b[38;5;231;48;5;16m';
6
+ const RESET = '\x1b[0m';
7
+ /** The modules, `true` for dark, with a quiet zone of light modules around them. */
8
+ export function qrModules(text) {
9
+ const { data } = encode(text, { ecc: 'L', border: 0 });
10
+ const size = data.length + QUIET * 2;
11
+ const blank = () => Array.from({ length: size }, () => false);
12
+ return [
13
+ ...Array.from({ length: QUIET }, blank),
14
+ ...data.map((row) => [...Array.from({ length: QUIET }, () => false), ...row, ...Array.from({ length: QUIET }, () => false)]),
15
+ ...Array.from({ length: QUIET }, blank)
16
+ ];
17
+ }
18
+ /** One line per two module rows; each line is as wide as the code. */
19
+ export function qrLines(text) {
20
+ const modules = qrModules(text);
21
+ const lines = [];
22
+ for (let y = 0; y < modules.length; y += 2) {
23
+ const top = modules[y];
24
+ const bottom = modules[y + 1] ?? top.map(() => false);
25
+ let line = '';
26
+ for (let x = 0; x < top.length; x += 1) {
27
+ // The foreground is light and the background dark, so each cell shows its two modules.
28
+ const a = top[x];
29
+ const b = bottom[x];
30
+ line += !a && !b ? '█' : !a && b ? '▀' : a && !b ? '▄' : ' ';
31
+ }
32
+ lines.push(`${LIGHT_ON_DARK}${line}${RESET}`);
33
+ }
34
+ return lines;
35
+ }
@@ -145,7 +145,13 @@ export async function createTerminalRuntime(args, host) {
145
145
  // A selection is recorded against the mode it was made in; a one-shot plan run is always plan.
146
146
  const recordingMode = () => (planRun.active ? 'plan' : currentMode);
147
147
  const modelFor = (reference) => resolveCliModel({ cliModel: reference, modelRuntime }).model;
148
- const applyMode = () => modeChoices.apply(native.session, currentMode, modelFor);
148
+ // The level Pi resolves when no mode has saved an effort: the model's own default, then the account's.
149
+ const defaultEffort = (session) => {
150
+ const model = session.model;
151
+ return ((model ? session.settingsManager.getModelThinkingLevel(model.provider, model.id) : undefined)
152
+ ?? session.settingsManager.getDefaultThinkingLevel() ?? 'medium');
153
+ };
154
+ const applyMode = () => modeChoices.apply(native.session, currentMode, modelFor, defaultEffort(native.session));
149
155
  const restoreChoice = async (session, previous) => {
150
156
  if (previous.model && (session.model?.provider !== previous.model.provider || session.model?.id !== previous.model.id)) {
151
157
  await session.setModel(previous.model, { persist: false }).catch(() => undefined);
@@ -325,7 +331,7 @@ export async function createTerminalRuntime(args, host) {
325
331
  planRun.active = true;
326
332
  try {
327
333
  session.setActiveToolsByName(allowedTools);
328
- await modeChoices.apply(session, 'plan', modelFor);
334
+ await modeChoices.apply(session, 'plan', modelFor, defaultEffort(session));
329
335
  await session.prompt(text, { expandPromptTemplates: false, ...(images?.length ? { images } : {}) });
330
336
  }
331
337
  finally {
@@ -1,4 +1,5 @@
1
- import { Input, matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
1
+ import { matchesKey, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
2
+ import { MouseSafeInput } from "./mouseReport.js";
2
3
  export const SEARCH_GLYPH = '⌕';
3
4
  export const SEARCH_PLACEHOLDER = 'Type to search';
4
5
  export const SEARCH_FIELD_ROWS = 5;
@@ -14,7 +15,7 @@ export class SearchField {
14
15
  input;
15
16
  constructor(theme, placeholder = SEARCH_PLACEHOLDER) {
16
17
  this.theme = theme;
17
- this.input = new Input({ prompt: '', placeholder, placeholderStyle: text => this.theme().fg('dim', text) });
18
+ this.input = new MouseSafeInput({ prompt: '', placeholder, placeholderStyle: text => this.theme().fg('dim', text) });
18
19
  }
19
20
  get value() { return this.input.getValue(); }
20
21
  set focused(value) { this.input.focused = value; }
@@ -32,6 +32,7 @@ export declare class SideQuestion {
32
32
  private startedAt;
33
33
  private afterSequence;
34
34
  private answerOffset;
35
+ private readonly answerMarkdown;
35
36
  private readonly dock;
36
37
  constructor(options: SideQuestionOptions);
37
38
  get visible(): boolean;
@@ -1,5 +1,6 @@
1
1
  import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
2
2
  import { contentWidth, footerRow, neutralRule, padded, safeText } from "./chrome.js";
3
+ import { MarkdownBlock, markdownSource } from "./markdown.js";
3
4
  import { getWorkingSpinnerFrames, SPINNER_INTERVAL_MS, spinnerFrameAt } from "./workingStatus.js";
4
5
  const QUESTION_ROWS = 2;
5
6
  const ANSWER_ROWS = 8;
@@ -74,6 +75,7 @@ export class SideQuestion {
74
75
  startedAt = 0;
75
76
  afterSequence = -1;
76
77
  answerOffset = 0;
78
+ answerMarkdown = new MarkdownBlock();
77
79
  dock;
78
80
  constructor(options) {
79
81
  this.options = options;
@@ -211,11 +213,14 @@ export class SideQuestion {
211
213
  });
212
214
  if (asked.length > QUESTION_ROWS)
213
215
  question[QUESTION_ROWS - 1] = truncateToWidth(question[QUESTION_ROWS - 1], inner - 1, '') + theme.fg('muted', '…');
214
- const text = this.current === 'failed' ? `${this.answerText ? `${this.answerText}\n` : ''}${this.error ?? 'The side question failed.'}` : this.answerText;
215
- const wrapped = text ? text.split('\n').flatMap(line => line ? wrapTextWithAnsi(safeText(line), inner) : ['']) : [];
216
+ const answer = this.answerText ? this.answerMarkdown.lines(markdownSource(this.answerText), inner, theme) : [];
217
+ const failure = this.current === 'failed'
218
+ ? wrapTextWithAnsi(safeText(this.error ?? 'The side question failed.'), inner).map(line => theme.fg('error', line))
219
+ : [];
220
+ const wrapped = [...answer, ...(answer.length && failure.length ? [''] : []), ...failure];
216
221
  const maxOffset = Math.max(0, wrapped.length - ANSWER_ROWS);
217
222
  this.answerOffset = Math.min(this.answerOffset, maxOffset);
218
- const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS).map(line => this.current === 'failed' ? theme.fg('error', line) : line);
223
+ const shown = wrapped.slice(this.answerOffset, this.answerOffset + ANSWER_ROWS);
219
224
  const before = this.answerOffset;
220
225
  const after = Math.max(0, wrapped.length - before - shown.length);
221
226
  const textHint = before || after ? `PgUp/PgDn browse · ${before ? `${before} above` : ''}${before && after ? ' · ' : ''}${after ? `${after} below` : ''} · ` : '';
@@ -3,7 +3,26 @@ export interface SkillEntry {
3
3
  name: string;
4
4
  description: string;
5
5
  }
6
- /** Rewrites a leading `$name` of a loaded skill into `/skill:name`. Anything else passes through, so `$5` stays text. */
7
- export declare function expandSkillInvocation(text: string, skills: ReadonlySet<string>): string;
6
+ export interface SkillToken {
7
+ /** What has been typed after the `$`. */
8
+ query: string;
9
+ /** Where the `$` is. */
10
+ from: number;
11
+ /** The caret. */
12
+ to: number;
13
+ }
14
+ export interface SkillInvocationMatch {
15
+ name: string;
16
+ /** Where the `$` is. */
17
+ from: number;
18
+ /** Just after the name. */
19
+ to: number;
20
+ }
21
+ /** The skill token being typed at `caret`, or null when the caret is not in one. */
22
+ export declare function skillTokenAt(text: string, caret: number): SkillToken | null;
23
+ /** Every `$name` token in the message, whether or not the name is a loaded skill. */
24
+ export declare function skillInvocationMatches(text: string): SkillInvocationMatch[];
25
+ /** Every `$name` in the message that names an enabled skill, in message order, once each. */
26
+ export declare function skillInvocations(text: string, skills: ReadonlySet<string>): string[];
8
27
  /** Offers the loaded skills at a `$` that starts a word. Every other completion is `base`'s. */
9
28
  export declare function skillCompletions(base: AutocompleteProvider, skills: () => readonly SkillEntry[]): AutocompleteProvider;
@@ -1,24 +1,44 @@
1
- /** Rewrites a leading `$name` of a loaded skill into `/skill:name`. Anything else passes through, so `$5` stays text. */
2
- export function expandSkillInvocation(text, skills) {
3
- const trimmed = text.trimStart();
4
- const match = /^\$(\S+)(?=\s|$)/.exec(trimmed);
5
- if (!match || !skills.has(match[1]))
6
- return text;
7
- return `/skill:${match[1]}${trimmed.slice(match[0].length)}`;
8
- }
9
1
  /** A `$` that starts a word, and the partial name after it, at the cursor. */
10
- const SKILL_TOKEN = /(?:^|\s)\$([^\s$]*)$/;
2
+ const SKILL_TOKEN = /(?:^|[\s(])\$([^\s$]*)$/;
3
+ /** A `$name` at a word start, ending at whitespace, punctuation or the end of the message. */
4
+ const SKILL_INVOCATION = /(?:^|[\s(])\$([A-Za-z0-9][A-Za-z0-9_-]*)(?=[\s.,;:!?)]|$)/gu;
11
5
  /** A line whose first word is a skill invocation. */
12
6
  const SKILL_LINE = /^\s*\$\S/;
7
+ /** The skill token being typed at `caret`, or null when the caret is not in one. */
8
+ export function skillTokenAt(text, caret) {
9
+ const match = SKILL_TOKEN.exec(text.slice(0, caret));
10
+ if (!match)
11
+ return null;
12
+ const query = match[1] ?? '';
13
+ return { query, from: caret - query.length - 1, to: caret };
14
+ }
15
+ /** Every `$name` token in the message, whether or not the name is a loaded skill. */
16
+ export function skillInvocationMatches(text) {
17
+ const found = [];
18
+ for (const match of text.matchAll(SKILL_INVOCATION)) {
19
+ const from = match.index + match[0].indexOf('$');
20
+ found.push({ name: match[1], from, to: from + 1 + match[1].length });
21
+ }
22
+ return found;
23
+ }
24
+ /** Every `$name` in the message that names an enabled skill, in message order, once each. */
25
+ export function skillInvocations(text, skills) {
26
+ const found = [];
27
+ for (const match of skillInvocationMatches(text)) {
28
+ if (skills.has(match.name) && !found.includes(match.name))
29
+ found.push(match.name);
30
+ }
31
+ return found;
32
+ }
13
33
  /** Offers the loaded skills at a `$` that starts a word. Every other completion is `base`'s. */
14
34
  export function skillCompletions(base, skills) {
15
35
  return {
16
36
  triggerCharacters: [...(base.triggerCharacters ?? []), '$'],
17
37
  async getSuggestions(lines, cursorLine, cursorCol, options) {
18
38
  const line = lines[cursorLine] ?? '';
19
- const token = SKILL_TOKEN.exec(line.slice(0, cursorCol));
39
+ const token = skillTokenAt(line, cursorCol);
20
40
  if (token) {
21
- const partial = token[1];
41
+ const partial = token.query;
22
42
  const items = skills()
23
43
  .filter((skill) => skill.name.startsWith(partial))
24
44
  .map((skill) => ({ value: skill.name, label: `$${skill.name}`, description: skill.description }));
@@ -11,8 +11,14 @@ export interface BandState {
11
11
  account?: string;
12
12
  inputTokens: number;
13
13
  outputTokens: number;
14
+ /** Share of the model's window the latest request used; null until something measured it. */
15
+ contextPercent?: number | null;
16
+ /** Auto-compaction is on, so the band says so beside the reading. */
17
+ autoCompact?: boolean;
14
18
  }
15
19
  export declare function singleLine(text: string): string;
16
20
  export declare function displayProjectName(cwd: string): string;
21
+ /** `18.3%/1M`, `?/1M` before anything measured it, and `(auto)` when Pi compacts on its own. */
22
+ export declare function formatContextReading(state: Pick<BandState, 'model' | 'contextPercent' | 'autoCompact'>): string;
17
23
  export declare function formatTokenCount(value: number): string;
18
24
  export declare function renderStatusBand(state: BandState, width: number, theme: Theme): string;
@@ -15,6 +15,14 @@ export function singleLine(text) {
15
15
  export function displayProjectName(cwd) {
16
16
  return singleLine(basename(cwd) || cwd || sep);
17
17
  }
18
+ /** `18.3%/1M`, `?/1M` before anything measured it, and `(auto)` when Pi compacts on its own. */
19
+ export function formatContextReading(state) {
20
+ const window = state.model?.contextWindow && state.model.contextWindow > 0 ? formatTokenCount(state.model.contextWindow) : '?';
21
+ if (state.contextPercent === null || state.contextPercent === undefined || !Number.isFinite(state.contextPercent))
22
+ return `?/${window}${state.autoCompact ? ' (auto)' : ''}`;
23
+ const bounded = Math.max(0, Math.min(999, state.contextPercent));
24
+ return `${bounded.toFixed(1)}%/${window}${state.autoCompact ? ' (auto)' : ''}`;
25
+ }
18
26
  export function formatTokenCount(value) {
19
27
  const count = Math.max(0, Number.isFinite(value) ? Math.floor(value) : 0);
20
28
  if (count >= 1_000_000_000)
@@ -60,7 +68,13 @@ export function renderStatusBand(state, width, theme) {
60
68
  { text: displayProjectName(state.cwd), color: colors.brightAluminum },
61
69
  { text: singleLine(state.branch ?? '') || '—', color: colors.readoutGreen },
62
70
  { text: `${account} · ${model} · ${effort}`, color: colors.electricBlue },
63
- { text: `↑ ${formatTokenCount(state.inputTokens)} ↓ ${formatTokenCount(state.outputTokens)}`, color: colors.titaniumGold }
71
+ { text: `↑ ${formatTokenCount(state.inputTokens)} ↓ ${formatTokenCount(state.outputTokens)}`, color: colors.titaniumGold },
72
+ ...(state.contextPercent === undefined ? [] : [{
73
+ text: formatContextReading(state),
74
+ color: state.contextPercent !== null && state.contextPercent >= 90
75
+ ? colors.alertRed
76
+ : state.contextPercent !== null && state.contextPercent >= 70 ? colors.warningAmber : colors.dimAluminum
77
+ }])
64
78
  ], size);
65
79
  const separator = color(theme, colors.subtleGray, ' | ');
66
80
  return parts.map(part => color(theme, part.color, part.text)).join(separator);
@@ -26,6 +26,15 @@
26
26
  * SOFTWARE.
27
27
  */
28
28
  import { Theme } from '@earendil-works/pi-coding-agent';
29
+ /**
30
+ * Categorical colours for a bar that splits one reading by kind — the same values as the App's
31
+ * `--data-1..4` tokens, so a screen and a terminal show the same split in the same colours. They
32
+ * carry no severity: a red run is a category, not a problem.
33
+ */
34
+ export declare const SERIES_COLORS: {
35
+ readonly dark: readonly ["#3987e5", "#d95926", "#199e70", "#c98500"];
36
+ readonly light: readonly ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"];
37
+ };
29
38
  export declare const TITANIUM: {
30
39
  readonly brushedTitanium: "#151820";
31
40
  readonly darkTitanium: "#0f1216";
@@ -28,6 +28,15 @@
28
28
  import { Theme } from '@earendil-works/pi-coding-agent';
29
29
  import { SELECTION_COLORS } from "./selection.js";
30
30
  const orange = { dark: '#ffb347', light: '#9a7326' };
31
+ /**
32
+ * Categorical colours for a bar that splits one reading by kind — the same values as the App's
33
+ * `--data-1..4` tokens, so a screen and a terminal show the same split in the same colours. They
34
+ * carry no severity: a red run is a category, not a problem.
35
+ */
36
+ export const SERIES_COLORS = {
37
+ dark: ['#3987e5', '#d95926', '#199e70', '#c98500'],
38
+ light: ['#2a78d6', '#eb6834', '#1baf7a', '#eda100']
39
+ };
31
40
  export const TITANIUM = {
32
41
  brushedTitanium: '#151820',
33
42
  darkTitanium: '#0f1216',
@@ -1,4 +1,23 @@
1
+ /** A skill folder name, without `skills/` or backticks. */
2
+ export declare const SKILL_NAME: RegExp;
3
+ /** One skill's file: what `skill_load` reads, and what the prompt compiler includes. */
4
+ export interface SkillFile {
5
+ name: string;
6
+ /** The `SKILL.md` file the text came from. */
7
+ path: string;
8
+ /** The skill folder that relative references resolve against. */
9
+ baseDir: string;
10
+ /** The instructions after the frontmatter. */
11
+ body: string;
12
+ /** Files in the skill's `scripts/` folder, empty when it has none. */
13
+ helpers: string[];
14
+ }
1
15
  /** Locate release-owned resources from source, the SDK, or a bundled executable. */
2
16
  export declare function defaultSkillPath(): string;
3
17
  /** Variant skills win on a name collision, without modifying a pinned variant. */
4
18
  export declare function defaultSkillPaths(variantDir: string | null | undefined): string[];
19
+ /**
20
+ * A skill by folder name: the pinned variant first, then the shipped `plugin-authoring` skill.
21
+ * The body has its frontmatter removed. Returns null when no skill has that name.
22
+ */
23
+ export declare function readSkillFile(variantDir: string | null | undefined, name: string): SkillFile | null;
@@ -1,6 +1,9 @@
1
- import { existsSync } from 'node:fs';
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { bodyOf } from "../core/frontmatter.js";
5
+ /** A skill folder name, without `skills/` or backticks. */
6
+ export const SKILL_NAME = /^[a-z0-9][a-z0-9_-]*$/;
4
7
  /** Locate release-owned resources from source, the SDK, or a bundled executable. */
5
8
  export function defaultSkillPath() {
6
9
  let dir = dirname(fileURLToPath(import.meta.url));
@@ -18,3 +21,26 @@ export function defaultSkillPath() {
18
21
  export function defaultSkillPaths(variantDir) {
19
22
  return variantDir && existsSync(join(variantDir, 'skills', 'plugin-authoring', 'SKILL.md')) ? [] : [defaultSkillPath()];
20
23
  }
24
+ /**
25
+ * A skill by folder name: the pinned variant first, then the shipped `plugin-authoring` skill.
26
+ * The body has its frontmatter removed. Returns null when no skill has that name.
27
+ */
28
+ export function readSkillFile(variantDir, name) {
29
+ const wanted = name.trim().replace(/^skills\//, '').replace(/`/g, '');
30
+ if (!SKILL_NAME.test(wanted))
31
+ return null;
32
+ const variant = variantDir ? join(variantDir, 'skills', wanted, 'SKILL.md') : null;
33
+ const builtin = wanted === 'plugin-authoring' && defaultSkillPaths(variantDir).length ? defaultSkillPath() : null;
34
+ const path = variant && existsSync(variant) && statSync(variant).isFile() ? variant : builtin;
35
+ if (!path)
36
+ return null;
37
+ const baseDir = dirname(path);
38
+ const scripts = join(baseDir, 'scripts');
39
+ return {
40
+ name: wanted,
41
+ path,
42
+ baseDir,
43
+ body: bodyOf(readFileSync(path, 'utf8')),
44
+ helpers: existsSync(scripts) ? readdirSync(scripts) : []
45
+ };
46
+ }
@@ -8,7 +8,7 @@ import * as recall from "../history/recall.js";
8
8
  import * as trajectory from "../history/trajectory.js";
9
9
  import * as notes from "../wiki/notes.js";
10
10
  import * as proposals from "../plugins/proposals.js";
11
- import { defaultSkillPaths } from "./defaultSkills.js";
11
+ import { defaultSkillPaths, readSkillFile, SKILL_NAME } from "./defaultSkills.js";
12
12
  function str(params, key) {
13
13
  const value = params[key];
14
14
  return typeof value === 'string' ? value : '';
@@ -60,20 +60,19 @@ export function dispatch(env, context, call, params, options = {}) {
60
60
  /** A skill's text from the run's variant, or the list of its skills. */
61
61
  export function loadSkill(variantDir, name) {
62
62
  const skills = variantDir && existsSync(join(variantDir, 'skills')) ? readdirSync(join(variantDir, 'skills'), { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(join(variantDir, 'skills', entry.name, 'SKILL.md'))).map((entry) => entry.name).sort() : [];
63
- const defaults = defaultSkillPaths(variantDir);
64
- if (defaults.length)
63
+ if (!skills.includes('plugin-authoring') && defaultSkillPaths(variantDir).length)
65
64
  skills.push('plugin-authoring');
66
65
  skills.sort();
67
66
  const wanted = name.trim().replace(/^skills\//, '').replace(/`/g, '');
68
67
  if (!wanted)
69
68
  return skills.length ? `Your skills: ${skills.join(', ')}. Load one with skill_load and its name.` : 'You have no skills.';
70
- if (!/^[a-z0-9][a-z0-9_-]*$/.test(wanted))
69
+ if (!SKILL_NAME.test(wanted))
71
70
  throw invalid('A skill name is lowercase letters, digits, _ or -.');
72
71
  if (!skills.includes(wanted))
73
72
  return `There is no skill named ${wanted}.${skills.length ? ` Your skills: ${skills.join(', ')}.` : ''}`;
74
- if (wanted === 'plugin-authoring' && defaults.length)
75
- return readFileSync(defaults[0], 'utf8');
76
- const dir = join(variantDir, 'skills', wanted);
77
- const helpers = existsSync(join(dir, 'scripts')) ? readdirSync(join(dir, 'scripts')) : [];
78
- return `${readFileSync(join(dir, 'SKILL.md'), 'utf8')}${helpers.length ? `\n\n(This skill's helpers are in ${join(dir, 'scripts')}: ${helpers.join(', ')}.)` : ''}`;
73
+ const skill = readSkillFile(variantDir, wanted);
74
+ if (!skill)
75
+ return `There is no skill named ${wanted}.${skills.length ? ` Your skills: ${skills.join(', ')}.` : ''}`;
76
+ const helperNote = skill.helpers.length ? `\n\n(This skill's helpers are in ${join(skill.baseDir, 'scripts')}: ${skill.helpers.join(', ')}.)` : '';
77
+ return `${readFileSync(skill.path, 'utf8')}${helperNote}`;
79
78
  }
@@ -1,4 +1,4 @@
1
1
  import type { Subagents } from "../sessions/subagentService.js";
2
2
  import type { ToolSpec } from "./types.js";
3
- export { SPAWN_SUBAGENT, SUBAGENT_RELATION, DEFAULT_SUBAGENT_DEPTH, MAX_SUBAGENT_DEPTH, subagentDepth, subagentReport, type SubagentOptions } from "../sessions/subagents.js";
3
+ export { SPAWN_SUBAGENT, SUBAGENT_RELATION, DEFAULT_SUBAGENT_CHILDREN, DEFAULT_SUBAGENT_DEPTH, MAX_SUBAGENT_CHILDREN, MAX_SUBAGENT_DEPTH, subagentDepth, subagentQuota, subagentReport, type SubagentOptions, type SubagentQuota } from "../sessions/subagents.js";
4
4
  export declare function subagentTools(service: Subagents, parentRunId: string): ToolSpec[];
@@ -1,6 +1,6 @@
1
1
  import { HarnessError, invalid } from "../core/errors.js";
2
2
  import { SPAWN_SUBAGENT, WAIT_SUBAGENTS, SUBAGENT_RECEIPT, MAX_SUBAGENT_TITLE_WORDS, subagentTitle } from "../sessions/subagents.js";
3
- export { SPAWN_SUBAGENT, SUBAGENT_RELATION, DEFAULT_SUBAGENT_DEPTH, MAX_SUBAGENT_DEPTH, subagentDepth, subagentReport } from "../sessions/subagents.js";
3
+ export { SPAWN_SUBAGENT, SUBAGENT_RELATION, DEFAULT_SUBAGENT_CHILDREN, DEFAULT_SUBAGENT_DEPTH, MAX_SUBAGENT_CHILDREN, MAX_SUBAGENT_DEPTH, subagentDepth, subagentQuota, subagentReport } from "../sessions/subagents.js";
4
4
  function reported(parentRunId, results, spawned) {
5
5
  const included = [];
6
6
  let length = 0;
@@ -14,6 +14,8 @@ function reported(parentRunId, results, spawned) {
14
14
  return { text: JSON.stringify({ results: included, ...(results.length > included.length ? { remaining: results.slice(included.length).map((result) => result.runId) } : {}) }), details: { [SUBAGENT_RECEIPT]: receipt } };
15
15
  }
16
16
  export function subagentTools(service, parentRunId) {
17
+ const quota = service.quota(parentRunId);
18
+ const budget = `This run allows at most ${quota.children} children: ${Object.entries(quota.profiles).map(([name, value]) => `${value} ${name}`).join(', ')}, ${quota.other} of any other profile and ${quota.unprofiled} unprofiled; a refused spawn means do the work yourself.`;
17
19
  const execute = (fn) => async (input) => {
18
20
  try {
19
21
  return await fn(input);
@@ -27,7 +29,7 @@ export function subagentTools(service, parentRunId) {
27
29
  return [{
28
30
  name: SPAWN_SUBAGENT,
29
31
  label: 'Start a subagent',
30
- description: 'Start a fresh child run for independent work. Delegate substantial, bounded tasks that benefit from a separate context, not simple lookups, tiny edits or tightly coupled steps. Prefer a named specialist profile; omit agent only when no profile fits. Plan mode permits only eligible read-only research profiles. Give a short title and a self-contained brief: the child has no conversation history and no more capabilities than you. The optional tools field only narrows the profile and parent intersection; in plan mode, omit it unless you need a stricter subset. Returns its run ID immediately by default so you can continue other useful work. Results arrive automatically before you finish. Use wait_subagents when you need results before proceeding, or wait: true for an inline result. Avoid overlapping write assignments. Stopping you stops your children. To resume a child that stopped before finishing (interrupted or failed), pass continue with its run ID and no title, agent or tools: it reopens that child\'s own conversation with the same profile and tools, and brief becomes an optional extra instruction.',
32
+ description: 'Start a fresh child run for independent work. Delegate substantial, bounded tasks that benefit from a separate context, not simple lookups, tiny edits or tightly coupled steps. Prefer a named specialist profile; omit agent only when no profile fits. Plan mode permits only eligible read-only research profiles. Give a short title and a self-contained brief: the child has no conversation history and no more capabilities than you. The optional tools field only narrows the profile and parent intersection; in plan mode, omit it unless you need a stricter subset. Returns its run ID immediately by default so you can continue other useful work. Results arrive automatically before you finish. Use wait_subagents when you need results before proceeding, or wait: true for an inline result. Avoid overlapping write assignments. Stopping you stops your children. To resume a child that stopped before finishing (interrupted or failed), pass continue with its run ID and no title, agent or tools: it reopens that child\'s own conversation with the same profile and tools, and brief becomes an optional extra instruction. ' + budget,
31
33
  planModeSafe: input => service.planSpawnRefusal(parentRunId, input) === null,
32
34
  parameters: (Type) => Type.Object({
33
35
  title: Type.Optional(Type.String({ description: `Required for a new child: a short imperative title for the roster, at most ${MAX_SUBAGENT_TITLE_WORDS} words, such as "Map the auth flow"` })),