@restranger/repi-lib 0.0.0-stage → 0.0.1-ca9b82c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ export * from "./completion.js";
2
+ export * from "./config.js";
3
+ export * from "./contracts/index.js";
4
+ export * from "./contracts.js";
5
+ export * from "./disposable.js";
6
+ export * from "./model-scoring.js";
7
+ export * from "./overlay.js";
8
+ export * from "./pi.js";
9
+ export * from "./seam.js";
10
+ export * from "./session.js";
11
+ export * from "./shimmer.js";
12
+ export * from "./text.js";
13
+ export * from "./view.js";
@@ -0,0 +1,46 @@
1
+ export interface ModelLike {
2
+ readonly id: string;
3
+ readonly provider: string;
4
+ readonly name?: string;
5
+ }
6
+
7
+ /** Check whether a value has the structural shape of a model (id and provider). */
8
+ export function isModelLike(candidate: unknown): candidate is ModelLike {
9
+ if (typeof candidate !== "object" || candidate === null) {
10
+ return false;
11
+ }
12
+ const record = candidate as Record<string, unknown>;
13
+ return typeof record.id === "string" && typeof record.provider === "string";
14
+ }
15
+
16
+ /**
17
+ * Score how well a model matches a search query.
18
+ *
19
+ * Used by model resolution in `model-fallback` and `subagents`.
20
+ * Returns a score from 0 to 100:
21
+ * - 100: exact match on id or provider/id
22
+ * - 60-90: query is a substring of id or provider/id
23
+ * - 40-60: query is a substring of display name
24
+ * - 20: all whitespace/dash/slash-separated tokens match id, name, or provider
25
+ * - 0: no match
26
+ */
27
+ export function scoreModel(model: ModelLike, query: string): number {
28
+ const id = model.id.toLowerCase();
29
+ const name = (model.name ?? "").toLowerCase();
30
+ const provider = model.provider.toLowerCase();
31
+ const full = `${provider}/${id}`;
32
+ if (id === query || full === query) {
33
+ return 100;
34
+ }
35
+ if (id.includes(query) || full.includes(query)) {
36
+ return 60 + (query.length / Math.max(id.length, 1)) * 30;
37
+ }
38
+ if (name.includes(query)) {
39
+ return 40 + (query.length / Math.max(name.length, 1)) * 20;
40
+ }
41
+ const parts = query.split(/[\s\-/]+/).filter(Boolean);
42
+ if (parts.length > 0 && parts.every((part) => id.includes(part) || name.includes(part) || provider.includes(part))) {
43
+ return 20;
44
+ }
45
+ return 0;
46
+ }
package/src/overlay.ts ADDED
@@ -0,0 +1,207 @@
1
+ import type { PiUiCustomComponent, PiUiCustomKeybindings, PiUiCustomTheme, PiUiCustomTui } from "./pi.js";
2
+
3
+ /**
4
+ * Shared scaffolding for full-screen list overlays.
5
+ *
6
+ * `@restranger/repi-subagents` and `@restranger/repi-model-fallback` each shipped their own copy of the same fifteen
7
+ * methods: attach/refresh/dispose, selection clamping, detail scrolling, terminal row budgeting,
8
+ * safe `theme.fg`, safe keybinding lookup and the close handshake. The copies drifted (one handled
9
+ * `getKeys` failures, the other did not), so this is the single implementation.
10
+ *
11
+ * Subclasses own their data, rendering and key handling; everything about *host interaction* lives
12
+ * here.
13
+ */
14
+ export interface ListOverlayOptions {
15
+ /** Rows the host granted; defaults to the attached terminal, then to 32. */
16
+ readonly maxRows?: number;
17
+ }
18
+
19
+ /** Frame rows reserved for header/separator/footer lines. */
20
+ export const OVERLAY_FRAME_CHROME_ROWS = 6;
21
+
22
+ export abstract class ListOverlay implements PiUiCustomComponent {
23
+ protected tui?: PiUiCustomTui;
24
+ protected theme?: PiUiCustomTheme;
25
+ protected keybindings?: PiUiCustomKeybindings;
26
+ private done?: (value: undefined) => void;
27
+
28
+ protected selected = 0;
29
+ protected detailScroll = 0;
30
+ /** Last scroll ceiling seen by `render`, so `scrollDetail` can clamp without rendering first. */
31
+ protected maxDetailScroll = 0;
32
+
33
+ protected constructor(protected readonly overlayOptions: ListOverlayOptions = {}) {}
34
+
35
+ abstract render(width: number): string[];
36
+ abstract handleInput(data: string): void;
37
+
38
+ /** Number of selectable rows; `0` makes every move a no-op. */
39
+ protected abstract itemCount(): number;
40
+
41
+ /** Hook for subclasses that reset their own state when selection changes. */
42
+ protected onSelectionChanged(): void {}
43
+
44
+ /** Hook for subclasses that must run cleanup after the overlay closes. */
45
+ protected onClose(): void {}
46
+
47
+ attach(
48
+ tui: PiUiCustomTui,
49
+ theme: PiUiCustomTheme,
50
+ keybindings: PiUiCustomKeybindings,
51
+ done: (value: undefined) => void,
52
+ ): void {
53
+ this.tui = tui;
54
+ this.theme = theme;
55
+ this.keybindings = keybindings;
56
+ this.done = done;
57
+ }
58
+
59
+ /** Called by the plugin whenever underlying state changes. */
60
+ refresh(): void {
61
+ this.clampSelection();
62
+ this.tui?.requestRender();
63
+ }
64
+
65
+ dispose(): void {
66
+ this.close();
67
+ this.tui = undefined;
68
+ this.theme = undefined;
69
+ this.keybindings = undefined;
70
+ }
71
+
72
+ invalidate(): void {
73
+ this.clampSelection();
74
+ }
75
+
76
+ protected move(delta: number): void {
77
+ const length = this.itemCount();
78
+ if (length === 0) {
79
+ return;
80
+ }
81
+ this.select(this.selected + delta);
82
+ }
83
+
84
+ protected select(index: number): void {
85
+ const length = this.itemCount();
86
+ if (length === 0) {
87
+ return;
88
+ }
89
+ this.selected = Math.max(0, Math.min(index, length - 1));
90
+ this.detailScroll = 0;
91
+ this.onSelectionChanged();
92
+ this.tui?.requestRender();
93
+ }
94
+
95
+ protected clampSelection(): void {
96
+ this.selected = Math.max(0, Math.min(this.selected, Math.max(0, this.itemCount() - 1)));
97
+ }
98
+
99
+ protected scrollDetail(delta: number): void {
100
+ this.detailScroll = Math.max(0, Math.min(this.detailScroll + delta, this.maxDetailScroll));
101
+ this.tui?.requestRender();
102
+ }
103
+
104
+ protected rowsBudget(): number {
105
+ return Math.max(1, Math.floor(this.overlayOptions.maxRows ?? this.tui?.terminal?.rows ?? 32));
106
+ }
107
+
108
+ /**
109
+ * Body rows after the frame chrome. `bodyHeight + OVERLAY_FRAME_CHROME_ROWS` must stay inside
110
+ * the budget, or the host clips the footer away on a short terminal.
111
+ */
112
+ protected bodyHeightFor(rows: number): number {
113
+ return Math.max(1, Math.floor(rows * 0.85) - OVERLAY_FRAME_CHROME_ROWS);
114
+ }
115
+
116
+ protected bodyRows(): number {
117
+ return this.bodyHeightFor(this.rowsBudget());
118
+ }
119
+
120
+ /** Window over `body` honouring the current detail scroll position. */
121
+ protected windowBody(body: readonly string[], height: number): string[] {
122
+ if (height <= 0) {
123
+ return [];
124
+ }
125
+ const maxScroll = Math.max(0, body.length - height);
126
+ this.maxDetailScroll = maxScroll;
127
+ const start = Math.max(0, Math.min(this.detailScroll, maxScroll));
128
+ return body.slice(start, start + height);
129
+ }
130
+
131
+ protected close(): void {
132
+ const done = this.done;
133
+ this.done = undefined;
134
+ done?.(undefined);
135
+ this.onClose();
136
+ }
137
+
138
+ protected matches(data: string, key: string): boolean {
139
+ try {
140
+ return this.keybindings?.matches(data, key) ?? false;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+
146
+ /** Human label for an action, falling back to the conventional key. */
147
+ protected keyLabel(key: string, fallback: string): string {
148
+ try {
149
+ const keys = this.keybindings?.getKeys?.(key);
150
+ if (!keys || keys.length === 0) {
151
+ return fallback;
152
+ }
153
+ return keys
154
+ .map((binding) => (binding === "up" ? "↑" : binding === "down" ? "↓" : binding === "escape" ? "Esc" : binding))
155
+ .join("/");
156
+ } catch {
157
+ return fallback;
158
+ }
159
+ }
160
+
161
+ /** `theme.fg` for a token that may be missing from a host theme; never throws. */
162
+ protected paint(color: string, text: string): string {
163
+ try {
164
+ return this.theme?.fg(color, text) ?? text;
165
+ } catch {
166
+ return text;
167
+ }
168
+ }
169
+
170
+ protected border(text: string): string {
171
+ return this.paint("border", text);
172
+ }
173
+ }
174
+
175
+ function parseSgrCode(data: string): number | undefined {
176
+ if (!data.startsWith("\x1b[<")) return undefined;
177
+ const semicolon = data.indexOf(";", 3);
178
+ if (semicolon === -1) return undefined;
179
+ const code = Number.parseInt(data.slice(3, semicolon), 10);
180
+ return Number.isNaN(code) ? undefined : code;
181
+ }
182
+
183
+ /**
184
+ * Decode an SGR mouse scroll event into a direction.
185
+ *
186
+ * Terminals report the wheel as button 64 (up) / 65 (down) in three encodings; getting one wrong
187
+ * means scrolling silently does nothing, which is why this lives next to the overlay instead of in
188
+ * each component.
189
+ */
190
+ export function mouseWheelDirection(data: string): -1 | 1 | undefined {
191
+ if (data.startsWith("\x1b[<64;")) return -1;
192
+ if (data.startsWith("\x1b[<65;")) return 1;
193
+ const code = parseSgrCode(data);
194
+ if (code !== undefined) {
195
+ if ((code & 64) !== 0) {
196
+ return (code & 1) === 0 ? -1 : 1;
197
+ }
198
+ return undefined;
199
+ }
200
+ if (data.startsWith("\x1b[M") && data.length >= 4) {
201
+ const encoded = data.charCodeAt(3) - 32;
202
+ if ((encoded & 64) !== 0) {
203
+ return (encoded & 1) === 0 ? -1 : 1;
204
+ }
205
+ }
206
+ return undefined;
207
+ }
package/src/pi.ts ADDED
@@ -0,0 +1,272 @@
1
+ import type { EventBus } from "./seam.js";
2
+ import { type SessionContextLike, getSessionId } from "./session.js";
3
+
4
+ /**
5
+ * Structural view of the Pi extension API this ecosystem uses.
6
+ *
7
+ * We intentionally do not import `@earendil-works/pi-coding-agent` at runtime: a plugin package
8
+ * must stay usable when the host is provided by Pi itself, and tests should not need the full
9
+ * agent dependency. The shapes below are assignable from the real API.
10
+ */
11
+ export interface PiUiCustomTheme {
12
+ fg(color: string, text: string): string;
13
+ bold?(text: string): string;
14
+ }
15
+
16
+ export interface PiUiCustomKeybindings {
17
+ matches(data: string, key: string): boolean;
18
+ /** Keys bound to an action id; used to print the user's real bindings in a footer. */
19
+ getKeys?(key: string): readonly string[];
20
+ }
21
+
22
+ export interface PiUiTerminalSize {
23
+ readonly columns: number;
24
+ readonly rows: number;
25
+ }
26
+
27
+ export interface PiUiCustomTui {
28
+ requestRender(): void;
29
+ /** `regular` (main screen, terminal owns scrollback) or `fullscreen` (alt screen). */
30
+ readonly mode?: "regular" | "fullscreen";
31
+ readonly terminal?: PiUiTerminalSize;
32
+ }
33
+
34
+ export interface PiUiCustomComponent {
35
+ render(width: number): string[];
36
+ handleInput?(data: string): void;
37
+ invalidate?(): void;
38
+ dispose?(): void;
39
+ }
40
+
41
+ /** Widget factory form of `ctx.ui.setWidget`; the host calls it again on every remount. */
42
+ export type PiUiWidgetFactory = (tui: PiUiCustomTui, theme: PiUiCustomTheme) => PiUiCustomComponent;
43
+ export type PiUiWidgetContent = readonly string[] | PiUiWidgetFactory | undefined;
44
+
45
+ export interface PiUiWidgetOptions {
46
+ readonly placement?: "aboveEditor" | "belowEditor";
47
+ }
48
+
49
+ export interface PiUiCustomOptions {
50
+ readonly overlay?: boolean;
51
+ /** Host overlay sizing/anchor options; ignored by hosts without overlays. */
52
+ readonly overlayOptions?: unknown;
53
+ }
54
+
55
+ export interface PiUi {
56
+ select(title: string, options: string[], opts?: unknown): Promise<string | undefined>;
57
+ confirm(title: string, message: string, opts?: unknown): Promise<boolean>;
58
+ input(title: string, placeholder?: string, opts?: unknown): Promise<string | undefined>;
59
+ notify(message: string, type?: "info" | "warning" | "error"): void;
60
+ setStatus?(key: string, text?: string): void;
61
+ /**
62
+ * Persistent widget above or below the editor. Hosts render the factory form with the live
63
+ * `width`, but RPC/print/JSON hosts only forward `string[]` — callers must pass plain lines
64
+ * there or the widget is silently dropped.
65
+ */
66
+ setWidget?(key: string, content: PiUiWidgetContent, options?: PiUiWidgetOptions): void;
67
+ setTitle?(title: string): void;
68
+ setWorkingMessage?(message?: string): void;
69
+ /** Inline TUI component; absent in RPC/print and in minimal test hosts. */
70
+ custom?<T>(
71
+ factory: (
72
+ tui: PiUiCustomTui,
73
+ theme: PiUiCustomTheme,
74
+ keybindings: PiUiCustomKeybindings,
75
+ done: (value: T) => void,
76
+ ) => PiUiCustomComponent,
77
+ opts?: PiUiCustomOptions,
78
+ ): Promise<T>;
79
+ }
80
+
81
+ export interface PiSessionManager {
82
+ getSessionId(): string;
83
+ /** Persisted transcript path, when the host stores sessions on disk. */
84
+ getSessionFile?(): string | undefined;
85
+ }
86
+
87
+ /** Structural view of a model selected in the parent session. */
88
+ export interface PiModel {
89
+ readonly id: string;
90
+ readonly provider: string;
91
+ readonly name?: string;
92
+ readonly [key: string]: unknown;
93
+ }
94
+
95
+ /** Structural view of the host's model registry. */
96
+ export interface PiModelRegistry {
97
+ find(provider: string, modelId: string): PiModel | undefined;
98
+ getAll(): readonly PiModel[];
99
+ getAvailable?(): readonly PiModel[];
100
+ /**
101
+ * The host's canonical model runtime behind this facade.
102
+ *
103
+ * Pi exposes only the registry to extensions, but provider extensions register their
104
+ * providers and auth methods on that runtime. A child session must reuse it; otherwise it
105
+ * creates an empty runtime with the child's temporary `agentDir`, where custom providers
106
+ * (OAuth, header-injecting gateways) and their credentials are unknown.
107
+ */
108
+ readonly runtime?: unknown;
109
+ }
110
+
111
+ export interface PiContext extends SessionContextLike {
112
+ readonly cwd: string;
113
+ readonly ui: PiUi;
114
+ readonly sessionManager?: PiSessionManager;
115
+ readonly hasUI?: boolean;
116
+ readonly mode?: string;
117
+ readonly signal?: AbortSignal;
118
+ /** Model selected in the parent session; inherited by declarative child agents. */
119
+ readonly model?: PiModel;
120
+ /** Parent model registry, used to resolve an agent's `model:` frontmatter. */
121
+ readonly modelRegistry?: PiModelRegistry;
122
+ /** Current parent thinking level, when the host exposes it. */
123
+ readonly thinkingLevel?: string;
124
+ /** Parent system prompt; exposed for prompt inheritance. */
125
+ getSystemPrompt?(): string;
126
+ /** Whether the project's local configuration is trusted. */
127
+ isProjectTrusted?(): boolean;
128
+ }
129
+
130
+ /**
131
+ * `before_agent_start` event.
132
+ *
133
+ * Pi renders the system prompt from structured sections and diffs them across turns, so writing a
134
+ * section is the cheapest way to add context (a changed section is appended as a transcript delta
135
+ * instead of replacing the whole prompt). `sections` is optional because a minimal host may not
136
+ * expose the structured options.
137
+ */
138
+ export interface PiBeforeAgentStartEvent {
139
+ readonly systemPrompt: string;
140
+ readonly systemPromptOptions?: {
141
+ readonly sections?: Record<string, string>;
142
+ };
143
+ }
144
+
145
+ export interface PiToolResult {
146
+ readonly content: ReadonlyArray<{ type: "text"; text: string }>;
147
+ readonly details?: unknown;
148
+ readonly isError?: boolean;
149
+ }
150
+
151
+ export interface PiToolRenderResultOptions {
152
+ readonly expanded: boolean;
153
+ readonly isPartial?: boolean;
154
+ }
155
+
156
+ export interface PiToolDefinition {
157
+ readonly name: string;
158
+ readonly label?: string;
159
+ readonly description: string;
160
+ /**
161
+ * Guideline bullets Pi appends to the system prompt `<rules>` block while this tool is active.
162
+ *
163
+ * This is where behavioural rules belong: a rule attached to the tool disappears together with
164
+ * it, and it lands next to the other tool rules instead of in a separate section the model may
165
+ * weight differently. Hosts without support simply ignore the field.
166
+ */
167
+ readonly promptGuidelines?: readonly string[];
168
+ /**
169
+ * One-line snippet for the `Available tools` list in the default Pi prompt.
170
+ *
171
+ * Custom tools without a snippet are omitted from that list entirely, which makes the tool
172
+ * effectively invisible until the model reads its full declaration.
173
+ */
174
+ readonly promptSnippet?: string;
175
+ readonly parameters: unknown;
176
+ readonly execute: (
177
+ toolCallId: string,
178
+ params: Record<string, unknown>,
179
+ signal?: AbortSignal,
180
+ onUpdate?: unknown,
181
+ ctx?: PiContext,
182
+ ) => Promise<PiToolResult> | PiToolResult;
183
+ readonly renderCall?: (
184
+ args: Record<string, unknown>,
185
+ theme: PiUiCustomTheme,
186
+ context?: unknown,
187
+ ) => PiUiCustomComponent;
188
+ readonly renderResult?: (
189
+ result: PiToolResult,
190
+ options: PiToolRenderResultOptions,
191
+ theme: PiUiCustomTheme,
192
+ context?: unknown,
193
+ ) => PiUiCustomComponent;
194
+ }
195
+
196
+ /**
197
+ * One argument-autocomplete row, mirroring `AutocompleteItem` from `@earendil-works/pi-tui`.
198
+ *
199
+ * `value` is what Pi writes over the whole argument text, so an item for a nested slot carries the
200
+ * already-typed tokens as a prefix (`"fleet r-12"`), not just its own word.
201
+ */
202
+ export interface PiAutocompleteItem {
203
+ readonly value: string;
204
+ readonly label: string;
205
+ readonly description?: string;
206
+ }
207
+
208
+ export interface PiCommandOptions {
209
+ readonly description?: string;
210
+ readonly handler: (args: string, ctx: PiContext) => Promise<void> | void;
211
+ /**
212
+ * Tab completions for the text after the command name. Pi passes everything typed after the
213
+ * first space, including a trailing space (`"fleet "`), and shows nothing when this returns
214
+ * null. Hosts without argument completion simply ignore the field.
215
+ */
216
+ readonly getArgumentCompletions?: (argumentPrefix: string) => PiAutocompleteItem[] | null;
217
+ }
218
+
219
+ /** Where a host tool came from; extension tools carry the loaded module path. */
220
+ export interface PiToolSourceInfo {
221
+ readonly path?: string;
222
+ readonly source?: string;
223
+ readonly scope?: string;
224
+ readonly origin?: string;
225
+ readonly baseDir?: string;
226
+ readonly [key: string]: unknown;
227
+ }
228
+
229
+ export interface PiToolInfo {
230
+ readonly name: string;
231
+ readonly description?: string;
232
+ readonly sourceInfo?: PiToolSourceInfo;
233
+ readonly [key: string]: unknown;
234
+ }
235
+
236
+ export interface PiExtensionAPI {
237
+ /**
238
+ * Pi returns an unsubscribe function for extension handlers. Hosts that return nothing are
239
+ * still supported structurally, but a plugin may dispose its own subscription.
240
+ */
241
+ on(event: string, handler: (event: unknown, ctx: PiContext) => unknown): (() => void) | undefined;
242
+ registerTool(tool: PiToolDefinition): void;
243
+ registerCommand(name: string, options: PiCommandOptions): void;
244
+ readonly events: EventBus;
245
+ getActiveTools?(): string[];
246
+ getAllTools?(): readonly PiToolInfo[];
247
+ setActiveTools?(toolNames: string[]): void;
248
+ sendMessage?(message: unknown, options?: unknown): void;
249
+ sendUserMessage?(content: unknown, options?: unknown): void;
250
+ setModel?(model: unknown): Promise<boolean>;
251
+ }
252
+
253
+ /** Session id from a Pi context, falling back to `default` on hosts without sessions. */
254
+ export function piSessionId(ctx: PiContext | undefined, fallback = "default"): string {
255
+ return getSessionId(ctx ?? {}, fallback);
256
+ }
257
+
258
+ /** All tool names Pi knows about, not just the currently active subset. */
259
+ export function allPiToolNames(pi: PiExtensionAPI): readonly string[] {
260
+ try {
261
+ if (typeof pi.getAllTools === "function") {
262
+ return pi.getAllTools().map((tool) => tool.name);
263
+ }
264
+ if (typeof pi.getActiveTools === "function") {
265
+ return pi.getActiveTools();
266
+ }
267
+ } catch {
268
+ // Tool enumeration is optional host functionality; a host that cannot answer must not break
269
+ // extension startup.
270
+ }
271
+ return [];
272
+ }