@restranger/repi-lib 0.0.0-stage → 0.0.1-562ada7

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.
@@ -0,0 +1,29 @@
1
+ export interface Disposable {
2
+ dispose(): void;
3
+ }
4
+
5
+ /** Wrap a cleanup function so it runs at most once. */
6
+ export function toDisposable(cleanup: () => void): Disposable {
7
+ let disposed = false;
8
+ return {
9
+ dispose() {
10
+ if (disposed) {
11
+ return;
12
+ }
13
+ disposed = true;
14
+ cleanup();
15
+ },
16
+ };
17
+ }
18
+
19
+ /** Best-effort LIFO cleanup: one broken disposer never prevents the rest from running. */
20
+ export function disposeAll(disposables: Iterable<Disposable>): void {
21
+ const ordered = [...disposables];
22
+ for (let index = ordered.length - 1; index >= 0; index -= 1) {
23
+ try {
24
+ ordered[index]?.dispose();
25
+ } catch {
26
+ // Cleanup is best effort; a broken plugin must not leak the others' registrations.
27
+ }
28
+ }
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
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 "./pi.js";
8
+ export * from "./seam.js";
9
+ export * from "./session.js";
10
+ export * from "./shimmer.js";
11
+ export * from "./text.js";
@@ -0,0 +1,118 @@
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
+ }
47
+
48
+ /** Format a model into its canonical key representation ("provider/id"). */
49
+ export function modelKey(model: ModelLike): string {
50
+ return `${model.provider}/${model.id}`;
51
+ }
52
+
53
+ /** Parse a string key ("provider/id" or legacy "provider:id") into its provider and modelId components. */
54
+ export function parseModelKey(input: string): { provider: string; modelId: string } | undefined {
55
+ const trimmed = input.trim();
56
+ if (!trimmed) {
57
+ return undefined;
58
+ }
59
+ const slash = trimmed.indexOf("/");
60
+ if (slash > 0 && slash < trimmed.length - 1) {
61
+ return {
62
+ provider: trimmed.slice(0, slash),
63
+ modelId: trimmed.slice(slash + 1),
64
+ };
65
+ }
66
+ const colon = trimmed.indexOf(":");
67
+ if (colon > 0 && colon < trimmed.length - 1) {
68
+ return {
69
+ provider: trimmed.slice(0, colon),
70
+ modelId: trimmed.slice(colon + 1),
71
+ };
72
+ }
73
+ return undefined;
74
+ }
75
+
76
+ export interface ModelRegistryLike {
77
+ find?(provider: string, id: string): unknown;
78
+ getAvailable?(): readonly unknown[];
79
+ getAll?(): readonly unknown[];
80
+ }
81
+
82
+ /** Resolve a model identifier or search term against a model registry. */
83
+ export function resolveModel<T extends ModelLike = ModelLike>(
84
+ input: string,
85
+ registry: ModelRegistryLike | undefined,
86
+ ): T | undefined {
87
+ if (!registry) {
88
+ return undefined;
89
+ }
90
+
91
+ const all = (registry.getAvailable?.() ?? registry.getAll?.() ?? []) as readonly unknown[];
92
+ const models = all.filter(isModelLike) as T[];
93
+ const normalized = input.trim().toLowerCase();
94
+
95
+ const exact = models.find((m) => `${m.provider}/${m.id}`.toLowerCase() === normalized);
96
+ if (exact) {
97
+ return exact;
98
+ }
99
+
100
+ const parsed = parseModelKey(normalized);
101
+ if (parsed && typeof registry.find === "function") {
102
+ const found = registry.find(parsed.provider, parsed.modelId);
103
+ if (isModelLike(found)) {
104
+ return found as T;
105
+ }
106
+ }
107
+
108
+ const scored = models
109
+ .map((model) => ({ model, score: scoreModel(model, normalized) }))
110
+ .filter((entry) => entry.score >= 20)
111
+ .sort((left, right) => right.score - left.score);
112
+ const best = scored[0];
113
+ if (best && (!scored[1] || scored[1].score < best.score)) {
114
+ return best.model;
115
+ }
116
+
117
+ return undefined;
118
+ }
package/src/pi.ts ADDED
@@ -0,0 +1,285 @@
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
+ getEntries?(): readonly unknown[];
86
+ getLeafId?(): unknown;
87
+ }
88
+
89
+ export type Tone = "default" | "muted" | "accent" | "success" | "warning" | "danger";
90
+
91
+ /** Structural view of a model selected in the parent session. */
92
+ export interface PiModel {
93
+ readonly id: string;
94
+ readonly provider: string;
95
+ readonly name?: string;
96
+ readonly reasoning?: boolean;
97
+ readonly thinkingLevelMap?: Record<string, string | null>;
98
+ readonly [key: string]: unknown;
99
+ }
100
+
101
+ /** Structural view of the host's model registry. */
102
+ export interface PiModelRegistry {
103
+ find(provider: string, modelId: string): PiModel | undefined;
104
+ getAll(): readonly PiModel[];
105
+ getAvailable?(): readonly PiModel[];
106
+ getApiKeyAndHeaders?(
107
+ model: PiModel,
108
+ ): Promise<{ ok: boolean; apiKey?: string; headers?: Record<string, string>; error?: string }>;
109
+ /**
110
+ * The host's canonical model runtime behind this facade.
111
+ *
112
+ * Pi exposes only the registry to extensions, but provider extensions register their
113
+ * providers and auth methods on that runtime. A child session must reuse it; otherwise it
114
+ * creates an empty runtime with the child's temporary `agentDir`, where custom providers
115
+ * (OAuth, header-injecting gateways) and their credentials are unknown.
116
+ */
117
+ readonly runtime?: unknown;
118
+ }
119
+
120
+ export interface PiContext extends SessionContextLike {
121
+ readonly cwd: string;
122
+ readonly ui: PiUi;
123
+ readonly sessionManager?: PiSessionManager;
124
+ readonly hasUI?: boolean;
125
+ readonly mode?: string;
126
+ readonly signal?: AbortSignal;
127
+ /** Model selected in the parent session; inherited by declarative child agents. */
128
+ readonly model?: PiModel;
129
+ /** Parent model registry, used to resolve an agent's `model:` frontmatter. */
130
+ readonly modelRegistry?: PiModelRegistry;
131
+ /** Current parent thinking level, when the host exposes it. */
132
+ readonly thinkingLevel?: string;
133
+ /** Parent system prompt; exposed for prompt inheritance. */
134
+ getSystemPrompt?(): string;
135
+ /** Whether the project's local configuration is trusted. */
136
+ isProjectTrusted?(): boolean;
137
+ readonly entries?: readonly unknown[];
138
+ readonly messages?: readonly unknown[];
139
+ }
140
+
141
+ /**
142
+ * `before_agent_start` event.
143
+ *
144
+ * Pi renders the system prompt from structured sections and diffs them across turns, so writing a
145
+ * section is the cheapest way to add context (a changed section is appended as a transcript delta
146
+ * instead of replacing the whole prompt). `sections` is optional because a minimal host may not
147
+ * expose the structured options.
148
+ */
149
+ export interface PiBeforeAgentStartEvent {
150
+ readonly systemPrompt: string;
151
+ readonly systemPromptOptions?: {
152
+ readonly sections?: Record<string, string>;
153
+ };
154
+ }
155
+
156
+ export interface PiToolResult {
157
+ readonly content: ReadonlyArray<{ type: "text"; text: string }>;
158
+ readonly details?: unknown;
159
+ readonly isError?: boolean;
160
+ }
161
+
162
+ export interface PiToolRenderResultOptions {
163
+ readonly expanded: boolean;
164
+ readonly isPartial?: boolean;
165
+ }
166
+
167
+ export interface PiToolDefinition {
168
+ readonly name: string;
169
+ readonly label?: string;
170
+ readonly description: string;
171
+ /**
172
+ * Guideline bullets Pi appends to the system prompt `<rules>` block while this tool is active.
173
+ *
174
+ * This is where behavioural rules belong: a rule attached to the tool disappears together with
175
+ * it, and it lands next to the other tool rules instead of in a separate section the model may
176
+ * weight differently. Hosts without support simply ignore the field.
177
+ */
178
+ readonly promptGuidelines?: readonly string[];
179
+ /**
180
+ * One-line snippet for the `Available tools` list in the default Pi prompt.
181
+ *
182
+ * Custom tools without a snippet are omitted from that list entirely, which makes the tool
183
+ * effectively invisible until the model reads its full declaration.
184
+ */
185
+ readonly promptSnippet?: string;
186
+ readonly parameters: unknown;
187
+ readonly execute: (
188
+ toolCallId: string,
189
+ params: Record<string, unknown>,
190
+ signal?: AbortSignal,
191
+ onUpdate?: unknown,
192
+ ctx?: PiContext,
193
+ ) => Promise<PiToolResult> | PiToolResult;
194
+ readonly renderCall?: (
195
+ args: Record<string, unknown>,
196
+ theme: PiUiCustomTheme,
197
+ context?: unknown,
198
+ ) => PiUiCustomComponent;
199
+ readonly renderResult?: (
200
+ result: PiToolResult,
201
+ options: PiToolRenderResultOptions,
202
+ theme: PiUiCustomTheme,
203
+ context?: unknown,
204
+ ) => PiUiCustomComponent;
205
+ }
206
+
207
+ /**
208
+ * One argument-autocomplete row, mirroring `AutocompleteItem` from `@earendil-works/pi-tui`.
209
+ *
210
+ * `value` is what Pi writes over the whole argument text, so an item for a nested slot carries the
211
+ * already-typed tokens as a prefix (`"fleet r-12"`), not just its own word.
212
+ */
213
+ export interface PiAutocompleteItem {
214
+ readonly value: string;
215
+ readonly label: string;
216
+ readonly description?: string;
217
+ }
218
+
219
+ export interface PiCommandOptions {
220
+ readonly description?: string;
221
+ readonly handler: (args: string, ctx: PiContext) => Promise<void> | void;
222
+ /**
223
+ * Tab completions for the text after the command name. Pi passes everything typed after the
224
+ * first space, including a trailing space (`"fleet "`), and shows nothing when this returns
225
+ * null. Hosts without argument completion simply ignore the field.
226
+ */
227
+ readonly getArgumentCompletions?: (argumentPrefix: string) => PiAutocompleteItem[] | null;
228
+ }
229
+
230
+ /** Where a host tool came from; extension tools carry the loaded module path. */
231
+ export interface PiToolSourceInfo {
232
+ readonly path?: string;
233
+ readonly source?: string;
234
+ readonly scope?: string;
235
+ readonly origin?: string;
236
+ readonly baseDir?: string;
237
+ readonly [key: string]: unknown;
238
+ }
239
+
240
+ export interface PiToolInfo {
241
+ readonly name: string;
242
+ readonly description?: string;
243
+ readonly sourceInfo?: PiToolSourceInfo;
244
+ readonly [key: string]: unknown;
245
+ }
246
+
247
+ export interface PiExtensionAPI {
248
+ /**
249
+ * Pi returns an unsubscribe function for extension handlers. Hosts that return nothing are
250
+ * still supported structurally, but a plugin may dispose its own subscription.
251
+ */
252
+ on(event: string, handler: (event: unknown, ctx: PiContext) => unknown): (() => void) | undefined;
253
+ registerTool(tool: PiToolDefinition): void;
254
+ registerCommand(name: string, options: PiCommandOptions): void;
255
+ readonly events: EventBus;
256
+ getActiveTools?(): string[];
257
+ getAllTools?(): readonly PiToolInfo[];
258
+ setActiveTools?(toolNames: string[]): void;
259
+ getThinkingLevel?(): string | undefined;
260
+ getSettings?(): Record<string, unknown>;
261
+ sendMessage?(message: unknown, options?: unknown): void;
262
+ sendUserMessage?(content: unknown, options?: unknown): void;
263
+ setModel?(model: unknown): Promise<boolean>;
264
+ }
265
+
266
+ /** Session id from a Pi context, falling back to `default` on hosts without sessions. */
267
+ export function piSessionId(ctx: PiContext | undefined, fallback = "default"): string {
268
+ return getSessionId(ctx ?? {}, fallback);
269
+ }
270
+
271
+ /** All tool names Pi knows about, not just the currently active subset. */
272
+ export function allPiToolNames(pi: PiExtensionAPI): readonly string[] {
273
+ try {
274
+ if (typeof pi.getAllTools === "function") {
275
+ return pi.getAllTools().map((tool) => tool.name);
276
+ }
277
+ if (typeof pi.getActiveTools === "function") {
278
+ return pi.getActiveTools();
279
+ }
280
+ } catch {
281
+ // Tool enumeration is optional host functionality; a host that cannot answer must not break
282
+ // extension startup.
283
+ }
284
+ return [];
285
+ }
package/src/seam.ts ADDED
@@ -0,0 +1,205 @@
1
+ import { type ContractId, READY_CHANNEL, type ReadyEvent, isReadyEvent } from "./contracts.js";
2
+ import { type Disposable, toDisposable } from "./disposable.js";
3
+
4
+ /**
5
+ * Process-global service registry.
6
+ *
7
+ * `Symbol.for` and `globalThis` are process-global by spec, so they survive Pi's per-extension
8
+ * module isolation (jiti with `moduleCache: false`). A normal module-level singleton would not:
9
+ * every extension would get its own copy and discovery would silently fail.
10
+ */
11
+ const REGISTRY_KEY = Symbol.for("repi.services.v1");
12
+
13
+ interface ServiceEntry {
14
+ readonly owner: string;
15
+ readonly impl: unknown;
16
+ }
17
+
18
+ type SessionServices = Map<string, ServiceEntry>;
19
+ type Registry = Map<ContractId, SessionServices>;
20
+
21
+ function registry(): Registry {
22
+ const store = globalThis as Record<PropertyKey, unknown>;
23
+ let current = store[REGISTRY_KEY] as Registry | undefined;
24
+ if (!current) {
25
+ current = new Map();
26
+ store[REGISTRY_KEY] = current;
27
+ }
28
+ return current;
29
+ }
30
+
31
+ function assertNonEmpty(value: string, name: string): void {
32
+ if (typeof value !== "string" || value.length === 0) {
33
+ throw new TypeError(`${name} must be a non-empty string.`);
34
+ }
35
+ }
36
+
37
+ export interface PublishServiceOptions<T> {
38
+ /** Contract id including its major version, e.g. `re:permissions@1`. */
39
+ readonly contract: ContractId;
40
+ /** Session node that owns this implementation. */
41
+ readonly sessionId: string;
42
+ /** Stable plugin id. Used to distinguish a reload from a conflicting provider. */
43
+ readonly owner: string;
44
+ readonly impl: T;
45
+ }
46
+
47
+ /**
48
+ * Publish a service for one contract + session.
49
+ *
50
+ * The same owner may replace its own service (reload / new generation). A different owner is a
51
+ * conflict: two plugins claiming the same contract for the same session is a configuration error,
52
+ * not something to resolve silently by load order.
53
+ */
54
+ export function publishService<T>(options: PublishServiceOptions<T>): Disposable {
55
+ const { contract, sessionId, owner, impl } = options;
56
+ assertNonEmpty(contract, "contract");
57
+ assertNonEmpty(sessionId, "sessionId");
58
+ assertNonEmpty(owner, "owner");
59
+
60
+ const reg = registry();
61
+ let services = reg.get(contract);
62
+ if (!services) {
63
+ services = new Map();
64
+ reg.set(contract, services);
65
+ }
66
+
67
+ const existing = services.get(sessionId);
68
+ if (existing && existing.owner !== owner) {
69
+ throw new Error(
70
+ `Contract "${contract}" for session "${sessionId}" is already provided by "${existing.owner}"; ` +
71
+ `"${owner}" cannot replace it.`,
72
+ );
73
+ }
74
+
75
+ const entry: ServiceEntry = { owner, impl };
76
+ services.set(sessionId, entry);
77
+
78
+ return toDisposable(() => {
79
+ if (services.get(sessionId) === entry) {
80
+ services.delete(sessionId);
81
+ if (services.size === 0) {
82
+ reg.delete(contract);
83
+ }
84
+ }
85
+ });
86
+ }
87
+
88
+ /** Resolve the service for a contract + session, or `undefined` when that node has none. */
89
+ export function getService<T>(contract: ContractId, sessionId: string): T | undefined {
90
+ return registry().get(contract)?.get(sessionId)?.impl as T | undefined;
91
+ }
92
+
93
+ export function hasService(contract: ContractId, sessionId: string): boolean {
94
+ return registry().get(contract)?.has(sessionId) ?? false;
95
+ }
96
+
97
+ export interface ServiceDescriptor {
98
+ readonly contract: ContractId;
99
+ readonly sessionId: string;
100
+ readonly owner: string;
101
+ }
102
+
103
+ /** Snapshot for diagnostics. Sorted so output is deterministic. */
104
+ export function listServices(): readonly ServiceDescriptor[] {
105
+ const result: ServiceDescriptor[] = [];
106
+ for (const [contract, sessions] of registry()) {
107
+ for (const [sessionId, entry] of sessions) {
108
+ result.push({ contract, sessionId, owner: entry.owner });
109
+ }
110
+ }
111
+ return result.sort((left, right) =>
112
+ left.contract < right.contract
113
+ ? -1
114
+ : left.contract > right.contract
115
+ ? 1
116
+ : left.sessionId < right.sessionId
117
+ ? -1
118
+ : left.sessionId > right.sessionId
119
+ ? 1
120
+ : 0,
121
+ );
122
+ }
123
+
124
+ /** The subset of Pi's event bus this library needs. Kept structural so `lib` stays host-agnostic. */
125
+ export interface EventBus {
126
+ on(event: string, handler: (data: unknown) => void): () => void;
127
+ emit(event: string, data?: unknown): void;
128
+ }
129
+
130
+ /** Announce a ready event. The payload is data; the service stays in the seam. */
131
+ export function announceReady(bus: EventBus, event: ReadyEvent): void {
132
+ bus.emit(READY_CHANNEL, event);
133
+ }
134
+
135
+ /**
136
+ * Subscribe to ready announcements for one contract.
137
+ *
138
+ * A throwing consumer cannot break the provider or other consumers. The returned disposable is
139
+ * idempotent.
140
+ */
141
+ /** An `async` handler must not surface as a process-level unhandled rejection. */
142
+ function swallowRejection(result: unknown): void {
143
+ const maybePromise = result as PromiseLike<unknown> | undefined;
144
+ if (maybePromise && typeof maybePromise.then === "function") {
145
+ void Promise.resolve(maybePromise).catch(() => undefined);
146
+ }
147
+ }
148
+
149
+ export function onReady(bus: EventBus, contract: ContractId, handler: (event: ReadyEvent) => unknown): Disposable {
150
+ const off = bus.on(READY_CHANNEL, (data) => {
151
+ if (!isReadyEvent(data) || data.contract !== contract) {
152
+ return;
153
+ }
154
+ try {
155
+ swallowRejection(handler(data));
156
+ } catch {
157
+ // The bus is a broadcast channel; one broken listener must not take down the rest.
158
+ }
159
+ });
160
+ return toDisposable(off);
161
+ }
162
+
163
+ /**
164
+ * Pull + push integration in one call: invoke `handler` with the current service if it already
165
+ * exists, then again whenever a matching ready event arrives. Re-announcing the same service does
166
+ * not invoke the handler twice.
167
+ */
168
+ export function onService<T>(
169
+ bus: EventBus,
170
+ contract: ContractId,
171
+ sessionId: string,
172
+ handler: (service: T, event?: ReadyEvent) => unknown,
173
+ ): Disposable {
174
+ let disposed = false;
175
+ let last: T | undefined;
176
+
177
+ const deliver = (event?: ReadyEvent): void => {
178
+ if (disposed) {
179
+ return;
180
+ }
181
+ const service = getService<T>(contract, sessionId);
182
+ if (service === undefined || service === last) {
183
+ return;
184
+ }
185
+ last = service;
186
+ try {
187
+ swallowRejection(handler(service, event));
188
+ } catch {
189
+ // Keep the subscription alive; the next generation may be healthy.
190
+ }
191
+ };
192
+
193
+ const off = onReady(bus, contract, (event) => {
194
+ if (event.sessionId === sessionId) {
195
+ deliver(event);
196
+ }
197
+ });
198
+ // Subscribe first, then pull: a publish between the two is still observed.
199
+ deliver();
200
+
201
+ return toDisposable(() => {
202
+ disposed = true;
203
+ off.dispose();
204
+ });
205
+ }
package/src/session.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The smallest shape needed to resolve a session id. Both direct `sessionId` fields and Pi's
3
+ * `sessionManager.getSessionId()` are accepted so the helper works across host contexts.
4
+ */
5
+ export interface SessionContextLike {
6
+ readonly sessionId?: string;
7
+ readonly sessionManager?: {
8
+ getSessionId?(): string | undefined;
9
+ };
10
+ }
11
+
12
+ /**
13
+ * Resolve the current session id.
14
+ *
15
+ * A missing id falls back to `default` so a plugin still works on a host without session support.
16
+ * Multi-session integration degrades in that case; standalone behavior does not.
17
+ */
18
+ export function getSessionId(ctx: SessionContextLike, fallback = "default"): string {
19
+ const direct = ctx.sessionId;
20
+ if (typeof direct === "string" && direct.length > 0) {
21
+ return direct;
22
+ }
23
+ const managed = ctx.sessionManager?.getSessionId?.();
24
+ if (typeof managed === "string" && managed.length > 0) {
25
+ return managed;
26
+ }
27
+ return fallback;
28
+ }