@roam-agent/roam-sdk 0.0.0-stage → 0.2.51
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/CHANGELOG.md +32 -0
- package/README.md +144 -2
- package/anthropic.js +75 -0
- package/api.d.ts +841 -0
- package/api.js +2280 -0
- package/bedrock-converse-stream.js +89 -0
- package/core/export-html/template.css +1085 -0
- package/core/export-html/template.html +56 -0
- package/core/export-html/template.js +2044 -0
- package/core/export-html/vendor/highlight.min.js +1213 -0
- package/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
- package/core/export-html/vendor/marked.min.js +79 -0
- package/github-copilot.js +2 -0
- package/image-resize-worker.js +2 -0
- package/kimi-coding.js +2 -0
- package/modes/interactive/assets/clankolas.png +0 -0
- package/modes/interactive/theme/dark.json +78 -0
- package/modes/interactive/theme/light.json +78 -0
- package/openai-codex.js +75 -0
- package/openrouter.js +75 -0
- package/package.json +42 -5
- package/radius.js +75 -0
- package/xai.js +2 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `createPlusAgentSessionRuntime()` now returns host-owned Bash execution alongside the upstream runtime: `runtime.executeBash(command, onChunk?, { id?, excludeFromContext?, operations? })` records the result in session context and `runtime.abortBash()` cancels in-flight commands. This is the stable embedding API for host-initiated commands such as a desktop composer's `!` runner; it bypasses the model tool-permission gate by design, so hosts remain responsible for user consent.
|
|
8
|
+
- The diagram extension (`roam-diagram`, shared core `packages/plus/src/extensions/diagram/`) joins `plusSdkExtensionFactories`: SDK sessions get the `draw_diagram` tool (structured JSON spec → layered layout → box-drawing ASCII in `details`, optional `file` write of a standalone HTML/SVG document), and the SDK surface re-exports the rendering pieces directly — `renderDiagramHtml(spec, options?)` for hosts that want self-contained HTML/SVG from a spec without a tool call, plus `layoutDiagram`, the `DiagramSpec`/`DiagramNode`/`DiagramEdge`/`DiagramShape`/`DiagramDetails` types, and `DiagramError`/`DIAGRAM_TOOL_NAME`.
|
|
9
|
+
|
|
10
|
+
- `createPlusSdkExtensionFactories(agentDir?: string)` builds the hidden non-TUI roam extension factories with the session's agent dir bound into the sub-agent-spawning extensions (`roam-subagent`, `roam-memory`); `plusSdkExtensionFactories` stays the env-fallback binding (`createPlusSdkExtensionFactories()`), so hosts importing the array directly keep the roam-CLI behavior. Declared in `api.d.ts`.
|
|
11
|
+
- The SDK entry now owns the session/host-facing surface that previously required direct upstream edits: `api.js` re-exports `getDefaultSessionDir` through the roam session overlay and the `ConfiguredPackage`, `PackageUpdate`, and `DefaultResourceLoaderOptions` types via type-only imports from their source modules (the coding-agent barrel stays pristine), and `api.d.ts` declares the roam runtime additions — `AgentSession.getSlashCommands()`, `SessionManager.deleteSession()`, `SessionManager.search()` (instance side via module augmentation, statics via a shadow class export) — plus inline mirrors of the four re-exported names. Embedding hosts keep the same runtime and typed surface as before the upstream edits were moved into the plus packages.
|
|
12
|
+
- The web search extension (`roam-web-search`, shared core `packages/plus/src/extensions/web-search/`) joins `plusSdkExtensionFactories`: SDK sessions get the `WebSearch` (provider chain over `WEB_SEARCH_PROVIDER`/`*_API_KEY` env vars, keyless DuckDuckGo fallback last) and `WebFetch` (URL → text) tools, registered exactly as the CLI wrapper registers them.
|
|
13
|
+
- Session recap failures are re-exported from the SDK surface (`packages/plus/src/extensions/recap/events.ts`): `subscribeToRecapFailures(listener)` — fires with a `{ sessionId, reason: "timeout" | "error", message }` `RecapFailure` after every failed auto-title call (the one-off recap LLM call after the first prompt or a compaction hitting its 30s timeout, or a provider error), returning an unsubscribe function — plus the `RecapFailure`/`RecapFailureReason` types. A host (e.g. the roam desktop) can show its own "session name not set" indicator or trigger a retry without polling. In-process only. Hosts that wire `PlusUIDialogHandlers.notify` via `createPlusUIContext` also receive the failure as a transcript warning through the notify bridge, since the TUI warning that replaced the old stderr dump routes through the same `ui.notify`.
|
|
14
|
+
- `/plan <prompt>` in the plan extension (shared core): any argument other than the `show` / `edit` subcommands turns plan mode on (when off) and forwards the text to the model as a user message (queued as steering while the agent is streaming).
|
|
15
|
+
- The plan review dialog renders the plan as markdown instead of raw text (shared core, `packages/plus/src/extensions/plan/component.ts`): `ExitPlanMode` presents the plan file in a scrollable rendered-markdown view with the three Claude Code choices — Approve and proceed / Stay in plan mode / Edit plan — driven by ↑↓/j/k + enter, digit keys 1-3, or esc to stay (a plain-text `ui.select` remains the fallback for RPC / headless hosts). `/plan show` reuses the same view read-only, replacing the raw `ui.notify` dump.
|
|
16
|
+
- MCP server management is re-exported from the SDK surface (`src/mcp.ts`): the programmatic form of `pi mcp` for hosts (roam disables the TUI `/mcp` commands). Config CRUD on the two files pi loads — `listMcpServers` (merged global `<agentDir>/mcp.json` + trusted-project `<cwd>/.pi/mcp.json`, never throws on a broken file), `addMcpServer` (validates via `validateMcpServer`, refuses project writes when untrusted), `removeMcpServer`, and `updateMcpServer` (`enabled`/`exposure` patches; auto-scope writes the file defining/overriding the entry, `scope: "project"` creates an override, extension-registered servers are rejected). `checkMcpServers` connects to every enabled server in parallel and reports state (`connected`/`needs-auth`/`failed`/`disabled`), namespaced tools, per-tool exposure, and errors like `pi mcp list`. `loginMcpServer` runs pi's OAuth authorization-code + loopback-callback flow (host supplies `openUrl`; optional `promptForRedirectUrl` for remote hosts; 5-minute default deadline, `McpSignInCancelledError` on abort/timeout), `logoutMcpServer` drops a server's stored credentials, and `listMcpCredentials` summarizes `<agentDir>/mcp-auth.json` without secret material. All entries take `cwd`/`agentDir`/`projectTrusted` and reuse pi's own MCP runtime (`extensions/mcp/*`) — no duplicated connection or credential logic.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- Sessions created through the SDK no longer leak the session model to the stored default profile's endpoint via background sub-agent spawns: `createPlusAgentSession` and `createPlusAgentSessionRuntime` now build their extension list with `createPlusSdkExtensionFactories(agentDir)` so spawned `roam` children carry `--as <profile>` (see the roam changelog for the mechanism). Hosts like the Pi+ desktop never set `PI_CODING_AGENT_DIR`, so before this the turn-end memory extractor and sub-agent tool re-resolved the default profile and hit its auth/baseUrl with the session's model.
|
|
21
|
+
- Plan mode no longer blocks writes to the plan file itself: the plan extension's gate state moved into a module-level shared holder (`sharedPlanGateState`) that the permissions extension's "plan" permission mode keeps in sync with the mode — so both gates agree on the plan-file carve-out however plan mode is engaged (`/plan`, `EnterPlanMode`, Shift+Tab, `/permissions plan`, or a host writing the shared mode holder). Permission-only plan mode used to be a carve-out-less read-only mode with no plan file at all; now mode "plan" always means full plan mode with the session plan file as the one writable path, exiting plan mode drops a permissions-side "plan" mode to "bypass" instead of leaving the read-only gate latched, and the plan-mode footer indicator renders once (the plan extension no longer sets its own status slot on top of the permissions footer).
|
|
22
|
+
|
|
23
|
+
- The task store API is re-exported from the SDK surface (`packages/plus/src/extensions/tasks/store.ts`): `TaskStore` (file-backed `TaskCreate`/`TaskUpdate`/`TaskList`/`TaskGet` storage under `<agentDir>/tasks/<sessionId>/`, now a per-process singleton per list id), `subscribeToTasks(listId, listener)` — fires immediately with the current list, then with the full post-mutation list after every task-tool change in this process, returning an unsubscribe function — plus the `Task`/`TaskStatus`/`TaskListListener` types. A host (e.g. the roam desktop) can render a native task panel that stays in sync without polling the files. In-process only: writers in another process are not observed.
|
|
24
|
+
- Runtime settings layering for hub profiles applies to SDK hosts with no environment plumbing (shared `loader/redirects.mjs` entry for `coding-agent/src/core/settings-manager.ts`): whenever the agent dir passed to `SettingsManager.create` is a hub-materialized profile dir (a direct child of `~/.pi/pi-hub/profiles`, honoring `PI_HUB_PI_DIR`/`PI_HUB_DIR`; the roam-set `ROAM_BASE_AGENT_DIR` marker also still activates it), the global scope reads the base agent `settings.json` deep-merged under the profile `settings.json` with the profile winning, and writes route per top-level key — the profile-scoped `defaultProvider`/`defaultModel`/`defaultThinkingLevel` to the profile file, everything else to the agent file with any profile shadow cleared. Any other agent dir keeps `SettingsManager.create` behaving exactly as upstream.
|
|
25
|
+
- The roam context settings are re-exported from the SDK surface (`packages/plus/src/context/threshold-setting.ts`): `readPlusSettings/writePlusSettings/getPlusSettingsPath` for the roam settings store next to `settings.json`, plus the typed getters/setters and UI formatters behind the roam `/settings` rows — `get/setAutoCompactThresholdPercent` (default 80%), `get/setContextFloorTokens` (default/built-in minimum 13000), and `get/setContextWindowCapTokens` (undefined = no cap). Embedding hosts get the same knobs the TUI edits, against the same file detection actually reads. `SessionManager.deleteSession` and `SessionManager.search` (defined by the roam session overlay, reachable through the SDK surface) cover transcript deletion and title/content search for history-management UIs.
|
|
26
|
+
- Initial **`roam-sdk`** npm artifact (published from this package): the programmatic roam entry, split out of the `roam` package so library hosts embed pi in-process with zero CLI logic. `import { createPlusAgentSession, createPlusUIContext, plusSdkExtensionFactories } from "roam-sdk"` gives a host application (e.g. a desktop app) the compaction/context/reasoning overrides (baked in at bundle time by the shared redirect plugin) plus the nine non-TUI roam extensions (subagent, tasks, memory, plan, ask-user, hooks, context-guard, /cd, /init). `createPlusAgentSession()` composes the upstream `createAgentSession` with a `DefaultResourceLoader` carrying those factories, reloads it, and binds extensions once (emitting `session_start`); hosts pass dialog handlers via the `ui` option to get working `ask_user` questions (select/confirm/input bridged to native UI), or omit it for a headless session. The staged package has an `exports` map (deep imports closed off), ships a hand-authored `api.d.ts` re-exporting `@earendil-works/pi-coding-agent` types (added as an exact-pinned dependency for type resolution only; the runtime stays self-contained), and has no bin. Hosts without a pi CLI on PATH should pass `excludeTools: ["subagent"]`: the subagent tool launches a pi subprocess and could otherwise relaunch the host app itself.
|
|
27
|
+
- The `/init` extension (shared core, `packages/plus/src/extensions/init/`) is registered by `plusSdkExtensionFactories` too: the `/init` command creates or improves `AGENTS.md` at the cwd root — pi's default project instructions file, loaded automatically by upstream's context loader.
|
|
28
|
+
- `createPlusAgentSessionRuntime(options?)` — a runtime-backed sibling of `createPlusAgentSession` for embedding hosts that need the CLI's session-replacement machinery. It composes `createAgentSessionServices`/`createAgentSessionFromServices`/`createAgentSessionRuntime` (the same layering the CLI's main uses, trimmed to host concerns) with the roam extension factories and binding rules: extensions are bound exactly once per session through the rebind hook (initial bind plus every `switchSession`/`fork`/`newSession` replacement, emitting one `session_start` each with the matching reason), and the default `commandContextActions` route `waitForIdle`/`newSession`/`fork`/`navigateTree`/`switchSession`/`reload` to the runtime + live session, which is what makes `/cd` (and `/clone`-style `runtime.fork(leafId, { position: "at" })`) work in-process. The live session is `runtime.session` — hosts read it after each replacement or subscribe in the new `onRebind` callback; the initial session defaults to `SessionManager.create(cwd, getDefaultSessionDir(cwd, agentDir))`, and `projectTrusted` (default true) plus `resourceLoaderOptions` passthroughs cover per-cwd settings and loader customization. The SDK entry additionally re-exports `getDefaultSessionDir` (through the roam session overlay, plus the `DefaultResourceLoaderOptions` type via a type-only deep import) to support this entry, keeping the coding-agent barrel pristine.
|
|
29
|
+
- `addProfileModel(name, model)` and `removeProfileModel(name, model)` join the curated profile surface (implemented in `@earendil-works/pi-hub`): append a model without selecting it (bounded by the same three-models-per-profile limit) and remove one with the `roam` CLI delete semantics — the default promotes to the next remaining model, and removing the last clears `models`/`model` so the profile inherits. Both return a human-readable message for host UIs, completing the per-profile model editing that `setProfileDefaultModel` started.
|
|
30
|
+
- `setProfileDefaultModel(name, model)` joins the curated profile surface (implemented in `@earendil-works/pi-hub`): selects a profile's default model — the list position 1 that materialization writes as `settings.defaultModel` — moving an existing model or adding a new one (bounded by the same three-models-per-profile limit the `roam` CLI enforces), and returns a human-readable message for host UIs. This is the library entry for the "select model" behavior that previously lived only in the CLI command layer.
|
|
31
|
+
- The SDK build redirects the upstream `main.ts` to a stub that throws — the CLI entry graph (startup UI, session picker, auth command, …) stays out of `api.js`, and calling `main()` is a clear error instead of silently running un-layered upstream pi. The re-exported `parseArgs`/`SettingsSelectorComponent` resolve to upstream pi (no roam help text or CLI settings rows leak into the library surface).
|
|
32
|
+
- The session recap extension (`roam-session-recap`, shared core `packages/plus/src/extensions/recap/`) joins `plusSdkExtensionFactories`: after the first prompt is answered and after every compaction, a one-off LLM call distills a ≤8-word recap applied as the session name via `setSessionName`, so embedding hosts' session lists/titles read meaningfully without manual naming. Manual renames lock the session against further recaps; failures are logged and never surface.
|
package/README.md
CHANGED
|
@@ -1,3 +1,145 @@
|
|
|
1
|
-
#
|
|
1
|
+
# plus-api
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Builds the **`roam-sdk`** npm package: pi with the roam override layer as an
|
|
4
|
+
embeddable library, for hosts that run pi in-process (e.g. a desktop app) instead of
|
|
5
|
+
running the `roam` CLI. The CLI counterpart is [`../plus-cli`](../plus-cli) (the
|
|
6
|
+
`roam` package); the shared override core is [`../plus`](../plus).
|
|
7
|
+
|
|
8
|
+
## Usage
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
import { createPlusAgentSession } from "roam-sdk";
|
|
12
|
+
|
|
13
|
+
const { session } = await createPlusAgentSession({
|
|
14
|
+
cwd: projectDir,
|
|
15
|
+
ui: {
|
|
16
|
+
select: async (title, options) => showPicker(title, options),
|
|
17
|
+
confirm: async (title, message) => showConfirm(title, message),
|
|
18
|
+
input: async (title, placeholder) => showInput(title, placeholder),
|
|
19
|
+
},
|
|
20
|
+
// Hosts without a pi CLI on PATH should exclude the subagent tool: it
|
|
21
|
+
// launches a pi subprocess and could otherwise relaunch the host app.
|
|
22
|
+
excludeTools: ["subagent"],
|
|
23
|
+
});
|
|
24
|
+
await session.prompt("Review this repository");
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- The full roam layer is included: the compaction/context/reasoning overrides are
|
|
28
|
+
baked into `api.js` by the shared bundle-time redirect plugin, and the twelve
|
|
29
|
+
non-TUI roam extensions (subagent, tasks, memory, plan, ask-user, hooks,
|
|
30
|
+
context-guard, recap, diagram, `/cd`, `/init`, web-search) are registered exactly as the CLI wrapper registers them. The diagram capability is also exposed directly: `renderDiagramHtml(spec)` turns a node-edge `DiagramSpec` into a self-contained HTML/SVG document without a tool round-trip (`layoutDiagram`, the `Diagram*` types, and `DiagramError` are re-exported too). No CLI
|
|
31
|
+
logic ships in this artifact: no hub command dispatch (`roam profile ...`), no
|
|
32
|
+
completion, no roam help text, no banner/vim/tab-title/plain-tools.
|
|
33
|
+
- Profile management ships as a library: the curated `@roam-agent/roam-hub`
|
|
34
|
+
surface is re-exported (`src/profiles.ts`) — `loadProfiles/findProfile/
|
|
35
|
+
addProfile/addProfileModel/updateProfile/removeProfile/removeProfileModel/
|
|
36
|
+
renameProfile/setDefaultProfile/clearDefaultProfile/getDefaultProfileName/
|
|
37
|
+
setProfileDefaultModel` for
|
|
38
|
+
`~/.pi/profiles.json`, and
|
|
39
|
+
`materializeProfile/removeProfileDir/profileDirFor/AGENT_DIR/
|
|
40
|
+
syncProfilePackagesToSource` for the per-profile agent dirs. Hosts get the
|
|
41
|
+
exact contract the `roam` CLI dispatches instead of reimplementing it.
|
|
42
|
+
- The roam context settings ship as a library: `readRoamSettings/updateRoamSettings`
|
|
43
|
+
and the `get/setAutoCompactThresholdPercent`, `get/setContextFloorTokens`,
|
|
44
|
+
`get/setContextWindowCapTokens` helpers (plus formatters/parsers) manage the
|
|
45
|
+
`roam` block of the base agent `settings.json` that drives auto-compaction
|
|
46
|
+
trigger math — the same store the roam TUI `/settings` rows edit. Hosts store
|
|
47
|
+
their own keys in the same block via the generic pair.
|
|
48
|
+
Session history management completes the surface: `SessionManager.listAll` to
|
|
49
|
+
enumerate, `SessionManager.search(query)` to match titles and transcript text, and
|
|
50
|
+
`SessionManager.deleteSession(path)` to remove a transcript.
|
|
51
|
+
- Pi package maintenance ships as a library (`src/packages.ts`): `listPackages`,
|
|
52
|
+
`installPackage`, `removePackage`, and `updatePackages` are the programmatic form
|
|
53
|
+
of `pi install`/`remove`/`list`/`update --extensions` — the pi packages (extensions,
|
|
54
|
+
skills, prompts, themes) surface from pi.dev/docs/latest/packages. They take
|
|
55
|
+
explicit `cwd`/`agentDir` (or a caller-owned `SettingsManager`) plus `projectTrusted`
|
|
56
|
+
and an `onProgress` callback; project-scope (`local`) writes are refused by the
|
|
57
|
+
underlying manager when the project is not trusted.
|
|
58
|
+
- MCP server management ships as a library (`src/mcp.ts`): `listMcpServers`,
|
|
59
|
+
`addMcpServer`, `removeMcpServer`, and `updateMcpServer` are the programmatic form of
|
|
60
|
+
`pi mcp`'s config CRUD (the global `<agentDir>/mcp.json`, or the trusted project's
|
|
61
|
+
`<cwd>/.pi/mcp.json` via `local`/`scope`); `validateMcpServer` checks an entry without
|
|
62
|
+
writing it; `checkMcpServers` reports each server's connection state, tools, and errors
|
|
63
|
+
like `pi mcp list`; and `loginMcpServer`/`logoutMcpServer`/`listMcpCredentials` run pi's
|
|
64
|
+
OAuth sign-in (browser `openUrl` callback, loopback redirect) and credential management.
|
|
65
|
+
roam disables the TUI `/mcp` commands, so this is the MCP management entry for hosts.
|
|
66
|
+
- Provider login ships as a library (`src/auth.ts`): `loginProvider(providerId, { agentDir?, interaction?, signal?, method? })`
|
|
67
|
+
runs pi's model-runtime login flow (OAuth login page / API-key setup — the same
|
|
68
|
+
flow `roam profile add <name> -p <provider>` and the `--sign-in` flag on
|
|
69
|
+
`roam profile add`/`profile update` trigger) and persists the credential
|
|
70
|
+
to `<agentDir>/auth.json`; `createTerminalAuthInteraction()` provides the readline
|
|
71
|
+
terminal UI for CLI use, and hosts pass their own `AuthInteraction` to drive the
|
|
72
|
+
prompts from a custom UI. To mirror the CLI's sign-in token overwrite, write the
|
|
73
|
+
returned credential's `key` into `Profile.token` via `updateProfile` (and clear
|
|
74
|
+
the field for OAuth logins, whose credential only lives in the profile's
|
|
75
|
+
`auth.json` — a stored token would overwrite it at the next launch). roam disables the TUI `/login` (the `interactive-mode`
|
|
76
|
+
and `slash-commands` core redirects are baked in here too), so this is the login
|
|
77
|
+
entry for the whole product.
|
|
78
|
+
- `createPlusAgentSession()` extends the upstream `createAgentSession` (re-exported,
|
|
79
|
+
with the whole upstream SDK surface) and always binds extensions once — do not call
|
|
80
|
+
`session.bindExtensions()` yourself. Pass `ui` dialog handlers to get working
|
|
81
|
+
`ask_user` questions (bound with mode `"rpc"`, so the tool falls back to sequential
|
|
82
|
+
select/input/confirm dialogs bridged to your UI); omit `ui` for a headless session.
|
|
83
|
+
- `createPlusAgentSessionRuntime()` returns a `PlusAgentSessionRuntime` (an
|
|
84
|
+
`AgentSessionRuntime` plus host-owned Bash execution) instead of a single
|
|
85
|
+
session: the same roam layer and one-bind-per-session rules, plus the
|
|
86
|
+
CLI's session-replacement machinery — `runtime.cd`-style switches
|
|
87
|
+
(`switchSession`), `newSession`, and `fork` (with `{position: "at"}` for the CLI's
|
|
88
|
+
in-place `/clone`). The roam `/cd`/`/init` extensions and anything else needing
|
|
89
|
+
`commandContextActions` work out of the box: the factory wires runtime-routed
|
|
90
|
+
actions by default (override via the `commandContextActions` option). The live
|
|
91
|
+
session is `runtime.session` and **changes on every replacement** — re-subscribe in
|
|
92
|
+
the `onRebind` callback (it also fires for the initial bind) and never call
|
|
93
|
+
`bindExtensions()` yourself. `runtime.dispose()` is async and emits
|
|
94
|
+
`session_shutdown`.
|
|
95
|
+
|
|
96
|
+
- `session.setAutoCompactionEnabled(bool)` writes the **global**
|
|
97
|
+
`<agentDir>/settings.json` compaction flag (not a per-session setting), so a host
|
|
98
|
+
toggle labeled per-session would surprise users — it also flips behavior for the
|
|
99
|
+
`roam` CLI sharing that agent dir.
|
|
100
|
+
- Session recap failures are observable: the recap extension (auto-titles the
|
|
101
|
+
session after the first prompt and every compaction) publishes every failed title
|
|
102
|
+
call to `subscribeToRecapFailures(listener)` — `{ sessionId, reason: "timeout" |
|
|
103
|
+
"error", message }` — so a host can surface "session name not set" in its own UI
|
|
104
|
+
or trigger a retry. In-process only (one process hosts the session). Hosts that
|
|
105
|
+
wire `ui.notify` also receive the failure as a transcript warning through the
|
|
106
|
+
notify bridge.
|
|
107
|
+
- The staged `package.json` has an `exports` map, so deep imports are not reachable;
|
|
108
|
+
`api.d.ts` re-exports the `@earendil-works/pi-coding-agent` types (exact-pinned
|
|
109
|
+
dependency, type resolution only — the runtime is self-contained).
|
|
110
|
+
- `main` is re-exported from the upstream barrel but redirects to a stub that throws:
|
|
111
|
+
the CLI entry is not part of the SDK. Likewise `parseArgs`/`Args` and
|
|
112
|
+
`SettingsSelectorComponent` are upstream pi's versions, not the roam-branded CLI
|
|
113
|
+
wrappers.
|
|
114
|
+
|
|
115
|
+
### Bash execution
|
|
116
|
+
|
|
117
|
+
Hosts can run shell commands outside an LLM turn through the runtime:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const result = await runtime.executeBash("git status", (chunk) => {
|
|
121
|
+
process.stdout.write(chunk);
|
|
122
|
+
}, { id: "status-1" });
|
|
123
|
+
|
|
124
|
+
runtime.abortBash(); // cancels every command currently running on the session
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The result is recorded in the session context unless `excludeFromContext` is
|
|
128
|
+
set. This API is for host-initiated actions (for example, a user-entered `!`
|
|
129
|
+
command); it does not route through the model's tool-permission gate, so the
|
|
130
|
+
host must obtain any required user consent before calling it. `excludeTools:
|
|
131
|
+
["bash"]` only controls the model-facing Bash tool during LLM turns.
|
|
132
|
+
|
|
133
|
+
## Building the artifact
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
npm run build:offline # at the repo root, first
|
|
137
|
+
npm run build # in packages/plus-api
|
|
138
|
+
npm publish --access public --ignore-scripts # in packages/plus-api/dist/npm
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Tests
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
npx vitest run # from packages/plus-api
|
|
145
|
+
```
|
package/anthropic.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { createRequire as __roamSdkCreateRequire } from "node:module"; const require = __roamSdkCreateRequire(import.meta.url);
|
|
2
|
+
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}import{createServer}from"node:http";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
3
|
+
<html lang="en">
|
|
4
|
+
<head>
|
|
5
|
+
<meta charset="utf-8" />
|
|
6
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
7
|
+
<title>${title}</title>
|
|
8
|
+
<style>
|
|
9
|
+
:root {
|
|
10
|
+
--text: #fafafa;
|
|
11
|
+
--text-dim: #a1a1aa;
|
|
12
|
+
--page-bg: #09090b;
|
|
13
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
14
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
15
|
+
}
|
|
16
|
+
* { box-sizing: border-box; }
|
|
17
|
+
html { color-scheme: dark; }
|
|
18
|
+
body {
|
|
19
|
+
margin: 0;
|
|
20
|
+
min-height: 100vh;
|
|
21
|
+
display: flex;
|
|
22
|
+
align-items: center;
|
|
23
|
+
justify-content: center;
|
|
24
|
+
padding: 24px;
|
|
25
|
+
background: var(--page-bg);
|
|
26
|
+
color: var(--text);
|
|
27
|
+
font-family: var(--font-sans);
|
|
28
|
+
text-align: center;
|
|
29
|
+
}
|
|
30
|
+
main {
|
|
31
|
+
width: 100%;
|
|
32
|
+
max-width: 560px;
|
|
33
|
+
display: flex;
|
|
34
|
+
flex-direction: column;
|
|
35
|
+
align-items: center;
|
|
36
|
+
justify-content: center;
|
|
37
|
+
}
|
|
38
|
+
.logo {
|
|
39
|
+
width: 72px;
|
|
40
|
+
height: 72px;
|
|
41
|
+
display: block;
|
|
42
|
+
margin-bottom: 24px;
|
|
43
|
+
}
|
|
44
|
+
h1 {
|
|
45
|
+
margin: 0 0 10px;
|
|
46
|
+
font-size: 28px;
|
|
47
|
+
line-height: 1.15;
|
|
48
|
+
font-weight: 650;
|
|
49
|
+
color: var(--text);
|
|
50
|
+
}
|
|
51
|
+
p {
|
|
52
|
+
margin: 0;
|
|
53
|
+
line-height: 1.7;
|
|
54
|
+
color: var(--text-dim);
|
|
55
|
+
font-size: 15px;
|
|
56
|
+
}
|
|
57
|
+
.details {
|
|
58
|
+
margin-top: 16px;
|
|
59
|
+
font-family: var(--font-mono);
|
|
60
|
+
font-size: 13px;
|
|
61
|
+
color: var(--text-dim);
|
|
62
|
+
white-space: pre-wrap;
|
|
63
|
+
word-break: break-word;
|
|
64
|
+
}
|
|
65
|
+
</style>
|
|
66
|
+
</head>
|
|
67
|
+
<body>
|
|
68
|
+
<main>
|
|
69
|
+
<div class="logo">${LOGO_SVG}</div>
|
|
70
|
+
<h1>${heading}</h1>
|
|
71
|
+
<p>${message}</p>
|
|
72
|
+
${details?`<div class="details">${details}</div>`:""}
|
|
73
|
+
</main>
|
|
74
|
+
</body>
|
|
75
|
+
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}function sendPage(response,status,html){response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(html)}async function startOAuthCallbackServer(options){let{providerName,signal}=options;if(signal?.aborted)throw new Error("Login cancelled");let resolveWait=()=>{},rejectWait=()=>{},waitPromise=new Promise((resolve,reject)=>{resolveWait=resolve,rejectWait=reject});waitPromise.catch(()=>{});let claimed=!1,settled=!1,timer,onAbort=()=>finish({error:new Error("Login cancelled")}),finish=result=>{settled||(settled=!0,timer&&clearTimeout(timer),signal?.removeEventListener("abort",onAbort),"error"in result?rejectWait(result.error):resolveWait(result.value))},server=createServer((request,response)=>{(async()=>{let url=new URL(request.url??"/","http://localhost");if(request.method!=="GET"||url.pathname!==options.path){sendPage(response,404,oauthErrorHtml("Callback route not found."));return}if(options.state!==void 0&&url.searchParams.get("state")!==options.state){sendPage(response,400,oauthErrorHtml("State mismatch."));return}if(claimed||settled){sendPage(response,409,oauthErrorHtml("This sign-in has already been handled."));return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;sendPage(response,400,oauthErrorHtml(`${providerName} authorization failed.`,description)),finish({error:new Error(`${providerName} authorization failed: ${description}`)});return}let code=url.searchParams.get("code");if(!code){sendPage(response,400,oauthErrorHtml("Missing authorization code."));return}claimed=!0;try{let value=await options.complete(code);sendPage(response,200,oauthSuccessHtml(`Signed in to ${providerName}. You may now close this page.`)),finish({value})}catch(error2){let failure=error2 instanceof Error?error2:new Error(String(error2));sendPage(response,502,oauthErrorHtml(`${providerName} sign-in failed.`,failure.message)),finish({error:failure})}})()});await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>{server.off("error",reject),resolve()})});let address=server.address();if(!address||typeof address=="string")throw server.close(),new Error("OAuth callback server did not bind to TCP");server.on("error",error=>finish({error})),signal?.addEventListener("abort",onAbort,{once:!0}),options.timeoutMs!==void 0&&(timer=setTimeout(()=>finish({error:new Error(`${providerName} sign-in timed out`)}),options.timeoutMs));let redirectHost=options.redirectHost??options.host;return{redirectUri:`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${options.path}`,wait:()=>waitPromise,cancel:()=>{claimed||finish({value:void 0})},close:()=>{finish({error:new Error("OAuth callback server closed")}),server.close()}}}async function waitForCallbackOrManualInput(interaction,callback,prompt){let manualAbort=new AbortController,manualError,manual=interaction.prompt({type:"manual_code",...prompt,signal:manualAbort.signal}).then(input=>(callback?.cancel(),input)).catch(error=>{manualError=error instanceof Error?error:new Error(String(error)),callback?.cancel()});try{let value=await callback?.wait();if(manualError)throw manualError;if(value!==void 0)return{type:"callback",value};let input=await manual;if(manualError)throw manualError;return{type:"manual",input:input??""}}finally{manualAbort.abort()}}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var decode=s=>atob(s),CLIENT_ID=decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),AUTHORIZE_URL="https://claude.ai/oauth/authorize",TOKEN_URL="https://platform.claude.com/v1/oauth/token",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=53692,CALLBACK_PATH="/callback",REDIRECT_URI=`http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`,COPY_CODE_REDIRECT_URI="https://platform.claude.com/oauth/code/callback",ANTHROPIC_BROWSER_LOGIN_METHOD="browser",ANTHROPIC_COPY_CODE_LOGIN_METHOD="copy_code",SCOPES="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";function parseAuthorizationInput(input){let value=input.trim();if(!value)return{};try{let url=new URL(value);return{code:url.searchParams.get("code")??void 0,state:url.searchParams.get("state")??void 0}}catch{}if(value.includes("#")){let[code,state]=value.split("#",2);return{code,state}}if(value.includes("code=")){let params=new URLSearchParams(value);return{code:params.get("code")??void 0,state:params.get("state")??void 0}}return{code:value}}function formatErrorDetails(error){if(error instanceof Error){let details=[`${error.name}: ${error.message}`],errorWithCode=error;return errorWithCode.code&&details.push(`code=${errorWithCode.code}`),typeof errorWithCode.errno<"u"&&details.push(`errno=${String(errorWithCode.errno)}`),typeof error.cause<"u"&&details.push(`cause=${formatErrorDetails(error.cause)}`),error.stack&&details.push(`stack=${error.stack}`),details.join("; ")}return String(error)}async function postJson(url,body,signal){let response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body),signal:AbortSignal.any([signal,AbortSignal.timeout(3e4)])}),responseBody=await response.text();if(!response.ok)throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);return responseBody}async function exchangeAuthorizationCode(code,state,verifier,redirectUri,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"authorization_code",client_id:CLIENT_ID,code,state,redirect_uri:redirectUri,code_verifier:verifier},signal)}catch(error){throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`)}let tokenData;try{tokenData=JSON.parse(responseBody)}catch(error){throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`)}return{type:"oauth",refresh:tokenData.refresh_token,access:tokenData.access_token,expires:Date.now()+tokenData.expires_in*1e3-300*1e3}}async function loginAnthropic(interaction){let{verifier,challenge}=await generatePKCE(),startCallbackServer=port=>startOAuthCallbackServer({providerName:"Anthropic",host:CALLBACK_HOST,port,path:CALLBACK_PATH,redirectHost:"localhost",state:verifier,complete:async code=>code,signal:interaction.signal}),callback=await startCallbackServer(CALLBACK_PORT).catch(()=>startCallbackServer(0)).catch(()=>{}),redirectUri=callback?.redirectUri??REDIRECT_URI;try{let authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:redirectUri,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."});let result=await waitForCallbackOrManualInput(interaction,callback,{message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:redirectUri}),code,state=verifier;if(result.type==="callback")code=result.value;else{let parsed=parseAuthorizationInput(result.input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");code=parsed.code,state=parsed.state??verifier}if(!code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(code,state,verifier,redirectUri,interaction.signal)}finally{callback?.close()}}async function loginAnthropicCopyCode(interaction){let{verifier,challenge}=await generatePKCE(),authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:COPY_CODE_REDIRECT_URI,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser, then copy the code Anthropic shows and paste it here."});let input=await interaction.prompt({type:"manual_code",message:"Paste the code Anthropic shows after you sign in:",placeholder:"code#state",signal:interaction.signal}),parsed=parseAuthorizationInput(input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");if(!parsed.code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(parsed.code,parsed.state??verifier,verifier,COPY_CODE_REDIRECT_URI,interaction.signal)}async function refreshAnthropicToken(refreshToken,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"refresh_token",client_id:CLIENT_ID,refresh_token:refreshToken},signal)}catch(error){throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`)}let data;try{data=JSON.parse(responseBody)}catch(error){throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`)}return{type:"oauth",refresh:data.refresh_token,access:data.access_token,expires:Date.now()+data.expires_in*1e3-300*1e3}}var anthropicOAuth={name:"Anthropic (Claude Pro/Max)",isSubscription:!0,async login(interaction){let method=await interaction.prompt({type:"select",message:"Select Anthropic login method:",options:[{id:ANTHROPIC_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:ANTHROPIC_COPY_CODE_LOGIN_METHOD,label:"Copy code login (headless)"}]});if(method===ANTHROPIC_COPY_CODE_LOGIN_METHOD)return loginAnthropicCopyCode(interaction);if(method!==ANTHROPIC_BROWSER_LOGIN_METHOD)throw new Error(`Unknown Anthropic login method: ${method}`);return loginAnthropic(interaction)},refresh:(credential,signal)=>refreshAnthropicToken(credential.refresh,signal),async toAuth(credential){return{apiKey:credential.access}}};export{anthropicOAuth};
|