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