doukui 0.0.0-stage → 0.3.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.
Files changed (135) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +42 -0
  3. package/README.md +147 -2
  4. package/bin/commands/build.js +178 -0
  5. package/bin/commands/config.js +88 -0
  6. package/bin/commands/help.js +83 -0
  7. package/bin/commands/init.js +194 -0
  8. package/bin/commands/install.js +202 -0
  9. package/bin/commands/interactive.js +352 -0
  10. package/bin/commands/list.js +108 -0
  11. package/bin/commands/loop-server.js +357 -0
  12. package/bin/commands/loop.js +1398 -0
  13. package/bin/commands/migrate.js +120 -0
  14. package/bin/commands/setup-global.js +81 -0
  15. package/bin/commands/status.js +140 -0
  16. package/bin/commands/team-cleanup.js +190 -0
  17. package/bin/commands/validate-config.js +35 -0
  18. package/bin/commands/validate.js +21 -0
  19. package/bin/commands/version.js +22 -0
  20. package/bin/context.js +143 -0
  21. package/bin/doukui.js +216 -0
  22. package/package.json +47 -4
  23. package/plugins/contracts/capabilities.js +268 -0
  24. package/plugins/contracts/checkresult-schema.json +75 -0
  25. package/plugins/contracts/config-schema.json +179 -0
  26. package/plugins/contracts/plugin-interface.js +262 -0
  27. package/plugins/contracts/plugin-schema.json +104 -0
  28. package/plugins/core/hook-session-start/index.js +281 -0
  29. package/plugins/core/hook-session-start/plugin.json +7 -0
  30. package/plugins/core/hook-skill-gate/index.js +661 -0
  31. package/plugins/core/hook-skill-gate/plugin.json +12 -0
  32. package/plugins/core/provider-loop-engine/index.js +1397 -0
  33. package/plugins/core/provider-loop-engine/plugin.json +15 -0
  34. package/plugins/core/provider-memory-store/index.js +510 -0
  35. package/plugins/core/provider-memory-store/plugin.json +9 -0
  36. package/plugins/core/provider-role-registry/index.js +376 -0
  37. package/plugins/core/provider-role-registry/plugin.json +9 -0
  38. package/plugins/core/provider-state-store/index.js +244 -0
  39. package/plugins/core/provider-state-store/plugin.json +9 -0
  40. package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
  41. package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
  42. package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
  43. package/plugins/core/provider-watchdog/index.js +151 -0
  44. package/plugins/core/provider-watchdog/plugin.json +13 -0
  45. package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
  46. package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
  47. package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
  48. package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
  49. package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
  50. package/plugins/core/skill-agentic-loop/plugin.json +20 -0
  51. package/plugins/core/skill-agentic-loop/skill.md +572 -0
  52. package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
  53. package/plugins/core/skill-batch-task-creator/skill.md +620 -0
  54. package/plugins/core/skill-checklist/plugin.json +10 -0
  55. package/plugins/core/skill-checklist/skill.md +171 -0
  56. package/plugins/core/skill-completion-report/plugin.json +10 -0
  57. package/plugins/core/skill-completion-report/skill.md +331 -0
  58. package/plugins/core/skill-doukui-plan/plugin.json +15 -0
  59. package/plugins/core/skill-doukui-plan/skill.md +233 -0
  60. package/plugins/core/skill-doukui-sync/plugin.json +10 -0
  61. package/plugins/core/skill-doukui-sync/skill.md +76 -0
  62. package/plugins/core/skill-experience-logger/plugin.json +10 -0
  63. package/plugins/core/skill-experience-logger/skill.md +235 -0
  64. package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
  65. package/plugins/core/skill-human-checkpoint/skill.md +194 -0
  66. package/plugins/core/skill-progress-tracker/plugin.json +10 -0
  67. package/plugins/core/skill-progress-tracker/skill.md +228 -0
  68. package/plugins/core/skill-role-manager/plugin.json +10 -0
  69. package/plugins/core/skill-role-manager/skill.md +252 -0
  70. package/plugins/core/skill-split-work-package/plugin.json +15 -0
  71. package/plugins/core/skill-split-work-package/skill.md +441 -0
  72. package/plugins/core/skill-task-archive/plugin.json +10 -0
  73. package/plugins/core/skill-task-archive/skill.md +116 -0
  74. package/plugins/core/skill-task-creator/plugin.json +15 -0
  75. package/plugins/core/skill-task-creator/skill.md +886 -0
  76. package/plugins/core/skill-team-cleanup/plugin.json +10 -0
  77. package/plugins/core/skill-team-cleanup/skill.md +266 -0
  78. package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
  79. package/plugins/core/skill-watchdog-manager/skill.md +143 -0
  80. package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
  81. package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
  82. package/plugins/core/validator-doc-sync/index.js +248 -0
  83. package/plugins/core/validator-doc-sync/plugin.json +12 -0
  84. package/plugins/core/validator-work-package/index.js +300 -0
  85. package/plugins/core/validator-work-package/plugin.json +12 -0
  86. package/plugins/plugin-registry.json +186 -0
  87. package/plugins/runtime/agent-def-generator.js +150 -0
  88. package/plugins/runtime/audit-logger.js +311 -0
  89. package/plugins/runtime/build-cli.js +89 -0
  90. package/plugins/runtime/checkresult-validator.js +131 -0
  91. package/plugins/runtime/claude-md-injector.js +159 -0
  92. package/plugins/runtime/cleanup-utils.js +293 -0
  93. package/plugins/runtime/config-manager.js +317 -0
  94. package/plugins/runtime/config-validator.js +320 -0
  95. package/plugins/runtime/context-window.js +81 -0
  96. package/plugins/runtime/event-bus.js +207 -0
  97. package/plugins/runtime/executor-claude.js +828 -0
  98. package/plugins/runtime/executor-default.js +448 -0
  99. package/plugins/runtime/executor-local.js +178 -0
  100. package/plugins/runtime/executor-sdk.js +390 -0
  101. package/plugins/runtime/harness-build.js +1037 -0
  102. package/plugins/runtime/hook-dispatcher.js +315 -0
  103. package/plugins/runtime/logger.js +192 -0
  104. package/plugins/runtime/loop-actuator.js +292 -0
  105. package/plugins/runtime/loop-coordinator.js +347 -0
  106. package/plugins/runtime/loop-defaults.js +29 -0
  107. package/plugins/runtime/loop-dispatch-batch.js +247 -0
  108. package/plugins/runtime/loop-executor.js +120 -0
  109. package/plugins/runtime/loop-report.js +327 -0
  110. package/plugins/runtime/loop-server-core.js +750 -0
  111. package/plugins/runtime/loop-snapshot.js +581 -0
  112. package/plugins/runtime/loop-trace.js +242 -0
  113. package/plugins/runtime/loop-worktree.js +404 -0
  114. package/plugins/runtime/manifest-resolver.js +457 -0
  115. package/plugins/runtime/multi-window-coordinator.js +560 -0
  116. package/plugins/runtime/objective-verifier.js +136 -0
  117. package/plugins/runtime/plan-reader.js +763 -0
  118. package/plugins/runtime/plugin-loader.js +798 -0
  119. package/plugins/runtime/plugin-trust.js +182 -0
  120. package/plugins/runtime/plugin-validator.js +491 -0
  121. package/plugins/runtime/provider-failover.js +114 -0
  122. package/plugins/runtime/provider-resolver.js +342 -0
  123. package/plugins/runtime/reflection-evaluator.js +540 -0
  124. package/plugins/runtime/resolve-plugin-path.js +297 -0
  125. package/plugins/runtime/safe-path.js +119 -0
  126. package/plugins/runtime/sandbox-context.js +235 -0
  127. package/plugins/runtime/sandbox-manager.js +609 -0
  128. package/plugins/runtime/sandbox-worker.js +215 -0
  129. package/plugins/runtime/settings-merger.js +172 -0
  130. package/plugins/runtime/state-store.js +527 -0
  131. package/plugins/runtime/team-cleanup.js +497 -0
  132. package/plugins/runtime/text-tokenize.js +25 -0
  133. package/plugins/runtime/validator-pipeline.js +475 -0
  134. package/plugins/runtime/yaml-parser.js +692 -0
  135. package/templates/harness-config.yaml +388 -0
package/bin/context.js ADDED
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+
3
+ var path = require('path');
4
+ var fs = require('fs');
5
+ var HarnessBuild = require('../plugins/runtime/harness-build');
6
+
7
+ /**
8
+ * Color definitions for CLI output.
9
+ */
10
+ var colors = {
11
+ reset: '\x1b[0m',
12
+ green: '\x1b[32m',
13
+ yellow: '\x1b[33m',
14
+ red: '\x1b[31m',
15
+ cyan: '\x1b[36m',
16
+ dim: '\x1b[2m',
17
+ };
18
+
19
+ /**
20
+ * Apply color to text if colors are enabled.
21
+ * @param {string} text - The text to color
22
+ * @param {string} color - Color name from colors object
23
+ * @param {boolean} noColor - If true, skip colorization
24
+ * @returns {string}
25
+ */
26
+ function colorize(text, color, noColor) {
27
+ if (noColor) {
28
+ return text;
29
+ }
30
+ return (colors[color] || '') + text + (colors.reset || '');
31
+ }
32
+
33
+ /**
34
+ * Create a command execution context.
35
+ *
36
+ * @param {object} opts
37
+ * @param {string} opts.packageRoot - Root directory of this npm package
38
+ * @param {string} opts.targetRoot - Target project root directory
39
+ * @param {object} opts.flags - Parsed CLI flags
40
+ * @param {string} opts.command - Resolved command name
41
+ * @param {string} opts.packageVersion - Package version string
42
+ */
43
+ function createContext(opts) {
44
+ var ctx = {
45
+ packageRoot: opts.packageRoot,
46
+ targetRoot: opts.targetRoot,
47
+ flags: opts.flags,
48
+ command: opts.command,
49
+ packageVersion: opts.packageVersion,
50
+ // Command arguments after the command name (parsed by bin/doukui.js).
51
+ // May be undefined for older callers; commands that need args should default to [].
52
+ argv: opts.argv || [],
53
+
54
+ // Convenience path accessors
55
+ get skillsDir() {
56
+ return path.join(this.targetRoot, '.claude', 'skills');
57
+ },
58
+ get hooksDir() {
59
+ return path.join(this.targetRoot, '.claude', 'hooks');
60
+ },
61
+ get configDir() {
62
+ return path.join(this.targetRoot, '.claude', 'config');
63
+ },
64
+ get settingsPath() {
65
+ return path.join(this.targetRoot, '.claude', 'settings.json');
66
+ },
67
+ get configPath() {
68
+ return path.join(this.targetRoot, '.claude', 'config', 'harness-config.yaml');
69
+ },
70
+ get registryPath() {
71
+ return path.join(this.packageRoot, 'plugins', 'plugin-registry.json');
72
+ },
73
+ get pluginsDir() {
74
+ return path.join(this.packageRoot, 'plugins', 'core');
75
+ },
76
+
77
+ /**
78
+ * Colorize text, respecting --no-color flag.
79
+ */
80
+ colorize: function (text, color) {
81
+ return colorize(text, color, this.flags.noColor);
82
+ },
83
+
84
+ /**
85
+ * Create a configured HarnessBuild instance.
86
+ */
87
+ createBuilder: function (overrides) {
88
+ var opts = {
89
+ rootDir: this.targetRoot,
90
+ packageRoot: this.packageRoot,
91
+ registryPath: this.registryPath,
92
+ pluginsDir: this.pluginsDir,
93
+ outputSkillsDir: path.join(this.targetRoot, '.claude', 'skills'),
94
+ outputHooksDir: path.join(this.targetRoot, '.claude', 'hooks'),
95
+ verbose: this.flags.verbose,
96
+ };
97
+ if (overrides) {
98
+ for (var key in overrides) {
99
+ if (overrides.hasOwnProperty(key)) {
100
+ opts[key] = overrides[key];
101
+ }
102
+ }
103
+ }
104
+ return new HarnessBuild(opts);
105
+ },
106
+
107
+ /**
108
+ * Exit the process with the given code.
109
+ *
110
+ * A4: in test mode (DOUKUI_TEST_MODE=1), throws a sentinel error instead
111
+ * of calling process.exit so that bin/commands can be exercised inside a
112
+ * test runner without killing the process. The CLI entry point
113
+ * (bin/doukui.js) catches ExitSignal and converts it back to process.exit.
114
+ * In production (no env var), behaves exactly as before (process.exit).
115
+ */
116
+ exit: function (code) {
117
+ if (process.env.DOUKUI_TEST_MODE === '1') {
118
+ var err = new Error('ExitSignal:' + code);
119
+ err.isExitSignal = true;
120
+ err.exitCode = code;
121
+ throw err;
122
+ }
123
+ process.exit(code);
124
+ },
125
+ };
126
+
127
+ return ctx;
128
+ }
129
+
130
+ /**
131
+ * Sentinel error name for exit signals thrown in test mode (A4).
132
+ * Callers that catch exceptions can check `err.isExitSignal` to distinguish
133
+ * a process-exit request from a real error.
134
+ * @public
135
+ */
136
+ var EXIT_SIGNAL = 'ExitSignal';
137
+
138
+ module.exports = {
139
+ colors: colors,
140
+ colorize: colorize,
141
+ createContext: createContext,
142
+ EXIT_SIGNAL: EXIT_SIGNAL,
143
+ };
package/bin/doukui.js ADDED
@@ -0,0 +1,216 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * doukui - CLI entry point
4
+ * Lightweight router: parses args, resolves --root, dispatches to commands/*.js
5
+ * Run `doukui --help` for usage.
6
+ */
7
+
8
+ 'use strict';
9
+
10
+ var path = require('path');
11
+ var fs = require('fs');
12
+ var safePath = require('../plugins/runtime/safe-path');
13
+ var createContext = require('./context').createContext;
14
+
15
+ var packageJson = require('../package.json');
16
+ var PACKAGE_VERSION = packageJson.version;
17
+
18
+ var packageRoot = path.resolve(__dirname, '..');
19
+ var targetRoot = process.cwd();
20
+
21
+ // CLI arg parsing
22
+
23
+ var args = process.argv.slice(2);
24
+ var flags = {
25
+ root: null,
26
+ verbose: false,
27
+ noColor: false,
28
+ help: false,
29
+ version: false,
30
+ };
31
+
32
+ var filteredArgs = [];
33
+ // B10: helper to detect flag-shaped args so `--root --verbose` doesn't
34
+ // consume `--verbose` as the root path.
35
+ function _isFlag(arg) {
36
+ return typeof arg === 'string' && arg.indexOf('--') === 0;
37
+ }
38
+ for (var i = 0; i < args.length; i++) {
39
+ if (args[i] === '--root' && args[i + 1] && !_isFlag(args[i + 1])) {
40
+ flags.root = args[++i];
41
+ } else if (args[i] === '--verbose') {
42
+ flags.verbose = true;
43
+ } else if (args[i] === '--no-color') {
44
+ flags.noColor = true;
45
+ } else if (args[i] === '--version' || args[i] === '-v') {
46
+ flags.version = true;
47
+ } else if (args[i] === '--help' || args[i] === '-h') {
48
+ flags.help = true;
49
+ } else {
50
+ filteredArgs.push(args[i]);
51
+ }
52
+ }
53
+
54
+ var command;
55
+ if (flags.help) {
56
+ command = 'help';
57
+ } else if (flags.version) {
58
+ command = 'version';
59
+ } else {
60
+ command = filteredArgs[0] || 'build';
61
+ }
62
+
63
+ // Minimal color helper for early errors before context is created
64
+ function colorize(text, color) {
65
+ if (flags.noColor) return text;
66
+ var codes = { red: '\x1b[31m', yellow: '\x1b[33m' };
67
+ return (codes[color] || '') + text + '\x1b[0m';
68
+ }
69
+
70
+ // Resolve --root
71
+ if (flags.root) {
72
+ var rootPath = flags.root;
73
+ if (/^[a-zA-Z]:[^\\\/]/.test(rootPath)) {
74
+ rootPath = rootPath.substring(0, 2) + '\\' + rootPath.substring(2);
75
+ }
76
+ var resolvedRoot = path.resolve(rootPath);
77
+ var normalizedPath = path.normalize(resolvedRoot);
78
+
79
+ try {
80
+ var stats = fs.statSync(normalizedPath);
81
+ if (!stats.isDirectory()) {
82
+ console.error(colorize('Error: --root path must be a directory', 'red'));
83
+ process.exit(1);
84
+ }
85
+ } catch (e) {
86
+ if (command !== 'init') {
87
+ console.error(colorize('Error: --root path does not exist: ' + normalizedPath, 'red'));
88
+ process.exit(1);
89
+ }
90
+ }
91
+
92
+ var cwdResolved = path.resolve(flags.root);
93
+ // S6:用 isWithin 替代 indexOf===0,避免 /foo 误判为 /foobar 父目录
94
+ if (!safePath.isWithin(process.cwd(), cwdResolved) && command !== 'init') {
95
+ console.warn(colorize('Warning: --root path is outside current working directory', 'yellow'));
96
+ }
97
+
98
+ targetRoot = normalizedPath;
99
+ }
100
+
101
+ // Command loading and dispatch
102
+ var commandsDir = path.join(__dirname, 'commands');
103
+
104
+ /**
105
+ * Built-in command name to module file mapping.
106
+ * New commands can be added by simply creating a file in commands/.
107
+ */
108
+ var commandModules = {
109
+ 'build': 'build.js',
110
+ 'validate': 'validate.js',
111
+ 'validate-config': 'validate-config.js',
112
+ 'init': 'init.js',
113
+ 'migrate': 'migrate.js',
114
+ 'status': 'status.js',
115
+ 'config': 'config.js',
116
+ 'list': 'list.js',
117
+ 'interactive': 'interactive.js',
118
+ 'i': 'interactive.js',
119
+ 'setup-global': 'setup-global.js',
120
+ 'version': 'version.js',
121
+ 'help': 'help.js',
122
+ 'install': 'install.js',
123
+ 'team-cleanup': 'team-cleanup.js',
124
+ 'loop': 'loop.js',
125
+ 'loop-server': 'loop-server.js',
126
+ };
127
+
128
+ function loadCommand(cmdName) {
129
+ // Try built-in mapping first
130
+ var moduleFile = commandModules[cmdName];
131
+ if (moduleFile) {
132
+ var modulePath = path.join(commandsDir, moduleFile);
133
+ if (fs.existsSync(modulePath)) {
134
+ return require(modulePath);
135
+ }
136
+ }
137
+
138
+ // Try auto-discovery: commands/<cmdName>.js
139
+ var autoPath = path.join(commandsDir, cmdName + '.js');
140
+ if (fs.existsSync(autoPath)) {
141
+ return require(autoPath);
142
+ }
143
+
144
+ // Check alias support in all command modules
145
+ if (!fs.existsSync(commandsDir)) {
146
+ return null;
147
+ }
148
+ var entries = fs.readdirSync(commandsDir);
149
+ for (var j = 0; j < entries.length; j++) {
150
+ if (entries[j].endsWith('.js')) {
151
+ try {
152
+ var mod = require(path.join(commandsDir, entries[j]));
153
+ if (mod.aliases && mod.aliases.indexOf(cmdName) !== -1) {
154
+ return mod;
155
+ }
156
+ } catch (e) {
157
+ // skip unloadable modules
158
+ }
159
+ }
160
+ }
161
+
162
+ return null;
163
+ }
164
+
165
+ var cmdModule = loadCommand(command);
166
+
167
+ if (!cmdModule) {
168
+ console.error(colorize('Error: Unknown command "' + command + '"', 'red'));
169
+ console.error('');
170
+ // Load help command to show usage
171
+ var helpModule = loadCommand('help');
172
+ if (helpModule) {
173
+ var ctx = createContext({
174
+ packageRoot: packageRoot,
175
+ targetRoot: targetRoot,
176
+ flags: flags,
177
+ command: 'help',
178
+ packageVersion: PACKAGE_VERSION,
179
+ });
180
+ helpModule.execute(ctx);
181
+ }
182
+ process.exit(1);
183
+ }
184
+
185
+ // Create context and execute.
186
+ // argv: command arguments after the command name (e.g. ['plan.md','--executor=local']).
187
+ var context = createContext({
188
+ packageRoot: packageRoot,
189
+ targetRoot: targetRoot,
190
+ flags: flags,
191
+ command: command,
192
+ packageVersion: PACKAGE_VERSION,
193
+ argv: filteredArgs.slice(1),
194
+ });
195
+
196
+ // #11:顶层错误兜底——命令可能同步抛错(如 team-cleanup 的非法输入),
197
+ // 也可能返回被 reject 的 Promise(如 loop/loop-server 异步命令)。
198
+ // 任一情况都给出干净的退出码 + 错误信息,而非裸露的 Node 堆栈/unhandledRejection。
199
+ function failCommand(err) {
200
+ var msg = err && err.message ? err.message : String(err);
201
+ console.error(colorize('Error: ' + msg, 'red'));
202
+ process.exit(1);
203
+ }
204
+
205
+ try {
206
+ var result = cmdModule.execute(context);
207
+ // 异步命令:result 是 Promise(或 thenable)→ 捕获 rejection
208
+ if (result && typeof result.then === 'function') {
209
+ result.then(function (exitEarly) {
210
+ // 命令可能 resolve 一个退出码(约定 truthy 即视为已 exit;正常 resolve 无需动作)
211
+ if (exitEarly && typeof exitEarly === 'number') process.exit(exitEarly);
212
+ }, failCommand);
213
+ }
214
+ } catch (err) {
215
+ failCommand(err);
216
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "doukui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "Doukui (斗魁) - multi-provider AI agent orchestration harness for Claude Code: goal-driven agentic loop, dependency-graph dispatch, per-WP worktree isolation, for GLM/DeepSeek/MiMo and Claude",
5
+ "bin": {
6
+ "doukui": "bin/doukui.js"
7
+ },
8
+ "files": [
9
+ "bin/",
10
+ "plugins/",
11
+ "templates/"
12
+ ],
13
+ "scripts": {
14
+ "build": "node bin/doukui.js build",
15
+ "validate": "node bin/doukui.js validate",
16
+ "test": "node scripts/test-runner.js",
17
+ "test:runtime": "node scripts/test-runner.js test/runtime",
18
+ "test:integration": "node scripts/test-runner.js test/integration",
19
+ "test:e2e": "node scripts/test-runner.js test/e2e",
20
+ "test:coverage": "node --experimental-test-coverage scripts/test-runner.js",
21
+ "test:smoke": "node test/smoke-test.js",
22
+ "postinstall": "node bin/doukui.js setup-global"
23
+ },
24
+ "keywords": [
25
+ "claude",
26
+ "claude-code",
27
+ "agent",
28
+ "harness",
29
+ "plugin",
30
+ "workflow"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/chen-xiaochen/doukui.git"
35
+ },
36
+ "author": "Doukui Contributors",
37
+ "homepage": "https://github.com/chen-xiaochen/doukui#readme",
38
+ "bugs": {
39
+ "url": "https://github.com/chen-xiaochen/doukui/issues"
40
+ },
41
+ "license": "MIT",
42
+ "optionalDependencies": {
43
+ "@anthropic-ai/claude-agent-sdk": "^0.3.319",
44
+ "ajv": "^8.12.0"
45
+ },
46
+ "engines": {
47
+ "node": ">=18.0.0"
48
+ }
49
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Capabilities - Capability declaration and runtime enforcement for plugin sandboxing
3
+ *
4
+ * Defines:
5
+ * - Capability enumeration (fs.read, fs.write, net.*, child_process, env, plugin.access)
6
+ * - CapabilityLevel risk classification (safe, low_risk, medium, high_risk)
7
+ * - CAPABILITY_LEVELS mapping (capability -> risk level)
8
+ * - TRUST_LEVELS matrix (sourceType -> allowed capabilities)
9
+ * - Runtime checker: isCapabilityAllowed(sourceType, capability)
10
+ *
11
+ * Design based on docs/design/harness-universal-platform-final-design.md section 3.2-3.4.
12
+ *
13
+ * @module capabilities
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Capability enumeration
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /**
23
+ * All recognized capabilities that a plugin may declare in plugin.json.
24
+ * Core services (eventBus, stateStore, logger, config) are always available
25
+ * and do not need to be declared.
26
+ * @public
27
+ */
28
+ var Capability = Object.freeze({
29
+ // File system access
30
+ FS_READ: 'fs.read',
31
+ FS_WRITE: 'fs.write',
32
+
33
+ // Network access
34
+ NET_REQUEST: 'net.request',
35
+ NET_LISTEN: 'net.listen',
36
+
37
+ // Process control
38
+ CHILD_PROCESS: 'child_process',
39
+
40
+ // Environment variables
41
+ ENV_READ: 'env.read',
42
+
43
+ // Cross-plugin provider access
44
+ PLUGIN_ACCESS: 'plugin.access',
45
+ });
46
+
47
+ /**
48
+ * Risk classification for capabilities.
49
+ * Used to determine audit severity and UI presentation.
50
+ * @public
51
+ */
52
+ var CapabilityLevel = Object.freeze({
53
+ SAFE: 'safe',
54
+ LOW_RISK: 'low_risk',
55
+ MEDIUM: 'medium',
56
+ HIGH_RISK: 'high_risk',
57
+ });
58
+
59
+ /**
60
+ * Maps each capability to its risk level.
61
+ * Used by audit logger and capability display logic.
62
+ * @public
63
+ */
64
+ var CAPABILITY_LEVELS = {};
65
+ CAPABILITY_LEVELS[Capability.FS_READ] = CapabilityLevel.LOW_RISK;
66
+ CAPABILITY_LEVELS[Capability.FS_WRITE] = CapabilityLevel.MEDIUM;
67
+ CAPABILITY_LEVELS[Capability.NET_REQUEST] = CapabilityLevel.MEDIUM;
68
+ CAPABILITY_LEVELS[Capability.NET_LISTEN] = CapabilityLevel.HIGH_RISK;
69
+ CAPABILITY_LEVELS[Capability.CHILD_PROCESS] = CapabilityLevel.HIGH_RISK;
70
+ CAPABILITY_LEVELS[Capability.ENV_READ] = CapabilityLevel.LOW_RISK;
71
+ CAPABILITY_LEVELS[Capability.PLUGIN_ACCESS] = CapabilityLevel.LOW_RISK;
72
+
73
+ Object.freeze(CAPABILITY_LEVELS);
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Trust levels and capability restriction matrix
77
+ // ---------------------------------------------------------------------------
78
+
79
+ /**
80
+ * Trust levels by source type.
81
+ * core — fully trusted, all capabilities available, no sandboxing
82
+ * npm — moderate trust, capabilities must be declared, sandboxed
83
+ * local — low trust, capabilities must be declared, sandboxed + path audit
84
+ * @public
85
+ */
86
+ var TRUST_LEVELS = Object.freeze({
87
+ core: 'full',
88
+ npm: 'moderate',
89
+ local: 'low',
90
+ });
91
+
92
+ /**
93
+ * Per-sourceType capability restrictions.
94
+ *
95
+ * 'auto' — always granted without declaration
96
+ * 'declared' — granted only if declared in plugin.json capabilities
97
+ * 'forbidden' — never granted (blocked at runtime)
98
+ *
99
+ * NOTE: npm and local share identical restriction matrices by design.
100
+ * Both require explicit capability declaration (declared) and forbid
101
+ * child_process. Although TRUST_LEVELS differentiates 'moderate' vs 'low',
102
+ * the capability enforcement is intentionally uniform — any third-party
103
+ * plugin (whether from npm or local filesystem) must declare its capabilities.
104
+ * If differentiated restrictions are needed in the future, the structure
105
+ * supports independent modification per sourceType.
106
+ *
107
+ * @internal 此数据结构可能在不同版本间变更以支持新的安全策略
108
+ */
109
+ var CAPABILITY_RESTRICTIONS = Object.freeze({
110
+ core: Object.freeze({
111
+ 'fs.read': 'auto',
112
+ 'fs.write': 'auto',
113
+ 'net.request': 'auto',
114
+ 'net.listen': 'auto',
115
+ 'child_process': 'auto',
116
+ 'env.read': 'auto',
117
+ 'plugin.access': 'auto',
118
+ }),
119
+ npm: Object.freeze({
120
+ 'fs.read': 'declared',
121
+ 'fs.write': 'declared',
122
+ 'net.request': 'declared',
123
+ 'net.listen': 'declared',
124
+ 'child_process': 'forbidden',
125
+ 'env.read': 'declared',
126
+ 'plugin.access': 'declared',
127
+ }),
128
+ local: Object.freeze({
129
+ 'fs.read': 'declared',
130
+ 'fs.write': 'declared',
131
+ 'net.request': 'declared',
132
+ 'net.listen': 'declared',
133
+ 'child_process': 'forbidden',
134
+ 'env.read': 'declared',
135
+ 'plugin.access': 'declared',
136
+ }),
137
+ });
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Runtime capability checker
141
+ // ---------------------------------------------------------------------------
142
+
143
+ /**
144
+ * Check whether a specific capability is allowed for a given source type.
145
+ *
146
+ * @public
147
+ * @param {string} sourceType - 'core' | 'npm' | 'local'
148
+ * @param {string} capability - one of Capability values
149
+ * @param {object} [declaredCapabilities] - the capabilities field from plugin.json (optional)
150
+ * @returns {{ allowed: boolean, reason: string }}
151
+ */
152
+ function isCapabilityAllowed(sourceType, capability, declaredCapabilities) {
153
+ // Core plugins: everything allowed
154
+ if (sourceType === 'core') {
155
+ return { allowed: true, reason: 'core plugin: full trust' };
156
+ }
157
+
158
+ // Validate sourceType
159
+ if (!CAPABILITY_RESTRICTIONS[sourceType]) {
160
+ return { allowed: false, reason: 'unknown sourceType: ' + sourceType };
161
+ }
162
+
163
+ var restrictions = CAPABILITY_RESTRICTIONS[sourceType];
164
+ var restriction = restrictions[capability];
165
+
166
+ if (!restriction) {
167
+ // Unknown capability — deny by default for non-core
168
+ return { allowed: false, reason: 'unknown capability: ' + capability };
169
+ }
170
+
171
+ if (restriction === 'auto') {
172
+ return { allowed: true, reason: 'auto-granted for ' + sourceType };
173
+ }
174
+
175
+ if (restriction === 'forbidden') {
176
+ return { allowed: false, reason: capability + ' is forbidden for ' + sourceType + ' plugins' };
177
+ }
178
+
179
+ // restriction === 'declared': check if declared in plugin.json
180
+ if (declaredCapabilities) {
181
+ // The capabilities field maps top-level keys like "filesystem", "network", "child_process", "env"
182
+ // to sub-structures. We need to map capability enums back to top-level keys.
183
+ var capKey = _capabilityToTopLevelKey(capability);
184
+ if (capKey && declaredCapabilities[capKey] !== undefined) {
185
+ // If the value is explicitly false, treat as not declared
186
+ if (declaredCapabilities[capKey] === false) {
187
+ return { allowed: false, reason: capability + ' explicitly disabled in plugin.json' };
188
+ }
189
+ return { allowed: true, reason: capability + ' declared in plugin.json' };
190
+ }
191
+ }
192
+
193
+ return { allowed: false, reason: capability + ' not declared in plugin.json capabilities' };
194
+ }
195
+
196
+ /**
197
+ * Determine if a plugin should run in a sandbox (Worker Thread).
198
+ * Core plugins run in the main process; npm/local plugins run sandboxed.
199
+ *
200
+ * @public
201
+ * @param {string} sourceType - 'core' | 'npm' | 'local'
202
+ * @returns {boolean}
203
+ */
204
+ function shouldSandbox(sourceType) {
205
+ return sourceType === 'npm' || sourceType === 'local';
206
+ }
207
+
208
+ /**
209
+ * Get all allowed capabilities for a source type, given declared capabilities.
210
+ *
211
+ * @public
212
+ * @param {string} sourceType
213
+ * @param {object} [declaredCapabilities]
214
+ * @returns {string[]} list of allowed Capability values
215
+ */
216
+ function getAllowedCapabilities(sourceType, declaredCapabilities) {
217
+ var allCaps = Object.keys(Capability).map(function (k) { return Capability[k]; });
218
+ var allowed = [];
219
+
220
+ for (var i = 0; i < allCaps.length; i++) {
221
+ var result = isCapabilityAllowed(sourceType, allCaps[i], declaredCapabilities);
222
+ if (result.allowed) {
223
+ allowed.push(allCaps[i]);
224
+ }
225
+ }
226
+
227
+ return allowed;
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------
231
+ // Internal helpers
232
+ // ---------------------------------------------------------------------------
233
+
234
+ /**
235
+ * Map a Capability enum value back to the top-level plugin.json key.
236
+ * e.g. 'fs.read' -> 'filesystem', 'net.request' -> 'network', etc.
237
+ *
238
+ * @internal
239
+ * @param {string} capability
240
+ * @returns {string|null}
241
+ */
242
+ function _capabilityToTopLevelKey(capability) {
243
+ var map = {
244
+ 'fs.read': 'filesystem',
245
+ 'fs.write': 'filesystem',
246
+ 'net.request': 'network',
247
+ 'net.listen': 'network',
248
+ 'child_process': 'child_process',
249
+ 'env.read': 'env',
250
+ 'plugin.access': 'plugin_access',
251
+ };
252
+ return map[capability] || null;
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Exports
257
+ // ---------------------------------------------------------------------------
258
+
259
+ module.exports = {
260
+ Capability: Capability,
261
+ CapabilityLevel: CapabilityLevel,
262
+ CAPABILITY_LEVELS: CAPABILITY_LEVELS,
263
+ TRUST_LEVELS: TRUST_LEVELS,
264
+ CAPABILITY_RESTRICTIONS: CAPABILITY_RESTRICTIONS,
265
+ isCapabilityAllowed: isCapabilityAllowed,
266
+ shouldSandbox: shouldSandbox,
267
+ getAllowedCapabilities: getAllowedCapabilities,
268
+ };