@juicesharp/rpiv-btw 1.20.0 → 2.1.0

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/README.md CHANGED
@@ -1,94 +1,103 @@
1
- # rpiv-btw
1
+ # @juicesharp/rpiv-btw
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@juicesharp/rpiv-btw.svg)](https://www.npmjs.com/package/@juicesharp/rpiv-btw)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
2
5
 
3
6
  <div align="center">
4
7
  <a href="https://github.com/juicesharp/rpiv-mono/tree/main/packages/rpiv-btw">
5
- <picture>
6
- <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/cover.png" alt="rpiv-btw cover" width="50%">
7
- </picture>
8
+ <img src="https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/cover.png" alt="rpiv-btw cover art: a Pi transcript with a /btw side question answered below it, labelled ephemeral and never written" width="50%">
8
9
  </a>
9
10
  </div>
10
11
 
11
- Ask a side question without polluting the main conversation. `rpiv-btw` adds `/btw <question>` to [Pi Agent](https://github.com/badlogic/pi-mono) - a lightweight side agent picks up a **read-only clone** of your current conversation and answers in a panel at the bottom of the terminal. The side agent remembers its own `/btw` thread for follow-ups, while your main chat keeps going - its transcript is never polluted.
12
-
13
- ![The /btw side-question panel at the bottom of the Pi terminal](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/overlay.jpg)
12
+ Ask a side question without polluting the main conversation. `rpiv-btw` adds
13
+ `/btw <question>` to [Pi Agent](https://github.com/badlogic/pi-mono) — your same
14
+ primary model answers in a panel at the bottom of the terminal, using a read-only
15
+ clone of the current conversation as context. The answer never enters the
16
+ transcript and never touches disk.
14
17
 
15
18
  ## Install
16
19
 
17
- ```bash
20
+ ```sh
18
21
  pi install npm:@juicesharp/rpiv-btw
19
22
  ```
20
23
 
21
- Restart your Pi Agent session, then type `/btw` followed by your question:
24
+ Restart your Pi session.
25
+
26
+ ## Quick start
27
+
28
+ Type `/btw` followed by your question:
22
29
 
23
30
  ```
24
31
  /btw why did we switch from sockets to SSE last week?
25
32
  ```
26
33
 
27
- ## Usage
34
+ A panel opens at the bottom of the terminal with your question on a banner, a `…`
35
+ while the model works, and the answer when it arrives. Prior `/btw` questions from
36
+ this session are listed under the banner, so follow-ups have context.
28
37
 
29
- ### What you see
38
+ `/btw` uses whatever model is already driving your session — there is nothing to
39
+ pick, but Pi needs an active model with working credentials (`/login`).
30
40
 
31
- A panel opens at the bottom of the terminal with:
32
-
33
- - your question on a banner,
34
- - a `…` while the model is thinking,
35
- - the answer when it arrives.
36
-
37
- Prior `/btw` questions from the same session appear above the banner, so follow-ups have context.
38
-
39
- ### Keys
41
+ ![The /btw panel at the bottom of a Pi Agent terminal, showing the echoed question, a multi-paragraph answer, and the key-hint footer](https://raw.githubusercontent.com/juicesharp/rpiv-mono/main/packages/rpiv-btw/docs/overlay.jpg)
40
42
 
41
43
  | Key | Action |
42
- |---|---|
43
- | `↑` / `↓` | Scroll the panel (when its content overflows) |
44
- | `x` | Clear this session's `/btw` history (hidden until you have a prior entry) |
45
- | `Esc` | Close the panel; cancel the request if it's still running |
46
-
47
- ### What the model sees
48
-
49
- The side agent is a fresh, tool-less instance of the same primary model, handed a read-only clone of your current conversation. When you press enter, `/btw` sends it:
50
-
51
- 1. A snapshot of your main conversation so far - so it knows what you've been working on. The side agent only reads the clone, so nothing it does pollutes your main transcript.
52
- 2. Your previous `/btw` questions and answers in this session - so follow-ups make sense.
53
- 3. The question you just typed.
54
-
55
- ### What it does *not* do
56
-
57
- - Your main conversation is never polluted. The side answer lives only in the panel and in memory - it's not written to the agent's transcript or to disk.
58
- - `/btw` has no tools. The model answers in plain text.
59
- - History is lost when you exit Pi Agent. Your main session is unaffected.
60
-
61
- ## Commands
62
-
63
- | Command | Description |
64
- |---|---|
65
- | `/btw <question>` | Ask a side question without polluting the main conversation |
66
-
67
- ## Architecture
68
-
69
- ```
70
- rpiv-btw/
71
- ├── index.ts - extension entry; registers command + hooks
72
- ├── btw.ts - state, message threading, model call
73
- ├── btw-ui.ts - bottom panel renderer
74
- └── prompts/
75
- └── btw-system.txt - system prompt for the side call
76
- ```
77
-
78
- Pi Agent discovers the extension via `"pi": { "extensions": ["./index.ts"] }` in `package.json`.
44
+ | --- | --- |
45
+ | `↑` / `↓` | Scroll the panel whenever content overflows — the hint appears once the answer arrives |
46
+ | `x` | Clear this session's `/btw` history — hint shown only when you have prior entries |
47
+ | `Esc` | Dismiss the panel, cancelling the call if it is still running |
48
+
49
+ ## What you get
50
+
51
+ - **Nothing leaks into the main chat** — the answer is drawn in an overlay, never
52
+ emitted as an agent message, never written to the transcript, never written to disk.
53
+ - **The side question already knows your work** — it is handed a read-only clone
54
+ of the current conversation branch, so you do not re-explain context.
55
+ - **Follow-ups have their own thread** — every `/btw` turn in a session is replayed
56
+ into the next one, so the side conversation remembers itself.
57
+ - **`Esc` cancels only the side question** — cancelling it never interrupts what
58
+ the main session is doing.
59
+ - **Survives `/new`, `/fork`, `/resume`, `/reload`** — history is held in the
60
+ running Pi process and clears when Pi exits.
61
+ - **Correct after compaction** — the context snapshot is rebuilt whenever the
62
+ conversation is compacted or re-branched, so a later `/btw` never answers off a
63
+ stale view.
64
+ - **No tools, plain text** — a side question cannot edit a file or run a command.
65
+
66
+ ## Reference
67
+
68
+ - [Context model](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-btw/docs/context-model.md) — exactly what each `/btw` call
69
+ sends to the model: the branch snapshot and its invalidation rules, session
70
+ history threading, the cross-session question hint, and the no-pollution
71
+ guarantees.
72
+ - [Architecture](https://github.com/juicesharp/rpiv-mono/blob/main/packages/rpiv-btw/docs/architecture.md) — modules, registered command and
73
+ hooks, overlay layout and key handling, process-scoped state, Pi host-version
74
+ tolerance, and the full error-message list.
75
+
76
+ ## Requirements
77
+
78
+ - **An interactive terminal.** `/btw` refuses to run without a UI — it is not
79
+ available under `pi --print` or RPC.
80
+ - **An active primary model with resolvable credentials.** Any provider works.
79
81
 
80
82
  ## Troubleshooting
81
83
 
82
84
  | Symptom | Cause | Fix |
83
- |---|---|---|
84
- | `/btw requires interactive mode` | Running in `pi --print …` or RPC mode | `/btw` needs a terminal - run Pi interactively |
85
- | `/btw requires an active model` | No primary model configured | Set one with `/login` or edit `~/.pi/agent/models.json` |
86
- | Panel opens but answer never arrives | Model call failed or network dropped | Press `Esc` to cancel; check your provider credentials |
87
- | History missing after restart | Expected - no disk persistence | `/btw` history is per-Pi-process by design |
85
+ | --- | --- | --- |
86
+ | `/btw requires interactive mode` | Running under `pi --print …` or RPC | Run Pi interactively |
87
+ | `/btw requires an active model` | No primary model configured | Set one with `/login`, or edit Pi's own `~/.pi/agent/models.json` |
88
+ | `/btw model (…) has no API key available.` | Credentials for the active model do not resolve | Re-authenticate that provider |
89
+ | `Usage: /btw <question>` | `/btw` ran with no argument | Put the question on the same line |
90
+ | Pressing `X` does nothing | Only lowercase `x` is bound to clear history | Press `x` |
91
+ | History gone after restarting Pi | By design — state is process-scoped, never written to disk | Nothing to fix; your main session is unaffected |
92
+
93
+ ## Related
94
+
95
+ - [`@juicesharp/rpiv-pi`](https://www.npmjs.com/package/@juicesharp/rpiv-pi) — the
96
+ umbrella package. It does not install `rpiv-btw`; install this one yourself when
97
+ you want `/btw`.
98
+ - [juicesharp/rpiv-mono](https://github.com/juicesharp/rpiv-mono#readme) — the rest
99
+ of the rpiv family.
88
100
 
89
101
  ## License
90
102
 
91
- [![npm version](https://img.shields.io/npm/v/@juicesharp/rpiv-btw.svg)](https://www.npmjs.com/package/@juicesharp/rpiv-btw)
92
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
93
-
94
- MIT
103
+ MIT — see [LICENSE](LICENSE).
package/btw.ts CHANGED
@@ -9,13 +9,7 @@
9
9
 
10
10
  import { readFileSync } from "node:fs";
11
11
  import { fileURLToPath } from "node:url";
12
- import {
13
- type AssistantMessage,
14
- completeSimple,
15
- type Message,
16
- type StopReason,
17
- type UserMessage,
18
- } from "@earendil-works/pi-ai";
12
+ import type { AssistantMessage, Message, StopReason, UserMessage } from "@earendil-works/pi-ai";
19
13
  import {
20
14
  convertToLlm,
21
15
  type ExtensionAPI,
@@ -24,6 +18,7 @@ import {
24
18
  type SessionEntry,
25
19
  } from "@earendil-works/pi-coding-agent";
26
20
  import { showBtwOverlay } from "./btw-ui.js";
21
+ import { loadCompleteSimple } from "./pi-compat.js";
27
22
 
28
23
  // ---------------------------------------------------------------------------
29
24
  // Constants — flat named consts, grouped by concern (advisor pattern, b9428e9)
@@ -230,6 +225,7 @@ export async function executeBtw(
230
225
  const systemPrompt = buildSystemPrompt();
231
226
 
232
227
  try {
228
+ const completeSimple = await loadCompleteSimple();
233
229
  const response = await completeSimple(
234
230
  model,
235
231
  { systemPrompt, messages, tools: [] },
@@ -0,0 +1,161 @@
1
+ # rpiv-btw architecture
2
+
3
+ Module layout, what the extension registers with Pi, how the overlay is laid out,
4
+ how state is stored, and how the package tolerates different Pi host versions.
5
+
6
+ ## Modules
7
+
8
+ ```
9
+ rpiv-btw/
10
+ ├── index.ts — extension entry; registers the command + 3 hooks
11
+ ├── btw.ts — state, snapshotting, message threading, the model call
12
+ ├── btw-ui.ts — bottom-anchored overlay component and key handling
13
+ ├── pi-compat.ts — host-version-tolerant loader for pi-ai's completeSimple
14
+ └── prompts/
15
+ └── btw-system.txt — system prompt for the side call
16
+ ```
17
+
18
+ Pi discovers the extension through the manifest block in `package.json`:
19
+
20
+ ```json
21
+ "pi": { "extensions": ["./index.ts"] }
22
+ ```
23
+
24
+ That is the entire registration surface. The package ships no skills, no agents,
25
+ no `bin`, and declares no `exports` or `main`. A test (`ship-manifest.test.ts`)
26
+ asserts that the published `files` list covers every production module.
27
+
28
+ ## What gets registered
29
+
30
+ One slash command:
31
+
32
+ | Command | Description string |
33
+ | --- | --- |
34
+ | `/btw <question>` | `Ask a side question without polluting the main conversation` |
35
+
36
+ Three lifecycle hooks:
37
+
38
+ | Event | Behavior |
39
+ | --- | --- |
40
+ | `message_end` | Snapshots the branch, only for assistant messages whose `stopReason` is not `toolUse` |
41
+ | `session_compact` | Invalidates this session's cached snapshot |
42
+ | `session_tree` | Invalidates this session's cached snapshot |
43
+
44
+ No tools are registered. No CLI flags are added.
45
+
46
+ ## State
47
+
48
+ All state lives on a single process-wide cell:
49
+
50
+ ```ts
51
+ export const BTW_STATE_KEY = Symbol.for("rpiv-btw");
52
+ ```
53
+
54
+ It holds two maps — `histories` and `snapshots` — both keyed by
55
+ `ctx.sessionManager.getSessionFile()`, with `memory:<sessionId>` as the fallback
56
+ key when there is no session file.
57
+
58
+ Using `globalThis` plus `Symbol.for()` (the same idiom OpenTelemetry uses for
59
+ cross-import-graph singletons) means the cell survives module re-import, so
60
+ `/btw` history outlives `/new`, `/fork`, `/resume`, and `/reload`. It is lost
61
+ when the Pi process exits — by design. Nothing is persisted to disk, and the
62
+ package reads no environment variables and no config files.
63
+
64
+ ## Overlay
65
+
66
+ `showBtwOverlay` mounts a `Component` through `ctx.ui.custom` with these options:
67
+
68
+ | Option | Value |
69
+ | --- | --- |
70
+ | `anchor` | `bottom-center` |
71
+ | `width` | `100%` |
72
+ | `maxHeight` | `85%` (`BTW_MAX_HEIGHT_RATIO = 0.85`) |
73
+ | `margin` | `{ left: 0, right: 0, bottom: 0 }` |
74
+
75
+ Render order, top to bottom:
76
+
77
+ ```
78
+ banner — your question on a themed stripe, padded to full width
79
+ (blank)
80
+ history — prior "/btw <q>" lines for this session
81
+ echo — "/btw <q>" for the current question
82
+ (blank)
83
+ answer — "…" while pending, the answer text, or the error in red
84
+ (blank)
85
+ footer — key hints
86
+ ```
87
+
88
+ History and echo use a 2-column left gutter; the answer body uses 4. The panel
89
+ grows upward with content. When the natural height exceeds
90
+ `floor(terminalRows × 0.85)` (terminal rows default to 24 if unknown, with a
91
+ floor of 4 rows), it clips from the top and `↑`/`↓` scroll that window —
92
+ offset `0` shows the newest content.
93
+
94
+ ### Keys and footer gates
95
+
96
+ | Key | Action | Matching |
97
+ | --- | --- | --- |
98
+ | `Esc` | Aborts the in-flight call and dismisses the overlay | `matchesKey` (ANSI + Kitty) |
99
+ | `↑` | Scroll up one row, clamped at 0 | `matchesKey` |
100
+ | `↓` | Scroll down one row, clamped to the overflow amount | `matchesKey` |
101
+ | `x` | Clears this session's `/btw` history and resets scroll | raw `data === "x"` — uppercase `X` is not bound |
102
+
103
+ | Footer hint | Shown when |
104
+ | --- | --- |
105
+ | `↑/↓ to scroll` | the call is no longer pending (an answer or error has arrived) |
106
+ | `x to clear history` | this session has at least one prior `/btw` turn |
107
+ | `Esc to dismiss` | always |
108
+
109
+ Hints are joined with `" · "` and truncated to the panel width.
110
+
111
+ ## Host-version tolerance
112
+
113
+ pi-ai resolves at runtime against the *host's* copy (all three pi peers are
114
+ declared `"*"`), and pi moved the global dispatch API to a `/compat` entrypoint
115
+ in 0.80.1. `pi-compat.ts` therefore resolves `completeSimple` lazily:
116
+
117
+ 1. `import("@earendil-works/pi-ai/compat")` — pi >= 0.80.1.
118
+ 2. On a **module-resolution** failure only, fall back to
119
+ `import("@earendil-works/pi-ai")` — pi <= 0.79.x, which has no `/compat`
120
+ subpath at all.
121
+
122
+ The fallback is gated on the error codes `ERR_PACKAGE_PATH_NOT_EXPORTED`,
123
+ `ERR_MODULE_NOT_FOUND`, and `MODULE_NOT_FOUND`, walked down the `cause` chain
124
+ (bounded at 16 links, because ESM loaders and test mock layers nest the real
125
+ code). Any other `/compat` error — the entrypoint exists but throws at module
126
+ init — rethrows, so a real failure surfaces instead of being masked by a root
127
+ import that may not have the export.
128
+
129
+ If neither entrypoint exposes the function, the call fails with
130
+ `pi-ai does not expose completeSimple on /compat or the package root — unsupported host pi-ai version`.
131
+
132
+ `/compat` is documented upstream as temporary, so this module is the single place
133
+ to migrate when it is removed.
134
+
135
+ ## Messages and errors
136
+
137
+ Every user-visible string the package can produce:
138
+
139
+ | String | When |
140
+ | --- | --- |
141
+ | `/btw requires interactive mode` (error) | `ctx.hasUI` is false — `pi --print`, RPC |
142
+ | `Usage: /btw <question>` (warning) | the argument is empty or whitespace-only |
143
+ | `/btw requires an active model` (error) | there is no `ctx.model` |
144
+ | `/btw model (<provider>:<id>) is misconfigured: <err>` | credential lookup returned an error |
145
+ | `/btw model (<provider>:<id>) has no API key available.` | lookup succeeded but the API key is empty |
146
+ | `/btw call failed: <err ?? "unknown error">` | the completion returned `stopReason: "error"` |
147
+ | `/btw call threw: <message>` | the completion threw and the call was not aborted |
148
+ | `/btw returned no text content.` | the response contained no text parts |
149
+
150
+ The first three are `ctx.ui.notify` toasts raised before the overlay opens; the
151
+ rest render inside the overlay in the error style.
152
+
153
+ ## Boundaries
154
+
155
+ - **No runtime dependencies.** No `dependencies`, no `devDependencies` — only the
156
+ three `@earendil-works` peers.
157
+ - **No sibling imports at runtime.** `pi-compat.ts` deliberately duplicates
158
+ rpiv-core's `isModuleNotFound` rather than importing it, because the rpiv
159
+ packages never import each other at runtime.
160
+ - **Standalone.** rpiv-btw is excluded from `rpiv-pi`'s auto-install sibling list,
161
+ and a test asserts that exclusion.
@@ -0,0 +1,95 @@
1
+ # What `/btw` sends to the model
2
+
3
+ Exactly what every `/btw` call puts in front of your primary model, where each
4
+ piece comes from, and what is guaranteed never to leave the panel.
5
+
6
+ ## The request
7
+
8
+ Each `/btw` call is a single non-streaming completion against `ctx.model` — the
9
+ same primary model driving your session. There is no model picker and no
10
+ lighter-weight side model.
11
+
12
+ | Part | Value |
13
+ | --- | --- |
14
+ | Model | `ctx.model`, with credentials from `ctx.modelRegistry.getApiKeyAndHeaders(model)` |
15
+ | System prompt | the bundled `prompts/btw-system.txt`, plus the cross-session hint appendix |
16
+ | Messages | `[...branch clone, ...this-session /btw turns, your question]` |
17
+ | Tools | `[]` — none, always |
18
+ | Abort signal | a fresh `AbortController` owned by `/btw`, never `ctx.signal` |
19
+
20
+ ## The branch clone
21
+
22
+ The first block of messages is a read-only clone of your current session branch,
23
+ so you do not have to re-explain what you have been working on.
24
+
25
+ - The `message_end` hook takes the snapshot: it reads `ctx.sessionManager.getBranch()`
26
+ and converts it with `convertToLlm`.
27
+ - It snapshots **only** on `role === "assistant"` messages, and **only** when
28
+ `stopReason !== "toolUse"` — so mid-tool-call states never become the context.
29
+ - Snapshots are cached per session, keyed by `ctx.sessionManager.getSessionFile()`,
30
+ falling back to `memory:<sessionId>` when there is no session file.
31
+ - Cold start: if no `message_end` has fired yet, `/btw` reads the branch live
32
+ instead of using a cache.
33
+
34
+ ### Invalidation
35
+
36
+ The cached snapshot is deleted on both `session_compact` and `session_tree`, so a
37
+ `/btw` issued after compaction or a branch switch never answers off a stale view
38
+ of the conversation.
39
+
40
+ Auto-compaction races session disposal in pi-core: `session_compact` can fire
41
+ with an already-invalidated `ctx` proxy. `/btw` swallows only that specific stale
42
+ error (`stale after session replacement`) — the session being compacted has no
43
+ snapshot worth invalidating. Every other error propagates, because it is a bug.
44
+
45
+ ## The `/btw` history
46
+
47
+ After a successful answer, the turn is appended to this session's `/btw` history,
48
+ and every later `/btw` call in the same session replays that history between the
49
+ branch clone and your new question. Follow-ups therefore work: the side thread
50
+ has its own memory.
51
+
52
+ History stores the **actual** `UserMessage` and `AssistantMessage` object
53
+ references returned by the call — nothing is reconstructed or re-serialised.
54
+ Concatenated in a fixed order, this keeps the prompt prefix byte-identical
55
+ across calls, so provider-side prompt caching keeps hitting.
56
+
57
+ Press `x` in the overlay to clear this session's history. It is also dropped when
58
+ the Pi process exits.
59
+
60
+ ## The cross-session hint
61
+
62
+ The system prompt gets an appendix listing the last **10** `/btw` *question
63
+ strings* from **all** sessions in the current Pi process, oldest first, under the
64
+ heading `## Recent /btw questions across sessions (oldest first)`. Each is
65
+ whitespace-collapsed and truncated to 200 characters.
66
+
67
+ - Only your question text crosses sessions — never answers, never branch content.
68
+ - The system prompt tells the model to treat it as a pattern hint, useful only
69
+ when the side question is itself about recent topics or trends.
70
+ - Clearing a session's history with `x` removes its contributions to the hint.
71
+ - It lives on the same process-scoped state, so it is gone when Pi exits.
72
+
73
+ ## The system prompt
74
+
75
+ `prompts/btw-system.txt` tells the side call to:
76
+
77
+ - treat the primary conversation as background, not as work to continue — the
78
+ side question is self-contained, and it must not pick up a tool call mid-flight;
79
+ - answer directly and concisely, in compact bullets or short paragraphs;
80
+ - cite files, functions, and line numbers when grounding a claim in the context;
81
+ - say so briefly when the context is insufficient, rather than guessing;
82
+ - use no tools and reply in plain text only, even if prior assistant turns in the
83
+ context demonstrate tool use.
84
+
85
+ ## What never happens
86
+
87
+ - **No transcript entry.** The answer is rendered through `ctx.ui.custom` as an
88
+ overlay component. It is never emitted as an agent message.
89
+ - **No disk writes.** History and snapshots live on `globalThis[Symbol.for("rpiv-btw")]`.
90
+ The package's only filesystem access is one read of its own bundled prompt file
91
+ at module init.
92
+ - **No tool use.** The call runs with `tools: []`, so a side question cannot edit
93
+ a file or run a command even if it wanted to.
94
+ - **No effect on the main session.** `Esc` aborts the `/btw` controller only; the
95
+ main agent's signal is never touched.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-btw",
3
- "version": "1.20.0",
3
+ "version": "2.1.0",
4
4
  "description": "Pi extension. The /btw slash command, for putting a one-off side question to the same primary model without polluting the main conversation.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -32,7 +32,12 @@
32
32
  "index.ts",
33
33
  "btw.ts",
34
34
  "btw-ui.ts",
35
+ "pi-compat.ts",
35
36
  "prompts/",
37
+ "docs/",
38
+ "!docs/*.png",
39
+ "!docs/*.jpg",
40
+ "!docs/*.svg",
36
41
  "README.md",
37
42
  "LICENSE"
38
43
  ],
package/pi-compat.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Host-version-tolerant loader for pi-ai's `completeSimple`.
3
+ *
4
+ * Pi >= 0.80.1 moved the global dispatch API (`completeSimple` et al.) to the
5
+ * "@earendil-works/pi-ai/compat" entrypoint; hosts <= 0.79.x export it from
6
+ * the package root and have no /compat entrypoint at all. pi-ai resolves at
7
+ * runtime against the HOST's copy (peerDependency "*"), so neither path can
8
+ * be a static import — try /compat first, fall back to the root entrypoint.
9
+ *
10
+ * The fallback is reserved for RESOLUTION failures (the /compat subpath does
11
+ * not exist on this host); any other /compat error — the entrypoint exists but
12
+ * throws at module init — rethrows so the real failure surfaces at the call
13
+ * site instead of being masked by a root import that may lack the export.
14
+ *
15
+ * /compat is documented as temporary (deleted with pi's ModelManager
16
+ * migration); when that lands, this module is the single place to migrate.
17
+ */
18
+
19
+ type CompleteSimpleFn = typeof import("@earendil-works/pi-ai/compat").completeSimple;
20
+
21
+ /**
22
+ * Error codes meaning "the /compat entrypoint is not resolvable on this host":
23
+ * - `ERR_PACKAGE_PATH_NOT_EXPORTED` — Node's ESM resolver when the installed
24
+ * pi-ai (<= 0.79.x) resolves but has no "./compat" in its `exports` map —
25
+ * the code an old host actually produces.
26
+ * - `ERR_MODULE_NOT_FOUND` / `MODULE_NOT_FOUND` — Node's / jiti's resolver
27
+ * for an unresolvable module (jiti is what Pi loads `.ts` extensions with).
28
+ * Mirrors rpiv-core's `isModuleNotFound` (plus the subpath-export code) —
29
+ * duplicated because siblings never import each other at runtime.
30
+ */
31
+ const MODULE_NOT_FOUND_CODES = new Set(["ERR_PACKAGE_PATH_NOT_EXPORTED", "ERR_MODULE_NOT_FOUND", "MODULE_NOT_FOUND"]);
32
+
33
+ /** True for a module-resolution failure. Walks the `cause` chain — ESM loaders
34
+ * and tooling (vitest's mock layer, some bundlers) nest the real code under
35
+ * `.cause`. Bounded against pathological self-referential chains. */
36
+ function isModuleNotFound(err: unknown): boolean {
37
+ for (
38
+ let cur: unknown = err, depth = 0;
39
+ cur != null && depth < 16;
40
+ cur = (cur as { cause?: unknown }).cause, depth++
41
+ ) {
42
+ if (typeof cur === "object" && MODULE_NOT_FOUND_CODES.has((cur as { code?: unknown }).code as string)) {
43
+ return true;
44
+ }
45
+ }
46
+ return false;
47
+ }
48
+
49
+ export async function loadCompleteSimple(): Promise<CompleteSimpleFn> {
50
+ let mod: { completeSimple?: CompleteSimpleFn };
51
+ try {
52
+ mod = (await import("@earendil-works/pi-ai/compat")) as { completeSimple?: CompleteSimpleFn };
53
+ } catch (err) {
54
+ if (!isModuleNotFound(err)) throw err; // a real /compat failure must surface, not mask as a fallback
55
+ mod = (await import("@earendil-works/pi-ai")) as { completeSimple?: CompleteSimpleFn };
56
+ }
57
+ const completeSimple = mod.completeSimple;
58
+ if (typeof completeSimple !== "function") {
59
+ throw new Error(
60
+ "pi-ai does not expose completeSimple on /compat or the package root — unsupported host pi-ai version",
61
+ );
62
+ }
63
+ return completeSimple;
64
+ }