Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
176 lines (160 loc) · 5.26 KB
/
Copy pathruntime.ts
File metadata and controls
176 lines (160 loc) · 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { spawn } from "node:child_process"
import * as fs from "node:fs/promises"
import * as path from "node:path"
import { fileURLToPath } from "node:url"
const PLUGIN_ROOT = path.dirname(fileURLToPath(import.meta.url))
const BUNDLED_RUNTIME = path.join(PLUGIN_ROOT, "scripts", "echoes_vault.py")
export type EchoesCommand =
| "init"
| "migrate"
| "upgrade"
| "protocol"
| "configure-agents"
| "inspect"
| "hydrate"
| "start"
| "status"
| "search"
| "append"
| "upsert"
| "end"
| "hash"
| "rebuild-index"
export type RunEchoesOptions = {
args?: string[]
payload?: Record<string, unknown>
signal?: AbortSignal
adapterVersion?: string
launcherPath?: string
}
export class EchoesRuntimeError extends Error {
readonly exitCode: number | null
readonly stdout: string
readonly stderr: string
constructor(message: string, exitCode: number | null, stdout: string, stderr: string) {
super(message)
this.name = "EchoesRuntimeError"
this.exitCode = exitCode
this.stdout = stdout
this.stderr = stderr
}
}
/**
* Prefer OpenCode's current session directory over its worktree hint. Some global-plugin launches
* report `/` as the worktree even when the session directory points at the real project.
*/
export const resolveEchoesWorkspace = (...candidates: Array<string | undefined>): string => {
for (const candidate of candidates) {
if (!candidate?.trim()) continue
const resolved = path.resolve(candidate)
if (resolved !== path.parse(resolved).root) return resolved
}
throw new EchoesRuntimeError(
"OpenCode did not provide a safe project directory. Refusing to use the filesystem root as the EchoesVault workspace.",
null,
"",
"",
)
}
let adapterVersionPromise: Promise<string> | undefined
export const getAdapterVersion = async (): Promise<string> => {
adapterVersionPromise ??= fs
.readFile(path.join(PLUGIN_ROOT, "package.json"), "utf-8")
.then((raw) => {
const value = (JSON.parse(raw) as { version?: unknown }).version
return typeof value === "string" && value.trim() ? value : "0.0.0"
})
.catch(() => "0.0.0")
return adapterVersionPromise
}
const runtimeMessage = (stderr: string, stdout: string, exitCode: number | null): string => {
const raw = stderr.trim() || stdout.trim()
if (raw) {
try {
const parsed = JSON.parse(raw) as { error?: unknown }
if (typeof parsed.error === "string" && parsed.error.trim()) return parsed.error
} catch {
// The runtime may emit a plain Python/process error instead of protocol JSON.
}
return raw
}
return `EchoesVault runtime exited with code ${exitCode ?? "unknown"}.`
}
/**
* Invoke the bundled launcher as an argv array. The launcher bootstraps or upgrades only for
* explicit lifecycle commands and delegates normal operations to the project-local runtime.
*/
export const runEchoes = async (
workspace: string,
command: EchoesCommand,
options: RunEchoesOptions = {},
): Promise<string> => {
const resolvedWorkspace = resolveEchoesWorkspace(workspace)
const adapterVersion = options.adapterVersion ?? (await getAdapterVersion())
const launcher = options.launcherPath ?? BUNDLED_RUNTIME
const commandArgs = options.args ?? []
const payload = options.payload === undefined ? undefined : JSON.stringify(options.payload)
const python = process.env.ECHOES_VAULT_PYTHON?.trim() || "python3"
const argv = [
launcher,
"--workspace",
resolvedWorkspace,
"--agent",
"opencode",
"--adapter-version",
adapterVersion,
command,
...commandArgs,
]
return await new Promise<string>((resolve, reject) => {
const child = spawn(python, argv, {
cwd: resolvedWorkspace,
stdio: [payload === undefined ? "ignore" : "pipe", "pipe", "pipe"],
})
const stdout: Buffer[] = []
const stderr: Buffer[] = []
const abort = () => child.kill("SIGTERM")
options.signal?.addEventListener("abort", abort, { once: true })
child.stdout!.on("data", (chunk: Buffer) => stdout.push(chunk))
child.stderr!.on("data", (chunk: Buffer) => stderr.push(chunk))
child.once("error", (error) => {
options.signal?.removeEventListener("abort", abort)
reject(
new EchoesRuntimeError(
`Cannot start EchoesVault runtime with ${python}: ${error.message}`,
null,
Buffer.concat(stdout).toString("utf-8"),
Buffer.concat(stderr).toString("utf-8"),
),
)
})
child.once("close", (exitCode) => {
options.signal?.removeEventListener("abort", abort)
const output = Buffer.concat(stdout).toString("utf-8")
const errors = Buffer.concat(stderr).toString("utf-8")
if (exitCode === 0) {
resolve(output)
return
}
reject(new EchoesRuntimeError(runtimeMessage(errors, output, exitCode), exitCode, output, errors))
})
if (payload !== undefined) child.stdin!.end(payload)
})
}
export const runEchoesJson = async <Value>(
workspace: string,
command: EchoesCommand,
options: RunEchoesOptions = {},
): Promise<Value> => {
const output = await runEchoes(workspace, command, options)
try {
return JSON.parse(output) as Value
} catch {
throw new EchoesRuntimeError(
"EchoesVault runtime returned invalid JSON.",
0,
output,
"",
)
}
}