opencode-acp-provider 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +357 -2
- package/package.json +41 -4
- package/src/acp-client.ts +1033 -0
- package/src/acp-tools.ts +311 -0
- package/src/agent-command.ts +20 -0
- package/src/agents/README.md +63 -0
- package/src/agents/cmd/index.ts +55 -0
- package/src/agents/cmd/mods/no-native-orchestration.ts +54 -0
- package/src/agents/cmd/mods/opencode-skills.ts +21 -0
- package/src/commands.ts +275 -0
- package/src/debug.ts +71 -0
- package/src/index.ts +640 -0
- package/src/inventory.ts +90 -0
- package/src/language-model.ts +427 -0
- package/src/mcp-bridge.mjs +150 -0
- package/src/mcp-config.ts +198 -0
- package/src/mcp-server.ts +943 -0
- package/src/prompt.ts +100 -0
- package/src/server-manager.ts +1042 -0
- package/src/setup.ts +100 -0
- package/src/shim.ts +436 -0
- package/src/skills.ts +232 -0
- package/src/steering.ts +85 -0
- package/src/util.ts +94 -0
package/src/skills.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
|
|
2
|
+
import { tmpdir } from "node:os"
|
|
3
|
+
import { basename, dirname, join, sep } from "node:path"
|
|
4
|
+
import type { Plugin } from "@opencode/plugin"
|
|
5
|
+
import type { LogFn } from "./server-manager.ts"
|
|
6
|
+
import { errorMessage } from "./util.ts"
|
|
7
|
+
|
|
8
|
+
/** Agent Skills IDs are portable only as lowercase kebab-case. */
|
|
9
|
+
const SKILL_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
10
|
+
const MAX_SKILL_ID = 64
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* A temporary, agent-owned skill tree. The root is handed to ACP agents as an
|
|
14
|
+
* `additionalDirectories` entry; Codex looks in `<root>/.agents/skills` and
|
|
15
|
+
* Claude Code looks in `<root>/.claude/skills`.
|
|
16
|
+
*/
|
|
17
|
+
export interface SkillMirror {
|
|
18
|
+
root: string
|
|
19
|
+
/** Locations a `--skill` flag can take (cmd). */
|
|
20
|
+
agentsDir: string
|
|
21
|
+
claudeDir: string
|
|
22
|
+
/** Skills mirrored by the latest sync. */
|
|
23
|
+
readonly count: number
|
|
24
|
+
/** Re-read OpenCode's skills and bring the mirror in line with them. */
|
|
25
|
+
sync: () => Promise<void>
|
|
26
|
+
close: () => Promise<void>
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface MirrorableSkill {
|
|
30
|
+
id: unknown
|
|
31
|
+
description?: unknown
|
|
32
|
+
autoinvoke?: unknown
|
|
33
|
+
path: unknown
|
|
34
|
+
content?: unknown
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface SkillMirrorOptions {
|
|
38
|
+
/** When set, only mirror these skill IDs. */
|
|
39
|
+
include?: readonly string[]
|
|
40
|
+
log?: LogFn
|
|
41
|
+
/**
|
|
42
|
+
* Follow `skill.updated` and re-check shortly after creation. OpenCode
|
|
43
|
+
* discovers skills in the background, so the first list is often partial.
|
|
44
|
+
* Defaults to true.
|
|
45
|
+
*/
|
|
46
|
+
watch?: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Delays for re-reading skills after setup, in case discovery finished before the subscription. */
|
|
50
|
+
const SETTLE_DELAYS_MS = [250, 1_000, 3_000]
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Run `sync` on every `skill.updated`, and from `settle()` a few more times
|
|
54
|
+
* while OpenCode's background skill discovery finishes. Create it before the
|
|
55
|
+
* first read so an event fired meanwhile is not lost, and call `settle()` after
|
|
56
|
+
* that read: discovery can finish before the subscription, and then no event
|
|
57
|
+
* ever arrives.
|
|
58
|
+
*/
|
|
59
|
+
export function followSkillUpdates(ctx: Plugin.Context, sync: () => Promise<void>) {
|
|
60
|
+
const controller = new AbortController()
|
|
61
|
+
const timers: ReturnType<typeof setTimeout>[] = []
|
|
62
|
+
if (typeof ctx.event?.subscribe === "function") {
|
|
63
|
+
void (async () => {
|
|
64
|
+
try {
|
|
65
|
+
for await (const _ of ctx.event.subscribe({ types: ["skill.updated"], signal: controller.signal })) {
|
|
66
|
+
if (controller.signal.aborted) break
|
|
67
|
+
await sync()
|
|
68
|
+
}
|
|
69
|
+
} catch {
|
|
70
|
+
// The stream ends on dispose; the caller keeps its last state.
|
|
71
|
+
}
|
|
72
|
+
})()
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
settle() {
|
|
76
|
+
for (const delay of SETTLE_DELAYS_MS) {
|
|
77
|
+
const timer = setTimeout(() => void sync(), delay)
|
|
78
|
+
timer.unref?.()
|
|
79
|
+
timers.push(timer)
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
dispose() {
|
|
83
|
+
for (const timer of timers) clearTimeout(timer)
|
|
84
|
+
controller.abort()
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Copy OpenCode's own skills into a throwaway directory that ACP agents already
|
|
91
|
+
* know how to scan. Skills that live in `.agents/skills` or `.claude/skills`
|
|
92
|
+
* belong to the agents, so they are left where they are and each agent keeps
|
|
93
|
+
* loading them through its native discovery. That means the mirror contains
|
|
94
|
+
* only built-in/OpenCode-registered skills, not shared agent skills.
|
|
95
|
+
*
|
|
96
|
+
* Supporting files are copied rather than symlinked so they stay inside the
|
|
97
|
+
* additional directory the agent was granted.
|
|
98
|
+
*
|
|
99
|
+
* The mirror stays up even while it is empty: skills that OpenCode discovers
|
|
100
|
+
* later are added on `skill.updated`, and agents see them in their next session.
|
|
101
|
+
*/
|
|
102
|
+
export async function createSkillMirror(
|
|
103
|
+
ctx: Plugin.Context,
|
|
104
|
+
options: SkillMirrorOptions = {},
|
|
105
|
+
): Promise<SkillMirror> {
|
|
106
|
+
const log = options.log ?? (() => {})
|
|
107
|
+
const include = options.include ? new Set(options.include) : undefined
|
|
108
|
+
const root = await mkdtemp(join(tmpdir(), "opencode-acp-provider-skills-"))
|
|
109
|
+
const agentsDir = join(root, ".agents", "skills")
|
|
110
|
+
const claudeDir = join(root, ".claude", "skills")
|
|
111
|
+
await mkdir(agentsDir, { recursive: true })
|
|
112
|
+
await mkdir(claudeDir, { recursive: true })
|
|
113
|
+
|
|
114
|
+
let count = 0
|
|
115
|
+
let closed = false
|
|
116
|
+
let mirrored = new Set<string>()
|
|
117
|
+
|
|
118
|
+
const rebuild = async () => {
|
|
119
|
+
if (closed) return
|
|
120
|
+
const { data } = await ctx.skill.list()
|
|
121
|
+
const next = new Set<string>()
|
|
122
|
+
for (const skill of data as readonly MirrorableSkill[]) {
|
|
123
|
+
if (closed) return
|
|
124
|
+
if (!mirrorable(skill)) continue
|
|
125
|
+
const id = String(skill.id)
|
|
126
|
+
if (include && !include.has(id)) continue
|
|
127
|
+
const source = String(skill.path)
|
|
128
|
+
const virtual = source.startsWith("skill://")
|
|
129
|
+
if (!virtual && sharedSource(source)) continue
|
|
130
|
+
const sourceDirectory = !virtual && basename(source) === "SKILL.md" ? dirname(source) : undefined
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
for (const target of [agentsDir, claudeDir]) {
|
|
134
|
+
const destination = join(target, id)
|
|
135
|
+
// Start clean so files removed from the source do not linger.
|
|
136
|
+
await rm(destination, { recursive: true, force: true })
|
|
137
|
+
if (sourceDirectory)
|
|
138
|
+
await cp(sourceDirectory, destination, {
|
|
139
|
+
recursive: true,
|
|
140
|
+
dereference: true,
|
|
141
|
+
force: true,
|
|
142
|
+
filter: copyFilter,
|
|
143
|
+
})
|
|
144
|
+
else await mkdir(destination, { recursive: true })
|
|
145
|
+
await writeFile(join(destination, "SKILL.md"), renderSkill(skill), "utf8")
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
log("warn", `could not mirror skill "${id}": ${errorMessage(error)}`)
|
|
149
|
+
continue
|
|
150
|
+
}
|
|
151
|
+
next.add(id)
|
|
152
|
+
}
|
|
153
|
+
for (const id of mirrored) {
|
|
154
|
+
if (next.has(id)) continue
|
|
155
|
+
for (const target of [agentsDir, claudeDir]) {
|
|
156
|
+
await rm(join(target, id), { recursive: true, force: true }).catch(() => {})
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (next.size !== count) log("info", `Mirrored ${next.size} OpenCode skill(s) for ACP agents`)
|
|
160
|
+
mirrored = next
|
|
161
|
+
count = next.size
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
let queue: Promise<void> = Promise.resolve()
|
|
165
|
+
const sync = () => {
|
|
166
|
+
const run = queue.then(rebuild).catch((error) => {
|
|
167
|
+
log("warn", `could not refresh OpenCode skills mirror: ${errorMessage(error)}`)
|
|
168
|
+
})
|
|
169
|
+
queue = run
|
|
170
|
+
return run
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const watcher = options.watch !== false ? followSkillUpdates(ctx, sync) : undefined
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
await rebuild()
|
|
177
|
+
} catch (error) {
|
|
178
|
+
watcher?.dispose()
|
|
179
|
+
await rm(root, { recursive: true, force: true }).catch(() => {})
|
|
180
|
+
throw error
|
|
181
|
+
}
|
|
182
|
+
if (count === 0) log("info", "Mirrored 0 OpenCode skill(s) for ACP agents; watching for more")
|
|
183
|
+
watcher?.settle()
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
root,
|
|
187
|
+
agentsDir,
|
|
188
|
+
claudeDir,
|
|
189
|
+
get count() {
|
|
190
|
+
return count
|
|
191
|
+
},
|
|
192
|
+
sync,
|
|
193
|
+
close: async () => {
|
|
194
|
+
closed = true
|
|
195
|
+
watcher?.dispose()
|
|
196
|
+
await queue.catch(() => {})
|
|
197
|
+
|
|
198
|
+
await rm(root, { recursive: true, force: true }).catch(() => {})
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function mirrorable(skill: MirrorableSkill) {
|
|
204
|
+
const id = typeof skill.id === "string" ? skill.id : ""
|
|
205
|
+
if (!id || id.length > MAX_SKILL_ID || !SKILL_ID.test(id)) return false
|
|
206
|
+
if (typeof skill.description !== "string" || !skill.description.trim()) return false
|
|
207
|
+
if (skill.autoinvoke === false) return false
|
|
208
|
+
if (typeof skill.path !== "string" || !skill.path) return false
|
|
209
|
+
return typeof skill.content === "string"
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Skills in `.agents/skills` or `.claude/skills` are owned by the agents, not OpenCode. */
|
|
213
|
+
function sharedSource(source: string) {
|
|
214
|
+
const normalized = source.replaceAll(sep, "/").replaceAll("\\", "/")
|
|
215
|
+
return normalized.includes("/.agents/skills/") || normalized.includes("/.claude/skills/")
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function copyFilter(path: string) {
|
|
219
|
+
const name = basename(path)
|
|
220
|
+
return name !== ".git" && name !== "node_modules"
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function renderSkill(skill: MirrorableSkill) {
|
|
224
|
+
const id = String(skill.id)
|
|
225
|
+
const description =
|
|
226
|
+
typeof skill.description === "string" ? skill.description.trim().slice(0, 1024) : ""
|
|
227
|
+
const body = String(skill.content ?? "").replace(/^\s*\n/, "").trimEnd()
|
|
228
|
+
// JSON strings are valid YAML flow scalars. `name` is the directory id so
|
|
229
|
+
// strict loaders (cmd) accept the skill, and tools that display a label fall
|
|
230
|
+
// back to the description.
|
|
231
|
+
return `---\nname: ${JSON.stringify(id)}\ndescription: ${JSON.stringify(description)}\n---\n\n${body}\n`
|
|
232
|
+
}
|
package/src/steering.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { AcpServerManager, LogFn } from "./server-manager.ts"
|
|
2
|
+
import { basicAuth, errorMessage, sleep } from "./util.ts"
|
|
3
|
+
|
|
4
|
+
/** Local HTTP API of the OpenCode server hosting this plugin. */
|
|
5
|
+
export interface LocalService {
|
|
6
|
+
url: string
|
|
7
|
+
password: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface SteeringPrompt {
|
|
11
|
+
readonly sessionID: string
|
|
12
|
+
readonly delivery: "steer" | "queue"
|
|
13
|
+
readonly prompt: {
|
|
14
|
+
readonly text?: string
|
|
15
|
+
readonly files?: readonly unknown[]
|
|
16
|
+
readonly skills?: readonly unknown[]
|
|
17
|
+
readonly agents?: readonly unknown[]
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SteeringOptions {
|
|
22
|
+
manager: Pick<AcpServerManager, "interrupt" | "running">
|
|
23
|
+
localService: () => Promise<LocalService | undefined>
|
|
24
|
+
directory: string
|
|
25
|
+
log: LogFn
|
|
26
|
+
/** Total budget for checking and waiting on an ACP turn that has not reached the shim. */
|
|
27
|
+
startTimeoutMs?: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const DEFAULT_START_TIMEOUT_MS = 1_500
|
|
31
|
+
const ACTIVE_REQUEST_TIMEOUT_MS = 250
|
|
32
|
+
const START_POLL_MS = 25
|
|
33
|
+
|
|
34
|
+
async function sessionRunning(service: LocalService, directory: string, sessionID: string, timeoutMs: number) {
|
|
35
|
+
const response = await fetch(`${service.url.replace(/\/+$/, "")}/api/session/active`, {
|
|
36
|
+
headers: {
|
|
37
|
+
authorization: basicAuth(service.password),
|
|
38
|
+
"x-opencode-directory": encodeURIComponent(directory),
|
|
39
|
+
},
|
|
40
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
41
|
+
})
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
await response.body?.cancel()
|
|
44
|
+
return false
|
|
45
|
+
}
|
|
46
|
+
const { data } = (await response.json()) as { data?: unknown }
|
|
47
|
+
return Boolean(data && typeof data === "object" && Object.hasOwn(data, sessionID))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Admission runs before OpenCode durably queues the prompt. Do not send its
|
|
52
|
+
* contents from here: OpenCode must be the only owner of delivery. Interrupt
|
|
53
|
+
* the current ACP turn so OpenCode can deliver the intact message next.
|
|
54
|
+
*/
|
|
55
|
+
export function createSteering(options: SteeringOptions) {
|
|
56
|
+
return async function steer(event: SteeringPrompt): Promise<void> {
|
|
57
|
+
const { sessionID, delivery, prompt } = event
|
|
58
|
+
if (delivery !== "steer") return
|
|
59
|
+
const hasText = typeof prompt.text === "string" && Boolean(prompt.text.trim())
|
|
60
|
+
if (!hasText && !prompt.files?.length && !prompt.skills?.length && !prompt.agents?.length) return
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
if (!options.manager.running(sessionID)) {
|
|
64
|
+
// Ordinary prompts also arrive as "steer". Only wait if the host is
|
|
65
|
+
// already executing this session and ACP may still be starting up.
|
|
66
|
+
const deadline = performance.now() + (options.startTimeoutMs ?? DEFAULT_START_TIMEOUT_MS)
|
|
67
|
+
const service = await options.localService()
|
|
68
|
+
const remaining = Math.ceil(deadline - performance.now())
|
|
69
|
+
if (!service || remaining <= 0) return
|
|
70
|
+
if (!(await sessionRunning(service, options.directory, sessionID, Math.min(remaining, ACTIVE_REQUEST_TIMEOUT_MS)))) {
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
while (!options.manager.running(sessionID)) {
|
|
74
|
+
const delay = Math.min(START_POLL_MS, deadline - performance.now())
|
|
75
|
+
if (delay <= 0) return
|
|
76
|
+
await sleep(delay)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
options.manager.interrupt(sessionID)
|
|
80
|
+
} catch (error) {
|
|
81
|
+
// A failed lookup must never prevent the host from admitting the prompt.
|
|
82
|
+
options.log("debug", `ACP steering skipped: ${errorMessage(error)}`)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/util.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { IncomingMessage, Server, ServerResponse } from "node:http"
|
|
2
|
+
|
|
3
|
+
export class BodyTooLargeError extends Error {}
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Read a request body as UTF-8, rejecting with `BodyTooLargeError` past
|
|
7
|
+
* `maxBytes`. The request is left open so the caller can send its 413 before
|
|
8
|
+
* destroying it; destroying here would take the response down with it.
|
|
9
|
+
*/
|
|
10
|
+
export function readBody(req: IncomingMessage, maxBytes: number) {
|
|
11
|
+
return new Promise<string>((resolve, reject) => {
|
|
12
|
+
const chunks: Buffer[] = []
|
|
13
|
+
let size = 0
|
|
14
|
+
let settled = false
|
|
15
|
+
req.on("data", (chunk) => {
|
|
16
|
+
if (settled) return
|
|
17
|
+
size += chunk.length
|
|
18
|
+
if (size > maxBytes) {
|
|
19
|
+
settled = true
|
|
20
|
+
reject(new BodyTooLargeError(`Request body exceeds ${maxBytes} bytes`))
|
|
21
|
+
return
|
|
22
|
+
}
|
|
23
|
+
chunks.push(Buffer.from(chunk))
|
|
24
|
+
})
|
|
25
|
+
req.on("end", () => {
|
|
26
|
+
if (settled) return
|
|
27
|
+
settled = true
|
|
28
|
+
resolve(Buffer.concat(chunks).toString("utf8"))
|
|
29
|
+
})
|
|
30
|
+
req.on("error", (error) => {
|
|
31
|
+
if (settled) return
|
|
32
|
+
settled = true
|
|
33
|
+
reject(error)
|
|
34
|
+
})
|
|
35
|
+
})
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Wait `ms`, rejecting with the signal's reason if it aborts first. */
|
|
39
|
+
export function sleep(ms: number, signal?: AbortSignal) {
|
|
40
|
+
return new Promise<void>((resolve, reject) => {
|
|
41
|
+
if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"))
|
|
42
|
+
const onAbort = () => {
|
|
43
|
+
clearTimeout(timer)
|
|
44
|
+
reject(signal?.reason ?? new Error("aborted"))
|
|
45
|
+
}
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
signal?.removeEventListener("abort", onAbort)
|
|
48
|
+
resolve()
|
|
49
|
+
}, ms)
|
|
50
|
+
timer.unref?.()
|
|
51
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Authorization header for OpenCode's local server. */
|
|
56
|
+
export function basicAuth(password: string) {
|
|
57
|
+
return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The agent's display name without the " (ACP)" provider suffix. */
|
|
61
|
+
export function agentName(config: { name?: string; id: string }) {
|
|
62
|
+
return (config.name ?? config.id).replace(/\s*\(ACP\)$/, "")
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The message of a thrown value, whatever was thrown. */
|
|
66
|
+
export function errorMessage(error: unknown) {
|
|
67
|
+
return error instanceof Error ? error.message : String(error)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Listen on an ephemeral loopback port and return it. */
|
|
71
|
+
export async function listenLocal(server: Server) {
|
|
72
|
+
await new Promise<void>((resolve, reject) => {
|
|
73
|
+
server.once("error", reject)
|
|
74
|
+
server.listen(0, "127.0.0.1", () => resolve())
|
|
75
|
+
})
|
|
76
|
+
const address = server.address()
|
|
77
|
+
return typeof address === "object" && address ? address.port : 0
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** End a response whose handler threw, with a 500 when nothing was sent yet. */
|
|
81
|
+
export function endFailedResponse(res: ServerResponse) {
|
|
82
|
+
if (res.destroyed) return
|
|
83
|
+
try {
|
|
84
|
+
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" })
|
|
85
|
+
} catch {
|
|
86
|
+
// the connection was closed
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
if (!res.writableEnded) res.end()
|
|
90
|
+
} catch {
|
|
91
|
+
// the connection was closed
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
}
|