@snack-kit/porygon 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.
@@ -0,0 +1,715 @@
1
+ import { EventEmitter } from 'node:events';
2
+
3
+ /**
4
+ * 代理配置
5
+ */
6
+ interface ProxyConfig {
7
+ url: string;
8
+ noProxy?: string;
9
+ }
10
+ /**
11
+ * 后端配置
12
+ */
13
+ interface BackendConfig {
14
+ model?: string;
15
+ appendSystemPrompt?: string;
16
+ proxy?: ProxyConfig;
17
+ cwd?: string;
18
+ /** 透传给 CLI 的后端特定选项 */
19
+ options?: Record<string, unknown>;
20
+ }
21
+ /**
22
+ * Porygon 全局配置
23
+ */
24
+ interface PorygonConfig {
25
+ defaultBackend?: string;
26
+ backends?: Record<string, BackendConfig>;
27
+ defaults?: {
28
+ appendSystemPrompt?: string;
29
+ timeoutMs?: number;
30
+ maxTurns?: number;
31
+ };
32
+ proxy?: ProxyConfig;
33
+ }
34
+
35
+ /**
36
+ * MCP 服务器配置
37
+ */
38
+ interface McpServerConfig {
39
+ command: string;
40
+ args?: string[];
41
+ env?: Record<string, string>;
42
+ url?: string;
43
+ }
44
+ /**
45
+ * 用户传递给 query()/run() 的请求参数
46
+ */
47
+ interface PromptRequest {
48
+ prompt: string;
49
+ backend?: string;
50
+ /** 恢复会话的 session ID */
51
+ resume?: string;
52
+ /** 系统提示词(替换模式) */
53
+ systemPrompt?: string;
54
+ /** 系统提示词(追加模式) */
55
+ appendSystemPrompt?: string;
56
+ model?: string;
57
+ timeoutMs?: number;
58
+ allowedTools?: string[];
59
+ disallowedTools?: string[];
60
+ mcpServers?: Record<string, McpServerConfig>;
61
+ maxTurns?: number;
62
+ cwd?: string;
63
+ /** 透传给后端的额外选项 */
64
+ backendOptions?: Record<string, unknown>;
65
+ /** 注入到子进程的额外环境变量(如 CLAUDE_CODE_OAUTH_TOKEN、代理变量等) */
66
+ envVars?: Record<string, string>;
67
+ }
68
+ /**
69
+ * 统一输出消息联合类型
70
+ */
71
+ type AgentMessage = AgentSystemMessage | AgentAssistantMessage | AgentToolUseMessage | AgentStreamChunkMessage | AgentResultMessage | AgentErrorMessage;
72
+ interface BaseAgentMessage {
73
+ timestamp: number;
74
+ sessionId?: string;
75
+ /** 后端原始数据 */
76
+ raw?: unknown;
77
+ }
78
+ interface AgentSystemMessage extends BaseAgentMessage {
79
+ type: "system";
80
+ model?: string;
81
+ tools?: string[];
82
+ cwd?: string;
83
+ }
84
+ interface AgentAssistantMessage extends BaseAgentMessage {
85
+ type: "assistant";
86
+ text: string;
87
+ }
88
+ interface AgentToolUseMessage extends BaseAgentMessage {
89
+ type: "tool_use";
90
+ toolName: string;
91
+ input: Record<string, unknown>;
92
+ output?: string;
93
+ }
94
+ interface AgentStreamChunkMessage extends BaseAgentMessage {
95
+ type: "stream_chunk";
96
+ text: string;
97
+ }
98
+ interface AgentResultMessage extends BaseAgentMessage {
99
+ type: "result";
100
+ text: string;
101
+ durationMs?: number;
102
+ costUsd?: number;
103
+ inputTokens?: number;
104
+ outputTokens?: number;
105
+ }
106
+ interface AgentErrorMessage extends BaseAgentMessage {
107
+ type: "error";
108
+ message: string;
109
+ code?: string;
110
+ }
111
+
112
+ /**
113
+ * 适配器能力声明
114
+ */
115
+ interface AdapterCapabilities {
116
+ features: Set<"streaming" | "session-resume" | "system-prompt" | "tool-restriction" | "mcp" | "subagents" | "worktree" | "budget-limit" | "serve-mode">;
117
+ outputFormats: string[];
118
+ testedVersionRange: string;
119
+ }
120
+ /**
121
+ * 兼容性检查结果
122
+ */
123
+ interface CompatibilityResult {
124
+ version: string;
125
+ supported: boolean;
126
+ warnings: string[];
127
+ }
128
+ /**
129
+ * 会话信息
130
+ */
131
+ interface SessionInfo {
132
+ sessionId: string;
133
+ backend: string;
134
+ summary?: string;
135
+ lastModified: number;
136
+ cwd?: string;
137
+ metadata?: Record<string, unknown>;
138
+ }
139
+ /**
140
+ * 会话列表查询选项
141
+ */
142
+ interface SessionListOptions {
143
+ limit?: number;
144
+ cwd?: string;
145
+ }
146
+ /**
147
+ * Agent 适配器接口
148
+ */
149
+ interface IAgentAdapter {
150
+ readonly backend: string;
151
+ isAvailable(): Promise<boolean>;
152
+ getVersion(): Promise<string>;
153
+ getCapabilities(): AdapterCapabilities;
154
+ checkCompatibility(): Promise<CompatibilityResult>;
155
+ query(request: PromptRequest): AsyncGenerator<AgentMessage>;
156
+ listSessions(options?: SessionListOptions): Promise<SessionInfo[]>;
157
+ getSettings(): Promise<Record<string, unknown>>;
158
+ updateSettings(settings: Record<string, unknown>): Promise<void>;
159
+ /** 获取可用模型列表 */
160
+ listModels(): Promise<ModelInfo[]>;
161
+ abort(sessionId: string): void;
162
+ dispose(): Promise<void>;
163
+ }
164
+ /**
165
+ * 模型信息
166
+ */
167
+ interface ModelInfo {
168
+ id: string;
169
+ name?: string;
170
+ provider?: string;
171
+ }
172
+
173
+ type InterceptorDirection = "input" | "output";
174
+ interface InterceptorContext {
175
+ direction: InterceptorDirection;
176
+ backend: string;
177
+ sessionId?: string;
178
+ /** 仅输出方向可用 */
179
+ messageType?: string;
180
+ }
181
+ /**
182
+ * 拦截器函数签名
183
+ * - 返回 string: 替换文本,传递给下一个拦截器
184
+ * - 返回 false: 拒绝消息,抛出 InterceptorRejectedError
185
+ * - 返回 true/undefined: 不修改,传递原始文本给下一个拦截器
186
+ */
187
+ type InterceptorFn = (text: string, context: InterceptorContext) => string | boolean | undefined | Promise<string | boolean | undefined>;
188
+
189
+ /**
190
+ * Porygon 事件类型定义
191
+ */
192
+ interface PorygonEvents {
193
+ "session:created": (info: SessionInfo) => void;
194
+ "session:resumed": (info: SessionInfo) => void;
195
+ "process:spawn": (backend: string, pid: number) => void;
196
+ "process:exit": (backend: string, code: number | null) => void;
197
+ "process:error": (backend: string, error: Error) => void;
198
+ "process:restart": (backend: string, attempt: number) => void;
199
+ "interceptor:rejected": (direction: string, reason: string) => void;
200
+ "health:degraded": (backend: string, warning: string) => void;
201
+ }
202
+ /**
203
+ * Porygon 主门面类,提供统一的 LLM 后端交互接口。
204
+ * 管理适配器注册、拦截器流水线、进程生命周期和会话管理。
205
+ */
206
+ declare class Porygon extends EventEmitter {
207
+ private config;
208
+ private adapters;
209
+ private interceptors;
210
+ private processManager;
211
+ private sessionManager;
212
+ constructor(config?: Partial<PorygonConfig>);
213
+ /**
214
+ * 注册内置适配器
215
+ */
216
+ private registerBuiltinAdapters;
217
+ /**
218
+ * 注册自定义适配器
219
+ * @param adapter 适配器实例
220
+ */
221
+ registerAdapter(adapter: IAgentAdapter): void;
222
+ /**
223
+ * 获取指定后端的适配器
224
+ * @param backend 后端名称,默认使用配置中的 defaultBackend
225
+ */
226
+ private getAdapter;
227
+ /**
228
+ * 流式查询,返回 AgentMessage 异步生成器。
229
+ * 作为与 LLM 后端交互的主要入口。
230
+ * @param request 提示请求参数
231
+ * @yields AgentMessage 消息流
232
+ */
233
+ query(request: PromptRequest): AsyncGenerator<AgentMessage>;
234
+ /**
235
+ * 简单运行模式,收集所有消息并返回最终结果文本
236
+ * @param request 提示请求参数
237
+ * @returns 最终结果文本
238
+ */
239
+ run(request: PromptRequest): Promise<string>;
240
+ /**
241
+ * 注册拦截器
242
+ * @param direction 拦截方向
243
+ * @param fn 拦截器函数
244
+ * @returns 取消注册的函数
245
+ */
246
+ use(direction: InterceptorDirection, fn: InterceptorFn): () => void;
247
+ /**
248
+ * 获取后端能力声明
249
+ * @param backend 后端名称
250
+ */
251
+ getCapabilities(backend?: string): AdapterCapabilities;
252
+ /**
253
+ * 获取指定后端的可用模型列表
254
+ * @param backend 后端名称
255
+ */
256
+ listModels(backend?: string): Promise<ModelInfo[]>;
257
+ /**
258
+ * 对所有已注册后端进行健康检查
259
+ */
260
+ healthCheck(): Promise<Record<string, {
261
+ available: boolean;
262
+ compatibility: CompatibilityResult | null;
263
+ error?: string;
264
+ }>>;
265
+ /**
266
+ * 读取或更新后端设置
267
+ * @param backend 后端名称
268
+ * @param newSettings 要更新的设置项(可选)
269
+ * @returns 当前设置
270
+ */
271
+ settings(backend: string, newSettings?: Record<string, unknown>): Promise<Record<string, unknown>>;
272
+ /**
273
+ * 列出指定后端的会话
274
+ * @param backend 后端名称
275
+ * @param options 查询选项
276
+ */
277
+ listSessions(backend?: string, options?: SessionListOptions): Promise<SessionInfo[]>;
278
+ /**
279
+ * 中止正在运行的查询
280
+ * @param backend 后端名称
281
+ * @param sessionId 会话 ID
282
+ */
283
+ abort(backend: string, sessionId: string): void;
284
+ /**
285
+ * 释放所有资源
286
+ */
287
+ dispose(): Promise<void>;
288
+ /**
289
+ * 合并请求参数与配置默认值
290
+ * @param request 原始请求
291
+ * @param backend 后端名称
292
+ * @returns 合并后的请求
293
+ */
294
+ private mergeRequest;
295
+ }
296
+ /**
297
+ * 创建 Porygon 实例的工厂函数
298
+ * @param config 可选的配置参数
299
+ * @returns Porygon 实例
300
+ */
301
+ declare function createPorygon(config?: Partial<PorygonConfig>): Porygon;
302
+
303
+ /**
304
+ * Porygon 基础错误类
305
+ */
306
+ declare class PorygonError extends Error {
307
+ readonly code: string;
308
+ constructor(code: string, message: string, options?: ErrorOptions);
309
+ }
310
+ declare class AdapterNotFoundError extends PorygonError {
311
+ constructor(backend: string, options?: ErrorOptions);
312
+ }
313
+ declare class AdapterNotAvailableError extends PorygonError {
314
+ constructor(backend: string, options?: ErrorOptions);
315
+ }
316
+ declare class AdapterIncompatibleError extends PorygonError {
317
+ constructor(backend: string, version: string, options?: ErrorOptions);
318
+ }
319
+ declare class SessionNotFoundError extends PorygonError {
320
+ constructor(sessionId: string, options?: ErrorOptions);
321
+ }
322
+ declare class InterceptorRejectedError extends PorygonError {
323
+ constructor(reason: string, options?: ErrorOptions);
324
+ }
325
+ declare class AgentExecutionError extends PorygonError {
326
+ constructor(message: string, options?: ErrorOptions);
327
+ }
328
+ declare class AgentTimeoutError extends PorygonError {
329
+ constructor(timeoutMs: number, options?: ErrorOptions);
330
+ }
331
+ declare class ConfigValidationError extends PorygonError {
332
+ constructor(message: string, options?: ErrorOptions);
333
+ }
334
+
335
+ /**
336
+ * 防护拦截器触发时的处理动作
337
+ */
338
+ type GuardAction = "reject" | "redact";
339
+ /**
340
+ * 防护拦截器配置选项
341
+ */
342
+ interface GuardOptions {
343
+ /**
344
+ * 输入侧:阻止用户通过 prompt 注入攻击套取系统提示词或绕过规则。
345
+ * 匹配到任一模式时触发防护。
346
+ * @example [/忽略.*指令/, /重复.*系统提示/, /ignore.*instructions/i]
347
+ */
348
+ blockedPatterns?: RegExp[];
349
+ /**
350
+ * 输出侧:防止模型在回复中泄露系统提示词内容。
351
+ * 提供需要保护的关键词列表,若输出中包含这些关键词则触发防护。
352
+ * @example ["内部密钥", "SECRET_TOKEN"]
353
+ */
354
+ sensitiveKeywords?: string[];
355
+ /**
356
+ * 触发防护时的处理动作:
357
+ * - "reject": 拒绝消息,抛出 InterceptorRejectedError(默认)
358
+ * - "redact": 替换匹配内容为 [REDACTED],允许消息继续传递
359
+ */
360
+ action?: GuardAction;
361
+ /**
362
+ * 自定义判定函数,在内置规则之后执行。
363
+ * 返回 true 表示触发防护,返回 false 或 undefined 表示放行。
364
+ */
365
+ customCheck?: (text: string, context: InterceptorContext) => boolean | undefined;
366
+ /**
367
+ * 仅对指定后端生效,不设则对所有后端生效
368
+ */
369
+ backends?: string[];
370
+ }
371
+ /**
372
+ * 创建输入防护拦截器。
373
+ * 检测并阻止常见的 prompt 注入攻击,防止用户套取系统提示词或绕过规则。
374
+ *
375
+ * @param options 防护配置选项
376
+ * @returns 可注册到 `porygon.use("input", ...)` 的拦截器函数
377
+ *
378
+ * @example
379
+ * ```ts
380
+ * // 使用内置规则
381
+ * porygon.use("input", createInputGuard());
382
+ *
383
+ * // 自定义阻止模式
384
+ * porygon.use("input", createInputGuard({
385
+ * blockedPatterns: [/我是管理员/, /sudo mode/i],
386
+ * action: "reject",
387
+ * }));
388
+ * ```
389
+ */
390
+ declare function createInputGuard(options?: GuardOptions): InterceptorFn;
391
+ /**
392
+ * 创建输出防护拦截器。
393
+ * 检测模型输出中是否包含敏感关键词,防止系统提示词内容泄露。
394
+ *
395
+ * @param options 防护配置选项
396
+ * @returns 可注册到 `porygon.use("output", ...)` 的拦截器函数
397
+ *
398
+ * @example
399
+ * ```ts
400
+ * porygon.use("output", createOutputGuard({
401
+ * sensitiveKeywords: ["内部API密钥", "sk-xxxx"],
402
+ * action: "redact",
403
+ * }));
404
+ * ```
405
+ */
406
+ declare function createOutputGuard(options?: GuardOptions): InterceptorFn;
407
+
408
+ /**
409
+ * 进程启动选项
410
+ */
411
+ interface SpawnOptions {
412
+ command: string;
413
+ args: string[];
414
+ cwd?: string;
415
+ env?: Record<string, string>;
416
+ timeoutMs?: number;
417
+ }
418
+ /**
419
+ * 进程执行结果
420
+ */
421
+ interface ProcessResult {
422
+ exitCode: number | null;
423
+ signal: string | null;
424
+ stdout: string;
425
+ stderr: string;
426
+ }
427
+ /**
428
+ * 持久进程选项
429
+ */
430
+ interface PersistentProcessOptions {
431
+ command: string;
432
+ args: string[];
433
+ cwd?: string;
434
+ env?: Record<string, string>;
435
+ maxRestarts: number;
436
+ restartIntervalMs: number;
437
+ healthCheckIntervalMs: number;
438
+ healthCheckFn?: () => Promise<boolean>;
439
+ }
440
+
441
+ /**
442
+ * EphemeralProcess:一次性进程执行,支持流式输出。
443
+ * 适用于 `claude -p` 和 `opencode run` 等短生命周期调用场景。
444
+ */
445
+ declare class EphemeralProcess {
446
+ private childProcess;
447
+ private aborted;
448
+ /**
449
+ * 执行命令并收集输出。支持 AbortController 进行取消操作。
450
+ * @param options 进程启动选项
451
+ * @param abortSignal 可选的中止信号
452
+ * @returns 进程执行结果
453
+ */
454
+ execute(options: SpawnOptions, abortSignal?: AbortSignal): Promise<ProcessResult>;
455
+ /**
456
+ * 以流式方式执行命令,逐行输出 stdout 内容。
457
+ * @param options 进程启动选项
458
+ * @param abortSignal 可选的中止信号
459
+ */
460
+ executeStreaming(options: SpawnOptions, abortSignal?: AbortSignal): AsyncGenerator<string>;
461
+ /** 获取底层子进程的 PID */
462
+ get pid(): number | undefined;
463
+ /** 终止进程:先发送 SIGTERM,超时后发送 SIGKILL */
464
+ terminate(): void;
465
+ }
466
+ /**
467
+ * PersistentProcess:长期运行的服务进程,支持自动重启。
468
+ * 适用于 `opencode serve` 等持久化服务场景。
469
+ */
470
+ declare class PersistentProcess extends EventEmitter {
471
+ private process;
472
+ private restartCount;
473
+ private stopped;
474
+ private healthCheckTimer;
475
+ private readonly options;
476
+ constructor(options: PersistentProcessOptions);
477
+ /** 启动持久进程 */
478
+ start(): Promise<void>;
479
+ /** 处理进程崩溃,按指数退避策略重启 */
480
+ private handleCrash;
481
+ /** 停止健康检查定时器 */
482
+ private stopHealthCheck;
483
+ /** 停止持久进程 */
484
+ stop(): Promise<void>;
485
+ /** 获取底层子进程的 PID */
486
+ get pid(): number | undefined;
487
+ /** 当前进程是否正在运行 */
488
+ get isRunning(): boolean;
489
+ }
490
+
491
+ /**
492
+ * ProcessManager:统一管理所有子进程。
493
+ * 注册退出钩子,确保主进程退出时清理所有子进程。
494
+ */
495
+ declare class ProcessManager {
496
+ private readonly ephemeral;
497
+ private readonly persistent;
498
+ /** 全局静态标记,确保信号处理器只注册一次 */
499
+ private static cleanupRegistered;
500
+ /** 所有活跃的 ProcessManager 实例(弱引用避免阻止 GC) */
501
+ private static readonly instances;
502
+ constructor();
503
+ /** 注册进程退出清理钩子(仅清理资源,不劫持宿主退出行为) */
504
+ private static registerCleanup;
505
+ /**
506
+ * 创建一次性进程实例并注册到管理器
507
+ * @param sessionId 会话标识
508
+ * @returns 一次性进程实例
509
+ */
510
+ createEphemeral(sessionId: string): EphemeralProcess;
511
+ /**
512
+ * 从管理器中移除一次性进程
513
+ * @param sessionId 会话标识
514
+ */
515
+ removeEphemeral(sessionId: string): void;
516
+ /**
517
+ * 启动或获取持久进程
518
+ * @param backend 后端标识
519
+ * @param options 持久进程选项
520
+ * @returns 持久进程实例
521
+ */
522
+ startPersistent(backend: string, options: PersistentProcessOptions): Promise<PersistentProcess>;
523
+ /**
524
+ * 获取指定后端的持久进程
525
+ * @param backend 后端标识
526
+ */
527
+ getPersistent(backend: string): PersistentProcess | undefined;
528
+ /**
529
+ * 获取指定会话的一次性进程
530
+ * @param sessionId 会话标识
531
+ */
532
+ getEphemeral(sessionId: string): EphemeralProcess | undefined;
533
+ /** 异步终止所有托管进程 */
534
+ terminateAll(): Promise<void>;
535
+ /** 同步终止所有托管进程(用于 exit 钩子) */
536
+ private terminateAllSync;
537
+ /**
538
+ * 销毁实例,从全局实例列表中移除
539
+ */
540
+ destroy(): void;
541
+ }
542
+
543
+ /**
544
+ * Agent 适配器抽象基类,实现 IAgentAdapter 接口的公共逻辑。
545
+ * 子类需实现所有 abstract 方法以完成具体后端的适配。
546
+ */
547
+ declare abstract class AbstractAgentAdapter implements IAgentAdapter {
548
+ abstract readonly backend: string;
549
+ /** 活跃的 AbortController 映射,按 sessionId 索引 */
550
+ protected readonly abortControllers: Map<string, AbortController>;
551
+ protected readonly processManager: ProcessManager;
552
+ protected readonly config?: BackendConfig;
553
+ constructor(processManager: ProcessManager, config?: BackendConfig);
554
+ /**
555
+ * 默认兼容性检查:获取当前版本并与 testedVersionRange 进行比较
556
+ */
557
+ checkCompatibility(): Promise<CompatibilityResult>;
558
+ /**
559
+ * 中止指定会话的执行
560
+ * @param sessionId 会话标识
561
+ */
562
+ abort(sessionId: string): void;
563
+ /**
564
+ * 创建并注册 AbortController
565
+ * @param sessionId 会话标识
566
+ * @returns AbortController 实例
567
+ */
568
+ protected createAbortController(sessionId: string): AbortController;
569
+ /**
570
+ * 清理指定会话的 AbortController
571
+ * @param sessionId 会话标识
572
+ */
573
+ protected removeAbortController(sessionId: string): void;
574
+ abstract isAvailable(): Promise<boolean>;
575
+ abstract getVersion(): Promise<string>;
576
+ abstract getCapabilities(): AdapterCapabilities;
577
+ abstract query(request: PromptRequest): AsyncGenerator<AgentMessage>;
578
+ abstract listSessions(options?: SessionListOptions): Promise<SessionInfo[]>;
579
+ abstract listModels(): Promise<ModelInfo[]>;
580
+ abstract getSettings(): Promise<Record<string, unknown>>;
581
+ abstract updateSettings(settings: Record<string, unknown>): Promise<void>;
582
+ abstract dispose(): Promise<void>;
583
+ }
584
+
585
+ /**
586
+ * Claude Code CLI 适配器。
587
+ * 通过 `claude -p --output-format stream-json` 命令与 Claude Code 交互。
588
+ */
589
+ declare class ClaudeAdapter extends AbstractAgentAdapter {
590
+ readonly backend = "claude";
591
+ /**
592
+ * 检查 Claude CLI 是否可用
593
+ */
594
+ isAvailable(): Promise<boolean>;
595
+ /**
596
+ * 获取 Claude CLI 版本号
597
+ */
598
+ getVersion(): Promise<string>;
599
+ /**
600
+ * 获取 Claude 适配器能力声明
601
+ */
602
+ getCapabilities(): AdapterCapabilities;
603
+ /**
604
+ * 向 Claude 发送提示并以流式方式接收响应
605
+ * @param request 提示请求参数
606
+ */
607
+ query(request: PromptRequest): AsyncGenerator<AgentMessage>;
608
+ /**
609
+ * 列出 Claude 会话
610
+ * @param options 查询选项
611
+ */
612
+ listSessions(options?: SessionListOptions): Promise<SessionInfo[]>;
613
+ /**
614
+ * 获取 Claude 可用模型列表。
615
+ * Claude CLI 支持使用简短别名(sonnet/opus/haiku)自动选择当前最新版本。
616
+ */
617
+ listModels(): Promise<ModelInfo[]>;
618
+ /**
619
+ * 读取 Claude 设置
620
+ */
621
+ getSettings(): Promise<Record<string, unknown>>;
622
+ /**
623
+ * 更新 Claude 设置(读取-合并-写入)
624
+ * @param settings 要合并的设置项
625
+ */
626
+ updateSettings(settings: Record<string, unknown>): Promise<void>;
627
+ /**
628
+ * 释放适配器资源
629
+ */
630
+ dispose(): Promise<void>;
631
+ /**
632
+ * 将代理配置注入到环境变量中
633
+ * @param env 环境变量对象
634
+ * @param proxyUrl 代理地址
635
+ * @param noProxy 不走代理的地址列表
636
+ */
637
+ private applyProxyEnv;
638
+ private buildArgs;
639
+ }
640
+
641
+ /**
642
+ * OpenCode 适配器。
643
+ * 通过 `opencode serve` 启动 HTTP 服务,使用 REST API + SSE 进行交互。
644
+ */
645
+ declare class OpenCodeAdapter extends AbstractAgentAdapter {
646
+ readonly backend = "opencode";
647
+ private apiClient;
648
+ private servePort;
649
+ /**
650
+ * @param processManager 进程管理器实例
651
+ * @param servePort 可选的 serve 服务端口
652
+ */
653
+ constructor(processManager: ProcessManager, servePort?: number);
654
+ /**
655
+ * 检查 opencode 命令是否可用
656
+ */
657
+ isAvailable(): Promise<boolean>;
658
+ /**
659
+ * 获取 opencode 版本号
660
+ */
661
+ getVersion(): Promise<string>;
662
+ /**
663
+ * 获取适配器能力声明
664
+ */
665
+ getCapabilities(): AdapterCapabilities;
666
+ /**
667
+ * 执行查询:启动 serve 进程(如未启动),创建/恢复会话,发送消息并流式返回结果
668
+ * @param request 请求参数
669
+ * @yields AgentMessage 统一消息流
670
+ */
671
+ query(request: PromptRequest): AsyncGenerator<AgentMessage>;
672
+ /**
673
+ * 列出历史会话
674
+ * @param options 查询选项
675
+ */
676
+ listSessions(options?: SessionListOptions): Promise<SessionInfo[]>;
677
+ /**
678
+ * 获取 OpenCode 可用模型列表(通过 `opencode models` 命令)
679
+ */
680
+ listModels(): Promise<ModelInfo[]>;
681
+ /**
682
+ * 读取 opencode 配置文件
683
+ */
684
+ getSettings(): Promise<Record<string, unknown>>;
685
+ /**
686
+ * 更新 opencode 配置文件(读取-合并-写入)
687
+ * @param settings 要合并的配置项
688
+ */
689
+ updateSettings(settings: Record<string, unknown>): Promise<void>;
690
+ /**
691
+ * 释放资源:停止 serve 进程,中止所有活跃流
692
+ */
693
+ dispose(): Promise<void>;
694
+ /**
695
+ * 确保 opencode serve 进程已启动并可用
696
+ * @returns 可用的 API 客户端
697
+ */
698
+ private ensureServeRunning;
699
+ /**
700
+ * 轮询等待 serve 服务可达
701
+ * @param client API 客户端
702
+ */
703
+ private waitForServeReady;
704
+ /**
705
+ * 延迟指定毫秒
706
+ * @param ms 毫秒数
707
+ */
708
+ private delay;
709
+ /**
710
+ * 获取 opencode 配置文件路径
711
+ */
712
+ private getConfigPath;
713
+ }
714
+
715
+ export { AbstractAgentAdapter, type AdapterCapabilities, AdapterIncompatibleError, AdapterNotAvailableError, AdapterNotFoundError, type AgentAssistantMessage, type AgentErrorMessage, AgentExecutionError, type AgentMessage, type AgentResultMessage, type AgentStreamChunkMessage, type AgentSystemMessage, AgentTimeoutError, type AgentToolUseMessage, type BackendConfig, ClaudeAdapter, type CompatibilityResult, ConfigValidationError, type GuardAction, type GuardOptions, type IAgentAdapter, type InterceptorContext, type InterceptorDirection, type InterceptorFn, InterceptorRejectedError, type McpServerConfig, type ModelInfo, OpenCodeAdapter, Porygon, type PorygonConfig, PorygonError, type PorygonEvents, type PromptRequest, type ProxyConfig, type SessionInfo, type SessionListOptions, SessionNotFoundError, createInputGuard, createOutputGuard, createPorygon };