pi-odd-worktree 3.15.1 → 3.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +70 -212
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/session-auto-name-wiring.test.js +39 -0
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,523 @@
1
+ /**
2
+ * The runtime handshake: how a plugin reaches this bridge without a path, an environment variable
3
+ * or an import.
4
+ *
5
+ * Pi gives two independent projects exactly one sanctioned channel that needs no install detail:
6
+ * `globalThis` (`docs/extensions.md:1965-1972`). So the package publishes a frozen, versioned
7
+ * service object at a stable symbol, at module load:
8
+ *
9
+ * ```ts
10
+ * Symbol.for("gentle-shell-bridge/api/v1") → { schema, version, VERSION, registerRows,
11
+ * registerSection, registerCardStyle,
12
+ * registerTransform, registerToolDesign,
13
+ * registerMessageDesign, createStore,
14
+ * requestRepaint }
15
+ * ```
16
+ *
17
+ * A plugin registers from its own `session_start` handler. But Pi does NOT guarantee that this
18
+ * package loaded first: the real TUI showed global extensions (`~/.pi/agent/extensions`) loading —
19
+ * and receiving `session_start` — before a configured package's module ever published. So the
20
+ * symbol's presence is the complete answer only when it is present. When it is absent, the plugin
21
+ * still needs a way to hear about a bridge that publishes later, and it hears it on Pi's own
22
+ * cross-extension bus (`docs/extensions.md:1965-1972`):
23
+ *
24
+ * ```ts
25
+ * pi.events.on("gentle-shell-bridge:ready", ({ schema, version, VERSION }) => …)
26
+ * ```
27
+ *
28
+ * The bridge emits that event once per process, after a successful publish and never for an
29
+ * incompatible slot (`announceBridgeReady`). A plugin that imports this package calls
30
+ * `onBridgeApi(handler, pi.events)`, which serves it immediately when the object is already there
31
+ * and subscribes when it is not. The symbol stays the authority: the announcement only says "look
32
+ * again", so a copy that publishes an incompatible slot announces nothing and a listener that
33
+ * hears the event still gates on the object itself.
34
+ *
35
+ * Why a symbol instead of a path or `GENTLE_SHELL_BRIDGE_MODULE`: a path is not a contract between
36
+ * two projects — it names one checkout on one machine, and it breaks the day either project moves.
37
+ * The symbol key is the contract, and `v1` in the key is the major version: a future major takes a
38
+ * NEW key rather than mutating this one. `pi-lens` publishes its IO bridge the same way
39
+ * (`clients/io-bridge-contract.ts:26-31`, `clients/process-bridge.ts:31-66`): stable symbol, a
40
+ * version constant, a frozen non-writable slot, and "version mismatch means unsupported".
41
+ *
42
+ * ## First wins, and nothing is ever reset
43
+ *
44
+ * Pi loads every extension through its own jiti loader with `moduleCache: false`, so this module
45
+ * exists once per copy. Every copy's functions operate on the same process-global bus
46
+ * (`./bus.ts`, `./store.ts`), which makes them interchangeable: whoever publishes first owns the
47
+ * slot, and later copies hand the same object back. A slot that holds something incompatible is
48
+ * treated as ABSENT — never overwritten, never deleted.
49
+ *
50
+ * ## Version skew
51
+ *
52
+ * Consumers gate on the schema string, `version === 1` and the three callable members
53
+ * (`isBridgeApi`). A mismatch is not an error and never a fallback to a half-working object: the
54
+ * caller sees `undefined`, and one notice is recorded per process (shown once, in the TUI).
55
+ *
56
+ * ## Why the gate is also documented inline
57
+ *
58
+ * A plugin that does not depend on this package must be able to do the same thing in about six
59
+ * lines, so README.md carries the inline copy of the gate and the symbol. Keep the two in sync.
60
+ */
61
+
62
+ import { registerCardStyle, registerRows, registerSection, registerTransform } from "./bus.ts";
63
+ import { registerMessageDesign } from "./message-designs.ts";
64
+ import { recordNotice } from "./notices.ts";
65
+ import { requestRepaint } from "./repaint.ts";
66
+ import { createStore } from "./store.ts";
67
+ import { registerToolDesign, resolveToolDesignSelection } from "./tool-designs.ts";
68
+
69
+ /** The release that published the object; informational, never the compatibility check. */
70
+ export const VERSION = "0.16.2";
71
+
72
+ /** Identity of the object, so a foreign payload at the symbol is never mistaken for ours. */
73
+ export const API_SCHEMA = "gentle-shell-bridge/api";
74
+
75
+ /** Major version of the published shape. A breaking change means a new symbol key. */
76
+ export const API_VERSION = 1;
77
+
78
+ /** The published service object's stable, process-global key. */
79
+ export const BRIDGE_API_KEY: symbol = Symbol.for("gentle-shell-bridge/api/v1");
80
+
81
+ /**
82
+ * The channel this package announces itself on, on Pi's cross-extension bus.
83
+ *
84
+ * A plugin loaded before this package has no object to read yet, so it subscribes here. The
85
+ * announcement is a notification, never a registry: it says "the object is published now", and the
86
+ * listener reads the symbol. That keeps one authority (the symbol and its shape gate) and one
87
+ * channel for the timing.
88
+ */
89
+ export const BRIDGE_READY_EVENT = "gentle-shell-bridge:ready";
90
+
91
+ /** What the announcement carries: identity, major version and the publishing release. */
92
+ export interface BridgeReadyPayload {
93
+ readonly schema: typeof API_SCHEMA;
94
+ readonly version: typeof API_VERSION;
95
+ readonly VERSION: string;
96
+ }
97
+
98
+ /**
99
+ * The two members of `pi.events` this package uses (`docs/extensions.md:1965-1972`). Both are
100
+ * optional so a host without a bus is a normal case, not a type error: no bus means the symbol is
101
+ * the only channel, which is exactly how this worked before.
102
+ */
103
+ export type BridgeEventUnsubscribe = () => void;
104
+
105
+ export interface BridgeEventBus {
106
+ emit?(channel: string, data: unknown): void;
107
+ on?(channel: string, handler: (data: unknown) => void): BridgeEventUnsubscribe | void;
108
+ }
109
+
110
+ /** The one payload every announcement carries; frozen like the published object. */
111
+ const READY_PAYLOAD: BridgeReadyPayload = Object.freeze({
112
+ schema: API_SCHEMA,
113
+ version: API_VERSION,
114
+ VERSION,
115
+ });
116
+
117
+ /**
118
+ * Bookkeeping for "one announcement per process", keyed by a symbol so two copies of this module
119
+ * share it, exactly like the slot and the skew notice.
120
+ */
121
+ const READY_KEY: symbol = Symbol.for("gentle-shell-bridge/api/v1.ready");
122
+
123
+ /** Bookkeeping for "one skew notice per process", kept off module scope for the same reason as the bus. */
124
+ const WARNED_KEY: symbol = Symbol.for("gentle-shell-bridge/api/v1.warned");
125
+
126
+ /** The object published at `BRIDGE_API_KEY`. */
127
+ export interface BridgeApi {
128
+ readonly schema: typeof API_SCHEMA;
129
+ readonly version: typeof API_VERSION;
130
+ /** The publishing release, e.g. `"0.2.0"`. Informational. */
131
+ readonly VERSION: string;
132
+ readonly registerRows: typeof registerRows;
133
+ readonly registerSection: typeof registerSection;
134
+ /**
135
+ * Card styles (S1). Absent only on an object published by a copy that predates this surface: the
136
+ * slot is first-wins, so a mixed-copy process can hand back the older object. The shape gate does
137
+ * NOT demand it, deliberately — an older object is still a usable bridge for rows, sections and
138
+ * the store, and a plugin that needs card styles checks `typeof api.registerCardStyle ===
139
+ * "function"` before using it. Demanding it here would turn a working bridge into "absent" for
140
+ * every row-only plugin.
141
+ */
142
+ readonly registerCardStyle?: typeof registerCardStyle;
143
+ /**
144
+ * Transcript transforms (S1). Optional for the same reason as `registerCardStyle`: the slot is
145
+ * first-wins, so a mixed-copy process can hand back an object published before this surface. A
146
+ * plugin that needs the pipeline checks `typeof api.registerTransform === "function"`; demanding
147
+ * it in the gate would turn a working bridge into "absent" for every row-only plugin.
148
+ */
149
+ readonly registerTransform?: typeof registerTransform;
150
+ /**
151
+ * A repaint of what the host draws (T4, S13): one DIFFERENTIAL frame, `requestRender()` with no
152
+ * argument, after bumping the host's sidebar revision. It does NOT invalidate the component tree and
153
+ * does NOT force a full redraw: measured on a 600-child transcript with real pi components, that cost
154
+ * 753 ms and 6.9 MB per switch against 20 ms for the differential frame, because invalidating clears
155
+ * every Markdown cache. A design change still reaches the cards ALREADY on screen because the design
156
+ * wrapper re-applies the live selection to the host's rows on every render pass.
157
+ *
158
+ * Returns what the diagnostics record holds as the last repaint, and never throws — with no host
159
+ * captured yet the request is reported as `unavailable` with its reason.
160
+ *
161
+ * Optional for the same reason as `registerCardStyle`: the slot is first-wins, so a mixed-copy
162
+ * process can hand back an object published before this member existed. A plugin that needs it
163
+ * checks `typeof api.requestRepaint === "function"`; demanding it in the gate would turn a working
164
+ * bridge into "absent" for every plugin that does not.
165
+ */
166
+ readonly requestRepaint?: typeof requestRepaint;
167
+ /**
168
+ * A card DESIGN for one tool name (S4, S5, S7): the bridge owns the single
169
+ * `pi.registerToolRenderer` resolver and fans it out to every design a plugin registers here. A
170
+ * design receives the rows the host's own card produced and returns the rows to draw, so the frame
171
+ * stays the host's.
172
+ *
173
+ * Optional for the same reason as `registerCardStyle`: the slot is first-wins, so a mixed-copy
174
+ * process can hand back an object published before this member existed. A plugin that needs it
175
+ * checks `typeof api.registerToolDesign === "function"`; demanding it in the gate would turn a
176
+ * working bridge into "absent" for every plugin that does not register a design.
177
+ */
178
+ readonly registerToolDesign?: typeof registerToolDesign;
179
+ /**
180
+ * What a tool's card is drawing RIGHT NOW (S6/D4): `{ kind: "native" }` for the host's own card,
181
+ * `{ kind: "design", design }` for the design on screen, `{ kind: "missing", id }` when the design
182
+ * the line names is gone, and `{ kind: "not-covered", id }` when the line's value is a design that
183
+ * does not paint this tool. The same answer the bridge's own card wrapper acts on, so a plugin that
184
+ * paints its own chrome for a tool can gate on the user's switch instead of parsing the store file
185
+ * and re-deriving the rule.
186
+ *
187
+ * Pure read, and it never throws: an unreadable selection reads as `native`. It costs ONE
188
+ * persisted-selection read per call — exactly what one render pass already pays (`./tool-design-wiring.ts`),
189
+ * so a caller may ask on every frame for the tool it is painting. Asking for every tool on every
190
+ * frame multiplies that count, and nothing here caches the answer for you.
191
+ *
192
+ * Optional for the same reason as `registerCardStyle`: the slot is first-wins, so a mixed-copy
193
+ * process can hand back an object published before this member existed. A plugin that needs it
194
+ * checks `typeof api.resolveToolDesignSelection === "function"` first.
195
+ */
196
+ readonly resolveToolDesignSelection?: typeof resolveToolDesignSelection;
197
+ /**
198
+ * A card DESIGN for one Pi custom message type (S1, S2, S3): the rows of the host's own message
199
+ * renderer in, the rows to draw out. A type with NO host renderer hands the design no rows
200
+ * (`[]`) and the design owns the box; a type that HAS one keeps it, and the design only rewrites
201
+ * its rows, so `float`/`neon` stay the host's. Nothing is installed for a type nobody claimed, so
202
+ * Pi's own output for it is byte-identical (S4).
203
+ *
204
+ * The bridge does not register anything into Pi's `registerMessageRenderer` map: that map belongs
205
+ * to the extension that registered, and the runner answers the FIRST renderer in load order with
206
+ * no `next()` chain. The bridge adopts the renderer Pi already resolved onto each message instead,
207
+ * which is why a message mounted before the first conversation pass is reached on the next one.
208
+ *
209
+ * Optional for the same reason as `registerCardStyle`: the slot is first-wins, so a mixed-copy
210
+ * process can hand back an object published before this member existed. A plugin that needs it
211
+ * checks `typeof api.registerMessageDesign === "function"`; demanding it in the gate would turn a
212
+ * working bridge into "absent" for every plugin that does not register one.
213
+ */
214
+ readonly registerMessageDesign?: typeof registerMessageDesign;
215
+ readonly createStore: typeof createStore;
216
+ }
217
+
218
+ function apiHost(): Record<symbol, unknown> {
219
+ // SAFETY: `globalThis` accepts symbol keys, and every write to these slots happens in this module
220
+ // behind the shape checks below.
221
+ return globalThis as unknown as Record<symbol, unknown>;
222
+ }
223
+
224
+ interface WarnedState {
225
+ skew: boolean;
226
+ }
227
+
228
+ /** One announcement per process, no matter how many copies publish or how often they ask. */
229
+ interface ReadyState {
230
+ announced: boolean;
231
+ }
232
+
233
+ /**
234
+ * The process-global state for a symbol-keyed flag, created on first use. A foreign object at the
235
+ * key is replaced by a fresh one: this state belongs to this package alone, and it carries nothing
236
+ * a consumer reads.
237
+ */
238
+ function flagState<T extends object>(key: symbol, shape: (candidate: Partial<T>) => boolean, created: T): T {
239
+ const host = apiHost();
240
+ const existing = host[key];
241
+ if (typeof existing === "object" && existing !== null) {
242
+ const candidate = existing as Partial<T>;
243
+ if (shape(candidate)) return candidate as T;
244
+ }
245
+ host[key] = created;
246
+ return created;
247
+ }
248
+
249
+ function warnedState(): WarnedState {
250
+ return flagState<WarnedState>(
251
+ WARNED_KEY,
252
+ (candidate) => typeof candidate.skew === "boolean",
253
+ { skew: false },
254
+ );
255
+ }
256
+
257
+ function readyState(): ReadyState {
258
+ return flagState<ReadyState>(
259
+ READY_KEY,
260
+ (candidate) => typeof candidate.announced === "boolean",
261
+ { announced: false },
262
+ );
263
+ }
264
+
265
+ /** The schema and version an incompatible object actually carries, for the notice. */
266
+ function foreignShape(): { schema: string; version: string } {
267
+ // The object is another plugin's, so reading it can throw (an accessor): describing it must never
268
+ // be the reason this package fails to load.
269
+ const read = (object: Record<string, unknown>, field: string): string => {
270
+ try {
271
+ const value = object[field];
272
+ return typeof value === "string" || typeof value === "number" ? String(value) : "none";
273
+ } catch {
274
+ return "unreadable";
275
+ }
276
+ };
277
+ const existing = apiHost()[BRIDGE_API_KEY];
278
+ const object = typeof existing === "object" && existing !== null ? (existing as Record<string, unknown>) : {};
279
+ return { schema: read(object, "schema"), version: read(object, "version") };
280
+ }
281
+
282
+ /** One clear notice per process, no matter how many copies ask. */
283
+ function warnSkewOnce(): void {
284
+ const state = warnedState();
285
+ if (state.skew) return;
286
+ state.skew = true;
287
+ const found = foreignShape();
288
+ recordNotice(
289
+ `odd-worktree: another plugin already published an incompatible object on ` +
290
+ `${String(BRIDGE_API_KEY)} — schema "${found.schema}", version "${found.version}" — so ` +
291
+ "odd-worktree's sidebar sections, the Customize rows, the card designs and its other " +
292
+ "surfaces stay off. The slot is left exactly as it is and treated as absent; this notice is " +
293
+ "recorded once per process.",
294
+ "warning",
295
+ );
296
+ }
297
+
298
+ /**
299
+ * The shape gate: the schema string, `version === 1`, and the three members a consumer calls.
300
+ * Anything else — another library's object, a future major version, a partial object — is absent,
301
+ * never an error.
302
+ */
303
+ export function isBridgeApi(value: unknown): value is BridgeApi {
304
+ if (typeof value !== "object" || value === null) return false;
305
+ const candidate = value as Record<string, unknown>;
306
+ // The slot's object may be another plugin's, and any of these reads can be an accessor that throws:
307
+ // that makes it "not this API", never a reason for the loading package to fail.
308
+ try {
309
+ return (
310
+ candidate.schema === API_SCHEMA &&
311
+ candidate.version === API_VERSION &&
312
+ typeof candidate.registerRows === "function" &&
313
+ typeof candidate.registerSection === "function" &&
314
+ typeof candidate.createStore === "function"
315
+ );
316
+ } catch {
317
+ return false;
318
+ }
319
+ }
320
+
321
+ /** The object this copy publishes when it owns the slot (or when the slot is unusable). */
322
+ const LOCAL_API: BridgeApi = Object.freeze({
323
+ schema: API_SCHEMA,
324
+ version: API_VERSION,
325
+ VERSION,
326
+ registerRows,
327
+ registerSection,
328
+ registerCardStyle,
329
+ registerTransform,
330
+ requestRepaint,
331
+ registerToolDesign,
332
+ resolveToolDesignSelection,
333
+ registerMessageDesign,
334
+ createStore,
335
+ });
336
+
337
+ /** The slot's object when it passes the gate; `undefined` when it is absent or incompatible. */
338
+ function compatibleApi(): BridgeApi | undefined {
339
+ const existing = apiHost()[BRIDGE_API_KEY];
340
+ if (existing === undefined) return undefined;
341
+ if (isBridgeApi(existing)) return existing;
342
+ warnSkewOnce();
343
+ return undefined;
344
+ }
345
+
346
+ /**
347
+ * The validated published object as the slot holds it RIGHT NOW, or `undefined`.
348
+ *
349
+ * This is the whole handshake for a plugin that imports the package and is loaded after it. Call it
350
+ * from a `session_start` handler: an object means register now. `undefined` means nothing is
351
+ * published yet — which is "not yet", not necessarily "not installed", because Pi may load your
352
+ * plugin before this package. Use `onBridgeApi(handler, pi.events)` when both orders have to work;
353
+ * `bridgeApi()` itself never waits, defers or retries.
354
+ */
355
+ export function bridgeApi(): BridgeApi | undefined {
356
+ return compatibleApi();
357
+ }
358
+
359
+ /**
360
+ * Publish this copy's API object.
361
+ *
362
+ * Runs at module load, so loading the package — through `./extension.ts` or `./index.ts` — makes
363
+ * the API available before any `session_start`. First wins: a valid object already in the slot is
364
+ * kept and returned untouched. An incompatible object is kept too (never reset), and this copy's
365
+ * own object is returned so its own extension can still register through the same bus.
366
+ */
367
+ export function publishBridgeApi(): BridgeApi {
368
+ const host = apiHost();
369
+ const existing = host[BRIDGE_API_KEY];
370
+ if (existing === undefined) {
371
+ host[BRIDGE_API_KEY] = LOCAL_API;
372
+ return LOCAL_API;
373
+ }
374
+ if (isBridgeApi(existing)) return existing;
375
+ warnSkewOnce();
376
+ return LOCAL_API;
377
+ }
378
+
379
+ /**
380
+ * Test-only seam: forget the published object, the once-per-process notice flag and the
381
+ * announcement flag. Clearing the published object is what lets a test model "the bridge is not
382
+ * installed"; clearing the announcement flag is what lets one process prove "once" twice. The
383
+ * extension never calls this. Deliberately not re-exported from `src/index.ts`.
384
+ */
385
+ export function resetBridgeApiForTests(): void {
386
+ const host = apiHost();
387
+ delete host[BRIDGE_API_KEY];
388
+ delete host[WARNED_KEY];
389
+ delete host[READY_KEY];
390
+ }
391
+
392
+ // ---------------------------------------------------------------------------------------------
393
+ // The announcement: how a plugin loaded BEFORE the package learns about it
394
+ // ---------------------------------------------------------------------------------------------
395
+
396
+ /** The `emit` member of a bus-shaped object, bound to it, or `undefined` when unusable. */
397
+ function busEmitter(events: unknown): ((channel: string, data: unknown) => void) | undefined {
398
+ if (typeof events !== "object" || events === null) return undefined;
399
+ const emit = (events as BridgeEventBus).emit;
400
+ if (typeof emit !== "function") return undefined;
401
+ return (channel, data) => {
402
+ emit.call(events, channel, data);
403
+ };
404
+ }
405
+
406
+ /** The `on` member of a bus-shaped object, bound to it, or `undefined` when unusable. */
407
+ function busListener(
408
+ events: unknown,
409
+ ): ((channel: string, handler: (data: unknown) => void) => BridgeEventUnsubscribe | void) | undefined {
410
+ if (typeof events !== "object" || events === null) return undefined;
411
+ const on = (events as BridgeEventBus).on;
412
+ if (typeof on !== "function") return undefined;
413
+ return (channel, handler) => on.call(events, channel, handler);
414
+ }
415
+
416
+ /**
417
+ * Announce this process's bridge, on Pi's cross-extension bus, at most once.
418
+ *
419
+ * Called from the extension entry — the first moment `pi.events` exists — right after the module
420
+ * load that published the object. Rules, all of them observable in the tests:
421
+ *
422
+ * - **once per process**, across package copies: the flag lives on `globalThis`, like the slot;
423
+ * - **never for an incompatible slot**: a process whose slot holds another library's payload (or
424
+ * another major) has no bridge to announce, and telling plugins to look again would only send
425
+ * them to an object that is absent;
426
+ * - **silent without a bus**: Pi may have no `pi.events` in a bare harness; the symbol still works
427
+ * for any plugin that reads it, so nothing is reported and nothing throws.
428
+ *
429
+ * Returns whether this call emitted.
430
+ */
431
+ export function announceBridgeReady(events: unknown): boolean {
432
+ const emit = busEmitter(events);
433
+ if (emit === undefined) return false;
434
+ const state = readyState();
435
+ if (state.announced) return false;
436
+ // The announcement says "the slot is usable now": an incompatible slot is never announced.
437
+ if (compatibleApi() === undefined) return false;
438
+ state.announced = true;
439
+ try {
440
+ emit(BRIDGE_READY_EVENT, READY_PAYLOAD);
441
+ } catch {
442
+ // A bus that throws cannot un-announce the process: the flag stays set, so `once` holds even
443
+ // when the delivery failed. Nothing is written to the terminal.
444
+ }
445
+ return true;
446
+ }
447
+
448
+ /** What a consumer does with the published object. */
449
+ export type BridgeApiHandler = (api: BridgeApi) => void;
450
+
451
+ /**
452
+ * Serve a plugin the published API, now or when it is announced.
453
+ *
454
+ * This is the helper form of the corrected timing rule:
455
+ *
456
+ * - **the object is already published** (this package loaded first): the handler runs immediately, in
457
+ * the same turn, and nothing is subscribed — calling it twice cannot leak a listener;
458
+ * - **it is not published yet** (the plugin loaded first, the real defect): the handler runs when the
459
+ * bridge announces itself, at most once per subscription, and the listener detaches itself.
460
+ *
461
+ * `events` is `pi.events`. Without a bus the helper cannot hear a later publication: it returns a
462
+ * no-op disposer and never calls the handler, which is the honest answer for a host with no bus.
463
+ * A handler that throws is contained: one plugin's failure must not break the announcement for the
464
+ * next listener.
465
+ */
466
+ export function onBridgeApi(handler: BridgeApiHandler, events?: unknown): () => void {
467
+ /** One plugin's throw is its own: the bus must survive to notify the next listener. */
468
+ const deliver = (api: BridgeApi): void => {
469
+ try {
470
+ handler(api);
471
+ } catch {
472
+ // Contained on purpose (see the contract: nothing a plugin does may throw into Pi's render).
473
+ }
474
+ };
475
+
476
+ const existing = bridgeApi();
477
+ if (existing !== undefined) {
478
+ deliver(existing);
479
+ return () => {};
480
+ }
481
+
482
+ const listen = busListener(events);
483
+ if (listen === undefined) return () => {};
484
+
485
+ let active = true;
486
+ let unsubscribe: BridgeEventUnsubscribe | void;
487
+
488
+ const detach = (): void => {
489
+ const off = unsubscribe;
490
+ unsubscribe = undefined;
491
+ if (typeof off !== "function") return;
492
+ try {
493
+ off();
494
+ } catch {
495
+ // A disposer that throws cannot resurrect the subscription.
496
+ }
497
+ };
498
+
499
+ const onReady = (): void => {
500
+ if (!active) return;
501
+ const api = bridgeApi();
502
+ if (api === undefined) return; // an announcement not backed by a usable slot
503
+ active = false;
504
+ detach();
505
+ deliver(api);
506
+ };
507
+
508
+ try {
509
+ unsubscribe = listen(BRIDGE_READY_EVENT, onReady);
510
+ } catch {
511
+ return () => {};
512
+ }
513
+
514
+ return () => {
515
+ active = false;
516
+ detach();
517
+ };
518
+ }
519
+
520
+ // The publishing point: loading this module publishes the API. `./extension.ts` imports it, so the
521
+ // object exists as soon as the package has loaded at all — and, when the package loads after a
522
+ // plugin, `announceBridgeReady` from the same entry is how that plugin hears about it.
523
+ publishBridgeApi();
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Arm lifecycle (S3 bullet 1, S4): one entry point that picks a backend and arms it.
3
+ *
4
+ * Pi keeps ONE `ctx.ui` object per runner but rebuilds it on every bind
5
+ * (`runner.ts:895-898`, `:573`, `:577-587`), so the bridge arms from `session_start` — possibly
6
+ * more than once per process, and against a fresh UI object each rebind. Arming is therefore
7
+ * idempotent per UI object: the capture backend marks the target it wrapped, and the hook backend
8
+ * marks the host registry it pushed into.
9
+ *
10
+ * Backend choice, in order:
11
+ * 1. the host registry (`installHookBackend`) when it exists and its shape is usable — nothing is
12
+ * patched, which is the whole reason to prefer it;
13
+ * 2. otherwise the proven capture backend. A present-but-unusable registry is reported as
14
+ * `fallback-capture` with `reason: "hook-unusable"` instead of being ignored.
15
+ *
16
+ * Nothing here runs at import time: no backend arms itself, so importing the module (or the
17
+ * package entry that will call it) has no side effect on the host.
18
+ */
19
+
20
+ import { disableCaptureBackend, installCaptureBackend } from "./capture.ts";
21
+ import { installHookBackend } from "./hook.ts";
22
+
23
+ /** Which interception is active after arming. */
24
+ export type ArmBackend = "hook" | "capture" | "none";
25
+
26
+ /**
27
+ * What arming decided. `status` (S6) reports this verbatim, so every branch that ends in "no rows
28
+ * appeared" has a name here.
29
+ */
30
+ export type ArmOutcome =
31
+ | "hooked"
32
+ | "capture-armed"
33
+ | "already-armed"
34
+ | "fallback-capture"
35
+ | "no-ui";
36
+
37
+ export type ArmReason = "hook-unusable" | "ui-missing" | "custom-missing";
38
+
39
+ export interface ArmResult {
40
+ outcome: ArmOutcome;
41
+ backend: ArmBackend;
42
+ /** Present when nothing armed cleanly, or when arming fell back to the capture backend. */
43
+ reason?: ArmReason;
44
+ }
45
+
46
+ /**
47
+ * Arm the bridge against a `ctx.ui`-shaped object and report what happened. Safe to call on every
48
+ * `session_start`, and safe to call with a missing UI context (reported, never thrown).
49
+ */
50
+ export function armBridge(ui: unknown): ArmResult {
51
+ const hook = installHookBackend();
52
+ if (hook.installed) {
53
+ // An earlier arm may have wrapped a UI object that is still live. Disable the previous path
54
+ // before the hook becomes active, so one menu cannot receive two copies of the rows.
55
+ disableCaptureBackend();
56
+ return { outcome: "hooked", backend: "hook" };
57
+ }
58
+
59
+ // Any present-but-unusable registry, or any failed installation into one, gets the proven
60
+ // backend rather than silence. Only "no registry at all" is a clean capture arm.
61
+ const fallback: ArmReason | undefined = hook.outcome === "no-hook" ? undefined : "hook-unusable";
62
+ const capture = installCaptureBackend(ui);
63
+
64
+ if (capture.armed) {
65
+ return fallback === undefined
66
+ ? { outcome: "capture-armed", backend: "capture" }
67
+ : { outcome: "fallback-capture", backend: "capture", reason: fallback };
68
+ }
69
+
70
+ if (capture.outcome === "already-armed") {
71
+ return fallback === undefined
72
+ ? { outcome: "already-armed", backend: "capture" }
73
+ : { outcome: "already-armed", backend: "capture", reason: fallback };
74
+ }
75
+
76
+ // Nothing to wrap: distinguish "no UI context at all" from "a UI without a customize surface".
77
+ const hasUi = ui !== null && typeof ui === "object";
78
+ return {
79
+ outcome: "no-ui",
80
+ backend: "none",
81
+ reason: hasUi ? "custom-missing" : "ui-missing",
82
+ };
83
+ }