SLOPSHOPPER

statusline-native

In-session Client TUI for statusline configuration

panecommand
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · statusline-native
│ ┃ task.title ✕ › fix the failing auth test and add an audit log call │ ┃ task.title · task.readonly │ ┃ task.unknown ⏺ Read(src/auth.ts) │ ┃ native.lib.backend.check_the_bound_backend_e ⎿ Read 6 lines │ ┃ [ ↑ ] [ ↓ ] [ profiles.refresh ] [ task.clos ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /statusline-task │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · task.title
task.title · task.readonly task.unknown native.lib.backend.check_the_bound_backend_executable_a… [ ↑ ] [ ↓ ] [ profiles.refresh ] [ task.close ]
Pane · native.hooks.register.statusline_configuration
native.hooks.register.could_not_open_the_client_editor native.backend_error native.capacity.retained [ native.hooks.register.retry_client ] [ native.hooks.register.discard_pending_close ]
README

Claude Code Statusline

English | 简体中文

CI npm MIT License

A Claude Code status line for Linux, WSL, Windows, and macOS. See model and reasoning effort, directory, Git, context, usage limits, tokens, and task timing at a glance. Configure the main line and individual subagent rows through an in-session editor, a terminal UI, a wizard, or the CLI.

Features · Screenshots · Quick installation · Common configuration · User guide · Troubleshooting

<a id="phase-4-in-stable-v150"></a> <a id="phase-5-in-stable-v160"></a> <a id="v161-clearer-external-tui-sections"></a>

Features

  • Add explicit data sources: manage local JSON, GitHub checks and command values in either editor or CLI, with reviewed activation, optional session-owned GitHub refresh and directory/PR links. Extension guide.
  • Reuse display schemes across projects: save and preview named schemes, then bind project roots to complete display settings. Profile guide.
  • Inspect task evidence: open /statusline-task or the CLI for task, agent, timing-source and coverage details on demand. Task details.
  • Compose your statusline: add, copy and arrange independent components, linked groups, literal text and left/right alignment in either editor. Composition guide.
  • Control visibility and appearance: hide confirmed empty/clean states, set usage thresholds, choose per-item foreground/background colors, themes and short percentage bars, and opt into Powerline.
  • Choose your languages: English, 简体中文, 繁體中文, 日本語 and 한국어 for interfaces and actual statusline output, independently; interface changes save immediately, output language saves with display settings. See language examples.
  • Diagnose supplied input: inspect real statusline JSON and matching saved observations without collecting or writing. See input diagnosis.
  • Find what to show: 65 main metrics and 15 subagent metrics, plus text and flexible spacers, with ranked multilingual search, category filters and source/requirement guidance.
  • Estimate session cost rates: choose session or cumulative API time as the denominator, with a one-minute observation window and explicit units. Metric definitions.
  • Track the right scope: session token totals, per-task subagent rows, and total task time covering queueing, agents and main-agent wrap-up; optional execution time excludes verified user waits.
  • Adjust presentation: model and number formats, labels, built-in icons, colors, directory styles, and automatic or explicit rows with priorities and width limits.
  • Keep Unicode intact: joined emoji, combining marks and CJK text stay together when rows wrap, clip or appear in previews.
  • Review configuration changes: three complete display schemes, six existing presets and portable JSON, with import differences and candidate previews before accepting a draft and saving.
  • Choose an editor: Main, Subagents, Settings, and Layout pages share the same configuration. Claude appearance and behavior preferences use a separate Apply action.
  • Follow Claude themes: the in-session editor adapts text, keys and selection to the applied theme; sample previews retain production colors on a separately chosen light/dark background.
  • Follow terminal colors: external TUI text and bold keys use terminal defaults, with cyan headings; previews show the selected palette on the current terminal background.
  • Enable optional live metrics: runtime state, agent count, tool progress, request timing, and per-task usage are opt-in. Missing or partial observations stay distinguishable.

Rendering uses Claude Code input and local state without making network requests or using model tokens. The question-and-answer wizard uses Claude model turns. See field definitions for data sources and availability.

<a id="界面预览"></a>

Screenshots

Component instances, copies and left/right layout captures.

Search, categories, source guidance and import review captures.

The main status line at the bottom of session screenshots shows actual data; configuration Preview regions use fixed samples. Fonts, colors and widths depend on terminal settings. Image sources and archive.

Linux terminal captures show the shared language selector and Chinese interface. These are reconstructions of actual PTY cells with sample previews; sources and all pages.

English native language selector

简体中文 native language selector

简体中文 external language selector

In-session TUI

Run /statusline-configure-native inside the current Claude Code session, then click the Client region once before using the keyboard. The editor follows the Claude theme; choose the preview background to match the terminal and compare the selected palette. Compare terminal/theme combinations.

Linux: Main and the status line

Linux in-session TUI Main page and actual main status line

Subagents: choose items and ordering for individual agent rows.

Linux in-session TUI Subagents page with sample preview

Settings: adjust appearance, refresh behavior and formatting.

Linux in-session TUI Settings page with sample preview

Layout: set rows, item priorities and maximum widths.

Linux in-session TUI Layout page with sample preview

Earlier theme captures used a dark preview surface; the current editor offers a separate light/dark preview choice. These images reconstruct real terminal cells. Capture provenance.

Linux light theme native editor

Linux dark theme native editor

Main: select and reorder main status line items.

Windows in-session TUI Main page with sample preview

Subagents: choose items and ordering for individual agent rows.

Windows in-session TUI Subagents page with sample preview

Settings: adjust appearance, refresh behavior and formatting.

Windows in-session TUI Settings page with sample preview

Layout: set rows, item priorities and maximum widths.

Windows in-session TUI Layout page with sample preview

Only Main was supplied for this batch. The existing interaction limitation and checks are documented in macOS mouse reporting and Client focus.

Main: select and reorder main status line items.

macOS in-session TUI Main page with sample preview

External TUI

Run /statusline-configure in Claude Code, or claude-statusline configure in a standalone terminal.

Previews use the current terminal background and selected palette. Compare ansi in Settings when default looks faint. These are terminal-output reconstructions from dedicated GNOME profiles; capture sources.

Light background, Palette: default

Linux light terminal with default palette

Light background, Palette: ansi

Linux light terminal with ANSI palette

Dark background, Palette: default

Linux dark terminal with default palette

Main: select and reorder main status line items.

Linux external TUI Main page with sample preview

Subagents: choose items and ordering for individual agent rows.

Linux external TUI Subagents page with sample preview

Settings: adjust appearance, refresh behavior and formatting.

Linux external TUI Settings page with sample preview

Layout: set rows, item priorities and maximum widths.

Linux external TUI Layout page with sample preview

Main: select and reorder main status line items.

Windows external TUI Main page with sample preview

Subagents: choose items and ordering for individual agent rows.

Windows external TUI Subagents page with sample preview

Settings: adjust appearance, refresh behavior and formatting.

Windows external TUI Settings page with sample preview

Layout: set rows, item priorities and maximum widths.

Windows external TUI Layout page with sample preview

Main: select and reorder main status line items.

macOS external TUI Main page with sample preview

Subagents: choose items and ordering for individual agent rows.

macOS external TUI Subagents page with sample preview

Settings: adjust appearance, refresh behavior and formatting.

macOS external TUI Settings page with sample preview

Layout: set rows, item priorities and maximum widths.

macOS external TUI Layout page with sample preview

Earlier screenshots and terminal reconstructions remain in the archive.

Supported platforms

PlatformSupported environment
Linux / WSLNode 22.x or 24.x, x64
Windows 10/11Node 22.x or 24.x, x64
macOS 14+Node 22.x or 24.x, Intel / Apple Silicon

Windows ARM devices use x64 Node under emulation; native Windows ARM64 and 32-bit runtimes are outside the current support contract. Git information requires git.

Claude Code feature requirements: subagent rows 2.1.205+; local argument-based configuration and external TUI entry 2.1.258+; in-session Client 2.1.287+; native timing and advanced live-metrics collection 2.1.289+. Unsupported or unknown host versions suspend the corresponding integration. See requirements.

<a id="install-current-source"></a> <a id="install-from-a-release-recommended"></a> <a id="install-source-at-a-fixed-tag"></a> <a id="从-release-安装推荐"></a> <a id="从固定标签源码安装"></a> <a id="从当前源码安装"></a> <a id="升级与卸载"></a> <a id="常用配置"></a> <a id="快速安装"></a> <a id="接入-claude-code"></a> <a id="支持范围"></a> <a id="文档与帮助"></a> <a id="许可证"></a>

Quick installation

Install Node 22.x or 24.x with npm and Claude Code CLI. One npm package includes the supported native dependencies and needs no Python or compiler. Existing Python installation and rollback.

Install the package

For a reviewed installation in an interactive terminal, run npx @fbincon/claude-code-statusline. It verifies the durable global entry before opening setup. An installed claude-statusline without a subcommand opens the same flow. Installation stages.

Bash, Zsh, and PowerShell:

npm install --global --ignore-scripts @fbincon/claude-code-statusline

Integrate with Claude Code

Ensure the npm command directory is on PATH, then run:

claude-statusline --version
claude-statusline setup --dry-run
claude-statusline setup
claude-statusline doctor

On Windows, use claude-statusline.cmd, or invoke the installed JavaScript entry with Node. Restart Claude Code in a trusted terminal after integration.

Both editors default on for compatible hosts, respecting saved disablement preferences. Native timing and advanced live metrics both require explicit opt-in on compatible hosts; saved choices are preserved. Package installation and Claude integration are separate steps. setup connects checks, scheme preview and integration review; install remains the direct integration command. Existing conflicting resources require explicit handling.

Source development on main uses Node and TypeScript; follow the source development guide. Release attachments support offline npm installation; the installation guide covers fixed versions and Python recovery.

Download checksums and platform-specific instructions are in the installation guide; source builds are in the development guide.

Common configuration

In either editor, use Ctrl+P or Settings → Quick setup to choose a use case, appearance and sample before editing or saving. Text fields support grapheme cursor editing. Item details explain configuration, requirements and sample fitting. See quick setup and explanation.

Find items, understand their sources, and review imports.

Entry pointUse
/statusline-configure-nativeClient TUI in the current session; see native editor
/statusline-configureTUI in a supported external terminal; see external entry
claude-statusline configureFull TUI in the current standalone terminal
/statusline-configClaude question-and-answer wizard; supported argument-based commands execute locally on compatible hosts
claude-statusline config ...Inspect settings, set exact ordering, or configure from scripts

<a id="v130a2-external-tui-and-in-session-client"></a>

Interface language

Both editors have Interface language (saved immediately) in Settings, with choices English / 简体中文 / 繁體中文(台灣) / 繁體中文(香港) / 日本語 / 한국어. The default is English. Switching keeps your page, selection, search and unsaved display edits; cancelling display changes keeps the language choice. Other open windows read it when reopened or reloaded.

claude-statusline config language set ja
claude-statusline config language show
claude-statusline config language reset
claude-statusline --language en --help

--language en|zh-CN|zh-TW|zh-HK|ja|ko precedes the command and affects only that invocation; for configure it sets the initial language. Commands, IDs, configuration values and custom text retain their values. Interface language does not change output language. See language settings.

Statusline language

Choose Statusline language (save with display settings) → English / 简体中文 / 繁體中文(台灣) / 繁體中文(香港) / 日本語 / 한국어 in either editor. Preview switches immediately; Save changes the actual main and subagent output on the next refresh, while Cancel discards the draft. English is the default.

claude-statusline config set statusline-language zh-TW
claude-statusline config set statusline-language en

English statusline output

Simplified Chinese statusline output

These are real CLI terminal captures with fixed input.

Built-in labels and known states are translated. Technical units, model names, branches, paths and custom text are preserved. See output language.

Native configuration editor

Click the Client region once. Use Tab to change pages, Space to toggle, arrows to select or reorder, Ctrl+E for item formatting and source guidance, / to search, and Ctrl+F for categories. Clear filters before reordering. S saves and stays, F saves and closes, and Q discards unsaved changes; lowercase letters work too. Footer controls follow the current page or input mode. Ctrl+G cancels input. Claude preferences apply separately.

External and standalone terminal TUI

Use Tab to change pages, Space to toggle, and arrows to select or reorder. Ctrl+S saves after field input is finished; Enter saves on item and original settings rows, or edits/confirms advanced fields. Esc cancels input first, then cancels the editor; Ctrl+C interrupts without saving. The minimum terminal size is 64×18.

The external entry uses tmux or GNOME Terminal on Linux, tmux or Terminal.app on macOS, and the system's new-console launcher on Windows. For SSH or unavailable launchers, run claude-statusline configure in the current terminal.

Define a compact main line:

claude-statusline config set-items model-with-effort current-dir git context-remaining task-timer
claude-statusline config set directory-style home
claude-statusline config show

Configuration is per user. set-items replaces the enabled set; enable and disable make incremental changes. See recipes, formatting and layouts, and the CLI reference.

<a id="upgrade-to-v161"></a>

Upgrading and uninstalling

Review and apply the package change, then restart Claude Code:

claude-statusline update --check
claude-statusline update
claude-statusline doctor

Use package management for exact versions, prefixes, rollback and separate configuration restoration. Existing Python installations should first follow the migration and rollback procedure. Saved display settings, runtime state, and integration preferences remain.

Remove Claude integration before uninstalling the package:

claude-statusline uninstall --dry-run
claude-statusline uninstall
npm uninstall --global @fbincon/claude-code-statusline

Display settings and backups remain available; see uninstalling.

Project structure

claude-code-statusline/
├── .github/
│   ├── ISSUE_TEMPLATE/               # Bilingual bug form and feedback links
│   ├── pull_request_template.md      # Bilingual PR template
│   ├── dependabot.yml                # Actions version-update policy
│   └── workflows/
│       ├── ci.yml                    # Documentation checks or complete product matrix
│       ├── npm-publish.yml           # npm publication through OIDC
│       ├── preview-downloads.yml     # Public bytes and installation checks
│       └── reference.yml             # Manual historical Python verification
├── packages/                     # Four business packages
│   ├── core/src/                 # Configuration, protocols, pure state, rendering and Unicode
│   │   ├── editor/               # Shared drafts, cursor input, quick setup and explanations
│   │   ├── rendering/            # Rendering, fitting and optional explanation records
│   │   ├── contracts/            # Independently versioned editor/runtime interfaces
│   │   └── i18n/                 # Registry-generated languages; sources in core/resources
│   ├── platform/src/             # Files, locks, processes, clocks and terminal adapters
│   ├── cli/                      # Commands, integration, runtime and recovery
│   │   ├── src/                  # Installation and editor protocols
│   │   └── resources/            # Two configuration skill templates
│   └── tui/src/                  # Standalone terminal editor
├── mods/
│   ├── statusline-native/        # In-session editor: hooks, lib, ui, tests
│   └── statusline-runtime/       # Timing and optional live metrics
├── tests/fixtures/               # Shared contracts, Unicode and frozen reference data
├── tools/
│   ├── generation/               # Shared resource generation
│   ├── checks/                   # Documentation, archive and aggregate checks
│   ├── build/                    # Fixed sources, universal offline packaging and digests
│   ├── acceptance/               # Installation, Mods, terminals, power and budgeted acceptance
│   ├── benchmarks/               # Functional fixtures and optional descriptive measurement
│   ├── release/                  # Candidate evidence and release-note preparation
│   ├── migration/                # Stage ledgers, frozen references and compatibility tests
│   ├── testing/                  # Development-only test support package
│   ├── typescript/               # Runtime constraints and test entry points
│   └── unicode/                  # Pinned data, provenance and licenses
├── archive/python/               # Frozen Python implementation, tests, tools and publishing workflows
├── examples/schemes/             # Shareable built-in complete schemes
├── docs/                         # Usage, development, migration and historical releases
│   ├── reference/                # CLI and configuration reference
│   ├── development/              # Architecture, testing and stage records
│   ├── images/                   # UI screenshots and historical captures
│   └── releases/                 # Historical release notes
├── package.json / package-lock.json
├── tsconfig*.json / .node-version
├── README.md / README.zh-CN.md
├── CONTRIBUTING.md / CONTRIBUTING.zh-CN.md
├── SECURITY.md / SECURITY.zh-CN.md
├── CHANGELOG.md / CHANGELOG.zh-CN.md
└── LICENSE

Documentation and help

Source 53 files
hooks/register.ts 986 lines
1import { performSourceAction, closeSources } from '../lib/editor/source-manager.ts';
2import { taskDetailLines } from '../lib/editor/task-detail.ts';
3import { receivePreset } from '../lib/editor/quick-setup.ts';
4import { performProfileAction } from '../lib/editor/profile-manager.ts';
5import type {
6  Register,
7  On,
8  EngineInterface,
9  PluginOptions,
10  Timer,
11} from 'claude-code';
12import {
13  BackendError,
14  parseResponse,
15  processFailure,
16  requestText,
17} from '../lib/backend.ts';
18import { Editor, copyDraft, sameDraft } from '../lib/editor/draft.ts';
19import { createReview } from '../lib/editor/import-review.ts';
20import { canEdit, validPreferenceValue, preferences, preferenceChanged } from '../lib/preferences.ts';
21import type {
22  Draft,
23  TaskDetails,
24  Operation,
25  ResultFor,
26} from '../lib/generated-contracts.ts';
27import { MIN_COLUMNS, MIN_ROWS, contentColumns, clip } from '../ui/layout.ts';
28import { recoveryButton, styles } from '../ui/theme.ts';
29import { clientProps } from '../lib/session.ts';
30import type { View } from '../lib/session.ts';
31import { withinBudget } from '../ui/frame.ts';
32import { parseBatch } from '../lib/client/messages.ts';
33import { handleKey } from '../lib/client/keys.ts';
34import { DEFAULT_PREVIEW_BACKGROUND, PREVIEW_BACKGROUND_KEY, previewBackground } from '../lib/preview-preferences.ts';
35import type { PreviewBackground } from '../lib/preview-preferences.ts';
36import { text as localizedText, t } from '../lib/i18n/index.ts';
37import type { Language } from '../lib/i18n/index.ts';
38import { setMessage, failureMessage, setResult, viewMessage } from '../lib/i18n/messages.ts';
39import { binding } from '../lib/launch.ts';
40
41const PANE = 'statusline-native';
42const COMMAND = 'statusline-configure-native';
43
44
45async function callBackend<O extends Operation>(
46  $: EngineInterface,
47  options: PluginOptions,
48  operation: O,
49  payload: unknown = {},
50): Promise<ResultFor<O>> {
51  try {
52    const launch = binding(options, await $.env.get('CLAUDE_STATUSLINE_NATIVE_EXECUTABLE') || undefined);
53    const directory =
54      (await $.env.get('CLAUDE_CONFIG_DIR')) ||
55      (typeof options.configDir === 'string' ? options.configDir : undefined);
56    const argv = directory
57      ? [launch.executable, ...launch.args, 'ui', '--config-dir', directory]
58      : [launch.executable, ...launch.args, 'ui'];
59    const output = await $.process.run(argv, {
60      stdin: requestText(operation, payload),
61      timeoutMs: 30000,
62    });
63    const result = parseResponse(operation, output);
64    if (
65      'backend_version' in result &&
66      typeof options.backendVersion === 'string' &&
67      options.backendVersion &&
68      result.backend_version !== options.backendVersion
69    ) {
70      throw new BackendError(
71        'backend_version_mismatch',
72        localizedText("native.hooks.register.the_installed_mod_and_backend_versions_differ_reinstall"),
73      );
74    }
75    return result;
76  } catch (error) {
77    throw processFailure(error);
78  }
79}
80
81function emptyView(): View {
82  return {
83    language: 'en',
84    previewBackground: DEFAULT_PREVIEW_BACKGROUND,
85    editor: null,
86    input: null,
87    preview: null,
88    preferences: [],
89    preferencesError: '',
90    error: '',
91    previewError: '',
92    previewBusy: false,
93    message: '',
94    busy: '',
95    uncertain: false,
96  };
97}
98
99function failureText(failure: unknown): string {
100  const error = processFailure(failure);
101  return `${error.code}: ${error.message}`.replace(
102    /[\x00-\x08\x0b-\x1f\x7f]/g,
103    '',
104  );
105}
106
107interface Session {
108  uiLanguage: Language;
109  previewBackground: PreviewBackground;
110  ownsCommand: boolean;
111  view: View;
112  ack: number;
113  generation: number;
114  columns: number;
115  rows: number;
116  displayColumns: number;
117  displayRows: number;
118  saveOutcome: 'none' | 'pending' | 'saved' | 'unknown' | 'refused';
119  placed: boolean;
120  clientFault: string;
121  inputChain: Promise<void>;
122  epoch: number;
123  previewKey: string;
124  previewTimer: Timer | null;
125  writing: boolean;
126  pendingSave: { draft: Draft; revision: string } | null;
127}
128
129function discard(state: Session): void {
130  state.previewTimer?.cancel();
131  state.previewTimer = null;
132  state.epoch += 1;
133  state.view = emptyView();
134  state.previewKey = '';
135  state.writing = false;
136  state.pendingSave = null;
137  state.ack = 0;
138  state.placed = false;
139  state.clientFault = '';
140  state.saveOutcome = 'none';
141}
142
143function props(state: Session) {
144  try {
145    const projected = clientProps(state.view, state.epoch, state.ack, ++state.generation, state.columns, state.rows);
146    state.displayColumns = projected.displayColumns;
147    state.displayRows = projected.displayRows;
148    return projected;
149  } catch (error) {
150    state.clientFault = failureText(error).slice(0, 200);
151    return null;
152  }
153}
154
155function clientReply($: EngineInterface, state: Session) {
156  const projected = props(state);
157  if (projected && !state.clientFault) return { props: projected };
158  $.ui.invalidate('ui.render');
159  return {};
160}
161
162async function load(
163  $: EngineInterface,
164  state: Session,
165  options: PluginOptions,
166) {
167  if (state.view.editor?.sources) await closeSources(state.view.editor,{request:(operation,payload)=>callBackend($,options,operation,payload)});
168  discard(state);
169  const opening = state.epoch;
170  setMessage(state.view, "busy", localizedText("native.hooks.register.loading_configuration"));
171  $.ui.invalidate('ui.render');
172  try {
173    const description = await callBackend($, options, 'describe');
174    const current = await callBackend($, options, 'read', { target: { kind: 'project', path: await $.session.cwd() } });
175    if (state.epoch !== opening) return;
176    if (description.backend_version !== current.backend_version) {
177      throw new BackendError(
178        'backend_version_mismatch',
179        localizedText("native.hooks.register.the_backend_changed_while_opening_reopen_the_editor"),
180      );
181    }
182    state.view.editor = new Editor(description, current);
183    try {
184      const preference = await callBackend($, options, 'read_ui_preferences');
185      if (state.epoch !== opening) return;
186      state.uiLanguage = preference.ui_language;
187      state.view.language = preference.ui_language;
188      if (preference.warning) setMessage(state.view, 'message', preference.warning);
189    } catch (failure) {
190      if (state.epoch === opening) {
191        state.view.language = state.uiLanguage;
192        setMessage(state.view, 'message', localizedText('native.language_read_failed', { detail: failureMessage(failure) }));
193      }
194    }
195    try {
196      const background = previewBackground(await $.store.get(PREVIEW_BACKGROUND_KEY));
197      if (state.epoch === opening) {
198        state.previewBackground = background;
199        state.view.previewBackground = background;
200      }
201    } catch {
202      if (state.epoch === opening) {
203        state.view.previewBackground = state.previewBackground;
204        setMessage(state.view, "message", localizedText("native.hooks.register.preview_background_preference_unavailable_using_the_last_choice"));
205      }
206    }
207    if (!current.installed)
208      setMessage(state.view, "message", localizedText("native.hooks.register.the_renderer_is_not_installed_run_claude_statusline"));
209    try {
210      const rows = await $.config.list();
211      if (state.epoch === opening) state.view.preferences = preferences(rows);
212    } catch (failure) {
213      if (state.epoch === opening)
214        setMessage(state.view, "preferencesError", localizedText("native.hooks.register.host_preferences_unavailable", {value0: failureMessage(failure)}));
215    }
216  } catch (failure) {
217    if (state.epoch === opening) setMessage(state.view, "error", failureMessage(failure));
218  } finally {
219    if (state.epoch === opening) {
220      state.view.busy = '';
221      $.ui.invalidate('ui.render');
222    }
223  }
224}
225
226async function reconcile(
227  $: EngineInterface,
228  state: Session,
229  options: PluginOptions,
230) {
231  const editor = state.view.editor;
232  const submitted = state.pendingSave;
233  if (!editor || !submitted || state.writing) return;
234  const saving = state.epoch;
235  state.writing = true;
236  setMessage(state.view, "busy", localizedText("native.hooks.register.checking_saved_configuration"));
237  $.ui.invalidate('ui.render');
238  try {
239    const current = await callBackend($, options, 'read', editor.baseline.configuration ? { target: editor.baseline.configuration.target } : {});
240    if (state.epoch !== saving) return;
241    if (
242      sameDraft(current.draft, submitted.draft) &&
243      current.installed &&
244      JSON.stringify(current.installation) ===
245        JSON.stringify(editor.baseline.installation)
246    ) {
247      editor.committed(current);
248      state.saveOutcome = 'saved';
249      setMessage(state.view, "message", localizedText("native.hooks.register.the_submitted_tool_configuration_is_saved"));
250      state.view.error = '';
251    } else if (current.revision === submitted.revision) {
252      state.saveOutcome = 'refused';
253      setMessage(state.view, "message", localizedText("native.hooks.register.no_tool_changes_were_committed_review_the_draft"));
254      state.view.error = '';
255    } else {
256      state.saveOutcome = 'refused';
257      setMessage(state.view, "error", localizedText("native.hooks.register.configuration_conflict_saved_configuration_differs_discard_the_draft"));
258    }
259    state.pendingSave = null;
260    state.view.uncertain = false;
261  } catch (failure) {
262    if (state.epoch === saving)
263      setMessage(state.view, "error", localizedText("native.hooks.register.save_outcome_remains_unknown", {value0: failureMessage(failure)}));
264  } finally {
265    if (state.epoch === saving) {
266      state.writing = false;
267      state.view.busy = '';
268      $.ui.invalidate('ui.render');
269    }
270  }
271}
272
273async function save(
274  $: EngineInterface,
275  state: Session,
276  options: PluginOptions,
277  finish = false,
278) {
279  const editor = state.view.editor;
280  if (!editor || state.writing || state.view.uncertain) return;
281  if (!editor.acceptNumeric()) {
282    setMessage(state.view, "error", localizedText("native.hooks.register.correct_the_numeric_fields_before_saving"));
283    editor.page = 'settings';
284    editor.setting = Object.keys(editor.fieldErrors)[0] || 'padding';
285    $.ui.invalidate('ui.render');
286    return;
287  }
288  const saving = state.epoch;
289  const submitted = {
290    draft: copyDraft(editor.draft),
291    revision: editor.baseline.revision,
292  };
293  state.pendingSave = submitted;
294  state.saveOutcome = 'pending';
295  state.writing = true;
296  setMessage(state.view, "busy", localizedText("native.hooks.register.saving_tool_configuration"));
297  state.view.error = '';
298  let saved = false;
299  $.ui.invalidate('ui.render');
300  try {
301    const result = await callBackend($, options, 'apply', {
302      draft: submitted.draft,
303      expected_revision: submitted.revision,
304      ...(editor.baseline.configuration ? { target: editor.baseline.configuration.target } : {}),
305    });
306    if (state.epoch !== saving) return;
307    editor.committed(result);
308    state.pendingSave = null;
309    saved = true;
310    state.saveOutcome = 'saved';
311    setMessage(state.view, "message", (result.changed ? localizedText("native.hooks.register.tool_configuration_saved_later_statusline_refreshes_use_these") : localizedText("native.hooks.register.tool_configuration_is_already_current")));
312  } catch (failure) {
313    if (state.epoch !== saving) return;
314    const error = processFailure(failure);
315    setMessage(state.view, "error", failureMessage(error));
316    const refused = [
317      'invalid_request',
318      'invalid_configuration',
319      'configuration_conflict',
320      'not_installed',
321      'ownership_mismatch',
322      'unsupported_protocol',
323      'unsupported_operation',
324    ].includes(error.code);
325    state.view.uncertain = !refused;
326    state.saveOutcome = refused ? 'refused' : 'unknown';
327    if (refused) state.pendingSave = null;
328  } finally {
329    if (state.epoch === saving) {
330      state.writing = false;
331      state.view.busy = '';
332      $.ui.invalidate('ui.render');
333    }
334  }
335  if (finish && saved && state.epoch === saving) {
336    if (state.view.preferences.some(preferenceChanged)) {
337      editor.page = 'settings';
338      editor.advanced = true;
339      editor.setting =
340        'host-' + state.view.preferences.find(preferenceChanged)!.row.key;
341      setMessage(state.view, "message", localizedText("native.hooks.register.tool_configuration_saved_host_changes_pending_a_apply"));
342      $.ui.invalidate('ui.render');
343    } else await close($, state, options);
344  }
345}
346
347async function transferDraft($: EngineInterface, state: Session, options: PluginOptions) {
348  const e = state.view.editor;
349  const action = e?.pendingTransfer;
350  if (!e || !action || state.writing || state.view.uncertain) return;
351  const epoch = state.epoch;
352  e.pendingTransfer = null;
353  state.writing = true;
354  setMessage(state.view, "busy", (action === 'export' ? localizedText("native.hooks.register.exporting_current_draft_may_be_unsaved") : localizedText("native.hooks.register.loading_draft")));
355  $.ui.invalidate('ui.render');
356  try {
357    if (action === 'import') {
358      const original = copyDraft(e.draft);
359      const candidate = new Editor(e.description, {...e.baseline, draft:copyDraft(e.draft)});
360      candidate.buffers = {...e.buffers};
361      if (!candidate.acceptNumeric()) { setMessage(state.view, 'message', localizedText('native.hooks.register.correct_numeric_fields_first')); return; }
362      const result = await callBackend($, options, 'review_import', {draft:copyDraft(candidate.draft), path:e.path});
363      if (state.epoch === epoch && state.view.editor === e) {
364        if (!sameDraft(e.draft, original)) { setMessage(state.view, 'message', localizedText('review.stale')); return; }
365        e.review = createReview(result, candidate.draft);
366        state.view.preview = null;
367        state.previewKey = '';
368        state.view.message = '';
369      }
370      return;
371    }
372    if (!e.acceptNumeric()) { setMessage(state.view, "message", localizedText("native.hooks.register.correct_numeric_fields_first")); return; }
373    const payload = action === 'preset' ? { draft: copyDraft(e.quick?.base ?? e.draft), preset: e.preset } : { draft: copyDraft(e.draft), path: e.path, overwrite: false };
374    if (action === 'export') {
375      const result = await callBackend($, options, action, payload);
376      if (state.epoch === epoch) setMessage(state.view, "message", localizedText("native.hooks.register.exported_current_draft_may_be_unsaved", {path: result.path}));
377    } else {
378      const result = await callBackend($, options, action, payload);
379      if (state.epoch === epoch) {
380        if (e.quick) receivePreset(e.quick,result.draft); else e.replaceDraft(result.draft);
381        setMessage(state.view, "message", localizedText("native.hooks.register.draft_replaced_review_preview_and_save_or_discard"));
382        state.previewKey = '';
383      }
384    }
385  } catch (failure) {
386    if (state.epoch === epoch) setMessage(state.view, "message", failureMessage(failure));
387  } finally {
388    if (state.epoch === epoch) {
389      state.writing = false;
390      state.view.busy = '';
391    }
392  }
393}
394
395async function applyPreferences(
396  $: EngineInterface,
397  state: Session,
398  options: PluginOptions,
399) {
400  if (state.writing || state.view.uncertain) return;
401  const applying = state.epoch;
402  state.writing = true;
403  setMessage(state.view, "busy", localizedText("native.hooks.register.applying_host_preferences"));
404  state.view.message = '';
405  state.view.preferencesError = '';
406  $.ui.invalidate('ui.render');
407  try {
408    for (const preference of state.view.preferences.filter(preferenceChanged)) {
409      const rows = await $.config.list();
410      if (state.epoch !== applying) return;
411      const latest = rows.find((row) => row.key === preference.row.key);
412      if (!latest) {
413        setResult(preference, localizedText("native.hooks.register.unavailable_not_applied"));
414        continue;
415      }
416      if (
417        JSON.stringify(latest.value) !== JSON.stringify(preference.baseline) ||
418        latest.kind !== preference.row.kind ||
419        JSON.stringify(latest.provider) !==
420          JSON.stringify(preference.row.provider)
421      ) {
422        setResult(preference, localizedText("native.hooks.register.changed_elsewhere_discard_and_reload_before_applying"));
423        continue;
424      }
425      preference.row = latest;
426      if (!canEdit(preference)) {
427        setResult(preference, (latest.isLocked ? localizedText("native.hooks.register.locked_by_host_policy_not_applied") : localizedText("native.hooks.register.unsupported_control_not_applied")));
428        continue;
429      }
430      if (!validPreferenceValue(preference)) {
431        setResult(preference, localizedText("native.hooks.register.value_no_longer_fits_this_row_discard_and"));
432        continue;
433      }
434      try {
435        const result = await $.config.set({
436          key: latest.key,
437          value: preference.value,
438        });
439        if (state.epoch !== applying) return;
440        if (result.deny !== undefined) {
441          setResult(preference, localizedText("native.hooks.register.refused", {deny: result.deny}));
442        } else {
443          preference.baseline = result.value;
444          preference.value = result.value;
445          preference.row = { ...latest, value: result.value };
446          setResult(preference, localizedText("native.hooks.register.applied"));
447        }
448      } catch (failure) {
449        if (state.epoch !== applying) return;
450        setResult(preference, localizedText("native.hooks.register.could_not_confirm_application_discard_and_reload_to", {value0: failureMessage(failure)}));
451      }
452    }
453  } catch (failure) {
454    if (state.epoch === applying)
455      setMessage(state.view, "preferencesError", failureMessage(failure));
456  } finally {
457    if (state.epoch === applying) {
458      state.writing = false;
459      state.view.busy = '';
460      $.ui.invalidate('ui.render');
461    }
462  }
463}
464
465async function close($: EngineInterface, state: Session, options: PluginOptions) {
466  if (state.view.editor?.sources) await closeSources(state.view.editor,{request:(operation,payload)=>callBackend($,options,operation,payload)});
467  // A plugin's own API calls skip its hooks; guard programmatic close here too.
468  if (state.writing || state.view.uncertain) {
469    setMessage(state.view, "error", (state.writing ? localizedText("native.hooks.register.wait_for_the_apply_result_before_closing") : localizedText("native.hooks.register.check_the_saved_state_before_closing_the_save")));
470    $.ui.invalidate('ui.render');
471    return;
472  }
473  try {
474    await $.ui.close({ id: PANE });
475    const open = await $.ui.panes();
476    if (!open.some((p) => p.id === PANE)) discard(state);
477  } catch (failure) {
478    setMessage(state.view, "error", failureMessage(failure));
479    $.ui.invalidate('ui.render');
480  }
481}
482
483async function openEditor(
484  $: EngineInterface,
485  state: Session,
486  options: PluginOptions,
487) {
488  const tr = (key: string, params: Record<string, unknown> = {}) => t(key, state.view.language ?? 'en', params);
489
490  if (state.writing || state.view.uncertain)
491    return {
492      text: tr("native.hooks.register.finish_checking_the_pending_save_before_reopening_the"),
493    };
494  if (!state.placed) {
495    const opening = state.epoch + 1;
496    await load($, state, options);
497    if (state.epoch !== opening) return {};
498  }
499  const opened = await $.ui.open({
500    id: PANE,
501    title: tr("native.hooks.register.statusline_configuration"),
502    focus: true,
503    closeOnEscape: true,
504    rows: 24,
505    columns: 72,
506  });
507  state.placed = opened.isPlaced;
508  if (!opened.isPlaced) return { text: opened.reason };
509  return {};
510}
511
512/** Task host calls stay in this statically inspected entry; presentation is shared in core. */
513const TASK_COMMAND = 'statusline-task', TASK_PANE = 'statusline-task-details';
514export interface TaskPaneState {
515  owned: boolean; loading: boolean; generation: number; offset: number;
516  language: Language; report: TaskDetails | null; error: string;
517}
518export function taskPaneState(): TaskPaneState {
519  return { owned:false, loading:false, generation:0, offset:0, language:'en', report:null, error:'' };
520}
521export async function startTaskDetails($: EngineInterface, state: TaskPaneState): Promise<void> {
522  state.generation++; state.loading=false; state.report=null; state.error=''; state.offset=0; state.owned=false;
523  const commands=await $.command.list();
524  if(!commands.some(c=>c.name===TASK_COMMAND && c.plugin!=='statusline-native')) {
525    await $.command.register({name:TASK_COMMAND,description:t('task.title',state.language)}); state.owned=true;
526  }
527}
528async function refreshTaskDetails($: EngineInterface, options: PluginOptions, state: TaskPaneState): Promise<void> {
529  if (state.loading) return;
530  state.loading=true; state.error=''; const epoch=state.generation;
531  $.ui.invalidate('ui.render');
532  try {
533    const launch=binding(options,await $.env.get('CLAUDE_STATUSLINE_NATIVE_EXECUTABLE') || undefined);
534    const directory=await $.env.get('CLAUDE_CONFIG_DIR') || (typeof options.configDir==='string' ? options.configDir : '');
535    const argv=[launch.executable,...launch.args,'ui',...(directory ? ['--config-dir',directory] : [])];
536    const session=await $.session.id();
537    let host_agents: { observed_at:number; agents:{id:string;name:string|null}[] } | undefined;
538    try {
539      const agents=await $.agent.list();
540      host_agents={observed_at:await $.clock.now(),agents:agents.slice(0,256).map(a=>({id:a.id,name:[...(a.name ?? a.description ?? '').replace(/[\p{Cc}\p{Cs}]/gu,'')].slice(0,256).join('') || null}))};
541    } catch { /* Published evidence remains usable without a host snapshot. */ }
542    const preference=parseResponse('read_ui_preferences',await $.process.run(argv,{stdin:requestText('read_ui_preferences',{}),timeoutMs:30000}));
543    const result=parseResponse('task_details',await $.process.run(argv,{stdin:requestText('task_details',{session_id:session,...(host_agents ? {host_agents} : {})}),timeoutMs:30000}));
544    if(result.session_id!==session)throw new Error(t('task.error.input',state.language));
545    if(state.generation!==epoch)return;
546    state.report=result;state.language=preference.ui_language;state.offset=0;
547  } catch(failure) {
548    if(state.generation===epoch)state.error=failure instanceof Error ? failure.message : String(failure);
549  } finally {
550    if(state.generation===epoch){state.loading=false;$.ui.invalidate('ui.render');}
551  }
552}
553export function registerTaskDetails(on: On, options: PluginOptions, state: TaskPaneState): void {
554  const tr=(key:string)=>t(key,state.language);
555  on('command.run',{command:'statusline-task'},async($,e,next)=>{
556    if(!state.owned)return next(e);
557    const opened=await $.ui.open({id:TASK_PANE,title:tr('task.title'),focus:true,closeOnEscape:true,rows:24,columns:88});
558    if(!opened.isPlaced)return {text:tr('task.fallback')};
559    await refreshTaskDetails($,options,state);return {};
560  });
561  on('ui.close',{id:'statusline-task-details'},async($,e,next)=>{
562    state.generation++;state.loading=false;state.report=null;state.error='';return next(e);
563  });
564  on('ui.render',{component:'Pane',requestId:'statusline-task-details'},async($,e,next)=>{
565    if(!state.owned)return next(e);
566    const {Box,Text,Button}=$.ui.resolve(e);
567    if(e.surface!=='terminal')return Text({...styles.text,children:[tr('task.fallback')]});
568    const width=Math.max(2,e.props.bodyColumns),height=Math.max(4,e.props.scroll.bodyRows),capacity=Math.max(1,height-3);
569    const lines=state.report ? taskDetailLines(state.report,state.language,Math.max(2,width-2)) : [tr(state.loading?'profiles.loading':'task.unknown')];
570    state.offset=Math.max(0,Math.min(state.offset,Math.max(0,lines.length-capacity)));
571    return Box({width,height,flexDirection:'column',children:[
572      Text({...styles.accent,bold:true,wrap:'truncate',children:[tr('task.title')+' · '+(state.loading?tr('profiles.loading'):tr('task.readonly'))]}),
573      ...lines.slice(state.offset,state.offset+capacity).map(line=>Text({...styles.text,wrap:'truncate',children:[line]})),
574      ...(state.error?[Text({...styles.error,wrap:'truncate',children:[state.error.replace(/[\p{Cc}\p{Cs}]/gu,'')]} )]:[]),
575      Box({flexDirection:'row',columnGap:1,children:[
576        Button({...recoveryButton,key:'task-up',label:'↑',hotkey:'k',onPress:()=>{state.offset=Math.max(0,state.offset-capacity);$.ui.invalidate('ui.render');}}),
577        Button({...recoveryButton,key:'task-down',label:'↓',hotkey:'j',onPress:()=>{state.offset=Math.min(Math.max(0,lines.length-capacity),state.offset+capacity);$.ui.invalidate('ui.render');}}),
578        Button({...recoveryButton,key:'task-refresh',label:tr('profiles.refresh'),hotkey:'r',onPress:()=>refreshTaskDetails($,options,state)}),
579        Button({...recoveryButton,key:'task-close',label:tr('task.close'),hotkey:'q',onPress:()=>$.ui.close({id:TASK_PANE})}),
580      ]}),
581    ]});
582  });
583}
584
585export const register: Register = (on, options) => {
586  const taskDetails = taskPaneState();
587  registerTaskDetails(on, options, taskDetails);
588  const tr = (key: string, params: Record<string, unknown> = {}) => t(key, state.view.language ?? 'en', params);
589
590  const state: Session = {
591    uiLanguage: 'en',
592    previewBackground: DEFAULT_PREVIEW_BACKGROUND,
593    ownsCommand: false,
594    view: emptyView(),
595    epoch: 0,
596    ack: 0,
597    generation: 0,
598    columns: 72,
599    rows: 24,
600    displayColumns: 72,
601    displayRows: 24,
602    saveOutcome: 'none',
603    placed: false,
604    clientFault: '',
605    inputChain: Promise.resolve(),
606    previewKey: '',
607    previewTimer: null,
608    writing: false,
609    pendingSave: null,
610  };
611
612  on('session.start', async ($, e, next) => {
613    await startTaskDetails($, taskDetails);
614    state.ownsCommand = false;
615    if (state.view.editor?.sources) await closeSources(state.view.editor,{request:(operation,payload)=>callBackend($,options,operation,payload)});
616    discard(state);
617    const open = await $.ui.panes();
618    if (open.some((p) => p.id === PANE)) {
619      await $.ui.close({ id: PANE });
620      $.ui.toast('Statusline editor reloaded. Unsaved drafts were discarded.');
621    }
622    const commands = await $.command.list();
623    const collision = commands.find((command) => command.name === COMMAND);
624    if (collision && collision.plugin !== 'statusline-native') {
625      $.ui.log(
626        '/statusline-configure-native belongs to another command; the Client entry is inactive.',
627      );
628    } else {
629      await $.command.register({
630        name: 'statusline-configure-native',
631        description: tr("native.hooks.register.open_the_experimental_in_session_client_tui"),
632      });
633      state.ownsCommand = true;
634    }
635    return next(e);
636  });
637
638  on(
639    'command.run',
640    { command: 'statusline-configure-native' },
641    async ($, e, next) => {
642      if (!state.ownsCommand) return next(e);
643      return openEditor($, state, options);
644    },
645  );
646
647  on('ui.close', { id: 'statusline-native' }, async ($, e, next) => {
648    if (e.origin.kind !== 'unload' && (state.writing || state.view.uncertain)) {
649      setMessage(state.view, "error", (state.writing ? localizedText("native.hooks.register.wait_for_the_apply_result_before_closing") : localizedText("native.hooks.register.check_the_saved_state_before_closing_the_save")));
650      $.ui.invalidate('ui.render');
651      return { deny: state.view.error };
652    }
653    if (state.view.editor?.sources) await closeSources(state.view.editor,{request:(operation,payload)=>callBackend($,options,operation,payload)});
654    const result = await next(e);
655    const open = await $.ui.panes();
656    if (!open.some((p) => p.id === PANE)) discard(state);
657    return result;
658  });
659
660  // Namespace registration remains valid on hosts predating ui.fault.
661  on('ui.*', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
662    if (String(next.event) === 'ui.fault' && state.ownsCommand) {
663      const fault = e as unknown as { component?: string; requestId?: string; element?: string; module?: string; surface?: string; reason?: unknown };
664      if (fault.component === 'Pane' && fault.requestId === PANE && fault.element === 'statusline-client-' + state.epoch && fault.module === 'ui/client/surface.ts' && fault.surface === 'terminal') {
665        state.clientFault = failureText(fault.reason).slice(0, 200);
666      }
667    }
668    return next(e);
669  });
670
671  on('ui.message', { component: 'Pane' }, async ($, e, next) => {
672    if (
673      e.requestId !== PANE ||
674      e.element !== 'statusline-client-' + state.epoch ||
675      e.module !== 'ui/client/surface.ts' ||
676      e.surface !== 'terminal' ||
677      !state.ownsCommand
678    )
679      return next(e);
680    const fault = e.data as { epoch?: unknown; fault?: unknown } | null;
681    if (
682      fault &&
683      typeof fault === 'object' &&
684      Object.keys(fault).sort().join(',') === 'epoch,fault' &&
685      fault.epoch === state.epoch &&
686      typeof fault.fault === 'string' &&
687      fault.fault.length > 0 &&
688      fault.fault.length <= 200
689    ) {
690      state.clientFault = failureText(fault.fault);
691      $.ui.invalidate('ui.render');
692      return {};
693    }
694    const batch = parseBatch(e.data);
695    if (!batch) {
696      setMessage(state.view, "error", localizedText("native.hooks.register.invalid_client_input_retry_the_client_region"));
697      return clientReply($, state);
698    }
699    const run = state.inputChain.then(async () => {
700      if (batch.epoch !== state.epoch || !state.placed) return {};
701      const currentEpoch = state.epoch;
702      if (state.columns !== batch.columns || state.rows !== batch.rows) {
703        state.columns = batch.columns;
704        state.rows = batch.rows;
705        props(state);
706      }
707      for (const message of batch.events) {
708        if (message.seq <= state.ack) continue;
709        if (message.seq !== state.ack + 1) {
710          setMessage(state.view, "error", localizedText("native.hooks.register.client_input_sequence_is_incomplete_retry_the_client"));
711          break;
712        }
713        state.ack = message.seq;
714        state.view.message = '';
715        const effect = handleKey(
716          state.view,
717          message.event,
718          state.displayColumns,
719          state.displayRows,
720        );
721        if (effect === 'save' || effect === 'finish') {
722          await save($, state, options, effect === 'finish');
723        } else if (effect === 'close') await close($, state, options);
724        else if (effect === 'reload') {
725          await load($, state, options);
726          state.placed = true;
727        } else if (effect === 'reconcile') await reconcile($, state, options);
728        else if (effect === 'transfer') await transferDraft($, state, options);
729        else if (effect === 'sources' && state.view.editor) {
730          state.writing=true;
731          try { await performSourceAction(state.view.editor,{request:(operation,payload)=>callBackend($,options,operation,payload)}); }
732          finally {state.writing=false;state.previewKey='';}
733        }
734        else if (effect === 'profiles' && state.view.editor) {
735          state.writing = true;
736          try { await performProfileAction(state.view.editor, { request: (operation, payload) => callBackend($, options, operation, payload) }); }
737          finally { state.writing = false; state.previewKey = ''; }
738        }
739        else if (effect === 'applyPreferences')
740          await applyPreferences($, state, options);
741        else if (effect === 'retry') state.previewKey = '';
742        else if (effect === 'reviewPreview' || effect === 'explain') {
743          state.previewTimer?.cancel();
744          state.previewKey = '';
745          state.view.preview = null;
746          state.view.previewError = '';
747        }
748        else if (effect === 'uiLanguage') {
749          const requested = state.view.language ?? 'en';
750          try {
751            const preference = await callBackend($, options, 'set_ui_language', {ui_language: requested});
752            if (state.epoch === currentEpoch) {
753              state.uiLanguage = preference.ui_language;
754              state.view.language = preference.ui_language;
755              if (state.view.localized?.error?.key === 'native.language_save_failed') state.view.error = '';
756              setMessage(state.view, 'message', localizedText('native.language_saved'));
757            }
758          } catch (failure) {
759            if (state.epoch === currentEpoch) {
760              state.view.language = state.uiLanguage;
761              setMessage(state.view, 'error', localizedText('native.language_save_failed', {detail: failureMessage(failure)}));
762            }
763          }
764        }
765        else if (effect === 'previewBackground') {
766          const background = previewBackground(state.view.previewBackground);
767          try {
768            await $.store.set(PREVIEW_BACKGROUND_KEY, background);
769            if (state.epoch === currentEpoch) {
770              state.previewBackground = background;
771              if (state.view.localized?.error?.key === 'native.remember_preview_failed') state.view.error = '';
772              setMessage(state.view, "message", localizedText("native.hooks.register.preview_background_remembered_status_line_colors_unchanged"));
773            }
774          } catch {
775            if (state.epoch === currentEpoch) {
776              state.view.previewBackground = state.previewBackground;
777              setMessage(state.view, 'error', localizedText('native.remember_preview_failed'));
778            }
779          }
780        }
781        if (state.epoch !== currentEpoch) break;
782      }
783      $.ui.invalidate('ui.render');
784      if (state.epoch !== currentEpoch) return {};
785      return clientReply($, state);
786    });
787    state.inputChain = run.then(
788      () => {},
789      () => {},
790    );
791    return run;
792  }).catch(($, e, next) => {
793    if (e.requestId !== PANE || !state.ownsCommand) return next(e);
794    state.clientFault = failureText(next.error.message ?? 'Client reply failed').slice(0, 200);
795    $.ui.invalidate('ui.render');
796    return {};
797  });
798
799  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
800    if (e.requestId !== PANE || !state.ownsCommand) return next(e);
801    const ui = $.ui.resolve(e);
802    if (e.surface !== 'terminal')
803      return ui.Text({
804        ...styles.text,
805        children: [tr("native.hooks.register.open_this_editor_in_the_claude_code_terminal")],
806      });
807    const { Box, Text, Button, Client } = $.ui.resolve(e);
808    const width = Math.max(2, Math.min(10000, e.props.bodyColumns));
809    const height = Math.max(0, Math.min(10000, e.props.scroll.bodyRows));
810    state.columns = width;
811    state.rows = height;
812    const editor = state.view.editor;
813    const previewDraft = editor?.profiles?.candidate ? { ...editor.draft, display: editor.profiles.candidate } : editor?.quick?.candidate ?? editor?.review?.result.draft ?? editor?.draft;
814    const previewColumns = contentColumns(width, height);
815    const explanation=editor?.explanation;
816    const key = `${state.epoch}:${previewColumns}:${explanation ? explanation.scope+':'+explanation.id : ''}:${previewDraft ? JSON.stringify(previewDraft) : ''}`;
817    if (
818      editor &&
819      width >= MIN_COLUMNS &&
820      height >= MIN_ROWS &&
821      !state.writing &&
822      state.previewKey !== key
823    ) {
824      state.previewKey = key;
825      const requestedEpoch = state.epoch;
826      const draft = copyDraft(previewDraft!);
827      state.previewTimer?.cancel();
828      state.view.previewBusy = true;
829      state.previewTimer = $.clock.after(0, async () => {
830        try {
831          const explained=explanation ? await callBackend($,options,'explain',{draft,scope:explanation.scope,width:previewColumns}) : null;
832          if(explained && (explained.scope!==explanation!.scope || explained.width!==previewColumns)) throw new Error('Explanation response does not match the request');
833          const preview=explained?.preview ?? await callBackend($, options, 'preview', {draft,width:previewColumns});
834          if (state.epoch === requestedEpoch && state.previewKey === key) {
835            if(explanation && explained) { explanation.result=explained;explanation.error=''; }
836            state.view.preview = preview;
837            state.view.previewError = '';
838          }
839        } catch (failure) {
840          if (state.epoch === requestedEpoch && state.previewKey === key) {
841            if(explanation) explanation.error=failureMessage(failure).fallback;
842            state.view.preview = null;
843            setMessage(state.view, "previewError", failureMessage(failure));
844          }
845        } finally {
846          if (state.epoch === requestedEpoch && state.previewKey === key) {
847            state.view.previewBusy = false;
848            state.previewTimer = null;
849            $.ui.invalidate('ui.render');
850          }
851        }
852      });
853    }
854    const retry = async () => {
855      if (state.writing || state.view.uncertain) return;
856      if (!state.view.editor) await load($, state, options);
857      else {
858        state.epoch++;
859        state.ack = 0;
860        state.clientFault = '';
861        state.view.error = '';
862      }
863      state.placed = true;
864      $.ui.invalidate('ui.render');
865    };
866    if (
867      editor &&
868      !state.clientFault &&
869      width >= MIN_COLUMNS &&
870      height >= MIN_ROWS
871    ) {
872      const projected = props(state);
873      const tree = projected ? Box({
874        width,
875        height,
876        flexDirection: 'column',
877        children: [
878          Client({
879            key: 'statusline-client-' + state.epoch,
880            module: '../ui/client/surface.ts',
881            width,
882            height,
883            props: projected,
884          }),
885          Box({
886            position: 'absolute',
887            top: 0,
888            right: 0,
889            width: 20,
890            height: 1,
891            flexDirection: 'row',
892            columnGap: 1,
893            children: [
894              Button({ ...recoveryButton, key: 'retry-client', label: tr("native.hooks.register.retry"), onPress: retry }),
895              Button({
896                ...recoveryButton,
897                key: 'close',
898                label: tr("native.hooks.register.close"),
899                onPress: () => close($, state, options),
900              }),
901            ],
902          }),
903        ],
904      }) : null;
905      if (tree && withinBudget(tree)) return tree;
906      state.clientFault ||= tr('native.capacity.failed');
907    }
908    return Box({
909      backgroundColor: styles.text.backgroundColor,
910      flexDirection: 'column',
911      width,
912      // Keep the requested height while undersized; otherwise an inline host
913      // measures the short error tree and never grows it after a terminal resize.
914      height: Math.max(24, height),
915      children: [
916        Text({
917          ...styles.text,
918          bold: true,
919          wrap: 'truncate',
920          children: [
921            width < MIN_COLUMNS || height < MIN_ROWS
922              ? tr("native.hooks.register.resize_pane_to_32x12_draft_kept")
923              : state.clientFault
924                ? tr("native.hooks.register.client_failed_received_draft_kept")
925                : viewMessage(state.view, 'busy') || tr("native.hooks.register.could_not_open_the_client_editor"),
926          ],
927        }),
928        Text({
929          ...styles.error,
930          wrap: 'truncate',
931          children: [clip((state.clientFault || viewMessage(state.view, 'error') || ' ').slice(0, 200), Math.min(width, 200))],
932        }),
933        Text({ ...styles.text, wrap: 'truncate', children: [clip(
934          state.saveOutcome === 'saved' ? tr('native.capacity.saved') : state.view.uncertain ? tr('native.capacity.unknown') : state.writing ? viewMessage(state.view, 'busy') : tr('native.capacity.retained'),
935          Math.min(width, 200),
936        )] }),
937        ...(state.view.uncertain
938          ? [
939              Button({
940                ...recoveryButton,
941                key: 'reconcile',
942                label: tr("native.hooks.register.check_saved_state"),
943                hotkey: 'k',
944                onPress: () => reconcile($, state, options),
945              }),
946            ]
947          : []),
948        ...(!state.view.busy && !state.view.uncertain
949          ? [
950              Button({
951                ...recoveryButton,
952                key: 'retry-client',
953                label: tr("native.hooks.register.retry_client"),
954                hotkey: 'r',
955                onPress: retry,
956              }),
957            ]
958          : []),
959        Button({
960          ...recoveryButton,
961          key: 'close',
962          label: tr("native.hooks.register.discard_pending_close"),
963          hotkey: 'q',
964          onPress: () => close($, state, options),
965        }),
966      ],
967    });
968  }).catch(($, e, next) => {
969    if (e.requestId !== PANE || !state.ownsCommand || e.surface !== 'terminal') return next(e);
970    state.clientFault = failureText(next.error.message ?? 'Pane rendering failed').slice(0, 200);
971    $.ui.invalidate('ui.render');
972    const { Box, Text, Button } = $.ui.resolve(e);
973    return Box({ flexDirection: 'column', children: [
974      Text({ children: [tr('native.capacity.failed')] }),
975      Text({ children: [state.saveOutcome === 'saved' ? tr('native.capacity.saved') : state.view.uncertain ? tr('native.capacity.unknown') : tr('native.capacity.retained')] }),
976      Button({ ...recoveryButton, key: 'retry-client', label: tr('native.hooks.register.retry_client'), onPress: () => {
977        if (state.writing || state.view.uncertain) return;
978        state.epoch++; state.ack = 0; state.clientFault = '';
979        $.ui.invalidate('ui.render');
980      } }),
981      ...(state.view.uncertain ? [Button({ ...recoveryButton, key: 'reconcile', label: tr('native.hooks.register.check_saved_state'), onPress: () => reconcile($, state, options) })] : []),
982      Button({ ...recoveryButton, key: 'close', label: tr('native.hooks.register.discard_pending_close'), onPress: () => close($, state, options) }),
983    ] });
984  });
985};
986
lib/editor/source-manager.ts 305 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import type { Operation, ResultFor, SourcesResult, SourceDefinition, SourceContext, SourceJob, SourceReview, Scope } from '../generated-contracts.ts';
3import type { Editor } from './draft.ts';
4import { t, text, type Language, type LocalizedText } from '../i18n/index.ts';
5import { inputKey, inputView, textInput, type TextInput, type TextKey } from './text-input.ts';
6import { wrapText } from '../../ui/text.ts';
7import { BackendError } from '../backend.ts';
8type Action = 'edit' | 'review' | 'disable' | 'remove' | 'bind' | 'unbind' | 'refresh' | 'status' | 'cancel' | 'diagnose' | 'auto-review' | 'auto-off';
9export interface SourceManager {
10    library: SourcesResult | null;
11    context: SourceContext | null;
12    owner: string;
13    page: 'list' | 'actions' | 'kind' | 'form' | 'review' | 'remove' | 'bind' | 'unbind' | 'diagnose' | 'auto-review';
14    automaticInterval: number;
15    cursor: number;
16    scroll: number;
17    selected: string | null;
18    kind: SourceDefinition['kind'];
19    editing: boolean;
20    fields: {
21        key: string;
22        input: TextInput;
23    }[];
24    review: SourceReview | null;
25    details: string[];
26    jobs: SourceJob[];
27    message: LocalizedText | null;
28    effect: 'load' | 'save' | 'review' | 'enable' | 'disable' | 'remove' | 'bind' | 'refresh' | 'status' | 'cancel' | 'diagnose' | 'close' | 'auto-review' | 'auto-on' | 'auto-off' | null;
29    target: {
30        scope: Scope;
31        id: string;
32    } | null;
33}
34export interface SourceBackend {
35    request<O extends Operation>(operation: O, payload?: unknown): ResultFor<O> | Promise<ResultFor<O>>;
36}
37const external = ['external-value', 'github-pr', 'github-ci'];
38export function openSources(editor: Editor): void {
39    editor.sources = { library: null, context: null, owner: 'editor-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2), page: 'list', automaticInterval: 300, cursor: 0, scroll: 0, selected: null, kind: 'json', editing: false, fields: [], review: null, details: [], jobs: [], message: null, effect: 'load', target: null };
40}
41function source(editor: Editor): SourceDefinition | undefined { return editor.sources!.library?.sources.find(s => s.id === editor.sources!.selected); }
42function actions(editor: Editor): Action[] { return ['edit', 'review', ...(source(editor)?.enabled ? ['disable' as const] : []), 'bind', 'refresh', 'status', 'cancel', 'diagnose', 'remove', 'unbind', ...(source(editor)?.kind === 'github' ? ['auto-review' as const, 'auto-off' as const] : [])]; }
43function targets(editor: Editor) {
44    const s = source(editor);
45    return (['main', 'subagent'] as const).flatMap(scope => (scope === 'main' ? editor.draft.display.instances : editor.draft.display.subagents.instances)
46        .filter(node => external.includes(node.type_id) && (s?.kind === 'github' || !node.type_id.startsWith('github-')) && (editor.sources!.page !== 'unbind' || editor.sources!.library?.bindings.some(binding => binding.source_id === s?.id && binding.id === node.source?.binding))).map(node => ({ scope, id: node.id })));
47}
48function form(editor: Editor, kind: SourceDefinition['kind'], editing = false): void {
49    const m = editor.sources!, s = editing ? source(editor) : undefined, settings = s?.settings ?? {};
50    const common: Record<string, unknown> = { id: s?.id ?? '', name: s?.name ?? '', project: s ? s.scope.project ?? '' : m.context?.project ?? '', session: s?.scope.session ?? '', agent: s?.scope.agent ?? '', ttl_seconds: s?.ttl_seconds ?? 300 };
51    const extra = kind === 'json' ? { path: settings.path ?? '', pointer: settings.pointer ?? '/value', observed_at_pointer: settings.observed_at_pointer ?? '/observed_at', unit: settings.unit ?? '' }
52        : kind === 'github' ? { host: settings.host ?? 'github.com', repository: settings.repository ?? '', branch: settings.branch ?? m.context?.branch ?? '', account: settings.account ?? '', pr: settings.pr ?? '' }
53            : { executable: settings.executable ?? '', args: JSON.stringify(settings.args ?? []), cwd: settings.cwd ?? m.context?.project ?? '', input: JSON.stringify(settings.input ?? {}), output: settings.output ?? 'json', timeout_ms: settings.timeout_ms ?? 5000 };
54    m.kind = kind;
55    m.editing = editing;
56    m.page = 'form';
57    m.cursor = 0;
58    m.scroll = 0;
59    m.message = null;
60    m.fields = Object.entries({ ...common, ...extra }).map(([key, value]) => ({ key, input: textInput(String(value)) }));
61}
62function count(editor: Editor): number {
63    const m = editor.sources!;
64    return m.page === 'list' ? (m.library?.sources.length ?? 0) + 1 : m.page === 'actions' ? actions(editor).length : m.page === 'kind' ? 3 : m.page === 'form' ? m.fields.length : m.page === 'bind' || m.page === 'unbind' ? targets(editor).length : 1;
65}
66export function sourcesKey(editor: Editor, event: TextKey): 'sources' | null {
67    const m = editor.sources;
68    if (!m)
69        return null;
70    const key = event.key === 'return' ? 'enter' : event.key, plain = !event.text && !event.paste && !event.ctrl && !event.meta;
71    if (!event.text && !event.paste && (key === 'escape' || event.ctrl && key.toLowerCase() === 'g')) {
72        if (m.page === 'list')
73            m.effect = 'close';
74        else {
75            m.page = 'list';
76            m.cursor = 0;
77            m.scroll = 0;
78            m.message = null;
79        }
80        return m.effect ? 'sources' : null;
81    }
82    if (m.page === 'form') {
83        if (!event.text && (key === 'tab' || plain && ['up', 'down'].includes(key)))
84            m.cursor = Math.max(0, Math.min(m.fields.length - 1, m.cursor + (key === 'up' ? -1 : 1)));
85        else if (!event.text && (key === 'enter' || event.ctrl && key.toLowerCase() === 's')) {
86            if (key === 'enter' && m.cursor < m.fields.length - 1)
87                m.cursor++;
88            else
89                m.effect = 'save';
90        }
91        else {
92            const field = m.fields[m.cursor]!;
93            if (!(m.editing && field.key === 'id')) {
94                const changed = inputKey(field.input.value, field.input, event, 8192);
95                field.input = changed.state;
96                m.message = changed.error ? text('input.' + changed.error, { limit: 8192 }) : null;
97            }
98        }
99        return m.effect ? 'sources' : null;
100    }
101    if (!plain)
102        return null;
103    if (['review', 'diagnose', 'auto-review'].includes(m.page) && ['up', 'down', 'pageup', 'pagedown', 'home'].includes(key)) {
104        m.scroll = key === 'home' ? 0 : Math.max(0, m.scroll + (key === 'up' ? -1 : key === 'pageup' ? -8 : key === 'pagedown' ? 8 : 1));
105        return null;
106    }
107    if (m.page === 'auto-review' && ['left', 'right'].includes(key)) { m.automaticInterval = Math.max(60, Math.min(86400, m.automaticInterval + (key === 'left' ? -60 : 60))); return null; }
108    if (key === 'up' || key === 'down')
109        m.cursor = Math.max(0, Math.min(count(editor) - 1, m.cursor + (key === 'up' ? -1 : 1)));
110    if (key === 'r' && m.page === 'list')
111        m.effect = 'load';
112    if (key === 'enter') {
113        if (m.page === 'list') {
114            const selected = m.library?.sources[m.cursor];
115            if (selected) {
116                m.selected = selected.id;
117                m.page = 'actions';
118            }
119            else
120                m.page = 'kind';
121            m.cursor = 0;
122        }
123        else if (m.page === 'kind')
124            form(editor, (['json', 'github', 'command'] as const)[m.cursor]!);
125        else if (m.page === 'actions') {
126            const action = actions(editor)[m.cursor]!;
127            if (action === 'edit')
128                form(editor, source(editor)!.kind, true);
129            else if (action === 'bind' || action === 'unbind' || action === 'remove') {
130                m.page = action;
131                m.cursor = 0;
132            }
133            else
134                m.effect = action;
135        }
136        else if (m.page === 'review') m.effect = 'enable';
137        else if (m.page === 'auto-review') m.effect = 'auto-on';
138        else if (m.page === 'remove')
139            m.effect = 'remove';
140        else if (m.page === 'unbind') {
141            const target = targets(editor)[m.cursor];
142            const node = target && editor.instance(target.scope, target.id);
143            if (node?.source) {
144                node.source = { ...node.source, binding: null };
145                m.message = text('sources.bound');
146                m.page = 'list';
147                m.cursor = 0;
148            }
149        }
150        else if (m.page === 'bind') {
151            m.target = targets(editor)[m.cursor] ?? null;
152            if (m.target)
153                m.effect = 'bind';
154        }
155    }
156    return m.effect ? 'sources' : null;
157}
158export async function closeSources(editor: Editor, backend: SourceBackend): Promise<void> {
159    const m = editor.sources;
160    if (!m)
161        return;
162    let failed: unknown;
163    for (const job of m.jobs.filter(job => job.state === 'running' && job.owner === m.owner && job.trigger === 'manual')) {
164        try { await backend.request('source_cancel', { id: job.id }); }
165        catch (error) { failed = error; }
166    }
167    if (failed) throw failed;
168    if (editor.sources === m)
169        editor.sources = null;
170}
171export async function performSourceAction(editor: Editor, backend: SourceBackend): Promise<void> {
172    const m = editor.sources, effect = m?.effect;
173    if (!m || !effect)
174        return;
175    m.effect = null;
176    m.message = null;
177    try {
178        if (effect === 'close') {
179            await closeSources(editor, backend);
180            return;
181        }
182        if (effect === 'load') {
183            m.library = await backend.request('sources_read', {});
184            const target = editor.baseline.configuration;
185            m.context = await backend.request('source_context', { project: target?.project_root ?? (target?.target.kind === 'project' ? target.target.path : null), session: null, agent: null });
186            return;
187        }
188        if (effect === 'review' || effect === 'auto-review') {
189            m.review = await backend.request('source_review', { id: m.selected });
190            m.page = effect;
191            m.automaticInterval = m.library?.automatic.find(p => p.source_id === m.selected)?.interval_seconds ?? Math.max(60, Math.min(86400, m.review.source.ttl_seconds));
192            m.scroll = 0;
193            return;
194        }
195        if (effect === 'status' || effect === 'cancel') {
196            const selected = source(editor)!;
197            const context = await backend.request('source_context', { project: selected.scope.project ?? m.context?.project ?? null, session: selected.scope.session, agent: selected.scope.agent });
198            const observed = await backend.request('source_diagnose', { id: m.selected, context });
199            const jobs = await Promise.all(observed.jobs.map(job => backend.request(effect === 'cancel' && job.state === 'running' ? 'source_cancel' : 'source_status', { id: job.id })));
200            m.jobs = m.jobs.map(job => jobs.find(updated => updated.id === job.id) ?? job);
201            m.details = [JSON.stringify(observed.automatic, null, 2), ...jobs.map(job => `${job.id}: ${job.state} (${job.reason})`)];
202            m.page = 'diagnose';
203            m.scroll = 0;
204            return;
205        }
206        if (effect === 'refresh' || effect === 'diagnose') {
207            const selected = source(editor)!;
208            const context = await backend.request('source_context', { project: selected.scope.project ?? m.context?.project ?? null, session: selected.scope.session, agent: selected.scope.agent });
209            if (effect === 'refresh') {
210                const job = await backend.request('source_refresh', { id: m.selected, context, owner: m.owner });
211                m.jobs.push(job);
212                m.message = text('sources.refresh_started');
213            }
214            else {
215                const result = await backend.request('source_diagnose', { id: m.selected, context });
216                m.details = JSON.stringify(result, null, 2).split('\n');
217                m.page = 'diagnose';
218                m.scroll = 0;
219            }
220            return;
221        }
222        const payload: Record<string, unknown> = { action: effect, id: m.selected, expected_revision: m.library!.revision };
223        if (effect === 'save') {
224            const values = Object.fromEntries(m.fields.map(field => [field.key, field.input.value]));
225            const { id, name, project, session, agent, ttl_seconds, ...settings } = values;
226            const parsed: Record<string, unknown> = { ...settings };
227            for (const key of ['args', 'input'])
228                if (key in parsed)
229                    parsed[key] = JSON.parse(String(parsed[key]));
230            if ('timeout_ms' in parsed)
231                parsed.timeout_ms = Number(parsed.timeout_ms);
232            if ('pr' in parsed)
233                parsed.pr = parsed.pr === '' ? null : Number(parsed.pr);
234            Object.assign(payload, { action: m.editing ? 'edit' : 'add', id, source: { name: name || id, kind: m.kind, scope: { project: project || null, session: session || null, agent: agent || null }, ttl_seconds: Number(ttl_seconds), settings: parsed } });
235        }
236        if (effect === 'enable' || effect === 'auto-on') payload.review_revision = m.review?.review_revision;
237        if (effect === 'auto-on') payload.interval_seconds = m.automaticInterval;
238        const result = await backend.request('sources_apply', payload);
239        m.library = result;
240        if (effect === 'bind' && m.target && result.binding) {
241            const node = editor.instance(m.target.scope, m.target.id);
242            if (node)
243                node.source = result.binding;
244            m.message = text('sources.bound');
245        }
246        else
247            m.message = text(effect === 'auto-on' ? 'sources.automatic_saved' : 'sources.saved');
248        m.page = 'list';
249        m.cursor = 0;
250        m.scroll = 0;
251    }
252    catch (error) {
253        m.message = error instanceof BackendError ? error.localization ?? text('sources.failed') : text('sources.failed');
254    }
255}
256export function sourcesView(editor: Editor, language: Language, width: number, height: number): {
257    text: string;
258    selected: boolean;
259}[] {
260    const m = editor.sources!;
261    const tr = (key: string) => t('sources.' + key, language), rows: {
262        text: string;
263        selected: boolean;
264    }[] = [];
265    const add = (value: string, selected = false) => rows.push({ text: value, selected });
266    add(tr('separate_save'));
267    if (m.message)
268        add(t(m.message.key, language, m.message.params));
269    if (m.page === 'list') {
270        m.library?.sources.forEach((s, i) => add(`${s.name} · ${s.kind} · ${tr(s.enabled ? 'enabled' : 'disabled')}${s.kind === 'github' ? ' · ' + tr(m.library!.automatic.some(p => p.source_id === s.id && p.enabled) ? 'automatic_on' : 'automatic_off') : ''}`, m.cursor === i));
271        add('+ ' + tr('add'), m.cursor === (m.library?.sources.length ?? 0));
272    }
273    else if (m.page === 'actions')
274        actions(editor).forEach((action, i) => add(tr(action), m.cursor === i));
275    else if (m.page === 'kind')
276        ['json', 'github', 'command'].forEach((kind, i) => add(tr(kind), m.cursor === i));
277    else if (m.page === 'form') {
278        m.fields.forEach((field, i) => {
279            const label = tr('field.' + field.key) + ': ', space = Math.max(2, width - label.length);
280            const view = inputView({ ...field.input }, space);
281            add(label + view, m.cursor === i);
282        });
283        add(tr('form_help'));
284    }
285    else if (m.page === 'bind' || m.page === 'unbind') {
286        const entries = targets(editor);
287        if (!entries.length)
288            add(tr('no_components'));
289        entries.forEach((target, i) => add(`${target.scope}: ${editor.instanceLabel(target.scope, target.id, language)}`, m.cursor === i));
290    }
291    else if (m.page === 'remove')
292        add(tr('remove_confirm') + ' ' + source(editor)?.name, true);
293    else {
294        const lines = ['review', 'auto-review'].includes(m.page) ? [tr(m.page === 'auto-review' ? 'automatic_review' : 'enable_review'), ...(m.page === 'auto-review' ? [tr('interval') + ': ' + m.automaticInterval + ' s (←/→)'] : []), ...JSON.stringify(m.review?.source, null, 2).split('\n')] : m.details;
295        const wrapped = lines.flatMap(line => wrapText([line], width));
296        const capacity = Math.max(1, height - rows.length);
297        const start = Math.min(m.scroll, Math.max(0, wrapped.length - capacity));
298        wrapped.slice(start, start + capacity).forEach(line => add(line));
299        return rows;
300    }
301    const fixed = rows.slice(0, 1 + Number(!!m.message)), entries = rows.slice(fixed.length), capacity = Math.max(1, height - fixed.length);
302    const selected = Math.max(0, entries.findIndex(row => row.selected)), start = Math.max(0, selected - capacity + 1);
303    return [...fixed, ...entries.slice(start, start + capacity)];
304}
305
lib/editor/task-detail.ts 28 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import type { TaskDetails } from '../generated-contracts.ts';
3import { t, type Language } from '../i18n/index.ts';
4import { wrapText } from '../../ui/text.ts';
5
6/** Both native and CLI presentations retain every evidence source and timestamp. */
7export function taskDetailLines(report: TaskDetails, language: Language, width = 100): string[] {
8    const tr = (key: string, params: Record<string, unknown> = {}) => t(key, language, params);
9    const status = (value: string | null) => value === null ? tr('task.unknown') : t('task.value.' + value, language, {}, value);
10    const duration = (value: number | null) => value === null ? tr('task.unknown') : value.toFixed(1) + 's';
11    const lines = [
12        tr('task.session', { value: report.session_id }), tr('task.prompt', { value: report.prompt_id ?? tr('task.unknown') }),
13        tr('task.captured', { value: report.captured_at }),
14        tr('task.status', { value: status(report.status), phase: status(report.phase) }),
15        tr('task.elapsed', { value: duration(report.elapsed_seconds) }), tr('task.active', { value: duration(report.active_seconds) }),
16        tr('task.progress', { value: report.progress ? report.progress.completed + '/' + report.progress.total : tr('task.unknown') }),
17        tr('task.agents'),
18        ...report.agents.flatMap(agent => [
19            `${agent.parent_id ? agent.parent_id + ' → ' : ''}${agent.name ?? agent.id} [${agent.id}]: ${status(agent.status)}`,
20            ...agent.evidence.map(e => tr('task.evidence', { source:e.source, scope:e.scope, status:status(e.status), time:e.observed_at ?? tr('task.unknown'), freshness:status(e.freshness) })),
21        ]),
22        tr('task.sources'),
23        ...report.evidence.map(e => tr('task.evidence', { source:e.source, scope:e.scope, status:status(e.status), time:e.observed_at ?? tr('task.unknown'), freshness:status(e.freshness) })),
24        ...report.limitations.map(reason => t('task.limit.' + reason, language, {}, reason)),
25    ];
26    return wrapText(lines.map(line=>line.replace(/\x1b\[[0-?]*[ -/]*[@-~]/gu,'').replace(/[\p{Cc}\p{Cs}]/gu,'')), Math.max(2,width));
27}
28
lib/editor/quick-setup.ts 86 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import type { Editor } from './draft.ts';
3import type { Draft, Scope } from '../generated-contracts.ts';
4import { THEME_VALUES, PALETTE_VALUES, SEPARATORSTYLE_VALUES, PRESETS } from '../generated-contracts.ts';
5import { copyDraft } from './draft.ts';
6import { t, type Language } from '../i18n/index.ts';
7import { wrapText } from '../../ui/text.ts';
8import { saveProfileCopy } from './profile-manager.ts';
9
10export interface QuickSetup {
11  base: Draft;
12  candidate: Draft;
13  step: 'scenario' | 'appearance' | 'review';
14  selected: number;
15  preset: string;
16  previewScope: Scope;
17  detailScroll: number;
18}
19export function openQuick(draft: Draft, preset = 'developer'): QuickSetup {
20  return {base:copyDraft(draft),candidate:copyDraft(draft),step:'scenario',selected:Math.max(0, PRESETS.findIndex(p=>p.id===preset)),preset,previewScope:'main',detailScroll:0};
21}
22export function receivePreset(quick: QuickSetup, draft: Draft): void {
23  quick.candidate = copyDraft(draft); quick.step = 'appearance'; quick.selected = 0; quick.detailScroll = 0;
24}
25export function quickKey(quick: QuickSetup, key: string): 'preset' | 'accept' | 'save' | 'copy' | 'cancel' | null {
26  const count = quick.step === 'scenario' ? PRESETS.length : quick.step === 'appearance' ? 5 : 4;
27  if (key === 'escape' || key === 'cancel') return 'cancel';
28  if (key === 'pageup' || key === 'pagedown') { quick.detailScroll = Math.max(0, quick.detailScroll + (key === 'pageup' ? -1 : 1)); return null; }
29  if (key === 'tab') { quick.previewScope = quick.previewScope === 'main' ? 'subagent' : 'main'; return null; }
30  if (key === 'backspace' || quick.step === 'review' && quick.selected === 3 && key === 'return') {
31    if (quick.step === 'scenario') return 'cancel';
32    quick.step = quick.step === 'review' ? 'appearance' : 'scenario';
33    quick.selected = quick.step === 'scenario' ? Math.max(0, PRESETS.findIndex(p => p.id === quick.preset)) : 0;
34    quick.detailScroll = 0; return null;
35  }
36  if (key === 'up' || key === 'down' || key === 'home' || key === 'end') {
37    quick.selected = key === 'home' ? 0 : key === 'end' ? count - 1 : Math.max(0,Math.min(count-1,quick.selected+(key==='up'?-1:1)));
38    quick.detailScroll = 0; return null;
39  }
40  if (quick.step === 'scenario' && key === 'return') { quick.preset = PRESETS[quick.selected]!.id; return 'preset'; }
41  if (quick.step === 'review' && key === 'return') return quick.selected === 0 ? 'accept' : quick.selected === 1 ? 'save' : 'copy';
42  if (quick.step !== 'appearance' || !['left','right','return'].includes(key)) return null;
43  const d = quick.candidate.display, delta = key === 'left' ? -1 : 1;
44  const cycle = <T>(values: readonly T[], value: T): T => values[(values.indexOf(value)+delta+values.length)%values.length]!;
45  if (quick.selected === 0) d.theme = cycle(THEME_VALUES,d.theme);
46  if (quick.selected === 1) d.use_colors = !d.use_colors;
47  if (quick.selected === 2) d.palette = cycle(PALETTE_VALUES,d.palette);
48  if (quick.selected === 3) d.separator_style = cycle(SEPARATORSTYLE_VALUES,d.separator_style);
49  if (quick.selected === 4 && key === 'return') { quick.step='review'; quick.selected=0; quick.detailScroll=0; }
50  return null;
51}
52/** Both adapters use the same menu, selection window and scrollable requirement text. */
53export function quickView(quick: QuickSetup, language: Language, width: number, height: number, sharedProjects: readonly string[] = []): {text:string;selected:boolean}[] {
54  const tr = (key:string,params:Record<string,unknown>={}) => t(key,language,params);
55  const preset = PRESETS.find(p=>p.id === (quick.step === 'scenario' ? PRESETS[quick.selected]!.id : quick.preset))!;
56  const d=quick.candidate.display;
57  const rows = quick.step === 'scenario' ? PRESETS.map(p=>(p.example ? tr('quick.example')+': ' : '')+tr('quick.purpose.'+p.id))
58    : quick.step === 'appearance' ? [
59      tr('fields.global.theme.label')+': '+tr('values.'+d.theme),
60      tr('settings.colors')+': '+tr('values.'+(d.use_colors?'on':'off')),
61      tr('settings.palette')+': '+d.palette,
62      tr('settings.separator-style')+': '+tr('values.'+d.separator_style), tr('quick.next'),
63    ] : [tr('quick.fine_tune'),tr('quick.save'),tr('quick.copy'),tr('quick.back')];
64  const paragraphs=[...(quick.step === 'review' && quick.selected === 1 && sharedProjects.length ? [tr('profiles.shared',{count:sharedProjects.length}), ...sharedProjects] : []),
65    tr(preset.requirements_key),tr('quick.sample'),
66    ...(!d.subagents.enabled && ['multi-agent','agent-focus'].includes(preset.id) ? [tr('quick.subagents_off')] : []),
67    ...(quick.step==='review' ? [tr('quick.replace')] : [])];
68  const detail=wrapText(paragraphs,width), menuHeight=Math.max(1, Math.min(rows.length,Math.floor(height/2)));
69  const start=Math.max(0, Math.min(quick.selected,rows.length-menuHeight,quick.selected-menuHeight+1));
70  const result=rows.slice(start,start+menuHeight).map((text,index)=>({text:(start+index===quick.selected?'› ':'  ')+text,selected:start+index===quick.selected}));
71  const capacity=Math.max(0,height-result.length), offset=Math.min(quick.detailScroll,Math.max(0,detail.length-capacity));
72  result.push(...detail.slice(offset,offset+capacity).map(text=>({text,selected:false})));
73  return result;
74}
75
76export function controlQuick(editor: Editor, key: string): 'transfer' | 'save' | 'profiles' | null {
77  const quick = editor.quick;
78  if (!quick) return null;
79  const effect = quickKey(quick,key);
80  if (effect === 'cancel') editor.quick = null;
81  if (effect === 'preset') { editor.preset=quick.preset; editor.pendingTransfer='preset'; return 'transfer'; }
82  if (effect === 'copy') { saveProfileCopy(editor, quick.candidate.display); editor.quick=null; return 'profiles'; }
83  if (effect === 'accept' || effect === 'save') { editor.replaceDraft(quick.candidate); editor.quick=null; return effect === 'save' ? 'save' : null; }
84  return null;
85}
86
lib/editor/profile-manager.ts 268 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import { createReview, navigateReview } from './import-review.ts';
3import { differences } from './import-differences.ts';
4import type { ConfigTarget, DisplayDraft, Operation, ProfilesResult, ResultFor } from '../generated-contracts.ts';
5import { t, text, type Language, type LocalizedText } from '../i18n/index.ts';
6import type { Editor } from './draft.ts';
7import { inputKey, inputView, textInput, type TextInput, type TextKey } from './text-input.ts';
8import { wrapText } from '../../ui/text.ts';
9import { BackendError } from '../backend.ts';
10
11type Action = 'edit' | 'activate' | 'save' | 'save_bind' | 'rename' | 'delete' | 'bind' | 'unbind' | 'import' | 'reuse' | 'export';
12type Switch = { target: ConfigTarget; display?: DisplayDraft };
13type Effect = { kind: 'load' } | { kind: 'switch'; next: Switch; save: boolean } |
14    { kind: 'mutation'; payload: Record<string, unknown> } | { kind: 'import'; path: string } | { kind: 'reuse'; path: string } |
15    { kind: 'export'; path: string; name: string; display: DisplayDraft; overwrite: boolean };
16export interface ProfileManager {
17    library: ProfilesResult | null;
18    page: 'list' | 'actions' | 'form' | 'confirm' | 'dirty';
19    selected: string | null;
20    projectRoot: string | null;
21    cursor: number;
22    detailScroll: number;
23    action: Action | null;
24    fields: { key: 'name' | 'path'; input: TextInput }[];
25    field: number;
26    candidate: DisplayDraft | null;
27    confirmation: Effect | null;
28    next: Switch | null;
29    effect: Effect | null;
30    message: LocalizedText | null;
31    uncertain: boolean;
32}
33export interface ProfileBackend { request<O extends Operation>(operation: O, payload?: unknown): ResultFor<O> | Promise<ResultFor<O>> }
34export function openProfiles(editor: Editor): void {
35    editor.profiles = { library: null, page: 'list', selected: null, projectRoot: null, cursor: 0, detailScroll: 0, action: null, fields: [], field: 0, candidate: null,
36        confirmation: null, next: null, effect: { kind: 'load' }, message: null, uncertain: false };
37}
38/** Open Save as without replacing the caller's unsaved draft. */
39export function saveProfileCopy(editor: Editor, display: DisplayDraft): void {
40    openProfiles(editor);
41    editor.profiles!.candidate = JSON.parse(JSON.stringify(display)) as DisplayDraft;
42    editor.profiles!.action = 'save';
43}
44export function targetLabel(editor: Editor, language: Language): string {
45    const c = editor.baseline.configuration;
46    if (!c) return t('profiles.user', language);
47    return t('profiles.target', language, { name: c.profile_name ?? t('profiles.user', language),
48        root: c.project_root ?? '—', count: c.shared_projects.length });
49}
50function entries(m: ProfileManager): { key: string; label: string; raw?: boolean }[] {
51    if (m.page === 'actions') return ['edit','activate','rename','delete','bind','export'].map(key => ({ key, label: 'profiles.action.' + key }));
52    return [{ key: 'user', label: 'profiles.user' }, ...(m.library?.profiles ?? []).map(p => ({ key: p.id, label: p.name, raw: true })),
53        ...(m.library?.bindings ?? []).map(b=>({key:'binding:'+b.root,label:b.root+' → '+(m.library!.profiles.find(p=>p.id===b.profile_id)?.name ?? b.profile_id),raw:true})),
54        ...['save','save_bind','import','unbind','reuse'].map(key => ({ key: 'action:' + key, label: 'profiles.action.' + key }))];
55}
56function startForm(e: Editor, action: Action): void {
57    const m = e.profiles!, profile = m.library?.profiles.find(p => p.id === m.selected), project = e.baseline.configuration;
58    const path = m.projectRoot ?? (project?.target.kind === 'project' ? project.target.path : project?.project_root ?? '');
59    m.action = action; m.page = 'form'; m.field = 0; m.message = null;
60    const keys = ['save','rename'].includes(action) ? ['name'] : action === 'save_bind' ? ['name','path'] : ['path'];
61    m.fields = keys.map(key => ({ key: key as 'name' | 'path', input: textInput(key === 'name' ? action === 'rename' ? profile?.name ?? '' : '' : ['bind','unbind','save_bind'].includes(action) ? path : 'profile.json') }));
62}
63function switching(e: Editor, next: Switch): void {
64    const m = e.profiles!;
65    if (e.modified) { m.next = next; m.page = 'dirty'; m.cursor = 0; }
66    else m.effect = { kind: 'switch', next, save: false };
67}
68function submitForm(e: Editor): void {
69    const m = e.profiles!, values = Object.fromEntries(m.fields.map(f => [f.key, f.input.value]));
70    const profile = m.library?.profiles.find(p => p.id === m.selected);
71    if (m.fields.some(f => !f.input.value.trim())) { m.message = text('profiles.required'); return; }
72    if (m.action === 'import' || m.action === 'reuse') { m.effect = { kind: m.action, path: values.path! }; return; }
73    if (m.action === 'export' && profile) {
74        m.confirmation = { kind: 'export', path: values.path!, name: profile.name, display: profile.display, overwrite: false };
75    } else {
76        const payload: Record<string, unknown> = { action: m.action === 'save_bind' ? 'save' : m.action, expected_revision: m.library!.revision, overwrite: false };
77        if (m.action === 'save' || m.action === 'save_bind') Object.assign(payload, { name: values.name, display: m.candidate ?? e.draft.display, ...(m.action === 'save_bind' ? { bind_path: values.path } : {}) });
78        if (m.action === 'rename') Object.assign(payload, { id: m.selected, name: values.name });
79        if (m.action === 'bind') Object.assign(payload, { id: m.selected, path: values.path });
80        if (m.action === 'unbind') payload.path = values.path;
81        m.confirmation = { kind: 'mutation', payload };
82    }
83    m.page = 'confirm'; m.cursor = 0; m.detailScroll = 0;
84}
85/** One reducer supplies both editors; text never dispatches shortcuts. */
86export function profilesKey(e: Editor, event: TextKey): 'profiles' | null {
87    const m = e.profiles;
88    if (!m) return null;
89    const key = event.key === 'return' ? 'enter' : event.key, plain = !event.ctrl && !event.meta && !event.text && !event.paste;
90    const cancel = !event.text && !event.paste && (key === 'escape' || event.ctrl && key.toLowerCase() === 'g');
91    if (event.overflow) { m.message = text('input.overflow'); return null; }
92    if (cancel) {
93        if (m.uncertain) { m.message = text('profiles.uncertain'); return null; }
94        if (m.page === 'list') e.profiles = null;
95        else { m.page = 'list'; m.cursor = 0; m.candidate = null; m.confirmation = null; }
96        return null;
97    }
98    if (m.page === 'form') {
99        if (plain && key === 'enter') {
100            if (m.field + 1 < m.fields.length) m.field++;
101            else submitForm(e);
102        } else if (plain && key === 'tab') m.field = (m.field + 1) % m.fields.length;
103        else {
104            const field = m.fields[m.field]!, edited = inputKey(field.input.value, field.input, event, field.key === 'name' ? 128 : 4096);
105            field.input = edited.state;
106            m.message = edited.error ? text('input.' + edited.error, { limit: field.key === 'name' ? 128 : 4096 }) : null;
107        }
108        return m.effect ? 'profiles' : null;
109    }
110    if (!plain) return null;
111    if (key.toLowerCase() === 'r') { m.effect = { kind: 'load' }; return 'profiles'; }
112    if (m.uncertain) { m.message = text('profiles.uncertain'); return null; }
113    if (m.page === 'dirty') {
114        const choices = ['save','discard','cancel'];
115        if (key === 'up') m.cursor = Math.max(0, m.cursor - 1);
116        if (key === 'down') m.cursor = Math.min(2, m.cursor + 1);
117        if (key === 'enter') {
118            if (choices[m.cursor] === 'cancel') { m.page = 'list'; m.cursor = 0; }
119            else m.effect = { kind: 'switch', next: m.next!, save: m.cursor === 0 };
120        }
121        return m.effect ? 'profiles' : null;
122    }
123    if (m.page === 'confirm') {
124        if (key === 'pageup' || key === 'pagedown') { m.detailScroll = Math.max(0, m.detailScroll + (key === 'pageup' ? -1 : 1)); return null; }
125        if (key === 'up' || key === 'down') m.cursor = 1 - m.cursor;
126        if (key === 'enter') {
127            if (m.cursor === 1) { m.page = 'list'; m.cursor = 0; m.confirmation = null; }
128            else { m.effect = m.confirmation; return 'profiles'; }
129        }
130        return null;
131    }
132    const rows = entries(m);
133    if (key === 'up') m.cursor = Math.max(0, m.cursor - 1);
134    if (key === 'down') m.cursor = Math.min(rows.length - 1, m.cursor + 1);
135    if (key === 'home') m.cursor = 0;
136    if (key === 'end') m.cursor = rows.length - 1;
137    if (key === 'pageup') m.cursor = Math.max(0, m.cursor - 5);
138    if (key === 'pagedown') m.cursor = Math.min(rows.length - 1, m.cursor + 5);
139    if (key === 'enter') {
140        const row = rows[m.cursor]!;
141        if (m.page === 'list') {
142            if (row.key === 'user') switching(e, { target: { kind: 'user' } });
143            else if (row.key.startsWith('action:')) { m.candidate = null; startForm(e, row.key.slice(7) as Action); }
144            else {
145                m.projectRoot = row.key.startsWith('binding:') ? row.key.slice(8) : null;
146                m.selected = m.projectRoot ? m.library!.bindings.find(b=>b.root===m.projectRoot)!.profile_id : row.key;
147                const selected = m.library!.profiles.find(p=>p.id===m.selected);
148                if (!selected) { m.message=text('profiles.error.missing',{value:m.selected}); return null; }
149                m.candidate=selected.display; m.page='actions';m.cursor=0;
150            }
151        } else if (row.key === 'edit') switching(e, { target: m.projectRoot ? {kind:'project',path:m.projectRoot} : { kind: 'profile', id: m.selected! } });
152        else if (row.key === 'activate') switching(e, { target: { kind: 'user' }, display: m.candidate! });
153        else if (row.key === 'delete') {
154            m.action = 'delete'; m.confirmation = { kind: 'mutation', payload: { action: 'delete', id: m.selected, expected_revision: m.library!.revision } };
155            m.page = 'confirm'; m.cursor = 1;
156        } else startForm(e, row.key as Action);
157    }
158    return m.effect ? 'profiles' : null;
159}
160export async function performProfileAction(e: Editor, backend: ProfileBackend): Promise<void> {
161    const m = e.profiles, effect = m?.effect;
162    if (!m || !effect) return;
163    m.effect = null;
164    let writing = false;
165    try {
166        if (effect.kind === 'load') {
167            const copy = m.action === 'save' && m.candidate !== null;
168            m.library = await backend.request('profiles_read'); m.page = 'list'; m.cursor = 0;
169            if (copy) startForm(e, 'save');
170            m.message = m.uncertain ? text('profiles.review_saved') : null; m.uncertain = false; return;
171        }
172        if (effect.kind === 'switch') {
173            if (effect.save) {
174                if (!e.acceptNumeric()) throw new BackendError('invalid_draft', text('profiles.invalid_draft'));
175                writing = true;
176                const saved = await backend.request('apply', { draft: e.draft, expected_revision: e.baseline.revision,
177                    ...(e.baseline.configuration ? { target: e.baseline.configuration.target } : {}) });
178                e.committed(saved); writing = false;
179            }
180            const current = await backend.request('read', { target: effect.next.target });
181            e.committed(current);
182            e.replaceDraft(current.draft);
183            if (effect.next.display) e.replaceDraft({ ...current.draft, display: JSON.parse(JSON.stringify(effect.next.display)) as DisplayDraft });
184            e.profiles = null; return;
185        }
186        if (effect.kind === 'import' || effect.kind === 'reuse') {
187            const original = JSON.stringify(e.draft);
188            const result = await backend.request('profile_import', { path: effect.path });
189            if (effect.kind === 'reuse') {
190                if (JSON.stringify(e.draft) !== original || e.profiles !== m) throw new BackendError('stale_import', text('review.stale'));
191                const draft = { display: result.display, host: e.draft.host };
192                e.review = createReview({ draft, changes: differences(e.draft, draft) }, e.draft);
193                navigateReview(e.review, 's', 'en', 80, 20); e.profiles = null; return;
194            }
195            m.candidate = result.display; startForm(e, 'save'); m.fields[0]!.input = textInput(result.name);
196            m.message = text('profiles.import_review'); return;
197        }
198        writing = true;
199        if (effect.kind === 'export') {
200            await backend.request('profile_export', { path: effect.path, name: effect.name, display: effect.display, overwrite: effect.overwrite });
201        } else {
202            m.library = await backend.request('profiles_apply', effect.payload);
203            writing = false;
204            if (effect.payload.bind_path && typeof effect.payload.bind_path === 'string') {
205                const host = e.draft.host;
206                const current = await backend.request('read', { target: { kind: 'project', path: effect.payload.bind_path } });
207                e.committed(current); e.replaceDraft({ ...current.draft, host });
208            } else if (e.baseline.configuration && (e.baseline.configuration.target.kind !== 'profile' ||
209                m.library.profiles.some(p=>p.id===e.baseline.configuration!.profile_id))) {
210                const current = await backend.request('read', { target: e.baseline.configuration.target });
211                if (current.configuration?.profile_id === e.baseline.configuration.profile_id &&
212                    JSON.stringify(current.draft) === JSON.stringify(e.baseline.draft)) e.baseline = current;
213            }
214        }
215        m.page = 'list'; m.cursor = 0; m.candidate = null; m.confirmation = null; m.message = text('profiles.saved');
216    } catch (error) {
217        const code = error instanceof BackendError ? error.code : '';
218        if (code === 'profile_duplicate' || code === 'profile_bound' || effect.kind === 'export' && code === 'io_error' && /EEXIST/u.test(String(error))) {
219            m.confirmation = effect.kind === 'mutation' ? { ...effect, payload: { ...effect.payload, overwrite: true } }
220                : effect.kind === 'export' ? { ...effect, overwrite: true } : null;
221            m.page = 'confirm'; m.cursor = 1; m.message = text('profiles.overwrite');
222        } else {
223            m.uncertain = writing && !['profile_conflict','profile_referenced','profile_invalid','profile_name','profile_path','ownership_mismatch','configuration_conflict','invalid_request','profile_size'].includes(code);
224            m.message = error instanceof BackendError && error.localization ? error.localization : text('profiles.failed', { value: error instanceof Error ? error.message : String(error) });
225        }
226    }
227}
228export function profilesView(e: Editor, language: Language, width: number, height: number): { text: string; selected: boolean }[] {
229    const m = e.profiles!;
230    const tr = (key: string) => t(key, language);
231    const lines: { text: string; selected: boolean }[] = [];
232    const add = (value: string, selected = false) => lines.push({ text: value, selected });
233    if (m.message) for (const line of wrapText([t(m.message.key, language, m.message.params)], width)) add(line);
234    if (m.uncertain) add(tr('profiles.uncertain'));
235    if (!m.library) { add(tr('profiles.loading')); return lines.slice(0, height); }
236    if (m.page === 'form') {
237        add(tr('profiles.action.' + m.action));
238        m.fields.forEach((f,i) => add(tr('profiles.field.' + f.key) + ': ' + inputView({ ...f.input }, Math.max(1, width - 12)), i === m.field));
239        add(tr('profiles.form_help')); return lines.slice(0, height);
240    }
241    const rows = m.page === 'confirm' ? [{ key:'confirm',label:'profiles.confirm' },{ key:'cancel',label:'profiles.cancel' }] :
242        m.page === 'dirty' ? ['save','discard','cancel'].map(key => ({ key, label:'profiles.'+key })) : entries(m);
243    if (m.page === 'dirty') add(tr('profiles.dirty'));
244    if (m.page === 'confirm') {
245        const value = m.confirmation;
246        add(tr('profiles.action.' + (m.action ?? 'export')));
247        if (value?.kind === 'mutation') add(String(value.payload.name ?? value.payload.path ?? m.library.profiles.find(p=>p.id===value.payload.id)?.name ?? ''));
248        if (value?.kind === 'export') add(value.path);
249        if (value?.kind === 'mutation' && value.payload.action === 'save' && typeof value.payload.name === 'string') {
250            const profile = m.library.profiles.find(profile => profile.name === (value.payload.name as string).trim().normalize('NFC'));
251            const roots = m.library.bindings.filter(binding => binding.profile_id === profile?.id).map(binding => binding.root);
252            if (roots.length) for (const line of wrapText([t('profiles.shared', language, { count: roots.length }), ...roots], width)) add(line);
253        }
254        // Keep both confirmation actions reachable even with many bound projects.
255        const capacity = Math.max(0, height - 3), start = Math.min(m.detailScroll, Math.max(0, lines.length - capacity));
256        return [...lines.slice(start, start + capacity), ...rows.map((row, index) => ({ text: tr(row.label), selected: index === m.cursor })),
257            { text: tr('profiles.navigation'), selected: false }].slice(0, height);
258    }
259    if (m.page === 'actions') {
260        add(m.library.profiles.find(p => p.id === m.selected)?.name ?? '');
261        add(t('profiles.shared', language, { count: m.library.bindings.filter(b => b.profile_id === m.selected).length }));
262    }
263    const capacity = Math.max(1, height - lines.length - 1), start = Math.max(0, Math.min(m.cursor, rows.length - capacity));
264    rows.slice(start,start+capacity).forEach((row,i) => add(('raw' in row && row.raw ? row.label : tr(row.label)), start+i === m.cursor));
265    add(tr('profiles.navigation'));
266    return lines.slice(0,height);
267}
268
lib/backend.ts 606 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import { validAlignments } from './editor/alignments.ts';
3import { GRADIENT_KEYS, validGradient } from './editor/gradients.ts';
4import { validCostRateOptions } from './editor/cost-rate.ts';
5import { validGroups } from './editor/groups.ts';
6import { INDICATOR_KEYS, validIndicatorOptions } from './editor/indicators.ts';
7import { SAMPLE_REASONS, EXPLAIN_REASONS, LAYOUT_REASONS, EVIDENCE_STATUSES } from './generated-contracts.ts';
8import { text as localizedText } from './i18n/index.ts';
9/** Protocol parsing only. Host calls stay in the hooks entry for static analysis. */
10import {
11  PROTOCOL_VERSION,
12  MAIN_ITEM_IDS,
13  SUBAGENT_ITEM_IDS,
14  PALETTE_VALUES, THEME_VALUES, POWERLINEGLYPH_VALUES,
15  DIRECTORYSTYLE_VALUES,
16  SEPARATORSTYLE_VALUES,
17  SCOPELABELS_VALUES,
18  STATUSLINELANGUAGE_VALUES,
19  UNAVAILABLEREASON_VALUES,
20  FORMAT_CHOICES, PRESETS, EDITOR_FIELDS, POWERLINE_FIELDS, GUIDANCE_KEYS, ITEM_DEFAULTS,
21} from './generated-contracts.ts';
22import type {
23  Capabilities,
24  CatalogItem,
25  ConfigurationOptions,
26  Draft,
27  Operation,
28  ResultFor,
29  Span,
30} from './generated-contracts.ts';
31import { validColor, visibilityChoices } from './editor/appearance.ts';
32import { isSourceResult } from './editor/source-validation.ts';
33import { isLocalizedText } from './i18n/index.ts';
34import type { LocalizedText } from './i18n/index.ts';
35
36export class BackendError extends Error {
37  constructor(
38    public readonly code: string,
39    message: string | LocalizedText,
40    public readonly localization: LocalizedText | null = typeof message === 'string' ? null : message,
41  ) {
42    super(typeof message === 'string' ? message : message.fallback);
43  }
44}
45
46export function processFailure(error: unknown): BackendError {
47  if (error instanceof BackendError) return error;
48  const message =
49    error instanceof Error
50      ? error.message
51      : 'The backend process could not run.';
52  const timedOut =
53    error instanceof Error &&
54    (error.name === 'TimeoutError' || /timed?\s*out|timeout/i.test(message));
55  return new BackendError(
56    timedOut ? 'backend_timeout' : 'backend_process',
57    message,
58  );
59}
60
61function object(value: unknown): value is Record<string, unknown> {
62  return typeof value === 'object' && value !== null && !Array.isArray(value);
63}
64
65function fail(): never {
66  throw new BackendError(
67    'invalid_backend_result',
68    localizedText("native.lib.backend.the_backend_returned_an_invalid_configuration_result"),
69  );
70}
71
72function exact(
73  value: Record<string, unknown>,
74  keys: readonly string[],
75): boolean {
76  return (
77    Object.keys(value).length === keys.length &&
78    keys.every((key) => key in value)
79  );
80}
81
82function text(value: unknown): value is string {
83  return typeof value === 'string' && !/[\p{Cc}\p{Cs}]/u.test(value);
84}
85
86function strings(value: unknown): value is string[] {
87  return Array.isArray(value) && value.every(text);
88}
89
90function selection(value: unknown, ids: readonly string[]): value is string[] {
91  return (
92    strings(value) &&
93    value.every((id) => ids.includes(id)) &&
94    new Set(value).size === value.length
95  );
96}
97
98function range(value: unknown, min: number, max: number, nullable = false): boolean {
99  return (nullable && value === null) ||
100    (typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max);
101}
102
103function formatOverrides(value: unknown): boolean {
104  if (!object(value)) return false;
105  return Object.entries(value).every(([key, v]) =>
106    key in FORMAT_CHOICES && typeof v === 'string' &&
107    (FORMAT_CHOICES[key as keyof typeof FORMAT_CHOICES] as readonly string[]).includes(v));
108}
109
110function itemOptions(value: unknown, ids: readonly string[], scope: "main" | "subagent"): boolean {
111  if (!object(value)) return false;
112  return Object.entries(value).every(([id, option]) => ids.includes(id) && object(option) &&
113    exact(option, [...GRADIENT_KEYS.filter(key => Object.hasOwn(option, key)), 'label', 'icon', 'priority', 'max_width', 'formatting', 'foreground', 'background', 'visibility', 'visibility_threshold', ...(option.link !== undefined ? ['link'] : []), ...INDICATOR_KEYS.filter(key => Object.hasOwn(option, key)), ...(Object.hasOwn(option, 'cost_rate_basis') ? ['cost_rate_basis'] : [])]) && (option.link === undefined || ['off','auto','on'].includes(String(option.link))) &&
114    (option.label === null || (text(option.label) && [...option.label].length <= 256)) &&
115    (option.icon === null || (text(option.icon) && [...option.icon].length <= 256)) &&
116    GRADIENT_KEYS.every(key => option[key] === undefined || id !== 'spacer' && validGradient(option[key])) && validIndicatorOptions(option, scope, id) && validCostRateOptions(option, scope, id) && range(option.priority, 0, 100) && range(option.max_width, 2, 10000, true) &&
117    formatOverrides(option.formatting) && validColor(option.foreground) && validColor(option.background) &&
118    typeof option.visibility === "string" && visibilityChoices(scope, id).includes(option.visibility) &&
119    range(option.visibility_threshold, 0, 100));
120}
121
122function formatting(value: unknown): boolean {
123  if (!object(value) || !exact(value, [...Object.keys(FORMAT_CHOICES), 'thresholds'])) return false;
124  const { thresholds, ...choices } = value;
125  return formatOverrides(choices) && object(thresholds) &&
126    exact(thresholds, ['enabled', 'warning', 'critical']) &&
127    typeof thresholds.enabled === 'boolean' && range(thresholds.warning, 0, 100) &&
128    range(thresholds.critical, 0, 100) && Number(thresholds.warning) < Number(thresholds.critical);
129}
130
131function instanceList(value: unknown, ids: readonly string[], scope: "main" | "subagent"): value is import('./generated-contracts.ts').InstanceDraft[] {
132  if (!Array.isArray(value)) return false;
133  const seen = new Set<string>();
134  return value.every(node => {
135    if (!object(node) || !exact(node,['id','type_id','enabled','options','text', ...(node.source !== undefined ? ['source'] : [])]) || node.source !== undefined && (!object(node.source) || !exact(node.source,['binding','hint']) || !(node.source.binding === null || text(node.source.binding)) || !text(node.source.hint)) ||
136        typeof node.id !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,95}$/.test(node.id) || seen.has(node.id) ||
137        typeof node.type_id !== 'string' || !ids.includes(node.type_id) || typeof node.enabled !== 'boolean' ||
138        !itemOptions({[node.type_id]: node.options},ids,scope)) return false;
139    seen.add(node.id);
140    const option = node.options as Record<string,unknown>;
141    if (node.type_id === 'spacer') {
142      if (JSON.stringify(option) !== JSON.stringify(ITEM_DEFAULTS)) {
143        if (Object.entries(ITEM_DEFAULTS).some(([key,v]) => JSON.stringify(option[key]) !== JSON.stringify(v))) return false;
144      }
145    }
146    if (['text','spacer'].includes(node.type_id) && (option.visibility !== 'always' || Object.keys(option.formatting as object).length)) return false;
147    return node.type_id === 'text' ? text(node.text) && [...node.text].length <= 256 : node.text === null;
148  });
149}
150
151export function isDraft(value: unknown): value is Draft {
152  if (
153    !object(value) ||
154    !exact(value, ['display', 'host']) ||
155    !object(value.display) ||
156    !object(value.host)
157  )
158    return false;
159  const d = value.display;
160  const h = value.host;
161  if (
162    !exact(d, [
163      'schema_version', 'groups',
164      'statusline_language',
165      'instances',
166      'use_colors',
167      'palette', 'theme', 'powerline_glyph', 'powerline',
168      'directory_style',
169      'separator_style',
170      'scope_labels',
171      'subagents',
172      'formatting', 'layout', 'metrics',
173    ]) ||
174    !exact(h, ['padding', 'refresh_interval', 'hide_vim_mode_indicator'])
175  )
176    return false;
177  if (
178    d.schema_version !== 15 ||
179    !object(d.powerline) || !exact(d.powerline, POWERLINE_FIELDS.map(f => f.key.slice(10))) ||
180    !POWERLINE_FIELDS.every(f => f.kind === 'boolean' ? typeof (d.powerline as Record<string, unknown>)[f.key.slice(10)] === 'boolean' :
181      (f.choices as readonly unknown[]).includes((d.powerline as Record<string, unknown>)[f.key.slice(10)])) ||
182    !THEME_VALUES.some(x => x === d.theme) || !POWERLINEGLYPH_VALUES.some(x => x === d.powerline_glyph) ||
183    !STATUSLINELANGUAGE_VALUES.some((x) => x === d.statusline_language) ||
184    !object(d.metrics) || !exact(d.metrics, ['branch_diff_base_ref']) ||
185    !(d.metrics.branch_diff_base_ref === null || (text(d.metrics.branch_diff_base_ref) && [...d.metrics.branch_diff_base_ref].length <= 256 &&
186      d.metrics.branch_diff_base_ref.length > 0 && !/[\s]|^-/.test(d.metrics.branch_diff_base_ref))) ||
187    !formatting(d.formatting) ||
188    typeof d.use_colors !== 'boolean' ||
189    !instanceList(d.instances, MAIN_ITEM_IDS, "main") ||
190    !PALETTE_VALUES.some((x) => x === d.palette) ||
191    !DIRECTORYSTYLE_VALUES.some((x) => x === d.directory_style) ||
192    !SEPARATORSTYLE_VALUES.some((x) => x === d.separator_style) ||
193    !SCOPELABELS_VALUES.some((x) => x === d.scope_labels)
194  )
195    return false;
196  const sub = d.subagents;
197  if (
198    !object(sub) ||
199    !exact(sub, ['enabled', 'instances', 'groups', 'visibility', 'hide_completed', 'row_limit', 'task_max_width']) ||
200    !['all', 'running'].includes(String(sub.visibility)) ||
201    typeof sub.hide_completed !== 'boolean' || !range(sub.row_limit, 0, 10000, true) ||
202    !range(sub.task_max_width, 2, 10000, true) ||
203    typeof sub.enabled !== 'boolean' ||
204    !instanceList(sub.instances, SUBAGENT_ITEM_IDS, "subagent")
205  )
206    return false;
207  if (sub.instances.filter(i => i.type_id === 'spacer').length > 1) return false;
208  const types = new Set(sub.instances.filter(i=>i.enabled).map(i=>i.type_id));
209  if (types.has('status-elapsed') && (types.has('status') || types.has('elapsed'))) return false;
210  const ids = d.instances.map(i=>i.id);
211  const spacers = new Set(d.instances.filter(i=>i.type_id==='spacer').map(i=>i.id));
212  const layout = d.layout;
213  if (!object(layout) || !exact(layout, ['mode', 'rows', ...(Object.hasOwn(layout, 'alignments') ? ['alignments'] : [])]) ||
214      !['auto', 'explicit'].includes(String(layout.mode)) || !Array.isArray(layout.rows) ||
215      !layout.rows.every((r) => selection(r, ids) && r.length > 0 && r.filter(id => spacers.has(id)).length <= 1) ||
216      (layout.mode === 'auto' ? layout.rows.length !== 0 || spacers.size > 0 :
217        JSON.stringify(layout.rows.flat()) !== JSON.stringify(ids))) return false;
218  if (!validGroups(d.groups, d.instances, layout as unknown as import('./generated-contracts.ts').LayoutDraft) || !validGroups(sub.groups, sub.instances)) return false;
219  if (!validAlignments(layout.alignments, layout as unknown as import('./generated-contracts.ts').LayoutDraft, d.instances, d.groups)) return false;
220  // Exclusions come from describe; the backend remains the final draft validator.
221  return (
222    typeof h.padding === 'number' &&
223    Number.isInteger(h.padding) &&
224    h.padding >= 0 &&
225    h.padding <= 32 &&
226    typeof h.hide_vim_mode_indicator === 'boolean' &&
227    (h.refresh_interval === 'event' ||
228      (typeof h.refresh_interval === 'number' &&
229        Number.isInteger(h.refresh_interval) &&
230        h.refresh_interval >= 1 &&
231        h.refresh_interval <= 3600))
232  );
233}
234
235export function isSpan(value: unknown): value is Span {
236  if (!object(value) || !text(value.text) || typeof value.bold !== 'boolean')
237    return false;
238  return [value.foreground, value.background].every(color =>
239    color === null ||
240    (object(color) &&
241      ((color.kind === 'rgb' && typeof color.value === 'string' && /^#[0-9a-f]{6}$/i.test(color.value)) ||
242       (color.kind === 'ansi' && typeof color.value === 'number' && Number.isInteger(color.value) &&
243        color.value >= 0 && color.value <= 255))));
244}
245
246function isCapabilities(value: unknown): value is Capabilities {
247  return (
248    object(value) &&
249    (value.host_version === null || text(value.host_version)) &&
250    ['unknown', 'supported', 'unsupported'].includes(
251      String(value.subagent_rows),
252    ) &&
253    ['unknown', 'unverified', 'unsupported'].includes(
254      String(value.native_mod),
255    ) &&
256    value.native_mod_loaded === null &&
257    value.data_observation === 'not_observed'
258  );
259}
260
261function isGuidance(value: unknown): boolean {
262  return object(value) && selection(value.source_kinds, GUIDANCE_KEYS.source_kinds) && value.source_kinds.length > 0 &&
263    GUIDANCE_KEYS.scopes.some(scope => scope === value.measurement_scope) &&
264    selection(value.requirements, GUIDANCE_KEYS.requirements) && strings(value.setup);
265}
266
267function isImportChange(value: unknown): boolean {
268  if (!object(value) || !exact(value, ['section', 'kind', 'scope', 'item_id', 'path', 'before', 'after', 'label']) ||
269      !['main','subagent','formatting','layout','language','host'].includes(String(value.section)) ||
270      !['add','remove','enable','disable','reorder','change'].includes(String(value.kind)) ||
271      !(value.scope === null || value.scope === 'main' || value.scope === 'subagent') ||
272      !strings(value.path) || !value.path.length || value.path.length > 8 ||
273      !['display','host'].includes(value.path[0]!) || !isLocalizedText(value.label)) return false;
274  if (value.item_id !== null && (typeof value.item_id !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,95}$/.test(value.item_id))) return false;
275  if (value.kind === 'enable' || value.kind === 'disable')
276    return value.item_id !== null && value.before === (value.kind === 'disable') && value.after === (value.kind === 'enable');
277  if (value.kind === 'add' || value.kind === 'remove')
278    return value.item_id !== null && (value.kind === 'add' ? value.before === null && object(value.after) : object(value.before) && value.after === null);
279  if (value.kind === 'reorder')
280    return value.item_id === null && strings(value.before) && strings(value.after) &&
281      new Set(value.before).size === value.before.length && new Set(value.after).size === value.after.length &&
282      value.before.length === value.after.length && value.before.every(id => (value.after as string[]).includes(id));
283  return true;
284}
285
286function isCatalog(value: unknown): value is CatalogItem[] {
287  if (
288    !Array.isArray(value) ||
289    value.length !== MAIN_ITEM_IDS.length + SUBAGENT_ITEM_IDS.length
290  )
291    return false;
292  const seen = new Set<string>();
293  return value.every((item) => {
294    if (
295      !object(item) ||
296      !text(item.id) ||
297      !text(item.label) ||
298      !text(item.description) ||
299      !text(item.group) ||
300      !strings(item.sources) ||
301      !strings(item.examples) ||
302      !strings(item.format_options) ||
303      !strings(item.unavailable_reasons) ||
304      !isGuidance(item.guidance) ||
305      typeof item.default_enabled !== 'boolean' ||
306      !(item.minimum_version === null || text(item.minimum_version)) ||
307      !(
308        item.default_position === null ||
309        (typeof item.default_position === 'number' &&
310          Number.isInteger(item.default_position) &&
311          item.default_position >= 0)
312      ) ||
313      item.default_enabled !== (item.default_position !== null) ||
314      item.minimum_version_status !==
315        (item.minimum_version ? 'verified' : 'unknown')
316    )
317      return false;
318    const ids =
319      item.scope === 'main'
320        ? MAIN_ITEM_IDS
321        : item.scope === 'subagent'
322          ? SUBAGENT_ITEM_IDS
323          : [];
324    const key = `${item.scope}:${item.id}`;
325    if (
326      !ids.some((id) => id === item.id) ||
327      !selection(item.excludes, ids) ||
328      item.excludes.includes(item.id) ||
329      seen.has(key)
330    )
331      return false;
332    seen.add(key);
333    return item.unavailable_reasons.every((reason) =>
334      UNAVAILABLEREASON_VALUES.some((known) => known === reason),
335    );
336  });
337}
338
339function isOptions(value: unknown): value is ConfigurationOptions {
340  if (!object(value)) return false;
341  const choices: Record<string, readonly (string | boolean)[]> = {
342    colors: [true, false],
343    palette: PALETTE_VALUES,
344    theme: THEME_VALUES,
345    "powerline-glyph": POWERLINEGLYPH_VALUES,
346    ...Object.fromEntries(POWERLINE_FIELDS.map(f => [f.key.replaceAll('.', '-').replaceAll('_', '-'), f.kind === 'boolean' ? [true, false] : f.choices])),
347    'directory-style': DIRECTORYSTYLE_VALUES,
348    'separator-style': SEPARATORSTYLE_VALUES,
349    'scope-labels': SCOPELABELS_VALUES,
350    'statusline-language': STATUSLINELANGUAGE_VALUES,
351    'subagent-statusline': [true, false],
352    'hide-vim-mode-indicator': [true, false],
353  };
354  for (const [key, allowed] of Object.entries(choices)) {
355    const option = value[key];
356    if (
357      !object(option) ||
358      !Array.isArray(option.choices) ||
359      option.choices.length !== allowed.length ||
360      new Set(option.choices).size !== option.choices.length ||
361      !option.choices.every((choice) => allowed.includes(choice))
362    )
363      return false;
364  }
365  for (const [key, minimum, maximum] of [
366    ['padding', 0, 32],
367    ['refresh-interval', 1, 3600],
368  ] as const) {
369    const option = value[key];
370    if (
371      !object(option) ||
372      option.minimum !== minimum ||
373      option.maximum !== maximum
374    )
375      return false;
376    if (key === 'refresh-interval' && option.special !== 'event') return false;
377  }
378  return true;
379}
380
381export function requestText(
382  operation: Operation,
383  payload: unknown = {},
384): string {
385  return JSON.stringify({
386    protocol_version: PROTOCOL_VERSION,
387    operation,
388    payload,
389  });
390}
391
392export function parseResponse<O extends Operation>(
393  operation: O,
394  process: {
395    exitCode: number;
396    stdout: string;
397    stderr: string;
398    isStdoutTruncated?: boolean;
399  },
400): ResultFor<O> {
401  if (process.isStdoutTruncated) {
402    throw new BackendError(
403      'backend_output_truncated',
404      localizedText("native.lib.backend.the_backend_json_was_truncated_by_the_host"),
405    );
406  }
407  let response: unknown;
408  try {
409    response = JSON.parse(process.stdout);
410  } catch {
411    const message =
412      process.exitCode !== 0
413        ? `The backend exited with status ${process.exitCode}.`
414        : 'The backend did not return complete JSON.';
415    throw new BackendError(
416      process.exitCode !== 0 ? 'backend_exit' : 'invalid_backend_json',
417      localizedText("native.lib.backend.check_the_bound_backend_executable_and_reinstall_matching", {message: message}),
418    );
419  }
420  if (!object(response) || response.protocol_version !== PROTOCOL_VERSION) {
421    throw new BackendError(
422      'protocol_mismatch',
423      localizedText("native.lib.backend.the_frontend_and_backend_protocol_versions_do_not"),
424    );
425  }
426  if (
427    'error' in response === 'result' in response ||
428    !exact(response, [
429      'protocol_version',
430      'error' in response ? 'error' : 'result',
431    ])
432  )
433    fail();
434  if ('error' in response) {
435    if (
436      !object(response.error) ||
437      !exact(response.error, ['code', 'message', ...('localization' in response.error ? ['localization'] : [])]) ||
438      !text(response.error.code) ||
439      typeof response.error.message !== 'string' ||
440      !(!('localization' in response.error) || response.error.localization === null || isLocalizedText(response.error.localization))
441    )
442      fail();
443    throw new BackendError(response.error.code, response.error.message, isLocalizedText(response.error.localization) ? response.error.localization : null);
444  }
445  if (process.exitCode !== 0) {
446    throw new BackendError(
447      'backend_exit',
448      localizedText("native.lib.backend.the_backend_exited_with_status", {exitCode: process.exitCode}),
449    );
450  }
451  const result = response.result;
452  if (!object(result)) fail();
453  if (operation === 'read_ui_preferences' || operation === 'set_ui_language') {
454    if (!exact(result, ['schema_version', 'ui_language', 'warning']) || result.schema_version !== 1 ||
455        !STATUSLINELANGUAGE_VALUES.some(language => language === result.ui_language) ||
456        !(result.warning === null || isLocalizedText(result.warning))) fail();
457  } else if (operation === 'read' || operation === 'apply') {
458    if (result.configuration !== undefined && !isConfiguration(result.configuration)) fail();
459    if (
460      !isDraft(result.draft) ||
461      typeof result.revision !== 'string' ||
462      !/^[0-9a-f]{64}$/.test(result.revision) ||
463      typeof result.installed !== 'boolean' ||
464      !object(result.installation) ||
465      !isCapabilities(result.capabilities) ||
466      !text(result.backend_version) ||
467      !result.backend_version
468    )
469      fail();
470    if (
471      operation === 'apply' &&
472      (typeof result.changed !== 'boolean' ||
473        !(result.backup_dir === null || typeof result.backup_dir === 'string'))
474    )
475      fail();
476  } else if (operation === 'review_import') {
477    if (!exact(result, ['draft','changes']) || !isDraft(result.draft) || !Array.isArray(result.changes) || !result.changes.every(isImportChange)) fail();
478  } else if (operation === 'import' || operation === 'preset') {
479    if (!isDraft(result.draft)) fail();
480  } else if (operation.startsWith('source')) {
481    if (!isSourceResult(operation,result)) fail();
482  } else if (operation === 'profiles_read' || operation === 'profiles_apply') {
483    if (!isProfiles(result) || operation === 'profiles_apply' && (typeof result.changed !== 'boolean' || !(result.backup_dir === null || text(result.backup_dir)))) fail();
484  } else if (operation === 'profile_import') {
485    if (!exact(result, ['name','display']) || !text(result.name) || !displayDraft(result.display)) fail();
486  } else if (operation === 'task_details') {
487    if (!isTaskDetails(result)) fail();
488  } else if (operation === 'export' || operation === 'profile_export') {
489    if (!text(result.path) || !result.path) fail();
490  } else if (operation === 'explain') {
491    if (!exact(result,['sample','scope','width','actual_availability','preview','instances']) || result.sample!==true ||
492        !['main','subagent'].includes(String(result.scope)) || !Number.isInteger(result.width) || Number(result.width)<2 || Number(result.width)>10000 || result.actual_availability!=='not_observed' ||
493        !object(result.preview) || result.preview.sample!==true || !Array.isArray(result.preview.main) || !Array.isArray(result.preview.subagents) ||
494        ![...result.preview.main,...result.preview.subagents].every(row=>Array.isArray(row)&&row.every(isSpan)) ||
495        !Array.isArray(result.instances) || result.instances.length>10000) fail();
496    const ids=new Set<string>();
497    for(const item of result.instances as unknown[]) {
498      if(!object(item)||!exact(item,['id','type_id','enabled','reasons','samples'])||!text(item.id)||ids.has(item.id)||!text(item.type_id)||typeof item.enabled!=='boolean'||!Array.isArray(item.reasons)||!Array.isArray(item.samples)) fail();
499      ids.add(item.id as string);
500      if(!item.reasons.every((reason:unknown)=>object(reason)&&exact(reason,['code','origin'])&&EXPLAIN_REASONS.includes(reason.code as typeof EXPLAIN_REASONS[number])&&['configuration','local_configuration','host_capability','unknown'].includes(String(reason.origin)))) fail();
501      if(!item.samples.every((row:unknown)=>object(row)&&exact(row,['row_id','outcome','truncated'])&&text(row.row_id)&&SAMPLE_REASONS.includes(row.outcome as typeof SAMPLE_REASONS[number])&&typeof row.truncated==='boolean')) fail();
502    }
503  } else if (operation === 'diagnose') {
504    if (!isDiagnosis(result)) fail();
505  } else if (operation === 'preview') {
506    if (
507      result.sample !== true ||
508      !Array.isArray(result.main) ||
509      !Array.isArray(result.subagents) ||
510      ![...result.main, ...result.subagents].every(
511        (row) => Array.isArray(row) && row.every(isSpan),
512      )
513    )
514      fail();
515  } else if (operation === 'describe') {
516    if (
517      !text(result.backend_version) ||
518      !result.backend_version ||
519      !isOptions(result.options) ||
520      !isCapabilities(result.capabilities) ||
521      !selection(result.operations, ['sources_read','sources_apply','source_review','source_context','source_refresh','source_status','source_cancel','source_diagnose','describe', 'read', 'preview', 'apply', 'import', 'export', 'preset', 'read_ui_preferences', 'set_ui_language', 'review_import', 'explain', 'diagnose', 'profiles_read', 'profiles_apply', 'profile_import', 'profile_export', 'task_details']) ||
522      result.operations.length !== 25 ||
523      JSON.stringify(result.editor_fields) !== JSON.stringify(EDITOR_FIELDS) ||
524      JSON.stringify(result.presets) !== JSON.stringify(PRESETS) ||
525      !object(result.formatting_options) ||
526      JSON.stringify(result.formatting_options) !== JSON.stringify(FORMAT_CHOICES) ||
527      !isCatalog(result.catalog)
528    )
529      fail();
530  }
531  return result as unknown as ResultFor<O>;
532}
533
534function displayDraft(display: unknown): boolean {
535  return isDraft({ display, host: { padding: 0, refresh_interval: 'event', hide_vim_mode_indicator: false } });
536}
537function isConfiguration(value: unknown): boolean {
538  if (!object(value) || !exact(value, ['target','profile_id','profile_name','project_root','reason','shared_projects']) || !object(value.target)) return false;
539  const target = value.target;
540  return (target.kind === 'user' && exact(target,['kind']) || target.kind === 'profile' && exact(target,['kind','id']) && text(target.id) ||
541    target.kind === 'project' && exact(target,['kind','path']) && text(target.path)) &&
542    ['profile_id','profile_name','project_root'].every(k => value[k] === null || text(value[k])) && text(value.reason) && strings(value.shared_projects);
543}
544function isProfiles(value: Record<string, unknown>): boolean {
545  if (value.version !== 1 || !text(value.revision) || !/^[a-f0-9]{64}$/u.test(value.revision) ||
546      !Array.isArray(value.profiles) || !Array.isArray(value.bindings) || value.profiles.length > 128 || value.bindings.length > 512) return false;
547  const ids = new Set<string>(), names = new Set<string>(), roots = new Set<string>();
548  return value.profiles.every(p => {
549    if (!object(p) || !exact(p,['id','name','display']) || !text(p.id) || !text(p.name) || ids.has(p.id) || names.has(p.name) || !displayDraft(p.display)) return false;
550    ids.add(p.id); names.add(p.name); return true;
551  }) && value.bindings.every(b => {
552    if (!object(b) || !exact(b,['root','profile_id']) || !text(b.root) || !text(b.profile_id) || roots.has(b.root)) return false;
553    roots.add(b.root); return true;
554  });
555}
556function isTaskDetails(value: Record<string, unknown>): boolean {
557  const nullable = (v: unknown) => v === null || text(v);
558  const count = (v: unknown) => v === null || typeof v === 'number' && Number.isFinite(v) && v >= 0;
559  const stamp = (v: unknown) => v === null || text(v) && Number.isFinite(Date.parse(v));
560  const evidence = (v: unknown) => object(v) && exact(v,['source','scope','status','observed_at','freshness']) && text(v.source) &&
561    text(v.scope) && text(v.status) && stamp(v.observed_at) && ['current','stale','unknown','newer_than_input'].includes(String(v.freshness));
562  if (!exact(value,['version','session_id','prompt_id','captured_at','status','phase','elapsed_seconds','active_seconds','progress','agents','evidence','limitations']) ||
563      value.version !== 1 || !text(value.session_id) || !nullable(value.prompt_id) || !text(value.captured_at) || !stamp(value.captured_at) ||
564      !nullable(value.status) || !nullable(value.phase) || !count(value.elapsed_seconds) || !count(value.active_seconds) ||
565      !Array.isArray(value.evidence) || !value.evidence.every(evidence) || !strings(value.limitations) || !Array.isArray(value.agents)) return false;
566  if (value.progress !== null && (!object(value.progress) || !exact(value.progress,['completed','total']) || !range(value.progress.completed,0,100000) ||
567      !range(value.progress.total,0,100000) || Number(value.progress.completed) > Number(value.progress.total))) return false;
568  const ids = new Set<string>();
569  return value.agents.every(agent => {
570    if (!object(agent) || !exact(agent,['id','parent_id','name','status','evidence']) || !text(agent.id) || ids.has(agent.id) ||
571        !nullable(agent.parent_id) || !nullable(agent.name) || !nullable(agent.status) || !Array.isArray(agent.evidence) || !agent.evidence.every(evidence)) return false;
572    ids.add(agent.id); return true;
573  });
574}
575
576function isDiagnosis(value: Record<string, unknown>): boolean {
577  const nullable = (v: unknown) => v === null || text(v);
578  const stamp = (v: unknown) => v === null || typeof v === 'string' && Number.isFinite(Date.parse(v));
579  if (!exact(value, ['sample','scope','width','source','observed_at','diagnosed_at','session_id','prompt_id','host_version','include_local','output','instances','host_fields', ...(value.configuration !== undefined ? ['configuration'] : [])]) ||
580      value.configuration !== undefined && !isConfiguration(value.configuration) ||
581      value.sample !== false || !['main','subagent'].includes(String(value.scope)) || !range(value.width,2,10000) || !text(value.source) ||
582      !stamp(value.observed_at) || value.diagnosed_at === null || !stamp(value.diagnosed_at) || !nullable(value.session_id) || !nullable(value.prompt_id) ||
583      !nullable(value.host_version) || typeof value.include_local !== 'boolean' || !Array.isArray(value.output) || !Array.isArray(value.instances) || !object(value.host_fields)) return false;
584  if (!value.output.every(row => object(row) && exact(row,['id','spans']) && text(row.id) && Array.isArray(row.spans) && row.spans.every(isSpan))) return false;
585  const ids = new Set<string>();
586  if (!value.instances.every(item => {
587    if (!object(item) || !exact(item,['id','type_id','enabled','reasons','evidence','rows']) || !text(item.id) || ids.has(item.id) || !text(item.type_id) || typeof item.enabled !== 'boolean' || !Array.isArray(item.reasons) || !Array.isArray(item.evidence) || !Array.isArray(item.rows)) return false;
588    ids.add(item.id);
589    return item.reasons.every((reason: unknown) => object(reason) && exact(reason,['code','origin']) && EXPLAIN_REASONS.includes(reason.code as typeof EXPLAIN_REASONS[number]) && ['configuration','local_configuration','host_capability','unknown'].includes(String(reason.origin))) &&
590      item.evidence.every((e: unknown) => object(e) && exact(e,['source','scope','status','observed_at','freshness','fields']) && text(e.source) && text(e.scope) && EVIDENCE_STATUSES.includes(e.status as typeof EVIDENCE_STATUSES[number]) && stamp(e.observed_at) && ['current','stale','unknown','newer_than_input'].includes(String(e.freshness)) && Array.isArray(e.fields) && e.fields.every((f: unknown) => object(f) && exact(f,['path','status']) && text(f.path) && ['observed','not_observed','invalid_field'].includes(String(f.status)))) &&
591      item.rows.every((row: unknown) => object(row) && exact(row,['row_id','outcome','truncated']) && text(row.row_id) && LAYOUT_REASONS.includes(row.outcome as typeof LAYOUT_REASONS[number]) && typeof row.truncated === 'boolean');
592  })) return false;
593  const tree = value.host_fields.worktree, cache = value.host_fields.cache_miss;
594  return exact(value.host_fields,['worktree','cache_miss']) && object(tree) && exact(tree,['session_name','git_name','selected_source']) && nullable(tree.session_name) && nullable(tree.git_name) && [null,'worktree.name','workspace.git_worktree'].includes(tree.selected_source as string | null) &&
595    object(cache) && exact(cache,['status','causes','last_miss_at','tools_added','tools_removed','system_char_delta']) && ['observed','not_observed','no_misses','unidentified','invalid_field'].includes(String(cache.status)) && strings(cache.causes) &&
596    ['last_miss_at','tools_added','tools_removed','system_char_delta'].every(key => cache[key] === null || typeof cache[key] === 'number' && Number.isFinite(cache[key]));
597}
598
599export function spanColor(span: Span, channel: 'foreground' | 'background' = 'foreground'): string | undefined {
600  const color = span[channel];
601  if (color?.kind === 'rgb') return String(color.value);
602  if (color?.kind === 'ansi')
603    return `ansi256(${Number(color.value)})`;
604  return undefined;
605}
606
lib/editor/draft.ts 282 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import type { AlignmentManager } from './alignment-manager.ts';
3import type { GroupManager } from './group-manager.ts';
4import { reconcileGroups, insertionAfter } from './groups.ts';
5import type { ExplanationView } from './explanation.ts';
6import type { SourceManager } from './source-manager.ts';
7import type { ProfileManager } from './profile-manager.ts';
8import type { QuickSetup } from './quick-setup.ts';
9import { t, text, type Language } from '../i18n/index.ts';
10import { alignmentConflicts } from './alignments.ts';
11import { nodes, newInstance, reconcileRows } from './instances.ts';
12import { isDraft } from '../backend.ts';
13import type {
14  CatalogItem,
15  DescribeResult,
16  Draft,
17  ReadResult,
18  Scope,
19} from '../generated-contracts.ts';
20import { NUMERIC_FIELDS, numericValue, numericDiagnostic } from './numeric.ts';
21import { bestMatch, fields, normalize } from './search.ts';
22import type { Match } from './search.ts';
23import type { ReviewState } from './import-review.ts';
24import type { LocalizedText } from '../i18n/index.ts';
25import type { NumericField } from './numeric.ts';
26export type { NumericField } from './numeric.ts';
27
28export type Page = 'main' | 'subagents' | 'settings' | 'layout';
29
30/** Copy wire data without sharing editable arrays with the opening snapshot. */
31export function copyDraft(draft: Draft): Draft {
32  return JSON.parse(JSON.stringify(draft)) as Draft;
33}
34
35export function sameDraft(left: Draft, right: Draft): boolean {
36  return JSON.stringify(left) === JSON.stringify(right);
37}
38
39/** Pure tool draft. Persistence and host configuration calls live in the hook. */
40export class Editor {
41  draft: Draft;
42  baseline: ReadResult;
43  page: Page = 'main';
44  advanced = false;
45  adding = false;
46  pickerSaved: {search:string;category:string;selected:string} | null = null;
47  detail: { scope: Scope; id: string } | null = null;
48  guidanceScroll: number | null = null;
49  review: ReviewState | null = null;
50  quick: QuickSetup | null = null;
51  explanation: ExplanationView | null = null;
52  profiles: ProfileManager | null = null;
53  sources: SourceManager | null = null;
54  groupManager: GroupManager | null = null;
55  alignmentManager: AlignmentManager | null = null;
56  compositionError: LocalizedText = text('composition.invalid');
57  preset = 'minimal';
58  path = 'statusline.json';
59  pendingTransfer: 'import' | 'export' | 'preset' | null = null;
60  setting = 'colors';
61  activeNumeric: NumericField | null = null;
62  selected: Record<Scope, string>;
63  order: Record<Scope, string[]>;
64  search: Record<Scope, string> = { main: '', subagent: '' };
65  category: Record<Scope, string> = { main: 'all', subagent: 'all' };
66  buffers: Record<NumericField, string>;
67  fieldErrors: Partial<Record<NumericField, string>> = {};
68  fieldErrorMessages: Partial<Record<NumericField, LocalizedText>> = {};
69
70  constructor(
71    public readonly description: DescribeResult,
72    current: ReadResult,
73  ) {
74    description.catalog.forEach(item => fields(item));
75    this.baseline = { ...current, draft: copyDraft(current.draft) };
76    this.draft = copyDraft(current.draft);
77    this.order = { main: [], subagent: [] };
78    this.selected = { main: '', subagent: '' };
79    for (const scope of ['main', 'subagent'] as const) {
80      this.order[scope] = nodes(this.draft,scope).map(i=>i.id);
81      this.selected[scope] = this.order[scope][0] || '';
82    }
83    this.buffers = {
84      padding: String(this.draft.host.padding),
85      refresh_interval: String(this.draft.host.refresh_interval),
86    };
87  }
88
89  replaceDraft(draft: Draft): void {
90    this.draft = copyDraft(draft);
91    for (const scope of ['main', 'subagent'] as const) {
92      this.order[scope] = nodes(this.draft,scope).map(i=>i.id);
93      if (!this.order[scope].includes(this.selected[scope])) this.selected[scope] = this.order[scope][0] || '';
94    }
95    this.buffers = { padding: String(draft.host.padding), refresh_interval: String(draft.host.refresh_interval) };
96    this.fieldErrors = {};
97    this.fieldErrorMessages = {};
98    this.activeNumeric = null;
99    this.detail = null;
100    this.guidanceScroll = null;
101    this.explanation = null;
102    this.review = null; this.alignmentManager = null;
103  }
104
105  get modified(): boolean {
106    return (
107      !sameDraft(this.draft, this.baseline.draft) ||
108      this.buffers.padding !== String(this.draft.host.padding) ||
109      this.buffers.refresh_interval !== String(this.draft.host.refresh_interval)
110    );
111  }
112
113  catalog(scope: Scope): CatalogItem[] {
114    return this.description.catalog.filter((item) => item.scope === scope);
115  }
116
117  items(scope: Scope): string[] {
118    return nodes(this.draft,scope).filter(i=>i.enabled).map(i=>i.id);
119  }
120
121  instance(scope: Scope, id: string) { return nodes(this.draft,scope).find(i=>i.id===id); }
122  definition(scope: Scope, id: string): CatalogItem | undefined {
123    return this.catalog(scope).find(i=>i.id===(this.instance(scope,id)?.type_id ?? id));
124  }
125
126  instanceLabel(scope:Scope,id:string,language:Language='en'):string {
127    const node=this.instance(scope,id),type=node?.type_id??id;
128    const peers=nodes(this.draft,scope).filter(i=>i.type_id===type);
129    return (node?.options.label || (type==='text'?node?.text:null) || t(`items.${scope}.${type}.label`,language))+
130      (node&&peers.length>1?` (${peers.indexOf(node)+1})`:'');
131  }
132
133  visible(scope: Scope): CatalogItem[] { return this.matches(scope).map(result => result.item); }
134
135  matches(scope: Scope): {item: CatalogItem & {type_id?:string;custom_label?:string|null;ordinal?:number}; match: Match}[] {
136    const catalog = new Map(this.catalog(scope).map(item=>[item.id as string,item]));
137    const order = this.adding ? [...catalog.keys()] : this.order[scope];
138    return order.flatMap(id=> {
139      const node = this.adding ? undefined : this.instance(scope,id);
140      const definition = catalog.get(node?.type_id ?? id);
141      if (!definition || (this.category[scope] !== 'all' && definition.group !== this.category[scope])) return [];
142      const peers = node ? nodes(this.draft,scope).filter(i=>i.type_id===node.type_id) : [];
143      const item = {...definition,id,type_id:definition.id,custom_label:node?.options.label || (node?.type_id==='text'?node.text:null),ordinal:peers.length>1?peers.indexOf(node!)+1:undefined};
144      const match = normalize(this.search[scope]).characters.length
145        ? bestMatch(fields(definition,item.custom_label),this.search[scope])
146        : {rank:5,positions:[],text:id,field:'id'};
147      return match ? [{item,match}] : [];
148    }).sort((a,b)=>a.match.rank-b.match.rank);
149  }
150
151  openPicker(scope: Scope): void {
152    this.pickerSaved={search:this.search[scope],category:this.category[scope],selected:this.selected[scope]};
153    this.adding=true; this.search[scope]='';this.category[scope]='all';this.selected[scope]=this.catalog(scope)[0]?.id ?? '';
154  }
155  closePicker(scope: Scope): void {
156    if(this.pickerSaved){this.search[scope]=this.pickerSaved.search;this.category[scope]=this.pickerSaved.category;this.selected[scope]=this.pickerSaved.selected;}
157    this.adding=false;this.pickerSaved=null;
158  }
159  instanceAction(scope: Scope, action:'add'|'copy'|'remove', typeId?:string): boolean {
160    this.compositionError = text('composition.invalid');
161    const draft=copyDraft(this.draft), list=nodes(draft,scope);
162    const selected=this.adding ? this.pickerSaved?.selected : this.selected[scope];
163    const index=list.findIndex(i=>i.id===selected);
164    let next=selected ?? '';
165    if(action==='remove'){
166      if(index<0)return false;
167      list.splice(index,1);next=list[Math.min(index,list.length-1)]?.id??'';
168    }else{
169      if(action==='copy'&&index<0)return false;
170      const node=newInstance(typeId??list[index]!.type_id,list,action==='copy'?list[index]:undefined);
171      list.splice(insertionAfter(list, (scope === 'main' ? draft.display : draft.display.subagents).groups, selected),0,node);next=node.id;
172    }
173    const target = scope === 'main' ? draft.display : draft.display.subagents;
174    target.groups = reconcileGroups(target.groups, list);
175    if(scope==='main')reconcileRows(draft);
176    if(!this.acceptStructure(draft))return false;
177    if(this.adding){this.closePicker(scope);this.search[scope]='';this.category[scope]='all';}
178    this.draft=draft;this.order[scope]=list.map(i=>i.id);this.selected[scope]=next;
179    return true;
180  }
181
182  categories(scope: Scope): string[] {
183    return ['all', ...new Set(this.catalog(scope).map(item => item.group))];
184  }
185
186  filtered(scope: Scope): boolean {
187    return this.category[scope] !== 'all' || normalize(this.search[scope]).characters.length > 0;
188  }
189
190  chooseCategory(scope: Scope, category: string): void {
191    if (!this.categories(scope).includes(category)) return;
192    this.category[scope] = category;
193    this.filter(scope, this.search[scope]);
194  }
195
196  filter(scope: Scope, value: string): void {
197    this.search[scope] = value;
198    const matches = this.matches(scope), selected = matches.find(result => result.item.id === this.selected[scope]);
199    if (!selected || selected.match.rank > matches[0]!.match.rank) {
200      this.selected[scope] = matches[0]?.item.id || '';
201    }
202  }
203
204  toggle(scope: Scope, id: string): boolean {
205    this.compositionError = text('composition.invalid');
206    if(this.adding)return this.instanceAction(scope,'add',id);
207    const draft=copyDraft(this.draft),node=nodes(draft,scope).find(i=>i.id===id);
208    if(!node)return false;
209    node.enabled=!node.enabled;
210    if(!isDraft(draft))return false;
211    this.draft=draft;return true;
212  }
213
214  move(scope: Scope, delta: -1 | 1): boolean {
215    this.compositionError = text('composition.invalid');
216    if (this.adding || this.filtered(scope)) return false;
217    const visible = this.visible(scope).map((item) => item.id as string);
218    const id = this.selected[scope];
219    const index = visible.indexOf(id);
220    const target = visible[index + delta];
221    if (index < 0 || !target) return false;
222    const draft = copyDraft(this.draft);
223    const ordered = nodes(draft, scope);
224    const sourceIndex = ordered.findIndex(node => node.id === id);
225    const [moving] = ordered.splice(sourceIndex, 1);
226    ordered.splice(ordered.findIndex(node => node.id === target) + (delta > 0 ? 1 : 0), 0, moving!);
227    if (scope === 'main') reconcileRows(draft);
228    if (!this.acceptStructure(draft)) return false;
229    this.draft = draft;
230    this.order[scope] = ordered.map(node => node.id);
231    return true;
232  }
233
234  private acceptStructure(draft: Draft): boolean {
235    const ids = alignmentConflicts(draft.display);
236    if (ids.length) this.compositionError = text('alignment.references', { ids: ids.join(', ') });
237    return isDraft(draft);
238  }
239
240  setBuffer(field: NumericField, value: string): void {
241    this.activeNumeric = field;
242    this.buffers[field] = value;
243    delete this.fieldErrors[field];
244    delete this.fieldErrorMessages[field];
245  }
246
247  cancelNumeric(field?: NumericField): void {
248    for (const key of field ? [field] : NUMERIC_FIELDS) {
249      this.buffers[key] = String(this.draft.host[key]);
250      delete this.fieldErrors[key];
251      delete this.fieldErrorMessages[key];
252    }
253    if (!field || this.activeNumeric === field) this.activeNumeric = null;
254  }
255
256  acceptNumeric(field?: NumericField): boolean {
257    const values: Partial<Record<NumericField, number | 'event'>> = {};
258    const fields = field ? [field] : NUMERIC_FIELDS;
259    for (const key of fields) {
260      delete this.fieldErrors[key];
261      delete this.fieldErrorMessages[key];
262      const parsed = numericValue(this.description, key, this.buffers[key]);
263      if (parsed.error !== undefined) { this.fieldErrors[key] = parsed.error; this.fieldErrorMessages[key] = numericDiagnostic(this.description, key); }
264      else values[key] = parsed.value;
265    }
266    if (fields.some((key) => this.fieldErrors[key])) return false;
267    if (values.padding !== undefined)
268      this.draft.host.padding = values.padding as number;
269    if (values.refresh_interval !== undefined)
270      this.draft.host.refresh_interval = values.refresh_interval;
271    this.cancelNumeric(field);
272    return true;
273  }
274
275  committed(current: ReadResult): void {
276    this.baseline = { ...current, draft: copyDraft(current.draft) };
277    this.draft = copyDraft(current.draft);
278    this.cancelNumeric();
279  }
280
281}
282
lib/editor/import-review.ts 103 lines
1// Generated by tools/generation/resources.ts; do not edit.
2import type { Draft, ImportReviewResult, Scope } from '../generated-contracts.ts';
3import { IMPORT_FIELDS, selectImport, type ImportField } from './import-selection.ts';
4import { differences } from './import-differences.ts';
5import type { Language } from '../i18n/index.ts';
6import { renderMessage, t } from '../i18n/index.ts';
7import { wrapText } from '../../ui/text.ts';
8
9export const REVIEW_SECTIONS = ['main','subagent','formatting','layout','language','host'] as const;
10export interface ReviewState {
11  result: ImportReviewResult;
12  selected: string;
13  expanded: string[];
14  scroll: number;
15  previewScope: Scope;
16  base?: Draft;
17  incoming?: ImportReviewResult;
18  choosing?: boolean;
19  selection?: ImportField[];
20  cursor?: number;
21}
22export interface ReviewRow { text: string; section: string; heading: boolean }
23export function sections(review: ReviewState): string[] {
24  return REVIEW_SECTIONS.filter(section => review.result.changes.some(change => change.section === section));
25}
26export function createReview(result: ImportReviewResult, base?: Draft): ReviewState {
27  const review: ReviewState = {result, selected:'', expanded:[], scroll:0, previewScope:'main'};
28  if (base) Object.assign(review, { base: JSON.parse(JSON.stringify(base)), incoming: result, selection: [], cursor: 0 });
29  review.selected = sections(review)[0] ?? '';
30  return review;
31}
32export function reviewRows(review: ReviewState, language: Language, width: number): ReviewRow[] {
33  if (review.choosing) return IMPORT_FIELDS.map((key, index) => ({ heading: true, section: key,
34    text: `${review.cursor === index ? '› ' : '  '}[${review.selection?.includes(key) ? 'x' : ' '}] ${selectionLabel(key, language)}` }));
35  const rows: ReviewRow[] = [];
36  for (const section of sections(review)) {
37    const changes = review.result.changes.filter(change => change.section === section);
38    rows.push({section, heading:true, text:`${review.selected === section ? '› ' : '  '}${review.expanded.includes(section) ? '[-]' : '[+]'} ${t('review.sections.' + section, language)} (${changes.length})`});
39    if (review.expanded.includes(section)) for (const change of changes) {
40      const paragraphs = [renderMessage(change.label, language),
41        t('review.before', language, {value:JSON.stringify(change.before)}),
42        t('review.after', language, {value:JSON.stringify(change.after)})];
43      rows.push(...wrapText(paragraphs, width).map(text => ({text, section, heading:false})));
44    }
45  }
46  return rows.length ? rows : [{text:t('review.empty', language),section:'',heading:false}];
47}
48export function navigateReview(review: ReviewState, key: string, language: Language, width: number, capacity: number): void {
49  if (review.base && review.incoming && key.toLowerCase() === 's') {
50    review.choosing = true; review.scroll = 0; review.cursor = 0; review.selected = IMPORT_FIELDS[0];
51    updateSelection(review); return;
52  }
53  if (review.base && review.incoming && key.toLowerCase() === 'f') {
54    review.choosing = false; review.result = review.incoming; review.selected = sections(review)[0] ?? ''; review.scroll = 0; return;
55  }
56  if (review.choosing) {
57    let cursor = review.cursor ?? 0;
58    if (key === 'up') cursor--;
59    if (key === 'down') cursor++;
60    if (key === 'home') cursor = 0;
61    if (key === 'end') cursor = IMPORT_FIELDS.length - 1;
62    if (key === 'pageup') cursor -= capacity;
63    if (key === 'pagedown') cursor += capacity;
64    review.cursor = Math.max(0, Math.min(IMPORT_FIELDS.length - 1, cursor));
65    review.selected = IMPORT_FIELDS[review.cursor]!;
66    if (key === 'space' || key === ' ') {
67      const field = IMPORT_FIELDS[review.cursor]!, values = review.selection ?? [];
68      review.selection = values.includes(field) ? values.filter(v => v !== field) : [...values, field]; updateSelection(review);
69    }
70    if (key === 'return' || key === 'enter') { review.choosing = false; review.selected = sections(review)[0] ?? ''; review.scroll = 0; }
71    else review.scroll = Math.max(0, Math.min(review.scroll, review.cursor));
72    if (review.choosing && review.cursor >= review.scroll + capacity) review.scroll = review.cursor - capacity + 1;
73    return;
74  }
75  const groups = sections(review);
76  let follow = false;
77  if (key === 'up' || key === 'down') {
78    review.selected = groups[Math.max(0, Math.min(groups.length - 1, groups.indexOf(review.selected) + (key === 'up' ? -1 : 1)))] ?? '';
79    follow = true;
80  } else if (key === 'return' && review.selected) {
81    review.expanded = review.expanded.includes(review.selected) ? review.expanded.filter(group => group !== review.selected) : [...review.expanded, review.selected];
82    follow = true;
83  } else if (key === 'tab') review.previewScope = review.previewScope === 'main' ? 'subagent' : 'main';
84  else if (key === 'pageup') review.scroll -= capacity;
85  else if (key === 'pagedown') review.scroll += capacity;
86  else if (key === 'home') review.scroll = 0;
87  else if (key === 'end') review.scroll = Number.MAX_SAFE_INTEGER;
88  const rows = reviewRows(review, language, width);
89  if (follow) review.scroll = Math.max(0, rows.findIndex(row => row.heading && row.section === review.selected));
90  review.scroll = Math.max(0, Math.min(Math.max(0, rows.length - capacity), review.scroll));
91}
92
93function updateSelection(review: ReviewState): void {
94  const draft = selectImport(review.base!, review.incoming!.draft, review.selection ?? []);
95  review.result = { draft, changes: differences(review.base!, draft) };
96}
97function selectionLabel(key: ImportField, language: Language): string {
98  if (key === 'main' || key === 'subagent') return t('review.selection.' + key, language);
99  if (key === 'formatting.thresholds') return t('review.selection.thresholds', language);
100  const message = ['use_colors','palette','directory_style','separator_style','scope_labels'].includes(key) ? 'review.fields.' + key : 'fields.global.' + key + '.label';
101  return t(message, language);
102}
103
lib/preferences.ts 62 lines
1import type { ConfigRow, ConfigValue } from 'claude-code';
2import type { LocalizedText } from './i18n/index.ts';
3
4/** Actual config-menu row IDs differ from persisted settings keys. */
5export const PREFERENCE_SPECS = [
6  { id: 'theme', keys: ['theme'], label: 'Theme', group: 'Claude appearance', entry: '/config theme' },
7  { id: 'verbose', keys: ['verbose'], label: 'Verbose output', group: 'Claude appearance', entry: '/config verbose' },
8  { id: 'showTurnDuration', keys: ['turnDuration', 'showTurnDuration'], label: 'Show turn duration', group: 'Claude appearance', entry: '/config' },
9  { id: 'prefersReducedMotion', keys: ['reduceMotion', 'prefersReducedMotion'], label: 'Reduce motion', group: 'Claude appearance', entry: '/config' },
10  { id: 'spinnerTipsEnabled', keys: ['tips', 'spinnerTipsEnabled'], label: 'Spinner tips', group: 'Claude appearance', entry: '/config' },
11  { id: 'terminalProgressBarEnabled', keys: ['progressBar', 'terminalProgressBarEnabled'], label: 'Terminal progress bar', group: 'Claude appearance', entry: '/config' },
12  { id: 'preferredNotifChannel', keys: ['notifChannel', 'preferredNotifChannel'], label: 'Notification channel', group: 'Claude appearance', entry: '/config' },
13  { id: 'timeFormat', keys: ['timeFormat'], label: 'Time format', group: 'Claude time / title', entry: '/config timeFormat (24-hour-utc selects UTC)' },
14  { id: 'timeZone', keys: ['timeZone'], label: 'Time zone', group: 'Claude time / title', entry: '/config timeFormat or official settings reference' },
15  { id: 'title', keys: ['terminalTitle', 'terminalTitleEnabled'], label: 'Terminal title', group: 'Claude time / title', entry: 'Official settings reference: terminal title preferences' },
16  { id: 'model', keys: ['model'], label: 'Model behavior', group: 'Claude behavior', entry: '/model' },
17  { id: 'effort', keys: ['effort', 'effortLevel'], label: 'Reasoning effort', group: 'Claude behavior', entry: '/effort' },
18  { id: 'thinking', keys: ['thinking'], label: 'Thinking behavior', group: 'Claude behavior', entry: '/config' },
19  { id: 'fast', keys: ['fast', 'fastMode'], label: 'Fast mode behavior', group: 'Claude behavior', entry: '/fast' },
20] as const;
21
22export interface Preference {
23  row: ConfigRow;
24  baseline: ConfigValue;
25  value: ConfigValue;
26  result: string;
27  localizedResult?: LocalizedText;
28}
29
30export function specFor(preference: Preference) {
31  return PREFERENCE_SPECS.find((spec) => (spec.keys as readonly string[]).includes(preference.row.key));
32}
33
34export function preferences(rows: readonly ConfigRow[]): Preference[] {
35  return PREFERENCE_SPECS.flatMap((spec) => {
36    const row = rows.find((row) => (spec.keys as readonly string[]).includes(row.key));
37    return row ? [{ row: { ...row }, baseline: row.value, value: row.value, result: '' }] : [];
38  });
39}
40
41export function canEdit(preference: Preference): boolean {
42  const row = preference.row;
43  return !row.isLocked && (
44    (row.kind === 'choice' && typeof row.value === 'string' && !!row.options?.length && row.options.every((s) => typeof s === 'string')) ||
45    (row.kind === 'boolean' && typeof row.value === 'boolean') ||
46    (row.kind === 'text' && typeof row.value === 'string') ||
47    (row.kind === 'number' && typeof row.value === 'number' && Number.isFinite(row.value)));
48}
49
50export function validPreferenceValue(preference: Preference): boolean {
51  const row = preference.row, value = preference.value;
52  return canEdit(preference) && (
53    row.kind === 'boolean' ? typeof value === 'boolean' :
54    row.kind === 'choice' ? typeof value === 'string' && !!row.options?.includes(value) :
55    row.kind === 'number' ? typeof value === 'number' && Number.isFinite(value) :
56    typeof value === 'string' && value.length <= 256 && !/[\x00-\x1f\x7f]/.test(value));
57}
58
59export function preferenceChanged(preference: Preference): boolean {
60  return JSON.stringify(preference.value) !== JSON.stringify(preference.baseline);
61}
62
lib/generated-contracts.ts 972 lines
1// Generated by tools/generation/resources.ts; do not edit.
2export const PROTOCOL_VERSION = 24 as const;
3export const ITEM_DEFAULTS = {"label": null, "icon": null, "priority": 50, "max_width": null, "formatting": {}, "foreground": null, "background": null, "visibility": "always", "visibility_threshold": 70};
4export const VISIBILITY_ITEMS = {"main": {"git": "git-dirty", "git-changes": "git-dirty", "active-agents": "nonzero", "task-progress": "nonzero", "context-used": "used-at-least", "context-remaining": "used-at-least", "five-hour-limit": "used-at-least", "weekly-limit": "used-at-least", "spend-limit": "used-at-least"}, "subagent": {"context-used": "used-at-least", "context-remaining": "used-at-least"}} as const;
5export const GUIDANCE_KEYS = {"source_kinds": ["configuration", "official_input", "local_git", "local_system", "transcript", "local_state", "lifecycle", "native_timing", "live_metrics", "telemetry"], "scopes": ["main", "main_context", "session", "all_sessions", "task", "subagent", "subagent_context", "repository", "local", "latest_request"], "requirements": ["observed_field", "subagent_rows", "agent_context", "configured_effort", "agent_effort_optional", "git_repository", "git_upstream", "git_base", "pull_request", "worktree_session", "usage_records", "task_observation", "native_timing", "complete_waits", "live_metrics", "owned_agents", "checklist_events", "tool_events", "complete_stream", "request_coverage", "existing_telemetry", "gateway", "gateway_284", "valid_window", "warm_cache", "fast_mode", "thinking", "agent_mode", "vim_mode", "context_observation", "cost_rate"]} as const;
6export const POWERLINE_FIELDS = [
7  {
8    "key": "powerline.padding",
9    "label": "Block padding",
10    "group": "Appearance",
11    "kind": "choice",
12    "choices": [
13      "none",
14      "left",
15      "right",
16      "both"
17    ],
18    "minimum": 0,
19    "maximum": 10000,
20    "nullable": false
21  },
22  {
23    "key": "powerline.separator",
24    "label": "Block separator",
25    "group": "Appearance",
26    "kind": "choice",
27    "choices": [
28      "arrow",
29      "slash",
30      "bar",
31      "none"
32    ],
33    "minimum": 0,
34    "maximum": 10000,
35    "nullable": false
36  },
37  {
38    "key": "powerline.start_cap",
39    "label": "Start decoration",
40    "group": "Appearance",
41    "kind": "boolean",
42    "choices": [],
43    "minimum": 0,
44    "maximum": 10000,
45    "nullable": false
46  },
47  {
48    "key": "powerline.end_cap",
49    "label": "End decoration",
50    "group": "Appearance",
51    "kind": "boolean",
52    "choices": [],
53    "minimum": 0,
54    "maximum": 10000,
55    "nullable": false
56  },
57  {
58    "key": "powerline.color_mode",
59    "label": "Block colors across lines",
60    "group": "Appearance",
61    "kind": "choice",
62    "choices": [
63      "semantic",
64      "continuous",
65      "restart"
66    ],
67    "minimum": 0,
68    "maximum": 10000,
69    "nullable": false
70  }
71] as const;
72export const EDITOR_FIELDS = {
73  "global": [
74    {
75      "key": "theme",
76      "label": "Statusline theme",
77      "group": "Appearance",
78      "kind": "choice",
79      "choices": [
80        "classic",
81        "dark",
82        "light",
83        "terminal"
84      ],
85      "minimum": 0,
86      "maximum": 10000,
87      "nullable": false
88    },
89    {
90      "key": "powerline_glyph",
91      "label": "Powerline separator",
92      "group": "Appearance",
93      "kind": "choice",
94      "choices": [
95        "ascii",
96        "powerline"
97      ],
98      "minimum": 0,
99      "maximum": 10000,
100      "nullable": false
101    },
102    ...POWERLINE_FIELDS,
103    {
104      "key": "statusline_language",
105      "label": "Statusline language (save with display settings)",
106      "group": "Appearance",
107      "kind": "choice",
108      "choices": ["en", "zh-CN", "zh-TW", "zh-HK", "ja", "ko"],
109      "minimum": 0,
110      "maximum": 10000,
111      "nullable": false
112    },
113    {
114      "key": "metrics.branch_diff_base_ref",
115      "label": "Branch diff base (inherit = auto)",
116      "group": "Git metrics",
117      "kind": "text",
118      "choices": [],
119      "minimum": 0,
120      "maximum": 10000,
121      "nullable": true
122    },
123    {
124      "key": "formatting.model_name",
125      "label": "Model Name",
126      "group": "Formatting",
127      "kind": "choice",
128      "choices": [
129        "original",
130        "short"
131      ],
132      "minimum": 0,
133      "maximum": 10000,
134      "nullable": false
135    },
136    {
137      "key": "formatting.number_format",
138      "label": "Number Format",
139      "group": "Formatting",
140      "kind": "choice",
141      "choices": [
142        "legacy",
143        "compact",
144        "full",
145        "grouped"
146      ],
147      "minimum": 0,
148      "maximum": 10000,
149      "nullable": false
150    },
151    {
152      "key": "formatting.labels",
153      "label": "Labels",
154      "group": "Formatting",
155      "kind": "choice",
156      "choices": [
157        "legacy",
158        "short",
159        "off"
160      ],
161      "minimum": 0,
162      "maximum": 10000,
163      "nullable": false
164    },
165    {
166      "key": "formatting.icons",
167      "label": "Icons",
168      "group": "Formatting",
169      "kind": "choice",
170      "choices": [
171        "legacy",
172        "unicode",
173        "ascii",
174        "off"
175      ],
176      "minimum": 0,
177      "maximum": 10000,
178      "nullable": false
179    },
180    {
181      "key": "formatting.allowance",
182      "label": "Allowance",
183      "group": "Formatting",
184      "kind": "choice",
185      "choices": [
186        "remaining",
187        "used"
188      ],
189      "minimum": 0,
190      "maximum": 10000,
191      "nullable": false
192    },
193    {
194      "key": "formatting.reset_format",
195      "label": "Reset Format",
196      "group": "Formatting",
197      "kind": "choice",
198      "choices": [
199        "countdown",
200        "time",
201        "datetime"
202      ],
203      "minimum": 0,
204      "maximum": 10000,
205      "nullable": false
206    },
207    {
208      "key": "formatting.reset_timezone",
209      "label": "Reset Timezone",
210      "group": "Formatting",
211      "kind": "choice",
212      "choices": [
213        "local",
214        "UTC"
215      ],
216      "minimum": 0,
217      "maximum": 10000,
218      "nullable": false
219    },
220    {
221      "key": "formatting.thresholds.enabled",
222      "label": "Threshold colors",
223      "group": "Risk colors",
224      "kind": "boolean",
225      "choices": [],
226      "minimum": 0,
227      "maximum": 10000,
228      "nullable": false
229    },
230    {
231      "key": "formatting.thresholds.warning",
232      "label": "Warning (%)",
233      "group": "Risk colors",
234      "kind": "integer",
235      "choices": [],
236      "minimum": 0,
237      "maximum": 100,
238      "nullable": false
239    },
240    {
241      "key": "formatting.thresholds.critical",
242      "label": "Critical (%)",
243      "group": "Risk colors",
244      "kind": "integer",
245      "choices": [],
246      "minimum": 0,
247      "maximum": 100,
248      "nullable": false
249    },
250    {
251      "key": "subagents.visibility",
252      "label": "Visible agents",
253      "group": "Subagent visibility",
254      "kind": "choice",
255      "choices": [
256        "all",
257        "running"
258      ],
259      "minimum": 0,
260      "maximum": 10000,
261      "nullable": false
262    },
263    {
264      "key": "subagents.hide_completed",
265      "label": "Hide completed",
266      "group": "Subagent visibility",
267      "kind": "boolean",
268      "choices": [],
269      "minimum": 0,
270      "maximum": 10000,
271      "nullable": false
272    },
273    {
274      "key": "subagents.row_limit",
275      "label": "Agent row limit",
276      "group": "Subagent visibility",
277      "kind": "integer",
278      "choices": [],
279      "minimum": 0,
280      "maximum": 10000,
281      "nullable": true
282    },
283    {
284      "key": "subagents.task_max_width",
285      "label": "Task text width",
286      "group": "Subagent visibility",
287      "kind": "integer",
288      "choices": [],
289      "minimum": 2,
290      "maximum": 10000,
291      "nullable": true
292    }
293  ],
294  "item": [
295    {
296      "key": "foreground",
297      "label": "Foreground (inherit/default/ansi:N/#RRGGBB)",
298      "group": "Item colors",
299      "kind": "text",
300      "choices": [],
301      "minimum": 0,
302      "maximum": 10000,
303      "nullable": true
304    },
305    {
306      "key": "background",
307      "label": "Background (inherit/default/ansi:N/#RRGGBB)",
308      "group": "Item colors",
309      "kind": "text",
310      "choices": [],
311      "minimum": 0,
312      "maximum": 10000,
313      "nullable": true
314    },
315    {
316      "key": "visibility",
317      "label": "Visibility rule",
318      "group": "Conditional visibility",
319      "kind": "choice",
320      "choices": [
321        "always",
322        "git-dirty",
323        "nonzero",
324        "used-at-least"
325      ],
326      "minimum": 0,
327      "maximum": 10000,
328      "nullable": false
329    },
330    {
331      "key": "visibility_threshold",
332      "label": "Minimum used (%)",
333      "group": "Conditional visibility",
334      "kind": "integer",
335      "choices": [],
336      "minimum": 0,
337      "maximum": 100,
338      "nullable": false
339    },
340    {
341      "key": "label",
342      "label": "Label (inherit = default)",
343      "group": "Item format",
344      "kind": "text",
345      "choices": [],
346      "minimum": 0,
347      "maximum": 10000,
348      "nullable": true
349    },
350    {
351      "key": "icon",
352      "label": "Icon (inherit = default)",
353      "group": "Item format",
354      "kind": "text",
355      "choices": [],
356      "minimum": 0,
357      "maximum": 10000,
358      "nullable": true
359    },
360    {
361      "key": "priority",
362      "label": "Priority",
363      "group": "Item fitting",
364      "kind": "integer",
365      "choices": [],
366      "minimum": 0,
367      "maximum": 100,
368      "nullable": false
369    },
370    {
371      "key": "max_width",
372      "label": "Maximum width",
373      "group": "Item fitting",
374      "kind": "integer",
375      "choices": [],
376      "minimum": 2,
377      "maximum": 10000,
378      "nullable": true
379    },
380    {
381      "key": "model_name",
382      "label": "Model Name",
383      "group": "Item format",
384      "kind": "choice",
385      "choices": [
386        "inherit",
387        "original",
388        "short"
389      ],
390      "minimum": 0,
391      "maximum": 10000,
392      "nullable": false
393    },
394    {
395      "key": "number_format",
396      "label": "Number Format",
397      "group": "Item format",
398      "kind": "choice",
399      "choices": [
400        "inherit",
401        "legacy",
402        "compact",
403        "full",
404        "grouped"
405      ],
406      "minimum": 0,
407      "maximum": 10000,
408      "nullable": false
409    },
410    {
411      "key": "labels",
412      "label": "Labels",
413      "group": "Item format",
414      "kind": "choice",
415      "choices": [
416        "inherit",
417        "legacy",
418        "short",
419        "off"
420      ],
421      "minimum": 0,
422      "maximum": 10000,
423      "nullable": false
424    },
425    {
426      "key": "icons",
427      "label": "Icons",
428      "group": "Item format",
429      "kind": "choice",
430      "choices": [
431        "inherit",
432        "legacy",
433        "unicode",
434        "ascii",
435        "off"
436      ],
437      "minimum": 0,
438      "maximum": 10000,
439      "nullable": false
440    },
441    {
442      "key": "allowance",
443      "label": "Allowance",
444      "group": "Item format",
445      "kind": "choice",
446      "choices": [
447        "inherit",
448        "remaining",
449        "used"
450      ],
451      "minimum": 0,
452      "maximum": 10000,
453      "nullable": false
454    },
455    {
456      "key": "reset_format",
457      "label": "Reset Format",
458      "group": "Item format",
459      "kind": "choice",
460      "choices": [
461        "inherit",
462        "countdown",
463        "time",
464        "datetime"
465      ],
466      "minimum": 0,
467      "maximum": 10000,
468      "nullable": false
469    },
470    {
471      "key": "reset_timezone",
472      "label": "Reset Timezone",
473      "group": "Item format",
474      "kind": "choice",
475      "choices": [
476        "inherit",
477        "local",
478        "UTC"
479      ],
480      "minimum": 0,
481      "maximum": 10000,
482      "nullable": false
483    }
484  ]
485} as const;
486export const PRESETS = [{"id": "developer", "purpose_key": "quick.purpose.developer", "requirements_key": "quick.requirements.developer", "example": false, "label": "Developer", "rows": [["model-with-effort", "current-dir", "git"], ["context-remaining", "tokens", "task-timer", "session-cost"]], "layout_mode": "explicit"}, {"id": "minimal", "purpose_key": "quick.purpose.minimal", "requirements_key": "quick.requirements.minimal", "example": false, "label": "Minimal", "rows": [["model-with-effort", "current-dir", "context-remaining", "task-timer"]], "layout_mode": "auto"}, {"id": "monitoring", "purpose_key": "quick.purpose.monitoring", "requirements_key": "quick.requirements.monitoring", "example": false, "label": "Monitoring", "rows": [["context-used", "five-hour-limit", "weekly-limit", "spend-limit"], ["five-hour-reset", "weekly-reset", "cache-state", "cache-expires"], ["session-cost", "session-duration", "api-duration", "api-requests", "cache-misses"]], "layout_mode": "explicit"}, {"id": "multi-agent", "purpose_key": "quick.purpose.multi-agent", "requirements_key": "quick.requirements.multi-agent", "example": false, "label": "Multi Agent", "rows": [["model-with-effort", "current-dir", "git"], ["context-remaining", "tokens", "task-timer"]], "layout_mode": "explicit"}, {"id": "left-right", "purpose_key": "quick.purpose.left-right", "requirements_key": "quick.requirements.left-right", "example": true, "label": "Left Right", "rows": [["model-with-effort", "git", "spacer", "context-remaining"]], "layout_mode": "explicit"}, {"id": "repeated-metrics", "purpose_key": "quick.purpose.repeated-metrics", "requirements_key": "quick.requirements.repeated-metrics", "example": true, "label": "Repeated Metrics", "rows": [["input-tokens", "input-tokens"]], "layout_mode": "explicit"}, {"id": "daily-development", "purpose_key": "quick.purpose.daily-development", "requirements_key": "quick.requirements.daily-development", "example": false, "label": "Daily Development", "rows": [["model-with-effort", "current-dir", "git", "context-remaining", "task-timer"], ["session-cost"]], "layout_mode": "explicit"}, {"id": "agent-focus", "purpose_key": "quick.purpose.agent-focus", "requirements_key": "quick.requirements.agent-focus", "example": false, "label": "Agent Focus", "rows": [["task-timer", "context-remaining", "git"], ["run-state", "task-progress", "active-agents"]], "layout_mode": "explicit"}, {"id": "quota-watch", "purpose_key": "quick.purpose.quota-watch", "requirements_key": "quick.requirements.quota-watch", "example": false, "label": "Quota Watch", "rows": [["context-used", "five-hour-limit", "weekly-limit"], ["five-hour-reset", "weekly-reset"], ["session-cost", "spend-limit", "cache-state", "cache-expires"]], "layout_mode": "explicit"}] as const;
487export const FORMAT_CHOICES = {"model_name": ["original", "short"], "number_format": ["legacy", "compact", "full", "grouped"], "labels": ["legacy", "short", "off"], "icons": ["legacy", "unicode", "ascii", "off"], "allowance": ["remaining", "used"], "reset_format": ["countdown", "time", "datetime"], "reset_timezone": ["local", "UTC"]} as const;
488export const FORMAT_DEFAULTS = {"model_name": "original", "number_format": "legacy", "labels": "legacy", "icons": "legacy", "allowance": "remaining", "reset_format": "countdown", "reset_timezone": "local", "thresholds": {"enabled": false, "warning": 70, "critical": 90}} as const;
489export type MainItemId = "model-with-effort" | "model" | "effort" | "fast-mode" | "thinking" | "current-dir" | "project-name" | "hostname" | "git" | "git-branch" | "git-changes" | "git-ahead-behind" | "branch-diff" | "pr" | "repo" | "worktree" | "context-remaining" | "context-used" | "context-window-size" | "context-tokens" | "five-hour-limit" | "five-hour-reset" | "weekly-limit" | "weekly-reset" | "spend-limit" | "spend-amount" | "spend-period" | "tokens" | "input-tokens" | "output-tokens" | "prompt-cache" | "cache-state" | "cache-expires" | "cache-misses" | "cache-miss-reason" | "api-requests" | "task-timer" | "task-active-timer" | "version" | "session" | "session-name" | "session-id" | "session-id-short" | "output-style" | "cost" | "session-cost" | "session-cost-rate" | "session-duration" | "api-duration" | "lines-changed" | "agent" | "vim-mode" | "run-state" | "permission-mode" | "active-agents" | "task-progress" | "last-tool" | "ttft" | "output-rate" | "prompt-input-tokens" | "prompt-output-tokens" | "prompt-cost" | "text" | "spacer" | "external-value" | "github-pr" | "github-ci";
490export type SubagentItemId = "status-elapsed" | "status" | "name" | "model-with-effort" | "model" | "effort" | "context-remaining" | "context-used" | "context-tokens" | "context-window-size" | "elapsed" | "task" | "tokens" | "current-dir" | "text" | "spacer" | "external-value";
491export type Palette = "default" | "ansi";
492export type Theme = "classic" | "dark" | "light" | "terminal";
493export type PowerlineGlyph = "ascii" | "powerline";
494export type VisibilityRule = "always" | "git-dirty" | "nonzero" | "used-at-least";
495export type DirectoryStyle = "full" | "home" | "project-relative" | "basename";
496export type SeparatorStyle = "classic" | "compact" | "powerline";
497export type ScopeLabels = "off" | "when-subagents" | "always";
498export type StatuslineLanguage = "en" | "zh-CN" | "zh-TW" | "zh-HK" | "ja" | "ko";
499export type Scope = "main" | "subagent";
500export type UnavailableReason = "not_observed" | "unsupported_host" | "unknown_host_version" | "source_unavailable" | "condition_not_met" | "runtime_disabled" | "native_timing_disabled" | "wait_coverage_missing" | "stale" | "incomplete" | "ambiguous_owner" | "observed_only" | "missing_stream" | "synthetic_response" | "abnormal_clock" | "inconsistent_request" | "request_join_unavailable";
501export const MAIN_ITEM_IDS = ["model-with-effort", "model", "effort", "fast-mode", "thinking", "current-dir", "project-name", "hostname", "git", "git-branch", "git-changes", "git-ahead-behind", "branch-diff", "pr", "repo", "worktree", "context-remaining", "context-used", "context-window-size", "context-tokens", "five-hour-limit", "five-hour-reset", "weekly-limit", "weekly-reset", "spend-limit", "spend-amount", "spend-period", "tokens", "input-tokens", "output-tokens", "prompt-cache", "cache-state", "cache-expires", "cache-misses", "cache-miss-reason", "api-requests", "task-timer", "task-active-timer", "version", "session", "session-name", "session-id", "session-id-short", "output-style", "cost", "session-cost", "session-cost-rate", "session-duration", "api-duration", "lines-changed", "agent", "vim-mode", "run-state", "permission-mode", "active-agents", "task-progress", "last-tool", "ttft", "output-rate", "prompt-input-tokens", "prompt-output-tokens", "prompt-cost", "text", "spacer", "external-value", "github-pr", "github-ci"] as const;
502export const SUBAGENT_ITEM_IDS = ["status-elapsed", "status", "name", "model-with-effort", "model", "effort", "context-remaining", "context-used", "context-tokens", "context-window-size", "elapsed", "task", "tokens", "current-dir", "text", "spacer", "external-value"] as const;
503export const PALETTE_VALUES = ["default", "ansi"] as const;
504export const THEME_VALUES = ["classic", "dark", "light", "terminal"] as const;
505export const POWERLINEGLYPH_VALUES = ["ascii", "powerline"] as const;
506export const VISIBILITYRULE_VALUES = ["always", "git-dirty", "nonzero", "used-at-least"] as const;
507export const DIRECTORYSTYLE_VALUES = ["full", "home", "project-relative", "basename"] as const;
508export const SEPARATORSTYLE_VALUES = ["classic", "compact", "powerline"] as const;
509export const SCOPELABELS_VALUES = ["off", "when-subagents", "always"] as const;
510export const STATUSLINELANGUAGE_VALUES = ["en", "zh-CN", "zh-TW", "zh-HK", "ja", "ko"] as const;
511export const UNAVAILABLEREASON_VALUES = ["not_observed", "unsupported_host", "unknown_host_version", "source_unavailable", "condition_not_met", "runtime_disabled", "native_timing_disabled", "wait_coverage_missing", "stale", "incomplete", "ambiguous_owner", "observed_only", "missing_stream", "synthetic_response", "abnormal_clock", "inconsistent_request", "request_join_unavailable"] as const;
512export type Operation = "sources_read" | "sources_apply" | "source_review" | "source_context" | "source_refresh" | "source_status" | "source_cancel" | "source_diagnose" | "describe" | "read" | "preview" | "apply" | "import" | "export" | "preset" | "read_ui_preferences" | "set_ui_language" | "review_import" | "explain" | "diagnose" | "profiles_read" | "profiles_apply" | "profile_import" | "profile_export" | "task_details";
513export interface ItemGuidance {
514  source_kinds: string[];
515  measurement_scope: string;
516  requirements: string[];
517  setup: string[];
518}
519export interface CatalogItem {
520  scope: Scope;
521  id: string;
522  label: string;
523  description: string;
524  group: string;
525  sources: string[];
526  examples: string[];
527  default_position: number | null;
528  minimum_version: string | null;
529  format_options: string[];
530  excludes: string[];
531  unavailable_reasons: UnavailableReason[];
532  default_enabled: boolean;
533  minimum_version_status: "verified" | "unknown";
534  guidance: ItemGuidance;
535  capabilities?: ItemCapability;
536}
537export interface ItemCapability {
538  indicator?: boolean;
539  formats: string[];
540  visibility: string[];
541  link: boolean;
542  source: 'none' | 'external' | 'github';
543  preview: string;
544  explanation: string;
545}
546export interface ChoiceOptions {
547  choices: (string | boolean)[];
548}
549export interface RangeOptions {
550  minimum: number;
551  maximum: number;
552}
553export interface RefreshOptions {
554  minimum: number;
555  maximum: number;
556  special: "event";
557}
558export interface ConfigurationOptions {
559  colors: ChoiceOptions;
560  palette: ChoiceOptions;
561  theme: ChoiceOptions;
562  "powerline-glyph": ChoiceOptions;
563  "powerline-padding": ChoiceOptions;
564  "powerline-separator": ChoiceOptions;
565  "powerline-start-cap": ChoiceOptions;
566  "powerline-end-cap": ChoiceOptions;
567  "powerline-color-mode": ChoiceOptions;
568  "directory-style": ChoiceOptions;
569  "separator-style": ChoiceOptions;
570  "scope-labels": ChoiceOptions;
571  "statusline-language": ChoiceOptions;
572  "subagent-statusline": ChoiceOptions;
573  padding: RangeOptions;
574  "refresh-interval": RefreshOptions;
575  "hide-vim-mode-indicator": ChoiceOptions;
576}
577export const POWERLINE_OPTIONS = Object.fromEntries(POWERLINE_FIELDS.map(field => [
578  field.key.replaceAll('.', '-').replaceAll('_', '-'),
579  { choices: field.kind === 'boolean' ? [true, false] : [...field.choices] },
580])) as Pick<ConfigurationOptions, 'powerline-padding' | 'powerline-separator' | 'powerline-start-cap' | 'powerline-end-cap' | 'powerline-color-mode'>;
581export interface Capabilities {
582  host_version: string | null;
583  subagent_rows: "unknown" | "supported" | "unsupported";
584  native_mod: "unknown" | "unverified" | "unsupported";
585  native_mod_loaded: null;
586  data_observation: "not_observed";
587}
588export interface ThresholdDraft {
589  enabled: boolean;
590  warning: number;
591  critical: number;
592}
593export interface FormattingDraft {
594  model_name: "original" | "short";
595  number_format: "legacy" | "compact" | "full" | "grouped";
596  labels: "legacy" | "short" | "off";
597  icons: "legacy" | "unicode" | "ascii" | "off";
598  allowance: "remaining" | "used";
599  reset_format: "countdown" | "time" | "datetime";
600  reset_timezone: "local" | "UTC";
601  thresholds: ThresholdDraft;
602}
603export type GradientDraft = string[];
604export interface ItemOptionsDraft {
605  foreground_gradient?: GradientDraft | null;
606  background_gradient?: GradientDraft | null;
607  presentation?: "numeric" | "bar";
608  bar_width?: number;
609  cost_rate_basis?: 'session' | 'api';
610  bar_style?: "auto" | "unicode" | "ascii";
611  link?: 'off' | 'auto' | 'on';
612  label: string | null;
613  icon: string | null;
614  priority: number;
615  max_width: number | null;
616  formatting: Record<string, string>;
617  foreground: string | null;
618  background: string | null;
619  visibility: VisibilityRule;
620  visibility_threshold: number;
621}
622export interface InstanceDraft {
623  source?: SourceReference;
624  id: string;
625  type_id: string;
626  enabled: boolean;
627  options: ItemOptionsDraft;
628  text: string | null;
629}
630export interface GroupDraft {
631  id: string; member_ids: string[]; primary_id: string; link_visibility: boolean; shared_powerline: boolean;
632}
633export interface AlignmentRef { kind: 'instance' | 'group'; id: string }
634export interface AlignmentDraft { id: string; columns: AlignmentRef[][] }
635export interface LayoutDraft {
636  alignments?: AlignmentDraft[];
637  mode: "auto" | "explicit";
638  rows: string[][];
639}
640export interface SubagentDraft {
641  groups: GroupDraft[];
642  enabled: boolean;
643  instances: InstanceDraft[];
644  visibility: "all" | "running";
645  hide_completed: boolean;
646  row_limit: number | null;
647  task_max_width: number | null;
648}
649export interface MetricsDraft {
650  branch_diff_base_ref: string | null;
651}
652export interface PowerlineDraft {
653  padding: "none" | "left" | "right" | "both";
654  separator: "arrow" | "slash" | "bar" | "none";
655  start_cap: boolean;
656  end_cap: boolean;
657  color_mode: "semantic" | "continuous" | "restart";
658}
659export interface DisplayDraft {
660  groups: GroupDraft[];
661  schema_version: 15;
662  statusline_language: StatuslineLanguage;
663  instances: InstanceDraft[];
664  use_colors: boolean;
665  palette: Palette;
666  theme: Theme;
667  powerline_glyph: PowerlineGlyph;
668  powerline: PowerlineDraft;
669  directory_style: DirectoryStyle;
670  separator_style: SeparatorStyle;
671  scope_labels: ScopeLabels;
672  subagents: SubagentDraft;
673  formatting: FormattingDraft;
674  layout: LayoutDraft;
675  metrics: MetricsDraft;
676}
677export interface HostDraft {
678  padding: number;
679  refresh_interval: number | "event";
680  hide_vim_mode_indicator: boolean;
681}
682export interface Draft {
683  display: DisplayDraft;
684  host: HostDraft;
685}
686export interface Foreground {
687  kind: "rgb" | "ansi";
688  value: string | number;
689}
690export interface Span {
691  link?: string;
692  text: string;
693  bold: boolean;
694  foreground: Foreground | null;
695  background: Foreground | null;
696}
697
698/** Machine-local source authorization is never part of a portable display. */
699export interface SourceReference { binding: string | null; hint: string }
700export type SourceKind = 'json' | 'github' | 'command';
701export interface SourceScope { project: string | null; session: string | null; agent: string | null }
702export interface SourceContext extends SourceScope { branch: string | null; head: string | null }
703export interface SourceSettings {
704  path?: string;
705  pointer?: string;
706  observed_at_pointer?: string;
707  unit?: string;
708  executable?: string;
709  args?: string[];
710  cwd?: string;
711  input?: Record<string, string>;
712  output?: 'json' | 'text';
713  timeout_ms?: number;
714  host?: string;
715  repository?: string;
716  branch?: string;
717  account?: string;
718  pr?: number | null;
719}
720export interface SourceDefinition {
721  id: string; name: string; kind: SourceKind; scope: SourceScope;
722  ttl_seconds: number; settings: SourceSettings; enabled: boolean; revision: string;
723}
724export interface SourceBinding { id: string; source_id: string }
725export interface AutomaticPolicy { source_id: string; enabled: boolean; review_revision: string; interval_seconds: number; auth_revision: string }
726export interface AutomaticStatus { state: 'off' | 'waiting' | 'running' | 'backoff' | 'paused'; reason: string; next_at: string | null; last_attempt: string | null; last_success: string | null; interval_seconds: number }
727export interface SourceRegistry { version: 2; sources: SourceDefinition[]; bindings: SourceBinding[]; automatic: AutomaticPolicy[] }
728export interface SourcesResult extends SourceRegistry { revision: string }
729export type SourceState = 'valid' | 'missing' | 'partial' | 'error' | 'unsupported';
730export interface SourceObservation {
731  version: 1; source_id: string; source_revision: string; context: SourceContext;
732  observed_at: string | null; state: SourceState; reason: string;
733  value: string | number | boolean | null; unit: string | null;
734  fields?: Record<string, string | number | boolean | null>;
735  identity?: { host: string; repository: string; account: string; auth_revision: string };
736}
737export interface SourceView {
738  source_id: string | null; name: string; state: SourceState | 'disabled' | 'unbound' | 'mismatch';
739  reason: string; observed_at: string | null; freshness: 'current' | 'stale' | 'unknown';
740  value: string | number | boolean | null; unit: string | null;
741  fields?: Record<string, string | number | boolean | null>;
742}
743export interface SourceJob {
744  version: 2; id: string; source_id: string; source_revision: string; owner: string; trigger: 'manual' | 'automatic'; identity: string;
745  context: SourceContext; started_at: string; deadline_at: string;
746  state: 'running' | 'completed' | 'failed' | 'cancelled'; reason: string;
747}
748export interface SourceReview { source: SourceDefinition; review_revision: string }
749export interface SourceMutationResult extends SourcesResult { binding?: SourceReference; backup_dir: string | null }
750export interface PreviewResult {
751  sample: true;
752  main: Span[][];
753  subagents: Span[][];
754}
755export const SAMPLE_REASONS = ['sample_group_hidden','sample_visible','sample_empty','sample_condition_hidden','sample_truncated','sample_priority_omitted','sample_width_omitted','sample_row_hidden','sample_spacer'] as const;
756export type SampleReason = typeof SAMPLE_REASONS[number];
757export const EXPLAIN_REASONS = ['alignment_active','alignment_collapsed','cost_rate_session','cost_rate_api','indicator_bar','source_bound','source_unbound','configured_on','configured_off','scope_disabled','installation_owned','installation_absent','installation_foreign','installation_unknown','unknown_host_version','host_supported','unsupported_host','host_requirement_unknown','collector_unknown','native_timing_on','native_timing_off','live_metrics_on','live_metrics_off','actual_not_observed'] as const;
758export interface ExplainReason { code: string; origin: 'configuration' | 'local_configuration' | 'host_capability' | 'unknown'; }
759export interface InstanceSample { row_id: string; outcome: SampleReason; truncated: boolean; }
760export interface ExplainInstance {
761  id: string; type_id: string; enabled: boolean;
762  reasons: ExplainReason[];
763  samples: InstanceSample[];
764}
765export interface ExplainResult {
766  sample: true;
767  scope: Scope;
768  width: number;
769  actual_availability: 'not_observed';
770  preview: PreviewResult;
771  instances: ExplainInstance[];
772}
773export const LAYOUT_REASONS = ['group_hidden','visible','empty','condition_hidden','priority_omitted','width_omitted','row_hidden','spacer'] as const;
774export type LayoutReason = typeof LAYOUT_REASONS[number];
775export interface InstanceLayout { row_id: string; outcome: LayoutReason; truncated: boolean; }
776export const EVIDENCE_STATUSES = ['observed','not_observed','invalid_field','source_unavailable','association_unavailable','session_mismatch','prompt_mismatch','stale','partial','collector_off','input_only','newer_than_input','unsupported_host','no_misses','unidentified'] as const;
777export type EvidenceStatus = typeof EVIDENCE_STATUSES[number];
778export interface DiagnosticEvidence {
779  source: string;
780  scope: string;
781  status: EvidenceStatus;
782  observed_at: string | null;
783  freshness: 'current' | 'stale' | 'unknown' | 'newer_than_input';
784  fields: { path: string; status: 'observed' | 'not_observed' | 'invalid_field' }[];
785}
786export interface DiagnoseInstance {
787  id: string; type_id: string; enabled: boolean;
788  reasons: ExplainReason[];
789  evidence: DiagnosticEvidence[];
790  rows: InstanceLayout[];
791}
792export interface DiagnoseResult {
793  sample: false;
794  scope: Scope;
795  width: number;
796  source: string;
797  observed_at: string | null;
798  diagnosed_at: string;
799  session_id: string | null;
800  prompt_id: string | null;
801  host_version: string | null;
802  include_local: boolean;
803  configuration?: ResolvedConfiguration;
804  output: { id: string; spans: Span[] }[];
805  instances: DiagnoseInstance[];
806  host_fields: {
807    worktree: { session_name: string | null; git_name: string | null; selected_source: string | null };
808    cache_miss: { status: string; causes: string[]; last_miss_at: number | null; tools_added: number | null; tools_removed: number | null; system_char_delta: number | null };
809  };
810}
811export interface LocalizedMessage {
812  key: string;
813  params: Record<string, unknown>;
814  fallback: string;
815}
816export interface UiPreferencesResult {
817  schema_version: 1;
818  ui_language: StatuslineLanguage;
819  warning: LocalizedMessage | null;
820}
821export interface ProtocolError {
822  code: string;
823  message: string;
824  localization: LocalizedMessage | null;
825}
826export interface ReadResult {
827  draft: Draft;
828  revision: string;
829  installed: boolean;
830  installation: Record<string, unknown>;
831  capabilities: Capabilities;
832  backend_version: string;
833  configuration?: ResolvedConfiguration;
834}
835export type ConfigTarget = { kind: "user" } | { kind: "profile"; id: string } | { kind: "project"; path: string };
836export interface DisplayProfile { id: string; name: string; display: DisplayDraft }
837export interface ProjectBinding { root: string; profile_id: string }
838export interface ProfileCollection { version: 1; profiles: DisplayProfile[]; bindings: ProjectBinding[] }
839export interface ResolvedConfiguration {
840  target: ConfigTarget;
841  profile_id: string | null;
842  profile_name: string | null;
843  project_root: string | null;
844  reason: string;
845  shared_projects: string[];
846}
847export interface ProfilesResult extends ProfileCollection { revision: string; changed?: boolean; backup_dir?: string | null }
848export interface ProfileImportResult { name: string; display: DisplayDraft }
849export interface TaskEvidence {
850  source: string;
851  scope: string;
852  status: string;
853  observed_at: string | null;
854  freshness: "current" | "stale" | "unknown" | "newer_than_input";
855}
856export interface TaskAgentDetail {
857  id: string;
858  parent_id: string | null;
859  name: string | null;
860  status: string | null;
861  evidence: TaskEvidence[];
862}
863export interface TaskDetails {
864  version: 1;
865  session_id: string;
866  prompt_id: string | null;
867  captured_at: string;
868  status: string | null;
869  phase: string | null;
870  elapsed_seconds: number | null;
871  active_seconds: number | null;
872  progress: { completed: number; total: number } | null;
873  agents: TaskAgentDetail[];
874  evidence: TaskEvidence[];
875  limitations: string[];
876}
877export interface EditorField {
878  key: string;
879  label: string;
880  group: string;
881  kind: "choice" | "boolean" | "integer" | "text";
882  choices: string[];
883  minimum: number;
884  maximum: number;
885  nullable: boolean;
886}
887export interface PresetDescription {
888  purpose_key: string;
889  requirements_key: string;
890  example: boolean;
891  id: string;
892  label: string;
893  rows: string[][];
894  layout_mode: "auto" | "explicit";
895}
896export interface TransferResult {
897  draft: Draft;
898}
899export interface ImportChange {
900  section: "main" | "subagent" | "formatting" | "layout" | "language" | "host";
901  kind: "add" | "remove" | "enable" | "disable" | "reorder" | "change";
902  scope: Scope | null;
903  item_id: string | null;
904  path: string[];
905  before: unknown;
906  after: unknown;
907  label: LocalizedMessage;
908}
909export interface ImportReviewResult {
910  draft: Draft;
911  changes: ImportChange[];
912}
913export interface ExportResult {
914  path: string;
915}
916export interface DescribeResult {
917  catalog: CatalogItem[];
918  options: ConfigurationOptions;
919  capabilities: Capabilities;
920  backend_version: string;
921  operations: string[];
922  formatting_options: Record<string, string[]>;
923  presets: PresetDescription[];
924  editor_fields: Record<string, EditorField[]>;
925}
926export interface ApplyResult {
927  draft: Draft;
928  revision: string;
929  installed: boolean;
930  installation: Record<string, unknown>;
931  capabilities: Capabilities;
932  backend_version: string;
933  changed: boolean;
934  backup_dir: string | null;
935  configuration?: ResolvedConfiguration;
936}
937export interface ResultMap {
938  sources_read: SourcesResult;
939  sources_apply: SourceMutationResult;
940  source_review: SourceReview;
941  source_context: SourceContext;
942  source_refresh: SourceJob;
943  source_status: SourceJob;
944  source_cancel: SourceJob;
945  source_diagnose: { source: SourceDefinition; view: SourceView; jobs: SourceJob[]; automatic: AutomaticStatus };
946  describe: DescribeResult;
947  read: ReadResult;
948  preview: PreviewResult;
949  explain: ExplainResult;
950  diagnose: DiagnoseResult;
951  apply: ApplyResult;
952  import: TransferResult;
953  review_import: ImportReviewResult;
954  export: ExportResult;
955  preset: TransferResult;
956  read_ui_preferences: UiPreferencesResult;
957  set_ui_language: UiPreferencesResult;
958  profiles_read: ProfilesResult;
959  profiles_apply: ProfilesResult;
960  profile_import: ProfileImportResult;
961  profile_export: ExportResult;
962  task_details: TaskDetails;
963}
964export type ResultFor<O extends Operation> = ResultMap[O];
965export interface Request {
966  protocol_version: typeof PROTOCOL_VERSION;
967  operation: Operation;
968  payload: unknown;
969}
970export type Result = DiagnoseResult | ExplainResult | PreviewResult | UiPreferencesResult | ReadResult | TransferResult | ImportReviewResult | ExportResult | DescribeResult | ApplyResult | ProfilesResult | ProfileImportResult | TaskDetails;
971export type Response = { protocol_version: typeof PROTOCOL_VERSION; result: Result } | { protocol_version: typeof PROTOCOL_VERSION; error: ProtocolError };
972
ui/layout.ts 50 lines
1export const MIN_COLUMNS = 32;
2export const MIN_ROWS = 12;
3
4/** Columns available inside the same frame used by editor drawing. */
5export function contentColumns(columns: number, rows: number): number {
6  return Math.max(1, columns - (columns >= 64 && rows >= 20 ? 2 : 0));
7}
8
9/** Budget a paged body between the header, preview and action rows. */
10export function dimensions(columns: number, rows: number, footerRows = 2) {
11  const framed = columns >= 64 && rows >= 20;
12  const previewRows = Math.min(3, Math.max(1, Math.floor((rows - 8 - footerRows) / 4)));
13  const previewHeight = previewRows + (framed ? 2 : 1);
14  const bodyHeight = Math.max(1, rows - 3 - footerRows - previewHeight);
15  const bodyRows = Math.max(1, bodyHeight - (framed ? 2 : 1));
16  const tableHeading = columns >= 64 && bodyRows >= 4;
17  const showSummary = bodyRows >= (tableHeading ? 4 : 3);
18  const showDetails = bodyRows >= (tableHeading ? 5 : 4);
19  return {
20    columns,
21    rows,
22    framed,
23    previewRows,
24    previewHeight,
25    bodyHeight,
26    bodyRows,
27    tableHeading,
28    showSummary,
29    showDetails,
30    footerRows,
31    itemCapacity: Math.max(1, bodyRows - 1 - Number(tableHeading) - Number(showSummary) - Number(showDetails)),
32    formHeight: Math.max(1, bodyRows - Number(tableHeading) - Number(showSummary)),
33    available: columns >= MIN_COLUMNS && rows >= MIN_ROWS,
34  };
35}
36
37export { cellWidth, displayWidth } from '../lib/unicode.ts';
38import { displayWidth, clip as clipGraphemes } from '../lib/unicode.ts';
39
40/** Clip at complete graphemes after replacing single-line control input. */
41export function clip(text: string, width: number): string {
42  return clipGraphemes(text.replace(/[\x00-\x1f\x7f]/g, ' '), width);
43}
44
45/** Pad clipped labels by terminal cells, including wide and combining text. */
46export function column(text: string, width: number): string {
47  const label = clip(text, width);
48  return label + ' '.repeat(Math.max(0, width - displayWidth(label)));
49}
50
ui/theme.ts 28 lines
1import type { ClientElements, RenderElement, TextProps } from 'claude-code';
2
3/** Host theme tokens follow the applied theme, including auto/custom themes. */
4export const styles = {
5  text: { color: 'text', backgroundColor: 'inverseText', dimColor: false },
6  muted: { color: 'inactive', dimColor: false },
7  accent: { color: 'suggestion', dimColor: false },
8  error: { color: 'error', dimColor: false },
9  selected: { color: 'inverseText', backgroundColor: 'text', dimColor: false },
10  key: { color: 'text', bold: true, dimColor: false },
11} satisfies Record<string, TextProps>;
12
13/** Button has no base color prop; primary uses the host's suggestion token. */
14export const recoveryButton = { variant: 'primary' as const, dimColor: false };
15
16export function rowStyle(selected: boolean, editable = true): TextProps {
17  return selected ? styles.selected : editable ? styles.text : styles.muted;
18}
19
20/** Paint chrome locally so no themed ancestor covers the sample preview. */
21export function chromeRow(ui: ClientElements, child: RenderElement, width: number): RenderElement {
22  return ui.Box({
23    width, height: 1, flexShrink: 0, overflow: 'hidden',
24    backgroundColor: styles.text.backgroundColor,
25    children: [child],
26  });
27}
28