opencode-copilot-auto 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-22)
4
+
5
+ - Makes GitHub Copilot Free work in OpenCode 2.x by routing requests through Copilot's Auto mode.
6
+ - Turns on only for accounts OpenCode can't serve by itself, and follows login changes within 30 seconds.
7
+ - Shows one picker entry, "Auto (Copilot picks the model)", since Auto decides which model answers.
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,79 @@
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 one GitHub Copilot entry in the model picker, **Auto (Copilot picks the model)**,
23
+ because Auto decides which model answers whatever you pick, and
24
+ - routes requests for it (and any other model your account allows) through Auto: it asks Copilot which model to
25
+ use, switches the request to it, and adds Auto's session token. Auto keeps its
26
+ pick for the session until the token is about to expire, or until the session
27
+ is compacted.
28
+
29
+ On any other account it does nothing, so OpenCode's own Copilot support is
30
+ untouched. A reconnect or disconnect is noticed within 30 seconds. It doesn't impersonate another client: requests use your OpenCode
31
+ Copilot login and identify themselves as `opencode-copilot-auto`.
32
+
33
+ ## Install
34
+
35
+ 1. Connect GitHub Copilot in OpenCode as usual.
36
+ 2. Add the plugin to `opencode.json`:
37
+
38
+ ```json
39
+ { "plugin": ["opencode-copilot-auto@0.1.0"] }
40
+ ```
41
+
42
+ or copy `index.js` to `~/.config/opencode/plugins/copilot-auto.js`.
43
+ 3. Restart OpenCode and pick **Auto (Copilot picks the model)** under GitHub Copilot.
44
+
45
+ The model that actually answered is shown under each reply.
46
+
47
+ Your latest message (up to 2,000 characters) is sent to Copilot's `/auto`
48
+ endpoint so Copilot can choose a model, as Copilot's own clients do.
49
+
50
+ ## Settings
51
+
52
+ | `OPENCODE_COPILOT_AUTO` | Effect |
53
+ |---|---|
54
+ | unset or `auto` | Route through Auto only when OpenCode can't serve the account (Copilot Free) |
55
+ | `always` | Route through Auto on every plan |
56
+ | `off` | Do nothing |
57
+
58
+ ## Limits
59
+
60
+ - Copilot Free has a small monthly chat allowance, and an agent sends one
61
+ request per tool step, so long tasks use it up quickly.
62
+ - Session titles aren't routed (they would spend the allowance). Set a
63
+ `small_model` from another provider for titles.
64
+ - It relies on OpenCode's plugin API (`integration.connection`, `model.transform`,
65
+ `session.hook`) and on Copilot's `/auto` endpoint, neither of which is a
66
+ documented stable API. Tested with OpenCode 2.3.2 on 2026-11-18. On older
67
+ OpenCode versions that lack the API it does nothing.
68
+ - It sends the Copilot API versions OpenCode 2.3 sends (`X-GitHub-Api-Version`
69
+ `2026-08-01`, and `2025-04-01` for the account check). When GitHub retires
70
+ those, requests fail with an HTTP error until the plugin is updated.
71
+
72
+ ## Development
73
+
74
+ ```bash
75
+ npm test
76
+ ```
77
+
78
+ The tests use a fake OpenCode host and a fake Copilot API; they make no network
79
+ requests.
package/index.js ADDED
@@ -0,0 +1,242 @@
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 one entry in the model picker, "Auto (Copilot picks the model)",
13
+ // since Auto decides which model answers whatever is picked,
14
+ // - when it (or any model the account allows) is used, asks Auto which model
15
+ // to run and routes the request there with Auto's session token.
16
+ // On any other account it does nothing, so OpenCode's own Copilot support is untouched.
17
+ //
18
+ // Set OPENCODE_COPILOT_AUTO=off to turn it off, or =always to route through Auto
19
+ // whatever the plan.
20
+
21
+ import { createHash } from "node:crypto"
22
+
23
+ export const VERSION = "0.1.0"
24
+ const PROVIDER = "github-copilot"
25
+ const USER_AGENT = `opencode-copilot-auto/${VERSION}`
26
+ const API_VERSION = "2026-08-01" // what OpenCode 2.3 sends to the Copilot API
27
+ const USER_API_VERSION = "2025-04-01" // what OpenCode 2.3 sends to copilot_internal/user
28
+ const CREDENTIAL_TTL_MS = 30 * 1000 // notice a reconnect or disconnect within 30 seconds
29
+ const ACCOUNT_TTL_MS = 60 * 60 * 1000 // re-check plan and models hourly
30
+ const ACCOUNT_RETRY_MS = 60 * 1000 // after a failed check, try again a minute later
31
+ const RENEW_EARLY_MS = 5 * 60 * 1000 // renew Auto's pick 5 minutes before its token expires
32
+ const DEFAULT_ROUTE_MS = 20 * 60 * 1000 // when Auto gives no expiry
33
+ const TIMEOUT_MS = 15 * 1000
34
+ const MAX_SESSIONS = 200
35
+ const MAX_PROMPT_CHARS = 2000
36
+ const AUTO_NAME = "Auto (Copilot picks the model)"
37
+
38
+ // ---------- reading OpenCode's Copilot login ----------
39
+
40
+ // Uses OpenCode's own integration API, so the plugin never touches its database.
41
+ export async function readCredentialFromOpenCode(ctx) {
42
+ const connections = ctx?.integration?.connection
43
+ if (typeof connections?.active !== "function" || typeof connections?.resolve !== "function") return undefined
44
+ const connection = await connections.active(PROVIDER)
45
+ if (!connection) return undefined
46
+ const credential = await connections.resolve(connection)
47
+ const token = credential?.type === "oauth" ? credential.refresh || credential.access : undefined
48
+ if (typeof token !== "string" || !token) return undefined
49
+ return { token, metadata: credential.metadata ?? {} }
50
+ }
51
+
52
+ // ---------- the plugin ----------
53
+
54
+ export function createPlugin(deps = {}) {
55
+ const readCredentialFrom = deps.readCredential ?? readCredentialFromOpenCode
56
+ const http = deps.fetch ?? ((...args) => fetch(...args))
57
+ const now = deps.now ?? (() => Date.now())
58
+ const mode = (deps.mode ?? process.env.OPENCODE_COPILOT_AUTO ?? "auto").toLowerCase()
59
+ const log = deps.log ?? (() => {})
60
+
61
+ let account // { key, needsAuto, models: Set, base, plan, checkedAt, ok }
62
+ let accountLoad // in-flight account check
63
+ const routes = new Map() // sessionID -> { model, token, until, key }
64
+ const picking = new Map() // sessionID -> in-flight pick
65
+
66
+ async function request(url, { token, version, body }) {
67
+ const response = await http(url, {
68
+ method: body === undefined ? "GET" : "POST",
69
+ headers: {
70
+ Accept: "application/json",
71
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
72
+ Authorization: "Bearer " + token,
73
+ "User-Agent": USER_AGENT,
74
+ "X-GitHub-Api-Version": version,
75
+ },
76
+ body: body === undefined ? undefined : JSON.stringify(body),
77
+ signal: AbortSignal.timeout(TIMEOUT_MS),
78
+ })
79
+ if (!response.ok) throw new Error(`${new URL(url).pathname} answered HTTP ${response.status}`)
80
+ return response.json()
81
+ }
82
+
83
+ async function checkAccount(credential, key) {
84
+ const enterprise = typeof credential.metadata.enterpriseUrl === "string" && credential.metadata.enterpriseUrl
85
+ const enterpriseHost = enterprise ? enterprise.replace(/^https?:\/\//, "").replace(/\/+$/, "") : undefined
86
+ const apiHost = enterpriseHost ? `https://api.${enterpriseHost}` : "https://api.github.com"
87
+ const user = await request(`${apiHost}/copilot_internal/user`, { token: credential.token, version: USER_API_VERSION })
88
+ const base = String(
89
+ user?.endpoints?.api || credential.metadata.apiEndpoint ||
90
+ (enterpriseHost ? `https://copilot-api.${enterpriseHost}` : "https://api.githubcopilot.com"),
91
+ ).replace(/\/+$/, "")
92
+ const list = await request(`${base}/models`, { token: credential.token, version: API_VERSION })
93
+ const data = (Array.isArray(list?.data) ? list.data : []).filter((m) => m && typeof m.id === "string")
94
+ // OpenCode serves an account by itself when it can show models or route Auto.
95
+ const servedByOpenCode = data.some((m) => m.model_picker_enabled === true || m.billing?.auto_discount !== undefined)
96
+ const models = new Set(
97
+ data
98
+ .filter((m) =>
99
+ m.policy?.state === "enabled" &&
100
+ (m.capabilities?.type ?? "chat") === "chat" && m.capabilities?.supports?.tool_calls === true)
101
+ .map((m) => m.id),
102
+ )
103
+ return { key, needsAuto: !servedByOpenCode, base, models, plan: String(user?.access_type_sku ?? ""), ok: true }
104
+ }
105
+
106
+ // The current login, re-read at most every 30 seconds. Never throws.
107
+ let login // { credential, key, at }
108
+ async function currentLogin(ctx) {
109
+ if (login && now() - login.at < CREDENTIAL_TTL_MS) return login
110
+ let credential
111
+ try { credential = await readCredentialFrom(ctx) } catch (error) { log("reading the Copilot login failed: " + error.message) }
112
+ const key = credential ? createHash("sha256").update(credential.token).digest("hex").slice(0, 16) : undefined
113
+ login = { credential, key, at: now() }
114
+ return login
115
+ }
116
+
117
+ // Cached account state for the current login; never throws (a failed check means "do nothing").
118
+ async function getAccount(ctx) {
119
+ const { credential, key } = await currentLogin(ctx)
120
+ if (!credential) return { key: undefined, needsAuto: false, models: new Set() }
121
+ if (account && account.key === key) {
122
+ const age = now() - account.checkedAt
123
+ if (age < (account.ok ? ACCOUNT_TTL_MS : ACCOUNT_RETRY_MS)) return account
124
+ }
125
+ if (!accountLoad || accountLoad.key !== key) {
126
+ const load = checkAccount(credential, key)
127
+ .catch((error) => {
128
+ log("account check failed: " + error.message)
129
+ const previous = account?.key === key ? account : { key, needsAuto: false, models: new Set() }
130
+ return { ...previous, ok: false }
131
+ })
132
+ .then((result) => {
133
+ account = { ...result, checkedAt: now() }
134
+ return account
135
+ })
136
+ .finally(() => { if (accountLoad?.promise === load) accountLoad = undefined })
137
+ accountLoad = { key, promise: load }
138
+ }
139
+ return accountLoad.promise
140
+ }
141
+
142
+ function active(acct) {
143
+ return mode !== "off" && acct.key !== undefined && (acct.needsAuto || mode === "always")
144
+ }
145
+
146
+ async function promptFor(ctx, sessionID) {
147
+ try {
148
+ if (typeof ctx.session?.context !== "function") return undefined
149
+ const entries = await ctx.session.context({ sessionID })
150
+ const user = Array.isArray(entries) ? entries.findLast((e) => e?.type === "user") : undefined
151
+ return typeof user?.text === "string" ? user.text.slice(0, MAX_PROMPT_CHARS) : undefined
152
+ } catch {
153
+ return undefined
154
+ }
155
+ }
156
+
157
+ async function pick(ctx, sessionID, acct) {
158
+ const { credential, key } = await currentLogin(ctx)
159
+ if (!credential || key !== acct.key) throw new Error("the GitHub Copilot login changed; try again")
160
+ const prompt = (await promptFor(ctx, sessionID)) || "Help me with my code."
161
+ const answer = await request(`${acct.base}/auto`, { token: credential.token, version: API_VERSION, body: { prompt } })
162
+ const model = answer?.selected_model?.id
163
+ if (typeof model !== "string" || typeof answer?.session_token !== "string") {
164
+ throw new Error("Copilot Auto returned no model")
165
+ }
166
+ const expires = Number(answer.expires_at) * 1000
167
+ const until = Number.isFinite(expires) && expires > now() ? Math.max(now(), expires - RENEW_EARLY_MS) : now() + DEFAULT_ROUTE_MS
168
+ return { model, token: answer.session_token, until, key: acct.key }
169
+ }
170
+
171
+ function remember(sessionID, route) {
172
+ routes.delete(sessionID)
173
+ routes.set(sessionID, route)
174
+ while (routes.size > MAX_SESSIONS) routes.delete(routes.keys().next().value)
175
+ }
176
+
177
+ async function routeFor(ctx, sessionID, acct) {
178
+ const cached = routes.get(sessionID)
179
+ if (cached && cached.key === acct.key && cached.until > now()) return cached
180
+ let pending = picking.get(sessionID)
181
+ if (!pending) {
182
+ pending = pick(ctx, sessionID, acct)
183
+ .then((route) => { remember(sessionID, route); return route })
184
+ .finally(() => picking.delete(sessionID))
185
+ picking.set(sessionID, pending)
186
+ }
187
+ return pending
188
+ }
189
+
190
+ return {
191
+ id: "copilot-auto",
192
+ async setup(ctx) {
193
+ if (mode === "off") return
194
+ // Check the account now. OpenCode may have built its model list already,
195
+ // so rebuild it once the allowed models are known, to show the Auto entry.
196
+ getAccount(ctx).then((acct) => {
197
+ if (!active(acct) || !acct.models.size || typeof ctx.model?.reload !== "function") return
198
+ try {
199
+ Promise.resolve(ctx.model.reload()).catch(() => {})
200
+ } catch {}
201
+ })
202
+
203
+ if (typeof ctx.model?.transform === "function") {
204
+ await ctx.model.transform((models) => {
205
+ if (!account || !active(account) || account.key !== login?.key) return
206
+ // One picker entry: picking a specific model would be ignored by Auto anyway.
207
+ // It stands on the first allowed model; the others are hidden.
208
+ const [entry, ...rest] = [...account.models].filter((id) => models.get(PROVIDER, id))
209
+ if (!entry) return
210
+ models.update(PROVIDER, entry, (m) => { m.enabled = true; m.name = AUTO_NAME })
211
+ for (const id of rest) models.update(PROVIDER, id, (m) => { m.enabled = false })
212
+ })
213
+ }
214
+
215
+ await ctx.session.hook("experimental.model.resolve", async (call) => {
216
+ if (call.kind === "title" || call.model?.providerID !== PROVIDER) return
217
+ const acct = await getAccount(ctx)
218
+ if (!active(acct) || !acct.models.has(call.model.id)) return
219
+ let route
220
+ try {
221
+ route = await routeFor(ctx, call.sessionID, acct)
222
+ } catch (error) {
223
+ throw new Error(`copilot-auto: Copilot Auto failed (${error.message}). Try again in a moment, or pick another model.`)
224
+ }
225
+ call.model = { providerID: PROVIDER, id: route.model }
226
+ }, { providerID: PROVIDER })
227
+
228
+ await ctx.session.hook("model.request", (call) => {
229
+ if (call.kind === "title") return
230
+ const route = routes.get(call.sessionID)
231
+ if (route && route.model === call.model?.id && route.until > now()) {
232
+ call.headers["Copilot-Session-Token"] = route.token
233
+ }
234
+ }, { providerID: PROVIDER })
235
+
236
+ // A compacted session asks Auto again.
237
+ await ctx.session.hook("compaction", (call) => { routes.delete(call.sessionID) }, { providerID: PROVIDER })
238
+ },
239
+ }
240
+ }
241
+
242
+ 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.0",
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
+ }