opencode-copilot-delegate 0.9.0 → 0.10.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.
@@ -0,0 +1,379 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import type { ZodIssue, ZodType } from 'zod'
5
+ import {
6
+ type HealthResponse,
7
+ HealthResponseSchema,
8
+ type PortFile,
9
+ PortFileSchema,
10
+ TasksCancelRequestSchema,
11
+ type TasksCancelResponse,
12
+ TasksCancelResponseSchema,
13
+ type TasksListResponse,
14
+ TasksListResponseSchema,
15
+ } from '../runtime/rpc-contract'
16
+
17
+ type CreateRpcClientOptions = {
18
+ baseDir?: string
19
+ sessionDiscriminator?: string
20
+ fetchImpl?: typeof fetch
21
+ requestTimeoutMs?: number
22
+ }
23
+
24
+ type RequestOptions<T> = {
25
+ method: 'GET' | 'POST'
26
+ path: string
27
+ schema: ZodType<T>
28
+ authenticated?: boolean
29
+ body?: unknown
30
+ }
31
+
32
+ type RpcRequestContext = {
33
+ path: string
34
+ url: string
35
+ }
36
+
37
+ export class RpcUnreachableError extends Error {
38
+ constructor(message: string, options?: { cause?: unknown }) {
39
+ super(message, options)
40
+ this.name = 'RpcUnreachableError'
41
+ Object.setPrototypeOf(this, new.target.prototype)
42
+ }
43
+ }
44
+
45
+ export class RpcValidationError extends Error {
46
+ readonly issues?: string[]
47
+
48
+ constructor(
49
+ message: string,
50
+ options?: { cause?: unknown; issues?: string[] },
51
+ ) {
52
+ super(message, options)
53
+ this.name = 'RpcValidationError'
54
+ this.issues = options?.issues
55
+ Object.setPrototypeOf(this, new.target.prototype)
56
+ }
57
+ }
58
+
59
+ export class RpcServerError extends Error {
60
+ readonly status: number
61
+ readonly path: string
62
+
63
+ constructor(
64
+ message: string,
65
+ options: { cause?: unknown; path: string; status: number },
66
+ ) {
67
+ super(message, options)
68
+ this.name = 'RpcServerError'
69
+ this.status = options.status
70
+ this.path = options.path
71
+ Object.setPrototypeOf(this, new.target.prototype)
72
+ }
73
+ }
74
+
75
+ export class RpcAuthError extends RpcServerError {
76
+ constructor(
77
+ message: string,
78
+ options: { cause?: unknown; path: string; status: number },
79
+ ) {
80
+ super(message, options)
81
+ this.name = 'RpcAuthError'
82
+ Object.setPrototypeOf(this, new.target.prototype)
83
+ }
84
+ }
85
+
86
+ function defaultBaseDir(): string {
87
+ const cacheHome =
88
+ process.env.XDG_CACHE_HOME ?? join(process.env.HOME ?? homedir(), '.cache')
89
+
90
+ return join(cacheHome, 'opencode', 'copilot-delegate')
91
+ }
92
+
93
+ function defaultSessionDiscriminator(): string {
94
+ return process.env.OPENCODE_SESSION_ID ?? String(process.pid)
95
+ }
96
+
97
+ function resolvePortFilePath(options: CreateRpcClientOptions): string {
98
+ return join(
99
+ options.baseDir ?? defaultBaseDir(),
100
+ options.sessionDiscriminator ?? defaultSessionDiscriminator(),
101
+ 'server-port.json',
102
+ )
103
+ }
104
+
105
+ function summarizeIssues(issues: ZodIssue[]): string[] {
106
+ return issues.map((issue) => {
107
+ const path = issue.path.length > 0 ? issue.path.join('.') : '(root)'
108
+ return `${path}: ${issue.message}`
109
+ })
110
+ }
111
+
112
+ function errorMessage(error: unknown): string {
113
+ if (error instanceof Error && error.message.length > 0) {
114
+ return error.message
115
+ }
116
+
117
+ return String(error)
118
+ }
119
+
120
+ async function readPortFile(portFilePath: string): Promise<PortFile> {
121
+ let raw: string
122
+
123
+ try {
124
+ raw = await readFile(portFilePath, 'utf8')
125
+ } catch (error) {
126
+ throw new RpcUnreachableError(
127
+ `Copilot delegate RPC port file is unavailable at ${portFilePath}`,
128
+ { cause: error },
129
+ )
130
+ }
131
+
132
+ let parsed: unknown
133
+
134
+ try {
135
+ parsed = JSON.parse(raw)
136
+ } catch (error) {
137
+ throw new RpcValidationError(
138
+ `Copilot delegate RPC port file contains invalid JSON at ${portFilePath}`,
139
+ { cause: error },
140
+ )
141
+ }
142
+
143
+ const validated = PortFileSchema.safeParse(parsed)
144
+ if (!validated.success) {
145
+ const issues = summarizeIssues(validated.error.issues)
146
+
147
+ throw new RpcValidationError(
148
+ `Copilot delegate RPC port file is invalid at ${portFilePath}: ${issues.join('; ')}`,
149
+ {
150
+ cause: validated.error,
151
+ issues,
152
+ },
153
+ )
154
+ }
155
+
156
+ return validated.data
157
+ }
158
+
159
+ async function parseOkResponse(response: Response, context: RpcRequestContext) {
160
+ const text = await response.text()
161
+
162
+ try {
163
+ return JSON.parse(text) as unknown
164
+ } catch (error) {
165
+ throw new RpcValidationError(
166
+ `Copilot delegate RPC returned invalid JSON for ${context.path} (${context.url})`,
167
+ { cause: error },
168
+ )
169
+ }
170
+ }
171
+
172
+ async function parseErrorResponse(response: Response): Promise<unknown> {
173
+ const text = await response.text()
174
+ if (text.length === 0) {
175
+ return undefined
176
+ }
177
+
178
+ try {
179
+ return JSON.parse(text) as unknown
180
+ } catch {
181
+ return text
182
+ }
183
+ }
184
+
185
+ function buildServerErrorMessage(
186
+ response: Response,
187
+ context: RpcRequestContext,
188
+ body: unknown,
189
+ ): string {
190
+ let detail = ''
191
+
192
+ if (typeof body === 'string' && body.trim().length > 0) {
193
+ detail = body.trim()
194
+ } else if (
195
+ typeof body === 'object' &&
196
+ body !== null &&
197
+ 'error' in body &&
198
+ typeof body.error === 'string' &&
199
+ body.error.length > 0
200
+ ) {
201
+ detail = body.error
202
+ }
203
+
204
+ const prefix =
205
+ response.status === 401
206
+ ? `Copilot delegate RPC authorization failed for ${context.path} (${context.url}) with status ${response.status}`
207
+ : `Copilot delegate RPC request failed for ${context.path} (${context.url}) with status ${response.status}`
208
+
209
+ return detail ? `${prefix}: ${detail}` : prefix
210
+ }
211
+
212
+ function validateBody<T>(
213
+ schema: ZodType<T>,
214
+ parsed: unknown,
215
+ context: RpcRequestContext,
216
+ ): T {
217
+ const validated = schema.safeParse(parsed)
218
+ if (!validated.success) {
219
+ const issues = summarizeIssues(validated.error.issues)
220
+
221
+ throw new RpcValidationError(
222
+ `Copilot delegate RPC response for ${context.path} is invalid: ${issues.join('; ')}`,
223
+ {
224
+ cause: validated.error,
225
+ issues,
226
+ },
227
+ )
228
+ }
229
+
230
+ return validated.data
231
+ }
232
+
233
+ function validateCancelTaskId(taskId: string): { taskId: string } {
234
+ const validated = TasksCancelRequestSchema.safeParse({ taskId })
235
+ if (!validated.success) {
236
+ const issues = summarizeIssues(validated.error.issues)
237
+
238
+ throw new RpcValidationError(
239
+ `Copilot delegate RPC cancel request is invalid: ${issues.join('; ')}`,
240
+ {
241
+ cause: validated.error,
242
+ issues,
243
+ },
244
+ )
245
+ }
246
+
247
+ return validated.data
248
+ }
249
+
250
+ function createRequestSignal(
251
+ parentSignal: AbortSignal,
252
+ timeoutMs: number,
253
+ ): { cleanup: () => void; signal: AbortSignal } {
254
+ const requestAbortController = new AbortController()
255
+ const timeoutHandle = globalThis.setTimeout(() => {
256
+ requestAbortController.abort()
257
+ }, timeoutMs)
258
+ const abortRequest = () => requestAbortController.abort()
259
+ parentSignal.addEventListener('abort', abortRequest, { once: true })
260
+
261
+ if (parentSignal.aborted) {
262
+ requestAbortController.abort()
263
+ }
264
+
265
+ return {
266
+ cleanup() {
267
+ globalThis.clearTimeout(timeoutHandle)
268
+ parentSignal.removeEventListener('abort', abortRequest)
269
+ },
270
+ signal: requestAbortController.signal,
271
+ }
272
+ }
273
+
274
+ export function createRpcClient(options: CreateRpcClientOptions = {}) {
275
+ const portFilePath = resolvePortFilePath(options)
276
+ const fetchImpl = options.fetchImpl ?? fetch
277
+ const abortController = new AbortController()
278
+ const requestTimeoutMs = options.requestTimeoutMs ?? 5_000
279
+
280
+ async function request<T>(requestOptions: RequestOptions<T>): Promise<T> {
281
+ const portFile = await readPortFile(portFilePath)
282
+ const url = `http://127.0.0.1:${portFile.port}${requestOptions.path}`
283
+ const context = { path: requestOptions.path, url }
284
+ const headers = new Headers()
285
+
286
+ if (requestOptions.authenticated) {
287
+ headers.set('Authorization', `Bearer ${portFile.token}`)
288
+ }
289
+
290
+ if (requestOptions.method === 'POST') {
291
+ headers.set('content-type', 'application/json')
292
+ }
293
+
294
+ let response: Response
295
+
296
+ const requestSignal = createRequestSignal(
297
+ abortController.signal,
298
+ requestTimeoutMs,
299
+ )
300
+
301
+ try {
302
+ response = await fetchImpl(url, {
303
+ method: requestOptions.method,
304
+ headers,
305
+ body:
306
+ requestOptions.method === 'POST'
307
+ ? JSON.stringify(requestOptions.body ?? {})
308
+ : undefined,
309
+ signal: requestSignal.signal,
310
+ })
311
+ } catch (error) {
312
+ throw new RpcUnreachableError(
313
+ `Failed to reach Copilot delegate RPC at ${url}: ${errorMessage(error)}`,
314
+ { cause: error },
315
+ )
316
+ } finally {
317
+ requestSignal.cleanup()
318
+ }
319
+
320
+ if (!response.ok) {
321
+ const body = await parseErrorResponse(response)
322
+ const message = buildServerErrorMessage(response, context, body)
323
+
324
+ if (response.status === 401) {
325
+ throw new RpcAuthError(message, {
326
+ path: requestOptions.path,
327
+ status: response.status,
328
+ })
329
+ }
330
+
331
+ throw new RpcServerError(message, {
332
+ path: requestOptions.path,
333
+ status: response.status,
334
+ })
335
+ }
336
+
337
+ return validateBody(
338
+ requestOptions.schema,
339
+ await parseOkResponse(response, context),
340
+ context,
341
+ )
342
+ }
343
+
344
+ return {
345
+ health(): Promise<HealthResponse> {
346
+ return request({
347
+ method: 'GET',
348
+ path: '/health',
349
+ schema: HealthResponseSchema,
350
+ })
351
+ },
352
+
353
+ tasksList(): Promise<TasksListResponse> {
354
+ return request({
355
+ method: 'POST',
356
+ path: '/tasks/list',
357
+ authenticated: true,
358
+ body: {},
359
+ schema: TasksListResponseSchema,
360
+ })
361
+ },
362
+
363
+ tasksCancel(taskId: string): Promise<TasksCancelResponse> {
364
+ return request({
365
+ method: 'POST',
366
+ path: '/tasks/cancel',
367
+ authenticated: true,
368
+ body: validateCancelTaskId(taskId),
369
+ schema: TasksCancelResponseSchema,
370
+ })
371
+ },
372
+
373
+ dispose(): void {
374
+ abortController.abort()
375
+ },
376
+ }
377
+ }
378
+
379
+ export type RpcClient = ReturnType<typeof createRpcClient>