@wwkit/harness 1.0.43 → 1.0.45

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/README.md CHANGED
@@ -36,12 +36,21 @@ npm install @wwkit/harness
36
36
 
37
37
  | 方式 | 配置 | 提供内容 | 适用 |
38
38
  |------|------|---------|------|
39
- | **A. 插件模式(仅技能)** | 在 `~/.config/opencode/opencode.jsonc` 注册插件 | 仅 `extract`/`revise` **技能** | 只需要技能能力 |
40
- | **B. 环境变量模式(完整,推荐)** | 设置 `OPENCODE_CONFIG_DIR` 指向包目录 | **代理 + 技能 + 命令**(原生扫描 `agents/`、`skills/`、`commands/`) | 需要完整能力 |
39
+ | **A. 插件模式(完整,推荐)** | 在 `~/.config/opencode/opencode.jsonc` 注册插件 | **代理 + 技能 + 命令**(plugin `config` hook 内联注入) | 需要完整能力,支持多包共存 |
40
+ | **B. 环境变量模式(完整)** | 设置 `OPENCODE_CONFIG_DIR` 指向包目录 | **代理 + 技能 + 命令**(原生扫描 `agents/`、`skills/`、`commands/`) | 单包使用,不想改 `opencode.jsonc` |
41
41
 
42
- ### 方式 A:插件模式(仅技能)
42
+ ### 方式 A:插件模式(完整,推荐)
43
43
 
44
- 在 `~/.config/opencode/opencode.jsonc` 中注册插件:
44
+ `plugin.js` 的 `config` hook 会自动将包内的 `agents/*.md`、`skills/`、`commands/*.md` 注入到 opencode 配置中——agents 通过 `config.agent` 内联注入,commands 通过 `config.command` 内联注入,skills 通过 `config.skills.paths` 目录注入。无需设置环境变量,不污染全局目录。
45
+
46
+ **安装**:
47
+
48
+ ```bash
49
+ cd ~/.config/opencode
50
+ npm install @wwkit/harness
51
+ ```
52
+
53
+ **配置**:在 `~/.config/opencode/opencode.jsonc` 中声明插件:
45
54
 
46
55
  ```jsonc
47
56
  {
@@ -49,9 +58,30 @@ npm install @wwkit/harness
49
58
  }
50
59
  ```
51
60
 
52
- 该模式仅注册技能(`extract`/`revise`)。opencode 不支持通过插件注册代理或命令(`agents.paths`/`commands.paths` 字段不存在),因此**方式 A 不含代理与命令**。
61
+ opencode 启动时自动加载插件,代理/技能/命令从包内读取,全局目录零新增。
62
+
63
+ **多包共存**:插件模式支持多个 npm 能力包自由叠加,各自注入互不干扰:
64
+
65
+ ```jsonc
66
+ {
67
+ "plugin": [
68
+ "node_modules/@wwkit/harness",
69
+ "node_modules/@otherscope/opencode-tools"
70
+ ]
71
+ }
72
+ ```
73
+
74
+ 每个包的 `config` hook 依次用同一个配置对象调用,同名条目"先到先得"(用 `??=` 避免覆盖)。
75
+
76
+ **字段映射**:plugin 从各 `.md` 文件的 YAML frontmatter 解析字段并注入:
77
+
78
+ | 能力 | frontmatter 字段 | 注入目标 |
79
+ |------|-----------------|---------|
80
+ | agents | `description`、`mode`、`temperature`、`permission`、`steps`→`maxSteps`、`model` | `config.agent[name]`(`prompt` 取 body) |
81
+ | commands | `description`、`agent`、`model` | `config.command[name]`(`template` 取 body) |
82
+ | skills | — | `config.skills.paths`(目录递归扫描 `**/SKILL.md`) |
53
83
 
54
- ### 方式 B:环境变量模式(完整,推荐)
84
+ ### 方式 B:环境变量模式(完整)
55
85
 
56
86
  将 `OPENCODE_CONFIG_DIR` 指向包的安装目录,opencode 会把它当作配置目录,原生发现其中的 `agents/`、`skills/`、`commands/`:
57
87
 
@@ -62,8 +92,8 @@ echo 'export OPENCODE_CONFIG_DIR="$HOME/.config/opencode/node_modules/@wwkit/har
62
92
  说明:
63
93
  - 需在**启动 opencode 前**设置环境变量;
64
94
  - 与用户原有配置目录是**叠加**关系,不覆盖已有代理/技能/命令;
65
- - 该变量为**单一路径**,同时只能指向一个目录;
66
- - 若之前注册过插件(方式 A),改用方式 B 时请移除 `opencode.jsonc` 中的 `plugin` 项,避免技能重复扫描。
95
+ - 该变量为**单一路径**,同时只能指向一个目录——如需多包共存请改用方式 A;
96
+ - 若之前注册过插件(方式 A),改用方式 B 时请移除 `opencode.jsonc` 中的 `plugin` 项,避免重复扫描。
67
97
 
68
98
  ## 功能
69
99
 
@@ -108,7 +138,7 @@ opencode run --agent general '请用 skill 工具加载 query 技能(name=quer
108
138
 
109
139
  ## 使用命令(Commands)
110
140
 
111
- 命令由 opencode 原生加载(需方式 B:`OPENCODE_CONFIG_DIR` 指向本包),在 TUI 内输入命令名即可调用:
141
+ 命令通过插件模式(方式 A)或环境变量模式(方式 B)注册后在 TUI 内可用,输入命令名即可调用:
112
142
 
113
143
  ```text
114
144
  /tl <要翻译的文本> # 中英互译;中文→英文附关键词解析,英文→中文
package/bin/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { execSync, spawn } from 'node:child_process'
4
- import { readFileSync, readdirSync, existsSync } from 'node:fs'
4
+ import { readFileSync, writeFileSync, readdirSync, existsSync } from 'node:fs'
5
5
  import path from 'node:path'
6
6
  import { fileURLToPath } from 'node:url'
7
+ import JSON5 from 'json5'
7
8
  import { getConfigPath, mergeBuiltinConfig } from '../src/config.js'
8
9
 
9
10
  // Lazy-init: if user config doesn't exist (postinstall skipped), create it now
@@ -196,6 +197,17 @@ function cmdUpgrade() {
196
197
  * @param {string[]} args - process.argv.slice(3)
197
198
  */
198
199
  function cmdOpencode(args) {
200
+ // 拦截管理子命令:harness opencode config / harness opencode plugin ...
201
+ const sub = args[0]
202
+ if (sub === 'config') {
203
+ cmdConfig()
204
+ return
205
+ }
206
+ if (sub === 'plugin') {
207
+ cmdPlugin(args[1], args[2])
208
+ return
209
+ }
210
+
199
211
  let workDir = process.cwd()
200
212
  const passThrough = []
201
213
  for (let i = 0; i < args.length; i++) {
@@ -243,6 +255,254 @@ function cmdOpencode(args) {
243
255
  })
244
256
  }
245
257
 
258
+ // ─── opencode 全局配置路径解析 ───
259
+
260
+ /**
261
+ * 解析 opencode 全局配置目录。
262
+ * 优先 $XDG_CONFIG_HOME/opencode,fallback ~/.config/opencode。
263
+ * @returns {string}
264
+ */
265
+ function getOpencodeConfigDir() {
266
+ const xdg = process.env.XDG_CONFIG_HOME
267
+ if (xdg) return path.join(xdg, 'opencode')
268
+ const home = process.env.HOME || process.env.USERPROFILE || ''
269
+ return path.join(home, '.config', 'opencode')
270
+ }
271
+
272
+ /**
273
+ * 查找 opencode 全局配置文件,优先 .jsonc,其次 .json。
274
+ * 如果都不存在,返回 .jsonc 的路径(作为默认创建路径)。
275
+ * @returns {string}
276
+ */
277
+ function findOpencodeConfigFile() {
278
+ const dir = getOpencodeConfigDir()
279
+ const jsoncPath = path.join(dir, 'opencode.jsonc')
280
+ const jsonPath = path.join(dir, 'opencode.json')
281
+ if (existsSync(jsoncPath)) return jsoncPath
282
+ if (existsSync(jsonPath)) return jsonPath
283
+ return jsoncPath
284
+ }
285
+
286
+ /**
287
+ * 读取 opencode 配置文件(JSON5 解析,保留注释能力)。
288
+ * 文件不存在时返回空对象。
289
+ * @returns {{ data: object, filePath: string }}
290
+ */
291
+ function readOpencodeConfig() {
292
+ const filePath = findOpencodeConfigFile()
293
+ if (!existsSync(filePath)) return { data: {}, filePath }
294
+ const text = readFileSync(filePath, 'utf8')
295
+ const data = JSON5.parse(text)
296
+ return { data, filePath }
297
+ }
298
+
299
+ /**
300
+ * 将配置对象写回文件(JSON5 格式,2 空格缩进)。
301
+ * @param {object} data
302
+ * @param {string} filePath
303
+ */
304
+ function writeOpencodeConfig(data, filePath) {
305
+ const text = JSON.stringify(data, null, 2)
306
+ writeFileSync(filePath, text + '\n', 'utf8')
307
+ }
308
+
309
+ // ─── config 子命令 ───
310
+
311
+ /**
312
+ * 用系统编辑器打开 opencode 全局配置文件。
313
+ * 编辑器优先级:$EDITOR > $VISUAL > vim > vi > nano。
314
+ * 文件不存在时先创建空 JSON5 骨架。
315
+ */
316
+ function cmdConfig() {
317
+ const filePath = findOpencodeConfigFile()
318
+
319
+ // 文件不存在则创建骨架
320
+ if (!existsSync(filePath)) {
321
+ const dir = path.dirname(filePath)
322
+ if (!existsSync(dir)) {
323
+ console.error(`配置目录不存在: ${dir}`)
324
+ process.exit(1)
325
+ }
326
+ writeFileSync(filePath, '{\n // opencode 全局配置\n}\n', 'utf8')
327
+ console.log(`已创建: ${filePath}`)
328
+ }
329
+
330
+ // 编辑器优先级链:vim > vi > 系统设置($EDITOR/$VISUAL)> nano
331
+ const editor =
332
+ findInPath('vim') ||
333
+ findInPath('vi') ||
334
+ process.env.EDITOR ||
335
+ process.env.VISUAL ||
336
+ findInPath('nano')
337
+
338
+ if (!editor) {
339
+ console.error('未找到可用的编辑器。请设置 $EDITOR 环境变量,或安装 vim/vi/nano。')
340
+ console.error(`配置文件路径: ${filePath}`)
341
+ process.exit(1)
342
+ }
343
+
344
+ console.log(`正在用 ${editor} 打开: ${filePath}`)
345
+ const child = spawn(editor, [filePath], {
346
+ stdio: 'inherit',
347
+ shell: process.platform === 'win32',
348
+ })
349
+ child.on('error', (err) => {
350
+ console.error(`启动编辑器失败: ${err.message}`)
351
+ process.exit(1)
352
+ })
353
+ child.on('close', (code) => {
354
+ process.exit(code ?? 0)
355
+ })
356
+ }
357
+
358
+ /**
359
+ * 在 PATH 中查找可执行文件,返回完整路径或 null。
360
+ * @param {string} name
361
+ * @returns {string|null}
362
+ */
363
+ function findInPath(name) {
364
+ try {
365
+ const which = process.platform === 'win32' ? 'where' : 'which'
366
+ const result = execSync(`${which} ${name}`, {
367
+ encoding: 'utf8',
368
+ stdio: ['pipe', 'pipe', 'pipe'],
369
+ }).trim()
370
+ return result.split('\n')[0] || null
371
+ } catch {
372
+ return null
373
+ }
374
+ }
375
+
376
+ // ─── plugin 子命令 ───
377
+
378
+ const PKG_NAME = '@wwkit/harness'
379
+
380
+ /**
381
+ * 判断某 plugin 条目是否与给定目标指向同一包。
382
+ * 兼容:精确值、node_modules/ 前缀、以 /target 结尾(含绝对路径)。
383
+ * @param {string} p
384
+ * @param {string} target
385
+ * @returns {boolean}
386
+ */
387
+ function isSameEntry(p, target) {
388
+ return p === target || p === `node_modules/${target}` || p.endsWith(`/${target}`)
389
+ }
390
+
391
+ /**
392
+ * 判断某 plugin 条目是否指向当前 harness 包。
393
+ * 兼容:绝对路径 pkgRoot、file:// URL、包名、node_modules 相对路径。
394
+ * @param {string} p
395
+ * @returns {boolean}
396
+ */
397
+ function isCurrentPackageEntry(p) {
398
+ return (
399
+ p === pkgRoot ||
400
+ p === `file://${pkgRoot}` ||
401
+ isSameEntry(p, PKG_NAME)
402
+ )
403
+ }
404
+
405
+ /**
406
+ * 管理当前工程在 opencode 全局配置中的 plugin 声明。
407
+ *
408
+ * 用法:
409
+ * harness opencode plugin add [name] 追加当前工程(默认写绝对路径)或指定 name
410
+ * harness opencode plugin remove [name] 移除当前工程(默认)或指定 name
411
+ * harness opencode plugin list 列出当前 plugin 数组
412
+ *
413
+ * 不带 name 时,默认使用当前 harness 包的绝对路径 pkgRoot——复用已安装的包,
414
+ * 避免 opencode 到 cache 里重复安装。显式传 name 时按 name 原样写入。
415
+ * add 时若已存在指向同一目标的条目则先删后加,保证幂等。
416
+ */
417
+ function cmdPlugin(action, name) {
418
+ if (!action || action === 'list') {
419
+ cmdPluginList()
420
+ return
421
+ }
422
+
423
+ if (action === 'add') {
424
+ cmdPluginAdd(name)
425
+ } else if (action === 'remove' || action === 'rm') {
426
+ cmdPluginRemove(name)
427
+ } else {
428
+ console.error(`未知的 plugin 操作: ${action}`)
429
+ console.error('可用操作: add, remove, list')
430
+ process.exit(1)
431
+ }
432
+ }
433
+
434
+ function cmdPluginList() {
435
+ const { data, filePath } = readOpencodeConfig()
436
+ const plugins = data.plugin || []
437
+ console.log(`opencode 配置: ${filePath}`)
438
+ console.log(`plugin (${plugins.length}):`)
439
+ if (plugins.length === 0) {
440
+ console.log(' (无)')
441
+ return
442
+ }
443
+ for (const p of plugins) {
444
+ console.log(` ${p} ${isCurrentPackageEntry(p) ? '← 当前工程' : ''}`)
445
+ }
446
+ }
447
+
448
+ function cmdPluginAdd(name) {
449
+ const { data, filePath } = readOpencodeConfig()
450
+
451
+ // 确保 plugin 数组存在
452
+ if (!Array.isArray(data.plugin)) {
453
+ data.plugin = []
454
+ }
455
+
456
+ // 默认写当前包的绝对路径,复用已安装的包,避免 opencode 重复安装
457
+ const target = name || pkgRoot
458
+ // 无 name 或显式传包名,都视为「当前工程」,移除其所有变体后再写入
459
+ const isCurrent = !name || name === PKG_NAME
460
+
461
+ // 幂等:先移除指向同一目标的旧条目(含包名/相对路径/绝对路径变体)
462
+ data.plugin = data.plugin.filter((p) =>
463
+ isCurrent ? !isCurrentPackageEntry(p) : !isSameEntry(p, target)
464
+ )
465
+
466
+ // 追加
467
+ data.plugin.push(target)
468
+ writeOpencodeConfig(data, filePath)
469
+
470
+ console.log(`✓ 已添加 plugin: ${target}`)
471
+ console.log(` 配置文件: ${filePath}`)
472
+ console.log(` 当前 plugin 数组: ${JSON.stringify(data.plugin)}`)
473
+ }
474
+
475
+ function cmdPluginRemove(name) {
476
+ const { data, filePath } = readOpencodeConfig()
477
+
478
+ if (!Array.isArray(data.plugin) || data.plugin.length === 0) {
479
+ console.log('plugin 数组为空,无需移除。')
480
+ return
481
+ }
482
+
483
+ const isCurrent = !name || name === PKG_NAME
484
+ const target = name || pkgRoot
485
+ const before = data.plugin.length
486
+ // 当前工程(无 name 或传包名)移除所有变体;其他 name 按 name 匹配
487
+ data.plugin = data.plugin.filter((p) =>
488
+ isCurrent ? !isCurrentPackageEntry(p) : !isSameEntry(p, target)
489
+ )
490
+ const after = data.plugin.length
491
+
492
+ if (after === before) {
493
+ console.log(`未找到 plugin: ${target}`)
494
+ console.log(` 当前 plugin 数组: ${JSON.stringify(data.plugin)}`)
495
+ return
496
+ }
497
+
498
+ // 如果 plugin 数组变空,保留空数组(不删除 key)
499
+ writeOpencodeConfig(data, filePath)
500
+
501
+ console.log(`✓ 已移除 plugin: ${target}`)
502
+ console.log(` 配置文件: ${filePath}`)
503
+ console.log(` 当前 plugin 数组: ${JSON.stringify(data.plugin)}`)
504
+ }
505
+
246
506
  function printHelp() {
247
507
  console.log(`harness - WebWork abilities for opencode
248
508
 
@@ -256,10 +516,15 @@ function printHelp() {
256
516
  harness upgrade 升级 harness 自身(npm install -g @wwkit/harness@latest)
257
517
  harness opencode [args] 启动 opencode(自动设置 OPENCODE_CONFIG_DIR)
258
518
  harness opencode -d <dir> 在指定目录启动 opencode
519
+ harness opencode config 用系统编辑器打开 opencode 全局配置文件
520
+ harness opencode plugin list 列出全局配置中的 plugin 数组
521
+ harness opencode plugin add [name] 追加当前工程绝对路径(或指定 name)到 plugin 数组
522
+ harness opencode plugin remove [name] 从 plugin 数组移除当前工程(或指定 name)
259
523
  harness help 显示本帮助
260
524
 
261
525
  安装目录: ${pkgRoot}
262
526
  配置: OPENCODE_CONFIG_DIR 环境变量(由 postinstall 或 harness opencode 自动设置)
527
+ 编辑器: harness opencode config 优先 vim > vi > $EDITOR > $VISUAL > nano
263
528
  `)
264
529
  }
265
530
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwkit/harness",
3
- "version": "1.0.43",
3
+ "version": "1.0.45",
4
4
  "author": "bluesliu <langcai163@163.com>",
5
5
  "description": "WebWork abilities for opencode",
6
6
  "type": "module",
package/plugin.js CHANGED
@@ -1,19 +1,70 @@
1
- import path from 'path';
2
- import { fileURLToPath } from 'url';
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
3
4
 
4
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
5
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
6
+
7
+ /**
8
+ * 解析 markdown 目录:拆出 YAML frontmatter(简单 key: value)与 body。
9
+ * @returns {{ name: string, meta: Record<string,string>, body: string }[]}
10
+ */
11
+ function loadMarkdownDir(dir) {
12
+ if (!fs.existsSync(dir)) return []
13
+ return fs.readdirSync(dir)
14
+ .filter((f) => f.endsWith('.md'))
15
+ .map((f) => {
16
+ const text = fs.readFileSync(path.join(dir, f), 'utf8')
17
+ const name = f.replace(/\.md$/, '')
18
+ const m = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
19
+ if (!m) return { name, meta: {}, body: text.trim() }
20
+ const meta = {}
21
+ for (const line of m[1].split('\n')) {
22
+ const kv = line.match(/^([\w-]+)\s*:\s*(.*)$/)
23
+ if (kv) meta[kv[1]] = kv[2].replace(/^["']|["']$/g, '')
24
+ }
25
+ return { name, meta, body: m[2].trim() }
26
+ })
27
+ }
5
28
 
6
29
  export const WebWorkAbilityPlugin = async () => {
7
- const root = path.resolve(__dirname);
30
+ const root = path.resolve(__dirname)
8
31
 
9
32
  return {
10
33
  config: async (config) => {
11
- const skillsDir = path.join(root, 'skills');
12
- config.skills = config.skills || {};
13
- config.skills.paths = config.skills.paths || [];
34
+ // ── agents(内联注入 config.agent)──
35
+ config.agent = config.agent || {}
36
+ for (const a of loadMarkdownDir(path.join(root, 'agents'))) {
37
+ const agentCfg = {
38
+ description: a.meta.description,
39
+ mode: a.meta.mode || 'subagent',
40
+ prompt: a.body,
41
+ }
42
+ if (a.meta.model) agentCfg.model = a.meta.model
43
+ if (a.meta.temperature) agentCfg.temperature = Number(a.meta.temperature)
44
+ if (a.meta.permission) agentCfg.permission = a.meta.permission
45
+ if (a.meta.steps) agentCfg.maxSteps = Number(a.meta.steps)
46
+ config.agent[a.name] ??= agentCfg
47
+ }
48
+
49
+ // ── skills(目录递归扫描)──
50
+ config.skills = config.skills || {}
51
+ config.skills.paths = config.skills.paths || []
52
+ const skillsDir = path.join(root, 'skills')
14
53
  if (!config.skills.paths.includes(skillsDir)) {
15
- config.skills.paths.push(skillsDir);
54
+ config.skills.paths.push(skillsDir)
55
+ }
56
+
57
+ // ── commands(内联注入 config.command)──
58
+ config.command = config.command || {}
59
+ for (const c of loadMarkdownDir(path.join(root, 'commands'))) {
60
+ const cmdCfg = {
61
+ template: c.body,
62
+ }
63
+ if (c.meta.description) cmdCfg.description = c.meta.description
64
+ if (c.meta.agent) cmdCfg.agent = c.meta.agent
65
+ if (c.meta.model) cmdCfg.model = c.meta.model
66
+ config.command[c.name] ??= cmdCfg
16
67
  }
17
- }
18
- };
19
- };
68
+ },
69
+ }
70
+ }