opencode-copilot-auto 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.1 (2026-11-22)
4
+
5
+ - Fixes 0.1.0 hiding the models Auto routes to. OpenCode refuses a hidden model, so a request failed whenever Auto picked a model other than the picker's one entry. All allowed models stay on again, each labelled "· via Auto".
6
+
7
+ ## 0.1.0 (2026-11-22)
8
+
9
+ - Makes GitHub Copilot Free work in OpenCode 2.x by routing requests through Copilot's Auto mode.
10
+ - Turns on only for accounts OpenCode can't serve by itself, and follows login changes within 30 seconds.
11
+ - Shows one picker entry, "Auto (Copilot picks the model)", since Auto decides which model answers. (This broke routing; fixed in 0.1.1.)
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 the opencode-copilot-auto authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # opencode-copilot-auto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Makes **GitHub Copilot Free** work in [OpenCode](https://opencode.ai) 2.x.
4
+
5
+ ## The problem
6
+
7
+ With a Copilot Free account connected, OpenCode's model picker shows the Copilot
8
+ models for a moment and then empties. Picking one by name fails with
9
+ `The requested model is not supported.`
10
+
11
+ Copilot Free only serves requests that go through Copilot's **Auto** mode: the
12
+ client asks Copilot which model to use, then sends the request to that model with
13
+ a short-lived session token. OpenCode only does this for plans whose models carry
14
+ an Auto discount, which Free doesn't have.
15
+
16
+ ## What the plugin does
17
+
18
+ It turns on only when OpenCode can't serve your account by itself: GitHub marks
19
+ none of your models as pickable and none has an Auto discount. That's Copilot
20
+ Free today; the check doesn't rely on plan names. It then:
21
+
22
+ - shows the chat models GitHub allows your account in the model picker, each
23
+ labelled **· via Auto**, because Auto decides which model answers whatever you
24
+ pick, and
25
+ - routes requests for those models through Auto: it asks Copilot which model to
26
+ use, switches the request to it, and adds Auto's session token. Auto keeps its
27
+ pick for the session until the token is about to expire, or until the session
28
+ is compacted.
29
+
30
+ On any other account it does nothing, so OpenCode's own Copilot support is
31
+ untouched. A reconnect or disconnect is noticed within 30 seconds. It doesn't impersonate another client: requests use your OpenCode
32
+ Copilot login and identify themselves as `opencode-copilot-auto`.
33
+
34
+ ## Install
35
+
36
+ 1. Connect GitHub Copilot in OpenCode as usual.
37
+ 2. Add the plugin to `opencode.json`:
38
+
39
+ ```json
40
+ { "plugin": ["opencode-copilot-auto@0.1.0"] }
41
+ ```
42
+
43
+ or copy `index.js` to `~/.config/opencode/plugins/copilot-auto.js`.
44
+ 3. Restart OpenCode and pick any GitHub Copilot model marked **· via Auto**.
45
+
46
+ The model that actually answered is shown under each reply.
47
+
48
+ Your latest message (up to 2,000 characters) is sent to Copilot's `/auto`
49
+ endpoint so Copilot can choose a model, as Copilot's own clients do.
50
+
51
+ ## Settings
52
+
53
+ | `OPENCODE_COPILOT_AUTO` | Effect |
54
+ |---|---|
55
+ | unset or `auto` | Route through Auto only when OpenCode can't serve the account (Copilot Free) |
56
+ | `always` | Route through Auto on every plan |
57
+ | `off` | Do nothing |
58
+
59
+ ## Limits
60
+
61
+ - Copilot Free has a small monthly chat allowance, and an agent sends one
62
+ request per tool step, so long tasks use it up quickly.
63
+ - Session titles aren't routed (they would spend the allowance). Set a
64
+ `small_model` from another provider for titles.
65
+ - It relies on OpenCode's plugin API (`integration.connection`, `model.transform`,
66
+ `session.hook`) and on Copilot's `/auto` endpoint, neither of which is a
67
+ documented stable API. Tested with OpenCode 2.3.2 on 2026-11-18. On older
68
+ OpenCode versions that lack the API it does nothing.
69
+ - It sends the Copilot API versions OpenCode 2.3 sends (`X-GitHub-Api-Version`
70
+ `2026-08-01`, and `2025-04-01` for the account check). When GitHub retires
71
+ those, requests fail with an HTTP error until the plugin is updated.
72
+
73
+ ## Development
74
+
75
+ ```bash
76
+ npm test
77
+ ```
78
+
79
+ The tests use a fake OpenCode host and a fake Copilot API; they make no network
80
+ requests.
package/index.js ADDED
@@ -0,0 +1,248 @@
1
+ // opencode-copilot-auto: makes GitHub Copilot Free usable in OpenCode 2.x.
2
+ //
3
+ // Copilot Free only answers requests that go through Copilot's Auto mode: ask
4
+ // /auto which model to use, then send the request to that model together with
5
+ // the session token Auto returned. OpenCode only does this for plans whose models
6
+ // carry an Auto discount, which Free doesn't, so every request fails with
7
+ // "The requested model is not supported" and the model picker stays empty.
8
+ //
9
+ // It turns on only when OpenCode can't serve the account by itself: GitHub marks
10
+ // none of the account's models as pickable and none has an Auto discount. That is
11
+ // Copilot Free today. It then:
12
+ // - shows the chat models GitHub allows the account in the model picker,
13
+ // each labelled "· via Auto", since Auto decides which model answers
14
+ // whatever is picked. They all stay switched on: OpenCode refuses to run a
15
+ // hidden model, and Auto may pick any of them.
16
+ // - when one is used, asks Auto which model to run and routes the request
17
+ // there with Auto's session token.
18
+ // On any other account it does nothing, so OpenCode's own Copilot support is untouched.
19
+ //
20
+ // Set OPENCODE_COPILOT_AUTO=off to turn it off, or =always to route through Auto
21
+ // whatever the plan.
22
+
23
+ import { createHash } from "node:crypto"
24
+
25
+ export const VERSION = "0.1.1"
26
+ const PROVIDER = "github-copilot"
27
+ const USER_AGENT = `opencode-copilot-auto/${VERSION}`
28
+ const API_VERSION = "2026-08-01" // what OpenCode 2.3 sends to the Copilot API
29
+ const USER_API_VERSION = "2025-04-01" // what OpenCode 2.3 sends to copilot_internal/user
30
+ const CREDENTIAL_TTL_MS = 30 * 1000 // notice a reconnect or disconnect within 30 seconds
31
+ const ACCOUNT_TTL_MS = 60 * 60 * 1000 // re-check plan and models hourly
32
+ const ACCOUNT_RETRY_MS = 60 * 1000 // after a failed check, try again a minute later
33
+ const RENEW_EARLY_MS = 5 * 60 * 1000 // renew Auto's pick 5 minutes before its token expires
34
+ const DEFAULT_ROUTE_MS = 20 * 60 * 1000 // when Auto gives no expiry
35
+ const TIMEOUT_MS = 15 * 1000
36
+ const MAX_SESSIONS = 200
37
+ const MAX_PROMPT_CHARS = 2000
38
+ const VIA_AUTO = " · via Auto"
39
+
40
+ // ---------- reading OpenCode's Copilot login ----------
41
+
42
+ // Uses OpenCode's own integration API, so the plugin never touches its database.
43
+ export async function readCredentialFromOpenCode(ctx) {
44
+ const connections = ctx?.integration?.connection
45
+ if (typeof connections?.active !== "function" || typeof connections?.resolve !== "function") return undefined
46
+ const connection = await connections.active(PROVIDER)
47
+ if (!connection) return undefined
48
+ const credential = await connections.resolve(connection)
49
+ const token = credential?.type === "oauth" ? credential.refresh || credential.access : undefined
50
+ if (typeof token !== "string" || !token) return undefined
51
+ return { token, metadata: credential.metadata ?? {} }
52
+ }
53
+
54
+ // ---------- the plugin ----------
55
+
56
+ export function createPlugin(deps = {}) {
57
+ const readCredentialFrom = deps.readCredential ?? readCredentialFromOpenCode
58
+ const http = deps.fetch ?? ((...args) => fetch(...args))
59
+ const now = deps.now ?? (() => Date.now())
60
+ const mode = (deps.mode ?? process.env.OPENCODE_COPILOT_AUTO ?? "auto").toLowerCase()
61
+ const log = deps.log ?? (() => {})
62
+
63
+ let account // { key, needsAuto, models: Set, base, plan, checkedAt, ok }
64
+ let accountLoad // in-flight account check
65
+ const routes = new Map() // sessionID -> { model, token, until, key }
66
+ const picking = new Map() // sessionID -> in-flight pick
67
+
68
+ async function request(url, { token, version, body }) {
69
+ const response = await http(url, {
70
+ method: body === undefined ? "GET" : "POST",
71
+ headers: {
72
+ Accept: "application/json",
73
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
74
+ Authorization: "Bearer " + token,
75
+ "User-Agent": USER_AGENT,
76
+ "X-GitHub-Api-Version": version,
77
+ },
78
+ body: body === undefined ? undefined : JSON.stringify(body),
79
+ signal: AbortSignal.timeout(TIMEOUT_MS),
80
+ })
81
+ if (!response.ok) throw new Error(`${new URL(url).pathname} answered HTTP ${response.status}`)
82
+ return response.json()
83
+ }
84
+
85
+ async function checkAccount(credential, key) {
86
+ const enterprise = typeof credential.metadata.enterpriseUrl === "string" && credential.metadata.enterpriseUrl
87
+ const enterpriseHost = enterprise ? enterprise.replace(/^https?:\/\//, "").replace(/\/+$/, "") : undefined
88
+ const apiHost = enterpriseHost ? `https://api.${enterpriseHost}` : "https://api.github.com"
89
+ const user = await request(`${apiHost}/copilot_internal/user`, { token: credential.token, version: USER_API_VERSION })
90
+ const base = String(
91
+ user?.endpoints?.api || credential.metadata.apiEndpoint ||
92
+ (enterpriseHost ? `https://copilot-api.${enterpriseHost}` : "https://api.githubcopilot.com"),
93
+ ).replace(/\/+$/, "")
94
+ const list = await request(`${base}/models`, { token: credential.token, version: API_VERSION })
95
+ const data = (Array.isArray(list?.data) ? list.data : []).filter((m) => m && typeof m.id === "string")
96
+ // OpenCode serves an account by itself when it can show models or route Auto.
97
+ const servedByOpenCode = data.some((m) => m.model_picker_enabled === true || m.billing?.auto_discount !== undefined)
98
+ const models = new Set(
99
+ data
100
+ .filter((m) =>
101
+ m.policy?.state === "enabled" &&
102
+ (m.capabilities?.type ?? "chat") === "chat" && m.capabilities?.supports?.tool_calls === true)
103
+ .map((m) => m.id),
104
+ )
105
+ return { key, needsAuto: !servedByOpenCode, base, models, plan: String(user?.access_type_sku ?? ""), ok: true }
106
+ }
107
+
108
+ // The current login, re-read at most every 30 seconds. Never throws.
109
+ let login // { credential, key, at }
110
+ async function currentLogin(ctx) {
111
+ if (login && now() - login.at < CREDENTIAL_TTL_MS) return login
112
+ let credential
113
+ try { credential = await readCredentialFrom(ctx) } catch (error) { log("reading the Copilot login failed: " + error.message) }
114
+ const key = credential ? createHash("sha256").update(credential.token).digest("hex").slice(0, 16) : undefined
115
+ login = { credential, key, at: now() }
116
+ return login
117
+ }
118
+
119
+ // Cached account state for the current login; never throws (a failed check means "do nothing").
120
+ async function getAccount(ctx) {
121
+ const { credential, key } = await currentLogin(ctx)
122
+ if (!credential) return { key: undefined, needsAuto: false, models: new Set() }
123
+ if (account && account.key === key) {
124
+ const age = now() - account.checkedAt
125
+ if (age < (account.ok ? ACCOUNT_TTL_MS : ACCOUNT_RETRY_MS)) return account
126
+ }
127
+ if (!accountLoad || accountLoad.key !== key) {
128
+ const load = checkAccount(credential, key)
129
+ .catch((error) => {
130
+ log("account check failed: " + error.message)
131
+ const previous = account?.key === key ? account : { key, needsAuto: false, models: new Set() }
132
+ return { ...previous, ok: false }
133
+ })
134
+ .then((result) => {
135
+ account = { ...result, checkedAt: now() }
136
+ return account
137
+ })
138
+ .finally(() => { if (accountLoad?.promise === load) accountLoad = undefined })
139
+ accountLoad = { key, promise: load }
140
+ }
141
+ return accountLoad.promise
142
+ }
143
+
144
+ function active(acct) {
145
+ return mode !== "off" && acct.key !== undefined && (acct.needsAuto || mode === "always")
146
+ }
147
+
148
+ async function promptFor(ctx, sessionID) {
149
+ try {
150
+ if (typeof ctx.session?.context !== "function") return undefined
151
+ const entries = await ctx.session.context({ sessionID })
152
+ const user = Array.isArray(entries) ? entries.findLast((e) => e?.type === "user") : undefined
153
+ return typeof user?.text === "string" ? user.text.slice(0, MAX_PROMPT_CHARS) : undefined
154
+ } catch {
155
+ return undefined
156
+ }
157
+ }
158
+
159
+ async function pick(ctx, sessionID, acct) {
160
+ const { credential, key } = await currentLogin(ctx)
161
+ if (!credential || key !== acct.key) throw new Error("the GitHub Copilot login changed; try again")
162
+ const prompt = (await promptFor(ctx, sessionID)) || "Help me with my code."
163
+ const answer = await request(`${acct.base}/auto`, { token: credential.token, version: API_VERSION, body: { prompt } })
164
+ const model = answer?.selected_model?.id
165
+ if (typeof model !== "string" || typeof answer?.session_token !== "string") {
166
+ throw new Error("Copilot Auto returned no model")
167
+ }
168
+ const expires = Number(answer.expires_at) * 1000
169
+ const until = Number.isFinite(expires) && expires > now() ? Math.max(now(), expires - RENEW_EARLY_MS) : now() + DEFAULT_ROUTE_MS
170
+ return { model, token: answer.session_token, until, key: acct.key }
171
+ }
172
+
173
+ function remember(sessionID, route) {
174
+ routes.delete(sessionID)
175
+ routes.set(sessionID, route)
176
+ while (routes.size > MAX_SESSIONS) routes.delete(routes.keys().next().value)
177
+ }
178
+
179
+ async function routeFor(ctx, sessionID, acct) {
180
+ const cached = routes.get(sessionID)
181
+ if (cached && cached.key === acct.key && cached.until > now()) return cached
182
+ let pending = picking.get(sessionID)
183
+ if (!pending) {
184
+ pending = pick(ctx, sessionID, acct)
185
+ .then((route) => { remember(sessionID, route); return route })
186
+ .finally(() => picking.delete(sessionID))
187
+ picking.set(sessionID, pending)
188
+ }
189
+ return pending
190
+ }
191
+
192
+ return {
193
+ id: "copilot-auto",
194
+ async setup(ctx) {
195
+ if (mode === "off") return
196
+ // Check the account now. OpenCode may have built its model list already,
197
+ // so rebuild it once the allowed models are known, to unhide them.
198
+ getAccount(ctx).then((acct) => {
199
+ if (!active(acct) || !acct.models.size || typeof ctx.model?.reload !== "function") return
200
+ try {
201
+ Promise.resolve(ctx.model.reload()).catch(() => {})
202
+ } catch {}
203
+ })
204
+
205
+ if (typeof ctx.model?.transform === "function") {
206
+ await ctx.model.transform((models) => {
207
+ if (!account || !active(account) || account.key !== login?.key) return
208
+ // Every allowed model stays on: Auto may route to any of them, and OpenCode
209
+ // refuses a hidden one. The label says Auto decides, whatever is picked.
210
+ for (const id of account.models) {
211
+ if (!models.get(PROVIDER, id)) continue
212
+ models.update(PROVIDER, id, (m) => {
213
+ m.enabled = true
214
+ const name = typeof m.name === "string" && m.name ? m.name : id
215
+ if (!name.endsWith(VIA_AUTO)) m.name = name + VIA_AUTO
216
+ })
217
+ }
218
+ })
219
+ }
220
+
221
+ await ctx.session.hook("experimental.model.resolve", async (call) => {
222
+ if (call.kind === "title" || call.model?.providerID !== PROVIDER) return
223
+ const acct = await getAccount(ctx)
224
+ if (!active(acct) || !acct.models.has(call.model.id)) return
225
+ let route
226
+ try {
227
+ route = await routeFor(ctx, call.sessionID, acct)
228
+ } catch (error) {
229
+ throw new Error(`copilot-auto: Copilot Auto failed (${error.message}). Try again in a moment, or pick another model.`)
230
+ }
231
+ call.model = { providerID: PROVIDER, id: route.model }
232
+ }, { providerID: PROVIDER })
233
+
234
+ await ctx.session.hook("model.request", (call) => {
235
+ if (call.kind === "title") return
236
+ const route = routes.get(call.sessionID)
237
+ if (route && route.model === call.model?.id && route.until > now()) {
238
+ call.headers["Copilot-Session-Token"] = route.token
239
+ }
240
+ }, { providerID: PROVIDER })
241
+
242
+ // A compacted session asks Auto again.
243
+ await ctx.session.hook("compaction", (call) => { routes.delete(call.sessionID) }, { providerID: PROVIDER })
244
+ },
245
+ }
246
+ }
247
+
248
+ export default createPlugin()
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "opencode-copilot-auto",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "OpenCode plugin that makes GitHub Copilot Free work by routing requests through Copilot's Auto mode",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": { ".": "./index.js" },
8
+ "files": ["index.js", "README.md", "LICENSE", "CHANGELOG.md"],
9
+ "scripts": { "test": "node --test" },
10
+ "keywords": ["opencode", "opencode-plugin", "github-copilot", "copilot-free"],
11
+ "engines": { "node": ">=20" },
12
+ "license": "MIT",
13
+ "repository": { "type": "git", "url": "git+https://github.com/amirhakimnejad/opencode-copilot-auto.git" }
14
+ }