@bivy/bivy 0.0.0 → 0.1.0-staging.2

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 (146) hide show
  1. package/LICENSE +105 -0
  2. package/README.md +265 -5
  3. package/bin/acp-shim.mjs +298 -0
  4. package/bin/agent-manifest.json +277 -0
  5. package/bin/bivy.mjs +4100 -0
  6. package/bin/codex-app-server-shim.mjs +447 -0
  7. package/bin/patch-pi-dependencies.mjs +44 -0
  8. package/bin/prune-sessions.mjs +52 -0
  9. package/bin/sessions-list.mjs +27 -0
  10. package/bin/shim-path.mjs +126 -0
  11. package/bin/uninstall-paths.mjs +48 -0
  12. package/dist/approval.js +87 -0
  13. package/dist/attach.js +248 -0
  14. package/dist/auth.js +258 -0
  15. package/dist/bivy-login.js +180 -0
  16. package/dist/browser-open.js +50 -0
  17. package/dist/control-plane-tasks.js +236 -0
  18. package/dist/data-dir.js +25 -0
  19. package/dist/device-registry.js +201 -0
  20. package/dist/e2e.js +70 -0
  21. package/dist/ephemeral-exec.js +109 -0
  22. package/dist/exec.js +209 -0
  23. package/dist/git-auth.js +155 -0
  24. package/dist/github-app-auth.js +107 -0
  25. package/dist/github-app-connect.js +235 -0
  26. package/dist/github-app-manifest.js +82 -0
  27. package/dist/github-app-sync-cli.js +93 -0
  28. package/dist/github-app-vault.js +106 -0
  29. package/dist/github-apps.js +121 -0
  30. package/dist/github-connect-repo.js +74 -0
  31. package/dist/github-device-auth.js +109 -0
  32. package/dist/github-tasks.js +650 -0
  33. package/dist/guard.js +109 -0
  34. package/dist/harness/cache-evict.js +88 -0
  35. package/dist/harness/checkpoint.js +0 -0
  36. package/dist/harness/cow-clone.js +84 -0
  37. package/dist/harness/dep-cache.js +78 -0
  38. package/dist/harness/disk-admission.js +46 -0
  39. package/dist/harness/egress.js +30 -0
  40. package/dist/harness/manager.js +97 -0
  41. package/dist/harness/mcp-config-formats.js +164 -0
  42. package/dist/harness/mcp-config.js +111 -0
  43. package/dist/harness/mcp-inject.js +134 -0
  44. package/dist/harness/mcp-proxy-cli.js +88 -0
  45. package/dist/harness/mcp-proxy.js +150 -0
  46. package/dist/harness/net-proxy.js +120 -0
  47. package/dist/harness/sandbox.js +96 -0
  48. package/dist/history-sync.js +26 -0
  49. package/dist/hosted-endpoints.d.mts +14 -0
  50. package/dist/hosted-endpoints.mjs +35 -0
  51. package/dist/identity.js +153 -0
  52. package/dist/integrations/index.js +4 -0
  53. package/dist/integrations/manager.js +279 -0
  54. package/dist/integrations/oauth.js +78 -0
  55. package/dist/integrations/registry.js +239 -0
  56. package/dist/integrations/store.js +54 -0
  57. package/dist/integrations/types.js +1 -0
  58. package/dist/linear-tasks.js +49 -0
  59. package/dist/metadata.js +226 -0
  60. package/dist/multiplexer.js +79 -0
  61. package/dist/native-pi.js +38 -0
  62. package/dist/node-stats.js +237 -0
  63. package/dist/pairing-crypto.js +105 -0
  64. package/dist/policy/conditions.js +103 -0
  65. package/dist/policy/policy-engine.js +20 -0
  66. package/dist/policy/risk.js +18 -0
  67. package/dist/policy/ruleset.js +113 -0
  68. package/dist/policy/run-policy.js +108 -0
  69. package/dist/policy/session-reroute.js +96 -0
  70. package/dist/pty-runner.py +95 -0
  71. package/dist/question.js +146 -0
  72. package/dist/redact.js +97 -0
  73. package/dist/relay-attach.js +345 -0
  74. package/dist/relay-chunk.js +73 -0
  75. package/dist/relay-cli-crypto.js +70 -0
  76. package/dist/relay-client.js +344 -0
  77. package/dist/relay-setup.js +262 -0
  78. package/dist/repo-workspace.js +208 -0
  79. package/dist/runtime/adoption.js +45 -0
  80. package/dist/runtime/agent-service-bin.js +149 -0
  81. package/dist/runtime/agent-service.js +439 -0
  82. package/dist/runtime/ansi.js +27 -0
  83. package/dist/runtime/anthropic-preflight.js +80 -0
  84. package/dist/runtime/claude-code.js +1364 -0
  85. package/dist/runtime/cli-parsers.js +647 -0
  86. package/dist/runtime/codex-auth.js +168 -0
  87. package/dist/runtime/codex-preflight.js +60 -0
  88. package/dist/runtime/codex-sessions.js +229 -0
  89. package/dist/runtime/control-plane-location.js +74 -0
  90. package/dist/runtime/credential-ingest.js +122 -0
  91. package/dist/runtime/credential-provisioning.js +79 -0
  92. package/dist/runtime/credential-store.js +435 -0
  93. package/dist/runtime/credentials.js +153 -0
  94. package/dist/runtime/host.js +153 -0
  95. package/dist/runtime/index.js +1548 -0
  96. package/dist/runtime/local-model-store.js +194 -0
  97. package/dist/runtime/location-registry.js +28 -0
  98. package/dist/runtime/model-catalog.js +97 -0
  99. package/dist/runtime/model-namer.js +85 -0
  100. package/dist/runtime/native-process-scan.js +102 -0
  101. package/dist/runtime/native-session-discovery.js +103 -0
  102. package/dist/runtime/normalize.js +75 -0
  103. package/dist/runtime/oauth/model-oauth-providers.js +75 -0
  104. package/dist/runtime/oauth/model-oauth.js +324 -0
  105. package/dist/runtime/opencode-preflight.js +55 -0
  106. package/dist/runtime/pi-auth.js +82 -0
  107. package/dist/runtime/pi-oauth.js +52 -0
  108. package/dist/runtime/pi-session-discovery.js +42 -0
  109. package/dist/runtime/pi.js +518 -0
  110. package/dist/runtime/process.js +499 -0
  111. package/dist/runtime/protocol.js +630 -0
  112. package/dist/runtime/remote.js +541 -0
  113. package/dist/runtime/rpc-protocol.js +56 -0
  114. package/dist/runtime/ruleset-store.js +117 -0
  115. package/dist/runtime/session-location.js +50 -0
  116. package/dist/runtime/types.js +17 -0
  117. package/dist/secrets-cli.js +134 -0
  118. package/dist/secrets.js +264 -0
  119. package/dist/server.js +9411 -0
  120. package/dist/session/bivy-session.js +1 -0
  121. package/dist/session/checkpoint-pack.js +133 -0
  122. package/dist/session/event-log.js +340 -0
  123. package/dist/session/fork-dirty.js +73 -0
  124. package/dist/session/fork-prereqs.js +61 -0
  125. package/dist/session/fork.js +57 -0
  126. package/dist/session/native-import.js +56 -0
  127. package/dist/session/reconnect.js +168 -0
  128. package/dist/session/replication-service.js +236 -0
  129. package/dist/session/replication.js +106 -0
  130. package/dist/session/replicator.js +140 -0
  131. package/dist/session/session-new-dedupe.js +42 -0
  132. package/dist/session/sibling-client.js +201 -0
  133. package/dist/session/transcript-merge.js +131 -0
  134. package/dist/session/transcript-normal.js +130 -0
  135. package/dist/session/workspace-context.js +1 -0
  136. package/dist/session-event-coalescer.js +50 -0
  137. package/dist/session-identity.js +34 -0
  138. package/dist/session-ref.js +65 -0
  139. package/dist/stt-cli.js +131 -0
  140. package/dist/stt.js +168 -0
  141. package/dist/terminal.js +409 -0
  142. package/dist/wire-format.js +67 -0
  143. package/dist/worktree-provision.js +118 -0
  144. package/dist/worktree.js +117 -0
  145. package/package.json +40 -6
  146. package/public/qr.js +464 -0
package/LICENSE ADDED
@@ -0,0 +1,105 @@
1
+ # Functional Source License, Version 1.1, ALv2 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-ALv2
6
+
7
+ ## Notice
8
+
9
+ Copyright 2026 Petter André Sjulstad
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -1,8 +1,268 @@
1
- # @bivy/bivy
1
+ # Bivy
2
2
 
3
- Placeholder package reserving the `@bivy/bivy` name on npm.
3
+ Route coding-agent work to infrastructure you own.
4
4
 
5
- This package does not contain any functionality yet. It is intended to eventually
6
- hold the distributable parts of the [Bivy](https://github.com/) project.
5
+ Bivy turns GitHub issues, Slack requests, signed webhooks, schedules, and live
6
+ prompts into governed agent runs on your laptop, server, or cloud account. Choose
7
+ the node, agent, and model; burst onto a short-lived runner in your own cloud;
8
+ then watch, steer, and approve from a phone, browser, or terminal.
7
9
 
8
- Stay tuned.
10
+ Agents run with your repository, keys, and toolchain. Bivy's relay and control
11
+ plane do not receive repository contents, prompts, transcripts, or model keys.
12
+ Bivy adds routing, durable sessions, approvals, fallback rules, and outcome
13
+ reports around agents you already use.
14
+
15
+ - **Website:** [bivy.sh](https://bivy.sh)
16
+ - **Documentation:** [`docs/`](docs/README.md) — start with the [quickstart](docs/quickstart.md)
17
+ - **License:** [FSL-1.1-ALv2](LICENSE) (source-available; converts to Apache-2.0 two years after each release)
18
+
19
+ > Bivy is 0.x software. The core loop is solid and used daily, but interfaces
20
+ > and behaviour can change between releases.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ curl -fsSL https://bivy.sh/install.sh | bash
26
+ ```
27
+
28
+ macOS and Linux. Requires Node 22.19 or newer; the installer sets it up if
29
+ missing. It installs the [`@bivy/bivy`](https://www.npmjs.com/package/@bivy/bivy) package
30
+ from npm, then runs the guided `bivy setup` wizard — workspace, relay/control-
31
+ plane sign-in, and an auto-start background service (launchd on macOS, systemd
32
+ on Linux).
33
+
34
+ Already have Node? The installer is optional:
35
+
36
+ ```bash
37
+ npm install -g @bivy/bivy
38
+ bivy setup
39
+ ```
40
+
41
+ Releases are published from CI with provenance attestations; verify with
42
+ `npm audit signatures`. See [`docs/releasing.md`](docs/releasing.md).
43
+
44
+ Already have the repository checked out:
45
+
46
+ ```bash
47
+ npm install
48
+ npm run setup
49
+ ```
50
+
51
+ See [`docs/install.md`](docs/install.md) for service management and uninstall.
52
+
53
+ ## Architecture
54
+
55
+ Bivy has three parts. Only the first one holds your data.
56
+
57
+ ```text
58
+ your machine hosted or self-hosted
59
+
60
+ ┌──────────────┐ ┌─────────┐ ┌───────────────┐
61
+ │ node daemon │ ──dials──▶ │ relay │ ◀────▶ │ control plane │
62
+ │ agents, keys │ outbound │ opaque │ │ accounts, web │
63
+ │ repo, tools │ │ frames │ │ app, metadata │
64
+ └──────────────┘ └─────────┘ └───────────────┘
65
+ ▲ ▲
66
+ └────────── end-to-end encrypted session ───────────┘
67
+ phone · browser · another terminal
68
+ ```
69
+
70
+ - **Node** — a daemon on your machine. Owns the workspace, credentials, and agent
71
+ processes. Serves an API and WebSocket on `http://localhost:4317` plus a
72
+ `/healthz` probe. **It hosts no web UI.**
73
+ - **Relay** — forwards encrypted frames between your node and your devices. Your
74
+ node dials out, so no inbound port is opened. The relay cannot read the frames.
75
+ - **Control plane** — holds your account, node registry, and session index, and
76
+ serves the web/PWA client. Use the hosted one or run your own.
77
+
78
+ Because the node serves no UI, a browser or phone needs a control plane — hosted
79
+ at `app.bivy.sh`, or one you deploy yourself. The terminal CLI needs neither.
80
+
81
+ See [`docs/remote-access.md`](docs/remote-access.md) and
82
+ [`docs/security-model.md`](docs/security-model.md).
83
+
84
+ ## Supported agents
85
+
86
+ Nineteen agents are available in the picker, each driven through its native interface:
87
+
88
+ | Agent | Command | Notes |
89
+ |---|---|---|
90
+ | Pi | `bivy run pi` | Default; bundled |
91
+ | Claude Code | `bivy run claude` | Bundled SDK |
92
+ | Codex | `bivy run codex` | Installs `@openai/codex` |
93
+ | OpenCode | `bivy run opencode` | Installs `opencode-ai/opencode` |
94
+ | Gemini CLI | `bivy run gemini` | Installs `@google/gemini-cli` |
95
+ | Qwen Code | `bivy run qwen` | Installs `@qwen-code/qwen-code` |
96
+ | Goose | `bivy run goose` | Requires `goose` on PATH |
97
+ | Aider | `bivy run aider` | No session resume (upstream gap) |
98
+ | Cline | `bivy run cline` | Installs `cline` |
99
+ | Crush | `bivy run crush` | No session resume (upstream gap) |
100
+ | Cursor | `bivy run cursor` | ACP-capable |
101
+ | GitHub Copilot | `bivy run copilot` | ACP-capable |
102
+ | Grok | `bivy run grok` | Model selection |
103
+ | Amp | `bivy run amp` | Native thread resume |
104
+ | Auggie | `bivy run auggie` | Headless CLI |
105
+ | Droid | `bivy run droid` | Model selection |
106
+ | Continue | `bivy run continue` | Headless CLI |
107
+ | Kilo Code | `bivy run kilocode` | ACP-capable |
108
+ | Rovo Dev | `bivy run rovodev` | Installed out of band |
109
+
110
+ Any other command works via `bivy run -- ./your-agent --flags`. ACP-capable
111
+ agents can be promoted to Bivy's governed protocol path for per-tool approvals
112
+ and native resume.
113
+
114
+ [`docs/runtime-support-matrix.md`](docs/runtime-support-matrix.md) lists exactly
115
+ what each agent supports — resume, model selection, approvals, sandboxing.
116
+
117
+ ## Common commands
118
+
119
+ ```bash
120
+ bivy # launch the default agent as a durable session
121
+ bivy run claude # run a specific agent
122
+ bivy sessions # list live and saved sessions
123
+ bivy resume # resume the most recent session
124
+ bivy open # open the web app (requires relay setup)
125
+ bivy status # config summary and node reachability
126
+ bivy doctor # health check
127
+ bivy logs -f # tail node logs
128
+ bivy update # update Bivy and restart the service
129
+ ```
130
+
131
+ Full command list, flags, and examples: [`docs/cli-reference.md`](docs/cli-reference.md).
132
+
133
+ ## Configuration
134
+
135
+ The common knobs:
136
+
137
+ ```bash
138
+ BIVY_WORKSPACE=/path/to/repo # default workspace
139
+ BIVY_SANDBOX=read-only # read-only | workspace-write (default) | danger-full-access
140
+ BIVY_APPROVAL_MODE=risky # never | risky | always | autonomous (default)
141
+ ```
142
+
143
+ Every environment variable, config file, and precedence rule:
144
+ [`docs/configuration.md`](docs/configuration.md).
145
+
146
+ ## Approvals and sandboxing
147
+
148
+ The default approval mode is **`autonomous`**: agents act without per-action
149
+ prompts. Safety comes from a floor that applies in *every* mode — catastrophic
150
+ commands and writes outside the workspace are refused outright, and a backstop
151
+ set (force-push, publish, deploy, sudo) always pauses for a human.
152
+
153
+ If you want to be asked about more, set the mode explicitly:
154
+
155
+ ```bash
156
+ BIVY_APPROVAL_MODE=risky # prompt on risky shell commands and file edits
157
+ BIVY_APPROVAL_MODE=always # prompt on every tool call
158
+ BIVY_APPROVAL_MODE=never # no prompts beyond the hard floor
159
+ ```
160
+
161
+ Approve from the terminal, browser, or phone.
162
+
163
+ Sandbox tiers (`read-only`, `workspace-write`, `danger-full-access`) are enforced
164
+ natively by agents that support them — Codex, Claude Code, Gemini CLI, Qwen Code.
165
+ Agents without a native sandbox are governed at the filesystem, MCP, and network
166
+ layer. **Bivy does not ship its own OS-level jail in 0.1.**
167
+
168
+ ## Credentials
169
+
170
+ Provider credentials stay on the node or in a vault you control. Bivy Cloud does
171
+ not receive model keys, GitHub repository tokens, OAuth refresh tokens, prompts,
172
+ transcripts, or workspace files.
173
+
174
+ ```bash
175
+ bivy secrets list
176
+ bivy secrets set github.repo-token
177
+ bivy secrets ref github.repo-token op://Bivy/GitHub/repo-token
178
+ bivy secrets doctor
179
+ ```
180
+
181
+ `secret://`, `env://`, and `op://` (1Password) references are resolved before the
182
+ daemon starts. See [`docs/key-management.md`](docs/key-management.md).
183
+
184
+ ## GitHub work queue
185
+
186
+ Label an issue `bivy` (or `bivy/<node>` to target a machine), or mention the Bivy
187
+ GitHub App in a comment. A node you own claims the work, runs the agent in an
188
+ isolated worktree, and the agent opens the pull request itself.
189
+
190
+ Available on every plan: interactive CLI/app sessions are unlimited. Free
191
+ accounts also get 10 unattended automations per rolling 7-day window across
192
+ GitHub, Slack, webhooks, and schedules; Pro removes the automation cap.
193
+ Self-hosted stacks are unlimited.
194
+
195
+ A private GitHub App only installs on the account that owns it, so connect one
196
+ app per GitHub account — one for your personal repos, one per organization
197
+ (`bivy github:app-create --org <org>`). A node can serve several at once, each
198
+ with its own key and `@`-mention handle.
199
+
200
+ See [`docs/github-work-queue.md`](docs/github-work-queue.md).
201
+
202
+ ## Linear work queue
203
+
204
+ Apply `bivy` or `bivy/<node>` to a Linear issue to dispatch it to the same hosted queue. The node fetches issue content directly from Linear, works in an isolated GitHub worktree, and asks the agent to open a pull request. See [`docs/linear-work-queue.md`](docs/linear-work-queue.md).
205
+
206
+ ## Development
207
+
208
+ ```bash
209
+ npm install
210
+ npm run dev # node daemon on http://localhost:4317
211
+ npm run dev:web # web client dev server (proxies /api and /ws to the node)
212
+ ```
213
+
214
+ Checks — all of these run in CI:
215
+
216
+ ```bash
217
+ npm run typecheck
218
+ npm run typecheck:web
219
+ npm run lint
220
+ npm run test:unit
221
+ npm run test:core
222
+ npm run check:licenses
223
+ npm run check:secrets
224
+ ```
225
+
226
+ Repository layout:
227
+
228
+ - `src/` — node daemon, runtime adapters, approvals, secrets, sessions
229
+ - `bin/` — the `bivy` CLI
230
+ - `packages/core` — shared protocol, pairing, wire format
231
+ - `packages/web` — the React/Vite PWA client (`@bivy/web`)
232
+ - `services/relay` — self-hostable relay
233
+ - `services/control-plane` — self-hostable control plane
234
+ - `deploy/` — self-host deployment examples
235
+
236
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md).
237
+
238
+ ## Self-hosting
239
+
240
+ Node, relay, and control plane are all in this repository, and the CLI accepts
241
+ flags to point at your own deployment:
242
+
243
+ ```bash
244
+ bivy relay:setup --relay wss://relay.example.com \
245
+ --control-plane https://bivy.example.com
246
+ ```
247
+
248
+ **Self-hosting is unsupported** — no SLA, community best-effort via GitHub
249
+ issues. You own TLS, backups, upgrades, and hardening. See
250
+ [`docs/self-host.md`](docs/self-host.md).
251
+
252
+ ## Security
253
+
254
+ Report vulnerabilities through [GitHub private vulnerability reporting](https://github.com/bivysh/bivy/security/advisories/new).
255
+ Please do not open a public issue. See [`SECURITY.md`](SECURITY.md) for scope,
256
+ response times, and safe harbour, and [`docs/security-model.md`](docs/security-model.md)
257
+ for the trust model and known limitations.
258
+
259
+ ## License
260
+
261
+ Bivy Core is licensed under the Functional Source License (FSL-1.1-ALv2): you may
262
+ use, modify, and self-host it for any purpose **except a Competing Use** —
263
+ offering it to others as a product or service that substitutes for Bivy or Bivy
264
+ Cloud. Two years after each release, that version converts to Apache-2.0.
265
+
266
+ This is a source-available licence, not an OSI-approved open source licence.
267
+
268
+ See [`LICENSE`](LICENSE), [`CORE.md`](CORE.md), and [`CLOUD.md`](CLOUD.md).
@@ -0,0 +1,298 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: FSL-1.1-ALv2
3
+ // Copyright (c) 2026 Petter André Sjulstad
4
+ // ACP ⇄ Bivy Agent Protocol shim — the GENERAL high-capability adapter.
5
+ //
6
+ // The Codex shim (codex-app-server-shim.mjs) proved that driving an agent's
7
+ // bidirectional JSON-RPC app-server — instead of a one-shot stdout pipe — buys
8
+ // per-tool approvals, streaming, and resume. Everything there is Codex-specific is
9
+ // the *protocol*. ACP (Agent Client Protocol, https://agentclientprotocol.com) is
10
+ // the open standard for exactly that surface, and a growing set of agents speak it
11
+ // (Gemini CLI `--experimental-acp`, and others). This shim bridges ANY ACP agent to
12
+ // the bivy-agent-protocol JSONL that ProtocolRuntime (src/runtime/protocol.ts)
13
+ // speaks — so a new ACP agent becomes fully governed (Approve/Deny per tool),
14
+ // streaming, and resumable as DATA (one catalog entry), never per-agent code.
15
+ //
16
+ // Usage (spawned by the daemon's `acp` runtime):
17
+ // node acp-shim.mjs --agent <cmd> [-- <agent args…>]
18
+ //
19
+ // ACP surface implemented (client side of the protocol):
20
+ // → initialize / session/new / session/load / session/prompt / session/cancel
21
+ // ← session/update (agent_message_chunk, agent_thought_chunk, tool_call,
22
+ // tool_call_update, plan) → streamed transcript
23
+ // ← session/request_permission → a bivy `tool.call` we block on until the human
24
+ // taps Approve/Deny (answered as the ACP selected option)
25
+ // ← fs/read_text_file / fs/write_text_file → serviced against the workspace
26
+ //
27
+ // Transport is newline-delimited JSON-RPC 2.0 over the agent's stdio (as Gemini's
28
+ // ACP mode emits). Experimental: validate against your ACP agent, then promote it
29
+ // into the picker as data. Fail-closed on permission (deny if the human declines),
30
+ // fail-safe elsewhere (surface errors as session.error rather than wedging).
31
+
32
+ import { spawn } from "node:child_process";
33
+ import { createInterface } from "node:readline";
34
+ import fs from "node:fs";
35
+
36
+ // --- arg parsing: --agent <cmd> [-- <args…>] --------------------------------
37
+ const argv = process.argv.slice(2);
38
+ let agentCmd = process.env.BIVY_ACP_COMMAND || "";
39
+ let agentArgs = [];
40
+ for (let i = 0; i < argv.length; i++) {
41
+ if (argv[i] === "--agent") agentCmd = argv[++i] ?? "";
42
+ else if (argv[i] === "--") { agentArgs = argv.slice(i + 1); break; }
43
+ }
44
+ if (process.env.BIVY_ACP_ARGS && agentArgs.length === 0) {
45
+ try { const p = JSON.parse(process.env.BIVY_ACP_ARGS); if (Array.isArray(p)) agentArgs = p.map(String); } catch { /* ignore */ }
46
+ }
47
+ if (!agentCmd) {
48
+ process.stderr.write("acp-shim: no agent command (set --agent <cmd> or BIVY_ACP_COMMAND)\n");
49
+ process.exit(2);
50
+ }
51
+
52
+ // --- bivy-agent-protocol output (our stdout) --------------------------------
53
+ function bivy(obj) {
54
+ process.stdout.write(`${JSON.stringify(obj)}\n`);
55
+ }
56
+
57
+ // --- ACP agent (child JSON-RPC over its stdio) ------------------------------
58
+ const agent = spawn(agentCmd, agentArgs, { stdio: ["pipe", "pipe", "pipe"] });
59
+ agent.stderr.on("data", (d) => process.stderr.write(`[acp-agent] ${d}`));
60
+ agent.on("error", (e) => bivy({ type: "session.error", error: `acp agent spawn failed: ${e.message}` }));
61
+ agent.on("exit", (code) => {
62
+ if (code && code !== 0) bivy({ type: "session.error", error: `acp agent exited (${code})` });
63
+ });
64
+
65
+ let nextId = 1;
66
+ const pending = new Map(); // jsonrpc id -> {resolve, reject}
67
+ function agentRequest(method, params) {
68
+ const id = nextId++;
69
+ agent.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
70
+ return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
71
+ }
72
+ function agentReply(id, result) {
73
+ agent.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
74
+ }
75
+ function agentReplyError(id, code, message) {
76
+ agent.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`);
77
+ }
78
+ function agentNotify(method, params) {
79
+ agent.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
80
+ }
81
+
82
+ // --- session state ----------------------------------------------------------
83
+ let sessionId = null;
84
+ let cwd = process.cwd();
85
+ let initialized = false;
86
+ // toolCallId -> { requestId, options } so a later bivy tool.decision answers the
87
+ // right ACP permission request with a concrete optionId.
88
+ const permissionRequests = new Map();
89
+
90
+ async function ensureInitialized() {
91
+ if (initialized) return;
92
+ await agentRequest("initialize", {
93
+ protocolVersion: 1,
94
+ clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
95
+ });
96
+ initialized = true;
97
+ }
98
+
99
+ // --- ACP → bivy: streamed session/update notifications ----------------------
100
+ function onSessionUpdate(params) {
101
+ const u = params?.update;
102
+ if (!u || typeof u !== "object") return;
103
+ const kind = String(u.sessionUpdate || "");
104
+ const textOf = (content) => {
105
+ if (!content) return "";
106
+ if (typeof content === "string") return content;
107
+ if (Array.isArray(content)) return content.map(textOf).join("");
108
+ if (content.type === "text" && typeof content.text === "string") return content.text;
109
+ if (typeof content.text === "string") return content.text;
110
+ return "";
111
+ };
112
+ switch (kind) {
113
+ case "agent_message_chunk": {
114
+ const t = textOf(u.content);
115
+ if (t) bivy({ type: "message.delta", text: t });
116
+ break;
117
+ }
118
+ case "agent_thought_chunk": {
119
+ const t = textOf(u.content);
120
+ if (t) bivy({ type: "message.reasoning", text: t });
121
+ break;
122
+ }
123
+ case "tool_call": {
124
+ // An auto-run tool (no permission requested) — surface it so the transcript
125
+ // shows the action; the result arrives via tool_call_update.
126
+ const toolCallId = String(u.toolCallId ?? u.id ?? "");
127
+ bivy({ type: "tool.call", toolCallId, name: String(u.title || u.kind || "tool"), input: u.rawInput ?? u.input ?? {} });
128
+ break;
129
+ }
130
+ case "tool_call_update": {
131
+ const toolCallId = String(u.toolCallId ?? u.id ?? "");
132
+ const status = String(u.status || "");
133
+ if (status === "completed" || status === "failed") {
134
+ bivy({ type: "tool.result", toolCallId, name: String(u.title || "tool"), result: textOf(u.content) || status });
135
+ }
136
+ break;
137
+ }
138
+ case "plan":
139
+ // Optional planning stream — fold into reasoning so nothing is lost.
140
+ if (Array.isArray(u.entries)) bivy({ type: "message.reasoning", text: u.entries.map((e) => `• ${e.content ?? ""}`).join("\n") });
141
+ break;
142
+ default:
143
+ break;
144
+ }
145
+ }
146
+
147
+ // --- ACP → bivy: agent→client requests (permission, fs) ---------------------
148
+ async function onAgentRequest(id, method, params) {
149
+ switch (method) {
150
+ case "session/request_permission": {
151
+ // Turn the ACP permission prompt into a bivy tool.call the daemon gates via
152
+ // guardianInterceptor; remember the options so the human's decision maps back
153
+ // to a concrete ACP optionId.
154
+ const tc = params?.toolCall ?? {};
155
+ const toolCallId = String(tc.toolCallId ?? tc.id ?? `perm-${id}`);
156
+ const options = Array.isArray(params?.options) ? params.options : [];
157
+ permissionRequests.set(toolCallId, { requestId: id, options });
158
+ bivy({ type: "tool.call", toolCallId, name: String(tc.title || tc.kind || "tool"), input: tc.rawInput ?? tc.input ?? {} });
159
+ return;
160
+ }
161
+ case "fs/read_text_file": {
162
+ try {
163
+ let text = fs.readFileSync(String(params?.path ?? ""), "utf8");
164
+ if (typeof params?.line === "number" || typeof params?.limit === "number") {
165
+ const lines = text.split("\n");
166
+ const start = Math.max(0, (params.line ?? 1) - 1);
167
+ text = lines.slice(start, params.limit ? start + params.limit : undefined).join("\n");
168
+ }
169
+ agentReply(id, { content: text });
170
+ } catch (e) {
171
+ agentReplyError(id, -32000, `read failed: ${e.message}`);
172
+ }
173
+ return;
174
+ }
175
+ case "fs/write_text_file": {
176
+ try {
177
+ fs.writeFileSync(String(params?.path ?? ""), String(params?.content ?? ""));
178
+ agentReply(id, {});
179
+ } catch (e) {
180
+ agentReplyError(id, -32000, `write failed: ${e.message}`);
181
+ }
182
+ return;
183
+ }
184
+ default:
185
+ // Unknown client method (e.g. terminal/*): decline so the agent can fall back
186
+ // instead of hanging on a request we don't implement.
187
+ agentReplyError(id, -32601, `unsupported client method: ${method}`);
188
+ return;
189
+ }
190
+ }
191
+
192
+ // --- read the ACP agent's stdout (JSON-RPC lines) ---------------------------
193
+ createInterface({ input: agent.stdout }).on("line", (line) => {
194
+ const t = line.trim();
195
+ if (!t) return;
196
+ let msg;
197
+ try { msg = JSON.parse(t); } catch { return; }
198
+ // Response to one of our requests.
199
+ if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
200
+ const p = pending.get(msg.id);
201
+ if (p) {
202
+ pending.delete(msg.id);
203
+ if (msg.error) p.reject(new Error(msg.error.message || "acp error"));
204
+ else p.resolve(msg.result);
205
+ }
206
+ return;
207
+ }
208
+ // Agent→client request (has id + method).
209
+ if (msg.id !== undefined && msg.method) { void onAgentRequest(msg.id, msg.method, msg.params); return; }
210
+ // Notification (method, no id).
211
+ if (msg.method === "session/update") onSessionUpdate(msg.params);
212
+ });
213
+
214
+ // --- bivy commands in (daemon → us) -----------------------------------------
215
+ async function onBivyCommand(msg) {
216
+ const type = String(msg.type || "");
217
+ const id = msg.id;
218
+ try {
219
+ switch (type) {
220
+ case "hello.ack":
221
+ return;
222
+ case "session.create": {
223
+ await ensureInitialized();
224
+ cwd = String(msg.cwd || msg.workspace || cwd);
225
+ const res = await agentRequest("session/new", { cwd, mcpServers: [] });
226
+ sessionId = res?.sessionId ?? res?.session?.id ?? null;
227
+ bivy({ replyTo: id, ok: true, runtimeSessionRef: sessionId });
228
+ return;
229
+ }
230
+ case "session.resume": {
231
+ await ensureInitialized();
232
+ const ref = String(msg.runtimeSessionRef || msg.resumeRef || msg.sessionId || "");
233
+ cwd = String(msg.cwd || msg.workspace || cwd);
234
+ if (!ref) { bivy({ replyTo: id, ok: false, error: "missing resume ref" }); return; }
235
+ try {
236
+ const res = await agentRequest("session/load", { sessionId: ref, cwd, mcpServers: [] });
237
+ sessionId = res?.sessionId ?? ref;
238
+ } catch {
239
+ // Agent doesn't support session/load — start fresh so the chat still opens.
240
+ const res = await agentRequest("session/new", { cwd, mcpServers: [] });
241
+ sessionId = res?.sessionId ?? null;
242
+ }
243
+ bivy({ replyTo: id, ok: true, runtimeSessionRef: sessionId });
244
+ return;
245
+ }
246
+ case "chat.send": {
247
+ if (!sessionId) { bivy({ replyTo: id, ok: false, error: "no acp session" }); return; }
248
+ // Ack immediately; the turn streams via session/update and finishes when the
249
+ // session/prompt request resolves (approval cards can make a turn outlast
250
+ // ProtocolRuntime's command timeout, so we must not defer the ack).
251
+ bivy({ replyTo: id, ok: true });
252
+ bivy({ type: "session.status", status: "working" });
253
+ agentRequest("session/prompt", { sessionId, prompt: [{ type: "text", text: String(msg.text ?? "") }] })
254
+ .then(() => { bivy({ type: "session.status", status: "idle" }); bivy({ type: "session.done" }); })
255
+ .catch((e) => bivy({ type: "session.error", error: e instanceof Error ? e.message : String(e) }));
256
+ return;
257
+ }
258
+ case "tool.decision": {
259
+ const entry = permissionRequests.get(msg.toolCallId);
260
+ if (entry) {
261
+ permissionRequests.delete(msg.toolCallId);
262
+ const allow = msg.decision !== "deny";
263
+ // Pick an ACP option matching the human's choice by its `kind`
264
+ // (allow_once/allow_always vs reject_once/reject_always); fall back to the
265
+ // first option, or a cancelled outcome when nothing fits.
266
+ const want = allow ? /^allow/ : /^reject/;
267
+ const opt = entry.options.find((o) => want.test(String(o.kind || ""))) ?? entry.options[0];
268
+ if (opt && opt.optionId !== undefined) agentReply(entry.requestId, { outcome: { outcome: "selected", optionId: opt.optionId } });
269
+ else agentReply(entry.requestId, { outcome: { outcome: "cancelled" } });
270
+ }
271
+ return;
272
+ }
273
+ case "session.abort": {
274
+ if (sessionId) agentNotify("session/cancel", { sessionId });
275
+ if (id !== undefined) bivy({ replyTo: id, ok: true });
276
+ return;
277
+ }
278
+ default:
279
+ if (id !== undefined) bivy({ replyTo: id, ok: true });
280
+ return;
281
+ }
282
+ } catch (error) {
283
+ if (id !== undefined) bivy({ replyTo: id, ok: false, error: error instanceof Error ? error.message : String(error) });
284
+ else bivy({ type: "session.error", error: error instanceof Error ? error.message : String(error) });
285
+ }
286
+ }
287
+
288
+ // Announce capabilities: ACP agents are governed (per-tool permission) and
289
+ // resumable (session/load). Models aren't part of the core ACP surface, so we
290
+ // don't advertise a picker we can't drive.
291
+ bivy({ type: "hello", runtime: { capabilities: { toolInterception: true, modelSelection: false, resume: true } } });
292
+
293
+ createInterface({ input: process.stdin }).on("line", (line) => {
294
+ if (!line.trim()) return;
295
+ let msg;
296
+ try { msg = JSON.parse(line); } catch { return; }
297
+ void onBivyCommand(msg);
298
+ });