@tduyng/pi-opencode-z 0.0.0-stage → 0.0.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.
- package/LICENSE +178 -0
- package/README.md +69 -2
- package/package.json +42 -4
- package/src/client.ts +282 -0
- package/src/config.ts +96 -0
- package/src/index.ts +197 -0
- package/src/mcp.ts +315 -0
- package/src/models.ts +86 -0
- package/src/session.ts +191 -0
- package/src/stream.ts +1013 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
Use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 tduyng
|
package/README.md
CHANGED
|
@@ -1,3 +1,70 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-opencode-z
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Use opencode's Zen models from Pi, including the free ones.
|
|
4
|
+
|
|
5
|
+
Since September 2026 the free tier answers any direct API call with `403 FreeTierError: "OpenCode's free tier can only be used from within OpenCode"`. No API key or proxy gets around it, because the check is on where the request originates. So this extension does not call the Zen API. It drives the opencode background server already running on your machine and lets opencode make the upstream call, which is the one thing the free tier accepts.
|
|
6
|
+
|
|
7
|
+
## How it works
|
|
8
|
+
|
|
9
|
+
The bridge reads the server's url and password from `~/.local/state/opencode/service.json` and talks to it over HTTP basic auth as user `opencode`. If the server is not running, `opencode service start` brings it back.
|
|
10
|
+
|
|
11
|
+
Each Pi session gets one opencode session, rooted in a throwaway temp directory that holds its `opencode.jsonc`. Nothing is written to your repo or to `~/.config/opencode`.
|
|
12
|
+
|
|
13
|
+
Pi's own tools reach the model through a local MCP server, exposed as `pi_read`, `pi_bash`, `pi_edit` and so on. When the model calls one, the bridge holds that MCP request open, hands the call to Pi, and Pi runs the real tool against your real project. The answer goes back over the same held request and opencode carries on in the same session, none the wiser. The model never touches your files directly. Pi does, under Pi's own permissions.
|
|
14
|
+
|
|
15
|
+
Pi hands providers a transcript rather than a prompt and a tool list, so the bridge replays the transcript's system messages to recover the current instructions and tool set before each turn.
|
|
16
|
+
|
|
17
|
+
Cold start costs nothing extra. A plain `opencode run` on a free model spends 9176 input tokens on a one-line prompt. The bridge spends 6941, with 2048 of those served from cache. That 7k floor is opencode's own system prompt and built-in tool schemas. Every approach to this problem pays it, because stripping those tools is exactly what trips the 403.
|
|
18
|
+
|
|
19
|
+
The savings are per turn. opencode holds the conversation, so each turn sends only the new message instead of re-serializing the whole transcript. Tool schemas sit in the cached prefix rather than being pasted back as prose every time. Extensions that drive the opencode CLI instead have to resend everything on every turn and teach the model to hand-write tool calls inside text markers. A mode switch that adds or removes tools keeps the session too: the bridge pushes `notifications/tools/list_changed` over MCP, opencode re-lists, and the cached prefix survives.
|
|
20
|
+
|
|
21
|
+
A full tool-calling turn, measured end to end including a real file read, takes about 10 seconds.
|
|
22
|
+
|
|
23
|
+
## Using it
|
|
24
|
+
|
|
25
|
+
Run `/model` and pick anything under the `opencode-z` provider, for example `opencode-z/mimo-v2.6-flash-free`.
|
|
26
|
+
|
|
27
|
+
From the command line:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pi --provider opencode-z --model mimo-v2.6-flash-free
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Commands
|
|
34
|
+
|
|
35
|
+
`/opencode-z status` shows the server url, the config file, the active models filter, the MCP endpoint, live sessions and the model list. `/opencode-z models` lists the models alone, free ones first. `/opencode-z refresh` re-reads the config file and the catalogue from opencode. `/opencode-z config` shows the resolved settings and where they come from. `/opencode-z help` prints usage.
|
|
36
|
+
|
|
37
|
+
## Settings
|
|
38
|
+
|
|
39
|
+
Settings live in `opencode-z.json` inside Pi's agent directory (usually `~/.pi/agent/opencode-z.json`). A project's `.pi/opencode-z.json` overrides it field by field. Environment variables override both, so either mechanism works and one-off runs never need to touch a file. `/opencode-z config` shows the resolved values, and `/opencode-z refresh` re-reads both files without restarting Pi.
|
|
40
|
+
|
|
41
|
+
Free models only:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"models": "free"
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A pinned list with a custom binary:
|
|
50
|
+
|
|
51
|
+
```json
|
|
52
|
+
{
|
|
53
|
+
"bin": "/path/to/opencode",
|
|
54
|
+
"models": ["mimo-v2.6-flash-free", "muse-spark-1.3"]
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`bin` overrides the `opencode` executable. `models` narrows what gets registered: `free` keeps zero-cost models, a comma-separated string or an array of ids pins the list. Unset or empty, the bridge registers every Zen model your account can reach, free and paid. Only Zen models appear here (the `opencode` provider in opencode's catalogue), never other providers. `OPENCODE_Z_BIN` and `OPENCODE_Z_MODELS` do the same per process and win over the file.
|
|
59
|
+
|
|
60
|
+
## Notes
|
|
61
|
+
|
|
62
|
+
The bridge never denies opencode's built-in tools. A `deny` rule anywhere in the agent's permissions trips the free tier 403 even for tools that were allowed, so every action stays on `ask` and the bridge rejects the unwanted ones at runtime. A weaker model sometimes reaches for its built-in `read` first, gets refused, and retries with `pi_read`, which costs one round trip.
|
|
63
|
+
|
|
64
|
+
opencode adds and retires Zen models often. The catalogue is read live at startup, and `/opencode-z refresh` re-reads it without restarting Pi.
|
|
65
|
+
|
|
66
|
+
The first prompt lists the exact MCP names available in that turn. Some model hosts display these tools under a `functions.` namespace. The bridge states that the label does not rename a tool, which keeps a model from mistaking disabled `read` for `pi_read`. A successful model step with reasoning but no text or tool call is re-prompted through the same bounded recovery path, and so is a step whose only text is a pi_ call written out as chat template markup instead of dispatched.
|
|
67
|
+
|
|
68
|
+
opencode stops a whole step when the model calls two of its built-in tools at once: refusing one declines the rest. The bridge counts its own refusals and, when that stop was its doing, re-prompts the same session with a nudge back to the pi_ tools (at most twice per turn) instead of failing the turn.
|
|
69
|
+
|
|
70
|
+
When a turn fails, the bridge interrupts opencode and answers waiting tool calls with an error. It keeps the opencode session when Pi's transcript still ends at the last completed user message, so a retry can reuse the prompt cache. If Pi's transcript contains a partial assistant or tool result, the bridge drops the session and rebuilds it from Pi's transcript. A timeout usually means the model was still working (large contexts on high thinking levels are slow) or opencode got stuck waiting.
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tduyng/pi-opencode-z",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Use opencode's Zen models from Pi, including the free ones, by driving the local opencode server and bridging Pi tools over MCP.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi",
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"opencode",
|
|
11
|
+
"models"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-opencode-z#readme",
|
|
14
|
+
"bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
|
|
15
|
+
"license": "Apache-2.0",
|
|
16
|
+
"author": "tduyng",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://gitlab.com/tduyng/pi-agent.git",
|
|
20
|
+
"directory": "extensions/pi-opencode-z"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"files": [
|
|
24
|
+
"src",
|
|
25
|
+
"!src/**/*.test.ts",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE"
|
|
28
|
+
],
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@earendil-works/pi-ai": "*",
|
|
31
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"pi": {
|
|
37
|
+
"extensions": [
|
|
38
|
+
"./src/index.ts"
|
|
39
|
+
]
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"ata-validator": "^1.62.1"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
import { Validator } from 'ata-validator'
|
|
7
|
+
import { t } from 'ata-validator/t'
|
|
8
|
+
|
|
9
|
+
import { bridgeBin } from './config.js'
|
|
10
|
+
const isString = new Validator(t.string()).isValidObject
|
|
11
|
+
|
|
12
|
+
export type ServiceInfo = {
|
|
13
|
+
url: string
|
|
14
|
+
password: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type JsonInput = null | boolean | number | string | undefined | JsonInput[] | JsonInputRecord
|
|
18
|
+
|
|
19
|
+
interface JsonInputRecord {
|
|
20
|
+
[key: string]: JsonInput
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type OpenCodeEvent = {
|
|
24
|
+
type: string
|
|
25
|
+
data?: JsonInputRecord
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type RequestBody = JsonInputRecord
|
|
29
|
+
|
|
30
|
+
const OpenCodeEventSchema = t.object({ type: t.string() }, { additionalProperties: true })
|
|
31
|
+
const isOpenCodeEventSchema = new Validator(OpenCodeEventSchema).isValidObject
|
|
32
|
+
|
|
33
|
+
const SERVICE_USER = 'opencode'
|
|
34
|
+
const PROBE_TIMEOUT_MS = 4_000
|
|
35
|
+
const START_ATTEMPTS = 10
|
|
36
|
+
const START_DELAY_MS = 500
|
|
37
|
+
const RECONNECT_DELAY_MS = 1_000
|
|
38
|
+
const MAX_SSE_LINE_BYTES = 8 * 1024 * 1024
|
|
39
|
+
const API_TIMEOUT_MS = 15_000
|
|
40
|
+
|
|
41
|
+
let service: ServiceInfo | undefined
|
|
42
|
+
|
|
43
|
+
export function opencodeBin(): string {
|
|
44
|
+
return bridgeBin()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function statePath(): string {
|
|
48
|
+
const xdg = process.env['XDG_STATE_HOME']?.trim()
|
|
49
|
+
const base = xdg || join(homedir(), '.local', 'state')
|
|
50
|
+
return join(base, 'opencode', 'service.json')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function readService(): Promise<ServiceInfo | undefined> {
|
|
54
|
+
try {
|
|
55
|
+
const raw = await readFile(statePath(), 'utf8')
|
|
56
|
+
const parsed = JSON.parse(raw) as { url?: unknown; password?: unknown }
|
|
57
|
+
if (!isString(parsed.url) || !parsed.url) return undefined
|
|
58
|
+
if (!isString(parsed.password) || !parsed.password) return undefined
|
|
59
|
+
return { url: parsed.url.replace(/\/+$/, ''), password: parsed.password }
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function basic(info: ServiceInfo): string {
|
|
66
|
+
return `Basic ${Buffer.from(`${SERVICE_USER}:${info.password}`).toString('base64')}`
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function probe(info: ServiceInfo): Promise<boolean> {
|
|
70
|
+
try {
|
|
71
|
+
const response = await fetch(`${info.url}/api/info`, {
|
|
72
|
+
headers: { authorization: basic(info) },
|
|
73
|
+
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
|
|
74
|
+
})
|
|
75
|
+
return response.ok
|
|
76
|
+
} catch {
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function startService(): void {
|
|
82
|
+
try {
|
|
83
|
+
const child = spawn(opencodeBin(), ['service', 'start'], {
|
|
84
|
+
stdio: 'ignore',
|
|
85
|
+
env: { ...process.env, OPENCODE_DISABLE_UPDATE_CHECK: '1' }
|
|
86
|
+
})
|
|
87
|
+
child.on('error', () => undefined)
|
|
88
|
+
child.unref?.()
|
|
89
|
+
} catch {}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
93
|
+
|
|
94
|
+
export async function resolveService(force = false): Promise<ServiceInfo> {
|
|
95
|
+
if (service && !force && (await probe(service))) return service
|
|
96
|
+
|
|
97
|
+
const existing = await readService()
|
|
98
|
+
if (existing && (await probe(existing))) {
|
|
99
|
+
service = existing
|
|
100
|
+
return service
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
startService()
|
|
104
|
+
for (let attempt = 0; attempt < START_ATTEMPTS; attempt++) {
|
|
105
|
+
await sleep(START_DELAY_MS)
|
|
106
|
+
const info = await readService()
|
|
107
|
+
if (info && (await probe(info))) {
|
|
108
|
+
service = info
|
|
109
|
+
return service
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
throw new Error(
|
|
113
|
+
`opencode server is not reachable. Checked ${statePath()}; run \`${opencodeBin()} service start\` and retry.`
|
|
114
|
+
)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function currentService(): ServiceInfo | undefined {
|
|
118
|
+
return service
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function api<T = unknown>(
|
|
122
|
+
method: string,
|
|
123
|
+
path: string,
|
|
124
|
+
body?: RequestBody,
|
|
125
|
+
signal?: AbortSignal
|
|
126
|
+
): Promise<T> {
|
|
127
|
+
const info = service ?? (await resolveService())
|
|
128
|
+
try {
|
|
129
|
+
return await request<T>(info, method, path, body, signal)
|
|
130
|
+
} catch (error) {
|
|
131
|
+
// A cached url or password goes stale when the server restarts. Retry a read, or a write
|
|
132
|
+
// the server rejected outright with 401; a POST that drops mid-flight may already have run.
|
|
133
|
+
const stale =
|
|
134
|
+
(error instanceof Error && error.message.includes('(401)')) ||
|
|
135
|
+
((method === 'GET' || method === 'DELETE') && error instanceof TypeError)
|
|
136
|
+
if (signal?.aborted || !stale) throw error
|
|
137
|
+
service = undefined
|
|
138
|
+
return request<T>(await resolveService(), method, path, body, signal)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function request<T>(
|
|
143
|
+
info: ServiceInfo,
|
|
144
|
+
method: string,
|
|
145
|
+
path: string,
|
|
146
|
+
body?: RequestBody,
|
|
147
|
+
signal?: AbortSignal
|
|
148
|
+
): Promise<T> {
|
|
149
|
+
const timeout = AbortSignal.timeout(API_TIMEOUT_MS)
|
|
150
|
+
const headers = new Headers({ authorization: basic(info) })
|
|
151
|
+
if (body !== undefined) headers.set('content-type', 'application/json')
|
|
152
|
+
const response = await fetch(`${info.url}${path}`, {
|
|
153
|
+
method,
|
|
154
|
+
headers,
|
|
155
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
156
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout
|
|
157
|
+
})
|
|
158
|
+
const text = await response.text()
|
|
159
|
+
if (!response.ok) {
|
|
160
|
+
throw new Error(`opencode ${method} ${path} failed (${response.status}): ${text.slice(0, 400)}`)
|
|
161
|
+
}
|
|
162
|
+
return (text ? JSON.parse(text) : undefined) as T
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export type ZenModel = {
|
|
166
|
+
id: string
|
|
167
|
+
name?: string
|
|
168
|
+
providerID: string
|
|
169
|
+
status?: string
|
|
170
|
+
enabled?: boolean
|
|
171
|
+
capabilities?: { tools?: boolean; input?: string[]; output?: string[] }
|
|
172
|
+
variants?: { id: string }[]
|
|
173
|
+
cost?: { input?: number; output?: number; cache?: { read?: number; write?: number } }[]
|
|
174
|
+
limit?: { context?: number; output?: number }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function fetchZenModels(): Promise<ZenModel[]> {
|
|
178
|
+
const payload = await api<{ data?: ZenModel[] }>('GET', '/api/model')
|
|
179
|
+
const all = payload?.data ?? []
|
|
180
|
+
return all.filter(
|
|
181
|
+
(model) =>
|
|
182
|
+
model.providerID === 'opencode' &&
|
|
183
|
+
model.enabled !== false &&
|
|
184
|
+
(model.status === undefined || model.status === 'active')
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export type EventStreamHandle = {
|
|
189
|
+
stop(): void
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
type SseLineParser = {
|
|
193
|
+
push(text: string): string[]
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function parseOpenCodeEvent(raw: string): OpenCodeEvent | undefined {
|
|
197
|
+
try {
|
|
198
|
+
const value: unknown = JSON.parse(raw)
|
|
199
|
+
return isOpenCodeEventSchema(value) ? value : undefined
|
|
200
|
+
} catch {
|
|
201
|
+
return undefined
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function createSseLineParser(maxLineBytes = MAX_SSE_LINE_BYTES): SseLineParser {
|
|
206
|
+
let buffered = ''
|
|
207
|
+
let discarding = false
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
push(text: string): string[] {
|
|
211
|
+
if (!text) return []
|
|
212
|
+
buffered += text
|
|
213
|
+
const lines: string[] = []
|
|
214
|
+
while (true) {
|
|
215
|
+
const newline = buffered.indexOf('\n')
|
|
216
|
+
if (newline < 0) {
|
|
217
|
+
if (Buffer.byteLength(buffered, 'utf8') > maxLineBytes) {
|
|
218
|
+
buffered = ''
|
|
219
|
+
discarding = true
|
|
220
|
+
}
|
|
221
|
+
return lines
|
|
222
|
+
}
|
|
223
|
+
const line = buffered.slice(0, newline)
|
|
224
|
+
buffered = buffered.slice(newline + 1)
|
|
225
|
+
if (discarding) {
|
|
226
|
+
discarding = false
|
|
227
|
+
continue
|
|
228
|
+
}
|
|
229
|
+
if (Buffer.byteLength(line, 'utf8') <= maxLineBytes) lines.push(line)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function startEventStream(onEvent: (event: OpenCodeEvent) => void): EventStreamHandle {
|
|
236
|
+
const state = { stopped: false }
|
|
237
|
+
let controller: AbortController | undefined
|
|
238
|
+
|
|
239
|
+
const run = async () => {
|
|
240
|
+
while (!state.stopped) {
|
|
241
|
+
try {
|
|
242
|
+
const info = await resolveService()
|
|
243
|
+
controller = new AbortController()
|
|
244
|
+
const response = await fetch(`${info.url}/api/event`, {
|
|
245
|
+
headers: { authorization: basic(info), accept: 'text/event-stream' },
|
|
246
|
+
signal: controller.signal
|
|
247
|
+
})
|
|
248
|
+
if (!response.ok || !response.body) throw new Error(`event stream returned ${response.status}`)
|
|
249
|
+
|
|
250
|
+
const reader = response.body.getReader()
|
|
251
|
+
const decoder = new TextDecoder()
|
|
252
|
+
const parser = createSseLineParser()
|
|
253
|
+
while (!state.stopped) {
|
|
254
|
+
const { value, done } = await reader.read()
|
|
255
|
+
if (done) break
|
|
256
|
+
for (const line of parser.push(decoder.decode(value, { stream: true }))) {
|
|
257
|
+
if (!line.startsWith('data:')) continue
|
|
258
|
+
const raw = line.slice(5).trim()
|
|
259
|
+
if (!raw) continue
|
|
260
|
+
const event = parseOpenCodeEvent(raw)
|
|
261
|
+
if (event) {
|
|
262
|
+
try {
|
|
263
|
+
onEvent(event)
|
|
264
|
+
} catch {}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
} catch {}
|
|
269
|
+
if (state.stopped) return
|
|
270
|
+
await sleep(RECONNECT_DELAY_MS)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
void run()
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
stop() {
|
|
278
|
+
state.stopped = true
|
|
279
|
+
controller?.abort()
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent'
|
|
4
|
+
import type { JsonObject, JsonValue } from '@earendil-works/pi-ai'
|
|
5
|
+
import { Validator } from 'ata-validator'
|
|
6
|
+
import { t } from 'ata-validator/t'
|
|
7
|
+
|
|
8
|
+
const isString = new Validator(t.string()).isValidObject
|
|
9
|
+
|
|
10
|
+
export type BridgeFileConfig = {
|
|
11
|
+
bin?: string
|
|
12
|
+
models?: string | string[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const BRIDGE_CONFIG_FILE = 'opencode-z.json'
|
|
16
|
+
|
|
17
|
+
export function configPath(): string {
|
|
18
|
+
return join(getAgentDir(), BRIDGE_CONFIG_FILE)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function projectConfigPath(): string {
|
|
22
|
+
return join(process.cwd(), '.pi', BRIDGE_CONFIG_FILE)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const BridgeFileSchema = t.object({}, { additionalProperties: true })
|
|
26
|
+
const isBridgeFileSchema = new Validator(BridgeFileSchema).isValidObject
|
|
27
|
+
|
|
28
|
+
function isJsonRecord(value: JsonValue | undefined): value is JsonObject {
|
|
29
|
+
return isBridgeFileSchema(value) && !Array.isArray(value)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function parseBridgeFile(raw: JsonValue | undefined): BridgeFileConfig {
|
|
33
|
+
if (!isJsonRecord(raw)) return {}
|
|
34
|
+
const config: BridgeFileConfig = {}
|
|
35
|
+
const bin = raw['bin']
|
|
36
|
+
if (isString(bin) && bin.trim()) config.bin = bin.trim()
|
|
37
|
+
const models = raw['models']
|
|
38
|
+
if (isString(models) && models.trim()) {
|
|
39
|
+
config.models = models.trim()
|
|
40
|
+
} else if (Array.isArray(models)) {
|
|
41
|
+
const ids = models
|
|
42
|
+
.filter((id): id is string => isString(id))
|
|
43
|
+
.map((id) => id.trim())
|
|
44
|
+
.filter(Boolean)
|
|
45
|
+
if (ids.length > 0) config.models = ids
|
|
46
|
+
}
|
|
47
|
+
return config
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readBridgeFile(path: string): BridgeFileConfig {
|
|
51
|
+
try {
|
|
52
|
+
return parseBridgeFile(JSON.parse(readFileSync(path, 'utf8')))
|
|
53
|
+
} catch {
|
|
54
|
+
return {}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function mergeBridgeFile(base: BridgeFileConfig, project: BridgeFileConfig): BridgeFileConfig {
|
|
59
|
+
return { ...base, ...project }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function loadBridgeFile(path?: string): BridgeFileConfig {
|
|
63
|
+
if (path !== undefined) return readBridgeFile(path)
|
|
64
|
+
return mergeBridgeFile(readBridgeFile(configPath()), readBridgeFile(projectConfigPath()))
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function normalizeModelsFilter(value: string | string[] | undefined): string | undefined {
|
|
68
|
+
if (isString(value)) return value.trim() || undefined
|
|
69
|
+
if (Array.isArray(value)) {
|
|
70
|
+
const joined = value
|
|
71
|
+
.map((id) => id.trim())
|
|
72
|
+
.filter(Boolean)
|
|
73
|
+
.join(',')
|
|
74
|
+
return joined || undefined
|
|
75
|
+
}
|
|
76
|
+
return undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function resolveModelsRaw(
|
|
80
|
+
envRaw: string | undefined,
|
|
81
|
+
fileModels: string | string[] | undefined
|
|
82
|
+
): string | undefined {
|
|
83
|
+
return envRaw?.trim() || normalizeModelsFilter(fileModels)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function resolveBin(envRaw: string | undefined, fileBin: string | undefined): string {
|
|
87
|
+
return envRaw?.trim() || fileBin?.trim() || 'opencode'
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function bridgeBin(): string {
|
|
91
|
+
return resolveBin(process.env['OPENCODE_Z_BIN'], readBridgeFile(configPath()).bin)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function bridgeModelsRaw(): string | undefined {
|
|
95
|
+
return resolveModelsRaw(process.env['OPENCODE_Z_MODELS'], loadBridgeFile().models)
|
|
96
|
+
}
|