@luchenglong/cli-bridge 0.2.9 → 0.2.10
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/CHANGELOG.md +42 -0
- package/PROVIDER-CONTRACT.md +34 -1
- package/docs/HANDOVER.md +109 -15
- package/dynamic/claude.host.js +138 -81
- package/dynamic/codebuddy.host.js +1426 -1378
- package/dynamic/codex.host.js +78 -103
- package/dynamic/mimo.host.js +720 -514
- package/dynamic/mimo.host.template.mjs +2 -0
- package/dynamic/opencode.host.js +740 -584
- package/dynamic/opencode.host.template.mjs +2 -0
- package/home-plugin/cli-bridge-indicator/lib/client.js +590 -600
- package/home-plugin/cli-bridge-indicator/lib/index.mjs +48 -0
- package/home-plugin/cli-bridge-indicator/lib/preset-declarations.mjs +1 -1
- package/mcp/cli-bridge-mcp.mjs +3 -3
- package/mcp/providers/codebuddy.mjs +427 -427
- package/package.json +3 -3
- package/providers/claude-models.mjs +80 -76
- package/providers/claude.mjs +59 -6
- package/providers/codebuddy-catalog.mjs +367 -599
- package/providers/codebuddy-consts.mjs +72 -72
- package/providers/codebuddy-models-source.mjs +254 -0
- package/providers/codebuddy-models-tool.mjs +106 -106
- package/providers/codebuddy-schemas.mjs +46 -46
- package/providers/codebuddy.mjs +600 -578
- package/providers/codex-cli.mjs +33 -99
- package/providers/codex.mjs +45 -4
- package/providers/mimo-pure.mjs +270 -111
- package/providers/mimo.mjs +453 -517
- package/providers/opencode-exe.mjs +190 -63
- package/providers/opencode.mjs +553 -587
- package/scripts/build.mjs +261 -261
package/providers/opencode.mjs
CHANGED
|
@@ -1,587 +1,553 @@
|
|
|
1
|
-
// providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
|
|
2
|
-
//
|
|
3
|
-
// 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
|
|
4
|
-
// 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
|
|
5
|
-
// • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
|
|
6
|
-
// `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
|
|
7
|
-
// • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
|
|
8
|
-
// • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
|
|
9
|
-
// • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
|
|
10
|
-
// step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
|
|
11
|
-
//
|
|
12
|
-
// 红线(PROVIDER-CONTRACT.md §8 + §1):
|
|
13
|
-
// - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
|
|
14
|
-
// process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
|
|
15
|
-
// - 只允许 import '../core/bridge-kit.mjs'
|
|
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
|
-
const
|
|
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
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
return
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
if (
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
const r =
|
|
439
|
-
const
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
const
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
if (e.OPENCODE_BIN || e.OPENCODE_CLI)
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
const
|
|
525
|
-
|
|
526
|
-
const
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
descriptor.statusToolLogic = function (args) {
|
|
555
|
-
const a = args || {}
|
|
556
|
-
const snap = this.engine.statusSnapshot()
|
|
557
|
-
if (a.cwd) {
|
|
558
|
-
const key = String(a.cwd)
|
|
559
|
-
snap.projects = snap.projects.filter((p) => p.cwd === key)
|
|
560
|
-
const g = snap.projects[0]
|
|
561
|
-
if (g) {
|
|
562
|
-
Object.assign(snap, {
|
|
563
|
-
state: g.state, running: g.running, current: g.current, trail: g.trail,
|
|
564
|
-
lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
|
|
565
|
-
lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
|
|
566
|
-
})
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
return snap
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
descriptor.attach = function (hostOpts) {
|
|
573
|
-
host = hostOpts || {}
|
|
574
|
-
// 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
|
|
575
|
-
try {
|
|
576
|
-
if (typeof host.getSettings === 'function') {
|
|
577
|
-
const s = host.getSettings('opencode')
|
|
578
|
-
if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
|
|
579
|
-
}
|
|
580
|
-
} catch (e) { }
|
|
581
|
-
this.engine = createStatusEngine({ provider: this, publish: host.publish })
|
|
582
|
-
const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
|
|
583
|
-
this.runner = runner
|
|
584
|
-
return runner
|
|
585
|
-
}
|
|
586
|
-
return descriptor
|
|
587
|
-
}
|
|
1
|
+
// providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
|
|
2
|
+
//
|
|
3
|
+
// 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
|
|
4
|
+
// 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
|
|
5
|
+
// • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
|
|
6
|
+
// `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
|
|
7
|
+
// • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
|
|
8
|
+
// • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
|
|
9
|
+
// • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
|
|
10
|
+
// step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
|
|
11
|
+
//
|
|
12
|
+
// 红线(PROVIDER-CONTRACT.md §8 + §1):
|
|
13
|
+
// - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
|
|
14
|
+
// process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
|
|
15
|
+
// - 只允许 import '../core/bridge-kit.mjs'(以及同目录的 opencode-exe.mjs 片文件,
|
|
16
|
+
// build 会把 providers/opencode-*.mjs 一并内联进同一沙箱作用域)。
|
|
17
|
+
// 契约 §3.2:设置面板**不自动探测**模型列表 —— settings.meta() 只读上次手动拉取的
|
|
18
|
+
// 缓存(缓存在 providers/opencode-exe.mjs),用户点「拉取可用模型」才走 refreshModels。
|
|
19
|
+
import { createStatusEngine, createRunner, clampInt, isLimited } from '../core/bridge-kit.mjs'
|
|
20
|
+
import {
|
|
21
|
+
candidateExePaths, resolveExePrefix, parseModelList,
|
|
22
|
+
sortModelsFreeFirst, fetchModelsDetailed, cachedModels, rememberModels
|
|
23
|
+
} from './opencode-exe.mjs'
|
|
24
|
+
export { candidateExePaths, resolveExePrefix, parseModelList }
|
|
25
|
+
|
|
26
|
+
function nowIso() { return new Date().toISOString() }
|
|
27
|
+
|
|
28
|
+
// 模型清单 → 下拉选项 / id→label 映射(免费模型带 [free] 后缀,与 opencode_models 展示一致)。
|
|
29
|
+
function modelLabel(m) { return String(m.id) + ((m && m.free) ? ' [free]' : '') }
|
|
30
|
+
function modelsToOptions(models) {
|
|
31
|
+
return (Array.isArray(models) ? models : []).map((m) => ({ value: String(m.id), label: modelLabel(m) }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 可执行文件探测 / 模型清单解析 / 手动拉取缓存全部在 providers/opencode-exe.mjs,
|
|
35
|
+
// 本文件只消费(契约 §3.2:settings.meta 只读缓存,绝不在面板渲染时 spawn)。
|
|
36
|
+
// 二进制名是 opencode-cli(V2 桌面版自带):V1/V2 不能并存安装(官方原话),
|
|
37
|
+
// 故不做 opencode.exe 兜底,以免误命中另一个版本。
|
|
38
|
+
|
|
39
|
+
// ── 三工具 schema ────────────────────────────────────────────────────────────
|
|
40
|
+
const RUN_PARAMS = {
|
|
41
|
+
type: 'object',
|
|
42
|
+
additionalProperties: false,
|
|
43
|
+
required: ['prompt'],
|
|
44
|
+
properties: {
|
|
45
|
+
prompt: { type: 'string', description: 'The task instruction for opencode. On first dispatch for a topic, include a compact CONTEXT preamble (goal, repo root, key paths, decisions/constraints; point at paths, do not paste file contents — opencode reads the repo itself). For follow-ups on the same topic, use opencode_continue with latest=true or sessionId (opencode keeps session context; state only what is new).' },
|
|
46
|
+
model: { type: 'string', description: 'Optional model in provider/model form (e.g. "opencode/big-pickle"). Prefer a -free model when the task does not need a frontier model. Omit to use the model chosen in the CLI Bridge settings panel, or (if unset there) opencode\'s own default.' },
|
|
47
|
+
agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
|
|
48
|
+
cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
|
|
49
|
+
files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
|
|
50
|
+
title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
|
|
51
|
+
timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
|
|
52
|
+
autoApprove: { type: 'boolean', description: 'Default true: pass --auto so opencode auto-approves permissions and never blocks on a prompt. Set false to require explicit approval (opencode may then block and hit the timeout).' },
|
|
53
|
+
background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const CONTINUE_PARAMS = {
|
|
57
|
+
type: 'object',
|
|
58
|
+
additionalProperties: false,
|
|
59
|
+
required: ['prompt'],
|
|
60
|
+
properties: {
|
|
61
|
+
prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
|
|
62
|
+
sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
|
|
63
|
+
latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
|
|
64
|
+
model: { type: 'string', description: 'Optional model in provider/model form.' },
|
|
65
|
+
agent: { type: 'string', description: 'Optional opencode agent name.' },
|
|
66
|
+
cwd: { type: 'string', description: 'Working directory for opencode.' },
|
|
67
|
+
files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
|
|
68
|
+
timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
|
|
69
|
+
autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
|
|
70
|
+
background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
|
|
74
|
+
|
|
75
|
+
// opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
|
|
76
|
+
const MODELS_PARAMS = {
|
|
77
|
+
type: 'object',
|
|
78
|
+
additionalProperties: false,
|
|
79
|
+
required: [],
|
|
80
|
+
properties: {
|
|
81
|
+
freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
|
|
82
|
+
provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const MODELS_DESCRIPTION = 'List the models available to the local opencode CLI (from `opencode models`). Returns { ok, models: [{id, provider, name, free}], count }. Use this to pick a model before opencode_run, or to check which models are free. Prefer a -free model for routine work and reserve paid/frontier models for tasks that genuinely need them. If the CLI is missing or not logged in, this returns ok:false with an actionable error — it never silently invents a model list.'
|
|
86
|
+
|
|
87
|
+
function renderModels(value) {
|
|
88
|
+
const v = value || {}
|
|
89
|
+
if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
|
|
90
|
+
const list = Array.isArray(v.models) ? v.models : []
|
|
91
|
+
if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
|
|
92
|
+
const lines = ['opencode models (' + list.length + '):']
|
|
93
|
+
for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
|
|
94
|
+
if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
|
|
95
|
+
const free = list.filter((m) => m.free).length
|
|
96
|
+
lines.push('free: ' + free + ' / ' + list.length)
|
|
97
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export default function defineProvider(deps = {}) {
|
|
101
|
+
const env = deps.env || {}
|
|
102
|
+
let host = null
|
|
103
|
+
let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
|
|
107
|
+
* 面板改默认模型后无需重启即生效:
|
|
108
|
+
* 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
|
|
109
|
+
* 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
|
|
110
|
+
* 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
|
|
111
|
+
* 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
|
|
112
|
+
*
|
|
113
|
+
* 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
|
|
114
|
+
* defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
|
|
115
|
+
* 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
|
|
116
|
+
*/
|
|
117
|
+
function currentSettings() {
|
|
118
|
+
const out = Object.assign({}, settingsRef)
|
|
119
|
+
try {
|
|
120
|
+
if (typeof deps.readSettings === 'function') {
|
|
121
|
+
const r = deps.readSettings()
|
|
122
|
+
if (r && typeof r === 'object') {
|
|
123
|
+
const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
|
|
124
|
+
if (part && typeof part === 'object') Object.assign(out, part)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} catch (e) { }
|
|
128
|
+
try {
|
|
129
|
+
if (host && typeof host.getSettings === 'function') {
|
|
130
|
+
const s = host.getSettings('opencode')
|
|
131
|
+
if (s && typeof s === 'object') Object.assign(out, s)
|
|
132
|
+
}
|
|
133
|
+
} catch (e) { }
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const descriptor = {
|
|
138
|
+
id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
|
|
139
|
+
exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
|
|
140
|
+
|
|
141
|
+
// 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
|
|
142
|
+
backends() { return null },
|
|
143
|
+
normalizeBackend() { return null },
|
|
144
|
+
resolveBackend(args, target, preferred) { return null },
|
|
145
|
+
|
|
146
|
+
// 实测 flag 集(V2.0.29)。
|
|
147
|
+
buildArgv(exePrefix, args, opts) {
|
|
148
|
+
const o = opts || {}
|
|
149
|
+
const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
|
|
150
|
+
argv.push('run', String(args.prompt), '--format', 'json')
|
|
151
|
+
if (args.autoApprove !== false) argv.push('--auto')
|
|
152
|
+
const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
|
|
153
|
+
// 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
|
|
154
|
+
// 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
|
|
155
|
+
const model = args.model || currentSettings().defaultModel || ''
|
|
156
|
+
if (model) argv.push('--model', String(model))
|
|
157
|
+
const agent = args.agent || currentSettings().defaultAgent || ''
|
|
158
|
+
if (agent) argv.push('--agent', String(agent))
|
|
159
|
+
if (args.title) argv.push('--title', String(args.title))
|
|
160
|
+
if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
|
|
161
|
+
if (args.sessionId) argv.push('--session', String(args.sessionId))
|
|
162
|
+
else if (args.continueLatest) argv.push('--continue')
|
|
163
|
+
return { argv, mode: 'auto', timeoutSec }
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
// JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
|
|
167
|
+
// step_start / text / reasoning / tool_use / step_finish / error。
|
|
168
|
+
// ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
|
|
169
|
+
// ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
|
|
170
|
+
// cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
|
|
171
|
+
// ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
|
|
172
|
+
// step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
|
|
173
|
+
// 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
|
|
174
|
+
// 是活的必经分支,不是死代码。
|
|
175
|
+
// 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
|
|
176
|
+
// 回填进 part.text,让 buildResult 统一从 part.text 读正文。
|
|
177
|
+
// 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
|
|
178
|
+
parseJson(stdoutText) {
|
|
179
|
+
const trimmed = String(stdoutText || '').trim()
|
|
180
|
+
if (!trimmed) return null
|
|
181
|
+
const lines = trimmed.split(/\r?\n/).filter(Boolean)
|
|
182
|
+
let lastText = null
|
|
183
|
+
let lastTextStr = ''
|
|
184
|
+
let terminal = null
|
|
185
|
+
let fallback = null
|
|
186
|
+
for (const raw of lines) {
|
|
187
|
+
const ln = raw.trim()
|
|
188
|
+
if (!ln.startsWith('{')) continue
|
|
189
|
+
let obj
|
|
190
|
+
try { obj = JSON.parse(ln) } catch (e) { continue }
|
|
191
|
+
if (!obj || typeof obj !== 'object') continue
|
|
192
|
+
const part = obj.part && typeof obj.part === 'object' ? obj.part : null
|
|
193
|
+
if (obj.type === 'text' && part && typeof part.text === 'string') {
|
|
194
|
+
lastText = obj
|
|
195
|
+
lastTextStr = part.text
|
|
196
|
+
} else if (obj.type === 'error') {
|
|
197
|
+
terminal = obj
|
|
198
|
+
} else if (obj.type === 'step_finish') {
|
|
199
|
+
if (!terminal || terminal.type !== 'error') terminal = obj
|
|
200
|
+
}
|
|
201
|
+
fallback = obj
|
|
202
|
+
}
|
|
203
|
+
if (terminal) {
|
|
204
|
+
const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
|
|
205
|
+
if (lastTextStr && !(part && typeof part.text === 'string')) {
|
|
206
|
+
terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
|
|
207
|
+
}
|
|
208
|
+
return terminal
|
|
209
|
+
}
|
|
210
|
+
return lastText || fallback
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
// 统一结果对象(契约 §1 buildResult 行)。
|
|
214
|
+
// 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
|
|
215
|
+
// 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
|
|
216
|
+
buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
|
|
217
|
+
const exitCode = outcome ? outcome.exitCode : null
|
|
218
|
+
const stderr = stderrText ? String(stderrText).slice(-2000) : ''
|
|
219
|
+
if (parsed && typeof parsed === 'object') {
|
|
220
|
+
const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
|
|
221
|
+
: (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
|
|
222
|
+
const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
|
|
223
|
+
const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
|
|
224
|
+
const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
|
|
225
|
+
const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
|
|
226
|
+
: (errObj && typeof errObj.message === 'string' ? errObj.message
|
|
227
|
+
: (typeof parsed.error === 'string' ? parsed.error : ''))
|
|
228
|
+
let response = ''
|
|
229
|
+
if (typeof part.text === 'string') response = part.text
|
|
230
|
+
else if (typeof parsed.response === 'string') response = parsed.response
|
|
231
|
+
const isErrorEvent = parsed.type === 'error'
|
|
232
|
+
let status
|
|
233
|
+
if (exitCode === 130) status = 'ABORTED'
|
|
234
|
+
else if (isErrorEvent) status = 'ERROR'
|
|
235
|
+
else if (typeof parsed.status === 'string') status = parsed.status
|
|
236
|
+
else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
|
|
237
|
+
const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
|
|
238
|
+
let totalTokens = null
|
|
239
|
+
if (tokens) {
|
|
240
|
+
if (typeof tokens.total === 'number') totalTokens = tokens.total
|
|
241
|
+
else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
|
|
242
|
+
else {
|
|
243
|
+
let sum = 0
|
|
244
|
+
let any = false
|
|
245
|
+
for (const k of Object.keys(tokens)) {
|
|
246
|
+
if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
|
|
247
|
+
}
|
|
248
|
+
if (any) totalTokens = sum
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
ok: exitCode === 0 && !isErrorEvent,
|
|
253
|
+
status,
|
|
254
|
+
response,
|
|
255
|
+
sessionId,
|
|
256
|
+
durationSeconds: null,
|
|
257
|
+
numTurns: null,
|
|
258
|
+
totalTokens,
|
|
259
|
+
exitCode, mode, backend: backend || null,
|
|
260
|
+
stderr: (stderr ? stderr + ' ' : '') + errMsg,
|
|
261
|
+
cost: typeof part.cost === 'number' ? part.cost : null
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const text = String(stdoutText || '').trim()
|
|
265
|
+
return {
|
|
266
|
+
ok: exitCode === 0,
|
|
267
|
+
status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
|
|
268
|
+
response: text,
|
|
269
|
+
sessionId: null,
|
|
270
|
+
durationSeconds: null, numTurns: null, totalTokens: null,
|
|
271
|
+
exitCode, mode, backend: backend || null, stderr,
|
|
272
|
+
rawStdout: text.slice(-2000)
|
|
273
|
+
}
|
|
274
|
+
},
|
|
275
|
+
|
|
276
|
+
// 实时步骤折叠(写 project.current/trail)。
|
|
277
|
+
// tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
|
|
278
|
+
// text.part = { text:"…", time:{start,end} }
|
|
279
|
+
foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
|
|
280
|
+
if (!ev || typeof ev !== 'object') return
|
|
281
|
+
const type = ev.type
|
|
282
|
+
if (!type) return
|
|
283
|
+
const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
|
|
284
|
+
p.updatedAt = Date.now()
|
|
285
|
+
if (type === 'tool_use') {
|
|
286
|
+
const tool = part.tool || part.name || 'tool'
|
|
287
|
+
const st = part.state && typeof part.state === 'object' ? part.state : {}
|
|
288
|
+
const args = summarizeArgs(st.input || part.input)
|
|
289
|
+
const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
|
|
290
|
+
const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
|
|
291
|
+
p.trail.push(entry)
|
|
292
|
+
const cap = maxTrail || 12
|
|
293
|
+
if (p.trail.length > cap) p.trail.shift()
|
|
294
|
+
if (p.current) p.current = null
|
|
295
|
+
} else if (type === 'text' || type === 'reasoning') {
|
|
296
|
+
const delta = typeof part.text === 'string' ? part.text : ''
|
|
297
|
+
if (!delta) return
|
|
298
|
+
const capLen = maxArgLen || 120
|
|
299
|
+
p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
|
|
300
|
+
} else if (type === 'step_finish') {
|
|
301
|
+
if (p.current) p.current = null
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
|
|
305
|
+
isTransientCliError(res) {
|
|
306
|
+
if (!res || res.ok) return false
|
|
307
|
+
if (isLimited(res)) return false
|
|
308
|
+
return res.status === 'ERROR_DURING_EXECUTION'
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
failureHint(res) {
|
|
312
|
+
if (!res || res.ok) return ''
|
|
313
|
+
const st = String(res.status || '')
|
|
314
|
+
if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
|
|
315
|
+
const hay = String(res.stderr || '') + ' ' + String(res.response || '')
|
|
316
|
+
if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
|
|
317
|
+
return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
|
|
318
|
+
}
|
|
319
|
+
if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
|
|
320
|
+
return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
|
|
321
|
+
}
|
|
322
|
+
if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
|
|
323
|
+
return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
|
|
324
|
+
}
|
|
325
|
+
return ''
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
isSuccessStatus(st) { return st === 'SUCCESS' },
|
|
329
|
+
|
|
330
|
+
tools: {
|
|
331
|
+
run: { name: 'opencode_run', description: 'Dispatch a coding/build/debug/investigation task to the local opencode agent CLI and return its final answer. Prefer this for implementation, edits, refactors, multi-file investigation and debugging in every mode. DSH fully controls opencode: it always runs non-interactively with permissions auto-approved (opencode never blocks on a prompt). Use read-only native tools only for quick lookups and for final build/test verification. Runs in the background by default (returns a jobId immediately; collect with job_output); set background=false to block for the final answer.', inputSchema: RUN_PARAMS },
|
|
332
|
+
continue: { name: 'opencode_continue', description: 'Continue an existing opencode session with a follow-up prompt, reusing opencode context. Pass sessionId from a prior opencode_run result, or set latest=true to continue the most recent opencode session. Same DSH-controlled, no-prompt execution as opencode_run.', inputSchema: CONTINUE_PARAMS },
|
|
333
|
+
status: { name: 'opencode_status', description: 'Read a live snapshot of what the local opencode agent is currently doing. Returns one section per project (working directory): running count, the current step (tool name + arguments being executed, or agent_response thinking/typing), the recent step trail (tools executed, done/error), and the last completed run status + session id. Optional cwd filters to a single project. Call this to check on an in-flight opencode_run/opencode_continue without waiting for it to finish.', inputSchema: STATUS_PARAMS }
|
|
334
|
+
},
|
|
335
|
+
|
|
336
|
+
// opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
|
|
337
|
+
// deps.nodeChild;dynamic 沙箱形态省略)。
|
|
338
|
+
extraTools: (deps.process || deps.nodeChild) ? [{
|
|
339
|
+
name: 'opencode_models',
|
|
340
|
+
description: MODELS_DESCRIPTION,
|
|
341
|
+
inputSchema: MODELS_PARAMS,
|
|
342
|
+
render: renderModels,
|
|
343
|
+
async logic(args) {
|
|
344
|
+
return await descriptor.listModels(args || {})
|
|
345
|
+
}
|
|
346
|
+
}] : [],
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* 列出可用模型(三形态共用)。真实执行 `opencode models`;
|
|
350
|
+
* CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
|
|
351
|
+
*/
|
|
352
|
+
async listModels(args) {
|
|
353
|
+
const a = args || {}
|
|
354
|
+
const child = deps.nodeChild
|
|
355
|
+
if (!child || typeof child.spawn !== 'function') {
|
|
356
|
+
// preset 形态:宿主 subprocess(attach 后可用)。
|
|
357
|
+
if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
|
|
358
|
+
}
|
|
359
|
+
const prefix = resolveExePrefix(env, currentSettings().binPath)
|
|
360
|
+
const argv = prefix.slice(1).concat(['models'])
|
|
361
|
+
const run = child && typeof child.spawn === 'function'
|
|
362
|
+
? spawnModelsNode(child, prefix[0], argv)
|
|
363
|
+
: spawnModelsHost(argv)
|
|
364
|
+
let res
|
|
365
|
+
try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
|
|
366
|
+
if (!res.ok) return res
|
|
367
|
+
let list = res.models
|
|
368
|
+
if (a.provider) {
|
|
369
|
+
const pv = String(a.provider).toLowerCase()
|
|
370
|
+
list = list.filter((m) => String(m.provider).toLowerCase() === pv)
|
|
371
|
+
}
|
|
372
|
+
if (a.freeOnly) list = list.filter((m) => m.free)
|
|
373
|
+
// 免费模型优先展示(用户要求:优先用免费模型),与设置面板拉取列表同一排序。
|
|
374
|
+
list = sortModelsFreeFirst(list)
|
|
375
|
+
return { ok: true, models: list, count: list.length }
|
|
376
|
+
},
|
|
377
|
+
|
|
378
|
+
// 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
|
|
379
|
+
settings: {
|
|
380
|
+
keys: ['binPath', 'defaultModel', 'defaultAgent'],
|
|
381
|
+
defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
|
|
382
|
+
normalize: (raw) => {
|
|
383
|
+
const r = raw && typeof raw === 'object' ? raw : {}
|
|
384
|
+
const out = { binPath: '', defaultModel: '', defaultAgent: '' }
|
|
385
|
+
for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
|
|
386
|
+
if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
|
|
387
|
+
}
|
|
388
|
+
return out
|
|
389
|
+
},
|
|
390
|
+
meta: (env2) => {
|
|
391
|
+
const e = env2 && typeof env2 === 'object' ? env2 : {}
|
|
392
|
+
const s = currentSettings()
|
|
393
|
+
// 契约 §3.2:面板渲染**只读缓存**(命中就填 options,没命中留空),绝不 spawn。
|
|
394
|
+
// 探测改由用户点「拉取可用模型」显式触发(settings.refreshModels)。
|
|
395
|
+
const options = modelsToOptions(cachedModels())
|
|
396
|
+
// 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
|
|
397
|
+
const exeCandidates = []
|
|
398
|
+
if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
|
|
399
|
+
for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
|
|
400
|
+
return {
|
|
401
|
+
titleSuffix: 'OpenCode',
|
|
402
|
+
fields: [
|
|
403
|
+
{
|
|
404
|
+
key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
|
|
405
|
+
options: exeCandidates.map((p) => ({ value: p, label: p })),
|
|
406
|
+
placeholder: '留空 = 自动探测桌面版 / PATH',
|
|
407
|
+
note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
|
|
408
|
+
},
|
|
409
|
+
{
|
|
410
|
+
key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
|
|
411
|
+
options: options,
|
|
412
|
+
refresh: { label: '拉取可用模型' },
|
|
413
|
+
placeholder: '留空 = 由 opencode 自身配置决定',
|
|
414
|
+
note: options.length
|
|
415
|
+
? '共 ' + options.length + ' 个可用模型(上次手动拉取的结果,免费模型已排在前面)。点「拉取可用模型」可重新拉取;调用时传 model 可覆盖本项。'
|
|
416
|
+
: '还没拉取过可用模型清单 —— 点右侧「拉取可用模型」按钮拉取(面板不再自动探测,避免拖慢首屏)。拉取失败会显示具体原因(CLI 未安装 / 未登录 / 超时)。仍可手动输入 provider/model。'
|
|
417
|
+
},
|
|
418
|
+
{
|
|
419
|
+
key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
|
|
420
|
+
options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
|
|
421
|
+
placeholder: '留空 = opencode 默认 agent',
|
|
422
|
+
note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
|
|
423
|
+
}
|
|
424
|
+
]
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
/**
|
|
428
|
+
* 契约 §3.2:手动拉取可用模型(面板按钮 → POST /cli-bridge/settings/models)。
|
|
429
|
+
* 复用 opencode-exe.mjs 的同步探测(包一层 async 即可 —— 该端点本身就是串行
|
|
430
|
+
* 请求,为它再写一套异步 spawn 只会多一份要维护的探测代码)。
|
|
431
|
+
* 成功写回缓存让随后的 meta() 命中;失败**必须** ok:false + 可操作原因,
|
|
432
|
+
* 绝不返回 { ok:true, ids:[] },也绝不硬编码模型名冒充清单。
|
|
433
|
+
*/
|
|
434
|
+
async refreshModels(settings, envArg) {
|
|
435
|
+
const s = settings && typeof settings === 'object' ? settings : {}
|
|
436
|
+
const e = envArg && typeof envArg === 'object' ? envArg : env
|
|
437
|
+
const binPath = (typeof s.binPath === 'string' && s.binPath.trim()) ? s.binPath.trim() : (currentSettings().binPath || '')
|
|
438
|
+
const r = fetchModelsDetailed(e, binPath, 15000)
|
|
439
|
+
const source = 'opencode-models'
|
|
440
|
+
if (!r.ok) return { ok: false, ids: [], source: source, error: r.error }
|
|
441
|
+
const models = sortModelsFreeFirst(r.models)
|
|
442
|
+
rememberModels(models)
|
|
443
|
+
const labels = Object.create(null)
|
|
444
|
+
for (const m of models) labels[m.id] = modelLabel(m)
|
|
445
|
+
return { ok: true, ids: models.map((m) => String(m.id)), labels: labels, source: source }
|
|
446
|
+
},
|
|
447
|
+
diagnose: (settings, env2) => {
|
|
448
|
+
const s = settings && typeof settings === 'object' ? settings : {}
|
|
449
|
+
const e = env2 && typeof env2 === 'object' ? env2 : {}
|
|
450
|
+
const bits = []
|
|
451
|
+
const found = candidateExePaths(e)
|
|
452
|
+
if (s.binPath) bits.push('bin=设置:' + s.binPath)
|
|
453
|
+
else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
|
|
454
|
+
else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
|
|
455
|
+
else bits.push('bin=PATH:opencode-cli')
|
|
456
|
+
bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
|
|
457
|
+
if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
|
|
458
|
+
return bits.join(' · ')
|
|
459
|
+
}
|
|
460
|
+
},
|
|
461
|
+
|
|
462
|
+
mcp: { version: '0.2.2' }
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// MCP/测试形态:真 child_process。
|
|
466
|
+
function spawnModelsNode(child, exe, argv) {
|
|
467
|
+
return new Promise((resolve) => {
|
|
468
|
+
let c
|
|
469
|
+
try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
|
|
470
|
+
catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
|
|
471
|
+
let out = ''
|
|
472
|
+
let err = ''
|
|
473
|
+
const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
|
|
474
|
+
c.stdout.on('data', (d) => { out += d })
|
|
475
|
+
c.stderr.on('data', (d) => { err += d })
|
|
476
|
+
c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
|
|
477
|
+
c.on('close', (code) => {
|
|
478
|
+
clearTimeout(timer)
|
|
479
|
+
if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
|
|
480
|
+
const list = parseModelList(out)
|
|
481
|
+
if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
|
|
482
|
+
resolve({ ok: true, models: list })
|
|
483
|
+
})
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// preset 形态:DSH subprocess。
|
|
488
|
+
async function spawnModelsHost(argv) {
|
|
489
|
+
try {
|
|
490
|
+
const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
|
|
491
|
+
if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
|
|
492
|
+
const handle = host.subprocess.spawn(spec)
|
|
493
|
+
const outcome = await handle.done
|
|
494
|
+
const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
|
|
495
|
+
const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
|
|
496
|
+
if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
|
|
497
|
+
const list = parseModelList(stdoutText)
|
|
498
|
+
if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
|
|
499
|
+
return { ok: true, models: list }
|
|
500
|
+
} catch (e) { return { ok: false, error: String(e && e.message || e) } }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
descriptor.runToolLogic = async function (args, exec) {
|
|
504
|
+
const a = args || {}
|
|
505
|
+
const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
|
|
506
|
+
return this.runner.coreExecute(normalized, exec)
|
|
507
|
+
}
|
|
508
|
+
descriptor.continueToolLogic = async function (args, exec) {
|
|
509
|
+
const a = args || {}
|
|
510
|
+
const mapped = {
|
|
511
|
+
prompt: a.prompt, model: a.model, agent: a.agent,
|
|
512
|
+
cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
|
|
513
|
+
background: a.background === undefined ? true : a.background
|
|
514
|
+
}
|
|
515
|
+
const sid = a.sessionId || null
|
|
516
|
+
if (sid) mapped.sessionId = sid
|
|
517
|
+
else if (a.latest) mapped.continueLatest = true
|
|
518
|
+
return this.runner.coreExecute(mapped, exec)
|
|
519
|
+
}
|
|
520
|
+
descriptor.statusToolLogic = function (args) {
|
|
521
|
+
const a = args || {}
|
|
522
|
+
const snap = this.engine.statusSnapshot()
|
|
523
|
+
if (a.cwd) {
|
|
524
|
+
const key = String(a.cwd)
|
|
525
|
+
snap.projects = snap.projects.filter((p) => p.cwd === key)
|
|
526
|
+
const g = snap.projects[0]
|
|
527
|
+
if (g) {
|
|
528
|
+
Object.assign(snap, {
|
|
529
|
+
state: g.state, running: g.running, current: g.current, trail: g.trail,
|
|
530
|
+
lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
|
|
531
|
+
lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
|
|
532
|
+
})
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return snap
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
descriptor.attach = function (hostOpts) {
|
|
539
|
+
host = hostOpts || {}
|
|
540
|
+
// 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
|
|
541
|
+
try {
|
|
542
|
+
if (typeof host.getSettings === 'function') {
|
|
543
|
+
const s = host.getSettings('opencode')
|
|
544
|
+
if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
|
|
545
|
+
}
|
|
546
|
+
} catch (e) { }
|
|
547
|
+
this.engine = createStatusEngine({ provider: this, publish: host.publish })
|
|
548
|
+
const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
|
|
549
|
+
this.runner = runner
|
|
550
|
+
return runner
|
|
551
|
+
}
|
|
552
|
+
return descriptor
|
|
553
|
+
}
|